diff --git a/.gitattributes b/.gitattributes index c788f7a97c46c5ed43bb39ebd0e7e79ea3e7d811..6d0f25cc3d68a8a471ef2d133b3f245330adba06 100644 --- a/.gitattributes +++ b/.gitattributes @@ -164,3 +164,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/fontTools/pens/momentsPen.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/fontTools/qu2cu/qu2cu.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/fontTools/subset/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otConverters.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otData.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otTables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/varLib/iup.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/.venv/lib/python3.12/site-packages/fontTools/svgLib/__init__.py b/.venv/lib/python3.12/site-packages/fontTools/svgLib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c049006bf2e58bed7786432e7ec84c8c8b40edf0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/svgLib/__init__.py @@ -0,0 +1,3 @@ +from .path import SVGPath, parse_path + +__all__ = ["SVGPath", "parse_path"] diff --git a/.venv/lib/python3.12/site-packages/fontTools/svgLib/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/svgLib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d4c8154cf85019074bded3b8872fd662779489f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/svgLib/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/svgLib/path/__init__.py b/.venv/lib/python3.12/site-packages/fontTools/svgLib/path/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d277946226d19c42896407b38ec26b781510d41e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/svgLib/path/__init__.py @@ -0,0 +1,64 @@ +from fontTools.pens.transformPen import TransformPen +from fontTools.misc import etree +from fontTools.misc.textTools import tostr +from .parser import parse_path +from .shapes import PathBuilder + +__all__ = [tostr(s) for s in ("SVGPath", "parse_path")] + + +class SVGPath(object): + """Parse SVG ``path`` elements from a file or string, and draw them + onto a glyph object that supports the FontTools Pen protocol. + + For example, reading from an SVG file and drawing to a Defcon Glyph: + + .. code-block:: + + import defcon + glyph = defcon.Glyph() + pen = glyph.getPen() + svg = SVGPath("path/to/a.svg") + svg.draw(pen) + + Or reading from a string containing SVG data, using the alternative + 'fromstring' (a class method): + + .. code-block:: + + data = ' 1: + rx *= sqrt(radii_scale) + ry *= sqrt(radii_scale) + self.rx, self.ry = rx, ry + + point_transform = Scale(1 / rx, 1 / ry).rotate(-self.angle) + + point1 = _map_point(point_transform, self.current_point) + point2 = _map_point(point_transform, self.target_point) + delta = point2 - point1 + + d = delta.real * delta.real + delta.imag * delta.imag + scale_factor_squared = max(1 / d - 0.25, 0.0) + + scale_factor = sqrt(scale_factor_squared) + if self.sweep == self.large: + scale_factor = -scale_factor + + delta *= scale_factor + center_point = (point1 + point2) * 0.5 + center_point += complex(-delta.imag, delta.real) + point1 -= center_point + point2 -= center_point + + theta1 = atan2(point1.imag, point1.real) + theta2 = atan2(point2.imag, point2.real) + + theta_arc = theta2 - theta1 + if theta_arc < 0 and self.sweep: + theta_arc += TWO_PI + elif theta_arc > 0 and not self.sweep: + theta_arc -= TWO_PI + + self.theta1 = theta1 + self.theta2 = theta1 + theta_arc + self.theta_arc = theta_arc + self.center_point = center_point + + return True + + def _decompose_to_cubic_curves(self): + if self.center_point is None and not self._parametrize(): + return + + point_transform = Identity.rotate(self.angle).scale(self.rx, self.ry) + + # Some results of atan2 on some platform implementations are not exact + # enough. So that we get more cubic curves than expected here. Adding 0.001f + # reduces the count of sgements to the correct count. + num_segments = int(ceil(fabs(self.theta_arc / (PI_OVER_TWO + 0.001)))) + for i in range(num_segments): + start_theta = self.theta1 + i * self.theta_arc / num_segments + end_theta = self.theta1 + (i + 1) * self.theta_arc / num_segments + + t = (4 / 3) * tan(0.25 * (end_theta - start_theta)) + if not isfinite(t): + return + + sin_start_theta = sin(start_theta) + cos_start_theta = cos(start_theta) + sin_end_theta = sin(end_theta) + cos_end_theta = cos(end_theta) + + point1 = complex( + cos_start_theta - t * sin_start_theta, + sin_start_theta + t * cos_start_theta, + ) + point1 += self.center_point + target_point = complex(cos_end_theta, sin_end_theta) + target_point += self.center_point + point2 = target_point + point2 += complex(t * sin_end_theta, -t * cos_end_theta) + + point1 = _map_point(point_transform, point1) + point2 = _map_point(point_transform, point2) + target_point = _map_point(point_transform, target_point) + + yield point1, point2, target_point + + def draw(self, pen): + for point1, point2, target_point in self._decompose_to_cubic_curves(): + pen.curveTo( + (point1.real, point1.imag), + (point2.real, point2.imag), + (target_point.real, target_point.imag), + ) diff --git a/.venv/lib/python3.12/site-packages/fontTools/svgLib/path/parser.py b/.venv/lib/python3.12/site-packages/fontTools/svgLib/path/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..2b3523a8c229a82fb0289204dadc70a43e5935a8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/svgLib/path/parser.py @@ -0,0 +1,350 @@ +# SVG Path specification parser. +# This is an adaptation from 'svg.path' by Lennart Regebro (@regebro), +# modified so that the parser takes a FontTools Pen object instead of +# returning a list of svg.path Path objects. +# The original code can be found at: +# https://github.com/regebro/svg.path/blob/4f9b6e3/src/svg/path/parser.py +# Copyright (c) 2013-2014 Lennart Regebro +# License: MIT + +from .arc import EllipticalArc +import cmath +import re + +COMMANDS = set("MmZzLlHhVvCcSsQqTtAa") +ARC_COMMANDS = set("Aa") +UPPERCASE = set("MZLHVCSQTA") + +COMMAND_RE = re.compile("([MmZzLlHhVvCcSsQqTtAa])") + +# https://www.w3.org/TR/css-syntax-3/#number-token-diagram +# but -6.e-5 will be tokenized as "-6" then "-5" and confuse parsing +FLOAT_RE = re.compile( + r"[-+]?" # optional sign + r"(?:" + r"(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?" # int/float + r"|" + r"(?:\.[0-9]+(?:[eE][-+]?[0-9]+)?)" # float with leading dot (e.g. '.42') + r")" +) +BOOL_RE = re.compile("^[01]") +SEPARATOR_RE = re.compile(f"[, \t]") + + +def _tokenize_path(pathdef): + arc_cmd = None + for x in COMMAND_RE.split(pathdef): + if x in COMMANDS: + arc_cmd = x if x in ARC_COMMANDS else None + yield x + continue + + if arc_cmd: + try: + yield from _tokenize_arc_arguments(x) + except ValueError as e: + raise ValueError(f"Invalid arc command: '{arc_cmd}{x}'") from e + else: + for token in FLOAT_RE.findall(x): + yield token + + +ARC_ARGUMENT_TYPES = ( + ("rx", FLOAT_RE), + ("ry", FLOAT_RE), + ("x-axis-rotation", FLOAT_RE), + ("large-arc-flag", BOOL_RE), + ("sweep-flag", BOOL_RE), + ("x", FLOAT_RE), + ("y", FLOAT_RE), +) + + +def _tokenize_arc_arguments(arcdef): + raw_args = [s for s in SEPARATOR_RE.split(arcdef) if s] + if not raw_args: + raise ValueError(f"Not enough arguments: '{arcdef}'") + raw_args.reverse() + + i = 0 + while raw_args: + arg = raw_args.pop() + + name, pattern = ARC_ARGUMENT_TYPES[i] + match = pattern.search(arg) + if not match: + raise ValueError(f"Invalid argument for '{name}' parameter: {arg!r}") + + j, k = match.span() + yield arg[j:k] + arg = arg[k:] + + if arg: + raw_args.append(arg) + + # wrap around every 7 consecutive arguments + if i == 6: + i = 0 + else: + i += 1 + + if i != 0: + raise ValueError(f"Not enough arguments: '{arcdef}'") + + +def parse_path(pathdef, pen, current_pos=(0, 0), arc_class=EllipticalArc): + """Parse SVG path definition (i.e. "d" attribute of elements) + and call a 'pen' object's moveTo, lineTo, curveTo, qCurveTo and closePath + methods. + + If 'current_pos' (2-float tuple) is provided, the initial moveTo will + be relative to that instead being absolute. + + If the pen has an "arcTo" method, it is called with the original values + of the elliptical arc curve commands: + + .. code-block:: + + pen.arcTo(rx, ry, rotation, arc_large, arc_sweep, (x, y)) + + Otherwise, the arcs are approximated by series of cubic Bezier segments + ("curveTo"), one every 90 degrees. + """ + # In the SVG specs, initial movetos are absolute, even if + # specified as 'm'. This is the default behavior here as well. + # But if you pass in a current_pos variable, the initial moveto + # will be relative to that current_pos. This is useful. + current_pos = complex(*current_pos) + + elements = list(_tokenize_path(pathdef)) + # Reverse for easy use of .pop() + elements.reverse() + + # A path data segment (if there is one) must begin with a moveto + # command (https://www.w3.org/TR/SVG11/paths.html#PathDataMovetoCommands); + # raise before any pen call instead of inventing a start point. + if elements and elements[-1] not in ("M", "m"): + raise ValueError("Path must start with a moveto command: %r" % pathdef) + + # start_pos is the initial point of the current subpath; it is retained + # after a closepath so that a drawto command following Z can start a new + # subpath at that same point, while subpath_open tracks whether there is + # a subpath in progress that still needs closePath/endPath. + start_pos = None + subpath_open = False + command = None + last_control = None + + have_arcTo = hasattr(pen, "arcTo") + + while elements: + if elements[-1] in COMMANDS: + # New command. + last_command = command # Used by S and T + command = elements.pop() + absolute = command in UPPERCASE + command = command.upper() + else: + # If this element starts with numbers, it is an implicit command + # and we don't change the command. Check that it's allowed: + if command is None: + raise ValueError( + "Unallowed implicit command in %s, position %s" + % (pathdef, len(pathdef.split()) - len(elements)) + ) + last_command = command # Used by S and T + + if command not in ("M", "Z") and not subpath_open and start_pos is not None: + # If a closepath is followed immediately by any other command, + # the next subpath starts at the same initial point as the + # current subpath: + # https://www.w3.org/TR/SVG11/paths.html#PathDataClosePathCommand + pen.moveTo((start_pos.real, start_pos.imag)) + subpath_open = True + + if command == "M": + # Moveto command. + x = elements.pop() + y = elements.pop() + pos = float(x) + float(y) * 1j + if absolute: + current_pos = pos + else: + current_pos += pos + + # M is not preceded by Z; it's an open subpath + if subpath_open: + pen.endPath() + + pen.moveTo((current_pos.real, current_pos.imag)) + + # when M is called, reset start_pos + # This behavior of Z is defined in svg spec: + # http://www.w3.org/TR/SVG/paths.html#PathDataClosePathCommand + start_pos = current_pos + subpath_open = True + + # Implicit moveto commands are treated as lineto commands. + # So we set command to lineto here, in case there are + # further implicit commands after this moveto. + command = "L" + + elif command == "Z": + # Close path + # A redundant Z with no open subpath (e.g. "M0,0 Z Z") is valid + # per the SVG path grammar and has no effect; ignore it instead + # of emitting a second closePath. + if subpath_open: + if not cmath.isclose( + current_pos, start_pos, rel_tol=1e-15, abs_tol=1e-15 + ): + pen.lineTo((start_pos.real, start_pos.imag)) + pen.closePath() + current_pos = start_pos + subpath_open = False + command = None # You can't have implicit commands after closing. + + elif command == "L": + x = elements.pop() + y = elements.pop() + pos = float(x) + float(y) * 1j + if not absolute: + pos += current_pos + pen.lineTo((pos.real, pos.imag)) + current_pos = pos + + elif command == "H": + x = elements.pop() + pos = float(x) + current_pos.imag * 1j + if not absolute: + pos += current_pos.real + pen.lineTo((pos.real, pos.imag)) + current_pos = pos + + elif command == "V": + y = elements.pop() + pos = current_pos.real + float(y) * 1j + if not absolute: + pos += current_pos.imag * 1j + pen.lineTo((pos.real, pos.imag)) + current_pos = pos + + elif command == "C": + control1 = float(elements.pop()) + float(elements.pop()) * 1j + control2 = float(elements.pop()) + float(elements.pop()) * 1j + end = float(elements.pop()) + float(elements.pop()) * 1j + + if not absolute: + control1 += current_pos + control2 += current_pos + end += current_pos + + pen.curveTo( + (control1.real, control1.imag), + (control2.real, control2.imag), + (end.real, end.imag), + ) + current_pos = end + last_control = control2 + + elif command == "S": + # Smooth curve. First control point is the "reflection" of + # the second control point in the previous path. + + # last_command is None right after a closepath (Z is not C/S) + if last_command not in ("C", "S"): + # If there is no previous command or if the previous command + # was not an C, c, S or s, assume the first control point is + # coincident with the current point. + control1 = current_pos + else: + # The first control point is assumed to be the reflection of + # the second control point on the previous command relative + # to the current point. + control1 = current_pos + current_pos - last_control + + control2 = float(elements.pop()) + float(elements.pop()) * 1j + end = float(elements.pop()) + float(elements.pop()) * 1j + + if not absolute: + control2 += current_pos + end += current_pos + + pen.curveTo( + (control1.real, control1.imag), + (control2.real, control2.imag), + (end.real, end.imag), + ) + current_pos = end + last_control = control2 + + elif command == "Q": + control = float(elements.pop()) + float(elements.pop()) * 1j + end = float(elements.pop()) + float(elements.pop()) * 1j + + if not absolute: + control += current_pos + end += current_pos + + pen.qCurveTo((control.real, control.imag), (end.real, end.imag)) + current_pos = end + last_control = control + + elif command == "T": + # Smooth curve. Control point is the "reflection" of + # the second control point in the previous path. + + # last_command is None right after a closepath (Z is not Q/T) + if last_command not in ("Q", "T"): + # If there is no previous command or if the previous command + # was not an Q, q, T or t, assume the first control point is + # coincident with the current point. + control = current_pos + else: + # The control point is assumed to be the reflection of + # the control point on the previous command relative + # to the current point. + control = current_pos + current_pos - last_control + + end = float(elements.pop()) + float(elements.pop()) * 1j + + if not absolute: + end += current_pos + + pen.qCurveTo((control.real, control.imag), (end.real, end.imag)) + current_pos = end + last_control = control + + elif command == "A": + rx = abs(float(elements.pop())) + ry = abs(float(elements.pop())) + rotation = float(elements.pop()) + arc_large = bool(int(elements.pop())) + arc_sweep = bool(int(elements.pop())) + end = float(elements.pop()) + float(elements.pop()) * 1j + + if not absolute: + end += current_pos + + # if the pen supports arcs, pass the values unchanged, otherwise + # approximate the arc with a series of cubic bezier curves + if have_arcTo: + pen.arcTo( + rx, + ry, + rotation, + arc_large, + arc_sweep, + (end.real, end.imag), + ) + else: + arc = arc_class( + current_pos, rx, ry, rotation, arc_large, arc_sweep, end + ) + arc.draw(pen) + + current_pos = end + + # no final Z command, it's an open path + if subpath_open: + pen.endPath() diff --git a/.venv/lib/python3.12/site-packages/fontTools/svgLib/path/shapes.py b/.venv/lib/python3.12/site-packages/fontTools/svgLib/path/shapes.py new file mode 100644 index 0000000000000000000000000000000000000000..112d17fd4eaae885f82dd2ef85e3024215655531 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/svgLib/path/shapes.py @@ -0,0 +1,185 @@ +import re + + +def _prefer_non_zero(*args): + for arg in args: + if arg != 0: + return arg + return 0.0 + + +def _ntos(n): + # %f likes to add unnecessary 0's, %g isn't consistent about # decimals + return ("%.3f" % n).rstrip("0").rstrip(".") + + +def _strip_xml_ns(tag): + # ElementTree API doesn't provide a way to ignore XML namespaces in tags + # so we here strip them ourselves: cf. https://bugs.python.org/issue18304 + return tag.split("}", 1)[1] if "}" in tag else tag + + +def _transform(raw_value): + # TODO assumes a 'matrix' transform. + # No other transform functions are supported at the moment. + # https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform + # start simple: if you aren't exactly matrix(...) then no love + match = re.match(r"matrix\((.*)\)", raw_value) + if not match: + raise NotImplementedError + matrix = tuple(float(p) for p in re.split(r"\s+|,", match.group(1))) + if len(matrix) != 6: + raise ValueError("wrong # of terms in %s" % raw_value) + return matrix + + +class PathBuilder(object): + def __init__(self): + self.paths = [] + self.transforms = [] + + def _start_path(self, initial_path=""): + self.paths.append(initial_path) + self.transforms.append(None) + + def _end_path(self): + self._add("z") + + def _add(self, path_snippet): + path = self.paths[-1] + if path: + path += " " + path_snippet + else: + path = path_snippet + self.paths[-1] = path + + def _move(self, c, x, y): + self._add("%s%s,%s" % (c, _ntos(x), _ntos(y))) + + def M(self, x, y): + self._move("M", x, y) + + def m(self, x, y): + self._move("m", x, y) + + def _arc(self, c, rx, ry, x, y, large_arc): + self._add( + "%s%s,%s 0 %d 1 %s,%s" + % (c, _ntos(rx), _ntos(ry), large_arc, _ntos(x), _ntos(y)) + ) + + def A(self, rx, ry, x, y, large_arc=0): + self._arc("A", rx, ry, x, y, large_arc) + + def a(self, rx, ry, x, y, large_arc=0): + self._arc("a", rx, ry, x, y, large_arc) + + def _vhline(self, c, x): + self._add("%s%s" % (c, _ntos(x))) + + def H(self, x): + self._vhline("H", x) + + def h(self, x): + self._vhline("h", x) + + def V(self, y): + self._vhline("V", y) + + def v(self, y): + self._vhline("v", y) + + def _line(self, c, x, y): + self._add("%s%s,%s" % (c, _ntos(x), _ntos(y))) + + def L(self, x, y): + self._line("L", x, y) + + def l(self, x, y): + self._line("l", x, y) + + def _parse_line(self, line): + x1 = float(line.attrib.get("x1", 0)) + y1 = float(line.attrib.get("y1", 0)) + x2 = float(line.attrib.get("x2", 0)) + y2 = float(line.attrib.get("y2", 0)) + + self._start_path() + self.M(x1, y1) + self.L(x2, y2) + + def _parse_rect(self, rect): + x = float(rect.attrib.get("x", 0)) + y = float(rect.attrib.get("y", 0)) + w = float(rect.attrib.get("width")) + h = float(rect.attrib.get("height")) + rx = float(rect.attrib.get("rx", 0)) + ry = float(rect.attrib.get("ry", 0)) + + rx = _prefer_non_zero(rx, ry) + ry = _prefer_non_zero(ry, rx) + # TODO there are more rules for adjusting rx, ry + + self._start_path() + self.M(x + rx, y) + self.H(x + w - rx) + if rx > 0: + self.A(rx, ry, x + w, y + ry) + self.V(y + h - ry) + if rx > 0: + self.A(rx, ry, x + w - rx, y + h) + self.H(x + rx) + if rx > 0: + self.A(rx, ry, x, y + h - ry) + self.V(y + ry) + if rx > 0: + self.A(rx, ry, x + rx, y) + self._end_path() + + def _parse_path(self, path): + if "d" in path.attrib: + self._start_path(initial_path=path.attrib["d"]) + + def _parse_polygon(self, poly): + if "points" in poly.attrib: + self._start_path("M" + poly.attrib["points"]) + self._end_path() + + def _parse_polyline(self, poly): + if "points" in poly.attrib: + self._start_path("M" + poly.attrib["points"]) + + def _parse_circle(self, circle): + cx = float(circle.attrib.get("cx", 0)) + cy = float(circle.attrib.get("cy", 0)) + r = float(circle.attrib.get("r")) + + # arc doesn't seem to like being a complete shape, draw two halves + self._start_path() + self.M(cx - r, cy) + self.A(r, r, cx + r, cy, large_arc=1) + self.A(r, r, cx - r, cy, large_arc=1) + + def _parse_ellipse(self, ellipse): + cx = float(ellipse.attrib.get("cx", 0)) + cy = float(ellipse.attrib.get("cy", 0)) + rx = float(ellipse.attrib.get("rx")) + ry = float(ellipse.attrib.get("ry")) + + # arc doesn't seem to like being a complete shape, draw two halves + self._start_path() + self.M(cx - rx, cy) + self.A(rx, ry, cx + rx, cy, large_arc=1) + self.A(rx, ry, cx - rx, cy, large_arc=1) + + def add_path_from_element(self, el): + if not isinstance(el.tag, str): + return False + tag = _strip_xml_ns(el.tag) + parse_fn = getattr(self, "_parse_%s" % tag.lower(), None) + if not callable(parse_fn): + return False + parse_fn(el) + if "transform" in el.attrib: + self.transforms[-1] = _transform(el.attrib["transform"]) + return True diff --git a/.venv/lib/python3.12/site-packages/fontTools/t1Lib/__init__.py b/.venv/lib/python3.12/site-packages/fontTools/t1Lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fa51a27f69f04f69cb30e9ef33ca1a709d0d61ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/t1Lib/__init__.py @@ -0,0 +1,648 @@ +"""fontTools.t1Lib.py -- Tools for PostScript Type 1 fonts. + +Functions for reading and writing raw Type 1 data: + +read(path) + reads any Type 1 font file, returns the raw data and a type indicator: + 'LWFN', 'PFB' or 'OTHER', depending on the format of the file pointed + to by 'path'. + Raises an error when the file does not contain valid Type 1 data. + +write(path, data, kind='OTHER', dohex=False) + writes raw Type 1 data to the file pointed to by 'path'. + 'kind' can be one of 'LWFN', 'PFB' or 'OTHER'; it defaults to 'OTHER'. + 'dohex' is a flag which determines whether the eexec encrypted + part should be written as hexadecimal or binary, but only if kind + is 'OTHER'. +""" + +import fontTools +from fontTools.misc import eexec +from fontTools.misc.macCreatorType import getMacCreatorAndType +from fontTools.misc.textTools import bytechr, byteord, bytesjoin, tobytes +from fontTools.misc.psOperators import ( + _type1_pre_eexec_order, + _type1_fontinfo_order, + _type1_post_eexec_order, +) +from fontTools.encodings.StandardEncoding import StandardEncoding +import os +import re + +__author__ = "jvr" +__version__ = "1.0b3" +DEBUG = 0 + + +try: + try: + from Carbon import Res + except ImportError: + import Res # MacPython < 2.2 +except ImportError: + haveMacSupport = 0 +else: + haveMacSupport = 1 + + +class T1Error(Exception): + pass + + +class T1Font(object): + """Type 1 font class. + + Uses a minimal interpeter that supports just about enough PS to parse + Type 1 fonts. + """ + + def __init__(self, path, encoding="ascii", kind=None): + if kind is None: + self.data, _ = read(path) + elif kind == "LWFN": + self.data = readLWFN(path) + elif kind == "PFB": + self.data = readPFB(path) + elif kind == "OTHER": + self.data = readOther(path) + else: + raise ValueError(kind) + self.encoding = encoding + + def saveAs(self, path, type, dohex=False): + write(path, self.getData(), type, dohex) + + def getData(self): + if not hasattr(self, "data"): + self.data = self.createData() + return self.data + + def getGlyphSet(self): + """Return a generic GlyphSet, which is a dict-like object + mapping glyph names to glyph objects. The returned glyph objects + have a .draw() method that supports the Pen protocol, and will + have an attribute named 'width', but only *after* the .draw() method + has been called. + + In the case of Type 1, the GlyphSet is simply the CharStrings dict. + """ + return self["CharStrings"] + + def __getitem__(self, key): + if not hasattr(self, "font"): + self.parse() + return self.font[key] + + def parse(self): + from fontTools.misc import psLib + from fontTools.misc import psCharStrings + + self.font = psLib.suckfont(self.data, self.encoding) + charStrings = self.font["CharStrings"] + lenIV = self.font["Private"].get("lenIV", 4) + assert lenIV >= 0 + subrs = self.font["Private"]["Subrs"] + for glyphName, charString in charStrings.items(): + charString, R = eexec.decrypt(charString, 4330) + charStrings[glyphName] = psCharStrings.T1CharString( + charString[lenIV:], subrs=subrs + ) + for i in range(len(subrs)): + charString, R = eexec.decrypt(subrs[i], 4330) + subrs[i] = psCharStrings.T1CharString(charString[lenIV:], subrs=subrs) + del self.data + + def createData(self): + sf = self.font + + eexec_began = False + eexec_dict = {} + lines = [] + lines.extend( + [ + self._tobytes(f"%!FontType1-1.1: {sf['FontName']}"), + self._tobytes(f"%t1Font: ({fontTools.version})"), + self._tobytes(f"%%BeginResource: font {sf['FontName']}"), + ] + ) + # follow t1write.c:writeRegNameKeyedFont + size = 3 # Headroom for new key addition + size += 1 # FontMatrix is always counted + size += 1 + 1 # Private, CharStings + for key in font_dictionary_keys: + size += int(key in sf) + lines.append(self._tobytes(f"{size} dict dup begin")) + + for key, value in sf.items(): + if eexec_began: + eexec_dict[key] = value + continue + + if key == "FontInfo": + fi = sf["FontInfo"] + # follow t1write.c:writeFontInfoDict + size = 3 # Headroom for new key addition + for subkey in FontInfo_dictionary_keys: + size += int(subkey in fi) + lines.append(self._tobytes(f"/FontInfo {size} dict dup begin")) + + for subkey, subvalue in fi.items(): + lines.extend(self._make_lines(subkey, subvalue)) + lines.append(b"end def") + elif key in _type1_post_eexec_order: # usually 'Private' + eexec_dict[key] = value + eexec_began = True + else: + lines.extend(self._make_lines(key, value)) + lines.append(b"end") + eexec_portion = self.encode_eexec(eexec_dict) + lines.append(bytesjoin([b"currentfile eexec ", eexec_portion])) + + for _ in range(8): + lines.append(self._tobytes("0" * 64)) + lines.extend([b"cleartomark", b"%%EndResource", b"%%EOF"]) + + data = bytesjoin(lines, "\n") + return data + + def encode_eexec(self, eexec_dict): + lines = [] + + # '-|', '|-', '|' + RD_key, ND_key, NP_key = None, None, None + lenIV = 4 + subrs = std_subrs + + # Ensure we look at Private first, because we need RD_key, ND_key, NP_key and lenIV + sortedItems = sorted(eexec_dict.items(), key=lambda item: item[0] != "Private") + + for key, value in sortedItems: + if key == "Private": + pr = eexec_dict["Private"] + # follow t1write.c:writePrivateDict + size = 3 # for RD, ND, NP + for subkey in Private_dictionary_keys: + size += int(subkey in pr) + lines.append(b"dup /Private") + lines.append(self._tobytes(f"{size} dict dup begin")) + for subkey, subvalue in pr.items(): + if not RD_key and subvalue == RD_value: + RD_key = subkey + elif not ND_key and subvalue in ND_values: + ND_key = subkey + elif not NP_key and subvalue in PD_values: + NP_key = subkey + + if subkey == "lenIV": + lenIV = subvalue + + if subkey == "OtherSubrs": + # XXX: assert that no flex hint is used + lines.append(self._tobytes(hintothers)) + elif subkey == "Subrs": + for subr_bin in subvalue: + subr_bin.compile() + subrs = [subr_bin.bytecode for subr_bin in subvalue] + lines.append(f"/Subrs {len(subrs)} array".encode("ascii")) + for i, subr_bin in enumerate(subrs): + encrypted_subr, R = eexec.encrypt( + bytesjoin([char_IV[:lenIV], subr_bin]), 4330 + ) + lines.append( + bytesjoin( + [ + self._tobytes( + f"dup {i} {len(encrypted_subr)} {RD_key} " + ), + encrypted_subr, + self._tobytes(f" {NP_key}"), + ] + ) + ) + lines.append(b"def") + + lines.append(b"put") + else: + lines.extend(self._make_lines(subkey, subvalue)) + elif key == "CharStrings": + lines.append(b"dup /CharStrings") + lines.append( + self._tobytes(f"{len(eexec_dict['CharStrings'])} dict dup begin") + ) + for glyph_name, char_bin in eexec_dict["CharStrings"].items(): + char_bin.compile() + encrypted_char, R = eexec.encrypt( + bytesjoin([char_IV[:lenIV], char_bin.bytecode]), 4330 + ) + lines.append( + bytesjoin( + [ + self._tobytes( + f"/{glyph_name} {len(encrypted_char)} {RD_key} " + ), + encrypted_char, + self._tobytes(f" {ND_key}"), + ] + ) + ) + lines.append(b"end put") + else: + lines.extend(self._make_lines(key, value)) + + lines.extend( + [ + b"end", + b"dup /FontName get exch definefont pop", + b"mark", + b"currentfile closefile\n", + ] + ) + + eexec_portion = bytesjoin(lines, "\n") + encrypted_eexec, R = eexec.encrypt(bytesjoin([eexec_IV, eexec_portion]), 55665) + + return encrypted_eexec + + def _make_lines(self, key, value): + if key == "FontName": + return [self._tobytes(f"/{key} /{value} def")] + if key in ["isFixedPitch", "ForceBold", "RndStemUp"]: + return [self._tobytes(f"/{key} {'true' if value else 'false'} def")] + elif key == "Encoding": + if value == StandardEncoding: + return [self._tobytes(f"/{key} StandardEncoding def")] + else: + # follow fontTools.misc.psOperators._type1_Encoding_repr + lines = [] + lines.append(b"/Encoding 256 array") + lines.append(b"0 1 255 {1 index exch /.notdef put} for") + for i in range(256): + name = value[i] + if name != ".notdef": + lines.append(self._tobytes(f"dup {i} /{name} put")) + lines.append(b"def") + return lines + if isinstance(value, str): + return [self._tobytes(f"/{key} ({value}) def")] + elif isinstance(value, bool): + return [self._tobytes(f"/{key} {'true' if value else 'false'} def")] + elif isinstance(value, list): + return [self._tobytes(f"/{key} [{' '.join(str(v) for v in value)}] def")] + elif isinstance(value, tuple): + return [self._tobytes(f"/{key} {{{' '.join(str(v) for v in value)}}} def")] + else: + return [self._tobytes(f"/{key} {value} def")] + + def _tobytes(self, s, errors="strict"): + return tobytes(s, self.encoding, errors) + + +# low level T1 data read and write functions + + +def read(path, onlyHeader=False): + """reads any Type 1 font file, returns raw data""" + _, ext = os.path.splitext(path) + ext = ext.lower() + creator, typ = getMacCreatorAndType(path) + if typ == "LWFN": + return readLWFN(path, onlyHeader), "LWFN" + if ext == ".pfb": + return readPFB(path, onlyHeader), "PFB" + else: + return readOther(path), "OTHER" + + +def write(path, data, kind="OTHER", dohex=False): + assertType1(data) + kind = kind.upper() + try: + os.remove(path) + except os.error: + pass + err = 1 + try: + if kind == "LWFN": + writeLWFN(path, data) + elif kind == "PFB": + writePFB(path, data) + else: + writeOther(path, data, dohex) + err = 0 + finally: + if err and not DEBUG: + try: + os.remove(path) + except os.error: + pass + + +# -- internal -- + +LWFNCHUNKSIZE = 2000 +HEXLINELENGTH = 80 + + +def readLWFN(path, onlyHeader=False): + """reads an LWFN font file, returns raw data""" + from fontTools.misc.macRes import ResourceReader + + reader = ResourceReader(path) + try: + data = [] + for res in reader.get("POST", []): + code = byteord(res.data[0]) + if byteord(res.data[1]) != 0: + raise T1Error("corrupt LWFN file") + if code in [1, 2]: + if onlyHeader and code == 2: + break + data.append(res.data[2:]) + elif code in [3, 5]: + break + elif code == 4: + with open(path, "rb") as f: + data.append(f.read()) + elif code == 0: + pass # comment, ignore + else: + raise T1Error("bad chunk code: " + repr(code)) + finally: + reader.close() + data = bytesjoin(data) + assertType1(data) + return data + + +def readPFB(path, onlyHeader=False): + """reads a PFB font file, returns raw data""" + data = [] + with open(path, "rb") as f: + while True: + if f.read(1) != bytechr(128): + raise T1Error("corrupt PFB file") + code = byteord(f.read(1)) + if code in [1, 2]: + chunklen = stringToLong(f.read(4)) + chunk = f.read(chunklen) + assert len(chunk) == chunklen + data.append(chunk) + elif code == 3: + break + else: + raise T1Error("bad chunk code: " + repr(code)) + if onlyHeader: + break + data = bytesjoin(data) + assertType1(data) + return data + + +def readOther(path): + """reads any (font) file, returns raw data""" + with open(path, "rb") as f: + data = f.read() + assertType1(data) + chunks = findEncryptedChunks(data) + data = [] + for isEncrypted, chunk in chunks: + if isEncrypted and isHex(chunk[:4]): + data.append(deHexString(chunk)) + else: + data.append(chunk) + return bytesjoin(data) + + +# file writing tools + + +def writeLWFN(path, data): + # Res.FSpCreateResFile was deprecated in OS X 10.5 + Res.FSpCreateResFile(path, "just", "LWFN", 0) + resRef = Res.FSOpenResFile(path, 2) # write-only + try: + Res.UseResFile(resRef) + resID = 501 + chunks = findEncryptedChunks(data) + for isEncrypted, chunk in chunks: + if isEncrypted: + code = 2 + else: + code = 1 + while chunk: + res = Res.Resource(bytechr(code) + "\0" + chunk[: LWFNCHUNKSIZE - 2]) + res.AddResource("POST", resID, "") + chunk = chunk[LWFNCHUNKSIZE - 2 :] + resID = resID + 1 + res = Res.Resource(bytechr(5) + "\0") + res.AddResource("POST", resID, "") + finally: + Res.CloseResFile(resRef) + + +def writePFB(path, data): + chunks = findEncryptedChunks(data) + with open(path, "wb") as f: + for isEncrypted, chunk in chunks: + if isEncrypted: + code = 2 + else: + code = 1 + f.write(bytechr(128) + bytechr(code)) + f.write(longToString(len(chunk))) + f.write(chunk) + f.write(bytechr(128) + bytechr(3)) + + +def writeOther(path, data, dohex=False): + chunks = findEncryptedChunks(data) + with open(path, "wb") as f: + hexlinelen = HEXLINELENGTH // 2 + for isEncrypted, chunk in chunks: + if isEncrypted: + code = 2 + else: + code = 1 + if code == 2 and dohex: + while chunk: + f.write(eexec.hexString(chunk[:hexlinelen])) + f.write(b"\r") + chunk = chunk[hexlinelen:] + else: + f.write(chunk) + + +# decryption tools + +EEXECBEGIN = b"currentfile eexec" +# The spec allows for 512 ASCII zeros interrupted by arbitrary whitespace to +# follow eexec +EEXECEND = re.compile(b"(0[ \t\r\n]*){512}", flags=re.M) +EEXECINTERNALEND = b"currentfile closefile" +EEXECBEGINMARKER = b"%-- eexec start\r" +EEXECENDMARKER = b"%-- eexec end\r" + +_ishexRE = re.compile(b"[0-9A-Fa-f]*$") + + +def isHex(text): + return _ishexRE.match(text) is not None + + +def decryptType1(data): + chunks = findEncryptedChunks(data) + data = [] + for isEncrypted, chunk in chunks: + if isEncrypted: + if isHex(chunk[:4]): + chunk = deHexString(chunk) + decrypted, R = eexec.decrypt(chunk, 55665) + decrypted = decrypted[4:] + if ( + decrypted[-len(EEXECINTERNALEND) - 1 : -1] != EEXECINTERNALEND + and decrypted[-len(EEXECINTERNALEND) - 2 : -2] != EEXECINTERNALEND + ): + raise T1Error("invalid end of eexec part") + decrypted = decrypted[: -len(EEXECINTERNALEND) - 2] + b"\r" + data.append(EEXECBEGINMARKER + decrypted + EEXECENDMARKER) + else: + if chunk[-len(EEXECBEGIN) - 1 : -1] == EEXECBEGIN: + data.append(chunk[: -len(EEXECBEGIN) - 1]) + else: + data.append(chunk) + return bytesjoin(data) + + +def findEncryptedChunks(data): + chunks = [] + while True: + eBegin = data.find(EEXECBEGIN) + if eBegin < 0: + break + eBegin = eBegin + len(EEXECBEGIN) + 1 + endMatch = EEXECEND.search(data, eBegin) + if endMatch is None: + raise T1Error("can't find end of eexec part") + eEnd = endMatch.start() + cypherText = data[eBegin : eEnd + 2] + if isHex(cypherText[:4]): + cypherText = deHexString(cypherText) + plainText, R = eexec.decrypt(cypherText, 55665) + eEndLocal = plainText.find(EEXECINTERNALEND) + if eEndLocal < 0: + raise T1Error("can't find end of eexec part") + chunks.append((0, data[:eBegin])) + chunks.append((1, cypherText[: eEndLocal + len(EEXECINTERNALEND) + 1])) + data = data[eEnd:] + chunks.append((0, data)) + return chunks + + +def deHexString(hexstring): + return eexec.deHexString(bytesjoin(hexstring.split())) + + +# Type 1 assertion + +_fontType1RE = re.compile(rb"/FontType\s+1\s+def") + + +def assertType1(data): + for head in [b"%!PS-AdobeFont", b"%!FontType1"]: + if data[: len(head)] == head: + break + else: + raise T1Error("not a PostScript font") + if not _fontType1RE.search(data): + raise T1Error("not a Type 1 font") + if data.find(b"currentfile eexec") < 0: + raise T1Error("not an encrypted Type 1 font") + # XXX what else? + return data + + +# pfb helpers + + +def longToString(long): + s = b"" + for i in range(4): + s += bytechr((long & (0xFF << (i * 8))) >> i * 8) + return s + + +def stringToLong(s): + if len(s) != 4: + raise ValueError("string must be 4 bytes long") + l = 0 + for i in range(4): + l += byteord(s[i]) << (i * 8) + return l + + +# PS stream helpers + +font_dictionary_keys = list(_type1_pre_eexec_order) +# t1write.c:writeRegNameKeyedFont +# always counts following keys +font_dictionary_keys.remove("FontMatrix") + +FontInfo_dictionary_keys = list(_type1_fontinfo_order) +# extend because AFDKO tx may use following keys +FontInfo_dictionary_keys.extend( + [ + "FSType", + "Copyright", + ] +) + +Private_dictionary_keys = [ + # We don't know what names will be actually used. + # "RD", + # "ND", + # "NP", + "Subrs", + "OtherSubrs", + "UniqueID", + "BlueValues", + "OtherBlues", + "FamilyBlues", + "FamilyOtherBlues", + "BlueScale", + "BlueShift", + "BlueFuzz", + "StdHW", + "StdVW", + "StemSnapH", + "StemSnapV", + "ForceBold", + "LanguageGroup", + "password", + "lenIV", + "MinFeature", + "RndStemUp", +] + +# t1write_hintothers.h +hintothers = """/OtherSubrs[{}{}{}{systemdict/internaldict known not{pop 3}{1183615869 +systemdict/internaldict get exec dup/startlock known{/startlock get exec}{dup +/strtlck known{/strtlck get exec}{pop 3}ifelse}ifelse}ifelse}executeonly]def""" +# t1write.c:saveStdSubrs +std_subrs = [ + # 3 0 callother pop pop setcurrentpoint return + b"\x8e\x8b\x0c\x10\x0c\x11\x0c\x11\x0c\x21\x0b", + # 0 1 callother return + b"\x8b\x8c\x0c\x10\x0b", + # 0 2 callother return + b"\x8b\x8d\x0c\x10\x0b", + # return + b"\x0b", + # 3 1 3 callother pop callsubr return + b"\x8e\x8c\x8e\x0c\x10\x0c\x11\x0a\x0b", +] +# follow t1write.c:writeRegNameKeyedFont +eexec_IV = b"cccc" +char_IV = b"\x0c\x0c\x0c\x0c" +RD_value = ("string", "currentfile", "exch", "readstring", "pop") +ND_values = [("def",), ("noaccess", "def")] +PD_values = [("put",), ("noaccess", "put")] diff --git a/.venv/lib/python3.12/site-packages/fontTools/t1Lib/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/t1Lib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fa7e0e59f706bf70fd9b2b63cb1c06fc5358c73 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/t1Lib/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/tfmLib.py b/.venv/lib/python3.12/site-packages/fontTools/tfmLib.py new file mode 100644 index 0000000000000000000000000000000000000000..884a099b57066d2e2bb7418bc3779faa68060117 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/tfmLib.py @@ -0,0 +1,460 @@ +"""Module for reading TFM (TeX Font Metrics) files. + +The TFM format is described in the TFtoPL WEB source code, whose typeset form +can be found on `CTAN `_. + + >>> from fontTools.tfmLib import TFM + >>> tfm = TFM("Tests/tfmLib/data/cmr10.tfm") + >>> + >>> # Accessing an attribute gets you metadata. + >>> tfm.checksum + 1274110073 + >>> tfm.designsize + 10.0 + >>> tfm.codingscheme + 'TeX text' + >>> tfm.family + 'CMR' + >>> tfm.seven_bit_safe_flag + False + >>> tfm.face + 234 + >>> tfm.extraheader + {} + >>> tfm.fontdimens + {'SLANT': 0.0, 'SPACE': 0.33333396911621094, 'STRETCH': 0.16666698455810547, 'SHRINK': 0.11111164093017578, 'XHEIGHT': 0.4305553436279297, 'QUAD': 1.0000028610229492, 'EXTRASPACE': 0.11111164093017578} + >>> # Accessing a character gets you its metrics. + >>> # “width” is always available, other metrics are available only when + >>> # applicable. All values are relative to “designsize”. + >>> tfm.chars[ord("g")] + {'width': 0.5000019073486328, 'height': 0.4305553436279297, 'depth': 0.1944446563720703, 'italic': 0.013888359069824219} + >>> # Kerning and ligature can be accessed as well. + >>> tfm.kerning[ord("c")] + {104: -0.02777862548828125, 107: -0.02777862548828125} + >>> tfm.ligatures[ord("f")] + {105: ('LIG', 12), 102: ('LIG', 11), 108: ('LIG', 13)} +""" + +from types import SimpleNamespace + +from fontTools.misc.sstruct import calcsize, unpack, unpack2 + +SIZES_FORMAT = """ + > + lf: h # length of the entire file, in words + lh: h # length of the header data, in words + bc: h # smallest character code in the font + ec: h # largest character code in the font + nw: h # number of words in the width table + nh: h # number of words in the height table + nd: h # number of words in the depth table + ni: h # number of words in the italic correction table + nl: h # number of words in the ligature/kern table + nk: h # number of words in the kern table + ne: h # number of words in the extensible character table + np: h # number of font parameter words +""" + +SIZES_SIZE = calcsize(SIZES_FORMAT) + +FIXED_FORMAT = "12.20F" + +HEADER_FORMAT1 = f""" + > + checksum: L + designsize: {FIXED_FORMAT} +""" + +HEADER_FORMAT2 = f""" + {HEADER_FORMAT1} + codingscheme: 40p +""" + +HEADER_FORMAT3 = f""" + {HEADER_FORMAT2} + family: 20p +""" + +HEADER_FORMAT4 = f""" + {HEADER_FORMAT3} + seven_bit_safe_flag: ? + ignored: x + ignored: x + face: B +""" + +HEADER_SIZE1 = calcsize(HEADER_FORMAT1) +HEADER_SIZE2 = calcsize(HEADER_FORMAT2) +HEADER_SIZE3 = calcsize(HEADER_FORMAT3) +HEADER_SIZE4 = calcsize(HEADER_FORMAT4) + +LIG_KERN_COMMAND = """ + > + skip_byte: B + next_char: B + op_byte: B + remainder: B +""" + +BASE_PARAMS = [ + "SLANT", + "SPACE", + "STRETCH", + "SHRINK", + "XHEIGHT", + "QUAD", + "EXTRASPACE", +] + +MATHSY_PARAMS = [ + "NUM1", + "NUM2", + "NUM3", + "DENOM1", + "DENOM2", + "SUP1", + "SUP2", + "SUP3", + "SUB1", + "SUB2", + "SUPDROP", + "SUBDROP", + "DELIM1", + "DELIM2", + "AXISHEIGHT", +] + +MATHEX_PARAMS = [ + "DEFAULTRULETHICKNESS", + "BIGOPSPACING1", + "BIGOPSPACING2", + "BIGOPSPACING3", + "BIGOPSPACING4", + "BIGOPSPACING5", +] + +VANILLA = 0 +MATHSY = 1 +MATHEX = 2 + +UNREACHABLE = 0 +PASSTHROUGH = 1 +ACCESSABLE = 2 + +NO_TAG = 0 +LIG_TAG = 1 +LIST_TAG = 2 +EXT_TAG = 3 + +STOP_FLAG = 128 +KERN_FLAG = 128 + + +class TFMException(Exception): + def __init__(self, message): + super().__init__(message) + + +class TFM: + def __init__(self, file): + self._read(file) + + def __repr__(self): + return ( + f"" + ) + + def _read(self, file): + if hasattr(file, "read"): + data = file.read() + else: + with open(file, "rb") as fp: + data = fp.read() + + self._data = data + + if len(data) < SIZES_SIZE: + raise TFMException("Too short input file") + + sizes = SimpleNamespace() + unpack2(SIZES_FORMAT, data, sizes) + + # Do some file structure sanity checks. + # TeX and TFtoPL do additional functional checks and might even correct + # “errors” in the input file, but we instead try to output the file as + # it is as long as it is parsable, even if the data make no sense. + + if sizes.lf < 0: + raise TFMException("The file claims to have negative or zero length!") + + if len(data) < sizes.lf * 4: + raise TFMException("The file has fewer bytes than it claims!") + + for name, length in vars(sizes).items(): + if length < 0: + raise TFMException("The subfile size: '{name}' is negative!") + + if sizes.lh < 2: + raise TFMException(f"The header length is only {sizes.lh}!") + + if sizes.bc > sizes.ec + 1 or sizes.ec > 255: + raise TFMException( + f"The character code range {sizes.bc}..{sizes.ec} is illegal!" + ) + + if sizes.nw == 0 or sizes.nh == 0 or sizes.nd == 0 or sizes.ni == 0: + raise TFMException("Incomplete subfiles for character dimensions!") + + if sizes.ne > 256: + raise TFMException(f"There are {ne} extensible recipes!") + + if sizes.lf != ( + 6 + + sizes.lh + + (sizes.ec - sizes.bc + 1) + + sizes.nw + + sizes.nh + + sizes.nd + + sizes.ni + + sizes.nl + + sizes.nk + + sizes.ne + + sizes.np + ): + raise TFMException("Subfile sizes don’t add up to the stated total") + + # Subfile offsets, used in the helper function below. These all are + # 32-bit word offsets not 8-bit byte offsets. + char_base = 6 + sizes.lh - sizes.bc + width_base = char_base + sizes.ec + 1 + height_base = width_base + sizes.nw + depth_base = height_base + sizes.nh + italic_base = depth_base + sizes.nd + lig_kern_base = italic_base + sizes.ni + kern_base = lig_kern_base + sizes.nl + exten_base = kern_base + sizes.nk + param_base = exten_base + sizes.ne + + # Helper functions for accessing individual data. If this looks + # nonidiomatic Python, I blame the effect of reading the literate WEB + # documentation of TFtoPL. + def char_info(c): + return 4 * (char_base + c) + + def width_index(c): + return data[char_info(c)] + + def noneexistent(c): + return c < sizes.bc or c > sizes.ec or width_index(c) == 0 + + def height_index(c): + return data[char_info(c) + 1] // 16 + + def depth_index(c): + return data[char_info(c) + 1] % 16 + + def italic_index(c): + return data[char_info(c) + 2] // 4 + + def tag(c): + return data[char_info(c) + 2] % 4 + + def remainder(c): + return data[char_info(c) + 3] + + def width(c): + r = 4 * (width_base + width_index(c)) + return read_fixed(r, "v")["v"] + + def height(c): + r = 4 * (height_base + height_index(c)) + return read_fixed(r, "v")["v"] + + def depth(c): + r = 4 * (depth_base + depth_index(c)) + return read_fixed(r, "v")["v"] + + def italic(c): + r = 4 * (italic_base + italic_index(c)) + return read_fixed(r, "v")["v"] + + def exten(c): + return 4 * (exten_base + remainder(c)) + + def lig_step(i): + return 4 * (lig_kern_base + i) + + def lig_kern_command(i): + command = SimpleNamespace() + unpack2(LIG_KERN_COMMAND, data[i:], command) + return command + + def kern(i): + r = 4 * (kern_base + i) + return read_fixed(r, "v")["v"] + + def param(i): + return 4 * (param_base + i) + + def read_fixed(index, key, obj=None): + ret = unpack2(f">;{key}:{FIXED_FORMAT}", data[index:], obj) + return ret[0] + + # Set all attributes to empty values regardless of the header size. + unpack(HEADER_FORMAT4, [0] * HEADER_SIZE4, self) + + offset = 24 + length = sizes.lh * 4 + self.extraheader = {} + if length >= HEADER_SIZE4: + rest = unpack2(HEADER_FORMAT4, data[offset:], self)[1] + if self.face < 18: + s = self.face % 2 + b = self.face // 2 + self.face = "MBL"[b % 3] + "RI"[s] + "RCE"[b // 3] + for i in range(sizes.lh - HEADER_SIZE4 // 4): + rest = unpack2(f">;HEADER{i + 18}:l", rest, self.extraheader)[1] + elif length >= HEADER_SIZE3: + unpack2(HEADER_FORMAT3, data[offset:], self) + elif length >= HEADER_SIZE2: + unpack2(HEADER_FORMAT2, data[offset:], self) + elif length >= HEADER_SIZE1: + unpack2(HEADER_FORMAT1, data[offset:], self) + + self.fonttype = VANILLA + scheme = self.codingscheme.upper() + if scheme.startswith("TEX MATH SY"): + self.fonttype = MATHSY + elif scheme.startswith("TEX MATH EX"): + self.fonttype = MATHEX + + self.fontdimens = {} + for i in range(sizes.np): + name = f"PARAMETER{i+1}" + if i <= 6: + name = BASE_PARAMS[i] + elif self.fonttype == MATHSY and i <= 21: + name = MATHSY_PARAMS[i - 7] + elif self.fonttype == MATHEX and i <= 12: + name = MATHEX_PARAMS[i - 7] + read_fixed(param(i), name, self.fontdimens) + + lig_kern_map = {} + self.right_boundary_char = None + self.left_boundary_char = None + if sizes.nl > 0: + cmd = lig_kern_command(lig_step(0)) + if cmd.skip_byte == 255: + self.right_boundary_char = cmd.next_char + + cmd = lig_kern_command(lig_step((sizes.nl - 1))) + if cmd.skip_byte == 255: + self.left_boundary_char = 256 + r = 256 * cmd.op_byte + cmd.remainder + lig_kern_map[self.left_boundary_char] = r + + self.chars = {} + for c in range(sizes.bc, sizes.ec + 1): + if width_index(c) > 0: + self.chars[c] = info = {} + info["width"] = width(c) + if height_index(c) > 0: + info["height"] = height(c) + if depth_index(c) > 0: + info["depth"] = depth(c) + if italic_index(c) > 0: + info["italic"] = italic(c) + char_tag = tag(c) + if char_tag == NO_TAG: + pass + elif char_tag == LIG_TAG: + lig_kern_map[c] = remainder(c) + elif char_tag == LIST_TAG: + info["nextlarger"] = remainder(c) + elif char_tag == EXT_TAG: + info["varchar"] = varchar = {} + for i in range(4): + part = data[exten(c) + i] + if i == 3 or part > 0: + name = "rep" + if i == 0: + name = "top" + elif i == 1: + name = "mid" + elif i == 2: + name = "bot" + if noneexistent(part): + varchar[name] = c + else: + varchar[name] = part + + self.ligatures = {} + self.kerning = {} + for c, i in sorted(lig_kern_map.items()): + cmd = lig_kern_command(lig_step(i)) + if cmd.skip_byte > STOP_FLAG: + i = 256 * cmd.op_byte + cmd.remainder + + while i < sizes.nl: + cmd = lig_kern_command(lig_step(i)) + if cmd.skip_byte > STOP_FLAG: + pass + else: + if cmd.op_byte >= KERN_FLAG: + r = 256 * (cmd.op_byte - KERN_FLAG) + cmd.remainder + self.kerning.setdefault(c, {})[cmd.next_char] = kern(r) + else: + r = cmd.op_byte + if r == 4 or (r > 7 and r != 11): + # Ligature step with nonstandard code, we output + # the code verbatim. + lig = r + else: + lig = "" + if r % 4 > 1: + lig += "/" + lig += "LIG" + if r % 2 != 0: + lig += "/" + while r > 3: + lig += ">" + r -= 4 + self.ligatures.setdefault(c, {})[cmd.next_char] = ( + lig, + cmd.remainder, + ) + + if cmd.skip_byte >= STOP_FLAG: + break + i += cmd.skip_byte + 1 + + +if __name__ == "__main__": + import sys + + tfm = TFM(sys.argv[1]) + print( + "\n".join( + x + for x in [ + f"tfm.checksum={tfm.checksum}", + f"tfm.designsize={tfm.designsize}", + f"tfm.codingscheme={tfm.codingscheme}", + f"tfm.fonttype={tfm.fonttype}", + f"tfm.family={tfm.family}", + f"tfm.seven_bit_safe_flag={tfm.seven_bit_safe_flag}", + f"tfm.face={tfm.face}", + f"tfm.extraheader={tfm.extraheader}", + f"tfm.fontdimens={tfm.fontdimens}", + f"tfm.right_boundary_char={tfm.right_boundary_char}", + f"tfm.left_boundary_char={tfm.left_boundary_char}", + f"tfm.kerning={tfm.kerning}", + f"tfm.ligatures={tfm.ligatures}", + f"tfm.chars={tfm.chars}", + ] + ) + ) + print(tfm) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__init__.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a02e5decec536279971c94c406c811959f0f44f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__init__.py @@ -0,0 +1,29 @@ +"""fontTools.ttLib -- a package for dealing with TrueType fonts.""" + +from fontTools.config import OPTIONS +from fontTools.misc.loggingTools import deprecateFunction +import logging + +log = logging.getLogger(__name__) + + +OPTIMIZE_FONT_SPEED = OPTIONS["fontTools.ttLib:OPTIMIZE_FONT_SPEED"] + + +class TTLibError(Exception): + pass + + +class TTLibFileIsCollectionError(TTLibError): + pass + + +@deprecateFunction("use logging instead", category=DeprecationWarning) +def debugmsg(msg): + import time + + print(msg + time.strftime(" (%H:%M:%S)", time.localtime(time.time()))) + + +from fontTools.ttLib.ttFont import * +from fontTools.ttLib.ttCollection import TTCollection diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__main__.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..720bdb7e7991bd845813684de7a211c650d99174 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__main__.py @@ -0,0 +1,148 @@ +import sys +from fontTools.ttLib import OPTIMIZE_FONT_SPEED, TTLibError, TTLibFileIsCollectionError +from fontTools.ttLib.ttFont import * +from fontTools.ttLib.ttCollection import TTCollection + + +def main(args=None): + """Open/save fonts with TTFont() or TTCollection() + + ./fonttools ttLib [-oFILE] [-yNUMBER] files... + + If multiple files are given on the command-line, + they are each opened (as a font or collection), + and added to the font list. + + If -o (output-file) argument is given, the font + list is then saved to the output file, either as + a single font, if there is only one font, or as + a collection otherwise. + + If -y (font-number) argument is given, only the + specified font from collections is opened. + + The above allow extracting a single font from a + collection, or combining multiple fonts into a + collection. + + If --lazy or --no-lazy are give, those are passed + to the TTFont() or TTCollection() constructors. + """ + from fontTools import configLogger + + if args is None: + args = sys.argv[1:] + + import argparse + + parser = argparse.ArgumentParser( + "fonttools ttLib", + description="Open/save fonts with TTFont() or TTCollection()", + epilog=""" + If multiple files are given on the command-line, + they are each opened (as a font or collection), + and added to the font list. + + The above, when combined with -o / --output, + allows for extracting a single font from a + collection, or combining multiple fonts into a + collection. + """, + ) + parser.add_argument("font", metavar="font", nargs="*", help="Font file.") + parser.add_argument( + "-t", "--table", metavar="table", action="append", help="Tables to decompile." + ) + parser.add_argument( + "-o", "--output", metavar="FILE", default=None, help="Output file." + ) + parser.add_argument( + "-y", metavar="NUMBER", default=-1, help="Font number to load from collections." + ) + parser.add_argument( + "--lazy", action="store_true", default=None, help="Load fonts lazily." + ) + parser.add_argument( + "--no-lazy", dest="lazy", action="store_false", help="Load fonts immediately." + ) + parser.add_argument( + "--flavor", + dest="flavor", + default=None, + help="Flavor of output font. 'woff' or 'woff2'.", + ) + parser.add_argument( + "--no-recalc-timestamp", + dest="recalcTimestamp", + action="store_false", + help="Keep the original font 'modified' timestamp.", + ) + parser.add_argument( + "-b", + dest="recalcBBoxes", + action="store_false", + help="Don't recalc glyph bounding boxes: use the values in the original font.", + ) + parser.add_argument( + "--optimize-font-speed", + action="store_true", + help=( + "Enable optimizations that prioritize speed over file size. This " + "mainly affects how glyf table and gvar / VARC tables are compiled." + ), + ) + options = parser.parse_args(args) + + fontNumber = int(options.y) if options.y is not None else None + outFile = options.output + lazy = options.lazy + flavor = options.flavor + tables = options.table + recalcBBoxes = options.recalcBBoxes + recalcTimestamp = options.recalcTimestamp + optimizeFontSpeed = options.optimize_font_speed + + fonts = [] + for f in options.font: + try: + font = TTFont( + f, + recalcBBoxes=recalcBBoxes, + recalcTimestamp=recalcTimestamp, + fontNumber=fontNumber, + lazy=lazy, + ) + if optimizeFontSpeed: + font.cfg[OPTIMIZE_FONT_SPEED] = optimizeFontSpeed + fonts.append(font) + except TTLibFileIsCollectionError: + collection = TTCollection(f, lazy=lazy) + fonts.extend(collection.fonts) + + if tables is None: + if lazy is False: + tables = ["*"] + elif optimizeFontSpeed: + tables = {"glyf", "gvar", "VARC"}.intersection(font.keys()) + else: + tables = [] + for font in fonts: + if "GlyphOrder" in tables: + font.getGlyphOrder() + for table in tables if "*" not in tables else font.keys(): + font[table] # Decompiles + + if outFile is not None: + if len(fonts) == 1: + fonts[0].flavor = flavor + fonts[0].save(outFile) + else: + if flavor is not None: + raise TTLibError("Cannot set flavor for collections.") + collection = TTCollection() + collection.fonts = fonts + collection.save(outFile) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c16b6df24fa01c493c794830dc312db1e0ad5b06 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1bc91a398ecbd2f686e294a8aead605020fc9e7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/macUtils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/macUtils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b33c2d6c816b17facfe156e7632d08bebf22e9b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/macUtils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/removeOverlaps.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/removeOverlaps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af509812f03530a2802c2c58cfb9bc9940621839 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/removeOverlaps.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/reorderGlyphs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/reorderGlyphs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d86a6824beffbb72734d638504b53c53dddfae34 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/reorderGlyphs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/scaleUpem.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/scaleUpem.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a34a025f68e35dbfe0b04048cdc89b01828e244f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/scaleUpem.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/sfnt.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/sfnt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2494af782af3801e4e1f1efed1a90aab819174d5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/sfnt.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/standardGlyphOrder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/standardGlyphOrder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef319f89a537b8cb63d5a9b26592ea1fd238f93a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/standardGlyphOrder.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttCollection.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttCollection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05dcabaada7eae074117bebe06cc3f69fa59cbe8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttCollection.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttFont.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttFont.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c1c17a6f930d7c5e52b711b58e1aa395a5af196 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttFont.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttGlyphSet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttGlyphSet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..851b7d2f5610317632e194bc2458c542e654fdef Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttGlyphSet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttVisitor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttVisitor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1b341499ecb71cf04a2e15a1d4d5adbf3797070 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttVisitor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/woff2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/woff2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..423f8f7d250e32a8955e0bcb4cd2b7fd300f94ac Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/woff2.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/macUtils.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/macUtils.py new file mode 100644 index 0000000000000000000000000000000000000000..0959a6fc2776ff4b7ff968031191aa05c6ec50a4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/macUtils.py @@ -0,0 +1,54 @@ +"""ttLib.macUtils.py -- Various Mac-specific stuff.""" + +from io import BytesIO +from fontTools.misc.macRes import ResourceReader, ResourceError + + +def getSFNTResIndices(path): + """Determine whether a file has a 'sfnt' resource fork or not.""" + try: + reader = ResourceReader(path) + indices = reader.getIndices("sfnt") + reader.close() + return indices + except ResourceError: + return [] + + +def openTTFonts(path): + """Given a pathname, return a list of TTFont objects. In the case + of a flat TTF/OTF file, the list will contain just one font object; + but in the case of a Mac font suitcase it will contain as many + font objects as there are sfnt resources in the file. + """ + from fontTools import ttLib + + fonts = [] + sfnts = getSFNTResIndices(path) + if not sfnts: + fonts.append(ttLib.TTFont(path)) + else: + for index in sfnts: + fonts.append(ttLib.TTFont(path, index)) + if not fonts: + raise ttLib.TTLibError("no fonts found in file '%s'" % path) + return fonts + + +class SFNTResourceReader(BytesIO): + """Simple read-only file wrapper for 'sfnt' resources.""" + + def __init__(self, path, res_name_or_index): + from fontTools import ttLib + + reader = ResourceReader(path) + if isinstance(res_name_or_index, str): + rsrc = reader.getNamedResource("sfnt", res_name_or_index) + else: + rsrc = reader.getIndResource("sfnt", res_name_or_index) + if rsrc is None: + raise ttLib.TTLibError("sfnt resource not found: %s" % res_name_or_index) + reader.close() + self.rsrc = rsrc + super(SFNTResourceReader, self).__init__(rsrc.data) + self.name = path diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/removeOverlaps.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/removeOverlaps.py new file mode 100644 index 0000000000000000000000000000000000000000..a512b6a34563eec7ce9c2da41c0e1d84e7589754 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/removeOverlaps.py @@ -0,0 +1,394 @@ +"""Simplify TrueType glyphs by merging overlapping contours/components. + +Requires https://github.com/fonttools/skia-pathops +""" + +import itertools +import logging +from typing import Callable, Iterable, Optional, Mapping + +from fontTools.cffLib import CFFFontSet +from fontTools.ttLib import ttFont +from fontTools.ttLib.tables import _g_l_y_f +from fontTools.ttLib.tables import _h_m_t_x +from fontTools.misc.psCharStrings import T2CharString +from fontTools.misc.roundTools import otRound, noRound +from fontTools.pens.ttGlyphPen import TTGlyphPen +from fontTools.pens.t2CharStringPen import T2CharStringPen + +import pathops + +__all__ = ["removeOverlaps"] + + +class RemoveOverlapsError(Exception): + pass + + +log = logging.getLogger("fontTools.ttLib.removeOverlaps") + +_TTGlyphMapping = Mapping[str, ttFont._TTGlyph] + + +def skPathFromGlyph(glyphName: str, glyphSet: _TTGlyphMapping) -> pathops.Path: + path = pathops.Path() + pathPen = path.getPen(glyphSet=glyphSet) + glyphSet[glyphName].draw(pathPen) + return path + + +def skPathFromGlyphComponent( + component: _g_l_y_f.GlyphComponent, glyphSet: _TTGlyphMapping +): + baseGlyphName, transformation = component.getComponentInfo() + path = skPathFromGlyph(baseGlyphName, glyphSet) + return path.transform(*transformation) + + +def componentsOverlap(glyph: _g_l_y_f.Glyph, glyphSet: _TTGlyphMapping) -> bool: + if not glyph.isComposite(): + raise ValueError("This method only works with TrueType composite glyphs") + if len(glyph.components) < 2: + return False # single component, no overlaps + + component_paths = {} + + def _get_nth_component_path(index: int) -> pathops.Path: + if index not in component_paths: + component_paths[index] = skPathFromGlyphComponent( + glyph.components[index], glyphSet + ) + return component_paths[index] + + return any( + pathops.op( + _get_nth_component_path(i), + _get_nth_component_path(j), + pathops.PathOp.INTERSECTION, + fix_winding=False, + keep_starting_points=False, + ) + for i, j in itertools.combinations(range(len(glyph.components)), 2) + ) + + +def ttfGlyphFromSkPath(path: pathops.Path) -> _g_l_y_f.Glyph: + # Skia paths have no 'components', no need for glyphSet + ttPen = TTGlyphPen(glyphSet=None) + path.draw(ttPen) + glyph = ttPen.glyph() + assert not glyph.isComposite() + # compute glyph.xMin (glyfTable parameter unused for non composites) + glyph.recalcBounds(glyfTable=None) + return glyph + + +def _charString_from_SkPath( + path: pathops.Path, charString: T2CharString +) -> T2CharString: + if charString.width == charString.private.defaultWidthX: + width = None + else: + width = charString.width - charString.private.nominalWidthX + t2Pen = T2CharStringPen(width=width, glyphSet=None) + path.draw(t2Pen) + return t2Pen.getCharString(charString.private, charString.globalSubrs) + + +def _round_path( + path: pathops.Path, round: Callable[[float], float] = otRound +) -> pathops.Path: + rounded_path = pathops.Path() + for verb, points in path: + rounded_path.add(verb, *((round(p[0]), round(p[1])) for p in points)) + return rounded_path + + +def _simplify( + path: pathops.Path, + debugGlyphName: str, + *, + round: Callable[[float], float] = otRound, +) -> pathops.Path: + # skia-pathops has a bug where it sometimes fails to simplify paths when there + # are float coordinates and control points are very close to one another. + # Rounding coordinates to integers works around the bug. + # Since we are going to round glyf coordinates later on anyway, here it is + # ok(-ish) to also round before simplify. Better than failing the whole process + # for the entire font. + # https://bugs.chromium.org/p/skia/issues/detail?id=11958 + # https://github.com/google/fonts/issues/3365 + # TODO(anthrotype): remove once this Skia bug is fixed + try: + return pathops.simplify(path, clockwise=path.clockwise) + except pathops.PathOpsError: + pass + + path = _round_path(path, round=round) + try: + path = pathops.simplify(path, clockwise=path.clockwise) + log.debug( + "skia-pathops failed to simplify '%s' with float coordinates, " + "but succeded using rounded integer coordinates", + debugGlyphName, + ) + return path + except pathops.PathOpsError as e: + if log.isEnabledFor(logging.DEBUG): + path.dump() + raise RemoveOverlapsError( + f"Failed to remove overlaps from glyph {debugGlyphName!r}" + ) from e + + raise AssertionError("Unreachable") + + +def _same_path(path1: pathops.Path, path2: pathops.Path) -> bool: + return {tuple(c) for c in path1.contours} == {tuple(c) for c in path2.contours} + + +def removeTTGlyphOverlaps( + glyphName: str, + glyphSet: _TTGlyphMapping, + glyfTable: _g_l_y_f.table__g_l_y_f, + hmtxTable: _h_m_t_x.table__h_m_t_x, + removeHinting: bool = True, +) -> bool: + glyph = glyfTable[glyphName] + # decompose composite glyphs only if components overlap each other + if ( + glyph.numberOfContours > 0 + or glyph.isComposite() + and componentsOverlap(glyph, glyphSet) + ): + path = skPathFromGlyph(glyphName, glyphSet) + + # remove overlaps + path2 = _simplify(path, glyphName) + + # replace TTGlyph if simplified path is different (ignoring contour order) + if not _same_path(path, path2): + glyfTable[glyphName] = glyph = ttfGlyphFromSkPath(path2) + # simplified glyph is always unhinted + assert not glyph.program + # also ensure hmtx LSB == glyph.xMin so glyph origin is at x=0 + width, lsb = hmtxTable[glyphName] + if lsb != glyph.xMin: + hmtxTable[glyphName] = (width, glyph.xMin) + return True + + if removeHinting: + glyph.removeHinting() + return False + + +def _remove_glyf_overlaps( + *, + font: ttFont.TTFont, + glyphNames: Iterable[str], + glyphSet: _TTGlyphMapping, + removeHinting: bool, + ignoreErrors: bool, +) -> None: + glyfTable = font["glyf"] + hmtxTable = font["hmtx"] + + # process all simple glyphs first, then composites with increasing component depth, + # so that by the time we test for component intersections the respective base glyphs + # have already been simplified + glyphNames = sorted( + glyphNames, + key=lambda name: ( + ( + glyfTable[name].getCompositeMaxpValues(glyfTable).maxComponentDepth + if glyfTable[name].isComposite() + else 0 + ), + name, + ), + ) + modified = set() + for glyphName in glyphNames: + try: + if removeTTGlyphOverlaps( + glyphName, glyphSet, glyfTable, hmtxTable, removeHinting + ): + modified.add(glyphName) + except RemoveOverlapsError: + if not ignoreErrors: + raise + log.error("Failed to remove overlaps for '%s'", glyphName) + + log.debug("Removed overlaps for %s glyphs:\n%s", len(modified), " ".join(modified)) + + +def _remove_charstring_overlaps( + *, + glyphName: str, + glyphSet: _TTGlyphMapping, + cffFontSet: CFFFontSet, +) -> bool: + path = skPathFromGlyph(glyphName, glyphSet) + + # remove overlaps + path2 = _simplify(path, glyphName, round=noRound) + + # replace TTGlyph if simplified path is different (ignoring contour order) + if not _same_path(path, path2): + charStrings = cffFontSet[0].CharStrings + charStrings[glyphName] = _charString_from_SkPath(path2, charStrings[glyphName]) + return True + + return False + + +def _remove_cff_overlaps( + *, + font: ttFont.TTFont, + glyphNames: Iterable[str], + glyphSet: _TTGlyphMapping, + removeHinting: bool, + ignoreErrors: bool, + table_tag: str, + removeUnusedSubroutines: bool = True, +) -> None: + cffFontSet = font[table_tag].cff + modified = set() + for glyphName in glyphNames: + try: + if _remove_charstring_overlaps( + glyphName=glyphName, + glyphSet=glyphSet, + cffFontSet=cffFontSet, + ): + modified.add(glyphName) + except RemoveOverlapsError: + if not ignoreErrors: + raise + log.error("Failed to remove overlaps for '%s'", glyphName) + + if not modified: + log.debug("No overlaps found in the specified CFF glyphs") + return + + if removeHinting: + cffFontSet.remove_hints() + + if removeUnusedSubroutines: + cffFontSet.remove_unused_subroutines() + + log.debug("Removed overlaps for %s glyphs:\n%s", len(modified), " ".join(modified)) + + +def removeOverlaps( + font: ttFont.TTFont, + glyphNames: Optional[Iterable[str]] = None, + removeHinting: bool = True, + ignoreErrors: bool = False, + *, + removeUnusedSubroutines: bool = True, +) -> None: + """Simplify glyphs in TTFont by merging overlapping contours. + + Overlapping components are first decomposed to simple contours, then merged. + + Currently this only works for fonts with 'glyf' or 'CFF ' tables. + Raises NotImplementedError if 'glyf' or 'CFF ' tables are absent. + + Note that removing overlaps invalidates the hinting. By default we drop hinting + from all glyphs whether or not overlaps are removed from a given one, as it would + look weird if only some glyphs are left (un)hinted. + + Args: + font: input TTFont object, modified in place. + glyphNames: optional iterable of glyph names (str) to remove overlaps from. + By default, all glyphs in the font are processed. + removeHinting (bool): set to False to keep hinting for unmodified glyphs. + ignoreErrors (bool): set to True to ignore errors while removing overlaps, + thus keeping the tricky glyphs unchanged (fonttools/fonttools#2363). + removeUnusedSubroutines (bool): set to False to keep unused subroutines + in CFF table after removing overlaps. Default is to remove them if + any glyphs are modified. + """ + + if "glyf" not in font and "CFF " not in font and "CFF2" not in font: + raise NotImplementedError( + "No outline data found in the font: missing 'glyf', 'CFF ', or 'CFF2' table" + ) + + if glyphNames is None: + glyphNames = font.getGlyphOrder() + + # Wraps the underlying glyphs, takes care of interfacing with drawing pens + glyphSet = font.getGlyphSet() + + if "glyf" in font: + _remove_glyf_overlaps( + font=font, + glyphNames=glyphNames, + glyphSet=glyphSet, + removeHinting=removeHinting, + ignoreErrors=ignoreErrors, + ) + + if "CFF " in font or "CFF2" in font: + _remove_cff_overlaps( + font=font, + glyphNames=glyphNames, + glyphSet=glyphSet, + removeHinting=removeHinting, + ignoreErrors=ignoreErrors, + table_tag="CFF " if "CFF " in font else "CFF2", + removeUnusedSubroutines=removeUnusedSubroutines, + ) + + +def main(args=None): + """Simplify glyphs in TTFont by merging overlapping contours.""" + + import argparse + + parser = argparse.ArgumentParser( + "fonttools ttLib.removeOverlaps", description=__doc__ + ) + + parser.add_argument("input", metavar="INPUT.ttf", help="Input font file") + parser.add_argument("output", metavar="OUTPUT.ttf", help="Output font file") + parser.add_argument( + "glyphs", + metavar="GLYPHS", + nargs="*", + help="Optional list of glyph names to remove overlaps from", + ) + parser.add_argument( + "--keep-hinting", + action="store_true", + help="Keep hinting for unmodified glyphs, default is to drop hinting", + ) + parser.add_argument( + "--ignore-errors", + action="store_true", + help="ignore errors while removing overlaps, " + "thus keeping the tricky glyphs unchanged", + ) + parser.add_argument( + "--keep-unused-subroutines", + action="store_true", + help="Keep unused subroutines in CFF table after removing overlaps, " + "default is to remove them if any glyphs are modified", + ) + args = parser.parse_args(args) + + with ttFont.TTFont(args.input) as font: + removeOverlaps( + font=font, + glyphNames=args.glyphs or None, + removeHinting=not args.keep_hinting, + ignoreErrors=args.ignore_errors, + removeUnusedSubroutines=not args.keep_unused_subroutines, + ) + font.save(args.output) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/reorderGlyphs.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/reorderGlyphs.py new file mode 100644 index 0000000000000000000000000000000000000000..7e1be32cb8ff453a83aecd39ab4b4d3e662bdad1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/reorderGlyphs.py @@ -0,0 +1,284 @@ +"""Reorder glyphs in a font.""" + +__author__ = "Rod Sheeter" + +# See https://docs.google.com/document/d/1h9O-C_ndods87uY0QeIIcgAMiX2gDTpvO_IhMJsKAqs/ +# for details. + + +from fontTools import ttLib +from fontTools.ttLib.tables import otBase +from fontTools.ttLib.tables import otTables as ot +from abc import ABC, abstractmethod +from dataclasses import dataclass +from collections import deque +from typing import ( + Optional, + Any, + Callable, + Deque, + Iterable, + List, + Tuple, +) + +_COVERAGE_ATTR = "Coverage" # tables that have one coverage use this name + + +def _sort_by_gid( + get_glyph_id: Callable[[str], int], + glyphs: List[str], + parallel_list: Optional[List[Any]], +): + if parallel_list: + reordered = sorted( + ((g, e) for g, e in zip(glyphs, parallel_list)), + key=lambda t: get_glyph_id(t[0]), + ) + sorted_glyphs, sorted_parallel_list = map(list, zip(*reordered)) + parallel_list[:] = sorted_parallel_list + else: + sorted_glyphs = sorted(glyphs, key=get_glyph_id) + + glyphs[:] = sorted_glyphs + + +def _get_dotted_attr(value: Any, dotted_attr: str) -> Any: + attr_names = dotted_attr.split(".") + assert attr_names + + while attr_names: + attr_name = attr_names.pop(0) + value = getattr(value, attr_name) + return value + + +class ReorderRule(ABC): + """A rule to reorder something in a font to match the fonts glyph order.""" + + @abstractmethod + def apply(self, font: ttLib.TTFont, value: otBase.BaseTable) -> None: ... + + +@dataclass(frozen=True) +class ReorderCoverage(ReorderRule): + """Reorder a Coverage table, and optionally a list that is sorted parallel to it.""" + + # A list that is parallel to Coverage + parallel_list_attr: Optional[str] = None + coverage_attr: str = _COVERAGE_ATTR + + def apply(self, font: ttLib.TTFont, value: otBase.BaseTable) -> None: + coverage = _get_dotted_attr(value, self.coverage_attr) + + if type(coverage) is not list: + # Normal path, process one coverage that might have a parallel list + parallel_list = None + if self.parallel_list_attr: + parallel_list = _get_dotted_attr(value, self.parallel_list_attr) + assert ( + type(parallel_list) is list + ), f"{self.parallel_list_attr} should be a list" + assert len(parallel_list) == len(coverage.glyphs), "Nothing makes sense" + + _sort_by_gid(font.getGlyphID, coverage.glyphs, parallel_list) + + else: + # A few tables have a list of coverage. No parallel list can exist. + assert ( + not self.parallel_list_attr + ), f"Can't have multiple coverage AND a parallel list; {self}" + for coverage_entry in coverage: + _sort_by_gid(font.getGlyphID, coverage_entry.glyphs, None) + + +@dataclass(frozen=True) +class ReorderList(ReorderRule): + """Reorder the items within a list to match the updated glyph order. + + Useful when a list ordered by coverage itself contains something ordered by a gid. + For example, the PairSet table of https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-2-pair-adjustment-positioning-subtable. + """ + + list_attr: str + key: str + + def apply(self, font: ttLib.TTFont, value: otBase.BaseTable) -> None: + lst = _get_dotted_attr(value, self.list_attr) + assert isinstance(lst, list), f"{self.list_attr} should be a list" + lst.sort(key=lambda v: font.getGlyphID(getattr(v, self.key))) + + +# (Type, Optional Format) => List[ReorderRule] +# Encodes the relationships Cosimo identified +_REORDER_RULES = { + # GPOS + (ot.SinglePos, 1): [ReorderCoverage()], + (ot.SinglePos, 2): [ReorderCoverage(parallel_list_attr="Value")], + (ot.PairPos, 1): [ReorderCoverage(parallel_list_attr="PairSet")], + (ot.PairSet, None): [ReorderList("PairValueRecord", key="SecondGlyph")], + (ot.PairPos, 2): [ReorderCoverage()], + (ot.CursivePos, 1): [ReorderCoverage(parallel_list_attr="EntryExitRecord")], + (ot.MarkBasePos, 1): [ + ReorderCoverage( + coverage_attr="MarkCoverage", parallel_list_attr="MarkArray.MarkRecord" + ), + ReorderCoverage( + coverage_attr="BaseCoverage", parallel_list_attr="BaseArray.BaseRecord" + ), + ], + (ot.MarkLigPos, 1): [ + ReorderCoverage( + coverage_attr="MarkCoverage", parallel_list_attr="MarkArray.MarkRecord" + ), + ReorderCoverage( + coverage_attr="LigatureCoverage", + parallel_list_attr="LigatureArray.LigatureAttach", + ), + ], + (ot.MarkMarkPos, 1): [ + ReorderCoverage( + coverage_attr="Mark1Coverage", parallel_list_attr="Mark1Array.MarkRecord" + ), + ReorderCoverage( + coverage_attr="Mark2Coverage", parallel_list_attr="Mark2Array.Mark2Record" + ), + ], + (ot.ContextPos, 1): [ReorderCoverage(parallel_list_attr="PosRuleSet")], + (ot.ContextPos, 2): [ReorderCoverage()], + (ot.ContextPos, 3): [ReorderCoverage()], + (ot.ChainContextPos, 1): [ReorderCoverage(parallel_list_attr="ChainPosRuleSet")], + (ot.ChainContextPos, 2): [ReorderCoverage()], + (ot.ChainContextPos, 3): [ + ReorderCoverage(coverage_attr="BacktrackCoverage"), + ReorderCoverage(coverage_attr="InputCoverage"), + ReorderCoverage(coverage_attr="LookAheadCoverage"), + ], + # GSUB + (ot.ContextSubst, 1): [ReorderCoverage(parallel_list_attr="SubRuleSet")], + (ot.ContextSubst, 2): [ReorderCoverage()], + (ot.ContextSubst, 3): [ReorderCoverage()], + (ot.ChainContextSubst, 1): [ReorderCoverage(parallel_list_attr="ChainSubRuleSet")], + (ot.ChainContextSubst, 2): [ReorderCoverage()], + (ot.ChainContextSubst, 3): [ + ReorderCoverage(coverage_attr="BacktrackCoverage"), + ReorderCoverage(coverage_attr="InputCoverage"), + ReorderCoverage(coverage_attr="LookAheadCoverage"), + ], + (ot.ReverseChainSingleSubst, 1): [ + ReorderCoverage(parallel_list_attr="Substitute"), + ReorderCoverage(coverage_attr="BacktrackCoverage"), + ReorderCoverage(coverage_attr="LookAheadCoverage"), + ], + # GDEF + (ot.AttachList, None): [ReorderCoverage(parallel_list_attr="AttachPoint")], + (ot.LigCaretList, None): [ReorderCoverage(parallel_list_attr="LigGlyph")], + (ot.MarkGlyphSetsDef, None): [ReorderCoverage()], + # MATH + (ot.MathGlyphInfo, None): [ReorderCoverage(coverage_attr="ExtendedShapeCoverage")], + (ot.MathItalicsCorrectionInfo, None): [ + ReorderCoverage(parallel_list_attr="ItalicsCorrection") + ], + (ot.MathTopAccentAttachment, None): [ + ReorderCoverage( + coverage_attr="TopAccentCoverage", parallel_list_attr="TopAccentAttachment" + ) + ], + (ot.MathKernInfo, None): [ + ReorderCoverage( + coverage_attr="MathKernCoverage", parallel_list_attr="MathKernInfoRecords" + ) + ], + (ot.MathVariants, None): [ + ReorderCoverage( + coverage_attr="VertGlyphCoverage", + parallel_list_attr="VertGlyphConstruction", + ), + ReorderCoverage( + coverage_attr="HorizGlyphCoverage", + parallel_list_attr="HorizGlyphConstruction", + ), + ], +} + + +# TODO Port to otTraverse + +SubTablePath = Tuple[otBase.BaseTable.SubTableEntry, ...] + + +def _bfs_base_table( + root: otBase.BaseTable, root_accessor: str +) -> Iterable[SubTablePath]: + yield from _traverse_ot_data( + root, root_accessor, lambda frontier, new: frontier.extend(new) + ) + + +# Given f(current frontier, new entries) add new entries to frontier +AddToFrontierFn = Callable[[Deque[SubTablePath], List[SubTablePath]], None] + + +def _traverse_ot_data( + root: otBase.BaseTable, root_accessor: str, add_to_frontier_fn: AddToFrontierFn +) -> Iterable[SubTablePath]: + # no visited because general otData is forward-offset only and thus cannot cycle + + frontier: Deque[SubTablePath] = deque() + frontier.append((otBase.BaseTable.SubTableEntry(root_accessor, root),)) + while frontier: + # path is (value, attr_name) tuples. attr_name is attr of parent to get value + path = frontier.popleft() + current = path[-1].value + + yield path + + new_entries = [] + for subtable_entry in current.iterSubTables(): + new_entries.append(path + (subtable_entry,)) + + add_to_frontier_fn(frontier, new_entries) + + +def reorderGlyphs(font: ttLib.TTFont, new_glyph_order: List[str]): + old_glyph_order = font.getGlyphOrder() + if len(new_glyph_order) != len(old_glyph_order): + raise ValueError( + f"New glyph order contains {len(new_glyph_order)} glyphs, " + f"but font has {len(old_glyph_order)} glyphs" + ) + + if set(old_glyph_order) != set(new_glyph_order): + raise ValueError( + "New glyph order does not contain the same set of glyphs as the font:\n" + f"* only in new: {set(new_glyph_order) - set(old_glyph_order)}\n" + f"* only in old: {set(old_glyph_order) - set(new_glyph_order)}" + ) + + # Changing the order of glyphs in a TTFont requires that all tables that use + # glyph indexes have been fully. + # Cf. https://github.com/fonttools/fonttools/issues/2060 + font.ensureDecompiled() + not_loaded = sorted(t for t in font.keys() if not font.isLoaded(t)) + if not_loaded: + raise ValueError(f"Everything should be loaded, following aren't: {not_loaded}") + + font.setGlyphOrder(new_glyph_order) + + coverage_containers = {"GDEF", "GPOS", "GSUB", "MATH"} + for tag in coverage_containers: + if tag in font.keys(): + for path in _bfs_base_table(font[tag].table, f'font["{tag}"]'): + value = path[-1].value + reorder_key = (type(value), getattr(value, "Format", None)) + for reorder in _REORDER_RULES.get(reorder_key, []): + reorder.apply(font, value) + + for tag in ["CFF ", "CFF2"]: + if tag in font: + cff_table = font[tag] + charstrings = cff_table.cff.topDictIndex[0].CharStrings.charStrings + cff_table.cff.topDictIndex[0].charset = new_glyph_order + cff_table.cff.topDictIndex[0].CharStrings.charStrings = { + k: charstrings.get(k) for k in new_glyph_order + } diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/scaleUpem.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/scaleUpem.py new file mode 100644 index 0000000000000000000000000000000000000000..cdd560620e52b55aa96651c7419253f70c25a6bb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/scaleUpem.py @@ -0,0 +1,435 @@ +"""Change the units-per-EM of a font. + +AAT and Graphite tables are not supported. CFF/CFF2 fonts +are de-subroutinized.""" + +from fontTools.ttLib.ttVisitor import TTVisitor +import fontTools.ttLib as ttLib +import fontTools.ttLib.tables.otBase as otBase +import fontTools.ttLib.tables.otTables as otTables +from fontTools.cffLib import VarStoreData +import fontTools.cffLib.specializer as cffSpecializer +from fontTools.varLib import builder # for VarData.calculateNumShorts +from fontTools.varLib.multiVarStore import OnlineMultiVarStoreBuilder +from fontTools.misc.vector import Vector +from fontTools.misc.fixedTools import otRound +from fontTools.misc.iterTools import batched + +__all__ = ["scale_upem", "ScalerVisitor"] + + +class ScalerVisitor(TTVisitor): + def __init__(self, scaleFactor): + self.scaleFactor = scaleFactor + + def scale(self, v): + return otRound(v * self.scaleFactor) + + +@ScalerVisitor.register_attrs( + ( + (ttLib.getTableClass("head"), ("unitsPerEm", "xMin", "yMin", "xMax", "yMax")), + (ttLib.getTableClass("post"), ("underlinePosition", "underlineThickness")), + (ttLib.getTableClass("VORG"), ("defaultVertOriginY")), + ( + ttLib.getTableClass("hhea"), + ( + "ascent", + "descent", + "lineGap", + "advanceWidthMax", + "minLeftSideBearing", + "minRightSideBearing", + "xMaxExtent", + "caretOffset", + ), + ), + ( + ttLib.getTableClass("vhea"), + ( + "ascent", + "descent", + "lineGap", + "advanceHeightMax", + "minTopSideBearing", + "minBottomSideBearing", + "yMaxExtent", + "caretOffset", + ), + ), + ( + ttLib.getTableClass("OS/2"), + ( + "xAvgCharWidth", + "ySubscriptXSize", + "ySubscriptYSize", + "ySubscriptXOffset", + "ySubscriptYOffset", + "ySuperscriptXSize", + "ySuperscriptYSize", + "ySuperscriptXOffset", + "ySuperscriptYOffset", + "yStrikeoutSize", + "yStrikeoutPosition", + "sTypoAscender", + "sTypoDescender", + "sTypoLineGap", + "usWinAscent", + "usWinDescent", + "sxHeight", + "sCapHeight", + ), + ), + ( + otTables.ValueRecord, + ("XAdvance", "YAdvance", "XPlacement", "YPlacement"), + ), # GPOS + (otTables.Anchor, ("XCoordinate", "YCoordinate")), # GPOS + (otTables.CaretValue, ("Coordinate")), # GDEF + (otTables.BaseCoord, ("Coordinate")), # BASE + (otTables.MathValueRecord, ("Value")), # MATH + (otTables.ClipBox, ("xMin", "yMin", "xMax", "yMax")), # COLR + ) +) +def visit(visitor, obj, attr, value): + setattr(obj, attr, visitor.scale(value)) + + +@ScalerVisitor.register_attr( + (ttLib.getTableClass("hmtx"), ttLib.getTableClass("vmtx")), "metrics" +) +def visit(visitor, obj, attr, metrics): + for g in metrics: + advance, lsb = metrics[g] + metrics[g] = visitor.scale(advance), visitor.scale(lsb) + + +@ScalerVisitor.register_attr(ttLib.getTableClass("VMTX"), "VOriginRecords") +def visit(visitor, obj, attr, VOriginRecords): + for g in VOriginRecords: + VOriginRecords[g] = visitor.scale(VOriginRecords[g]) + + +@ScalerVisitor.register_attr(ttLib.getTableClass("glyf"), "glyphs") +def visit(visitor, obj, attr, glyphs): + for g in glyphs.values(): + for attr in ("xMin", "xMax", "yMin", "yMax"): + v = getattr(g, attr, None) + if v is not None: + setattr(g, attr, visitor.scale(v)) + + if g.isComposite(): + for component in g.components: + component.x = visitor.scale(component.x) + component.y = visitor.scale(component.y) + continue + + if hasattr(g, "coordinates"): + coordinates = g.coordinates + for i, (x, y) in enumerate(coordinates): + coordinates[i] = visitor.scale(x), visitor.scale(y) + + +@ScalerVisitor.register_attr(ttLib.getTableClass("gvar"), "variations") +def visit(visitor, obj, attr, variations): + glyfTable = visitor.font["glyf"] + + for glyphName, varlist in variations.items(): + glyph = glyfTable[glyphName] + for var in varlist: + coordinates = var.coordinates + for i, xy in enumerate(coordinates): + if xy is None: + continue + coordinates[i] = visitor.scale(xy[0]), visitor.scale(xy[1]) + + +@ScalerVisitor.register_attr(ttLib.getTableClass("VARC"), "table") +def visit(visitor, obj, attr, varc): + # VarComposite variations are a pain + + fvar = visitor.font["fvar"] + fvarAxes = [a.axisTag for a in fvar.axes] + + store = varc.MultiVarStore + storeBuilder = OnlineMultiVarStoreBuilder(fvarAxes) + + for g in varc.VarCompositeGlyphs.VarCompositeGlyph: + for component in g.components: + t = component.transform + t.translateX = visitor.scale(t.translateX) + t.translateY = visitor.scale(t.translateY) + t.tCenterX = visitor.scale(t.tCenterX) + t.tCenterY = visitor.scale(t.tCenterY) + + if component.axisValuesVarIndex != otTables.NO_VARIATION_INDEX: + varIdx = component.axisValuesVarIndex + # TODO Move this code duplicated below to MultiVarStore.__getitem__, + # or a getDeltasAndSupports(). + if varIdx != otTables.NO_VARIATION_INDEX: + major = varIdx >> 16 + minor = varIdx & 0xFFFF + varData = store.MultiVarData[major] + vec = varData.Item[minor] + storeBuilder.setSupports(store.get_supports(major, fvar.axes)) + if vec: + m = len(vec) // varData.VarRegionCount + vec = list(batched(vec, m)) + vec = [Vector(v) for v in vec] + component.axisValuesVarIndex = storeBuilder.storeDeltas(vec) + else: + component.axisValuesVarIndex = otTables.NO_VARIATION_INDEX + + if component.transformVarIndex != otTables.NO_VARIATION_INDEX: + varIdx = component.transformVarIndex + if varIdx != otTables.NO_VARIATION_INDEX: + major = varIdx >> 16 + minor = varIdx & 0xFFFF + vec = varData.Item[varIdx & 0xFFFF] + major = varIdx >> 16 + minor = varIdx & 0xFFFF + varData = store.MultiVarData[major] + vec = varData.Item[minor] + storeBuilder.setSupports(store.get_supports(major, fvar.axes)) + if vec: + m = len(vec) // varData.VarRegionCount + flags = component.flags + vec = list(batched(vec, m)) + newVec = [] + for v in vec: + v = list(v) + i = 0 + ## Scale translate & tCenter + if flags & otTables.VarComponentFlags.HAVE_TRANSLATE_X: + v[i] = visitor.scale(v[i]) + i += 1 + if flags & otTables.VarComponentFlags.HAVE_TRANSLATE_Y: + v[i] = visitor.scale(v[i]) + i += 1 + if flags & otTables.VarComponentFlags.HAVE_ROTATION: + i += 1 + if flags & otTables.VarComponentFlags.HAVE_SCALE_X: + i += 1 + if flags & otTables.VarComponentFlags.HAVE_SCALE_Y: + i += 1 + if flags & otTables.VarComponentFlags.HAVE_SKEW_X: + i += 1 + if flags & otTables.VarComponentFlags.HAVE_SKEW_Y: + i += 1 + if flags & otTables.VarComponentFlags.HAVE_TCENTER_X: + v[i] = visitor.scale(v[i]) + i += 1 + if flags & otTables.VarComponentFlags.HAVE_TCENTER_Y: + v[i] = visitor.scale(v[i]) + i += 1 + + newVec.append(Vector(v)) + vec = newVec + + component.transformVarIndex = storeBuilder.storeDeltas(vec) + else: + component.transformVarIndex = otTables.NO_VARIATION_INDEX + + varc.MultiVarStore = storeBuilder.finish() + + +@ScalerVisitor.register_attr(ttLib.getTableClass("kern"), "kernTables") +def visit(visitor, obj, attr, kernTables): + for table in kernTables: + kernTable = table.kernTable + for k in kernTable.keys(): + kernTable[k] = visitor.scale(kernTable[k]) + + +def _cff_scale(visitor, args): + for i, arg in enumerate(args): + if not isinstance(arg, list): + if not isinstance(arg, bytes): + args[i] = visitor.scale(arg) + else: + num_blends = arg[-1] + _cff_scale(visitor, arg) + arg[-1] = num_blends + + +@ScalerVisitor.register_attr( + (ttLib.getTableClass("CFF "), ttLib.getTableClass("CFF2")), "cff" +) +def visit(visitor, obj, attr, cff): + cff.desubroutinize() + topDict = cff.topDictIndex[0] + varStore = getattr(topDict, "VarStore", None) + getNumRegions = varStore.getNumRegions if varStore is not None else None + privates = set() + for fontname in cff.keys(): + font = cff[fontname] + cs = font.CharStrings + for g in font.charset: + c, _ = cs.getItemAndSelector(g) + privates.add(c.private) + + commands = cffSpecializer.programToCommands( + c.program, getNumRegions=getNumRegions + ) + for op, args in commands: + if op == "vsindex": + continue + _cff_scale(visitor, args) + c.program[:] = cffSpecializer.commandsToProgram(commands) + + # Annoying business of scaling numbers that do not matter whatsoever + + for attr in ( + "UnderlinePosition", + "UnderlineThickness", + "FontBBox", + "StrokeWidth", + ): + value = getattr(topDict, attr, None) + if value is None: + continue + if isinstance(value, list): + _cff_scale(visitor, value) + else: + setattr(topDict, attr, visitor.scale(value)) + + for i in range(6): + topDict.FontMatrix[i] /= visitor.scaleFactor + + for private in privates: + for attr in ( + "BlueValues", + "OtherBlues", + "FamilyBlues", + "FamilyOtherBlues", + # "BlueScale", + # "BlueShift", + # "BlueFuzz", + "StdHW", + "StdVW", + "StemSnapH", + "StemSnapV", + "defaultWidthX", + "nominalWidthX", + ): + value = getattr(private, attr, None) + if value is None: + continue + if isinstance(value, list): + _cff_scale(visitor, value) + else: + setattr(private, attr, visitor.scale(value)) + + +# ItemVariationStore + + +@ScalerVisitor.register(otTables.VarData) +def visit(visitor, varData): + for item in varData.Item: + for i, v in enumerate(item): + item[i] = visitor.scale(v) + varData.calculateNumShorts() + + +# COLRv1 + + +def _setup_scale_paint(paint, scale): + if -2 <= scale <= 2 - (1 >> 14): + paint.Format = otTables.PaintFormat.PaintScaleUniform + paint.scale = scale + return + + transform = otTables.Affine2x3() + transform.populateDefaults() + transform.xy = transform.yx = transform.dx = transform.dy = 0 + transform.xx = transform.yy = scale + + paint.Format = otTables.PaintFormat.PaintTransform + paint.Transform = transform + + +@ScalerVisitor.register(otTables.BaseGlyphPaintRecord) +def visit(visitor, record): + oldPaint = record.Paint + + scale = otTables.Paint() + _setup_scale_paint(scale, visitor.scaleFactor) + scale.Paint = oldPaint + + record.Paint = scale + + return True + + +@ScalerVisitor.register(otTables.Paint) +def visit(visitor, paint): + if paint.Format != otTables.PaintFormat.PaintGlyph: + return True + + newPaint = otTables.Paint() + newPaint.Format = paint.Format + newPaint.Paint = paint.Paint + newPaint.Glyph = paint.Glyph + del paint.Paint + del paint.Glyph + + _setup_scale_paint(paint, 1 / visitor.scaleFactor) + paint.Paint = newPaint + + visitor.visit(newPaint.Paint) + + return False + + +def scale_upem(font, new_upem): + """Change the units-per-EM of font to the new value.""" + upem = font["head"].unitsPerEm + visitor = ScalerVisitor(new_upem / upem) + visitor.visit(font) + + +def main(args=None): + """Change the units-per-EM of fonts""" + + if args is None: + import sys + + args = sys.argv[1:] + + from fontTools.ttLib import TTFont + from fontTools.misc.cliTools import makeOutputFileName + import argparse + + parser = argparse.ArgumentParser( + "fonttools ttLib.scaleUpem", description="Change the units-per-EM of fonts" + ) + parser.add_argument("font", metavar="font", help="Font file.") + parser.add_argument( + "new_upem", metavar="new-upem", help="New units-per-EM integer value." + ) + parser.add_argument( + "--output-file", metavar="path", default=None, help="Output file." + ) + + options = parser.parse_args(args) + + font = TTFont(options.font) + new_upem = int(options.new_upem) + output_file = ( + options.output_file + if options.output_file is not None + else makeOutputFileName(options.font, overWrite=True, suffix="-scaled") + ) + + scale_upem(font, new_upem) + + print("Writing %s" % output_file) + font.save(output_file) + + +if __name__ == "__main__": + import sys + + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/sfnt.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/sfnt.py new file mode 100644 index 0000000000000000000000000000000000000000..7694573cdbfa872cb447722e2908a339e4cb0dcb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/sfnt.py @@ -0,0 +1,708 @@ +"""ttLib/sfnt.py -- low-level module to deal with the sfnt file format. + +Defines two public classes: + +- SFNTReader +- SFNTWriter + +(Normally you don't have to use these classes explicitly; they are +used automatically by ttLib.TTFont.) + +The reading and writing of sfnt files is separated in two distinct +classes, since whenever the number of tables changes or whenever +a table's length changes you need to rewrite the whole file anyway. +""" + +from __future__ import annotations + +from collections.abc import KeysView +from io import BytesIO +from types import SimpleNamespace +from fontTools.misc.textTools import Tag +from fontTools.misc import sstruct +from fontTools.ttLib import TTLibError, TTLibFileIsCollectionError +import struct +from collections import OrderedDict +import logging + +log = logging.getLogger(__name__) + + +class SFNTReader(object): + def __new__(cls, *args, **kwargs): + """Return an instance of the SFNTReader sub-class which is compatible + with the input file type. + """ + if args and cls is SFNTReader: + infile = args[0] + infile.seek(0) + sfntVersion = Tag(infile.read(4)) + infile.seek(0) + if sfntVersion == "wOF2": + # return new WOFF2Reader object + from fontTools.ttLib.woff2 import WOFF2Reader + + return object.__new__(WOFF2Reader) + # return default object + return object.__new__(cls) + + def __init__(self, file, checkChecksums=0, fontNumber=-1): + self.file = file + self.checkChecksums = checkChecksums + + self.flavor = None + self.flavorData = None + self.DirectoryEntry = SFNTDirectoryEntry + self.file.seek(0) + self.sfntVersion = self.file.read(4) + self.file.seek(0) + if self.sfntVersion == b"ttcf": + header = readTTCHeader(self.file) + numFonts = header.numFonts + if not 0 <= fontNumber < numFonts: + raise TTLibFileIsCollectionError( + "specify a font number between 0 and %d (inclusive)" + % (numFonts - 1) + ) + self.numFonts = numFonts + self.file.seek(header.offsetTable[fontNumber]) + data = self.file.read(sfntDirectorySize) + if len(data) != sfntDirectorySize: + raise TTLibError("Not a Font Collection (not enough data)") + sstruct.unpack(sfntDirectoryFormat, data, self) + elif self.sfntVersion == b"wOFF": + self.flavor = "woff" + self.DirectoryEntry = WOFFDirectoryEntry + data = self.file.read(woffDirectorySize) + if len(data) != woffDirectorySize: + raise TTLibError("Not a WOFF font (not enough data)") + sstruct.unpack(woffDirectoryFormat, data, self) + else: + data = self.file.read(sfntDirectorySize) + if len(data) != sfntDirectorySize: + raise TTLibError("Not a TrueType or OpenType font (not enough data)") + sstruct.unpack(sfntDirectoryFormat, data, self) + self.sfntVersion = Tag(self.sfntVersion) + + if self.sfntVersion not in ("\x00\x01\x00\x00", "OTTO", "true"): + raise TTLibError("Not a TrueType or OpenType font (bad sfntVersion)") + tables: dict[Tag, DirectoryEntry] = {} + for i in range(self.numTables): + entry = self.DirectoryEntry() + entry.fromFile(self.file) + tag = Tag(entry.tag) + tables[tag] = entry + self.tables = OrderedDict(sorted(tables.items(), key=lambda i: i[1].offset)) + + # Load flavor data if any + if self.flavor == "woff": + self.flavorData = WOFFFlavorData(self) + + def has_key(self, tag: str | bytes) -> bool: + return tag in self.tables + + __contains__ = has_key + + def keys(self) -> KeysView[Tag]: + return self.tables.keys() + + def __getitem__(self, tag: str | bytes) -> bytes: + """Fetch the raw table data.""" + entry = self.tables[Tag(tag)] + data = entry.loadData(self.file) + if self.checkChecksums: + if tag == "head": + # Beh: we have to special-case the 'head' table. + checksum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:]) + else: + checksum = calcChecksum(data) + if self.checkChecksums > 1: + # Be obnoxious, and barf when it's wrong + assert checksum == entry.checkSum, "bad checksum for '%s' table" % tag + elif checksum != entry.checkSum: + # Be friendly, and just log a warning. + log.warning("bad checksum for '%s' table", tag) + return data + + def __delitem__(self, tag: str | bytes) -> None: + del self.tables[Tag(tag)] + + def close(self) -> None: + self.file.close() + + # We define custom __getstate__ and __setstate__ to make SFNTReader pickle-able + # and deepcopy-able. When a TTFont is loaded as lazy=True, SFNTReader holds a + # reference to an external file object which is not pickleable. So in __getstate__ + # we store the file name and current position, and in __setstate__ we reopen the + # same named file after unpickling. + + def __getstate__(self): + if isinstance(self.file, BytesIO): + # BytesIO is already pickleable, return the state unmodified + return self.__dict__ + + # remove unpickleable file attribute, and only store its name and pos + state = self.__dict__.copy() + del state["file"] + state["_filename"] = self.file.name + state["_filepos"] = self.file.tell() + return state + + def __setstate__(self, state): + if "file" not in state: + self.file = open(state.pop("_filename"), "rb") + self.file.seek(state.pop("_filepos")) + self.__dict__.update(state) + + +# default compression level for WOFF 1.0 tables and metadata +ZLIB_COMPRESSION_LEVEL = 6 + +# if set to True, use zopfli instead of zlib for compressing WOFF 1.0. +# The Python bindings are available at https://pypi.python.org/pypi/zopfli +USE_ZOPFLI = False + +# mapping between zlib's compression levels and zopfli's 'numiterations'. +# Use lower values for files over several MB in size or it will be too slow +ZOPFLI_LEVELS = { + # 0: 0, # can't do 0 iterations... + 1: 1, + 2: 3, + 3: 5, + 4: 8, + 5: 10, + 6: 15, + 7: 25, + 8: 50, + 9: 100, +} + + +def compress(data, level=ZLIB_COMPRESSION_LEVEL): + """Compress 'data' to Zlib format. If 'USE_ZOPFLI' variable is True, + zopfli is used instead of the zlib module. + The compression 'level' must be between 0 and 9. 1 gives best speed, + 9 gives best compression (0 gives no compression at all). + The default value is a compromise between speed and compression (6). + """ + if not (0 <= level <= 9): + raise ValueError("Bad compression level: %s" % level) + if not USE_ZOPFLI or level == 0: + from zlib import compress + + return compress(data, level) + else: + from zopfli.zlib import compress + + return compress(data, numiterations=ZOPFLI_LEVELS[level]) + + +class SFNTWriter(object): + def __new__(cls, *args, **kwargs): + """Return an instance of the SFNTWriter sub-class which is compatible + with the specified 'flavor'. + """ + flavor = None + if kwargs and "flavor" in kwargs: + flavor = kwargs["flavor"] + elif args and len(args) > 3: + flavor = args[3] + if cls is SFNTWriter: + if flavor == "woff2": + # return new WOFF2Writer object + from fontTools.ttLib.woff2 import WOFF2Writer + + return object.__new__(WOFF2Writer) + # return default object + return object.__new__(cls) + + def __init__( + self, + file, + numTables, + sfntVersion="\000\001\000\000", + flavor=None, + flavorData=None, + ): + self.file = file + self.numTables = numTables + self.sfntVersion = Tag(sfntVersion) + self.flavor = flavor + self.flavorData = flavorData + + if self.flavor == "woff": + self.directoryFormat = woffDirectoryFormat + self.directorySize = woffDirectorySize + self.DirectoryEntry = WOFFDirectoryEntry + + self.signature = "wOFF" + + # to calculate WOFF checksum adjustment, we also need the original SFNT offsets + self.origNextTableOffset = ( + sfntDirectorySize + numTables * sfntDirectoryEntrySize + ) + else: + assert not self.flavor, "Unknown flavor '%s'" % self.flavor + self.directoryFormat = sfntDirectoryFormat + self.directorySize = sfntDirectorySize + self.DirectoryEntry = SFNTDirectoryEntry + + from fontTools.ttLib import getSearchRange + + self.searchRange, self.entrySelector, self.rangeShift = getSearchRange( + numTables, 16 + ) + + self.directoryOffset = self.file.tell() + self.nextTableOffset = ( + self.directoryOffset + + self.directorySize + + numTables * self.DirectoryEntry.formatSize + ) + # clear out directory area + self.file.seek(self.nextTableOffset) + # make sure we're actually where we want to be. (old cStringIO bug) + self.file.write(b"\0" * (self.nextTableOffset - self.file.tell())) + self.tables = OrderedDict() + + def setEntry(self, tag, entry): + if tag in self.tables: + raise TTLibError("cannot rewrite '%s' table" % tag) + + self.tables[tag] = entry + + def __setitem__(self, tag, data): + """Write raw table data to disk.""" + if tag in self.tables: + raise TTLibError("cannot rewrite '%s' table" % tag) + + entry = self.DirectoryEntry() + entry.tag = tag + entry.offset = self.nextTableOffset + if tag == "head": + entry.checkSum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:]) + self.headTable = data + entry.uncompressed = True + else: + entry.checkSum = calcChecksum(data) + entry.saveData(self.file, data) + + if self.flavor == "woff": + entry.origOffset = self.origNextTableOffset + self.origNextTableOffset += (entry.origLength + 3) & ~3 + + self.nextTableOffset = self.nextTableOffset + ((entry.length + 3) & ~3) + # Add NUL bytes to pad the table data to a 4-byte boundary. + # Don't depend on f.seek() as we need to add the padding even if no + # subsequent write follows (seek is lazy), ie. after the final table + # in the font. + self.file.write(b"\0" * (self.nextTableOffset - self.file.tell())) + assert self.nextTableOffset == self.file.tell() + + self.setEntry(tag, entry) + + def __getitem__(self, tag): + return self.tables[tag] + + def close(self): + """All tables must have been written to disk. Now write the + directory. + """ + tables = sorted(self.tables.items()) + if len(tables) != self.numTables: + raise TTLibError( + "wrong number of tables; expected %d, found %d" + % (self.numTables, len(tables)) + ) + + if self.flavor == "woff": + self.signature = b"wOFF" + self.reserved = 0 + + self.totalSfntSize = 12 + self.totalSfntSize += 16 * len(tables) + for tag, entry in tables: + self.totalSfntSize += (entry.origLength + 3) & ~3 + + data = self.flavorData if self.flavorData else WOFFFlavorData() + if data.majorVersion is not None and data.minorVersion is not None: + self.majorVersion = data.majorVersion + self.minorVersion = data.minorVersion + else: + if hasattr(self, "headTable"): + self.majorVersion, self.minorVersion = struct.unpack( + ">HH", self.headTable[4:8] + ) + else: + self.majorVersion = self.minorVersion = 0 + if data.metaData: + self.metaOrigLength = len(data.metaData) + self.file.seek(0, 2) + self.metaOffset = self.file.tell() + compressedMetaData = compress(data.metaData) + self.metaLength = len(compressedMetaData) + self.file.write(compressedMetaData) + else: + self.metaOffset = self.metaLength = self.metaOrigLength = 0 + if data.privData: + self.file.seek(0, 2) + off = self.file.tell() + paddedOff = (off + 3) & ~3 + self.file.write(b"\0" * (paddedOff - off)) + self.privOffset = self.file.tell() + self.privLength = len(data.privData) + self.file.write(data.privData) + else: + self.privOffset = self.privLength = 0 + + self.file.seek(0, 2) + self.length = self.file.tell() + + else: + assert not self.flavor, "Unknown flavor '%s'" % self.flavor + pass + + directory = sstruct.pack(self.directoryFormat, self) + + self.file.seek(self.directoryOffset + self.directorySize) + seenHead = 0 + for tag, entry in tables: + if tag == "head": + seenHead = 1 + directory = directory + entry.toString() + if seenHead: + self.writeMasterChecksum(directory) + self.file.seek(self.directoryOffset) + self.file.write(directory) + + def _calcMasterChecksum(self, directory): + # calculate checkSumAdjustment + checksums = [] + for tag in self.tables.keys(): + checksums.append(self.tables[tag].checkSum) + + if self.DirectoryEntry != SFNTDirectoryEntry: + # Create a SFNT directory for checksum calculation purposes + from fontTools.ttLib import getSearchRange + + self.searchRange, self.entrySelector, self.rangeShift = getSearchRange( + self.numTables, 16 + ) + directory = sstruct.pack(sfntDirectoryFormat, self) + tables = sorted(self.tables.items()) + for tag, entry in tables: + sfntEntry = SFNTDirectoryEntry() + sfntEntry.tag = entry.tag + sfntEntry.checkSum = entry.checkSum + sfntEntry.offset = entry.origOffset + sfntEntry.length = entry.origLength + directory = directory + sfntEntry.toString() + + directory_end = sfntDirectorySize + len(self.tables) * sfntDirectoryEntrySize + assert directory_end == len(directory) + + checksums.append(calcChecksum(directory)) + checksum = sum(checksums) & 0xFFFFFFFF + # BiboAfba! + checksumadjustment = (0xB1B0AFBA - checksum) & 0xFFFFFFFF + return checksumadjustment + + def writeMasterChecksum(self, directory): + checksumadjustment = self._calcMasterChecksum(directory) + # write the checksum to the file + self.file.seek(self.tables["head"].offset + 8) + self.file.write(struct.pack(">L", checksumadjustment)) + + def reordersTables(self): + return False + + +# -- sfnt directory helpers and cruft + +ttcHeaderFormat = """ + > # big endian + TTCTag: 4s # "ttcf" + Version: L # 0x00010000 or 0x00020000 + numFonts: L # number of fonts + # OffsetTable[numFonts]: L # array with offsets from beginning of file + # ulDsigTag: L # version 2.0 only + # ulDsigLength: L # version 2.0 only + # ulDsigOffset: L # version 2.0 only +""" + +ttcHeaderSize = sstruct.calcsize(ttcHeaderFormat) + +ttcTailFormatV2 = """ + > # big endian + ulDsigTag: L # version 2.0 only + ulDsigLength: L # version 2.0 only + ulDsigOffset: L # version 2.0 only +""" + +ttcTailSizeV2 = sstruct.calcsize(ttcTailFormatV2) + +TTC_V1 = 0x00010000 +TTC_V2 = 0x00020000 + +sfntDirectoryFormat = """ + > # big endian + sfntVersion: 4s + numTables: H # number of tables + searchRange: H # (max2 <= numTables)*16 + entrySelector: H # log2(max2 <= numTables) + rangeShift: H # numTables*16-searchRange +""" + +sfntDirectorySize = sstruct.calcsize(sfntDirectoryFormat) + +sfntDirectoryEntryFormat = """ + > # big endian + tag: 4s + checkSum: L + offset: L + length: L +""" + +sfntDirectoryEntrySize = sstruct.calcsize(sfntDirectoryEntryFormat) + +woffDirectoryFormat = """ + > # big endian + signature: 4s # "wOFF" + sfntVersion: 4s + length: L # total woff file size + numTables: H # number of tables + reserved: H # set to 0 + totalSfntSize: L # uncompressed size + majorVersion: H # major version of WOFF file + minorVersion: H # minor version of WOFF file + metaOffset: L # offset to metadata block + metaLength: L # length of compressed metadata + metaOrigLength: L # length of uncompressed metadata + privOffset: L # offset to private data block + privLength: L # length of private data block +""" + +woffDirectorySize = sstruct.calcsize(woffDirectoryFormat) + +woffDirectoryEntryFormat = """ + > # big endian + tag: 4s + offset: L + length: L # compressed length + origLength: L # original length + checkSum: L # original checksum +""" + +woffDirectoryEntrySize = sstruct.calcsize(woffDirectoryEntryFormat) + + +class DirectoryEntry(object): + def __init__(self): + self.uncompressed = False # if True, always embed entry raw + + def fromFile(self, file): + data = file.read(self.formatSize) + if len(data) != self.formatSize: + # A file truncated inside the table directory, or one whose + # numTables is corrupt, would otherwise fail with a struct.error. + raise TTLibError( + "unexpected end of table directory: expected %d bytes but got %d" + % (self.formatSize, len(data)) + ) + sstruct.unpack(self.format, data, self) + + def fromString(self, str): + sstruct.unpack(self.format, str, self) + + def toString(self): + return sstruct.pack(self.format, self) + + def __repr__(self): + if hasattr(self, "tag"): + return "<%s '%s' at %x>" % (self.__class__.__name__, self.tag, id(self)) + else: + return "<%s at %x>" % (self.__class__.__name__, id(self)) + + def loadData(self, file): + file.seek(self.offset) + data = file.read(self.length) + if len(data) != self.length: + # A corrupt or truncated table directory entry can point past the + # end of the file; raise a TTLibError instead of a bare assertion + # (which is also silently skipped under `python -O`). + tag = getattr(self, "tag", None) + raise TTLibError( + "unexpected end of '%s' table data: expected %d bytes but got " + "%d at offset %d" + % ( + Tag(tag) if tag is not None else "????", + self.length, + len(data), + self.offset, + ) + ) + if hasattr(self.__class__, "decodeData"): + data = self.decodeData(data) + return data + + def saveData(self, file, data): + if hasattr(self.__class__, "encodeData"): + data = self.encodeData(data) + self.length = len(data) + file.seek(self.offset) + file.write(data) + + def decodeData(self, rawData): + return rawData + + def encodeData(self, data): + return data + + +class SFNTDirectoryEntry(DirectoryEntry): + format = sfntDirectoryEntryFormat + formatSize = sfntDirectoryEntrySize + + +class WOFFDirectoryEntry(DirectoryEntry): + format = woffDirectoryEntryFormat + formatSize = woffDirectoryEntrySize + + def __init__(self): + super(WOFFDirectoryEntry, self).__init__() + # With fonttools<=3.1.2, the only way to set a different zlib + # compression level for WOFF directory entries was to set the class + # attribute 'zlibCompressionLevel'. This is now replaced by a globally + # defined `ZLIB_COMPRESSION_LEVEL`, which is also applied when + # compressing the metadata. For backward compatibility, we still + # use the class attribute if it was already set. + if not hasattr(WOFFDirectoryEntry, "zlibCompressionLevel"): + self.zlibCompressionLevel = ZLIB_COMPRESSION_LEVEL + + def decodeData(self, rawData): + import zlib + + if self.length == self.origLength: + data = rawData + else: + assert self.length < self.origLength + data = zlib.decompress(rawData) + assert len(data) == self.origLength + return data + + def encodeData(self, data): + self.origLength = len(data) + if not self.uncompressed: + compressedData = compress(data, self.zlibCompressionLevel) + if self.uncompressed or len(compressedData) >= self.origLength: + # Encode uncompressed + rawData = data + self.length = self.origLength + else: + rawData = compressedData + self.length = len(rawData) + return rawData + + +class WOFFFlavorData: + Flavor = "woff" + + def __init__(self, reader=None): + self.majorVersion = None + self.minorVersion = None + self.metaData = None + self.privData = None + if reader: + self.majorVersion = reader.majorVersion + self.minorVersion = reader.minorVersion + if reader.metaLength: + reader.file.seek(reader.metaOffset) + rawData = reader.file.read(reader.metaLength) + assert len(rawData) == reader.metaLength + data = self._decompress(rawData) + assert len(data) == reader.metaOrigLength + self.metaData = data + if reader.privLength: + reader.file.seek(reader.privOffset) + data = reader.file.read(reader.privLength) + assert len(data) == reader.privLength + self.privData = data + + def _decompress(self, rawData): + import zlib + + return zlib.decompress(rawData) + + +def calcChecksum(data): + """Calculate the checksum for an arbitrary block of data. + + If the data length is not a multiple of four, it assumes + it is to be padded with null byte. + + >>> print(calcChecksum(b"abcd")) + 1633837924 + >>> print(calcChecksum(b"abcdxyz")) + 3655064932 + """ + remainder = len(data) % 4 + if remainder: + data += b"\0" * (4 - remainder) + value = 0 + blockSize = 4096 + assert blockSize % 4 == 0 + for i in range(0, len(data), blockSize): + block = data[i : i + blockSize] + longs = struct.unpack(">%dL" % (len(block) // 4), block) + value = (value + sum(longs)) & 0xFFFFFFFF + return value + + +def readTTCHeader(file): + file.seek(0) + data = file.read(ttcHeaderSize) + if len(data) != ttcHeaderSize: + raise TTLibError("Not a Font Collection (not enough data)") + self = SimpleNamespace() + sstruct.unpack(ttcHeaderFormat, data, self) + if self.TTCTag != "ttcf": + raise TTLibError("Not a Font Collection") + assert self.Version in (TTC_V1, TTC_V2), ( + "unrecognized TTC version 0x%08x" % self.Version + ) + self.offsetTable = struct.unpack( + ">%dL" % self.numFonts, file.read(self.numFonts * 4) + ) + if self.Version == TTC_V2: + # Unpack additional DSIG fields + data = file.read(ttcTailSizeV2) + if len(data) != ttcTailSizeV2: + raise TTLibError("Not a Font Collection (not enough data)") + sstruct.unpack(ttcTailFormatV2, data, self) + return self + + +def writeTTCHeader(file, numFonts, version=TTC_V1): + self = SimpleNamespace() + self.TTCTag = "ttcf" + self.Version = version + assert self.Version in (TTC_V1, TTC_V2), ( + "unrecognized TTC version 0x%08x" % self.Version + ) + self.numFonts = numFonts + file.seek(0) + file.write(sstruct.pack(ttcHeaderFormat, self)) + offset = file.tell() + file.write(struct.pack(">%dL" % self.numFonts, *([0] * self.numFonts))) + if version == TTC_V2: + # write empty ulDsigTag, ulDsigLength, ulDsigOffset + # Actual values are be written in TTCollection.save() + file.write(struct.pack(">3L", 0, 0, 0)) + return offset + + +if __name__ == "__main__": + import sys + import doctest + + sys.exit(doctest.testmod().failed) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/standardGlyphOrder.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/standardGlyphOrder.py new file mode 100644 index 0000000000000000000000000000000000000000..4062385240096ac822814aebb8bf7c59cf003a8f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/standardGlyphOrder.py @@ -0,0 +1,271 @@ +# +# 'post' table formats 1.0 and 2.0 rely on this list of "standard" +# glyphs. +# +# My list is correct according to the Apple documentation for the 'post' table: +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html +# (However, it seems that TTFdump (from MS) and FontLab disagree, at +# least with respect to the last glyph, which they list as 'dslash' +# instead of 'dcroat'.) +# + +standardGlyphOrder = [ + ".notdef", # 0 + ".null", # 1 + "nonmarkingreturn", # 2 + "space", # 3 + "exclam", # 4 + "quotedbl", # 5 + "numbersign", # 6 + "dollar", # 7 + "percent", # 8 + "ampersand", # 9 + "quotesingle", # 10 + "parenleft", # 11 + "parenright", # 12 + "asterisk", # 13 + "plus", # 14 + "comma", # 15 + "hyphen", # 16 + "period", # 17 + "slash", # 18 + "zero", # 19 + "one", # 20 + "two", # 21 + "three", # 22 + "four", # 23 + "five", # 24 + "six", # 25 + "seven", # 26 + "eight", # 27 + "nine", # 28 + "colon", # 29 + "semicolon", # 30 + "less", # 31 + "equal", # 32 + "greater", # 33 + "question", # 34 + "at", # 35 + "A", # 36 + "B", # 37 + "C", # 38 + "D", # 39 + "E", # 40 + "F", # 41 + "G", # 42 + "H", # 43 + "I", # 44 + "J", # 45 + "K", # 46 + "L", # 47 + "M", # 48 + "N", # 49 + "O", # 50 + "P", # 51 + "Q", # 52 + "R", # 53 + "S", # 54 + "T", # 55 + "U", # 56 + "V", # 57 + "W", # 58 + "X", # 59 + "Y", # 60 + "Z", # 61 + "bracketleft", # 62 + "backslash", # 63 + "bracketright", # 64 + "asciicircum", # 65 + "underscore", # 66 + "grave", # 67 + "a", # 68 + "b", # 69 + "c", # 70 + "d", # 71 + "e", # 72 + "f", # 73 + "g", # 74 + "h", # 75 + "i", # 76 + "j", # 77 + "k", # 78 + "l", # 79 + "m", # 80 + "n", # 81 + "o", # 82 + "p", # 83 + "q", # 84 + "r", # 85 + "s", # 86 + "t", # 87 + "u", # 88 + "v", # 89 + "w", # 90 + "x", # 91 + "y", # 92 + "z", # 93 + "braceleft", # 94 + "bar", # 95 + "braceright", # 96 + "asciitilde", # 97 + "Adieresis", # 98 + "Aring", # 99 + "Ccedilla", # 100 + "Eacute", # 101 + "Ntilde", # 102 + "Odieresis", # 103 + "Udieresis", # 104 + "aacute", # 105 + "agrave", # 106 + "acircumflex", # 107 + "adieresis", # 108 + "atilde", # 109 + "aring", # 110 + "ccedilla", # 111 + "eacute", # 112 + "egrave", # 113 + "ecircumflex", # 114 + "edieresis", # 115 + "iacute", # 116 + "igrave", # 117 + "icircumflex", # 118 + "idieresis", # 119 + "ntilde", # 120 + "oacute", # 121 + "ograve", # 122 + "ocircumflex", # 123 + "odieresis", # 124 + "otilde", # 125 + "uacute", # 126 + "ugrave", # 127 + "ucircumflex", # 128 + "udieresis", # 129 + "dagger", # 130 + "degree", # 131 + "cent", # 132 + "sterling", # 133 + "section", # 134 + "bullet", # 135 + "paragraph", # 136 + "germandbls", # 137 + "registered", # 138 + "copyright", # 139 + "trademark", # 140 + "acute", # 141 + "dieresis", # 142 + "notequal", # 143 + "AE", # 144 + "Oslash", # 145 + "infinity", # 146 + "plusminus", # 147 + "lessequal", # 148 + "greaterequal", # 149 + "yen", # 150 + "mu", # 151 + "partialdiff", # 152 + "summation", # 153 + "product", # 154 + "pi", # 155 + "integral", # 156 + "ordfeminine", # 157 + "ordmasculine", # 158 + "Omega", # 159 + "ae", # 160 + "oslash", # 161 + "questiondown", # 162 + "exclamdown", # 163 + "logicalnot", # 164 + "radical", # 165 + "florin", # 166 + "approxequal", # 167 + "Delta", # 168 + "guillemotleft", # 169 + "guillemotright", # 170 + "ellipsis", # 171 + "nonbreakingspace", # 172 + "Agrave", # 173 + "Atilde", # 174 + "Otilde", # 175 + "OE", # 176 + "oe", # 177 + "endash", # 178 + "emdash", # 179 + "quotedblleft", # 180 + "quotedblright", # 181 + "quoteleft", # 182 + "quoteright", # 183 + "divide", # 184 + "lozenge", # 185 + "ydieresis", # 186 + "Ydieresis", # 187 + "fraction", # 188 + "currency", # 189 + "guilsinglleft", # 190 + "guilsinglright", # 191 + "fi", # 192 + "fl", # 193 + "daggerdbl", # 194 + "periodcentered", # 195 + "quotesinglbase", # 196 + "quotedblbase", # 197 + "perthousand", # 198 + "Acircumflex", # 199 + "Ecircumflex", # 200 + "Aacute", # 201 + "Edieresis", # 202 + "Egrave", # 203 + "Iacute", # 204 + "Icircumflex", # 205 + "Idieresis", # 206 + "Igrave", # 207 + "Oacute", # 208 + "Ocircumflex", # 209 + "apple", # 210 + "Ograve", # 211 + "Uacute", # 212 + "Ucircumflex", # 213 + "Ugrave", # 214 + "dotlessi", # 215 + "circumflex", # 216 + "tilde", # 217 + "macron", # 218 + "breve", # 219 + "dotaccent", # 220 + "ring", # 221 + "cedilla", # 222 + "hungarumlaut", # 223 + "ogonek", # 224 + "caron", # 225 + "Lslash", # 226 + "lslash", # 227 + "Scaron", # 228 + "scaron", # 229 + "Zcaron", # 230 + "zcaron", # 231 + "brokenbar", # 232 + "Eth", # 233 + "eth", # 234 + "Yacute", # 235 + "yacute", # 236 + "Thorn", # 237 + "thorn", # 238 + "minus", # 239 + "multiply", # 240 + "onesuperior", # 241 + "twosuperior", # 242 + "threesuperior", # 243 + "onehalf", # 244 + "onequarter", # 245 + "threequarters", # 246 + "franc", # 247 + "Gbreve", # 248 + "gbreve", # 249 + "Idotaccent", # 250 + "Scedilla", # 251 + "scedilla", # 252 + "Cacute", # 253 + "cacute", # 254 + "Ccaron", # 255 + "ccaron", # 256 + "dcroat", # 257 +] diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/B_A_S_E_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/B_A_S_E_.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4b1c3c5a7a3fe53de316dfd9b23fe5096eeb37 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/B_A_S_E_.py @@ -0,0 +1,14 @@ +from .otBase import BaseTTXConverter + + +class table_B_A_S_E_(BaseTTXConverter): + """Baseline table + + The ``BASE`` table contains information needed to align glyphs in + different scripts, from different fonts, or at different sizes + within the same line of text. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/base + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/BitmapGlyphMetrics.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/BitmapGlyphMetrics.py new file mode 100644 index 0000000000000000000000000000000000000000..3cc997c784c63a61f71860f5684266e122028ed6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/BitmapGlyphMetrics.py @@ -0,0 +1,63 @@ +# Since bitmap glyph metrics are shared between EBLC and EBDT +# this class gets its own python file. +from fontTools.misc import sstruct +from fontTools.misc.textTools import safeEval +import logging + +log = logging.getLogger(__name__) + +bigGlyphMetricsFormat = """ + > # big endian + height: B + width: B + horiBearingX: b + horiBearingY: b + horiAdvance: B + vertBearingX: b + vertBearingY: b + vertAdvance: B +""" + +smallGlyphMetricsFormat = """ + > # big endian + height: B + width: B + BearingX: b + BearingY: b + Advance: B +""" + + +class BitmapGlyphMetrics(object): + def toXML(self, writer, ttFont): + writer.begintag(self.__class__.__name__) + writer.newline() + for metricName in sstruct.getformat(self.__class__.binaryFormat)[1]: + writer.simpletag(metricName, value=getattr(self, metricName)) + writer.newline() + writer.endtag(self.__class__.__name__) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + metricNames = set(sstruct.getformat(self.__class__.binaryFormat)[1]) + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + # Make sure this is a metric that is needed by GlyphMetrics. + if name in metricNames: + vars(self)[name] = safeEval(attrs["value"]) + else: + log.warning( + "unknown name '%s' being ignored in %s.", + name, + self.__class__.__name__, + ) + + +class BigGlyphMetrics(BitmapGlyphMetrics): + binaryFormat = bigGlyphMetricsFormat + + +class SmallGlyphMetrics(BitmapGlyphMetrics): + binaryFormat = smallGlyphMetricsFormat diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_B_D_T_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_B_D_T_.py new file mode 100644 index 0000000000000000000000000000000000000000..0f9924745ebb4519be2d0cdcddadb86cc741cf8b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_B_D_T_.py @@ -0,0 +1,113 @@ +# Copyright 2013 Google, Inc. All Rights Reserved. +# +# Google Author(s): Matt Fontaine + + +from fontTools.misc.textTools import bytesjoin +from fontTools.misc import sstruct +from . import E_B_D_T_ +from .BitmapGlyphMetrics import ( + BigGlyphMetrics, + bigGlyphMetricsFormat, + SmallGlyphMetrics, + smallGlyphMetricsFormat, +) +from .E_B_D_T_ import ( + BitmapGlyph, + BitmapPlusSmallMetricsMixin, + BitmapPlusBigMetricsMixin, +) +import struct + + +class table_C_B_D_T_(E_B_D_T_.table_E_B_D_T_): + """Color Bitmap Data table + + The ``CBDT`` table contains color bitmap data for glyphs. It must + be used in concert with the ``CBLC`` table. + + It is backwards-compatible with the monochrome/grayscale ``EBDT`` table. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/cbdt + """ + + # Change the data locator table being referenced. + locatorName = "CBLC" + + # Modify the format class accessor for color bitmap use. + def getImageFormatClass(self, imageFormat): + try: + return E_B_D_T_.table_E_B_D_T_.getImageFormatClass(self, imageFormat) + except KeyError: + return cbdt_bitmap_classes[imageFormat] + + +# Helper method for removing export features not supported by color bitmaps. +# Write data in the parent class will default to raw if an option is unsupported. +def _removeUnsupportedForColor(dataFunctions): + dataFunctions = dict(dataFunctions) + del dataFunctions["row"] + return dataFunctions + + +class ColorBitmapGlyph(BitmapGlyph): + fileExtension = ".png" + xmlDataFunctions = _removeUnsupportedForColor(BitmapGlyph.xmlDataFunctions) + + +class cbdt_bitmap_format_17(BitmapPlusSmallMetricsMixin, ColorBitmapGlyph): + def decompile(self): + self.metrics = SmallGlyphMetrics() + dummy, data = sstruct.unpack2(smallGlyphMetricsFormat, self.data, self.metrics) + (dataLen,) = struct.unpack(">L", data[:4]) + data = data[4:] + + # For the image data cut it to the size specified by dataLen. + assert dataLen <= len(data), "Data overun in format 17" + self.imageData = data[:dataLen] + + def compile(self, ttFont): + dataList = [] + dataList.append(sstruct.pack(smallGlyphMetricsFormat, self.metrics)) + dataList.append(struct.pack(">L", len(self.imageData))) + dataList.append(self.imageData) + return bytesjoin(dataList) + + +class cbdt_bitmap_format_18(BitmapPlusBigMetricsMixin, ColorBitmapGlyph): + def decompile(self): + self.metrics = BigGlyphMetrics() + dummy, data = sstruct.unpack2(bigGlyphMetricsFormat, self.data, self.metrics) + (dataLen,) = struct.unpack(">L", data[:4]) + data = data[4:] + + # For the image data cut it to the size specified by dataLen. + assert dataLen <= len(data), "Data overun in format 18" + self.imageData = data[:dataLen] + + def compile(self, ttFont): + dataList = [] + dataList.append(sstruct.pack(bigGlyphMetricsFormat, self.metrics)) + dataList.append(struct.pack(">L", len(self.imageData))) + dataList.append(self.imageData) + return bytesjoin(dataList) + + +class cbdt_bitmap_format_19(ColorBitmapGlyph): + def decompile(self): + (dataLen,) = struct.unpack(">L", self.data[:4]) + data = self.data[4:] + + assert dataLen <= len(data), "Data overun in format 19" + self.imageData = data[:dataLen] + + def compile(self, ttFont): + return struct.pack(">L", len(self.imageData)) + self.imageData + + +# Dict for CBDT extended formats. +cbdt_bitmap_classes = { + 17: cbdt_bitmap_format_17, + 18: cbdt_bitmap_format_18, + 19: cbdt_bitmap_format_19, +} diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_B_L_C_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_B_L_C_.py new file mode 100644 index 0000000000000000000000000000000000000000..0673fb7ed2215f481f303c5b98c9941accd916bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_B_L_C_.py @@ -0,0 +1,19 @@ +# Copyright 2013 Google, Inc. All Rights Reserved. +# +# Google Author(s): Matt Fontaine + +from . import E_B_L_C_ + + +class table_C_B_L_C_(E_B_L_C_.table_E_B_L_C_): + """Color Bitmap Location table + + The ``CBLC`` table contains the locations of color bitmaps for glyphs. It must + be used in concert with the ``CBDT`` table. + + It is backwards-compatible with the monochrome/grayscale ``EBLC`` table. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/cblc + """ + + dependencies = ["CBDT"] diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_F_F_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_F_F_.py new file mode 100644 index 0000000000000000000000000000000000000000..3d974ced88e9d9a1e9c0494c4d0eac996ec315b8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_F_F_.py @@ -0,0 +1,61 @@ +from io import BytesIO +from fontTools import cffLib +from . import DefaultTable + + +class table_C_F_F_(DefaultTable.DefaultTable): + """Compact Font Format table (version 1) + + The ``CFF`` table embeds a CFF-formatted font. The CFF font format + predates OpenType and could be used as a standalone font file, but the + ``CFF`` table is also used to package CFF fonts into an OpenType + container. + + .. note:: + ``CFF`` has been succeeded by ``CFF2``, which eliminates much of + the redundancy incurred by embedding CFF version 1 in an OpenType + font. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/cff + """ + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.cff = cffLib.CFFFontSet() + self._gaveGlyphOrder = False + + def decompile(self, data, otFont): + self.cff.decompile(BytesIO(data), otFont, isCFF2=False) + assert len(self.cff) == 1, "can't deal with multi-font CFF tables." + + def compile(self, otFont): + f = BytesIO() + self.cff.compile(f, otFont, isCFF2=False) + return f.getvalue() + + def haveGlyphNames(self): + if hasattr(self.cff[self.cff.fontNames[0]], "ROS"): + return False # CID-keyed font + else: + return True + + def getGlyphOrder(self): + if self._gaveGlyphOrder: + from fontTools import ttLib + + raise ttLib.TTLibError("illegal use of getGlyphOrder()") + self._gaveGlyphOrder = True + return self.cff[self.cff.fontNames[0]].getGlyphOrder() + + def setGlyphOrder(self, glyphOrder): + pass + # XXX + # self.cff[self.cff.fontNames[0]].setGlyphOrder(glyphOrder) + + def toXML(self, writer, otFont): + self.cff.toXML(writer) + + def fromXML(self, name, attrs, content, otFont): + if not hasattr(self, "cff"): + self.cff = cffLib.CFFFontSet() + self.cff.fromXML(name, attrs, content, otFont) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_F_F__2.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_F_F__2.py new file mode 100644 index 0000000000000000000000000000000000000000..ff07682d24f0399b6579f529ae70cf4fd87abf21 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_F_F__2.py @@ -0,0 +1,26 @@ +from io import BytesIO +from fontTools.ttLib.tables.C_F_F_ import table_C_F_F_ + + +class table_C_F_F__2(table_C_F_F_): + """Compact Font Format version 2 table + + The ``CFF2`` table contains glyph data for a CFF2-flavored OpenType + font. + + .. note:: + ``CFF2`` is the successor to ``CFF``, and eliminates much of + the redundancy incurred by embedding CFF version 1 in an OpenType + font. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/cff2 + """ + + def decompile(self, data, otFont): + self.cff.decompile(BytesIO(data), otFont, isCFF2=True) + assert len(self.cff) == 1, "can't deal with multi-font CFF tables." + + def compile(self, otFont): + f = BytesIO() + self.cff.compile(f, otFont, isCFF2=True) + return f.getvalue() diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_O_L_R_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_O_L_R_.py new file mode 100644 index 0000000000000000000000000000000000000000..266a11c41dffc5eed42ee446c0268373104cbf7a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_O_L_R_.py @@ -0,0 +1,165 @@ +# Copyright 2013 Google, Inc. All Rights Reserved. +# +# Google Author(s): Behdad Esfahbod + +from fontTools.misc.textTools import safeEval +from . import DefaultTable + + +class table_C_O_L_R_(DefaultTable.DefaultTable): + """Color table + + The ``COLR`` table defines color presentation of outline glyphs. It must + be used in concert with the ``CPAL`` table, which contains the color + descriptors used. + + This table is structured so that you can treat it like a dictionary keyed by glyph name. + + ``ttFont['COLR'][]`` will return the color layers for any glyph. + + ``ttFont['COLR'][] = `` will set the color layers for any glyph. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/colr + """ + + @staticmethod + def _decompileColorLayersV0(table): + if not table.LayerRecordArray: + return {} + colorLayerLists = {} + layerRecords = table.LayerRecordArray.LayerRecord + numLayerRecords = len(layerRecords) + for baseRec in table.BaseGlyphRecordArray.BaseGlyphRecord: + baseGlyph = baseRec.BaseGlyph + firstLayerIndex = baseRec.FirstLayerIndex + numLayers = baseRec.NumLayers + assert firstLayerIndex + numLayers <= numLayerRecords + layers = [] + for i in range(firstLayerIndex, firstLayerIndex + numLayers): + layerRec = layerRecords[i] + layers.append(LayerRecord(layerRec.LayerGlyph, layerRec.PaletteIndex)) + colorLayerLists[baseGlyph] = layers + return colorLayerLists + + def _toOTTable(self, ttFont): + from . import otTables + from fontTools.colorLib.builder import populateCOLRv0 + + tableClass = getattr(otTables, self.tableTag) + table = tableClass() + table.Version = self.version + + populateCOLRv0( + table, + { + baseGlyph: [(layer.name, layer.colorID) for layer in layers] + for baseGlyph, layers in self.ColorLayers.items() + }, + glyphMap=ttFont.getReverseGlyphMap(rebuild=True), + ) + return table + + def decompile(self, data, ttFont): + from .otBase import OTTableReader + from . import otTables + + # We use otData to decompile, but we adapt the decompiled otTables to the + # existing COLR v0 API for backward compatibility. + reader = OTTableReader(data, tableTag=self.tableTag) + tableClass = getattr(otTables, self.tableTag) + table = tableClass() + table.decompile(reader, ttFont) + + self.version = table.Version + if self.version == 0: + self.ColorLayers = self._decompileColorLayersV0(table) + else: + # for new versions, keep the raw otTables around + self.table = table + + def compile(self, ttFont): + from .otBase import OTTableWriter + + if hasattr(self, "table"): + table = self.table + else: + table = self._toOTTable(ttFont) + + writer = OTTableWriter(tableTag=self.tableTag) + table.compile(writer, ttFont) + return writer.getAllData() + + def toXML(self, writer, ttFont): + if hasattr(self, "table"): + self.table.toXML2(writer, ttFont) + else: + writer.simpletag("version", value=self.version) + writer.newline() + for baseGlyph in sorted(self.ColorLayers.keys(), key=ttFont.getGlyphID): + writer.begintag("ColorGlyph", name=baseGlyph) + writer.newline() + for layer in self.ColorLayers[baseGlyph]: + layer.toXML(writer, ttFont) + writer.endtag("ColorGlyph") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "version": # old COLR v0 API + setattr(self, name, safeEval(attrs["value"])) + elif name == "ColorGlyph": + if not hasattr(self, "ColorLayers"): + self.ColorLayers = {} + glyphName = attrs["name"] + for element in content: + if isinstance(element, str): + continue + layers = [] + for element in content: + if isinstance(element, str): + continue + layer = LayerRecord() + layer.fromXML(element[0], element[1], element[2], ttFont) + layers.append(layer) + self.ColorLayers[glyphName] = layers + else: # new COLR v1 API + from . import otTables + + if not hasattr(self, "table"): + tableClass = getattr(otTables, self.tableTag) + self.table = tableClass() + self.table.fromXML(name, attrs, content, ttFont) + self.table.populateDefaults() + self.version = self.table.Version + + def __getitem__(self, glyphName): + if not isinstance(glyphName, str): + raise TypeError(f"expected str, found {type(glyphName).__name__}") + return self.ColorLayers[glyphName] + + def __setitem__(self, glyphName, value): + if not isinstance(glyphName, str): + raise TypeError(f"expected str, found {type(glyphName).__name__}") + if value is not None: + self.ColorLayers[glyphName] = value + elif glyphName in self.ColorLayers: + del self.ColorLayers[glyphName] + + def __delitem__(self, glyphName): + del self.ColorLayers[glyphName] + + +class LayerRecord(object): + def __init__(self, name=None, colorID=None): + self.name = name + self.colorID = colorID + + def toXML(self, writer, ttFont): + writer.simpletag("layer", name=self.name, colorID=self.colorID) + writer.newline() + + def fromXML(self, eltname, attrs, content, ttFont): + for name, value in attrs.items(): + if name == "name": + setattr(self, name, value) + else: + setattr(self, name, safeEval(value)) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_P_A_L_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_P_A_L_.py new file mode 100644 index 0000000000000000000000000000000000000000..5ec8c843c516f2ac31bbbc9ff2dd0166a3a0e159 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_P_A_L_.py @@ -0,0 +1,305 @@ +# Copyright 2013 Google, Inc. All Rights Reserved. +# +# Google Author(s): Behdad Esfahbod + +from fontTools.misc.textTools import bytesjoin, safeEval +from . import DefaultTable +import array +from collections import namedtuple +import struct +import sys + + +class table_C_P_A_L_(DefaultTable.DefaultTable): + """Color Palette table + + The ``CPAL`` table contains a set of one or more color palettes. The color + records in each palette can be referenced by the ``COLR`` table to specify + the colors used in a color glyph. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/cpal + """ + + NO_NAME_ID = 0xFFFF + DEFAULT_PALETTE_TYPE = 0 + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.palettes = [] + self.paletteTypes = [] + self.paletteLabels = [] + self.paletteEntryLabels = [] + + def decompile(self, data, ttFont): + ( + self.version, + self.numPaletteEntries, + numPalettes, + numColorRecords, + goffsetFirstColorRecord, + ) = struct.unpack(">HHHHL", data[:12]) + assert ( + self.version <= 1 + ), "Version of CPAL table is higher than I know how to handle" + self.palettes = [] + pos = 12 + for i in range(numPalettes): + startIndex = struct.unpack(">H", data[pos : pos + 2])[0] + assert startIndex + self.numPaletteEntries <= numColorRecords + pos += 2 + palette = [] + ppos = goffsetFirstColorRecord + startIndex * 4 + for j in range(self.numPaletteEntries): + palette.append(Color(*struct.unpack(">BBBB", data[ppos : ppos + 4]))) + ppos += 4 + self.palettes.append(palette) + if self.version == 0: + offsetToPaletteTypeArray = 0 + offsetToPaletteLabelArray = 0 + offsetToPaletteEntryLabelArray = 0 + else: + pos = 12 + numPalettes * 2 + ( + offsetToPaletteTypeArray, + offsetToPaletteLabelArray, + offsetToPaletteEntryLabelArray, + ) = struct.unpack(">LLL", data[pos : pos + 12]) + self.paletteTypes = self._decompileUInt32Array( + data, + offsetToPaletteTypeArray, + numPalettes, + default=self.DEFAULT_PALETTE_TYPE, + ) + self.paletteLabels = self._decompileUInt16Array( + data, offsetToPaletteLabelArray, numPalettes, default=self.NO_NAME_ID + ) + self.paletteEntryLabels = self._decompileUInt16Array( + data, + offsetToPaletteEntryLabelArray, + self.numPaletteEntries, + default=self.NO_NAME_ID, + ) + + def _decompileUInt16Array(self, data, offset, numElements, default=0): + if offset == 0: + return [default] * numElements + result = array.array("H", data[offset : offset + 2 * numElements]) + if sys.byteorder != "big": + result.byteswap() + assert len(result) == numElements, result + return result.tolist() + + def _decompileUInt32Array(self, data, offset, numElements, default=0): + if offset == 0: + return [default] * numElements + result = array.array("I", data[offset : offset + 4 * numElements]) + if sys.byteorder != "big": + result.byteswap() + assert len(result) == numElements, result + return result.tolist() + + def compile(self, ttFont): + colorRecordIndices, colorRecords = self._compileColorRecords() + paletteTypes = self._compilePaletteTypes() + paletteLabels = self._compilePaletteLabels() + paletteEntryLabels = self._compilePaletteEntryLabels() + numColorRecords = len(colorRecords) // 4 + offsetToFirstColorRecord = 12 + len(colorRecordIndices) + if self.version >= 1: + offsetToFirstColorRecord += 12 + header = struct.pack( + ">HHHHL", + self.version, + self.numPaletteEntries, + len(self.palettes), + numColorRecords, + offsetToFirstColorRecord, + ) + if self.version == 0: + dataList = [header, colorRecordIndices, colorRecords] + else: + pos = offsetToFirstColorRecord + len(colorRecords) + if len(paletteTypes) == 0: + offsetToPaletteTypeArray = 0 + else: + offsetToPaletteTypeArray = pos + pos += len(paletteTypes) + if len(paletteLabels) == 0: + offsetToPaletteLabelArray = 0 + else: + offsetToPaletteLabelArray = pos + pos += len(paletteLabels) + if len(paletteEntryLabels) == 0: + offsetToPaletteEntryLabelArray = 0 + else: + offsetToPaletteEntryLabelArray = pos + pos += len(paletteLabels) + header1 = struct.pack( + ">LLL", + offsetToPaletteTypeArray, + offsetToPaletteLabelArray, + offsetToPaletteEntryLabelArray, + ) + dataList = [ + header, + colorRecordIndices, + header1, + colorRecords, + paletteTypes, + paletteLabels, + paletteEntryLabels, + ] + return bytesjoin(dataList) + + def _compilePalette(self, palette): + assert len(palette) == self.numPaletteEntries + pack = lambda c: struct.pack(">BBBB", c.blue, c.green, c.red, c.alpha) + return bytesjoin([pack(color) for color in palette]) + + def _compileColorRecords(self): + colorRecords, colorRecordIndices, pool = [], [], {} + for palette in self.palettes: + packedPalette = self._compilePalette(palette) + if packedPalette in pool: + index = pool[packedPalette] + else: + index = len(colorRecords) + colorRecords.append(packedPalette) + pool[packedPalette] = index + colorRecordIndices.append(struct.pack(">H", index * self.numPaletteEntries)) + return bytesjoin(colorRecordIndices), bytesjoin(colorRecords) + + def _compilePaletteTypes(self): + if self.version == 0 or not any(self.paletteTypes): + return b"" + assert len(self.paletteTypes) == len(self.palettes) + result = bytesjoin([struct.pack(">I", ptype) for ptype in self.paletteTypes]) + assert len(result) == 4 * len(self.palettes) + return result + + def _compilePaletteLabels(self): + if self.version == 0 or all(l == self.NO_NAME_ID for l in self.paletteLabels): + return b"" + assert len(self.paletteLabels) == len(self.palettes) + result = bytesjoin([struct.pack(">H", label) for label in self.paletteLabels]) + assert len(result) == 2 * len(self.palettes) + return result + + def _compilePaletteEntryLabels(self): + if self.version == 0 or all( + l == self.NO_NAME_ID for l in self.paletteEntryLabels + ): + return b"" + assert len(self.paletteEntryLabels) == self.numPaletteEntries + result = bytesjoin( + [struct.pack(">H", label) for label in self.paletteEntryLabels] + ) + assert len(result) == 2 * self.numPaletteEntries + return result + + def toXML(self, writer, ttFont): + numPalettes = len(self.palettes) + paletteLabels = {i: nameID for (i, nameID) in enumerate(self.paletteLabels)} + paletteTypes = {i: typ for (i, typ) in enumerate(self.paletteTypes)} + writer.simpletag("version", value=self.version) + writer.newline() + writer.simpletag("numPaletteEntries", value=self.numPaletteEntries) + writer.newline() + for index, palette in enumerate(self.palettes): + attrs = {"index": index} + paletteType = paletteTypes.get(index, self.DEFAULT_PALETTE_TYPE) + paletteLabel = paletteLabels.get(index, self.NO_NAME_ID) + if self.version > 0 and paletteLabel != self.NO_NAME_ID: + attrs["label"] = paletteLabel + if self.version > 0 and paletteType != self.DEFAULT_PALETTE_TYPE: + attrs["type"] = paletteType + writer.begintag("palette", **attrs) + writer.newline() + if ( + self.version > 0 + and paletteLabel != self.NO_NAME_ID + and ttFont + and "name" in ttFont + ): + name = ttFont["name"].getDebugName(paletteLabel) + if name is not None: + writer.comment(name) + writer.newline() + assert len(palette) == self.numPaletteEntries + for cindex, color in enumerate(palette): + color.toXML(writer, ttFont, cindex) + writer.endtag("palette") + writer.newline() + if self.version > 0 and not all( + l == self.NO_NAME_ID for l in self.paletteEntryLabels + ): + writer.begintag("paletteEntryLabels") + writer.newline() + for index, label in enumerate(self.paletteEntryLabels): + if label != self.NO_NAME_ID: + writer.simpletag("label", index=index, value=label) + if self.version > 0 and label and ttFont and "name" in ttFont: + name = ttFont["name"].getDebugName(label) + if name is not None: + writer.comment(name) + writer.newline() + writer.endtag("paletteEntryLabels") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "palette": + self.paletteLabels.append(int(attrs.get("label", self.NO_NAME_ID))) + self.paletteTypes.append(int(attrs.get("type", self.DEFAULT_PALETTE_TYPE))) + palette = [] + for element in content: + if isinstance(element, str): + continue + attrs = element[1] + color = Color.fromHex(attrs["value"]) + palette.append(color) + self.palettes.append(palette) + elif name == "paletteEntryLabels": + colorLabels = {} + for element in content: + if isinstance(element, str): + continue + elementName, elementAttr, _ = element + if elementName == "label": + labelIndex = safeEval(elementAttr["index"]) + nameID = safeEval(elementAttr["value"]) + colorLabels[labelIndex] = nameID + self.paletteEntryLabels = [ + colorLabels.get(i, self.NO_NAME_ID) + for i in range(self.numPaletteEntries) + ] + elif "value" in attrs: + value = safeEval(attrs["value"]) + setattr(self, name, value) + if name == "numPaletteEntries": + self.paletteEntryLabels = [self.NO_NAME_ID] * self.numPaletteEntries + + +class Color(namedtuple("Color", "blue green red alpha")): + def hex(self): + return "#%02X%02X%02X%02X" % (self.red, self.green, self.blue, self.alpha) + + def __repr__(self): + return self.hex() + + def toXML(self, writer, ttFont, index=None): + writer.simpletag("color", value=self.hex(), index=index) + writer.newline() + + @classmethod + def fromHex(cls, value): + if value[0] == "#": + value = value[1:] + red = int(value[0:2], 16) + green = int(value[2:4], 16) + blue = int(value[4:6], 16) + alpha = int(value[6:8], 16) if len(value) >= 8 else 0xFF + return cls(red=red, green=green, blue=blue, alpha=alpha) + + @classmethod + def fromRGBA(cls, red, green, blue, alpha): + return cls(red=red, green=green, blue=blue, alpha=alpha) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/D_S_I_G_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/D_S_I_G_.py new file mode 100644 index 0000000000000000000000000000000000000000..deb7d58d92e0e26664aad32fac6c48ea10a0afc6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/D_S_I_G_.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +import base64 +from typing import TYPE_CHECKING + +from fontTools.misc import sstruct +from fontTools.misc.textTools import bytesjoin, safeEval, strjoin, tobytes, tostr + +from . import DefaultTable + +if TYPE_CHECKING: + from fontTools.misc.xmlWriter import XMLWriter + from fontTools.ttLib import TTFont + +DSIG_HeaderFormat = """ + > # big endian + ulVersion: L + usNumSigs: H + usFlag: H +""" +# followed by an array of usNumSigs DSIG_Signature records +DSIG_SignatureFormat = """ + > # big endian + ulFormat: L + ulLength: L # length includes DSIG_SignatureBlock header + ulOffset: L +""" +# followed by an array of usNumSigs DSIG_SignatureBlock records, +# each followed immediately by the pkcs7 bytes +DSIG_SignatureBlockFormat = """ + > # big endian + usReserved1: H + usReserved2: H + cbSignature: l # length of following raw pkcs7 data +""" + +# +# NOTE +# the DSIG table format allows for SignatureBlocks residing +# anywhere in the table and possibly in a different order as +# listed in the array after the first table header +# +# this implementation does not keep track of any gaps and/or data +# before or after the actual signature blocks while decompiling, +# and puts them in the same physical order as listed in the header +# on compilation with no padding whatsoever. +# + + +class table_D_S_I_G_(DefaultTable.DefaultTable): + """Digital Signature table + + The ``DSIG`` table contains cryptographic signatures for the font. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/dsig + """ + + def decompile(self, data: bytes, ttFont: TTFont) -> None: + dummy, newData = sstruct.unpack2(DSIG_HeaderFormat, data, self) + assert self.ulVersion == 1, "DSIG ulVersion must be 1" + assert self.usFlag & ~1 == 0, "DSIG usFlag must be 0x1 or 0x0" + self.signatureRecords: list[SignatureRecord] = [] + sigrecs = self.signatureRecords + for n in range(self.usNumSigs): + sigrec, newData = sstruct.unpack2( + DSIG_SignatureFormat, newData, SignatureRecord() + ) + assert sigrec.ulFormat == 1, ( + "DSIG signature record #%d ulFormat must be 1" % n + ) + sigrecs.append(sigrec) + for sigrec in sigrecs: + dummy, newData = sstruct.unpack2( + DSIG_SignatureBlockFormat, data[sigrec.ulOffset :], sigrec + ) + assert sigrec.usReserved1 == 0, ( + "DSIG signature record #%d usReserverd1 must be 0" % n + ) + assert sigrec.usReserved2 == 0, ( + "DSIG signature record #%d usReserverd2 must be 0" % n + ) + sigrec.pkcs7 = newData[: sigrec.cbSignature] + + def compile(self, ttFont: TTFont) -> bytes: + packed = sstruct.pack(DSIG_HeaderFormat, self) + headers = [packed] + offset = len(packed) + self.usNumSigs * sstruct.calcsize(DSIG_SignatureFormat) + data = [] + for sigrec in self.signatureRecords: + # first pack signature block + sigrec.cbSignature = len(sigrec.pkcs7) + packed = sstruct.pack(DSIG_SignatureBlockFormat, sigrec) + sigrec.pkcs7 + data.append(packed) + # update redundant length field + sigrec.ulLength = len(packed) + # update running table offset + sigrec.ulOffset = offset + headers.append(sstruct.pack(DSIG_SignatureFormat, sigrec)) + offset += sigrec.ulLength + if offset % 2: + # Pad to even bytes + data.append(b"\0") + return bytesjoin(headers + data) + + def toXML(self, xmlWriter: XMLWriter, ttFont: TTFont) -> None: + xmlWriter.comment( + "note that the Digital Signature will be invalid after recompilation!" + ) + xmlWriter.newline() + xmlWriter.simpletag( + "tableHeader", + version=self.ulVersion, + numSigs=self.usNumSigs, + flag="0x%X" % self.usFlag, + ) + for sigrec in self.signatureRecords: + xmlWriter.newline() + sigrec.toXML(xmlWriter, ttFont) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "tableHeader": + self.signatureRecords = [] + self.ulVersion = safeEval(attrs["version"]) + self.usNumSigs = safeEval(attrs["numSigs"]) + self.usFlag = safeEval(attrs["flag"]) + return + if name == "SignatureRecord": + sigrec = SignatureRecord() + sigrec.fromXML(name, attrs, content, ttFont) + self.signatureRecords.append(sigrec) + + +pem_spam = lambda l, spam={ + "-----BEGIN PKCS7-----": True, + "-----END PKCS7-----": True, + "": True, +}: not spam.get(l.strip()) + + +def b64encode(b): + s = base64.b64encode(b) + # Line-break at 76 chars. + items = [] + while s: + items.append(tostr(s[:76])) + items.append("\n") + s = s[76:] + return strjoin(items) + + +class SignatureRecord: + def __repr__(self) -> str: + return "<%s: %s>" % (self.__class__.__name__, self.__dict__) + + def toXML(self, writer, ttFont: TTFont) -> None: + writer.begintag(self.__class__.__name__, format=self.ulFormat) + writer.newline() + writer.write_noindent("-----BEGIN PKCS7-----\n") + writer.write_noindent(b64encode(self.pkcs7)) + writer.write_noindent("-----END PKCS7-----\n") + writer.endtag(self.__class__.__name__) + + def fromXML( + self, name: str, attrs: dict[str, str], content: str, ttFont: TTFont + ) -> None: + self.ulFormat: int = safeEval(attrs["format"]) + self.usReserved1: int = safeEval(attrs.get("reserved1", "0")) + self.usReserved2: int = safeEval(attrs.get("reserved2", "0")) + self.pkcs7 = base64.b64decode(tobytes(strjoin(filter(pem_spam, content)))) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/D__e_b_g.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/D__e_b_g.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1653d79d4f99ad729b25c96346459c40a4681e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/D__e_b_g.py @@ -0,0 +1,35 @@ +import json +from textwrap import indent + +from . import DefaultTable +from fontTools.misc.textTools import tostr + + +class table_D__e_b_g(DefaultTable.DefaultTable): + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.data = {} + + def decompile(self, data, ttFont): + self.data = json.loads(data) + + def compile(self, ttFont): + return json.dumps(self.data).encode("utf-8") + + def toXML(self, writer, ttFont): + # make sure json indentation inside CDATA block matches XMLWriter's + data = json.dumps(self.data, indent=len(writer.indentwhite)) + prefix = tostr(writer.indentwhite) * (writer.indentlevel + 1) + # but don't indent the first json line so it's adjacent to ` None: + if tag is None: + tag = getClassTag(self.__class__) + self.tableTag = Tag(tag) + + def decompile(self, data: bytes, ttFont: TTFont) -> None: + self.data = data + + def compile(self, ttFont: TTFont) -> bytes: + return self.data + + def toXML(self, writer: XMLWriter, ttFont: TTFont, **kwargs: Any) -> None: + if hasattr(self, "ERROR"): + writer.comment("An error occurred during the decompilation of this table") + writer.newline() + writer.comment(self.ERROR) + writer.newline() + writer.begintag("hexdata") + writer.newline() + writer.dumphex(self.compile(ttFont)) + writer.endtag("hexdata") + writer.newline() + + def fromXML( + self, name: str, attrs: XMLAttrs, content: XMLContent, ttFont: TTFont + ) -> None: + from fontTools import ttLib + from fontTools.misc.textTools import readHex + + if name != "hexdata": + raise ttLib.TTLibError("can't handle '%s' element" % name) + self.decompile(readHex(content), ttFont) + + def __repr__(self) -> str: + return "<'%s' table at %x>" % (self.tableTag, id(self)) + + def __eq__(self, other: object) -> bool: + if type(self) is not type(other): + return NotImplemented + return self.__dict__ == other.__dict__ + + def __ne__(self, other: object) -> bool: + result = self.__eq__(other) + return result if result is NotImplemented else not result diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_D_T_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_D_T_.py new file mode 100644 index 0000000000000000000000000000000000000000..29edc4aa1b82b287808233b1de606631cd1335e0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_D_T_.py @@ -0,0 +1,856 @@ +from fontTools.misc import sstruct +from fontTools.misc.textTools import ( + bytechr, + byteord, + bytesjoin, + strjoin, + safeEval, + readHex, + hexStr, + deHexStr, +) +from .BitmapGlyphMetrics import ( + BigGlyphMetrics, + bigGlyphMetricsFormat, + SmallGlyphMetrics, + smallGlyphMetricsFormat, +) +from . import DefaultTable +import itertools +import os +import re +from urllib.parse import quote + +# a glyph name is usable as a filename as-is unless it contains a path +# separator (on any platform, not just this one) or the '%' that marks an +# encoded name +_UNSAFE_IN_FILENAME = re.compile(r"[%/\\]") +import struct +import logging + +log = logging.getLogger(__name__) + +ebdtTableVersionFormat = """ + > # big endian + version: 16.16F +""" + +ebdtComponentFormat = """ + > # big endian + glyphCode: H + xOffset: b + yOffset: b +""" + + +class table_E_B_D_T_(DefaultTable.DefaultTable): + """Embedded Bitmap Data table + + The ``EBDT`` table contains monochrome or grayscale bitmap data for + glyphs. It must be used in concert with the ``EBLC`` table. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt + """ + + # Keep a reference to the name of the data locator table. + locatorName = "EBLC" + + # This method can be overridden in subclasses to support new formats + # without changing the other implementation. Also can be used as a + # convenience method for coverting a font file to an alternative format. + def getImageFormatClass(self, imageFormat): + return ebdt_bitmap_classes[imageFormat] + + def decompile(self, data, ttFont): + # Get the version but don't advance the slice. + # Most of the lookup for this table is done relative + # to the begining so slice by the offsets provided + # in the EBLC table. + sstruct.unpack2(ebdtTableVersionFormat, data, self) + + # Keep a dict of glyphs that have been seen so they aren't remade. + # This dict maps intervals of data to the BitmapGlyph. + glyphDict = {} + + # Pull out the EBLC table and loop through glyphs. + # A strike is a concept that spans both tables. + # The actual bitmap data is stored in the EBDT. + locator = ttFont[self.__class__.locatorName] + self.strikeData = [] + for curStrike in locator.strikes: + bitmapGlyphDict = {} + self.strikeData.append(bitmapGlyphDict) + for indexSubTable in curStrike.indexSubTables: + dataIter = zip(indexSubTable.names, indexSubTable.locations) + for curName, curLoc in dataIter: + # Don't create duplicate data entries for the same glyphs. + # Instead just use the structures that already exist if they exist. + if curLoc in glyphDict: + curGlyph = glyphDict[curLoc] + else: + curGlyphData = data[slice(*curLoc)] + imageFormatClass = self.getImageFormatClass( + indexSubTable.imageFormat + ) + curGlyph = imageFormatClass(curGlyphData, ttFont) + glyphDict[curLoc] = curGlyph + bitmapGlyphDict[curName] = curGlyph + + def compile(self, ttFont): + dataList = [] + dataList.append(sstruct.pack(ebdtTableVersionFormat, self)) + dataSize = len(dataList[0]) + + # Keep a dict of glyphs that have been seen so they aren't remade. + # This dict maps the id of the BitmapGlyph to the interval + # in the data. + glyphDict = {} + + # Go through the bitmap glyph data. Just in case the data for a glyph + # changed the size metrics should be recalculated. There are a variety + # of formats and they get stored in the EBLC table. That is why + # recalculation is defered to the EblcIndexSubTable class and just + # pass what is known about bitmap glyphs from this particular table. + locator = ttFont[self.__class__.locatorName] + for curStrike, curGlyphDict in zip(locator.strikes, self.strikeData): + for curIndexSubTable in curStrike.indexSubTables: + dataLocations = [] + for curName in curIndexSubTable.names: + # Handle the data placement based on seeing the glyph or not. + # Just save a reference to the location if the glyph has already + # been saved in compile. This code assumes that glyphs will only + # be referenced multiple times from indexFormat5. By luck the + # code may still work when referencing poorly ordered fonts with + # duplicate references. If there is a font that is unlucky the + # respective compile methods for the indexSubTables will fail + # their assertions. All fonts seem to follow this assumption. + # More complicated packing may be needed if a counter-font exists. + glyph = curGlyphDict[curName] + objectId = id(glyph) + if objectId not in glyphDict: + data = glyph.compile(ttFont) + data = curIndexSubTable.padBitmapData(data) + startByte = dataSize + dataSize += len(data) + endByte = dataSize + dataList.append(data) + dataLoc = (startByte, endByte) + glyphDict[objectId] = dataLoc + else: + dataLoc = glyphDict[objectId] + dataLocations.append(dataLoc) + # Just use the new data locations in the indexSubTable. + # The respective compile implementations will take care + # of any of the problems in the convertion that may arise. + curIndexSubTable.locations = dataLocations + + return bytesjoin(dataList) + + def toXML(self, writer, ttFont): + # When exporting to XML if one of the data export formats + # requires metrics then those metrics may be in the locator. + # In this case populate the bitmaps with "export metrics". + if ttFont.bitmapGlyphDataFormat in ("row", "bitwise"): + locator = ttFont[self.__class__.locatorName] + for curStrike, curGlyphDict in zip(locator.strikes, self.strikeData): + for curIndexSubTable in curStrike.indexSubTables: + for curName in curIndexSubTable.names: + glyph = curGlyphDict[curName] + # I'm not sure which metrics have priority here. + # For now if both metrics exist go with glyph metrics. + if hasattr(glyph, "metrics"): + glyph.exportMetrics = glyph.metrics + else: + glyph.exportMetrics = curIndexSubTable.metrics + glyph.exportBitDepth = curStrike.bitmapSizeTable.bitDepth + + writer.simpletag("header", [("version", self.version)]) + writer.newline() + locator = ttFont[self.__class__.locatorName] + for strikeIndex, bitmapGlyphDict in enumerate(self.strikeData): + writer.begintag("strikedata", [("index", strikeIndex)]) + writer.newline() + for curName, curBitmap in bitmapGlyphDict.items(): + curBitmap.toXML(strikeIndex, curName, writer, ttFont) + writer.endtag("strikedata") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "header": + self.version = safeEval(attrs["version"]) + elif name == "strikedata": + if not hasattr(self, "strikeData"): + self.strikeData = [] + strikeIndex = safeEval(attrs["index"]) + + bitmapGlyphDict = {} + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name[4:].startswith(_bitmapGlyphSubclassPrefix[4:]): + imageFormat = safeEval(name[len(_bitmapGlyphSubclassPrefix) :]) + glyphName = attrs["name"] + imageFormatClass = self.getImageFormatClass(imageFormat) + curGlyph = imageFormatClass(None, None) + curGlyph.fromXML(name, attrs, content, ttFont) + assert glyphName not in bitmapGlyphDict, ( + "Duplicate glyphs with the same name '%s' in the same strike." + % glyphName + ) + bitmapGlyphDict[glyphName] = curGlyph + else: + log.warning("%s being ignored by %s", name, self.__class__.__name__) + + # Grow the strike data array to the appropriate size. The XML + # format allows the strike index value to be out of order. + if strikeIndex >= len(self.strikeData): + self.strikeData += [None] * (strikeIndex + 1 - len(self.strikeData)) + assert ( + self.strikeData[strikeIndex] is None + ), "Duplicate strike EBDT indices." + self.strikeData[strikeIndex] = bitmapGlyphDict + + +class EbdtComponent(object): + def toXML(self, writer, ttFont): + writer.begintag("ebdtComponent", [("name", self.name)]) + writer.newline() + for componentName in sstruct.getformat(ebdtComponentFormat)[1][1:]: + writer.simpletag(componentName, value=getattr(self, componentName)) + writer.newline() + writer.endtag("ebdtComponent") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + self.name = attrs["name"] + componentNames = set(sstruct.getformat(ebdtComponentFormat)[1][1:]) + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name in componentNames: + vars(self)[name] = safeEval(attrs["value"]) + else: + log.warning("unknown name '%s' being ignored by EbdtComponent.", name) + + +# Helper functions for dealing with binary. + + +def _data2binary(data, numBits): + binaryList = [] + for curByte in data: + value = byteord(curByte) + numBitsCut = min(8, numBits) + for i in range(numBitsCut): + if value & 0x1: + binaryList.append("1") + else: + binaryList.append("0") + value = value >> 1 + numBits -= numBitsCut + return strjoin(binaryList) + + +def _binary2data(binary): + byteList = [] + for bitLoc in range(0, len(binary), 8): + byteString = binary[bitLoc : bitLoc + 8] + curByte = 0 + for curBit in reversed(byteString): + curByte = curByte << 1 + if curBit == "1": + curByte |= 1 + byteList.append(bytechr(curByte)) + return bytesjoin(byteList) + + +def _memoize(f): + class memodict(dict): + def __missing__(self, key): + ret = f(key) + if isinstance(key, int) or len(key) == 1: + self[key] = ret + return ret + + return memodict().__getitem__ + + +# 00100111 -> 11100100 per byte, not to be confused with little/big endian. +# Bitmap data per byte is in the order that binary is written on the page +# with the least significant bit as far right as possible. This is the +# opposite of what makes sense algorithmically and hence this function. +@_memoize +def _reverseBytes(data): + r""" + >>> bin(ord(_reverseBytes(0b00100111))) + '0b11100100' + >>> _reverseBytes(b'\x00\xf0') + b'\x00\x0f' + """ + if isinstance(data, bytes) and len(data) != 1: + return bytesjoin(map(_reverseBytes, data)) + byte = byteord(data) + result = 0 + for i in range(8): + result = result << 1 + result |= byte & 1 + byte = byte >> 1 + return bytechr(result) + + +# This section of code is for reading and writing image data to/from XML. + + +def _writeRawImageData(strikeIndex, glyphName, bitmapObject, writer, ttFont): + writer.begintag("rawimagedata") + writer.newline() + writer.dumphex(bitmapObject.imageData) + writer.endtag("rawimagedata") + writer.newline() + + +def _readRawImageData(bitmapObject, name, attrs, content, ttFont): + bitmapObject.imageData = readHex(content) + + +def _writeRowImageData(strikeIndex, glyphName, bitmapObject, writer, ttFont): + metrics = bitmapObject.exportMetrics + del bitmapObject.exportMetrics + bitDepth = bitmapObject.exportBitDepth + del bitmapObject.exportBitDepth + + writer.begintag( + "rowimagedata", bitDepth=bitDepth, width=metrics.width, height=metrics.height + ) + writer.newline() + for curRow in range(metrics.height): + rowData = bitmapObject.getRow(curRow, bitDepth=bitDepth, metrics=metrics) + writer.simpletag("row", value=hexStr(rowData)) + writer.newline() + writer.endtag("rowimagedata") + writer.newline() + + +def _readRowImageData(bitmapObject, name, attrs, content, ttFont): + bitDepth = safeEval(attrs["bitDepth"]) + metrics = SmallGlyphMetrics() + metrics.width = safeEval(attrs["width"]) + metrics.height = safeEval(attrs["height"]) + + dataRows = [] + for element in content: + if not isinstance(element, tuple): + continue + name, attr, content = element + # Chop off 'imagedata' from the tag to get just the option. + if name == "row": + dataRows.append(deHexStr(attr["value"])) + bitmapObject.setRows(dataRows, bitDepth=bitDepth, metrics=metrics) + + +def _writeBitwiseImageData(strikeIndex, glyphName, bitmapObject, writer, ttFont): + metrics = bitmapObject.exportMetrics + del bitmapObject.exportMetrics + bitDepth = bitmapObject.exportBitDepth + del bitmapObject.exportBitDepth + + # A dict for mapping binary to more readable/artistic ASCII characters. + binaryConv = {"0": ".", "1": "@"} + + writer.begintag( + "bitwiseimagedata", + bitDepth=bitDepth, + width=metrics.width, + height=metrics.height, + ) + writer.newline() + for curRow in range(metrics.height): + rowData = bitmapObject.getRow( + curRow, bitDepth=1, metrics=metrics, reverseBytes=True + ) + rowData = _data2binary(rowData, metrics.width) + # Make the output a readable ASCII art form. + rowData = strjoin(map(binaryConv.get, rowData)) + writer.simpletag("row", value=rowData) + writer.newline() + writer.endtag("bitwiseimagedata") + writer.newline() + + +def _readBitwiseImageData(bitmapObject, name, attrs, content, ttFont): + bitDepth = safeEval(attrs["bitDepth"]) + metrics = SmallGlyphMetrics() + metrics.width = safeEval(attrs["width"]) + metrics.height = safeEval(attrs["height"]) + + # A dict for mapping from ASCII to binary. All characters are considered + # a '1' except space, period and '0' which maps to '0'. + binaryConv = {" ": "0", ".": "0", "0": "0"} + + dataRows = [] + for element in content: + if not isinstance(element, tuple): + continue + name, attr, content = element + if name == "row": + mapParams = zip(attr["value"], itertools.repeat("1")) + rowData = strjoin(itertools.starmap(binaryConv.get, mapParams)) + dataRows.append(_binary2data(rowData)) + + bitmapObject.setRows( + dataRows, bitDepth=bitDepth, metrics=metrics, reverseBytes=True + ) + + +def _extFileName(glyphName): + # Glyph names come straight from the font and may contain path separators + # (e.g. a crafted 'post' table), which would let the exported bitmap escape + # the output folder. Names that are usable as a filename verbatim -- i.e. + # every real glyph name -- are returned unchanged, so existing exports keep + # their filenames; the rest are percent-encoded and marked with a leading + # '%'. The mapping has to be injective, or two glyphs quietly share one + # file and the second overwrites the first: a plain name is never encoded + # and never contains '%', an encoded one always starts with '%', and + # percent-encoding is itself reversible, so no two names can meet. + if glyphName not in ("", ".", "..") and not _UNSAFE_IN_FILENAME.search(glyphName): + return glyphName + return "%" + quote(glyphName, safe="", encoding="utf-8", errors="surrogatepass") + + +def _writeExtFileImageData(strikeIndex, glyphName, bitmapObject, writer, ttFont): + try: + folder = os.path.dirname(writer.file.name) + except AttributeError: + # fall back to current directory if output file's directory isn't found + folder = "." + folder = os.path.join(folder, "bitmaps") + filename = _extFileName(glyphName) + bitmapObject.fileExtension + if not os.path.isdir(folder): + os.makedirs(folder) + folder = os.path.join(folder, "strike%d" % strikeIndex) + if not os.path.isdir(folder): + os.makedirs(folder) + + fullPath = os.path.join(folder, filename) + writer.simpletag("extfileimagedata", value=fullPath) + writer.newline() + + with open(fullPath, "wb") as file: + file.write(bitmapObject.imageData) + + +def _readExtFileImageData(bitmapObject, name, attrs, content, ttFont): + fullPath = attrs["value"] + with open(fullPath, "rb") as file: + bitmapObject.imageData = file.read() + + +# End of XML writing code. + +# Important information about the naming scheme. Used for identifying formats +# in XML. +_bitmapGlyphSubclassPrefix = "ebdt_bitmap_format_" + + +class BitmapGlyph(object): + # For the external file format. This can be changed in subclasses. This way + # when the extfile option is turned on files have the form: glyphName.ext + # The default is just a flat binary file with no meaning. + fileExtension = ".bin" + + # Keep track of reading and writing of various forms. + xmlDataFunctions = { + "raw": (_writeRawImageData, _readRawImageData), + "row": (_writeRowImageData, _readRowImageData), + "bitwise": (_writeBitwiseImageData, _readBitwiseImageData), + "extfile": (_writeExtFileImageData, _readExtFileImageData), + } + + def __init__(self, data, ttFont): + self.data = data + self.ttFont = ttFont + # TODO Currently non-lazy decompilation is untested here... + # if not ttFont.lazy: + # self.decompile() + # del self.data + + def __getattr__(self, attr): + # Allow lazy decompile. + if attr[:2] == "__": + raise AttributeError(attr) + if attr == "data": + raise AttributeError(attr) + self.decompile() + del self.data + return getattr(self, attr) + + def ensureDecompiled(self, recurse=False): + if hasattr(self, "data"): + self.decompile() + del self.data + + # Not a fan of this but it is needed for safer safety checking. + def getFormat(self): + return safeEval(self.__class__.__name__[len(_bitmapGlyphSubclassPrefix) :]) + + def toXML(self, strikeIndex, glyphName, writer, ttFont): + writer.begintag(self.__class__.__name__, [("name", glyphName)]) + writer.newline() + + self.writeMetrics(writer, ttFont) + # Use the internal write method to write using the correct output format. + self.writeData(strikeIndex, glyphName, writer, ttFont) + + writer.endtag(self.__class__.__name__) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + self.readMetrics(name, attrs, content, ttFont) + for element in content: + if not isinstance(element, tuple): + continue + name, attr, content = element + if not name.endswith("imagedata"): + continue + # Chop off 'imagedata' from the tag to get just the option. + option = name[: -len("imagedata")] + assert option in self.__class__.xmlDataFunctions + self.readData(name, attr, content, ttFont) + + # Some of the glyphs have the metrics. This allows for metrics to be + # added if the glyph format has them. Default behavior is to do nothing. + def writeMetrics(self, writer, ttFont): + pass + + # The opposite of write metrics. + def readMetrics(self, name, attrs, content, ttFont): + pass + + def writeData(self, strikeIndex, glyphName, writer, ttFont): + try: + writeFunc, readFunc = self.__class__.xmlDataFunctions[ + ttFont.bitmapGlyphDataFormat + ] + except KeyError: + writeFunc = _writeRawImageData + writeFunc(strikeIndex, glyphName, self, writer, ttFont) + + def readData(self, name, attrs, content, ttFont): + # Chop off 'imagedata' from the tag to get just the option. + option = name[: -len("imagedata")] + writeFunc, readFunc = self.__class__.xmlDataFunctions[option] + readFunc(self, name, attrs, content, ttFont) + + +# A closure for creating a mixin for the two types of metrics handling. +# Most of the code is very similar so its easier to deal with here. +# Everything works just by passing the class that the mixin is for. +def _createBitmapPlusMetricsMixin(metricsClass): + # Both metrics names are listed here to make meaningful error messages. + metricStrings = [BigGlyphMetrics.__name__, SmallGlyphMetrics.__name__] + curMetricsName = metricsClass.__name__ + # Find which metrics this is for and determine the opposite name. + metricsId = metricStrings.index(curMetricsName) + oppositeMetricsName = metricStrings[1 - metricsId] + + class BitmapPlusMetricsMixin(object): + def writeMetrics(self, writer, ttFont): + self.metrics.toXML(writer, ttFont) + + def readMetrics(self, name, attrs, content, ttFont): + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name == curMetricsName: + self.metrics = metricsClass() + self.metrics.fromXML(name, attrs, content, ttFont) + elif name == oppositeMetricsName: + log.warning( + "Warning: %s being ignored in format %d.", + oppositeMetricsName, + self.getFormat(), + ) + + return BitmapPlusMetricsMixin + + +# Since there are only two types of mixin's just create them here. +BitmapPlusBigMetricsMixin = _createBitmapPlusMetricsMixin(BigGlyphMetrics) +BitmapPlusSmallMetricsMixin = _createBitmapPlusMetricsMixin(SmallGlyphMetrics) + + +# Data that is bit aligned can be tricky to deal with. These classes implement +# helper functionality for dealing with the data and getting a particular row +# of bitwise data. Also helps implement fancy data export/import in XML. +class BitAlignedBitmapMixin(object): + def _getBitRange(self, row, bitDepth, metrics): + rowBits = bitDepth * metrics.width + bitOffset = row * rowBits + return (bitOffset, bitOffset + rowBits) + + def getRow(self, row, bitDepth=1, metrics=None, reverseBytes=False): + if metrics is None: + metrics = self.metrics + assert 0 <= row and row < metrics.height, "Illegal row access in bitmap" + + # Loop through each byte. This can cover two bytes in the original data or + # a single byte if things happen to be aligned. The very last entry might + # not be aligned so take care to trim the binary data to size and pad with + # zeros in the row data. Bit aligned data is somewhat tricky. + # + # Example of data cut. Data cut represented in x's. + # '|' represents byte boundary. + # data = ...0XX|XXXXXX00|000... => XXXXXXXX + # or + # data = ...0XX|XXXX0000|000... => XXXXXX00 + # or + # data = ...000|XXXXXXXX|000... => XXXXXXXX + # or + # data = ...000|00XXXX00|000... => XXXX0000 + # + dataList = [] + bitRange = self._getBitRange(row, bitDepth, metrics) + stepRange = bitRange + (8,) + for curBit in range(*stepRange): + endBit = min(curBit + 8, bitRange[1]) + numBits = endBit - curBit + cutPoint = curBit % 8 + firstByteLoc = curBit // 8 + secondByteLoc = endBit // 8 + if firstByteLoc < secondByteLoc: + numBitsCut = 8 - cutPoint + else: + numBitsCut = endBit - curBit + curByte = _reverseBytes(self.imageData[firstByteLoc]) + firstHalf = byteord(curByte) >> cutPoint + firstHalf = ((1 << numBitsCut) - 1) & firstHalf + newByte = firstHalf + if firstByteLoc < secondByteLoc and secondByteLoc < len(self.imageData): + curByte = _reverseBytes(self.imageData[secondByteLoc]) + secondHalf = byteord(curByte) << numBitsCut + newByte = (firstHalf | secondHalf) & ((1 << numBits) - 1) + dataList.append(bytechr(newByte)) + + # The way the data is kept is opposite the algorithm used. + data = bytesjoin(dataList) + if not reverseBytes: + data = _reverseBytes(data) + return data + + def setRows(self, dataRows, bitDepth=1, metrics=None, reverseBytes=False): + if metrics is None: + metrics = self.metrics + if not reverseBytes: + dataRows = list(map(_reverseBytes, dataRows)) + + # Keep track of a list of ordinal values as they are easier to modify + # than a list of strings. Map to actual strings later. + numBytes = (self._getBitRange(len(dataRows), bitDepth, metrics)[0] + 7) // 8 + ordDataList = [0] * numBytes + for row, data in enumerate(dataRows): + bitRange = self._getBitRange(row, bitDepth, metrics) + stepRange = bitRange + (8,) + for curBit, curByte in zip(range(*stepRange), data): + endBit = min(curBit + 8, bitRange[1]) + cutPoint = curBit % 8 + firstByteLoc = curBit // 8 + secondByteLoc = endBit // 8 + if firstByteLoc < secondByteLoc: + numBitsCut = 8 - cutPoint + else: + numBitsCut = endBit - curBit + curByte = byteord(curByte) + firstByte = curByte & ((1 << numBitsCut) - 1) + ordDataList[firstByteLoc] |= firstByte << cutPoint + if firstByteLoc < secondByteLoc and secondByteLoc < numBytes: + secondByte = (curByte >> numBitsCut) & ((1 << 8 - numBitsCut) - 1) + ordDataList[secondByteLoc] |= secondByte + + # Save the image data with the bits going the correct way. + self.imageData = _reverseBytes(bytesjoin(map(bytechr, ordDataList))) + + +class ByteAlignedBitmapMixin(object): + def _getByteRange(self, row, bitDepth, metrics): + rowBytes = (bitDepth * metrics.width + 7) // 8 + byteOffset = row * rowBytes + return (byteOffset, byteOffset + rowBytes) + + def getRow(self, row, bitDepth=1, metrics=None, reverseBytes=False): + if metrics is None: + metrics = self.metrics + assert 0 <= row and row < metrics.height, "Illegal row access in bitmap" + byteRange = self._getByteRange(row, bitDepth, metrics) + data = self.imageData[slice(*byteRange)] + if reverseBytes: + data = _reverseBytes(data) + return data + + def setRows(self, dataRows, bitDepth=1, metrics=None, reverseBytes=False): + if metrics is None: + metrics = self.metrics + if reverseBytes: + dataRows = map(_reverseBytes, dataRows) + self.imageData = bytesjoin(dataRows) + + +class ebdt_bitmap_format_1( + ByteAlignedBitmapMixin, BitmapPlusSmallMetricsMixin, BitmapGlyph +): + def decompile(self): + self.metrics = SmallGlyphMetrics() + dummy, data = sstruct.unpack2(smallGlyphMetricsFormat, self.data, self.metrics) + self.imageData = data + + def compile(self, ttFont): + data = sstruct.pack(smallGlyphMetricsFormat, self.metrics) + return data + self.imageData + + +class ebdt_bitmap_format_2( + BitAlignedBitmapMixin, BitmapPlusSmallMetricsMixin, BitmapGlyph +): + def decompile(self): + self.metrics = SmallGlyphMetrics() + dummy, data = sstruct.unpack2(smallGlyphMetricsFormat, self.data, self.metrics) + self.imageData = data + + def compile(self, ttFont): + data = sstruct.pack(smallGlyphMetricsFormat, self.metrics) + return data + self.imageData + + +class ebdt_bitmap_format_5(BitAlignedBitmapMixin, BitmapGlyph): + def decompile(self): + self.imageData = self.data + + def compile(self, ttFont): + return self.imageData + + +class ebdt_bitmap_format_6( + ByteAlignedBitmapMixin, BitmapPlusBigMetricsMixin, BitmapGlyph +): + def decompile(self): + self.metrics = BigGlyphMetrics() + dummy, data = sstruct.unpack2(bigGlyphMetricsFormat, self.data, self.metrics) + self.imageData = data + + def compile(self, ttFont): + data = sstruct.pack(bigGlyphMetricsFormat, self.metrics) + return data + self.imageData + + +class ebdt_bitmap_format_7( + BitAlignedBitmapMixin, BitmapPlusBigMetricsMixin, BitmapGlyph +): + def decompile(self): + self.metrics = BigGlyphMetrics() + dummy, data = sstruct.unpack2(bigGlyphMetricsFormat, self.data, self.metrics) + self.imageData = data + + def compile(self, ttFont): + data = sstruct.pack(bigGlyphMetricsFormat, self.metrics) + return data + self.imageData + + +class ComponentBitmapGlyph(BitmapGlyph): + def toXML(self, strikeIndex, glyphName, writer, ttFont): + writer.begintag(self.__class__.__name__, [("name", glyphName)]) + writer.newline() + + self.writeMetrics(writer, ttFont) + + writer.begintag("components") + writer.newline() + for curComponent in self.componentArray: + curComponent.toXML(writer, ttFont) + writer.endtag("components") + writer.newline() + + writer.endtag(self.__class__.__name__) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + self.readMetrics(name, attrs, content, ttFont) + for element in content: + if not isinstance(element, tuple): + continue + name, attr, content = element + if name == "components": + self.componentArray = [] + for compElement in content: + if not isinstance(compElement, tuple): + continue + name, attrs, content = compElement + if name == "ebdtComponent": + curComponent = EbdtComponent() + curComponent.fromXML(name, attrs, content, ttFont) + self.componentArray.append(curComponent) + else: + log.warning("'%s' being ignored in component array.", name) + + +class ebdt_bitmap_format_8(BitmapPlusSmallMetricsMixin, ComponentBitmapGlyph): + def decompile(self): + self.metrics = SmallGlyphMetrics() + dummy, data = sstruct.unpack2(smallGlyphMetricsFormat, self.data, self.metrics) + data = data[1:] + + (numComponents,) = struct.unpack(">H", data[:2]) + data = data[2:] + self.componentArray = [] + for i in range(numComponents): + curComponent = EbdtComponent() + dummy, data = sstruct.unpack2(ebdtComponentFormat, data, curComponent) + curComponent.name = self.ttFont.getGlyphName(curComponent.glyphCode) + self.componentArray.append(curComponent) + + def compile(self, ttFont): + dataList = [] + dataList.append(sstruct.pack(smallGlyphMetricsFormat, self.metrics)) + dataList.append(b"\0") + dataList.append(struct.pack(">H", len(self.componentArray))) + for curComponent in self.componentArray: + curComponent.glyphCode = ttFont.getGlyphID(curComponent.name) + dataList.append(sstruct.pack(ebdtComponentFormat, curComponent)) + return bytesjoin(dataList) + + +class ebdt_bitmap_format_9(BitmapPlusBigMetricsMixin, ComponentBitmapGlyph): + def decompile(self): + self.metrics = BigGlyphMetrics() + dummy, data = sstruct.unpack2(bigGlyphMetricsFormat, self.data, self.metrics) + (numComponents,) = struct.unpack(">H", data[:2]) + data = data[2:] + self.componentArray = [] + for i in range(numComponents): + curComponent = EbdtComponent() + dummy, data = sstruct.unpack2(ebdtComponentFormat, data, curComponent) + curComponent.name = self.ttFont.getGlyphName(curComponent.glyphCode) + self.componentArray.append(curComponent) + + def compile(self, ttFont): + dataList = [] + dataList.append(sstruct.pack(bigGlyphMetricsFormat, self.metrics)) + dataList.append(struct.pack(">H", len(self.componentArray))) + for curComponent in self.componentArray: + curComponent.glyphCode = ttFont.getGlyphID(curComponent.name) + dataList.append(sstruct.pack(ebdtComponentFormat, curComponent)) + return bytesjoin(dataList) + + +# Dictionary of bitmap formats to the class representing that format +# currently only the ones listed in this map are the ones supported. +ebdt_bitmap_classes = { + 1: ebdt_bitmap_format_1, + 2: ebdt_bitmap_format_2, + 5: ebdt_bitmap_format_5, + 6: ebdt_bitmap_format_6, + 7: ebdt_bitmap_format_7, + 8: ebdt_bitmap_format_8, + 9: ebdt_bitmap_format_9, +} diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_L_C_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_L_C_.py new file mode 100644 index 0000000000000000000000000000000000000000..1f5c7a38a953f0e81f30362e3fa614521630524c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_L_C_.py @@ -0,0 +1,717 @@ +from fontTools.misc import sstruct +from . import DefaultTable +from fontTools.misc.textTools import bytesjoin, safeEval +from .BitmapGlyphMetrics import ( + BigGlyphMetrics, + bigGlyphMetricsFormat, + SmallGlyphMetrics, + smallGlyphMetricsFormat, +) +import struct +import itertools +from collections import deque +import logging + +log = logging.getLogger(__name__) + +eblcHeaderFormat = """ + > # big endian + version: 16.16F + numSizes: I +""" +# The table format string is split to handle sbitLineMetrics simply. +bitmapSizeTableFormatPart1 = """ + > # big endian + indexSubTableArrayOffset: I + indexTablesSize: I + numberOfIndexSubTables: I + colorRef: I +""" +# The compound type for hori and vert. +sbitLineMetricsFormat = """ + > # big endian + ascender: b + descender: b + widthMax: B + caretSlopeNumerator: b + caretSlopeDenominator: b + caretOffset: b + minOriginSB: b + minAdvanceSB: b + maxBeforeBL: b + minAfterBL: b + pad1: b + pad2: b +""" +# hori and vert go between the two parts. +bitmapSizeTableFormatPart2 = """ + > # big endian + startGlyphIndex: H + endGlyphIndex: H + ppemX: B + ppemY: B + bitDepth: B + flags: b +""" + +indexSubTableArrayFormat = ">HHL" +indexSubTableArraySize = struct.calcsize(indexSubTableArrayFormat) + +indexSubHeaderFormat = ">HHL" +indexSubHeaderSize = struct.calcsize(indexSubHeaderFormat) + +codeOffsetPairFormat = ">HH" +codeOffsetPairSize = struct.calcsize(codeOffsetPairFormat) + + +class table_E_B_L_C_(DefaultTable.DefaultTable): + """Embedded Bitmap Location table + + The ``EBLC`` table contains the locations of monochrome or grayscale + bitmaps for glyphs. It must be used in concert with the ``EBDT`` table. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/eblc + """ + + dependencies = ["EBDT"] + + # This method can be overridden in subclasses to support new formats + # without changing the other implementation. Also can be used as a + # convenience method for coverting a font file to an alternative format. + def getIndexFormatClass(self, indexFormat): + return eblc_sub_table_classes[indexFormat] + + def decompile(self, data, ttFont): + # Save the original data because offsets are from the start of the table. + origData = data + i = 0 + + dummy = sstruct.unpack(eblcHeaderFormat, data[:8], self) + i += 8 + + self.strikes = [] + for curStrikeIndex in range(self.numSizes): + curStrike = Strike() + self.strikes.append(curStrike) + curTable = curStrike.bitmapSizeTable + dummy = sstruct.unpack2( + bitmapSizeTableFormatPart1, data[i : i + 16], curTable + ) + i += 16 + for metric in ("hori", "vert"): + metricObj = SbitLineMetrics() + vars(curTable)[metric] = metricObj + dummy = sstruct.unpack2( + sbitLineMetricsFormat, data[i : i + 12], metricObj + ) + i += 12 + dummy = sstruct.unpack( + bitmapSizeTableFormatPart2, data[i : i + 8], curTable + ) + i += 8 + + for curStrike in self.strikes: + curTable = curStrike.bitmapSizeTable + for subtableIndex in range(curTable.numberOfIndexSubTables): + i = ( + curTable.indexSubTableArrayOffset + + subtableIndex * indexSubTableArraySize + ) + + tup = struct.unpack( + indexSubTableArrayFormat, data[i : i + indexSubTableArraySize] + ) + firstGlyphIndex, lastGlyphIndex, additionalOffsetToIndexSubtable = tup + i = curTable.indexSubTableArrayOffset + additionalOffsetToIndexSubtable + + tup = struct.unpack( + indexSubHeaderFormat, data[i : i + indexSubHeaderSize] + ) + indexFormat, imageFormat, imageDataOffset = tup + + indexFormatClass = self.getIndexFormatClass(indexFormat) + indexSubTable = indexFormatClass(data[i + indexSubHeaderSize :], ttFont) + indexSubTable.firstGlyphIndex = firstGlyphIndex + indexSubTable.lastGlyphIndex = lastGlyphIndex + indexSubTable.additionalOffsetToIndexSubtable = ( + additionalOffsetToIndexSubtable + ) + indexSubTable.indexFormat = indexFormat + indexSubTable.imageFormat = imageFormat + indexSubTable.imageDataOffset = imageDataOffset + indexSubTable.decompile() # https://github.com/fonttools/fonttools/issues/317 + curStrike.indexSubTables.append(indexSubTable) + + def compile(self, ttFont): + dataList = [] + self.numSizes = len(self.strikes) + dataList.append(sstruct.pack(eblcHeaderFormat, self)) + + # Data size of the header + bitmapSizeTable needs to be calculated + # in order to form offsets. This value will hold the size of the data + # in dataList after all the data is consolidated in dataList. + dataSize = len(dataList[0]) + + # The table will be structured in the following order: + # (0) header + # (1) Each bitmapSizeTable [1 ... self.numSizes] + # (2) Alternate between indexSubTableArray and indexSubTable + # for each bitmapSizeTable present. + # + # The issue is maintaining the proper offsets when table information + # gets moved around. All offsets and size information must be recalculated + # when building the table to allow editing within ttLib and also allow easy + # import/export to and from XML. All of this offset information is lost + # when exporting to XML so everything must be calculated fresh so importing + # from XML will work cleanly. Only byte offset and size information is + # calculated fresh. Count information like numberOfIndexSubTables is + # checked through assertions. If the information in this table was not + # touched or was changed properly then these types of values should match. + # + # The table will be rebuilt the following way: + # (0) Precompute the size of all the bitmapSizeTables. This is needed to + # compute the offsets properly. + # (1) For each bitmapSizeTable compute the indexSubTable and + # indexSubTableArray pair. The indexSubTable must be computed first + # so that the offset information in indexSubTableArray can be + # calculated. Update the data size after each pairing. + # (2) Build each bitmapSizeTable. + # (3) Consolidate all the data into the main dataList in the correct order. + + for _ in self.strikes: + dataSize += sstruct.calcsize(bitmapSizeTableFormatPart1) + dataSize += len(("hori", "vert")) * sstruct.calcsize(sbitLineMetricsFormat) + dataSize += sstruct.calcsize(bitmapSizeTableFormatPart2) + + indexSubTablePairDataList = [] + for curStrike in self.strikes: + curTable = curStrike.bitmapSizeTable + curTable.numberOfIndexSubTables = len(curStrike.indexSubTables) + curTable.indexSubTableArrayOffset = dataSize + + # Precompute the size of the indexSubTableArray. This information + # is important for correctly calculating the new value for + # additionalOffsetToIndexSubtable. + sizeOfSubTableArray = ( + curTable.numberOfIndexSubTables * indexSubTableArraySize + ) + lowerBound = dataSize + dataSize += sizeOfSubTableArray + upperBound = dataSize + + indexSubTableDataList = [] + for indexSubTable in curStrike.indexSubTables: + indexSubTable.additionalOffsetToIndexSubtable = ( + dataSize - curTable.indexSubTableArrayOffset + ) + glyphIds = list(map(ttFont.getGlyphID, indexSubTable.names)) + indexSubTable.firstGlyphIndex = min(glyphIds) + indexSubTable.lastGlyphIndex = max(glyphIds) + data = indexSubTable.compile(ttFont) + indexSubTableDataList.append(data) + dataSize += len(data) + curTable.startGlyphIndex = min( + ist.firstGlyphIndex for ist in curStrike.indexSubTables + ) + curTable.endGlyphIndex = max( + ist.lastGlyphIndex for ist in curStrike.indexSubTables + ) + + for i in curStrike.indexSubTables: + data = struct.pack( + indexSubHeaderFormat, + i.firstGlyphIndex, + i.lastGlyphIndex, + i.additionalOffsetToIndexSubtable, + ) + indexSubTablePairDataList.append(data) + indexSubTablePairDataList.extend(indexSubTableDataList) + curTable.indexTablesSize = dataSize - curTable.indexSubTableArrayOffset + + for curStrike in self.strikes: + curTable = curStrike.bitmapSizeTable + data = sstruct.pack(bitmapSizeTableFormatPart1, curTable) + dataList.append(data) + for metric in ("hori", "vert"): + metricObj = vars(curTable)[metric] + data = sstruct.pack(sbitLineMetricsFormat, metricObj) + dataList.append(data) + data = sstruct.pack(bitmapSizeTableFormatPart2, curTable) + dataList.append(data) + dataList.extend(indexSubTablePairDataList) + + return bytesjoin(dataList) + + def toXML(self, writer, ttFont): + writer.simpletag("header", [("version", self.version)]) + writer.newline() + for curIndex, curStrike in enumerate(self.strikes): + curStrike.toXML(curIndex, writer, ttFont) + + def fromXML(self, name, attrs, content, ttFont): + if name == "header": + self.version = safeEval(attrs["version"]) + elif name == "strike": + if not hasattr(self, "strikes"): + self.strikes = [] + strikeIndex = safeEval(attrs["index"]) + curStrike = Strike() + curStrike.fromXML(name, attrs, content, ttFont, self) + + # Grow the strike array to the appropriate size. The XML format + # allows for the strike index value to be out of order. + if strikeIndex >= len(self.strikes): + self.strikes += [None] * (strikeIndex + 1 - len(self.strikes)) + assert self.strikes[strikeIndex] is None, "Duplicate strike EBLC indices." + self.strikes[strikeIndex] = curStrike + + +class Strike(object): + def __init__(self): + self.bitmapSizeTable = BitmapSizeTable() + self.indexSubTables = [] + + def toXML(self, strikeIndex, writer, ttFont): + writer.begintag("strike", [("index", strikeIndex)]) + writer.newline() + self.bitmapSizeTable.toXML(writer, ttFont) + writer.comment( + "GlyphIds are written but not read. The firstGlyphIndex and\nlastGlyphIndex values will be recalculated by the compiler." + ) + writer.newline() + for indexSubTable in self.indexSubTables: + indexSubTable.toXML(writer, ttFont) + writer.endtag("strike") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont, locator): + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name == "bitmapSizeTable": + self.bitmapSizeTable.fromXML(name, attrs, content, ttFont) + elif name.startswith(_indexSubTableSubclassPrefix): + indexFormat = safeEval(name[len(_indexSubTableSubclassPrefix) :]) + indexFormatClass = locator.getIndexFormatClass(indexFormat) + indexSubTable = indexFormatClass(None, None) + indexSubTable.indexFormat = indexFormat + indexSubTable.fromXML(name, attrs, content, ttFont) + self.indexSubTables.append(indexSubTable) + + +class BitmapSizeTable(object): + # Returns all the simple metric names that bitmap size table + # cares about in terms of XML creation. + def _getXMLMetricNames(self): + dataNames = sstruct.getformat(bitmapSizeTableFormatPart1)[1] + dataNames = {**dataNames, **sstruct.getformat(bitmapSizeTableFormatPart2)[1]} + # Skip the first 3 data names because they are byte offsets and counts. + return list(dataNames.keys())[3:] + + def toXML(self, writer, ttFont): + writer.begintag("bitmapSizeTable") + writer.newline() + for metric in ("hori", "vert"): + getattr(self, metric).toXML(metric, writer, ttFont) + for metricName in self._getXMLMetricNames(): + writer.simpletag(metricName, value=getattr(self, metricName)) + writer.newline() + writer.endtag("bitmapSizeTable") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + # Create a lookup for all the simple names that make sense to + # bitmap size table. Only read the information from these names. + dataNames = set(self._getXMLMetricNames()) + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name == "sbitLineMetrics": + direction = attrs["direction"] + assert direction in ( + "hori", + "vert", + ), "SbitLineMetrics direction specified invalid." + metricObj = SbitLineMetrics() + metricObj.fromXML(name, attrs, content, ttFont) + vars(self)[direction] = metricObj + elif name in dataNames: + vars(self)[name] = safeEval(attrs["value"]) + else: + log.warning("unknown name '%s' being ignored in BitmapSizeTable.", name) + + +class SbitLineMetrics(object): + def toXML(self, name, writer, ttFont): + writer.begintag("sbitLineMetrics", [("direction", name)]) + writer.newline() + for metricName in sstruct.getformat(sbitLineMetricsFormat)[1]: + writer.simpletag(metricName, value=getattr(self, metricName)) + writer.newline() + writer.endtag("sbitLineMetrics") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + metricNames = set(sstruct.getformat(sbitLineMetricsFormat)[1]) + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name in metricNames: + vars(self)[name] = safeEval(attrs["value"]) + + +# Important information about the naming scheme. Used for identifying subtables. +_indexSubTableSubclassPrefix = "eblc_index_sub_table_" + + +class EblcIndexSubTable(object): + def __init__(self, data, ttFont): + self.data = data + self.ttFont = ttFont + # TODO Currently non-lazy decompiling doesn't work for this class... + # if not ttFont.lazy: + # self.decompile() + # del self.data, self.ttFont + + def __getattr__(self, attr): + # Allow lazy decompile. + if attr[:2] == "__": + raise AttributeError(attr) + if attr == "data": + raise AttributeError(attr) + self.decompile() + return getattr(self, attr) + + def ensureDecompiled(self, recurse=False): + if hasattr(self, "data"): + self.decompile() + + # This method just takes care of the indexSubHeader. Implementing subclasses + # should call it to compile the indexSubHeader and then continue compiling + # the remainder of their unique format. + def compile(self, ttFont): + return struct.pack( + indexSubHeaderFormat, + self.indexFormat, + self.imageFormat, + self.imageDataOffset, + ) + + # Creates the XML for bitmap glyphs. Each index sub table basically makes + # the same XML except for specific metric information that is written + # out via a method call that a subclass implements optionally. + def toXML(self, writer, ttFont): + writer.begintag( + self.__class__.__name__, + [ + ("imageFormat", self.imageFormat), + ("firstGlyphIndex", self.firstGlyphIndex), + ("lastGlyphIndex", self.lastGlyphIndex), + ], + ) + writer.newline() + self.writeMetrics(writer, ttFont) + # Write out the names as thats all thats needed to rebuild etc. + # For font debugging of consecutive formats the ids are also written. + # The ids are not read when moving from the XML format. + glyphIds = map(ttFont.getGlyphID, self.names) + for glyphName, glyphId in zip(self.names, glyphIds): + writer.simpletag("glyphLoc", name=glyphName, id=glyphId) + writer.newline() + writer.endtag(self.__class__.__name__) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + # Read all the attributes. Even though the glyph indices are + # recalculated, they are still read in case there needs to + # be an immediate export of the data. + self.imageFormat = safeEval(attrs["imageFormat"]) + self.firstGlyphIndex = safeEval(attrs["firstGlyphIndex"]) + self.lastGlyphIndex = safeEval(attrs["lastGlyphIndex"]) + + self.readMetrics(name, attrs, content, ttFont) + + self.names = [] + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name == "glyphLoc": + self.names.append(attrs["name"]) + + # A helper method that writes the metrics for the index sub table. It also + # is responsible for writing the image size for fixed size data since fixed + # size is not recalculated on compile. Default behavior is to do nothing. + def writeMetrics(self, writer, ttFont): + pass + + # A helper method that is the inverse of writeMetrics. + def readMetrics(self, name, attrs, content, ttFont): + pass + + # This method is for fixed glyph data sizes. There are formats where + # the glyph data is fixed but are actually composite glyphs. To handle + # this the font spec in indexSubTable makes the data the size of the + # fixed size by padding the component arrays. This function abstracts + # out this padding process. Input is data unpadded. Output is data + # padded only in fixed formats. Default behavior is to return the data. + def padBitmapData(self, data): + return data + + # Remove any of the glyph locations and names that are flagged as skipped. + # This only occurs in formats {1,3}. + def removeSkipGlyphs(self): + # Determines if a name, location pair is a valid data location. + # Skip glyphs are marked when the size is equal to zero. + def isValidLocation(args): + name, (startByte, endByte) = args + return startByte < endByte + + # Remove all skip glyphs. + dataPairs = list(filter(isValidLocation, zip(self.names, self.locations))) + self.names, self.locations = list(map(list, zip(*dataPairs))) + + +# A closure for creating a custom mixin. This is done because formats 1 and 3 +# are very similar. The only difference between them is the size per offset +# value. Code put in here should handle both cases generally. +def _createOffsetArrayIndexSubTableMixin(formatStringForDataType): + # Prep the data size for the offset array data format. + dataFormat = ">" + formatStringForDataType + offsetDataSize = struct.calcsize(dataFormat) + + class OffsetArrayIndexSubTableMixin(object): + def decompile(self): + numGlyphs = self.lastGlyphIndex - self.firstGlyphIndex + 1 + indexingOffsets = [ + glyphIndex * offsetDataSize for glyphIndex in range(numGlyphs + 2) + ] + indexingLocations = zip(indexingOffsets, indexingOffsets[1:]) + offsetArray = [ + struct.unpack(dataFormat, self.data[slice(*loc)])[0] + for loc in indexingLocations + ] + + glyphIds = list(range(self.firstGlyphIndex, self.lastGlyphIndex + 1)) + modifiedOffsets = [offset + self.imageDataOffset for offset in offsetArray] + self.locations = list(zip(modifiedOffsets, modifiedOffsets[1:])) + + self.names = list(map(self.ttFont.getGlyphName, glyphIds)) + self.removeSkipGlyphs() + del self.data, self.ttFont + + def compile(self, ttFont): + # First make sure that all the data lines up properly. Formats 1 and 3 + # must have all its data lined up consecutively. If not this will fail. + for curLoc, nxtLoc in zip(self.locations, self.locations[1:]): + assert ( + curLoc[1] == nxtLoc[0] + ), "Data must be consecutive in indexSubTable offset formats" + + glyphIds = list(map(ttFont.getGlyphID, self.names)) + # Make sure that all ids are sorted strictly increasing. + assert all(glyphIds[i] < glyphIds[i + 1] for i in range(len(glyphIds) - 1)) + + # Run a simple algorithm to add skip glyphs to the data locations at + # the places where an id is not present. + idQueue = deque(glyphIds) + locQueue = deque(self.locations) + allGlyphIds = list(range(self.firstGlyphIndex, self.lastGlyphIndex + 1)) + allLocations = [] + for curId in allGlyphIds: + if curId != idQueue[0]: + allLocations.append((locQueue[0][0], locQueue[0][0])) + else: + idQueue.popleft() + allLocations.append(locQueue.popleft()) + + # Now that all the locations are collected, pack them appropriately into + # offsets. This is the form where offset[i] is the location and + # offset[i+1]-offset[i] is the size of the data location. + offsets = list(allLocations[0]) + [loc[1] for loc in allLocations[1:]] + # Image data offset must be less than or equal to the minimum of locations. + # This offset may change the value for round tripping but is safer and + # allows imageDataOffset to not be required to be in the XML version. + self.imageDataOffset = min(offsets) + offsetArray = [offset - self.imageDataOffset for offset in offsets] + + dataList = [EblcIndexSubTable.compile(self, ttFont)] + dataList += [ + struct.pack(dataFormat, offsetValue) for offsetValue in offsetArray + ] + # Take care of any padding issues. Only occurs in format 3. + if offsetDataSize * len(offsetArray) % 4 != 0: + dataList.append(struct.pack(dataFormat, 0)) + return bytesjoin(dataList) + + return OffsetArrayIndexSubTableMixin + + +# A Mixin for functionality shared between the different kinds +# of fixed sized data handling. Both kinds have big metrics so +# that kind of special processing is also handled in this mixin. +class FixedSizeIndexSubTableMixin(object): + def writeMetrics(self, writer, ttFont): + writer.simpletag("imageSize", value=self.imageSize) + writer.newline() + self.metrics.toXML(writer, ttFont) + + def readMetrics(self, name, attrs, content, ttFont): + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name == "imageSize": + self.imageSize = safeEval(attrs["value"]) + elif name == BigGlyphMetrics.__name__: + self.metrics = BigGlyphMetrics() + self.metrics.fromXML(name, attrs, content, ttFont) + elif name == SmallGlyphMetrics.__name__: + log.warning( + "SmallGlyphMetrics being ignored in format %d.", self.indexFormat + ) + + def padBitmapData(self, data): + # Make sure that the data isn't bigger than the fixed size. + assert len(data) <= self.imageSize, ( + "Data in indexSubTable format %d must be less than the fixed size." + % self.indexFormat + ) + # Pad the data so that it matches the fixed size. + pad = (self.imageSize - len(data)) * b"\0" + return data + pad + + +class eblc_index_sub_table_1( + _createOffsetArrayIndexSubTableMixin("L"), EblcIndexSubTable +): + pass + + +class eblc_index_sub_table_2(FixedSizeIndexSubTableMixin, EblcIndexSubTable): + def decompile(self): + (self.imageSize,) = struct.unpack(">L", self.data[:4]) + self.metrics = BigGlyphMetrics() + sstruct.unpack2(bigGlyphMetricsFormat, self.data[4:], self.metrics) + glyphIds = list(range(self.firstGlyphIndex, self.lastGlyphIndex + 1)) + offsets = [ + self.imageSize * i + self.imageDataOffset for i in range(len(glyphIds) + 1) + ] + self.locations = list(zip(offsets, offsets[1:])) + self.names = list(map(self.ttFont.getGlyphName, glyphIds)) + del self.data, self.ttFont + + def compile(self, ttFont): + glyphIds = list(map(ttFont.getGlyphID, self.names)) + # Make sure all the ids are consecutive. This is required by Format 2. + assert glyphIds == list( + range(self.firstGlyphIndex, self.lastGlyphIndex + 1) + ), "Format 2 ids must be consecutive." + self.imageDataOffset = min(next(iter(zip(*self.locations)))) + + dataList = [EblcIndexSubTable.compile(self, ttFont)] + dataList.append(struct.pack(">L", self.imageSize)) + dataList.append(sstruct.pack(bigGlyphMetricsFormat, self.metrics)) + return bytesjoin(dataList) + + +class eblc_index_sub_table_3( + _createOffsetArrayIndexSubTableMixin("H"), EblcIndexSubTable +): + pass + + +class eblc_index_sub_table_4(EblcIndexSubTable): + def decompile(self): + (numGlyphs,) = struct.unpack(">L", self.data[:4]) + data = self.data[4:] + indexingOffsets = [ + glyphIndex * codeOffsetPairSize for glyphIndex in range(numGlyphs + 2) + ] + indexingLocations = zip(indexingOffsets, indexingOffsets[1:]) + glyphArray = [ + struct.unpack(codeOffsetPairFormat, data[slice(*loc)]) + for loc in indexingLocations + ] + glyphIds, offsets = list(map(list, zip(*glyphArray))) + # There are one too many glyph ids. Get rid of the last one. + glyphIds.pop() + + offsets = [offset + self.imageDataOffset for offset in offsets] + self.locations = list(zip(offsets, offsets[1:])) + self.names = list(map(self.ttFont.getGlyphName, glyphIds)) + del self.data, self.ttFont + + def compile(self, ttFont): + # First make sure that all the data lines up properly. Format 4 + # must have all its data lined up consecutively. If not this will fail. + for curLoc, nxtLoc in zip(self.locations, self.locations[1:]): + assert ( + curLoc[1] == nxtLoc[0] + ), "Data must be consecutive in indexSubTable format 4" + + offsets = list(self.locations[0]) + [loc[1] for loc in self.locations[1:]] + # Image data offset must be less than or equal to the minimum of locations. + # Resetting this offset may change the value for round tripping but is safer + # and allows imageDataOffset to not be required to be in the XML version. + self.imageDataOffset = min(offsets) + offsets = [offset - self.imageDataOffset for offset in offsets] + glyphIds = list(map(ttFont.getGlyphID, self.names)) + # Create an iterator over the ids plus a padding value. + idsPlusPad = list(itertools.chain(glyphIds, [0])) + + dataList = [EblcIndexSubTable.compile(self, ttFont)] + dataList.append(struct.pack(">L", len(glyphIds))) + tmp = [ + struct.pack(codeOffsetPairFormat, *cop) for cop in zip(idsPlusPad, offsets) + ] + dataList += tmp + data = bytesjoin(dataList) + return data + + +class eblc_index_sub_table_5(FixedSizeIndexSubTableMixin, EblcIndexSubTable): + def decompile(self): + self.origDataLen = 0 + (self.imageSize,) = struct.unpack(">L", self.data[:4]) + data = self.data[4:] + self.metrics, data = sstruct.unpack2( + bigGlyphMetricsFormat, data, BigGlyphMetrics() + ) + (numGlyphs,) = struct.unpack(">L", data[:4]) + data = data[4:] + glyphIds = [ + struct.unpack(">H", data[2 * i : 2 * (i + 1)])[0] for i in range(numGlyphs) + ] + + offsets = [ + self.imageSize * i + self.imageDataOffset for i in range(len(glyphIds) + 1) + ] + self.locations = list(zip(offsets, offsets[1:])) + self.names = list(map(self.ttFont.getGlyphName, glyphIds)) + del self.data, self.ttFont + + def compile(self, ttFont): + self.imageDataOffset = min(next(iter(zip(*self.locations)))) + dataList = [EblcIndexSubTable.compile(self, ttFont)] + dataList.append(struct.pack(">L", self.imageSize)) + dataList.append(sstruct.pack(bigGlyphMetricsFormat, self.metrics)) + glyphIds = list(map(ttFont.getGlyphID, self.names)) + dataList.append(struct.pack(">L", len(glyphIds))) + dataList += [struct.pack(">H", curId) for curId in glyphIds] + if len(glyphIds) % 2 == 1: + dataList.append(struct.pack(">H", 0)) + return bytesjoin(dataList) + + +# Dictionary of indexFormat to the class representing that format. +eblc_sub_table_classes = { + 1: eblc_index_sub_table_1, + 2: eblc_index_sub_table_2, + 3: eblc_index_sub_table_3, + 4: eblc_index_sub_table_4, + 5: eblc_index_sub_table_5, +} diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_S_C_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_S_C_.py new file mode 100644 index 0000000000000000000000000000000000000000..74ff8b575010d56e22d07d8d68a933fcbec3f96c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_S_C_.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +from typing import Any + +from fontTools.misc import sstruct +from fontTools.misc.textTools import bytesjoin, safeEval +from fontTools.misc.xmlWriter import XMLWriter +from fontTools.ttLib import TTFont, TTLibError +from fontTools.ttLib.tables import DefaultTable +from fontTools.ttLib.tables.DefaultTable import XMLAttrs, XMLContent +from fontTools.ttLib.tables.E_B_L_C_ import sbitLineMetricsFormat, SbitLineMetrics + +ebscHeaderFormat = """ + > # big endian + version: 16.16F + numSizes: I +""" + +bitmapScaleTableFormatPart2 = """ + > # big endian + ppemX: B + ppemY: B + substitutePpemX: B + substitutePpemY: B +""" + + +class table_E_B_S_C_(DefaultTable.DefaultTable): + """ + Embedded Bitmap Scaling Table + + The ``EBSC`` table provides a mechanism for describing embedded bitmaps which are created by + scaling other embedded bitmaps. While this is the sort of thing that outline font technologies + were invented to avoid, there are cases (small sizes of Kanji, for example) where scaling a bitmap + produces more legible glyphs than scan-converting an outline. For this reason, the EBSC table + allows a font to define a bitmap strike as a scaled version of another strike. + + The ``EBSC`` table is used together with the ``EBDT`` table, which provides embedded monochrome or + grayscale bitmap data, and the ``EBLC`` table, which provides embedded bitmap locators. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/ebsc + """ + + dependencies = ["EBDT", "EBLC"] + + version: float + numSizes: int + bitmapScaleTables: list[BitmapScaleTable] + + def decompile(self, data: bytes, ttFont: TTFont): + _, data = sstruct.unpack2(ebscHeaderFormat, data, self) + self.bitmapScaleTables = [] + for _ in range(self.numSizes): + bitmapScaleTable = BitmapScaleTable() + data = bitmapScaleTable.decompile(data) + self.bitmapScaleTables.append(bitmapScaleTable) + + def compile(self, ttFont: TTFont) -> bytes: + self.numSizes = len(self.bitmapScaleTables) + dataList = [sstruct.pack(ebscHeaderFormat, self)] + for bitmapScaleTable in self.bitmapScaleTables: + dataList.append(bitmapScaleTable.compile()) + return bytesjoin(dataList) + + def toXML(self, writer: XMLWriter, ttFont: TTFont, **kwargs: Any): + writer.simpletag( + "header", + [("version", self.version), ("numSizes", len(self.bitmapScaleTables))], + ) + writer.newline() + for index, bitmapScaleTable in enumerate(self.bitmapScaleTables): + bitmapScaleTable.toXML(index, writer, ttFont) + + def fromXML( + self, name: str, attrs: dict[str, str], content: XMLContent, ttFont: TTFont + ): + if not hasattr(self, "bitmapScaleTables"): + self.bitmapScaleTables = [] + if name == "header": + self.version = safeEval(attrs["version"]) + self.numSizes = safeEval(attrs["numSizes"]) + elif name == "bitmapScaleTable": + bitmapScaleTable = BitmapScaleTable() + bitmapScaleTable.fromXML(content, ttFont) + self.bitmapScaleTables.append(bitmapScaleTable) + + +class BitmapScaleTable: + hori: SbitLineMetrics + vert: SbitLineMetrics + ppemX: int + ppemY: int + substitutePpemX: int + substitutePpemY: int + + def __init__( + self, + hori: SbitLineMetrics | None = None, + vert: SbitLineMetrics | None = None, + ppemX: int = 0, + ppemY: int = 0, + substitutePpemX: int = 0, + substitutePpemY: int = 0, + ): + self.hori = hori if hori is not None else SbitLineMetrics() + self.vert = vert if vert is not None else SbitLineMetrics() + self.ppemX = ppemX + self.ppemY = ppemY + self.substitutePpemX = substitutePpemX + self.substitutePpemY = substitutePpemY + + def decompile(self, data: bytes) -> bytes: + dummy, data = sstruct.unpack2(sbitLineMetricsFormat, data, self.hori) + dummy, data = sstruct.unpack2(sbitLineMetricsFormat, data, self.vert) + dummy, data = sstruct.unpack2(bitmapScaleTableFormatPart2, data, self) + return data + + def compile(self) -> bytes: + dataList = [ + sstruct.pack(sbitLineMetricsFormat, self.hori), + sstruct.pack(sbitLineMetricsFormat, self.vert), + sstruct.pack(bitmapScaleTableFormatPart2, self), + ] + return bytesjoin(dataList) + + def toXML(self, index: int, writer: XMLWriter, ttFont: TTFont): + writer.begintag("bitmapScaleTable", [("index", index)]) + writer.newline() + self.hori.toXML("hori", writer, ttFont) + self.vert.toXML("vert", writer, ttFont) + for name in sstruct.getformat(bitmapScaleTableFormatPart2)[1]: + writer.simpletag(name, value=getattr(self, name)) + writer.newline() + writer.endtag("bitmapScaleTable") + writer.newline() + + def fromXML(self, content: XMLContent, ttFont: TTFont): + dataNames = set(sstruct.getformat(bitmapScaleTableFormatPart2)[1]) + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name == "sbitLineMetrics": + direction = attrs["direction"] + if direction not in ("hori", "vert"): + raise TTLibError( + f"invalid sbitLineMetrics direction: {direction!r}" + ) + metricObj = SbitLineMetrics() + metricObj.fromXML(name, attrs, content, ttFont) + setattr(self, direction, metricObj) + elif name in dataNames: + setattr(self, name, safeEval(attrs["value"])) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/F_F_T_M_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/F_F_T_M_.py new file mode 100644 index 0000000000000000000000000000000000000000..20b72346611911a1044ae0d52eb2a5c9efdf5540 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/F_F_T_M_.py @@ -0,0 +1,52 @@ +from fontTools.misc import sstruct +from fontTools.misc.textTools import safeEval +from fontTools.misc.timeTools import timestampFromString, timestampToString +from . import DefaultTable + +FFTMFormat = """ + > # big endian + version: I + FFTimeStamp: Q + sourceCreated: Q + sourceModified: Q +""" + + +class table_F_F_T_M_(DefaultTable.DefaultTable): + """FontForge Time Stamp table + + The ``FFTM`` table is used by the free-software font editor + FontForge to record timestamps for the creation and modification + of font source (.sfd) files and a timestamp for FontForge's + own source code. + + See also https://fontforge.org/docs/techref/non-standard.html + """ + + def decompile(self, data, ttFont): + dummy, rest = sstruct.unpack2(FFTMFormat, data, self) + + def compile(self, ttFont): + data = sstruct.pack(FFTMFormat, self) + return data + + def toXML(self, writer, ttFont): + writer.comment( + "FontForge's timestamp, font source creation and modification dates" + ) + writer.newline() + formatstring, names, fixes = sstruct.getformat(FFTMFormat) + for name in names: + value = getattr(self, name) + if name in ("FFTimeStamp", "sourceCreated", "sourceModified"): + value = timestampToString(value) + writer.simpletag(name, value=value) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + value = attrs["value"] + if name in ("FFTimeStamp", "sourceCreated", "sourceModified"): + value = timestampFromString(value) + else: + value = safeEval(value) + setattr(self, name, value) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/F__e_a_t.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/F__e_a_t.py new file mode 100644 index 0000000000000000000000000000000000000000..86758ad30bd933cc22bbfdb6de27d90c0b2bcff0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/F__e_a_t.py @@ -0,0 +1,159 @@ +from fontTools.misc import sstruct +from fontTools.misc.fixedTools import floatToFixedToStr +from fontTools.misc.textTools import safeEval +from . import DefaultTable +from . import grUtils +import struct + +Feat_hdr_format = """ + > + version: 16.16F +""" + + +class table_F__e_a_t(DefaultTable.DefaultTable): + """Feature table + + The ``Feat`` table is used exclusively by the Graphite shaping engine + to store features and possible settings specified in GDL. Graphite features + determine what rules are applied to transform a glyph stream. + + Not to be confused with ``feat``, or the OpenType Layout tables + ``GSUB``/``GPOS``. + + See also https://graphite.sil.org/graphite_techAbout#graphite-font-tables + """ + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.features = {} + + def decompile(self, data, ttFont): + _, data = sstruct.unpack2(Feat_hdr_format, data, self) + self.version = float(floatToFixedToStr(self.version, precisionBits=16)) + (numFeats,) = struct.unpack(">H", data[:2]) + data = data[8:] + allfeats = [] + maxsetting = 0 + for i in range(numFeats): + if self.version >= 2.0: + fid, nums, _, offset, flags, lid = struct.unpack( + ">LHHLHH", data[16 * i : 16 * (i + 1)] + ) + offset = int((offset - 12 - 16 * numFeats) / 4) + else: + fid, nums, offset, flags, lid = struct.unpack( + ">HHLHH", data[12 * i : 12 * (i + 1)] + ) + offset = int((offset - 12 - 12 * numFeats) / 4) + allfeats.append((fid, nums, offset, flags, lid)) + maxsetting = max(maxsetting, offset + nums) + data = data[16 * numFeats :] + allsettings = [] + for i in range(maxsetting): + if len(data) >= 4 * (i + 1): + val, lid = struct.unpack(">HH", data[4 * i : 4 * (i + 1)]) + allsettings.append((val, lid)) + for i, f in enumerate(allfeats): + fid, nums, offset, flags, lid = f + fobj = Feature() + fobj.flags = flags + fobj.label = lid + self.features[grUtils.num2tag(fid)] = fobj + fobj.settings = {} + fobj.default = None + fobj.index = i + for i in range(offset, offset + nums): + if i >= len(allsettings): + continue + vid, vlid = allsettings[i] + fobj.settings[vid] = vlid + if fobj.default is None: + fobj.default = vid + + def compile(self, ttFont): + fdat = b"" + vdat = b"" + offset = 0 + for f, v in sorted(self.features.items(), key=lambda x: x[1].index): + fnum = grUtils.tag2num(f) + if self.version >= 2.0: + fdat += struct.pack( + ">LHHLHH", + grUtils.tag2num(f), + len(v.settings), + 0, + offset * 4 + 12 + 16 * len(self.features), + v.flags, + v.label, + ) + elif fnum > 65535: # self healing for alphabetic ids + self.version = 2.0 + return self.compile(ttFont) + else: + fdat += struct.pack( + ">HHLHH", + grUtils.tag2num(f), + len(v.settings), + offset * 4 + 12 + 12 * len(self.features), + v.flags, + v.label, + ) + for s, l in sorted( + v.settings.items(), key=lambda x: (-1, x[1]) if x[0] == v.default else x + ): + vdat += struct.pack(">HH", s, l) + offset += len(v.settings) + hdr = sstruct.pack(Feat_hdr_format, self) + return hdr + struct.pack(">HHL", len(self.features), 0, 0) + fdat + vdat + + def toXML(self, writer, ttFont): + writer.simpletag("version", version=self.version) + writer.newline() + nameTable = ttFont["name"] if "name" in ttFont else None + for f, v in sorted(self.features.items(), key=lambda x: x[1].index): + name = nameTable.getDebugName(v.label) if nameTable else None + if name is not None: + writer.newline() + writer.comment(name) + writer.newline() + writer.begintag( + "feature", + fid=f, + label=v.label, + flags=v.flags, + default=(v.default if v.default else 0), + ) + writer.newline() + for s, l in sorted(v.settings.items()): + writer.simpletag("setting", value=s, label=l) + name = nameTable.getDebugName(l) if nameTable else None + if name is not None: + writer.write(" ") + writer.comment(name) + writer.newline() + writer.endtag("feature") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "version": + self.version = float(safeEval(attrs["version"])) + elif name == "feature": + fid = attrs["fid"] + fobj = Feature() + fobj.flags = int(safeEval(attrs["flags"])) + fobj.label = int(safeEval(attrs["label"])) + fobj.default = int(safeEval(attrs.get("default", "0"))) + fobj.index = len(self.features) + self.features[fid] = fobj + fobj.settings = {} + for element in content: + if not isinstance(element, tuple): + continue + tag, a, c = element + if tag == "setting": + fobj.settings[int(safeEval(a["value"]))] = int(safeEval(a["label"])) + + +class Feature(object): + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G_D_E_F_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G_D_E_F_.py new file mode 100644 index 0000000000000000000000000000000000000000..922a9cb2063777cae486a3369d3d6380f9f626cf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G_D_E_F_.py @@ -0,0 +1,13 @@ +from .otBase import BaseTTXConverter + + +class table_G_D_E_F_(BaseTTXConverter): + """Glyph Definition table + + The ``GDEF`` table stores various glyph properties that are used + by OpenType Layout. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/gdef + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G_P_O_S_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G_P_O_S_.py new file mode 100644 index 0000000000000000000000000000000000000000..03bdc612ead945133c97f4a4d0002e8ca31c60c4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G_P_O_S_.py @@ -0,0 +1,14 @@ +from .otBase import BaseTTXConverter + + +class table_G_P_O_S_(BaseTTXConverter): + """Glyph Positioning table + + The ``GPOS`` table stores advanced glyph-positioning data + used in OpenType Layout features, such as mark attachment, + cursive attachment, kerning, and other position adjustments. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/gpos + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G_S_U_B_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G_S_U_B_.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1aff8b0680bf22550c460819627b4d2b14a463 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G_S_U_B_.py @@ -0,0 +1,13 @@ +from .otBase import BaseTTXConverter + + +class table_G_S_U_B_(BaseTTXConverter): + """Glyph Substitution table + + The ``GSUB`` table contains glyph-substitution rules used in + OpenType Layout. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/gsub + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G_V_A_R_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G_V_A_R_.py new file mode 100644 index 0000000000000000000000000000000000000000..889b1f2a3bd712b68140a6b9102e732ce794587c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G_V_A_R_.py @@ -0,0 +1,5 @@ +from ._g_v_a_r import table__g_v_a_r + + +class table_G_V_A_R_(table__g_v_a_r): + gid_size = 3 diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G__l_a_t.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G__l_a_t.py new file mode 100644 index 0000000000000000000000000000000000000000..22c255c1c846822129c8a5b1bbdf04c88b6bd53f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G__l_a_t.py @@ -0,0 +1,234 @@ +from fontTools.misc import sstruct +from fontTools.misc.fixedTools import floatToFixedToStr +from fontTools.misc.textTools import safeEval + +# from itertools import * +from functools import partial +from . import DefaultTable +from . import grUtils +import struct + +Glat_format_0 = """ + > # big endian + version: 16.16F +""" + +Glat_format_3 = """ + > + version: 16.16F + compression:L # compression scheme or reserved +""" + +Glat_format_1_entry = """ + > + attNum: B # Attribute number of first attribute + num: B # Number of attributes in this run +""" +Glat_format_23_entry = """ + > + attNum: H # Attribute number of first attribute + num: H # Number of attributes in this run +""" + +Glat_format_3_octabox_metrics = """ + > + subboxBitmap: H # Which subboxes exist on 4x4 grid + diagNegMin: B # Defines minimum negatively-sloped diagonal (si) + diagNegMax: B # Defines maximum negatively-sloped diagonal (sa) + diagPosMin: B # Defines minimum positively-sloped diagonal (di) + diagPosMax: B # Defines maximum positively-sloped diagonal (da) +""" + +Glat_format_3_subbox_entry = """ + > + left: B # xi + right: B # xa + bottom: B # yi + top: B # ya + diagNegMin: B # Defines minimum negatively-sloped diagonal (si) + diagNegMax: B # Defines maximum negatively-sloped diagonal (sa) + diagPosMin: B # Defines minimum positively-sloped diagonal (di) + diagPosMax: B # Defines maximum positively-sloped diagonal (da) +""" + + +class _Object: + pass + + +class _Dict(dict): + pass + + +class table_G__l_a_t(DefaultTable.DefaultTable): + """Graphite Glyph Attributes table + + See also https://graphite.sil.org/graphite_techAbout#graphite-font-tables + """ + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.scheme = 0 + + def decompile(self, data, ttFont): + sstruct.unpack2(Glat_format_0, data, self) + self.version = float(floatToFixedToStr(self.version, precisionBits=16)) + if self.version <= 1.9: + decoder = partial(self.decompileAttributes12, fmt=Glat_format_1_entry) + elif self.version <= 2.9: + decoder = partial(self.decompileAttributes12, fmt=Glat_format_23_entry) + elif self.version >= 3.0: + data, self.scheme = grUtils.decompress(data) + sstruct.unpack2(Glat_format_3, data, self) + self.hasOctaboxes = (self.compression & 1) == 1 + decoder = self.decompileAttributes3 + + gloc = ttFont["Gloc"] + self.attributes = {} + count = 0 + for s, e in zip(gloc, gloc[1:]): + self.attributes[ttFont.getGlyphName(count)] = decoder(data[s:e]) + count += 1 + + def decompileAttributes12(self, data, fmt): + attributes = _Dict() + while len(data) > 3: + e, data = sstruct.unpack2(fmt, data, _Object()) + keys = range(e.attNum, e.attNum + e.num) + if len(data) >= 2 * e.num: + vals = struct.unpack_from((">%dh" % e.num), data) + attributes.update(zip(keys, vals)) + data = data[2 * e.num :] + return attributes + + def decompileAttributes3(self, data): + if self.hasOctaboxes: + o, data = sstruct.unpack2(Glat_format_3_octabox_metrics, data, _Object()) + numsub = bin(o.subboxBitmap).count("1") + o.subboxes = [] + for b in range(numsub): + if len(data) >= 8: + subbox, data = sstruct.unpack2( + Glat_format_3_subbox_entry, data, _Object() + ) + o.subboxes.append(subbox) + attrs = self.decompileAttributes12(data, Glat_format_23_entry) + if self.hasOctaboxes: + attrs.octabox = o + return attrs + + def compile(self, ttFont): + data = sstruct.pack(Glat_format_0, self) + if self.version <= 1.9: + encoder = partial(self.compileAttributes12, fmt=Glat_format_1_entry) + elif self.version <= 2.9: + encoder = partial(self.compileAttributes12, fmt=Glat_format_1_entry) + elif self.version >= 3.0: + self.compression = (self.scheme << 27) + (1 if self.hasOctaboxes else 0) + data = sstruct.pack(Glat_format_3, self) + encoder = self.compileAttributes3 + + glocs = [] + for n in range(len(self.attributes)): + glocs.append(len(data)) + data += encoder(self.attributes[ttFont.getGlyphName(n)]) + glocs.append(len(data)) + ttFont["Gloc"].set(glocs) + + if self.version >= 3.0: + data = grUtils.compress(self.scheme, data) + return data + + def compileAttributes12(self, attrs, fmt): + data = b"" + for e in grUtils.entries(attrs): + data += sstruct.pack(fmt, {"attNum": e[0], "num": e[1]}) + struct.pack( + (">%dh" % len(e[2])), *e[2] + ) + return data + + def compileAttributes3(self, attrs): + if self.hasOctaboxes: + o = attrs.octabox + data = sstruct.pack(Glat_format_3_octabox_metrics, o) + numsub = bin(o.subboxBitmap).count("1") + for b in range(numsub): + data += sstruct.pack(Glat_format_3_subbox_entry, o.subboxes[b]) + else: + data = "" + return data + self.compileAttributes12(attrs, Glat_format_23_entry) + + def toXML(self, writer, ttFont): + writer.simpletag("version", version=self.version, compressionScheme=self.scheme) + writer.newline() + for n, a in sorted( + self.attributes.items(), key=lambda x: ttFont.getGlyphID(x[0]) + ): + writer.begintag("glyph", name=n) + writer.newline() + if hasattr(a, "octabox"): + o = a.octabox + formatstring, names, fixes = sstruct.getformat( + Glat_format_3_octabox_metrics + ) + vals = {} + for k in names: + if k == "subboxBitmap": + continue + vals[k] = "{:.3f}%".format(getattr(o, k) * 100.0 / 255) + vals["bitmap"] = "{:0X}".format(o.subboxBitmap) + writer.begintag("octaboxes", **vals) + writer.newline() + formatstring, names, fixes = sstruct.getformat( + Glat_format_3_subbox_entry + ) + for s in o.subboxes: + vals = {} + for k in names: + vals[k] = "{:.3f}%".format(getattr(s, k) * 100.0 / 255) + writer.simpletag("octabox", **vals) + writer.newline() + writer.endtag("octaboxes") + writer.newline() + for k, v in sorted(a.items()): + writer.simpletag("attribute", index=k, value=v) + writer.newline() + writer.endtag("glyph") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "version": + self.version = float(safeEval(attrs["version"])) + self.scheme = int(safeEval(attrs["compressionScheme"])) + if name != "glyph": + return + if not hasattr(self, "attributes"): + self.attributes = {} + gname = attrs["name"] + attributes = _Dict() + for element in content: + if not isinstance(element, tuple): + continue + tag, attrs, subcontent = element + if tag == "attribute": + k = int(safeEval(attrs["index"])) + v = int(safeEval(attrs["value"])) + attributes[k] = v + elif tag == "octaboxes": + self.hasOctaboxes = True + o = _Object() + o.subboxBitmap = int(attrs["bitmap"], 16) + o.subboxes = [] + del attrs["bitmap"] + for k, v in attrs.items(): + setattr(o, k, int(float(v[:-1]) * 255.0 / 100.0 + 0.5)) + for element in subcontent: + if not isinstance(element, tuple): + continue + tag, attrs, subcontent = element + so = _Object() + for k, v in attrs.items(): + setattr(so, k, int(float(v[:-1]) * 255.0 / 100.0 + 0.5)) + o.subboxes.append(so) + attributes.octabox = o + self.attributes[gname] = attributes diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G__l_o_c.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G__l_o_c.py new file mode 100644 index 0000000000000000000000000000000000000000..68cf1e29da27aac512325779d16b54427d3da8ba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/G__l_o_c.py @@ -0,0 +1,84 @@ +from fontTools.misc import sstruct +from fontTools.misc.textTools import safeEval +from . import DefaultTable +import array +import sys + +Gloc_header = """ + > # big endian + version: 16.16F # Table version + flags: H # bit 0: 1=long format, 0=short format + # bit 1: 1=attribute names, 0=no names + numAttribs: H # NUmber of attributes +""" + + +class table_G__l_o_c(DefaultTable.DefaultTable): + """Graphite Index to Glyph Atttributes table + + See also https://graphite.sil.org/graphite_techAbout#graphite-font-tables + """ + + dependencies = ["Glat"] + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.attribIds = None + self.numAttribs = 0 + + def decompile(self, data, ttFont): + _, data = sstruct.unpack2(Gloc_header, data, self) + flags = self.flags + del self.flags + self.locations = array.array("I" if flags & 1 else "H") + self.locations.frombytes(data[: len(data) - self.numAttribs * (flags & 2)]) + if sys.byteorder != "big": + self.locations.byteswap() + self.attribIds = array.array("H") + if flags & 2: + self.attribIds.frombytes(data[-self.numAttribs * 2 :]) + if sys.byteorder != "big": + self.attribIds.byteswap() + + def compile(self, ttFont): + data = sstruct.pack( + Gloc_header, + dict( + version=1.0, + flags=(bool(self.attribIds) << 1) + (self.locations.typecode == "I"), + numAttribs=self.numAttribs, + ), + ) + if sys.byteorder != "big": + self.locations.byteswap() + data += self.locations.tobytes() + if sys.byteorder != "big": + self.locations.byteswap() + if self.attribIds: + if sys.byteorder != "big": + self.attribIds.byteswap() + data += self.attribIds.tobytes() + if sys.byteorder != "big": + self.attribIds.byteswap() + return data + + def set(self, locations): + long_format = max(locations) >= 65536 + self.locations = array.array("I" if long_format else "H", locations) + + def toXML(self, writer, ttFont): + writer.simpletag("attributes", number=self.numAttribs) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "attributes": + self.numAttribs = int(safeEval(attrs["number"])) + + def __getitem__(self, index): + return self.locations[index] + + def __len__(self): + return len(self.locations) + + def __iter__(self): + return iter(self.locations) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/H_V_A_R_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/H_V_A_R_.py new file mode 100644 index 0000000000000000000000000000000000000000..48e7fd67cf0f89e5dc6057e5cbae7f07324a0402 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/H_V_A_R_.py @@ -0,0 +1,13 @@ +from .otBase import BaseTTXConverter + + +class table_H_V_A_R_(BaseTTXConverter): + """Horizontal Metrics Variations table + + The ``HVAR`` table contains variations in horizontal glyph metrics + in variable fonts. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/hvar + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/I_F_T_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/I_F_T_.py new file mode 100644 index 0000000000000000000000000000000000000000..3aa5f3f61ce694c10175c4d3a1d71b4bf96686f7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/I_F_T_.py @@ -0,0 +1,12 @@ +"""IFT - Incremental Font Transfer table.""" + +# Reference: https://github.com/googlefonts/fontations/blob/main/read-fonts/src/tables/ift.rs + + +from .otBase import BaseTTXConverter + + +class table_I_F_T_(BaseTTXConverter): + """Incremental Font Transfer table.""" + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/I_F_T_X_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/I_F_T_X_.py new file mode 100644 index 0000000000000000000000000000000000000000..4ce3b9a50da8f04259988314bb46d0d7a411b4aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/I_F_T_X_.py @@ -0,0 +1,12 @@ +"""IFT - Incremental Font Transfer table.""" + +# Reference: https://github.com/googlefonts/fontations/blob/main/read-fonts/src/tables/ift.rs + + +from .otBase import BaseTTXConverter + + +class table_I_F_T_X_(BaseTTXConverter): + """Incremental Font Transfer table.""" + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/J_S_T_F_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/J_S_T_F_.py new file mode 100644 index 0000000000000000000000000000000000000000..b185f30f3a9a2978c1d4278b920f69969fe79b97 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/J_S_T_F_.py @@ -0,0 +1,13 @@ +from .otBase import BaseTTXConverter + + +class table_J_S_T_F_(BaseTTXConverter): + """Justification table + + The ``JSTF`` table contains glyph substitution and positioning + data used to perform text justification. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/jstf + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/L_T_S_H_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/L_T_S_H_.py new file mode 100644 index 0000000000000000000000000000000000000000..e691c06e9bfdc270127c2a5be33acf6505177d85 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/L_T_S_H_.py @@ -0,0 +1,58 @@ +from fontTools.misc.textTools import safeEval +from . import DefaultTable +import struct +import array + +# XXX I've lowered the strictness, to make sure Apple's own Chicago +# XXX gets through. They're looking into it, I hope to raise the standards +# XXX back to normal eventually. + + +class table_L_T_S_H_(DefaultTable.DefaultTable): + """Linear Threshold table + + The ``LTSH`` table contains per-glyph settings indicating the ppem sizes + at which the advance width metric should be scaled linearly, despite the + effects of any TrueType instructions that might otherwise alter the + advance width. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/ltsh + """ + + def decompile(self, data, ttFont): + version, numGlyphs = struct.unpack(">HH", data[:4]) + data = data[4:] + assert version == 0, "unknown version: %s" % version + assert (len(data) % numGlyphs) < 4, "numGlyphs doesn't match data length" + # ouch: the assertion is not true in Chicago! + # assert numGlyphs == ttFont['maxp'].numGlyphs + yPels = array.array("B") + yPels.frombytes(data) + self.yPels = {} + for i in range(numGlyphs): + self.yPels[ttFont.getGlyphName(i)] = yPels[i] + + def compile(self, ttFont): + version = 0 + names = list(self.yPels.keys()) + numGlyphs = len(names) + yPels = [0] * numGlyphs + # ouch: the assertion is not true in Chicago! + # assert len(self.yPels) == ttFont['maxp'].numGlyphs == numGlyphs + for name in names: + yPels[ttFont.getGlyphID(name)] = self.yPels[name] + yPels = array.array("B", yPels) + return struct.pack(">HH", version, numGlyphs) + yPels.tobytes() + + def toXML(self, writer, ttFont): + names = sorted(self.yPels.keys()) + for name in names: + writer.simpletag("yPel", name=name, value=self.yPels[name]) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if not hasattr(self, "yPels"): + self.yPels = {} + if name != "yPel": + return # ignore unknown tags + self.yPels[attrs["name"]] = safeEval(attrs["value"]) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/M_A_T_H_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/M_A_T_H_.py new file mode 100644 index 0000000000000000000000000000000000000000..35d29e9b13e9c8aeca0a95a3e965c52e7c96aed1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/M_A_T_H_.py @@ -0,0 +1,13 @@ +from .otBase import BaseTTXConverter + + +class table_M_A_T_H_(BaseTTXConverter): + """Mathematical Typesetting table + + The ``MATH`` table contains a variety of information needed to + typeset glyphs in mathematical formulas and expressions. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/math + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/M_V_A_R_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/M_V_A_R_.py new file mode 100644 index 0000000000000000000000000000000000000000..c7e7e90fb49965b962f502a3ac9135a1c00b0374 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/M_V_A_R_.py @@ -0,0 +1,13 @@ +from .otBase import BaseTTXConverter + + +class table_M_V_A_R_(BaseTTXConverter): + """Metrics Variations table + + The ``MVAR`` table contains variation information for font-wide + metrics in a variable font. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/mvar + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/O_S_2f_2.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/O_S_2f_2.py new file mode 100644 index 0000000000000000000000000000000000000000..7ada7f3fc76ded08a73d8c50bc4cdd786d3f8cc6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/O_S_2f_2.py @@ -0,0 +1,752 @@ +from fontTools.misc import sstruct +from fontTools.misc.roundTools import otRound +from fontTools.misc.textTools import safeEval, num2binary, binary2num +from fontTools.ttLib.tables import DefaultTable +import bisect +import logging + +log = logging.getLogger(__name__) + +# panose classification + +panoseFormat = """ + bFamilyType: B + bSerifStyle: B + bWeight: B + bProportion: B + bContrast: B + bStrokeVariation: B + bArmStyle: B + bLetterForm: B + bMidline: B + bXHeight: B +""" + + +class Panose(object): + def __init__(self, **kwargs): + _, names, _ = sstruct.getformat(panoseFormat) + for name in names: + setattr(self, name, kwargs.pop(name, 0)) + for k in kwargs: + raise TypeError(f"Panose() got an unexpected keyword argument {k!r}") + + def toXML(self, writer, ttFont): + formatstring, names, fixes = sstruct.getformat(panoseFormat) + for name in names: + writer.simpletag(name, value=getattr(self, name)) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + setattr(self, name, safeEval(attrs["value"])) + + +# 'sfnt' OS/2 and Windows Metrics table - 'OS/2' + +OS2_format_0 = """ + > # big endian + version: H # version + xAvgCharWidth: h # average character width + usWeightClass: H # degree of thickness of strokes + usWidthClass: H # aspect ratio + fsType: H # type flags + ySubscriptXSize: h # subscript horizontal font size + ySubscriptYSize: h # subscript vertical font size + ySubscriptXOffset: h # subscript x offset + ySubscriptYOffset: h # subscript y offset + ySuperscriptXSize: h # superscript horizontal font size + ySuperscriptYSize: h # superscript vertical font size + ySuperscriptXOffset: h # superscript x offset + ySuperscriptYOffset: h # superscript y offset + yStrikeoutSize: h # strikeout size + yStrikeoutPosition: h # strikeout position + sFamilyClass: h # font family class and subclass + panose: 10s # panose classification number + ulUnicodeRange1: L # character range + ulUnicodeRange2: L # character range + ulUnicodeRange3: L # character range + ulUnicodeRange4: L # character range + achVendID: 4s # font vendor identification + fsSelection: H # font selection flags + usFirstCharIndex: H # first unicode character index + usLastCharIndex: H # last unicode character index + sTypoAscender: h # typographic ascender + sTypoDescender: h # typographic descender + sTypoLineGap: h # typographic line gap + usWinAscent: H # Windows ascender + usWinDescent: H # Windows descender +""" + +OS2_format_1_addition = """ + ulCodePageRange1: L + ulCodePageRange2: L +""" + +OS2_format_2_addition = OS2_format_1_addition + """ + sxHeight: h + sCapHeight: h + usDefaultChar: H + usBreakChar: H + usMaxContext: H +""" + +OS2_format_5_addition = OS2_format_2_addition + """ + usLowerOpticalPointSize: H + usUpperOpticalPointSize: H +""" + +bigendian = " > # big endian\n" + +OS2_format_1 = OS2_format_0 + OS2_format_1_addition +OS2_format_2 = OS2_format_0 + OS2_format_2_addition +OS2_format_5 = OS2_format_0 + OS2_format_5_addition +OS2_format_1_addition = bigendian + OS2_format_1_addition +OS2_format_2_addition = bigendian + OS2_format_2_addition +OS2_format_5_addition = bigendian + OS2_format_5_addition + + +class table_O_S_2f_2(DefaultTable.DefaultTable): + """OS/2 and Windows Metrics table + + The ``OS/2`` table contains a variety of font-wide metrics and + parameters that may be useful to an operating system or other + software for system-integration purposes. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/os2 + """ + + dependencies = ["head", "bhed"] + + def decompile(self, data, ttFont): + dummy, data = sstruct.unpack2(OS2_format_0, data, self) + + if self.version == 1: + dummy, data = sstruct.unpack2(OS2_format_1_addition, data, self) + elif self.version in (2, 3, 4): + dummy, data = sstruct.unpack2(OS2_format_2_addition, data, self) + elif self.version == 5: + dummy, data = sstruct.unpack2(OS2_format_5_addition, data, self) + self.usLowerOpticalPointSize /= 20 + self.usUpperOpticalPointSize /= 20 + elif self.version != 0: + from fontTools import ttLib + + raise ttLib.TTLibError( + "unknown format for OS/2 table: version %s" % self.version + ) + if len(data): + log.warning("too much 'OS/2' table data") + + self.panose = sstruct.unpack(panoseFormat, self.panose, Panose()) + + def compile(self, ttFont): + self.updateFirstAndLastCharIndex(ttFont) + panose = self.panose + self._checkHeadMacStyle("head", ttFont) + self._checkHeadMacStyle("bhed", ttFont) + if (self.fsSelection & 1 << 6) and (self.fsSelection & 1 + (1 << 5)): + log.warning( + "fsSelection bit 6 (regular) is set, " + "bits 0 (italic) and 5 (bold) must be clear" + ) + if self.version < 4 and self.fsSelection & 0b1110000000: + log.warning( + "fsSelection bits 7, 8 and 9 are only defined in " + "OS/2 table version 4 and up: version %s", + self.version, + ) + self.panose = sstruct.pack(panoseFormat, self.panose) + if self.version == 0: + data = sstruct.pack(OS2_format_0, self) + elif self.version == 1: + data = sstruct.pack(OS2_format_1, self) + elif self.version in (2, 3, 4): + data = sstruct.pack(OS2_format_2, self) + elif self.version == 5: + d = self.__dict__.copy() + d["usLowerOpticalPointSize"] = round(self.usLowerOpticalPointSize * 20) + d["usUpperOpticalPointSize"] = round(self.usUpperOpticalPointSize * 20) + data = sstruct.pack(OS2_format_5, d) + else: + from fontTools import ttLib + + raise ttLib.TTLibError( + "unknown format for OS/2 table: version %s" % self.version + ) + self.panose = panose + return data + + def toXML(self, writer, ttFont): + writer.comment( + "The fields 'usFirstCharIndex' and 'usLastCharIndex'\n" + "will be recalculated by the compiler" + ) + writer.newline() + if self.version == 1: + format = OS2_format_1 + elif self.version in (2, 3, 4): + format = OS2_format_2 + elif self.version == 5: + format = OS2_format_5 + else: + format = OS2_format_0 + formatstring, names, fixes = sstruct.getformat(format) + for name in names: + value = getattr(self, name) + if name == "panose": + writer.begintag("panose") + writer.newline() + value.toXML(writer, ttFont) + writer.endtag("panose") + elif name in ( + "ulUnicodeRange1", + "ulUnicodeRange2", + "ulUnicodeRange3", + "ulUnicodeRange4", + "ulCodePageRange1", + "ulCodePageRange2", + ): + writer.simpletag(name, value=num2binary(value)) + elif name in ("fsType", "fsSelection"): + writer.simpletag(name, value=num2binary(value, 16)) + elif name == "achVendID": + writer.simpletag(name, value=repr(value)[1:-1]) + else: + writer.simpletag(name, value=value) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "panose": + self.panose = panose = Panose() + for element in content: + if isinstance(element, tuple): + name, attrs, content = element + panose.fromXML(name, attrs, content, ttFont) + elif name in ( + "ulUnicodeRange1", + "ulUnicodeRange2", + "ulUnicodeRange3", + "ulUnicodeRange4", + "ulCodePageRange1", + "ulCodePageRange2", + "fsType", + "fsSelection", + ): + setattr(self, name, binary2num(attrs["value"])) + elif name == "achVendID": + setattr(self, name, safeEval("'''" + attrs["value"] + "'''")) + else: + setattr(self, name, safeEval(attrs["value"])) + + def updateFirstAndLastCharIndex(self, ttFont): + if "cmap" not in ttFont: + return + codes = set() + for table in getattr(ttFont["cmap"], "tables", []): + if table.isUnicode(): + codes.update(table.cmap.keys()) + if codes: + minCode = min(codes) + maxCode = max(codes) + # USHORT cannot hold codepoints greater than 0xFFFF + self.usFirstCharIndex = min(0xFFFF, minCode) + self.usLastCharIndex = min(0xFFFF, maxCode) + + def _checkHeadMacStyle(self, tag, ttFont): + if tag in ttFont: + head = ttFont[tag] + if (self.fsSelection & 1) and not (head.macStyle & 1 << 1): + log.warning( + "fsSelection bit 0 (italic) and " + "%s table macStyle bit 1 (italic) should match", + tag, + ) + if (self.fsSelection & 1 << 5) and not (head.macStyle & 1): + log.warning( + "fsSelection bit 5 (bold) and " + "%s table macStyle bit 0 (bold) should match", + tag, + ) + + # misspelled attributes kept for legacy reasons + + @property + def usMaxContex(self): + return self.usMaxContext + + @usMaxContex.setter + def usMaxContex(self, value): + self.usMaxContext = value + + @property + def fsFirstCharIndex(self): + return self.usFirstCharIndex + + @fsFirstCharIndex.setter + def fsFirstCharIndex(self, value): + self.usFirstCharIndex = value + + @property + def fsLastCharIndex(self): + return self.usLastCharIndex + + @fsLastCharIndex.setter + def fsLastCharIndex(self, value): + self.usLastCharIndex = value + + def getUnicodeRanges(self): + """Return the set of 'ulUnicodeRange*' bits currently enabled.""" + bits = set() + ul1, ul2 = self.ulUnicodeRange1, self.ulUnicodeRange2 + ul3, ul4 = self.ulUnicodeRange3, self.ulUnicodeRange4 + for i in range(32): + if ul1 & (1 << i): + bits.add(i) + if ul2 & (1 << i): + bits.add(i + 32) + if ul3 & (1 << i): + bits.add(i + 64) + if ul4 & (1 << i): + bits.add(i + 96) + return bits + + def setUnicodeRanges(self, bits): + """Set the 'ulUnicodeRange*' fields to the specified 'bits'.""" + ul1, ul2, ul3, ul4 = 0, 0, 0, 0 + for bit in bits: + if 0 <= bit < 32: + ul1 |= 1 << bit + elif 32 <= bit < 64: + ul2 |= 1 << (bit - 32) + elif 64 <= bit < 96: + ul3 |= 1 << (bit - 64) + elif 96 <= bit < 128: + ul4 |= 1 << (bit - 96) + else: + raise ValueError("expected 0 <= int <= 127, found: %r" % bit) + self.ulUnicodeRange1, self.ulUnicodeRange2 = ul1, ul2 + self.ulUnicodeRange3, self.ulUnicodeRange4 = ul3, ul4 + + def recalcUnicodeRanges(self, ttFont, pruneOnly=False): + """Intersect the codepoints in the font's Unicode cmap subtables with + the Unicode block ranges defined in the OpenType specification (v1.7), + and set the respective 'ulUnicodeRange*' bits if there is at least ONE + intersection. + If 'pruneOnly' is True, only clear unused bits with NO intersection. + """ + unicodes = set() + for table in ttFont["cmap"].tables: + if table.isUnicode(): + unicodes.update(table.cmap.keys()) + if pruneOnly: + empty = intersectUnicodeRanges(unicodes, inverse=True) + bits = self.getUnicodeRanges() - empty + else: + bits = intersectUnicodeRanges(unicodes) + self.setUnicodeRanges(bits) + return bits + + def getCodePageRanges(self): + """Return the set of 'ulCodePageRange*' bits currently enabled.""" + bits = set() + if self.version < 1: + return bits + ul1, ul2 = self.ulCodePageRange1, self.ulCodePageRange2 + for i in range(32): + if ul1 & (1 << i): + bits.add(i) + if ul2 & (1 << i): + bits.add(i + 32) + return bits + + def setCodePageRanges(self, bits): + """Set the 'ulCodePageRange*' fields to the specified 'bits'.""" + ul1, ul2 = 0, 0 + for bit in bits: + if 0 <= bit < 32: + ul1 |= 1 << bit + elif 32 <= bit < 64: + ul2 |= 1 << (bit - 32) + else: + raise ValueError(f"expected 0 <= int <= 63, found: {bit:r}") + if self.version < 1: + self.version = 1 + self.ulCodePageRange1, self.ulCodePageRange2 = ul1, ul2 + + def recalcCodePageRanges(self, ttFont, pruneOnly=False): + unicodes = set() + for table in ttFont["cmap"].tables: + if table.isUnicode(): + unicodes.update(table.cmap.keys()) + bits = calcCodePageRanges(unicodes) + if pruneOnly: + bits &= self.getCodePageRanges() + # when no codepage ranges can be enabled, fall back to enabling bit 0 + # (Latin 1) so that the font works in MS Word: + # https://github.com/googlei18n/fontmake/issues/468 + if not bits: + bits = {0} + self.setCodePageRanges(bits) + return bits + + def recalcAvgCharWidth(self, ttFont): + """Recalculate xAvgCharWidth using metrics from ttFont's 'hmtx' table. + + Set it to 0 if the unlikely event 'hmtx' table is not found. + """ + avg_width = 0 + hmtx = ttFont.get("hmtx") + if hmtx is not None: + widths = [width for width, _ in hmtx.metrics.values() if width > 0] + if widths: + avg_width = otRound(sum(widths) / len(widths)) + self.xAvgCharWidth = avg_width + return avg_width + + +# Unicode ranges data from the OpenType OS/2 table specification v1.7 + +OS2_UNICODE_RANGES = ( + (("Basic Latin", (0x0000, 0x007F)),), + (("Latin-1 Supplement", (0x0080, 0x00FF)),), + (("Latin Extended-A", (0x0100, 0x017F)),), + (("Latin Extended-B", (0x0180, 0x024F)),), + ( + ("IPA Extensions", (0x0250, 0x02AF)), + ("Phonetic Extensions", (0x1D00, 0x1D7F)), + ("Phonetic Extensions Supplement", (0x1D80, 0x1DBF)), + ), + ( + ("Spacing Modifier Letters", (0x02B0, 0x02FF)), + ("Modifier Tone Letters", (0xA700, 0xA71F)), + ), + ( + ("Combining Diacritical Marks", (0x0300, 0x036F)), + ("Combining Diacritical Marks Supplement", (0x1DC0, 0x1DFF)), + ), + (("Greek and Coptic", (0x0370, 0x03FF)),), + (("Coptic", (0x2C80, 0x2CFF)),), + ( + ("Cyrillic", (0x0400, 0x04FF)), + ("Cyrillic Supplement", (0x0500, 0x052F)), + ("Cyrillic Extended-A", (0x2DE0, 0x2DFF)), + ("Cyrillic Extended-B", (0xA640, 0xA69F)), + ), + (("Armenian", (0x0530, 0x058F)),), + (("Hebrew", (0x0590, 0x05FF)),), + (("Vai", (0xA500, 0xA63F)),), + (("Arabic", (0x0600, 0x06FF)), ("Arabic Supplement", (0x0750, 0x077F))), + (("NKo", (0x07C0, 0x07FF)),), + (("Devanagari", (0x0900, 0x097F)),), + (("Bengali", (0x0980, 0x09FF)),), + (("Gurmukhi", (0x0A00, 0x0A7F)),), + (("Gujarati", (0x0A80, 0x0AFF)),), + (("Oriya", (0x0B00, 0x0B7F)),), + (("Tamil", (0x0B80, 0x0BFF)),), + (("Telugu", (0x0C00, 0x0C7F)),), + (("Kannada", (0x0C80, 0x0CFF)),), + (("Malayalam", (0x0D00, 0x0D7F)),), + (("Thai", (0x0E00, 0x0E7F)),), + (("Lao", (0x0E80, 0x0EFF)),), + (("Georgian", (0x10A0, 0x10FF)), ("Georgian Supplement", (0x2D00, 0x2D2F))), + (("Balinese", (0x1B00, 0x1B7F)),), + (("Hangul Jamo", (0x1100, 0x11FF)),), + ( + ("Latin Extended Additional", (0x1E00, 0x1EFF)), + ("Latin Extended-C", (0x2C60, 0x2C7F)), + ("Latin Extended-D", (0xA720, 0xA7FF)), + ), + (("Greek Extended", (0x1F00, 0x1FFF)),), + ( + ("General Punctuation", (0x2000, 0x206F)), + ("Supplemental Punctuation", (0x2E00, 0x2E7F)), + ), + (("Superscripts And Subscripts", (0x2070, 0x209F)),), + (("Currency Symbols", (0x20A0, 0x20CF)),), + (("Combining Diacritical Marks For Symbols", (0x20D0, 0x20FF)),), + (("Letterlike Symbols", (0x2100, 0x214F)),), + (("Number Forms", (0x2150, 0x218F)),), + ( + ("Arrows", (0x2190, 0x21FF)), + ("Supplemental Arrows-A", (0x27F0, 0x27FF)), + ("Supplemental Arrows-B", (0x2900, 0x297F)), + ("Miscellaneous Symbols and Arrows", (0x2B00, 0x2BFF)), + ), + ( + ("Mathematical Operators", (0x2200, 0x22FF)), + ("Supplemental Mathematical Operators", (0x2A00, 0x2AFF)), + ("Miscellaneous Mathematical Symbols-A", (0x27C0, 0x27EF)), + ("Miscellaneous Mathematical Symbols-B", (0x2980, 0x29FF)), + ), + (("Miscellaneous Technical", (0x2300, 0x23FF)),), + (("Control Pictures", (0x2400, 0x243F)),), + (("Optical Character Recognition", (0x2440, 0x245F)),), + (("Enclosed Alphanumerics", (0x2460, 0x24FF)),), + (("Box Drawing", (0x2500, 0x257F)),), + (("Block Elements", (0x2580, 0x259F)),), + (("Geometric Shapes", (0x25A0, 0x25FF)),), + (("Miscellaneous Symbols", (0x2600, 0x26FF)),), + (("Dingbats", (0x2700, 0x27BF)),), + (("CJK Symbols And Punctuation", (0x3000, 0x303F)),), + (("Hiragana", (0x3040, 0x309F)),), + ( + ("Katakana", (0x30A0, 0x30FF)), + ("Katakana Phonetic Extensions", (0x31F0, 0x31FF)), + ), + (("Bopomofo", (0x3100, 0x312F)), ("Bopomofo Extended", (0x31A0, 0x31BF))), + (("Hangul Compatibility Jamo", (0x3130, 0x318F)),), + (("Phags-pa", (0xA840, 0xA87F)),), + (("Enclosed CJK Letters And Months", (0x3200, 0x32FF)),), + (("CJK Compatibility", (0x3300, 0x33FF)),), + (("Hangul Syllables", (0xAC00, 0xD7AF)),), + (("Non-Plane 0 *", (0xD800, 0xDFFF)),), + (("Phoenician", (0x10900, 0x1091F)),), + ( + ("CJK Unified Ideographs", (0x4E00, 0x9FFF)), + ("CJK Radicals Supplement", (0x2E80, 0x2EFF)), + ("Kangxi Radicals", (0x2F00, 0x2FDF)), + ("Ideographic Description Characters", (0x2FF0, 0x2FFF)), + ("CJK Unified Ideographs Extension A", (0x3400, 0x4DBF)), + ("CJK Unified Ideographs Extension B", (0x20000, 0x2A6DF)), + ("Kanbun", (0x3190, 0x319F)), + ), + (("Private Use Area (plane 0)", (0xE000, 0xF8FF)),), + ( + ("CJK Strokes", (0x31C0, 0x31EF)), + ("CJK Compatibility Ideographs", (0xF900, 0xFAFF)), + ("CJK Compatibility Ideographs Supplement", (0x2F800, 0x2FA1F)), + ), + (("Alphabetic Presentation Forms", (0xFB00, 0xFB4F)),), + (("Arabic Presentation Forms-A", (0xFB50, 0xFDFF)),), + (("Combining Half Marks", (0xFE20, 0xFE2F)),), + ( + ("Vertical Forms", (0xFE10, 0xFE1F)), + ("CJK Compatibility Forms", (0xFE30, 0xFE4F)), + ), + (("Small Form Variants", (0xFE50, 0xFE6F)),), + (("Arabic Presentation Forms-B", (0xFE70, 0xFEFF)),), + (("Halfwidth And Fullwidth Forms", (0xFF00, 0xFFEF)),), + (("Specials", (0xFFF0, 0xFFFF)),), + (("Tibetan", (0x0F00, 0x0FFF)),), + (("Syriac", (0x0700, 0x074F)),), + (("Thaana", (0x0780, 0x07BF)),), + (("Sinhala", (0x0D80, 0x0DFF)),), + (("Myanmar", (0x1000, 0x109F)),), + ( + ("Ethiopic", (0x1200, 0x137F)), + ("Ethiopic Supplement", (0x1380, 0x139F)), + ("Ethiopic Extended", (0x2D80, 0x2DDF)), + ), + (("Cherokee", (0x13A0, 0x13FF)),), + (("Unified Canadian Aboriginal Syllabics", (0x1400, 0x167F)),), + (("Ogham", (0x1680, 0x169F)),), + (("Runic", (0x16A0, 0x16FF)),), + (("Khmer", (0x1780, 0x17FF)), ("Khmer Symbols", (0x19E0, 0x19FF))), + (("Mongolian", (0x1800, 0x18AF)),), + (("Braille Patterns", (0x2800, 0x28FF)),), + (("Yi Syllables", (0xA000, 0xA48F)), ("Yi Radicals", (0xA490, 0xA4CF))), + ( + ("Tagalog", (0x1700, 0x171F)), + ("Hanunoo", (0x1720, 0x173F)), + ("Buhid", (0x1740, 0x175F)), + ("Tagbanwa", (0x1760, 0x177F)), + ), + (("Old Italic", (0x10300, 0x1032F)),), + (("Gothic", (0x10330, 0x1034F)),), + (("Deseret", (0x10400, 0x1044F)),), + ( + ("Byzantine Musical Symbols", (0x1D000, 0x1D0FF)), + ("Musical Symbols", (0x1D100, 0x1D1FF)), + ("Ancient Greek Musical Notation", (0x1D200, 0x1D24F)), + ), + (("Mathematical Alphanumeric Symbols", (0x1D400, 0x1D7FF)),), + ( + ("Private Use (plane 15)", (0xF0000, 0xFFFFD)), + ("Private Use (plane 16)", (0x100000, 0x10FFFD)), + ), + ( + ("Variation Selectors", (0xFE00, 0xFE0F)), + ("Variation Selectors Supplement", (0xE0100, 0xE01EF)), + ), + (("Tags", (0xE0000, 0xE007F)),), + (("Limbu", (0x1900, 0x194F)),), + (("Tai Le", (0x1950, 0x197F)),), + (("New Tai Lue", (0x1980, 0x19DF)),), + (("Buginese", (0x1A00, 0x1A1F)),), + (("Glagolitic", (0x2C00, 0x2C5F)),), + (("Tifinagh", (0x2D30, 0x2D7F)),), + (("Yijing Hexagram Symbols", (0x4DC0, 0x4DFF)),), + (("Syloti Nagri", (0xA800, 0xA82F)),), + ( + ("Linear B Syllabary", (0x10000, 0x1007F)), + ("Linear B Ideograms", (0x10080, 0x100FF)), + ("Aegean Numbers", (0x10100, 0x1013F)), + ), + (("Ancient Greek Numbers", (0x10140, 0x1018F)),), + (("Ugaritic", (0x10380, 0x1039F)),), + (("Old Persian", (0x103A0, 0x103DF)),), + (("Shavian", (0x10450, 0x1047F)),), + (("Osmanya", (0x10480, 0x104AF)),), + (("Cypriot Syllabary", (0x10800, 0x1083F)),), + (("Kharoshthi", (0x10A00, 0x10A5F)),), + (("Tai Xuan Jing Symbols", (0x1D300, 0x1D35F)),), + ( + ("Cuneiform", (0x12000, 0x123FF)), + ("Cuneiform Numbers and Punctuation", (0x12400, 0x1247F)), + ), + (("Counting Rod Numerals", (0x1D360, 0x1D37F)),), + (("Sundanese", (0x1B80, 0x1BBF)),), + (("Lepcha", (0x1C00, 0x1C4F)),), + (("Ol Chiki", (0x1C50, 0x1C7F)),), + (("Saurashtra", (0xA880, 0xA8DF)),), + (("Kayah Li", (0xA900, 0xA92F)),), + (("Rejang", (0xA930, 0xA95F)),), + (("Cham", (0xAA00, 0xAA5F)),), + (("Ancient Symbols", (0x10190, 0x101CF)),), + (("Phaistos Disc", (0x101D0, 0x101FF)),), + ( + ("Carian", (0x102A0, 0x102DF)), + ("Lycian", (0x10280, 0x1029F)), + ("Lydian", (0x10920, 0x1093F)), + ), + (("Domino Tiles", (0x1F030, 0x1F09F)), ("Mahjong Tiles", (0x1F000, 0x1F02F))), +) + + +_unicodeStarts = [] +_unicodeValues = [None] + + +def _getUnicodeRanges(): + # build the ranges of codepoints for each unicode range bit, and cache result + if not _unicodeStarts: + unicodeRanges = [ + (start, (stop, bit)) + for bit, blocks in enumerate(OS2_UNICODE_RANGES) + for _, (start, stop) in blocks + ] + for start, (stop, bit) in sorted(unicodeRanges): + _unicodeStarts.append(start) + _unicodeValues.append((stop, bit)) + return _unicodeStarts, _unicodeValues + + +def intersectUnicodeRanges(unicodes, inverse=False): + """Intersect a sequence of (int) Unicode codepoints with the Unicode block + ranges defined in the OpenType specification v1.7, and return the set of + 'ulUnicodeRanges' bits for which there is at least ONE intersection. + If 'inverse' is True, return the the bits for which there is NO intersection. + + >>> intersectUnicodeRanges([0x0410]) == {9} + True + >>> intersectUnicodeRanges([0x0410, 0x1F000]) == {9, 57, 122} + True + >>> intersectUnicodeRanges([0x0410, 0x1F000], inverse=True) == ( + ... set(range(len(OS2_UNICODE_RANGES))) - {9, 57, 122}) + True + """ + unicodes = set(unicodes) + unicodestarts, unicodevalues = _getUnicodeRanges() + bits = set() + for code in unicodes: + stop, bit = unicodevalues[bisect.bisect(unicodestarts, code)] + if code <= stop: + bits.add(bit) + # The spec says that bit 57 ("Non Plane 0") implies that there's + # at least one codepoint beyond the BMP; so I also include all + # the non-BMP codepoints here + if any(0x10000 <= code < 0x110000 for code in unicodes): + bits.add(57) + return set(range(len(OS2_UNICODE_RANGES))) - bits if inverse else bits + + +def calcCodePageRanges(unicodes): + """Given a set of Unicode codepoints (integers), calculate the + corresponding OS/2 CodePage range bits. + This is a direct translation of FontForge implementation: + https://github.com/fontforge/fontforge/blob/7b2c074/fontforge/tottf.c#L3158 + """ + bits = set() + hasAscii = set(range(0x20, 0x7E)).issubset(unicodes) + hasLineart = ord("┤") in unicodes + + for uni in unicodes: + if uni == ord("Þ") and hasAscii: + bits.add(0) # Latin 1 + elif uni == ord("Ľ") and hasAscii: + bits.add(1) # Latin 2: Eastern Europe + if hasLineart: + bits.add(58) # Latin 2 + elif uni == ord("Б"): + bits.add(2) # Cyrillic + if ord("Ѕ") in unicodes and hasLineart: + bits.add(57) # IBM Cyrillic + if ord("╜") in unicodes and hasLineart: + bits.add(49) # MS-DOS Russian + elif uni == ord("Ά"): + bits.add(3) # Greek + if hasLineart and ord("½") in unicodes: + bits.add(48) # IBM Greek + if hasLineart and ord("√") in unicodes: + bits.add(60) # Greek, former 437 G + elif uni == ord("İ") and hasAscii: + bits.add(4) # Turkish + if hasLineart: + bits.add(56) # IBM turkish + elif uni == ord("א"): + bits.add(5) # Hebrew + if hasLineart and ord("√") in unicodes: + bits.add(53) # Hebrew + elif uni == ord("ر"): + bits.add(6) # Arabic + if ord("√") in unicodes: + bits.add(51) # Arabic + if hasLineart: + bits.add(61) # Arabic; ASMO 708 + elif uni == ord("ŗ") and hasAscii: + bits.add(7) # Windows Baltic + if hasLineart: + bits.add(59) # MS-DOS Baltic + elif uni == ord("₫") and hasAscii: + bits.add(8) # Vietnamese + elif uni == ord("ๅ"): + bits.add(16) # Thai + elif uni == ord("エ"): + bits.add(17) # JIS/Japan + elif uni == ord("ㄅ"): + bits.add(18) # Chinese: Simplified + elif uni == ord("ㄱ"): + bits.add(19) # Korean wansung + elif uni == ord("央"): + bits.add(20) # Chinese: Traditional + elif uni == ord("곴"): + bits.add(21) # Korean Johab + elif uni == ord("♥") and hasAscii: + bits.add(30) # OEM Character Set + # TODO: Symbol bit has a special meaning (check the spec), we need + # to confirm if this is wanted by default. + # elif chr(0xF000) <= char <= chr(0xF0FF): + # codepageRanges.add(31) # Symbol Character Set + elif uni == ord("þ") and hasAscii and hasLineart: + bits.add(54) # MS-DOS Icelandic + elif uni == ord("╚") and hasAscii: + bits.add(62) # WE/Latin 1 + bits.add(63) # US + elif hasAscii and hasLineart and ord("√") in unicodes: + if uni == ord("Å"): + bits.add(50) # MS-DOS Nordic + elif uni == ord("é"): + bits.add(52) # MS-DOS Canadian French + elif uni == ord("õ"): + bits.add(55) # MS-DOS Portuguese + + if hasAscii and ord("‰") in unicodes and ord("∑") in unicodes: + bits.add(29) # Macintosh Character Set (US Roman) + + return bits + + +if __name__ == "__main__": + import doctest, sys + + sys.exit(doctest.testmod().failed) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/S_T_A_T_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/S_T_A_T_.py new file mode 100644 index 0000000000000000000000000000000000000000..86e1271a9817ecb71b663e60ffa685cbf9205bd5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/S_T_A_T_.py @@ -0,0 +1,15 @@ +from .otBase import BaseTTXConverter + + +class table_S_T_A_T_(BaseTTXConverter): + """Style Attributes table + + The ``STAT`` table records stylistic or typeface-design attributes that + differentiate the individual fonts within a font family from one another. + Those attributes can be used to assist users when navigating the style + variations of a variable font or a family of static fonts. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/stat + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/S_V_G_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/S_V_G_.py new file mode 100644 index 0000000000000000000000000000000000000000..3a728b461029a9ce79afb8a50bcb4bc5d7f14c43 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/S_V_G_.py @@ -0,0 +1,222 @@ +"""Compiles/decompiles SVG table. + +https://docs.microsoft.com/en-us/typography/opentype/spec/svg + +The XML format is: + +.. code-block:: xml + + + + <complete SVG doc> ]] + </svgDoc> + ... + <svgDoc endGlyphID="n" startGlyphID="m"> + <![CDATA[ <complete SVG doc> ]] + </svgDoc> + </SVG> +""" + +from fontTools.misc.textTools import bytesjoin, safeEval, strjoin, tobytes, tostr +from fontTools.misc import sstruct +from . import DefaultTable +from collections.abc import Sequence +from dataclasses import dataclass, astuple +from io import BytesIO +import struct +import logging + +log = logging.getLogger(__name__) + + +SVG_format_0 = """ + > # big endian + version: H + offsetToSVGDocIndex: L + reserved: L +""" + +SVG_format_0Size = sstruct.calcsize(SVG_format_0) + +doc_index_entry_format_0 = """ + > # big endian + startGlyphID: H + endGlyphID: H + svgDocOffset: L + svgDocLength: L +""" + +doc_index_entry_format_0Size = sstruct.calcsize(doc_index_entry_format_0) + + +class table_S_V_G_(DefaultTable.DefaultTable): + """Scalable Vector Graphics table + + The ``SVG`` table contains representations for glyphs in the SVG + image format. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/stat + """ + + def decompile(self, data, ttFont): + self.docList = [] + # Version 0 is the standardized version of the table; and current. + # https://www.microsoft.com/typography/otspec/svg.htm + sstruct.unpack(SVG_format_0, data[:SVG_format_0Size], self) + if self.version != 0: + log.warning( + "Unknown SVG table version '%s'. Decompiling as version 0.", + self.version, + ) + # read in SVG Documents Index + # data starts with the first entry of the entry list. + pos = subTableStart = self.offsetToSVGDocIndex + self.numEntries = struct.unpack(">H", data[pos : pos + 2])[0] + pos += 2 + if self.numEntries > 0: + data2 = data[pos:] + entries = [] + for i in range(self.numEntries): + record_data = data2[ + i + * doc_index_entry_format_0Size : (i + 1) + * doc_index_entry_format_0Size + ] + docIndexEntry = sstruct.unpack( + doc_index_entry_format_0, record_data, DocumentIndexEntry() + ) + entries.append(docIndexEntry) + + for entry in entries: + start = entry.svgDocOffset + subTableStart + end = start + entry.svgDocLength + doc = data[start:end] + compressed = False + if doc.startswith(b"\x1f\x8b"): + import gzip + + bytesIO = BytesIO(doc) + with gzip.GzipFile(None, "r", fileobj=bytesIO) as gunzipper: + doc = gunzipper.read() + del bytesIO + compressed = True + doc = tostr(doc, "utf_8") + self.docList.append( + SVGDocument(doc, entry.startGlyphID, entry.endGlyphID, compressed) + ) + + def compile(self, ttFont): + version = 0 + offsetToSVGDocIndex = ( + SVG_format_0Size # I start the SVGDocIndex right after the header. + ) + # get SGVDoc info. + docList = [] + entryList = [] + numEntries = len(self.docList) + datum = struct.pack(">H", numEntries) + entryList.append(datum) + curOffset = len(datum) + doc_index_entry_format_0Size * numEntries + seenDocs = {} + allCompressed = getattr(self, "compressed", False) + for i, doc in enumerate(self.docList): + if isinstance(doc, (list, tuple)): + doc = SVGDocument(*doc) + self.docList[i] = doc + docBytes = tobytes(doc.data, encoding="utf_8") + if (allCompressed or doc.compressed) and not docBytes.startswith( + b"\x1f\x8b" + ): + import gzip + + bytesIO = BytesIO() + # mtime=0 strips the useless timestamp and makes gzip output reproducible; + # equivalent to `gzip -n` + with gzip.GzipFile(None, "w", fileobj=bytesIO, mtime=0) as gzipper: + gzipper.write(docBytes) + gzipped = bytesIO.getvalue() + if len(gzipped) < len(docBytes): + docBytes = gzipped + del gzipped, bytesIO + docLength = len(docBytes) + if docBytes in seenDocs: + docOffset = seenDocs[docBytes] + else: + docOffset = curOffset + curOffset += docLength + seenDocs[docBytes] = docOffset + docList.append(docBytes) + entry = struct.pack( + ">HHLL", doc.startGlyphID, doc.endGlyphID, docOffset, docLength + ) + entryList.append(entry) + entryList.extend(docList) + svgDocData = bytesjoin(entryList) + + reserved = 0 + header = struct.pack(">HLL", version, offsetToSVGDocIndex, reserved) + data = [header, svgDocData] + data = bytesjoin(data) + return data + + def toXML(self, writer, ttFont): + for i, doc in enumerate(self.docList): + if isinstance(doc, (list, tuple)): + doc = SVGDocument(*doc) + self.docList[i] = doc + attrs = {"startGlyphID": doc.startGlyphID, "endGlyphID": doc.endGlyphID} + if doc.compressed: + attrs["compressed"] = 1 + writer.begintag("svgDoc", **attrs) + writer.newline() + writer.writecdata(doc.data) + writer.newline() + writer.endtag("svgDoc") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "svgDoc": + if not hasattr(self, "docList"): + self.docList = [] + doc = strjoin(content) + doc = doc.strip() + startGID = int(attrs["startGlyphID"]) + endGID = int(attrs["endGlyphID"]) + compressed = bool(safeEval(attrs.get("compressed", "0"))) + self.docList.append(SVGDocument(doc, startGID, endGID, compressed)) + else: + log.warning("Unknown %s %s", name, content) + + +class DocumentIndexEntry(object): + def __init__(self): + self.startGlyphID = None # USHORT + self.endGlyphID = None # USHORT + self.svgDocOffset = None # ULONG + self.svgDocLength = None # ULONG + + def __repr__(self): + return ( + "startGlyphID: %s, endGlyphID: %s, svgDocOffset: %s, svgDocLength: %s" + % (self.startGlyphID, self.endGlyphID, self.svgDocOffset, self.svgDocLength) + ) + + +@dataclass +class SVGDocument(Sequence): + data: str + startGlyphID: int + endGlyphID: int + compressed: bool = False + + # Previously, the SVG table's docList attribute contained a lists of 3 items: + # [doc, startGlyphID, endGlyphID]; later, we added a `compressed` attribute. + # For backward compatibility with code that depends of them being sequences of + # fixed length=3, we subclass the Sequence abstract base class and pretend only + # the first three items are present. 'compressed' is only accessible via named + # attribute lookup like regular dataclasses: i.e. `doc.compressed`, not `doc[3]` + def __getitem__(self, index): + return astuple(self)[:3][index] + + def __len__(self): + return 3 diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/S__i_l_f.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/S__i_l_f.py new file mode 100644 index 0000000000000000000000000000000000000000..d6476c8d26dc5a136a1872a86d6b1c214854d45d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/S__i_l_f.py @@ -0,0 +1,1040 @@ +from fontTools.misc import sstruct +from fontTools.misc.fixedTools import floatToFixedToStr +from fontTools.misc.textTools import byteord, safeEval + +# from itertools import * +from . import DefaultTable +from . import grUtils +from array import array +from functools import reduce +import struct, re, sys + +Silf_hdr_format = """ + > + version: 16.16F +""" + +Silf_hdr_format_3 = """ + > + version: 16.16F + compilerVersion: L + numSilf: H + x + x +""" + +Silf_part1_format_v3 = """ + > + ruleVersion: 16.16F + passOffset: H + pseudosOffset: H +""" + +Silf_part1_format = """ + > + maxGlyphID: H + extraAscent: h + extraDescent: h + numPasses: B + iSubst: B + iPos: B + iJust: B + iBidi: B + flags: B + maxPreContext: B + maxPostContext: B + attrPseudo: B + attrBreakWeight: B + attrDirectionality: B + attrMirroring: B + attrSkipPasses: B + numJLevels: B +""" + +Silf_justify_format = """ + > + attrStretch: B + attrShrink: B + attrStep: B + attrWeight: B + runto: B + x + x + x +""" + +Silf_part2_format = """ + > + numLigComp: H + numUserDefn: B + maxCompPerLig: B + direction: B + attCollisions: B + x + x + x + numCritFeatures: B +""" + +Silf_pseudomap_format = """ + > + unicode: L + nPseudo: H +""" + +Silf_pseudomap_format_h = """ + > + unicode: H + nPseudo: H +""" + +Silf_classmap_format = """ + > + numClass: H + numLinear: H +""" + +Silf_lookupclass_format = """ + > + numIDs: H + searchRange: H + entrySelector: H + rangeShift: H +""" + +Silf_lookuppair_format = """ + > + glyphId: H + index: H +""" + +Silf_pass_format = """ + > + flags: B + maxRuleLoop: B + maxRuleContext: B + maxBackup: B + numRules: H + fsmOffset: H + pcCode: L + rcCode: L + aCode: L + oDebug: L + numRows: H + numTransitional: H + numSuccess: H + numColumns: H +""" + +aCode_info = ( + ("NOP", 0), + ("PUSH_BYTE", "b"), + ("PUSH_BYTE_U", "B"), + ("PUSH_SHORT", ">h"), + ("PUSH_SHORT_U", ">H"), + ("PUSH_LONG", ">L"), + ("ADD", 0), + ("SUB", 0), + ("MUL", 0), + ("DIV", 0), + ("MIN", 0), + ("MAX", 0), + ("NEG", 0), + ("TRUNC8", 0), + ("TRUNC16", 0), + ("COND", 0), + ("AND", 0), # x10 + ("OR", 0), + ("NOT", 0), + ("EQUAL", 0), + ("NOT_EQ", 0), + ("LESS", 0), + ("GTR", 0), + ("LESS_EQ", 0), + ("GTR_EQ", 0), + ("NEXT", 0), + ("NEXT_N", "b"), + ("COPY_NEXT", 0), + ("PUT_GLYPH_8BIT_OBS", "B"), + ("PUT_SUBS_8BIT_OBS", "bBB"), + ("PUT_COPY", "b"), + ("INSERT", 0), + ("DELETE", 0), # x20 + ("ASSOC", -1), + ("CNTXT_ITEM", "bB"), + ("ATTR_SET", "B"), + ("ATTR_ADD", "B"), + ("ATTR_SUB", "B"), + ("ATTR_SET_SLOT", "B"), + ("IATTR_SET_SLOT", "BB"), + ("PUSH_SLOT_ATTR", "Bb"), + ("PUSH_GLYPH_ATTR_OBS", "Bb"), + ("PUSH_GLYPH_METRIC", "Bbb"), + ("PUSH_FEAT", "Bb"), + ("PUSH_ATT_TO_GATTR_OBS", "Bb"), + ("PUSH_ATT_TO_GLYPH_METRIC", "Bbb"), + ("PUSH_ISLOT_ATTR", "Bbb"), + ("PUSH_IGLYPH_ATTR", "Bbb"), + ("POP_RET", 0), # x30 + ("RET_ZERO", 0), + ("RET_TRUE", 0), + ("IATTR_SET", "BB"), + ("IATTR_ADD", "BB"), + ("IATTR_SUB", "BB"), + ("PUSH_PROC_STATE", "B"), + ("PUSH_VERSION", 0), + ("PUT_SUBS", ">bHH"), + ("PUT_SUBS2", 0), + ("PUT_SUBS3", 0), + ("PUT_GLYPH", ">H"), + ("PUSH_GLYPH_ATTR", ">Hb"), + ("PUSH_ATT_TO_GLYPH_ATTR", ">Hb"), + ("BITOR", 0), + ("BITAND", 0), + ("BITNOT", 0), # x40 + ("BITSET", ">HH"), + ("SET_FEAT", "Bb"), +) +aCode_map = dict([(x[0], (i, x[1])) for i, x in enumerate(aCode_info)]) + + +def disassemble(aCode): + codelen = len(aCode) + pc = 0 + res = [] + while pc < codelen: + opcode = byteord(aCode[pc : pc + 1]) + if opcode > len(aCode_info): + instr = aCode_info[0] + else: + instr = aCode_info[opcode] + pc += 1 + if instr[1] != 0 and pc >= codelen: + return res + if instr[1] == -1: + count = byteord(aCode[pc]) + fmt = "%dB" % count + pc += 1 + elif instr[1] == 0: + fmt = "" + else: + fmt = instr[1] + if fmt == "": + res.append(instr[0]) + continue + parms = struct.unpack_from(fmt, aCode[pc:]) + res.append(instr[0] + "(" + ", ".join(map(str, parms)) + ")") + pc += struct.calcsize(fmt) + return res + + +instre = re.compile(r"^\s*([^(]+)\s*(?:\(([^)]+)\))?") + + +def assemble(instrs): + res = b"" + for inst in instrs: + m = instre.match(inst) + if not m or not m.group(1) in aCode_map: + continue + opcode, parmfmt = aCode_map[m.group(1)] + res += struct.pack("B", opcode) + if m.group(2): + if parmfmt == 0: + continue + parms = [int(x) for x in re.split(r",\s*", m.group(2))] + if parmfmt == -1: + l = len(parms) + res += struct.pack(("%dB" % (l + 1)), l, *parms) + else: + res += struct.pack(parmfmt, *parms) + return res + + +def writecode(tag, writer, instrs): + writer.begintag(tag) + writer.newline() + for l in disassemble(instrs): + writer.write(l) + writer.newline() + writer.endtag(tag) + writer.newline() + + +def readcode(content): + res = [] + for e in content_string(content).split("\n"): + e = e.strip() + if not len(e): + continue + res.append(e) + return assemble(res) + + +attrs_info = ( + "flags", + "extraAscent", + "extraDescent", + "maxGlyphID", + "numLigComp", + "numUserDefn", + "maxCompPerLig", + "direction", + "lbGID", +) +attrs_passindexes = ("iSubst", "iPos", "iJust", "iBidi") +attrs_contexts = ("maxPreContext", "maxPostContext") +attrs_attributes = ( + "attrPseudo", + "attrBreakWeight", + "attrDirectionality", + "attrMirroring", + "attrSkipPasses", + "attCollisions", +) +pass_attrs_info = ( + "flags", + "maxRuleLoop", + "maxRuleContext", + "maxBackup", + "minRulePreContext", + "maxRulePreContext", + "collisionThreshold", +) +pass_attrs_fsm = ("numRows", "numTransitional", "numSuccess", "numColumns") + + +def writesimple(tag, self, writer, *attrkeys): + attrs = dict([(k, getattr(self, k)) for k in attrkeys]) + writer.simpletag(tag, **attrs) + writer.newline() + + +def getSimple(self, attrs, *attr_list): + for k in attr_list: + if k in attrs: + setattr(self, k, int(safeEval(attrs[k]))) + + +def content_string(contents): + res = "" + for element in contents: + if isinstance(element, tuple): + continue + res += element + return res.strip() + + +def wrapline(writer, dat, length=80): + currline = "" + for d in dat: + if len(currline) > length: + writer.write(currline[:-1]) + writer.newline() + currline = "" + currline += d + " " + if len(currline): + writer.write(currline[:-1]) + writer.newline() + + +class _Object: + pass + + +class table_S__i_l_f(DefaultTable.DefaultTable): + """Graphite Rules table + + See also https://graphite.sil.org/graphite_techAbout#graphite-font-tables + """ + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.silfs = [] + + def decompile(self, data, ttFont): + sstruct.unpack2(Silf_hdr_format, data, self) + self.version = float(floatToFixedToStr(self.version, precisionBits=16)) + if self.version >= 5.0: + data, self.scheme = grUtils.decompress(data) + sstruct.unpack2(Silf_hdr_format_3, data, self) + base = sstruct.calcsize(Silf_hdr_format_3) + elif self.version < 3.0: + self.numSilf = struct.unpack(">H", data[4:6]) + self.scheme = 0 + self.compilerVersion = 0 + base = 8 + else: + self.scheme = 0 + sstruct.unpack2(Silf_hdr_format_3, data, self) + base = sstruct.calcsize(Silf_hdr_format_3) + + silfoffsets = struct.unpack_from((">%dL" % self.numSilf), data[base:]) + for offset in silfoffsets: + s = Silf() + self.silfs.append(s) + s.decompile(data[offset:], ttFont, self.version) + + def compile(self, ttFont): + self.numSilf = len(self.silfs) + if self.version < 3.0: + hdr = sstruct.pack(Silf_hdr_format, self) + hdr += struct.pack(">HH", self.numSilf, 0) + else: + hdr = sstruct.pack(Silf_hdr_format_3, self) + offset = len(hdr) + 4 * self.numSilf + data = b"" + for s in self.silfs: + hdr += struct.pack(">L", offset) + subdata = s.compile(ttFont, self.version) + offset += len(subdata) + data += subdata + if self.version >= 5.0: + return grUtils.compress(self.scheme, hdr + data) + return hdr + data + + def toXML(self, writer, ttFont): + writer.comment("Attributes starting with _ are informative only") + writer.newline() + writer.simpletag( + "version", + version=self.version, + compilerVersion=self.compilerVersion, + compressionScheme=self.scheme, + ) + writer.newline() + for s in self.silfs: + writer.begintag("silf") + writer.newline() + s.toXML(writer, ttFont, self.version) + writer.endtag("silf") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "version": + self.scheme = int(safeEval(attrs["compressionScheme"])) + self.version = float(safeEval(attrs["version"])) + self.compilerVersion = int(safeEval(attrs["compilerVersion"])) + return + if name == "silf": + s = Silf() + self.silfs.append(s) + for element in content: + if not isinstance(element, tuple): + continue + tag, attrs, subcontent = element + s.fromXML(tag, attrs, subcontent, ttFont, self.version) + + +class Silf(object): + """A particular Silf subtable""" + + def __init__(self): + self.passes = [] + self.scriptTags = [] + self.critFeatures = [] + self.jLevels = [] + self.pMap = {} + + def decompile(self, data, ttFont, version=2.0): + if version >= 3.0: + _, data = sstruct.unpack2(Silf_part1_format_v3, data, self) + self.ruleVersion = float( + floatToFixedToStr(self.ruleVersion, precisionBits=16) + ) + _, data = sstruct.unpack2(Silf_part1_format, data, self) + for jlevel in range(self.numJLevels): + j, data = sstruct.unpack2(Silf_justify_format, data, _Object()) + self.jLevels.append(j) + _, data = sstruct.unpack2(Silf_part2_format, data, self) + if self.numCritFeatures: + self.critFeatures = struct.unpack_from( + (">%dH" % self.numCritFeatures), data + ) + data = data[self.numCritFeatures * 2 + 1 :] + (numScriptTag,) = struct.unpack_from("B", data) + if numScriptTag: + self.scriptTags = [ + struct.unpack("4s", data[x : x + 4])[0].decode("ascii") + for x in range(1, 1 + 4 * numScriptTag, 4) + ] + data = data[1 + 4 * numScriptTag :] + (self.lbGID,) = struct.unpack(">H", data[:2]) + if self.numPasses: + self.oPasses = struct.unpack( + (">%dL" % (self.numPasses + 1)), data[2 : 6 + 4 * self.numPasses] + ) + data = data[6 + 4 * self.numPasses :] + (numPseudo,) = struct.unpack(">H", data[:2]) + for i in range(numPseudo): + if version >= 3.0: + pseudo = sstruct.unpack( + Silf_pseudomap_format, data[8 + 6 * i : 14 + 6 * i], _Object() + ) + else: + pseudo = sstruct.unpack( + Silf_pseudomap_format_h, data[8 + 4 * i : 12 + 4 * i], _Object() + ) + self.pMap[pseudo.unicode] = ttFont.getGlyphName(pseudo.nPseudo) + data = data[8 + 6 * numPseudo :] + currpos = ( + sstruct.calcsize(Silf_part1_format) + + sstruct.calcsize(Silf_justify_format) * self.numJLevels + + sstruct.calcsize(Silf_part2_format) + + 2 * self.numCritFeatures + + 1 + + 1 + + 4 * numScriptTag + + 6 + + 4 * self.numPasses + + 8 + + 6 * numPseudo + ) + if version >= 3.0: + currpos += sstruct.calcsize(Silf_part1_format_v3) + self.classes = Classes() + self.classes.decompile(data, ttFont, version) + for i in range(self.numPasses): + p = Pass() + self.passes.append(p) + p.decompile( + data[self.oPasses[i] - currpos : self.oPasses[i + 1] - currpos], + ttFont, + version, + ) + + def compile(self, ttFont, version=2.0): + self.numPasses = len(self.passes) + self.numJLevels = len(self.jLevels) + self.numCritFeatures = len(self.critFeatures) + numPseudo = len(self.pMap) + data = b"" + if version >= 3.0: + hdroffset = sstruct.calcsize(Silf_part1_format_v3) + else: + hdroffset = 0 + data += sstruct.pack(Silf_part1_format, self) + for j in self.jLevels: + data += sstruct.pack(Silf_justify_format, j) + data += sstruct.pack(Silf_part2_format, self) + if self.numCritFeatures: + data += struct.pack((">%dH" % self.numCritFeaturs), *self.critFeatures) + data += struct.pack("BB", 0, len(self.scriptTags)) + if len(self.scriptTags): + tdata = [struct.pack("4s", x.encode("ascii")) for x in self.scriptTags] + data += b"".join(tdata) + data += struct.pack(">H", self.lbGID) + self.passOffset = len(data) + + data1 = grUtils.bininfo(numPseudo, 6) + currpos = hdroffset + len(data) + 4 * (self.numPasses + 1) + self.pseudosOffset = currpos + len(data1) + for u, p in sorted(self.pMap.items()): + data1 += struct.pack( + (">LH" if version >= 3.0 else ">HH"), u, ttFont.getGlyphID(p) + ) + data1 += self.classes.compile(ttFont, version) + currpos += len(data1) + data2 = b"" + datao = b"" + for i, p in enumerate(self.passes): + base = currpos + len(data2) + datao += struct.pack(">L", base) + data2 += p.compile(ttFont, base, version) + datao += struct.pack(">L", currpos + len(data2)) + + if version >= 3.0: + data3 = sstruct.pack(Silf_part1_format_v3, self) + else: + data3 = b"" + return data3 + data + datao + data1 + data2 + + def toXML(self, writer, ttFont, version=2.0): + if version >= 3.0: + writer.simpletag("version", ruleVersion=self.ruleVersion) + writer.newline() + writesimple("info", self, writer, *attrs_info) + writesimple("passindexes", self, writer, *attrs_passindexes) + writesimple("contexts", self, writer, *attrs_contexts) + writesimple("attributes", self, writer, *attrs_attributes) + if len(self.jLevels): + writer.begintag("justifications") + writer.newline() + jformat, jnames, jfixes = sstruct.getformat(Silf_justify_format) + for i, j in enumerate(self.jLevels): + attrs = dict([(k, getattr(j, k)) for k in jnames]) + writer.simpletag("justify", **attrs) + writer.newline() + writer.endtag("justifications") + writer.newline() + if len(self.critFeatures): + writer.begintag("critFeatures") + writer.newline() + writer.write(" ".join(map(str, self.critFeatures))) + writer.newline() + writer.endtag("critFeatures") + writer.newline() + if len(self.scriptTags): + writer.begintag("scriptTags") + writer.newline() + writer.write(" ".join(self.scriptTags)) + writer.newline() + writer.endtag("scriptTags") + writer.newline() + if self.pMap: + writer.begintag("pseudoMap") + writer.newline() + for k, v in sorted(self.pMap.items()): + writer.simpletag("pseudo", unicode=hex(k), pseudo=v) + writer.newline() + writer.endtag("pseudoMap") + writer.newline() + self.classes.toXML(writer, ttFont, version) + if len(self.passes): + writer.begintag("passes") + writer.newline() + for i, p in enumerate(self.passes): + writer.begintag("pass", _index=i) + writer.newline() + p.toXML(writer, ttFont, version) + writer.endtag("pass") + writer.newline() + writer.endtag("passes") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont, version=2.0): + if name == "version": + self.ruleVersion = float(safeEval(attrs.get("ruleVersion", "0"))) + if name == "info": + getSimple(self, attrs, *attrs_info) + elif name == "passindexes": + getSimple(self, attrs, *attrs_passindexes) + elif name == "contexts": + getSimple(self, attrs, *attrs_contexts) + elif name == "attributes": + getSimple(self, attrs, *attrs_attributes) + elif name == "justifications": + for element in content: + if not isinstance(element, tuple): + continue + tag, attrs, subcontent = element + if tag == "justify": + j = _Object() + for k, v in attrs.items(): + setattr(j, k, int(v)) + self.jLevels.append(j) + elif name == "critFeatures": + self.critFeatures = [] + element = content_string(content) + self.critFeatures.extend(map(int, element.split())) + elif name == "scriptTags": + self.scriptTags = [] + element = content_string(content) + for n in element.split(): + self.scriptTags.append(n) + elif name == "pseudoMap": + self.pMap = {} + for element in content: + if not isinstance(element, tuple): + continue + tag, attrs, subcontent = element + if tag == "pseudo": + k = int(attrs["unicode"], 16) + v = attrs["pseudo"] + self.pMap[k] = v + elif name == "classes": + self.classes = Classes() + for element in content: + if not isinstance(element, tuple): + continue + tag, attrs, subcontent = element + self.classes.fromXML(tag, attrs, subcontent, ttFont, version) + elif name == "passes": + for element in content: + if not isinstance(element, tuple): + continue + tag, attrs, subcontent = element + if tag == "pass": + p = Pass() + for e in subcontent: + if not isinstance(e, tuple): + continue + p.fromXML(e[0], e[1], e[2], ttFont, version) + self.passes.append(p) + + +class Classes(object): + def __init__(self): + self.linear = [] + self.nonLinear = [] + + def decompile(self, data, ttFont, version=2.0): + sstruct.unpack2(Silf_classmap_format, data, self) + if version >= 4.0: + oClasses = struct.unpack( + (">%dL" % (self.numClass + 1)), data[4 : 8 + 4 * self.numClass] + ) + else: + oClasses = struct.unpack( + (">%dH" % (self.numClass + 1)), data[4 : 6 + 2 * self.numClass] + ) + for s, e in zip(oClasses[: self.numLinear], oClasses[1 : self.numLinear + 1]): + self.linear.append( + ttFont.getGlyphName(x) + for x in struct.unpack((">%dH" % ((e - s) / 2)), data[s:e]) + ) + for s, e in zip( + oClasses[self.numLinear : self.numClass], + oClasses[self.numLinear + 1 : self.numClass + 1], + ): + nonLinids = [ + struct.unpack(">HH", data[x : x + 4]) for x in range(s + 8, e, 4) + ] + nonLin = dict([(ttFont.getGlyphName(x[0]), x[1]) for x in nonLinids]) + self.nonLinear.append(nonLin) + + def compile(self, ttFont, version=2.0): + data = b"" + oClasses = [] + if version >= 4.0: + offset = 8 + 4 * (len(self.linear) + len(self.nonLinear)) + else: + offset = 6 + 2 * (len(self.linear) + len(self.nonLinear)) + for l in self.linear: + oClasses.append(len(data) + offset) + gs = [ttFont.getGlyphID(x) for x in l] + data += struct.pack((">%dH" % len(l)), *gs) + for l in self.nonLinear: + oClasses.append(len(data) + offset) + gs = [(ttFont.getGlyphID(x[0]), x[1]) for x in l.items()] + data += grUtils.bininfo(len(gs)) + data += b"".join([struct.pack(">HH", *x) for x in sorted(gs)]) + oClasses.append(len(data) + offset) + self.numClass = len(oClasses) - 1 + self.numLinear = len(self.linear) + return ( + sstruct.pack(Silf_classmap_format, self) + + struct.pack( + ((">%dL" if version >= 4.0 else ">%dH") % len(oClasses)), *oClasses + ) + + data + ) + + def toXML(self, writer, ttFont, version=2.0): + writer.begintag("classes") + writer.newline() + writer.begintag("linearClasses") + writer.newline() + for i, l in enumerate(self.linear): + writer.begintag("linear", _index=i) + writer.newline() + wrapline(writer, l) + writer.endtag("linear") + writer.newline() + writer.endtag("linearClasses") + writer.newline() + writer.begintag("nonLinearClasses") + writer.newline() + for i, l in enumerate(self.nonLinear): + writer.begintag("nonLinear", _index=i + self.numLinear) + writer.newline() + for inp, ind in l.items(): + writer.simpletag("map", glyph=inp, index=ind) + writer.newline() + writer.endtag("nonLinear") + writer.newline() + writer.endtag("nonLinearClasses") + writer.newline() + writer.endtag("classes") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont, version=2.0): + if name == "linearClasses": + for element in content: + if not isinstance(element, tuple): + continue + tag, attrs, subcontent = element + if tag == "linear": + l = content_string(subcontent).split() + self.linear.append(l) + elif name == "nonLinearClasses": + for element in content: + if not isinstance(element, tuple): + continue + tag, attrs, subcontent = element + if tag == "nonLinear": + l = {} + for e in subcontent: + if not isinstance(e, tuple): + continue + tag, attrs, subsubcontent = e + if tag == "map": + l[attrs["glyph"]] = int(safeEval(attrs["index"])) + self.nonLinear.append(l) + + +class Pass(object): + def __init__(self): + self.colMap = {} + self.rules = [] + self.rulePreContexts = [] + self.ruleSortKeys = [] + self.ruleConstraints = [] + self.passConstraints = b"" + self.actions = [] + self.stateTrans = [] + self.startStates = [] + + def decompile(self, data, ttFont, version=2.0): + _, data = sstruct.unpack2(Silf_pass_format, data, self) + numRange, _, _, _ = struct.unpack(">4H", data[:8]) + data = data[8:] + for i in range(numRange): + first, last, col = struct.unpack(">3H", data[6 * i : 6 * i + 6]) + for g in range(first, last + 1): + self.colMap[ttFont.getGlyphName(g)] = col + data = data[6 * numRange :] + oRuleMap = struct.unpack_from((">%dH" % (self.numSuccess + 1)), data) + data = data[2 + 2 * self.numSuccess :] + rules = struct.unpack_from((">%dH" % oRuleMap[-1]), data) + self.rules = [rules[s:e] for (s, e) in zip(oRuleMap, oRuleMap[1:])] + data = data[2 * oRuleMap[-1] :] + self.minRulePreContext, self.maxRulePreContext = struct.unpack("BB", data[:2]) + numStartStates = self.maxRulePreContext - self.minRulePreContext + 1 + self.startStates = struct.unpack( + (">%dH" % numStartStates), data[2 : 2 + numStartStates * 2] + ) + data = data[2 + numStartStates * 2 :] + self.ruleSortKeys = struct.unpack( + (">%dH" % self.numRules), data[: 2 * self.numRules] + ) + data = data[2 * self.numRules :] + self.rulePreContexts = struct.unpack( + ("%dB" % self.numRules), data[: self.numRules] + ) + data = data[self.numRules :] + self.collisionThreshold, pConstraint = struct.unpack(">BH", data[:3]) + oConstraints = list( + struct.unpack( + (">%dH" % (self.numRules + 1)), data[3 : 5 + self.numRules * 2] + ) + ) + data = data[5 + self.numRules * 2 :] + oActions = list( + struct.unpack((">%dH" % (self.numRules + 1)), data[: 2 + self.numRules * 2]) + ) + data = data[2 * self.numRules + 2 :] + for i in range(self.numTransitional): + a = array( + "H", data[i * self.numColumns * 2 : (i + 1) * self.numColumns * 2] + ) + if sys.byteorder != "big": + a.byteswap() + self.stateTrans.append(a) + data = data[self.numTransitional * self.numColumns * 2 + 1 :] + self.passConstraints = data[:pConstraint] + data = data[pConstraint:] + for i in range(len(oConstraints) - 2, -1, -1): + if oConstraints[i] == 0: + oConstraints[i] = oConstraints[i + 1] + self.ruleConstraints = [ + (data[s:e] if (e - s > 1) else b"") + for (s, e) in zip(oConstraints, oConstraints[1:]) + ] + data = data[oConstraints[-1] :] + self.actions = [ + (data[s:e] if (e - s > 1) else "") for (s, e) in zip(oActions, oActions[1:]) + ] + data = data[oActions[-1] :] + # not using debug + + def compile(self, ttFont, base, version=2.0): + # build it all up backwards + oActions = reduce( + lambda a, x: (a[0] + len(x), a[1] + [a[0]]), self.actions + [b""], (0, []) + )[1] + oConstraints = reduce( + lambda a, x: (a[0] + len(x), a[1] + [a[0]]), + self.ruleConstraints + [b""], + (1, []), + )[1] + constraintCode = b"\000" + b"".join(self.ruleConstraints) + transes = [] + for t in self.stateTrans: + if sys.byteorder != "big": + t.byteswap() + transes.append(t.tobytes()) + if sys.byteorder != "big": + t.byteswap() + if not len(transes): + self.startStates = [0] + oRuleMap = reduce( + lambda a, x: (a[0] + len(x), a[1] + [a[0]]), self.rules + [[]], (0, []) + )[1] + passRanges = [] + gidcolmap = dict([(ttFont.getGlyphID(x[0]), x[1]) for x in self.colMap.items()]) + for e in grUtils.entries(gidcolmap, sameval=True): + if e[1]: + passRanges.append((e[0], e[0] + e[1] - 1, e[2][0])) + self.numRules = len(self.actions) + self.fsmOffset = ( + sstruct.calcsize(Silf_pass_format) + + 8 + + len(passRanges) * 6 + + len(oRuleMap) * 2 + + 2 * oRuleMap[-1] + + 2 + + 2 * len(self.startStates) + + 3 * self.numRules + + 3 + + 4 * self.numRules + + 4 + ) + self.pcCode = ( + self.fsmOffset + 2 * self.numTransitional * self.numColumns + 1 + base + ) + self.rcCode = self.pcCode + len(self.passConstraints) + self.aCode = self.rcCode + len(constraintCode) + self.oDebug = 0 + # now generate output + data = sstruct.pack(Silf_pass_format, self) + data += grUtils.bininfo(len(passRanges), 6) + data += b"".join(struct.pack(">3H", *p) for p in passRanges) + data += struct.pack((">%dH" % len(oRuleMap)), *oRuleMap) + flatrules = reduce(lambda a, x: a + x, self.rules, []) + data += struct.pack((">%dH" % oRuleMap[-1]), *flatrules) + data += struct.pack("BB", self.minRulePreContext, self.maxRulePreContext) + data += struct.pack((">%dH" % len(self.startStates)), *self.startStates) + data += struct.pack((">%dH" % self.numRules), *self.ruleSortKeys) + data += struct.pack(("%dB" % self.numRules), *self.rulePreContexts) + data += struct.pack(">BH", self.collisionThreshold, len(self.passConstraints)) + data += struct.pack((">%dH" % (self.numRules + 1)), *oConstraints) + data += struct.pack((">%dH" % (self.numRules + 1)), *oActions) + return ( + data + + b"".join(transes) + + struct.pack("B", 0) + + self.passConstraints + + constraintCode + + b"".join(self.actions) + ) + + def toXML(self, writer, ttFont, version=2.0): + writesimple("info", self, writer, *pass_attrs_info) + writesimple("fsminfo", self, writer, *pass_attrs_fsm) + writer.begintag("colmap") + writer.newline() + wrapline( + writer, + [ + "{}={}".format(*x) + for x in sorted( + self.colMap.items(), key=lambda x: ttFont.getGlyphID(x[0]) + ) + ], + ) + writer.endtag("colmap") + writer.newline() + writer.begintag("staterulemap") + writer.newline() + for i, r in enumerate(self.rules): + writer.simpletag( + "state", + number=self.numRows - self.numSuccess + i, + rules=" ".join(map(str, r)), + ) + writer.newline() + writer.endtag("staterulemap") + writer.newline() + writer.begintag("rules") + writer.newline() + for i, action in enumerate(self.actions): + writer.begintag( + "rule", + index=i, + precontext=self.rulePreContexts[i], + sortkey=self.ruleSortKeys[i], + ) + writer.newline() + if len(self.ruleConstraints[i]): + writecode("constraint", writer, self.ruleConstraints[i]) + writecode("action", writer, action) + writer.endtag("rule") + writer.newline() + writer.endtag("rules") + writer.newline() + if len(self.passConstraints): + writecode("passConstraint", writer, self.passConstraints) + if len(self.stateTrans): + writer.begintag("fsm") + writer.newline() + writer.begintag("starts") + writer.write(" ".join(map(str, self.startStates))) + writer.endtag("starts") + writer.newline() + for i, s in enumerate(self.stateTrans): + writer.begintag("row", _i=i) + # no newlines here + writer.write(" ".join(map(str, s))) + writer.endtag("row") + writer.newline() + writer.endtag("fsm") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont, version=2.0): + if name == "info": + getSimple(self, attrs, *pass_attrs_info) + elif name == "fsminfo": + getSimple(self, attrs, *pass_attrs_fsm) + elif name == "colmap": + e = content_string(content) + for w in e.split(): + x = w.split("=") + if len(x) != 2 or x[0] == "" or x[1] == "": + continue + self.colMap[x[0]] = int(x[1]) + elif name == "staterulemap": + for e in content: + if not isinstance(e, tuple): + continue + tag, a, c = e + if tag == "state": + self.rules.append([int(x) for x in a["rules"].split(" ")]) + elif name == "rules": + for element in content: + if not isinstance(element, tuple): + continue + tag, a, c = element + if tag != "rule": + continue + self.rulePreContexts.append(int(a["precontext"])) + self.ruleSortKeys.append(int(a["sortkey"])) + con = b"" + act = b"" + for e in c: + if not isinstance(e, tuple): + continue + tag, a, subc = e + if tag == "constraint": + con = readcode(subc) + elif tag == "action": + act = readcode(subc) + self.actions.append(act) + self.ruleConstraints.append(con) + elif name == "passConstraint": + self.passConstraints = readcode(content) + elif name == "fsm": + for element in content: + if not isinstance(element, tuple): + continue + tag, a, c = element + if tag == "row": + s = array("H") + e = content_string(c) + s.extend(map(int, e.split())) + self.stateTrans.append(s) + elif tag == "starts": + s = [] + e = content_string(c) + s.extend(map(int, e.split())) + self.startStates = s diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/S__i_l_l.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/S__i_l_l.py new file mode 100644 index 0000000000000000000000000000000000000000..f562edf1965bec63edd63e0712c8c30aa6dc651c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/S__i_l_l.py @@ -0,0 +1,92 @@ +from fontTools.misc import sstruct +from fontTools.misc.fixedTools import floatToFixedToStr +from fontTools.misc.textTools import safeEval +from . import DefaultTable +from . import grUtils +import struct + +Sill_hdr = """ + > + version: 16.16F +""" + + +class table_S__i_l_l(DefaultTable.DefaultTable): + """Graphite Languages table + + See also https://graphite.sil.org/graphite_techAbout#graphite-font-tables + """ + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.langs = {} + + def decompile(self, data, ttFont): + _, data = sstruct.unpack2(Sill_hdr, data, self) + self.version = float(floatToFixedToStr(self.version, precisionBits=16)) + (numLangs,) = struct.unpack(">H", data[:2]) + data = data[8:] + maxsetting = 0 + langinfo = [] + for i in range(numLangs): + langcode, numsettings, offset = struct.unpack( + ">4sHH", data[i * 8 : (i + 1) * 8] + ) + offset = int(offset / 8) - (numLangs + 1) + langcode = langcode.replace(b"\000", b"") + langinfo.append((langcode.decode("utf-8"), numsettings, offset)) + maxsetting = max(maxsetting, offset + numsettings) + data = data[numLangs * 8 :] + finfo = [] + for i in range(maxsetting): + fid, val, _ = struct.unpack(">LHH", data[i * 8 : (i + 1) * 8]) + finfo.append((fid, val)) + self.langs = {} + for c, n, o in langinfo: + self.langs[c] = [] + for i in range(o, o + n): + self.langs[c].append(finfo[i]) + + def compile(self, ttFont): + ldat = b"" + fdat = b"" + offset = len(self.langs) + for c, inf in sorted(self.langs.items()): + ldat += struct.pack(">4sHH", c.encode("utf8"), len(inf), 8 * offset + 20) + for fid, val in inf: + fdat += struct.pack(">LHH", fid, val, 0) + offset += len(inf) + ldat += struct.pack(">LHH", 0x80808080, 0, 8 * offset + 20) + return ( + sstruct.pack(Sill_hdr, self) + + grUtils.bininfo(len(self.langs)) + + ldat + + fdat + ) + + def toXML(self, writer, ttFont): + writer.simpletag("version", version=self.version) + writer.newline() + for c, inf in sorted(self.langs.items()): + writer.begintag("lang", name=c) + writer.newline() + for fid, val in inf: + writer.simpletag("feature", fid=grUtils.num2tag(fid), val=val) + writer.newline() + writer.endtag("lang") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "version": + self.version = float(safeEval(attrs["version"])) + elif name == "lang": + c = attrs["name"] + self.langs[c] = [] + for element in content: + if not isinstance(element, tuple): + continue + tag, a, subcontent = element + if tag == "feature": + self.langs[c].append( + (grUtils.tag2num(a["fid"]), int(safeEval(a["val"]))) + ) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_B_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_B_.py new file mode 100644 index 0000000000000000000000000000000000000000..66462a39fa5cc70ac176749c79d7fc91b0cbcd8e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_B_.py @@ -0,0 +1,13 @@ +"""TSI{B,C,D,J,P,S,V} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its table source data. + +TSIB contains the source text for the ``BASE`` table. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +from .T_S_I_V_ import table_T_S_I_V_ + + +class table_T_S_I_B_(table_T_S_I_V_): + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_C_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_C_.py new file mode 100644 index 0000000000000000000000000000000000000000..b59de0f2b9b4ad1f1939b9ece67604b987a6acd5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_C_.py @@ -0,0 +1,14 @@ +"""TSI{B,C,D,J,P,S,V} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its table source data. + +TSIC contains the source text for the Variation CVT window and data for +the ``cvar`` table. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +from .otBase import BaseTTXConverter + + +class table_T_S_I_C_(BaseTTXConverter): + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_D_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_D_.py new file mode 100644 index 0000000000000000000000000000000000000000..3905aeaecde2c86dc3c466ae43c707c29bdc2779 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_D_.py @@ -0,0 +1,13 @@ +"""TSI{B,C,D,J,P,S,V} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its table source data. + +TSID contains the source text for the ``GDEF`` table. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +from .T_S_I_V_ import table_T_S_I_V_ + + +class table_T_S_I_D_(table_T_S_I_V_): + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_J_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_J_.py new file mode 100644 index 0000000000000000000000000000000000000000..76f592521da7d12461c9404cf096676f18cc771e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_J_.py @@ -0,0 +1,13 @@ +"""TSI{B,C,D,J,P,S,V} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its table source data. + +TSIJ contains the source text for the ``JSTF`` table. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +from .T_S_I_V_ import table_T_S_I_V_ + + +class table_T_S_I_J_(table_T_S_I_V_): + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_P_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_P_.py new file mode 100644 index 0000000000000000000000000000000000000000..4fbc8f221908f57743f230874134e206d9a4df4f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_P_.py @@ -0,0 +1,13 @@ +"""TSI{B,C,D,J,P,S,V} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its table source data. + +TSIP contains the source text for the ``GPOS`` table. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +from .T_S_I_V_ import table_T_S_I_V_ + + +class table_T_S_I_P_(table_T_S_I_V_): + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_S_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_S_.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ddd8e2d40a2e9fea6d61fc10ea69b12e9b03b7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_S_.py @@ -0,0 +1,13 @@ +"""TSI{B,C,D,J,P,S,V} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its table source data. + +TSIS contains the source text for the ``GSUB`` table. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +from .T_S_I_V_ import table_T_S_I_V_ + + +class table_T_S_I_S_(table_T_S_I_V_): + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_V_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_V_.py new file mode 100644 index 0000000000000000000000000000000000000000..bf5679777e30740bc5a89a64b3929188e0a9a807 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I_V_.py @@ -0,0 +1,26 @@ +"""TSI{B,C,D,J,P,S,V} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its table source data. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +from fontTools.misc.textTools import strjoin, tobytes, tostr +from . import asciiTable + + +class table_T_S_I_V_(asciiTable.asciiTable): + def toXML(self, writer, ttFont): + data = tostr(self.data) + # removing null bytes. XXX needed?? + data = data.split("\0") + data = strjoin(data) + writer.begintag("source") + writer.newline() + writer.write_noindent(data.replace("\r", "\n")) + writer.newline() + writer.endtag("source") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + lines = strjoin(content).split("\n") + self.data = tobytes("\r".join(lines[1:-1])) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__0.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__0.py new file mode 100644 index 0000000000000000000000000000000000000000..d60e783c60873c85487463f151dc25f061cde97f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__0.py @@ -0,0 +1,70 @@ +"""TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its hinting source data. + +TSI0 is the index table containing the lengths and offsets for the glyph +programs and 'extra' programs ('fpgm', 'prep', and 'cvt') that are contained +in the TSI1 table. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +import logging +import struct + +from . import DefaultTable + +log = logging.getLogger(__name__) + +tsi0Format = ">HHL" + + +def fixlongs(glyphID, textLength, textOffset): + return int(glyphID), int(textLength), textOffset + + +class table_T_S_I__0(DefaultTable.DefaultTable): + dependencies = ["TSI1"] + + def decompile(self, data, ttFont): + numGlyphs = ttFont["maxp"].numGlyphs + indices = [] + size = struct.calcsize(tsi0Format) + numEntries = len(data) // size + if numEntries != numGlyphs + 5: + diff = numEntries - numGlyphs - 5 + log.warning( + "Number of glyphPrograms differs from the number of glyphs in the font " + f"by {abs(diff)} ({numEntries - 5} programs vs. {numGlyphs} glyphs)." + ) + for _ in range(numEntries): + glyphID, textLength, textOffset = fixlongs( + *struct.unpack(tsi0Format, data[:size]) + ) + indices.append((glyphID, textLength, textOffset)) + data = data[size:] + assert len(data) == 0 + assert indices[-5] == (0xFFFE, 0, 0xABFC1F34), "bad magic number" + self.indices = indices[:-5] + self.extra_indices = indices[-4:] + + def compile(self, ttFont): + if not hasattr(self, "indices"): + # We have no corresponding table (TSI1 or TSI3); let's return + # no data, which effectively means "ignore us". + return b"" + data = b"" + for index, textLength, textOffset in self.indices: + data = data + struct.pack(tsi0Format, index, textLength, textOffset) + data = data + struct.pack(tsi0Format, 0xFFFE, 0, 0xABFC1F34) + for index, textLength, textOffset in self.extra_indices: + data = data + struct.pack(tsi0Format, index, textLength, textOffset) + return data + + def set(self, indices, extra_indices): + # gets called by 'TSI1' or 'TSI3' + self.indices = indices + self.extra_indices = extra_indices + + def toXML(self, writer, ttFont): + writer.comment("This table will be calculated by the compiler") + writer.newline() diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__1.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__1.py new file mode 100644 index 0000000000000000000000000000000000000000..6cdce17faaf11652e1b21cb17460f232e417bd16 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__1.py @@ -0,0 +1,163 @@ +"""TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its hinting source data. + +TSI1 contains the text of the glyph programs in the form of low-level assembly +code, as well as the 'extra' programs 'fpgm', 'ppgm' (i.e. 'prep'), and 'cvt'. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +from . import DefaultTable +from fontTools.misc.loggingTools import LogMixin +from fontTools.misc.textTools import strjoin, tobytes, tostr + + +class table_T_S_I__1(LogMixin, DefaultTable.DefaultTable): + extras = {0xFFFA: "ppgm", 0xFFFB: "cvt", 0xFFFC: "reserved", 0xFFFD: "fpgm"} + + indextable = "TSI0" + + def decompile(self, data, ttFont): + totalLength = len(data) + indextable = ttFont[self.indextable] + for indices, isExtra in zip( + (indextable.indices, indextable.extra_indices), (False, True) + ): + programs = {} + for i, (glyphID, textLength, textOffset) in enumerate(indices): + if isExtra: + name = self.extras[glyphID] + else: + name = ttFont.getGlyphName(glyphID) + if textOffset > totalLength: + self.log.warning("textOffset > totalLength; %r skipped" % name) + continue + if textLength < 0x8000: + # If the length stored in the record is less than 32768, then use + # that as the length of the record. + pass + elif textLength == 0x8000: + # If the length is 32768, compute the actual length as follows: + isLast = i == (len(indices) - 1) + if isLast: + if isExtra: + # For the last "extra" record (the very last record of the + # table), the length is the difference between the total + # length of the TSI1 table and the textOffset of the final + # record. + nextTextOffset = totalLength + else: + # For the last "normal" record (the last record just prior + # to the record containing the "magic number"), the length + # is the difference between the textOffset of the record + # following the "magic number" (0xFFFE) record (i.e. the + # first "extra" record), and the textOffset of the last + # "normal" record. + nextTextOffset = indextable.extra_indices[0][2] + else: + # For all other records with a length of 0x8000, the length is + # the difference between the textOffset of the record in + # question and the textOffset of the next record. + nextTextOffset = indices[i + 1][2] + assert nextTextOffset >= textOffset, "entries not sorted by offset" + if nextTextOffset > totalLength: + self.log.warning( + "nextTextOffset > totalLength; %r truncated" % name + ) + nextTextOffset = totalLength + textLength = nextTextOffset - textOffset + else: + from fontTools import ttLib + + raise ttLib.TTLibError( + "%r textLength (%d) must not be > 32768" % (name, textLength) + ) + text = data[textOffset : textOffset + textLength] + assert len(text) == textLength + text = tostr(text, encoding="utf-8") + if text: + programs[name] = text + if isExtra: + self.extraPrograms = programs + else: + self.glyphPrograms = programs + + def compile(self, ttFont): + if not hasattr(self, "glyphPrograms"): + self.glyphPrograms = {} + self.extraPrograms = {} + data = b"" + indextable = ttFont[self.indextable] + glyphNames = ttFont.getGlyphOrder() + + indices = [] + for i, name in enumerate(glyphNames): + if len(data) % 2: + data = ( + data + b"\015" + ) # align on 2-byte boundaries, fill with return chars. Yum. + if name in self.glyphPrograms: + text = tobytes(self.glyphPrograms[name], encoding="utf-8") + else: + text = b"" + textLength = len(text) + if textLength >= 0x8000: + textLength = 0x8000 + indices.append((i, textLength, len(data))) + data = data + text + + extra_indices = [] + for code, name in sorted(self.extras.items()): + if len(data) % 2: + data = ( + data + b"\015" + ) # align on 2-byte boundaries, fill with return chars. + if name in self.extraPrograms: + text = tobytes(self.extraPrograms[name], encoding="utf-8") + else: + text = b"" + textLength = len(text) + if textLength >= 0x8000: + textLength = 0x8000 + extra_indices.append((code, textLength, len(data))) + data = data + text + indextable.set(indices, extra_indices) + return data + + def toXML(self, writer, ttFont): + names = sorted(self.glyphPrograms.keys()) + writer.newline() + for name in names: + text = self.glyphPrograms[name] + if not text: + continue + writer.begintag("glyphProgram", name=name) + writer.newline() + writer.write_noindent(text.replace("\r", "\n")) + writer.newline() + writer.endtag("glyphProgram") + writer.newline() + writer.newline() + extra_names = sorted(self.extraPrograms.keys()) + for name in extra_names: + text = self.extraPrograms[name] + if not text: + continue + writer.begintag("extraProgram", name=name) + writer.newline() + writer.write_noindent(text.replace("\r", "\n")) + writer.newline() + writer.endtag("extraProgram") + writer.newline() + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if not hasattr(self, "glyphPrograms"): + self.glyphPrograms = {} + self.extraPrograms = {} + lines = strjoin(content).replace("\r", "\n").split("\n") + text = "\r".join(lines[1:-1]) + if name == "glyphProgram": + self.glyphPrograms[attrs["name"]] = text + elif name == "extraProgram": + self.extraPrograms[attrs["name"]] = text diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__2.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__2.py new file mode 100644 index 0000000000000000000000000000000000000000..78077bac8dec39add93ce7e2a4a8a95ecd82b406 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__2.py @@ -0,0 +1,17 @@ +"""TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its hinting source data. + +TSI2 is the index table containing the lengths and offsets for the glyph +programs that are contained in the TSI3 table. It uses the same format as +the TSI0 table. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +from fontTools import ttLib + +superclass = ttLib.getTableClass("TSI0") + + +class table_T_S_I__2(superclass): + dependencies = ["TSI3"] diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__3.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__3.py new file mode 100644 index 0000000000000000000000000000000000000000..553cb1d44635bc19585a70d82791db49a383fff2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__3.py @@ -0,0 +1,22 @@ +"""TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its hinting source data. + +TSI3 contains the text of the glyph programs in the form of 'VTTTalk' code. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +from fontTools import ttLib + +superclass = ttLib.getTableClass("TSI1") + + +class table_T_S_I__3(superclass): + extras = { + 0xFFFA: "reserved0", + 0xFFFB: "reserved1", + 0xFFFC: "reserved2", + 0xFFFD: "reserved3", + } + + indextable = "TSI2" diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__5.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__5.py new file mode 100644 index 0000000000000000000000000000000000000000..8aa382e43ca0e4bb33994d2e093459a09ba12a9b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_S_I__5.py @@ -0,0 +1,60 @@ +"""TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT) +tool to store its hinting source data. + +TSI5 contains the VTT character groups. + +See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables +""" + +import array +import logging +import sys + +from fontTools.misc.textTools import safeEval + +from . import DefaultTable + +log = logging.getLogger(__name__) + + +class table_T_S_I__5(DefaultTable.DefaultTable): + def decompile(self, data, ttFont): + numGlyphs = ttFont["maxp"].numGlyphs + a = array.array("H") + a.frombytes(data) + if sys.byteorder != "big": + a.byteswap() + self.glyphGrouping = {} + numEntries = len(data) // 2 + if numEntries != numGlyphs: + diff = numEntries - numGlyphs + log.warning( + "Number of entries differs from the number of glyphs in the font " + f"by {abs(diff)} ({numEntries} entries vs. {numGlyphs} glyphs)." + ) + for i in range(numEntries): + self.glyphGrouping[ttFont.getGlyphName(i)] = a[i] + + def compile(self, ttFont): + glyphNames = ttFont.getGlyphOrder() + a = array.array("H") + for glyphName in glyphNames: + a.append(self.glyphGrouping.get(glyphName, 0)) + if sys.byteorder != "big": + a.byteswap() + return a.tobytes() + + def toXML(self, writer, ttFont): + names = sorted(self.glyphGrouping.keys()) + for glyphName in names: + writer.simpletag( + "glyphgroup", name=glyphName, value=self.glyphGrouping[glyphName] + ) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if not hasattr(self, "glyphGrouping"): + self.glyphGrouping = {} + if name != "glyphgroup": + return + self.glyphGrouping[attrs["name"]] = safeEval(attrs["value"]) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_T_F_A_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_T_F_A_.py new file mode 100644 index 0000000000000000000000000000000000000000..4b6b06871a91d9401bcf9fbd99aeb3c30ca0705f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/T_T_F_A_.py @@ -0,0 +1,14 @@ +from . import asciiTable + + +class table_T_T_F_A_(asciiTable.asciiTable): + """ttfautohint parameters table + + The ``TTFA`` table is used by the free-software `ttfautohint` program + to record the parameters that `ttfautohint` was called with when it + was used to auto-hint the font. + + See also http://freetype.org/ttfautohint/doc/ttfautohint.html#miscellaneous-1 + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/TupleVariation.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/TupleVariation.py new file mode 100644 index 0000000000000000000000000000000000000000..9a3c2bdeed5e745cd1f014e7287771272febf7d6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/TupleVariation.py @@ -0,0 +1,885 @@ +from fontTools.misc.fixedTools import ( + fixedToFloat as fi2fl, + floatToFixed as fl2fi, + floatToFixedToStr as fl2str, + strToFixedToFloat as str2fl, + otRound, +) +from fontTools.misc.textTools import safeEval +import array +from collections import Counter, defaultdict +import logging +import struct +import sys +import warnings + +# https://www.microsoft.com/typography/otspec/otvarcommonformats.htm + +EMBEDDED_PEAK_TUPLE = 0x8000 +INTERMEDIATE_REGION = 0x4000 +PRIVATE_POINT_NUMBERS = 0x2000 + +DELTAS_ARE_ZERO = 0x80 +DELTAS_ARE_WORDS = 0x40 +DELTAS_ARE_LONGS = 0xC0 +DELTAS_SIZE_MASK = 0xC0 +DELTA_RUN_COUNT_MASK = 0x3F + +POINTS_ARE_WORDS = 0x80 +POINT_RUN_COUNT_MASK = 0x7F + +TUPLES_SHARE_POINT_NUMBERS = 0x8000 +TUPLE_COUNT_MASK = 0x0FFF +TUPLE_INDEX_MASK = 0x0FFF + +log = logging.getLogger(__name__) + + +class TupleVariation(object): + def __init__(self, axes, coordinates): + self.axes = axes.copy() + self.coordinates = list(coordinates) + + def __repr__(self): + axes = ",".join( + sorted(["%s=%s" % (name, value) for (name, value) in self.axes.items()]) + ) + return "<TupleVariation %s %s>" % (axes, self.coordinates) + + def __eq__(self, other): + return self.coordinates == other.coordinates and self.axes == other.axes + + def getUsedPoints(self): + # Empty set means "all points used". + if None not in self.coordinates: + return frozenset() + used = frozenset([i for i, p in enumerate(self.coordinates) if p is not None]) + # Return None if no points used. + return used if used else None + + def hasImpact(self): + """Returns True if this TupleVariation has any visible impact. + + If the result is False, the TupleVariation can be omitted from the font + without making any visible difference. + """ + return any(c is not None for c in self.coordinates) + + def toXML(self, writer, axisTags): + writer.begintag("tuple") + writer.newline() + for axis in axisTags: + value = self.axes.get(axis) + if value is not None: + minValue, value, maxValue = value + defaultMinValue = min(value, 0.0) # -0.3 --> -0.3; 0.7 --> 0.0 + defaultMaxValue = max(value, 0.0) # -0.3 --> 0.0; 0.7 --> 0.7 + if minValue == defaultMinValue and maxValue == defaultMaxValue: + writer.simpletag("coord", axis=axis, value=fl2str(value, 14)) + else: + attrs = [ + ("axis", axis), + ("min", fl2str(minValue, 14)), + ("value", fl2str(value, 14)), + ("max", fl2str(maxValue, 14)), + ] + writer.simpletag("coord", attrs) + writer.newline() + wrote_any_deltas = False + for i, delta in enumerate(self.coordinates): + if type(delta) == tuple and len(delta) == 2: + writer.simpletag("delta", pt=i, x=delta[0], y=delta[1]) + writer.newline() + wrote_any_deltas = True + elif type(delta) == int: + writer.simpletag("delta", cvt=i, value=delta) + writer.newline() + wrote_any_deltas = True + elif delta is not None: + log.error("bad delta format") + writer.comment("bad delta #%d" % i) + writer.newline() + wrote_any_deltas = True + if not wrote_any_deltas: + writer.comment("no deltas") + writer.newline() + writer.endtag("tuple") + writer.newline() + + def fromXML(self, name, attrs, _content): + if name == "coord": + axis = attrs["axis"] + value = str2fl(attrs["value"], 14) + defaultMinValue = min(value, 0.0) # -0.3 --> -0.3; 0.7 --> 0.0 + defaultMaxValue = max(value, 0.0) # -0.3 --> 0.0; 0.7 --> 0.7 + minValue = str2fl(attrs.get("min", defaultMinValue), 14) + maxValue = str2fl(attrs.get("max", defaultMaxValue), 14) + self.axes[axis] = (minValue, value, maxValue) + elif name == "delta": + if "pt" in attrs: + point = safeEval(attrs["pt"]) + x = safeEval(attrs["x"]) + y = safeEval(attrs["y"]) + self.coordinates[point] = (x, y) + elif "cvt" in attrs: + cvt = safeEval(attrs["cvt"]) + value = safeEval(attrs["value"]) + self.coordinates[cvt] = value + else: + log.warning("bad delta format: %s" % ", ".join(sorted(attrs.keys()))) + + def compile( + self, axisTags, sharedCoordIndices={}, pointData=None, *, optimizeSize=True + ): + assert set(self.axes.keys()) <= set(axisTags), ( + "Unknown axis tag found.", + self.axes.keys(), + axisTags, + ) + + tupleData = [] + auxData = [] + + if pointData is None: + usedPoints = self.getUsedPoints() + if usedPoints is None: # Nothing to encode + return b"", b"" + pointData = self.compilePoints(usedPoints) + + coord = self.compileCoord(axisTags) + flags = sharedCoordIndices.get(coord) + if flags is None: + flags = EMBEDDED_PEAK_TUPLE + tupleData.append(coord) + + intermediateCoord = self.compileIntermediateCoord(axisTags) + if intermediateCoord is not None: + flags |= INTERMEDIATE_REGION + tupleData.append(intermediateCoord) + + # pointData of b'' implies "use shared points". + if pointData: + flags |= PRIVATE_POINT_NUMBERS + auxData.append(pointData) + + auxData.append(self.compileDeltas(optimizeSize=optimizeSize)) + auxData = b"".join(auxData) + + tupleData.insert(0, struct.pack(">HH", len(auxData), flags)) + return b"".join(tupleData), auxData + + def compileCoord(self, axisTags): + result = [] + axes = self.axes + for axis in axisTags: + triple = axes.get(axis) + if triple is None: + result.append(b"\0\0") + else: + result.append(struct.pack(">h", fl2fi(triple[1], 14))) + return b"".join(result) + + def compileIntermediateCoord(self, axisTags): + needed = False + for axis in axisTags: + minValue, value, maxValue = self.axes.get(axis, (0.0, 0.0, 0.0)) + defaultMinValue = min(value, 0.0) # -0.3 --> -0.3; 0.7 --> 0.0 + defaultMaxValue = max(value, 0.0) # -0.3 --> 0.0; 0.7 --> 0.7 + if (minValue != defaultMinValue) or (maxValue != defaultMaxValue): + needed = True + break + if not needed: + return None + minCoords = [] + maxCoords = [] + for axis in axisTags: + minValue, value, maxValue = self.axes.get(axis, (0.0, 0.0, 0.0)) + minCoords.append(struct.pack(">h", fl2fi(minValue, 14))) + maxCoords.append(struct.pack(">h", fl2fi(maxValue, 14))) + return b"".join(minCoords + maxCoords) + + @staticmethod + def decompileCoord_(axisTags, data, offset): + coord = {} + pos = offset + for axis in axisTags: + coord[axis] = fi2fl(struct.unpack(">h", data[pos : pos + 2])[0], 14) + pos += 2 + return coord, pos + + @staticmethod + def compilePoints(points): + # If the set consists of all points in the glyph, it gets encoded with + # a special encoding: a single zero byte. + # + # To use this optimization, points passed in must be empty set. + # The following two lines are not strictly necessary as the main code + # below would emit the same. But this is most common and faster. + if not points: + return b"\0" + + # In the 'gvar' table, the packing of point numbers is a little surprising. + # It consists of multiple runs, each being a delta-encoded list of integers. + # For example, the point set {17, 18, 19, 20, 21, 22, 23} gets encoded as + # [6, 17, 1, 1, 1, 1, 1, 1]. The first value (6) is the run length minus 1. + # There are two types of runs, with values being either 8 or 16 bit unsigned + # integers. + points = list(points) + points.sort() + numPoints = len(points) + + result = bytearray() + # The binary representation starts with the total number of points in the set, + # encoded into one or two bytes depending on the value. + if numPoints < 0x80: + result.append(numPoints) + else: + result.append((numPoints >> 8) | 0x80) + result.append(numPoints & 0xFF) + + MAX_RUN_LENGTH = 127 + pos = 0 + lastValue = 0 + while pos < numPoints: + runLength = 0 + + headerPos = len(result) + result.append(0) + + useByteEncoding = None + while pos < numPoints and runLength <= MAX_RUN_LENGTH: + curValue = points[pos] + delta = curValue - lastValue + if useByteEncoding is None: + useByteEncoding = 0 <= delta <= 0xFF + if useByteEncoding and (delta > 0xFF or delta < 0): + # we need to start a new run (which will not use byte encoding) + break + # TODO This never switches back to a byte-encoding from a short-encoding. + # That's suboptimal. + if useByteEncoding: + result.append(delta) + else: + result.append(delta >> 8) + result.append(delta & 0xFF) + lastValue = curValue + pos += 1 + runLength += 1 + if useByteEncoding: + result[headerPos] = runLength - 1 + else: + result[headerPos] = (runLength - 1) | POINTS_ARE_WORDS + + return result + + @staticmethod + def decompilePoints_(numPoints, data, offset, tableTag): + """(numPoints, data, offset, tableTag) --> ([point1, point2, ...], newOffset)""" + assert tableTag in ("cvar", "gvar") + pos = offset + numPointsInData = data[pos] + pos += 1 + if (numPointsInData & POINTS_ARE_WORDS) != 0: + numPointsInData = (numPointsInData & POINT_RUN_COUNT_MASK) << 8 | data[pos] + pos += 1 + if numPointsInData == 0: + return (range(numPoints), pos) + + result = [] + while len(result) < numPointsInData: + runHeader = data[pos] + pos += 1 + numPointsInRun = (runHeader & POINT_RUN_COUNT_MASK) + 1 + point = 0 + if (runHeader & POINTS_ARE_WORDS) != 0: + points = array.array("H") + pointsSize = numPointsInRun * 2 + else: + points = array.array("B") + pointsSize = numPointsInRun + points.frombytes(data[pos : pos + pointsSize]) + if sys.byteorder != "big": + points.byteswap() + + assert len(points) == numPointsInRun + pos += pointsSize + + result.extend(points) + + # Convert relative to absolute + absolute = [] + current = 0 + for delta in result: + current += delta + absolute.append(current) + result = absolute + del absolute + + badPoints = {str(p) for p in result if p < 0 or p >= numPoints} + if badPoints: + log.warning( + "point %s out of range in '%s' table" + % (",".join(sorted(badPoints)), tableTag) + ) + return (result, pos) + + def compileDeltas(self, optimizeSize=True): + deltaX = [] + deltaY = [] + if self.getCoordWidth() == 2: + for c in self.coordinates: + if c is None: + continue + deltaX.append(c[0]) + deltaY.append(c[1]) + else: + for c in self.coordinates: + if c is None: + continue + deltaX.append(c) + bytearr = bytearray() + self.compileDeltaValues_(deltaX, bytearr, optimizeSize=optimizeSize) + self.compileDeltaValues_(deltaY, bytearr, optimizeSize=optimizeSize) + return bytearr + + @staticmethod + def compileDeltaValues_(deltas, bytearr=None, *, optimizeSize=True): + """[value1, value2, value3, ...] --> bytearray + + Emits a sequence of runs. Each run starts with a + byte-sized header whose 6 least significant bits + (header & 0x3F) indicate how many values are encoded + in this run. The stored length is the actual length + minus one; run lengths are thus in the range [1..64]. + If the header byte has its most significant bit (0x80) + set, all values in this run are zero, and no data + follows. Otherwise, the header byte is followed by + ((header & 0x3F) + 1) signed values. If (header & + 0x40) is clear, the delta values are stored as signed + bytes; if (header & 0x40) is set, the delta values are + signed 16-bit integers. + """ # Explaining the format because the 'gvar' spec is hard to understand. + if bytearr is None: + bytearr = bytearray() + + pos = 0 + numDeltas = len(deltas) + + if optimizeSize: + while pos < numDeltas: + value = deltas[pos] + if value == 0: + pos = TupleVariation.encodeDeltaRunAsZeroes_(deltas, pos, bytearr) + elif -128 <= value <= 127: + pos = TupleVariation.encodeDeltaRunAsBytes_(deltas, pos, bytearr) + elif -32768 <= value <= 32767: + pos = TupleVariation.encodeDeltaRunAsWords_(deltas, pos, bytearr) + else: + pos = TupleVariation.encodeDeltaRunAsLongs_(deltas, pos, bytearr) + else: + minVal, maxVal = min(deltas), max(deltas) + if minVal == 0 == maxVal: + pos = TupleVariation.encodeDeltaRunAsZeroes_(deltas, pos, bytearr) + elif -128 <= minVal <= maxVal <= 127: + pos = TupleVariation.encodeDeltaRunAsBytes_( + deltas, pos, bytearr, optimizeSize=False + ) + elif -32768 <= minVal <= maxVal <= 32767: + pos = TupleVariation.encodeDeltaRunAsWords_( + deltas, pos, bytearr, optimizeSize=False + ) + else: + pos = TupleVariation.encodeDeltaRunAsLongs_( + deltas, pos, bytearr, optimizeSize=False + ) + + assert pos == numDeltas, (pos, numDeltas) + + return bytearr + + @staticmethod + def encodeDeltaRunAsZeroes_(deltas, offset, bytearr): + pos = offset + numDeltas = len(deltas) + while pos < numDeltas and deltas[pos] == 0: + pos += 1 + runLength = pos - offset + while runLength >= 64: + bytearr.append(DELTAS_ARE_ZERO | 63) + runLength -= 64 + if runLength: + bytearr.append(DELTAS_ARE_ZERO | (runLength - 1)) + return pos + + @staticmethod + def encodeDeltaRunAsBytes_(deltas, offset, bytearr, optimizeSize=True): + pos = offset + numDeltas = len(deltas) + while pos < numDeltas: + value = deltas[pos] + if not (-128 <= value <= 127): + break + # Within a byte-encoded run of deltas, a single zero + # is best stored literally as 0x00 value. However, + # if are two or more zeroes in a sequence, it is + # better to start a new run. For example, the sequence + # of deltas [15, 15, 0, 15, 15] becomes 6 bytes + # (04 0F 0F 00 0F 0F) when storing the zero value + # literally, but 7 bytes (01 0F 0F 80 01 0F 0F) + # when starting a new run. + if ( + optimizeSize + and value == 0 + and pos + 1 < numDeltas + and deltas[pos + 1] == 0 + ): + break + pos += 1 + runLength = pos - offset + while runLength >= 64: + bytearr.append(63) + bytearr.extend(array.array("b", deltas[offset : offset + 64])) + offset += 64 + runLength -= 64 + if runLength: + bytearr.append(runLength - 1) + bytearr.extend(array.array("b", deltas[offset:pos])) + return pos + + @staticmethod + def encodeDeltaRunAsWords_(deltas, offset, bytearr, optimizeSize=True): + pos = offset + numDeltas = len(deltas) + while pos < numDeltas: + value = deltas[pos] + + # Within a word-encoded run of deltas, it is easiest + # to start a new run (with a different encoding) + # whenever we encounter a zero value. For example, + # the sequence [0x6666, 0, 0x7777] needs 7 bytes when + # storing the zero literally (42 66 66 00 00 77 77), + # and equally 7 bytes when starting a new run + # (40 66 66 80 40 77 77). + if optimizeSize and value == 0: + break + + # Within a word-encoded run of deltas, a single value + # in the range (-128..127) should be encoded literally + # because it is more compact. For example, the sequence + # [0x6666, 2, 0x7777] becomes 7 bytes when storing + # the value literally (42 66 66 00 02 77 77), but 8 bytes + # when starting a new run (40 66 66 00 02 40 77 77). + if ( + optimizeSize + and (-128 <= value <= 127) + and pos + 1 < numDeltas + and (-128 <= deltas[pos + 1] <= 127) + ): + break + + if not (-32768 <= value <= 32767): + break + + pos += 1 + runLength = pos - offset + while runLength >= 64: + bytearr.append(DELTAS_ARE_WORDS | 63) + a = array.array("h", deltas[offset : offset + 64]) + if sys.byteorder != "big": + a.byteswap() + bytearr.extend(a) + offset += 64 + runLength -= 64 + if runLength: + bytearr.append(DELTAS_ARE_WORDS | (runLength - 1)) + a = array.array("h", deltas[offset:pos]) + if sys.byteorder != "big": + a.byteswap() + bytearr.extend(a) + return pos + + @staticmethod + def encodeDeltaRunAsLongs_(deltas, offset, bytearr, optimizeSize=True): + pos = offset + numDeltas = len(deltas) + while pos < numDeltas: + value = deltas[pos] + if optimizeSize and -32768 <= value <= 32767: + break + pos += 1 + runLength = pos - offset + while runLength >= 64: + bytearr.append(DELTAS_ARE_LONGS | 63) + a = array.array("i", deltas[offset : offset + 64]) + if sys.byteorder != "big": + a.byteswap() + bytearr.extend(a) + offset += 64 + runLength -= 64 + if runLength: + bytearr.append(DELTAS_ARE_LONGS | (runLength - 1)) + a = array.array("i", deltas[offset:pos]) + if sys.byteorder != "big": + a.byteswap() + bytearr.extend(a) + return pos + + @staticmethod + def decompileDeltas_(numDeltas, data, offset=0): + """(numDeltas, data, offset) --> ([delta, delta, ...], newOffset)""" + result = [] + pos = offset + while len(result) < numDeltas if numDeltas is not None else pos < len(data): + runHeader = data[pos] + pos += 1 + numDeltasInRun = (runHeader & DELTA_RUN_COUNT_MASK) + 1 + if (runHeader & DELTAS_SIZE_MASK) == DELTAS_ARE_ZERO: + result.extend([0] * numDeltasInRun) + else: + if (runHeader & DELTAS_SIZE_MASK) == DELTAS_ARE_LONGS: + deltas = array.array("i") + deltasSize = numDeltasInRun * 4 + elif (runHeader & DELTAS_SIZE_MASK) == DELTAS_ARE_WORDS: + deltas = array.array("h") + deltasSize = numDeltasInRun * 2 + else: + deltas = array.array("b") + deltasSize = numDeltasInRun + deltas.frombytes(data[pos : pos + deltasSize]) + if sys.byteorder != "big": + deltas.byteswap() + assert len(deltas) == numDeltasInRun, (len(deltas), numDeltasInRun) + pos += deltasSize + result.extend(deltas) + assert numDeltas is None or len(result) == numDeltas + return (result, pos) + + @staticmethod + def getTupleSize_(flags, axisCount): + size = 4 + if (flags & EMBEDDED_PEAK_TUPLE) != 0: + size += axisCount * 2 + if (flags & INTERMEDIATE_REGION) != 0: + size += axisCount * 4 + return size + + def getCoordWidth(self): + """Return 2 if coordinates are (x, y) as in gvar, 1 if single values + as in cvar, or 0 if empty. + """ + firstDelta = next((c for c in self.coordinates if c is not None), None) + if firstDelta is None: + return 0 # empty or has no impact + if type(firstDelta) in (int, float): + return 1 + if type(firstDelta) is tuple and len(firstDelta) == 2: + return 2 + raise TypeError( + "invalid type of delta; expected (int or float) number, or " + "Tuple[number, number]: %r" % firstDelta + ) + + def scaleDeltas(self, scalar): + if scalar == 1.0: + return # no change + coordWidth = self.getCoordWidth() + self.coordinates = [ + ( + None + if d is None + else d * scalar if coordWidth == 1 else (d[0] * scalar, d[1] * scalar) + ) + for d in self.coordinates + ] + + def roundDeltas(self): + coordWidth = self.getCoordWidth() + self.coordinates = [ + ( + None + if d is None + else otRound(d) if coordWidth == 1 else (otRound(d[0]), otRound(d[1])) + ) + for d in self.coordinates + ] + + def calcInferredDeltas(self, origCoords, endPts): + from fontTools.varLib.iup import iup_delta + + if self.getCoordWidth() == 1: + raise TypeError("Only 'gvar' TupleVariation can have inferred deltas") + if None in self.coordinates: + if len(self.coordinates) != len(origCoords): + raise ValueError( + "Expected len(origCoords) == %d; found %d" + % (len(self.coordinates), len(origCoords)) + ) + self.coordinates = iup_delta(self.coordinates, origCoords, endPts) + + def optimize(self, origCoords, endPts, tolerance=0.5, isComposite=False): + from fontTools.varLib.iup import iup_delta_optimize + + if isComposite: + warnings.warn( + "The isComposite argument is deprecated and may be removed in a future version", + DeprecationWarning, + ) + + if None in self.coordinates: + return # already optimized + + deltaOpt = iup_delta_optimize( + self.coordinates, origCoords, endPts, tolerance=tolerance + ) + if None in deltaOpt: + # Use "optimized" version only if smaller... + varOpt = TupleVariation(self.axes, deltaOpt) + + # Shouldn't matter that this is different from fvar...? + axisTags = sorted(self.axes.keys()) + tupleData, auxData = self.compile(axisTags) + unoptimizedLength = len(tupleData) + len(auxData) + tupleData, auxData = varOpt.compile(axisTags) + optimizedLength = len(tupleData) + len(auxData) + + if optimizedLength < unoptimizedLength: + self.coordinates = varOpt.coordinates + + def __imul__(self, scalar): + self.scaleDeltas(scalar) + return self + + def __iadd__(self, other): + if not isinstance(other, TupleVariation): + return NotImplemented + deltas1 = self.coordinates + length = len(deltas1) + deltas2 = other.coordinates + if len(deltas2) != length: + raise ValueError("cannot sum TupleVariation deltas with different lengths") + # 'None' values have different meanings in gvar vs cvar TupleVariations: + # within the gvar, when deltas are not provided explicitly for some points, + # they need to be inferred; whereas for the 'cvar' table, if deltas are not + # provided for some CVT values, then no adjustments are made (i.e. None == 0). + # Thus, we cannot sum deltas for gvar TupleVariations if they contain + # inferred inferred deltas (the latter need to be computed first using + # 'calcInferredDeltas' method), but we can treat 'None' values in cvar + # deltas as if they are zeros. + if self.getCoordWidth() == 2: + for i, d2 in zip(range(length), deltas2): + d1 = deltas1[i] + try: + deltas1[i] = (d1[0] + d2[0], d1[1] + d2[1]) + except TypeError: + raise ValueError("cannot sum gvar deltas with inferred points") + else: + for i, d2 in zip(range(length), deltas2): + d1 = deltas1[i] + if d1 is not None and d2 is not None: + deltas1[i] = d1 + d2 + elif d1 is None and d2 is not None: + deltas1[i] = d2 + # elif d2 is None do nothing + return self + + +def decompileSharedTuples(axisTags, sharedTupleCount, data, offset): + result = [] + for _ in range(sharedTupleCount): + t, offset = TupleVariation.decompileCoord_(axisTags, data, offset) + result.append(t) + return result + + +def compileSharedTuples( + axisTags, variations, MAX_NUM_SHARED_COORDS=TUPLE_INDEX_MASK + 1 +): + coordCount = Counter() + for var in variations: + coord = var.compileCoord(axisTags) + coordCount[coord] += 1 + # In python < 3.7, most_common() ordering is non-deterministic + # so apply a sort to make sure the ordering is consistent. + sharedCoords = sorted( + coordCount.most_common(MAX_NUM_SHARED_COORDS), + key=lambda item: (-item[1], item[0]), + ) + return [c[0] for c in sharedCoords if c[1] > 1] + + +def compileTupleVariationStore( + variations, + pointCount, + axisTags, + sharedTupleIndices, + useSharedPoints=True, + *, + optimizeSize=True, +): + # pointCount is actually unused. Keeping for API compat. + del pointCount + newVariations = [] + pointDatas = [] + # Compile all points and figure out sharing if desired + sharedPoints = None + + # Collect, count, and compile point-sets for all variation sets + pointSetCount = defaultdict(int) + for v in variations: + points = v.getUsedPoints() + if points is None: # Empty variations + continue + pointSetCount[points] += 1 + newVariations.append(v) + pointDatas.append(points) + variations = newVariations + del newVariations + + if not variations: + return (0, b"", b"") + + n = len(variations[0].coordinates) + assert all( + len(v.coordinates) == n for v in variations + ), "Variation sets have different sizes" + + compiledPoints = { + pointSet: TupleVariation.compilePoints(pointSet) for pointSet in pointSetCount + } + + tupleVariationCount = len(variations) + tuples = [] + data = [] + + if useSharedPoints: + # Find point-set which saves most bytes. + def key(pn): + pointSet = pn[0] + count = pn[1] + return len(compiledPoints[pointSet]) * (count - 1) + + sharedPoints = max(pointSetCount.items(), key=key)[0] + + data.append(compiledPoints[sharedPoints]) + tupleVariationCount |= TUPLES_SHARE_POINT_NUMBERS + + # b'' implies "use shared points" + pointDatas = [ + compiledPoints[points] if points != sharedPoints else b"" + for points in pointDatas + ] + + for v, p in zip(variations, pointDatas): + thisTuple, thisData = v.compile( + axisTags, sharedTupleIndices, pointData=p, optimizeSize=optimizeSize + ) + + tuples.append(thisTuple) + data.append(thisData) + + tuples = b"".join(tuples) + data = b"".join(data) + return tupleVariationCount, tuples, data + + +def decompileTupleVariationStore( + tableTag, + axisTags, + tupleVariationCount, + pointCount, + sharedTuples, + data, + pos, + dataPos, +): + numAxes = len(axisTags) + result = [] + if (tupleVariationCount & TUPLES_SHARE_POINT_NUMBERS) != 0: + sharedPoints, dataPos = TupleVariation.decompilePoints_( + pointCount, data, dataPos, tableTag + ) + else: + sharedPoints = [] + for _ in range(tupleVariationCount & TUPLE_COUNT_MASK): + dataSize, flags = struct.unpack(">HH", data[pos : pos + 4]) + tupleSize = TupleVariation.getTupleSize_(flags, numAxes) + tupleData = data[pos : pos + tupleSize] + pointDeltaData = data[dataPos : dataPos + dataSize] + result.append( + decompileTupleVariation_( + pointCount, + sharedTuples, + sharedPoints, + tableTag, + axisTags, + tupleData, + pointDeltaData, + ) + ) + pos += tupleSize + dataPos += dataSize + return result + + +def decompileTupleVariation_( + pointCount, sharedTuples, sharedPoints, tableTag, axisTags, data, tupleData +): + assert tableTag in ("cvar", "gvar"), tableTag + flags = struct.unpack(">H", data[2:4])[0] + pos = 4 + if (flags & EMBEDDED_PEAK_TUPLE) == 0: + peak = sharedTuples[flags & TUPLE_INDEX_MASK] + else: + peak, pos = TupleVariation.decompileCoord_(axisTags, data, pos) + if (flags & INTERMEDIATE_REGION) != 0: + start, pos = TupleVariation.decompileCoord_(axisTags, data, pos) + end, pos = TupleVariation.decompileCoord_(axisTags, data, pos) + else: + start, end = inferRegion_(peak) + axes = {} + for axis in axisTags: + region = start[axis], peak[axis], end[axis] + if region != (0.0, 0.0, 0.0): + axes[axis] = region + pos = 0 + if (flags & PRIVATE_POINT_NUMBERS) != 0: + points, pos = TupleVariation.decompilePoints_( + pointCount, tupleData, pos, tableTag + ) + else: + points = sharedPoints + + deltas = [None] * pointCount + + if tableTag == "cvar": + deltas_cvt, pos = TupleVariation.decompileDeltas_(len(points), tupleData, pos) + for p, delta in zip(points, deltas_cvt): + if 0 <= p < pointCount: + deltas[p] = delta + + elif tableTag == "gvar": + deltas_x, pos = TupleVariation.decompileDeltas_(len(points), tupleData, pos) + deltas_y, pos = TupleVariation.decompileDeltas_(len(points), tupleData, pos) + for p, x, y in zip(points, deltas_x, deltas_y): + if 0 <= p < pointCount: + deltas[p] = (x, y) + + return TupleVariation(axes, deltas) + + +def inferRegion_(peak): + """Infer start and end for a (non-intermediate) region + + This helper function computes the applicability region for + variation tuples whose INTERMEDIATE_REGION flag is not set in the + TupleVariationHeader structure. Variation tuples apply only to + certain regions of the variation space; outside that region, the + tuple has no effect. To make the binary encoding more compact, + TupleVariationHeaders can omit the intermediateStartTuple and + intermediateEndTuple fields. + """ + start, end = {}, {} + for axis, value in peak.items(): + start[axis] = min(value, 0.0) # -0.3 --> -0.3; 0.7 --> 0.0 + end[axis] = max(value, 0.0) # -0.3 --> 0.0; 0.7 --> 0.7 + return (start, end) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/V_A_R_C_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/V_A_R_C_.py new file mode 100644 index 0000000000000000000000000000000000000000..afc1497d14ffd4aed6668af4cb0587135e5562f9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/V_A_R_C_.py @@ -0,0 +1,12 @@ +from .otBase import BaseTTXConverter + + +class table_V_A_R_C_(BaseTTXConverter): + """Variable Components table + + The ``VARC`` table contains variation information for composite glyphs. + + See also https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/V_D_M_X_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/V_D_M_X_.py new file mode 100644 index 0000000000000000000000000000000000000000..6f8abc46de903fbc300fc4ee4b803cb47bf03ba0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/V_D_M_X_.py @@ -0,0 +1,249 @@ +from . import DefaultTable +from fontTools.misc import sstruct +from fontTools.misc.textTools import safeEval +import struct + +VDMX_HeaderFmt = """ + > # big endian + version: H # Version number (0 or 1) + numRecs: H # Number of VDMX groups present + numRatios: H # Number of aspect ratio groupings +""" +# the VMDX header is followed by an array of RatRange[numRatios] (i.e. aspect +# ratio ranges); +VDMX_RatRangeFmt = """ + > # big endian + bCharSet: B # Character set + xRatio: B # Value to use for x-Ratio + yStartRatio: B # Starting y-Ratio value + yEndRatio: B # Ending y-Ratio value +""" +# followed by an array of offset[numRatios] from start of VDMX table to the +# VDMX Group for this ratio range (offsets will be re-calculated on compile); +# followed by an array of Group[numRecs] records; +VDMX_GroupFmt = """ + > # big endian + recs: H # Number of height records in this group + startsz: B # Starting yPelHeight + endsz: B # Ending yPelHeight +""" +# followed by an array of vTable[recs] records. +VDMX_vTableFmt = """ + > # big endian + yPelHeight: H # yPelHeight to which values apply + yMax: h # Maximum value (in pels) for this yPelHeight + yMin: h # Minimum value (in pels) for this yPelHeight +""" + + +class table_V_D_M_X_(DefaultTable.DefaultTable): + """Vertical Device Metrics table + + The ``VDMX`` table records changes to the vertical glyph minima + and maxima that result from Truetype instructions. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/vdmx + """ + + def decompile(self, data, ttFont): + pos = 0 # track current position from to start of VDMX table + dummy, data = sstruct.unpack2(VDMX_HeaderFmt, data, self) + pos += sstruct.calcsize(VDMX_HeaderFmt) + self.ratRanges = [] + for i in range(self.numRatios): + ratio, data = sstruct.unpack2(VDMX_RatRangeFmt, data) + pos += sstruct.calcsize(VDMX_RatRangeFmt) + # the mapping between a ratio and a group is defined further below + ratio["groupIndex"] = None + self.ratRanges.append(ratio) + lenOffset = struct.calcsize(">H") + _offsets = [] # temporarily store offsets to groups + for i in range(self.numRatios): + offset = struct.unpack(">H", data[0:lenOffset])[0] + data = data[lenOffset:] + pos += lenOffset + _offsets.append(offset) + self.groups = [] + for groupIndex in range(self.numRecs): + # the offset to this group from beginning of the VDMX table + currOffset = pos + group, data = sstruct.unpack2(VDMX_GroupFmt, data) + # the group lenght and bounding sizes are re-calculated on compile + recs = group.pop("recs") + startsz = group.pop("startsz") + endsz = group.pop("endsz") + pos += sstruct.calcsize(VDMX_GroupFmt) + for j in range(recs): + vTable, data = sstruct.unpack2(VDMX_vTableFmt, data) + vTableLength = sstruct.calcsize(VDMX_vTableFmt) + pos += vTableLength + # group is a dict of (yMax, yMin) tuples keyed by yPelHeight + group[vTable["yPelHeight"]] = (vTable["yMax"], vTable["yMin"]) + # make sure startsz and endsz match the calculated values + minSize = min(group.keys()) + maxSize = max(group.keys()) + assert ( + startsz == minSize + ), "startsz (%s) must equal min yPelHeight (%s): group %d" % ( + group.startsz, + minSize, + groupIndex, + ) + assert ( + endsz == maxSize + ), "endsz (%s) must equal max yPelHeight (%s): group %d" % ( + group.endsz, + maxSize, + groupIndex, + ) + self.groups.append(group) + # match the defined offsets with the current group's offset + for offsetIndex, offsetValue in enumerate(_offsets): + # when numRecs < numRatios there can more than one ratio range + # sharing the same VDMX group + if currOffset == offsetValue: + # map the group with the ratio range thas has the same + # index as the offset to that group (it took me a while..) + self.ratRanges[offsetIndex]["groupIndex"] = groupIndex + # check that all ratio ranges have a group + for i in range(self.numRatios): + ratio = self.ratRanges[i] + if ratio["groupIndex"] is None: + from fontTools import ttLib + + raise ttLib.TTLibError("no group defined for ratRange %d" % i) + + def _getOffsets(self): + """ + Calculate offsets to VDMX_Group records. + For each ratRange return a list of offset values from the beginning of + the VDMX table to a VDMX_Group. + """ + lenHeader = sstruct.calcsize(VDMX_HeaderFmt) + lenRatRange = sstruct.calcsize(VDMX_RatRangeFmt) + lenOffset = struct.calcsize(">H") + lenGroupHeader = sstruct.calcsize(VDMX_GroupFmt) + lenVTable = sstruct.calcsize(VDMX_vTableFmt) + # offset to the first group + pos = lenHeader + self.numRatios * lenRatRange + self.numRatios * lenOffset + groupOffsets = [] + for group in self.groups: + groupOffsets.append(pos) + lenGroup = lenGroupHeader + len(group) * lenVTable + pos += lenGroup # offset to next group + offsets = [] + for ratio in self.ratRanges: + groupIndex = ratio["groupIndex"] + offsets.append(groupOffsets[groupIndex]) + return offsets + + def compile(self, ttFont): + if not (self.version == 0 or self.version == 1): + from fontTools import ttLib + + raise ttLib.TTLibError( + "unknown format for VDMX table: version %s" % self.version + ) + data = sstruct.pack(VDMX_HeaderFmt, self) + for ratio in self.ratRanges: + data += sstruct.pack(VDMX_RatRangeFmt, ratio) + # recalculate offsets to VDMX groups + for offset in self._getOffsets(): + data += struct.pack(">H", offset) + for group in self.groups: + recs = len(group) + startsz = min(group.keys()) + endsz = max(group.keys()) + gHeader = {"recs": recs, "startsz": startsz, "endsz": endsz} + data += sstruct.pack(VDMX_GroupFmt, gHeader) + for yPelHeight, (yMax, yMin) in sorted(group.items()): + vTable = {"yPelHeight": yPelHeight, "yMax": yMax, "yMin": yMin} + data += sstruct.pack(VDMX_vTableFmt, vTable) + return data + + def toXML(self, writer, ttFont): + writer.simpletag("version", value=self.version) + writer.newline() + writer.begintag("ratRanges") + writer.newline() + for ratio in self.ratRanges: + groupIndex = ratio["groupIndex"] + writer.simpletag( + "ratRange", + bCharSet=ratio["bCharSet"], + xRatio=ratio["xRatio"], + yStartRatio=ratio["yStartRatio"], + yEndRatio=ratio["yEndRatio"], + groupIndex=groupIndex, + ) + writer.newline() + writer.endtag("ratRanges") + writer.newline() + writer.begintag("groups") + writer.newline() + for groupIndex in range(self.numRecs): + group = self.groups[groupIndex] + recs = len(group) + startsz = min(group.keys()) + endsz = max(group.keys()) + writer.begintag("group", index=groupIndex) + writer.newline() + writer.comment("recs=%d, startsz=%d, endsz=%d" % (recs, startsz, endsz)) + writer.newline() + for yPelHeight, (yMax, yMin) in sorted(group.items()): + writer.simpletag( + "record", + [("yPelHeight", yPelHeight), ("yMax", yMax), ("yMin", yMin)], + ) + writer.newline() + writer.endtag("group") + writer.newline() + writer.endtag("groups") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "version": + self.version = safeEval(attrs["value"]) + elif name == "ratRanges": + if not hasattr(self, "ratRanges"): + self.ratRanges = [] + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name == "ratRange": + if not hasattr(self, "numRatios"): + self.numRatios = 1 + else: + self.numRatios += 1 + ratio = { + "bCharSet": safeEval(attrs["bCharSet"]), + "xRatio": safeEval(attrs["xRatio"]), + "yStartRatio": safeEval(attrs["yStartRatio"]), + "yEndRatio": safeEval(attrs["yEndRatio"]), + "groupIndex": safeEval(attrs["groupIndex"]), + } + self.ratRanges.append(ratio) + elif name == "groups": + if not hasattr(self, "groups"): + self.groups = [] + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name == "group": + if not hasattr(self, "numRecs"): + self.numRecs = 1 + else: + self.numRecs += 1 + group = {} + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name == "record": + yPelHeight = safeEval(attrs["yPelHeight"]) + yMax = safeEval(attrs["yMax"]) + yMin = safeEval(attrs["yMin"]) + group[yPelHeight] = (yMax, yMin) + self.groups.append(group) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/V_O_R_G_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/V_O_R_G_.py new file mode 100644 index 0000000000000000000000000000000000000000..2c53acba431059f58f86dbb1b89755a03f699f94 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/V_O_R_G_.py @@ -0,0 +1,165 @@ +from fontTools.misc.textTools import bytesjoin, safeEval +from . import DefaultTable +import struct + + +class table_V_O_R_G_(DefaultTable.DefaultTable): + """Vertical Origin table + + The ``VORG`` table contains the vertical origin of each glyph + in a `CFF` or `CFF2` font. + + This table is structured so that you can treat it like a dictionary keyed by glyph name. + + ``ttFont['VORG'][<glyphName>]`` will return the vertical origin for any glyph. + + ``ttFont['VORG'][<glyphName>] = <value>`` will set the vertical origin for any glyph. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/vorg + """ + + def decompile(self, data, ttFont): + self.getGlyphName = ( + ttFont.getGlyphName + ) # for use in get/set item functions, for access by GID + ( + self.majorVersion, + self.minorVersion, + self.defaultVertOriginY, + self.numVertOriginYMetrics, + ) = struct.unpack(">HHhH", data[:8]) + assert ( + self.majorVersion <= 1 + ), "Major version of VORG table is higher than I know how to handle" + data = data[8:] + vids = [] + gids = [] + pos = 0 + for i in range(self.numVertOriginYMetrics): + gid, vOrigin = struct.unpack(">Hh", data[pos : pos + 4]) + pos += 4 + gids.append(gid) + vids.append(vOrigin) + + self.VOriginRecords = vOrig = {} + glyphOrder = ttFont.getGlyphOrder() + try: + names = [glyphOrder[gid] for gid in gids] + except IndexError: + getGlyphName = self.getGlyphName + names = map(getGlyphName, gids) + + for name, vid in zip(names, vids): + vOrig[name] = vid + + def compile(self, ttFont): + vorgs = list(self.VOriginRecords.values()) + names = list(self.VOriginRecords.keys()) + nameMap = ttFont.getReverseGlyphMap() + try: + gids = [nameMap[name] for name in names] + except KeyError: + nameMap = ttFont.getReverseGlyphMap(rebuild=True) + gids = [nameMap[name] for name in names] + vOriginTable = list(zip(gids, vorgs)) + self.numVertOriginYMetrics = len(vorgs) + vOriginTable.sort() # must be in ascending GID order + dataList = [struct.pack(">Hh", rec[0], rec[1]) for rec in vOriginTable] + header = struct.pack( + ">HHhH", + self.majorVersion, + self.minorVersion, + self.defaultVertOriginY, + self.numVertOriginYMetrics, + ) + dataList.insert(0, header) + data = bytesjoin(dataList) + return data + + def toXML(self, writer, ttFont): + writer.simpletag("majorVersion", value=self.majorVersion) + writer.newline() + writer.simpletag("minorVersion", value=self.minorVersion) + writer.newline() + writer.simpletag("defaultVertOriginY", value=self.defaultVertOriginY) + writer.newline() + writer.simpletag("numVertOriginYMetrics", value=self.numVertOriginYMetrics) + writer.newline() + vOriginTable = [] + glyphNames = self.VOriginRecords.keys() + for glyphName in glyphNames: + try: + gid = ttFont.getGlyphID(glyphName) + except: + assert 0, ( + "VORG table contains a glyph name not in ttFont.getGlyphNames(): " + + str(glyphName) + ) + vOriginTable.append([gid, glyphName, self.VOriginRecords[glyphName]]) + vOriginTable.sort() + for entry in vOriginTable: + vOriginRec = VOriginRecord(entry[1], entry[2]) + vOriginRec.toXML(writer, ttFont) + + def fromXML(self, name, attrs, content, ttFont): + if not hasattr(self, "VOriginRecords"): + self.VOriginRecords = {} + self.getGlyphName = ( + ttFont.getGlyphName + ) # for use in get/set item functions, for access by GID + if name == "VOriginRecord": + vOriginRec = VOriginRecord() + for element in content: + if isinstance(element, str): + continue + name, attrs, content = element + vOriginRec.fromXML(name, attrs, content, ttFont) + self.VOriginRecords[vOriginRec.glyphName] = vOriginRec.vOrigin + elif "value" in attrs: + setattr(self, name, safeEval(attrs["value"])) + + def __getitem__(self, glyphSelector): + if isinstance(glyphSelector, int): + # its a gid, convert to glyph name + glyphSelector = self.getGlyphName(glyphSelector) + + if glyphSelector not in self.VOriginRecords: + return self.defaultVertOriginY + + return self.VOriginRecords[glyphSelector] + + def __setitem__(self, glyphSelector, value): + if isinstance(glyphSelector, int): + # its a gid, convert to glyph name + glyphSelector = self.getGlyphName(glyphSelector) + + if value != self.defaultVertOriginY: + self.VOriginRecords[glyphSelector] = value + elif glyphSelector in self.VOriginRecords: + del self.VOriginRecords[glyphSelector] + + def __delitem__(self, glyphSelector): + del self.VOriginRecords[glyphSelector] + + +class VOriginRecord(object): + def __init__(self, name=None, vOrigin=None): + self.glyphName = name + self.vOrigin = vOrigin + + def toXML(self, writer, ttFont): + writer.begintag("VOriginRecord") + writer.newline() + writer.simpletag("glyphName", value=self.glyphName) + writer.newline() + writer.simpletag("vOrigin", value=self.vOrigin) + writer.newline() + writer.endtag("VOriginRecord") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + value = attrs["value"] + if name == "glyphName": + setattr(self, name, value) + else: + setattr(self, name, safeEval(value)) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/V_V_A_R_.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/V_V_A_R_.py new file mode 100644 index 0000000000000000000000000000000000000000..c0c94e348b2c6cdfc856b030477214604c95d7c4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/V_V_A_R_.py @@ -0,0 +1,13 @@ +from .otBase import BaseTTXConverter + + +class table_V_V_A_R_(BaseTTXConverter): + """Vertical Metrics Variations table + + The ``VVAR`` table contains variation data for per-glyph vertical metrics + in a variable font. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/vvar + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__init__.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..59bfbd5dcab3169e3f8f7b78bd02c5033dbd0719 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__init__.py @@ -0,0 +1,101 @@ +# DON'T EDIT! This file is generated by MetaTools/buildTableList.py. +def _moduleFinderHint(): + """Dummy function to let modulefinder know what tables may be + dynamically imported. Generated by MetaTools/buildTableList.py. + + >>> _moduleFinderHint() + """ + from . import B_A_S_E_ + from . import C_B_D_T_ + from . import C_B_L_C_ + from . import C_F_F_ + from . import C_F_F__2 + from . import C_O_L_R_ + from . import C_P_A_L_ + from . import D_S_I_G_ + from . import D__e_b_g + from . import E_B_D_T_ + from . import E_B_L_C_ + from . import E_B_S_C_ + from . import F_F_T_M_ + from . import F__e_a_t + from . import G_D_E_F_ + from . import G_P_O_S_ + from . import G_S_U_B_ + from . import G_V_A_R_ + from . import G__l_a_t + from . import G__l_o_c + from . import H_V_A_R_ + from . import I_F_T_ + from . import I_F_T_X_ + from . import J_S_T_F_ + from . import L_T_S_H_ + from . import M_A_T_H_ + from . import M_V_A_R_ + from . import O_S_2f_2 + from . import S_T_A_T_ + from . import S_V_G_ + from . import S__i_l_f + from . import S__i_l_l + from . import T_S_I_B_ + from . import T_S_I_C_ + from . import T_S_I_D_ + from . import T_S_I_J_ + from . import T_S_I_P_ + from . import T_S_I_S_ + from . import T_S_I_V_ + from . import T_S_I__0 + from . import T_S_I__1 + from . import T_S_I__2 + from . import T_S_I__3 + from . import T_S_I__5 + from . import T_T_F_A_ + from . import V_A_R_C_ + from . import V_D_M_X_ + from . import V_O_R_G_ + from . import V_V_A_R_ + from . import _a_n_k_r + from . import _a_v_a_r + from . import _b_d_a_t + from . import _b_g_c_l + from . import _b_h_e_d + from . import _b_l_o_c + from . import _b_s_l_n + from . import _c_i_d_g + from . import _c_m_a_p + from . import _c_v_a_r + from . import _c_v_t + from . import _f_e_a_t + from . import _f_p_g_m + from . import _f_v_a_r + from . import _g_a_s_p + from . import _g_c_i_d + from . import _g_l_y_f + from . import _g_v_a_r + from . import _h_d_m_x + from . import _h_e_a_d + from . import _h_h_e_a + from . import _h_m_t_x + from . import _k_e_r_n + from . import _l_c_a_r + from . import _l_o_c_a + from . import _l_t_a_g + from . import _m_a_x_p + from . import _m_e_t_a + from . import _m_o_r_t + from . import _m_o_r_x + from . import _n_a_m_e + from . import _o_p_b_d + from . import _p_o_s_t + from . import _p_r_e_p + from . import _p_r_o_p + from . import _s_b_i_x + from . import _t_r_a_k + from . import _v_h_e_a + from . import _v_m_t_x + + +if __name__ == "__main__": + import doctest, sys + + sys.exit(doctest.testmod().failed) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/B_A_S_E_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/B_A_S_E_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c485976004010e85b7ca8d823f92fc6ce845c8bf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/B_A_S_E_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/BitmapGlyphMetrics.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/BitmapGlyphMetrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4b03246d34af09b136b67be88ba1fdaef51adf0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/BitmapGlyphMetrics.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_B_D_T_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_B_D_T_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75ec1108d702a23ee8ed3e031b9855bcf270b91d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_B_D_T_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_B_L_C_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_B_L_C_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..518226d97f7bc46d9c1653cac5da4be50ce116c6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_B_L_C_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..839eb1a5123c4feaf217616b453fa6fe9377e812 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F__2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F__2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..712108e36a8f46a3ffad43fa2e8aa82220e29e16 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F__2.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_O_L_R_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_O_L_R_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7640011bb8bb116b3fe2f7f13ddda7abf9db2c08 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_O_L_R_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_P_A_L_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_P_A_L_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11c1a5c087f780553ebc4281737ab2a9372a093f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/C_P_A_L_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/D_S_I_G_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/D_S_I_G_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eaef6695424faeec39134f0efb0235b31f7f0073 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/D_S_I_G_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/D__e_b_g.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/D__e_b_g.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..608a5cc8350f5c5b374b72c18f4cc4d985f96200 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/D__e_b_g.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/DefaultTable.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/DefaultTable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1c80f2781404601166607b3eebb67c359d2f074 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/DefaultTable.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/E_B_D_T_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/E_B_D_T_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..727eda5397448f351c912f7359ee1e0294027a14 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/E_B_D_T_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/E_B_L_C_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/E_B_L_C_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc35436c247c6c09567b1edeb9fa8be7506c165e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/E_B_L_C_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/E_B_S_C_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/E_B_S_C_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21dbc4892e8190cfc6133ddb0428f6db7bb1d45f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/E_B_S_C_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/F_F_T_M_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/F_F_T_M_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8796aa947274a727c4f6ff2b320c66d10fcb5a5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/F_F_T_M_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/F__e_a_t.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/F__e_a_t.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecd4114b68403e9ddd022d0cb02f6918a034ea14 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/F__e_a_t.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G_D_E_F_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G_D_E_F_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a82352cd3c55464a4f4bc7c0f8629f12bb0cf92 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G_D_E_F_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G_P_O_S_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G_P_O_S_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a03680a87aa74ab2765d79524e99478cc88b98c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G_P_O_S_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G_S_U_B_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G_S_U_B_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe88eabb3ef12ba92584ae26d2b92613ab9cf401 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G_S_U_B_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G_V_A_R_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G_V_A_R_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6359ee4ff1d046fb0e8ad1cd908710eaf6caeca8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G_V_A_R_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G__l_a_t.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G__l_a_t.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e90d57a087f408f39bd005a0bfe04e15aceddd6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G__l_a_t.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G__l_o_c.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G__l_o_c.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3258930764e33144ccead5e45f4857e941f82dd6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/G__l_o_c.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/H_V_A_R_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/H_V_A_R_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75812fdfb08bbf738bab377ebe3c1fe599f65e54 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/H_V_A_R_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/I_F_T_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/I_F_T_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e26e21a01ee84dc9927682a551462b8b9f2b2b48 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/I_F_T_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/I_F_T_X_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/I_F_T_X_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e53ec77b134ad90f952e430ef960537ff814731 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/I_F_T_X_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/J_S_T_F_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/J_S_T_F_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31a2e45a681b378b680c2ebe1d331a428c422257 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/J_S_T_F_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/L_T_S_H_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/L_T_S_H_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..212c6137049d85f33c0531944a5a0a62b3bb1ee6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/L_T_S_H_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/M_A_T_H_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/M_A_T_H_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..175e59476df85db3b125f3b2f8650ce8f1dd3cbd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/M_A_T_H_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/M_V_A_R_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/M_V_A_R_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3589e6d5f1f54b31ada1d05e692db75ae25a3ef Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/M_V_A_R_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/O_S_2f_2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/O_S_2f_2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9375d3b5ac19324b418f741a03f859653e480cdf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/O_S_2f_2.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/S_T_A_T_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/S_T_A_T_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c75527677b397a86aeb1cfa60e546a82a57f8580 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/S_T_A_T_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/S_V_G_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/S_V_G_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83542610f914a15b2211b05e61fd5d56f3cd8b49 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/S_V_G_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/S__i_l_f.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/S__i_l_f.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a0c2f7ad7f8f35661607fc7accaddac780c1210 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/S__i_l_f.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/S__i_l_l.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/S__i_l_l.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..326f6d19edd6af915a2f7af6b1448582ae574f1c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/S__i_l_l.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_B_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_B_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fedddbe25d3f9cb6aef8369260637fb321a2a0f7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_B_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_C_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_C_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e1c6993605d4200786561c455a3e6c9e3b185ed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_C_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_D_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_D_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c50fe01d1428722d186b8c755cbc9b01ea04ce5b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_D_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_J_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_J_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9fc129c6ce249a7a872e8b105cda666a13354db Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_J_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_P_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_P_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b31a4a46731ac8f3452186132fc5a45a1cb2d20 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_P_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_S_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_S_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7494e7eb15de5f9ed9446a24895c5a17ede94ae Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_S_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_V_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_V_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d68127ecee53b4d0ceda6c35469024656838b1a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_V_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__0.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__0.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf24e07a844c4aed10821db153c0d594b3fd2995 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__0.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__1.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__1.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..681f79f5b771a9f44c01cbba455a33f80a6c7b50 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__1.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12db32e4847e4554e7fccef99cee203425b2c619 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__2.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__3.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c2a3954b5c18c0d5f3134610a596d232017f278 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__3.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__5.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__5.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b2db3e6a347a28fdfc4ffb73e4b794f2fd2c18f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__5.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_T_F_A_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_T_F_A_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c44d6d83bd0e1d211fa1211f815860450bf6278f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/T_T_F_A_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/TupleVariation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/TupleVariation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..561d5e541846bb8d0ae1bc6abdf9a45138e2ade6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/TupleVariation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/V_A_R_C_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/V_A_R_C_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..381442b99524af0cd1e3c233ebc62e7807ad09f3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/V_A_R_C_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/V_D_M_X_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/V_D_M_X_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2515664b44777d0392cf0709c12c56f5c636f1a5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/V_D_M_X_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/V_O_R_G_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/V_O_R_G_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f48d178096772fbd6a960993666a3b7239d85e1f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/V_O_R_G_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/V_V_A_R_.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/V_V_A_R_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7a5375e6771b67dc0c993c35b3a697fd54c9c99 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/V_V_A_R_.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da67fdc441a57029033aa5ac8eae0686358f7d72 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_a_n_k_r.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_a_n_k_r.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e403b894219b019d1f6890c773c4d539cc4bcb43 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_a_n_k_r.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_a_v_a_r.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_a_v_a_r.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..354e843ab9c688ad54b441f99b58c7f284f93a24 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_a_v_a_r.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_d_a_t.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_d_a_t.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f36d7920c18757c532c07121c847b90b87fe0c9c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_d_a_t.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_g_c_l.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_g_c_l.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cad838b659fb2872acaca8aee8b014e9d69fdb4e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_g_c_l.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_h_e_d.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_h_e_d.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b386f911ddf126db635bcddd87718d071ddaa26b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_h_e_d.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_l_o_c.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_l_o_c.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff25a217b3f02007121dc15df69b4023b83e0e1e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_l_o_c.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_s_l_n.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_s_l_n.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae3c5ffa91e48d63bb4b27aed6286c24706469b1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_b_s_l_n.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_c_i_d_g.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_c_i_d_g.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4c1cd89cf408c7e916749b193b830aac0516691 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_c_i_d_g.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_c_m_a_p.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_c_m_a_p.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d95440ffcfa78716e797b285e19aa5d76777f2a1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_c_m_a_p.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_c_v_a_r.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_c_v_a_r.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cff3ee7330f9155c0188a9510e4c67561165d3e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_c_v_a_r.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_c_v_t.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_c_v_t.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37354b6e4c51ec4a69ca2b047c93418c4e460c66 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_c_v_t.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_f_e_a_t.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_f_e_a_t.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bbfda7cfb64ea36eeb23c25887f7b55a09a6066 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_f_e_a_t.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_f_p_g_m.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_f_p_g_m.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f02c4b1b45e9239c21737e6b8c24b21b504ae6dd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_f_p_g_m.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_f_v_a_r.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_f_v_a_r.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc1558204c089a604e33f40edf53bfb3a9df18ca Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_f_v_a_r.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_a_s_p.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_a_s_p.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eec35af61a4a58c6ceac428d69745c5fbdbf6cfa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_a_s_p.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_c_i_d.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_c_i_d.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfb098f3ca26413242e8ee3bbd87e310a6b481e3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_c_i_d.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_l_y_f.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_l_y_f.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94319fc7696f82d7cf53bc07a9af178c6ce60190 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_l_y_f.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_v_a_r.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_v_a_r.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25b8305a8240536689e53ddc84d68edf86106350 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_v_a_r.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_h_d_m_x.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_h_d_m_x.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..619b4c2e85e67b20b4b6f60d35d2f36a569958d3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_h_d_m_x.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_h_e_a_d.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_h_e_a_d.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2007d85f70fb08372ef4dc89f4421b1663f2658 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_h_e_a_d.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_h_h_e_a.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_h_h_e_a.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..179902bbe5c8525e86a8a89b846caaa81c2a0d64 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_h_h_e_a.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_h_m_t_x.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_h_m_t_x.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e52f66e3b6d89152b3fa24165ab530480064ef98 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_h_m_t_x.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_k_e_r_n.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_k_e_r_n.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6561c5ccd9e206f6c2a0fd0b0c19fddeafe64a58 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_k_e_r_n.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_l_c_a_r.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_l_c_a_r.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9128c2190e8592058c2a33a5002cd37d51829fd1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_l_c_a_r.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_l_o_c_a.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_l_o_c_a.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9971f9c5df6d35ccb8dfe010f35dc37dacab6a55 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_l_o_c_a.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_l_t_a_g.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_l_t_a_g.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5eab728334d7734a31b272f252c73f5827e8e77d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_l_t_a_g.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_m_a_x_p.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_m_a_x_p.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..210f3895639e04c4a5ed93b0b1cbf21c715783d7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_m_a_x_p.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_m_e_t_a.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_m_e_t_a.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bab8bda036bd6bb8538e2237f56fd45ab07430f9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_m_e_t_a.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_m_o_r_t.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_m_o_r_t.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..236e84dfd53fa4823c2d22dd1d693ab4cadc5330 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_m_o_r_t.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_m_o_r_x.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_m_o_r_x.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edb71ecf01650057c9501361d3f5d919cb4c3cfc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_m_o_r_x.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_n_a_m_e.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_n_a_m_e.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfde0bbebc85290767256932a778cb31d22faef1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_n_a_m_e.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_o_p_b_d.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_o_p_b_d.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40547ae2e47a68592b74db65e285cc5aaa3af17a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_o_p_b_d.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_p_o_s_t.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_p_o_s_t.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49df4598360968d5a85f251b66e41aede8ae9d47 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_p_o_s_t.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_p_r_e_p.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_p_r_e_p.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dd307ef90e2ad5e40f494351c719981d77ac095 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_p_r_e_p.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_p_r_o_p.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_p_r_o_p.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03737807f41d74dcfe1fb4b6e042dbc01f5809ac Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_p_r_o_p.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_s_b_i_x.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_s_b_i_x.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1778ea2c34ea2e85f0fd977900659c3e00aab067 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_s_b_i_x.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_t_r_a_k.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_t_r_a_k.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..982a424569bcd4f114fd352aab5ce46689ea2124 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_t_r_a_k.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_v_h_e_a.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_v_h_e_a.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03f1ed024043d7555d5db56b27d1d5d655b0f874 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_v_h_e_a.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_v_m_t_x.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_v_m_t_x.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f34883c35f466c54e33e338603bba0f4416d49cd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_v_m_t_x.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/asciiTable.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/asciiTable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71dec5cdc02c18e30589041ce806be1c6c91226e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/asciiTable.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/grUtils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/grUtils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3492b5542db6796c7a228f224f25ed03cbe2010 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/grUtils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otBase.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otBase.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ccf60bc5140f34dc5b20499b3f1209493b09182 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otBase.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otConverters.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otConverters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..530b5d43257acb24b9a429d89075121744f8b028 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otConverters.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93874224cddd3fb47c4b9da7321dc0d2e8bd072a4a25441c5145a28081893e52 +size 145003 diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otData.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otData.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecc31461c4873095e80d833bb9ceb46037af14de --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otData.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00f8b56e46279f65fb5502335f037f6bcb136c7aee689a0302f4955ef86c89bf +size 117065 diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otDataSchema.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otDataSchema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cd577cc5f5a9fda6cff45cd3ba27518848eedc2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otDataSchema.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otTables.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otTables.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f37948d4f47d51f233bdb8f6839c301c9a6ddda1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otTables.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0185977ab46036bd3d0911a435ab5fd4ace89354425e90c2e1a5e54f6ea5f87e +size 122475 diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otTraverse.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otTraverse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5aec77d6e5dd8ee3e1782460d5775a1f8af3cbff Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otTraverse.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/sbixGlyph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/sbixGlyph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68d886475735df2b316d845a6a81e7dbfe4124f1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/sbixGlyph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/sbixStrike.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/sbixStrike.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ee47dadb4686f111b1c51693c50f01fc3aa3d6b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/sbixStrike.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/ttProgram.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/ttProgram.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b7cd9eff222085605456c38b1fa198b5350e230 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/ttProgram.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_a_n_k_r.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_a_n_k_r.py new file mode 100644 index 0000000000000000000000000000000000000000..5466d42d4117f9935b54def71e5351fa1a0ee6ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_a_n_k_r.py @@ -0,0 +1,15 @@ +from .otBase import BaseTTXConverter + + +class table__a_n_k_r(BaseTTXConverter): + """Anchor Point table + + The anchor point table provides a way to define anchor points. + These are points within the coordinate space of a given glyph, + independent of the control points used to render the glyph. + Anchor points are used in conjunction with the ``kerx`` table. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ankr.html + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_a_v_a_r.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_a_v_a_r.py new file mode 100644 index 0000000000000000000000000000000000000000..be0045cd578f5d1f9180436d636041c03b89fe02 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_a_v_a_r.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +from typing import Mapping, TYPE_CHECKING +from fontTools.misc import sstruct +from fontTools.misc.fixedTools import ( + fixedToFloat as fi2fl, + floatToFixed as fl2fi, + floatToFixedToStr as fl2str, + strToFixedToFloat as str2fl, +) +from fontTools.misc.textTools import bytesjoin, safeEval +from fontTools.misc.roundTools import otRound +from fontTools.varLib.models import piecewiseLinearMap +from fontTools.varLib.varStore import VarStoreInstancer, NO_VARIATION_INDEX +from fontTools.ttLib import TTLibError +from . import DefaultTable +from . import otTables +import struct +import logging + +log = logging.getLogger(__name__) + +from .otBase import BaseTTXConverter + +if TYPE_CHECKING: + from ..ttFont import TTFont + + +class table__a_v_a_r(BaseTTXConverter): + """Axis Variations table + + This class represents the ``avar`` table of a variable font. The object has one + substantive attribute, ``segments``, which maps axis tags to a segments dictionary:: + + >>> font["avar"].segments # doctest: +SKIP + {'wght': {-1.0: -1.0, + 0.0: 0.0, + 0.125: 0.11444091796875, + 0.25: 0.23492431640625, + 0.5: 0.35540771484375, + 0.625: 0.5, + 0.75: 0.6566162109375, + 0.875: 0.81927490234375, + 1.0: 1.0}, + 'ital': {-1.0: -1.0, 0.0: 0.0, 1.0: 1.0}} + + Notice that the segments dictionary is made up of normalized values. A valid + ``avar`` segment mapping must contain the entries ``-1.0: -1.0, 0.0: 0.0, 1.0: 1.0``. + fontTools does not enforce this, so it is your responsibility to ensure that + mappings are valid. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/avar + """ + + dependencies = ["fvar"] + + def __init__(self, tag=None): + super().__init__(tag) + self.segments = {} + + def compile(self, ttFont): + axisTags = [axis.axisTag for axis in ttFont["fvar"].axes] + if not hasattr(self, "table"): + self.table = otTables.avar() + if not hasattr(self.table, "Reserved"): + self.table.Reserved = 0 + self.table.Version = (getattr(self, "majorVersion", 1) << 16) | getattr( + self, "minorVersion", 0 + ) + self.table.AxisCount = len(axisTags) + self.table.AxisSegmentMap = [] + for axis in axisTags: + mappings = self.segments[axis] + segmentMap = otTables.AxisSegmentMap() + segmentMap.PositionMapCount = len(mappings) + segmentMap.AxisValueMap = [] + for key, value in sorted(mappings.items()): + valueMap = otTables.AxisValueMap() + valueMap.FromCoordinate = key + valueMap.ToCoordinate = value + segmentMap.AxisValueMap.append(valueMap) + self.table.AxisSegmentMap.append(segmentMap) + return super().compile(ttFont) + + def decompile(self, data, ttFont): + super().decompile(data, ttFont) + self.majorVersion = self.table.Version >> 16 + self.minorVersion = self.table.Version & 0xFFFF + if self.majorVersion not in (1, 2): + raise NotImplementedError("Unknown avar table version") + axisTags = [axis.axisTag for axis in ttFont["fvar"].axes] + for axis in axisTags: + self.segments[axis] = {} + for axis, segmentMap in zip(axisTags, self.table.AxisSegmentMap): + segments = self.segments[axis] = {} + for segment in segmentMap.AxisValueMap: + segments[segment.FromCoordinate] = segment.ToCoordinate + + def toXML(self, writer, ttFont): + writer.simpletag( + "version", + major=getattr(self, "majorVersion", 1), + minor=getattr(self, "minorVersion", 0), + ) + writer.newline() + axisTags = [axis.axisTag for axis in ttFont["fvar"].axes] + for axis in axisTags: + writer.begintag("segment", axis=axis) + writer.newline() + for key, value in sorted(self.segments[axis].items()): + key = fl2str(key, 14) + value = fl2str(value, 14) + writer.simpletag("mapping", **{"from": key, "to": value}) + writer.newline() + writer.endtag("segment") + writer.newline() + if getattr(self, "majorVersion", 1) >= 2: + if self.table.VarIdxMap: + self.table.VarIdxMap.toXML(writer, ttFont, name="VarIdxMap") + if self.table.VarStore: + self.table.VarStore.toXML(writer, ttFont) + + def fromXML(self, name, attrs, content, ttFont): + if not hasattr(self, "table"): + self.table = otTables.avar() + if not hasattr(self.table, "Reserved"): + self.table.Reserved = 0 + if name == "version": + self.majorVersion = safeEval(attrs["major"]) + self.minorVersion = safeEval(attrs["minor"]) + self.table.Version = (getattr(self, "majorVersion", 1) << 16) | getattr( + self, "minorVersion", 0 + ) + elif name == "segment": + axis = attrs["axis"] + segment = self.segments[axis] = {} + for element in content: + if isinstance(element, tuple): + elementName, elementAttrs, _ = element + if elementName == "mapping": + fromValue = str2fl(elementAttrs["from"], 14) + toValue = str2fl(elementAttrs["to"], 14) + if fromValue in segment: + log.warning( + "duplicate entry for %s in axis '%s'", fromValue, axis + ) + segment[fromValue] = toValue + else: + super().fromXML(name, attrs, content, ttFont) + + def renormalizeLocation( + self, location: Mapping[str, float], font: TTFont, dropZeroes: bool = True + ) -> dict[str, float]: + majorVersion = getattr(self, "majorVersion", 1) + + if majorVersion not in (1, 2): + raise NotImplementedError("Unknown avar table version") + + avarSegments = self.segments + mappedLocation = {} + for axisTag, value in location.items(): + avarMapping = avarSegments.get(axisTag, None) + if avarMapping is not None: + value = piecewiseLinearMap(value, avarMapping) + mappedLocation[axisTag] = value + + if majorVersion < 2: + return mappedLocation + + # Version 2 + + varIdxMap = self.table.VarIdxMap + varStore = self.table.VarStore + axes = font["fvar"].axes + if varStore is not None: + varStoreInstancer = VarStoreInstancer(varStore, axes, mappedLocation) + + coords = list(fl2fi(mappedLocation.get(axis.axisTag, 0), 14) for axis in axes) + + out = [] + for varIdx, v in enumerate(coords): + if varIdxMap is not None: + varIdx = varIdxMap[varIdx] + + if varStore is not None: + delta = varStoreInstancer[varIdx] + v += otRound(delta) + v = min(max(v, -(1 << 14)), +(1 << 14)) + + out.append(v) + + mappedLocation = { + axis.axisTag: fi2fl(v, 14) + for v, axis in zip(out, axes) + if v != 0 or not dropZeroes + } + + return mappedLocation + + def renormalizeAxisLimits(self, axisLimits, font=None): + """Apply the avar v1 segment maps to normalized axis limits. + + The values of ``axisLimits`` may be (min, default, max) triples or + longer sequences whose trailing elements are user-space distances + (as in NormalizedAxisTripleAndDistances); only the first three + elements are coordinates, so only those are mapped — the distances + pass through untouched. The mapped coordinates are quantized to + F2Dot14, to avoid surprise interpolations. + + Returns a dict mapping axis tags to tuples of the same length as + the input values. avar version 2 mappings are NOT applied — the + VarStore-driven part of an avar 2 table is handled separately by + the instancer (see fontTools.varLib.instancer). + """ + if getattr(self, "majorVersion", 1) not in (1, 2): + raise NotImplementedError("Unknown avar table version") + + avarSegments = self.segments + mappedAxisLimits = {} + for axisTag, triple in axisLimits.items(): + coords = tuple(triple)[:3] + distances = tuple(triple)[3:] + avarMapping = avarSegments.get(axisTag, None) + if avarMapping is not None: + coords = tuple( + piecewiseLinearMap(value, avarMapping) for value in coords + ) + # Quantize to F2Dot14, to avoid surprise interpolations. + coords = tuple(fi2fl(fl2fi(value, 14), 14) for value in coords) + mappedAxisLimits[axisTag] = coords + distances + return mappedAxisLimits diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_d_a_t.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_d_a_t.py new file mode 100644 index 0000000000000000000000000000000000000000..537d4a9b70565e061dd8aad6fad5b7bb282f0712 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_d_a_t.py @@ -0,0 +1,5 @@ +from fontTools.ttLib.tables.E_B_D_T_ import table_E_B_D_T_ + + +class table__b_d_a_t(table_E_B_D_T_): + locatorName = "bloc" diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_g_c_l.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_g_c_l.py new file mode 100644 index 0000000000000000000000000000000000000000..7d4a2ffbfb292bbddf5ee65dd42bbc4f03eb7fe6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_g_c_l.py @@ -0,0 +1,136 @@ +"""Support for the `bgcl` (Apple Color Emoji background) table. + +This table stores a JSON blob. We decode it to a Python object on +decompile and emit human readable JSON in the TTX via a <json> element. +On compile we re-encode the JSON to UTF-8 bytes which is what Apple code +reads via CTFontCopyTable then JSONDecoder. + +On iOS 16 and later the `bgcl` payload is used as the wallpaper +background when the user selects an emoji wallpaper. + +Fields: + +- ``colors``: list of palette entries. Each entry is an array of four + integers ``[R, G, B, A]``. R/G/B are 0-255. A is 0-1. + +- ``emojicolors``: list of per-emoji palettes. Each item is an array of + three sublists: primary/dominant, accent, contextual + (names inferred). Each sublist contains integer indexes referencing + entries in ``colors``; the runtime uses these to assemble layered + background tints for an emoji. + +- ``indexmap``: mapping (glyph identifier → palette index). The map + maps a glyph identity to an integer index selecting an entry in + ``emojicolors``. The font/UI uses this to pick the correct palette + for a glyph when rendering wallpaper backgrounds. + +- ``version``: integer table version used for parsing/compatibility. + +Runtime usage summary: + +- The system fetches the table bytes with ``CTFontCopyTable('bgcl')``, + decodes the bytes as UTF‑8 JSON and runs the JSON through the app's + decoder into an internal ``BgclTable`` structure. The app looks up a + glyph's entry in ``indexmap``, retrieves the corresponding + ``emojicolors`` palette, then converts the referenced ``colors`` + entries into color objects (normalizing channels/alpha as needed). + This resulting color(s) drive the wallpaper background appearance for + emoji wallpapers on supported iOS versions. + +This implementation preserves the JSON payload and exposes convenience +attributes ``colors``, ``emojicolors``, ``indexmap`` and ``version`` +when available. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from fontTools.misc.textTools import tostr, strjoin +from . import DefaultTable +import json + +if TYPE_CHECKING: + from fontTools.misc.xmlWriter import XMLWriter + from fontTools.ttLib import TTFont + + +class table__b_g_c_l(DefaultTable.DefaultTable): + """bgcl table: stores a JSON blob describing background palettes. + + The JSON structure typically contains the top-level keys: + - colors: [[R,G,B,A], ...] + - emojicolors: [[[dominant...],[accent...],[contextual...]], ...] + - indexmap: {"glyphIndex": emojicolors_index, ...} + - version: int + """ + + def decompile(self, data: bytes, ttFont: TTFont) -> None: + """Store raw bytes and attempt to parse JSON. + + The JSON commonly includes palette/lookup data used at runtime to + construct wallpaper/background colors for emoji wallpapers on + recent iOS releases. + """ + self.data = data + try: + text = tostr(data, "utf_8") + self.json = json.loads(text) + except Exception as e: # keep table decompilation robust + self.json = None + self.ERROR = f"bgcl JSON parse error: {e!r}" + return + # convenient attributes + self.colors = self.json.get("colors") + self.emojicolors = self.json.get("emojicolors") + self.indexmap = self.json.get("indexmap") + self.version = self.json.get("version") + + def compile(self, ttFont: TTFont) -> bytes: + """Encode the JSON object to UTF-8 bytes for font binary storage.""" + if getattr(self, "json", None) is None: + # fallback to raw bytes if parsing failed earlier + return getattr(self, "data", b"") + # use compact representation for binary table + return json.dumps(self.json, separators=(",", ":"), ensure_ascii=False).encode( + "utf_8" + ) + + def toXML(self, writer: XMLWriter, ttFont: TTFont) -> None: + """Emit pretty-printed JSON inside a <json> element for human inspection.""" + if getattr(self, "json", None) is None: + # fallback to default hex output + DefaultTable.DefaultTable.toXML(self, writer, ttFont) + return + writer.begintag("json") + writer.newline() + pretty = json.dumps(self.json, indent=2, ensure_ascii=False) + writer.writecdata(pretty) + writer.newline() + writer.endtag("json") + writer.newline() + + def fromXML( + self, name: str, attrs: dict[str, str], content, ttFont: TTFont + ) -> None: + """Read JSON from the <json> element. `content` may be a list. + + This mirrors SVG/other table `fromXML` handlers which accept a + list of content chunks. + """ + if name != "json": + # fall back to DefaultTable behavior for unknown elements + return DefaultTable.DefaultTable.fromXML(self, name, attrs, content, ttFont) + text = strjoin(content).strip() + try: + self.json = json.loads(text) + # keep raw bytes in sync + self.data = text.encode("utf_8") + self.colors = self.json.get("colors") + self.emojicolors = self.json.get("emojicolors") + self.indexmap = self.json.get("indexmap") + self.version = self.json.get("version") + except Exception as e: + # store error and fall back to raw + self.json = None + self.ERROR = f"bgcl JSON parse error in fromXML: {e!r}" diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_h_e_d.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_h_e_d.py new file mode 100644 index 0000000000000000000000000000000000000000..3b53f3b19e086c5d911d5391918ebbe03c6da853 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_h_e_d.py @@ -0,0 +1,5 @@ +from fontTools.ttLib.tables._h_e_a_d import table__h_e_a_d + + +class table__b_h_e_d(table__h_e_a_d): + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_l_o_c.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_l_o_c.py new file mode 100644 index 0000000000000000000000000000000000000000..955d34086e11608c61ea7a0dffaa50e0b41ae523 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_l_o_c.py @@ -0,0 +1,5 @@ +from fontTools.ttLib.tables.E_B_L_C_ import table_E_B_L_C_ + + +class table__b_l_o_c(table_E_B_L_C_): + dependencies = ["bdat"] diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_s_l_n.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_s_l_n.py new file mode 100644 index 0000000000000000000000000000000000000000..85796b0a0479d26104a3fb63d9fe6085be29853a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_b_s_l_n.py @@ -0,0 +1,15 @@ +from .otBase import BaseTTXConverter + + +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6bsln.html +class table__b_s_l_n(BaseTTXConverter): + """Baseline table + + The AAT ``bsln`` table is similar in purpose to the OpenType ``BASE`` + table; it stores per-script baselines to support automatic alignment + of lines of text. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6bsln.html + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_c_i_d_g.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_c_i_d_g.py new file mode 100644 index 0000000000000000000000000000000000000000..c283e5a4dd1619a621a78b20171d38b14752c836 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_c_i_d_g.py @@ -0,0 +1,24 @@ +# coding: utf-8 +from .otBase import BaseTTXConverter + + +class table__c_i_d_g(BaseTTXConverter): + """CID to Glyph ID table + + The AAT ``cidg`` table has almost the same structure as ``gidc``, + just mapping CIDs to GlyphIDs instead of the reverse direction. + + It is useful for fonts that may be used by a PDF renderer in lieu of + a font reference with a known glyph collection but no subsetted + glyphs. For instance, a PDF can say “please use a font conforming + to Adobe-Japan-1”; the ``cidg`` mapping is necessary if the font is, + say, a TrueType font. ``gidc`` is lossy for this purpose and is + obsoleted by ``cidg``. + + For example, the first font in ``/System/Library/Fonts/PingFang.ttc`` + (which Apple ships pre-installed on MacOS 10.12.6) has a ``cidg`` table. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gcid.html + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_c_m_a_p.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_c_m_a_p.py new file mode 100644 index 0000000000000000000000000000000000000000..8719e8b448e6b399b9f6b958426778f94467f7bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_c_m_a_p.py @@ -0,0 +1,1675 @@ +from fontTools.misc.textTools import bytesjoin, safeEval, readHex +from fontTools.misc.encodingTools import getEncoding +from fontTools.ttLib import getSearchRange, TTLibError +from fontTools.unicode import Unicode +from . import DefaultTable +import sys +import struct +import array +import logging + +log = logging.getLogger(__name__) + + +def _make_map(font, chars, gids): + assert len(chars) == len(gids) + glyphNames = font.getGlyphNameMany(gids) + cmap = {} + for char, gid, name in zip(chars, gids, glyphNames): + if gid == 0: + continue + cmap[char] = name + return cmap + + +class table__c_m_a_p(DefaultTable.DefaultTable): + """Character to Glyph Index Mapping Table + + This class represents the `cmap <https://docs.microsoft.com/en-us/typography/opentype/spec/cmap>`_ + table, which maps between input characters (in Unicode or other system encodings) + and glyphs within the font. The ``cmap`` table contains one or more subtables + which determine the mapping of of characters to glyphs across different platforms + and encoding systems. + + ``table__c_m_a_p`` objects expose an accessor ``.tables`` which provides access + to the subtables, although it is normally easier to retrieve individual subtables + through the utility methods described below. To add new subtables to a font, + first determine the subtable format (if in doubt use format 4 for glyphs within + the BMP, format 12 for glyphs outside the BMP, and format 14 for Unicode Variation + Sequences) construct subtable objects with ``CmapSubtable.newSubtable(format)``, + and append them to the ``.tables`` list. + + Within a subtable, the mapping of characters to glyphs is provided by the ``.cmap`` + attribute. + + Example:: + + cmap4_0_3 = CmapSubtable.newSubtable(4) + cmap4_0_3.platformID = 0 + cmap4_0_3.platEncID = 3 + cmap4_0_3.language = 0 + cmap4_0_3.cmap = { 0xC1: "Aacute" } + + cmap = newTable("cmap") + cmap.tableVersion = 0 + cmap.tables = [cmap4_0_3] + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/cmap + """ + + def getcmap(self, platformID, platEncID): + """Returns the first subtable which matches the given platform and encoding. + + Args: + platformID (int): The platform ID. Use 0 for Unicode, 1 for Macintosh + (deprecated for new fonts), 2 for ISO (deprecated) and 3 for Windows. + encodingID (int): Encoding ID. Interpretation depends on the platform ID. + See the OpenType specification for details. + + Returns: + An object which is a subclass of :py:class:`CmapSubtable` if a matching + subtable is found within the font, or ``None`` otherwise. + """ + + for subtable in self.tables: + if subtable.platformID == platformID and subtable.platEncID == platEncID: + return subtable + return None # not found + + def getBestCmap( + self, + cmapPreferences=( + (3, 10), + (0, 6), + (0, 4), + (3, 1), + (0, 3), + (0, 2), + (0, 1), + (0, 0), + ), + ): + """Returns the 'best' Unicode cmap dictionary available in the font + or ``None``, if no Unicode cmap subtable is available. + + By default it will search for the following (platformID, platEncID) + pairs in order:: + + (3, 10), # Windows Unicode full repertoire + (0, 6), # Unicode full repertoire (format 13 subtable) + (0, 4), # Unicode 2.0 full repertoire + (3, 1), # Windows Unicode BMP + (0, 3), # Unicode 2.0 BMP + (0, 2), # Unicode ISO/IEC 10646 + (0, 1), # Unicode 1.1 + (0, 0) # Unicode 1.0 + + This particular order matches what HarfBuzz uses to choose what + subtable to use by default. This order prefers the largest-repertoire + subtable, and among those, prefers the Windows-platform over the + Unicode-platform as the former has wider support. + + This order can be customized via the ``cmapPreferences`` argument. + """ + for platformID, platEncID in cmapPreferences: + cmapSubtable = self.getcmap(platformID, platEncID) + if cmapSubtable is not None: + return cmapSubtable.cmap + return None # None of the requested cmap subtables were found + + def buildReversed(self): + """Builds a reverse mapping dictionary + + Iterates over all Unicode cmap tables and returns a dictionary mapping + glyphs to sets of codepoints, such as:: + + { + 'one': {0x31} + 'A': {0x41,0x391} + } + + The values are sets of Unicode codepoints because + some fonts map different codepoints to the same glyph. + For example, ``U+0041 LATIN CAPITAL LETTER A`` and ``U+0391 + GREEK CAPITAL LETTER ALPHA`` are sometimes the same glyph. + """ + result = {} + for subtable in self.tables: + if subtable.isUnicode(): + for codepoint, name in subtable.cmap.items(): + result.setdefault(name, set()).add(codepoint) + return result + + def buildReversedMin(self): + result = {} + for subtable in self.tables: + if subtable.isUnicode(): + for codepoint, name in subtable.cmap.items(): + if name in result: + result[name] = min(result[name], codepoint) + else: + result[name] = codepoint + return result + + def decompile(self, data, ttFont): + if len(data) < 4: + raise TTLibError("cmap table is too short") + tableVersion, numSubTables = struct.unpack(">HH", data[:4]) + self.tableVersion = int(tableVersion) + self.tables = tables = [] + seenOffsets = {} + for i in range(numSubTables): + entry = data[4 + i * 8 : 4 + (i + 1) * 8] + if len(entry) < 8: + raise TTLibError("cmap subtable directory is truncated") + platformID, platEncID, offset = struct.unpack(">HHL", entry) + platformID, platEncID = int(platformID), int(platEncID) + # subtableOffset is an unsigned Offset32 pointing somewhere inside + # the cmap table; a malformed font can put it past the end of the + # data, so guard the header reads below instead of letting + # struct.unpack raise struct.error. + if offset + 4 > len(data): + raise TTLibError( + "cmap subtable offset %d is out of bounds (data length %d)" + % (offset, len(data)) + ) + format, length = struct.unpack(">HH", data[offset : offset + 4]) + if format in [8, 10, 12, 13]: + if offset + 8 > len(data): + raise TTLibError("cmap subtable header is truncated") + format, reserved, length = struct.unpack( + ">HHL", data[offset : offset + 8] + ) + elif format in [14]: + if offset + 6 > len(data): + raise TTLibError("cmap subtable header is truncated") + format, length = struct.unpack(">HL", data[offset : offset + 6]) + + if not length: + log.error( + "cmap subtable is reported as having zero length: platformID %s, " + "platEncID %s, format %s offset %s. Skipping table.", + platformID, + platEncID, + format, + offset, + ) + continue + table = CmapSubtable.newSubtable(format) + table.platformID = platformID + table.platEncID = platEncID + # Note that by default we decompile only the subtable header info; + # any other data gets decompiled only when an attribute of the + # subtable is referenced. + # + # Make sure the body is actually present and large enough for the + # fixed header decompileHeader will unpack. Otherwise the slice is + # short and we hit either an AssertionError (silenced under python + # -O, leaving a bogus length) or a struct.error deep inside + # decompileHeader; surface a TTLibError in both cases. Formats + # without a fixed header (8, 10 and any unrecognised format, which + # fall back to cmap_format_unknown) have an empty headerFormat and + # so no minimum. + minHeaderSize = struct.calcsize(table.headerFormat) + if length < minHeaderSize: + raise TTLibError( + "cmap subtable header is truncated: length %d < %d" + % (length, minHeaderSize) + ) + if offset + length > len(data): + raise TTLibError( + "cmap subtable is truncated: needs %d bytes, only %d available" + % (length, len(data) - offset) + ) + table.decompileHeader(data[offset : offset + int(length)], ttFont) + if offset in seenOffsets: + table.data = None # Mark as decompiled + table.cmap = tables[seenOffsets[offset]].cmap + else: + seenOffsets[offset] = i + tables.append(table) + if ttFont.lazy is False: # Be lazy for None and True + self.ensureDecompiled() + + def ensureDecompiled(self, recurse=False): + # The recurse argument is unused, but part of the signature of + # ensureDecompiled across the library. + for st in self.tables: + st.ensureDecompiled() + + def compile(self, ttFont): + self.tables.sort() # sort according to the spec; see CmapSubtable.__lt__() + keys = [(t.platformID, t.platEncID, t.language) for t in self.tables] + seen = set() + duplicates = {k for k in keys if k in seen or seen.add(k)} + if duplicates: + raise ValueError( + "cmap subtables have duplicate (platformID, platEncID, language) " + f"entries, which the OpenType spec does not allow: {duplicates}" + ) + numSubTables = len(self.tables) + totalOffset = 4 + 8 * numSubTables + data = struct.pack(">HH", self.tableVersion, numSubTables) + tableData = b"" + seen = ( + {} + ) # Some tables are the same object reference. Don't compile them twice. + done = ( + {} + ) # Some tables are different objects, but compile to the same data chunk + for table in self.tables: + offset = seen.get(id(table.cmap)) + if offset is None: + chunk = table.compile(ttFont) + offset = done.get(chunk) + if offset is None: + offset = seen[id(table.cmap)] = done[chunk] = totalOffset + len( + tableData + ) + tableData = tableData + chunk + data = data + struct.pack(">HHL", table.platformID, table.platEncID, offset) + return data + tableData + + def toXML(self, writer, ttFont): + writer.simpletag("tableVersion", version=self.tableVersion) + writer.newline() + for table in self.tables: + table.toXML(writer, ttFont) + + def fromXML(self, name, attrs, content, ttFont): + if name == "tableVersion": + self.tableVersion = safeEval(attrs["version"]) + return + if name[:12] != "cmap_format_": + return + if not hasattr(self, "tables"): + self.tables = [] + format = safeEval(name[12:]) + table = CmapSubtable.newSubtable(format) + table.platformID = safeEval(attrs["platformID"]) + table.platEncID = safeEval(attrs["platEncID"]) + table.fromXML(name, attrs, content, ttFont) + self.tables.append(table) + + +class CmapSubtable(object): + """Base class for all cmap subtable formats. + + Subclasses which handle the individual subtable formats are named + ``cmap_format_0``, ``cmap_format_2`` etc. Use :py:meth:`getSubtableClass` + to retrieve the concrete subclass, or :py:meth:`newSubtable` to get a + new subtable object for a given format. + + The object exposes a ``.cmap`` attribute, which contains a dictionary mapping + character codepoints to glyph names. + """ + + headerFormat = ">HHH" + + @staticmethod + def getSubtableClass(format): + """Return the subtable class for a format.""" + return cmap_classes.get(format, cmap_format_unknown) + + @staticmethod + def newSubtable(format): + """Return a new instance of a subtable for the given format + .""" + subtableClass = CmapSubtable.getSubtableClass(format) + return subtableClass(format) + + def __init__(self, format): + self.format = format + self.data = None + self.ttFont = None + self.platformID = None #: The platform ID of this subtable + self.platEncID = None #: The encoding ID of this subtable (interpretation depends on ``platformID``) + self.language = ( + None #: The language ID of this subtable (Macintosh platform only) + ) + + def ensureDecompiled(self, recurse=False): + # The recurse argument is unused, but part of the signature of + # ensureDecompiled across the library. + if self.data is None: + return + self.decompile(None, None) # use saved data. + self.data = None # Once this table has been decompiled, make sure we don't + # just return the original data. Also avoids recursion when + # called with an attribute that the cmap subtable doesn't have. + + def __getattr__(self, attr): + # allow lazy decompilation of subtables. + if attr[:2] == "__": # don't handle requests for member functions like '__lt__' + raise AttributeError(attr) + if self.data is None: + raise AttributeError(attr) + self.ensureDecompiled() + return getattr(self, attr) + + def decompileHeader(self, data, ttFont): + headerSize = struct.calcsize(self.headerFormat) + format, length, language = struct.unpack(self.headerFormat, data[:headerSize]) + assert ( + len(data) == length + ), "corrupt cmap table format %d (data length: %d, header length: %d)" % ( + format, + len(data), + length, + ) + self.format = int(format) + self.length = int(length) + self.language = int(language) + self.data = data[headerSize:] + self.ttFont = ttFont + + def toXML(self, writer, ttFont): + writer.begintag( + self.__class__.__name__, + [ + ("platformID", self.platformID), + ("platEncID", self.platEncID), + ("language", self.language), + ], + ) + writer.newline() + codes = sorted(self.cmap.items()) + self._writeCodes(codes, writer) + writer.endtag(self.__class__.__name__) + writer.newline() + + def getEncoding(self, default=None): + """Returns the Python encoding name for this cmap subtable based on its platformID, + platEncID, and language. If encoding for these values is not known, by default + ``None`` is returned. That can be overridden by passing a value to the ``default`` + argument. + + Note that if you want to choose a "preferred" cmap subtable, most of the time + ``self.isUnicode()`` is what you want as that one only returns true for the modern, + commonly used, Unicode-compatible triplets, not the legacy ones. + """ + return getEncoding(self.platformID, self.platEncID, self.language, default) + + def isUnicode(self): + """Returns true if the characters are interpreted as Unicode codepoints.""" + return self.platformID == 0 or ( + self.platformID == 3 and self.platEncID in [0, 1, 10] + ) + + def isSymbol(self): + """Returns true if the subtable is for the Symbol encoding (3,0)""" + return self.platformID == 3 and self.platEncID == 0 + + def _writeCodes(self, codes, writer): + isUnicode = self.isUnicode() + for code, name in codes: + writer.simpletag("map", code=hex(code), name=name) + if isUnicode: + writer.comment(Unicode[code]) + writer.newline() + + def __lt__(self, other): + if not isinstance(other, CmapSubtable): + return NotImplemented + + # implemented so that list.sort() sorts according to the spec. + selfTuple = ( + getattr(self, "platformID", None), + getattr(self, "platEncID", None), + getattr(self, "language", None), + ) + otherTuple = ( + getattr(other, "platformID", None), + getattr(other, "platEncID", None), + getattr(other, "language", None), + ) + return selfTuple < otherTuple + + +class cmap_format_0(CmapSubtable): + def decompile(self, data, ttFont): + # we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None. + # If not, someone is calling the subtable decompile() directly, and must provide both args. + if data is not None and ttFont is not None: + self.decompileHeader(data, ttFont) + else: + assert ( + data is None and ttFont is None + ), "Need both data and ttFont arguments" + data = ( + self.data + ) # decompileHeader assigns the data after the header to self.data + assert 262 == self.length, "Format 0 cmap subtable not 262 bytes" + gids = array.array("B") + gids.frombytes(self.data) + charCodes = range(len(gids)) + self.cmap = _make_map(self.ttFont, charCodes, gids) + + def compile(self, ttFont): + if self.data: + return struct.pack(">HHH", 0, 262, self.language) + self.data + + cmap = self.cmap + assert set(cmap.keys()).issubset(range(256)) + getGlyphID = ttFont.getGlyphID + valueList = [getGlyphID(cmap[i]) if i in cmap else 0 for i in range(256)] + + gids = array.array("B", valueList) + data = struct.pack(">HHH", 0, 262, self.language) + gids.tobytes() + assert len(data) == 262 + return data + + def fromXML(self, name, attrs, content, ttFont): + self.language = safeEval(attrs["language"]) + if not hasattr(self, "cmap"): + self.cmap = {} + cmap = self.cmap + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name != "map": + continue + cmap[safeEval(attrs["code"])] = attrs["name"] + + +subHeaderFormat = ">HHhH" + + +class SubHeader(object): + def __init__(self): + self.firstCode = None + self.entryCount = None + self.idDelta = None + self.idRangeOffset = None + self.glyphIndexArray = [] + + +class cmap_format_2(CmapSubtable): + def setIDDelta(self, subHeader): + subHeader.idDelta = 0 + # An empty subheader (an all-notdef two-byte range) has no glyphs to + # adjust, so leave idDelta at 0 and bail before indexing the array. + if not subHeader.glyphIndexArray: + return + # find the minGI which is not zero. + minGI = subHeader.glyphIndexArray[0] + for gid in subHeader.glyphIndexArray: + if (gid != 0) and (gid < minGI): + minGI = gid + # The lowest gid in glyphIndexArray, after subtracting idDelta, must be 1. + # idDelta is a short, and must be between -32K and 32K. minGI can be between 1 and 64K. + # We would like to pick an idDelta such that the first glyphArray GID is 1, + # so that we are more likely to be able to combine glypharray GID subranges. + # This means that we have a problem when minGI is > 32K + # Since the final gi is reconstructed from the glyphArray GID by: + # (short)finalGID = (gid + idDelta) % 0x10000), + # we can get from a glypharray GID of 1 to a final GID of 65K by subtracting 2, and casting the + # negative number to an unsigned short. + + if minGI > 1: + if minGI > 0x7FFF: + subHeader.idDelta = -(0x10000 - minGI) - 1 + else: + subHeader.idDelta = minGI - 1 + idDelta = subHeader.idDelta + for i in range(subHeader.entryCount): + gid = subHeader.glyphIndexArray[i] + if gid > 0: + subHeader.glyphIndexArray[i] = gid - idDelta + + def decompile(self, data, ttFont): + # we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None. + # If not, someone is calling the subtable decompile() directly, and must provide both args. + if data is not None and ttFont is not None: + self.decompileHeader(data, ttFont) + else: + assert ( + data is None and ttFont is None + ), "Need both data and ttFont arguments" + + data = ( + self.data + ) # decompileHeader assigns the data after the header to self.data + subHeaderKeys = [] + maxSubHeaderindex = 0 + # get the key array, and determine the number of subHeaders. + allKeys = array.array("H") + allKeys.frombytes(data[:512]) + data = data[512:] + if sys.byteorder != "big": + allKeys.byteswap() + subHeaderKeys = [key // 8 for key in allKeys] + maxSubHeaderindex = max(subHeaderKeys) + + # Load subHeaders + subHeaderList = [] + pos = 0 + for i in range(maxSubHeaderindex + 1): + subHeader = SubHeader() + ( + subHeader.firstCode, + subHeader.entryCount, + subHeader.idDelta, + subHeader.idRangeOffset, + ) = struct.unpack(subHeaderFormat, data[pos : pos + 8]) + pos += 8 + giDataPos = pos + subHeader.idRangeOffset - 2 + giList = array.array("H") + giList.frombytes(data[giDataPos : giDataPos + subHeader.entryCount * 2]) + if sys.byteorder != "big": + giList.byteswap() + subHeader.glyphIndexArray = giList + subHeaderList.append(subHeader) + # How this gets processed. + # Charcodes may be one or two bytes. + # The first byte of a charcode is mapped through the subHeaderKeys, to select + # a subHeader. For any subheader but 0, the next byte is then mapped through the + # selected subheader. If subheader Index 0 is selected, then the byte itself is + # mapped through the subheader, and there is no second byte. + # Then assume that the subsequent byte is the first byte of the next charcode,and repeat. + # + # Each subheader references a range in the glyphIndexArray whose length is entryCount. + # The range in glyphIndexArray referenced by a sunheader may overlap with the range in glyphIndexArray + # referenced by another subheader. + # The only subheader that will be referenced by more than one first-byte value is the subheader + # that maps the entire range of glyphID values to glyphIndex 0, e.g notdef: + # {firstChar 0, EntryCount 0,idDelta 0,idRangeOffset xx} + # A byte being mapped though a subheader is treated as in index into a mapping of array index to font glyphIndex. + # A subheader specifies a subrange within (0...256) by the + # firstChar and EntryCount values. If the byte value is outside the subrange, then the glyphIndex is zero + # (e.g. glyph not in font). + # If the byte index is in the subrange, then an offset index is calculated as (byteIndex - firstChar). + # The index to glyphIndex mapping is a subrange of the glyphIndexArray. You find the start of the subrange by + # counting idRangeOffset bytes from the idRangeOffset word. The first value in this subrange is the + # glyphIndex for the index firstChar. The offset index should then be used in this array to get the glyphIndex. + # Example for Logocut-Medium + # first byte of charcode = 129; selects subheader 1. + # subheader 1 = {firstChar 64, EntryCount 108,idDelta 42,idRangeOffset 0252} + # second byte of charCode = 66 + # the index offset = 66-64 = 2. + # The subrange of the glyphIndexArray starting at 0x0252 bytes from the idRangeOffset word is: + # [glyphIndexArray index], [subrange array index] = glyphIndex + # [256], [0]=1 from charcode [129, 64] + # [257], [1]=2 from charcode [129, 65] + # [258], [2]=3 from charcode [129, 66] + # [259], [3]=4 from charcode [129, 67] + # So, the glyphIndex = 3 from the array. Then if idDelta is not zero and the glyph ID is not zero, + # add it to the glyphID to get the final glyphIndex + # value. In this case the final glyph index = 3+ 42 -> 45 for the final glyphIndex. Whew! + + self.data = b"" + cmap = {} + notdefGI = 0 + for firstByte in range(256): + subHeadindex = subHeaderKeys[firstByte] + subHeader = subHeaderList[subHeadindex] + if subHeadindex == 0: + if (firstByte < subHeader.firstCode) or ( + firstByte >= subHeader.firstCode + subHeader.entryCount + ): + continue # gi is notdef. + else: + charCode = firstByte + offsetIndex = firstByte - subHeader.firstCode + gi = subHeader.glyphIndexArray[offsetIndex] + if gi != 0: + gi = (gi + subHeader.idDelta) % 0x10000 + else: + continue # gi is notdef. + cmap[charCode] = gi + else: + if subHeader.entryCount: + charCodeOffset = firstByte * 256 + subHeader.firstCode + for offsetIndex in range(subHeader.entryCount): + charCode = charCodeOffset + offsetIndex + gi = subHeader.glyphIndexArray[offsetIndex] + if gi != 0: + gi = (gi + subHeader.idDelta) % 0x10000 + else: + continue + cmap[charCode] = gi + # If not subHeader.entryCount, then all char codes with this first byte are + # mapped to .notdef. We can skip this subtable, and leave the glyphs un-encoded, which is the + # same as mapping it to .notdef. + + gids = list(cmap.values()) + charCodes = list(cmap.keys()) + self.cmap = _make_map(self.ttFont, charCodes, gids) + + def compile(self, ttFont): + if self.data: + return ( + struct.pack(">HHH", self.format, self.length, self.language) + self.data + ) + kEmptyTwoCharCodeRange = -1 + notdefGI = 0 + + items = sorted(self.cmap.items()) + charCodes = [item[0] for item in items] + names = [item[1] for item in items] + nameMap = ttFont.getReverseGlyphMap() + try: + gids = [nameMap[name] for name in names] + except KeyError: + nameMap = ttFont.getReverseGlyphMap(rebuild=True) + try: + gids = [nameMap[name] for name in names] + except KeyError: + # allow virtual GIDs in format 2 tables + gids = [] + for name in names: + try: + gid = nameMap[name] + except KeyError: + try: + if name[:3] == "gid": + gid = int(name[3:]) + else: + gid = ttFont.getGlyphID(name) + except: + raise KeyError(name) + + gids.append(gid) + + # Process the (char code to gid) item list in char code order. + # By definition, all one byte char codes map to subheader 0. + # For all the two byte char codes, we assume that the first byte maps maps to the empty subhead (with an entry count of 0, + # which defines all char codes in its range to map to notdef) unless proven otherwise. + # Note that since the char code items are processed in char code order, all the char codes with the + # same first byte are in sequential order. + + subHeaderKeys = [ + kEmptyTwoCharCodeRange for x in range(256) + ] # list of indices into subHeaderList. + subHeaderList = [] + + # We force this subheader entry 0 to exist in the subHeaderList in the case where some one comes up + # with a cmap where all the one byte char codes map to notdef, + # with the result that the subhead 0 would not get created just by processing the item list. + # The same is true for an entirely empty (all-notdef) cmap, where there + # are no char codes to process at all. + if not charCodes or charCodes[0] > 255: + subHeader = SubHeader() + subHeader.firstCode = 0 + subHeader.entryCount = 0 + subHeader.idDelta = 0 + subHeader.idRangeOffset = 0 + subHeaderList.append(subHeader) + + lastFirstByte = -1 + items = zip(charCodes, gids) + for charCode, gid in items: + if gid == 0: + continue + firstbyte = charCode >> 8 + secondByte = charCode & 0x00FF + + if ( + firstbyte != lastFirstByte + ): # Need to update the current subhead, and start a new one. + if lastFirstByte > -1: + # fix GI's and iDelta of current subheader. + self.setIDDelta(subHeader) + + # If it was sunheader 0 for one-byte charCodes, then we need to set the subHeaderKeys value to zero + # for the indices matching the char codes. + if lastFirstByte == 0: + for index in range(subHeader.entryCount): + charCode = subHeader.firstCode + index + subHeaderKeys[charCode] = 0 + + assert subHeader.entryCount == len( + subHeader.glyphIndexArray + ), "Error - subhead entry count does not match len of glyphID subrange." + # init new subheader + subHeader = SubHeader() + subHeader.firstCode = secondByte + subHeader.entryCount = 1 + subHeader.glyphIndexArray.append(gid) + subHeaderList.append(subHeader) + subHeaderKeys[firstbyte] = len(subHeaderList) - 1 + lastFirstByte = firstbyte + else: + # need to fill in with notdefs all the code points between the last charCode and the current charCode. + codeDiff = secondByte - (subHeader.firstCode + subHeader.entryCount) + for i in range(codeDiff): + subHeader.glyphIndexArray.append(notdefGI) + subHeader.glyphIndexArray.append(gid) + subHeader.entryCount = subHeader.entryCount + codeDiff + 1 + + # fix GI's and iDelta of last subheader that we we added to the subheader array. + self.setIDDelta(subHeader) + + # Now we add a final subheader for the subHeaderKeys which maps to empty two byte charcode ranges. + subHeader = SubHeader() + subHeader.firstCode = 0 + subHeader.entryCount = 0 + subHeader.idDelta = 0 + subHeader.idRangeOffset = 2 + subHeaderList.append(subHeader) + emptySubheadIndex = len(subHeaderList) - 1 + for index in range(256): + if subHeaderKeys[index] == kEmptyTwoCharCodeRange: + subHeaderKeys[index] = emptySubheadIndex + # Since this is the last subheader, the GlyphIndex Array starts two bytes after the start of the + # idRangeOffset word of this subHeader. We can safely point to the first entry in the GlyphIndexArray, + # since the first subrange of the GlyphIndexArray is for subHeader 0, which always starts with + # charcode 0 and GID 0. + + idRangeOffset = ( + len(subHeaderList) - 1 + ) * 8 + 2 # offset to beginning of glyphIDArray from first subheader idRangeOffset. + subheadRangeLen = ( + len(subHeaderList) - 1 + ) # skip last special empty-set subheader; we've already hardocodes its idRangeOffset to 2. + for index in range(subheadRangeLen): + subHeader = subHeaderList[index] + subHeader.idRangeOffset = 0 + for j in range(index): + prevSubhead = subHeaderList[j] + if ( + prevSubhead.glyphIndexArray == subHeader.glyphIndexArray + ): # use the glyphIndexArray subarray + subHeader.idRangeOffset = ( + prevSubhead.idRangeOffset - (index - j) * 8 + ) + subHeader.glyphIndexArray = [] + break + if subHeader.idRangeOffset == 0: # didn't find one. + subHeader.idRangeOffset = idRangeOffset + idRangeOffset = ( + idRangeOffset - 8 + ) + subHeader.entryCount * 2 # one less subheader, one more subArray. + else: + idRangeOffset = idRangeOffset - 8 # one less subheader + + # Now we can write out the data! + length = ( + 6 + 512 + 8 * len(subHeaderList) + ) # header, 256 subHeaderKeys, and subheader array. + for subhead in subHeaderList[:-1]: + length = ( + length + len(subhead.glyphIndexArray) * 2 + ) # We can't use subhead.entryCount, as some of the subhead may share subArrays. + dataList = [struct.pack(">HHH", 2, length, self.language)] + for index in subHeaderKeys: + dataList.append(struct.pack(">H", index * 8)) + for subhead in subHeaderList: + dataList.append( + struct.pack( + subHeaderFormat, + subhead.firstCode, + subhead.entryCount, + subhead.idDelta, + subhead.idRangeOffset, + ) + ) + for subhead in subHeaderList[:-1]: + for gi in subhead.glyphIndexArray: + dataList.append(struct.pack(">H", gi)) + data = bytesjoin(dataList) + assert len(data) == length, ( + "Error: cmap format 2 is not same length as calculated! actual: " + + str(len(data)) + + " calc : " + + str(length) + ) + return data + + def fromXML(self, name, attrs, content, ttFont): + self.language = safeEval(attrs["language"]) + if not hasattr(self, "cmap"): + self.cmap = {} + cmap = self.cmap + + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name != "map": + continue + cmap[safeEval(attrs["code"])] = attrs["name"] + + +cmap_format_4_format = ">7H" + +# uint16 endCode[segCount] # Ending character code for each segment, last = 0xFFFF. +# uint16 reservedPad # This value should be zero +# uint16 startCode[segCount] # Starting character code for each segment +# uint16 idDelta[segCount] # Delta for all character codes in segment +# uint16 idRangeOffset[segCount] # Offset in bytes to glyph indexArray, or 0 +# uint16 glyphIndexArray[variable] # Glyph index array + + +def splitRange(startCode, endCode, cmap): + # Try to split a range of character codes into subranges with consecutive + # glyph IDs in such a way that the cmap4 subtable can be stored "most" + # efficiently. I can't prove I've got the optimal solution, but it seems + # to do well with the fonts I tested: none became bigger, many became smaller. + if startCode == endCode: + return [], [endCode] + + lastID = cmap[startCode] + lastCode = startCode + inOrder = None + orderedBegin = None + subRanges = [] + + # Gather subranges in which the glyph IDs are consecutive. + for code in range(startCode + 1, endCode + 1): + glyphID = cmap[code] + + if glyphID - 1 == lastID: + if inOrder is None or not inOrder: + inOrder = 1 + orderedBegin = lastCode + else: + if inOrder: + inOrder = 0 + subRanges.append((orderedBegin, lastCode)) + orderedBegin = None + + lastID = glyphID + lastCode = code + + if inOrder: + subRanges.append((orderedBegin, lastCode)) + assert lastCode == endCode + + # Now filter out those new subranges that would only make the data bigger. + # A new segment cost 8 bytes, not using a new segment costs 2 bytes per + # character. + newRanges = [] + for b, e in subRanges: + if b == startCode and e == endCode: + break # the whole range, we're fine + if b == startCode or e == endCode: + threshold = 4 # split costs one more segment + else: + threshold = 8 # split costs two more segments + if (e - b + 1) > threshold: + newRanges.append((b, e)) + subRanges = newRanges + + if not subRanges: + return [], [endCode] + + if subRanges[0][0] != startCode: + subRanges.insert(0, (startCode, subRanges[0][0] - 1)) + if subRanges[-1][1] != endCode: + subRanges.append((subRanges[-1][1] + 1, endCode)) + + # Fill the "holes" in the segments list -- those are the segments in which + # the glyph IDs are _not_ consecutive. + i = 1 + while i < len(subRanges): + if subRanges[i - 1][1] + 1 != subRanges[i][0]: + subRanges.insert(i, (subRanges[i - 1][1] + 1, subRanges[i][0] - 1)) + i = i + 1 + i = i + 1 + + # Transform the ranges into startCode/endCode lists. + start = [] + end = [] + for b, e in subRanges: + start.append(b) + end.append(e) + start.pop(0) + + assert len(start) + 1 == len(end) + return start, end + + +class cmap_format_4(CmapSubtable): + def decompile(self, data, ttFont): + # we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None. + # If not, someone is calling the subtable decompile() directly, and must provide both args. + if data is not None and ttFont is not None: + self.decompileHeader(data, ttFont) + else: + assert ( + data is None and ttFont is None + ), "Need both data and ttFont arguments" + + data = ( + self.data + ) # decompileHeader assigns the data after the header to self.data + segCountX2, searchRange, entrySelector, rangeShift = struct.unpack( + ">4H", data[:8] + ) + data = data[8:] + segCount = segCountX2 // 2 + + allCodes = array.array("H") + allCodes.frombytes(data) + self.data = data = None + + if sys.byteorder != "big": + allCodes.byteswap() + + # divide the data + endCode = allCodes[:segCount] + allCodes = allCodes[segCount + 1 :] # the +1 is skipping the reservedPad field + startCode = allCodes[:segCount] + allCodes = allCodes[segCount:] + idDelta = allCodes[:segCount] + allCodes = allCodes[segCount:] + idRangeOffset = allCodes[:segCount] + glyphIndexArray = allCodes[segCount:] + lenGIArray = len(glyphIndexArray) + + # build 2-byte character mapping + charCodes = [] + gids = [] + for i in range(len(startCode) - 1): # don't do 0xffff! + start = startCode[i] + delta = idDelta[i] + rangeOffset = idRangeOffset[i] + partial = rangeOffset // 2 - start + i - len(idRangeOffset) + + rangeCharCodes = list(range(startCode[i], endCode[i] + 1)) + charCodes.extend(rangeCharCodes) + if rangeOffset == 0: + gids.extend( + [(charCode + delta) & 0xFFFF for charCode in rangeCharCodes] + ) + else: + for charCode in rangeCharCodes: + index = charCode + partial + assert index < lenGIArray, ( + "In format 4 cmap, range (%d), the calculated index (%d) into the glyph index array is not less than the length of the array (%d) !" + % (i, index, lenGIArray) + ) + if glyphIndexArray[index] != 0: # if not missing glyph + glyphID = glyphIndexArray[index] + delta + else: + glyphID = 0 # missing glyph + gids.append(glyphID & 0xFFFF) + + self.cmap = _make_map(self.ttFont, charCodes, gids) + + def compile(self, ttFont): + if self.data: + return ( + struct.pack(">HHH", self.format, self.length, self.language) + self.data + ) + + charCodes = list(self.cmap.keys()) + if not charCodes: + startCode = [0xFFFF] + endCode = [0xFFFF] + else: + charCodes.sort() + names = [self.cmap[code] for code in charCodes] + nameMap = ttFont.getReverseGlyphMap() + try: + gids = [nameMap[name] for name in names] + except KeyError: + nameMap = ttFont.getReverseGlyphMap(rebuild=True) + try: + gids = [nameMap[name] for name in names] + except KeyError: + # allow virtual GIDs in format 4 tables + gids = [] + for name in names: + try: + gid = nameMap[name] + except KeyError: + try: + if name[:3] == "gid": + gid = int(name[3:]) + else: + gid = ttFont.getGlyphID(name) + except: + raise KeyError(name) + + gids.append(gid) + cmap = {} # code:glyphID mapping + for code, gid in zip(charCodes, gids): + cmap[code] = gid + + # Build startCode and endCode lists. + # Split the char codes in ranges of consecutive char codes, then split + # each range in more ranges of consecutive/not consecutive glyph IDs. + # See splitRange(). + lastCode = charCodes[0] + endCode = [] + startCode = [lastCode] + for charCode in charCodes[ + 1: + ]: # skip the first code, it's the first start code + if charCode == lastCode + 1: + lastCode = charCode + continue + start, end = splitRange(startCode[-1], lastCode, cmap) + startCode.extend(start) + endCode.extend(end) + startCode.append(charCode) + lastCode = charCode + start, end = splitRange(startCode[-1], lastCode, cmap) + startCode.extend(start) + endCode.extend(end) + startCode.append(0xFFFF) + endCode.append(0xFFFF) + + # build up rest of cruft + idDelta = [] + idRangeOffset = [] + glyphIndexArray = [] + for i in range(len(endCode) - 1): # skip the closing codes (0xffff) + indices = [] + for charCode in range(startCode[i], endCode[i] + 1): + indices.append(cmap[charCode]) + if indices == list(range(indices[0], indices[0] + len(indices))): + idDelta.append((indices[0] - startCode[i]) % 0x10000) + idRangeOffset.append(0) + else: + idDelta.append(0) + idRangeOffset.append(2 * (len(endCode) + len(glyphIndexArray) - i)) + glyphIndexArray.extend(indices) + idDelta.append(1) # 0xffff + 1 == (tadaa!) 0. So this end code maps to .notdef + idRangeOffset.append(0) + + # Insane. + segCount = len(endCode) + segCountX2 = segCount * 2 + searchRange, entrySelector, rangeShift = getSearchRange(segCount, 2) + + charCodeArray = array.array("H", endCode + [0] + startCode) + idDeltaArray = array.array("H", idDelta) + restArray = array.array("H", idRangeOffset + glyphIndexArray) + if sys.byteorder != "big": + charCodeArray.byteswap() + if sys.byteorder != "big": + idDeltaArray.byteswap() + if sys.byteorder != "big": + restArray.byteswap() + data = charCodeArray.tobytes() + idDeltaArray.tobytes() + restArray.tobytes() + + length = struct.calcsize(cmap_format_4_format) + len(data) + header = struct.pack( + cmap_format_4_format, + self.format, + length, + self.language, + segCountX2, + searchRange, + entrySelector, + rangeShift, + ) + return header + data + + def fromXML(self, name, attrs, content, ttFont): + self.language = safeEval(attrs["language"]) + if not hasattr(self, "cmap"): + self.cmap = {} + cmap = self.cmap + + for element in content: + if not isinstance(element, tuple): + continue + nameMap, attrsMap, dummyContent = element + if nameMap != "map": + assert 0, "Unrecognized keyword in cmap subtable" + cmap[safeEval(attrsMap["code"])] = attrsMap["name"] + + +class cmap_format_6(CmapSubtable): + def decompile(self, data, ttFont): + # we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None. + # If not, someone is calling the subtable decompile() directly, and must provide both args. + if data is not None and ttFont is not None: + self.decompileHeader(data, ttFont) + else: + assert ( + data is None and ttFont is None + ), "Need both data and ttFont arguments" + + data = ( + self.data + ) # decompileHeader assigns the data after the header to self.data + firstCode, entryCount = struct.unpack(">HH", data[:4]) + firstCode = int(firstCode) + data = data[4:] + # assert len(data) == 2 * entryCount # XXX not true in Apple's Helvetica!!! + gids = array.array("H") + gids.frombytes(data[: 2 * int(entryCount)]) + if sys.byteorder != "big": + gids.byteswap() + self.data = data = None + + charCodes = list(range(firstCode, firstCode + len(gids))) + self.cmap = _make_map(self.ttFont, charCodes, gids) + + def compile(self, ttFont): + if self.data: + return ( + struct.pack(">HHH", self.format, self.length, self.language) + self.data + ) + cmap = self.cmap + codes = sorted(cmap.keys()) + if codes: # yes, there are empty cmap tables. + codes = list(range(codes[0], codes[-1] + 1)) + firstCode = codes[0] + valueList = [ + ttFont.getGlyphID(cmap[code]) if code in cmap else 0 for code in codes + ] + gids = array.array("H", valueList) + if sys.byteorder != "big": + gids.byteswap() + data = gids.tobytes() + else: + data = b"" + firstCode = 0 + header = struct.pack( + ">HHHHH", 6, len(data) + 10, self.language, firstCode, len(codes) + ) + return header + data + + def fromXML(self, name, attrs, content, ttFont): + self.language = safeEval(attrs["language"]) + if not hasattr(self, "cmap"): + self.cmap = {} + cmap = self.cmap + + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name != "map": + continue + cmap[safeEval(attrs["code"])] = attrs["name"] + + +class cmap_format_12_or_13(CmapSubtable): + headerFormat = ">HHLLL" + + def __init__(self, format): + self.format = format + self.reserved = 0 + self.data = None + self.ttFont = None + + def decompileHeader(self, data, ttFont): + headerSize = struct.calcsize(self.headerFormat) + format, reserved, length, language, nGroups = struct.unpack( + self.headerFormat, data[:headerSize] + ) + if len(data) != length: + raise TTLibError( + "cmap subtable format %d is truncated: length %d, got %d bytes" + % (self.format, length, len(data)) + ) + expectedLength = headerSize + nGroups * 12 + if length != expectedLength: + raise TTLibError( + "cmap subtable format %d has an inconsistent group count: " + "length %d, but %d groups need %d bytes" + % (self.format, length, nGroups, expectedLength) + ) + self.format = format + self.reserved = reserved + self.length = length + self.language = language + self.nGroups = nGroups + self.data = data[headerSize:] + self.ttFont = ttFont + + def decompile(self, data, ttFont): + # we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None. + # If not, someone is calling the subtable decompile() directly, and must provide both args. + if data is not None and ttFont is not None: + self.decompileHeader(data, ttFont) + else: + assert ( + data is None and ttFont is None + ), "Need both data and ttFont arguments" + + data = ( + self.data + ) # decompileHeader assigns the data after the header to self.data + charCodes = [] + gids = [] + pos = 0 + groups = array.array("I", data[: self.nGroups * 12]) + if sys.byteorder != "big": + groups.byteswap() + for i in range(self.nGroups): + startCharCode = groups[i * 3] + endCharCode = groups[i * 3 + 1] + glyphID = groups[i * 3 + 2] + lenGroup = 1 + endCharCode - startCharCode + charCodes.extend(range(startCharCode, endCharCode + 1)) + gids.extend(self._computeGIDs(glyphID, lenGroup)) + self.data = data = None + self.cmap = _make_map(self.ttFont, charCodes, gids) + + def compile(self, ttFont): + if self.data: + return ( + struct.pack( + ">HHLLL", + self.format, + self.reserved, + self.length, + self.language, + self.nGroups, + ) + + self.data + ) + charCodes = list(self.cmap.keys()) + names = list(self.cmap.values()) + nameMap = ttFont.getReverseGlyphMap() + try: + gids = [nameMap[name] for name in names] + except KeyError: + nameMap = ttFont.getReverseGlyphMap(rebuild=True) + try: + gids = [nameMap[name] for name in names] + except KeyError: + # allow virtual GIDs in format 12 tables + gids = [] + for name in names: + try: + gid = nameMap[name] + except KeyError: + try: + if name[:3] == "gid": + gid = int(name[3:]) + else: + gid = ttFont.getGlyphID(name) + except: + raise KeyError(name) + + gids.append(gid) + + cmap = {} # code:glyphID mapping + for code, gid in zip(charCodes, gids): + cmap[code] = gid + + charCodes.sort() + index = 0 + startCharCode = charCodes[0] + startGlyphID = cmap[startCharCode] + lastGlyphID = startGlyphID - self._format_step + lastCharCode = startCharCode - 1 + nGroups = 0 + dataList = [] + maxIndex = len(charCodes) + for index in range(maxIndex): + charCode = charCodes[index] + glyphID = cmap[charCode] + if not self._IsInSameRun(glyphID, lastGlyphID, charCode, lastCharCode): + dataList.append( + struct.pack(">LLL", startCharCode, lastCharCode, startGlyphID) + ) + startCharCode = charCode + startGlyphID = glyphID + nGroups = nGroups + 1 + lastGlyphID = glyphID + lastCharCode = charCode + dataList.append(struct.pack(">LLL", startCharCode, lastCharCode, startGlyphID)) + nGroups = nGroups + 1 + data = bytesjoin(dataList) + lengthSubtable = len(data) + 16 + assert len(data) == (nGroups * 12) == (lengthSubtable - 16) + return ( + struct.pack( + ">HHLLL", + self.format, + self.reserved, + lengthSubtable, + self.language, + nGroups, + ) + + data + ) + + def toXML(self, writer, ttFont): + writer.begintag( + self.__class__.__name__, + [ + ("platformID", self.platformID), + ("platEncID", self.platEncID), + ("format", self.format), + ("reserved", self.reserved), + ("length", self.length), + ("language", self.language), + ("nGroups", self.nGroups), + ], + ) + writer.newline() + codes = sorted(self.cmap.items()) + self._writeCodes(codes, writer) + writer.endtag(self.__class__.__name__) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + self.format = safeEval(attrs["format"]) + self.reserved = safeEval(attrs["reserved"]) + self.length = safeEval(attrs["length"]) + self.language = safeEval(attrs["language"]) + self.nGroups = safeEval(attrs["nGroups"]) + if not hasattr(self, "cmap"): + self.cmap = {} + cmap = self.cmap + + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name != "map": + continue + cmap[safeEval(attrs["code"])] = attrs["name"] + + +class cmap_format_12(cmap_format_12_or_13): + _format_step = 1 + + def __init__(self, format=12): + cmap_format_12_or_13.__init__(self, format) + + def _computeGIDs(self, startingGlyph, numberOfGlyphs): + return range(startingGlyph, startingGlyph + numberOfGlyphs) + + def _IsInSameRun(self, glyphID, lastGlyphID, charCode, lastCharCode): + return (glyphID == 1 + lastGlyphID) and (charCode == 1 + lastCharCode) + + +class cmap_format_13(cmap_format_12_or_13): + _format_step = 0 + + def __init__(self, format=13): + cmap_format_12_or_13.__init__(self, format) + + def _computeGIDs(self, startingGlyph, numberOfGlyphs): + return [startingGlyph] * numberOfGlyphs + + def _IsInSameRun(self, glyphID, lastGlyphID, charCode, lastCharCode): + return (glyphID == lastGlyphID) and (charCode == 1 + lastCharCode) + + +def cvtToUVS(threeByteString): + data = b"\0" + threeByteString + (val,) = struct.unpack(">L", data) + return val + + +def cvtFromUVS(val): + assert 0 <= val < 0x1000000 + fourByteString = struct.pack(">L", val) + return fourByteString[1:] + + +class cmap_format_14(CmapSubtable): + headerFormat = ">HLL" + + def decompileHeader(self, data, ttFont): + headerSize = struct.calcsize(self.headerFormat) + format, length, numVarSelectorRecords = struct.unpack( + self.headerFormat, data[:headerSize] + ) + self.data = data[headerSize:] + self.length = length + self.numVarSelectorRecords = numVarSelectorRecords + self.ttFont = ttFont + self.language = 0xFF # has no language. + + def decompile(self, data, ttFont): + if data is not None and ttFont is not None: + self.decompileHeader(data, ttFont) + else: + assert ( + data is None and ttFont is None + ), "Need both data and ttFont arguments" + data = self.data + + self.cmap = ( + {} + ) # so that clients that expect this to exist in a cmap table won't fail. + uvsDict = {} + recOffset = 0 + for n in range(self.numVarSelectorRecords): + uvs, defOVSOffset, nonDefUVSOffset = struct.unpack( + ">3sLL", data[recOffset : recOffset + 11] + ) + recOffset += 11 + varUVS = cvtToUVS(uvs) + if defOVSOffset: + startOffset = defOVSOffset - 10 + (numValues,) = struct.unpack(">L", data[startOffset : startOffset + 4]) + startOffset += 4 + for r in range(numValues): + uv, addtlCnt = struct.unpack( + ">3sB", data[startOffset : startOffset + 4] + ) + startOffset += 4 + firstBaseUV = cvtToUVS(uv) + cnt = addtlCnt + 1 + baseUVList = list(range(firstBaseUV, firstBaseUV + cnt)) + glyphList = [None] * cnt + localUVList = zip(baseUVList, glyphList) + try: + uvsDict[varUVS].extend(localUVList) + except KeyError: + uvsDict[varUVS] = list(localUVList) + + if nonDefUVSOffset: + startOffset = nonDefUVSOffset - 10 + (numRecs,) = struct.unpack(">L", data[startOffset : startOffset + 4]) + startOffset += 4 + localUVList = [] + for r in range(numRecs): + uv, gid = struct.unpack(">3sH", data[startOffset : startOffset + 5]) + startOffset += 5 + uv = cvtToUVS(uv) + glyphName = self.ttFont.getGlyphName(gid) + localUVList.append((uv, glyphName)) + try: + uvsDict[varUVS].extend(localUVList) + except KeyError: + uvsDict[varUVS] = localUVList + + self.uvsDict = uvsDict + + def toXML(self, writer, ttFont): + writer.begintag( + self.__class__.__name__, + [ + ("platformID", self.platformID), + ("platEncID", self.platEncID), + ], + ) + writer.newline() + uvsDict = self.uvsDict + uvsList = sorted(uvsDict.keys()) + for uvs in uvsList: + uvList = uvsDict[uvs] + uvList.sort(key=lambda item: (item[1] is not None, item[0], item[1])) + for uv, gname in uvList: + attrs = [("uv", hex(uv)), ("uvs", hex(uvs))] + if gname is not None: + attrs.append(("name", gname)) + writer.simpletag("map", attrs) + writer.newline() + writer.endtag(self.__class__.__name__) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + self.language = 0xFF # provide a value so that CmapSubtable.__lt__() won't fail + if not hasattr(self, "cmap"): + self.cmap = ( + {} + ) # so that clients that expect this to exist in a cmap table won't fail. + if not hasattr(self, "uvsDict"): + self.uvsDict = {} + uvsDict = self.uvsDict + + # For backwards compatibility reasons we accept "None" as an indicator + # for "default mapping", unless the font actually has a glyph named + # "None". + _hasGlyphNamedNone = None + + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name != "map": + continue + uvs = safeEval(attrs["uvs"]) + uv = safeEval(attrs["uv"]) + gname = attrs.get("name") + if gname == "None": + if _hasGlyphNamedNone is None: + _hasGlyphNamedNone = "None" in ttFont.getGlyphOrder() + if not _hasGlyphNamedNone: + gname = None + try: + uvsDict[uvs].append((uv, gname)) + except KeyError: + uvsDict[uvs] = [(uv, gname)] + + def compile(self, ttFont): + if self.data: + return ( + struct.pack( + ">HLL", self.format, self.length, self.numVarSelectorRecords + ) + + self.data + ) + + uvsDict = self.uvsDict + uvsList = sorted(uvsDict.keys()) + self.numVarSelectorRecords = len(uvsList) + offset = ( + 10 + self.numVarSelectorRecords * 11 + ) # current value is end of VarSelectorRecords block. + data = [] + varSelectorRecords = [] + for uvs in uvsList: + entryList = uvsDict[uvs] + + defList = [entry for entry in entryList if entry[1] is None] + if defList: + defList = [entry[0] for entry in defList] + defOVSOffset = offset + defList.sort() + + lastUV = defList[0] + cnt = -1 + defRecs = [] + for defEntry in defList: + cnt += 1 + if (lastUV + cnt) != defEntry: + rec = struct.pack(">3sB", cvtFromUVS(lastUV), cnt - 1) + lastUV = defEntry + defRecs.append(rec) + cnt = 0 + + rec = struct.pack(">3sB", cvtFromUVS(lastUV), cnt) + defRecs.append(rec) + + numDefRecs = len(defRecs) + data.append(struct.pack(">L", numDefRecs)) + data.extend(defRecs) + offset += 4 + numDefRecs * 4 + else: + defOVSOffset = 0 + + ndefList = [entry for entry in entryList if entry[1] is not None] + if ndefList: + nonDefUVSOffset = offset + ndefList.sort() + numNonDefRecs = len(ndefList) + data.append(struct.pack(">L", numNonDefRecs)) + offset += 4 + numNonDefRecs * 5 + + for uv, gname in ndefList: + gid = ttFont.getGlyphID(gname) + ndrec = struct.pack(">3sH", cvtFromUVS(uv), gid) + data.append(ndrec) + else: + nonDefUVSOffset = 0 + + vrec = struct.pack(">3sLL", cvtFromUVS(uvs), defOVSOffset, nonDefUVSOffset) + varSelectorRecords.append(vrec) + + data = bytesjoin(varSelectorRecords) + bytesjoin(data) + self.length = 10 + len(data) + headerdata = struct.pack( + ">HLL", self.format, self.length, self.numVarSelectorRecords + ) + + return headerdata + data + + +class cmap_format_unknown(CmapSubtable): + headerFormat = "" # the body is kept verbatim, nothing is unpacked + + def __init__(self, format): + CmapSubtable.__init__(self, format) + # We can't read the subtable, so there are no mappings to offer. The raw + # data is kept instead, and written back out as-is. fromXML() does the + # same. + self.cmap = {} + + def ensureDecompiled(self, recurse=False): + # There is nothing to decompile, so hold on to the data; the base class + # would drop it. + pass + + def __getattr__(self, attr): + # The base class lazily decompiles and retries, relying on + # ensureDecompiled() clearing self.data to terminate. We keep the data, + # so retrying would recurse forever. + raise AttributeError(attr) + + def toXML(self, writer, ttFont): + cmapName = self.__class__.__name__[:12] + str(self.format) + writer.begintag( + cmapName, + [ + ("platformID", self.platformID), + ("platEncID", self.platEncID), + ], + ) + writer.newline() + writer.dumphex(self.data) + writer.endtag(cmapName) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + self.data = readHex(content) + self.cmap = {} + + def decompileHeader(self, data, ttFont): + self.language = 0 # dummy value + self.data = data + + def decompile(self, data, ttFont): + # we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None. + # If not, someone is calling the subtable decompile() directly, and must provide both args. + if data is not None and ttFont is not None: + self.decompileHeader(data, ttFont) + else: + assert ( + data is None and ttFont is None + ), "Need both data and ttFont arguments" + + def compile(self, ttFont): + if self.data: + return self.data + else: + return None + + +cmap_classes = { + 0: cmap_format_0, + 2: cmap_format_2, + 4: cmap_format_4, + 6: cmap_format_6, + 12: cmap_format_12, + 13: cmap_format_13, + 14: cmap_format_14, +} diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_c_v_a_r.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_c_v_a_r.py new file mode 100644 index 0000000000000000000000000000000000000000..eb082178f73d17b7121cb6ed85070152b887368d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_c_v_a_r.py @@ -0,0 +1,93 @@ +from . import DefaultTable +from fontTools.misc import sstruct +from fontTools.misc.textTools import bytesjoin +from fontTools.ttLib.tables.TupleVariation import ( + compileTupleVariationStore, + decompileTupleVariationStore, + TupleVariation, +) + +# https://www.microsoft.com/typography/otspec/cvar.htm +# https://www.microsoft.com/typography/otspec/otvarcommonformats.htm +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cvar.html + +CVAR_HEADER_FORMAT = """ + > # big endian + majorVersion: H + minorVersion: H + tupleVariationCount: H + offsetToData: H +""" + +CVAR_HEADER_SIZE = sstruct.calcsize(CVAR_HEADER_FORMAT) + + +class table__c_v_a_r(DefaultTable.DefaultTable): + """Control Value Table (CVT) variations table + + The ``cvar`` table contains variations for the values in a ``cvt`` + table. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/cvar + """ + + dependencies = ["cvt ", "fvar"] + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.majorVersion, self.minorVersion = 1, 0 + self.variations = [] + + def compile(self, ttFont, useSharedPoints=False): + tupleVariationCount, tuples, data = compileTupleVariationStore( + variations=[v for v in self.variations if v.hasImpact()], + pointCount=len(ttFont["cvt "].values), + axisTags=[axis.axisTag for axis in ttFont["fvar"].axes], + sharedTupleIndices={}, + useSharedPoints=useSharedPoints, + ) + header = { + "majorVersion": self.majorVersion, + "minorVersion": self.minorVersion, + "tupleVariationCount": tupleVariationCount, + "offsetToData": CVAR_HEADER_SIZE + len(tuples), + } + return b"".join([sstruct.pack(CVAR_HEADER_FORMAT, header), tuples, data]) + + def decompile(self, data, ttFont): + axisTags = [axis.axisTag for axis in ttFont["fvar"].axes] + header = {} + sstruct.unpack(CVAR_HEADER_FORMAT, data[0:CVAR_HEADER_SIZE], header) + self.majorVersion = header["majorVersion"] + self.minorVersion = header["minorVersion"] + assert self.majorVersion == 1, self.majorVersion + self.variations = decompileTupleVariationStore( + tableTag=self.tableTag, + axisTags=axisTags, + tupleVariationCount=header["tupleVariationCount"], + pointCount=len(ttFont["cvt "].values), + sharedTuples=None, + data=data, + pos=CVAR_HEADER_SIZE, + dataPos=header["offsetToData"], + ) + + def fromXML(self, name, attrs, content, ttFont): + if name == "version": + self.majorVersion = int(attrs.get("major", "1")) + self.minorVersion = int(attrs.get("minor", "0")) + elif name == "tuple": + valueCount = len(ttFont["cvt "].values) + var = TupleVariation({}, [None] * valueCount) + self.variations.append(var) + for tupleElement in content: + if isinstance(tupleElement, tuple): + tupleName, tupleAttrs, tupleContent = tupleElement + var.fromXML(tupleName, tupleAttrs, tupleContent) + + def toXML(self, writer, ttFont): + axisTags = [axis.axisTag for axis in ttFont["fvar"].axes] + writer.simpletag("version", major=self.majorVersion, minor=self.minorVersion) + writer.newline() + for var in self.variations: + var.toXML(writer, axisTags) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_c_v_t.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_c_v_t.py new file mode 100644 index 0000000000000000000000000000000000000000..c89fe2c239a0ab72fe763a1c0f700540d6b4126e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_c_v_t.py @@ -0,0 +1,56 @@ +from fontTools.misc.textTools import safeEval +from . import DefaultTable +import sys +import array + + +class table__c_v_t(DefaultTable.DefaultTable): + """Control Value Table + + The Control Value Table holds a list of values that can be referenced + by TrueType font instructions. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/cvt + """ + + def decompile(self, data, ttFont): + values = array.array("h") + values.frombytes(data) + if sys.byteorder != "big": + values.byteswap() + self.values = values + + def compile(self, ttFont): + if not hasattr(self, "values"): + return b"" + values = self.values[:] + if sys.byteorder != "big": + values.byteswap() + return values.tobytes() + + def toXML(self, writer, ttFont): + for i, value in enumerate(self.values): + writer.simpletag("cv", value=value, index=i) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if not hasattr(self, "values"): + self.values = array.array("h") + if name == "cv": + index = safeEval(attrs["index"]) + value = safeEval(attrs["value"]) + for i in range(1 + index - len(self.values)): + self.values.append(0) + self.values[index] = value + + def __len__(self): + return len(self.values) + + def __getitem__(self, index): + return self.values[index] + + def __setitem__(self, index, value): + self.values[index] = value + + def __delitem__(self, index): + del self.values[index] diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_f_e_a_t.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_f_e_a_t.py new file mode 100644 index 0000000000000000000000000000000000000000..8e279db0059613d5c0e0ac061dc9b2b62aefe73b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_f_e_a_t.py @@ -0,0 +1,15 @@ +from .otBase import BaseTTXConverter + + +class table__f_e_a_t(BaseTTXConverter): + """Feature name table + + The feature name table is an AAT (Apple Advanced Typography) table for + storing font features, settings, and their human-readable names. It should + not be confused with the ``Feat`` table or the OpenType Layout ``GSUB``/``GPOS`` + tables. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6feat.html + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_f_p_g_m.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_f_p_g_m.py new file mode 100644 index 0000000000000000000000000000000000000000..c21a9d4b6817d33bc68aabb8d866708657d1e068 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_f_p_g_m.py @@ -0,0 +1,62 @@ +from . import DefaultTable +from . import ttProgram + + +class table__f_p_g_m(DefaultTable.DefaultTable): + """Font Program table + + The ``fpgm`` table typically contains function defintions that are + used by font instructions. This Font Program is similar to the Control + Value Program that is stored in the ``prep`` table, but + the ``fpgm`` table is only executed one time, when the font is first + used. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/fpgm + """ + + def decompile(self, data, ttFont): + program = ttProgram.Program() + program.fromBytecode(data) + self.program = program + + def compile(self, ttFont): + if hasattr(self, "program"): + return self.program.getBytecode() + return b"" + + def toXML(self, writer, ttFont): + self.program.toXML(writer, ttFont) + + def fromXML(self, name, attrs, content, ttFont): + program = ttProgram.Program() + program.fromXML(name, attrs, content, ttFont) + self.program = program + + def __bool__(self): + """ + >>> fpgm = table__f_p_g_m() + >>> bool(fpgm) + False + >>> p = ttProgram.Program() + >>> fpgm.program = p + >>> bool(fpgm) + False + >>> bc = bytearray([0]) + >>> p.fromBytecode(bc) + >>> bool(fpgm) + True + >>> p.bytecode.pop() + 0 + >>> bool(fpgm) + False + """ + return hasattr(self, "program") and bool(self.program) + + __nonzero__ = __bool__ + + +if __name__ == "__main__": + import sys + import doctest + + sys.exit(doctest.testmod().failed) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_f_v_a_r.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_f_v_a_r.py new file mode 100644 index 0000000000000000000000000000000000000000..a00b4ab65049538e8ac606a712e4557afd2b2d53 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_f_v_a_r.py @@ -0,0 +1,258 @@ +from fontTools.misc import sstruct +from fontTools.misc.fixedTools import ( + fixedToFloat as fi2fl, + floatToFixed as fl2fi, + floatToFixedToStr as fl2str, + strToFixedToFloat as str2fl, +) +from fontTools.misc.textTools import Tag, bytesjoin, safeEval +from fontTools.ttLib import TTLibError +from . import DefaultTable +import struct + +# Apple's documentation of 'fvar': +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html + +FVAR_HEADER_FORMAT = """ + > # big endian + version: L + offsetToData: H + countSizePairs: H + axisCount: H + axisSize: H + instanceCount: H + instanceSize: H +""" + +FVAR_AXIS_FORMAT = """ + > # big endian + axisTag: 4s + minValue: 16.16F + defaultValue: 16.16F + maxValue: 16.16F + flags: H + axisNameID: H +""" + +FVAR_INSTANCE_FORMAT = """ + > # big endian + subfamilyNameID: H + flags: H +""" + + +class table__f_v_a_r(DefaultTable.DefaultTable): + """FonT Variations table + + The ``fvar`` table contains records of the variation axes and of the + named instances in a variable font. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html + """ + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.axes = [] + self.instances = [] + + def compile(self, ttFont): + instanceSize = sstruct.calcsize(FVAR_INSTANCE_FORMAT) + (len(self.axes) * 4) + includePostScriptNames = any( + instance.postscriptNameID != 0xFFFF for instance in self.instances + ) + if includePostScriptNames: + instanceSize += 2 + header = { + "version": 0x00010000, + "offsetToData": sstruct.calcsize(FVAR_HEADER_FORMAT), + "countSizePairs": 2, + "axisCount": len(self.axes), + "axisSize": sstruct.calcsize(FVAR_AXIS_FORMAT), + "instanceCount": len(self.instances), + "instanceSize": instanceSize, + } + result = [sstruct.pack(FVAR_HEADER_FORMAT, header)] + result.extend([axis.compile() for axis in self.axes]) + axisTags = [axis.axisTag for axis in self.axes] + for instance in self.instances: + result.append(instance.compile(axisTags, includePostScriptNames)) + return bytesjoin(result) + + def decompile(self, data, ttFont): + header = {} + headerSize = sstruct.calcsize(FVAR_HEADER_FORMAT) + header = sstruct.unpack(FVAR_HEADER_FORMAT, data[0:headerSize]) + if header["version"] != 0x00010000: + raise TTLibError("unsupported 'fvar' version %04x" % header["version"]) + pos = header["offsetToData"] + axisSize = header["axisSize"] + for _ in range(header["axisCount"]): + axis = Axis() + axis.decompile(data[pos : pos + axisSize]) + self.axes.append(axis) + pos += axisSize + instanceSize = header["instanceSize"] + axisTags = [axis.axisTag for axis in self.axes] + for _ in range(header["instanceCount"]): + instance = NamedInstance() + instance.decompile(data[pos : pos + instanceSize], axisTags) + self.instances.append(instance) + pos += instanceSize + + def toXML(self, writer, ttFont): + for axis in self.axes: + axis.toXML(writer, ttFont) + for instance in self.instances: + instance.toXML(writer, ttFont) + + def fromXML(self, name, attrs, content, ttFont): + if name == "Axis": + axis = Axis() + axis.fromXML(name, attrs, content, ttFont) + self.axes.append(axis) + elif name == "NamedInstance": + instance = NamedInstance() + instance.fromXML(name, attrs, content, ttFont) + self.instances.append(instance) + + def getAxes(self): + return {a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in self.axes} + + +class Axis(object): + def __init__(self): + self.axisTag = None + self.axisNameID = 0 + self.flags = 0 + self.minValue = -1.0 + self.defaultValue = 0.0 + self.maxValue = 1.0 + + def compile(self): + return sstruct.pack(FVAR_AXIS_FORMAT, self) + + def decompile(self, data): + sstruct.unpack2(FVAR_AXIS_FORMAT, data, self) + + def toXML(self, writer, ttFont): + name = ( + ttFont["name"].getDebugName(self.axisNameID) if "name" in ttFont else None + ) + if name is not None: + writer.newline() + writer.comment(name) + writer.newline() + writer.begintag("Axis") + writer.newline() + for tag, value in [ + ("AxisTag", self.axisTag), + ("Flags", "0x%X" % self.flags), + ("MinValue", fl2str(self.minValue, 16)), + ("DefaultValue", fl2str(self.defaultValue, 16)), + ("MaxValue", fl2str(self.maxValue, 16)), + ("AxisNameID", str(self.axisNameID)), + ]: + writer.begintag(tag) + writer.write(value) + writer.endtag(tag) + writer.newline() + writer.endtag("Axis") + writer.newline() + + def fromXML(self, name, _attrs, content, ttFont): + assert name == "Axis" + for tag, _, value in filter(lambda t: type(t) is tuple, content): + value = "".join(value) + if tag == "AxisTag": + self.axisTag = Tag(value) + elif tag in {"Flags", "MinValue", "DefaultValue", "MaxValue", "AxisNameID"}: + setattr( + self, + tag[0].lower() + tag[1:], + str2fl(value, 16) if tag.endswith("Value") else safeEval(value), + ) + + +class NamedInstance(object): + def __init__(self): + self.subfamilyNameID = 0 + self.postscriptNameID = 0xFFFF + self.flags = 0 + self.coordinates = {} + + def compile(self, axisTags, includePostScriptName): + result = [sstruct.pack(FVAR_INSTANCE_FORMAT, self)] + for axis in axisTags: + fixedCoord = fl2fi(self.coordinates[axis], 16) + result.append(struct.pack(">l", fixedCoord)) + if includePostScriptName: + result.append(struct.pack(">H", self.postscriptNameID)) + return bytesjoin(result) + + def decompile(self, data, axisTags): + sstruct.unpack2(FVAR_INSTANCE_FORMAT, data, self) + pos = sstruct.calcsize(FVAR_INSTANCE_FORMAT) + for axis in axisTags: + value = struct.unpack(">l", data[pos : pos + 4])[0] + self.coordinates[axis] = fi2fl(value, 16) + pos += 4 + if pos + 2 <= len(data): + self.postscriptNameID = struct.unpack(">H", data[pos : pos + 2])[0] + else: + self.postscriptNameID = 0xFFFF + + def toXML(self, writer, ttFont): + name = ( + ttFont["name"].getDebugName(self.subfamilyNameID) + if "name" in ttFont + else None + ) + if name is not None: + writer.newline() + writer.comment(name) + writer.newline() + psname = ( + ttFont["name"].getDebugName(self.postscriptNameID) + if "name" in ttFont + else None + ) + if psname is not None: + writer.comment("PostScript: " + psname) + writer.newline() + if self.postscriptNameID == 0xFFFF: + writer.begintag( + "NamedInstance", + flags=("0x%X" % self.flags), + subfamilyNameID=self.subfamilyNameID, + ) + else: + writer.begintag( + "NamedInstance", + flags=("0x%X" % self.flags), + subfamilyNameID=self.subfamilyNameID, + postscriptNameID=self.postscriptNameID, + ) + writer.newline() + for axis in ttFont["fvar"].axes: + writer.simpletag( + "coord", + axis=axis.axisTag, + value=fl2str(self.coordinates[axis.axisTag], 16), + ) + writer.newline() + writer.endtag("NamedInstance") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + assert name == "NamedInstance" + self.subfamilyNameID = safeEval(attrs["subfamilyNameID"]) + self.flags = safeEval(attrs.get("flags", "0")) + if "postscriptNameID" in attrs: + self.postscriptNameID = safeEval(attrs["postscriptNameID"]) + else: + self.postscriptNameID = 0xFFFF + + for tag, elementAttrs, _ in filter(lambda t: type(t) is tuple, content): + if tag == "coord": + value = str2fl(elementAttrs["value"], 16) + self.coordinates[elementAttrs["axis"]] = value diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_g_a_s_p.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_g_a_s_p.py new file mode 100644 index 0000000000000000000000000000000000000000..e2d6d837dd94927180e1be757f788b0cd1de8ac6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_g_a_s_p.py @@ -0,0 +1,62 @@ +from fontTools.misc.textTools import safeEval +from . import DefaultTable +import struct + +GASP_SYMMETRIC_GRIDFIT = 0x0004 +GASP_SYMMETRIC_SMOOTHING = 0x0008 +GASP_DOGRAY = 0x0002 +GASP_GRIDFIT = 0x0001 + + +class table__g_a_s_p(DefaultTable.DefaultTable): + """Grid-fitting and Scan-conversion Procedure table + + The ``gasp`` table defines the preferred rasterization settings for + the font when rendered on monochrome and greyscale output devices. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/gasp + """ + + def decompile(self, data, ttFont): + self.version, numRanges = struct.unpack(">HH", data[:4]) + assert 0 <= self.version <= 1, "unknown 'gasp' format: %s" % self.version + data = data[4:] + self.gaspRange = {} + for i in range(numRanges): + rangeMaxPPEM, rangeGaspBehavior = struct.unpack(">HH", data[:4]) + self.gaspRange[int(rangeMaxPPEM)] = int(rangeGaspBehavior) + data = data[4:] + assert not data, "too much data" + + def compile(self, ttFont): + version = 0 # ignore self.version + numRanges = len(self.gaspRange) + data = b"" + items = sorted(self.gaspRange.items()) + for rangeMaxPPEM, rangeGaspBehavior in items: + data = data + struct.pack(">HH", rangeMaxPPEM, rangeGaspBehavior) + if rangeGaspBehavior & ~(GASP_GRIDFIT | GASP_DOGRAY): + version = 1 + data = struct.pack(">HH", version, numRanges) + data + return data + + def toXML(self, writer, ttFont): + items = sorted(self.gaspRange.items()) + for rangeMaxPPEM, rangeGaspBehavior in items: + writer.simpletag( + "gaspRange", + [ + ("rangeMaxPPEM", rangeMaxPPEM), + ("rangeGaspBehavior", rangeGaspBehavior), + ], + ) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name != "gaspRange": + return + if not hasattr(self, "gaspRange"): + self.gaspRange = {} + self.gaspRange[safeEval(attrs["rangeMaxPPEM"])] = safeEval( + attrs["rangeGaspBehavior"] + ) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_g_c_i_d.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_g_c_i_d.py new file mode 100644 index 0000000000000000000000000000000000000000..9d6d6ae425384b47613c146d567847c00660a5cc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_g_c_i_d.py @@ -0,0 +1,13 @@ +from .otBase import BaseTTXConverter + + +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gcid.html +class table__g_c_i_d(BaseTTXConverter): + """Glyph ID to CID table + + The AAT ``gcid`` table stores glyphID-to-CID mappings. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gcid.html + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_g_l_y_f.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_g_l_y_f.py new file mode 100644 index 0000000000000000000000000000000000000000..428504bfc3ee7fe115c0c7d656edef3497bf0a3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_g_l_y_f.py @@ -0,0 +1,2329 @@ +"""_g_l_y_f.py -- Converter classes for the 'glyf' table.""" + +from collections import namedtuple +from collections.abc import ItemsView, ValuesView +from fontTools.misc import sstruct +from fontTools import ttLib +from fontTools import version +from fontTools.misc.transform import DecomposedTransform +from fontTools.misc.textTools import tostr, safeEval, pad +from fontTools.misc.arrayTools import updateBounds, pointInRect +from fontTools.misc.bezierTools import calcQuadraticBounds +from fontTools.misc.fixedTools import ( + fixedToFloat as fi2fl, + floatToFixed as fl2fi, + floatToFixedToStr as fl2str, + strToFixedToFloat as str2fl, +) +from fontTools.misc.roundTools import noRound, otRound +from fontTools.misc.vector import Vector +from numbers import Number +from . import DefaultTable +from . import ttProgram +import sys +import struct +import array +import logging +import math +import os +from fontTools.misc import xmlWriter +from fontTools.misc.filenames import userNameToFileName +from fontTools.misc.loggingTools import deprecateFunction +from enum import IntFlag +from functools import partial +from types import SimpleNamespace +from typing import Set + +log = logging.getLogger(__name__) + +# We compute the version the same as is computed in ttlib/__init__ +# so that we can write 'ttLibVersion' attribute of the glyf TTX files +# when glyf is written to separate files. +version = ".".join(version.split(".")[:2]) + +# +# The Apple and MS rasterizers behave differently for +# scaled composite components: one does scale first and then translate +# and the other does it vice versa. MS defined some flags to indicate +# the difference, but it seems nobody actually _sets_ those flags. +# +# Funny thing: Apple seems to _only_ do their thing in the +# WE_HAVE_A_SCALE (eg. Chicago) case, and not when it's WE_HAVE_AN_X_AND_Y_SCALE +# (eg. Charcoal)... +# +SCALE_COMPONENT_OFFSET_DEFAULT = 0 # 0 == MS, 1 == Apple + + +class table__g_l_y_f(DefaultTable.DefaultTable): + """Glyph Data table + + This class represents the `glyf <https://docs.microsoft.com/en-us/typography/opentype/spec/glyf>`_ + table, which contains outlines for glyphs in TrueType format. In many cases, + it is easier to access and manipulate glyph outlines through the ``GlyphSet`` + object returned from :py:meth:`fontTools.ttLib.ttFont.getGlyphSet`:: + + >> from fontTools.pens.boundsPen import BoundsPen + >> glyphset = font.getGlyphSet() + >> bp = BoundsPen(glyphset) + >> glyphset["A"].draw(bp) + >> bp.bounds + (19, 0, 633, 716) + + However, this class can be used for low-level access to the ``glyf`` table data. + Objects of this class support dictionary-like access, mapping glyph names to + :py:class:`Glyph` objects:: + + >> glyf = font["glyf"] + >> len(glyf["Aacute"].components) + 2 + + Note that when adding glyphs to the font via low-level access to the ``glyf`` + table, the new glyphs must also be added to the ``hmtx``/``vmtx`` table:: + + >> font["glyf"]["divisionslash"] = Glyph() + >> font["hmtx"]["divisionslash"] = (640, 0) + + """ + + # this attribute controls the amount of padding applied to glyph data upon compile. + # Glyph lenghts are aligned to multiples of the specified value. + # Allowed values are (0, 1, 2, 4). '0' means no padding; '1' (default) also means + # no padding, except for when padding would allow to use short loca offsets. + padding = 1 + + def decompile(self, data, ttFont): + loca = ttFont["loca"] + pos = int(loca[0]) + nextPos = 0 + noname = 0 + self.glyphs = {} + self.glyphOrder = glyphOrder = ttFont.getGlyphOrder() + self._reverseGlyphOrder = {} + for i in range(0, len(loca) - 1): + try: + glyphName = glyphOrder[i] + except IndexError: + noname = noname + 1 + glyphName = "ttxautoglyph%s" % i + nextPos = int(loca[i + 1]) + glyphdata = data[pos:nextPos] + if len(glyphdata) != (nextPos - pos): + raise ttLib.TTLibError("not enough 'glyf' table data") + glyph = Glyph(glyphdata) + self.glyphs[glyphName] = glyph + pos = nextPos + if len(data) - nextPos >= 4: + log.warning( + "too much 'glyf' table data: expected %d, received %d bytes", + nextPos, + len(data), + ) + if noname: + log.warning("%s glyphs have no name", noname) + if ttFont.lazy is False: # Be lazy for None and True + self.ensureDecompiled() + + def ensureDecompiled(self, recurse=False): + # The recurse argument is unused, but part of the signature of + # ensureDecompiled across the library. + for glyph in self.glyphs.values(): + glyph.expand(self) + + def compile(self, ttFont): + optimizeSpeed = ttFont.cfg[ttLib.OPTIMIZE_FONT_SPEED] + if not hasattr(self, "glyphOrder"): + self.glyphOrder = ttFont.getGlyphOrder() + padding = self.padding + assert padding in (0, 1, 2, 4) + locations = [] + currentLocation = 0 + dataList = [] + recalcBBoxes = ttFont.recalcBBoxes + boundsDone = set() + for glyphName in self.glyphOrder: + glyph = self.glyphs[glyphName] + glyphData = glyph.compile( + self, + recalcBBoxes, + boundsDone=boundsDone, + optimizeSize=not optimizeSpeed, + ) + if padding > 1: + glyphData = pad(glyphData, size=padding) + locations.append(currentLocation) + currentLocation = currentLocation + len(glyphData) + dataList.append(glyphData) + locations.append(currentLocation) + + if padding == 1 and currentLocation < 0x20000: + # See if we can pad any odd-lengthed glyphs to allow loca + # table to use the short offsets. + indices = [ + i for i, glyphData in enumerate(dataList) if len(glyphData) % 2 == 1 + ] + if indices and currentLocation + len(indices) < 0x20000: + # It fits. Do it. + for i in indices: + dataList[i] += b"\0" + currentLocation = 0 + for i, glyphData in enumerate(dataList): + locations[i] = currentLocation + currentLocation += len(glyphData) + locations[len(dataList)] = currentLocation + + data = b"".join(dataList) + if "loca" in ttFont: + ttFont["loca"].set(locations) + if "maxp" in ttFont: + ttFont["maxp"].numGlyphs = len(self.glyphs) + if not data: + # As a special case when all glyph in the font are empty, add a zero byte + # to the table, so that OTS doesn’t reject it, and to make the table work + # on Windows as well. + # See https://github.com/khaledhosny/ots/issues/52 + data = b"\0" + return data + + def toXML(self, writer, ttFont, splitGlyphs=False): + notice = ( + "The xMin, yMin, xMax and yMax values\n" + "will be recalculated by the compiler." + ) + glyphNames = ttFont.getGlyphNames() + if not splitGlyphs: + writer.newline() + writer.comment(notice) + writer.newline() + writer.newline() + numGlyphs = len(glyphNames) + if splitGlyphs: + path, ext = os.path.splitext(writer.file.name) + existingGlyphFiles = set() + for glyphName in glyphNames: + glyph = self.get(glyphName) + if glyph is None: + log.warning("glyph '%s' does not exist in glyf table", glyphName) + continue + if glyph.numberOfContours: + if splitGlyphs: + glyphPath = userNameToFileName( + tostr(glyphName, "utf-8"), + existingGlyphFiles, + prefix=path + ".", + suffix=ext, + ) + existingGlyphFiles.add(glyphPath.lower()) + glyphWriter = xmlWriter.XMLWriter( + glyphPath, + idlefunc=writer.idlefunc, + newlinestr=writer.newlinestr, + ) + glyphWriter.begintag("ttFont", ttLibVersion=version) + glyphWriter.newline() + glyphWriter.begintag("glyf") + glyphWriter.newline() + glyphWriter.comment(notice) + glyphWriter.newline() + writer.simpletag("TTGlyph", src=os.path.basename(glyphPath)) + else: + glyphWriter = writer + glyphWriter.begintag( + "TTGlyph", + [ + ("name", glyphName), + ("xMin", glyph.xMin), + ("yMin", glyph.yMin), + ("xMax", glyph.xMax), + ("yMax", glyph.yMax), + ], + ) + glyphWriter.newline() + glyph.toXML(glyphWriter, ttFont) + glyphWriter.endtag("TTGlyph") + glyphWriter.newline() + if splitGlyphs: + glyphWriter.endtag("glyf") + glyphWriter.newline() + glyphWriter.endtag("ttFont") + glyphWriter.newline() + glyphWriter.close() + else: + writer.simpletag("TTGlyph", name=glyphName) + writer.comment("contains no outline data") + if not splitGlyphs: + writer.newline() + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name != "TTGlyph": + return + if not hasattr(self, "glyphs"): + self.glyphs = {} + if not hasattr(self, "glyphOrder"): + self.glyphOrder = ttFont.getGlyphOrder() + glyphName = attrs["name"] + log.debug("unpacking glyph '%s'", glyphName) + glyph = Glyph() + for attr in ["xMin", "yMin", "xMax", "yMax"]: + setattr(glyph, attr, safeEval(attrs.get(attr, "0"))) + self.glyphs[glyphName] = glyph + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + glyph.fromXML(name, attrs, content, ttFont) + if not ttFont.recalcBBoxes: + glyph.compact(self, 0) + + def setGlyphOrder(self, glyphOrder): + """Sets the glyph order + + Args: + glyphOrder ([str]): List of glyph names in order. + """ + self.glyphOrder = glyphOrder + self._reverseGlyphOrder = {} + + def getGlyphName(self, glyphID): + """Returns the name for the glyph with the given ID. + + Raises a ``KeyError`` if the glyph name is not found in the font. + """ + return self.glyphOrder[glyphID] + + def _buildReverseGlyphOrderDict(self): + self._reverseGlyphOrder = d = {} + for glyphID, glyphName in enumerate(self.glyphOrder): + d[glyphName] = glyphID + + def getGlyphID(self, glyphName): + """Returns the ID of the glyph with the given name. + + Raises a ``ValueError`` if the glyph is not found in the font. + """ + glyphOrder = self.glyphOrder + id = getattr(self, "_reverseGlyphOrder", {}).get(glyphName) + if id is None or id >= len(glyphOrder) or glyphOrder[id] != glyphName: + self._buildReverseGlyphOrderDict() + id = self._reverseGlyphOrder.get(glyphName) + if id is None: + raise ValueError(glyphName) + return id + + def removeHinting(self): + """Removes TrueType hints from all glyphs in the glyphset. + + See :py:meth:`Glyph.removeHinting`. + """ + for glyph in self.glyphs.values(): + glyph.removeHinting() + + def keys(self): + return self.glyphs.keys() + + def __iter__(self): + return self.glyphs.__iter__() + + def values(self): + return ValuesView(self) + + def items(self): + return ItemsView(self) + + def has_key(self, glyphName): + return glyphName in self.glyphs + + __contains__ = has_key + + def get(self, glyphName, default=None): + glyph = self.glyphs.get(glyphName, default) + if glyph is not None: + glyph.expand(self) + return glyph + + def __getitem__(self, glyphName): + glyph = self.glyphs[glyphName] + glyph.expand(self) + return glyph + + def __setitem__(self, glyphName, glyph): + self.glyphs[glyphName] = glyph + # Use the reverse glyph map for O(1) membership so that building a font by + # repeatedly assigning glyphs stays linear instead of quadratic. Rebuild + # the map if it is missing or no longer matches the length of glyphOrder; + # reordering goes through setGlyphOrder, which clears it. + rev = getattr(self, "_reverseGlyphOrder", None) + if rev is None or len(rev) != len(self.glyphOrder): + self._buildReverseGlyphOrderDict() + rev = self._reverseGlyphOrder + if glyphName not in rev: + rev[glyphName] = len(self.glyphOrder) + self.glyphOrder.append(glyphName) + + def __delitem__(self, glyphName): + del self.glyphs[glyphName] + self.glyphOrder.remove(glyphName) + # glyph ids after the removed one shift down; rebuild lazily on next use. + self._reverseGlyphOrder = {} + + def __len__(self): + assert len(self.glyphOrder) == len(self.glyphs) + return len(self.glyphs) + + def _getPhantomPoints(self, glyphName, hMetrics, vMetrics=None): + """Compute the four "phantom points" for the given glyph from its bounding box + and the horizontal and vertical advance widths and sidebearings stored in the + ttFont's "hmtx" and "vmtx" tables. + + 'hMetrics' should be ttFont['hmtx'].metrics. + + 'vMetrics' should be ttFont['vmtx'].metrics if there is "vmtx" or None otherwise. + If there is no vMetrics passed in, vertical phantom points are set to the zero coordinate. + + https://docs.microsoft.com/en-us/typography/opentype/spec/tt_instructing_glyphs#phantoms + """ + glyph = self[glyphName] + if not hasattr(glyph, "xMin"): + glyph.recalcBounds(self) + + horizontalAdvanceWidth, leftSideBearing = hMetrics[glyphName] + leftSideX = glyph.xMin - leftSideBearing + rightSideX = leftSideX + horizontalAdvanceWidth + + if vMetrics: + verticalAdvanceWidth, topSideBearing = vMetrics[glyphName] + topSideY = topSideBearing + glyph.yMax + bottomSideY = topSideY - verticalAdvanceWidth + else: + bottomSideY = topSideY = 0 + + return [ + (leftSideX, 0), + (rightSideX, 0), + (0, topSideY), + (0, bottomSideY), + ] + + def _getCoordinatesAndControls( + self, glyphName, hMetrics, vMetrics=None, *, round=otRound + ): + """Return glyph coordinates and controls as expected by "gvar" table. + + The coordinates includes four "phantom points" for the glyph metrics, + as mandated by the "gvar" spec. + + The glyph controls is a namedtuple with the following attributes: + - numberOfContours: -1 for composite glyphs. + - endPts: list of indices of end points for each contour in simple + glyphs, or component indices in composite glyphs (used for IUP + optimization). + - flags: array of contour point flags for simple glyphs (None for + composite glyphs). + - components: list of base glyph names (str) for each component in + composite glyphs (None for simple glyphs). + + The "hMetrics" and vMetrics are used to compute the "phantom points" (see + the "_getPhantomPoints" method). + + Return None if the requested glyphName is not present. + """ + glyph = self.get(glyphName) + if glyph is None: + return None + if glyph.isComposite(): + coords = GlyphCoordinates( + [(getattr(c, "x", 0), getattr(c, "y", 0)) for c in glyph.components] + ) + controls = _GlyphControls( + numberOfContours=glyph.numberOfContours, + endPts=list(range(len(glyph.components))), + flags=None, + components=[ + (c.glyphName, getattr(c, "transform", None)) + for c in glyph.components + ], + ) + else: + coords, endPts, flags = glyph.getCoordinates(self) + coords = coords.copy() + controls = _GlyphControls( + numberOfContours=glyph.numberOfContours, + endPts=endPts, + flags=flags, + components=None, + ) + # Add phantom points for (left, right, top, bottom) positions. + phantomPoints = self._getPhantomPoints(glyphName, hMetrics, vMetrics) + coords.extend(phantomPoints) + coords.toInt(round=round) + return coords, controls + + def _setCoordinates(self, glyphName, coord, hMetrics, vMetrics=None): + """Set coordinates and metrics for the given glyph. + + "coord" is an array of GlyphCoordinates which must include the "phantom + points" as the last four coordinates. + + Both the horizontal/vertical advances and left/top sidebearings in "hmtx" + and "vmtx" tables (if any) are updated from four phantom points and + the glyph's bounding boxes. + + The "hMetrics" and vMetrics are used to propagate "phantom points" + into "hmtx" and "vmtx" tables if desired. (see the "_getPhantomPoints" + method). + """ + glyph = self[glyphName] + + # Handle phantom points for (left, right, top, bottom) positions. + assert len(coord) >= 4 + leftSideX = coord[-4][0] + rightSideX = coord[-3][0] + topSideY = coord[-2][1] + bottomSideY = coord[-1][1] + + coord = coord[:-4] + + if glyph.isComposite(): + assert len(coord) == len(glyph.components) + for p, comp in zip(coord, glyph.components): + if hasattr(comp, "x"): + comp.x, comp.y = p + elif glyph.numberOfContours == 0: + assert len(coord) == 0 + else: + assert len(coord) == len(glyph.coordinates) + glyph.coordinates = GlyphCoordinates(coord) + + glyph.recalcBounds(self, boundsDone=set()) + + horizontalAdvanceWidth = otRound(rightSideX - leftSideX) + if horizontalAdvanceWidth < 0: + # unlikely, but it can happen, see: + # https://github.com/fonttools/fonttools/pull/1198 + horizontalAdvanceWidth = 0 + leftSideBearing = otRound(glyph.xMin - leftSideX) + hMetrics[glyphName] = horizontalAdvanceWidth, leftSideBearing + + if vMetrics is not None: + verticalAdvanceWidth = otRound(topSideY - bottomSideY) + if verticalAdvanceWidth < 0: # unlikely but do the same as horizontal + verticalAdvanceWidth = 0 + topSideBearing = otRound(topSideY - glyph.yMax) + vMetrics[glyphName] = verticalAdvanceWidth, topSideBearing + + # Deprecated + + def _synthesizeVMetrics(self, glyphName, ttFont, defaultVerticalOrigin): + """This method is wrong and deprecated. + For rationale see: + https://github.com/fonttools/fonttools/pull/2266/files#r613569473 + """ + vMetrics = getattr(ttFont.get("vmtx"), "metrics", None) + if vMetrics is None: + verticalAdvanceWidth = ttFont["head"].unitsPerEm + topSideY = getattr(ttFont.get("hhea"), "ascent", None) + if topSideY is None: + if defaultVerticalOrigin is not None: + topSideY = defaultVerticalOrigin + else: + topSideY = verticalAdvanceWidth + glyph = self[glyphName] + glyph.recalcBounds(self) + topSideBearing = otRound(topSideY - glyph.yMax) + vMetrics = {glyphName: (verticalAdvanceWidth, topSideBearing)} + return vMetrics + + @deprecateFunction("use '_getPhantomPoints' instead", category=DeprecationWarning) + def getPhantomPoints(self, glyphName, ttFont, defaultVerticalOrigin=None): + """Old public name for self._getPhantomPoints(). + See: https://github.com/fonttools/fonttools/pull/2266""" + hMetrics = ttFont["hmtx"].metrics + vMetrics = self._synthesizeVMetrics(glyphName, ttFont, defaultVerticalOrigin) + return self._getPhantomPoints(glyphName, hMetrics, vMetrics) + + @deprecateFunction( + "use '_getCoordinatesAndControls' instead", category=DeprecationWarning + ) + def getCoordinatesAndControls(self, glyphName, ttFont, defaultVerticalOrigin=None): + """Old public name for self._getCoordinatesAndControls(). + See: https://github.com/fonttools/fonttools/pull/2266""" + hMetrics = ttFont["hmtx"].metrics + vMetrics = self._synthesizeVMetrics(glyphName, ttFont, defaultVerticalOrigin) + return self._getCoordinatesAndControls(glyphName, hMetrics, vMetrics) + + @deprecateFunction("use '_setCoordinates' instead", category=DeprecationWarning) + def setCoordinates(self, glyphName, ttFont): + """Old public name for self._setCoordinates(). + See: https://github.com/fonttools/fonttools/pull/2266""" + hMetrics = ttFont["hmtx"].metrics + vMetrics = getattr(ttFont.get("vmtx"), "metrics", None) + self._setCoordinates(glyphName, hMetrics, vMetrics) + + +_GlyphControls = namedtuple( + "_GlyphControls", "numberOfContours endPts flags components" +) + + +glyphHeaderFormat = """ + > # big endian + numberOfContours: h + xMin: h + yMin: h + xMax: h + yMax: h +""" + +# flags +flagOnCurve = 0x01 +flagXShort = 0x02 +flagYShort = 0x04 +flagRepeat = 0x08 +flagXsame = 0x10 +flagYsame = 0x20 +flagOverlapSimple = 0x40 +flagCubic = 0x80 + +# These flags are kept for XML output after decompiling the coordinates +keepFlags = flagOnCurve + flagOverlapSimple + flagCubic + +_flagSignBytes = { + 0: 2, + flagXsame: 0, + flagXShort | flagXsame: +1, + flagXShort: -1, + flagYsame: 0, + flagYShort | flagYsame: +1, + flagYShort: -1, +} + + +def flagBest(x, y, onCurve): + """For a given x,y delta pair, returns the flag that packs this pair + most efficiently, as well as the number of byte cost of such flag.""" + + flag = flagOnCurve if onCurve else 0 + cost = 0 + # do x + if x == 0: + flag = flag | flagXsame + elif -255 <= x <= 255: + flag = flag | flagXShort + if x > 0: + flag = flag | flagXsame + cost += 1 + else: + cost += 2 + # do y + if y == 0: + flag = flag | flagYsame + elif -255 <= y <= 255: + flag = flag | flagYShort + if y > 0: + flag = flag | flagYsame + cost += 1 + else: + cost += 2 + return flag, cost + + +def flagFits(newFlag, oldFlag, mask): + newBytes = _flagSignBytes[newFlag & mask] + oldBytes = _flagSignBytes[oldFlag & mask] + return newBytes == oldBytes or abs(newBytes) > abs(oldBytes) + + +def flagSupports(newFlag, oldFlag): + return ( + (oldFlag & flagOnCurve) == (newFlag & flagOnCurve) + and flagFits(newFlag, oldFlag, flagXsame | flagXShort) + and flagFits(newFlag, oldFlag, flagYsame | flagYShort) + ) + + +def flagEncodeCoord(flag, mask, coord, coordBytes): + byteCount = _flagSignBytes[flag & mask] + if byteCount == 1: + coordBytes.append(coord) + elif byteCount == -1: + coordBytes.append(-coord) + elif byteCount == 2: + coordBytes.extend(struct.pack(">h", coord)) + + +def flagEncodeCoords(flag, x, y, xBytes, yBytes): + flagEncodeCoord(flag, flagXsame | flagXShort, x, xBytes) + flagEncodeCoord(flag, flagYsame | flagYShort, y, yBytes) + + +ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes +ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points +ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true +WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0 +NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!) +MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one +WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy +WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11 +WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow +USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph +OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts +SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple) +UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS) + + +CompositeMaxpValues = namedtuple( + "CompositeMaxpValues", ["nPoints", "nContours", "maxComponentDepth"] +) + + +class Glyph(object): + """This class represents an individual TrueType glyph. + + TrueType glyph objects come in two flavours: simple and composite. Simple + glyph objects contain contours, represented via the ``.coordinates``, + ``.flags``, ``.numberOfContours``, and ``.endPtsOfContours`` attributes; + composite glyphs contain components, available through the ``.components`` + attributes. + + Because the ``.coordinates`` attribute (and other simple glyph attributes mentioned + above) is only set on simple glyphs and the ``.components`` attribute is only + set on composite glyphs, it is necessary to use the :py:meth:`isComposite` + method to test whether a glyph is simple or composite before attempting to + access its data. + + For a composite glyph, the components can also be accessed via array-like access:: + + >> assert(font["glyf"]["Aacute"].isComposite()) + >> font["glyf"]["Aacute"][0] + <fontTools.ttLib.tables._g_l_y_f.GlyphComponent at 0x1027b2ee0> + + """ + + def __init__(self, data=b""): + if not data: + # empty char + self.numberOfContours = 0 + return + self.data = data + + def compact(self, glyfTable, recalcBBoxes=True): + data = self.compile(glyfTable, recalcBBoxes) + self.__dict__.clear() + self.data = data + + def expand(self, glyfTable): + if not hasattr(self, "data"): + # already unpacked + return + if not self.data: + # empty char + del self.data + self.numberOfContours = 0 + return + dummy, data = sstruct.unpack2(glyphHeaderFormat, self.data, self) + del self.data + # Some fonts (eg. Neirizi.ttf) have a 0 for numberOfContours in + # some glyphs; decompileCoordinates assumes that there's at least + # one, so short-circuit here. + if self.numberOfContours == 0: + return + if self.isComposite(): + self.decompileComponents(data, glyfTable) + else: + self.decompileCoordinates(data) + + def compile( + self, glyfTable, recalcBBoxes=True, *, boundsDone=None, optimizeSize=True + ): + if hasattr(self, "data"): + if recalcBBoxes: + # must unpack glyph in order to recalculate bounding box + self.expand(glyfTable) + else: + return self.data + if self.numberOfContours == 0: + return b"" + + if recalcBBoxes: + self.recalcBounds(glyfTable, boundsDone=boundsDone) + + data = sstruct.pack(glyphHeaderFormat, self) + if self.isComposite(): + data = data + self.compileComponents(glyfTable) + else: + data = data + self.compileCoordinates(optimizeSize=optimizeSize) + return data + + def toXML(self, writer, ttFont): + if self.isComposite(): + for compo in self.components: + compo.toXML(writer, ttFont) + haveInstructions = hasattr(self, "program") + else: + last = 0 + for i in range(self.numberOfContours): + writer.begintag("contour") + writer.newline() + for j in range(last, self.endPtsOfContours[i] + 1): + attrs = [ + ("x", self.coordinates[j][0]), + ("y", self.coordinates[j][1]), + ("on", self.flags[j] & flagOnCurve), + ] + if self.flags[j] & flagOverlapSimple: + # Apple's rasterizer uses flagOverlapSimple in the first contour/first pt to flag glyphs that contain overlapping contours + attrs.append(("overlap", 1)) + if self.flags[j] & flagCubic: + attrs.append(("cubic", 1)) + writer.simpletag("pt", attrs) + writer.newline() + last = self.endPtsOfContours[i] + 1 + writer.endtag("contour") + writer.newline() + haveInstructions = self.numberOfContours > 0 + if haveInstructions: + if self.program: + writer.begintag("instructions") + writer.newline() + self.program.toXML(writer, ttFont) + writer.endtag("instructions") + else: + writer.simpletag("instructions") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "contour": + if self.numberOfContours < 0: + raise ttLib.TTLibError("can't mix composites and contours in glyph") + self.numberOfContours = self.numberOfContours + 1 + coordinates = GlyphCoordinates() + flags = bytearray() + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name != "pt": + continue # ignore anything but "pt" + coordinates.append((safeEval(attrs["x"]), safeEval(attrs["y"]))) + flag = bool(safeEval(attrs["on"])) + if "overlap" in attrs and bool(safeEval(attrs["overlap"])): + flag |= flagOverlapSimple + if "cubic" in attrs and bool(safeEval(attrs["cubic"])): + flag |= flagCubic + flags.append(flag) + if not hasattr(self, "coordinates"): + self.coordinates = coordinates + self.flags = flags + self.endPtsOfContours = [len(coordinates) - 1] + else: + self.coordinates.extend(coordinates) + self.flags.extend(flags) + self.endPtsOfContours.append(len(self.coordinates) - 1) + elif name == "component": + if self.numberOfContours > 0: + raise ttLib.TTLibError("can't mix composites and contours in glyph") + self.numberOfContours = -1 + if not hasattr(self, "components"): + self.components = [] + component = GlyphComponent() + self.components.append(component) + component.fromXML(name, attrs, content, ttFont) + elif name == "instructions": + self.program = ttProgram.Program() + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + self.program.fromXML(name, attrs, content, ttFont) + + def getCompositeMaxpValues(self, glyfTable, maxComponentDepth=1): + assert self.isComposite() + nContours = 0 + nPoints = 0 + initialMaxComponentDepth = maxComponentDepth + for compo in self.components: + baseGlyph = glyfTable[compo.glyphName] + if baseGlyph.numberOfContours == 0: + continue + elif baseGlyph.numberOfContours > 0: + nP, nC = baseGlyph.getMaxpValues() + else: + nP, nC, componentDepth = baseGlyph.getCompositeMaxpValues( + glyfTable, initialMaxComponentDepth + 1 + ) + maxComponentDepth = max(maxComponentDepth, componentDepth) + nPoints = nPoints + nP + nContours = nContours + nC + return CompositeMaxpValues(nPoints, nContours, maxComponentDepth) + + def getMaxpValues(self): + assert self.numberOfContours > 0 + return len(self.coordinates), len(self.endPtsOfContours) + + def decompileComponents(self, data, glyfTable): + self.components = [] + more = 1 + haveInstructions = 0 + while more: + component = GlyphComponent() + more, haveInstr, data = component.decompile(data, glyfTable) + haveInstructions = haveInstructions | haveInstr + self.components.append(component) + if haveInstructions: + (numInstructions,) = struct.unpack(">h", data[:2]) + data = data[2:] + self.program = ttProgram.Program() + self.program.fromBytecode(data[:numInstructions]) + data = data[numInstructions:] + if len(data) >= 4: + log.warning( + "too much glyph data at the end of composite glyph: %d excess bytes", + len(data), + ) + + def decompileCoordinates(self, data): + endPtsOfContours = array.array("H") + endPtsOfContours.frombytes(data[: 2 * self.numberOfContours]) + if sys.byteorder != "big": + endPtsOfContours.byteswap() + self.endPtsOfContours = endPtsOfContours.tolist() + + pos = 2 * self.numberOfContours + (instructionLength,) = struct.unpack(">h", data[pos : pos + 2]) + self.program = ttProgram.Program() + self.program.fromBytecode(data[pos + 2 : pos + 2 + instructionLength]) + pos += 2 + instructionLength + nCoordinates = self.endPtsOfContours[-1] + 1 + flags, xCoordinates, yCoordinates = self.decompileCoordinatesRaw( + nCoordinates, data, pos + ) + + # fill in repetitions and apply signs + self.coordinates = coordinates = GlyphCoordinates.zeros(nCoordinates) + xIndex = 0 + yIndex = 0 + for i in range(nCoordinates): + flag = flags[i] + # x coordinate + if flag & flagXShort: + if flag & flagXsame: + x = xCoordinates[xIndex] + else: + x = -xCoordinates[xIndex] + xIndex = xIndex + 1 + elif flag & flagXsame: + x = 0 + else: + x = xCoordinates[xIndex] + xIndex = xIndex + 1 + # y coordinate + if flag & flagYShort: + if flag & flagYsame: + y = yCoordinates[yIndex] + else: + y = -yCoordinates[yIndex] + yIndex = yIndex + 1 + elif flag & flagYsame: + y = 0 + else: + y = yCoordinates[yIndex] + yIndex = yIndex + 1 + coordinates[i] = (x, y) + assert xIndex == len(xCoordinates) + assert yIndex == len(yCoordinates) + coordinates.relativeToAbsolute() + # discard all flags except "keepFlags" + for i in range(len(flags)): + flags[i] &= keepFlags + self.flags = flags + + def decompileCoordinatesRaw(self, nCoordinates, data, pos=0): + # unpack flags and prepare unpacking of coordinates + flags = bytearray(nCoordinates) + # Warning: deep Python trickery going on. We use the struct module to unpack + # the coordinates. We build a format string based on the flags, so we can + # unpack the coordinates in one struct.unpack() call. + xFormat = ">" # big endian + yFormat = ">" # big endian + j = 0 + while True: + flag = data[pos] + pos += 1 + repeat = 1 + if flag & flagRepeat: + repeat = data[pos] + 1 + pos += 1 + for k in range(repeat): + if flag & flagXShort: + xFormat = xFormat + "B" + elif not (flag & flagXsame): + xFormat = xFormat + "h" + if flag & flagYShort: + yFormat = yFormat + "B" + elif not (flag & flagYsame): + yFormat = yFormat + "h" + flags[j] = flag + j = j + 1 + if j >= nCoordinates: + break + assert j == nCoordinates, "bad glyph flags" + # unpack raw coordinates, krrrrrr-tching! + xDataLen = struct.calcsize(xFormat) + yDataLen = struct.calcsize(yFormat) + if len(data) - pos - (xDataLen + yDataLen) >= 4: + log.warning( + "too much glyph data: %d excess bytes", + len(data) - pos - (xDataLen + yDataLen), + ) + xCoordinates = struct.unpack(xFormat, data[pos : pos + xDataLen]) + yCoordinates = struct.unpack( + yFormat, data[pos + xDataLen : pos + xDataLen + yDataLen] + ) + return flags, xCoordinates, yCoordinates + + def compileComponents(self, glyfTable): + data = b"" + lastcomponent = len(self.components) - 1 + more = 1 + haveInstructions = 0 + for i, compo in enumerate(self.components): + if i == lastcomponent: + haveInstructions = hasattr(self, "program") + more = 0 + data = data + compo.compile(more, haveInstructions, glyfTable) + if haveInstructions: + instructions = self.program.getBytecode() + data = data + struct.pack(">h", len(instructions)) + instructions + return data + + def compileCoordinates(self, *, optimizeSize=True): + assert len(self.coordinates) == len(self.flags) + data = [] + endPtsOfContours = array.array("H", self.endPtsOfContours) + if sys.byteorder != "big": + endPtsOfContours.byteswap() + data.append(endPtsOfContours.tobytes()) + instructions = self.program.getBytecode() + data.append(struct.pack(">h", len(instructions))) + data.append(instructions) + + deltas = self.coordinates.copy() + deltas.toInt() + deltas.absoluteToRelative() + + if optimizeSize: + # TODO(behdad): Add a configuration option for this? + deltas = self.compileDeltasGreedy(self.flags, deltas) + # deltas = self.compileDeltasOptimal(self.flags, deltas) + else: + deltas = self.compileDeltasForSpeed(self.flags, deltas) + + data.extend(deltas) + return b"".join(data) + + def compileDeltasGreedy(self, flags, deltas): + # Implements greedy algorithm for packing coordinate deltas: + # uses shortest representation one coordinate at a time. + compressedFlags = bytearray() + compressedXs = bytearray() + compressedYs = bytearray() + lastflag = None + repeat = 0 + for flag, (x, y) in zip(flags, deltas): + # Oh, the horrors of TrueType + # do x + if x == 0: + flag = flag | flagXsame + elif -255 <= x <= 255: + flag = flag | flagXShort + if x > 0: + flag = flag | flagXsame + else: + x = -x + compressedXs.append(x) + else: + compressedXs.extend(struct.pack(">h", x)) + # do y + if y == 0: + flag = flag | flagYsame + elif -255 <= y <= 255: + flag = flag | flagYShort + if y > 0: + flag = flag | flagYsame + else: + y = -y + compressedYs.append(y) + else: + compressedYs.extend(struct.pack(">h", y)) + # handle repeating flags + if flag == lastflag and repeat != 255: + repeat = repeat + 1 + if repeat == 1: + compressedFlags.append(flag) + else: + compressedFlags[-2] = flag | flagRepeat + compressedFlags[-1] = repeat + else: + repeat = 0 + compressedFlags.append(flag) + lastflag = flag + return (compressedFlags, compressedXs, compressedYs) + + def compileDeltasOptimal(self, flags, deltas): + # Implements optimal, dynaic-programming, algorithm for packing coordinate + # deltas. The savings are negligible :(. + candidates = [] + bestTuple = None + bestCost = 0 + repeat = 0 + for flag, (x, y) in zip(flags, deltas): + # Oh, the horrors of TrueType + flag, coordBytes = flagBest(x, y, flag) + bestCost += 1 + coordBytes + newCandidates = [ + (bestCost, bestTuple, flag, coordBytes), + (bestCost + 1, bestTuple, (flag | flagRepeat), coordBytes), + ] + for lastCost, lastTuple, lastFlag, coordBytes in candidates: + if ( + lastCost + coordBytes <= bestCost + 1 + and (lastFlag & flagRepeat) + and (lastFlag < 0xFF00) + and flagSupports(lastFlag, flag) + ): + if (lastFlag & 0xFF) == ( + flag | flagRepeat + ) and lastCost == bestCost + 1: + continue + newCandidates.append( + (lastCost + coordBytes, lastTuple, lastFlag + 256, coordBytes) + ) + candidates = newCandidates + bestTuple = min(candidates, key=lambda t: t[0]) + bestCost = bestTuple[0] + + flags = [] + while bestTuple: + cost, bestTuple, flag, coordBytes = bestTuple + flags.append(flag) + flags.reverse() + + compressedFlags = bytearray() + compressedXs = bytearray() + compressedYs = bytearray() + coords = iter(deltas) + ff = [] + for flag in flags: + repeatCount, flag = flag >> 8, flag & 0xFF + compressedFlags.append(flag) + if flag & flagRepeat: + assert repeatCount > 0 + compressedFlags.append(repeatCount) + else: + assert repeatCount == 0 + for i in range(1 + repeatCount): + x, y = next(coords) + flagEncodeCoords(flag, x, y, compressedXs, compressedYs) + ff.append(flag) + try: + next(coords) + raise Exception("internal error") + except StopIteration: + pass + + return (compressedFlags, compressedXs, compressedYs) + + def compileDeltasForSpeed(self, flags, deltas): + # uses widest representation needed, for all deltas. + compressedFlags = bytearray() + compressedXs = bytearray() + compressedYs = bytearray() + + # Compute the necessary width for each axis + xs = [d[0] for d in deltas] + ys = [d[1] for d in deltas] + minX, minY, maxX, maxY = min(xs), min(ys), max(xs), max(ys) + xZero = minX == 0 and maxX == 0 + yZero = minY == 0 and maxY == 0 + xShort = -255 <= minX <= maxX <= 255 + yShort = -255 <= minY <= maxY <= 255 + + lastflag = None + repeat = 0 + for flag, (x, y) in zip(flags, deltas): + # Oh, the horrors of TrueType + # do x + if xZero: + flag = flag | flagXsame + elif xShort: + flag = flag | flagXShort + if x > 0: + flag = flag | flagXsame + else: + x = -x + compressedXs.append(x) + else: + compressedXs.extend(struct.pack(">h", x)) + # do y + if yZero: + flag = flag | flagYsame + elif yShort: + flag = flag | flagYShort + if y > 0: + flag = flag | flagYsame + else: + y = -y + compressedYs.append(y) + else: + compressedYs.extend(struct.pack(">h", y)) + # handle repeating flags + if flag == lastflag and repeat != 255: + repeat = repeat + 1 + if repeat == 1: + compressedFlags.append(flag) + else: + compressedFlags[-2] = flag | flagRepeat + compressedFlags[-1] = repeat + else: + repeat = 0 + compressedFlags.append(flag) + lastflag = flag + return (compressedFlags, compressedXs, compressedYs) + + def recalcBounds(self, glyfTable, *, boundsDone=None): + """Recalculates the bounds of the glyph. + + Each glyph object stores its bounding box in the + ``xMin``/``yMin``/``xMax``/``yMax`` attributes. These bounds must be + recomputed when the ``coordinates`` change. The ``table__g_l_y_f`` bounds + must be provided to resolve component bounds. + """ + if self.isComposite() and self.tryRecalcBoundsComposite( + glyfTable, boundsDone=boundsDone + ): + return + try: + coords, endPts, flags = self.getCoordinates(glyfTable, round=otRound) + self.xMin, self.yMin, self.xMax, self.yMax = coords.calcIntBounds() + except NotImplementedError: + pass + + def tryRecalcBoundsComposite(self, glyfTable, *, boundsDone=None): + """Try recalculating the bounds of a composite glyph that has + certain constrained properties. Namely, none of the components + have a transform other than an integer translate, and none + uses the anchor points. + + Each glyph object stores its bounding box in the + ``xMin``/``yMin``/``xMax``/``yMax`` attributes. These bounds must be + recomputed when the ``coordinates`` change. The ``table__g_l_y_f`` bounds + must be provided to resolve component bounds. + + Return True if bounds were calculated, False otherwise. + """ + for compo in self.components: + if not compo._hasOnlyIntegerTranslate(): + return False + + # All components are untransformed and have an integer x/y translate + bounds = None + for compo in self.components: + glyphName = compo.glyphName + g = glyfTable[glyphName] + + if boundsDone is None or glyphName not in boundsDone: + try: + g.recalcBounds(glyfTable, boundsDone=boundsDone) + except RecursionError: + raise ttLib.TTLibError( + "glyph '%s' contains a recursive component reference" + % glyphName + ) + if boundsDone is not None: + boundsDone.add(glyphName) + # empty components shouldn't update the bounds of the parent glyph + if g.yMin == g.yMax and g.xMin == g.xMax: + continue + + x, y = compo.x, compo.y + bounds = updateBounds(bounds, (g.xMin + x, g.yMin + y)) + bounds = updateBounds(bounds, (g.xMax + x, g.yMax + y)) + + if bounds is None: + bounds = (0, 0, 0, 0) + self.xMin, self.yMin, self.xMax, self.yMax = bounds + return True + + def isComposite(self): + """Test whether a glyph has components""" + if hasattr(self, "data"): + return struct.unpack(">h", self.data[:2])[0] == -1 if self.data else False + else: + return self.numberOfContours == -1 + + def getCoordinates(self, glyfTable, *, round=noRound): + """Return the coordinates, end points and flags + + This method returns three values: A :py:class:`GlyphCoordinates` object, + a list of the indexes of the final points of each contour (allowing you + to split up the coordinates list into contours) and a list of flags. + + On simple glyphs, this method returns information from the glyph's own + contours; on composite glyphs, it "flattens" all components recursively + to return a list of coordinates representing all the components involved + in the glyph. + + To interpret the flags for each point, see the "Simple Glyph Flags" + section of the `glyf table specification <https://docs.microsoft.com/en-us/typography/opentype/spec/glyf#simple-glyph-description>`. + """ + + if self.numberOfContours > 0: + return self.coordinates, self.endPtsOfContours, self.flags + elif self.isComposite(): + # it's a composite + allCoords = GlyphCoordinates() + allFlags = bytearray() + allEndPts = [] + for compo in self.components: + g = glyfTable[compo.glyphName] + try: + coordinates, endPts, flags = g.getCoordinates( + glyfTable, round=round + ) + except RecursionError: + raise ttLib.TTLibError( + "glyph '%s' contains a recursive component reference" + % compo.glyphName + ) + coordinates = GlyphCoordinates(coordinates) + # if asked to round e.g. while computing bboxes, it's important we + # do it immediately before a component transform is applied to a + # simple glyph's coordinates in case these might still contain floats; + # however, if the referenced component glyph is another composite, we + # must not round here but only at the end, after all the nested + # transforms have been applied, or else rounding errors will compound. + if round is not noRound and g.numberOfContours > 0: + coordinates.toInt(round=round) + if hasattr(compo, "firstPt"): + # component uses two reference points: we apply the transform _before_ + # computing the offset between the points + if hasattr(compo, "transform"): + coordinates.transform(compo.transform) + x1, y1 = allCoords[compo.firstPt] + x2, y2 = coordinates[compo.secondPt] + move = x1 - x2, y1 - y2 + coordinates.translate(move) + else: + # component uses XY offsets + move = compo.x, compo.y + if not hasattr(compo, "transform"): + coordinates.translate(move) + else: + apple_way = compo.flags & SCALED_COMPONENT_OFFSET + ms_way = compo.flags & UNSCALED_COMPONENT_OFFSET + assert not (apple_way and ms_way) + if not (apple_way or ms_way): + scale_component_offset = ( + SCALE_COMPONENT_OFFSET_DEFAULT # see top of this file + ) + else: + scale_component_offset = apple_way + if scale_component_offset: + # the Apple way: first move, then scale (ie. scale the component offset) + coordinates.translate(move) + coordinates.transform(compo.transform) + else: + # the MS way: first scale, then move + coordinates.transform(compo.transform) + coordinates.translate(move) + offset = len(allCoords) + allEndPts.extend(e + offset for e in endPts) + allCoords.extend(coordinates) + allFlags.extend(flags) + return allCoords, allEndPts, allFlags + else: + return GlyphCoordinates(), [], bytearray() + + def getComponentNames(self, glyfTable): + """Returns a list of names of component glyphs used in this glyph + + This method can be used on simple glyphs (in which case it returns an + empty list) or composite glyphs. + """ + if not hasattr(self, "data"): + if self.isComposite(): + return [c.glyphName for c in self.components] + else: + return [] + + # Extract components without expanding glyph + + if not self.data or struct.unpack(">h", self.data[:2])[0] >= 0: + return [] # Not composite + + data = self.data + i = 10 + components = [] + more = 1 + while more: + flags, glyphID = struct.unpack(">HH", data[i : i + 4]) + i += 4 + flags = int(flags) + components.append(glyfTable.getGlyphName(int(glyphID))) + + if flags & ARG_1_AND_2_ARE_WORDS: + i += 4 + else: + i += 2 + if flags & WE_HAVE_A_SCALE: + i += 2 + elif flags & WE_HAVE_AN_X_AND_Y_SCALE: + i += 4 + elif flags & WE_HAVE_A_TWO_BY_TWO: + i += 8 + more = flags & MORE_COMPONENTS + + return components + + def trim(self, remove_hinting=False): + """Remove padding and, if requested, hinting, from a glyph. + This works on both expanded and compacted glyphs, without + expanding it.""" + if not hasattr(self, "data"): + if remove_hinting: + if self.isComposite(): + if hasattr(self, "program"): + del self.program + else: + self.program = ttProgram.Program() + self.program.fromBytecode([]) + # No padding to trim. + return + if not self.data: + return + numContours = struct.unpack(">h", self.data[:2])[0] + data = bytearray(self.data) + i = 10 + if numContours >= 0: + i += 2 * numContours # endPtsOfContours + nCoordinates = ((data[i - 2] << 8) | data[i - 1]) + 1 + instructionLen = (data[i] << 8) | data[i + 1] + if remove_hinting: + # Zero instruction length + data[i] = data[i + 1] = 0 + i += 2 + if instructionLen: + # Splice it out + data = data[:i] + data[i + instructionLen :] + instructionLen = 0 + else: + i += 2 + instructionLen + + coordBytes = 0 + j = 0 + while True: + flag = data[i] + i = i + 1 + repeat = 1 + if flag & flagRepeat: + repeat = data[i] + 1 + i = i + 1 + xBytes = yBytes = 0 + if flag & flagXShort: + xBytes = 1 + elif not (flag & flagXsame): + xBytes = 2 + if flag & flagYShort: + yBytes = 1 + elif not (flag & flagYsame): + yBytes = 2 + coordBytes += (xBytes + yBytes) * repeat + j += repeat + if j >= nCoordinates: + break + assert j == nCoordinates, "bad glyph flags" + i += coordBytes + # Remove padding + data = data[:i] + elif self.isComposite(): + more = 1 + we_have_instructions = False + while more: + flags = (data[i] << 8) | data[i + 1] + if remove_hinting: + flags &= ~WE_HAVE_INSTRUCTIONS + if flags & WE_HAVE_INSTRUCTIONS: + we_have_instructions = True + data[i + 0] = flags >> 8 + data[i + 1] = flags & 0xFF + i += 4 + flags = int(flags) + + if flags & ARG_1_AND_2_ARE_WORDS: + i += 4 + else: + i += 2 + if flags & WE_HAVE_A_SCALE: + i += 2 + elif flags & WE_HAVE_AN_X_AND_Y_SCALE: + i += 4 + elif flags & WE_HAVE_A_TWO_BY_TWO: + i += 8 + more = flags & MORE_COMPONENTS + if we_have_instructions: + instructionLen = (data[i] << 8) | data[i + 1] + i += 2 + instructionLen + # Remove padding + data = data[:i] + + self.data = data + + def removeHinting(self): + """Removes TrueType hinting instructions from the glyph.""" + self.trim(remove_hinting=True) + + def draw(self, pen, glyfTable, offset=0): + """Draws the glyph using the supplied pen object. + + Arguments: + pen: An object conforming to the pen protocol. + glyfTable: A :py:class:`table__g_l_y_f` object, to resolve components. + offset (int): A horizontal offset. If provided, all coordinates are + translated by this offset. + """ + + if self.isComposite(): + for component in self.components: + glyphName, transform = component.getComponentInfo() + pen.addComponent(glyphName, transform) + return + + self.expand(glyfTable) + coordinates, endPts, flags = self.getCoordinates(glyfTable) + if offset: + coordinates = coordinates.copy() + coordinates.translate((offset, 0)) + start = 0 + maybeInt = lambda v: int(v) if v == int(v) else v + for end in endPts: + end = end + 1 + contour = coordinates[start:end] + cFlags = [flagOnCurve & f for f in flags[start:end]] + cuFlags = [flagCubic & f for f in flags[start:end]] + start = end + if 1 not in cFlags: + assert all(cuFlags) or not any(cuFlags) + cubic = all(cuFlags) + if cubic: + count = len(contour) + assert count % 2 == 0, "Odd number of cubic off-curves undefined" + l = contour[-1] + f = contour[0] + p0 = (maybeInt((l[0] + f[0]) * 0.5), maybeInt((l[1] + f[1]) * 0.5)) + pen.moveTo(p0) + for i in range(0, count, 2): + p1 = contour[i] + p2 = contour[i + 1] + p4 = contour[i + 2 if i + 2 < count else 0] + p3 = ( + maybeInt((p2[0] + p4[0]) * 0.5), + maybeInt((p2[1] + p4[1]) * 0.5), + ) + pen.curveTo(p1, p2, p3) + else: + # There is not a single on-curve point on the curve, + # use pen.qCurveTo's special case by specifying None + # as the on-curve point. + contour.append(None) + pen.qCurveTo(*contour) + else: + # Shuffle the points so that the contour is guaranteed + # to *end* in an on-curve point, which we'll use for + # the moveTo. + firstOnCurve = cFlags.index(1) + 1 + contour = contour[firstOnCurve:] + contour[:firstOnCurve] + cFlags = cFlags[firstOnCurve:] + cFlags[:firstOnCurve] + cuFlags = cuFlags[firstOnCurve:] + cuFlags[:firstOnCurve] + pen.moveTo(contour[-1]) + while contour: + nextOnCurve = cFlags.index(1) + 1 + if nextOnCurve == 1: + # Skip a final lineTo(), as it is implied by + # pen.closePath() + if len(contour) > 1: + pen.lineTo(contour[0]) + else: + cubicFlags = [f for f in cuFlags[: nextOnCurve - 1]] + assert all(cubicFlags) or not any(cubicFlags) + cubic = any(cubicFlags) + if cubic: + assert all( + cubicFlags + ), "Mixed cubic and quadratic segment undefined" + + count = nextOnCurve + assert ( + count >= 3 + ), "At least two cubic off-curve points required" + assert ( + count - 1 + ) % 2 == 0, "Odd number of cubic off-curves undefined" + for i in range(0, count - 3, 2): + p1 = contour[i] + p2 = contour[i + 1] + p4 = contour[i + 2] + p3 = ( + maybeInt((p2[0] + p4[0]) * 0.5), + maybeInt((p2[1] + p4[1]) * 0.5), + ) + lastOnCurve = p3 + pen.curveTo(p1, p2, p3) + pen.curveTo(*contour[count - 3 : count]) + else: + pen.qCurveTo(*contour[:nextOnCurve]) + contour = contour[nextOnCurve:] + cFlags = cFlags[nextOnCurve:] + cuFlags = cuFlags[nextOnCurve:] + pen.closePath() + + def drawPoints(self, pen, glyfTable, offset=0): + """Draw the glyph using the supplied pointPen. As opposed to Glyph.draw(), + this will not change the point indices. + """ + + if self.isComposite(): + for component in self.components: + glyphName, transform = component.getComponentInfo() + pen.addComponent(glyphName, transform) + return + + coordinates, endPts, flags = self.getCoordinates(glyfTable) + if offset: + coordinates = coordinates.copy() + coordinates.translate((offset, 0)) + start = 0 + for end in endPts: + end = end + 1 + contour = coordinates[start:end] + cFlags = flags[start:end] + start = end + pen.beginPath() + # Start with the appropriate segment type based on the final segment + + if cFlags[-1] & flagOnCurve: + segmentType = "line" + elif cFlags[-1] & flagCubic: + segmentType = "curve" + else: + segmentType = "qcurve" + for i, pt in enumerate(contour): + if cFlags[i] & flagOnCurve: + pen.addPoint(pt, segmentType=segmentType) + segmentType = "line" + else: + pen.addPoint(pt) + segmentType = "curve" if cFlags[i] & flagCubic else "qcurve" + pen.endPath() + + def __eq__(self, other): + if type(self) != type(other): + return NotImplemented + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + result = self.__eq__(other) + return result if result is NotImplemented else not result + + +# Vector.__round__ uses the built-in (Banker's) `round` but we want +# to use otRound below +_roundv = partial(Vector.__round__, round=otRound) + + +def _is_mid_point(p0: tuple, p1: tuple, p2: tuple) -> bool: + # True if p1 is in the middle of p0 and p2, either before or after rounding + p0 = Vector(p0) + p1 = Vector(p1) + p2 = Vector(p2) + return ((p0 + p2) * 0.5).isclose(p1) or _roundv(p0) + _roundv(p2) == _roundv(p1) * 2 + + +def dropImpliedOnCurvePoints(*interpolatable_glyphs: Glyph) -> Set[int]: + """Drop impliable on-curve points from the (simple) glyph or glyphs. + + In TrueType glyf outlines, on-curve points can be implied when they are located at + the midpoint of the line connecting two consecutive off-curve points. + + If more than one glyphs are passed, these are assumed to be interpolatable masters + of the same glyph impliable, and thus only the on-curve points that are impliable + for all of them will actually be implied. + Composite glyphs or empty glyphs are skipped, only simple glyphs with 1 or more + contours are considered. + The input glyph(s) is/are modified in-place. + + Args: + interpolatable_glyphs: The glyph or glyphs to modify in-place. + + Returns: + The set of point indices that were dropped if any. + + Raises: + ValueError if simple glyphs are not in fact interpolatable because they have + different point flags or number of contours. + + Reference: + https://developer.apple.com/fonts/TrueType-Reference-Manual/RM01/Chap1.html + """ + staticAttributes = SimpleNamespace( + numberOfContours=None, flags=None, endPtsOfContours=None + ) + drop = None + simple_glyphs = [] + for i, glyph in enumerate(interpolatable_glyphs): + if glyph.numberOfContours < 1: + # ignore composite or empty glyphs + continue + + for attr in staticAttributes.__dict__: + expected = getattr(staticAttributes, attr) + found = getattr(glyph, attr) + if expected is None: + setattr(staticAttributes, attr, found) + elif expected != found: + raise ValueError( + f"Incompatible {attr} for glyph at master index {i}: " + f"expected {expected}, found {found}" + ) + + may_drop = set() + start = 0 + coords = glyph.coordinates + flags = staticAttributes.flags + endPtsOfContours = staticAttributes.endPtsOfContours + for last in endPtsOfContours: + for i in range(start, last + 1): + if not (flags[i] & flagOnCurve): + continue + prv = i - 1 if i > start else last + nxt = i + 1 if i < last else start + if (flags[prv] & flagOnCurve) or flags[prv] != flags[nxt]: + continue + # we may drop the ith on-curve if halfway between previous/next off-curves + if not _is_mid_point(coords[prv], coords[i], coords[nxt]): + continue + + may_drop.add(i) + start = last + 1 + # we only want to drop if ALL interpolatable glyphs have the same implied oncurves + if drop is None: + drop = may_drop + else: + drop.intersection_update(may_drop) + + simple_glyphs.append(glyph) + + if drop: + # Do the actual dropping + flags = staticAttributes.flags + assert flags is not None + newFlags = array.array( + "B", (flags[i] for i in range(len(flags)) if i not in drop) + ) + + endPts = staticAttributes.endPtsOfContours + assert endPts is not None + newEndPts = [] + i = 0 + delta = 0 + for d in sorted(drop): + while d > endPts[i]: + newEndPts.append(endPts[i] - delta) + i += 1 + delta += 1 + while i < len(endPts): + newEndPts.append(endPts[i] - delta) + i += 1 + + for glyph in simple_glyphs: + coords = glyph.coordinates + glyph.coordinates = GlyphCoordinates( + coords[i] for i in range(len(coords)) if i not in drop + ) + glyph.flags = newFlags + glyph.endPtsOfContours = newEndPts + + return drop if drop is not None else set() + + +class GlyphComponent(object): + """Represents a component within a composite glyph. + + The component is represented internally with four attributes: ``glyphName``, + ``x``, ``y`` and ``transform``. If there is no "two-by-two" matrix (i.e + no scaling, reflection, or rotation; only translation), the ``transform`` + attribute is not present. + """ + + # The above documentation is not *completely* true, but is *true enough* because + # the rare firstPt/lastPt attributes are not totally supported and nobody seems to + # mind - see below. + + def __init__(self): + pass + + def getComponentInfo(self): + """Return information about the component + + This method returns a tuple of two values: the glyph name of the component's + base glyph, and a transformation matrix. As opposed to accessing the attributes + directly, ``getComponentInfo`` always returns a six-element tuple of the + component's transformation matrix, even when the two-by-two ``.transform`` + matrix is not present. + """ + # XXX Ignoring self.firstPt & self.lastpt for now: I need to implement + # something equivalent in fontTools.objects.glyph (I'd rather not + # convert it to an absolute offset, since it is valuable information). + # This method will now raise "AttributeError: x" on glyphs that use + # this TT feature. + if hasattr(self, "transform"): + [[xx, xy], [yx, yy]] = self.transform + trans = (xx, xy, yx, yy, self.x, self.y) + else: + trans = (1, 0, 0, 1, self.x, self.y) + return self.glyphName, trans + + def decompile(self, data, glyfTable): + flags, glyphID = struct.unpack(">HH", data[:4]) + self.flags = int(flags) + glyphID = int(glyphID) + self.glyphName = glyfTable.getGlyphName(int(glyphID)) + data = data[4:] + + if self.flags & ARG_1_AND_2_ARE_WORDS: + if self.flags & ARGS_ARE_XY_VALUES: + self.x, self.y = struct.unpack(">hh", data[:4]) + else: + x, y = struct.unpack(">HH", data[:4]) + self.firstPt, self.secondPt = int(x), int(y) + data = data[4:] + else: + if self.flags & ARGS_ARE_XY_VALUES: + self.x, self.y = struct.unpack(">bb", data[:2]) + else: + x, y = struct.unpack(">BB", data[:2]) + self.firstPt, self.secondPt = int(x), int(y) + data = data[2:] + + if self.flags & WE_HAVE_A_SCALE: + (scale,) = struct.unpack(">h", data[:2]) + self.transform = [ + [fi2fl(scale, 14), 0], + [0, fi2fl(scale, 14)], + ] # fixed 2.14 + data = data[2:] + elif self.flags & WE_HAVE_AN_X_AND_Y_SCALE: + xscale, yscale = struct.unpack(">hh", data[:4]) + self.transform = [ + [fi2fl(xscale, 14), 0], + [0, fi2fl(yscale, 14)], + ] # fixed 2.14 + data = data[4:] + elif self.flags & WE_HAVE_A_TWO_BY_TWO: + xscale, scale01, scale10, yscale = struct.unpack(">hhhh", data[:8]) + self.transform = [ + [fi2fl(xscale, 14), fi2fl(scale01, 14)], + [fi2fl(scale10, 14), fi2fl(yscale, 14)], + ] # fixed 2.14 + data = data[8:] + more = self.flags & MORE_COMPONENTS + haveInstructions = self.flags & WE_HAVE_INSTRUCTIONS + self.flags = self.flags & ( + ROUND_XY_TO_GRID + | USE_MY_METRICS + | SCALED_COMPONENT_OFFSET + | UNSCALED_COMPONENT_OFFSET + | NON_OVERLAPPING + | OVERLAP_COMPOUND + ) + return more, haveInstructions, data + + def compile(self, more, haveInstructions, glyfTable): + data = b"" + + # reset all flags we will calculate ourselves + flags = self.flags & ( + ROUND_XY_TO_GRID + | USE_MY_METRICS + | SCALED_COMPONENT_OFFSET + | UNSCALED_COMPONENT_OFFSET + | NON_OVERLAPPING + | OVERLAP_COMPOUND + ) + if more: + flags = flags | MORE_COMPONENTS + if haveInstructions: + flags = flags | WE_HAVE_INSTRUCTIONS + + if hasattr(self, "firstPt"): + if (0 <= self.firstPt <= 255) and (0 <= self.secondPt <= 255): + data = data + struct.pack(">BB", self.firstPt, self.secondPt) + else: + data = data + struct.pack(">HH", self.firstPt, self.secondPt) + flags = flags | ARG_1_AND_2_ARE_WORDS + else: + x = otRound(self.x) + y = otRound(self.y) + flags = flags | ARGS_ARE_XY_VALUES + if (-128 <= x <= 127) and (-128 <= y <= 127): + data = data + struct.pack(">bb", x, y) + else: + data = data + struct.pack(">hh", x, y) + flags = flags | ARG_1_AND_2_ARE_WORDS + + if hasattr(self, "transform"): + transform = [[fl2fi(x, 14) for x in row] for row in self.transform] + if transform[0][1] or transform[1][0]: + flags = flags | WE_HAVE_A_TWO_BY_TWO + data = data + struct.pack( + ">hhhh", + transform[0][0], + transform[0][1], + transform[1][0], + transform[1][1], + ) + elif transform[0][0] != transform[1][1]: + flags = flags | WE_HAVE_AN_X_AND_Y_SCALE + data = data + struct.pack(">hh", transform[0][0], transform[1][1]) + else: + flags = flags | WE_HAVE_A_SCALE + data = data + struct.pack(">h", transform[0][0]) + + glyphID = glyfTable.getGlyphID(self.glyphName) + return struct.pack(">HH", flags, glyphID) + data + + def toXML(self, writer, ttFont): + attrs = [("glyphName", self.glyphName)] + if not hasattr(self, "firstPt"): + attrs = attrs + [("x", self.x), ("y", self.y)] + else: + attrs = attrs + [("firstPt", self.firstPt), ("secondPt", self.secondPt)] + + if hasattr(self, "transform"): + transform = self.transform + if transform[0][1] or transform[1][0]: + attrs = attrs + [ + ("scalex", fl2str(transform[0][0], 14)), + ("scale01", fl2str(transform[0][1], 14)), + ("scale10", fl2str(transform[1][0], 14)), + ("scaley", fl2str(transform[1][1], 14)), + ] + elif transform[0][0] != transform[1][1]: + attrs = attrs + [ + ("scalex", fl2str(transform[0][0], 14)), + ("scaley", fl2str(transform[1][1], 14)), + ] + else: + attrs = attrs + [("scale", fl2str(transform[0][0], 14))] + attrs = attrs + [("flags", hex(self.flags))] + writer.simpletag("component", attrs) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + self.glyphName = attrs["glyphName"] + if "firstPt" in attrs: + self.firstPt = safeEval(attrs["firstPt"]) + self.secondPt = safeEval(attrs["secondPt"]) + else: + self.x = safeEval(attrs["x"]) + self.y = safeEval(attrs["y"]) + if "scale01" in attrs: + scalex = str2fl(attrs["scalex"], 14) + scale01 = str2fl(attrs["scale01"], 14) + scale10 = str2fl(attrs["scale10"], 14) + scaley = str2fl(attrs["scaley"], 14) + self.transform = [[scalex, scale01], [scale10, scaley]] + elif "scalex" in attrs: + scalex = str2fl(attrs["scalex"], 14) + scaley = str2fl(attrs["scaley"], 14) + self.transform = [[scalex, 0], [0, scaley]] + elif "scale" in attrs: + scale = str2fl(attrs["scale"], 14) + self.transform = [[scale, 0], [0, scale]] + self.flags = safeEval(attrs["flags"]) + + def __eq__(self, other): + if type(self) != type(other): + return NotImplemented + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + result = self.__eq__(other) + return result if result is NotImplemented else not result + + def _hasOnlyIntegerTranslate(self): + """Return True if it's a 'simple' component. + + That is, it has no anchor points and no transform other than integer translate. + """ + return ( + not hasattr(self, "firstPt") + and not hasattr(self, "transform") + and float(self.x).is_integer() + and float(self.y).is_integer() + ) + + +class GlyphCoordinates(object): + """A list of glyph coordinates. + + Unlike an ordinary list, this is a numpy-like matrix object which supports + matrix addition, scalar multiplication and other operations described below. + """ + + def __init__(self, iterable=[]): + self._a = array.array("d") + self.extend(iterable) + + @property + def array(self): + """Returns the underlying array of coordinates""" + return self._a + + @staticmethod + def zeros(count): + """Creates a new ``GlyphCoordinates`` object with all coordinates set to (0,0)""" + g = GlyphCoordinates() + g._a.frombytes(bytes(count * 2 * g._a.itemsize)) + return g + + def copy(self): + """Creates a new ``GlyphCoordinates`` object which is a copy of the current one.""" + c = GlyphCoordinates() + c._a.extend(self._a) + return c + + def __len__(self): + """Returns the number of coordinates in the array.""" + return len(self._a) // 2 + + def __getitem__(self, k): + """Returns a two element tuple (x,y)""" + a = self._a + if isinstance(k, slice): + indices = range(*k.indices(len(self))) + # Instead of calling ourselves recursively, duplicate code; faster + ret = [] + for k in indices: + x = a[2 * k] + y = a[2 * k + 1] + ret.append( + (int(x) if x.is_integer() else x, int(y) if y.is_integer() else y) + ) + return ret + x = a[2 * k] + y = a[2 * k + 1] + return (int(x) if x.is_integer() else x, int(y) if y.is_integer() else y) + + def __setitem__(self, k, v): + """Sets a point's coordinates to a two element tuple (x,y)""" + if isinstance(k, slice): + indices = range(*k.indices(len(self))) + # XXX This only works if len(v) == len(indices) + for j, i in enumerate(indices): + self[i] = v[j] + return + self._a[2 * k], self._a[2 * k + 1] = v + + def __delitem__(self, i): + """Removes a point from the list""" + i = (2 * i) % len(self._a) + del self._a[i] + del self._a[i] + + def __repr__(self): + return "GlyphCoordinates([" + ",".join(str(c) for c in self) + "])" + + def append(self, p): + self._a.extend(tuple(p)) + + def extend(self, iterable): + for p in iterable: + self._a.extend(p) + + def toInt(self, *, round=otRound): + if round is noRound: + return + a = self._a + for i, value in enumerate(a): + a[i] = round(value) + + def calcBounds(self): + a = self._a + if not a: + return 0, 0, 0, 0 + xs = a[0::2] + ys = a[1::2] + return min(xs), min(ys), max(xs), max(ys) + + def calcIntBounds(self, round=otRound): + return tuple(round(v) for v in self.calcBounds()) + + def relativeToAbsolute(self): + a = self._a + x, y = 0, 0 + for i in range(0, len(a), 2): + a[i] = x = a[i] + x + a[i + 1] = y = a[i + 1] + y + + def absoluteToRelative(self): + a = self._a + x, y = 0, 0 + for i in range(0, len(a), 2): + nx = a[i] + ny = a[i + 1] + a[i] = nx - x + a[i + 1] = ny - y + x = nx + y = ny + + def translate(self, p): + """ + >>> GlyphCoordinates([(1,2)]).translate((.5,0)) + """ + x, y = p + if x == 0 and y == 0: + return + a = self._a + for i in range(0, len(a), 2): + a[i] += x + a[i + 1] += y + + def scale(self, p): + """ + >>> GlyphCoordinates([(1,2)]).scale((.5,0)) + """ + x, y = p + if x == 1 and y == 1: + return + a = self._a + for i in range(0, len(a), 2): + a[i] *= x + a[i + 1] *= y + + def transform(self, t): + """ + >>> GlyphCoordinates([(1,2)]).transform(((.5,0),(.2,.5))) + """ + a = self._a + for i in range(0, len(a), 2): + x = a[i] + y = a[i + 1] + px = x * t[0][0] + y * t[1][0] + py = x * t[0][1] + y * t[1][1] + a[i] = px + a[i + 1] = py + + def __eq__(self, other): + """ + >>> g = GlyphCoordinates([(1,2)]) + >>> g2 = GlyphCoordinates([(1.0,2)]) + >>> g3 = GlyphCoordinates([(1.5,2)]) + >>> g == g2 + True + >>> g == g3 + False + >>> g2 == g3 + False + """ + if type(self) != type(other): + return NotImplemented + return self._a == other._a + + def __ne__(self, other): + """ + >>> g = GlyphCoordinates([(1,2)]) + >>> g2 = GlyphCoordinates([(1.0,2)]) + >>> g3 = GlyphCoordinates([(1.5,2)]) + >>> g != g2 + False + >>> g != g3 + True + >>> g2 != g3 + True + """ + result = self.__eq__(other) + return result if result is NotImplemented else not result + + # Math operations + + def __pos__(self): + """ + >>> g = GlyphCoordinates([(1,2)]) + >>> g + GlyphCoordinates([(1, 2)]) + >>> g2 = +g + >>> g2 + GlyphCoordinates([(1, 2)]) + >>> g2.translate((1,0)) + >>> g2 + GlyphCoordinates([(2, 2)]) + >>> g + GlyphCoordinates([(1, 2)]) + """ + return self.copy() + + def __neg__(self): + """ + >>> g = GlyphCoordinates([(1,2)]) + >>> g + GlyphCoordinates([(1, 2)]) + >>> g2 = -g + >>> g2 + GlyphCoordinates([(-1, -2)]) + >>> g + GlyphCoordinates([(1, 2)]) + """ + r = self.copy() + a = r._a + for i, value in enumerate(a): + a[i] = -value + return r + + def __round__(self, *, round=otRound): + r = self.copy() + r.toInt(round=round) + return r + + def __add__(self, other): + return self.copy().__iadd__(other) + + def __sub__(self, other): + return self.copy().__isub__(other) + + def __mul__(self, other): + return self.copy().__imul__(other) + + def __truediv__(self, other): + return self.copy().__itruediv__(other) + + __radd__ = __add__ + __rmul__ = __mul__ + + def __rsub__(self, other): + return other + (-self) + + def __iadd__(self, other): + """ + >>> g = GlyphCoordinates([(1,2)]) + >>> g += (.5,0) + >>> g + GlyphCoordinates([(1.5, 2)]) + >>> g2 = GlyphCoordinates([(3,4)]) + >>> g += g2 + >>> g + GlyphCoordinates([(4.5, 6)]) + """ + if isinstance(other, tuple): + assert len(other) == 2 + self.translate(other) + return self + if isinstance(other, GlyphCoordinates): + other = other._a + a = self._a + assert len(a) == len(other) + for i, value in enumerate(other): + a[i] += value + return self + return NotImplemented + + def __isub__(self, other): + """ + >>> g = GlyphCoordinates([(1,2)]) + >>> g -= (.5,0) + >>> g + GlyphCoordinates([(0.5, 2)]) + >>> g2 = GlyphCoordinates([(3,4)]) + >>> g -= g2 + >>> g + GlyphCoordinates([(-2.5, -2)]) + """ + if isinstance(other, tuple): + assert len(other) == 2 + self.translate((-other[0], -other[1])) + return self + if isinstance(other, GlyphCoordinates): + other = other._a + a = self._a + assert len(a) == len(other) + for i, value in enumerate(other): + a[i] -= value + return self + return NotImplemented + + def __imul__(self, other): + """ + >>> g = GlyphCoordinates([(1,2)]) + >>> g *= (2,.5) + >>> g *= 2 + >>> g + GlyphCoordinates([(4, 2)]) + >>> g = GlyphCoordinates([(1,2)]) + >>> g *= 2 + >>> g + GlyphCoordinates([(2, 4)]) + """ + if isinstance(other, tuple): + assert len(other) == 2 + self.scale(other) + return self + if isinstance(other, Number): + if other == 1: + return self + a = self._a + for i in range(len(a)): + a[i] *= other + return self + return NotImplemented + + def __itruediv__(self, other): + """ + >>> g = GlyphCoordinates([(1,3)]) + >>> g /= (.5,1.5) + >>> g /= 2 + >>> g + GlyphCoordinates([(1, 1)]) + """ + if isinstance(other, Number): + other = (other, other) + if isinstance(other, tuple): + if other == (1, 1): + return self + assert len(other) == 2 + self.scale((1.0 / other[0], 1.0 / other[1])) + return self + return NotImplemented + + def __bool__(self): + """ + >>> g = GlyphCoordinates([]) + >>> bool(g) + False + >>> g = GlyphCoordinates([(0,0), (0.,0)]) + >>> bool(g) + True + >>> g = GlyphCoordinates([(0,0), (1,0)]) + >>> bool(g) + True + >>> g = GlyphCoordinates([(0,.5), (0,0)]) + >>> bool(g) + True + """ + return bool(self._a) + + __nonzero__ = __bool__ + + +if __name__ == "__main__": + import doctest, sys + + sys.exit(doctest.testmod().failed) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_g_v_a_r.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_g_v_a_r.py new file mode 100644 index 0000000000000000000000000000000000000000..15cc6fab5bd1b92fa0f778eb6d9952b195843786 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_g_v_a_r.py @@ -0,0 +1,340 @@ +from collections import deque +from functools import partial +from fontTools.misc import sstruct +from fontTools.misc.textTools import safeEval +from fontTools.misc.lazyTools import LazyDict +from fontTools.ttLib import OPTIMIZE_FONT_SPEED +from fontTools.ttLib.tables.TupleVariation import TupleVariation +from . import DefaultTable +import array +import itertools +import logging +import struct +import sys +import fontTools.ttLib.tables.TupleVariation as tv + +log = logging.getLogger(__name__) + +# https://www.microsoft.com/typography/otspec/gvar.htm +# https://www.microsoft.com/typography/otspec/otvarcommonformats.htm +# +# Apple's documentation of 'gvar': +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gvar.html +# +# FreeType2 source code for parsing 'gvar': +# http://git.savannah.gnu.org/cgit/freetype/freetype2.git/tree/src/truetype/ttgxvar.c + +GVAR_HEADER_FORMAT_HEAD = """ + > # big endian + version: H + reserved: H + axisCount: H + sharedTupleCount: H + offsetToSharedTuples: I +""" +# In between the HEAD and TAIL lies the glyphCount, which is +# of different size: 2 bytes for gvar, and 3 bytes for GVAR. +GVAR_HEADER_FORMAT_TAIL = """ + > # big endian + flags: H + offsetToGlyphVariationData: I +""" + +GVAR_HEADER_SIZE_HEAD = sstruct.calcsize(GVAR_HEADER_FORMAT_HEAD) +GVAR_HEADER_SIZE_TAIL = sstruct.calcsize(GVAR_HEADER_FORMAT_TAIL) + + +class table__g_v_a_r(DefaultTable.DefaultTable): + """Glyph Variations table + + The ``gvar`` table provides the per-glyph variation data that + describe how glyph outlines in the ``glyf`` table change across + the variation space that is defined for the font in the ``fvar`` + table. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/gvar + """ + + dependencies = ["fvar", "glyf"] + gid_size = 2 + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.version, self.reserved = 1, 0 + self.variations = {} + + def compile(self, ttFont): + axisTags = [axis.axisTag for axis in ttFont["fvar"].axes] + sharedTuples = tv.compileSharedTuples( + axisTags, itertools.chain(*self.variations.values()) + ) + sharedTupleIndices = {coord: i for i, coord in enumerate(sharedTuples)} + sharedTupleSize = sum([len(c) for c in sharedTuples]) + compiledGlyphs = self.compileGlyphs_(ttFont, axisTags, sharedTupleIndices) + offset = 0 + offsets = [] + for glyph in compiledGlyphs: + offsets.append(offset) + offset += len(glyph) + offsets.append(offset) + compiledOffsets, tableFormat = self.compileOffsets_(offsets) + + GVAR_HEADER_SIZE = GVAR_HEADER_SIZE_HEAD + self.gid_size + GVAR_HEADER_SIZE_TAIL + header = {} + header["version"] = self.version + header["reserved"] = self.reserved + header["axisCount"] = len(axisTags) + header["sharedTupleCount"] = len(sharedTuples) + header["offsetToSharedTuples"] = GVAR_HEADER_SIZE + len(compiledOffsets) + header["flags"] = tableFormat + header["offsetToGlyphVariationData"] = ( + header["offsetToSharedTuples"] + sharedTupleSize + ) + + result = [ + sstruct.pack(GVAR_HEADER_FORMAT_HEAD, header), + len(compiledGlyphs).to_bytes(self.gid_size, "big"), + sstruct.pack(GVAR_HEADER_FORMAT_TAIL, header), + ] + + result.append(compiledOffsets) + result.extend(sharedTuples) + result.extend(compiledGlyphs) + return b"".join(result) + + def compileGlyphs_(self, ttFont, axisTags, sharedCoordIndices): + optimizeSpeed = ttFont.cfg[OPTIMIZE_FONT_SPEED] + result = [] + glyf = ttFont["glyf"] + for glyphName in ttFont.getGlyphOrder(): + variations = self.variations.get(glyphName, []) + if not variations: + result.append(b"") + continue + pointCountUnused = 0 # pointCount is actually unused by compileGlyph + result.append( + compileGlyph_( + self.gid_size, + variations, + pointCountUnused, + axisTags, + sharedCoordIndices, + optimizeSize=not optimizeSpeed, + ) + ) + return result + + def decompile(self, data, ttFont): + axisTags = [axis.axisTag for axis in ttFont["fvar"].axes] + glyphs = ttFont.getGlyphOrder() + + # Parse the header + GVAR_HEADER_SIZE = GVAR_HEADER_SIZE_HEAD + self.gid_size + GVAR_HEADER_SIZE_TAIL + sstruct.unpack(GVAR_HEADER_FORMAT_HEAD, data[:GVAR_HEADER_SIZE_HEAD], self) + self.glyphCount = int.from_bytes( + data[GVAR_HEADER_SIZE_HEAD : GVAR_HEADER_SIZE_HEAD + self.gid_size], "big" + ) + sstruct.unpack( + GVAR_HEADER_FORMAT_TAIL, + data[GVAR_HEADER_SIZE_HEAD + self.gid_size : GVAR_HEADER_SIZE], + self, + ) + + assert len(glyphs) == self.glyphCount, (len(glyphs), self.glyphCount) + assert len(axisTags) == self.axisCount, ( + len(axisTags), + self.axisCount, + axisTags, + ) + sharedCoords = tv.decompileSharedTuples( + axisTags, self.sharedTupleCount, data, self.offsetToSharedTuples + ) + variations = {} + offsetToData = self.offsetToGlyphVariationData + glyf = ttFont["glyf"] + + def get_read_item(): + reverseGlyphMap = ttFont.getReverseGlyphMap() + tableFormat = self.flags & 1 + + def read_item(glyphName): + gid = reverseGlyphMap[glyphName] + offsetSize = 2 if tableFormat == 0 else 4 + startOffset = GVAR_HEADER_SIZE + offsetSize * gid + endOffset = startOffset + offsetSize * 2 + offsets = table__g_v_a_r.decompileOffsets_( + data[startOffset:endOffset], + tableFormat=tableFormat, + glyphCount=1, + ) + gvarData = data[offsetToData + offsets[0] : offsetToData + offsets[1]] + if not gvarData: + return [] + glyph = glyf[glyphName] + numPointsInGlyph = self.getNumPoints_(glyph) + return decompileGlyph_( + self.gid_size, numPointsInGlyph, sharedCoords, axisTags, gvarData + ) + + return read_item + + read_item = get_read_item() + l = LazyDict({glyphs[gid]: read_item for gid in range(self.glyphCount)}) + + self.variations = l + + if ttFont.lazy is False: # Be lazy for None and True + self.ensureDecompiled() + + def ensureDecompiled(self, recurse=False): + # The recurse argument is unused, but part of the signature of + # ensureDecompiled across the library. + # Use a zero-length deque to consume the lazy dict + deque(self.variations.values(), maxlen=0) + + @staticmethod + def decompileOffsets_(data, tableFormat, glyphCount): + if tableFormat == 0: + # Short format: array of UInt16 + offsets = array.array("H") + offsetsSize = (glyphCount + 1) * 2 + else: + # Long format: array of UInt32 + offsets = array.array("I") + offsetsSize = (glyphCount + 1) * 4 + offsets.frombytes(data[0:offsetsSize]) + if sys.byteorder != "big": + offsets.byteswap() + + # In the short format, offsets need to be multiplied by 2. + # This is not documented in Apple's TrueType specification, + # but can be inferred from the FreeType implementation, and + # we could verify it with two sample GX fonts. + if tableFormat == 0: + offsets = [off * 2 for off in offsets] + + return offsets + + @staticmethod + def compileOffsets_(offsets): + """Packs a list of offsets into a 'gvar' offset table. + + Returns a pair (bytestring, tableFormat). Bytestring is the + packed offset table. Format indicates whether the table + uses short (tableFormat=0) or long (tableFormat=1) integers. + The returned tableFormat should get packed into the flags field + of the 'gvar' header. + """ + assert len(offsets) >= 2 + for i in range(1, len(offsets)): + assert offsets[i - 1] <= offsets[i] + if max(offsets) <= 0xFFFF * 2: + packed = array.array("H", [n >> 1 for n in offsets]) + tableFormat = 0 + else: + packed = array.array("I", offsets) + tableFormat = 1 + if sys.byteorder != "big": + packed.byteswap() + return (packed.tobytes(), tableFormat) + + def toXML(self, writer, ttFont): + writer.simpletag("version", value=self.version) + writer.newline() + writer.simpletag("reserved", value=self.reserved) + writer.newline() + axisTags = [axis.axisTag for axis in ttFont["fvar"].axes] + for glyphName in ttFont.getGlyphNames(): + variations = self.variations.get(glyphName) + if not variations: + continue + writer.begintag("glyphVariations", glyph=glyphName) + writer.newline() + for gvar in variations: + gvar.toXML(writer, axisTags) + writer.endtag("glyphVariations") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "version": + self.version = safeEval(attrs["value"]) + elif name == "reserved": + self.reserved = safeEval(attrs["value"]) + elif name == "glyphVariations": + if not hasattr(self, "variations"): + self.variations = {} + glyphName = attrs["glyph"] + glyph = ttFont["glyf"][glyphName] + numPointsInGlyph = self.getNumPoints_(glyph) + glyphVariations = [] + for element in content: + if isinstance(element, tuple): + name, attrs, content = element + if name == "tuple": + gvar = TupleVariation({}, [None] * numPointsInGlyph) + glyphVariations.append(gvar) + for tupleElement in content: + if isinstance(tupleElement, tuple): + tupleName, tupleAttrs, tupleContent = tupleElement + gvar.fromXML(tupleName, tupleAttrs, tupleContent) + self.variations[glyphName] = glyphVariations + + @staticmethod + def getNumPoints_(glyph): + NUM_PHANTOM_POINTS = 4 + + if glyph.isComposite(): + return len(glyph.components) + NUM_PHANTOM_POINTS + else: + # Empty glyphs (eg. space, nonmarkingreturn) have no "coordinates" attribute. + return len(getattr(glyph, "coordinates", [])) + NUM_PHANTOM_POINTS + + +def compileGlyph_( + dataOffsetSize, + variations, + pointCount, + axisTags, + sharedCoordIndices, + *, + optimizeSize=True, +): + assert dataOffsetSize in (2, 3) + tupleVariationCount, tuples, data = tv.compileTupleVariationStore( + variations, pointCount, axisTags, sharedCoordIndices, optimizeSize=optimizeSize + ) + if tupleVariationCount == 0: + return b"" + + offsetToData = 2 + dataOffsetSize + len(tuples) + + result = [ + tupleVariationCount.to_bytes(2, "big"), + offsetToData.to_bytes(dataOffsetSize, "big"), + tuples, + data, + ] + if (offsetToData + len(data)) % 2 != 0: + result.append(b"\0") # padding + return b"".join(result) + + +def decompileGlyph_(dataOffsetSize, pointCount, sharedTuples, axisTags, data): + assert dataOffsetSize in (2, 3) + if len(data) < 2 + dataOffsetSize: + return [] + + tupleVariationCount = int.from_bytes(data[:2], "big") + offsetToData = int.from_bytes(data[2 : 2 + dataOffsetSize], "big") + + dataPos = offsetToData + return tv.decompileTupleVariationStore( + "gvar", + axisTags, + tupleVariationCount, + pointCount, + sharedTuples, + data, + 2 + dataOffsetSize, + offsetToData, + ) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_h_d_m_x.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_h_d_m_x.py new file mode 100644 index 0000000000000000000000000000000000000000..07c4566a98dcd36e9b3e2cdc9513793f902d1dd9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_h_d_m_x.py @@ -0,0 +1,127 @@ +from fontTools.misc import sstruct +from fontTools.misc.textTools import bytechr, byteord, strjoin +from . import DefaultTable +import array +from collections.abc import Mapping + +hdmxHeaderFormat = """ + > # big endian! + version: H + numRecords: H + recordSize: l +""" + + +class _GlyphnamedList(Mapping): + def __init__(self, reverseGlyphOrder, data): + self._array = data + self._map = dict(reverseGlyphOrder) + + def __getitem__(self, k): + return self._array[self._map[k]] + + def __len__(self): + return len(self._map) + + def __iter__(self): + return iter(self._map) + + def keys(self): + return self._map.keys() + + +class table__h_d_m_x(DefaultTable.DefaultTable): + """Horizontal Device Metrics table + + The ``hdmx`` table is an optional table that stores advance widths for + glyph outlines at specified pixel sizes. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/hdmx + """ + + def decompile(self, data, ttFont): + numGlyphs = ttFont["maxp"].numGlyphs + glyphOrder = ttFont.getGlyphOrder() + dummy, data = sstruct.unpack2(hdmxHeaderFormat, data, self) + self.hdmx = {} + for i in range(self.numRecords): + ppem = byteord(data[0]) + maxSize = byteord(data[1]) + widths = _GlyphnamedList( + ttFont.getReverseGlyphMap(), array.array("B", data[2 : 2 + numGlyphs]) + ) + self.hdmx[ppem] = widths + data = data[self.recordSize :] + assert len(data) == 0, "too much hdmx data" + + def compile(self, ttFont): + self.version = 0 + numGlyphs = ttFont["maxp"].numGlyphs + glyphOrder = ttFont.getGlyphOrder() + self.recordSize = 4 * ((2 + numGlyphs + 3) // 4) + pad = (self.recordSize - 2 - numGlyphs) * b"\0" + self.numRecords = len(self.hdmx) + data = sstruct.pack(hdmxHeaderFormat, self) + items = sorted(self.hdmx.items()) + for ppem, widths in items: + data = data + bytechr(ppem) + bytechr(max(widths.values())) + for glyphName in glyphOrder: + width = widths[glyphName] + data = data + bytechr(width) + data = data + pad + return data + + def toXML(self, writer, ttFont): + writer.begintag("hdmxData") + writer.newline() + ppems = sorted(self.hdmx.keys()) + records = [] + format = "" + for ppem in ppems: + widths = self.hdmx[ppem] + records.append(widths) + format = format + "%4d" + glyphNames = ttFont.getGlyphOrder()[:] + glyphNames.sort() + maxNameLen = max(map(len, glyphNames)) + format = "%" + repr(maxNameLen) + "s:" + format + " ;" + writer.write(format % (("ppem",) + tuple(ppems))) + writer.newline() + writer.newline() + for glyphName in glyphNames: + row = [] + for ppem in ppems: + widths = self.hdmx[ppem] + row.append(widths[glyphName]) + if ";" in glyphName: + glyphName = "\\x3b".join(glyphName.split(";")) + writer.write(format % ((glyphName,) + tuple(row))) + writer.newline() + writer.endtag("hdmxData") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name != "hdmxData": + return + content = strjoin(content) + lines = content.split(";") + topRow = lines[0].split() + assert topRow[0] == "ppem:", "illegal hdmx format" + ppems = list(map(int, topRow[1:])) + self.hdmx = hdmx = {} + for ppem in ppems: + hdmx[ppem] = {} + lines = (line.split() for line in lines[1:]) + for line in lines: + if not line: + continue + assert line[0][-1] == ":", "illegal hdmx format" + glyphName = line[0][:-1] + if "\\" in glyphName: + from fontTools.misc.textTools import safeEval + + glyphName = safeEval('"""' + glyphName + '"""') + line = list(map(int, line[1:])) + assert len(line) == len(ppems), "illegal hdmx format" + for i, ppem in enumerate(ppems): + hdmx[ppem][glyphName] = line[i] diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_h_e_a_d.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_h_e_a_d.py new file mode 100644 index 0000000000000000000000000000000000000000..6c3c0944177dfab2050ae08816b25b7c6d8c4191 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_h_e_a_d.py @@ -0,0 +1,129 @@ +from fontTools.misc import sstruct +from fontTools.misc.fixedTools import floatToFixedToStr, strToFixedToFloat +from fontTools.misc.textTools import safeEval, num2binary, binary2num +from fontTools.misc.timeTools import ( + timestampFromString, + timestampToString, + timestampNow, +) +from fontTools.misc.timeTools import epoch_diff as mac_epoch_diff # For backward compat +from fontTools.misc.arrayTools import intRect, unionRect +from . import DefaultTable +import logging + +log = logging.getLogger(__name__) + +headFormat = """ + > # big endian + tableVersion: 16.16F + fontRevision: 16.16F + checkSumAdjustment: I + magicNumber: I + flags: H + unitsPerEm: H + created: Q + modified: Q + xMin: h + yMin: h + xMax: h + yMax: h + macStyle: H + lowestRecPPEM: H + fontDirectionHint: h + indexToLocFormat: h + glyphDataFormat: h +""" + + +class table__h_e_a_d(DefaultTable.DefaultTable): + """Font Header table + + The ``head`` table contains a variety of font-wide information. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/head + """ + + dependencies = ["maxp", "loca", "CFF ", "CFF2"] + + def decompile(self, data, ttFont): + dummy, rest = sstruct.unpack2(headFormat, data, self) + if rest: + # this is quite illegal, but there seem to be fonts out there that do this + log.warning("extra bytes at the end of 'head' table") + assert rest == b"\0\0" + + # For timestamp fields, ignore the top four bytes. Some fonts have + # bogus values there. Since till 2038 those bytes only can be zero, + # ignore them. + # + # https://github.com/fonttools/fonttools/issues/99#issuecomment-66776810 + for stamp in "created", "modified": + value = getattr(self, stamp) + if value > 0xFFFFFFFF: + log.warning("'%s' timestamp out of range; ignoring top bytes", stamp) + value &= 0xFFFFFFFF + setattr(self, stamp, value) + if value < 0x7C259DC0: # January 1, 1970 00:00:00 + log.warning( + "'%s' timestamp seems very low; regarding as unix timestamp", stamp + ) + value += 0x7C259DC0 + setattr(self, stamp, value) + + def compile(self, ttFont): + if ttFont.recalcBBoxes: + # For TT-flavored fonts, xMin, yMin, xMax and yMax are set in table__m_a_x_p.recalc(). + if "CFF " in ttFont: + topDict = ttFont["CFF "].cff.topDictIndex[0] + self.xMin, self.yMin, self.xMax, self.yMax = intRect(topDict.FontBBox) + elif "CFF2" in ttFont: + topDict = ttFont["CFF2"].cff.topDictIndex[0] + charStrings = topDict.CharStrings + fontBBox = None + for charString in charStrings.values(): + bounds = charString.calcBounds(charStrings) + if bounds is not None: + if fontBBox is not None: + fontBBox = unionRect(fontBBox, bounds) + else: + fontBBox = bounds + if fontBBox is not None: + self.xMin, self.yMin, self.xMax, self.yMax = intRect(fontBBox) + if ttFont.recalcTimestamp: + self.modified = timestampNow() + data = sstruct.pack(headFormat, self) + return data + + def toXML(self, writer, ttFont): + writer.comment("Most of this table will be recalculated by the compiler") + writer.newline() + _, names, fixes = sstruct.getformat(headFormat) + for name in names: + value = getattr(self, name) + if name in fixes: + value = floatToFixedToStr(value, precisionBits=fixes[name]) + elif name in ("created", "modified"): + value = timestampToString(value) + elif name in ("magicNumber", "checkSumAdjustment"): + if value < 0: + value = value + 0x100000000 + value = hex(value) + if value[-1:] == "L": + value = value[:-1] + elif name in ("macStyle", "flags"): + value = num2binary(value, 16) + writer.simpletag(name, value=value) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + value = attrs["value"] + fixes = sstruct.getformat(headFormat)[2] + if name in fixes: + value = strToFixedToFloat(value, precisionBits=fixes[name]) + elif name in ("created", "modified"): + value = timestampFromString(value) + elif name in ("macStyle", "flags"): + value = binary2num(value) + else: + value = safeEval(value) + setattr(self, name, value) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_h_h_e_a.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_h_h_e_a.py new file mode 100644 index 0000000000000000000000000000000000000000..dbdfd7ac3c94dd64fb9ef388e441bdacd6a94644 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_h_h_e_a.py @@ -0,0 +1,146 @@ +from fontTools.misc import sstruct +from fontTools.misc.textTools import safeEval +from fontTools.misc.fixedTools import ( + ensureVersionIsLong as fi2ve, + versionToFixed as ve2fi, +) +from . import DefaultTable +import math + +hheaFormat = """ + > # big endian + tableVersion: L + ascent: h + descent: h + lineGap: h + advanceWidthMax: H + minLeftSideBearing: h + minRightSideBearing: h + xMaxExtent: h + caretSlopeRise: h + caretSlopeRun: h + caretOffset: h + reserved0: h + reserved1: h + reserved2: h + reserved3: h + metricDataFormat: h + numberOfHMetrics: H +""" + + +class table__h_h_e_a(DefaultTable.DefaultTable): + """Horizontal Header table + + The ``hhea`` table contains information needed during horizontal + text layout. + + .. note:: + This converter class is kept in sync with the :class:`._v_h_e_a.table__v_h_e_a` + table constructor. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/hhea + """ + + # Note: Keep in sync with table__v_h_e_a + + dependencies = ["hmtx", "glyf", "CFF ", "CFF2"] + + # OpenType spec renamed these, add aliases for compatibility + @property + def ascender(self): + return self.ascent + + @ascender.setter + def ascender(self, value): + self.ascent = value + + @property + def descender(self): + return self.descent + + @descender.setter + def descender(self, value): + self.descent = value + + def decompile(self, data, ttFont): + sstruct.unpack(hheaFormat, data, self) + + def compile(self, ttFont): + if ttFont.recalcBBoxes and ( + ttFont.isLoaded("glyf") + or ttFont.isLoaded("CFF ") + or ttFont.isLoaded("CFF2") + ): + self.recalc(ttFont) + self.tableVersion = fi2ve(self.tableVersion) + return sstruct.pack(hheaFormat, self) + + def recalc(self, ttFont): + if "hmtx" not in ttFont: + return + + hmtxTable = ttFont["hmtx"] + self.advanceWidthMax = max(adv for adv, _ in hmtxTable.metrics.values()) + + boundsWidthDict = {} + if "glyf" in ttFont: + glyfTable = ttFont["glyf"] + for name in ttFont.getGlyphOrder(): + g = glyfTable[name] + if g.numberOfContours == 0: + continue + if g.numberOfContours < 0 and not hasattr(g, "xMax"): + # Composite glyph without extents set. + # Calculate those. + g.recalcBounds(glyfTable) + boundsWidthDict[name] = g.xMax - g.xMin + elif "CFF " in ttFont or "CFF2" in ttFont: + if "CFF " in ttFont: + topDict = ttFont["CFF "].cff.topDictIndex[0] + else: + topDict = ttFont["CFF2"].cff.topDictIndex[0] + charStrings = topDict.CharStrings + for name in ttFont.getGlyphOrder(): + cs = charStrings[name] + bounds = cs.calcBounds(charStrings) + if bounds is not None: + boundsWidthDict[name] = int( + math.ceil(bounds[2]) - math.floor(bounds[0]) + ) + + if boundsWidthDict: + minLeftSideBearing = float("inf") + minRightSideBearing = float("inf") + xMaxExtent = -float("inf") + for name, boundsWidth in boundsWidthDict.items(): + advanceWidth, lsb = hmtxTable[name] + rsb = advanceWidth - lsb - boundsWidth + extent = lsb + boundsWidth + minLeftSideBearing = min(minLeftSideBearing, lsb) + minRightSideBearing = min(minRightSideBearing, rsb) + xMaxExtent = max(xMaxExtent, extent) + self.minLeftSideBearing = minLeftSideBearing + self.minRightSideBearing = minRightSideBearing + self.xMaxExtent = xMaxExtent + + else: # No glyph has outlines. + self.minLeftSideBearing = 0 + self.minRightSideBearing = 0 + self.xMaxExtent = 0 + + def toXML(self, writer, ttFont): + formatstring, names, fixes = sstruct.getformat(hheaFormat) + for name in names: + value = getattr(self, name) + if name == "tableVersion": + value = fi2ve(value) + value = "0x%08x" % value + writer.simpletag(name, value=value) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "tableVersion": + setattr(self, name, ve2fi(attrs["value"])) + return + setattr(self, name, safeEval(attrs["value"])) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_h_m_t_x.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_h_m_t_x.py new file mode 100644 index 0000000000000000000000000000000000000000..8a574d60ed69e3a544859d0d4eedf1733baff652 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_h_m_t_x.py @@ -0,0 +1,163 @@ +from fontTools.misc.roundTools import otRound +from fontTools import ttLib +from fontTools.misc.textTools import safeEval +from . import DefaultTable +import sys +import struct +import array +import logging + +log = logging.getLogger(__name__) + + +class table__h_m_t_x(DefaultTable.DefaultTable): + """Horizontal Metrics table + + The ``hmtx`` table contains per-glyph metrics for the glyphs in a + ``glyf``, ``CFF ``, or ``CFF2`` table, as needed for horizontal text + layout. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/hmtx + """ + + headerTag = "hhea" + advanceName = "width" + sideBearingName = "lsb" + numberOfMetricsName = "numberOfHMetrics" + longMetricFormat = "Hh" + + def decompile(self, data, ttFont): + numGlyphs = ttFont["maxp"].numGlyphs + headerTable = ttFont.get(self.headerTag) + if headerTable is not None: + numberOfMetrics = int(getattr(headerTable, self.numberOfMetricsName)) + else: + numberOfMetrics = numGlyphs + if numberOfMetrics > numGlyphs: + log.warning( + "The %s.%s exceeds the maxp.numGlyphs" + % (self.headerTag, self.numberOfMetricsName) + ) + numberOfMetrics = numGlyphs + numberOfSideBearings = numGlyphs - numberOfMetrics + tableSize = 4 * numberOfMetrics + 2 * numberOfSideBearings + if len(data) < tableSize: + raise ttLib.TTLibError( + f"not enough '{self.tableTag}' table data: " + f"expected {tableSize} bytes, got {len(data)}" + ) + # Note: advanceWidth is unsigned, but some font editors might + # read/write as signed. We can't be sure whether it was a mistake + # or not, so we read as unsigned but also issue a warning... + metricsFmt = ">" + self.longMetricFormat * numberOfMetrics + metrics = struct.unpack(metricsFmt, data[: 4 * numberOfMetrics]) + data = data[4 * numberOfMetrics :] + sideBearings = array.array("h", data[: 2 * numberOfSideBearings]) + data = data[2 * numberOfSideBearings :] + + if sys.byteorder != "big": + sideBearings.byteswap() + if data: + log.warning("too much '%s' table data" % self.tableTag) + self.metrics = {} + glyphOrder = ttFont.getGlyphOrder() + for i in range(numberOfMetrics): + glyphName = glyphOrder[i] + advanceWidth, lsb = metrics[i * 2 : i * 2 + 2] + if advanceWidth > 32767: + log.warning( + "Glyph %r has a huge advance %s (%d); is it intentional or " + "an (invalid) negative value?", + glyphName, + self.advanceName, + advanceWidth, + ) + self.metrics[glyphName] = (advanceWidth, lsb) + lastAdvance = metrics[-2] + for i in range(numberOfSideBearings): + glyphName = glyphOrder[i + numberOfMetrics] + self.metrics[glyphName] = (lastAdvance, sideBearings[i]) + + def compile(self, ttFont): + metrics = [] + hasNegativeAdvances = False + for glyphName in ttFont.getGlyphOrder(): + advanceWidth, sideBearing = self.metrics[glyphName] + if advanceWidth < 0: + log.error( + "Glyph %r has negative advance %s" % (glyphName, self.advanceName) + ) + hasNegativeAdvances = True + metrics.append([advanceWidth, sideBearing]) + + headerTable = ttFont.get(self.headerTag) + if headerTable is not None: + lastAdvance = metrics[-1][0] + lastIndex = len(metrics) + while metrics[lastIndex - 2][0] == lastAdvance: + lastIndex -= 1 + if lastIndex <= 1: + # all advances are equal + lastIndex = 1 + break + additionalMetrics = metrics[lastIndex:] + additionalMetrics = [otRound(sb) for _, sb in additionalMetrics] + metrics = metrics[:lastIndex] + numberOfMetrics = len(metrics) + setattr(headerTable, self.numberOfMetricsName, numberOfMetrics) + else: + # no hhea/vhea, can't store numberOfMetrics; assume == numGlyphs + numberOfMetrics = ttFont["maxp"].numGlyphs + additionalMetrics = [] + + allMetrics = [] + for advance, sb in metrics: + allMetrics.extend([otRound(advance), otRound(sb)]) + metricsFmt = ">" + self.longMetricFormat * numberOfMetrics + try: + data = struct.pack(metricsFmt, *allMetrics) + except struct.error as e: + if "out of range" in str(e) and hasNegativeAdvances: + raise ttLib.TTLibError( + "'%s' table can't contain negative advance %ss" + % (self.tableTag, self.advanceName) + ) + else: + raise + additionalMetrics = array.array("h", additionalMetrics) + if sys.byteorder != "big": + additionalMetrics.byteswap() + data = data + additionalMetrics.tobytes() + return data + + def toXML(self, writer, ttFont): + names = sorted(self.metrics.keys()) + for glyphName in names: + advance, sb = self.metrics[glyphName] + writer.simpletag( + "mtx", + [ + ("name", glyphName), + (self.advanceName, advance), + (self.sideBearingName, sb), + ], + ) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if not hasattr(self, "metrics"): + self.metrics = {} + if name == "mtx": + self.metrics[attrs["name"]] = ( + safeEval(attrs[self.advanceName]), + safeEval(attrs[self.sideBearingName]), + ) + + def __delitem__(self, glyphName): + del self.metrics[glyphName] + + def __getitem__(self, glyphName): + return self.metrics[glyphName] + + def __setitem__(self, glyphName, advance_sb_pair): + self.metrics[glyphName] = tuple(advance_sb_pair) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_k_e_r_n.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_k_e_r_n.py new file mode 100644 index 0000000000000000000000000000000000000000..c9fbc43f50bf50ed455d86eeee94dad858b43a6b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_k_e_r_n.py @@ -0,0 +1,288 @@ +from fontTools.ttLib import getSearchRange +from fontTools.misc.textTools import safeEval, readHex +from fontTools.misc.fixedTools import fixedToFloat as fi2fl, floatToFixed as fl2fi +from . import DefaultTable +import struct +import sys +import array +import logging + +log = logging.getLogger(__name__) + + +class table__k_e_r_n(DefaultTable.DefaultTable): + """Kerning table + + The ``kern`` table contains values that contextually adjust the inter-glyph + spacing for the glyphs in a ``glyf`` table. + + Note that similar contextual spacing adjustments can also be stored + in the "kern" feature of a ``GPOS`` table. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/kern + """ + + def getkern(self, format): + for subtable in self.kernTables: + if subtable.format == format: + return subtable + return None # not found + + def decompile(self, data, ttFont): + version, nTables = struct.unpack(">HH", data[:4]) + apple = False + if (len(data) >= 8) and (version == 1): + # AAT Apple's "new" format. Hm. + version, nTables = struct.unpack(">LL", data[:8]) + self.version = fi2fl(version, 16) + data = data[8:] + apple = True + else: + self.version = version + data = data[4:] + self.kernTables = [] + for i in range(nTables): + if self.version == 1.0: + # Apple + length, coverage, subtableFormat = struct.unpack(">LBB", data[:6]) + else: + # in OpenType spec the "version" field refers to the common + # subtable header; the actual subtable format is stored in + # the 8-15 mask bits of "coverage" field. + # This "version" is always 0 so we ignore it here + _, length, subtableFormat, coverage = struct.unpack(">HHBB", data[:6]) + if nTables == 1 and subtableFormat == 0: + # The "length" value is ignored since some fonts + # (like OpenSans and Calibri) have a subtable larger than + # its value. + (nPairs,) = struct.unpack(">H", data[6:8]) + calculated_length = (nPairs * 6) + 14 + if length != calculated_length: + log.warning( + "'kern' subtable longer than defined: " + "%d bytes instead of %d bytes" % (calculated_length, length) + ) + length = calculated_length + if subtableFormat not in kern_classes: + subtable = KernTable_format_unkown(subtableFormat) + else: + subtable = kern_classes[subtableFormat](apple) + subtable.decompile(data[:length], ttFont) + self.kernTables.append(subtable) + data = data[length:] + + def compile(self, ttFont): + if hasattr(self, "kernTables"): + nTables = len(self.kernTables) + else: + nTables = 0 + if self.version == 1.0: + # AAT Apple's "new" format. + data = struct.pack(">LL", fl2fi(self.version, 16), nTables) + else: + data = struct.pack(">HH", self.version, nTables) + if hasattr(self, "kernTables"): + for subtable in self.kernTables: + data = data + subtable.compile(ttFont) + return data + + def toXML(self, writer, ttFont): + writer.simpletag("version", value=self.version) + writer.newline() + for subtable in self.kernTables: + subtable.toXML(writer, ttFont) + + def fromXML(self, name, attrs, content, ttFont): + if name == "version": + self.version = safeEval(attrs["value"]) + return + if name != "kernsubtable": + return + if not hasattr(self, "kernTables"): + self.kernTables = [] + format = safeEval(attrs["format"]) + if format not in kern_classes: + subtable = KernTable_format_unkown(format) + else: + apple = self.version == 1.0 + subtable = kern_classes[format](apple) + self.kernTables.append(subtable) + subtable.fromXML(name, attrs, content, ttFont) + + +class KernTable_format_0(object): + # 'version' is kept for backward compatibility + version = format = 0 + + def __init__(self, apple=False): + self.apple = apple + + def decompile(self, data, ttFont): + if not self.apple: + version, length, subtableFormat, coverage = struct.unpack(">HHBB", data[:6]) + if version != 0: + from fontTools.ttLib import TTLibError + + raise TTLibError("unsupported kern subtable version: %d" % version) + tupleIndex = None + # Should we also assert length == len(data)? + data = data[6:] + else: + length, coverage, subtableFormat, tupleIndex = struct.unpack( + ">LBBH", data[:8] + ) + data = data[8:] + assert self.format == subtableFormat, "unsupported format" + self.coverage = coverage + self.tupleIndex = tupleIndex + + self.kernTable = kernTable = {} + + nPairs, searchRange, entrySelector, rangeShift = struct.unpack( + ">HHHH", data[:8] + ) + data = data[8:] + + datas = array.array("H", data[: 6 * nPairs]) + if sys.byteorder != "big": + datas.byteswap() + it = iter(datas) + glyphOrder = ttFont.getGlyphOrder() + for k in range(nPairs): + left, right, value = next(it), next(it), next(it) + if value >= 32768: + value -= 65536 + try: + kernTable[(glyphOrder[left], glyphOrder[right])] = value + except IndexError: + # Slower, but will not throw an IndexError on an invalid + # glyph id. + kernTable[(ttFont.getGlyphName(left), ttFont.getGlyphName(right))] = ( + value + ) + if len(data) > 6 * nPairs + 4: # Ignore up to 4 bytes excess + log.warning( + "excess data in 'kern' subtable: %d bytes", len(data) - 6 * nPairs + ) + + def compile(self, ttFont): + nPairs = min(len(self.kernTable), 0xFFFF) + searchRange, entrySelector, rangeShift = getSearchRange(nPairs, 6) + searchRange &= 0xFFFF + entrySelector = min(entrySelector, 0xFFFF) + rangeShift = min(rangeShift, 0xFFFF) + data = struct.pack(">HHHH", nPairs, searchRange, entrySelector, rangeShift) + + # yeehee! (I mean, turn names into indices) + try: + reverseOrder = ttFont.getReverseGlyphMap() + kernTable = sorted( + (reverseOrder[left], reverseOrder[right], value) + for ((left, right), value) in self.kernTable.items() + ) + except KeyError: + # Slower, but will not throw KeyError on invalid glyph id. + getGlyphID = ttFont.getGlyphID + kernTable = sorted( + (getGlyphID(left), getGlyphID(right), value) + for ((left, right), value) in self.kernTable.items() + ) + + for left, right, value in kernTable: + data = data + struct.pack(">HHh", left, right, value) + + if not self.apple: + version = 0 + length = len(data) + 6 + if length >= 0x10000: + log.warning( + '"kern" subtable overflow, ' + "truncating length value while preserving pairs." + ) + length &= 0xFFFF + header = struct.pack(">HHBB", version, length, self.format, self.coverage) + else: + if self.tupleIndex is None: + # sensible default when compiling a TTX from an old fonttools + # or when inserting a Windows-style format 0 subtable into an + # Apple version=1.0 kern table + log.warning("'tupleIndex' is None; default to 0") + self.tupleIndex = 0 + length = len(data) + 8 + header = struct.pack( + ">LBBH", length, self.coverage, self.format, self.tupleIndex + ) + return header + data + + def toXML(self, writer, ttFont): + attrs = dict(coverage=self.coverage, format=self.format) + if self.apple: + if self.tupleIndex is None: + log.warning("'tupleIndex' is None; default to 0") + attrs["tupleIndex"] = 0 + else: + attrs["tupleIndex"] = self.tupleIndex + writer.begintag("kernsubtable", **attrs) + writer.newline() + items = sorted(self.kernTable.items()) + for (left, right), value in items: + writer.simpletag("pair", [("l", left), ("r", right), ("v", value)]) + writer.newline() + writer.endtag("kernsubtable") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + self.coverage = safeEval(attrs["coverage"]) + subtableFormat = safeEval(attrs["format"]) + if self.apple: + if "tupleIndex" in attrs: + self.tupleIndex = safeEval(attrs["tupleIndex"]) + else: + # previous fontTools versions didn't export tupleIndex + log.warning("Apple kern subtable is missing 'tupleIndex' attribute") + self.tupleIndex = None + else: + self.tupleIndex = None + assert subtableFormat == self.format, "unsupported format" + if not hasattr(self, "kernTable"): + self.kernTable = {} + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + self.kernTable[(attrs["l"], attrs["r"])] = safeEval(attrs["v"]) + + def __getitem__(self, pair): + return self.kernTable[pair] + + def __setitem__(self, pair, value): + self.kernTable[pair] = value + + def __delitem__(self, pair): + del self.kernTable[pair] + + +class KernTable_format_unkown(object): + def __init__(self, format): + self.format = format + + def decompile(self, data, ttFont): + self.data = data + + def compile(self, ttFont): + return self.data + + def toXML(self, writer, ttFont): + writer.begintag("kernsubtable", format=self.format) + writer.newline() + writer.comment("unknown 'kern' subtable format") + writer.newline() + writer.dumphex(self.data) + writer.endtag("kernsubtable") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + self.decompile(readHex(content), ttFont) + + +kern_classes = {0: KernTable_format_0} diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_l_c_a_r.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_l_c_a_r.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb32d23d9d636361117e068fb7846d319f1b52c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_l_c_a_r.py @@ -0,0 +1,13 @@ +from .otBase import BaseTTXConverter + + +class table__l_c_a_r(BaseTTXConverter): + """Ligature Caret table + + The AAT ``lcar`` table stores division points within ligatures, which applications + can use to position carets properly between the logical parts of the ligature. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6lcar.html + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_l_o_c_a.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_l_o_c_a.py new file mode 100644 index 0000000000000000000000000000000000000000..3e2600f7ae9b33268c241b8d81715839e30d955f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_l_o_c_a.py @@ -0,0 +1,69 @@ +from . import DefaultTable +import sys +import array +import logging + +log = logging.getLogger(__name__) + + +class table__l_o_c_a(DefaultTable.DefaultTable): + """Index to Location table + + The ``loca`` table stores the offsets in the ``glyf`` table that correspond + to the descriptions of each glyph. The glyphs are references by Glyph ID. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/loca + """ + + dependencies = ["glyf"] + + def decompile(self, data, ttFont): + longFormat = ttFont["head"].indexToLocFormat + if longFormat: + format = "I" + else: + format = "H" + locations = array.array(format) + locations.frombytes(data) + if sys.byteorder != "big": + locations.byteswap() + if not longFormat: + locations = array.array("I", (2 * l for l in locations)) + if len(locations) < (ttFont["maxp"].numGlyphs + 1): + log.warning( + "corrupt 'loca' table, or wrong numGlyphs in 'maxp': %d %d", + len(locations) - 1, + ttFont["maxp"].numGlyphs, + ) + self.locations = locations + + def compile(self, ttFont): + try: + max_location = max(self.locations) + except AttributeError: + self.set([]) + max_location = 0 + if max_location < 0x20000 and all(l % 2 == 0 for l in self.locations): + locations = array.array("H") + for location in self.locations: + locations.append(location // 2) + ttFont["head"].indexToLocFormat = 0 + else: + locations = array.array("I", self.locations) + ttFont["head"].indexToLocFormat = 1 + if sys.byteorder != "big": + locations.byteswap() + return locations.tobytes() + + def set(self, locations): + self.locations = array.array("I", locations) + + def toXML(self, writer, ttFont): + writer.comment("The 'loca' table will be calculated by the compiler") + writer.newline() + + def __getitem__(self, index): + return self.locations[index] + + def __len__(self): + return len(self.locations) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_l_t_a_g.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_l_t_a_g.py new file mode 100644 index 0000000000000000000000000000000000000000..fc47cd648bc7b6be6b4ca3011c5125cc2e1d897e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_l_t_a_g.py @@ -0,0 +1,72 @@ +from fontTools.misc.textTools import bytesjoin, tobytes, safeEval +from . import DefaultTable +import struct + +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ltag.html + + +class table__l_t_a_g(DefaultTable.DefaultTable): + """Language Tag table + + The AAT ``ltag`` table contains mappings between the numeric codes used + in the language field of the ``name`` table and IETF language tags. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ltag.html + """ + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.version, self.flags = 1, 0 + self.tags = [] + + def addTag(self, tag): + """Add 'tag' to the list of langauge tags if not already there. + + Returns the integer index of 'tag' in the list of all tags. + """ + try: + return self.tags.index(tag) + except ValueError: + self.tags.append(tag) + return len(self.tags) - 1 + + def decompile(self, data, ttFont): + self.version, self.flags, numTags = struct.unpack(">LLL", data[:12]) + assert self.version == 1 + self.tags = [] + for i in range(numTags): + pos = 12 + i * 4 + offset, length = struct.unpack(">HH", data[pos : pos + 4]) + tag = data[offset : offset + length].decode("ascii") + self.tags.append(tag) + + def compile(self, ttFont): + dataList = [struct.pack(">LLL", self.version, self.flags, len(self.tags))] + stringPool = "" + for tag in self.tags: + offset = stringPool.find(tag) + if offset < 0: + offset = len(stringPool) + stringPool = stringPool + tag + offset = offset + 12 + len(self.tags) * 4 + dataList.append(struct.pack(">HH", offset, len(tag))) + dataList.append(tobytes(stringPool)) + return bytesjoin(dataList) + + def toXML(self, writer, ttFont): + writer.simpletag("version", value=self.version) + writer.newline() + writer.simpletag("flags", value=self.flags) + writer.newline() + for tag in self.tags: + writer.simpletag("LanguageTag", tag=tag) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if not hasattr(self, "tags"): + self.tags = [] + if name == "LanguageTag": + self.tags.append(attrs["tag"]) + elif "value" in attrs: + value = safeEval(attrs["value"]) + setattr(self, name, value) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_m_a_x_p.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_m_a_x_p.py new file mode 100644 index 0000000000000000000000000000000000000000..c1576a578f22c375ad4c5c4534b38162329aadde --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_m_a_x_p.py @@ -0,0 +1,147 @@ +from fontTools.misc import sstruct +from fontTools.misc.textTools import safeEval +from . import DefaultTable + +maxpFormat_0_5 = """ + > # big endian + tableVersion: i + numGlyphs: H +""" + +maxpFormat_1_0_add = """ + > # big endian + maxPoints: H + maxContours: H + maxCompositePoints: H + maxCompositeContours: H + maxZones: H + maxTwilightPoints: H + maxStorage: H + maxFunctionDefs: H + maxInstructionDefs: H + maxStackElements: H + maxSizeOfInstructions: H + maxComponentElements: H + maxComponentDepth: H +""" + + +class table__m_a_x_p(DefaultTable.DefaultTable): + """Maximum Profile table + + The ``maxp`` table contains the memory requirements for the data in + the font. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/maxp + """ + + dependencies = ["glyf"] + + def decompile(self, data, ttFont): + dummy, data = sstruct.unpack2(maxpFormat_0_5, data, self) + self.numGlyphs = int(self.numGlyphs) + if self.tableVersion != 0x00005000: + dummy, data = sstruct.unpack2(maxpFormat_1_0_add, data, self) + assert len(data) == 0 + + def compile(self, ttFont): + if "glyf" in ttFont: + if ttFont.isLoaded("glyf") and ttFont.recalcBBoxes: + self.recalc(ttFont) + else: + pass # CFF + self.numGlyphs = len(ttFont.getGlyphOrder()) + if self.tableVersion != 0x00005000: + self.tableVersion = 0x00010000 + data = sstruct.pack(maxpFormat_0_5, self) + if self.tableVersion == 0x00010000: + data = data + sstruct.pack(maxpFormat_1_0_add, self) + return data + + def recalc(self, ttFont): + """Recalculate the font bounding box, and most other maxp values except + for the TT instructions values. Also recalculate the value of bit 1 + of the flags field and the font bounding box of the 'head' table. + """ + glyfTable = ttFont["glyf"] + hmtxTable = ttFont["hmtx"] + headTable = ttFont["head"] + self.numGlyphs = len(glyfTable) + INFINITY = 100000 + xMin = +INFINITY + yMin = +INFINITY + xMax = -INFINITY + yMax = -INFINITY + maxPoints = 0 + maxContours = 0 + maxCompositePoints = 0 + maxCompositeContours = 0 + maxComponentElements = 0 + maxComponentDepth = 0 + allXMinIsLsb = 1 + for glyphName in ttFont.getGlyphOrder(): + g = glyfTable[glyphName] + if g.numberOfContours: + if hmtxTable[glyphName][1] != g.xMin: + allXMinIsLsb = 0 + xMin = min(xMin, g.xMin) + yMin = min(yMin, g.yMin) + xMax = max(xMax, g.xMax) + yMax = max(yMax, g.yMax) + if g.numberOfContours > 0: + nPoints, nContours = g.getMaxpValues() + maxPoints = max(maxPoints, nPoints) + maxContours = max(maxContours, nContours) + elif g.isComposite(): + nPoints, nContours, componentDepth = g.getCompositeMaxpValues( + glyfTable + ) + maxCompositePoints = max(maxCompositePoints, nPoints) + maxCompositeContours = max(maxCompositeContours, nContours) + maxComponentElements = max(maxComponentElements, len(g.components)) + maxComponentDepth = max(maxComponentDepth, componentDepth) + if xMin == +INFINITY: + headTable.xMin = 0 + headTable.yMin = 0 + headTable.xMax = 0 + headTable.yMax = 0 + else: + headTable.xMin = xMin + headTable.yMin = yMin + headTable.xMax = xMax + headTable.yMax = yMax + self.maxPoints = maxPoints + self.maxContours = maxContours + self.maxCompositePoints = maxCompositePoints + self.maxCompositeContours = maxCompositeContours + self.maxComponentElements = maxComponentElements + self.maxComponentDepth = maxComponentDepth + if allXMinIsLsb: + headTable.flags = headTable.flags | 0x2 + else: + headTable.flags = headTable.flags & ~0x2 + + def testrepr(self): + items = sorted(self.__dict__.items()) + print(". . . . . . . . .") + for combo in items: + print(" %s: %s" % combo) + print(". . . . . . . . .") + + def toXML(self, writer, ttFont): + if self.tableVersion != 0x00005000: + writer.comment("Most of this table will be recalculated by the compiler") + writer.newline() + formatstring, names, fixes = sstruct.getformat(maxpFormat_0_5) + if self.tableVersion != 0x00005000: + formatstring, names_1_0, fixes = sstruct.getformat(maxpFormat_1_0_add) + names = {**names, **names_1_0} + for name in names: + value = getattr(self, name) + if name == "tableVersion": + value = hex(value) + writer.simpletag(name, value=value) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + setattr(self, name, safeEval(attrs["value"])) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_m_e_t_a.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_m_e_t_a.py new file mode 100644 index 0000000000000000000000000000000000000000..c5cea1b993e8e15968065f9a50b27784fcf4eb8c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_m_e_t_a.py @@ -0,0 +1,112 @@ +from fontTools.misc import sstruct +from fontTools.misc.textTools import bytesjoin, strjoin, readHex +from fontTools.ttLib import TTLibError +from . import DefaultTable + +# Apple's documentation of 'meta': +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html + +META_HEADER_FORMAT = """ + > # big endian + version: L + flags: L + dataOffset: L + numDataMaps: L +""" + + +DATA_MAP_FORMAT = """ + > # big endian + tag: 4s + dataOffset: L + dataLength: L +""" + + +class table__m_e_t_a(DefaultTable.DefaultTable): + """Metadata table + + The ``meta`` table contains various metadata values for the font. Each + category of metadata in the table is identified by a four-character tag. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/meta + """ + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.data = {} + + def decompile(self, data, ttFont): + headerSize = sstruct.calcsize(META_HEADER_FORMAT) + header = sstruct.unpack(META_HEADER_FORMAT, data[0:headerSize]) + if header["version"] != 1: + raise TTLibError("unsupported 'meta' version %d" % header["version"]) + dataMapSize = sstruct.calcsize(DATA_MAP_FORMAT) + for i in range(header["numDataMaps"]): + dataMapOffset = headerSize + i * dataMapSize + dataMap = sstruct.unpack( + DATA_MAP_FORMAT, data[dataMapOffset : dataMapOffset + dataMapSize] + ) + tag = dataMap["tag"] + offset = dataMap["dataOffset"] + self.data[tag] = data[offset : offset + dataMap["dataLength"]] + if tag in ["dlng", "slng"]: + self.data[tag] = self.data[tag].decode("utf-8") + + def compile(self, ttFont): + keys = sorted(self.data.keys()) + headerSize = sstruct.calcsize(META_HEADER_FORMAT) + dataOffset = headerSize + len(keys) * sstruct.calcsize(DATA_MAP_FORMAT) + header = sstruct.pack( + META_HEADER_FORMAT, + { + "version": 1, + "flags": 0, + "dataOffset": dataOffset, + "numDataMaps": len(keys), + }, + ) + dataMaps = [] + dataBlocks = [] + for tag in keys: + if tag in ["dlng", "slng"]: + data = self.data[tag].encode("utf-8") + else: + data = self.data[tag] + dataMaps.append( + sstruct.pack( + DATA_MAP_FORMAT, + {"tag": tag, "dataOffset": dataOffset, "dataLength": len(data)}, + ) + ) + dataBlocks.append(data) + dataOffset += len(data) + return bytesjoin([header] + dataMaps + dataBlocks) + + def toXML(self, writer, ttFont): + for tag in sorted(self.data.keys()): + if tag in ["dlng", "slng"]: + writer.begintag("text", tag=tag) + writer.newline() + writer.write(self.data[tag]) + writer.newline() + writer.endtag("text") + writer.newline() + else: + writer.begintag("hexdata", tag=tag) + writer.newline() + data = self.data[tag] + if min(data) >= 0x20 and max(data) <= 0x7E: + writer.comment("ascii: " + data.decode("ascii")) + writer.newline() + writer.dumphex(data) + writer.endtag("hexdata") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "hexdata": + self.data[attrs["tag"]] = readHex(content) + elif name == "text" and attrs["tag"] in ["dlng", "slng"]: + self.data[attrs["tag"]] = strjoin(content).strip() + else: + raise TTLibError("can't handle '%s' element" % name) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_m_o_r_t.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_m_o_r_t.py new file mode 100644 index 0000000000000000000000000000000000000000..5e5fa77ce73fff4906d92610afd9914eb2b61a3c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_m_o_r_t.py @@ -0,0 +1,14 @@ +from .otBase import BaseTTXConverter + + +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6mort.html +class table__m_o_r_t(BaseTTXConverter): + """The AAT ``mort`` table contains glyph transformations used for script shaping and + for various other optional smart features. + + Note: ``mort`` has been deprecated in favor of the newer ``morx`` table. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6mort.html + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_m_o_r_x.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_m_o_r_x.py new file mode 100644 index 0000000000000000000000000000000000000000..dfb3abcc5e35e426bbd670417c429dd4b4ce0962 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_m_o_r_x.py @@ -0,0 +1,15 @@ +from .otBase import BaseTTXConverter + + +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html +class table__m_o_r_x(BaseTTXConverter): + """The AAT ``morx`` table contains glyph transformations used for script shaping and + for various other optional smart features, akin to ``GSUB`` and ``GPOS`` features + in OpenType Layout. + + Note: ``morx`` is a replacement for the now deprecated ``mort`` table. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_n_a_m_e.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_n_a_m_e.py new file mode 100644 index 0000000000000000000000000000000000000000..2aac485b21059cac6cafbb940b7fcc0a8a620a17 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_n_a_m_e.py @@ -0,0 +1,1241 @@ +# -*- coding: utf-8 -*- +from __future__ import annotations + +from fontTools.misc import sstruct +from fontTools.misc.textTools import ( + bytechr, + byteord, + bytesjoin, + strjoin, + tobytes, + tostr, + safeEval, +) +from fontTools.misc.encodingTools import getEncoding +from fontTools.ttLib import newTable +from fontTools.ttLib.ttVisitor import TTVisitor +from fontTools import ttLib +import fontTools.ttLib.tables.otTables as otTables +from fontTools.ttLib.tables import C_P_A_L_ +from . import DefaultTable +import struct +import logging + +log = logging.getLogger(__name__) + +nameRecordFormat = """ + > # big endian + platformID: H + platEncID: H + langID: H + nameID: H + length: H + offset: H +""" + +nameRecordSize = sstruct.calcsize(nameRecordFormat) + + +class table__n_a_m_e(DefaultTable.DefaultTable): + """Naming table + + The ``name`` table is used to store a variety of strings that can be + associated with user-facing font information. Records in the ``name`` + table can be tagged with language tags to support multilingual naming + and can support platform-specific character-encoding variants. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/name + """ + + dependencies = ["ltag"] + + def __init__(self, tag=None): + super().__init__(tag) + self.names = [] + + def decompile(self, data, ttFont): + format, n, stringOffset = struct.unpack(b">HHH", data[:6]) + expectedStringOffset = 6 + n * nameRecordSize + if stringOffset != expectedStringOffset: + log.error( + "'name' table stringOffset incorrect. Expected: %s; Actual: %s", + expectedStringOffset, + stringOffset, + ) + stringData = data[stringOffset:] + data = data[6:] + self.names: list[NameRecord] = [] + for i in range(n): + if len(data) < 12: + log.error("skipping malformed name record #%d", i) + continue + name, data = sstruct.unpack2(nameRecordFormat, data, NameRecord()) + name.string = stringData[name.offset : name.offset + name.length] + if name.offset + name.length > len(stringData): + log.error("skipping malformed name record #%d", i) + continue + assert len(name.string) == name.length + # if (name.platEncID, name.platformID) in ((0, 0), (1, 3)): + # if len(name.string) % 2: + # print "2-byte string doesn't have even length!" + # print name.__dict__ + del name.offset, name.length + self.names.append(name) + + def compile(self, ttFont): + names = self.names + names.sort() # sort according to the spec; see NameRecord.__lt__() + stringData = b"" + format = 0 + n = len(names) + stringOffset = 6 + n * sstruct.calcsize(nameRecordFormat) + data = struct.pack(b">HHH", format, n, stringOffset) + lastoffset = 0 + done = {} # remember the data so we can reuse the "pointers" + for name in names: + string = name.toBytes() + if string in done: + name.offset, name.length = done[string] + else: + name.offset, name.length = done[string] = len(stringData), len(string) + stringData = bytesjoin([stringData, string]) + data = data + sstruct.pack(nameRecordFormat, name) + return data + stringData + + def toXML(self, writer, ttFont): + for name in self.names: + name.toXML(writer, ttFont) + + def fromXML(self, name, attrs, content, ttFont): + if name != "namerecord": + return # ignore unknown tags + name = NameRecord() + self.names.append(name) + name.fromXML(name, attrs, content, ttFont) + + def getName( + self, nameID: int, platformID: int, platEncID: int, langID: int | None = None + ) -> "NameRecord | None": + for namerecord in self.names: + if ( + namerecord.nameID == nameID + and namerecord.platformID == platformID + and namerecord.platEncID == platEncID + ): + if langID is None or namerecord.langID == langID: + return namerecord + return None # not found + + def getDebugName(self, nameID: int) -> str | None: + englishName: str | None = None + someName: str | None = None + for name in self.names: + if name.nameID != nameID: + continue + try: + unistr = name.toUnicode() + except UnicodeDecodeError: + continue + + someName = unistr + if (name.platformID, name.langID) in ((1, 0), (3, 0x409)): + englishName = unistr + break + if englishName: + return englishName + elif someName: + return someName + else: + return None + + def getFirstDebugName(self, nameIDs): + for nameID in nameIDs: + name = self.getDebugName(nameID) + if name is not None: + return name + return None + + def getBestFamilyName(self): + # 21 = WWS Family Name + # 16 = Typographic Family Name + # 1 = Family Name + return self.getFirstDebugName((21, 16, 1)) + + def getBestSubFamilyName(self): + # 22 = WWS SubFamily Name + # 17 = Typographic SubFamily Name + # 2 = SubFamily Name + return self.getFirstDebugName((22, 17, 2)) + + def getBestFullName(self): + # 4 = Full Name + # 6 = PostScript Name + for nameIDs in ((21, 22), (16, 17), (1, 2), (4,), (6,)): + if len(nameIDs) == 2: + name_fam = self.getDebugName(nameIDs[0]) + name_subfam = self.getDebugName(nameIDs[1]) + if None in [name_fam, name_subfam]: + continue # if any is None, skip + name = f"{name_fam} {name_subfam}" + if name_subfam.lower() == "regular": + name = f"{name_fam}" + return name + else: + name = self.getDebugName(nameIDs[0]) + if name is not None: + return name + return None + + def setName(self, string, nameID, platformID, platEncID, langID): + """Set the 'string' for the name record identified by 'nameID', 'platformID', + 'platEncID' and 'langID'. If a record with that nameID doesn't exist, create it + and append to the name table. + + 'string' can be of type `str` (`unicode` in PY2) or `bytes`. In the latter case, + it is assumed to be already encoded with the correct plaform-specific encoding + identified by the (platformID, platEncID, langID) triplet. A warning is issued + to prevent unexpected results. + """ + if not isinstance(string, str): + if isinstance(string, bytes): + log.warning( + "name string is bytes, ensure it's correctly encoded: %r", string + ) + else: + raise TypeError( + "expected unicode or bytes, found %s: %r" + % (type(string).__name__, string) + ) + namerecord = self.getName(nameID, platformID, platEncID, langID) + if namerecord: + namerecord.string = string + else: + self.names.append(makeName(string, nameID, platformID, platEncID, langID)) + + def removeNames(self, nameID=None, platformID=None, platEncID=None, langID=None): + """Remove any name records identified by the given combination of 'nameID', + 'platformID', 'platEncID' and 'langID'. + """ + args = { + argName: argValue + for argName, argValue in ( + ("nameID", nameID), + ("platformID", platformID), + ("platEncID", platEncID), + ("langID", langID), + ) + if argValue is not None + } + if not args: + # no arguments, nothing to do + return + self.names = [ + rec + for rec in self.names + if any( + argValue != getattr(rec, argName) for argName, argValue in args.items() + ) + ] + + @staticmethod + def removeUnusedNames(ttFont): + """Remove any name records which are not in NameID range 0-255 and not utilized + within the font itself.""" + visitor = NameRecordVisitor() + visitor.visit(ttFont) + toDelete = set() + for record in ttFont["name"].names: + # Name IDs 26 to 255, inclusive, are reserved for future standard names. + # https://learn.microsoft.com/en-us/typography/opentype/spec/name#name-ids + if record.nameID < 256: + continue + if record.nameID not in visitor.seen: + toDelete.add(record.nameID) + + for nameID in toDelete: + ttFont["name"].removeNames(nameID) + return toDelete + + def _findUnusedNameID(self, minNameID=256): + """Finds an unused name id. + + The nameID is assigned in the range between 'minNameID' and 32767 (inclusive), + following the last nameID in the name table. + """ + names = self.names + nameID = 1 + max([n.nameID for n in names] + [minNameID - 1]) + if nameID > 32767: + raise ValueError("nameID must be less than 32768") + return nameID + + def findMultilingualName( + self, names, windows=True, mac=True, minNameID=0, ttFont=None + ): + """Return the name ID of an existing multilingual name that + matches the 'names' dictionary, or None if not found. + + 'names' is a dictionary with the name in multiple languages, + such as {'en': 'Pale', 'de': 'Blaß', 'de-CH': 'Blass'}. + The keys can be arbitrary IETF BCP 47 language codes; + the values are Unicode strings. + + If 'windows' is True, the returned name ID is guaranteed + exist for all requested languages for platformID=3 and + platEncID=1. + If 'mac' is True, the returned name ID is guaranteed to exist + for all requested languages for platformID=1 and platEncID=0. + + The returned name ID will not be less than the 'minNameID' + argument. + """ + # Gather the set of requested + # (string, platformID, platEncID, langID) + # tuples + reqNameSet = set() + for lang, name in sorted(names.items()): + if windows: + windowsName = _makeWindowsName(name, None, lang) + if windowsName is not None: + reqNameSet.add( + ( + windowsName.string, + windowsName.platformID, + windowsName.platEncID, + windowsName.langID, + ) + ) + if mac: + macName = _makeMacName(name, None, lang, ttFont) + if macName is not None: + reqNameSet.add( + ( + macName.string, + macName.platformID, + macName.platEncID, + macName.langID, + ) + ) + + # Collect matching name IDs + matchingNames = dict() + for name in self.names: + try: + key = (name.toUnicode(), name.platformID, name.platEncID, name.langID) + except UnicodeDecodeError: + continue + if key in reqNameSet and name.nameID >= minNameID: + nameSet = matchingNames.setdefault(name.nameID, set()) + nameSet.add(key) + + # Return the first name ID that defines all requested strings + for nameID, nameSet in sorted(matchingNames.items()): + if nameSet == reqNameSet: + return nameID + + return None # not found + + def addMultilingualName( + self, names, ttFont=None, nameID=None, windows=True, mac=True, minNameID=0 + ): + """Add a multilingual name, returning its name ID + + 'names' is a dictionary with the name in multiple languages, + such as {'en': 'Pale', 'de': 'Blaß', 'de-CH': 'Blass'}. + The keys can be arbitrary IETF BCP 47 language codes; + the values are Unicode strings. + + 'ttFont' is the TTFont to which the names are added, or None. + If present, the font's 'ltag' table can get populated + to store exotic language codes, which allows encoding + names that otherwise cannot get encoded at all. + + 'nameID' is the name ID to be used, or None to let the library + find an existing set of name records that match, or pick an + unused name ID. + + If 'windows' is True, a platformID=3 name record will be added. + If 'mac' is True, a platformID=1 name record will be added. + + If the 'nameID' argument is None, the created nameID will not + be less than the 'minNameID' argument. + """ + if nameID is None: + # Reuse nameID if possible + nameID = self.findMultilingualName( + names, windows=windows, mac=mac, minNameID=minNameID, ttFont=ttFont + ) + if nameID is not None: + return nameID + nameID = self._findUnusedNameID() + # TODO: Should minimize BCP 47 language codes. + # https://github.com/fonttools/fonttools/issues/930 + for lang, name in sorted(names.items()): + if windows: + windowsName = _makeWindowsName(name, nameID, lang) + if windowsName is not None: + self.names.append(windowsName) + else: + # We cannot not make a Windows name: make sure we add a + # Mac name as a fallback. This can happen for exotic + # BCP47 language tags that have no Windows language code. + mac = True + if mac: + macName = _makeMacName(name, nameID, lang, ttFont) + if macName is not None: + self.names.append(macName) + return nameID + + def addName(self, string, platforms=((1, 0, 0), (3, 1, 0x409)), minNameID=255): + """Add a new name record containing 'string' for each (platformID, platEncID, + langID) tuple specified in the 'platforms' list. + + The nameID is assigned in the range between 'minNameID'+1 and 32767 (inclusive), + following the last nameID in the name table. + If no 'platforms' are specified, two English name records are added, one for the + Macintosh (platformID=0), and one for the Windows platform (3). + + The 'string' must be a Unicode string, so it can be encoded with different, + platform-specific encodings. + + Return the new nameID. + """ + assert ( + len(platforms) > 0 + ), "'platforms' must contain at least one (platformID, platEncID, langID) tuple" + if not isinstance(string, str): + raise TypeError( + "expected str, found %s: %r" % (type(string).__name__, string) + ) + nameID = self._findUnusedNameID(minNameID + 1) + for platformID, platEncID, langID in platforms: + self.names.append(makeName(string, nameID, platformID, platEncID, langID)) + return nameID + + +def makeName(string, nameID, platformID, platEncID, langID): + name = NameRecord() + name.string, name.nameID, name.platformID, name.platEncID, name.langID = ( + string, + nameID, + platformID, + platEncID, + langID, + ) + return name + + +def _makeWindowsName(name, nameID, language): + """Create a NameRecord for the Microsoft Windows platform + + 'language' is an arbitrary IETF BCP 47 language identifier such + as 'en', 'de-CH', 'de-AT-1901', or 'fa-Latn'. If Microsoft Windows + does not support the desired language, the result will be None. + Future versions of fonttools might return a NameRecord for the + OpenType 'name' table format 1, but this is not implemented yet. + """ + langID = _WINDOWS_LANGUAGE_CODES.get(language.lower()) + if langID is not None: + return makeName(name, nameID, 3, 1, langID) + else: + log.warning( + "cannot add Windows name in language %s " + "because fonttools does not yet support " + "name table format 1" % language + ) + return None + + +def _makeMacName(name, nameID, language, font=None): + """Create a NameRecord for Apple platforms + + 'language' is an arbitrary IETF BCP 47 language identifier such + as 'en', 'de-CH', 'de-AT-1901', or 'fa-Latn'. When possible, we + create a Macintosh NameRecord that is understood by old applications + (platform ID 1 and an old-style Macintosh language enum). If this + is not possible, we create a Unicode NameRecord (platform ID 0) + whose language points to the font’s 'ltag' table. The latter + can encode any string in any language, but legacy applications + might not recognize the format (in which case they will ignore + those names). + + 'font' should be the TTFont for which you want to create a name. + If 'font' is None, we only return NameRecords for legacy Macintosh; + in that case, the result will be None for names that need to + be encoded with an 'ltag' table. + + See the section “The language identifier” in Apple’s specification: + https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html + """ + macLang = _MAC_LANGUAGE_CODES.get(language.lower()) + macScript = _MAC_LANGUAGE_TO_SCRIPT.get(macLang) + if macLang is not None and macScript is not None: + encoding = getEncoding(1, macScript, macLang, default="ascii") + # Check if we can actually encode this name. If we can't, + # for example because we have no support for the legacy + # encoding, or because the name string contains Unicode + # characters that the legacy encoding cannot represent, + # we fall back to encoding the name in Unicode and put + # the language tag into the ltag table. + try: + _ = tobytes(name, encoding, errors="strict") + return makeName(name, nameID, 1, macScript, macLang) + except UnicodeEncodeError: + pass + if font is not None: + ltag = font.tables.get("ltag") + if ltag is None: + ltag = font["ltag"] = newTable("ltag") + # 0 = Unicode; 4 = “Unicode 2.0 or later semantics (non-BMP characters allowed)” + # “The preferred platform-specific code for Unicode would be 3 or 4.” + # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html + return makeName(name, nameID, 0, 4, ltag.addTag(language)) + else: + log.warning( + "cannot store language %s into 'ltag' table " + "without having access to the TTFont object" % language + ) + return None + + +class NameRecord(object): + def getEncoding(self, default="ascii"): + """Returns the Python encoding name for this name entry based on its platformID, + platEncID, and langID. If encoding for these values is not known, by default + 'ascii' is returned. That can be overriden by passing a value to the default + argument. + """ + return getEncoding(self.platformID, self.platEncID, self.langID, default) + + def encodingIsUnicodeCompatible(self): + return self.getEncoding(None) in ["utf_16_be", "ucs2be", "ascii", "latin1"] + + def __str__(self): + return self.toStr(errors="backslashreplace") + + def isUnicode(self): + return self.platformID == 0 or ( + self.platformID == 3 and self.platEncID in [0, 1, 10] + ) + + def toUnicode(self, errors: str = "strict") -> str: + """ + If self.string is a Unicode string, return it; otherwise try decoding the + bytes in self.string to a Unicode string using the encoding of this + entry as returned by self.getEncoding(); Note that self.getEncoding() + returns 'ascii' if the encoding is unknown to the library. + + Certain heuristics are performed to recover data from bytes that are + ill-formed in the chosen encoding, or that otherwise look misencoded + (mostly around bad UTF-16BE encoded bytes, or bytes that look like UTF-16BE + but marked otherwise). If the bytes are ill-formed and the heuristics fail, + the error is handled according to the errors parameter to this function, which is + passed to the underlying decode() function; by default it throws a + UnicodeDecodeError exception. + + Note: The mentioned heuristics mean that roundtripping a font to XML and back + to binary might recover some misencoded data whereas just loading the font + and saving it back will not change them. + """ + + def isascii(b: int) -> bool: + return (b >= 0x20 and b <= 0x7E) or b in [0x09, 0x0A, 0x0D] + + encoding = self.getEncoding() + string = self.string + + if ( + isinstance(string, bytes) + and encoding == "utf_16_be" + and len(string) % 2 == 1 + ): + # Recover badly encoded UTF-16 strings that have an odd number of bytes: + # - If the last byte is zero, drop it. Otherwise, + # - If all the odd bytes are zero and all the even bytes are ASCII, + # prepend one zero byte. Otherwise, + # - If first byte is zero and all other bytes are ASCII, insert zero + # bytes between consecutive ASCII bytes. + # + # (Yes, I've seen all of these in the wild... sigh) + if byteord(string[-1]) == 0: + string = string[:-1] + elif all( + byteord(b) == 0 if i % 2 else isascii(byteord(b)) + for i, b in enumerate(string) + ): + string = b"\0" + string + elif byteord(string[0]) == 0 and all( + isascii(byteord(b)) for b in string[1:] + ): + string = bytesjoin(b"\0" + bytechr(byteord(b)) for b in string[1:]) + + string = tostr(string, encoding=encoding, errors=errors) + + # If decoded strings still looks like UTF-16BE, it suggests a double-encoding. + # Fix it up. + if all( + ord(c) == 0 if i % 2 == 0 else isascii(ord(c)) for i, c in enumerate(string) + ): + # If string claims to be Mac encoding, but looks like UTF-16BE with ASCII text, + # narrow it down. + string = "".join(c for c in string[1::2]) + + return string + + def toBytes(self, errors="strict"): + """If self.string is a bytes object, return it; otherwise try encoding + the Unicode string in self.string to bytes using the encoding of this + entry as returned by self.getEncoding(); Note that self.getEncoding() + returns 'ascii' if the encoding is unknown to the library. + + If the Unicode string cannot be encoded to bytes in the chosen encoding, + the error is handled according to the errors parameter to this function, + which is passed to the underlying encode() function; by default it throws a + UnicodeEncodeError exception. + """ + return tobytes(self.string, encoding=self.getEncoding(), errors=errors) + + toStr = toUnicode + + def toXML(self, writer, ttFont): + try: + unistr = self.toUnicode() + except UnicodeDecodeError: + unistr = None + attrs = [ + ("nameID", self.nameID), + ("platformID", self.platformID), + ("platEncID", self.platEncID), + ("langID", hex(self.langID)), + ] + + if unistr is None or not self.encodingIsUnicodeCompatible(): + attrs.append(("unicode", unistr is not None)) + + writer.begintag("namerecord", attrs) + writer.newline() + if unistr is not None: + writer.write(unistr) + else: + writer.write8bit(self.string) + writer.newline() + writer.endtag("namerecord") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + self.nameID = safeEval(attrs["nameID"]) + self.platformID = safeEval(attrs["platformID"]) + self.platEncID = safeEval(attrs["platEncID"]) + self.langID = safeEval(attrs["langID"]) + s = strjoin(content).strip() + encoding = self.getEncoding() + if self.encodingIsUnicodeCompatible() or safeEval( + attrs.get("unicode", "False") + ): + self.string = s.encode(encoding) + else: + # This is the inverse of write8bit... + self.string = s.encode("latin1") + + def __lt__(self, other): + if type(self) != type(other): + return NotImplemented + + try: + selfTuple = ( + self.platformID, + self.platEncID, + self.langID, + self.nameID, + ) + otherTuple = ( + other.platformID, + other.platEncID, + other.langID, + other.nameID, + ) + except AttributeError: + # This can only happen for + # 1) an object that is not a NameRecord, or + # 2) an unlikely incomplete NameRecord object which has not been + # fully populated + return NotImplemented + + try: + # Include the actual NameRecord string in the comparison tuples + selfTuple = selfTuple + (self.toBytes(),) + otherTuple = otherTuple + (other.toBytes(),) + except UnicodeEncodeError as e: + # toBytes caused an encoding error in either of the two, so content + # to sorting based on IDs only + log.error("NameRecord sorting failed to encode: %s" % e) + + # Implemented so that list.sort() sorts according to the spec by using + # the order of the tuple items and their comparison + return selfTuple < otherTuple + + def __repr__(self): + return "<NameRecord NameID=%d; PlatformID=%d; LanguageID=%d>" % ( + self.nameID, + self.platformID, + self.langID, + ) + + +# Windows language ID → IETF BCP-47 language tag +# +# While Microsoft indicates a region/country for all its language +# IDs, we follow Unicode practice by omitting “most likely subtags” +# as per Unicode CLDR. For example, English is simply “en” and not +# “en-Latn” because according to Unicode, the default script +# for English is Latin. +# +# http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html +# http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry +_WINDOWS_LANGUAGES = { + 0x0436: "af", + 0x041C: "sq", + 0x0484: "gsw", + 0x045E: "am", + 0x1401: "ar-DZ", + 0x3C01: "ar-BH", + 0x0C01: "ar", + 0x0801: "ar-IQ", + 0x2C01: "ar-JO", + 0x3401: "ar-KW", + 0x3001: "ar-LB", + 0x1001: "ar-LY", + 0x1801: "ary", + 0x2001: "ar-OM", + 0x4001: "ar-QA", + 0x0401: "ar-SA", + 0x2801: "ar-SY", + 0x1C01: "aeb", + 0x3801: "ar-AE", + 0x2401: "ar-YE", + 0x042B: "hy", + 0x044D: "as", + 0x082C: "az-Cyrl", + 0x042C: "az", + 0x046D: "ba", + 0x042D: "eu", + 0x0423: "be", + 0x0845: "bn", + 0x0445: "bn-IN", + 0x201A: "bs-Cyrl", + 0x141A: "bs", + 0x047E: "br", + 0x0402: "bg", + 0x0403: "ca", + 0x0C04: "zh-HK", + 0x1404: "zh-MO", + 0x0804: "zh", + 0x1004: "zh-SG", + 0x0404: "zh-TW", + 0x0483: "co", + 0x041A: "hr", + 0x101A: "hr-BA", + 0x0405: "cs", + 0x0406: "da", + 0x048C: "prs", + 0x0465: "dv", + 0x0813: "nl-BE", + 0x0413: "nl", + 0x0C09: "en-AU", + 0x2809: "en-BZ", + 0x1009: "en-CA", + 0x2409: "en-029", + 0x4009: "en-IN", + 0x1809: "en-IE", + 0x2009: "en-JM", + 0x4409: "en-MY", + 0x1409: "en-NZ", + 0x3409: "en-PH", + 0x4809: "en-SG", + 0x1C09: "en-ZA", + 0x2C09: "en-TT", + 0x0809: "en-GB", + 0x0409: "en", + 0x3009: "en-ZW", + 0x0425: "et", + 0x0438: "fo", + 0x0464: "fil", + 0x040B: "fi", + 0x080C: "fr-BE", + 0x0C0C: "fr-CA", + 0x040C: "fr", + 0x140C: "fr-LU", + 0x180C: "fr-MC", + 0x100C: "fr-CH", + 0x0462: "fy", + 0x0456: "gl", + 0x0437: "ka", + 0x0C07: "de-AT", + 0x0407: "de", + 0x1407: "de-LI", + 0x1007: "de-LU", + 0x0807: "de-CH", + 0x0408: "el", + 0x046F: "kl", + 0x0447: "gu", + 0x0468: "ha", + 0x040D: "he", + 0x0439: "hi", + 0x040E: "hu", + 0x040F: "is", + 0x0470: "ig", + 0x0421: "id", + 0x045D: "iu", + 0x085D: "iu-Latn", + 0x083C: "ga", + 0x0434: "xh", + 0x0435: "zu", + 0x0410: "it", + 0x0810: "it-CH", + 0x0411: "ja", + 0x044B: "kn", + 0x043F: "kk", + 0x0453: "km", + 0x0486: "quc", + 0x0487: "rw", + 0x0441: "sw", + 0x0457: "kok", + 0x0412: "ko", + 0x0440: "ky", + 0x0454: "lo", + 0x0426: "lv", + 0x0427: "lt", + 0x082E: "dsb", + 0x046E: "lb", + 0x042F: "mk", + 0x083E: "ms-BN", + 0x043E: "ms", + 0x044C: "ml", + 0x043A: "mt", + 0x0481: "mi", + 0x047A: "arn", + 0x044E: "mr", + 0x047C: "moh", + 0x0450: "mn", + 0x0850: "mn-CN", + 0x0461: "ne", + 0x0414: "nb", + 0x0814: "nn", + 0x0482: "oc", + 0x0448: "or", + 0x0463: "ps", + 0x0415: "pl", + 0x0416: "pt", + 0x0816: "pt-PT", + 0x0446: "pa", + 0x046B: "qu-BO", + 0x086B: "qu-EC", + 0x0C6B: "qu", + 0x0418: "ro", + 0x0417: "rm", + 0x0419: "ru", + 0x243B: "smn", + 0x103B: "smj-NO", + 0x143B: "smj", + 0x0C3B: "se-FI", + 0x043B: "se", + 0x083B: "se-SE", + 0x203B: "sms", + 0x183B: "sma-NO", + 0x1C3B: "sms", + 0x044F: "sa", + 0x1C1A: "sr-Cyrl-BA", + 0x0C1A: "sr", + 0x181A: "sr-Latn-BA", + 0x081A: "sr-Latn", + 0x046C: "nso", + 0x0432: "tn", + 0x045B: "si", + 0x041B: "sk", + 0x0424: "sl", + 0x2C0A: "es-AR", + 0x400A: "es-BO", + 0x340A: "es-CL", + 0x240A: "es-CO", + 0x140A: "es-CR", + 0x1C0A: "es-DO", + 0x300A: "es-EC", + 0x440A: "es-SV", + 0x100A: "es-GT", + 0x480A: "es-HN", + 0x080A: "es-MX", + 0x4C0A: "es-NI", + 0x180A: "es-PA", + 0x3C0A: "es-PY", + 0x280A: "es-PE", + 0x500A: "es-PR", + # Microsoft has defined two different language codes for + # “Spanish with modern sorting” and “Spanish with traditional + # sorting”. This makes sense for collation APIs, and it would be + # possible to express this in BCP 47 language tags via Unicode + # extensions (eg., “es-u-co-trad” is “Spanish with traditional + # sorting”). However, for storing names in fonts, this distinction + # does not make sense, so we use “es” in both cases. + 0x0C0A: "es", + 0x040A: "es", + 0x540A: "es-US", + 0x380A: "es-UY", + 0x200A: "es-VE", + 0x081D: "sv-FI", + 0x041D: "sv", + 0x045A: "syr", + 0x0428: "tg", + 0x085F: "tzm", + 0x0449: "ta", + 0x0444: "tt", + 0x044A: "te", + 0x041E: "th", + 0x0451: "bo", + 0x041F: "tr", + 0x0442: "tk", + 0x0480: "ug", + 0x0422: "uk", + 0x042E: "hsb", + 0x0420: "ur", + 0x0843: "uz-Cyrl", + 0x0443: "uz", + 0x042A: "vi", + 0x0452: "cy", + 0x0488: "wo", + 0x0485: "sah", + 0x0478: "ii", + 0x046A: "yo", +} + + +_MAC_LANGUAGES = { + 0: "en", + 1: "fr", + 2: "de", + 3: "it", + 4: "nl", + 5: "sv", + 6: "es", + 7: "da", + 8: "pt", + 9: "no", + 10: "he", + 11: "ja", + 12: "ar", + 13: "fi", + 14: "el", + 15: "is", + 16: "mt", + 17: "tr", + 18: "hr", + 19: "zh-Hant", + 20: "ur", + 21: "hi", + 22: "th", + 23: "ko", + 24: "lt", + 25: "pl", + 26: "hu", + 27: "es", + 28: "lv", + 29: "se", + 30: "fo", + 31: "fa", + 32: "ru", + 33: "zh", + 34: "nl-BE", + 35: "ga", + 36: "sq", + 37: "ro", + 38: "cz", + 39: "sk", + 40: "sl", + 41: "yi", + 42: "sr", + 43: "mk", + 44: "bg", + 45: "uk", + 46: "be", + 47: "uz", + 48: "kk", + 49: "az-Cyrl", + 50: "az-Arab", + 51: "hy", + 52: "ka", + 53: "mo", + 54: "ky", + 55: "tg", + 56: "tk", + 57: "mn-CN", + 58: "mn", + 59: "ps", + 60: "ks", + 61: "ku", + 62: "sd", + 63: "bo", + 64: "ne", + 65: "sa", + 66: "mr", + 67: "bn", + 68: "as", + 69: "gu", + 70: "pa", + 71: "or", + 72: "ml", + 73: "kn", + 74: "ta", + 75: "te", + 76: "si", + 77: "my", + 78: "km", + 79: "lo", + 80: "vi", + 81: "id", + 82: "tl", + 83: "ms", + 84: "ms-Arab", + 85: "am", + 86: "ti", + 87: "om", + 88: "so", + 89: "sw", + 90: "rw", + 91: "rn", + 92: "ny", + 93: "mg", + 94: "eo", + 128: "cy", + 129: "eu", + 130: "ca", + 131: "la", + 132: "qu", + 133: "gn", + 134: "ay", + 135: "tt", + 136: "ug", + 137: "dz", + 138: "jv", + 139: "su", + 140: "gl", + 141: "af", + 142: "br", + 143: "iu", + 144: "gd", + 145: "gv", + 146: "ga", + 147: "to", + 148: "el-polyton", + 149: "kl", + 150: "az", + 151: "nn", +} + + +_WINDOWS_LANGUAGE_CODES = { + lang.lower(): code for code, lang in _WINDOWS_LANGUAGES.items() +} +_MAC_LANGUAGE_CODES = {lang.lower(): code for code, lang in _MAC_LANGUAGES.items()} + + +# MacOS language ID → MacOS script ID +# +# Note that the script ID is not sufficient to determine what encoding +# to use in TrueType files. For some languages, MacOS used a modification +# of a mainstream script. For example, an Icelandic name would be stored +# with smRoman in the TrueType naming table, but the actual encoding +# is a special Icelandic version of the normal Macintosh Roman encoding. +# As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal +# Syllables but MacOS had run out of available script codes, so this was +# done as a (pretty radical) “modification” of Ethiopic. +# +# http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt +_MAC_LANGUAGE_TO_SCRIPT = { + 0: 0, # langEnglish → smRoman + 1: 0, # langFrench → smRoman + 2: 0, # langGerman → smRoman + 3: 0, # langItalian → smRoman + 4: 0, # langDutch → smRoman + 5: 0, # langSwedish → smRoman + 6: 0, # langSpanish → smRoman + 7: 0, # langDanish → smRoman + 8: 0, # langPortuguese → smRoman + 9: 0, # langNorwegian → smRoman + 10: 5, # langHebrew → smHebrew + 11: 1, # langJapanese → smJapanese + 12: 4, # langArabic → smArabic + 13: 0, # langFinnish → smRoman + 14: 6, # langGreek → smGreek + 15: 0, # langIcelandic → smRoman (modified) + 16: 0, # langMaltese → smRoman + 17: 0, # langTurkish → smRoman (modified) + 18: 0, # langCroatian → smRoman (modified) + 19: 2, # langTradChinese → smTradChinese + 20: 4, # langUrdu → smArabic + 21: 9, # langHindi → smDevanagari + 22: 21, # langThai → smThai + 23: 3, # langKorean → smKorean + 24: 29, # langLithuanian → smCentralEuroRoman + 25: 29, # langPolish → smCentralEuroRoman + 26: 29, # langHungarian → smCentralEuroRoman + 27: 29, # langEstonian → smCentralEuroRoman + 28: 29, # langLatvian → smCentralEuroRoman + 29: 0, # langSami → smRoman + 30: 0, # langFaroese → smRoman (modified) + 31: 4, # langFarsi → smArabic (modified) + 32: 7, # langRussian → smCyrillic + 33: 25, # langSimpChinese → smSimpChinese + 34: 0, # langFlemish → smRoman + 35: 0, # langIrishGaelic → smRoman (modified) + 36: 0, # langAlbanian → smRoman + 37: 0, # langRomanian → smRoman (modified) + 38: 29, # langCzech → smCentralEuroRoman + 39: 29, # langSlovak → smCentralEuroRoman + 40: 0, # langSlovenian → smRoman (modified) + 41: 5, # langYiddish → smHebrew + 42: 7, # langSerbian → smCyrillic + 43: 7, # langMacedonian → smCyrillic + 44: 7, # langBulgarian → smCyrillic + 45: 7, # langUkrainian → smCyrillic (modified) + 46: 7, # langByelorussian → smCyrillic + 47: 7, # langUzbek → smCyrillic + 48: 7, # langKazakh → smCyrillic + 49: 7, # langAzerbaijani → smCyrillic + 50: 4, # langAzerbaijanAr → smArabic + 51: 24, # langArmenian → smArmenian + 52: 23, # langGeorgian → smGeorgian + 53: 7, # langMoldavian → smCyrillic + 54: 7, # langKirghiz → smCyrillic + 55: 7, # langTajiki → smCyrillic + 56: 7, # langTurkmen → smCyrillic + 57: 27, # langMongolian → smMongolian + 58: 7, # langMongolianCyr → smCyrillic + 59: 4, # langPashto → smArabic + 60: 4, # langKurdish → smArabic + 61: 4, # langKashmiri → smArabic + 62: 4, # langSindhi → smArabic + 63: 26, # langTibetan → smTibetan + 64: 9, # langNepali → smDevanagari + 65: 9, # langSanskrit → smDevanagari + 66: 9, # langMarathi → smDevanagari + 67: 13, # langBengali → smBengali + 68: 13, # langAssamese → smBengali + 69: 11, # langGujarati → smGujarati + 70: 10, # langPunjabi → smGurmukhi + 71: 12, # langOriya → smOriya + 72: 17, # langMalayalam → smMalayalam + 73: 16, # langKannada → smKannada + 74: 14, # langTamil → smTamil + 75: 15, # langTelugu → smTelugu + 76: 18, # langSinhalese → smSinhalese + 77: 19, # langBurmese → smBurmese + 78: 20, # langKhmer → smKhmer + 79: 22, # langLao → smLao + 80: 30, # langVietnamese → smVietnamese + 81: 0, # langIndonesian → smRoman + 82: 0, # langTagalog → smRoman + 83: 0, # langMalayRoman → smRoman + 84: 4, # langMalayArabic → smArabic + 85: 28, # langAmharic → smEthiopic + 86: 28, # langTigrinya → smEthiopic + 87: 28, # langOromo → smEthiopic + 88: 0, # langSomali → smRoman + 89: 0, # langSwahili → smRoman + 90: 0, # langKinyarwanda → smRoman + 91: 0, # langRundi → smRoman + 92: 0, # langNyanja → smRoman + 93: 0, # langMalagasy → smRoman + 94: 0, # langEsperanto → smRoman + 128: 0, # langWelsh → smRoman (modified) + 129: 0, # langBasque → smRoman + 130: 0, # langCatalan → smRoman + 131: 0, # langLatin → smRoman + 132: 0, # langQuechua → smRoman + 133: 0, # langGuarani → smRoman + 134: 0, # langAymara → smRoman + 135: 7, # langTatar → smCyrillic + 136: 4, # langUighur → smArabic + 137: 26, # langDzongkha → smTibetan + 138: 0, # langJavaneseRom → smRoman + 139: 0, # langSundaneseRom → smRoman + 140: 0, # langGalician → smRoman + 141: 0, # langAfrikaans → smRoman + 142: 0, # langBreton → smRoman (modified) + 143: 28, # langInuktitut → smEthiopic (modified) + 144: 0, # langScottishGaelic → smRoman (modified) + 145: 0, # langManxGaelic → smRoman (modified) + 146: 0, # langIrishGaelicScript → smRoman (modified) + 147: 0, # langTongan → smRoman + 148: 6, # langGreekAncient → smRoman + 149: 0, # langGreenlandic → smRoman + 150: 0, # langAzerbaijanRoman → smRoman + 151: 0, # langNynorsk → smRoman +} + + +class NameRecordVisitor(TTVisitor): + # Font tables that have NameIDs we need to collect. + TABLES = ("GSUB", "GPOS", "fvar", "CPAL", "STAT") + + def __init__(self): + self.seen = set() + + +@NameRecordVisitor.register_attrs( + ( + (otTables.FeatureParamsSize, ("SubfamilyNameID",)), + (otTables.FeatureParamsStylisticSet, ("UINameID",)), + (otTables.STAT, ("ElidedFallbackNameID",)), + (otTables.AxisRecord, ("AxisNameID",)), + (otTables.AxisValue, ("ValueNameID",)), + (otTables.FeatureName, ("FeatureNameID",)), + (otTables.Setting, ("SettingNameID",)), + ) +) +def visit(visitor, obj, attr, value): + visitor.seen.add(value) + + +@NameRecordVisitor.register(otTables.FeatureParamsCharacterVariants) +def visit(visitor, obj): + for attr in ("FeatUILabelNameID", "FeatUITooltipTextNameID", "SampleTextNameID"): + value = getattr(obj, attr) + visitor.seen.add(value) + # also include the sequence of UI strings for individual variants, if any + if obj.FirstParamUILabelNameID == 0 or obj.NumNamedParameters == 0: + return + visitor.seen.update( + range( + obj.FirstParamUILabelNameID, + obj.FirstParamUILabelNameID + obj.NumNamedParameters, + ) + ) + + +@NameRecordVisitor.register(ttLib.getTableClass("fvar")) +def visit(visitor, obj): + for inst in obj.instances: + if inst.postscriptNameID != 0xFFFF: + visitor.seen.add(inst.postscriptNameID) + visitor.seen.add(inst.subfamilyNameID) + + for axis in obj.axes: + visitor.seen.add(axis.axisNameID) + + +@NameRecordVisitor.register(ttLib.getTableClass("CPAL")) +def visit(visitor, obj): + if obj.version == 1: + visitor.seen.update(obj.paletteLabels) + visitor.seen.update(obj.paletteEntryLabels) + + +@NameRecordVisitor.register(ttLib.TTFont) +def visit(visitor, font, *args, **kwargs): + if hasattr(visitor, "font"): + return False + + visitor.font = font + for tag in visitor.TABLES: + if tag in font: + visitor.visit(font[tag], *args, **kwargs) + del visitor.font + return False diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_o_p_b_d.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_o_p_b_d.py new file mode 100644 index 0000000000000000000000000000000000000000..b4c5f568290e20563992de91c7a0f5e6928652bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_o_p_b_d.py @@ -0,0 +1,14 @@ +from .otBase import BaseTTXConverter + + +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6opbd.html +class table__o_p_b_d(BaseTTXConverter): + """Optical Bounds table + + The AAT ``opbd`` table contains optical boundary points for glyphs, which + applications can use for the visual alignment of lines of text. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6opbd.html + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_p_o_s_t.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_p_o_s_t.py new file mode 100644 index 0000000000000000000000000000000000000000..1564c89347b4b7934b978c8f4ae383851b6d18d5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_p_o_s_t.py @@ -0,0 +1,319 @@ +from fontTools import ttLib +from fontTools.ttLib.standardGlyphOrder import standardGlyphOrder +from fontTools.misc import sstruct +from fontTools.misc.textTools import bytechr, byteord, tobytes, tostr, safeEval, readHex +from . import DefaultTable +import sys +import struct +import array +import logging + +log = logging.getLogger(__name__) + +postFormat = """ + > + formatType: 16.16F + italicAngle: 16.16F # italic angle in degrees + underlinePosition: h + underlineThickness: h + isFixedPitch: L + minMemType42: L # minimum memory if TrueType font is downloaded + maxMemType42: L # maximum memory if TrueType font is downloaded + minMemType1: L # minimum memory if Type1 font is downloaded + maxMemType1: L # maximum memory if Type1 font is downloaded +""" + +postFormatSize = sstruct.calcsize(postFormat) + + +class table__p_o_s_t(DefaultTable.DefaultTable): + """PostScript table + + The ``post`` table contains information needed to use the font on + PostScript printers, including the PostScript names of glyphs and + data that was stored in the ``FontInfo`` dictionary for Type 1 fonts. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/post + """ + + def decompile(self, data, ttFont): + sstruct.unpack(postFormat, data[:postFormatSize], self) + data = data[postFormatSize:] + if self.formatType == 1.0: + self.decode_format_1_0(data, ttFont) + elif self.formatType == 2.0: + self.decode_format_2_0(data, ttFont) + elif self.formatType == 3.0: + self.decode_format_3_0(data, ttFont) + elif self.formatType == 4.0: + self.decode_format_4_0(data, ttFont) + else: + # supported format + raise ttLib.TTLibError( + "'post' table format %f not supported" % self.formatType + ) + + def compile(self, ttFont): + data = sstruct.pack(postFormat, self) + if self.formatType == 1.0: + pass # we're done + elif self.formatType == 2.0: + data = data + self.encode_format_2_0(ttFont) + elif self.formatType == 3.0: + pass # we're done + elif self.formatType == 4.0: + data = data + self.encode_format_4_0(ttFont) + else: + # supported format + raise ttLib.TTLibError( + "'post' table format %f not supported" % self.formatType + ) + return data + + def getGlyphOrder(self): + """This function will get called by a ttLib.TTFont instance. + Do not call this function yourself, use TTFont().getGlyphOrder() + or its relatives instead! + """ + if not hasattr(self, "glyphOrder"): + raise ttLib.TTLibError("illegal use of getGlyphOrder()") + glyphOrder = self.glyphOrder + del self.glyphOrder + return glyphOrder + + def decode_format_1_0(self, data, ttFont): + self.glyphOrder = standardGlyphOrder[: ttFont["maxp"].numGlyphs] + + def decode_format_2_0(self, data, ttFont): + (numGlyphs,) = struct.unpack(">H", data[:2]) + numGlyphs = int(numGlyphs) + if numGlyphs > ttFont["maxp"].numGlyphs: + # Assume the numGlyphs field is bogus, so sync with maxp. + # I've seen this in one font, and if the assumption is + # wrong elsewhere, well, so be it: it's hard enough to + # work around _one_ non-conforming post format... + numGlyphs = ttFont["maxp"].numGlyphs + data = data[2:] + indices = array.array("H") + indices.frombytes(data[: 2 * numGlyphs]) + if sys.byteorder != "big": + indices.byteswap() + data = data[2 * numGlyphs :] + maxIndex = max(indices) + self.extraNames = extraNames = unpackPStrings(data, maxIndex - 257) + self.glyphOrder = glyphOrder = [""] * int(ttFont["maxp"].numGlyphs) + for glyphID in range(numGlyphs): + index = indices[glyphID] + if index > 257: + try: + name = extraNames[index - 258] + except IndexError: + name = "" + else: + # fetch names from standard list + name = standardGlyphOrder[index] + glyphOrder[glyphID] = name + self.build_psNameMapping(ttFont) + + def build_psNameMapping(self, ttFont): + mapping = {} + allNames = {} + glyphOrderNames = set(self.glyphOrder) + for i in range(ttFont["maxp"].numGlyphs): + glyphName = psName = self.glyphOrder[i] + if glyphName == "": + glyphName = "glyph%.5d" % i + + if glyphName in allNames: + # make up a new glyphName that's unique + n = allNames[glyphName] + # check if the glyph name exists in the glyph order + while f"{glyphName}.{n}" in glyphOrderNames: + n += 1 + allNames[glyphName] = n + 1 + glyphName = f"{glyphName}.{n}" + + allNames[glyphName] = 1 + if glyphName != psName: + self.glyphOrder[i] = glyphName + mapping[glyphName] = psName + + self.mapping = mapping + + def decode_format_3_0(self, data, ttFont): + # Setting self.glyphOrder to None will cause the TTFont object + # try and construct glyph names from a Unicode cmap table. + self.glyphOrder = None + + def decode_format_4_0(self, data, ttFont): + from fontTools import agl + + numGlyphs = ttFont["maxp"].numGlyphs + indices = array.array("H") + indices.frombytes(data) + if sys.byteorder != "big": + indices.byteswap() + # In some older fonts, the size of the post table doesn't match + # the number of glyphs. Sometimes it's bigger, sometimes smaller. + self.glyphOrder = glyphOrder = [""] * int(numGlyphs) + for i in range(min(len(indices), numGlyphs)): + if indices[i] == 0xFFFF: + self.glyphOrder[i] = "" + elif indices[i] in agl.UV2AGL: + self.glyphOrder[i] = agl.UV2AGL[indices[i]] + else: + self.glyphOrder[i] = "uni%04X" % indices[i] + self.build_psNameMapping(ttFont) + + def encode_format_2_0(self, ttFont): + numGlyphs = ttFont["maxp"].numGlyphs + glyphOrder = ttFont.getGlyphOrder() + assert len(glyphOrder) == numGlyphs + indices = array.array("H") + extraDict = {} + extraNames = self.extraNames = [ + n for n in self.extraNames if n not in standardGlyphOrder + ] + for i, name in enumerate(extraNames): + extraDict[name] = i + for glyphName in glyphOrder: + if glyphName in self.mapping: + psName = self.mapping[glyphName] + else: + psName = glyphName + if psName in extraDict: + index = 258 + extraDict[psName] + elif psName in standardGlyphOrder: + index = standardGlyphOrder.index(psName) + else: + index = 258 + len(extraNames) + extraDict[psName] = len(extraNames) + extraNames.append(psName) + indices.append(index) + if sys.byteorder != "big": + indices.byteswap() + return ( + struct.pack(">H", numGlyphs) + indices.tobytes() + packPStrings(extraNames) + ) + + def encode_format_4_0(self, ttFont): + from fontTools import agl + + numGlyphs = ttFont["maxp"].numGlyphs + glyphOrder = ttFont.getGlyphOrder() + assert len(glyphOrder) == numGlyphs + indices = array.array("H") + for glyphID in glyphOrder: + glyphID = glyphID.split("#")[0] + if glyphID in agl.AGL2UV: + indices.append(agl.AGL2UV[glyphID]) + elif len(glyphID) == 7 and glyphID[:3] == "uni": + indices.append(int(glyphID[3:], 16)) + else: + indices.append(0xFFFF) + if sys.byteorder != "big": + indices.byteswap() + return indices.tobytes() + + def toXML(self, writer, ttFont): + formatstring, names, fixes = sstruct.getformat(postFormat) + for name in names: + value = getattr(self, name) + writer.simpletag(name, value=value) + writer.newline() + if hasattr(self, "mapping"): + writer.begintag("psNames") + writer.newline() + writer.comment( + "This file uses unique glyph names based on the information\n" + "found in the 'post' table. Since these names might not be unique,\n" + "we have to invent artificial names in case of clashes. In order to\n" + "be able to retain the original information, we need a name to\n" + "ps name mapping for those cases where they differ. That's what\n" + "you see below.\n" + ) + writer.newline() + items = sorted(self.mapping.items()) + for name, psName in items: + writer.simpletag("psName", name=name, psName=psName) + writer.newline() + writer.endtag("psNames") + writer.newline() + if hasattr(self, "extraNames"): + writer.begintag("extraNames") + writer.newline() + writer.comment( + "following are the name that are not taken from the standard Mac glyph order" + ) + writer.newline() + for name in self.extraNames: + writer.simpletag("psName", name=name) + writer.newline() + writer.endtag("extraNames") + writer.newline() + if hasattr(self, "data"): + writer.begintag("hexdata") + writer.newline() + writer.dumphex(self.data) + writer.endtag("hexdata") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name not in ("psNames", "extraNames", "hexdata"): + setattr(self, name, safeEval(attrs["value"])) + elif name == "psNames": + self.mapping = {} + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name == "psName": + self.mapping[attrs["name"]] = attrs["psName"] + elif name == "extraNames": + self.extraNames = [] + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + if name == "psName": + self.extraNames.append(attrs["name"]) + else: + self.data = readHex(content) + + +def unpackPStrings(data, n): + # extract n Pascal strings from data. + # if there is not enough data, use "" + + strings = [] + index = 0 + dataLen = len(data) + + for _ in range(n): + if dataLen <= index: + length = 0 + else: + length = byteord(data[index]) + index += 1 + + if dataLen <= index + length - 1: + name = "" + else: + name = tostr(data[index : index + length], encoding="latin1") + strings.append(name) + index += length + + if index < dataLen: + log.warning("%d extra bytes in post.stringData array", dataLen - index) + + elif dataLen < index: + log.warning("not enough data in post.stringData array") + + return strings + + +def packPStrings(strings): + data = b"" + for s in strings: + data = data + bytechr(len(s)) + tobytes(s, encoding="latin1") + return data diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_p_r_e_p.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_p_r_e_p.py new file mode 100644 index 0000000000000000000000000000000000000000..cf4a5dd24f27ab08082cf9976bc2f5a9e1a967a5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_p_r_e_p.py @@ -0,0 +1,16 @@ +from fontTools import ttLib + +superclass = ttLib.getTableClass("fpgm") + + +class table__p_r_e_p(superclass): + """Control Value Program table + + The ``prep`` table contains TrueType instructions that can makee font-wide + alterations to the Control Value Table. It may potentially be executed + before any glyph is processed. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/prep + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_p_r_o_p.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_p_r_o_p.py new file mode 100644 index 0000000000000000000000000000000000000000..1d7de8098de797268cd14607939e78e0c5c7bf5a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_p_r_o_p.py @@ -0,0 +1,12 @@ +from .otBase import BaseTTXConverter + + +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6prop.html +class table__p_r_o_p(BaseTTXConverter): + """The AAT ``prop`` table can store a variety of per-glyph properties, such as + Unicode directionality or whether glyphs are non-spacing marks. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6prop.html + """ + + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_s_b_i_x.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_s_b_i_x.py new file mode 100644 index 0000000000000000000000000000000000000000..806c4b204ae51b256a9554df560e0ff6868212d1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_s_b_i_x.py @@ -0,0 +1,128 @@ +from fontTools.misc import sstruct +from fontTools.misc.textTools import safeEval, num2binary, binary2num +from . import DefaultTable +from .sbixStrike import Strike + +sbixHeaderFormat = """ + > + version: H # Version number (set to 1) + flags: H # The only two bits used in the flags field are bits 0 + # and 1. For historical reasons, bit 0 must always be 1. + # Bit 1 is a sbixDrawOutlines flag and is interpreted as + # follows: + # 0: Draw only 'sbix' bitmaps + # 1: Draw both 'sbix' bitmaps and outlines, in that + # order + numStrikes: L # Number of bitmap strikes to follow +""" +sbixHeaderFormatSize = sstruct.calcsize(sbixHeaderFormat) + + +sbixStrikeOffsetFormat = """ + > + strikeOffset: L # Offset from begining of table to data for the + # individual strike +""" +sbixStrikeOffsetFormatSize = sstruct.calcsize(sbixStrikeOffsetFormat) + + +class table__s_b_i_x(DefaultTable.DefaultTable): + """Standard Bitmap Graphics table + + The ``sbix`` table stores bitmap image data in standard graphics formats + like JPEG, PNG, or TIFF. The glyphs for which the ``sbix`` table provides + data are indexed by Glyph ID. For each such glyph, the ``sbix`` table can + hold different data for different sizes, called "strikes." + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/sbix + """ + + def __init__(self, tag=None): + DefaultTable.DefaultTable.__init__(self, tag) + self.version = 1 + self.flags = 1 + self.numStrikes = 0 + self.strikes = {} + self.strikeOffsets = [] + + def decompile(self, data, ttFont): + # read table header + sstruct.unpack(sbixHeaderFormat, data[:sbixHeaderFormatSize], self) + # collect offsets to individual strikes in self.strikeOffsets + for i in range(self.numStrikes): + current_offset = sbixHeaderFormatSize + i * sbixStrikeOffsetFormatSize + offset_entry = sbixStrikeOffset() + sstruct.unpack( + sbixStrikeOffsetFormat, + data[current_offset : current_offset + sbixStrikeOffsetFormatSize], + offset_entry, + ) + self.strikeOffsets.append(offset_entry.strikeOffset) + + # decompile Strikes + for i in range(self.numStrikes - 1, -1, -1): + current_strike = Strike(rawdata=data[self.strikeOffsets[i] :]) + data = data[: self.strikeOffsets[i]] + current_strike.decompile(ttFont) + # print " Strike length: %xh" % len(bitmapSetData) + # print "Number of Glyph entries:", len(current_strike.glyphs) + if current_strike.ppem in self.strikes: + from fontTools import ttLib + + raise ttLib.TTLibError("Pixel 'ppem' must be unique for each Strike") + self.strikes[current_strike.ppem] = current_strike + + # after the glyph data records have been extracted, we don't need the offsets anymore + del self.strikeOffsets + del self.numStrikes + + def compile(self, ttFont): + sbixData = b"" + self.numStrikes = len(self.strikes) + sbixHeader = sstruct.pack(sbixHeaderFormat, self) + + # calculate offset to start of first strike + setOffset = sbixHeaderFormatSize + sbixStrikeOffsetFormatSize * self.numStrikes + + for si in sorted(self.strikes.keys()): + current_strike = self.strikes[si] + current_strike.compile(ttFont) + # append offset to this strike to table header + current_strike.strikeOffset = setOffset + sbixHeader += sstruct.pack(sbixStrikeOffsetFormat, current_strike) + setOffset += len(current_strike.data) + sbixData += current_strike.data + + return sbixHeader + sbixData + + def toXML(self, xmlWriter, ttFont): + xmlWriter.simpletag("version", value=self.version) + xmlWriter.newline() + xmlWriter.simpletag("flags", value=num2binary(self.flags, 16)) + xmlWriter.newline() + for i in sorted(self.strikes.keys()): + self.strikes[i].toXML(xmlWriter, ttFont) + + def fromXML(self, name, attrs, content, ttFont): + if name == "version": + setattr(self, name, safeEval(attrs["value"])) + elif name == "flags": + setattr(self, name, binary2num(attrs["value"])) + elif name == "strike": + current_strike = Strike() + for element in content: + if isinstance(element, tuple): + name, attrs, content = element + current_strike.fromXML(name, attrs, content, ttFont) + self.strikes[current_strike.ppem] = current_strike + else: + from fontTools import ttLib + + raise ttLib.TTLibError("can't handle '%s' element" % name) + + +# Helper classes + + +class sbixStrikeOffset(object): + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_t_r_a_k.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_t_r_a_k.py new file mode 100644 index 0000000000000000000000000000000000000000..9184506108b1597044afcc3d0652fd7d1fb7ac16 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_t_r_a_k.py @@ -0,0 +1,329 @@ +from fontTools.misc import sstruct +from fontTools.misc.fixedTools import ( + fixedToFloat as fi2fl, + floatToFixed as fl2fi, + floatToFixedToStr as fl2str, + strToFixedToFloat as str2fl, +) +from fontTools.misc.textTools import bytesjoin, safeEval +from fontTools.ttLib import TTLibError +from . import DefaultTable +import struct +from collections.abc import MutableMapping + +# Apple's documentation of 'trak': +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6trak.html + +TRAK_HEADER_FORMAT = """ + > # big endian + version: 16.16F + format: H + horizOffset: H + vertOffset: H + reserved: H +""" + +TRAK_HEADER_FORMAT_SIZE = sstruct.calcsize(TRAK_HEADER_FORMAT) + + +TRACK_DATA_FORMAT = """ + > # big endian + nTracks: H + nSizes: H + sizeTableOffset: L +""" + +TRACK_DATA_FORMAT_SIZE = sstruct.calcsize(TRACK_DATA_FORMAT) + + +TRACK_TABLE_ENTRY_FORMAT = """ + > # big endian + track: 16.16F + nameIndex: H + offset: H +""" + +TRACK_TABLE_ENTRY_FORMAT_SIZE = sstruct.calcsize(TRACK_TABLE_ENTRY_FORMAT) + + +# size values are actually '16.16F' fixed-point values, but here I do the +# fixedToFloat conversion manually instead of relying on sstruct +SIZE_VALUE_FORMAT = ">l" +SIZE_VALUE_FORMAT_SIZE = struct.calcsize(SIZE_VALUE_FORMAT) + +# per-Size values are in 'FUnits', i.e. 16-bit signed integers +PER_SIZE_VALUE_FORMAT = ">h" +PER_SIZE_VALUE_FORMAT_SIZE = struct.calcsize(PER_SIZE_VALUE_FORMAT) + + +class table__t_r_a_k(DefaultTable.DefaultTable): + """The AAT ``trak`` table can store per-size adjustments to each glyph's + sidebearings to make when tracking is enabled, which applications can + use to provide more visually balanced line spacing. + + See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6trak.html + """ + + def compile(self, ttFont): + dataList = [] + offset = TRAK_HEADER_FORMAT_SIZE + for direction in ("horiz", "vert"): + trackData = getattr(self, direction + "Data", TrackData()) + offsetName = direction + "Offset" + # set offset to 0 if None or empty + if not trackData: + setattr(self, offsetName, 0) + continue + # TrackData table format must be longword aligned + alignedOffset = (offset + 3) & ~3 + padding, offset = b"\x00" * (alignedOffset - offset), alignedOffset + setattr(self, offsetName, offset) + + data = trackData.compile(offset) + offset += len(data) + dataList.append(padding + data) + + self.reserved = 0 + tableData = bytesjoin([sstruct.pack(TRAK_HEADER_FORMAT, self)] + dataList) + return tableData + + def decompile(self, data, ttFont): + sstruct.unpack(TRAK_HEADER_FORMAT, data[:TRAK_HEADER_FORMAT_SIZE], self) + for direction in ("horiz", "vert"): + trackData = TrackData() + offset = getattr(self, direction + "Offset") + if offset != 0: + trackData.decompile(data, offset) + setattr(self, direction + "Data", trackData) + + def toXML(self, writer, ttFont): + writer.simpletag("version", value=self.version) + writer.newline() + writer.simpletag("format", value=self.format) + writer.newline() + for direction in ("horiz", "vert"): + dataName = direction + "Data" + writer.begintag(dataName) + writer.newline() + trackData = getattr(self, dataName, TrackData()) + trackData.toXML(writer, ttFont) + writer.endtag(dataName) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "version": + self.version = safeEval(attrs["value"]) + elif name == "format": + self.format = safeEval(attrs["value"]) + elif name in ("horizData", "vertData"): + trackData = TrackData() + setattr(self, name, trackData) + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content_ = element + trackData.fromXML(name, attrs, content_, ttFont) + + +class TrackData(MutableMapping): + def __init__(self, initialdata={}): + self._map = dict(initialdata) + + def compile(self, offset): + nTracks = len(self) + sizes = self.sizes() + nSizes = len(sizes) + + # offset to the start of the size subtable + offset += TRACK_DATA_FORMAT_SIZE + TRACK_TABLE_ENTRY_FORMAT_SIZE * nTracks + trackDataHeader = sstruct.pack( + TRACK_DATA_FORMAT, + {"nTracks": nTracks, "nSizes": nSizes, "sizeTableOffset": offset}, + ) + + entryDataList = [] + perSizeDataList = [] + # offset to per-size tracking values + offset += SIZE_VALUE_FORMAT_SIZE * nSizes + # sort track table entries by track value + for track, entry in sorted(self.items()): + assert entry.nameIndex is not None + entry.track = track + entry.offset = offset + entryDataList += [sstruct.pack(TRACK_TABLE_ENTRY_FORMAT, entry)] + # sort per-size values by size + for size, value in sorted(entry.items()): + perSizeDataList += [struct.pack(PER_SIZE_VALUE_FORMAT, value)] + offset += PER_SIZE_VALUE_FORMAT_SIZE * nSizes + # sort size values + sizeDataList = [ + struct.pack(SIZE_VALUE_FORMAT, fl2fi(sv, 16)) for sv in sorted(sizes) + ] + + data = bytesjoin( + [trackDataHeader] + entryDataList + sizeDataList + perSizeDataList + ) + return data + + def decompile(self, data, offset): + # initial offset is from the start of trak table to the current TrackData + trackDataHeader = data[offset : offset + TRACK_DATA_FORMAT_SIZE] + if len(trackDataHeader) != TRACK_DATA_FORMAT_SIZE: + raise TTLibError("not enough data to decompile TrackData header") + sstruct.unpack(TRACK_DATA_FORMAT, trackDataHeader, self) + offset += TRACK_DATA_FORMAT_SIZE + + nSizes = self.nSizes + sizeTableOffset = self.sizeTableOffset + sizeTable = [] + for i in range(nSizes): + sizeValueData = data[ + sizeTableOffset : sizeTableOffset + SIZE_VALUE_FORMAT_SIZE + ] + if len(sizeValueData) < SIZE_VALUE_FORMAT_SIZE: + raise TTLibError("not enough data to decompile TrackData size subtable") + (sizeValue,) = struct.unpack(SIZE_VALUE_FORMAT, sizeValueData) + sizeTable.append(fi2fl(sizeValue, 16)) + sizeTableOffset += SIZE_VALUE_FORMAT_SIZE + + for i in range(self.nTracks): + entry = TrackTableEntry() + entryData = data[offset : offset + TRACK_TABLE_ENTRY_FORMAT_SIZE] + if len(entryData) < TRACK_TABLE_ENTRY_FORMAT_SIZE: + raise TTLibError("not enough data to decompile TrackTableEntry record") + sstruct.unpack(TRACK_TABLE_ENTRY_FORMAT, entryData, entry) + perSizeOffset = entry.offset + for j in range(nSizes): + size = sizeTable[j] + perSizeValueData = data[ + perSizeOffset : perSizeOffset + PER_SIZE_VALUE_FORMAT_SIZE + ] + if len(perSizeValueData) < PER_SIZE_VALUE_FORMAT_SIZE: + raise TTLibError( + "not enough data to decompile per-size track values" + ) + (perSizeValue,) = struct.unpack(PER_SIZE_VALUE_FORMAT, perSizeValueData) + entry[size] = perSizeValue + perSizeOffset += PER_SIZE_VALUE_FORMAT_SIZE + self[entry.track] = entry + offset += TRACK_TABLE_ENTRY_FORMAT_SIZE + + def toXML(self, writer, ttFont): + nTracks = len(self) + nSizes = len(self.sizes()) + writer.comment("nTracks=%d, nSizes=%d" % (nTracks, nSizes)) + writer.newline() + for track, entry in sorted(self.items()): + assert entry.nameIndex is not None + entry.track = track + entry.toXML(writer, ttFont) + + def fromXML(self, name, attrs, content, ttFont): + if name != "trackEntry": + return + entry = TrackTableEntry() + entry.fromXML(name, attrs, content, ttFont) + self[entry.track] = entry + + def sizes(self): + if not self: + return frozenset() + tracks = list(self.tracks()) + sizes = self[tracks.pop(0)].sizes() + for track in tracks: + entrySizes = self[track].sizes() + if sizes != entrySizes: + raise TTLibError( + "'trak' table entries must specify the same sizes: " + "%s != %s" % (sorted(sizes), sorted(entrySizes)) + ) + return frozenset(sizes) + + def __getitem__(self, track): + return self._map[track] + + def __delitem__(self, track): + del self._map[track] + + def __setitem__(self, track, entry): + self._map[track] = entry + + def __len__(self): + return len(self._map) + + def __iter__(self): + return iter(self._map) + + def keys(self): + return self._map.keys() + + tracks = keys + + def __repr__(self): + return "TrackData({})".format(self._map if self else "") + + +class TrackTableEntry(MutableMapping): + def __init__(self, values={}, nameIndex=None): + self.nameIndex = nameIndex + self._map = dict(values) + + def toXML(self, writer, ttFont): + name = ttFont["name"].getDebugName(self.nameIndex) + writer.begintag( + "trackEntry", + (("value", fl2str(self.track, 16)), ("nameIndex", self.nameIndex)), + ) + writer.newline() + if name: + writer.comment(name) + writer.newline() + for size, perSizeValue in sorted(self.items()): + writer.simpletag("track", size=fl2str(size, 16), value=perSizeValue) + writer.newline() + writer.endtag("trackEntry") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + self.track = str2fl(attrs["value"], 16) + self.nameIndex = safeEval(attrs["nameIndex"]) + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, _ = element + if name != "track": + continue + size = str2fl(attrs["size"], 16) + self[size] = safeEval(attrs["value"]) + + def __getitem__(self, size): + return self._map[size] + + def __delitem__(self, size): + del self._map[size] + + def __setitem__(self, size, value): + self._map[size] = value + + def __len__(self): + return len(self._map) + + def __iter__(self): + return iter(self._map) + + def keys(self): + return self._map.keys() + + sizes = keys + + def __repr__(self): + return "TrackTableEntry({}, nameIndex={})".format(self._map, self.nameIndex) + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return NotImplemented + return self.nameIndex == other.nameIndex and dict(self) == dict(other) + + def __ne__(self, other): + result = self.__eq__(other) + return result if result is NotImplemented else not result diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_v_h_e_a.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_v_h_e_a.py new file mode 100644 index 0000000000000000000000000000000000000000..97b3b726d697c53fb4e6b8134b87a33cf6d58418 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_v_h_e_a.py @@ -0,0 +1,138 @@ +from fontTools.misc import sstruct +from fontTools.misc.textTools import safeEval +from fontTools.misc.fixedTools import ( + ensureVersionIsLong as fi2ve, + versionToFixed as ve2fi, +) +from . import DefaultTable +import math + +vheaFormat = """ + > # big endian + tableVersion: L + ascent: h + descent: h + lineGap: h + advanceHeightMax: H + minTopSideBearing: h + minBottomSideBearing: h + yMaxExtent: h + caretSlopeRise: h + caretSlopeRun: h + caretOffset: h + reserved1: h + reserved2: h + reserved3: h + reserved4: h + metricDataFormat: h + numberOfVMetrics: H +""" + + +class table__v_h_e_a(DefaultTable.DefaultTable): + """Vertical Header table + + The ``vhea`` table contains information needed during vertical + text layout. + + .. note:: + This converter class is kept in sync with the :class:`._h_h_e_a.table__h_h_e_a` + table constructor. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/vhea + """ + + # Note: Keep in sync with table__h_h_e_a + + dependencies = ["vmtx", "glyf", "CFF ", "CFF2"] + + def decompile(self, data, ttFont): + sstruct.unpack(vheaFormat, data, self) + + def compile(self, ttFont): + if ttFont.recalcBBoxes and ( + ttFont.isLoaded("glyf") + or ttFont.isLoaded("CFF ") + or ttFont.isLoaded("CFF2") + ): + self.recalc(ttFont) + self.tableVersion = fi2ve(self.tableVersion) + return sstruct.pack(vheaFormat, self) + + def recalc(self, ttFont): + if "vmtx" not in ttFont: + return + + vmtxTable = ttFont["vmtx"] + self.advanceHeightMax = max(adv for adv, _ in vmtxTable.metrics.values()) + + boundsHeightDict = {} + if "glyf" in ttFont: + glyfTable = ttFont["glyf"] + for name in ttFont.getGlyphOrder(): + g = glyfTable[name] + if g.numberOfContours == 0: + continue + if g.numberOfContours < 0 and not hasattr(g, "yMax"): + # Composite glyph without extents set. + # Calculate those. + g.recalcBounds(glyfTable) + boundsHeightDict[name] = g.yMax - g.yMin + elif "CFF " in ttFont or "CFF2" in ttFont: + if "CFF " in ttFont: + topDict = ttFont["CFF "].cff.topDictIndex[0] + else: + topDict = ttFont["CFF2"].cff.topDictIndex[0] + charStrings = topDict.CharStrings + for name in ttFont.getGlyphOrder(): + cs = charStrings[name] + bounds = cs.calcBounds(charStrings) + if bounds is not None: + boundsHeightDict[name] = int( + math.ceil(bounds[3]) - math.floor(bounds[1]) + ) + + if boundsHeightDict: + minTopSideBearing = float("inf") + minBottomSideBearing = float("inf") + yMaxExtent = -float("inf") + for name, boundsHeight in boundsHeightDict.items(): + advanceHeight, tsb = vmtxTable[name] + bsb = advanceHeight - tsb - boundsHeight + extent = tsb + boundsHeight + minTopSideBearing = min(minTopSideBearing, tsb) + minBottomSideBearing = min(minBottomSideBearing, bsb) + yMaxExtent = max(yMaxExtent, extent) + self.minTopSideBearing = minTopSideBearing + self.minBottomSideBearing = minBottomSideBearing + self.yMaxExtent = yMaxExtent + + else: # No glyph has outlines. + self.minTopSideBearing = 0 + self.minBottomSideBearing = 0 + self.yMaxExtent = 0 + + def toXML(self, writer, ttFont): + formatstring, names, fixes = sstruct.getformat(vheaFormat) + for name in names: + value = getattr(self, name) + if name == "tableVersion": + value = fi2ve(value) + value = "0x%08x" % value + writer.simpletag(name, value=value) + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "tableVersion": + setattr(self, name, ve2fi(attrs["value"])) + return + setattr(self, name, safeEval(attrs["value"])) + + # reserved0 is caretOffset for legacy reasons + @property + def reserved0(self): + return self.caretOffset + + @reserved0.setter + def reserved0(self, value): + self.caretOffset = value diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_v_m_t_x.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_v_m_t_x.py new file mode 100644 index 0000000000000000000000000000000000000000..32662fc6a257e9bb3da60b259756d8f9f7fa7919 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/_v_m_t_x.py @@ -0,0 +1,19 @@ +from fontTools import ttLib + +superclass = ttLib.getTableClass("hmtx") + + +class table__v_m_t_x(superclass): + """Vertical Metrics table + + The ``vmtx`` table contains per-glyph metrics for the glyphs in a + ``glyf``, ``CFF ``, or ``CFF2`` table, as needed for vertical text + layout. + + See also https://learn.microsoft.com/en-us/typography/opentype/spec/vmtx + """ + + headerTag = "vhea" + advanceName = "height" + sideBearingName = "tsb" + numberOfMetricsName = "numberOfVMetrics" diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/asciiTable.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/asciiTable.py new file mode 100644 index 0000000000000000000000000000000000000000..6f81c526b372b268b253da47c337715e316ee4d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/asciiTable.py @@ -0,0 +1,20 @@ +from fontTools.misc.textTools import strjoin, tobytes, tostr +from . import DefaultTable + + +class asciiTable(DefaultTable.DefaultTable): + def toXML(self, writer, ttFont): + data = tostr(self.data) + # removing null bytes. XXX needed?? + data = data.split("\0") + data = strjoin(data) + writer.begintag("source") + writer.newline() + writer.write_noindent(data) + writer.newline() + writer.endtag("source") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + lines = strjoin(content).split("\n") + self.data = tobytes("\n".join(lines[1:-1])) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/grUtils.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/grUtils.py new file mode 100644 index 0000000000000000000000000000000000000000..785684b1eb30a76ae598bfe46416d4556fc422a0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/grUtils.py @@ -0,0 +1,92 @@ +import struct, warnings + +try: + import lz4 +except ImportError: + lz4 = None +else: + import lz4.block + +# old scheme for VERSION < 0.9 otherwise use lz4.block + + +def decompress(data): + (compression,) = struct.unpack(">L", data[4:8]) + scheme = compression >> 27 + size = compression & 0x07FFFFFF + if scheme == 0: + pass + elif scheme == 1 and lz4: + res = lz4.block.decompress(struct.pack("<L", size) + data[8:]) + if len(res) != size: + warnings.warn("Table decompression failed.") + else: + data = res + else: + warnings.warn("Table is compressed with an unsupported compression scheme") + return (data, scheme) + + +def compress(scheme, data): + hdr = data[:4] + struct.pack(">L", (scheme << 27) + (len(data) & 0x07FFFFFF)) + if scheme == 0: + return data + elif scheme == 1 and lz4: + res = lz4.block.compress( + data, mode="high_compression", compression=16, store_size=False + ) + return hdr + res + else: + warnings.warn("Table failed to compress by unsupported compression scheme") + return data + + +def _entries(attrs, sameval): + ak = 0 + vals = [] + lastv = 0 + for k, v in attrs: + if len(vals) and (k != ak + 1 or (sameval and v != lastv)): + yield (ak - len(vals) + 1, len(vals), vals) + vals = [] + ak = k + vals.append(v) + lastv = v + yield (ak - len(vals) + 1, len(vals), vals) + + +def entries(attributes, sameval=False): + g = _entries(sorted(attributes.items(), key=lambda x: int(x[0])), sameval) + return g + + +def bininfo(num, size=1): + if num == 0: + return struct.pack(">4H", 0, 0, 0, 0) + srange = 1 + select = 0 + while srange <= num: + srange *= 2 + select += 1 + select -= 1 + srange //= 2 + srange *= size + shift = num * size - srange + return struct.pack(">4H", num, srange, select, shift) + + +def num2tag(n): + if n < 0x200000: + return str(n) + else: + return ( + struct.unpack("4s", struct.pack(">L", n))[0].replace(b"\000", b"").decode() + ) + + +def tag2num(n): + try: + return int(n) + except ValueError: + n = (n + " ")[:4] + return struct.unpack(">L", n.encode("ascii"))[0] diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otBase.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otBase.py new file mode 100644 index 0000000000000000000000000000000000000000..1b252db193fecd339383d4838c366e55cd2ee948 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otBase.py @@ -0,0 +1,1467 @@ +from fontTools.config import OPTIONS +from fontTools.misc.textTools import Tag, bytesjoin +from .DefaultTable import DefaultTable +from enum import IntEnum +import sys +import array +import struct +import logging +from functools import lru_cache +from typing import Iterator, NamedTuple, Optional, Tuple + +log = logging.getLogger(__name__) + +have_uharfbuzz = False +try: + import uharfbuzz as hb + + have_uharfbuzz = True +except ImportError: + pass + +USE_HARFBUZZ_REPACKER = OPTIONS[f"{__name__}:USE_HARFBUZZ_REPACKER"] + + +class OverflowErrorRecord(object): + def __init__(self, overflowTuple): + self.tableType = overflowTuple[0] + self.LookupListIndex = overflowTuple[1] + self.SubTableIndex = overflowTuple[2] + self.itemName = overflowTuple[3] + self.itemIndex = overflowTuple[4] + + def __repr__(self): + return str( + ( + self.tableType, + "LookupIndex:", + self.LookupListIndex, + "SubTableIndex:", + self.SubTableIndex, + "ItemName:", + self.itemName, + "ItemIndex:", + self.itemIndex, + ) + ) + + +class OTLOffsetOverflowError(Exception): + def __init__(self, overflowErrorRecord): + self.value = overflowErrorRecord + + def __str__(self): + return repr(self.value) + + +class RepackerState(IntEnum): + # Repacking control flow is implemnted using a state machine. The state machine table: + # + # State | Packing Success | Packing Failed | Exception Raised | + # ------------+-----------------+----------------+------------------+ + # PURE_FT | Return result | PURE_FT | Return failure | + # HB_FT | Return result | HB_FT | FT_FALLBACK | + # FT_FALLBACK | HB_FT | FT_FALLBACK | Return failure | + + # Pack only with fontTools, don't allow sharing between extensions. + PURE_FT = 1 + + # Attempt to pack with harfbuzz (allowing sharing between extensions) + # use fontTools to attempt overflow resolution. + HB_FT = 2 + + # Fallback if HB/FT packing gets stuck. Pack only with fontTools, don't allow sharing between + # extensions. + FT_FALLBACK = 3 + + +class BaseTTXConverter(DefaultTable): + """Generic base class for TTX table converters. It functions as an + adapter between the TTX (ttLib actually) table model and the model + we use for OpenType tables, which is necessarily subtly different. + """ + + def decompile(self, data, font): + """Create an object from the binary data. Called automatically on access.""" + from . import otTables + + reader = OTTableReader(data, tableTag=self.tableTag) + tableClass = getattr(otTables, self.tableTag) + self.table = tableClass() + self.table.decompile(reader, font) + + def compile(self, font): + """Compiles the table into binary. Called automatically on save.""" + + # General outline: + # Create a top-level OTTableWriter for the GPOS/GSUB table. + # Call the compile method for the the table + # for each 'converter' record in the table converter list + # call converter's write method for each item in the value. + # - For simple items, the write method adds a string to the + # writer's self.items list. + # - For Struct/Table/Subtable items, it add first adds new writer to the + # to the writer's self.items, then calls the item's compile method. + # This creates a tree of writers, rooted at the GUSB/GPOS writer, with + # each writer representing a table, and the writer.items list containing + # the child data strings and writers. + # call the getAllData method + # call _doneWriting, which removes duplicates + # call _gatherTables. This traverses the tables, adding unique occurences to a flat list of tables + # Traverse the flat list of tables, calling getDataLength on each to update their position + # Traverse the flat list of tables again, calling getData each get the data in the table, now that + # pos's and offset are known. + + # If a lookup subtable overflows an offset, we have to start all over. + overflowRecord = None + # this is 3-state option: default (None) means automatically use hb.repack or + # silently fall back if it fails; True, use it and raise error if not possible + # or it errors out; False, don't use it, even if you can. + use_hb_repack = font.cfg[USE_HARFBUZZ_REPACKER] + if self.tableTag in ("GSUB", "GPOS"): + if use_hb_repack is False: + log.debug( + "hb.repack disabled, compiling '%s' with pure-python serializer", + self.tableTag, + ) + elif not have_uharfbuzz: + if use_hb_repack is True: + raise ImportError("No module named 'uharfbuzz'") + else: + assert use_hb_repack is None + log.debug( + "uharfbuzz not found, compiling '%s' with pure-python serializer", + self.tableTag, + ) + + if ( + use_hb_repack in (None, True) + and have_uharfbuzz + and self.tableTag in ("GSUB", "GPOS") + ): + state = RepackerState.HB_FT + else: + state = RepackerState.PURE_FT + + hb_first_error_logged = False + lastOverflowRecord = None + while True: + try: + writer = OTTableWriter(tableTag=self.tableTag) + self.table.compile(writer, font) + if state == RepackerState.HB_FT: + return self.tryPackingHarfbuzz(writer, hb_first_error_logged) + elif state == RepackerState.PURE_FT: + return self.tryPackingFontTools(writer) + elif state == RepackerState.FT_FALLBACK: + # Run packing with FontTools only, but don't return the result as it will + # not be optimally packed. Once a successful packing has been found, state is + # changed back to harfbuzz packing to produce the final, optimal, packing. + self.tryPackingFontTools(writer) + log.debug( + "Re-enabling sharing between extensions and switching back to " + "harfbuzz+fontTools packing." + ) + state = RepackerState.HB_FT + + except OTLOffsetOverflowError as e: + hb_first_error_logged = True + ok = self.tryResolveOverflow(font, e, lastOverflowRecord) + lastOverflowRecord = e.value + + if ok: + continue + + if state is RepackerState.HB_FT: + log.debug( + "Harfbuzz packing out of resolutions, disabling sharing between extensions and " + "switching to fontTools only packing." + ) + state = RepackerState.FT_FALLBACK + else: + raise + + def tryPackingHarfbuzz(self, writer, hb_first_error_logged): + try: + log.debug("serializing '%s' with hb.repack", self.tableTag) + return writer.getAllDataUsingHarfbuzz(self.tableTag) + except (ValueError, MemoryError, hb.RepackerError) as e: + # Only log hb repacker errors the first time they occur in + # the offset-overflow resolution loop, they are just noisy. + # Maybe we can revisit this if/when uharfbuzz actually gives + # us more info as to why hb.repack failed... + if not hb_first_error_logged: + error_msg = f"{type(e).__name__}" + if str(e) != "": + error_msg += f": {e}" + log.warning( + "hb.repack failed to serialize '%s', attempting fonttools resolutions " + "; the error message was: %s", + self.tableTag, + error_msg, + ) + hb_first_error_logged = True + return writer.getAllData(remove_duplicate=False) + + def tryPackingFontTools(self, writer): + return writer.getAllData() + + def tryResolveOverflow(self, font, e, lastOverflowRecord): + ok = 0 + if lastOverflowRecord == e.value: + # Oh well... + return ok + + overflowRecord = e.value + log.info("Attempting to fix OTLOffsetOverflowError %s", e) + + if overflowRecord.itemName is None: + from .otTables import fixLookupOverFlows + + ok = fixLookupOverFlows(font, overflowRecord) + else: + from .otTables import fixSubTableOverFlows + + ok = fixSubTableOverFlows(font, overflowRecord) + + if ok: + return ok + + # Try upgrading lookup to Extension and hope + # that cross-lookup sharing not happening would + # fix overflow... + from .otTables import fixLookupOverFlows + + return fixLookupOverFlows(font, overflowRecord) + + def toXML(self, writer, font): + self.table.toXML2(writer, font) + + def fromXML(self, name, attrs, content, font): + from . import otTables + + if not hasattr(self, "table"): + tableClass = getattr(otTables, self.tableTag) + self.table = tableClass() + self.table.fromXML(name, attrs, content, font) + self.table.populateDefaults() + + def ensureDecompiled(self, recurse=True): + self.table.ensureDecompiled(recurse=recurse) + + +# https://github.com/fonttools/fonttools/pull/2285#issuecomment-834652928 +assert len(struct.pack("i", 0)) == 4 +assert array.array("i").itemsize == 4, "Oops, file a bug against fonttools." + + +class OTTableReader(object): + """Helper class to retrieve data from an OpenType table.""" + + __slots__ = ("data", "offset", "pos", "localState", "tableTag") + + def __init__(self, data, localState=None, offset=0, tableTag=None): + self.data = data + self.offset = offset + self.pos = offset + self.localState = localState + self.tableTag = tableTag + + def advance(self, count): + self.pos += count + + def seek(self, pos): + self.pos = pos + + def copy(self): + other = self.__class__(self.data, self.localState, self.offset, self.tableTag) + other.pos = self.pos + return other + + def getSubReader(self, offset): + offset = self.offset + offset + return self.__class__(self.data, self.localState, offset, self.tableTag) + + def readValue(self, typecode, staticSize): + pos = self.pos + newpos = pos + staticSize + (value,) = struct.unpack(f">{typecode}", self.data[pos:newpos]) + self.pos = newpos + return value + + def readArray(self, typecode, staticSize, count): + pos = self.pos + newpos = pos + count * staticSize + value = array.array(typecode, self.data[pos:newpos]) + if sys.byteorder != "big": + value.byteswap() + self.pos = newpos + return value.tolist() + + def readInt8(self): + return self.readValue("b", staticSize=1) + + def readInt8Array(self, count): + return self.readArray("b", staticSize=1, count=count) + + def readShort(self): + return self.readValue("h", staticSize=2) + + def readShortArray(self, count): + return self.readArray("h", staticSize=2, count=count) + + def readLong(self): + return self.readValue("i", staticSize=4) + + def readLongArray(self, count): + return self.readArray("i", staticSize=4, count=count) + + def readUInt8(self): + return self.readValue("B", staticSize=1) + + def readUInt8Array(self, count): + return self.readArray("B", staticSize=1, count=count) + + def readUShort(self): + return self.readValue("H", staticSize=2) + + def readUShortArray(self, count): + return self.readArray("H", staticSize=2, count=count) + + def readULong(self): + return self.readValue("I", staticSize=4) + + def readULongArray(self, count): + return self.readArray("I", staticSize=4, count=count) + + def readUInt24(self): + pos = self.pos + newpos = pos + 3 + (value,) = struct.unpack(">l", b"\0" + self.data[pos:newpos]) + self.pos = newpos + return value + + def readInt24(self): + pos = self.pos + newpos = pos + 3 + b = self.data[pos:newpos] + pad = b"\xff" if b[0] & 0x80 else b"\0" + (value,) = struct.unpack(">l", pad + b) + self.pos = newpos + return value + + def readUInt24Array(self, count): + return [self.readUInt24() for _ in range(count)] + + def readTag(self): + pos = self.pos + newpos = pos + 4 + value = Tag(self.data[pos:newpos]) + assert len(value) == 4, value + self.pos = newpos + return value + + def readData(self, count): + pos = self.pos + newpos = pos + count + value = self.data[pos:newpos] + self.pos = newpos + return value + + def __setitem__(self, name, value): + state = self.localState.copy() if self.localState else dict() + state[name] = value + self.localState = state + + def __getitem__(self, name): + return self.localState and self.localState[name] + + def __contains__(self, name): + return self.localState and name in self.localState + + +class OffsetToWriter(object): + def __init__(self, subWriter, offsetSize): + self.subWriter = subWriter + self.offsetSize = offsetSize + + def __eq__(self, other): + if type(self) != type(other): + return NotImplemented + return self.subWriter == other.subWriter and self.offsetSize == other.offsetSize + + def __hash__(self): + # only works after self._doneWriting() has been called + return hash((self.subWriter, self.offsetSize)) + + +class OTTableWriter(object): + """Helper class to gather and assemble data for OpenType tables.""" + + def __init__(self, localState=None, tableTag=None): + self.items = [] + self.pos = None + self.localState = localState + self.tableTag = tableTag + self.parent = None + self.name = "<none>" + + def __setitem__(self, name, value): + state = self.localState.copy() if self.localState else dict() + state[name] = value + self.localState = state + + def __getitem__(self, name): + return self.localState[name] + + def __delitem__(self, name): + del self.localState[name] + + # assembler interface + + def getDataLength(self): + """Return the length of this table in bytes, without subtables.""" + l = 0 + for item in self.items: + if hasattr(item, "getCountData"): + l += item.size + elif hasattr(item, "subWriter"): + l += item.offsetSize + else: + l = l + len(item) + return l + + def getData(self): + """Assemble the data for this writer/table, without subtables.""" + items = list(self.items) # make a shallow copy + pos = self.pos + numItems = len(items) + for i in range(numItems): + item = items[i] + + if hasattr(item, "subWriter"): + if item.offsetSize == 4: + items[i] = packULong(item.subWriter.pos - pos) + elif item.offsetSize == 2: + try: + items[i] = packUShort(item.subWriter.pos - pos) + except struct.error: + # provide data to fix overflow problem. + overflowErrorRecord = self.getOverflowErrorRecord( + item.subWriter + ) + + raise OTLOffsetOverflowError(overflowErrorRecord) + elif item.offsetSize == 3: + items[i] = packUInt24(item.subWriter.pos - pos) + else: + raise ValueError(item.offsetSize) + + return bytesjoin(items) + + def getDataForHarfbuzz(self): + """Assemble the data for this writer/table with all offset field set to 0""" + items = list(self.items) + packFuncs = {2: packUShort, 3: packUInt24, 4: packULong} + for i, item in enumerate(items): + if hasattr(item, "subWriter"): + # Offset value is not needed in harfbuzz repacker, so setting offset to 0 to avoid overflow here + if item.offsetSize in packFuncs: + items[i] = packFuncs[item.offsetSize](0) + else: + raise ValueError(item.offsetSize) + + return bytesjoin(items) + + def __hash__(self): + # only works after self._doneWriting() has been called + return hash(self.items) + + def __ne__(self, other): + result = self.__eq__(other) + return result if result is NotImplemented else not result + + def __eq__(self, other): + if type(self) != type(other): + return NotImplemented + return self.items == other.items + + def _doneWriting(self, internedTables, shareExtension=False): + # Convert CountData references to data string items + # collapse duplicate table references to a unique entry + # "tables" are OTTableWriter objects. + + # For Extension Lookup types, we can + # eliminate duplicates only within the tree under the Extension Lookup, + # as offsets may exceed 64K even between Extension LookupTable subtables. + isExtension = hasattr(self, "Extension") + + # Certain versions of Uniscribe reject the font if the GSUB/GPOS top-level + # arrays (ScriptList, FeatureList, LookupList) point to the same, possibly + # empty, array. So, we don't share those. + # See: https://github.com/fonttools/fonttools/issues/518 + dontShare = hasattr(self, "DontShare") + + if isExtension and not shareExtension: + internedTables = {} + + items = self.items + for i, item in enumerate(items): + if hasattr(item, "getCountData"): + items[i] = item.getCountData() + elif hasattr(item, "subWriter"): + item.subWriter._doneWriting( + internedTables, shareExtension=shareExtension + ) + # At this point, all subwriters are hashable based on their items. + # (See hash and comparison magic methods above.) So the ``setdefault`` + # call here will return the first writer object we've seen with + # equal content, or store it in the dictionary if it's not been + # seen yet. We therefore replace the subwriter object with an equivalent + # object, which deduplicates the tree. + if not dontShare: + items[i].subWriter = internedTables.setdefault( + item.subWriter, item.subWriter + ) + self.items = tuple(items) + + def _gatherTables(self, tables, extTables, done): + # Convert table references in self.items tree to a flat + # list of tables in depth-first traversal order. + # "tables" are OTTableWriter objects. + # We do the traversal in reverse order at each level, in order to + # resolve duplicate references to be the last reference in the list of tables. + # For extension lookups, duplicate references can be merged only within the + # writer tree under the extension lookup. + + done[id(self)] = True + + numItems = len(self.items) + iRange = list(range(numItems)) + iRange.reverse() + + isExtension = hasattr(self, "Extension") + + selfTables = tables + + if isExtension: + assert ( + extTables is not None + ), "Program or XML editing error. Extension subtables cannot contain extensions subtables" + tables, extTables, done = extTables, None, {} + + # add Coverage table if it is sorted last. + sortCoverageLast = False + if hasattr(self, "sortCoverageLast"): + # Find coverage table + for i in range(numItems): + item = self.items[i] + if ( + hasattr(item, "subWriter") + and getattr(item.subWriter, "name", None) == "Coverage" + ): + sortCoverageLast = True + break + if id(item.subWriter) not in done: + item.subWriter._gatherTables(tables, extTables, done) + else: + # We're a new parent of item + pass + + for i in iRange: + item = self.items[i] + if not hasattr(item, "subWriter"): + continue + + if ( + sortCoverageLast + and (i == 1) + and getattr(item.subWriter, "name", None) == "Coverage" + ): + # we've already 'gathered' it above + continue + + if id(item.subWriter) not in done: + item.subWriter._gatherTables(tables, extTables, done) + else: + # Item is already written out by other parent + pass + + selfTables.append(self) + + def _gatherGraphForHarfbuzz(self, tables, obj_list, done, objidx, virtual_edges): + real_links = [] + virtual_links = [] + item_idx = objidx + + # Merge virtual_links from parent + for idx in virtual_edges: + virtual_links.append((0, 0, idx)) + + sortCoverageLast = False + coverage_idx = 0 + if hasattr(self, "sortCoverageLast"): + # Find coverage table + for i, item in enumerate(self.items): + if getattr(item, "name", None) == "Coverage": + sortCoverageLast = True + if id(item) not in done: + coverage_idx = item_idx = item._gatherGraphForHarfbuzz( + tables, obj_list, done, item_idx, virtual_edges + ) + else: + coverage_idx = done[id(item)] + virtual_edges.append(coverage_idx) + break + + child_idx = 0 + offset_pos = 0 + for i, item in enumerate(self.items): + if hasattr(item, "subWriter"): + pos = offset_pos + elif hasattr(item, "getCountData"): + offset_pos += item.size + continue + else: + offset_pos = offset_pos + len(item) + continue + + if id(item.subWriter) not in done: + child_idx = item_idx = item.subWriter._gatherGraphForHarfbuzz( + tables, obj_list, done, item_idx, virtual_edges + ) + else: + child_idx = done[id(item.subWriter)] + + real_edge = (pos, item.offsetSize, child_idx) + real_links.append(real_edge) + offset_pos += item.offsetSize + + tables.append(self) + obj_list.append((real_links, virtual_links)) + item_idx += 1 + done[id(self)] = item_idx + if sortCoverageLast: + virtual_edges.pop() + + return item_idx + + def getAllDataUsingHarfbuzz(self, tableTag): + """The Whole table is represented as a Graph. + Assemble graph data and call Harfbuzz repacker to pack the table. + Harfbuzz repacker is faster and retain as much sub-table sharing as possible, see also: + https://github.com/harfbuzz/harfbuzz/blob/main/docs/repacker.md + The input format for hb.repack() method is explained here: + https://github.com/harfbuzz/uharfbuzz/blob/main/src/uharfbuzz/_harfbuzz.pyx#L1149 + """ + internedTables = {} + self._doneWriting(internedTables, shareExtension=True) + tables = [] + obj_list = [] + done = {} + objidx = 0 + virtual_edges = [] + self._gatherGraphForHarfbuzz(tables, obj_list, done, objidx, virtual_edges) + # Gather all data in two passes: the absolute positions of all + # subtable are needed before the actual data can be assembled. + pos = 0 + for table in tables: + table.pos = pos + pos = pos + table.getDataLength() + + data = [] + for table in tables: + tableData = table.getDataForHarfbuzz() + data.append(tableData) + + return hb.serialize_with_tag(str(tableTag), data, obj_list) + + def getAllData(self, remove_duplicate=True): + """Assemble all data, including all subtables.""" + if remove_duplicate: + internedTables = {} + self._doneWriting(internedTables) + tables = [] + extTables = [] + done = {} + self._gatherTables(tables, extTables, done) + tables.reverse() + extTables.reverse() + # Gather all data in two passes: the absolute positions of all + # subtable are needed before the actual data can be assembled. + pos = 0 + for table in tables: + table.pos = pos + pos = pos + table.getDataLength() + + for table in extTables: + table.pos = pos + pos = pos + table.getDataLength() + + data = [] + for table in tables: + tableData = table.getData() + data.append(tableData) + + for table in extTables: + tableData = table.getData() + data.append(tableData) + + return bytesjoin(data) + + # interface for gathering data, as used by table.compile() + + def getSubWriter(self): + subwriter = self.__class__(self.localState, self.tableTag) + subwriter.parent = ( + self # because some subtables have idential values, we discard + ) + # the duplicates under the getAllData method. Hence some + # subtable writers can have more than one parent writer. + # But we just care about first one right now. + return subwriter + + def writeValue(self, typecode, value): + self.items.append(struct.pack(f">{typecode}", value)) + + def writeArray(self, typecode, values): + a = array.array(typecode, values) + if sys.byteorder != "big": + a.byteswap() + self.items.append(a.tobytes()) + + def writeInt8(self, value): + assert -128 <= value < 128, value + self.items.append(struct.pack(">b", value)) + + def writeInt8Array(self, values): + self.writeArray("b", values) + + def writeShort(self, value): + assert -32768 <= value < 32768, value + self.items.append(struct.pack(">h", value)) + + def writeShortArray(self, values): + self.writeArray("h", values) + + def writeLong(self, value): + self.items.append(struct.pack(">i", value)) + + def writeLongArray(self, values): + self.writeArray("i", values) + + def writeUInt8(self, value): + assert 0 <= value < 256, value + self.items.append(struct.pack(">B", value)) + + def writeUInt8Array(self, values): + self.writeArray("B", values) + + def writeUShort(self, value): + assert 0 <= value < 0x10000, value + self.items.append(struct.pack(">H", value)) + + def writeUShortArray(self, values): + self.writeArray("H", values) + + def writeULong(self, value): + self.items.append(struct.pack(">I", value)) + + def writeULongArray(self, values): + self.writeArray("I", values) + + def writeUInt24(self, value): + assert 0 <= value < 0x1000000, value + b = struct.pack(">L", value) + self.items.append(b[1:]) + + def writeUInt24Array(self, values): + for value in values: + self.writeUInt24(value) + + def writeTag(self, tag): + tag = Tag(tag).tobytes() + assert len(tag) == 4, tag + self.items.append(tag) + + def writeSubTable(self, subWriter, offsetSize): + self.items.append(OffsetToWriter(subWriter, offsetSize)) + + def writeCountReference(self, table, name, size=2, value=None): + ref = CountReference(table, name, size=size, value=value) + self.items.append(ref) + return ref + + def writeStruct(self, format, values): + data = struct.pack(*(format,) + values) + self.items.append(data) + + def writeData(self, data): + self.items.append(data) + + def getOverflowErrorRecord(self, item): + LookupListIndex = SubTableIndex = itemName = itemIndex = None + if self.name == "LookupList": + LookupListIndex = item.repeatIndex + elif self.name == "Lookup": + LookupListIndex = self.repeatIndex + SubTableIndex = item.repeatIndex + else: + itemName = getattr(item, "name", "<none>") + if hasattr(item, "repeatIndex"): + itemIndex = item.repeatIndex + if self.name == "SubTable": + LookupListIndex = self.parent.repeatIndex + SubTableIndex = self.repeatIndex + elif self.name == "ExtSubTable": + LookupListIndex = self.parent.parent.repeatIndex + SubTableIndex = self.parent.repeatIndex + else: # who knows how far below the SubTable level we are! Climb back up to the nearest subtable. + itemName = ".".join([self.name, itemName]) + p1 = self.parent + while p1 and p1.name not in ["ExtSubTable", "SubTable"]: + itemName = ".".join([p1.name, itemName]) + p1 = p1.parent + if p1: + if p1.name == "ExtSubTable": + LookupListIndex = p1.parent.parent.repeatIndex + SubTableIndex = p1.parent.repeatIndex + else: + LookupListIndex = p1.parent.repeatIndex + SubTableIndex = p1.repeatIndex + + return OverflowErrorRecord( + (self.tableTag, LookupListIndex, SubTableIndex, itemName, itemIndex) + ) + + +class CountReference(object): + """A reference to a Count value, not a count of references.""" + + def __init__(self, table, name, size=None, value=None): + self.table = table + self.name = name + self.size = size + if value is not None: + self.setValue(value) + + def setValue(self, value): + table = self.table + name = self.name + if table[name] is None: + table[name] = value + else: + assert table[name] == value, (name, table[name], value) + + def getValue(self): + return self.table[self.name] + + def getCountData(self): + v = self.table[self.name] + if v is None: + v = 0 + return {1: packUInt8, 2: packUShort, 4: packULong}[self.size](v) + + +def packUInt8(value): + return struct.pack(">B", value) + + +def packUShort(value): + return struct.pack(">H", value) + + +def packULong(value): + assert 0 <= value < 0x100000000, value + return struct.pack(">I", value) + + +def packUInt24(value): + assert 0 <= value < 0x1000000, value + return struct.pack(">I", value)[1:] + + +class BaseTable(object): + """Generic base class for all OpenType (sub)tables.""" + + def __getattr__(self, attr): + reader = self.__dict__.get("reader") + if reader: + del self.reader + font = self.font + del self.font + self.decompile(reader, font) + return getattr(self, attr) + + raise AttributeError(attr) + + def ensureDecompiled(self, recurse=False): + reader = self.__dict__.get("reader") + if reader: + del self.reader + font = self.font + del self.font + self.decompile(reader, font) + if recurse: + for subtable in self.iterSubTables(): + subtable.value.ensureDecompiled(recurse) + + def __getstate__(self): + # before copying/pickling 'lazy' objects, make a shallow copy of OTTableReader + # https://github.com/fonttools/fonttools/issues/2965 + if "reader" in self.__dict__: + state = self.__dict__.copy() + state["reader"] = self.__dict__["reader"].copy() + return state + return self.__dict__ + + @classmethod + def getRecordSize(cls, reader): + totalSize = 0 + for conv in cls.converters: + size = conv.getRecordSize(reader) + if size is NotImplemented: + return NotImplemented + countValue = 1 + if conv.repeat: + if conv.repeat in reader: + countValue = reader[conv.repeat] + conv.aux + else: + return NotImplemented + totalSize += size * countValue + return totalSize + + def getConverters(self): + return self.converters + + def getConverterByName(self, name): + return self.convertersByName[name] + + def populateDefaults(self, propagator=None): + for conv in self.getConverters(): + if conv.repeat: + if not hasattr(self, conv.name): + setattr(self, conv.name, []) + countValue = len(getattr(self, conv.name)) - conv.aux + try: + count_conv = self.getConverterByName(conv.repeat) + setattr(self, conv.repeat, countValue) + except KeyError: + # conv.repeat is a propagated count + if propagator and conv.repeat in propagator: + propagator[conv.repeat].setValue(countValue) + else: + if conv.aux and not eval(conv.aux, None, self.__dict__): + continue + if hasattr(self, conv.name): + continue # Warn if it should NOT be present?! + if hasattr(conv, "writeNullOffset"): + setattr(self, conv.name, None) # Warn? + # elif not conv.isCount: + # # Warn? + # pass + if hasattr(conv, "DEFAULT"): + # OptionalValue converters (e.g. VarIndex) + setattr(self, conv.name, conv.DEFAULT) + + def decompile(self, reader, font): + self.readFormat(reader) + table = {} + self.__rawTable = table # for debugging + for conv in self.getConverters(): + if conv.name == "SubTable": + conv = conv.getConverter(reader.tableTag, table["LookupType"]) + if conv.name == "ExtSubTable": + conv = conv.getConverter(reader.tableTag, table["ExtensionLookupType"]) + if conv.name == "FeatureParams": + conv = conv.getConverter(reader["FeatureTag"]) + if conv.name == "SubStruct": + conv = conv.getConverter(reader.tableTag, table["MorphType"]) + try: + if conv.repeat: + if isinstance(conv.repeat, int): + countValue = conv.repeat + elif conv.repeat in table: + countValue = table[conv.repeat] + else: + # conv.repeat is a propagated count + countValue = reader[conv.repeat] + countValue += conv.aux + table[conv.name] = conv.readArray(reader, font, table, countValue) + else: + if conv.aux and not eval(conv.aux, None, table): + continue + table[conv.name] = conv.read(reader, font, table) + if conv.isPropagated: + reader[conv.name] = table[conv.name] + except Exception as e: + name = conv.name + e.args = e.args + (name,) + raise + + if hasattr(self, "postRead"): + self.postRead(table, font) + else: + self.__dict__.update(table) + + del self.__rawTable # succeeded, get rid of debugging info + + def compile(self, writer, font): + self.ensureDecompiled() + # TODO Following hack to be removed by rewriting how FormatSwitching tables + # are handled. + # https://github.com/fonttools/fonttools/pull/2238#issuecomment-805192631 + if hasattr(self, "preWrite"): + deleteFormat = not hasattr(self, "Format") + table = self.preWrite(font) + deleteFormat = deleteFormat and hasattr(self, "Format") + else: + deleteFormat = False + table = self.__dict__.copy() + + # some count references may have been initialized in a custom preWrite; we set + # these in the writer's state beforehand (instead of sequentially) so they will + # be propagated to all nested subtables even if the count appears in the current + # table only *after* the offset to the subtable that it is counting. + for conv in self.getConverters(): + if conv.isCount and conv.isPropagated: + value = table.get(conv.name) + if isinstance(value, CountReference): + writer[conv.name] = value + + if hasattr(self, "sortCoverageLast"): + writer.sortCoverageLast = 1 + + if hasattr(self, "DontShare"): + writer.DontShare = True + + if hasattr(self.__class__, "LookupType"): + writer["LookupType"].setValue(self.__class__.LookupType) + + self.writeFormat(writer) + for conv in self.getConverters(): + value = table.get( + conv.name + ) # TODO Handle defaults instead of defaulting to None! + if conv.repeat: + if value is None: + value = [] + countValue = len(value) - conv.aux + if isinstance(conv.repeat, int): + assert len(value) == conv.repeat, "expected %d values, got %d" % ( + conv.repeat, + len(value), + ) + elif conv.repeat in table: + CountReference(table, conv.repeat, value=countValue) + else: + # conv.repeat is a propagated count + writer[conv.repeat].setValue(countValue) + try: + conv.writeArray(writer, font, table, value) + except Exception as e: + e.args = e.args + (conv.name + "[]",) + raise + elif conv.isCount: + # Special-case Count values. + # Assumption: a Count field will *always* precede + # the actual array(s). + # We need a default value, as it may be set later by a nested + # table. We will later store it here. + # We add a reference: by the time the data is assembled + # the Count value will be filled in. + # We ignore the current count value since it will be recomputed, + # unless it's a CountReference that was already initialized in a custom preWrite. + if isinstance(value, CountReference): + ref = value + ref.size = conv.staticSize + writer.writeData(ref) + table[conv.name] = ref.getValue() + else: + ref = writer.writeCountReference(table, conv.name, conv.staticSize) + table[conv.name] = None + if conv.isPropagated: + writer[conv.name] = ref + elif conv.isLookupType: + # We make sure that subtables have the same lookup type, + # and that the type is the same as the one set on the + # Lookup object, if any is set. + if conv.name not in table: + table[conv.name] = None + ref = writer.writeCountReference( + table, conv.name, conv.staticSize, table[conv.name] + ) + writer["LookupType"] = ref + else: + if conv.aux and not eval(conv.aux, None, table): + continue + try: + conv.write(writer, font, table, value) + except Exception as e: + name = value.__class__.__name__ if value is not None else conv.name + e.args = e.args + (name,) + raise + if conv.isPropagated: + writer[conv.name] = value + + if deleteFormat: + del self.Format + + def readFormat(self, reader): + pass + + def writeFormat(self, writer): + pass + + def toXML(self, xmlWriter, font, attrs=None, name=None): + tableName = name if name else self.__class__.__name__ + if attrs is None: + attrs = [] + if hasattr(self, "Format"): + attrs = attrs + [("Format", self.Format)] + xmlWriter.begintag(tableName, attrs) + xmlWriter.newline() + self.toXML2(xmlWriter, font) + xmlWriter.endtag(tableName) + xmlWriter.newline() + + def toXML2(self, xmlWriter, font): + # Simpler variant of toXML, *only* for the top level tables (like GPOS, GSUB). + # This is because in TTX our parent writes our main tag, and in otBase.py we + # do it ourselves. I think I'm getting schizophrenic... + for conv in self.getConverters(): + if conv.repeat: + value = getattr(self, conv.name, []) + for i, item in enumerate(value): + conv.xmlWrite(xmlWriter, font, item, conv.name, [("index", i)]) + else: + if conv.aux and not eval(conv.aux, None, vars(self)): + continue + value = getattr( + self, conv.name, None + ) # TODO Handle defaults instead of defaulting to None! + conv.xmlWrite(xmlWriter, font, value, conv.name, []) + + def fromXML(self, name, attrs, content, font): + try: + conv = self.getConverterByName(name) + except KeyError: + raise # XXX on KeyError, raise nice error + value = conv.xmlRead(attrs, content, font) + # Some manually-written tables have a conv.repeat of "" + # to represent lists. Hence comparing to None here to + # allow those lists to be read correctly from XML. + if conv.repeat is not None: + seq = getattr(self, conv.name, None) + if seq is None: + seq = [] + setattr(self, conv.name, seq) + seq.append(value) + else: + setattr(self, conv.name, value) + + def __ne__(self, other): + result = self.__eq__(other) + return result if result is NotImplemented else not result + + def __eq__(self, other): + if type(self) != type(other): + return NotImplemented + + self.ensureDecompiled() + other.ensureDecompiled() + + return self.__dict__ == other.__dict__ + + class SubTableEntry(NamedTuple): + """See BaseTable.iterSubTables()""" + + name: str + value: "BaseTable" + index: Optional[int] = None # index into given array, None for single values + + def iterSubTables(self) -> Iterator[SubTableEntry]: + """Yield (name, value, index) namedtuples for all subtables of current table. + + A sub-table is an instance of BaseTable (or subclass thereof) that is a child + of self, the current parent table. + The tuples also contain the attribute name (str) of the of parent table to get + a subtable, and optionally, for lists of subtables (i.e. attributes associated + with a converter that has a 'repeat'), an index into the list containing the + given subtable value. + This method can be useful to traverse trees of otTables. + """ + for conv in self.getConverters(): + name = conv.name + value = getattr(self, name, None) + if value is None: + continue + if isinstance(value, BaseTable): + yield self.SubTableEntry(name, value) + elif isinstance(value, list): + yield from ( + self.SubTableEntry(name, v, index=i) + for i, v in enumerate(value) + if isinstance(v, BaseTable) + ) + + # instance (not @class)method for consistency with FormatSwitchingBaseTable + def getVariableAttrs(self): + return getVariableAttrs(self.__class__) + + +class FormatSwitchingBaseTable(BaseTable): + """Minor specialization of BaseTable, for tables that have multiple + formats, eg. CoverageFormat1 vs. CoverageFormat2.""" + + @classmethod + def getRecordSize(cls, reader): + return NotImplemented + + def getConverters(self): + try: + fmt = self.Format + except AttributeError: + # some FormatSwitchingBaseTables (e.g. Coverage) no longer have 'Format' + # attribute after fully decompiled, only gain one in preWrite before being + # recompiled. In the decompiled state, these hand-coded classes defined in + # otTables.py lose their format-specific nature and gain more high-level + # attributes that are not tied to converters. + return [] + return self.converters.get(self.Format, []) + + def getConverterByName(self, name): + return self.convertersByName[self.Format][name] + + def readFormat(self, reader): + self.Format = reader.readUShort() + + def writeFormat(self, writer): + writer.writeUShort(self.Format) + + def toXML(self, xmlWriter, font, attrs=None, name=None): + BaseTable.toXML(self, xmlWriter, font, attrs, name) + + def getVariableAttrs(self): + return getVariableAttrs(self.__class__, self.Format) + + +class UInt8FormatSwitchingBaseTable(FormatSwitchingBaseTable): + def readFormat(self, reader): + self.Format = reader.readUInt8() + + def writeFormat(self, writer): + writer.writeUInt8(self.Format) + + +formatSwitchingBaseTables = { + "uint16": FormatSwitchingBaseTable, + "uint8": UInt8FormatSwitchingBaseTable, +} + + +def getFormatSwitchingBaseTableClass(formatType): + try: + return formatSwitchingBaseTables[formatType] + except KeyError: + raise TypeError(f"Unsupported format type: {formatType!r}") + + +# memoize since these are parsed from otData.py, thus stay constant +@lru_cache() +def getVariableAttrs(cls: BaseTable, fmt: Optional[int] = None) -> Tuple[str]: + """Return sequence of variable table field names (can be empty). + + Attributes are deemed "variable" when their otData.py's description contain + 'VarIndexBase + {offset}', e.g. COLRv1 PaintVar* tables. + """ + if not issubclass(cls, BaseTable): + raise TypeError(cls) + if issubclass(cls, FormatSwitchingBaseTable): + if fmt is None: + raise TypeError(f"'fmt' is required for format-switching {cls.__name__}") + converters = cls.convertersByName[fmt] + else: + converters = cls.convertersByName + # assume if no 'VarIndexBase' field is present, table has no variable fields + if "VarIndexBase" not in converters: + return () + varAttrs = {} + for name, conv in converters.items(): + offset = conv.getVarIndexOffset() + if offset is not None: + varAttrs[name] = offset + return tuple(sorted(varAttrs, key=varAttrs.__getitem__)) + + +# +# Support for ValueRecords +# +# This data type is so different from all other OpenType data types that +# it requires quite a bit of code for itself. It even has special support +# in OTTableReader and OTTableWriter... +# + +valueRecordFormat = [ + # Mask Name isDevice signed + (0x0001, "XPlacement", 0, 1), + (0x0002, "YPlacement", 0, 1), + (0x0004, "XAdvance", 0, 1), + (0x0008, "YAdvance", 0, 1), + (0x0010, "XPlaDevice", 1, 0), + (0x0020, "YPlaDevice", 1, 0), + (0x0040, "XAdvDevice", 1, 0), + (0x0080, "YAdvDevice", 1, 0), + # reserved: + (0x0100, "Reserved1", 0, 0), + (0x0200, "Reserved2", 0, 0), + (0x0400, "Reserved3", 0, 0), + (0x0800, "Reserved4", 0, 0), + (0x1000, "Reserved5", 0, 0), + (0x2000, "Reserved6", 0, 0), + (0x4000, "Reserved7", 0, 0), + (0x8000, "Reserved8", 0, 0), +] + + +def _buildDict(): + d = {} + for mask, name, isDevice, signed in valueRecordFormat: + d[name] = mask, isDevice, signed + return d + + +valueRecordFormatDict = _buildDict() + + +class ValueRecordFactory(object): + """Given a format code, this object convert ValueRecords.""" + + def __init__(self, valueFormat): + format = [] + for mask, name, isDevice, signed in valueRecordFormat: + if valueFormat & mask: + format.append((name, isDevice, signed)) + self.format = format + + def __len__(self): + return len(self.format) + + def readValueRecord(self, reader, font): + format = self.format + if not format: + return None + valueRecord = ValueRecord() + for name, isDevice, signed in format: + if signed: + value = reader.readShort() + else: + value = reader.readUShort() + if isDevice: + if value: + from . import otTables + + subReader = reader.getSubReader(value) + value = getattr(otTables, name)() + value.decompile(subReader, font) + else: + value = None + setattr(valueRecord, name, value) + return valueRecord + + def writeValueRecord(self, writer, font, valueRecord): + for name, isDevice, signed in self.format: + value = getattr(valueRecord, name, 0) + if isDevice: + if value: + subWriter = writer.getSubWriter() + writer.writeSubTable(subWriter, offsetSize=2) + value.compile(subWriter, font) + else: + writer.writeUShort(0) + elif signed: + writer.writeShort(value) + else: + writer.writeUShort(value) + + +class ValueRecord(object): + # see ValueRecordFactory + + def __init__(self, valueFormat=None, src=None): + if valueFormat is not None: + for mask, name, isDevice, signed in valueRecordFormat: + if valueFormat & mask: + setattr(self, name, None if isDevice else 0) + if src is not None: + for key, val in src.__dict__.items(): + if not hasattr(self, key): + continue + setattr(self, key, val) + elif src is not None: + self.__dict__ = src.__dict__.copy() + + def getFormat(self): + format = 0 + for name in self.__dict__.keys(): + format = format | valueRecordFormatDict[name][0] + return format + + def getEffectiveFormat(self): + format = 0 + for name, value in self.__dict__.items(): + if value: + format = format | valueRecordFormatDict[name][0] + return format + + def toXML(self, xmlWriter, font, valueName, attrs=None): + if attrs is None: + simpleItems = [] + else: + simpleItems = list(attrs) + for mask, name, isDevice, format in valueRecordFormat[:4]: # "simple" values + if hasattr(self, name): + simpleItems.append((name, getattr(self, name))) + deviceItems = [] + for mask, name, isDevice, format in valueRecordFormat[4:8]: # device records + if hasattr(self, name): + device = getattr(self, name) + if device is not None: + deviceItems.append((name, device)) + if deviceItems: + xmlWriter.begintag(valueName, simpleItems) + xmlWriter.newline() + for name, deviceRecord in deviceItems: + if deviceRecord is not None: + deviceRecord.toXML(xmlWriter, font, name=name) + xmlWriter.endtag(valueName) + xmlWriter.newline() + else: + xmlWriter.simpletag(valueName, simpleItems) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + from . import otTables + + for k, v in attrs.items(): + setattr(self, k, int(v)) + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + value = getattr(otTables, name)() + for elem2 in content: + if not isinstance(elem2, tuple): + continue + name2, attrs2, content2 = elem2 + value.fromXML(name2, attrs2, content2, font) + setattr(self, name, value) + + def __ne__(self, other): + result = self.__eq__(other) + return result if result is NotImplemented else not result + + def __eq__(self, other): + if type(self) != type(other): + return NotImplemented + return self.__dict__ == other.__dict__ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otConverters.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otConverters.py new file mode 100644 index 0000000000000000000000000000000000000000..3f686cfae313beb89c3c39f6a558269e7507d433 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otConverters.py @@ -0,0 +1,2988 @@ +from fontTools.misc.fixedTools import ( + fixedToFloat as fi2fl, + floatToFixed as fl2fi, + floatToFixedToStr as fl2str, + strToFixedToFloat as str2fl, + ensureVersionIsLong as fi2ve, + versionToFixed as ve2fi, +) +from fontTools.ttLib.tables.TupleVariation import TupleVariation +from fontTools.misc.roundTools import nearestMultipleShortestRepr, otRound +from fontTools.misc.textTools import bytesjoin, tobytes, tostr, pad, safeEval +from fontTools.misc.lazyTools import LazyList +from fontTools.ttLib import OPTIMIZE_FONT_SPEED, getSearchRange +from .otBase import ( + CountReference, + FormatSwitchingBaseTable, + OTTableReader, + OTTableWriter, + ValueRecordFactory, +) +from .otDataSchema import FieldSpec +from .otTables import ( + lookupTypes, + VarCompositeGlyph, + AATStateTable, + AATState, + AATAction, + ContextualMorphAction, + LigAction, + LigatureMorphAction, + InsertionMorphAction, + MortSubtable, + MorxSubtable, + ExtendMode as _ExtendMode, + CompositeMode as _CompositeMode, + NO_VARIATION_INDEX, +) +from itertools import zip_longest, accumulate +from functools import partial +from types import SimpleNamespace +import re +import struct +from typing import Optional +import logging +from enum import IntFlag + +log = logging.getLogger(__name__) +istuple = lambda t: isinstance(t, tuple) + + +def buildConverters(tableSpec: list[FieldSpec], tableNamespace): + """Given a table spec from otData.py, build a converter object for each + field of the table. This is called for each table in otData.py, and + the results are assigned to the corresponding class in otTables.py.""" + converters = [] + convertersByName = {} + for spec in tableSpec: + tableName = spec.name + if spec.name.startswith("ValueFormat"): + assert spec.type == "uint16" + converterClass = ValueFormat + elif spec.name.endswith("Count") or spec.name in ("StructLength", "MorphType"): + converterClass = { + "uint8": ComputedUInt8, + "uint16": ComputedUShort, + "uint32": ComputedULong, + }[spec.type] + elif spec.name == "SubTable": + converterClass = SubTable + elif spec.name == "ExtSubTable": + converterClass = ExtSubTable + elif spec.name == "SubStruct": + converterClass = SubStruct + elif spec.name == "FeatureParams": + converterClass = FeatureParams + elif spec.name in ("CIDGlyphMapping", "GlyphCIDMapping"): + converterClass = StructWithLength + else: + if not spec.type in converterMapping and "(" not in spec.type: + tableName = spec.type + converterClass = Struct + else: + converterClass = eval(spec.type, tableNamespace, converterMapping) + + conv = converterClass( + spec.name, spec.repeat, spec.aux, description=spec.description + ) + + if conv.tableClass: + # A "template" such as OffsetTo(AType) knows the table class already + tableClass = conv.tableClass + elif spec.type in ("MortChain", "MortSubtable", "MorxChain"): + tableClass = tableNamespace.get(spec.type) + else: + tableClass = tableNamespace.get(tableName) + + if not conv.tableClass: + conv.tableClass = tableClass + + if spec.name in ["SubTable", "ExtSubTable", "SubStruct"]: + conv.lookupTypes = tableNamespace["lookupTypes"] + # also create reverse mapping + for t in conv.lookupTypes.values(): + for cls in t.values(): + convertersByName[cls.__name__] = Table( + spec.name, spec.repeat, spec.aux, cls + ) + if spec.name == "FeatureParams": + conv.featureParamTypes = tableNamespace["featureParamTypes"] + conv.defaultFeatureParams = tableNamespace["FeatureParams"] + for cls in conv.featureParamTypes.values(): + convertersByName[cls.__name__] = Table( + spec.name, spec.repeat, spec.aux, cls + ) + converters.append(conv) + assert spec.name not in convertersByName, spec.name + convertersByName[spec.name] = conv + return converters, convertersByName + + +class BaseConverter(object): + """Base class for converter objects. Apart from the constructor, this + is an abstract class.""" + + def __init__(self, name, repeat, aux, tableClass=None, *, description=""): + self.name = name + self.repeat = repeat + self.aux = aux + if self.aux and not self.repeat: + self.aux = compile(self.aux, "<string>", "eval") + self.tableClass = tableClass + self.isCount = name.endswith("Count") or name in [ + "DesignAxisRecordSize", + "ValueRecordSize", + ] + self.isLookupType = name.endswith("LookupType") or name == "MorphType" + self.isPropagated = name in [ + "ClassCount", + "Class2Count", + "FeatureTag", + "SettingsCount", + "VarRegionCount", + "MappingCount", + "RegionAxisCount", + "DesignAxisCount", + "DesignAxisRecordSize", + "AxisValueCount", + "ValueRecordSize", + "AxisCount", + "BaseGlyphRecordCount", + "LayerRecordCount", + "AxisIndicesList", + # IFT - propagated to GlyphMap/FeatureMap/MappingEntries subtables + "NumGlyphs", + "MaxGlyphMapEntryIndex", + "MaxEntryIndex", + "NumEntries", + ] + self.description = description + + def readArray(self, reader, font, tableDict, count): + """Read an array of values from the reader.""" + lazy = font.lazy and count > 8 + if lazy: + recordSize = self.getRecordSize(reader) + if recordSize is NotImplemented: + lazy = False + if not lazy: + l = [] + for i in range(count): + l.append(self.read(reader, font, tableDict)) + return l + else: + + def get_read_item(): + reader_copy = reader.copy() + pos = reader.pos + + def read_item(i): + reader_copy.seek(pos + i * recordSize) + return self.read(reader_copy, font, {}) + + return read_item + + read_item = get_read_item() + l = LazyList(read_item for i in range(count)) + reader.advance(count * recordSize) + + return l + + def getRecordSize(self, reader): + if hasattr(self, "staticSize"): + return self.staticSize + return NotImplemented + + def read(self, reader, font, tableDict): + """Read a value from the reader.""" + raise NotImplementedError(self) + + def writeArray(self, writer, font, tableDict, values): + try: + for i, value in enumerate(values): + self.write(writer, font, tableDict, value, i) + except Exception as e: + e.args = e.args + (i,) + raise + + def write(self, writer, font, tableDict, value, repeatIndex=None): + """Write a value to the writer.""" + raise NotImplementedError(self) + + def xmlRead(self, attrs, content, font): + """Read a value from XML.""" + raise NotImplementedError(self) + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + """Write a value to XML.""" + raise NotImplementedError(self) + + varIndexBasePlusOffsetRE = re.compile(r"VarIndexBase\s*\+\s*(\d+)") + + def getVarIndexOffset(self) -> Optional[int]: + """If description has `VarIndexBase + {offset}`, return the offset else None.""" + m = self.varIndexBasePlusOffsetRE.search(self.description) + if not m: + return None + return int(m.group(1)) + + +class SimpleValue(BaseConverter): + @staticmethod + def toString(value): + return value + + @staticmethod + def fromString(value): + return value + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.simpletag(name, attrs + [("value", self.toString(value))]) + xmlWriter.newline() + + def xmlRead(self, attrs, content, font): + return self.fromString(attrs["value"]) + + +class OptionalValue(SimpleValue): + DEFAULT = None + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + if value != self.DEFAULT: + attrs.append(("value", self.toString(value))) + xmlWriter.simpletag(name, attrs) + xmlWriter.newline() + + def xmlRead(self, attrs, content, font): + if "value" in attrs: + return self.fromString(attrs["value"]) + return self.DEFAULT + + +class IntValue(SimpleValue): + @staticmethod + def fromString(value): + return int(value, 0) + + +class Long(IntValue): + staticSize = 4 + + def read(self, reader, font, tableDict): + return reader.readLong() + + def readArray(self, reader, font, tableDict, count): + return reader.readLongArray(count) + + def write(self, writer, font, tableDict, value, repeatIndex=None): + writer.writeLong(value) + + def writeArray(self, writer, font, tableDict, values): + writer.writeLongArray(values) + + +class ULong(IntValue): + staticSize = 4 + + def read(self, reader, font, tableDict): + return reader.readULong() + + def readArray(self, reader, font, tableDict, count): + return reader.readULongArray(count) + + def write(self, writer, font, tableDict, value, repeatIndex=None): + writer.writeULong(value) + + def writeArray(self, writer, font, tableDict, values): + writer.writeULongArray(values) + + +class Flags32(ULong): + @staticmethod + def toString(value): + return "0x%08X" % value + + +class VarIndex(OptionalValue, ULong): + DEFAULT = NO_VARIATION_INDEX + + +class Short(IntValue): + staticSize = 2 + + def read(self, reader, font, tableDict): + return reader.readShort() + + def readArray(self, reader, font, tableDict, count): + return reader.readShortArray(count) + + def write(self, writer, font, tableDict, value, repeatIndex=None): + writer.writeShort(value) + + def writeArray(self, writer, font, tableDict, values): + writer.writeShortArray(values) + + +class UShort(IntValue): + staticSize = 2 + + def read(self, reader, font, tableDict): + return reader.readUShort() + + def readArray(self, reader, font, tableDict, count): + return reader.readUShortArray(count) + + def write(self, writer, font, tableDict, value, repeatIndex=None): + writer.writeUShort(value) + + def writeArray(self, writer, font, tableDict, values): + writer.writeUShortArray(values) + + +class Int8(IntValue): + staticSize = 1 + + def read(self, reader, font, tableDict): + return reader.readInt8() + + def readArray(self, reader, font, tableDict, count): + return reader.readInt8Array(count) + + def write(self, writer, font, tableDict, value, repeatIndex=None): + writer.writeInt8(value) + + def writeArray(self, writer, font, tableDict, values): + writer.writeInt8Array(values) + + +class UInt8(IntValue): + staticSize = 1 + + def read(self, reader, font, tableDict): + return reader.readUInt8() + + def readArray(self, reader, font, tableDict, count): + return reader.readUInt8Array(count) + + def write(self, writer, font, tableDict, value, repeatIndex=None): + writer.writeUInt8(value) + + def writeArray(self, writer, font, tableDict, values): + writer.writeUInt8Array(values) + + +class UInt24(IntValue): + staticSize = 3 + + def read(self, reader, font, tableDict): + return reader.readUInt24() + + def write(self, writer, font, tableDict, value, repeatIndex=None): + writer.writeUInt24(value) + + +class ComputedInt(IntValue): + def xmlWrite(self, xmlWriter, font, value, name, attrs): + if value is not None: + xmlWriter.comment("%s=%s" % (name, value)) + xmlWriter.newline() + + +class ComputedUInt8(ComputedInt, UInt8): + pass + + +class ComputedUShort(ComputedInt, UShort): + pass + + +class ComputedULong(ComputedInt, ULong): + pass + + +class Tag(SimpleValue): + staticSize = 4 + + def read(self, reader, font, tableDict): + return reader.readTag() + + def write(self, writer, font, tableDict, value, repeatIndex=None): + writer.writeTag(value) + + +class GlyphID(SimpleValue): + staticSize = 2 + typecode = "H" + + def readArray(self, reader, font, tableDict, count): + return font.getGlyphNameMany( + reader.readArray(self.typecode, self.staticSize, count) + ) + + def read(self, reader, font, tableDict): + return font.getGlyphName(reader.readValue(self.typecode, self.staticSize)) + + def writeArray(self, writer, font, tableDict, values): + writer.writeArray(self.typecode, font.getGlyphIDMany(values)) + + def write(self, writer, font, tableDict, value, repeatIndex=None): + writer.writeValue(self.typecode, font.getGlyphID(value)) + + +class GlyphID32(GlyphID): + staticSize = 4 + typecode = "L" + + +class NameID(UShort): + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.simpletag(name, attrs + [("value", value)]) + if font and value: + nameTable = font.get("name") + if nameTable: + name = nameTable.getDebugName(value) + xmlWriter.write(" ") + if name: + xmlWriter.comment(name) + elif value == 0xFFFF: + xmlWriter.comment("None") + else: + xmlWriter.comment("missing from name table") + log.warning("name id %d missing from name table" % value) + xmlWriter.newline() + + +class STATFlags(UShort): + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.simpletag(name, attrs + [("value", value)]) + flags = [] + if value & 0x01: + flags.append("OlderSiblingFontAttribute") + if value & 0x02: + flags.append("ElidableAxisValueName") + if flags: + xmlWriter.write(" ") + xmlWriter.comment(" ".join(flags)) + xmlWriter.newline() + + +class FloatValue(SimpleValue): + @staticmethod + def fromString(value): + return float(value) + + +class DeciPoints(FloatValue): + staticSize = 2 + + def read(self, reader, font, tableDict): + return reader.readUShort() / 10 + + def write(self, writer, font, tableDict, value, repeatIndex=None): + writer.writeUShort(round(value * 10)) + + +class BaseFixedValue(FloatValue): + staticSize = NotImplemented + precisionBits = NotImplemented + readerMethod = NotImplemented + writerMethod = NotImplemented + + def read(self, reader, font, tableDict): + return self.fromInt(getattr(reader, self.readerMethod)()) + + def write(self, writer, font, tableDict, value, repeatIndex=None): + getattr(writer, self.writerMethod)(self.toInt(value)) + + @classmethod + def fromInt(cls, value): + return fi2fl(value, cls.precisionBits) + + @classmethod + def toInt(cls, value): + return fl2fi(value, cls.precisionBits) + + @classmethod + def fromString(cls, value): + return str2fl(value, cls.precisionBits) + + @classmethod + def toString(cls, value): + return fl2str(value, cls.precisionBits) + + +class Fixed(BaseFixedValue): + staticSize = 4 + precisionBits = 16 + readerMethod = "readLong" + writerMethod = "writeLong" + + +class F2Dot14(BaseFixedValue): + staticSize = 2 + precisionBits = 14 + readerMethod = "readShort" + writerMethod = "writeShort" + + +class Angle(F2Dot14): + # angles are specified in degrees, and encoded as F2Dot14 fractions of half + # circle: e.g. 1.0 => 180, -0.5 => -90, -2.0 => -360, etc. + bias = 0.0 + factor = 1.0 / (1 << 14) * 180 # 0.010986328125 + + @classmethod + def fromInt(cls, value): + return (super().fromInt(value) + cls.bias) * 180 + + @classmethod + def toInt(cls, value): + return super().toInt((value / 180) - cls.bias) + + @classmethod + def fromString(cls, value): + # quantize to nearest multiples of minimum fixed-precision angle + return otRound(float(value) / cls.factor) * cls.factor + + @classmethod + def toString(cls, value): + return nearestMultipleShortestRepr(value, cls.factor) + + +class BiasedAngle(Angle): + # A bias of 1.0 is used in the representation of start and end angles + # of COLRv1 PaintSweepGradients to allow for encoding +360deg + bias = 1.0 + + +class Version(SimpleValue): + staticSize = 4 + + def read(self, reader, font, tableDict): + value = reader.readLong() + return value + + def write(self, writer, font, tableDict, value, repeatIndex=None): + value = fi2ve(value) + writer.writeLong(value) + + @staticmethod + def fromString(value): + return ve2fi(value) + + @staticmethod + def toString(value): + return "0x%08x" % value + + @staticmethod + def fromFloat(v): + return fl2fi(v, 16) + + +class Char64(SimpleValue): + """An ASCII string with up to 64 characters. + + Unused character positions are filled with 0x00 bytes. + Used in Apple AAT fonts in the `gcid` table. + """ + + staticSize = 64 + + def read(self, reader, font, tableDict): + data = reader.readData(self.staticSize) + zeroPos = data.find(b"\0") + if zeroPos >= 0: + data = data[:zeroPos] + s = tostr(data, encoding="ascii", errors="replace") + if s != tostr(data, encoding="ascii", errors="ignore"): + log.warning('replaced non-ASCII characters in "%s"' % s) + return s + + def write(self, writer, font, tableDict, value, repeatIndex=None): + data = tobytes(value, encoding="ascii", errors="replace") + if data != tobytes(value, encoding="ascii", errors="ignore"): + log.warning('replacing non-ASCII characters in "%s"' % value) + if len(data) > self.staticSize: + log.warning( + 'truncating overlong "%s" to %d bytes' % (value, self.staticSize) + ) + data = (data + b"\0" * self.staticSize)[: self.staticSize] + writer.writeData(data) + + +class Struct(BaseConverter): + def getRecordSize(self, reader): + return self.tableClass and self.tableClass.getRecordSize(reader) + + def read(self, reader, font, tableDict): + table = self.tableClass() + table.decompile(reader, font) + return table + + def write(self, writer, font, tableDict, value, repeatIndex=None): + value.compile(writer, font) + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + if value is None: + if attrs: + # If there are attributes (probably index), then + # don't drop this even if it's NULL. It will mess + # up the array indices of the containing element. + xmlWriter.simpletag(name, attrs + [("empty", 1)]) + xmlWriter.newline() + else: + pass # NULL table, ignore + else: + value.toXML(xmlWriter, font, attrs, name=name) + + def xmlRead(self, attrs, content, font): + if "empty" in attrs and safeEval(attrs["empty"]): + return None + table = self.tableClass() + Format = attrs.get("Format") + if Format is not None: + table.Format = int(Format) + + noPostRead = not hasattr(table, "postRead") + if noPostRead: + # TODO Cache table.hasPropagated. + cleanPropagation = False + for conv in table.getConverters(): + if conv.isPropagated: + cleanPropagation = True + if not hasattr(font, "_propagator"): + font._propagator = {} + propagator = font._propagator + assert conv.name not in propagator, (conv.name, propagator) + setattr(table, conv.name, None) + propagator[conv.name] = CountReference(table.__dict__, conv.name) + + for element in content: + if isinstance(element, tuple): + name, attrs, content = element + table.fromXML(name, attrs, content, font) + else: + pass + + table.populateDefaults(propagator=getattr(font, "_propagator", None)) + + if noPostRead: + if cleanPropagation: + for conv in table.getConverters(): + if conv.isPropagated: + propagator = font._propagator + del propagator[conv.name] + if not propagator: + del font._propagator + + return table + + def __repr__(self): + return "Struct of " + repr(self.tableClass) + + +class StructWithLength(Struct): + def read(self, reader, font, tableDict): + pos = reader.pos + table = self.tableClass() + table.decompile(reader, font) + reader.seek(pos + table.StructLength) + return table + + def write(self, writer, font, tableDict, value, repeatIndex=None): + for convIndex, conv in enumerate(value.getConverters()): + if conv.name == "StructLength": + break + lengthIndex = len(writer.items) + convIndex + if isinstance(value, FormatSwitchingBaseTable): + lengthIndex += 1 # implicit Format field + deadbeef = {1: 0xDE, 2: 0xDEAD, 4: 0xDEADBEEF}[conv.staticSize] + + before = writer.getDataLength() + value.StructLength = deadbeef + value.compile(writer, font) + length = writer.getDataLength() - before + lengthWriter = writer.getSubWriter() + conv.write(lengthWriter, font, tableDict, length) + assert writer.items[lengthIndex] == b"\xde\xad\xbe\xef"[: conv.staticSize] + writer.items[lengthIndex] = lengthWriter.getAllData() + + +class Table(Struct): + staticSize = 2 + + def readOffset(self, reader): + return reader.readUShort() + + def writeNullOffset(self, writer): + writer.writeUShort(0) + + def read(self, reader, font, tableDict): + offset = self.readOffset(reader) + if offset == 0: + return None + table = self.tableClass() + reader = reader.getSubReader(offset) + if font.lazy: + table.reader = reader + table.font = font + else: + table.decompile(reader, font) + return table + + def write(self, writer, font, tableDict, value, repeatIndex=None): + if value is None: + self.writeNullOffset(writer) + else: + subWriter = writer.getSubWriter() + subWriter.name = self.name + if repeatIndex is not None: + subWriter.repeatIndex = repeatIndex + writer.writeSubTable(subWriter, offsetSize=self.staticSize) + value.compile(subWriter, font) + + +class LTable(Table): + staticSize = 4 + + def readOffset(self, reader): + return reader.readULong() + + def writeNullOffset(self, writer): + writer.writeULong(0) + + +# Table pointed to by a 24-bit, 3-byte long offset +class Table24(Table): + staticSize = 3 + + def readOffset(self, reader): + return reader.readUInt24() + + def writeNullOffset(self, writer): + writer.writeUInt24(0) + + +# TODO Clean / merge the SubTable and SubStruct + + +class SubStruct(Struct): + def getConverter(self, tableType, lookupType): + tableClass = self.lookupTypes[tableType][lookupType] + return self.__class__(self.name, self.repeat, self.aux, tableClass) + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + super(SubStruct, self).xmlWrite(xmlWriter, font, value, None, attrs) + + +class SubTable(Table): + def getConverter(self, tableType, lookupType): + tableClass = self.lookupTypes[tableType][lookupType] + return self.__class__(self.name, self.repeat, self.aux, tableClass) + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + super(SubTable, self).xmlWrite(xmlWriter, font, value, None, attrs) + + +class ExtSubTable(LTable, SubTable): + def write(self, writer, font, tableDict, value, repeatIndex=None): + writer.Extension = True # actually, mere presence of the field flags it as an Ext Subtable writer. + Table.write(self, writer, font, tableDict, value, repeatIndex) + + +class FeatureParams(Table): + def getConverter(self, featureTag): + tableClass = self.featureParamTypes.get(featureTag, self.defaultFeatureParams) + return self.__class__(self.name, self.repeat, self.aux, tableClass) + + +class ValueFormat(IntValue): + staticSize = 2 + + def __init__(self, name, repeat, aux, tableClass=None, *, description=""): + BaseConverter.__init__( + self, name, repeat, aux, tableClass, description=description + ) + self.which = "ValueFormat" + ("2" if name[-1] == "2" else "1") + + def read(self, reader, font, tableDict): + format = reader.readUShort() + reader[self.which] = ValueRecordFactory(format) + return format + + def write(self, writer, font, tableDict, format, repeatIndex=None): + writer.writeUShort(format) + writer[self.which] = ValueRecordFactory(format) + + +class ValueRecord(ValueFormat): + def getRecordSize(self, reader): + return 2 * len(reader[self.which]) + + def read(self, reader, font, tableDict): + return reader[self.which].readValueRecord(reader, font) + + def write(self, writer, font, tableDict, value, repeatIndex=None): + writer[self.which].writeValueRecord(writer, font, value) + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + if value is None: + pass # NULL table, ignore + else: + value.toXML(xmlWriter, font, self.name, attrs) + + def xmlRead(self, attrs, content, font): + from .otBase import ValueRecord + + value = ValueRecord() + value.fromXML(None, attrs, content, font) + return value + + +class AATLookup(BaseConverter): + BIN_SEARCH_HEADER_SIZE = 10 + + def __init__(self, name, repeat, aux, tableClass, *, description=""): + BaseConverter.__init__( + self, name, repeat, aux, tableClass, description=description + ) + if issubclass(self.tableClass, SimpleValue): + self.converter = self.tableClass(name="Value", repeat=None, aux=None) + else: + self.converter = Table( + name="Value", repeat=None, aux=None, tableClass=self.tableClass + ) + + def read(self, reader, font, tableDict): + format = reader.readUShort() + if format == 0: + return self.readFormat0(reader, font) + elif format == 2: + return self.readFormat2(reader, font) + elif format == 4: + return self.readFormat4(reader, font) + elif format == 6: + return self.readFormat6(reader, font) + elif format == 8: + return self.readFormat8(reader, font) + else: + assert False, "unsupported lookup format: %d" % format + + def write(self, writer, font, tableDict, value, repeatIndex=None): + values = list( + sorted([(font.getGlyphID(glyph), val) for glyph, val in value.items()]) + ) + # TODO: Also implement format 4. + formats = list( + sorted( + filter( + None, + [ + self.buildFormat0(writer, font, values), + self.buildFormat2(writer, font, values), + self.buildFormat6(writer, font, values), + self.buildFormat8(writer, font, values), + ], + ) + ) + ) + # We use the format ID as secondary sort key to make the output + # deterministic when multiple formats have same encoded size. + dataSize, lookupFormat, writeMethod = formats[0] + pos = writer.getDataLength() + writeMethod() + actualSize = writer.getDataLength() - pos + assert ( + actualSize == dataSize + ), "AATLookup format %d claimed to write %d bytes, but wrote %d" % ( + lookupFormat, + dataSize, + actualSize, + ) + + @staticmethod + def writeBinSearchHeader(writer, numUnits, unitSize): + writer.writeUShort(unitSize) + writer.writeUShort(numUnits) + searchRange, entrySelector, rangeShift = getSearchRange( + n=numUnits, itemSize=unitSize + ) + writer.writeUShort(searchRange) + writer.writeUShort(entrySelector) + writer.writeUShort(rangeShift) + + def buildFormat0(self, writer, font, values): + numGlyphs = len(font.getGlyphOrder()) + if len(values) != numGlyphs: + return None + valueSize = self.converter.staticSize + return ( + 2 + numGlyphs * valueSize, + 0, + lambda: self.writeFormat0(writer, font, values), + ) + + def writeFormat0(self, writer, font, values): + writer.writeUShort(0) + for glyphID_, value in values: + self.converter.write( + writer, font, tableDict=None, value=value, repeatIndex=None + ) + + def buildFormat2(self, writer, font, values): + segStart, segValue = values[0] + segEnd = segStart + segments = [] + for glyphID, curValue in values[1:]: + if glyphID != segEnd + 1 or curValue != segValue: + segments.append((segStart, segEnd, segValue)) + segStart = segEnd = glyphID + segValue = curValue + else: + segEnd = glyphID + segments.append((segStart, segEnd, segValue)) + valueSize = self.converter.staticSize + numUnits, unitSize = len(segments) + 1, valueSize + 4 + return ( + 2 + self.BIN_SEARCH_HEADER_SIZE + numUnits * unitSize, + 2, + lambda: self.writeFormat2(writer, font, segments), + ) + + def writeFormat2(self, writer, font, segments): + writer.writeUShort(2) + valueSize = self.converter.staticSize + numUnits, unitSize = len(segments), valueSize + 4 + self.writeBinSearchHeader(writer, numUnits, unitSize) + for firstGlyph, lastGlyph, value in segments: + writer.writeUShort(lastGlyph) + writer.writeUShort(firstGlyph) + self.converter.write( + writer, font, tableDict=None, value=value, repeatIndex=None + ) + writer.writeUShort(0xFFFF) + writer.writeUShort(0xFFFF) + writer.writeData(b"\x00" * valueSize) + + def buildFormat6(self, writer, font, values): + valueSize = self.converter.staticSize + numUnits, unitSize = len(values), valueSize + 2 + return ( + 2 + self.BIN_SEARCH_HEADER_SIZE + (numUnits + 1) * unitSize, + 6, + lambda: self.writeFormat6(writer, font, values), + ) + + def writeFormat6(self, writer, font, values): + writer.writeUShort(6) + valueSize = self.converter.staticSize + numUnits, unitSize = len(values), valueSize + 2 + self.writeBinSearchHeader(writer, numUnits, unitSize) + for glyphID, value in values: + writer.writeUShort(glyphID) + self.converter.write( + writer, font, tableDict=None, value=value, repeatIndex=None + ) + writer.writeUShort(0xFFFF) + writer.writeData(b"\x00" * valueSize) + + def buildFormat8(self, writer, font, values): + minGlyphID, maxGlyphID = values[0][0], values[-1][0] + if len(values) != maxGlyphID - minGlyphID + 1: + return None + valueSize = self.converter.staticSize + return ( + 6 + len(values) * valueSize, + 8, + lambda: self.writeFormat8(writer, font, values), + ) + + def writeFormat8(self, writer, font, values): + firstGlyphID = values[0][0] + writer.writeUShort(8) + writer.writeUShort(firstGlyphID) + writer.writeUShort(len(values)) + for _, value in values: + self.converter.write( + writer, font, tableDict=None, value=value, repeatIndex=None + ) + + def readFormat0(self, reader, font): + numGlyphs = len(font.getGlyphOrder()) + data = self.converter.readArray(reader, font, tableDict=None, count=numGlyphs) + return {font.getGlyphName(k): value for k, value in enumerate(data)} + + def readFormat2(self, reader, font): + mapping = {} + pos = reader.pos - 2 # start of table is at UShort for format + unitSize, numUnits = reader.readUShort(), reader.readUShort() + assert unitSize >= 4 + self.converter.staticSize, unitSize + for i in range(numUnits): + reader.seek(pos + i * unitSize + 12) + last = reader.readUShort() + first = reader.readUShort() + value = self.converter.read(reader, font, tableDict=None) + if last != 0xFFFF: + for k in range(first, last + 1): + mapping[font.getGlyphName(k)] = value + return mapping + + def readFormat4(self, reader, font): + mapping = {} + pos = reader.pos - 2 # start of table is at UShort for format + unitSize = reader.readUShort() + assert unitSize >= 6, unitSize + for i in range(reader.readUShort()): + reader.seek(pos + i * unitSize + 12) + last = reader.readUShort() + first = reader.readUShort() + offset = reader.readUShort() + if last != 0xFFFF: + dataReader = reader.getSubReader(0) # relative to current position + dataReader.seek(pos + offset) # relative to start of table + data = self.converter.readArray( + dataReader, font, tableDict=None, count=last - first + 1 + ) + for k, v in enumerate(data): + mapping[font.getGlyphName(first + k)] = v + return mapping + + def readFormat6(self, reader, font): + mapping = {} + pos = reader.pos - 2 # start of table is at UShort for format + unitSize = reader.readUShort() + assert unitSize >= 2 + self.converter.staticSize, unitSize + for i in range(reader.readUShort()): + reader.seek(pos + i * unitSize + 12) + glyphID = reader.readUShort() + value = self.converter.read(reader, font, tableDict=None) + if glyphID != 0xFFFF: + mapping[font.getGlyphName(glyphID)] = value + return mapping + + def readFormat8(self, reader, font): + first = reader.readUShort() + count = reader.readUShort() + data = self.converter.readArray(reader, font, tableDict=None, count=count) + return {font.getGlyphName(first + k): value for (k, value) in enumerate(data)} + + def xmlRead(self, attrs, content, font): + value = {} + for element in content: + if isinstance(element, tuple): + name, a, eltContent = element + if name == "Lookup": + value[a["glyph"]] = self.converter.xmlRead(a, eltContent, font) + return value + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.begintag(name, attrs) + xmlWriter.newline() + for glyph, value in sorted(value.items()): + self.converter.xmlWrite( + xmlWriter, font, value=value, name="Lookup", attrs=[("glyph", glyph)] + ) + xmlWriter.endtag(name) + xmlWriter.newline() + + +# The AAT 'ankr' table has an unusual structure: An offset to an AATLookup +# followed by an offset to a glyph data table. Other than usual, the +# offsets in the AATLookup are not relative to the beginning of +# the beginning of the 'ankr' table, but relative to the glyph data table. +# So, to find the anchor data for a glyph, one needs to add the offset +# to the data table to the offset found in the AATLookup, and then use +# the sum of these two offsets to find the actual data. +class AATLookupWithDataOffset(BaseConverter): + def read(self, reader, font, tableDict): + lookupOffset = reader.readULong() + dataOffset = reader.readULong() + lookupReader = reader.getSubReader(lookupOffset) + lookup = AATLookup("DataOffsets", None, None, UShort) + offsets = lookup.read(lookupReader, font, tableDict) + result = {} + for glyph, offset in offsets.items(): + dataReader = reader.getSubReader(offset + dataOffset) + item = self.tableClass() + item.decompile(dataReader, font) + result[glyph] = item + return result + + def write(self, writer, font, tableDict, value, repeatIndex=None): + # We do not work with OTTableWriter sub-writers because + # the offsets in our AATLookup are relative to our data + # table, for which we need to provide an offset value itself. + # It might have been possible to somehow make a kludge for + # performing this indirect offset computation directly inside + # OTTableWriter. But this would have made the internal logic + # of OTTableWriter even more complex than it already is, + # so we decided to roll our own offset computation for the + # contents of the AATLookup and associated data table. + offsetByGlyph, offsetByData, dataLen = {}, {}, 0 + compiledData = [] + for glyph in sorted(value, key=font.getGlyphID): + subWriter = OTTableWriter() + value[glyph].compile(subWriter, font) + data = subWriter.getAllData() + offset = offsetByData.get(data, None) + if offset == None: + offset = dataLen + dataLen = dataLen + len(data) + offsetByData[data] = offset + compiledData.append(data) + offsetByGlyph[glyph] = offset + # For calculating the offsets to our AATLookup and data table, + # we can use the regular OTTableWriter infrastructure. + lookupWriter = writer.getSubWriter() + lookup = AATLookup("DataOffsets", None, None, UShort) + lookup.write(lookupWriter, font, tableDict, offsetByGlyph, None) + + dataWriter = writer.getSubWriter() + writer.writeSubTable(lookupWriter, offsetSize=4) + writer.writeSubTable(dataWriter, offsetSize=4) + for d in compiledData: + dataWriter.writeData(d) + + def xmlRead(self, attrs, content, font): + lookup = AATLookup("DataOffsets", None, None, self.tableClass) + return lookup.xmlRead(attrs, content, font) + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + lookup = AATLookup("DataOffsets", None, None, self.tableClass) + lookup.xmlWrite(xmlWriter, font, value, name, attrs) + + +class MortSubtableConverter(BaseConverter): + def read(self, reader, font, tableDict): + pos = reader.pos + m = MortSubtable() + m.StructLength = reader.readUShort() + m.CoverageFlags = reader.readUInt8() + m.MorphType = reader.readUInt8() + m.SubFeatureFlags = reader.readULong() + tableClass = lookupTypes["mort"].get(m.MorphType) + if tableClass is None: + assert False, "unsupported 'mort' lookup type %s" % m.MorphType + + # Limit the state-table reader to this subtable. In particular, the + # legacy ligature format has no encoded ligature count and uses the end + # of the subtable as its only upper bound. + headerLength = reader.pos - pos + data = reader.data[reader.pos : reader.pos + m.StructLength - headerLength] + assert len(data) == m.StructLength - headerLength + subReader = OTTableReader(data=data, tableTag=reader.tableTag) + m.SubStruct = tableClass() + m.SubStruct.decompile(subReader, font) + reader.seek(pos + m.StructLength) + return m + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.begintag(name, attrs) + xmlWriter.newline() + xmlWriter.comment("StructLength=%d" % value.StructLength) + xmlWriter.newline() + xmlWriter.simpletag("CoverageFlags", value=value.CoverageFlags) + xmlWriter.newline() + xmlWriter.comment("MorphType=%d" % value.MorphType) + xmlWriter.newline() + xmlWriter.simpletag("SubFeatureFlags", value="0x%08x" % value.SubFeatureFlags) + xmlWriter.newline() + value.SubStruct.toXML(xmlWriter, font) + xmlWriter.endtag(name) + xmlWriter.newline() + + def xmlRead(self, attrs, content, font): + m = MortSubtable() + m.CoverageFlags = 0 + for eltName, eltAttrs, eltContent in filter(istuple, content): + if eltName == "CoverageFlags": + m.CoverageFlags = safeEval(eltAttrs["value"]) + elif eltName == "SubFeatureFlags": + m.SubFeatureFlags = safeEval(eltAttrs["value"]) + elif eltName.endswith("Morph"): + m.fromXML(eltName, eltAttrs, eltContent, font) + else: + assert False, eltName + return m + + def write(self, writer, font, tableDict, value, repeatIndex=None): + lengthIndex = len(writer.items) + before = writer.getDataLength() + value.StructLength = 0xDEAD + value.compile(writer, font) + assert writer.items[lengthIndex] == b"\xde\xad" + length = writer.getDataLength() - before + if length > 0xFFFF: + raise ValueError("mort subtable exceeds 65535 bytes") + writer.items[lengthIndex] = struct.pack(">H", length) + + +class MorxSubtableConverter(BaseConverter): + _PROCESSING_ORDERS = { + # bits 30 and 28 of morx.CoverageFlags; see morx spec + (False, False): "LayoutOrder", + (True, False): "ReversedLayoutOrder", + (False, True): "LogicalOrder", + (True, True): "ReversedLogicalOrder", + } + + _PROCESSING_ORDERS_REVERSED = {val: key for key, val in _PROCESSING_ORDERS.items()} + + def __init__(self, name, repeat, aux, tableClass=None, *, description=""): + BaseConverter.__init__( + self, name, repeat, aux, tableClass, description=description + ) + + def _setTextDirectionFromCoverageFlags(self, flags, subtable): + if (flags & 0x20) != 0: + subtable.TextDirection = "Any" + elif (flags & 0x80) != 0: + subtable.TextDirection = "Vertical" + else: + subtable.TextDirection = "Horizontal" + + def read(self, reader, font, tableDict): + pos = reader.pos + m = MorxSubtable() + m.StructLength = reader.readULong() + flags = reader.readUInt8() + orderKey = ((flags & 0x40) != 0, (flags & 0x10) != 0) + m.ProcessingOrder = self._PROCESSING_ORDERS[orderKey] + self._setTextDirectionFromCoverageFlags(flags, m) + m.Reserved = reader.readUShort() + m.Reserved |= (flags & 0xF) << 16 + m.MorphType = reader.readUInt8() + m.SubFeatureFlags = reader.readULong() + tableClass = lookupTypes["morx"].get(m.MorphType) + if tableClass is None: + assert False, "unsupported 'morx' lookup type %s" % m.MorphType + # To decode AAT ligatures, we need to know the subtable size. + # The easiest way to pass this along is to create a new reader + # that works on just the subtable as its data. + headerLength = reader.pos - pos + data = reader.data[reader.pos : reader.pos + m.StructLength - headerLength] + assert len(data) == m.StructLength - headerLength + subReader = OTTableReader(data=data, tableTag=reader.tableTag) + m.SubStruct = tableClass() + m.SubStruct.decompile(subReader, font) + reader.seek(pos + m.StructLength) + return m + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.begintag(name, attrs) + xmlWriter.newline() + xmlWriter.comment("StructLength=%d" % value.StructLength) + xmlWriter.newline() + xmlWriter.simpletag("TextDirection", value=value.TextDirection) + xmlWriter.newline() + xmlWriter.simpletag("ProcessingOrder", value=value.ProcessingOrder) + xmlWriter.newline() + if value.Reserved != 0: + xmlWriter.simpletag("Reserved", value="0x%04x" % value.Reserved) + xmlWriter.newline() + xmlWriter.comment("MorphType=%d" % value.MorphType) + xmlWriter.newline() + xmlWriter.simpletag("SubFeatureFlags", value="0x%08x" % value.SubFeatureFlags) + xmlWriter.newline() + value.SubStruct.toXML(xmlWriter, font) + xmlWriter.endtag(name) + xmlWriter.newline() + + def xmlRead(self, attrs, content, font): + m = MorxSubtable() + covFlags = 0 + m.Reserved = 0 + for eltName, eltAttrs, eltContent in filter(istuple, content): + if eltName == "CoverageFlags": + # Only in XML from old versions of fonttools. + covFlags = safeEval(eltAttrs["value"]) + orderKey = ((covFlags & 0x40) != 0, (covFlags & 0x10) != 0) + m.ProcessingOrder = self._PROCESSING_ORDERS[orderKey] + self._setTextDirectionFromCoverageFlags(covFlags, m) + elif eltName == "ProcessingOrder": + m.ProcessingOrder = eltAttrs["value"] + assert m.ProcessingOrder in self._PROCESSING_ORDERS_REVERSED, ( + "unknown ProcessingOrder: %s" % m.ProcessingOrder + ) + elif eltName == "TextDirection": + m.TextDirection = eltAttrs["value"] + assert m.TextDirection in {"Horizontal", "Vertical", "Any"}, ( + "unknown TextDirection %s" % m.TextDirection + ) + elif eltName == "Reserved": + m.Reserved = safeEval(eltAttrs["value"]) + elif eltName == "SubFeatureFlags": + m.SubFeatureFlags = safeEval(eltAttrs["value"]) + elif eltName.endswith("Morph"): + m.fromXML(eltName, eltAttrs, eltContent, font) + else: + assert False, eltName + m.Reserved = (covFlags & 0xF) << 16 | m.Reserved + return m + + def write(self, writer, font, tableDict, value, repeatIndex=None): + covFlags = (value.Reserved & 0x000F0000) >> 16 + reverseOrder, logicalOrder = self._PROCESSING_ORDERS_REVERSED[ + value.ProcessingOrder + ] + covFlags |= 0x80 if value.TextDirection == "Vertical" else 0 + covFlags |= 0x40 if reverseOrder else 0 + covFlags |= 0x20 if value.TextDirection == "Any" else 0 + covFlags |= 0x10 if logicalOrder else 0 + value.CoverageFlags = covFlags + lengthIndex = len(writer.items) + before = writer.getDataLength() + value.StructLength = 0xDEADBEEF + # The high nibble of value.Reserved is actuallly encoded + # into coverageFlags, so we need to clear it here. + origReserved = value.Reserved # including high nibble + value.Reserved = value.Reserved & 0xFFFF # without high nibble + value.compile(writer, font) + value.Reserved = origReserved # restore original value + assert writer.items[lengthIndex] == b"\xde\xad\xbe\xef" + length = writer.getDataLength() - before + writer.items[lengthIndex] = struct.pack(">L", length) + + +# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6Tables.html#ExtendedStateHeader +# TODO: Untangle the implementation of the various lookup-specific formats. +class STXHeader(BaseConverter): + def __init__(self, name, repeat, aux, tableClass, *, description=""): + BaseConverter.__init__( + self, name, repeat, aux, tableClass, description=description + ) + assert issubclass(self.tableClass, AATAction) + self.classLookup = AATLookup("GlyphClasses", None, None, UShort) + if issubclass(self.tableClass, ContextualMorphAction): + self.perGlyphLookup = AATLookup("PerGlyphLookup", None, None, GlyphID) + else: + self.perGlyphLookup = None + + def read(self, reader, font, tableDict): + table = AATStateTable() + pos = reader.pos + classTableReader = reader.getSubReader(0) + stateArrayReader = reader.getSubReader(0) + entryTableReader = reader.getSubReader(0) + actionReader = None + ligaturesReader = None + table.GlyphClassCount = reader.readULong() + classTableReader.seek(pos + reader.readULong()) + stateArrayReader.seek(pos + reader.readULong()) + entryTableReader.seek(pos + reader.readULong()) + if self.perGlyphLookup is not None: + perGlyphTableReader = reader.getSubReader(0) + perGlyphTableReader.seek(pos + reader.readULong()) + if issubclass(self.tableClass, LigatureMorphAction): + actionReader = reader.getSubReader(0) + actionReader.seek(pos + reader.readULong()) + ligComponentReader = reader.getSubReader(0) + ligComponentReader.seek(pos + reader.readULong()) + ligaturesReader = reader.getSubReader(0) + ligaturesReader.seek(pos + reader.readULong()) + numLigComponents = (ligaturesReader.pos - ligComponentReader.pos) // 2 + assert numLigComponents >= 0 + table.LigComponents = ligComponentReader.readUShortArray(numLigComponents) + table.Ligatures = self._readLigatures(ligaturesReader, font) + elif issubclass(self.tableClass, InsertionMorphAction): + actionReader = reader.getSubReader(0) + actionReader.seek(pos + reader.readULong()) + table.GlyphClasses = self.classLookup.read(classTableReader, font, tableDict) + numStates = int( + (entryTableReader.pos - stateArrayReader.pos) / (table.GlyphClassCount * 2) + ) + for stateIndex in range(numStates): + state = AATState() + table.States.append(state) + for glyphClass in range(table.GlyphClassCount): + entryIndex = stateArrayReader.readUShort() + state.Transitions[glyphClass] = self._readTransition( + entryTableReader, entryIndex, font, actionReader + ) + if self.perGlyphLookup is not None: + table.PerGlyphLookups = self._readPerGlyphLookups( + table, perGlyphTableReader, font + ) + return table + + def _readTransition(self, reader, entryIndex, font, actionReader): + transition = self.tableClass() + entryReader = reader.getSubReader( + reader.pos + entryIndex * transition.staticSize + ) + transition.decompile(entryReader, font, actionReader) + return transition + + def _readLigatures(self, reader, font): + limit = len(reader.data) + numLigatureGlyphs = (limit - reader.pos) // 2 + return font.getGlyphNameMany(reader.readUShortArray(numLigatureGlyphs)) + + def _countPerGlyphLookups(self, table): + # Somewhat annoyingly, the morx table does not encode + # the size of the per-glyph table. So we need to find + # the maximum value that MorphActions use as index + # into this table. + numLookups = 0 + for state in table.States: + for t in state.Transitions.values(): + if isinstance(t, ContextualMorphAction): + if t.MarkIndex != 0xFFFF: + numLookups = max(numLookups, t.MarkIndex + 1) + if t.CurrentIndex != 0xFFFF: + numLookups = max(numLookups, t.CurrentIndex + 1) + return numLookups + + def _readPerGlyphLookups(self, table, reader, font): + pos = reader.pos + lookups = [] + for _ in range(self._countPerGlyphLookups(table)): + lookupReader = reader.getSubReader(0) + lookupReader.seek(pos + reader.readULong()) + lookups.append(self.perGlyphLookup.read(lookupReader, font, {})) + return lookups + + def write(self, writer, font, tableDict, value, repeatIndex=None): + glyphClassWriter = OTTableWriter() + self.classLookup.write( + glyphClassWriter, font, tableDict, value.GlyphClasses, repeatIndex=None + ) + glyphClassData = pad(glyphClassWriter.getAllData(), 2) + glyphClassCount = max(value.GlyphClasses.values()) + 1 + glyphClassTableOffset = 16 # size of STXHeader + if self.perGlyphLookup is not None: + glyphClassTableOffset += 4 + + glyphClassTableOffset += self.tableClass.actionHeaderSize + actionData, actionIndex = self.tableClass.compileActions(font, value.States) + stateArrayData, entryTableData = self._compileStates( + font, value.States, glyphClassCount, actionIndex + ) + stateArrayOffset = glyphClassTableOffset + len(glyphClassData) + entryTableOffset = stateArrayOffset + len(stateArrayData) + perGlyphOffset = entryTableOffset + len(entryTableData) + perGlyphData = pad(self._compilePerGlyphLookups(value, font), 4) + if actionData is not None: + actionOffset = entryTableOffset + len(entryTableData) + else: + actionOffset = None + + ligaturesOffset, ligComponentsOffset = None, None + ligComponentsData = self._compileLigComponents(value, font) + ligaturesData = self._compileLigatures(value, font) + if ligComponentsData is not None: + assert len(perGlyphData) == 0 + ligComponentsOffset = actionOffset + len(actionData) + ligaturesOffset = ligComponentsOffset + len(ligComponentsData) + + writer.writeULong(glyphClassCount) + writer.writeULong(glyphClassTableOffset) + writer.writeULong(stateArrayOffset) + writer.writeULong(entryTableOffset) + if self.perGlyphLookup is not None: + writer.writeULong(perGlyphOffset) + if actionOffset is not None: + writer.writeULong(actionOffset) + if ligComponentsOffset is not None: + writer.writeULong(ligComponentsOffset) + writer.writeULong(ligaturesOffset) + writer.writeData(glyphClassData) + writer.writeData(stateArrayData) + writer.writeData(entryTableData) + writer.writeData(perGlyphData) + if actionData is not None: + writer.writeData(actionData) + if ligComponentsData is not None: + writer.writeData(ligComponentsData) + if ligaturesData is not None: + writer.writeData(ligaturesData) + + def _compileStates(self, font, states, glyphClassCount, actionIndex): + stateArrayWriter = OTTableWriter() + entries, entryIDs = [], {} + for state in states: + for glyphClass in range(glyphClassCount): + transition = state.Transitions[glyphClass] + entryWriter = OTTableWriter() + transition.compile(entryWriter, font, actionIndex) + entryData = entryWriter.getAllData() + assert ( + len(entryData) == transition.staticSize + ), "%s has staticSize %d, " "but actually wrote %d bytes" % ( + repr(transition), + transition.staticSize, + len(entryData), + ) + entryIndex = entryIDs.get(entryData) + if entryIndex is None: + entryIndex = len(entries) + entryIDs[entryData] = entryIndex + entries.append(entryData) + stateArrayWriter.writeUShort(entryIndex) + stateArrayData = pad(stateArrayWriter.getAllData(), 4) + entryTableData = pad(bytesjoin(entries), 4) + return stateArrayData, entryTableData + + def _compilePerGlyphLookups(self, table, font): + if self.perGlyphLookup is None: + return b"" + numLookups = self._countPerGlyphLookups(table) + assert len(table.PerGlyphLookups) == numLookups, ( + "len(AATStateTable.PerGlyphLookups) is %d, " + "but the actions inside the table refer to %d" + % (len(table.PerGlyphLookups), numLookups) + ) + writer = OTTableWriter() + for lookup in table.PerGlyphLookups: + lookupWriter = writer.getSubWriter() + self.perGlyphLookup.write(lookupWriter, font, {}, lookup, None) + writer.writeSubTable(lookupWriter, offsetSize=4) + return writer.getAllData() + + def _compileLigComponents(self, table, font): + if not hasattr(table, "LigComponents"): + return None + writer = OTTableWriter() + for component in table.LigComponents: + writer.writeUShort(component) + return writer.getAllData() + + def _compileLigatures(self, table, font): + if not hasattr(table, "Ligatures"): + return None + writer = OTTableWriter() + for glyphName in table.Ligatures: + writer.writeUShort(font.getGlyphID(glyphName)) + return writer.getAllData() + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.begintag(name, attrs) + xmlWriter.newline() + xmlWriter.comment("GlyphClassCount=%s" % value.GlyphClassCount) + xmlWriter.newline() + for g, klass in sorted(value.GlyphClasses.items()): + xmlWriter.simpletag("GlyphClass", glyph=g, value=klass) + xmlWriter.newline() + for stateIndex, state in enumerate(value.States): + xmlWriter.begintag("State", index=stateIndex) + xmlWriter.newline() + for glyphClass, trans in sorted(state.Transitions.items()): + trans.toXML( + xmlWriter, + font=font, + attrs={"onGlyphClass": glyphClass}, + name="Transition", + ) + xmlWriter.endtag("State") + xmlWriter.newline() + for i, lookup in enumerate(value.PerGlyphLookups): + xmlWriter.begintag("PerGlyphLookup", index=i) + xmlWriter.newline() + for glyph, val in sorted(lookup.items()): + xmlWriter.simpletag("Lookup", glyph=glyph, value=val) + xmlWriter.newline() + xmlWriter.endtag("PerGlyphLookup") + xmlWriter.newline() + if hasattr(value, "LigComponents"): + xmlWriter.begintag("LigComponents") + xmlWriter.newline() + for i, val in enumerate(getattr(value, "LigComponents")): + xmlWriter.simpletag("LigComponent", index=i, value=val) + xmlWriter.newline() + xmlWriter.endtag("LigComponents") + xmlWriter.newline() + if hasattr(value, "_MortLigatureRebase"): + xmlWriter.begintag("MortLigatureRebase") + xmlWriter.newline() + for componentIndex in sorted(value._MortLigatureRebase): + xmlWriter.simpletag("Component", index=componentIndex) + xmlWriter.newline() + xmlWriter.endtag("MortLigatureRebase") + xmlWriter.newline() + self._xmlWriteLigatures(xmlWriter, font, value, name, attrs) + xmlWriter.endtag(name) + xmlWriter.newline() + + def _xmlWriteLigatures(self, xmlWriter, font, value, name, attrs): + if not hasattr(value, "Ligatures"): + return + xmlWriter.begintag("Ligatures") + xmlWriter.newline() + for i, g in enumerate(getattr(value, "Ligatures")): + xmlWriter.simpletag("Ligature", index=i, glyph=g) + xmlWriter.newline() + xmlWriter.endtag("Ligatures") + xmlWriter.newline() + + def xmlRead(self, attrs, content, font): + table = AATStateTable() + for eltName, eltAttrs, eltContent in filter(istuple, content): + if eltName == "GlyphClass": + glyph = eltAttrs["glyph"] + value = eltAttrs["value"] + table.GlyphClasses[glyph] = safeEval(value) + elif eltName == "State": + state = self._xmlReadState(eltAttrs, eltContent, font) + table.States.append(state) + elif eltName == "PerGlyphLookup": + lookup = self.perGlyphLookup.xmlRead(eltAttrs, eltContent, font) + table.PerGlyphLookups.append(lookup) + elif eltName == "LigComponents": + table.LigComponents = self._xmlReadLigComponents( + eltAttrs, eltContent, font + ) + elif eltName == "MortLigatureRebase": + table._MortLigatureRebase = { + safeEval(componentAttrs["index"]) + for componentName, componentAttrs, _componentContent in filter( + istuple, eltContent + ) + if componentName == "Component" + } + elif eltName == "Ligatures": + table.Ligatures = self._xmlReadLigatures(eltAttrs, eltContent, font) + glyphClasses = list(table.GlyphClasses.values()) + glyphClasses.extend( + glyphClass for state in table.States for glyphClass in state.Transitions + ) + table.GlyphClassCount = max(glyphClasses, default=-1) + 1 + return table + + def _xmlReadState(self, attrs, content, font): + state = AATState() + for eltName, eltAttrs, eltContent in filter(istuple, content): + if eltName == "Transition": + glyphClass = safeEval(eltAttrs["onGlyphClass"]) + transition = self.tableClass() + transition.fromXML(eltName, eltAttrs, eltContent, font) + state.Transitions[glyphClass] = transition + return state + + def _xmlReadLigComponents(self, attrs, content, font): + ligComponents = [] + for eltName, eltAttrs, _eltContent in filter(istuple, content): + if eltName == "LigComponent": + ligComponents.append(safeEval(eltAttrs["value"])) + return ligComponents + + def _xmlReadLigatures(self, attrs, content, font): + ligs = [] + for eltName, eltAttrs, _eltContent in filter(istuple, content): + if eltName == "Ligature": + ligs.append(eltAttrs["glyph"]) + return ligs + + +class StateHeader(STXHeader): + """Converter for the obsolete, non-extended AAT state-table format.""" + + def read(self, reader, font, tableDict): + table = AATStateTable() + pos = reader.pos + table.GlyphClassCount = reader.readUShort() + classTableOffset = reader.readUShort() + stateArrayOffset = reader.readUShort() + entryTableOffset = reader.readUShort() + if table.GlyphClassCount == 0: + raise ValueError("mort state table has no glyph classes") + + substitutionTableOffset = None + actionOffset = componentOffset = ligatureOffset = None + actionReader = None + if issubclass(self.tableClass, ContextualMorphAction): + substitutionTableOffset = reader.readUShort() + elif issubclass(self.tableClass, LigatureMorphAction): + actionOffset = reader.readUShort() + componentOffset = reader.readUShort() + ligatureOffset = reader.readUShort() + if ( + componentOffset > ligatureOffset + or (ligatureOffset - componentOffset) % 2 + ): + raise ValueError("invalid mort ligature component table") + componentReader = reader.getSubReader(0) + componentReader.seek(pos + componentOffset) + rawComponents = componentReader.readUShortArray( + (ligatureOffset - componentOffset) // 2 + ) + if any(component % 2 for component in rawComponents): + raise ValueError("invalid mort ligature component value") + table.LigComponents = [component // 2 for component in rawComponents] + table.Ligatures = [] + table._MortLigatureRebase = set() + elif issubclass(self.tableClass, InsertionMorphAction): + actionOffset = reader.readUShort() + actionReader = reader.getSubReader(0) + actionReader.seek(pos + actionOffset) + + classTableReader = reader.getSubReader(0) + classTableReader.seek(pos + classTableOffset) + firstGlyph = classTableReader.readUShort() + glyphCount = classTableReader.readUShort() + glyphClasses = classTableReader.readUInt8Array(glyphCount) + table.GlyphClasses = { + font.getGlyphName(firstGlyph + i): glyphClass + for i, glyphClass in enumerate(glyphClasses) + } + + stateArrayReader = reader.getSubReader(0) + stateArrayReader.seek(pos + stateArrayOffset) + entryTableReader = reader.getSubReader(0) + entryTableReader.seek(pos + entryTableOffset) + stateDataLength = entryTableOffset - stateArrayOffset + if stateDataLength < 0: + raise ValueError("mort state-array offset follows its entry table") + numStates = stateDataLength // table.GlyphClassCount + transitionCache = {} + for _stateIndex in range(numStates): + state = AATState() + table.States.append(state) + for glyphClass in range(table.GlyphClassCount): + entryIndex = stateArrayReader.readUInt8() + transition = transitionCache.get(entryIndex) + if transition is None: + transition = self._readTransition( + entryTableReader, + entryIndex, + font, + actionReader, + pos, + stateArrayOffset, + componentOffset, + ligatureOffset, + table, + ) + transitionCache[entryIndex] = transition + state.Transitions[glyphClass] = transition + + if substitutionTableOffset is not None: + self._readContextualLookups( + table, reader, font, pos, substitutionTableOffset + ) + elif ligatureOffset is not None: + ligatureBase = ligatureOffset // 2 + table._MortLigatureRebase = { + componentIndex + for componentIndex in table._MortLigatureRebase + if table.LigComponents[componentIndex] >= ligatureBase + } + for componentIndex in table._MortLigatureRebase: + # Unused entries are commonly zero. Only values which actually + # include the ligature-table base need to be normalized. + table.LigComponents[componentIndex] -= ligatureBase + + ligatureCount = self._countLegacyLigatures(table, len(font.getGlyphOrder())) + ligatureReader = reader.getSubReader(0) + ligatureReader.seek(pos + ligatureOffset) + table.Ligatures = font.getGlyphNameMany( + ligatureReader.readUShortArray(ligatureCount) + ) + return table + + def _readTransition( + self, + reader, + entryIndex, + font, + actionReader, + stateTablePos, + stateArrayOffset, + componentOffset, + ligatureOffset, + table, + ): + transition = self.tableClass() + entrySize = ( + 4 + if issubclass(self.tableClass, LigatureMorphAction) + else transition.staticSize + ) + entryReader = reader.getSubReader(reader.pos + entryIndex * entrySize) + + if issubclass(self.tableClass, ContextualMorphAction): + transition.NewState = entryReader.readUShort() + flags = entryReader.readUShort() + transition.SetMark = bool(flags & 0x8000) + transition.DontAdvance = bool(flags & 0x4000) + transition.ReservedFlags = flags & 0x3FFF + transition._MortMarkOffset = entryReader.readShort() + transition._MortCurrentOffset = entryReader.readShort() + elif issubclass(self.tableClass, LigatureMorphAction): + transition.NewState = entryReader.readUShort() + flags = entryReader.readUShort() + transition.SetComponent = bool(flags & 0x8000) + transition.DontAdvance = bool(flags & 0x4000) + transition.ReservedFlags = 0 + transition.Actions = [] + ligActionOffset = flags & 0x3FFF + if ligActionOffset: + transition.Actions = self._readLigatureActions( + reader, + font, + stateTablePos, + ligActionOffset, + componentOffset, + ligatureOffset, + table, + ) + else: + transition.decompile(entryReader, font, actionReader) + + newStateOffset = transition.NewState - stateArrayOffset + if newStateOffset < 0 or newStateOffset % table.GlyphClassCount: + raise ValueError("invalid mort new-state offset") + transition.NewState = newStateOffset // table.GlyphClassCount + return transition + + def _readContextualLookups( + self, table, reader, font, stateTablePos, substitutionTableOffset + ): + transitions = { + transition + for state in table.States + for transition in state.Transitions.values() + } + offsets = sorted( + { + offset + for transition in transitions + for offset in ( + transition._MortMarkOffset, + transition._MortCurrentOffset, + ) + if offset + } + ) + offsetToIndex = {offset: i for i, offset in enumerate(offsets)} + glyphOrder = font.getGlyphOrder() + # reader.data holds just this subtable, so this is the room between + # the state-table header and the end of the subtable. + available = len(reader.data) - stateTablePos + for offset in offsets: + # The entry offset plus a glyph ID gives the word offset of that + # glyph's replacement, so an offset (which may be negative) exposes + # a per-glyph window rather than a whole lookup table. Fonts trim + # the windows: words before the substitution table mean "no + # substitution" (like HarfBuzz), and we also stop at the end of + # the subtable (stricter than HarfBuzz's blob-wide bound). + firstGlyph = max(0, (substitutionTableOffset + 1) // 2 - offset) + lastGlyph = min(len(glyphOrder) - 1, (available - 2) // 2 - offset) + lookup = {} + if firstGlyph <= lastGlyph: + lookupReader = reader.getSubReader(0) + lookupReader.seek(stateTablePos + 2 * (offset + firstGlyph)) + replacements = lookupReader.readUShortArray(lastGlyph - firstGlyph + 1) + lookup = { + glyphOrder[firstGlyph + i]: font.getGlyphName(replacement) + for i, replacement in enumerate(replacements) + if replacement != 0 + } + table.PerGlyphLookups.append(lookup) + for transition in transitions: + transition.MarkIndex = ( + offsetToIndex[transition._MortMarkOffset] + if transition._MortMarkOffset + else 0xFFFF + ) + transition.CurrentIndex = ( + offsetToIndex[transition._MortCurrentOffset] + if transition._MortCurrentOffset + else 0xFFFF + ) + del transition._MortMarkOffset + del transition._MortCurrentOffset + + def _readLigatureActions( + self, + reader, + font, + stateTablePos, + ligActionOffset, + componentOffset, + ligatureOffset, + table, + ): + actionReader = reader.getSubReader(0) + actionReader.seek(stateTablePos + ligActionOffset) + glyphCount = len(font.getGlyphOrder()) + result = [] + rebased = False + last = False + while not last: + value = actionReader.readULong() + last = bool(value & 0x80000000) + store = bool(value & 0x40000000) + componentWordOffset = value & 0x3FFFFFFF + if componentWordOffset & 0x20000000: + componentWordOffset -= 0x40000000 + componentIndex = componentWordOffset - componentOffset // 2 + if ( + componentIndex >= len(table.LigComponents) + or componentIndex + glyphCount <= 0 + ): + raise ValueError("mort ligature component offset is out of bounds") + if (store or last) and not rebased: + start = max(0, componentIndex) + limit = min(len(table.LigComponents), componentIndex + glyphCount) + table._MortLigatureRebase.update(range(start, limit)) + rebased = True + + action = LigAction() + action.Store = store + action.GlyphIndexDelta = componentIndex + result.append(action) + return result + + @staticmethod + def _countLegacyLigatures(table, glyphCount): + count = 0 + transitions = { + transition + for state in table.States + for transition in state.Transitions.values() + } + for transition in transitions: + cumulativeMax = 0 + for index, action in enumerate(transition.Actions): + start = max(0, action.GlyphIndexDelta) + limit = min( + len(table.LigComponents), + action.GlyphIndexDelta + glyphCount, + ) + cumulativeMax += max(table.LigComponents[start:limit], default=0) + if action.Store or index == len(transition.Actions) - 1: + count = max(count, cumulativeMax + 1) + return count + + def write(self, writer, font, tableDict, value, repeatIndex=None): + glyphClassCount = value.GlyphClassCount + if not 0 < glyphClassCount <= 256: + raise ValueError("mort state tables support 1 to 256 glyph classes") + + glyphClasses = sorted( + (font.getGlyphID(glyph), glyphClass) + for glyph, glyphClass in value.GlyphClasses.items() + ) + if glyphClasses: + firstGlyph = glyphClasses[0][0] + lastGlyph = glyphClasses[-1][0] + classValues = dict(glyphClasses) + classes = bytes( + classValues.get(glyphID, 1) + for glyphID in range(firstGlyph, lastGlyph + 1) + ) + else: + firstGlyph = 0 + classes = b"" + classData = struct.pack(">HH", firstGlyph, len(classes)) + classes + + genericActionData, genericActionIndex = self.tableClass.compileActions( + font, value.States + ) + entries = [] + entryIDs = {} + stateEntryIDs = [] + for state in value.States: + row = [] + for glyphClass in range(glyphClassCount): + transition = state.Transitions[glyphClass] + transitionWriter = OTTableWriter() + transition.compile(transitionWriter, font, genericActionIndex) + key = transitionWriter.getAllData() + entryIndex = entryIDs.get(key) + if entryIndex is None: + entryIndex = len(entries) + if entryIndex > 0xFF: + raise ValueError( + "mort state tables support at most 256 entries" + ) + entryIDs[key] = entryIndex + entries.append(transition) + row.append(entryIndex) + stateEntryIDs.append(row) + + extraSize = 0 + if issubclass(self.tableClass, ContextualMorphAction): + extraSize = 2 + elif issubclass(self.tableClass, LigatureMorphAction): + extraSize = 6 + elif issubclass(self.tableClass, InsertionMorphAction): + extraSize = 2 + classTableOffset = 8 + extraSize + stateArrayOffset = self._aligned(classTableOffset + len(classData), 2) + stateData = bytes(entry for row in stateEntryIDs for entry in row) + entryTableOffset = self._aligned(stateArrayOffset + len(stateData), 2) + entrySize = ( + 4 + if issubclass(self.tableClass, LigatureMorphAction) + else self.tableClass.staticSize + ) + tailOffset = entryTableOffset + len(entries) * entrySize + + extra = b"" + tail = b"" + contextOffsets = None + ligatureActionOffsets = None + if issubclass(self.tableClass, ContextualMorphAction): + extra, tail, contextOffsets = self._compileContextualLookups( + value, font, tailOffset + ) + elif issubclass(self.tableClass, LigatureMorphAction): + extra, tail, ligatureActionOffsets = self._compileLigatureData( + value, font, entries, tailOffset + ) + elif issubclass(self.tableClass, InsertionMorphAction): + if tailOffset > 0xFFFF: + raise ValueError("mort insertion-action offset exceeds 16 bits") + extra = struct.pack(">H", tailOffset) + tail = genericActionData + + entryData = b"".join( + self._compileTransition( + transition, + font, + genericActionIndex, + stateArrayOffset, + glyphClassCount, + contextOffsets, + ligatureActionOffsets, + ) + for transition in entries + ) + data = struct.pack( + ">HHHH", + glyphClassCount, + classTableOffset, + stateArrayOffset, + entryTableOffset, + ) + data += extra + classData + data = pad(data, 2) + stateData + data = pad(data, 2) + entryData + tail + data = pad(data, 4) + if len(data) > 0xFFFF: + raise ValueError("mort state table exceeds 65535 bytes") + writer.writeData(data) + + @staticmethod + def _aligned(value, alignment): + return value + (-value % alignment) + + def _compileContextualLookups(self, table, font, tailOffset): + count = self._countPerGlyphLookups(table) + if len(table.PerGlyphLookups) != count: + raise ValueError( + "mort contextual actions refer to %d lookups, but the table has %d" + % (count, len(table.PerGlyphLookups)) + ) + glyphOrder = font.getGlyphOrder() + offsets = [] + data = b"" + for lookup in table.PerGlyphLookups: + offset = (tailOffset + len(data)) // 2 + if offset > 0x7FFF: + raise ValueError("mort substitution offset exceeds signed 16 bits") + offsets.append(offset) + replacements = [] + for glyph in glyphOrder: + replacement = lookup.get(glyph) + replacements.append( + 0 if replacement is None else font.getGlyphID(replacement) + ) + data += struct.pack(">%dH" % len(replacements), *replacements) + if tailOffset > 0xFFFF: + raise ValueError("mort substitution-table offset exceeds 16 bits") + return struct.pack(">H", tailOffset), data, offsets + + def _compileLigatureData(self, table, font, entries, tailOffset): + sequences = [] + sequenceSet = set() + for transition in entries: + sequence = tuple( + (action.GlyphIndexDelta, action.Store) for action in transition.Actions + ) + if sequence and sequence not in sequenceSet: + sequenceSet.add(sequence) + sequences.append(sequence) + + actionOffset = self._aligned(tailOffset, 4) + actionCount = sum(len(sequence) for sequence in sequences) + componentOffset = actionOffset + actionCount * 4 + glyphCount = len(font.getGlyphOrder()) + ligatureOffset = componentOffset + len(table.LigComponents) * 2 + if max(actionOffset, componentOffset, ligatureOffset) > 0xFFFF: + raise ValueError("mort ligature-table offset exceeds 16 bits") + + actionOffsets = {} + actionData = b"" + rebaseComponents = getattr(table, "_MortLigatureRebase", None) + if rebaseComponents is None: + rebaseComponents = set() + else: + rebaseComponents = set(rebaseComponents) + for sequence in sequences: + sequenceOffset = actionOffset + len(actionData) + if sequenceOffset > 0x3FFF: + raise ValueError("mort ligature-action offset exceeds 14 bits") + actionOffsets[sequence] = sequenceOffset + rebased = False + for index, (delta, store) in enumerate(sequence): + value = componentOffset // 2 + delta + if not -(1 << 29) <= value < (1 << 29): + raise ValueError("mort ligature component offset exceeds 30 bits") + value &= 0x3FFFFFFF + last = index == len(sequence) - 1 + value |= 0x40000000 if store else 0 + value |= 0x80000000 if last else 0 + actionData += struct.pack(">I", value) + addBase = (store or last) and not rebased + if addBase and not hasattr(table, "_MortLigatureRebase"): + start = max(0, delta) + limit = min(len(table.LigComponents), delta + glyphCount) + rebaseComponents.update(range(start, limit)) + rebased |= store or last + + componentData = b"" + for componentIndex, component in enumerate(table.LigComponents): + component *= 2 + if componentIndex in rebaseComponents: + component += ligatureOffset + if not 0 <= component <= 0xFFFF: + raise ValueError("mort ligature component value exceeds 16 bits") + componentData += struct.pack(">H", component) + + ligatureData = b"".join( + struct.pack(">H", font.getGlyphID(glyph)) for glyph in table.Ligatures + ) + extra = struct.pack(">HHH", actionOffset, componentOffset, ligatureOffset) + tail = ( + bytes(actionOffset - tailOffset) + actionData + componentData + ligatureData + ) + return extra, tail, actionOffsets + + def _compileTransition( + self, + transition, + font, + actionIndex, + stateArrayOffset, + glyphClassCount, + contextOffsets, + ligatureActionOffsets, + ): + newState = stateArrayOffset + transition.NewState * glyphClassCount + if not 0 <= newState <= 0xFFFF: + raise ValueError("mort new-state offset exceeds 16 bits") + + if issubclass(self.tableClass, ContextualMorphAction): + flags = transition.ReservedFlags + flags |= 0x8000 if transition.SetMark else 0 + flags |= 0x4000 if transition.DontAdvance else 0 + markOffset = ( + 0 + if transition.MarkIndex == 0xFFFF + else contextOffsets[transition.MarkIndex] + ) + currentOffset = ( + 0 + if transition.CurrentIndex == 0xFFFF + else contextOffsets[transition.CurrentIndex] + ) + return struct.pack(">HHhh", newState, flags, markOffset, currentOffset) + + if issubclass(self.tableClass, LigatureMorphAction): + if transition.ReservedFlags: + raise ValueError("mort ligature entries cannot encode reserved flags") + flags = 0x8000 if transition.SetComponent else 0 + flags |= 0x4000 if transition.DontAdvance else 0 + sequence = tuple( + (action.GlyphIndexDelta, action.Store) for action in transition.Actions + ) + flags |= ligatureActionOffsets.get(sequence, 0) + return struct.pack(">HH", newState, flags) + + transitionWriter = OTTableWriter() + transition.compile(transitionWriter, font, actionIndex) + data = transitionWriter.getAllData() + return struct.pack(">H", newState) + data[2:] + + +class MorphStateTable(BaseConverter): + """Dispatch to classic or extended AAT state-table encoding by table tag.""" + + def __init__(self, name, repeat, aux, tableClass, *, description=""): + BaseConverter.__init__( + self, name, repeat, aux, tableClass, description=description + ) + self.legacy = StateHeader( + name, repeat, aux, tableClass, description=description + ) + self.extended = STXHeader( + name, repeat, aux, tableClass, description=description + ) + + def _converter(self, tableTag): + return self.legacy if tableTag == "mort" else self.extended + + def read(self, reader, font, tableDict): + return self._converter(reader.tableTag).read(reader, font, tableDict) + + def write(self, writer, font, tableDict, value, repeatIndex=None): + return self._converter(writer.tableTag).write( + writer, font, tableDict, value, repeatIndex + ) + + def xmlRead(self, attrs, content, font): + return self.extended.xmlRead(attrs, content, font) + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + return self.extended.xmlWrite(xmlWriter, font, value, name, attrs) + + +class CIDGlyphMap(BaseConverter): + def read(self, reader, font, tableDict): + numCIDs = reader.readUShort() + result = {} + for cid, glyphID in enumerate(reader.readUShortArray(numCIDs)): + if glyphID != 0xFFFF: + result[cid] = font.getGlyphName(glyphID) + return result + + def write(self, writer, font, tableDict, value, repeatIndex=None): + items = {cid: font.getGlyphID(glyph) for cid, glyph in value.items()} + count = max(items) + 1 if items else 0 + writer.writeUShort(count) + for cid in range(count): + writer.writeUShort(items.get(cid, 0xFFFF)) + + def xmlRead(self, attrs, content, font): + result = {} + for eName, eAttrs, _eContent in filter(istuple, content): + if eName == "CID": + result[safeEval(eAttrs["cid"])] = eAttrs["glyph"].strip() + return result + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.begintag(name, attrs) + xmlWriter.newline() + for cid, glyph in sorted(value.items()): + if glyph is not None and glyph != 0xFFFF: + xmlWriter.simpletag("CID", cid=cid, glyph=glyph) + xmlWriter.newline() + xmlWriter.endtag(name) + xmlWriter.newline() + + +class GlyphCIDMap(BaseConverter): + def read(self, reader, font, tableDict): + glyphOrder = font.getGlyphOrder() + count = reader.readUShort() + cids = reader.readUShortArray(count) + if count > len(glyphOrder): + log.warning( + "GlyphCIDMap has %d elements, " + "but the font has only %d glyphs; " + "ignoring the rest" % (count, len(glyphOrder)) + ) + result = {} + for glyphID in range(min(len(cids), len(glyphOrder))): + cid = cids[glyphID] + if cid != 0xFFFF: + result[glyphOrder[glyphID]] = cid + return result + + def write(self, writer, font, tableDict, value, repeatIndex=None): + items = { + font.getGlyphID(g): cid + for g, cid in value.items() + if cid is not None and cid != 0xFFFF + } + count = max(items) + 1 if items else 0 + writer.writeUShort(count) + for glyphID in range(count): + writer.writeUShort(items.get(glyphID, 0xFFFF)) + + def xmlRead(self, attrs, content, font): + result = {} + for eName, eAttrs, _eContent in filter(istuple, content): + if eName == "CID": + result[eAttrs["glyph"]] = safeEval(eAttrs["value"]) + return result + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.begintag(name, attrs) + xmlWriter.newline() + for glyph, cid in sorted(value.items()): + if cid is not None and cid != 0xFFFF: + xmlWriter.simpletag("CID", glyph=glyph, value=cid) + xmlWriter.newline() + xmlWriter.endtag(name) + xmlWriter.newline() + + +class DeltaValue(BaseConverter): + def read(self, reader, font, tableDict): + StartSize = tableDict["StartSize"] + EndSize = tableDict["EndSize"] + DeltaFormat = tableDict["DeltaFormat"] + assert DeltaFormat in (1, 2, 3), "illegal DeltaFormat" + nItems = EndSize - StartSize + 1 + nBits = 1 << DeltaFormat + minusOffset = 1 << nBits + mask = (1 << nBits) - 1 + signMask = 1 << (nBits - 1) + + DeltaValue = [] + tmp, shift = 0, 0 + for i in range(nItems): + if shift == 0: + tmp, shift = reader.readUShort(), 16 + shift = shift - nBits + value = (tmp >> shift) & mask + if value & signMask: + value = value - minusOffset + DeltaValue.append(value) + return DeltaValue + + def write(self, writer, font, tableDict, value, repeatIndex=None): + StartSize = tableDict["StartSize"] + EndSize = tableDict["EndSize"] + DeltaFormat = tableDict["DeltaFormat"] + DeltaValue = value + assert DeltaFormat in (1, 2, 3), "illegal DeltaFormat" + nItems = EndSize - StartSize + 1 + nBits = 1 << DeltaFormat + assert len(DeltaValue) == nItems + mask = (1 << nBits) - 1 + + tmp, shift = 0, 16 + for value in DeltaValue: + shift = shift - nBits + tmp = tmp | ((value & mask) << shift) + if shift == 0: + writer.writeUShort(tmp) + tmp, shift = 0, 16 + if shift != 16: + writer.writeUShort(tmp) + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.simpletag(name, attrs + [("value", value)]) + xmlWriter.newline() + + def xmlRead(self, attrs, content, font): + return safeEval(attrs["value"]) + + +class VarIdxMapValue(BaseConverter): + def read(self, reader, font, tableDict): + fmt = tableDict["EntryFormat"] + nItems = tableDict["MappingCount"] + + innerBits = 1 + (fmt & 0x000F) + innerMask = (1 << innerBits) - 1 + outerMask = 0xFFFFFFFF - innerMask + outerShift = 16 - innerBits + + entrySize = 1 + ((fmt & 0x0030) >> 4) + readArray = { + 1: reader.readUInt8Array, + 2: reader.readUShortArray, + 3: reader.readUInt24Array, + 4: reader.readULongArray, + }[entrySize] + + return [ + (((raw & outerMask) << outerShift) | (raw & innerMask)) + for raw in readArray(nItems) + ] + + def write(self, writer, font, tableDict, value, repeatIndex=None): + fmt = tableDict["EntryFormat"] + mapping = value + writer["MappingCount"].setValue(len(mapping)) + + innerBits = 1 + (fmt & 0x000F) + innerMask = (1 << innerBits) - 1 + outerShift = 16 - innerBits + + entrySize = 1 + ((fmt & 0x0030) >> 4) + writeArray = { + 1: writer.writeUInt8Array, + 2: writer.writeUShortArray, + 3: writer.writeUInt24Array, + 4: writer.writeULongArray, + }[entrySize] + + writeArray( + [ + (((idx & 0xFFFF0000) >> outerShift) | (idx & innerMask)) + for idx in mapping + ] + ) + + +class VarDataValue(BaseConverter): + def read(self, reader, font, tableDict): + values = [] + + regionCount = tableDict["VarRegionCount"] + wordCount = tableDict["NumShorts"] + + # https://github.com/fonttools/fonttools/issues/2279 + longWords = bool(wordCount & 0x8000) + wordCount = wordCount & 0x7FFF + + if longWords: + readBigArray, readSmallArray = reader.readLongArray, reader.readShortArray + else: + readBigArray, readSmallArray = reader.readShortArray, reader.readInt8Array + + n1, n2 = min(regionCount, wordCount), max(regionCount, wordCount) + values.extend(readBigArray(n1)) + values.extend(readSmallArray(n2 - n1)) + if n2 > regionCount: # Padding + del values[regionCount:] + + return values + + def write(self, writer, font, tableDict, values, repeatIndex=None): + regionCount = tableDict["VarRegionCount"] + wordCount = tableDict["NumShorts"] + + # https://github.com/fonttools/fonttools/issues/2279 + longWords = bool(wordCount & 0x8000) + wordCount = wordCount & 0x7FFF + + writeBigArray, writeSmallArray = { + False: (writer.writeShortArray, writer.writeInt8Array), + True: (writer.writeLongArray, writer.writeShortArray), + }[longWords] + + n1, n2 = min(regionCount, wordCount), max(regionCount, wordCount) + writeBigArray(values[:n1]) + writeSmallArray(values[n1:regionCount]) + if n2 > regionCount: # Padding + writer.writeSmallArray([0] * (n2 - regionCount)) + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.simpletag(name, attrs + [("value", value)]) + xmlWriter.newline() + + def xmlRead(self, attrs, content, font): + return safeEval(attrs["value"]) + + +class TupleValues: + def read(self, data, font): + return TupleVariation.decompileDeltas_(None, data)[0] + + def write(self, writer, font, tableDict, values, repeatIndex=None): + optimizeSpeed = font.cfg[OPTIMIZE_FONT_SPEED] + return bytes( + TupleVariation.compileDeltaValues_(values, optimizeSize=not optimizeSpeed) + ) + + def xmlRead(self, attrs, content, font): + return safeEval(attrs["value"]) + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.simpletag(name, attrs + [("value", value)]) + xmlWriter.newline() + + +class CFF2Index(BaseConverter): + def __init__( + self, + name, + repeat, + aux, + tableClass=None, + *, + itemClass=None, + itemConverterClass=None, + description="", + ): + BaseConverter.__init__( + self, name, repeat, aux, tableClass, description=description + ) + self._itemClass = itemClass + self._converter = ( + itemConverterClass() if itemConverterClass is not None else None + ) + + def read(self, reader, font, tableDict): + count = reader.readULong() + if count == 0: + return [] + offSize = reader.readUInt8() + + def getReadArray(reader, offSize): + return { + 1: reader.readUInt8Array, + 2: reader.readUShortArray, + 3: reader.readUInt24Array, + 4: reader.readULongArray, + }[offSize] + + readArray = getReadArray(reader, offSize) + + lazy = font.lazy is not False and count > 8 + if not lazy: + offsets = readArray(count + 1) + items = [] + lastOffset = offsets.pop(0) + reader.readData(lastOffset - 1) # In case first offset is not 1 + + for offset in offsets: + assert lastOffset <= offset + item = reader.readData(offset - lastOffset) + + if self._itemClass is not None: + obj = self._itemClass() + obj.decompile(item, font, reader.localState) + item = obj + elif self._converter is not None: + item = self._converter.read(item, font) + + items.append(item) + lastOffset = offset + return items + else: + + def get_read_item(): + reader_copy = reader.copy() + offset_pos = reader.pos + data_pos = offset_pos + (count + 1) * offSize - 1 + readArray = getReadArray(reader_copy, offSize) + + def read_item(i): + reader_copy.seek(offset_pos + i * offSize) + offsets = readArray(2) + reader_copy.seek(data_pos + offsets[0]) + item = reader_copy.readData(offsets[1] - offsets[0]) + + if self._itemClass is not None: + obj = self._itemClass() + obj.decompile(item, font, reader_copy.localState) + item = obj + elif self._converter is not None: + item = self._converter.read(item, font) + return item + + return read_item + + read_item = get_read_item() + l = LazyList([read_item] * count) + + # TODO: Advance reader + + return l + + def write(self, writer, font, tableDict, values, repeatIndex=None): + items = values + + writer.writeULong(len(items)) + if not len(items): + return + + if self._itemClass is not None: + items = [item.compile(font) for item in items] + elif self._converter is not None: + items = [ + self._converter.write(writer, font, tableDict, item, i) + for i, item in enumerate(items) + ] + + offsets = [len(item) for item in items] + offsets = list(accumulate(offsets, initial=1)) + + lastOffset = offsets[-1] + offSize = ( + 1 + if lastOffset < 0x100 + else 2 if lastOffset < 0x10000 else 3 if lastOffset < 0x1000000 else 4 + ) + writer.writeUInt8(offSize) + + writeArray = { + 1: writer.writeUInt8Array, + 2: writer.writeUShortArray, + 3: writer.writeUInt24Array, + 4: writer.writeULongArray, + }[offSize] + + writeArray(offsets) + for item in items: + writer.writeData(item) + + def xmlRead(self, attrs, content, font): + if self._itemClass is not None: + obj = self._itemClass() + obj.fromXML(None, attrs, content, font) + return obj + elif self._converter is not None: + return self._converter.xmlRead(attrs, content, font) + else: + raise NotImplementedError() + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + if self._itemClass is not None: + for i, item in enumerate(value): + item.toXML(xmlWriter, font, [("index", i)], name) + elif self._converter is not None: + for i, item in enumerate(value): + self._converter.xmlWrite( + xmlWriter, font, item, name, attrs + [("index", i)] + ) + else: + raise NotImplementedError() + + +class LookupFlag(UShort): + def xmlWrite(self, xmlWriter, font, value, name, attrs): + xmlWriter.simpletag(name, attrs + [("value", value)]) + flags = [] + if value & 0x01: + flags.append("rightToLeft") + if value & 0x02: + flags.append("ignoreBaseGlyphs") + if value & 0x04: + flags.append("ignoreLigatures") + if value & 0x08: + flags.append("ignoreMarks") + if value & 0x10: + flags.append("useMarkFilteringSet") + if value & 0xFF00: + flags.append("markAttachmentType[%i]" % (value >> 8)) + if flags: + xmlWriter.comment(" ".join(flags)) + xmlWriter.newline() + + +class _UInt8Enum(UInt8): + enumClass = NotImplemented + + def read(self, reader, font, tableDict): + return self.enumClass(super().read(reader, font, tableDict)) + + @classmethod + def fromString(cls, value): + return getattr(cls.enumClass, value.upper()) + + @classmethod + def toString(cls, value): + return cls.enumClass(value).name.lower() + + +class ExtendMode(_UInt8Enum): + enumClass = _ExtendMode + + +class CompositeMode(_UInt8Enum): + enumClass = _CompositeMode + + +class MappingEntryFormat(IntFlag): + HAS_SUBSET_DEF = 0x01 + HAS_CHILD_ENTRIES = 0x02 + HAS_ENTRY_ID = 0x04 + HAS_PATCH_FORMAT = 0x08 + # The code point bias is essentially a 2bit flag. + CODE_POINT_BIAS_BITS = 0x30 + + @property + def bias_present_u16(self): + return (self & MappingEntryFormat.CODE_POINT_BIAS_BITS) == 0x20 + + @property + def bias_present_u24(self): + return (self & MappingEntryFormat.CODE_POINT_BIAS_BITS) == 0x30 + + +# Reference implementation: +# https://github.com/googlefonts/fontations/blob/main/read-fonts/src/tables/ift.rs +class MappingEntriesConverter(BaseConverter): + def read(self, reader, font, tableDict): + from fontTools.misc.fixedTools import fixedToFloat as fi2fl + from fontTools.misc.iftSparseBitSet import decode as sbsDecode + + entryCount = reader["NumEntries"] + entries = [] + lastEntryId = -1 + + for _ in range(entryCount): + entry = {} + formatFlags = MappingEntryFormat(reader.readUInt8()) + entry["formatFlags"] = formatFlags + + if formatFlags & MappingEntryFormat.HAS_SUBSET_DEF: + featureCount = reader.readUInt8() + features = [] + for _ in range(featureCount): + tag = reader.readTag() + features.append(tag) + entry["featureTags"] = features + designSpaceCount = reader.readUShort() + segments = [] + for _ in range(designSpaceCount): + segTag = reader.readTag() + start = fi2fl(reader.readLong(), 16) + end = fi2fl(reader.readLong(), 16) + segments.append({"tag": segTag, "start": start, "end": end}) + entry["designSpaceSegments"] = segments + + if formatFlags & MappingEntryFormat.HAS_CHILD_ENTRIES: + modeAndCount = reader.readUInt8() + conjunctive = bool(modeAndCount & 0x80) + childCount = modeAndCount & 0x7F + entry["childEntryConjunctive"] = conjunctive + childIndices = [] + for _ in range(childCount): + idx = reader.readUInt24() + childIndices.append(idx) + entry["childEntryIndices"] = childIndices + + if formatFlags & MappingEntryFormat.HAS_ENTRY_ID: + ids = [] + while True: + # Per IFT spec, Entry IDs are delta-encoded. The value is a + # signed 24-bit integer. The least significant bit is a + # continuation flag (1 if more IDs follow). The remaining + # upper bits are a signed integer, representing the delta + # from the previous ID. + encodedVal = reader.readInt24() + delta = encodedVal >> 1 + hasMore = encodedVal & 0x01 + currentEntryId = lastEntryId + 1 + delta + ids.append(currentEntryId) + lastEntryId = currentEntryId + + if not hasMore: + break + entry["entryIds"] = ids + else: + entry["entryIds"] = [lastEntryId + 1] + lastEntryId = lastEntryId + 1 + + if formatFlags & MappingEntryFormat.HAS_PATCH_FORMAT: + entry["patchFormat"] = reader.readUInt8() + + if formatFlags & MappingEntryFormat.CODE_POINT_BIAS_BITS: + bias = 0 + if formatFlags.bias_present_u24: + bias = reader.readUInt24() + elif formatFlags.bias_present_u16: + bias = reader.readUShort() + entry["codePointsBias"] = bias + + codepoints, consumed = sbsDecode( + reader.data[reader.pos :], bias=bias, maxValue=0x10FFFF + ) + reader.advance(consumed) + entry["codePoints"] = sorted(codepoints) + + entries.append(entry) + return entries + + def write(self, writer, font, tableDict, value, repeatIndex=None): + from fontTools.misc.iftSparseBitSet import encode as sbsEncode + from fontTools.misc.fixedTools import floatToFixed as fl2fi + + entries = value + lastId = -1 + + for entry in entries: + # TODO: Automatically recompute formatFlags based on the contents of + # entry. + formatFlags = entry.get("formatFlags", MappingEntryFormat(0)) + writer.writeUInt8(formatFlags.value) + + if formatFlags & MappingEntryFormat.HAS_SUBSET_DEF: + features = entry.get("featureTags", []) + writer.writeUInt8(len(features)) + for tag in features: + writer.writeTag(tag) + segments = entry.get("designSpaceSegments", []) + writer.writeUShort(len(segments)) + for seg in segments: + writer.writeTag(seg["tag"]) + writer.writeLong(fl2fi(seg["start"], 16)) + writer.writeLong(fl2fi(seg["end"], 16)) + + if formatFlags & MappingEntryFormat.HAS_CHILD_ENTRIES: + childIndices = entry.get("childEntryIndices", []) + conjunctive = entry.get("childEntryConjunctive", False) + modeAndCount = (len(childIndices) & 0x7F) | (0x80 if conjunctive else 0) + writer.writeUInt8(modeAndCount) + for idx in childIndices: + writer.writeUInt24(idx) + + if formatFlags & MappingEntryFormat.HAS_ENTRY_ID: + ids = entry.get("entryIds", []) + for i, eid in enumerate(ids): + # Recreate the delta-encoded Entry ID. The delta is shifted + # left by one bit, and the least significant bit is set to 1 + # if more IDs follow in the list. + delta = eid - lastId - 1 + has_more = 1 if i < len(ids) - 1 else 0 + encoded_value = (delta << 1) | has_more + writer.writeUInt24(encoded_value & 0xFFFFFF) + lastId = eid + else: + lastId += 1 + + if formatFlags & MappingEntryFormat.HAS_PATCH_FORMAT: + writer.writeUInt8(entry.get("patchFormat", 0)) + + if formatFlags & MappingEntryFormat.CODE_POINT_BIAS_BITS: + bias = entry.get("codePointsBias", 0) + if formatFlags.bias_present_u24: + writer.writeUInt24(bias) + elif formatFlags.bias_present_u16: + writer.writeUShort(bias) + codepoints = entry.get("codePoints", []) + writer.writeData(sbsEncode([c - bias for c in codepoints if c >= bias])) + + def xmlWrite(self, xmlWriter, font, value, name, attrs): + for entry in value: + format_flags = entry.get("formatFlags", MappingEntryFormat(0)) + xmlWriter.begintag("entry", formatFlags=format_flags.value) + xmlWriter.newline() + if "entryIds" in entry: + for eid in entry["entryIds"]: + xmlWriter.simpletag("entryId", value=eid) + xmlWriter.newline() + if "featureTags" in entry: + for tag in entry["featureTags"]: + xmlWriter.simpletag("featureTag", value=tag) + xmlWriter.newline() + if "designSpaceSegments" in entry: + for seg in entry["designSpaceSegments"]: + xmlWriter.simpletag( + "designSpaceSegment", + tag=seg["tag"], + start=seg["start"], + end=seg["end"], + ) + xmlWriter.newline() + if "childEntryIndices" in entry: + xmlWriter.simpletag( + "childEntryConjunctive", + value=int(entry.get("childEntryConjunctive", False)), + ) + xmlWriter.newline() + for idx in entry["childEntryIndices"]: + xmlWriter.simpletag("childEntry", index=idx) + xmlWriter.newline() + if "patchFormat" in entry: + xmlWriter.simpletag("patchFormat", value=entry["patchFormat"]) + xmlWriter.newline() + if "codePoints" in entry: + xmlWriter.simpletag( + "codePointsBias", value=entry.get("codePointsBias", 0) + ) + xmlWriter.newline() + codePointsStr = " ".join(str(c) for c in entry["codePoints"]) + xmlWriter.simpletag("codePoints", value=codePointsStr) + xmlWriter.newline() + xmlWriter.endtag("entry") + xmlWriter.newline() + + def xmlRead(self, attrs, content, font): + entries = [] + for elem in content: + if not isinstance(elem, tuple): + continue + name, attrs, content = elem + if name == "entry": + format_flags_int = safeEval(attrs.get("formatFlags", "0")) + entry = {"formatFlags": MappingEntryFormat(format_flags_int)} + for e_elem in content: + if not isinstance(e_elem, tuple): + continue + ename, eattrs, econtent = e_elem + if ename == "entryId": + entry.setdefault("entryIds", []).append( + safeEval(eattrs["value"]) + ) + elif ename == "featureTag": + entry.setdefault("featureTags", []).append(eattrs["value"]) + elif ename == "designSpaceSegment": + entry.setdefault("designSpaceSegments", []).append( + { + "tag": eattrs["tag"], + "start": float(eattrs["start"]), + "end": float(eattrs["end"]), + } + ) + elif ename == "childEntryConjunctive": + entry["childEntryConjunctive"] = bool(safeEval(eattrs["value"])) + elif ename == "childEntry": + entry.setdefault("childEntryIndices", []).append( + safeEval(eattrs["index"]) + ) + elif ename == "patchFormat": + entry["patchFormat"] = safeEval(eattrs["value"]) + elif ename == "codePointsBias": + entry["codePointsBias"] = safeEval(eattrs["value"]) + elif ename == "codePoints": + entry["codePoints"] = [ + int(c) for c in eattrs["value"].split() if c + ] + entries.append(entry) + return entries + + +converterMapping = { + # type class + "int8": Int8, + "int16": Short, + "int32": Long, + "uint8": UInt8, + "uint16": UShort, + "uint24": UInt24, + "uint32": ULong, + "char64": Char64, + "Flags32": Flags32, + "VarIndex": VarIndex, + "Version": Version, + "Tag": Tag, + "GlyphID": GlyphID, + "GlyphID32": GlyphID32, + "NameID": NameID, + "DeciPoints": DeciPoints, + "Fixed": Fixed, + "F2Dot14": F2Dot14, + "Angle": Angle, + "BiasedAngle": BiasedAngle, + "struct": Struct, + "MappingEntries": MappingEntriesConverter, + "Offset": Table, + "LOffset": LTable, + "Offset24": Table24, + "ValueRecord": ValueRecord, + "DeltaValue": DeltaValue, + "VarIdxMapValue": VarIdxMapValue, + "VarDataValue": VarDataValue, + "LookupFlag": LookupFlag, + "ExtendMode": ExtendMode, + "CompositeMode": CompositeMode, + "STATFlags": STATFlags, + "TupleList": partial(CFF2Index, itemConverterClass=TupleValues), + "VarCompositeGlyphList": partial(CFF2Index, itemClass=VarCompositeGlyph), + # AAT + "CIDGlyphMap": CIDGlyphMap, + "GlyphCIDMap": GlyphCIDMap, + "MortChain": StructWithLength, + "MortSubtable": MortSubtableConverter, + "MorxChain": StructWithLength, + "MorxSubtable": MorxSubtableConverter, + # "Template" types + "AATLookup": lambda C: partial(AATLookup, tableClass=C), + "AATLookupWithDataOffset": lambda C: partial(AATLookupWithDataOffset, tableClass=C), + "MorphStateTable": lambda C: partial(MorphStateTable, tableClass=C), + "STXHeader": lambda C: partial(STXHeader, tableClass=C), + "OffsetTo": lambda C: partial(Table, tableClass=C), + "LOffsetTo": lambda C: partial(LTable, tableClass=C), + "LOffset24To": lambda C: partial(Table24, tableClass=C), +} diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otData.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otData.py new file mode 100644 index 0000000000000000000000000000000000000000..1db0e853137ba10e0b2fb18e0d2862ad16d77e8e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otData.py @@ -0,0 +1,5983 @@ +from .otDataSchema import FieldSpec + +otData = [ + # + # common + # + ("LookupOrder", []), + ( + "ScriptList", + [ + FieldSpec("uint16", "ScriptCount", description="Number of ScriptRecords"), + FieldSpec( + "struct", + "ScriptRecord", + repeat="ScriptCount", + aux=0, + description="Array of ScriptRecords -listed alphabetically by ScriptTag", + ), + ], + ), + ( + "ScriptRecord", + [ + FieldSpec("Tag", "ScriptTag", description="4-byte ScriptTag identifier"), + FieldSpec( + "Offset", + "Script", + description="Offset to Script table-from beginning of ScriptList", + ), + ], + ), + ( + "Script", + [ + FieldSpec( + "Offset", + "DefaultLangSys", + description="Offset to DefaultLangSys table-from beginning of Script table-may be NULL", + ), + FieldSpec( + "uint16", + "LangSysCount", + description="Number of LangSysRecords for this script-excluding the DefaultLangSys", + ), + FieldSpec( + "struct", + "LangSysRecord", + repeat="LangSysCount", + aux=0, + description="Array of LangSysRecords-listed alphabetically by LangSysTag", + ), + ], + ), + ( + "LangSysRecord", + [ + FieldSpec("Tag", "LangSysTag", description="4-byte LangSysTag identifier"), + FieldSpec( + "Offset", + "LangSys", + description="Offset to LangSys table-from beginning of Script table", + ), + ], + ), + ( + "LangSys", + [ + FieldSpec( + "Offset", + "LookupOrder", + description="= NULL (reserved for an offset to a reordering table)", + ), + FieldSpec( + "uint16", + "ReqFeatureIndex", + description="Index of a feature required for this language system- if no required features = 0xFFFF", + ), + FieldSpec( + "uint16", + "FeatureCount", + description="Number of FeatureIndex values for this language system-excludes the required feature", + ), + FieldSpec( + "uint16", + "FeatureIndex", + repeat="FeatureCount", + aux=0, + description="Array of indices into the FeatureList-in arbitrary order", + ), + ], + ), + ( + "FeatureList", + [ + FieldSpec( + "uint16", + "FeatureCount", + description="Number of FeatureRecords in this table", + ), + FieldSpec( + "struct", + "FeatureRecord", + repeat="FeatureCount", + aux=0, + description="Array of FeatureRecords-zero-based (first feature has FeatureIndex = 0)-listed alphabetically by FeatureTag", + ), + ], + ), + ( + "FeatureRecord", + [ + FieldSpec( + "Tag", "FeatureTag", description="4-byte feature identification tag" + ), + FieldSpec( + "Offset", + "Feature", + description="Offset to Feature table-from beginning of FeatureList", + ), + ], + ), + ( + "Feature", + [ + FieldSpec( + "Offset", + "FeatureParams", + description="= NULL (reserved for offset to FeatureParams)", + ), + FieldSpec( + "uint16", + "LookupCount", + description="Number of LookupList indices for this feature", + ), + FieldSpec( + "uint16", + "LookupListIndex", + repeat="LookupCount", + aux=0, + description="Array of LookupList indices for this feature -zero-based (first lookup is LookupListIndex = 0)", + ), + ], + ), + ("FeatureParams", []), + ( + "FeatureParamsSize", + [ + FieldSpec( + "DeciPoints", + "DesignSize", + description="The design size in 720/inch units (decipoints).", + ), + FieldSpec( + "uint16", + "SubfamilyID", + description="Serves as an identifier that associates fonts in a subfamily.", + ), + FieldSpec("NameID", "SubfamilyNameID", description="Subfamily NameID."), + FieldSpec( + "DeciPoints", + "RangeStart", + description="Small end of recommended usage range (exclusive) in 720/inch units.", + ), + FieldSpec( + "DeciPoints", + "RangeEnd", + description="Large end of recommended usage range (inclusive) in 720/inch units.", + ), + ], + ), + ( + "FeatureParamsStylisticSet", + [ + FieldSpec("uint16", "Version", description="Set to 0."), + FieldSpec("NameID", "UINameID", description="UI NameID."), + ], + ), + ( + "FeatureParamsCharacterVariants", + [ + FieldSpec("uint16", "Format", description="Set to 0."), + FieldSpec( + "NameID", "FeatUILabelNameID", description="Feature UI label NameID." + ), + FieldSpec( + "NameID", + "FeatUITooltipTextNameID", + description="Feature UI tooltip text NameID.", + ), + FieldSpec("NameID", "SampleTextNameID", description="Sample text NameID."), + FieldSpec( + "uint16", + "NumNamedParameters", + description="Number of named parameters.", + ), + FieldSpec( + "NameID", + "FirstParamUILabelNameID", + description="First NameID of UI feature parameters.", + ), + FieldSpec( + "uint16", + "CharCount", + description="Count of characters this feature provides glyph variants for.", + ), + FieldSpec( + "uint24", + "Character", + repeat="CharCount", + aux=0, + description="Unicode characters for which this feature provides glyph variants.", + ), + ], + ), + ( + "LookupList", + [ + FieldSpec( + "uint16", "LookupCount", description="Number of lookups in this table" + ), + FieldSpec( + "Offset", + "Lookup", + repeat="LookupCount", + aux=0, + description="Array of offsets to Lookup tables-from beginning of LookupList -zero based (first lookup is Lookup index = 0)", + ), + ], + ), + ( + "Lookup", + [ + FieldSpec( + "uint16", + "LookupType", + description="Different enumerations for GSUB and GPOS", + ), + FieldSpec("LookupFlag", "LookupFlag", description="Lookup qualifiers"), + FieldSpec( + "uint16", + "SubTableCount", + description="Number of SubTables for this lookup", + ), + FieldSpec( + "Offset", + "SubTable", + repeat="SubTableCount", + aux=0, + description="Array of offsets to SubTables-from beginning of Lookup table", + ), + FieldSpec( + "uint16", + "MarkFilteringSet", + aux="LookupFlag & 0x0010", + description="If set, indicates that the lookup table structure is followed by a MarkFilteringSet field. The layout engine skips over all mark glyphs not in the mark filtering set indicated.", + ), + ], + ), + ( + "CoverageFormat1", + [ + FieldSpec( + "uint16", "CoverageFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "uint16", "GlyphCount", description="Number of glyphs in the GlyphArray" + ), + FieldSpec( + "GlyphID", + "GlyphArray", + repeat="GlyphCount", + aux=0, + description="Array of GlyphIDs-in numerical order", + ), + ], + ), + ( + "CoverageFormat2", + [ + FieldSpec( + "uint16", "CoverageFormat", description="Format identifier-format = 2" + ), + FieldSpec("uint16", "RangeCount", description="Number of RangeRecords"), + FieldSpec( + "struct", + "RangeRecord", + repeat="RangeCount", + aux=0, + description="Array of glyph ranges-ordered by Start GlyphID", + ), + ], + ), + ( + "RangeRecord", + [ + FieldSpec("GlyphID", "Start", description="First GlyphID in the range"), + FieldSpec("GlyphID", "End", description="Last GlyphID in the range"), + FieldSpec( + "uint16", + "StartCoverageIndex", + description="Coverage Index of first GlyphID in range", + ), + ], + ), + ( + "ClassDefFormat1", + [ + FieldSpec( + "uint16", "ClassFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "GlyphID", + "StartGlyph", + description="First GlyphID of the ClassValueArray", + ), + FieldSpec( + "uint16", "GlyphCount", description="Size of the ClassValueArray" + ), + FieldSpec( + "uint16", + "ClassValueArray", + repeat="GlyphCount", + aux=0, + description="Array of Class Values-one per GlyphID", + ), + ], + ), + ( + "ClassDefFormat2", + [ + FieldSpec( + "uint16", "ClassFormat", description="Format identifier-format = 2" + ), + FieldSpec( + "uint16", "ClassRangeCount", description="Number of ClassRangeRecords" + ), + FieldSpec( + "struct", + "ClassRangeRecord", + repeat="ClassRangeCount", + aux=0, + description="Array of ClassRangeRecords-ordered by Start GlyphID", + ), + ], + ), + ( + "ClassRangeRecord", + [ + FieldSpec("GlyphID", "Start", description="First GlyphID in the range"), + FieldSpec("GlyphID", "End", description="Last GlyphID in the range"), + FieldSpec( + "uint16", "Class", description="Applied to all glyphs in the range" + ), + ], + ), + ( + "Device", + [ + FieldSpec( + "uint16", "StartSize", description="Smallest size to correct-in ppem" + ), + FieldSpec( + "uint16", "EndSize", description="Largest size to correct-in ppem" + ), + FieldSpec( + "uint16", + "DeltaFormat", + description="Format of DeltaValue array data: 1, 2, or 3", + ), + FieldSpec( + "DeltaValue", + "DeltaValue", + aux="DeltaFormat in (1,2,3)", + description="Array of compressed data", + ), + ], + ), + # + # gpos + # + ( + "GPOS", + [ + FieldSpec( + "Version", + "Version", + description="Version of the GPOS table- 0x00010000 or 0x00010001", + ), + FieldSpec( + "Offset", + "ScriptList", + description="Offset to ScriptList table-from beginning of GPOS table", + ), + FieldSpec( + "Offset", + "FeatureList", + description="Offset to FeatureList table-from beginning of GPOS table", + ), + FieldSpec( + "Offset", + "LookupList", + description="Offset to LookupList table-from beginning of GPOS table", + ), + FieldSpec( + "LOffset", + "FeatureVariations", + aux="Version >= 0x00010001", + description="Offset to FeatureVariations table-from beginning of GPOS table", + ), + ], + ), + ( + "SinglePosFormat1", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of SinglePos subtable", + ), + FieldSpec( + "uint16", + "ValueFormat", + description="Defines the types of data in the ValueRecord", + ), + FieldSpec( + "ValueRecord", + "Value", + description="Defines positioning value(s)-applied to all glyphs in the Coverage table", + ), + ], + ), + ( + "SinglePosFormat2", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 2" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of SinglePos subtable", + ), + FieldSpec( + "uint16", + "ValueFormat", + description="Defines the types of data in the ValueRecord", + ), + FieldSpec("uint16", "ValueCount", description="Number of ValueRecords"), + FieldSpec( + "ValueRecord", + "Value", + repeat="ValueCount", + aux=0, + description="Array of ValueRecords-positioning values applied to glyphs", + ), + ], + ), + ( + "PairPosFormat1", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of PairPos subtable-only the first glyph in each pair", + ), + FieldSpec( + "uint16", + "ValueFormat1", + description="Defines the types of data in ValueRecord1-for the first glyph in the pair -may be zero (0)", + ), + FieldSpec( + "uint16", + "ValueFormat2", + description="Defines the types of data in ValueRecord2-for the second glyph in the pair -may be zero (0)", + ), + FieldSpec("uint16", "PairSetCount", description="Number of PairSet tables"), + FieldSpec( + "Offset", + "PairSet", + repeat="PairSetCount", + aux=0, + description="Array of offsets to PairSet tables-from beginning of PairPos subtable-ordered by Coverage Index", + ), + ], + ), + ( + "PairSet", + [ + FieldSpec( + "uint16", "PairValueCount", description="Number of PairValueRecords" + ), + FieldSpec( + "struct", + "PairValueRecord", + repeat="PairValueCount", + aux=0, + description="Array of PairValueRecords-ordered by GlyphID of the second glyph", + ), + ], + ), + ( + "PairValueRecord", + [ + FieldSpec( + "GlyphID", + "SecondGlyph", + description="GlyphID of second glyph in the pair-first glyph is listed in the Coverage table", + ), + FieldSpec( + "ValueRecord", + "Value1", + description="Positioning data for the first glyph in the pair", + ), + FieldSpec( + "ValueRecord", + "Value2", + description="Positioning data for the second glyph in the pair", + ), + ], + ), + ( + "PairPosFormat2", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 2" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of PairPos subtable-for the first glyph of the pair", + ), + FieldSpec( + "uint16", + "ValueFormat1", + description="ValueRecord definition-for the first glyph of the pair-may be zero (0)", + ), + FieldSpec( + "uint16", + "ValueFormat2", + description="ValueRecord definition-for the second glyph of the pair-may be zero (0)", + ), + FieldSpec( + "Offset", + "ClassDef1", + description="Offset to ClassDef table-from beginning of PairPos subtable-for the first glyph of the pair", + ), + FieldSpec( + "Offset", + "ClassDef2", + description="Offset to ClassDef table-from beginning of PairPos subtable-for the second glyph of the pair", + ), + FieldSpec( + "uint16", + "Class1Count", + description="Number of classes in ClassDef1 table-includes Class0", + ), + FieldSpec( + "uint16", + "Class2Count", + description="Number of classes in ClassDef2 table-includes Class0", + ), + FieldSpec( + "struct", + "Class1Record", + repeat="Class1Count", + aux=0, + description="Array of Class1 records-ordered by Class1", + ), + ], + ), + ( + "Class1Record", + [ + FieldSpec( + "struct", + "Class2Record", + repeat="Class2Count", + aux=0, + description="Array of Class2 records-ordered by Class2", + ), + ], + ), + ( + "Class2Record", + [ + FieldSpec( + "ValueRecord", + "Value1", + description="Positioning for first glyph-empty if ValueFormat1 = 0", + ), + FieldSpec( + "ValueRecord", + "Value2", + description="Positioning for second glyph-empty if ValueFormat2 = 0", + ), + ], + ), + ( + "CursivePosFormat1", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of CursivePos subtable", + ), + FieldSpec( + "uint16", "EntryExitCount", description="Number of EntryExit records" + ), + FieldSpec( + "struct", + "EntryExitRecord", + repeat="EntryExitCount", + aux=0, + description="Array of EntryExit records-in Coverage Index order", + ), + ], + ), + ( + "EntryExitRecord", + [ + FieldSpec( + "Offset", + "EntryAnchor", + description="Offset to EntryAnchor table-from beginning of CursivePos subtable-may be NULL", + ), + FieldSpec( + "Offset", + "ExitAnchor", + description="Offset to ExitAnchor table-from beginning of CursivePos subtable-may be NULL", + ), + ], + ), + ( + "MarkBasePosFormat1", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "MarkCoverage", + description="Offset to MarkCoverage table-from beginning of MarkBasePos subtable", + ), + FieldSpec( + "Offset", + "BaseCoverage", + description="Offset to BaseCoverage table-from beginning of MarkBasePos subtable", + ), + FieldSpec( + "uint16", + "ClassCount", + description="Number of classes defined for marks", + ), + FieldSpec( + "Offset", + "MarkArray", + description="Offset to MarkArray table-from beginning of MarkBasePos subtable", + ), + FieldSpec( + "Offset", + "BaseArray", + description="Offset to BaseArray table-from beginning of MarkBasePos subtable", + ), + ], + ), + ( + "BaseArray", + [ + FieldSpec("uint16", "BaseCount", description="Number of BaseRecords"), + FieldSpec( + "struct", + "BaseRecord", + repeat="BaseCount", + aux=0, + description="Array of BaseRecords-in order of BaseCoverage Index", + ), + ], + ), + ( + "BaseRecord", + [ + FieldSpec( + "Offset", + "BaseAnchor", + repeat="ClassCount", + aux=0, + description="Array of offsets (one per class) to Anchor tables-from beginning of BaseArray table-ordered by class-zero-based", + ), + ], + ), + ( + "MarkLigPosFormat1", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "MarkCoverage", + description="Offset to Mark Coverage table-from beginning of MarkLigPos subtable", + ), + FieldSpec( + "Offset", + "LigatureCoverage", + description="Offset to Ligature Coverage table-from beginning of MarkLigPos subtable", + ), + FieldSpec( + "uint16", "ClassCount", description="Number of defined mark classes" + ), + FieldSpec( + "Offset", + "MarkArray", + description="Offset to MarkArray table-from beginning of MarkLigPos subtable", + ), + FieldSpec( + "Offset", + "LigatureArray", + description="Offset to LigatureArray table-from beginning of MarkLigPos subtable", + ), + ], + ), + ( + "LigatureArray", + [ + FieldSpec( + "uint16", + "LigatureCount", + description="Number of LigatureAttach table offsets", + ), + FieldSpec( + "Offset", + "LigatureAttach", + repeat="LigatureCount", + aux=0, + description="Array of offsets to LigatureAttach tables-from beginning of LigatureArray table-ordered by LigatureCoverage Index", + ), + ], + ), + ( + "LigatureAttach", + [ + FieldSpec( + "uint16", + "ComponentCount", + description="Number of ComponentRecords in this ligature", + ), + FieldSpec( + "struct", + "ComponentRecord", + repeat="ComponentCount", + aux=0, + description="Array of Component records-ordered in writing direction", + ), + ], + ), + ( + "ComponentRecord", + [ + FieldSpec( + "Offset", + "LigatureAnchor", + repeat="ClassCount", + aux=0, + description="Array of offsets (one per class) to Anchor tables-from beginning of LigatureAttach table-ordered by class-NULL if a component does not have an attachment for a class-zero-based array", + ), + ], + ), + ( + "MarkMarkPosFormat1", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Mark1Coverage", + description="Offset to Combining Mark Coverage table-from beginning of MarkMarkPos subtable", + ), + FieldSpec( + "Offset", + "Mark2Coverage", + description="Offset to Base Mark Coverage table-from beginning of MarkMarkPos subtable", + ), + FieldSpec( + "uint16", + "ClassCount", + description="Number of Combining Mark classes defined", + ), + FieldSpec( + "Offset", + "Mark1Array", + description="Offset to MarkArray table for Mark1-from beginning of MarkMarkPos subtable", + ), + FieldSpec( + "Offset", + "Mark2Array", + description="Offset to Mark2Array table for Mark2-from beginning of MarkMarkPos subtable", + ), + ], + ), + ( + "Mark2Array", + [ + FieldSpec("uint16", "Mark2Count", description="Number of Mark2 records"), + FieldSpec( + "struct", + "Mark2Record", + repeat="Mark2Count", + aux=0, + description="Array of Mark2 records-in Coverage order", + ), + ], + ), + ( + "Mark2Record", + [ + FieldSpec( + "Offset", + "Mark2Anchor", + repeat="ClassCount", + aux=0, + description="Array of offsets (one per class) to Anchor tables-from beginning of Mark2Array table-zero-based array", + ), + ], + ), + ( + "PosLookupRecord", + [ + FieldSpec( + "uint16", + "SequenceIndex", + description="Index to input glyph sequence-first glyph = 0", + ), + FieldSpec( + "uint16", + "LookupListIndex", + description="Lookup to apply to that position-zero-based", + ), + ], + ), + ( + "ContextPosFormat1", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of ContextPos subtable", + ), + FieldSpec( + "uint16", "PosRuleSetCount", description="Number of PosRuleSet tables" + ), + FieldSpec( + "Offset", + "PosRuleSet", + repeat="PosRuleSetCount", + aux=0, + description="Array of offsets to PosRuleSet tables-from beginning of ContextPos subtable-ordered by Coverage Index", + ), + ], + ), + ( + "PosRuleSet", + [ + FieldSpec("uint16", "PosRuleCount", description="Number of PosRule tables"), + FieldSpec( + "Offset", + "PosRule", + repeat="PosRuleCount", + aux=0, + description="Array of offsets to PosRule tables-from beginning of PosRuleSet-ordered by preference", + ), + ], + ), + ( + "PosRule", + [ + FieldSpec( + "uint16", + "GlyphCount", + description="Number of glyphs in the Input glyph sequence", + ), + FieldSpec("uint16", "PosCount", description="Number of PosLookupRecords"), + FieldSpec( + "GlyphID", + "Input", + repeat="GlyphCount", + aux=-1, + description="Array of input GlyphIDs-starting with the second glyph", + ), + FieldSpec( + "struct", + "PosLookupRecord", + repeat="PosCount", + aux=0, + description="Array of positioning lookups-in design order", + ), + ], + ), + ( + "ContextPosFormat2", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 2" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of ContextPos subtable", + ), + FieldSpec( + "Offset", + "ClassDef", + description="Offset to ClassDef table-from beginning of ContextPos subtable", + ), + FieldSpec( + "uint16", "PosClassSetCount", description="Number of PosClassSet tables" + ), + FieldSpec( + "Offset", + "PosClassSet", + repeat="PosClassSetCount", + aux=0, + description="Array of offsets to PosClassSet tables-from beginning of ContextPos subtable-ordered by class-may be NULL", + ), + ], + ), + ( + "PosClassSet", + [ + FieldSpec( + "uint16", + "PosClassRuleCount", + description="Number of PosClassRule tables", + ), + FieldSpec( + "Offset", + "PosClassRule", + repeat="PosClassRuleCount", + aux=0, + description="Array of offsets to PosClassRule tables-from beginning of PosClassSet-ordered by preference", + ), + ], + ), + ( + "PosClassRule", + [ + FieldSpec( + "uint16", "GlyphCount", description="Number of glyphs to be matched" + ), + FieldSpec("uint16", "PosCount", description="Number of PosLookupRecords"), + FieldSpec( + "uint16", + "Class", + repeat="GlyphCount", + aux=-1, + description="Array of classes-beginning with the second class-to be matched to the input glyph sequence", + ), + FieldSpec( + "struct", + "PosLookupRecord", + repeat="PosCount", + aux=0, + description="Array of positioning lookups-in design order", + ), + ], + ), + ( + "ContextPosFormat3", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 3" + ), + FieldSpec( + "uint16", + "GlyphCount", + description="Number of glyphs in the input sequence", + ), + FieldSpec("uint16", "PosCount", description="Number of PosLookupRecords"), + FieldSpec( + "Offset", + "Coverage", + repeat="GlyphCount", + aux=0, + description="Array of offsets to Coverage tables-from beginning of ContextPos subtable", + ), + FieldSpec( + "struct", + "PosLookupRecord", + repeat="PosCount", + aux=0, + description="Array of positioning lookups-in design order", + ), + ], + ), + ( + "ChainContextPosFormat1", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of ContextPos subtable", + ), + FieldSpec( + "uint16", + "ChainPosRuleSetCount", + description="Number of ChainPosRuleSet tables", + ), + FieldSpec( + "Offset", + "ChainPosRuleSet", + repeat="ChainPosRuleSetCount", + aux=0, + description="Array of offsets to ChainPosRuleSet tables-from beginning of ContextPos subtable-ordered by Coverage Index", + ), + ], + ), + ( + "ChainPosRuleSet", + [ + FieldSpec( + "uint16", + "ChainPosRuleCount", + description="Number of ChainPosRule tables", + ), + FieldSpec( + "Offset", + "ChainPosRule", + repeat="ChainPosRuleCount", + aux=0, + description="Array of offsets to ChainPosRule tables-from beginning of ChainPosRuleSet-ordered by preference", + ), + ], + ), + ( + "ChainPosRule", + [ + FieldSpec( + "uint16", + "BacktrackGlyphCount", + description="Total number of glyphs in the backtrack sequence (number of glyphs to be matched before the first glyph)", + ), + FieldSpec( + "GlyphID", + "Backtrack", + repeat="BacktrackGlyphCount", + aux=0, + description="Array of backtracking GlyphID's (to be matched before the input sequence)", + ), + FieldSpec( + "uint16", + "InputGlyphCount", + description="Total number of glyphs in the input sequence (includes the first glyph)", + ), + FieldSpec( + "GlyphID", + "Input", + repeat="InputGlyphCount", + aux=-1, + description="Array of input GlyphIDs (start with second glyph)", + ), + FieldSpec( + "uint16", + "LookAheadGlyphCount", + description="Total number of glyphs in the look ahead sequence (number of glyphs to be matched after the input sequence)", + ), + FieldSpec( + "GlyphID", + "LookAhead", + repeat="LookAheadGlyphCount", + aux=0, + description="Array of lookahead GlyphID's (to be matched after the input sequence)", + ), + FieldSpec("uint16", "PosCount", description="Number of PosLookupRecords"), + FieldSpec( + "struct", + "PosLookupRecord", + repeat="PosCount", + aux=0, + description="Array of PosLookupRecords (in design order)", + ), + ], + ), + ( + "ChainContextPosFormat2", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 2" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of ChainContextPos subtable", + ), + FieldSpec( + "Offset", + "BacktrackClassDef", + description="Offset to ClassDef table containing backtrack sequence context-from beginning of ChainContextPos subtable", + ), + FieldSpec( + "Offset", + "InputClassDef", + description="Offset to ClassDef table containing input sequence context-from beginning of ChainContextPos subtable", + ), + FieldSpec( + "Offset", + "LookAheadClassDef", + description="Offset to ClassDef table containing lookahead sequence context-from beginning of ChainContextPos subtable", + ), + FieldSpec( + "uint16", + "ChainPosClassSetCount", + description="Number of ChainPosClassSet tables", + ), + FieldSpec( + "Offset", + "ChainPosClassSet", + repeat="ChainPosClassSetCount", + aux=0, + description="Array of offsets to ChainPosClassSet tables-from beginning of ChainContextPos subtable-ordered by input class-may be NULL", + ), + ], + ), + ( + "ChainPosClassSet", + [ + FieldSpec( + "uint16", + "ChainPosClassRuleCount", + description="Number of ChainPosClassRule tables", + ), + FieldSpec( + "Offset", + "ChainPosClassRule", + repeat="ChainPosClassRuleCount", + aux=0, + description="Array of offsets to ChainPosClassRule tables-from beginning of ChainPosClassSet-ordered by preference", + ), + ], + ), + ( + "ChainPosClassRule", + [ + FieldSpec( + "uint16", + "BacktrackGlyphCount", + description="Total number of glyphs in the backtrack sequence (number of glyphs to be matched before the first glyph)", + ), + FieldSpec( + "uint16", + "Backtrack", + repeat="BacktrackGlyphCount", + aux=0, + description="Array of backtracking classes(to be matched before the input sequence)", + ), + FieldSpec( + "uint16", + "InputGlyphCount", + description="Total number of classes in the input sequence (includes the first class)", + ), + FieldSpec( + "uint16", + "Input", + repeat="InputGlyphCount", + aux=-1, + description="Array of input classes(start with second class; to be matched with the input glyph sequence)", + ), + FieldSpec( + "uint16", + "LookAheadGlyphCount", + description="Total number of classes in the look ahead sequence (number of classes to be matched after the input sequence)", + ), + FieldSpec( + "uint16", + "LookAhead", + repeat="LookAheadGlyphCount", + aux=0, + description="Array of lookahead classes(to be matched after the input sequence)", + ), + FieldSpec("uint16", "PosCount", description="Number of PosLookupRecords"), + FieldSpec( + "struct", + "PosLookupRecord", + repeat="PosCount", + aux=0, + description="Array of PosLookupRecords (in design order)", + ), + ], + ), + ( + "ChainContextPosFormat3", + [ + FieldSpec( + "uint16", "PosFormat", description="Format identifier-format = 3" + ), + FieldSpec( + "uint16", + "BacktrackGlyphCount", + description="Number of glyphs in the backtracking sequence", + ), + FieldSpec( + "Offset", + "BacktrackCoverage", + repeat="BacktrackGlyphCount", + aux=0, + description="Array of offsets to coverage tables in backtracking sequence, in glyph sequence order", + ), + FieldSpec( + "uint16", + "InputGlyphCount", + description="Number of glyphs in input sequence", + ), + FieldSpec( + "Offset", + "InputCoverage", + repeat="InputGlyphCount", + aux=0, + description="Array of offsets to coverage tables in input sequence, in glyph sequence order", + ), + FieldSpec( + "uint16", + "LookAheadGlyphCount", + description="Number of glyphs in lookahead sequence", + ), + FieldSpec( + "Offset", + "LookAheadCoverage", + repeat="LookAheadGlyphCount", + aux=0, + description="Array of offsets to coverage tables in lookahead sequence, in glyph sequence order", + ), + FieldSpec("uint16", "PosCount", description="Number of PosLookupRecords"), + FieldSpec( + "struct", + "PosLookupRecord", + repeat="PosCount", + aux=0, + description="Array of PosLookupRecords,in design order", + ), + ], + ), + ( + "ExtensionPosFormat1", + [ + FieldSpec( + "uint16", "ExtFormat", description="Format identifier. Set to 1." + ), + FieldSpec( + "uint16", + "ExtensionLookupType", + description="Lookup type of subtable referenced by ExtensionOffset (i.e. the extension subtable).", + ), + FieldSpec("LOffset", "ExtSubTable", description="Offset to SubTable"), + ], + ), + # ('ValueRecord', [ + # ('int16', 'XPlacement', None, None, 'Horizontal adjustment for placement-in design units'), + # ('int16', 'YPlacement', None, None, 'Vertical adjustment for placement-in design units'), + # ('int16', 'XAdvance', None, None, 'Horizontal adjustment for advance-in design units (only used for horizontal writing)'), + # ('int16', 'YAdvance', None, None, 'Vertical adjustment for advance-in design units (only used for vertical writing)'), + # ('Offset', 'XPlaDevice', None, None, 'Offset to Device table for horizontal placement-measured from beginning of PosTable (may be NULL)'), + # ('Offset', 'YPlaDevice', None, None, 'Offset to Device table for vertical placement-measured from beginning of PosTable (may be NULL)'), + # ('Offset', 'XAdvDevice', None, None, 'Offset to Device table for horizontal advance-measured from beginning of PosTable (may be NULL)'), + # ('Offset', 'YAdvDevice', None, None, 'Offset to Device table for vertical advance-measured from beginning of PosTable (may be NULL)'), + # ]), + ( + "AnchorFormat1", + [ + FieldSpec( + "uint16", "AnchorFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "int16", "XCoordinate", description="Horizontal value-in design units" + ), + FieldSpec( + "int16", "YCoordinate", description="Vertical value-in design units" + ), + ], + ), + ( + "AnchorFormat2", + [ + FieldSpec( + "uint16", "AnchorFormat", description="Format identifier-format = 2" + ), + FieldSpec( + "int16", "XCoordinate", description="Horizontal value-in design units" + ), + FieldSpec( + "int16", "YCoordinate", description="Vertical value-in design units" + ), + FieldSpec( + "uint16", "AnchorPoint", description="Index to glyph contour point" + ), + ], + ), + ( + "AnchorFormat3", + [ + FieldSpec( + "uint16", "AnchorFormat", description="Format identifier-format = 3" + ), + FieldSpec( + "int16", "XCoordinate", description="Horizontal value-in design units" + ), + FieldSpec( + "int16", "YCoordinate", description="Vertical value-in design units" + ), + FieldSpec( + "Offset", + "XDeviceTable", + description="Offset to Device table for X coordinate- from beginning of Anchor table (may be NULL)", + ), + FieldSpec( + "Offset", + "YDeviceTable", + description="Offset to Device table for Y coordinate- from beginning of Anchor table (may be NULL)", + ), + ], + ), + ( + "MarkArray", + [ + FieldSpec("uint16", "MarkCount", description="Number of MarkRecords"), + FieldSpec( + "struct", + "MarkRecord", + repeat="MarkCount", + aux=0, + description="Array of MarkRecords-in Coverage order", + ), + ], + ), + ( + "MarkRecord", + [ + FieldSpec("uint16", "Class", description="Class defined for this mark"), + FieldSpec( + "Offset", + "MarkAnchor", + description="Offset to Anchor table-from beginning of MarkArray table", + ), + ], + ), + # + # gsub + # + ( + "GSUB", + [ + FieldSpec( + "Version", + "Version", + description="Version of the GSUB table- 0x00010000 or 0x00010001", + ), + FieldSpec( + "Offset", + "ScriptList", + description="Offset to ScriptList table-from beginning of GSUB table", + ), + FieldSpec( + "Offset", + "FeatureList", + description="Offset to FeatureList table-from beginning of GSUB table", + ), + FieldSpec( + "Offset", + "LookupList", + description="Offset to LookupList table-from beginning of GSUB table", + ), + FieldSpec( + "LOffset", + "FeatureVariations", + aux="Version >= 0x00010001", + description="Offset to FeatureVariations table-from beginning of GSUB table", + ), + ], + ), + ( + "SingleSubstFormat1", + [ + FieldSpec( + "uint16", "SubstFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of Substitution table", + ), + FieldSpec( + "uint16", + "DeltaGlyphID", + description="Add to original GlyphID modulo 65536 to get substitute GlyphID", + ), + ], + ), + ( + "SingleSubstFormat2", + [ + FieldSpec( + "uint16", "SubstFormat", description="Format identifier-format = 2" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of Substitution table", + ), + FieldSpec( + "uint16", + "GlyphCount", + description="Number of GlyphIDs in the Substitute array", + ), + FieldSpec( + "GlyphID", + "Substitute", + repeat="GlyphCount", + aux=0, + description="Array of substitute GlyphIDs-ordered by Coverage Index", + ), + ], + ), + ( + "MultipleSubstFormat1", + [ + FieldSpec( + "uint16", "SubstFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of Substitution table", + ), + FieldSpec( + "uint16", + "SequenceCount", + description="Number of Sequence table offsets in the Sequence array", + ), + FieldSpec( + "Offset", + "Sequence", + repeat="SequenceCount", + aux=0, + description="Array of offsets to Sequence tables-from beginning of Substitution table-ordered by Coverage Index", + ), + ], + ), + ( + "Sequence", + [ + FieldSpec( + "uint16", + "GlyphCount", + description="Number of GlyphIDs in the Substitute array. This should always be greater than 0.", + ), + FieldSpec( + "GlyphID", + "Substitute", + repeat="GlyphCount", + aux=0, + description="String of GlyphIDs to substitute", + ), + ], + ), + ( + "AlternateSubstFormat1", + [ + FieldSpec( + "uint16", "SubstFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of Substitution table", + ), + FieldSpec( + "uint16", + "AlternateSetCount", + description="Number of AlternateSet tables", + ), + FieldSpec( + "Offset", + "AlternateSet", + repeat="AlternateSetCount", + aux=0, + description="Array of offsets to AlternateSet tables-from beginning of Substitution table-ordered by Coverage Index", + ), + ], + ), + ( + "AlternateSet", + [ + FieldSpec( + "uint16", + "GlyphCount", + description="Number of GlyphIDs in the Alternate array", + ), + FieldSpec( + "GlyphID", + "Alternate", + repeat="GlyphCount", + aux=0, + description="Array of alternate GlyphIDs-in arbitrary order", + ), + ], + ), + ( + "LigatureSubstFormat1", + [ + FieldSpec( + "uint16", "SubstFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of Substitution table", + ), + FieldSpec( + "uint16", "LigSetCount", description="Number of LigatureSet tables" + ), + FieldSpec( + "Offset", + "LigatureSet", + repeat="LigSetCount", + aux=0, + description="Array of offsets to LigatureSet tables-from beginning of Substitution table-ordered by Coverage Index", + ), + ], + ), + ( + "LigatureSet", + [ + FieldSpec( + "uint16", "LigatureCount", description="Number of Ligature tables" + ), + FieldSpec( + "Offset", + "Ligature", + repeat="LigatureCount", + aux=0, + description="Array of offsets to Ligature tables-from beginning of LigatureSet table-ordered by preference", + ), + ], + ), + ( + "Ligature", + [ + FieldSpec( + "GlyphID", "LigGlyph", description="GlyphID of ligature to substitute" + ), + FieldSpec( + "uint16", + "CompCount", + description="Number of components in the ligature", + ), + FieldSpec( + "GlyphID", + "Component", + repeat="CompCount", + aux=-1, + description="Array of component GlyphIDs-start with the second component-ordered in writing direction", + ), + ], + ), + ( + "SubstLookupRecord", + [ + FieldSpec( + "uint16", + "SequenceIndex", + description="Index into current glyph sequence-first glyph = 0", + ), + FieldSpec( + "uint16", + "LookupListIndex", + description="Lookup to apply to that position-zero-based", + ), + ], + ), + ( + "ContextSubstFormat1", + [ + FieldSpec( + "uint16", "SubstFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of Substitution table", + ), + FieldSpec( + "uint16", + "SubRuleSetCount", + description="Number of SubRuleSet tables-must equal GlyphCount in Coverage table", + ), + FieldSpec( + "Offset", + "SubRuleSet", + repeat="SubRuleSetCount", + aux=0, + description="Array of offsets to SubRuleSet tables-from beginning of Substitution table-ordered by Coverage Index", + ), + ], + ), + ( + "SubRuleSet", + [ + FieldSpec("uint16", "SubRuleCount", description="Number of SubRule tables"), + FieldSpec( + "Offset", + "SubRule", + repeat="SubRuleCount", + aux=0, + description="Array of offsets to SubRule tables-from beginning of SubRuleSet table-ordered by preference", + ), + ], + ), + ( + "SubRule", + [ + FieldSpec( + "uint16", + "GlyphCount", + description="Total number of glyphs in input glyph sequence-includes the first glyph", + ), + FieldSpec( + "uint16", "SubstCount", description="Number of SubstLookupRecords" + ), + FieldSpec( + "GlyphID", + "Input", + repeat="GlyphCount", + aux=-1, + description="Array of input GlyphIDs-start with second glyph", + ), + FieldSpec( + "struct", + "SubstLookupRecord", + repeat="SubstCount", + aux=0, + description="Array of SubstLookupRecords-in design order", + ), + ], + ), + ( + "ContextSubstFormat2", + [ + FieldSpec( + "uint16", "SubstFormat", description="Format identifier-format = 2" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of Substitution table", + ), + FieldSpec( + "Offset", + "ClassDef", + description="Offset to glyph ClassDef table-from beginning of Substitution table", + ), + FieldSpec( + "uint16", "SubClassSetCount", description="Number of SubClassSet tables" + ), + FieldSpec( + "Offset", + "SubClassSet", + repeat="SubClassSetCount", + aux=0, + description="Array of offsets to SubClassSet tables-from beginning of Substitution table-ordered by class-may be NULL", + ), + ], + ), + ( + "SubClassSet", + [ + FieldSpec( + "uint16", + "SubClassRuleCount", + description="Number of SubClassRule tables", + ), + FieldSpec( + "Offset", + "SubClassRule", + repeat="SubClassRuleCount", + aux=0, + description="Array of offsets to SubClassRule tables-from beginning of SubClassSet-ordered by preference", + ), + ], + ), + ( + "SubClassRule", + [ + FieldSpec( + "uint16", + "GlyphCount", + description="Total number of classes specified for the context in the rule-includes the first class", + ), + FieldSpec( + "uint16", "SubstCount", description="Number of SubstLookupRecords" + ), + FieldSpec( + "uint16", + "Class", + repeat="GlyphCount", + aux=-1, + description="Array of classes-beginning with the second class-to be matched to the input glyph class sequence", + ), + FieldSpec( + "struct", + "SubstLookupRecord", + repeat="SubstCount", + aux=0, + description="Array of Substitution lookups-in design order", + ), + ], + ), + ( + "ContextSubstFormat3", + [ + FieldSpec( + "uint16", "SubstFormat", description="Format identifier-format = 3" + ), + FieldSpec( + "uint16", + "GlyphCount", + description="Number of glyphs in the input glyph sequence", + ), + FieldSpec( + "uint16", "SubstCount", description="Number of SubstLookupRecords" + ), + FieldSpec( + "Offset", + "Coverage", + repeat="GlyphCount", + aux=0, + description="Array of offsets to Coverage table-from beginning of Substitution table-in glyph sequence order", + ), + FieldSpec( + "struct", + "SubstLookupRecord", + repeat="SubstCount", + aux=0, + description="Array of SubstLookupRecords-in design order", + ), + ], + ), + ( + "ChainContextSubstFormat1", + [ + FieldSpec( + "uint16", "SubstFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of Substitution table", + ), + FieldSpec( + "uint16", + "ChainSubRuleSetCount", + description="Number of ChainSubRuleSet tables-must equal GlyphCount in Coverage table", + ), + FieldSpec( + "Offset", + "ChainSubRuleSet", + repeat="ChainSubRuleSetCount", + aux=0, + description="Array of offsets to ChainSubRuleSet tables-from beginning of Substitution table-ordered by Coverage Index", + ), + ], + ), + ( + "ChainSubRuleSet", + [ + FieldSpec( + "uint16", + "ChainSubRuleCount", + description="Number of ChainSubRule tables", + ), + FieldSpec( + "Offset", + "ChainSubRule", + repeat="ChainSubRuleCount", + aux=0, + description="Array of offsets to ChainSubRule tables-from beginning of ChainSubRuleSet table-ordered by preference", + ), + ], + ), + ( + "ChainSubRule", + [ + FieldSpec( + "uint16", + "BacktrackGlyphCount", + description="Total number of glyphs in the backtrack sequence (number of glyphs to be matched before the first glyph)", + ), + FieldSpec( + "GlyphID", + "Backtrack", + repeat="BacktrackGlyphCount", + aux=0, + description="Array of backtracking GlyphID's (to be matched before the input sequence)", + ), + FieldSpec( + "uint16", + "InputGlyphCount", + description="Total number of glyphs in the input sequence (includes the first glyph)", + ), + FieldSpec( + "GlyphID", + "Input", + repeat="InputGlyphCount", + aux=-1, + description="Array of input GlyphIDs (start with second glyph)", + ), + FieldSpec( + "uint16", + "LookAheadGlyphCount", + description="Total number of glyphs in the look ahead sequence (number of glyphs to be matched after the input sequence)", + ), + FieldSpec( + "GlyphID", + "LookAhead", + repeat="LookAheadGlyphCount", + aux=0, + description="Array of lookahead GlyphID's (to be matched after the input sequence)", + ), + FieldSpec( + "uint16", "SubstCount", description="Number of SubstLookupRecords" + ), + FieldSpec( + "struct", + "SubstLookupRecord", + repeat="SubstCount", + aux=0, + description="Array of SubstLookupRecords (in design order)", + ), + ], + ), + ( + "ChainContextSubstFormat2", + [ + FieldSpec( + "uint16", "SubstFormat", description="Format identifier-format = 2" + ), + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table-from beginning of Substitution table", + ), + FieldSpec( + "Offset", + "BacktrackClassDef", + description="Offset to glyph ClassDef table containing backtrack sequence data-from beginning of Substitution table", + ), + FieldSpec( + "Offset", + "InputClassDef", + description="Offset to glyph ClassDef table containing input sequence data-from beginning of Substitution table", + ), + FieldSpec( + "Offset", + "LookAheadClassDef", + description="Offset to glyph ClassDef table containing lookahead sequence data-from beginning of Substitution table", + ), + FieldSpec( + "uint16", + "ChainSubClassSetCount", + description="Number of ChainSubClassSet tables", + ), + FieldSpec( + "Offset", + "ChainSubClassSet", + repeat="ChainSubClassSetCount", + aux=0, + description="Array of offsets to ChainSubClassSet tables-from beginning of Substitution table-ordered by input class-may be NULL", + ), + ], + ), + ( + "ChainSubClassSet", + [ + FieldSpec( + "uint16", + "ChainSubClassRuleCount", + description="Number of ChainSubClassRule tables", + ), + FieldSpec( + "Offset", + "ChainSubClassRule", + repeat="ChainSubClassRuleCount", + aux=0, + description="Array of offsets to ChainSubClassRule tables-from beginning of ChainSubClassSet-ordered by preference", + ), + ], + ), + ( + "ChainSubClassRule", + [ + FieldSpec( + "uint16", + "BacktrackGlyphCount", + description="Total number of glyphs in the backtrack sequence (number of glyphs to be matched before the first glyph)", + ), + FieldSpec( + "uint16", + "Backtrack", + repeat="BacktrackGlyphCount", + aux=0, + description="Array of backtracking classes(to be matched before the input sequence)", + ), + FieldSpec( + "uint16", + "InputGlyphCount", + description="Total number of classes in the input sequence (includes the first class)", + ), + FieldSpec( + "uint16", + "Input", + repeat="InputGlyphCount", + aux=-1, + description="Array of input classes(start with second class; to be matched with the input glyph sequence)", + ), + FieldSpec( + "uint16", + "LookAheadGlyphCount", + description="Total number of classes in the look ahead sequence (number of classes to be matched after the input sequence)", + ), + FieldSpec( + "uint16", + "LookAhead", + repeat="LookAheadGlyphCount", + aux=0, + description="Array of lookahead classes(to be matched after the input sequence)", + ), + FieldSpec( + "uint16", "SubstCount", description="Number of SubstLookupRecords" + ), + FieldSpec( + "struct", + "SubstLookupRecord", + repeat="SubstCount", + aux=0, + description="Array of SubstLookupRecords (in design order)", + ), + ], + ), + ( + "ChainContextSubstFormat3", + [ + FieldSpec( + "uint16", "SubstFormat", description="Format identifier-format = 3" + ), + FieldSpec( + "uint16", + "BacktrackGlyphCount", + description="Number of glyphs in the backtracking sequence", + ), + FieldSpec( + "Offset", + "BacktrackCoverage", + repeat="BacktrackGlyphCount", + aux=0, + description="Array of offsets to coverage tables in backtracking sequence, in glyph sequence order", + ), + FieldSpec( + "uint16", + "InputGlyphCount", + description="Number of glyphs in input sequence", + ), + FieldSpec( + "Offset", + "InputCoverage", + repeat="InputGlyphCount", + aux=0, + description="Array of offsets to coverage tables in input sequence, in glyph sequence order", + ), + FieldSpec( + "uint16", + "LookAheadGlyphCount", + description="Number of glyphs in lookahead sequence", + ), + FieldSpec( + "Offset", + "LookAheadCoverage", + repeat="LookAheadGlyphCount", + aux=0, + description="Array of offsets to coverage tables in lookahead sequence, in glyph sequence order", + ), + FieldSpec( + "uint16", "SubstCount", description="Number of SubstLookupRecords" + ), + FieldSpec( + "struct", + "SubstLookupRecord", + repeat="SubstCount", + aux=0, + description="Array of SubstLookupRecords, in design order", + ), + ], + ), + ( + "ExtensionSubstFormat1", + [ + FieldSpec( + "uint16", "ExtFormat", description="Format identifier. Set to 1." + ), + FieldSpec( + "uint16", + "ExtensionLookupType", + description="Lookup type of subtable referenced by ExtensionOffset (i.e. the extension subtable).", + ), + FieldSpec( + "LOffset", + "ExtSubTable", + description="Array of offsets to Lookup tables-from beginning of LookupList -zero based (first lookup is Lookup index = 0)", + ), + ], + ), + ( + "ReverseChainSingleSubstFormat1", + [ + FieldSpec( + "uint16", "SubstFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "Offset", + "Coverage", + aux=0, + description="Offset to Coverage table - from beginning of Substitution table", + ), + FieldSpec( + "uint16", + "BacktrackGlyphCount", + description="Number of glyphs in the backtracking sequence", + ), + FieldSpec( + "Offset", + "BacktrackCoverage", + repeat="BacktrackGlyphCount", + aux=0, + description="Array of offsets to coverage tables in backtracking sequence, in glyph sequence order", + ), + FieldSpec( + "uint16", + "LookAheadGlyphCount", + description="Number of glyphs in lookahead sequence", + ), + FieldSpec( + "Offset", + "LookAheadCoverage", + repeat="LookAheadGlyphCount", + aux=0, + description="Array of offsets to coverage tables in lookahead sequence, in glyph sequence order", + ), + FieldSpec( + "uint16", + "GlyphCount", + description="Number of GlyphIDs in the Substitute array", + ), + FieldSpec( + "GlyphID", + "Substitute", + repeat="GlyphCount", + aux=0, + description="Array of substitute GlyphIDs-ordered by Coverage index", + ), + ], + ), + # + # gdef + # + ( + "GDEF", + [ + FieldSpec( + "Version", + "Version", + description="Version of the GDEF table- 0x00010000, 0x00010002, or 0x00010003", + ), + FieldSpec( + "Offset", + "GlyphClassDef", + description="Offset to class definition table for glyph type-from beginning of GDEF header (may be NULL)", + ), + FieldSpec( + "Offset", + "AttachList", + description="Offset to list of glyphs with attachment points-from beginning of GDEF header (may be NULL)", + ), + FieldSpec( + "Offset", + "LigCaretList", + description="Offset to list of positioning points for ligature carets-from beginning of GDEF header (may be NULL)", + ), + FieldSpec( + "Offset", + "MarkAttachClassDef", + description="Offset to class definition table for mark attachment type-from beginning of GDEF header (may be NULL)", + ), + FieldSpec( + "Offset", + "MarkGlyphSetsDef", + aux="Version >= 0x00010002", + description="Offset to the table of mark set definitions-from beginning of GDEF header (may be NULL)", + ), + FieldSpec( + "LOffset", + "VarStore", + aux="Version >= 0x00010003", + description="Offset to variation store (may be NULL)", + ), + ], + ), + ( + "AttachList", + [ + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table - from beginning of AttachList table", + ), + FieldSpec( + "uint16", + "GlyphCount", + description="Number of glyphs with attachment points", + ), + FieldSpec( + "Offset", + "AttachPoint", + repeat="GlyphCount", + aux=0, + description="Array of offsets to AttachPoint tables-from beginning of AttachList table-in Coverage Index order", + ), + ], + ), + ( + "AttachPoint", + [ + FieldSpec( + "uint16", + "PointCount", + description="Number of attachment points on this glyph", + ), + FieldSpec( + "uint16", + "PointIndex", + repeat="PointCount", + aux=0, + description="Array of contour point indices -in increasing numerical order", + ), + ], + ), + ( + "LigCaretList", + [ + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table - from beginning of LigCaretList table", + ), + FieldSpec( + "uint16", "LigGlyphCount", description="Number of ligature glyphs" + ), + FieldSpec( + "Offset", + "LigGlyph", + repeat="LigGlyphCount", + aux=0, + description="Array of offsets to LigGlyph tables-from beginning of LigCaretList table-in Coverage Index order", + ), + ], + ), + ( + "LigGlyph", + [ + FieldSpec( + "uint16", + "CaretCount", + description="Number of CaretValues for this ligature (components - 1)", + ), + FieldSpec( + "Offset", + "CaretValue", + repeat="CaretCount", + aux=0, + description="Array of offsets to CaretValue tables-from beginning of LigGlyph table-in increasing coordinate order", + ), + ], + ), + ( + "CaretValueFormat1", + [ + FieldSpec( + "uint16", "CaretValueFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "int16", "Coordinate", description="X or Y value, in design units" + ), + ], + ), + ( + "CaretValueFormat2", + [ + FieldSpec( + "uint16", "CaretValueFormat", description="Format identifier-format = 2" + ), + FieldSpec( + "uint16", "CaretValuePoint", description="Contour point index on glyph" + ), + ], + ), + ( + "CaretValueFormat3", + [ + FieldSpec( + "uint16", "CaretValueFormat", description="Format identifier-format = 3" + ), + FieldSpec( + "int16", "Coordinate", description="X or Y value, in design units" + ), + FieldSpec( + "Offset", + "DeviceTable", + description="Offset to Device table for X or Y value-from beginning of CaretValue table", + ), + ], + ), + ( + "MarkGlyphSetsDef", + [ + FieldSpec( + "uint16", "MarkSetTableFormat", description="Format identifier == 1" + ), + FieldSpec( + "uint16", "MarkSetCount", description="Number of mark sets defined" + ), + FieldSpec( + "LOffset", + "Coverage", + repeat="MarkSetCount", + aux=0, + description="Array of offsets to mark set coverage tables.", + ), + ], + ), + # + # base + # + ( + "BASE", + [ + FieldSpec( + "Version", + "Version", + description="Version of the BASE table-initially 0x00010000", + ), + FieldSpec( + "Offset", + "HorizAxis", + description="Offset to horizontal Axis table-from beginning of BASE table-may be NULL", + ), + FieldSpec( + "Offset", + "VertAxis", + description="Offset to vertical Axis table-from beginning of BASE table-may be NULL", + ), + FieldSpec( + "LOffset", + "VarStore", + aux="Version >= 0x00010001", + description="Offset to variation store (may be NULL)", + ), + ], + ), + ( + "Axis", + [ + FieldSpec( + "Offset", + "BaseTagList", + description="Offset to BaseTagList table-from beginning of Axis table-may be NULL", + ), + FieldSpec( + "Offset", + "BaseScriptList", + description="Offset to BaseScriptList table-from beginning of Axis table", + ), + ], + ), + ( + "BaseTagList", + [ + FieldSpec( + "uint16", + "BaseTagCount", + description="Number of baseline identification tags in this text direction-may be zero (0)", + ), + FieldSpec( + "Tag", + "BaselineTag", + repeat="BaseTagCount", + aux=0, + description="Array of 4-byte baseline identification tags-must be in alphabetical order", + ), + ], + ), + ( + "BaseScriptList", + [ + FieldSpec( + "uint16", + "BaseScriptCount", + description="Number of BaseScriptRecords defined", + ), + FieldSpec( + "struct", + "BaseScriptRecord", + repeat="BaseScriptCount", + aux=0, + description="Array of BaseScriptRecords-in alphabetical order by BaseScriptTag", + ), + ], + ), + ( + "BaseScriptRecord", + [ + FieldSpec( + "Tag", "BaseScriptTag", description="4-byte script identification tag" + ), + FieldSpec( + "Offset", + "BaseScript", + description="Offset to BaseScript table-from beginning of BaseScriptList", + ), + ], + ), + ( + "BaseScript", + [ + FieldSpec( + "Offset", + "BaseValues", + description="Offset to BaseValues table-from beginning of BaseScript table-may be NULL", + ), + FieldSpec( + "Offset", + "DefaultMinMax", + description="Offset to MinMax table- from beginning of BaseScript table-may be NULL", + ), + FieldSpec( + "uint16", + "BaseLangSysCount", + description="Number of BaseLangSysRecords defined-may be zero (0)", + ), + FieldSpec( + "struct", + "BaseLangSysRecord", + repeat="BaseLangSysCount", + aux=0, + description="Array of BaseLangSysRecords-in alphabetical order by BaseLangSysTag", + ), + ], + ), + ( + "BaseLangSysRecord", + [ + FieldSpec( + "Tag", + "BaseLangSysTag", + description="4-byte language system identification tag", + ), + FieldSpec( + "Offset", + "MinMax", + description="Offset to MinMax table-from beginning of BaseScript table", + ), + ], + ), + ( + "BaseValues", + [ + FieldSpec( + "uint16", + "DefaultIndex", + description="Index number of default baseline for this script-equals index position of baseline tag in BaselineArray of the BaseTagList", + ), + FieldSpec( + "uint16", + "BaseCoordCount", + description="Number of BaseCoord tables defined-should equal BaseTagCount in the BaseTagList", + ), + FieldSpec( + "Offset", + "BaseCoord", + repeat="BaseCoordCount", + aux=0, + description="Array of offsets to BaseCoord-from beginning of BaseValues table-order matches BaselineTag array in the BaseTagList", + ), + ], + ), + ( + "MinMax", + [ + FieldSpec( + "Offset", + "MinCoord", + description="Offset to BaseCoord table-defines minimum extent value-from the beginning of MinMax table-may be NULL", + ), + FieldSpec( + "Offset", + "MaxCoord", + description="Offset to BaseCoord table-defines maximum extent value-from the beginning of MinMax table-may be NULL", + ), + FieldSpec( + "uint16", + "FeatMinMaxCount", + description="Number of FeatMinMaxRecords-may be zero (0)", + ), + FieldSpec( + "struct", + "FeatMinMaxRecord", + repeat="FeatMinMaxCount", + aux=0, + description="Array of FeatMinMaxRecords-in alphabetical order, by FeatureTableTag", + ), + ], + ), + ( + "FeatMinMaxRecord", + [ + FieldSpec( + "Tag", + "FeatureTableTag", + description="4-byte feature identification tag-must match FeatureTag in FeatureList", + ), + FieldSpec( + "Offset", + "MinCoord", + description="Offset to BaseCoord table-defines minimum extent value-from beginning of MinMax table-may be NULL", + ), + FieldSpec( + "Offset", + "MaxCoord", + description="Offset to BaseCoord table-defines maximum extent value-from beginning of MinMax table-may be NULL", + ), + ], + ), + ( + "BaseCoordFormat1", + [ + FieldSpec( + "uint16", "BaseCoordFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "int16", "Coordinate", description="X or Y value, in design units" + ), + ], + ), + ( + "BaseCoordFormat2", + [ + FieldSpec( + "uint16", "BaseCoordFormat", description="Format identifier-format = 2" + ), + FieldSpec( + "int16", "Coordinate", description="X or Y value, in design units" + ), + FieldSpec( + "GlyphID", "ReferenceGlyph", description="GlyphID of control glyph" + ), + FieldSpec( + "uint16", + "BaseCoordPoint", + description="Index of contour point on the ReferenceGlyph", + ), + ], + ), + ( + "BaseCoordFormat3", + [ + FieldSpec( + "uint16", "BaseCoordFormat", description="Format identifier-format = 3" + ), + FieldSpec( + "int16", "Coordinate", description="X or Y value, in design units" + ), + FieldSpec( + "Offset", + "DeviceTable", + description="Offset to Device table for X or Y value", + ), + ], + ), + # + # jstf + # + ( + "JSTF", + [ + FieldSpec( + "Version", + "Version", + description="Version of the JSTF table-initially set to 0x00010000", + ), + FieldSpec( + "uint16", + "JstfScriptCount", + description="Number of JstfScriptRecords in this table", + ), + FieldSpec( + "struct", + "JstfScriptRecord", + repeat="JstfScriptCount", + aux=0, + description="Array of JstfScriptRecords-in alphabetical order, by JstfScriptTag", + ), + ], + ), + ( + "JstfScriptRecord", + [ + FieldSpec( + "Tag", "JstfScriptTag", description="4-byte JstfScript identification" + ), + FieldSpec( + "Offset", + "JstfScript", + description="Offset to JstfScript table-from beginning of JSTF Header", + ), + ], + ), + ( + "JstfScript", + [ + FieldSpec( + "Offset", + "ExtenderGlyph", + description="Offset to ExtenderGlyph table-from beginning of JstfScript table-may be NULL", + ), + FieldSpec( + "Offset", + "DefJstfLangSys", + description="Offset to Default JstfLangSys table-from beginning of JstfScript table-may be NULL", + ), + FieldSpec( + "uint16", + "JstfLangSysCount", + description="Number of JstfLangSysRecords in this table- may be zero (0)", + ), + FieldSpec( + "struct", + "JstfLangSysRecord", + repeat="JstfLangSysCount", + aux=0, + description="Array of JstfLangSysRecords-in alphabetical order, by JstfLangSysTag", + ), + ], + ), + ( + "JstfLangSysRecord", + [ + FieldSpec( + "Tag", "JstfLangSysTag", description="4-byte JstfLangSys identifier" + ), + FieldSpec( + "Offset", + "JstfLangSys", + description="Offset to JstfLangSys table-from beginning of JstfScript table", + ), + ], + ), + ( + "ExtenderGlyph", + [ + FieldSpec( + "uint16", + "GlyphCount", + description="Number of Extender Glyphs in this script", + ), + FieldSpec( + "GlyphID", + "ExtenderGlyph", + repeat="GlyphCount", + aux=0, + description="GlyphIDs-in increasing numerical order", + ), + ], + ), + ( + "JstfLangSys", + [ + FieldSpec( + "uint16", + "JstfPriorityCount", + description="Number of JstfPriority tables", + ), + FieldSpec( + "Offset", + "JstfPriority", + repeat="JstfPriorityCount", + aux=0, + description="Array of offsets to JstfPriority tables-from beginning of JstfLangSys table-in priority order", + ), + ], + ), + ( + "JstfPriority", + [ + FieldSpec( + "Offset", + "ShrinkageEnableGSUB", + description="Offset to Shrinkage Enable JstfGSUBModList table-from beginning of JstfPriority table-may be NULL", + ), + FieldSpec( + "Offset", + "ShrinkageDisableGSUB", + description="Offset to Shrinkage Disable JstfGSUBModList table-from beginning of JstfPriority table-may be NULL", + ), + FieldSpec( + "Offset", + "ShrinkageEnableGPOS", + description="Offset to Shrinkage Enable JstfGPOSModList table-from beginning of JstfPriority table-may be NULL", + ), + FieldSpec( + "Offset", + "ShrinkageDisableGPOS", + description="Offset to Shrinkage Disable JstfGPOSModList table-from beginning of JstfPriority table-may be NULL", + ), + FieldSpec( + "Offset", + "ShrinkageJstfMax", + description="Offset to Shrinkage JstfMax table-from beginning of JstfPriority table -may be NULL", + ), + FieldSpec( + "Offset", + "ExtensionEnableGSUB", + description="Offset to Extension Enable JstfGSUBModList table-may be NULL", + ), + FieldSpec( + "Offset", + "ExtensionDisableGSUB", + description="Offset to Extension Disable JstfGSUBModList table-from beginning of JstfPriority table-may be NULL", + ), + FieldSpec( + "Offset", + "ExtensionEnableGPOS", + description="Offset to Extension Enable JstfGSUBModList table-may be NULL", + ), + FieldSpec( + "Offset", + "ExtensionDisableGPOS", + description="Offset to Extension Disable JstfGSUBModList table-from beginning of JstfPriority table-may be NULL", + ), + FieldSpec( + "Offset", + "ExtensionJstfMax", + description="Offset to Extension JstfMax table-from beginning of JstfPriority table -may be NULL", + ), + ], + ), + ( + "JstfGSUBModList", + [ + FieldSpec( + "uint16", + "LookupCount", + description="Number of lookups for this modification", + ), + FieldSpec( + "uint16", + "GSUBLookupIndex", + repeat="LookupCount", + aux=0, + description="Array of LookupIndex identifiers in GSUB-in increasing numerical order", + ), + ], + ), + ( + "JstfGPOSModList", + [ + FieldSpec( + "uint16", + "LookupCount", + description="Number of lookups for this modification", + ), + FieldSpec( + "uint16", + "GPOSLookupIndex", + repeat="LookupCount", + aux=0, + description="Array of LookupIndex identifiers in GPOS-in increasing numerical order", + ), + ], + ), + ( + "JstfMax", + [ + FieldSpec( + "uint16", + "LookupCount", + description="Number of lookup Indices for this modification", + ), + FieldSpec( + "Offset", + "Lookup", + repeat="LookupCount", + aux=0, + description="Array of offsets to GPOS-type lookup tables-from beginning of JstfMax table-in design order", + ), + ], + ), + # + # STAT + # + ( + "STAT", + [ + FieldSpec( + "Version", + "Version", + description="Version of the table-initially set to 0x00010000, currently 0x00010002.", + ), + FieldSpec( + "uint16", + "DesignAxisRecordSize", + description="Size in bytes of each design axis record", + ), + FieldSpec( + "uint16", "DesignAxisCount", description="Number of design axis records" + ), + FieldSpec( + "LOffsetTo(AxisRecordArray)", + "DesignAxisRecord", + description="Offset in bytes from the beginning of the STAT table to the start of the design axes array", + ), + FieldSpec( + "uint16", "AxisValueCount", description="Number of axis value tables" + ), + FieldSpec( + "LOffsetTo(AxisValueArray)", + "AxisValueArray", + description="Offset in bytes from the beginning of the STAT table to the start of the axes value offset array", + ), + FieldSpec( + "NameID", + "ElidedFallbackNameID", + aux="Version >= 0x00010001", + description="NameID to use when all style attributes are elided.", + ), + ], + ), + ( + "AxisRecordArray", + [ + FieldSpec( + "AxisRecord", + "Axis", + repeat="DesignAxisCount", + aux=0, + description="Axis records", + ), + ], + ), + ( + "AxisRecord", + [ + FieldSpec( + "Tag", + "AxisTag", + description="A tag identifying the axis of design variation", + ), + FieldSpec( + "NameID", + "AxisNameID", + description='The name ID for entries in the "name" table that provide a display string for this axis', + ), + FieldSpec( + "uint16", + "AxisOrdering", + description="A value that applications can use to determine primary sorting of face names, or for ordering of descriptors when composing family or face names", + ), + FieldSpec( + "uint8", + "MoreBytes", + repeat="DesignAxisRecordSize", + aux=-8, + description="Extra bytes. Set to empty array.", + ), + ], + ), + ( + "AxisValueArray", + [ + FieldSpec( + "Offset", + "AxisValue", + repeat="AxisValueCount", + aux=0, + description="Axis values", + ), + ], + ), + ( + "AxisValueFormat1", + [ + FieldSpec("uint16", "Format", description="Format, = 1"), + FieldSpec( + "uint16", + "AxisIndex", + description="Index into the axis record array identifying the axis of design variation to which the axis value record applies.", + ), + FieldSpec("STATFlags", "Flags", description="Flags."), + FieldSpec("NameID", "ValueNameID"), + FieldSpec("Fixed", "Value"), + ], + ), + ( + "AxisValueFormat2", + [ + FieldSpec("uint16", "Format", description="Format, = 2"), + FieldSpec( + "uint16", + "AxisIndex", + description="Index into the axis record array identifying the axis of design variation to which the axis value record applies.", + ), + FieldSpec("STATFlags", "Flags", description="Flags."), + FieldSpec("NameID", "ValueNameID"), + FieldSpec("Fixed", "NominalValue"), + FieldSpec("Fixed", "RangeMinValue"), + FieldSpec("Fixed", "RangeMaxValue"), + ], + ), + ( + "AxisValueFormat3", + [ + FieldSpec("uint16", "Format", description="Format, = 3"), + FieldSpec( + "uint16", + "AxisIndex", + description="Index into the axis record array identifying the axis of design variation to which the axis value record applies.", + ), + FieldSpec("STATFlags", "Flags", description="Flags."), + FieldSpec("NameID", "ValueNameID"), + FieldSpec("Fixed", "Value"), + FieldSpec("Fixed", "LinkedValue"), + ], + ), + ( + "AxisValueFormat4", + [ + FieldSpec("uint16", "Format", description="Format, = 4"), + FieldSpec( + "uint16", + "AxisCount", + description="The total number of axes contributing to this axis-values combination.", + ), + FieldSpec("STATFlags", "Flags", description="Flags."), + FieldSpec("NameID", "ValueNameID"), + FieldSpec( + "struct", + "AxisValueRecord", + repeat="AxisCount", + aux=0, + description="Array of AxisValue records that provide the combination of axis values, one for each contributing axis. ", + ), + ], + ), + ( + "AxisValueRecord", + [ + FieldSpec( + "uint16", + "AxisIndex", + description="Index into the axis record array identifying the axis of design variation to which the axis value record applies.", + ), + FieldSpec( + "Fixed", + "Value", + description="A numeric value for this attribute value.", + ), + ], + ), + # + # Variation fonts + # + # GSUB/GPOS FeatureVariations + ( + "FeatureVariations", + [ + FieldSpec( + "Version", + "Version", + description="Version of the table-initially set to 0x00010000", + ), + FieldSpec( + "uint32", + "FeatureVariationCount", + description="Number of records in the FeatureVariationRecord array", + ), + FieldSpec( + "struct", + "FeatureVariationRecord", + repeat="FeatureVariationCount", + aux=0, + description="Array of FeatureVariationRecord", + ), + ], + ), + ( + "FeatureVariationRecord", + [ + FieldSpec( + "LOffset", + "ConditionSet", + description="Offset to a ConditionSet table, from beginning of the FeatureVariations table.", + ), + FieldSpec( + "LOffset", + "FeatureTableSubstitution", + description="Offset to a FeatureTableSubstitution table, from beginning of the FeatureVariations table", + ), + ], + ), + ( + "ConditionList", + [ + FieldSpec( + "uint32", + "ConditionCount", + description="Number of condition tables in the ConditionTable array", + ), + FieldSpec( + "LOffset", + "ConditionTable", + repeat="ConditionCount", + aux=0, + description="Array of offset to condition tables, from the beginning of the ConditionList table.", + ), + ], + ), + ( + "ConditionSet", + [ + FieldSpec( + "uint16", + "ConditionCount", + description="Number of condition tables in the ConditionTable array", + ), + FieldSpec( + "LOffset", + "ConditionTable", + repeat="ConditionCount", + aux=0, + description="Array of offset to condition tables, from the beginning of the ConditionSet table.", + ), + ], + ), + ( + "ConditionTableFormat1", + [ + FieldSpec("uint16", "Format", description="Format, = 1"), + FieldSpec( + "uint16", + "AxisIndex", + description="Index for the variation axis within the fvar table, base 0.", + ), + FieldSpec( + "F2Dot14", + "FilterRangeMinValue", + description="Minimum normalized axis value of the font variation instances that satisfy this condition.", + ), + FieldSpec( + "F2Dot14", + "FilterRangeMaxValue", + description="Maximum value that satisfies this condition.", + ), + ], + ), + ( + "ConditionTableFormat2", + [ + FieldSpec("uint16", "Format", description="Format, = 2"), + FieldSpec( + "int16", "DefaultValue", description="Value at default instance." + ), + FieldSpec( + "uint32", + "VarIdx", + description="Variation index to vary the value based on current designspace location.", + ), + ], + ), + ( + "ConditionTableFormat3", + [ + FieldSpec("uint16", "Format", description="Format, = 3"), + FieldSpec( + "uint8", + "ConditionCount", + description="Index for the variation axis within the fvar table, base 0.", + ), + FieldSpec( + "Offset24", + "ConditionTable", + repeat="ConditionCount", + aux=0, + description="Array of condition tables for this conjunction (AND) expression.", + ), + ], + ), + ( + "ConditionTableFormat4", + [ + FieldSpec("uint16", "Format", description="Format, = 4"), + FieldSpec( + "uint8", + "ConditionCount", + description="Index for the variation axis within the fvar table, base 0.", + ), + FieldSpec( + "Offset24", + "ConditionTable", + repeat="ConditionCount", + aux=0, + description="Array of condition tables for this disjunction (OR) expression.", + ), + ], + ), + ( + "ConditionTableFormat5", + [ + FieldSpec("uint16", "Format", description="Format, = 5"), + FieldSpec("Offset24", "ConditionTable", description="Condition to negate."), + ], + ), + ( + "FeatureTableSubstitution", + [ + FieldSpec( + "Version", + "Version", + description="Version of the table-initially set to 0x00010000", + ), + FieldSpec( + "uint16", + "SubstitutionCount", + description="Number of records in the FeatureVariationRecords array", + ), + FieldSpec( + "FeatureTableSubstitutionRecord", + "SubstitutionRecord", + repeat="SubstitutionCount", + aux=0, + description="Array of FeatureTableSubstitutionRecord", + ), + ], + ), + ( + "FeatureTableSubstitutionRecord", + [ + FieldSpec( + "uint16", + "FeatureIndex", + description="The feature table index to match.", + ), + FieldSpec( + "LOffset", + "Feature", + description="Offset to an alternate feature table, from start of the FeatureTableSubstitution table.", + ), + ], + ), + # VariationStore + ( + "VarRegionAxis", + [ + FieldSpec("F2Dot14", "StartCoord"), + FieldSpec("F2Dot14", "PeakCoord"), + FieldSpec("F2Dot14", "EndCoord"), + ], + ), + ( + "VarRegion", + [ + FieldSpec("struct", "VarRegionAxis", repeat="RegionAxisCount", aux=0), + ], + ), + ( + "VarRegionList", + [ + FieldSpec("uint16", "RegionAxisCount"), + FieldSpec("uint16", "RegionCount"), + FieldSpec("VarRegion", "Region", repeat="RegionCount", aux=0), + ], + ), + ( + "VarData", + [ + FieldSpec("uint16", "ItemCount"), + FieldSpec("uint16", "NumShorts"), + FieldSpec("uint16", "VarRegionCount"), + FieldSpec("uint16", "VarRegionIndex", repeat="VarRegionCount", aux=0), + FieldSpec("VarDataValue", "Item", repeat="ItemCount", aux=0), + ], + ), + ( + "VarStore", + [ + FieldSpec("uint16", "Format", description="Set to 1."), + FieldSpec("LOffset", "VarRegionList"), + FieldSpec("uint16", "VarDataCount"), + FieldSpec("LOffset", "VarData", repeat="VarDataCount", aux=0), + ], + ), + # Variation helpers + ( + "VarIdxMap", + [ + FieldSpec("uint16", "EntryFormat"), # Automatically computed + FieldSpec("uint16", "MappingCount"), # Automatically computed + FieldSpec( + "VarIdxMapValue", + "mapping", + repeat="", + aux=0, + description="Array of compressed data", + ), + ], + ), + ( + "DeltaSetIndexMapFormat0", + [ + FieldSpec( + "uint8", "Format", description="Format of the DeltaSetIndexMap = 0" + ), + FieldSpec("uint8", "EntryFormat"), # Automatically computed + FieldSpec("uint16", "MappingCount"), # Automatically computed + FieldSpec( + "VarIdxMapValue", + "mapping", + repeat="", + aux=0, + description="Array of compressed data", + ), + ], + ), + ( + "DeltaSetIndexMapFormat1", + [ + FieldSpec( + "uint8", "Format", description="Format of the DeltaSetIndexMap = 1" + ), + FieldSpec("uint8", "EntryFormat"), # Automatically computed + FieldSpec("uint32", "MappingCount"), # Automatically computed + FieldSpec( + "VarIdxMapValue", + "mapping", + repeat="", + aux=0, + description="Array of compressed data", + ), + ], + ), + # MultiVariationStore + ( + "SparseVarRegionAxis", + [ + FieldSpec("uint16", "AxisIndex"), + FieldSpec("F2Dot14", "StartCoord"), + FieldSpec("F2Dot14", "PeakCoord"), + FieldSpec("F2Dot14", "EndCoord"), + ], + ), + ( + "SparseVarRegion", + [ + FieldSpec("uint16", "SparseRegionCount"), + FieldSpec( + "struct", "SparseVarRegionAxis", repeat="SparseRegionCount", aux=0 + ), + ], + ), + ( + "SparseVarRegionList", + [ + FieldSpec("uint16", "RegionCount"), + FieldSpec( + "LOffsetTo(SparseVarRegion)", "Region", repeat="RegionCount", aux=0 + ), + ], + ), + ( + "MultiVarData", + [ + FieldSpec("uint8", "Format", description="Set to 1."), + FieldSpec("uint16", "VarRegionCount"), + FieldSpec("uint16", "VarRegionIndex", repeat="VarRegionCount", aux=0), + FieldSpec("TupleList", "Item", repeat="", aux=0), + ], + ), + ( + "MultiVarStore", + [ + FieldSpec("uint16", "Format", description="Set to 1."), + FieldSpec("LOffset", "SparseVarRegionList"), + FieldSpec("uint16", "MultiVarDataCount"), + FieldSpec("LOffset", "MultiVarData", repeat="MultiVarDataCount", aux=0), + ], + ), + # VariableComposites + ( + "VARC", + [ + FieldSpec( + "Version", + "Version", + description="Version of the HVAR table-initially = 0x00010000", + ), + FieldSpec("LOffset", "Coverage"), + FieldSpec("LOffset", "MultiVarStore", description="(may be NULL)"), + FieldSpec("LOffset", "ConditionList", description="(may be NULL)"), + FieldSpec("LOffset", "AxisIndicesList", description="(may be NULL)"), + FieldSpec("LOffset", "VarCompositeGlyphs"), + ], + ), + ( + "AxisIndicesList", + [ + FieldSpec("TupleList", "Item", repeat="", aux=0), + ], + ), + ( + "VarCompositeGlyphs", + [ + FieldSpec("VarCompositeGlyphList", "VarCompositeGlyph", repeat=""), + ], + ), + # Glyph advance variations + ( + "HVAR", + [ + FieldSpec( + "Version", + "Version", + description="Version of the HVAR table-initially = 0x00010000", + ), + FieldSpec("LOffset", "VarStore"), + FieldSpec("LOffsetTo(VarIdxMap)", "AdvWidthMap"), + FieldSpec("LOffsetTo(VarIdxMap)", "LsbMap"), + FieldSpec("LOffsetTo(VarIdxMap)", "RsbMap"), + ], + ), + ( + "VVAR", + [ + FieldSpec( + "Version", + "Version", + description="Version of the VVAR table-initially = 0x00010000", + ), + FieldSpec("LOffset", "VarStore"), + FieldSpec("LOffsetTo(VarIdxMap)", "AdvHeightMap"), + FieldSpec("LOffsetTo(VarIdxMap)", "TsbMap"), + FieldSpec("LOffsetTo(VarIdxMap)", "BsbMap"), + FieldSpec( + "LOffsetTo(VarIdxMap)", + "VOrgMap", + description="Vertical origin mapping.", + ), + ], + ), + # Font-wide metrics variations + ( + "MetricsValueRecord", + [ + FieldSpec( + "Tag", "ValueTag", description="4-byte font-wide measure identifier" + ), + FieldSpec( + "uint32", "VarIdx", description="Combined outer-inner variation index" + ), + FieldSpec( + "uint8", + "MoreBytes", + repeat="ValueRecordSize", + aux=-8, + description="Extra bytes. Set to empty array.", + ), + ], + ), + ( + "MVAR", + [ + FieldSpec( + "Version", + "Version", + description="Version of the MVAR table-initially = 0x00010000", + ), + FieldSpec("uint16", "Reserved", description="Set to 0"), + FieldSpec("uint16", "ValueRecordSize"), + FieldSpec("uint16", "ValueRecordCount"), + FieldSpec("Offset", "VarStore"), + FieldSpec( + "MetricsValueRecord", "ValueRecord", repeat="ValueRecordCount", aux=0 + ), + ], + ), + # + # math + # + ( + "MATH", + [ + FieldSpec( + "Version", + "Version", + description="Version of the MATH table-initially set to 0x00010000.", + ), + FieldSpec( + "Offset", + "MathConstants", + description="Offset to MathConstants table - from the beginning of MATH table.", + ), + FieldSpec( + "Offset", + "MathGlyphInfo", + description="Offset to MathGlyphInfo table - from the beginning of MATH table.", + ), + FieldSpec( + "Offset", + "MathVariants", + description="Offset to MathVariants table - from the beginning of MATH table.", + ), + ], + ), + ( + "MathValueRecord", + [ + FieldSpec( + "int16", "Value", description="The X or Y value in design units." + ), + FieldSpec( + "Offset", + "DeviceTable", + description="Offset to the device table - from the beginning of parent table. May be NULL. Suggested format for device table is 1.", + ), + ], + ), + ( + "MathConstants", + [ + FieldSpec( + "int16", + "ScriptPercentScaleDown", + description="Percentage of scaling down for script level 1. Suggested value: 80%.", + ), + FieldSpec( + "int16", + "ScriptScriptPercentScaleDown", + description="Percentage of scaling down for script level 2 (ScriptScript). Suggested value: 60%.", + ), + FieldSpec( + "uint16", + "DelimitedSubFormulaMinHeight", + description="Minimum height required for a delimited expression to be treated as a subformula. Suggested value: normal line height x1.5.", + ), + FieldSpec( + "uint16", + "DisplayOperatorMinHeight", + description="Minimum height of n-ary operators (such as integral and summation) for formulas in display mode.", + ), + FieldSpec( + "MathValueRecord", + "MathLeading", + description="White space to be left between math formulas to ensure proper line spacing. For example, for applications that treat line gap as a part of line ascender, formulas with ink going above (os2.sTypoAscender + os2.sTypoLineGap - MathLeading) or with ink going below os2.sTypoDescender will result in increasing line height.", + ), + FieldSpec( + "MathValueRecord", "AxisHeight", description="Axis height of the font." + ), + FieldSpec( + "MathValueRecord", + "AccentBaseHeight", + description="Maximum (ink) height of accent base that does not require raising the accents. Suggested: x-height of the font (os2.sxHeight) plus any possible overshots.", + ), + FieldSpec( + "MathValueRecord", + "FlattenedAccentBaseHeight", + description="Maximum (ink) height of accent base that does not require flattening the accents. Suggested: cap height of the font (os2.sCapHeight).", + ), + FieldSpec( + "MathValueRecord", + "SubscriptShiftDown", + description="The standard shift down applied to subscript elements. Positive for moving in the downward direction. Suggested: os2.ySubscriptYOffset.", + ), + FieldSpec( + "MathValueRecord", + "SubscriptTopMax", + description="Maximum allowed height of the (ink) top of subscripts that does not require moving subscripts further down. Suggested: 4/5 x-height.", + ), + FieldSpec( + "MathValueRecord", + "SubscriptBaselineDropMin", + description="Minimum allowed drop of the baseline of subscripts relative to the (ink) bottom of the base. Checked for bases that are treated as a box or extended shape. Positive for subscript baseline dropped below the base bottom.", + ), + FieldSpec( + "MathValueRecord", + "SuperscriptShiftUp", + description="Standard shift up applied to superscript elements. Suggested: os2.ySuperscriptYOffset.", + ), + FieldSpec( + "MathValueRecord", + "SuperscriptShiftUpCramped", + description="Standard shift of superscripts relative to the base, in cramped style.", + ), + FieldSpec( + "MathValueRecord", + "SuperscriptBottomMin", + description="Minimum allowed height of the (ink) bottom of superscripts that does not require moving subscripts further up. Suggested: 1/4 x-height.", + ), + FieldSpec( + "MathValueRecord", + "SuperscriptBaselineDropMax", + description="Maximum allowed drop of the baseline of superscripts relative to the (ink) top of the base. Checked for bases that are treated as a box or extended shape. Positive for superscript baseline below the base top.", + ), + FieldSpec( + "MathValueRecord", + "SubSuperscriptGapMin", + description="Minimum gap between the superscript and subscript ink. Suggested: 4x default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "SuperscriptBottomMaxWithSubscript", + description="The maximum level to which the (ink) bottom of superscript can be pushed to increase the gap between superscript and subscript, before subscript starts being moved down. Suggested: 4/5 x-height.", + ), + FieldSpec( + "MathValueRecord", + "SpaceAfterScript", + description="Extra white space to be added after each subscript and superscript. Suggested: 0.5pt for a 12 pt font.", + ), + FieldSpec( + "MathValueRecord", + "UpperLimitGapMin", + description="Minimum gap between the (ink) bottom of the upper limit, and the (ink) top of the base operator.", + ), + FieldSpec( + "MathValueRecord", + "UpperLimitBaselineRiseMin", + description="Minimum distance between baseline of upper limit and (ink) top of the base operator.", + ), + FieldSpec( + "MathValueRecord", + "LowerLimitGapMin", + description="Minimum gap between (ink) top of the lower limit, and (ink) bottom of the base operator.", + ), + FieldSpec( + "MathValueRecord", + "LowerLimitBaselineDropMin", + description="Minimum distance between baseline of the lower limit and (ink) bottom of the base operator.", + ), + FieldSpec( + "MathValueRecord", + "StackTopShiftUp", + description="Standard shift up applied to the top element of a stack.", + ), + FieldSpec( + "MathValueRecord", + "StackTopDisplayStyleShiftUp", + description="Standard shift up applied to the top element of a stack in display style.", + ), + FieldSpec( + "MathValueRecord", + "StackBottomShiftDown", + description="Standard shift down applied to the bottom element of a stack. Positive for moving in the downward direction.", + ), + FieldSpec( + "MathValueRecord", + "StackBottomDisplayStyleShiftDown", + description="Standard shift down applied to the bottom element of a stack in display style. Positive for moving in the downward direction.", + ), + FieldSpec( + "MathValueRecord", + "StackGapMin", + description="Minimum gap between (ink) bottom of the top element of a stack, and the (ink) top of the bottom element. Suggested: 3x default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "StackDisplayStyleGapMin", + description="Minimum gap between (ink) bottom of the top element of a stack, and the (ink) top of the bottom element in display style. Suggested: 7x default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "StretchStackTopShiftUp", + description="Standard shift up applied to the top element of the stretch stack.", + ), + FieldSpec( + "MathValueRecord", + "StretchStackBottomShiftDown", + description="Standard shift down applied to the bottom element of the stretch stack. Positive for moving in the downward direction.", + ), + FieldSpec( + "MathValueRecord", + "StretchStackGapAboveMin", + description="Minimum gap between the ink of the stretched element, and the (ink) bottom of the element above. Suggested: UpperLimitGapMin", + ), + FieldSpec( + "MathValueRecord", + "StretchStackGapBelowMin", + description="Minimum gap between the ink of the stretched element, and the (ink) top of the element below. Suggested: LowerLimitGapMin.", + ), + FieldSpec( + "MathValueRecord", + "FractionNumeratorShiftUp", + description="Standard shift up applied to the numerator.", + ), + FieldSpec( + "MathValueRecord", + "FractionNumeratorDisplayStyleShiftUp", + description="Standard shift up applied to the numerator in display style. Suggested: StackTopDisplayStyleShiftUp.", + ), + FieldSpec( + "MathValueRecord", + "FractionDenominatorShiftDown", + description="Standard shift down applied to the denominator. Positive for moving in the downward direction.", + ), + FieldSpec( + "MathValueRecord", + "FractionDenominatorDisplayStyleShiftDown", + description="Standard shift down applied to the denominator in display style. Positive for moving in the downward direction. Suggested: StackBottomDisplayStyleShiftDown.", + ), + FieldSpec( + "MathValueRecord", + "FractionNumeratorGapMin", + description="Minimum tolerated gap between the (ink) bottom of the numerator and the ink of the fraction bar. Suggested: default rule thickness", + ), + FieldSpec( + "MathValueRecord", + "FractionNumDisplayStyleGapMin", + description="Minimum tolerated gap between the (ink) bottom of the numerator and the ink of the fraction bar in display style. Suggested: 3x default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "FractionRuleThickness", + description="Thickness of the fraction bar. Suggested: default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "FractionDenominatorGapMin", + description="Minimum tolerated gap between the (ink) top of the denominator and the ink of the fraction bar. Suggested: default rule thickness", + ), + FieldSpec( + "MathValueRecord", + "FractionDenomDisplayStyleGapMin", + description="Minimum tolerated gap between the (ink) top of the denominator and the ink of the fraction bar in display style. Suggested: 3x default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "SkewedFractionHorizontalGap", + description="Horizontal distance between the top and bottom elements of a skewed fraction.", + ), + FieldSpec( + "MathValueRecord", + "SkewedFractionVerticalGap", + description="Vertical distance between the ink of the top and bottom elements of a skewed fraction.", + ), + FieldSpec( + "MathValueRecord", + "OverbarVerticalGap", + description="Distance between the overbar and the (ink) top of he base. Suggested: 3x default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "OverbarRuleThickness", + description="Thickness of overbar. Suggested: default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "OverbarExtraAscender", + description="Extra white space reserved above the overbar. Suggested: default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "UnderbarVerticalGap", + description="Distance between underbar and (ink) bottom of the base. Suggested: 3x default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "UnderbarRuleThickness", + description="Thickness of underbar. Suggested: default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "UnderbarExtraDescender", + description="Extra white space reserved below the underbar. Always positive. Suggested: default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "RadicalVerticalGap", + description="Space between the (ink) top of the expression and the bar over it. Suggested: 1 1/4 default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "RadicalDisplayStyleVerticalGap", + description="Space between the (ink) top of the expression and the bar over it. Suggested: default rule thickness + 1/4 x-height.", + ), + FieldSpec( + "MathValueRecord", + "RadicalRuleThickness", + description="Thickness of the radical rule. This is the thickness of the rule in designed or constructed radical signs. Suggested: default rule thickness.", + ), + FieldSpec( + "MathValueRecord", + "RadicalExtraAscender", + description="Extra white space reserved above the radical. Suggested: RadicalRuleThickness.", + ), + FieldSpec( + "MathValueRecord", + "RadicalKernBeforeDegree", + description="Extra horizontal kern before the degree of a radical, if such is present. Suggested: 5/18 of em.", + ), + FieldSpec( + "MathValueRecord", + "RadicalKernAfterDegree", + description="Negative kern after the degree of a radical, if such is present. Suggested: 10/18 of em.", + ), + FieldSpec( + "uint16", + "RadicalDegreeBottomRaisePercent", + description="Height of the bottom of the radical degree, if such is present, in proportion to the ascender of the radical sign. Suggested: 60%.", + ), + ], + ), + ( + "MathGlyphInfo", + [ + FieldSpec( + "Offset", + "MathItalicsCorrectionInfo", + description="Offset to MathItalicsCorrectionInfo table - from the beginning of MathGlyphInfo table.", + ), + FieldSpec( + "Offset", + "MathTopAccentAttachment", + description="Offset to MathTopAccentAttachment table - from the beginning of MathGlyphInfo table.", + ), + FieldSpec( + "Offset", + "ExtendedShapeCoverage", + description="Offset to coverage table for Extended Shape glyphs - from the beginning of MathGlyphInfo table. When the left or right glyph of a box is an extended shape variant, the (ink) box (and not the default position defined by values in MathConstants table) should be used for vertical positioning purposes. May be NULL.", + ), + FieldSpec( + "Offset", + "MathKernInfo", + description="Offset to MathKernInfo table - from the beginning of MathGlyphInfo table.", + ), + ], + ), + ( + "MathItalicsCorrectionInfo", + [ + FieldSpec( + "Offset", + "Coverage", + description="Offset to Coverage table - from the beginning of MathItalicsCorrectionInfo table.", + ), + FieldSpec( + "uint16", + "ItalicsCorrectionCount", + description="Number of italics correction values. Should coincide with the number of covered glyphs.", + ), + FieldSpec( + "MathValueRecord", + "ItalicsCorrection", + repeat="ItalicsCorrectionCount", + aux=0, + description="Array of MathValueRecords defining italics correction values for each covered glyph.", + ), + ], + ), + ( + "MathTopAccentAttachment", + [ + FieldSpec( + "Offset", + "TopAccentCoverage", + description="Offset to Coverage table - from the beginning of MathTopAccentAttachment table.", + ), + FieldSpec( + "uint16", + "TopAccentAttachmentCount", + description="Number of top accent attachment point values. Should coincide with the number of covered glyphs", + ), + FieldSpec( + "MathValueRecord", + "TopAccentAttachment", + repeat="TopAccentAttachmentCount", + aux=0, + description="Array of MathValueRecords defining top accent attachment points for each covered glyph", + ), + ], + ), + ( + "MathKernInfo", + [ + FieldSpec( + "Offset", + "MathKernCoverage", + description="Offset to Coverage table - from the beginning of the MathKernInfo table.", + ), + FieldSpec( + "uint16", "MathKernCount", description="Number of MathKernInfoRecords." + ), + FieldSpec( + "MathKernInfoRecord", + "MathKernInfoRecords", + repeat="MathKernCount", + aux=0, + description="Array of MathKernInfoRecords, per-glyph information for mathematical positioning of subscripts and superscripts.", + ), + ], + ), + ( + "MathKernInfoRecord", + [ + FieldSpec( + "Offset", + "TopRightMathKern", + description="Offset to MathKern table for top right corner - from the beginning of MathKernInfo table. May be NULL.", + ), + FieldSpec( + "Offset", + "TopLeftMathKern", + description="Offset to MathKern table for the top left corner - from the beginning of MathKernInfo table. May be NULL.", + ), + FieldSpec( + "Offset", + "BottomRightMathKern", + description="Offset to MathKern table for bottom right corner - from the beginning of MathKernInfo table. May be NULL.", + ), + FieldSpec( + "Offset", + "BottomLeftMathKern", + description="Offset to MathKern table for bottom left corner - from the beginning of MathKernInfo table. May be NULL.", + ), + ], + ), + ( + "MathKern", + [ + FieldSpec( + "uint16", + "HeightCount", + description="Number of heights on which the kern value changes.", + ), + FieldSpec( + "MathValueRecord", + "CorrectionHeight", + repeat="HeightCount", + aux=0, + description="Array of correction heights at which the kern value changes. Sorted by the height value in design units.", + ), + FieldSpec( + "MathValueRecord", + "KernValue", + repeat="HeightCount", + aux=1, + description="Array of kern values corresponding to heights. First value is the kern value for all heights less or equal than the first height in this table.Last value is the value to be applied for all heights greater than the last height in this table. Negative values are interpreted as move glyphs closer to each other.", + ), + ], + ), + ( + "MathVariants", + [ + FieldSpec( + "uint16", + "MinConnectorOverlap", + description="Minimum overlap of connecting glyphs during glyph construction, in design units.", + ), + FieldSpec( + "Offset", + "VertGlyphCoverage", + description="Offset to Coverage table - from the beginning of MathVariants table.", + ), + FieldSpec( + "Offset", + "HorizGlyphCoverage", + description="Offset to Coverage table - from the beginning of MathVariants table.", + ), + FieldSpec( + "uint16", + "VertGlyphCount", + description="Number of glyphs for which information is provided for vertically growing variants.", + ), + FieldSpec( + "uint16", + "HorizGlyphCount", + description="Number of glyphs for which information is provided for horizontally growing variants.", + ), + FieldSpec( + "Offset", + "VertGlyphConstruction", + repeat="VertGlyphCount", + aux=0, + description="Array of offsets to MathGlyphConstruction tables - from the beginning of the MathVariants table, for shapes growing in vertical direction.", + ), + FieldSpec( + "Offset", + "HorizGlyphConstruction", + repeat="HorizGlyphCount", + aux=0, + description="Array of offsets to MathGlyphConstruction tables - from the beginning of the MathVariants table, for shapes growing in horizontal direction.", + ), + ], + ), + ( + "MathGlyphConstruction", + [ + FieldSpec( + "Offset", + "GlyphAssembly", + description="Offset to GlyphAssembly table for this shape - from the beginning of MathGlyphConstruction table. May be NULL", + ), + FieldSpec( + "uint16", + "VariantCount", + description="Count of glyph growing variants for this glyph.", + ), + FieldSpec( + "MathGlyphVariantRecord", + "MathGlyphVariantRecord", + repeat="VariantCount", + aux=0, + description="MathGlyphVariantRecords for alternative variants of the glyphs.", + ), + ], + ), + ( + "MathGlyphVariantRecord", + [ + FieldSpec( + "GlyphID", "VariantGlyph", description="Glyph ID for the variant." + ), + FieldSpec( + "uint16", + "AdvanceMeasurement", + description="Advance width/height, in design units, of the variant, in the direction of requested glyph extension.", + ), + ], + ), + ( + "GlyphAssembly", + [ + FieldSpec( + "MathValueRecord", + "ItalicsCorrection", + description="Italics correction of this GlyphAssembly. Should not depend on the assembly size.", + ), + FieldSpec( + "uint16", "PartCount", description="Number of parts in this assembly." + ), + FieldSpec( + "GlyphPartRecord", + "PartRecords", + repeat="PartCount", + aux=0, + description="Array of part records, from left to right and bottom to top.", + ), + ], + ), + ( + "GlyphPartRecord", + [ + FieldSpec("GlyphID", "glyph", description="Glyph ID for the part."), + FieldSpec( + "uint16", + "StartConnectorLength", + description="Advance width/ height of the straight bar connector material, in design units, is at the beginning of the glyph, in the direction of the extension.", + ), + FieldSpec( + "uint16", + "EndConnectorLength", + description="Advance width/ height of the straight bar connector material, in design units, is at the end of the glyph, in the direction of the extension.", + ), + FieldSpec( + "uint16", + "FullAdvance", + description="Full advance width/height for this part, in the direction of the extension. In design units.", + ), + FieldSpec( + "uint16", + "PartFlags", + description="Part qualifiers. PartFlags enumeration currently uses only one bit: 0x0001 fExtender: If set, the part can be skipped or repeated. 0xFFFE Reserved", + ), + ], + ), + ## + ## Apple Advanced Typography (AAT) tables + ## + ( + "AATLookupSegment", + [ + FieldSpec( + "uint16", "lastGlyph", description="Last glyph index in this segment." + ), + FieldSpec( + "uint16", "firstGlyph", description="First glyph index in this segment." + ), + FieldSpec( + "uint16", + "value", + description="A 16-bit offset from the start of the table to the data.", + ), + ], + ), + # + # ankr + # + ( + "ankr", + [ + FieldSpec("struct", "AnchorPoints", description="Anchor points table."), + ], + ), + ( + "AnchorPointsFormat0", + [ + FieldSpec( + "uint16", + "Format", + description="Format of the anchor points table, = 0.", + ), + FieldSpec( + "uint16", "Flags", description="Flags. Currenty unused, set to zero." + ), + FieldSpec( + "AATLookupWithDataOffset(AnchorGlyphData)", + "Anchors", + description="Table of with anchor overrides for each glyph.", + ), + ], + ), + ( + "AnchorGlyphData", + [ + FieldSpec( + "uint32", + "AnchorPointCount", + description="Number of anchor points for this glyph.", + ), + FieldSpec( + "struct", + "AnchorPoint", + repeat="AnchorPointCount", + aux=0, + description="Individual anchor points.", + ), + ], + ), + ( + "AnchorPoint", + [ + FieldSpec( + "int16", "XCoordinate", description="X coordinate of this anchor point." + ), + FieldSpec( + "int16", "YCoordinate", description="Y coordinate of this anchor point." + ), + ], + ), + # + # bsln + # + ( + "bsln", + [ + FieldSpec( + "Version", + "Version", + description="Version number of the AAT baseline table (0x00010000 for the initial version).", + ), + FieldSpec("struct", "Baseline", description="Baseline table."), + ], + ), + ( + "BaselineFormat0", + [ + FieldSpec( + "uint16", "Format", description="Format of the baseline table, = 0." + ), + FieldSpec( + "uint16", + "DefaultBaseline", + description="Default baseline value for all glyphs. This value can be from 0 through 31.", + ), + FieldSpec( + "uint16", + "Delta", + repeat=32, + aux=0, + description="These are the FUnit distance deltas from the font’s natural baseline to the other baselines used in the font. A total of 32 deltas must be assigned.", + ), + ], + ), + ( + "BaselineFormat1", + [ + FieldSpec( + "uint16", "Format", description="Format of the baseline table, = 1." + ), + FieldSpec( + "uint16", + "DefaultBaseline", + description="Default baseline value for all glyphs. This value can be from 0 through 31.", + ), + FieldSpec( + "uint16", + "Delta", + repeat=32, + aux=0, + description="These are the FUnit distance deltas from the font’s natural baseline to the other baselines used in the font. A total of 32 deltas must be assigned.", + ), + FieldSpec( + "AATLookup(uint16)", + "BaselineValues", + description="Lookup table that maps glyphs to their baseline values.", + ), + ], + ), + ( + "BaselineFormat2", + [ + FieldSpec( + "uint16", "Format", description="Format of the baseline table, = 1." + ), + FieldSpec( + "uint16", + "DefaultBaseline", + description="Default baseline value for all glyphs. This value can be from 0 through 31.", + ), + FieldSpec( + "GlyphID", + "StandardGlyph", + description="Glyph index of the glyph in this font to be used to set the baseline values. This glyph must contain a set of control points (whose numbers are contained in the following field) that determines baseline distances.", + ), + FieldSpec( + "uint16", + "ControlPoint", + repeat=32, + aux=0, + description="Array of 32 control point numbers, associated with the standard glyph. A value of 0xFFFF means there is no corresponding control point in the standard glyph.", + ), + ], + ), + ( + "BaselineFormat3", + [ + FieldSpec( + "uint16", "Format", description="Format of the baseline table, = 1." + ), + FieldSpec( + "uint16", + "DefaultBaseline", + description="Default baseline value for all glyphs. This value can be from 0 through 31.", + ), + FieldSpec( + "GlyphID", + "StandardGlyph", + description="Glyph index of the glyph in this font to be used to set the baseline values. This glyph must contain a set of control points (whose numbers are contained in the following field) that determines baseline distances.", + ), + FieldSpec( + "uint16", + "ControlPoint", + repeat=32, + aux=0, + description="Array of 32 control point numbers, associated with the standard glyph. A value of 0xFFFF means there is no corresponding control point in the standard glyph.", + ), + FieldSpec( + "AATLookup(uint16)", + "BaselineValues", + description="Lookup table that maps glyphs to their baseline values.", + ), + ], + ), + # + # cidg + # + ( + "cidg", + [ + FieldSpec( + "struct", "CIDGlyphMapping", description="CID-to-glyph mapping table." + ), + ], + ), + ( + "CIDGlyphMappingFormat0", + [ + FieldSpec( + "uint16", + "Format", + description="Format of the CID-to-glyph mapping table, = 0.", + ), + FieldSpec( + "uint16", "DataFormat", description="Currenty unused, set to zero." + ), + FieldSpec( + "uint32", "StructLength", description="Size of the table in bytes." + ), + FieldSpec("uint16", "Registry", description="The registry ID."), + FieldSpec( + "char64", + "RegistryName", + description="The registry name in ASCII; unused bytes should be set to 0.", + ), + FieldSpec("uint16", "Order", description="The order ID."), + FieldSpec( + "char64", + "OrderName", + description="The order name in ASCII; unused bytes should be set to 0.", + ), + FieldSpec( + "uint16", "SupplementVersion", description="The supplement version." + ), + FieldSpec( + "CIDGlyphMap", + "Mapping", + description="A mapping from CIDs to the glyphs in the font, starting with CID 0. If a CID from the identified collection has no glyph in the font, 0xFFFF is used", + ), + ], + ), + # + # feat + # + ( + "feat", + [ + FieldSpec( + "Version", + "Version", + description="Version of the feat table-initially set to 0x00010000.", + ), + FieldSpec("FeatureNames", "FeatureNames", description="The feature names."), + ], + ), + ( + "FeatureNames", + [ + FieldSpec( + "uint16", + "FeatureNameCount", + description="Number of entries in the feature name array.", + ), + FieldSpec("uint16", "Reserved1", description="Reserved (set to zero)."), + FieldSpec("uint32", "Reserved2", description="Reserved (set to zero)."), + FieldSpec( + "FeatureName", + "FeatureName", + repeat="FeatureNameCount", + aux=0, + description="The feature name array.", + ), + ], + ), + ( + "FeatureName", + [ + FieldSpec("uint16", "FeatureType", description="Feature type."), + FieldSpec( + "uint16", + "SettingsCount", + description="The number of records in the setting name array.", + ), + FieldSpec( + "LOffset", + "Settings", + description="Offset to setting table for this feature.", + ), + FieldSpec( + "uint16", + "FeatureFlags", + description="Single-bit flags associated with the feature type.", + ), + FieldSpec( + "NameID", + "FeatureNameID", + description="The name table index for the feature name.", + ), + ], + ), + ( + "Settings", + [ + FieldSpec( + "Setting", + "Setting", + repeat="SettingsCount", + aux=0, + description="The setting array.", + ), + ], + ), + ( + "Setting", + [ + FieldSpec("uint16", "SettingValue", description="The setting."), + FieldSpec( + "NameID", + "SettingNameID", + description="The name table index for the setting name.", + ), + ], + ), + # + # gcid + # + ( + "gcid", + [ + FieldSpec( + "struct", "GlyphCIDMapping", description="Glyph to CID mapping table." + ), + ], + ), + ( + "GlyphCIDMappingFormat0", + [ + FieldSpec( + "uint16", + "Format", + description="Format of the glyph-to-CID mapping table, = 0.", + ), + FieldSpec( + "uint16", "DataFormat", description="Currenty unused, set to zero." + ), + FieldSpec( + "uint32", "StructLength", description="Size of the table in bytes." + ), + FieldSpec("uint16", "Registry", description="The registry ID."), + FieldSpec( + "char64", + "RegistryName", + description="The registry name in ASCII; unused bytes should be set to 0.", + ), + FieldSpec("uint16", "Order", description="The order ID."), + FieldSpec( + "char64", + "OrderName", + description="The order name in ASCII; unused bytes should be set to 0.", + ), + FieldSpec( + "uint16", "SupplementVersion", description="The supplement version." + ), + FieldSpec( + "GlyphCIDMap", + "Mapping", + description="The CIDs for the glyphs in the font, starting with glyph 0. If a glyph does not correspond to a CID in the identified collection, 0xFFFF is used", + ), + ], + ), + # + # lcar + # + ( + "lcar", + [ + FieldSpec( + "Version", + "Version", + description="Version number of the ligature caret table (0x00010000 for the initial version).", + ), + FieldSpec("struct", "LigatureCarets", description="Ligature carets table."), + ], + ), + ( + "LigatureCaretsFormat0", + [ + FieldSpec( + "uint16", + "Format", + description="Format of the ligature caret table. Format 0 indicates division points are distances in font units, Format 1 indicates division points are indexes of control points.", + ), + FieldSpec( + "AATLookup(LigCaretDistances)", + "Carets", + description="Lookup table associating ligature glyphs with their caret positions, in font unit distances.", + ), + ], + ), + ( + "LigatureCaretsFormat1", + [ + FieldSpec( + "uint16", + "Format", + description="Format of the ligature caret table. Format 0 indicates division points are distances in font units, Format 1 indicates division points are indexes of control points.", + ), + FieldSpec( + "AATLookup(LigCaretPoints)", + "Carets", + description="Lookup table associating ligature glyphs with their caret positions, as control points.", + ), + ], + ), + ( + "LigCaretDistances", + [ + FieldSpec( + "uint16", "DivsionPointCount", description="Number of division points." + ), + FieldSpec( + "int16", + "DivisionPoint", + repeat="DivsionPointCount", + aux=0, + description="Distance in font units through which a subdivision is made orthogonally to the baseline.", + ), + ], + ), + ( + "LigCaretPoints", + [ + FieldSpec( + "uint16", "DivsionPointCount", description="Number of division points." + ), + FieldSpec( + "int16", + "DivisionPoint", + repeat="DivsionPointCount", + aux=0, + description="The number of the control point through which a subdivision is made orthogonally to the baseline.", + ), + ], + ), + # + # mort + # + ( + "mort", + [ + FieldSpec("Version", "Version", description="Version of the mort table."), + FieldSpec( + "uint32", + "MorphChainCount", + description="Number of metamorphosis chains.", + ), + FieldSpec( + "MortChain", + "MorphChain", + repeat="MorphChainCount", + aux=0, + description="Array of metamorphosis chains.", + ), + ], + ), + ( + "MortChain", + [ + FieldSpec( + "Flags32", + "DefaultFlags", + description="The default specification for subtables.", + ), + FieldSpec( + "uint32", + "StructLength", + description="Total byte count, including this header; must be a multiple of 4.", + ), + FieldSpec( + "uint16", + "MorphFeatureCount", + description="Number of metamorphosis feature entries.", + ), + FieldSpec( + "uint16", + "MorphSubtableCount", + description="The number of subtables in the chain.", + ), + FieldSpec( + "struct", + "MorphFeature", + repeat="MorphFeatureCount", + aux=0, + description="Array of metamorphosis features.", + ), + FieldSpec( + "MortSubtable", + "MorphSubtable", + repeat="MorphSubtableCount", + aux=0, + description="Array of metamorphosis subtables.", + ), + ], + ), + ( + "MortSubtable", + [ + FieldSpec( + "uint16", + "StructLength", + description="Total subtable length, including this header.", + ), + FieldSpec( + "uint8", + "CoverageFlags", + description="Most significant byte of coverage flags.", + ), + FieldSpec("uint8", "MorphType", description="Subtable type."), + FieldSpec( + "Flags32", + "SubFeatureFlags", + description="The 32-bit mask identifying which subtable this is (the subtable being executed if the AND of this value and the processed defaultFlags is nonzero).", + ), + FieldSpec("SubStruct", "SubStruct", description="SubTable."), + ], + ), + # + # morx + # + ( + "morx", + [ + FieldSpec("uint16", "Version", description="Version of the morx table."), + FieldSpec("uint16", "Reserved", description="Reserved (set to zero)."), + FieldSpec( + "uint32", + "MorphChainCount", + description="Number of extended metamorphosis chains.", + ), + FieldSpec( + "MorxChain", + "MorphChain", + repeat="MorphChainCount", + aux=0, + description="Array of extended metamorphosis chains.", + ), + ], + ), + ( + "MorxChain", + [ + FieldSpec( + "Flags32", + "DefaultFlags", + description="The default specification for subtables.", + ), + FieldSpec( + "uint32", + "StructLength", + description="Total byte count, including this header; must be a multiple of 4.", + ), + FieldSpec( + "uint32", + "MorphFeatureCount", + description="Number of feature subtable entries.", + ), + FieldSpec( + "uint32", + "MorphSubtableCount", + description="The number of subtables in the chain.", + ), + FieldSpec( + "MorphFeature", + "MorphFeature", + repeat="MorphFeatureCount", + aux=0, + description="Array of metamorphosis features.", + ), + FieldSpec( + "MorxSubtable", + "MorphSubtable", + repeat="MorphSubtableCount", + aux=0, + description="Array of extended metamorphosis subtables.", + ), + ], + ), + ( + "MorphFeature", + [ + FieldSpec("uint16", "FeatureType", description="The type of feature."), + FieldSpec( + "uint16", + "FeatureSetting", + description="The feature's setting (aka selector).", + ), + FieldSpec( + "Flags32", + "EnableFlags", + description="Flags for the settings that this feature and setting enables.", + ), + FieldSpec( + "Flags32", + "DisableFlags", + description="Complement of flags for the settings that this feature and setting disable.", + ), + ], + ), + # Apple TrueType Reference Manual, chapter “The ‘morx’ table”, + # section “Metamorphosis Subtables”. + # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html + ( + "MorxSubtable", + [ + FieldSpec( + "uint32", + "StructLength", + description="Total subtable length, including this header.", + ), + FieldSpec( + "uint8", + "CoverageFlags", + description="Most significant byte of coverage flags.", + ), + FieldSpec("uint16", "Reserved", description="Unused."), + FieldSpec("uint8", "MorphType", description="Subtable type."), + FieldSpec( + "Flags32", + "SubFeatureFlags", + description="The 32-bit mask identifying which subtable this is (the subtable being executed if the AND of this value and the processed defaultFlags is nonzero).", + ), + FieldSpec("SubStruct", "SubStruct", description="SubTable."), + ], + ), + ( + "StateHeader", + [ + FieldSpec( + "uint32", + "ClassCount", + description="Number of classes, which is the number of 16-bit entry indices in a single line in the state array.", + ), + FieldSpec( + "uint32", + "MorphClass", + description="Offset from the start of this state table header to the start of the class table.", + ), + FieldSpec( + "uint32", + "StateArrayOffset", + description="Offset from the start of this state table header to the start of the state array.", + ), + FieldSpec( + "uint32", + "EntryTableOffset", + description="Offset from the start of this state table header to the start of the entry table.", + ), + ], + ), + ( + "RearrangementMorph", + [ + FieldSpec( + "MorphStateTable(RearrangementMorphAction)", + "StateTable", + description="Finite-state transducer table for indic rearrangement.", + ), + ], + ), + ( + "ContextualMorph", + [ + FieldSpec( + "MorphStateTable(ContextualMorphAction)", + "StateTable", + description="Finite-state transducer for contextual glyph substitution.", + ), + ], + ), + ( + "LigatureMorph", + [ + FieldSpec( + "MorphStateTable(LigatureMorphAction)", + "StateTable", + description="Finite-state transducer for ligature substitution.", + ), + ], + ), + ( + "NoncontextualMorph", + [ + FieldSpec( + "AATLookup(GlyphID)", + "Substitution", + description="The noncontextual glyph substitution table.", + ), + ], + ), + ( + "InsertionMorph", + [ + FieldSpec( + "MorphStateTable(InsertionMorphAction)", + "StateTable", + description="Finite-state transducer for glyph insertion.", + ), + ], + ), + ( + "MorphClass", + [ + FieldSpec( + "uint16", + "FirstGlyph", + description="Glyph index of the first glyph in the class table.", + ), + # ('uint16', 'GlyphCount', None, None, 'Number of glyphs in class table.'), + # ('uint8', 'GlyphClass', 'GlyphCount', 0, 'The class codes (indexed by glyph index minus firstGlyph). Class codes range from 0 to the value of stateSize minus 1.'), + ], + ), + # If the 'morx' table version is 3 or greater, then the last subtable in the chain is followed by a subtableGlyphCoverageArray, as described below. + # ('Offset', 'MarkGlyphSetsDef', None, 'round(Version*0x10000) >= 0x00010002', 'Offset to the table of mark set definitions-from beginning of GDEF header (may be NULL)'), + # + # prop + # + ( + "prop", + [ + FieldSpec( + "Fixed", + "Version", + description="Version number of the AAT glyphs property table. Version 1.0 is the initial table version. Version 2.0, which is recognized by macOS 8.5 and later, adds support for the “attaches on right” bit. Version 3.0, which gets recognized by macOS X and iOS, adds support for the additional directional properties defined in Unicode 3.0.", + ), + FieldSpec("struct", "GlyphProperties", description="Glyph properties."), + ], + ), + ( + "GlyphPropertiesFormat0", + [ + FieldSpec("uint16", "Format", description="Format, = 0."), + FieldSpec( + "uint16", + "DefaultProperties", + description="Default properties applied to a glyph. Since there is no lookup table in prop format 0, the default properties get applied to every glyph in the font.", + ), + ], + ), + ( + "GlyphPropertiesFormat1", + [ + FieldSpec("uint16", "Format", description="Format, = 1."), + FieldSpec( + "uint16", + "DefaultProperties", + description="Default properties applied to a glyph if that glyph is not present in the Properties lookup table.", + ), + FieldSpec( + "AATLookup(uint16)", + "Properties", + description="Lookup data associating glyphs with their properties.", + ), + ], + ), + # + # opbd + # + ( + "opbd", + [ + FieldSpec( + "Version", + "Version", + description="Version number of the optical bounds table (0x00010000 for the initial version).", + ), + FieldSpec("struct", "OpticalBounds", description="Optical bounds table."), + ], + ), + ( + "OpticalBoundsFormat0", + [ + FieldSpec( + "uint16", + "Format", + description="Format of the optical bounds table, = 0.", + ), + FieldSpec( + "AATLookup(OpticalBoundsDeltas)", + "OpticalBoundsDeltas", + description="Lookup table associating glyphs with their optical bounds, given as deltas in font units.", + ), + ], + ), + ( + "OpticalBoundsFormat1", + [ + FieldSpec( + "uint16", + "Format", + description="Format of the optical bounds table, = 1.", + ), + FieldSpec( + "AATLookup(OpticalBoundsPoints)", + "OpticalBoundsPoints", + description="Lookup table associating glyphs with their optical bounds, given as references to control points.", + ), + ], + ), + ( + "OpticalBoundsDeltas", + [ + FieldSpec( + "int16", + "Left", + description="Delta value for the left-side optical edge.", + ), + FieldSpec( + "int16", "Top", description="Delta value for the top-side optical edge." + ), + FieldSpec( + "int16", + "Right", + description="Delta value for the right-side optical edge.", + ), + FieldSpec( + "int16", + "Bottom", + description="Delta value for the bottom-side optical edge.", + ), + ], + ), + ( + "OpticalBoundsPoints", + [ + FieldSpec( + "int16", + "Left", + description="Control point index for the left-side optical edge, or -1 if this glyph has none.", + ), + FieldSpec( + "int16", + "Top", + description="Control point index for the top-side optical edge, or -1 if this glyph has none.", + ), + FieldSpec( + "int16", + "Right", + description="Control point index for the right-side optical edge, or -1 if this glyph has none.", + ), + FieldSpec( + "int16", + "Bottom", + description="Control point index for the bottom-side optical edge, or -1 if this glyph has none.", + ), + ], + ), + # + # TSIC + # + ( + "TSIC", + [ + FieldSpec( + "Version", + "Version", + description="Version of table initially set to 0x00010000.", + ), + FieldSpec("uint16", "Flags", description="TSIC flags - set to 0"), + FieldSpec("uint16", "AxisCount", description="Axis count from fvar"), + FieldSpec("uint16", "RecordCount", description="TSIC record count"), + FieldSpec("uint16", "Reserved", description="Set to 0"), + FieldSpec( + "Tag", + "AxisArray", + repeat="AxisCount", + aux=0, + description="Array of axis tags in fvar order", + ), + FieldSpec( + "LocationRecord", + "RecordLocations", + repeat="RecordCount", + aux=0, + description="Location in variation space of TSIC record", + ), + FieldSpec( + "TSICRecord", + "Record", + repeat="RecordCount", + aux=0, + description="Array of TSIC records", + ), + ], + ), + ( + "LocationRecord", + [ + FieldSpec( + "F2Dot14", "Axis", repeat="AxisCount", aux=0, description="Axis record" + ), + ], + ), + ( + "TSICRecord", + [ + FieldSpec("uint16", "Flags", description="Record flags - set to 0"), + FieldSpec( + "uint16", + "NumCVTEntries", + description="Number of CVT number value pairs", + ), + FieldSpec( + "uint16", + "NameLength", + description="Length of optional user record name", + ), + FieldSpec( + "uint16", + "NameArray", + repeat="NameLength", + aux=0, + description="Unicode 16 name", + ), + FieldSpec( + "uint16", + "CVTArray", + repeat="NumCVTEntries", + aux=0, + description="CVT number array", + ), + FieldSpec( + "int16", + "CVTValueArray", + repeat="NumCVTEntries", + aux=0, + description="CVT value", + ), + ], + ), + # + # COLR + # + ( + "COLR", + [ + FieldSpec( + "uint16", "Version", description="Table version number (starts at 0)." + ), + FieldSpec( + "uint16", + "BaseGlyphRecordCount", + description="Number of Base Glyph Records.", + ), + FieldSpec( + "LOffset", + "BaseGlyphRecordArray", + description="Offset (from beginning of COLR table) to Base Glyph records.", + ), + FieldSpec( + "LOffset", + "LayerRecordArray", + description="Offset (from beginning of COLR table) to Layer Records.", + ), + FieldSpec( + "uint16", "LayerRecordCount", description="Number of Layer Records." + ), + FieldSpec( + "LOffset", + "BaseGlyphList", + aux="Version >= 1", + description="Offset (from beginning of COLR table) to array of Version-1 Base Glyph records.", + ), + FieldSpec( + "LOffset", + "LayerList", + aux="Version >= 1", + description="Offset (from beginning of COLR table) to LayerList.", + ), + FieldSpec( + "LOffset", + "ClipList", + aux="Version >= 1", + description="Offset to ClipList table (may be NULL)", + ), + FieldSpec( + "LOffsetTo(DeltaSetIndexMap)", + "VarIndexMap", + aux="Version >= 1", + description="Offset to DeltaSetIndexMap table (may be NULL)", + ), + FieldSpec( + "LOffset", + "VarStore", + aux="Version >= 1", + description="Offset to variation store (may be NULL)", + ), + ], + ), + ( + "BaseGlyphRecordArray", + [ + FieldSpec( + "BaseGlyphRecord", + "BaseGlyphRecord", + repeat="BaseGlyphRecordCount", + aux=0, + description="Base Glyph records.", + ), + ], + ), + ( + "BaseGlyphRecord", + [ + FieldSpec( + "GlyphID", + "BaseGlyph", + description="Glyph ID of reference glyph. This glyph is for reference only and is not rendered for color.", + ), + FieldSpec( + "uint16", + "FirstLayerIndex", + description="Index (from beginning of the Layer Records) to the layer record. There will be numLayers consecutive entries for this base glyph.", + ), + FieldSpec( + "uint16", + "NumLayers", + description="Number of color layers associated with this glyph.", + ), + ], + ), + ( + "LayerRecordArray", + [ + FieldSpec( + "LayerRecord", + "LayerRecord", + repeat="LayerRecordCount", + aux=0, + description="Layer records.", + ), + ], + ), + ( + "LayerRecord", + [ + FieldSpec( + "GlyphID", + "LayerGlyph", + description="Glyph ID of layer glyph (must be in z-order from bottom to top).", + ), + FieldSpec( + "uint16", + "PaletteIndex", + description="Index value to use with a selected color palette.", + ), + ], + ), + ( + "BaseGlyphList", + [ + FieldSpec( + "uint32", + "BaseGlyphCount", + description="Number of Version-1 Base Glyph records", + ), + FieldSpec( + "struct", + "BaseGlyphPaintRecord", + repeat="BaseGlyphCount", + aux=0, + description="Array of Version-1 Base Glyph records", + ), + ], + ), + ( + "BaseGlyphPaintRecord", + [ + FieldSpec( + "GlyphID", "BaseGlyph", description="Glyph ID of reference glyph." + ), + FieldSpec( + "LOffset", + "Paint", + description="Offset (from beginning of BaseGlyphPaintRecord) to Paint, typically a PaintColrLayers.", + ), + ], + ), + ( + "LayerList", + [ + FieldSpec("uint32", "LayerCount", description="Number of Version-1 Layers"), + FieldSpec( + "LOffset", + "Paint", + repeat="LayerCount", + aux=0, + description="Array of offsets to Paint tables, from the start of the LayerList table.", + ), + ], + ), + ( + "ClipListFormat1", + [ + FieldSpec( + "uint8", + "Format", + description="Format for ClipList with 16bit glyph IDs: 1", + ), + FieldSpec("uint32", "ClipCount", description="Number of Clip records."), + FieldSpec( + "struct", + "ClipRecord", + repeat="ClipCount", + aux=0, + description="Array of Clip records sorted by glyph ID.", + ), + ], + ), + ( + "ClipRecord", + [ + FieldSpec( + "uint16", "StartGlyphID", description="First glyph ID in the range." + ), + FieldSpec( + "uint16", "EndGlyphID", description="Last glyph ID in the range." + ), + FieldSpec("Offset24", "ClipBox", description="Offset to a ClipBox table."), + ], + ), + ( + "ClipBoxFormat1", + [ + FieldSpec( + "uint8", + "Format", + description="Format for ClipBox without variation: set to 1.", + ), + FieldSpec("int16", "xMin", description="Minimum x of clip box."), + FieldSpec("int16", "yMin", description="Minimum y of clip box."), + FieldSpec("int16", "xMax", description="Maximum x of clip box."), + FieldSpec("int16", "yMax", description="Maximum y of clip box."), + ], + ), + ( + "ClipBoxFormat2", + [ + FieldSpec( + "uint8", "Format", description="Format for variable ClipBox: set to 2." + ), + FieldSpec( + "int16", "xMin", description="Minimum x of clip box. VarIndexBase + 0." + ), + FieldSpec( + "int16", "yMin", description="Minimum y of clip box. VarIndexBase + 1." + ), + FieldSpec( + "int16", "xMax", description="Maximum x of clip box. VarIndexBase + 2." + ), + FieldSpec( + "int16", "yMax", description="Maximum y of clip box. VarIndexBase + 3." + ), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # COLRv1 Affine2x3 uses the same column-major order to serialize a 2D + # Affine Transformation as the one used by fontTools.misc.transform. + # However, for historical reasons, the labels 'xy' and 'yx' are swapped. + # Their fundamental meaning is the same though. + # COLRv1 Affine2x3 follows the names found in FreeType and Cairo. + # In all case, the second element in the 6-tuple correspond to the + # y-part of the x basis vector, and the third to the x-part of the y + # basis vector. + # See https://github.com/googlefonts/colr-gradients-spec/pull/85 + ( + "Affine2x3", + [ + FieldSpec("Fixed", "xx", description="x-part of x basis vector"), + FieldSpec("Fixed", "yx", description="y-part of x basis vector"), + FieldSpec("Fixed", "xy", description="x-part of y basis vector"), + FieldSpec("Fixed", "yy", description="y-part of y basis vector"), + FieldSpec("Fixed", "dx", description="Translation in x direction"), + FieldSpec("Fixed", "dy", description="Translation in y direction"), + ], + ), + ( + "VarAffine2x3", + [ + FieldSpec( + "Fixed", "xx", description="x-part of x basis vector. VarIndexBase + 0." + ), + FieldSpec( + "Fixed", "yx", description="y-part of x basis vector. VarIndexBase + 1." + ), + FieldSpec( + "Fixed", "xy", description="x-part of y basis vector. VarIndexBase + 2." + ), + FieldSpec( + "Fixed", "yy", description="y-part of y basis vector. VarIndexBase + 3." + ), + FieldSpec( + "Fixed", + "dx", + description="Translation in x direction. VarIndexBase + 4.", + ), + FieldSpec( + "Fixed", + "dy", + description="Translation in y direction. VarIndexBase + 5.", + ), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + ( + "ColorStop", + [ + FieldSpec("F2Dot14", "StopOffset"), + FieldSpec( + "uint16", "PaletteIndex", description="Index for a CPAL palette entry." + ), + FieldSpec( + "F2Dot14", "Alpha", description="Values outsided [0.,1.] reserved" + ), + ], + ), + ( + "VarColorStop", + [ + FieldSpec("F2Dot14", "StopOffset", description="VarIndexBase + 0."), + FieldSpec( + "uint16", "PaletteIndex", description="Index for a CPAL palette entry." + ), + FieldSpec( + "F2Dot14", + "Alpha", + description="Values outsided [0.,1.] reserved. VarIndexBase + 1.", + ), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + ( + "ColorLine", + [ + FieldSpec( + "ExtendMode", + "Extend", + description="Enum {PAD = 0, REPEAT = 1, REFLECT = 2}", + ), + FieldSpec("uint16", "StopCount", description="Number of Color stops."), + FieldSpec( + "ColorStop", + "ColorStop", + repeat="StopCount", + aux=0, + description="Array of Color stops.", + ), + ], + ), + ( + "VarColorLine", + [ + FieldSpec( + "ExtendMode", + "Extend", + description="Enum {PAD = 0, REPEAT = 1, REFLECT = 2}", + ), + FieldSpec("uint16", "StopCount", description="Number of Color stops."), + FieldSpec( + "VarColorStop", + "ColorStop", + repeat="StopCount", + aux=0, + description="Array of Color stops.", + ), + ], + ), + # PaintColrLayers + ( + "PaintFormat1", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 1" + ), + FieldSpec( + "uint8", + "NumLayers", + description="Number of offsets to Paint to read from LayerList.", + ), + FieldSpec("uint32", "FirstLayerIndex", description="Index into LayerList."), + ], + ), + # PaintSolid + ( + "PaintFormat2", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 2" + ), + FieldSpec( + "uint16", "PaletteIndex", description="Index for a CPAL palette entry." + ), + FieldSpec( + "F2Dot14", "Alpha", description="Values outsided [0.,1.] reserved" + ), + ], + ), + # PaintVarSolid + ( + "PaintFormat3", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 3" + ), + FieldSpec( + "uint16", "PaletteIndex", description="Index for a CPAL palette entry." + ), + FieldSpec( + "F2Dot14", + "Alpha", + description="Values outsided [0.,1.] reserved. VarIndexBase + 0.", + ), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintLinearGradient + ( + "PaintFormat4", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 4" + ), + FieldSpec( + "Offset24", + "ColorLine", + description="Offset (from beginning of PaintLinearGradient table) to ColorLine subtable.", + ), + FieldSpec("int16", "x0"), + FieldSpec("int16", "y0"), + FieldSpec("int16", "x1"), + FieldSpec("int16", "y1"), + FieldSpec("int16", "x2"), + FieldSpec("int16", "y2"), + ], + ), + # PaintVarLinearGradient + ( + "PaintFormat5", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 5" + ), + FieldSpec( + "LOffset24To(VarColorLine)", + "ColorLine", + description="Offset (from beginning of PaintVarLinearGradient table) to VarColorLine subtable.", + ), + FieldSpec("int16", "x0", description="VarIndexBase + 0."), + FieldSpec("int16", "y0", description="VarIndexBase + 1."), + FieldSpec("int16", "x1", description="VarIndexBase + 2."), + FieldSpec("int16", "y1", description="VarIndexBase + 3."), + FieldSpec("int16", "x2", description="VarIndexBase + 4."), + FieldSpec("int16", "y2", description="VarIndexBase + 5."), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintRadialGradient + ( + "PaintFormat6", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 6" + ), + FieldSpec( + "Offset24", + "ColorLine", + description="Offset (from beginning of PaintRadialGradient table) to ColorLine subtable.", + ), + FieldSpec("int16", "x0"), + FieldSpec("int16", "y0"), + FieldSpec("uint16", "r0"), + FieldSpec("int16", "x1"), + FieldSpec("int16", "y1"), + FieldSpec("uint16", "r1"), + ], + ), + # PaintVarRadialGradient + ( + "PaintFormat7", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 7" + ), + FieldSpec( + "LOffset24To(VarColorLine)", + "ColorLine", + description="Offset (from beginning of PaintVarRadialGradient table) to VarColorLine subtable.", + ), + FieldSpec("int16", "x0", description="VarIndexBase + 0."), + FieldSpec("int16", "y0", description="VarIndexBase + 1."), + FieldSpec("uint16", "r0", description="VarIndexBase + 2."), + FieldSpec("int16", "x1", description="VarIndexBase + 3."), + FieldSpec("int16", "y1", description="VarIndexBase + 4."), + FieldSpec("uint16", "r1", description="VarIndexBase + 5."), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintSweepGradient + ( + "PaintFormat8", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 8" + ), + FieldSpec( + "Offset24", + "ColorLine", + description="Offset (from beginning of PaintSweepGradient table) to ColorLine subtable.", + ), + FieldSpec("int16", "centerX", description="Center x coordinate."), + FieldSpec("int16", "centerY", description="Center y coordinate."), + FieldSpec( + "BiasedAngle", + "startAngle", + description="Start of the angular range of the gradient.", + ), + FieldSpec( + "BiasedAngle", + "endAngle", + description="End of the angular range of the gradient.", + ), + ], + ), + # PaintVarSweepGradient + ( + "PaintFormat9", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 9" + ), + FieldSpec( + "LOffset24To(VarColorLine)", + "ColorLine", + description="Offset (from beginning of PaintVarSweepGradient table) to VarColorLine subtable.", + ), + FieldSpec( + "int16", "centerX", description="Center x coordinate. VarIndexBase + 0." + ), + FieldSpec( + "int16", "centerY", description="Center y coordinate. VarIndexBase + 1." + ), + FieldSpec( + "BiasedAngle", + "startAngle", + description="Start of the angular range of the gradient. VarIndexBase + 2.", + ), + FieldSpec( + "BiasedAngle", + "endAngle", + description="End of the angular range of the gradient. VarIndexBase + 3.", + ), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintGlyph + ( + "PaintFormat10", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 10" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintGlyph table) to Paint subtable.", + ), + FieldSpec( + "GlyphID", "Glyph", description="Glyph ID for the source outline." + ), + ], + ), + # PaintColrGlyph + ( + "PaintFormat11", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 11" + ), + FieldSpec( + "GlyphID", + "Glyph", + description="Virtual glyph ID for a BaseGlyphList base glyph.", + ), + ], + ), + # PaintTransform + ( + "PaintFormat12", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 12" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintTransform table) to Paint subtable.", + ), + FieldSpec( + "LOffset24To(Affine2x3)", + "Transform", + description="2x3 matrix for 2D affine transformations.", + ), + ], + ), + # PaintVarTransform + ( + "PaintFormat13", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 13" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintVarTransform table) to Paint subtable.", + ), + FieldSpec( + "LOffset24To(VarAffine2x3)", + "Transform", + description="2x3 matrix for 2D affine transformations.", + ), + ], + ), + # PaintTranslate + ( + "PaintFormat14", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 14" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintTranslate table) to Paint subtable.", + ), + FieldSpec("int16", "dx", description="Translation in x direction."), + FieldSpec("int16", "dy", description="Translation in y direction."), + ], + ), + # PaintVarTranslate + ( + "PaintFormat15", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 15" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintVarTranslate table) to Paint subtable.", + ), + FieldSpec( + "int16", + "dx", + description="Translation in x direction. VarIndexBase + 0.", + ), + FieldSpec( + "int16", + "dy", + description="Translation in y direction. VarIndexBase + 1.", + ), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintScale + ( + "PaintFormat16", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 16" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintScale table) to Paint subtable.", + ), + FieldSpec("F2Dot14", "scaleX"), + FieldSpec("F2Dot14", "scaleY"), + ], + ), + # PaintVarScale + ( + "PaintFormat17", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 17" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintVarScale table) to Paint subtable.", + ), + FieldSpec("F2Dot14", "scaleX", description="VarIndexBase + 0."), + FieldSpec("F2Dot14", "scaleY", description="VarIndexBase + 1."), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintScaleAroundCenter + ( + "PaintFormat18", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 18" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintScaleAroundCenter table) to Paint subtable.", + ), + FieldSpec("F2Dot14", "scaleX"), + FieldSpec("F2Dot14", "scaleY"), + FieldSpec("int16", "centerX"), + FieldSpec("int16", "centerY"), + ], + ), + # PaintVarScaleAroundCenter + ( + "PaintFormat19", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 19" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintVarScaleAroundCenter table) to Paint subtable.", + ), + FieldSpec("F2Dot14", "scaleX", description="VarIndexBase + 0."), + FieldSpec("F2Dot14", "scaleY", description="VarIndexBase + 1."), + FieldSpec("int16", "centerX", description="VarIndexBase + 2."), + FieldSpec("int16", "centerY", description="VarIndexBase + 3."), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintScaleUniform + ( + "PaintFormat20", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 20" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintScaleUniform table) to Paint subtable.", + ), + FieldSpec("F2Dot14", "scale"), + ], + ), + # PaintVarScaleUniform + ( + "PaintFormat21", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 21" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintVarScaleUniform table) to Paint subtable.", + ), + FieldSpec("F2Dot14", "scale", description="VarIndexBase + 0."), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintScaleUniformAroundCenter + ( + "PaintFormat22", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 22" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintScaleUniformAroundCenter table) to Paint subtable.", + ), + FieldSpec("F2Dot14", "scale"), + FieldSpec("int16", "centerX"), + FieldSpec("int16", "centerY"), + ], + ), + # PaintVarScaleUniformAroundCenter + ( + "PaintFormat23", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 23" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintVarScaleUniformAroundCenter table) to Paint subtable.", + ), + FieldSpec("F2Dot14", "scale", description="VarIndexBase + 0"), + FieldSpec("int16", "centerX", description="VarIndexBase + 1"), + FieldSpec("int16", "centerY", description="VarIndexBase + 2"), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintRotate + ( + "PaintFormat24", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 24" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintRotate table) to Paint subtable.", + ), + FieldSpec("Angle", "angle"), + ], + ), + # PaintVarRotate + ( + "PaintFormat25", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 25" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintVarRotate table) to Paint subtable.", + ), + FieldSpec("Angle", "angle", description="VarIndexBase + 0."), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintRotateAroundCenter + ( + "PaintFormat26", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 26" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintRotateAroundCenter table) to Paint subtable.", + ), + FieldSpec("Angle", "angle"), + FieldSpec("int16", "centerX"), + FieldSpec("int16", "centerY"), + ], + ), + # PaintVarRotateAroundCenter + ( + "PaintFormat27", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 27" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintVarRotateAroundCenter table) to Paint subtable.", + ), + FieldSpec("Angle", "angle", description="VarIndexBase + 0."), + FieldSpec("int16", "centerX", description="VarIndexBase + 1."), + FieldSpec("int16", "centerY", description="VarIndexBase + 2."), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintSkew + ( + "PaintFormat28", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 28" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintSkew table) to Paint subtable.", + ), + FieldSpec("Angle", "xSkewAngle"), + FieldSpec("Angle", "ySkewAngle"), + ], + ), + # PaintVarSkew + ( + "PaintFormat29", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 29" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintVarSkew table) to Paint subtable.", + ), + FieldSpec("Angle", "xSkewAngle", description="VarIndexBase + 0."), + FieldSpec("Angle", "ySkewAngle", description="VarIndexBase + 1."), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintSkewAroundCenter + ( + "PaintFormat30", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 30" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintSkewAroundCenter table) to Paint subtable.", + ), + FieldSpec("Angle", "xSkewAngle"), + FieldSpec("Angle", "ySkewAngle"), + FieldSpec("int16", "centerX"), + FieldSpec("int16", "centerY"), + ], + ), + # PaintVarSkewAroundCenter + ( + "PaintFormat31", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 31" + ), + FieldSpec( + "Offset24", + "Paint", + description="Offset (from beginning of PaintVarSkewAroundCenter table) to Paint subtable.", + ), + FieldSpec("Angle", "xSkewAngle", description="VarIndexBase + 0."), + FieldSpec("Angle", "ySkewAngle", description="VarIndexBase + 1."), + FieldSpec("int16", "centerX", description="VarIndexBase + 2."), + FieldSpec("int16", "centerY", description="VarIndexBase + 3."), + FieldSpec( + "VarIndex", + "VarIndexBase", + description="Base index into DeltaSetIndexMap.", + ), + ], + ), + # PaintComposite + ( + "PaintFormat32", + [ + FieldSpec( + "uint8", "PaintFormat", description="Format identifier-format = 32" + ), + FieldSpec( + "LOffset24To(Paint)", + "SourcePaint", + description="Offset (from beginning of PaintComposite table) to source Paint subtable.", + ), + FieldSpec( + "CompositeMode", + "CompositeMode", + description="A CompositeMode enumeration value.", + ), + FieldSpec( + "LOffset24To(Paint)", + "BackdropPaint", + description="Offset (from beginning of PaintComposite table) to backdrop Paint subtable.", + ), + ], + ), + # + # avar + # + ( + "AxisValueMap", + [ + FieldSpec( + "F2Dot14", + "FromCoordinate", + description="A normalized coordinate value obtained using default normalization", + ), + FieldSpec( + "F2Dot14", + "ToCoordinate", + description="The modified, normalized coordinate value", + ), + ], + ), + ( + "AxisSegmentMap", + [ + FieldSpec( + "uint16", + "PositionMapCount", + description="The number of correspondence pairs for this axis", + ), + FieldSpec( + "AxisValueMap", + "AxisValueMap", + repeat="PositionMapCount", + aux=0, + description="The array of axis value map records for this axis", + ), + ], + ), + ( + "avar", + [ + FieldSpec( + "Version", + "Version", + description="Version of the avar table- 0x00010000 or 0x00020000", + ), + FieldSpec( + "uint16", "Reserved", description="Permanently reserved; set to zero" + ), + FieldSpec( + "uint16", + "AxisCount", + description='The number of variation axes for this font. This must be the same number as axisCount in the "fvar" table', + ), + FieldSpec( + "AxisSegmentMap", + "AxisSegmentMap", + repeat="AxisCount", + aux=0, + description='The segment maps array — one segment map for each axis, in the order of axes specified in the "fvar" table', + ), + FieldSpec( + "LOffsetTo(DeltaSetIndexMap)", "VarIdxMap", aux="Version >= 0x00020000" + ), + FieldSpec("LOffset", "VarStore", aux="Version >= 0x00020000"), + ], + ), + # + # IFT - Incremental Font Transfer tables + # https://w3c.github.io/IFT/Overview.html + # Reference: https://github.com/googlefonts/fontations/blob/main/read-fonts/src/tables/ift.rs + # + ( + "PatchMapFormat2", + [ + FieldSpec( + "uint8", "Format", description="Set to 2, identifies this as format 2." + ), + FieldSpec("uint24", "Reserved", description="Not used, set to 0."), + FieldSpec( + "uint8", + "Flags", + description="Bit 0: CffCharStringsOffset present. Bit 1: Cff2CharStringsOffset present.", + ), + FieldSpec( + "uint32", + "CompatibilityId", + repeat=4, + aux=0, + description="Unique ID to identify compatible patches (16 bytes).", + ), + FieldSpec( + "uint8", + "DefaultPatchFormat", + description="Default format of patches linked to by urlTemplate.", + ), + FieldSpec( + "uint24", + "NumEntries", + description="Number of entries encoded in this table.", + ), + FieldSpec( + "LOffset", + "MappingEntries", + description="Offset to a MappingEntries sub-table.", + ), + FieldSpec( + "LOffset", + "EntryIdStringData", + description="Offset to entry ID string data block. May be null (0).", + ), + FieldSpec( + "uint16", + "UrlTemplateLength", + description="Length of the urlTemplate byte array.", + ), + FieldSpec( + "uint8", + "UrlTemplate", + repeat="UrlTemplateLength", + aux=0, + description="URL Template bytes used to produce URL strings for each entry.", + ), + FieldSpec( + "uint32", + "CffCharStringsOffset", + aux="Flags & 0x01", + description="Offset from start of CFF table to CharStrings INDEX.", + ), + FieldSpec( + "uint32", + "Cff2CharStringsOffset", + aux="Flags & 0x02", + description="Offset from start of CFF2 table to CharStrings INDEX.", + ), + ], + ), + # 'MappingEntries' contains stateful, delta-encoded entry IDs. The custom + # 'MappingEntriesConverter' is used to do a stateful parsing of all records. + ( + "MappingEntries", + [ + FieldSpec( + "MappingEntries", + "entries", + description="Array of MappingEntry records.", + ) + ], + ), + ("EntryIdStringData", []), +] diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otDataSchema.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otDataSchema.py new file mode 100644 index 0000000000000000000000000000000000000000..2ea3481f6027bf50a487d0deebbea59afc8fc7ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otDataSchema.py @@ -0,0 +1,37 @@ +"""fontTools.ttLib.tables.otDataSchema -- contains the FieldSpec dataclass, which is +used to define the schema of OpenType tables in otData.py. +""" + +from typing import Any, NamedTuple + + +class FieldSpec(NamedTuple): + """Represents a single field in an OpenType table schema. + + These are defined in `otData.py` and used to construct converters in + `otConverters.py`. + + Attributes: + type: The type of the field. This string is used by `otConverters.py` to + select or construct the appropriate converter. It can be a simple + type name (e.g. 'uint16', 'Tag', 'Offset'), a specialized type (e.g. + 'ValueRecord', 'DeltaValue'), or a more complex expression (e.g. + 'OffsetTo(AatStateTable)', 'AATLookup(UShort)') which is evaluated + to create a converter factory. + name: The name of the field as defined in the OpenType specification. + repeat: If the field is an array, this defines how many times it + repeats. It can be an integer, or the name of another field (usually + a 'Count' field) that contains the number of repetitions. If it is a + string, it is used to lookup the count value from the table. + aux: Auxiliary data used by some converters. When `repeat` is not set + and `aux` is a string, it is often compiled into a Python + expression for evaluation. For repeating structs, it is often used + as a constant or an expression. + description: A human-readable description of the field's purpose. + """ + + type: str + name: str + repeat: Any = None + aux: Any = None + description: str = "" diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otTables.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otTables.py new file mode 100644 index 0000000000000000000000000000000000000000..8f111ee9565d2504dead244a82de66a2ef45f291 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otTables.py @@ -0,0 +1,2786 @@ +# coding: utf-8 +"""fontTools.ttLib.tables.otTables -- A collection of classes representing the various +OpenType subtables. + +Most are constructed upon import from data in otData.py, all are populated with +converter objects from otConverters.py. +""" + +import copy +from enum import IntEnum +from functools import reduce +from math import radians +import itertools +from collections import defaultdict, namedtuple +from fontTools.ttLib import OPTIMIZE_FONT_SPEED +from fontTools.ttLib.tables.TupleVariation import TupleVariation +from fontTools.ttLib.tables.otTraverse import dfs_base_table +from fontTools.misc.arrayTools import quantizeRect +from fontTools.misc.roundTools import otRound +from fontTools.misc.transform import Transform, Identity, DecomposedTransform +from fontTools.misc.textTools import bytesjoin, pad, safeEval +from fontTools.misc.vector import Vector +from fontTools.pens.boundsPen import ControlBoundsPen +from fontTools.pens.transformPen import TransformPen +from .otBase import ( + BaseTable, + FormatSwitchingBaseTable, + ValueRecord, + CountReference, + getFormatSwitchingBaseTableClass, + have_uharfbuzz, +) +from fontTools.misc.fixedTools import ( + fixedToFloat as fi2fl, + floatToFixed as fl2fi, + floatToFixedToStr as fl2str, + strToFixedToFloat as str2fl, +) +from fontTools.feaLib.lookupDebugInfo import LookupDebugInfo, LOOKUP_DEBUG_INFO_KEY +import logging +import struct +import array +import sys +from enum import IntFlag +from typing import TYPE_CHECKING, Iterator, List, Optional, Set + +if TYPE_CHECKING: + from fontTools.ttLib.ttGlyphSet import _TTGlyphSet + + +log = logging.getLogger(__name__) + + +class VarComponentFlags(IntFlag): + RESET_UNSPECIFIED_AXES = 1 << 0 + + HAVE_AXES = 1 << 1 + + AXIS_VALUES_HAVE_VARIATION = 1 << 2 + TRANSFORM_HAS_VARIATION = 1 << 3 + + HAVE_TRANSLATE_X = 1 << 4 + HAVE_TRANSLATE_Y = 1 << 5 + HAVE_ROTATION = 1 << 6 + + HAVE_CONDITION = 1 << 7 + + HAVE_SCALE_X = 1 << 8 + HAVE_SCALE_Y = 1 << 9 + HAVE_TCENTER_X = 1 << 10 + HAVE_TCENTER_Y = 1 << 11 + + GID_IS_24BIT = 1 << 12 + + HAVE_SKEW_X = 1 << 13 + HAVE_SKEW_Y = 1 << 14 + + RESERVED_MASK = (1 << 32) - (1 << 15) + + +VarTransformMappingValues = namedtuple( + "VarTransformMappingValues", + ["flag", "fractionalBits", "scale", "defaultValue"], +) + +VAR_TRANSFORM_MAPPING = { + "translateX": VarTransformMappingValues( + VarComponentFlags.HAVE_TRANSLATE_X, 0, 1, 0 + ), + "translateY": VarTransformMappingValues( + VarComponentFlags.HAVE_TRANSLATE_Y, 0, 1, 0 + ), + "rotation": VarTransformMappingValues(VarComponentFlags.HAVE_ROTATION, 12, 180, 0), + "scaleX": VarTransformMappingValues(VarComponentFlags.HAVE_SCALE_X, 10, 1, 1), + "scaleY": VarTransformMappingValues(VarComponentFlags.HAVE_SCALE_Y, 10, 1, 1), + "skewX": VarTransformMappingValues(VarComponentFlags.HAVE_SKEW_X, 12, -180, 0), + "skewY": VarTransformMappingValues(VarComponentFlags.HAVE_SKEW_Y, 12, 180, 0), + "tCenterX": VarTransformMappingValues(VarComponentFlags.HAVE_TCENTER_X, 0, 1, 0), + "tCenterY": VarTransformMappingValues(VarComponentFlags.HAVE_TCENTER_Y, 0, 1, 0), +} + +# Probably should be somewhere in fontTools.misc +_packer = { + 1: lambda v: struct.pack(">B", v), + 2: lambda v: struct.pack(">H", v), + 3: lambda v: struct.pack(">L", v)[1:], + 4: lambda v: struct.pack(">L", v), +} +_unpacker = { + 1: lambda v: struct.unpack(">B", v)[0], + 2: lambda v: struct.unpack(">H", v)[0], + 3: lambda v: struct.unpack(">L", b"\0" + v)[0], + 4: lambda v: struct.unpack(">L", v)[0], +} + + +def _read_uint32var(data, i): + """Read a variable-length number from data starting at index i. + + Return the number and the next index. + """ + + b0 = data[i] + if b0 < 0x80: + return b0, i + 1 + elif b0 < 0xC0: + return (b0 - 0x80) << 8 | data[i + 1], i + 2 + elif b0 < 0xE0: + return (b0 - 0xC0) << 16 | data[i + 1] << 8 | data[i + 2], i + 3 + elif b0 < 0xF0: + return (b0 - 0xE0) << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[ + i + 3 + ], i + 4 + else: + return (b0 - 0xF0) << 32 | data[i + 1] << 24 | data[i + 2] << 16 | data[ + i + 3 + ] << 8 | data[i + 4], i + 5 + + +def _write_uint32var(v): + """Write a variable-length number. + + Return the data. + """ + if v < 0x80: + return struct.pack(">B", v) + elif v < 0x4000: + return struct.pack(">H", (v | 0x8000)) + elif v < 0x200000: + return struct.pack(">L", (v | 0xC00000))[1:] + elif v < 0x10000000: + return struct.pack(">L", (v | 0xE0000000)) + else: + return struct.pack(">B", 0xF0) + struct.pack(">L", v) + + +class VarComponent: + def __init__(self): + self.populateDefaults() + + def populateDefaults(self, propagator=None): + self.flags = 0 + self.glyphName = None + self.conditionIndex = None + self.axisIndicesIndex = None + self.axisValues = () + self.axisValuesVarIndex = NO_VARIATION_INDEX + self.transformVarIndex = NO_VARIATION_INDEX + self.transform = DecomposedTransform() + + def decompile(self, data, font, localState): + i = 0 + self.flags, i = _read_uint32var(data, i) + flags = self.flags + + gidSize = 3 if flags & VarComponentFlags.GID_IS_24BIT else 2 + glyphID = _unpacker[gidSize](data[i : i + gidSize]) + i += gidSize + self.glyphName = font.glyphOrder[glyphID] + + if flags & VarComponentFlags.HAVE_CONDITION: + self.conditionIndex, i = _read_uint32var(data, i) + + if flags & VarComponentFlags.HAVE_AXES: + self.axisIndicesIndex, i = _read_uint32var(data, i) + else: + self.axisIndicesIndex = None + + if self.axisIndicesIndex is None: + numAxes = 0 + else: + axisIndices = localState["AxisIndicesList"].Item[self.axisIndicesIndex] + numAxes = len(axisIndices) + + if flags & VarComponentFlags.HAVE_AXES: + axisValues, i = TupleVariation.decompileDeltas_(numAxes, data, i) + self.axisValues = tuple(fi2fl(v, 14) for v in axisValues) + else: + self.axisValues = () + assert len(self.axisValues) == numAxes + + if flags & VarComponentFlags.AXIS_VALUES_HAVE_VARIATION: + self.axisValuesVarIndex, i = _read_uint32var(data, i) + else: + self.axisValuesVarIndex = NO_VARIATION_INDEX + if flags & VarComponentFlags.TRANSFORM_HAS_VARIATION: + self.transformVarIndex, i = _read_uint32var(data, i) + else: + self.transformVarIndex = NO_VARIATION_INDEX + + self.transform = DecomposedTransform() + + def read_transform_component(values): + nonlocal i + if flags & values.flag: + v = ( + fi2fl( + struct.unpack(">h", data[i : i + 2])[0], values.fractionalBits + ) + * values.scale + ) + i += 2 + return v + else: + return values.defaultValue + + for attr_name, mapping_values in VAR_TRANSFORM_MAPPING.items(): + value = read_transform_component(mapping_values) + setattr(self.transform, attr_name, value) + + if not (flags & VarComponentFlags.HAVE_SCALE_Y): + self.transform.scaleY = self.transform.scaleX + + n = flags & VarComponentFlags.RESERVED_MASK + while n: + _, i = _read_uint32var(data, i) + n &= n - 1 + + return data[i:] + + def compile(self, font): + optimizeSpeed = font.cfg[OPTIMIZE_FONT_SPEED] + + data = [] + + flags = self.flags + + glyphID = font.getGlyphID(self.glyphName) + if glyphID > 65535: + flags |= VarComponentFlags.GID_IS_24BIT + data.append(_packer[3](glyphID)) + else: + flags &= ~VarComponentFlags.GID_IS_24BIT + data.append(_packer[2](glyphID)) + + if self.conditionIndex is not None: + flags |= VarComponentFlags.HAVE_CONDITION + data.append(_write_uint32var(self.conditionIndex)) + + numAxes = len(self.axisValues) + + if numAxes: + flags |= VarComponentFlags.HAVE_AXES + data.append(_write_uint32var(self.axisIndicesIndex)) + data.append( + TupleVariation.compileDeltaValues_( + [fl2fi(v, 14) for v in self.axisValues], + optimizeSize=not optimizeSpeed, + ) + ) + else: + flags &= ~VarComponentFlags.HAVE_AXES + + if self.axisValuesVarIndex != NO_VARIATION_INDEX: + flags |= VarComponentFlags.AXIS_VALUES_HAVE_VARIATION + data.append(_write_uint32var(self.axisValuesVarIndex)) + else: + flags &= ~VarComponentFlags.AXIS_VALUES_HAVE_VARIATION + if self.transformVarIndex != NO_VARIATION_INDEX: + flags |= VarComponentFlags.TRANSFORM_HAS_VARIATION + data.append(_write_uint32var(self.transformVarIndex)) + else: + flags &= ~VarComponentFlags.TRANSFORM_HAS_VARIATION + + def write_transform_component(value, values): + if flags & values.flag: + return struct.pack( + ">h", fl2fi(value / values.scale, values.fractionalBits) + ) + else: + return b"" + + for attr_name, mapping_values in VAR_TRANSFORM_MAPPING.items(): + value = getattr(self.transform, attr_name) + data.append(write_transform_component(value, mapping_values)) + + return _write_uint32var(flags) + bytesjoin(data) + + def toXML(self, writer, ttFont, attrs): + writer.begintag("VarComponent", attrs) + writer.newline() + + def write(name, value, attrs=()): + if value is not None: + writer.simpletag(name, (("value", value),) + attrs) + writer.newline() + + write("glyphName", self.glyphName) + + if self.conditionIndex is not None: + write("conditionIndex", self.conditionIndex) + if self.axisIndicesIndex is not None: + write("axisIndicesIndex", self.axisIndicesIndex) + if ( + self.axisIndicesIndex is not None + or self.flags & VarComponentFlags.RESET_UNSPECIFIED_AXES + ): + if self.flags & VarComponentFlags.RESET_UNSPECIFIED_AXES: + attrs = (("resetUnspecifiedAxes", 1),) + else: + attrs = () + write("axisValues", [float(fl2str(v, 14)) for v in self.axisValues], attrs) + + if self.axisValuesVarIndex != NO_VARIATION_INDEX: + write("axisValuesVarIndex", self.axisValuesVarIndex) + if self.transformVarIndex != NO_VARIATION_INDEX: + write("transformVarIndex", self.transformVarIndex) + + # Only write transform components that are specified in the + # flags, even if they are the default value. + for attr_name, mapping in VAR_TRANSFORM_MAPPING.items(): + if not (self.flags & mapping.flag): + continue + v = getattr(self.transform, attr_name) + write(attr_name, fl2str(v, mapping.fractionalBits)) + + writer.endtag("VarComponent") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont): + content = [c for c in content if isinstance(c, tuple)] + + self.populateDefaults() + + for name, attrs, content in content: + assert not content + v = attrs["value"] + + if name == "glyphName": + self.glyphName = v + elif name == "conditionIndex": + self.conditionIndex = safeEval(v) + elif name == "axisIndicesIndex": + self.axisIndicesIndex = safeEval(v) + elif name == "axisValues": + self.axisValues = tuple(str2fl(v, 14) for v in safeEval(v)) + if safeEval(attrs.get("resetUnspecifiedAxes", "0")): + self.flags |= VarComponentFlags.RESET_UNSPECIFIED_AXES + elif name == "axisValuesVarIndex": + self.axisValuesVarIndex = safeEval(v) + elif name == "transformVarIndex": + self.transformVarIndex = safeEval(v) + elif name in VAR_TRANSFORM_MAPPING: + setattr( + self.transform, + name, + safeEval(v), + ) + self.flags |= VAR_TRANSFORM_MAPPING[name].flag + else: + assert False, name + + def applyTransformDeltas(self, deltas): + i = 0 + + def read_transform_component_delta(values): + nonlocal i + if self.flags & values.flag: + v = fi2fl(deltas[i], values.fractionalBits) * values.scale + i += 1 + return v + else: + return 0 + + for attr_name, mapping_values in VAR_TRANSFORM_MAPPING.items(): + value = read_transform_component_delta(mapping_values) + setattr( + self.transform, attr_name, getattr(self.transform, attr_name) + value + ) + + if not (self.flags & VarComponentFlags.HAVE_SCALE_Y): + self.transform.scaleY = self.transform.scaleX + + assert i == len(deltas), (i, len(deltas)) + + def __eq__(self, other): + if type(self) != type(other): + return NotImplemented + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + result = self.__eq__(other) + return result if result is NotImplemented else not result + + +class VarCompositeGlyph: + def __init__(self, components=None): + self.components = components if components is not None else [] + + def decompile(self, data, font, localState): + self.components = [] + while data: + component = VarComponent() + data = component.decompile(data, font, localState) + self.components.append(component) + + def compile(self, font): + data = [] + for component in self.components: + data.append(component.compile(font)) + return bytesjoin(data) + + def toXML(self, xmlWriter, font, attrs, name): + xmlWriter.begintag("VarCompositeGlyph", attrs) + xmlWriter.newline() + for i, component in enumerate(self.components): + component.toXML(xmlWriter, font, [("index", i)]) + xmlWriter.endtag("VarCompositeGlyph") + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + content = [c for c in content if isinstance(c, tuple)] + for name, attrs, content in content: + assert name == "VarComponent" + component = VarComponent() + component.fromXML(name, attrs, content, font) + self.components.append(component) + + +class AATStateTable(object): + def __init__(self): + self.GlyphClasses = {} # GlyphID --> GlyphClass + self.States = [] # List of AATState, indexed by state number + self.PerGlyphLookups = [] # [{GlyphID:GlyphID}, ...] + + +class AATState(object): + def __init__(self): + self.Transitions = {} # GlyphClass --> AATAction + + +class AATAction(object): + _FLAGS = None + + @staticmethod + def compileActions(font, states): + return (None, None) + + def _writeFlagsToXML(self, xmlWriter): + flags = [f for f in self._FLAGS if self.__dict__[f]] + if flags: + xmlWriter.simpletag("Flags", value=",".join(flags)) + xmlWriter.newline() + if self.ReservedFlags != 0: + xmlWriter.simpletag("ReservedFlags", value="0x%04X" % self.ReservedFlags) + xmlWriter.newline() + + def _setFlag(self, flag): + assert flag in self._FLAGS, "unsupported flag %s" % flag + self.__dict__[flag] = True + + +class RearrangementMorphAction(AATAction): + staticSize = 4 + actionHeaderSize = 0 + _FLAGS = ["MarkFirst", "DontAdvance", "MarkLast"] + + _VERBS = { + 0: "no change", + 1: "Ax ⇒ xA", + 2: "xD ⇒ Dx", + 3: "AxD ⇒ DxA", + 4: "ABx ⇒ xAB", + 5: "ABx ⇒ xBA", + 6: "xCD ⇒ CDx", + 7: "xCD ⇒ DCx", + 8: "AxCD ⇒ CDxA", + 9: "AxCD ⇒ DCxA", + 10: "ABxD ⇒ DxAB", + 11: "ABxD ⇒ DxBA", + 12: "ABxCD ⇒ CDxAB", + 13: "ABxCD ⇒ CDxBA", + 14: "ABxCD ⇒ DCxAB", + 15: "ABxCD ⇒ DCxBA", + } + + def __init__(self): + self.NewState = 0 + self.Verb = 0 + self.MarkFirst = False + self.DontAdvance = False + self.MarkLast = False + self.ReservedFlags = 0 + + def compile(self, writer, font, actionIndex): + assert actionIndex is None + writer.writeUShort(self.NewState) + assert self.Verb >= 0 and self.Verb <= 15, self.Verb + flags = self.Verb | self.ReservedFlags + if self.MarkFirst: + flags |= 0x8000 + if self.DontAdvance: + flags |= 0x4000 + if self.MarkLast: + flags |= 0x2000 + writer.writeUShort(flags) + + def decompile(self, reader, font, actionReader): + assert actionReader is None + self.NewState = reader.readUShort() + flags = reader.readUShort() + self.Verb = flags & 0xF + self.MarkFirst = bool(flags & 0x8000) + self.DontAdvance = bool(flags & 0x4000) + self.MarkLast = bool(flags & 0x2000) + self.ReservedFlags = flags & 0x1FF0 + + def toXML(self, xmlWriter, font, attrs, name): + xmlWriter.begintag(name, **attrs) + xmlWriter.newline() + xmlWriter.simpletag("NewState", value=self.NewState) + xmlWriter.newline() + self._writeFlagsToXML(xmlWriter) + xmlWriter.simpletag("Verb", value=self.Verb) + verbComment = self._VERBS.get(self.Verb) + if verbComment is not None: + xmlWriter.comment(verbComment) + xmlWriter.newline() + xmlWriter.endtag(name) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + self.NewState = self.Verb = self.ReservedFlags = 0 + self.MarkFirst = self.DontAdvance = self.MarkLast = False + content = [t for t in content if isinstance(t, tuple)] + for eltName, eltAttrs, eltContent in content: + if eltName == "NewState": + self.NewState = safeEval(eltAttrs["value"]) + elif eltName == "Verb": + self.Verb = safeEval(eltAttrs["value"]) + elif eltName == "ReservedFlags": + self.ReservedFlags = safeEval(eltAttrs["value"]) + elif eltName == "Flags": + for flag in eltAttrs["value"].split(","): + self._setFlag(flag.strip()) + + +class ContextualMorphAction(AATAction): + staticSize = 8 + actionHeaderSize = 0 + _FLAGS = ["SetMark", "DontAdvance"] + + def __init__(self): + self.NewState = 0 + self.SetMark, self.DontAdvance = False, False + self.ReservedFlags = 0 + self.MarkIndex, self.CurrentIndex = 0xFFFF, 0xFFFF + + def compile(self, writer, font, actionIndex): + assert actionIndex is None + writer.writeUShort(self.NewState) + flags = self.ReservedFlags + if self.SetMark: + flags |= 0x8000 + if self.DontAdvance: + flags |= 0x4000 + writer.writeUShort(flags) + writer.writeUShort(self.MarkIndex) + writer.writeUShort(self.CurrentIndex) + + def decompile(self, reader, font, actionReader): + assert actionReader is None + self.NewState = reader.readUShort() + flags = reader.readUShort() + self.SetMark = bool(flags & 0x8000) + self.DontAdvance = bool(flags & 0x4000) + self.ReservedFlags = flags & 0x3FFF + self.MarkIndex = reader.readUShort() + self.CurrentIndex = reader.readUShort() + + def toXML(self, xmlWriter, font, attrs, name): + xmlWriter.begintag(name, **attrs) + xmlWriter.newline() + xmlWriter.simpletag("NewState", value=self.NewState) + xmlWriter.newline() + self._writeFlagsToXML(xmlWriter) + xmlWriter.simpletag("MarkIndex", value=self.MarkIndex) + xmlWriter.newline() + xmlWriter.simpletag("CurrentIndex", value=self.CurrentIndex) + xmlWriter.newline() + xmlWriter.endtag(name) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + self.NewState = self.ReservedFlags = 0 + self.SetMark = self.DontAdvance = False + self.MarkIndex, self.CurrentIndex = 0xFFFF, 0xFFFF + content = [t for t in content if isinstance(t, tuple)] + for eltName, eltAttrs, eltContent in content: + if eltName == "NewState": + self.NewState = safeEval(eltAttrs["value"]) + elif eltName == "Flags": + for flag in eltAttrs["value"].split(","): + self._setFlag(flag.strip()) + elif eltName == "ReservedFlags": + self.ReservedFlags = safeEval(eltAttrs["value"]) + elif eltName == "MarkIndex": + self.MarkIndex = safeEval(eltAttrs["value"]) + elif eltName == "CurrentIndex": + self.CurrentIndex = safeEval(eltAttrs["value"]) + + +class LigAction(object): + def __init__(self): + self.Store = False + # GlyphIndexDelta is a (possibly negative) delta that gets + # added to the glyph ID at the top of the AAT runtime + # execution stack. It is *not* a byte offset into the + # morx table. The result of the addition, which is performed + # at run time by the shaping engine, is an index into + # the ligature components table. See 'morx' specification. + # In the AAT specification, this field is called Offset; + # but its meaning is quite different from other offsets + # in either AAT or OpenType, so we use a different name. + self.GlyphIndexDelta = 0 + + +class LigatureMorphAction(AATAction): + staticSize = 6 + + # 4 bytes for each of {action,ligComponents,ligatures}Offset + actionHeaderSize = 12 + + _FLAGS = ["SetComponent", "DontAdvance"] + + def __init__(self): + self.NewState = 0 + self.SetComponent, self.DontAdvance = False, False + self.ReservedFlags = 0 + self.Actions = [] + + def compile(self, writer, font, actionIndex): + assert actionIndex is not None + writer.writeUShort(self.NewState) + flags = self.ReservedFlags + if self.SetComponent: + flags |= 0x8000 + if self.DontAdvance: + flags |= 0x4000 + if len(self.Actions) > 0: + flags |= 0x2000 + writer.writeUShort(flags) + if len(self.Actions) > 0: + actions = self.compileLigActions() + writer.writeUShort(actionIndex[actions]) + else: + writer.writeUShort(0) + + def decompile(self, reader, font, actionReader): + assert actionReader is not None + self.NewState = reader.readUShort() + flags = reader.readUShort() + self.SetComponent = bool(flags & 0x8000) + self.DontAdvance = bool(flags & 0x4000) + performAction = bool(flags & 0x2000) + # As of 2017-09-12, the 'morx' specification says that + # the reserved bitmask in ligature subtables is 0x3FFF. + # However, the specification also defines a flag 0x2000, + # so the reserved value should actually be 0x1FFF. + # TODO: Report this specification bug to Apple. + self.ReservedFlags = flags & 0x1FFF + actionIndex = reader.readUShort() + if performAction: + self.Actions = self._decompileLigActions(actionReader, actionIndex) + else: + self.Actions = [] + + @staticmethod + def compileActions(font, states): + result, actions, actionIndex = b"", set(), {} + for state in states: + for _glyphClass, trans in state.Transitions.items(): + actions.add(trans.compileLigActions()) + # Sort the compiled actions in decreasing order of + # length, so that the longer sequence come before the + # shorter ones. For each compiled action ABCD, its + # suffixes BCD, CD, and D do not be encoded separately + # (in case they occur); instead, we can just store an + # index that points into the middle of the longer + # sequence. Every compiled AAT ligature sequence is + # terminated with an end-of-sequence flag, which can + # only be set on the last element of the sequence. + # Therefore, it is sufficient to consider just the + # suffixes. + for a in sorted(actions, key=lambda x: (-len(x), x)): + if a not in actionIndex: + for i in range(0, len(a), 4): + suffix = a[i:] + suffixIndex = (len(result) + i) // 4 + actionIndex.setdefault(suffix, suffixIndex) + result += a + result = pad(result, 4) + return (result, actionIndex) + + def compileLigActions(self): + result = [] + for i, action in enumerate(self.Actions): + last = i == len(self.Actions) - 1 + value = action.GlyphIndexDelta & 0x3FFFFFFF + value |= 0x80000000 if last else 0 + value |= 0x40000000 if action.Store else 0 + result.append(struct.pack(">L", value)) + return bytesjoin(result) + + def _decompileLigActions(self, actionReader, actionIndex): + actions = [] + last = False + reader = actionReader.getSubReader(actionReader.pos + actionIndex * 4) + while not last: + value = reader.readULong() + last = bool(value & 0x80000000) + action = LigAction() + actions.append(action) + action.Store = bool(value & 0x40000000) + delta = value & 0x3FFFFFFF + if delta >= 0x20000000: # sign-extend 30-bit value + delta = -0x40000000 + delta + action.GlyphIndexDelta = delta + return actions + + def fromXML(self, name, attrs, content, font): + self.NewState = self.ReservedFlags = 0 + self.SetComponent = self.DontAdvance = False + self.ReservedFlags = 0 + self.Actions = [] + content = [t for t in content if isinstance(t, tuple)] + for eltName, eltAttrs, eltContent in content: + if eltName == "NewState": + self.NewState = safeEval(eltAttrs["value"]) + elif eltName == "Flags": + for flag in eltAttrs["value"].split(","): + self._setFlag(flag.strip()) + elif eltName == "ReservedFlags": + self.ReservedFlags = safeEval(eltAttrs["value"]) + elif eltName == "Action": + action = LigAction() + flags = eltAttrs.get("Flags", "").split(",") + flags = [f.strip() for f in flags] + action.Store = "Store" in flags + action.GlyphIndexDelta = safeEval(eltAttrs["GlyphIndexDelta"]) + self.Actions.append(action) + + def toXML(self, xmlWriter, font, attrs, name): + xmlWriter.begintag(name, **attrs) + xmlWriter.newline() + xmlWriter.simpletag("NewState", value=self.NewState) + xmlWriter.newline() + self._writeFlagsToXML(xmlWriter) + for action in self.Actions: + attribs = [("GlyphIndexDelta", action.GlyphIndexDelta)] + if action.Store: + attribs.append(("Flags", "Store")) + xmlWriter.simpletag("Action", attribs) + xmlWriter.newline() + xmlWriter.endtag(name) + xmlWriter.newline() + + +class InsertionMorphAction(AATAction): + staticSize = 8 + actionHeaderSize = 4 # 4 bytes for actionOffset + _FLAGS = [ + "SetMark", + "DontAdvance", + "CurrentIsKashidaLike", + "MarkedIsKashidaLike", + "CurrentInsertBefore", + "MarkedInsertBefore", + ] + + def __init__(self): + self.NewState = 0 + for flag in self._FLAGS: + setattr(self, flag, False) + self.ReservedFlags = 0 + self.CurrentInsertionAction, self.MarkedInsertionAction = [], [] + + def compile(self, writer, font, actionIndex): + assert actionIndex is not None + writer.writeUShort(self.NewState) + flags = self.ReservedFlags + if self.SetMark: + flags |= 0x8000 + if self.DontAdvance: + flags |= 0x4000 + if self.CurrentIsKashidaLike: + flags |= 0x2000 + if self.MarkedIsKashidaLike: + flags |= 0x1000 + if self.CurrentInsertBefore: + flags |= 0x0800 + if self.MarkedInsertBefore: + flags |= 0x0400 + flags |= len(self.CurrentInsertionAction) << 5 + flags |= len(self.MarkedInsertionAction) + writer.writeUShort(flags) + if len(self.CurrentInsertionAction) > 0: + currentIndex = actionIndex[tuple(self.CurrentInsertionAction)] + else: + currentIndex = 0xFFFF + writer.writeUShort(currentIndex) + if len(self.MarkedInsertionAction) > 0: + markedIndex = actionIndex[tuple(self.MarkedInsertionAction)] + else: + markedIndex = 0xFFFF + writer.writeUShort(markedIndex) + + def decompile(self, reader, font, actionReader): + assert actionReader is not None + self.NewState = reader.readUShort() + flags = reader.readUShort() + self.SetMark = bool(flags & 0x8000) + self.DontAdvance = bool(flags & 0x4000) + self.CurrentIsKashidaLike = bool(flags & 0x2000) + self.MarkedIsKashidaLike = bool(flags & 0x1000) + self.CurrentInsertBefore = bool(flags & 0x0800) + self.MarkedInsertBefore = bool(flags & 0x0400) + self.CurrentInsertionAction = self._decompileInsertionAction( + actionReader, font, index=reader.readUShort(), count=((flags & 0x03E0) >> 5) + ) + self.MarkedInsertionAction = self._decompileInsertionAction( + actionReader, font, index=reader.readUShort(), count=(flags & 0x001F) + ) + + def _decompileInsertionAction(self, actionReader, font, index, count): + if index == 0xFFFF or count == 0: + return [] + reader = actionReader.getSubReader(actionReader.pos + index * 2) + return font.getGlyphNameMany(reader.readUShortArray(count)) + + def toXML(self, xmlWriter, font, attrs, name): + xmlWriter.begintag(name, **attrs) + xmlWriter.newline() + xmlWriter.simpletag("NewState", value=self.NewState) + xmlWriter.newline() + self._writeFlagsToXML(xmlWriter) + for g in self.CurrentInsertionAction: + xmlWriter.simpletag("CurrentInsertionAction", glyph=g) + xmlWriter.newline() + for g in self.MarkedInsertionAction: + xmlWriter.simpletag("MarkedInsertionAction", glyph=g) + xmlWriter.newline() + xmlWriter.endtag(name) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + self.__init__() + content = [t for t in content if isinstance(t, tuple)] + for eltName, eltAttrs, eltContent in content: + if eltName == "NewState": + self.NewState = safeEval(eltAttrs["value"]) + elif eltName == "Flags": + for flag in eltAttrs["value"].split(","): + self._setFlag(flag.strip()) + elif eltName == "CurrentInsertionAction": + self.CurrentInsertionAction.append(eltAttrs["glyph"]) + elif eltName == "MarkedInsertionAction": + self.MarkedInsertionAction.append(eltAttrs["glyph"]) + else: + assert False, eltName + + @staticmethod + def compileActions(font, states): + actions, actionIndex, result = set(), {}, b"" + for state in states: + for _glyphClass, trans in state.Transitions.items(): + if trans.CurrentInsertionAction is not None: + actions.add(tuple(trans.CurrentInsertionAction)) + if trans.MarkedInsertionAction is not None: + actions.add(tuple(trans.MarkedInsertionAction)) + # Sort the compiled actions in decreasing order of + # length, so that the longer sequence come before the + # shorter ones. + for action in sorted(actions, key=lambda x: (-len(x), x)): + # We insert all sub-sequences of the action glyph sequence + # into actionIndex. For example, if one action triggers on + # glyph sequence [A, B, C, D, E] and another action triggers + # on [C, D], we return result=[A, B, C, D, E] (as list of + # encoded glyph IDs), and actionIndex={('A','B','C','D','E'): 0, + # ('C','D'): 2}. + if action in actionIndex: + continue + for start in range(0, len(action)): + startIndex = (len(result) // 2) + start + for limit in range(start, len(action)): + glyphs = action[start : limit + 1] + actionIndex.setdefault(glyphs, startIndex) + for glyph in action: + glyphID = font.getGlyphID(glyph) + result += struct.pack(">H", glyphID) + return result, actionIndex + + +class FeatureParams(BaseTable): + def compile(self, writer, font): + assert ( + featureParamTypes.get(writer["FeatureTag"]) == self.__class__ + ), "Wrong FeatureParams type for feature '%s': %s" % ( + writer["FeatureTag"], + self.__class__.__name__, + ) + BaseTable.compile(self, writer, font) + + def toXML(self, xmlWriter, font, attrs=None, name=None): + BaseTable.toXML(self, xmlWriter, font, attrs, name=self.__class__.__name__) + + +class FeatureParamsSize(FeatureParams): + pass + + +class FeatureParamsStylisticSet(FeatureParams): + pass + + +class FeatureParamsCharacterVariants(FeatureParams): + pass + + +class Coverage(FormatSwitchingBaseTable): + # manual implementation to get rid of glyphID dependencies + + def populateDefaults(self, propagator=None): + if not hasattr(self, "glyphs"): + self.glyphs = [] + + def postRead(self, rawTable, font): + if self.Format == 1: + self.glyphs = rawTable["GlyphArray"] + elif self.Format == 2: + glyphs = self.glyphs = [] + ranges = rawTable["RangeRecord"] + # Some SIL fonts have coverage entries that don't have sorted + # StartCoverageIndex. If it is so, fixup and warn. We undo + # this when writing font out. + sorted_ranges = sorted(ranges, key=lambda a: a.StartCoverageIndex) + if ranges != sorted_ranges: + log.warning("GSUB/GPOS Coverage is not sorted by glyph ids.") + ranges = sorted_ranges + del sorted_ranges + for r in ranges: + start = r.Start + end = r.End + startID = font.getGlyphID(start) + endID = font.getGlyphID(end) + 1 + glyphs.extend(font.getGlyphNameMany(range(startID, endID))) + else: + self.glyphs = [] + log.warning("Unknown Coverage format: %s", self.Format) + del self.Format # Don't need this anymore + + def preWrite(self, font): + glyphs = getattr(self, "glyphs", None) + if glyphs is None: + glyphs = self.glyphs = [] + format = 1 + rawTable = {"GlyphArray": glyphs} + if glyphs: + # find out whether Format 2 is more compact or not + glyphIDs = font.getGlyphIDMany(glyphs) + brokenOrder = sorted(glyphIDs) != glyphIDs + + last = glyphIDs[0] + ranges = [[last]] + for glyphID in glyphIDs[1:]: + if glyphID != last + 1: + ranges[-1].append(last) + ranges.append([glyphID]) + last = glyphID + ranges[-1].append(last) + + if brokenOrder or len(ranges) * 3 < len(glyphs): # 3 words vs. 1 word + # Format 2 is more compact + index = 0 + for i, (start, end) in enumerate(ranges): + r = RangeRecord() + r.StartID = start + r.Start = font.getGlyphName(start) + r.End = font.getGlyphName(end) + r.StartCoverageIndex = index + ranges[i] = r + index = index + end - start + 1 + if brokenOrder: + log.warning("GSUB/GPOS Coverage is not sorted by glyph ids.") + ranges.sort(key=lambda a: a.StartID) + for r in ranges: + del r.StartID + format = 2 + rawTable = {"RangeRecord": ranges} + # else: + # fallthrough; Format 1 is more compact + self.Format = format + return rawTable + + def toXML2(self, xmlWriter, font): + for glyphName in getattr(self, "glyphs", []): + xmlWriter.simpletag("Glyph", value=glyphName) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + glyphs = getattr(self, "glyphs", None) + if glyphs is None: + glyphs = [] + self.glyphs = glyphs + glyphs.append(attrs["value"]) + + +# The special 0xFFFFFFFF delta-set index is used to indicate that there +# is no variation data in the ItemVariationStore for a given variable field +NO_VARIATION_INDEX = 0xFFFFFFFF + + +class DeltaSetIndexMap(getFormatSwitchingBaseTableClass("uint8")): + def populateDefaults(self, propagator=None): + if not hasattr(self, "mapping"): + self.mapping = [] + + def postRead(self, rawTable, font): + assert (rawTable["EntryFormat"] & 0xFFC0) == 0 + self.mapping = rawTable["mapping"] + + @staticmethod + def getEntryFormat(mapping): + ored = 0 + for idx in mapping: + ored |= idx + + inner = ored & 0xFFFF + innerBits = 0 + while inner: + innerBits += 1 + inner >>= 1 + innerBits = max(innerBits, 1) + assert innerBits <= 16 + + ored = (ored >> (16 - innerBits)) | (ored & ((1 << innerBits) - 1)) + if ored <= 0x000000FF: + entrySize = 1 + elif ored <= 0x0000FFFF: + entrySize = 2 + elif ored <= 0x00FFFFFF: + entrySize = 3 + else: + entrySize = 4 + + return ((entrySize - 1) << 4) | (innerBits - 1) + + def preWrite(self, font): + mapping = getattr(self, "mapping", None) + if mapping is None: + mapping = self.mapping = [] + self.Format = 1 if len(mapping) > 0xFFFF else 0 + rawTable = self.__dict__.copy() + rawTable["MappingCount"] = len(mapping) + rawTable["EntryFormat"] = self.getEntryFormat(mapping) + return rawTable + + def toXML2(self, xmlWriter, font): + # Make xml dump less verbose, by omitting no-op entries like: + # <Map index="..." outer="65535" inner="65535"/> + xmlWriter.comment("Omitted values default to 0xFFFF/0xFFFF (no variations)") + xmlWriter.newline() + for i, value in enumerate(getattr(self, "mapping", [])): + attrs = [("index", i)] + if value != NO_VARIATION_INDEX: + attrs.extend( + [ + ("outer", value >> 16), + ("inner", value & 0xFFFF), + ] + ) + xmlWriter.simpletag("Map", attrs) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + mapping = getattr(self, "mapping", None) + if mapping is None: + self.mapping = mapping = [] + index = safeEval(attrs["index"]) + outer = safeEval(attrs.get("outer", "0xFFFF")) + inner = safeEval(attrs.get("inner", "0xFFFF")) + assert inner <= 0xFFFF + mapping.insert(index, (outer << 16) | inner) + + def __getitem__(self, i): + return self.mapping[i] if i < len(self.mapping) else NO_VARIATION_INDEX + + +class VarIdxMap(BaseTable): + def populateDefaults(self, propagator=None): + if not hasattr(self, "mapping"): + self.mapping = {} + + def postRead(self, rawTable, font): + assert (rawTable["EntryFormat"] & 0xFFC0) == 0 + glyphOrder = font.getGlyphOrder() + mapList = rawTable["mapping"] + mapList.extend([mapList[-1]] * (len(glyphOrder) - len(mapList))) + self.mapping = dict(zip(glyphOrder, mapList)) + + def preWrite(self, font): + mapping = getattr(self, "mapping", None) + if mapping is None: + mapping = self.mapping = {} + + glyphOrder = font.getGlyphOrder() + mapping = [mapping[g] for g in glyphOrder] + while len(mapping) > 1 and mapping[-2] == mapping[-1]: + del mapping[-1] + + rawTable = {"mapping": mapping} + rawTable["MappingCount"] = len(mapping) + rawTable["EntryFormat"] = DeltaSetIndexMap.getEntryFormat(mapping) + return rawTable + + def toXML2(self, xmlWriter, font): + for glyph, value in sorted(getattr(self, "mapping", {}).items()): + attrs = ( + ("glyph", glyph), + ("outer", value >> 16), + ("inner", value & 0xFFFF), + ) + xmlWriter.simpletag("Map", attrs) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + mapping = getattr(self, "mapping", None) + if mapping is None: + mapping = {} + self.mapping = mapping + try: + glyph = attrs["glyph"] + except: # https://github.com/fonttools/fonttools/commit/21cbab8ce9ded3356fef3745122da64dcaf314e9#commitcomment-27649836 + glyph = font.getGlyphOrder()[attrs["index"]] + outer = safeEval(attrs["outer"]) + inner = safeEval(attrs["inner"]) + assert inner <= 0xFFFF + mapping[glyph] = (outer << 16) | inner + + def __getitem__(self, glyphName): + return self.mapping.get(glyphName, NO_VARIATION_INDEX) + + +class VarRegionList(BaseTable): + def preWrite(self, font): + # The OT spec says VarStore.VarRegionList.RegionAxisCount should always + # be equal to the fvar.axisCount, and OTS < v8.0.0 enforces this rule + # even when the VarRegionList is empty. We can't treat RegionAxisCount + # like a normal propagated count (== len(Region[i].VarRegionAxis)), + # otherwise it would default to 0 if VarRegionList is empty. + # Thus, we force it to always be equal to fvar.axisCount. + # https://github.com/khaledhosny/ots/pull/192 + fvarTable = font.get("fvar") + if fvarTable: + self.RegionAxisCount = len(fvarTable.axes) + return { + **self.__dict__, + "RegionAxisCount": CountReference(self.__dict__, "RegionAxisCount"), + } + + +class SingleSubst(FormatSwitchingBaseTable): + def populateDefaults(self, propagator=None): + if not hasattr(self, "mapping"): + self.mapping = {} + + def postRead(self, rawTable, font): + mapping = {} + input = _getGlyphsFromCoverageTable(rawTable["Coverage"]) + if self.Format == 1: + delta = rawTable["DeltaGlyphID"] + inputGIDS = font.getGlyphIDMany(input) + outGIDS = [(glyphID + delta) % 65536 for glyphID in inputGIDS] + outNames = font.getGlyphNameMany(outGIDS) + for inp, out in zip(input, outNames): + mapping[inp] = out + elif self.Format == 2: + assert ( + len(input) == rawTable["GlyphCount"] + ), "invalid SingleSubstFormat2 table" + subst = rawTable["Substitute"] + for inp, sub in zip(input, subst): + mapping[inp] = sub + else: + assert 0, "unknown format: %s" % self.Format + self.mapping = mapping + del self.Format # Don't need this anymore + + def preWrite(self, font): + mapping = getattr(self, "mapping", None) + if mapping is None: + mapping = self.mapping = {} + items = list(mapping.items()) + getGlyphID = font.getGlyphID + gidItems = [(getGlyphID(a), getGlyphID(b)) for a, b in items] + sortableItems = sorted(zip(gidItems, items)) + + # figure out format + format = 2 + delta = None + for inID, outID in gidItems: + if delta is None: + delta = (outID - inID) % 65536 + + if (inID + delta) % 65536 != outID: + break + else: + if delta is None: + # the mapping is empty, better use format 2 + format = 2 + else: + format = 1 + + rawTable = {} + self.Format = format + cov = Coverage() + input = [item[1][0] for item in sortableItems] + subst = [item[1][1] for item in sortableItems] + cov.glyphs = input + rawTable["Coverage"] = cov + if format == 1: + assert delta is not None + rawTable["DeltaGlyphID"] = delta + else: + rawTable["Substitute"] = subst + return rawTable + + def toXML2(self, xmlWriter, font): + items = sorted(self.mapping.items()) + for inGlyph, outGlyph in items: + xmlWriter.simpletag("Substitution", [("in", inGlyph), ("out", outGlyph)]) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + mapping = getattr(self, "mapping", None) + if mapping is None: + mapping = {} + self.mapping = mapping + mapping[attrs["in"]] = attrs["out"] + + +class MultipleSubst(FormatSwitchingBaseTable): + def populateDefaults(self, propagator=None): + if not hasattr(self, "mapping"): + self.mapping = {} + + def postRead(self, rawTable, font): + mapping = {} + if self.Format == 1: + glyphs = _getGlyphsFromCoverageTable(rawTable["Coverage"]) + subst = [s.Substitute for s in rawTable["Sequence"]] + mapping = dict(zip(glyphs, subst)) + else: + assert 0, "unknown format: %s" % self.Format + self.mapping = mapping + del self.Format # Don't need this anymore + + def preWrite(self, font): + mapping = getattr(self, "mapping", None) + if mapping is None: + mapping = self.mapping = {} + cov = Coverage() + cov.glyphs = sorted(list(mapping.keys()), key=font.getGlyphID) + self.Format = 1 + rawTable = { + "Coverage": cov, + "Sequence": [self.makeSequence_(mapping[glyph]) for glyph in cov.glyphs], + } + return rawTable + + def toXML2(self, xmlWriter, font): + items = sorted(self.mapping.items()) + for inGlyph, outGlyphs in items: + out = ",".join(outGlyphs) + xmlWriter.simpletag("Substitution", [("in", inGlyph), ("out", out)]) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + mapping = getattr(self, "mapping", None) + if mapping is None: + mapping = {} + self.mapping = mapping + + # TTX v3.0 and earlier. + if name == "Coverage": + self.old_coverage_ = [] + for element in content: + if not isinstance(element, tuple): + continue + element_name, element_attrs, _ = element + if element_name == "Glyph": + self.old_coverage_.append(element_attrs["value"]) + return + if name == "Sequence": + index = int(attrs.get("index", len(mapping))) + glyph = self.old_coverage_[index] + glyph_mapping = mapping[glyph] = [] + for element in content: + if not isinstance(element, tuple): + continue + element_name, element_attrs, _ = element + if element_name == "Substitute": + glyph_mapping.append(element_attrs["value"]) + return + + # TTX v3.1 and later. + outGlyphs = attrs["out"].split(",") if attrs["out"] else [] + mapping[attrs["in"]] = [g.strip() for g in outGlyphs] + + @staticmethod + def makeSequence_(g): + seq = Sequence() + seq.Substitute = g + return seq + + +class ClassDef(FormatSwitchingBaseTable): + def populateDefaults(self, propagator=None): + if not hasattr(self, "classDefs"): + self.classDefs = {} + + def postRead(self, rawTable, font): + classDefs = {} + + if self.Format == 1: + start = rawTable["StartGlyph"] + classList = rawTable["ClassValueArray"] + startID = font.getGlyphID(start) + endID = startID + len(classList) + glyphNames = font.getGlyphNameMany(range(startID, endID)) + for glyphName, cls in zip(glyphNames, classList): + if cls: + classDefs[glyphName] = cls + + elif self.Format == 2: + records = rawTable["ClassRangeRecord"] + for rec in records: + cls = rec.Class + if not cls: + continue + start = rec.Start + end = rec.End + startID = font.getGlyphID(start) + endID = font.getGlyphID(end) + 1 + glyphNames = font.getGlyphNameMany(range(startID, endID)) + for glyphName in glyphNames: + classDefs[glyphName] = cls + else: + log.warning("Unknown ClassDef format: %s", self.Format) + self.classDefs = classDefs + del self.Format # Don't need this anymore + + def _getClassRanges(self, font): + classDefs = getattr(self, "classDefs", None) + if classDefs is None: + self.classDefs = {} + return + getGlyphID = font.getGlyphID + items = [] + for glyphName, cls in classDefs.items(): + if not cls: + continue + items.append((getGlyphID(glyphName), glyphName, cls)) + if items: + items.sort() + last, lastName, lastCls = items[0] + ranges = [[lastCls, last, lastName]] + for glyphID, glyphName, cls in items[1:]: + if glyphID != last + 1 or cls != lastCls: + ranges[-1].extend([last, lastName]) + ranges.append([cls, glyphID, glyphName]) + last = glyphID + lastName = glyphName + lastCls = cls + ranges[-1].extend([last, lastName]) + return ranges + + def preWrite(self, font): + format = 2 + rawTable = {"ClassRangeRecord": []} + ranges = self._getClassRanges(font) + if ranges: + startGlyph = ranges[0][1] + endGlyph = ranges[-1][3] + glyphCount = endGlyph - startGlyph + 1 + if len(ranges) * 3 < glyphCount + 1: + # Format 2 is more compact + for i, (cls, start, startName, end, endName) in enumerate(ranges): + rec = ClassRangeRecord() + rec.Start = startName + rec.End = endName + rec.Class = cls + ranges[i] = rec + format = 2 + rawTable = {"ClassRangeRecord": ranges} + else: + # Format 1 is more compact + startGlyphName = ranges[0][2] + classes = [0] * glyphCount + for cls, start, startName, end, endName in ranges: + for g in range(start - startGlyph, end - startGlyph + 1): + classes[g] = cls + format = 1 + rawTable = {"StartGlyph": startGlyphName, "ClassValueArray": classes} + self.Format = format + return rawTable + + def toXML2(self, xmlWriter, font): + items = sorted(self.classDefs.items()) + for glyphName, cls in items: + xmlWriter.simpletag("ClassDef", [("glyph", glyphName), ("class", cls)]) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + classDefs = getattr(self, "classDefs", None) + if classDefs is None: + classDefs = {} + self.classDefs = classDefs + classDefs[attrs["glyph"]] = int(attrs["class"]) + + +class AlternateSubst(FormatSwitchingBaseTable): + def populateDefaults(self, propagator=None): + if not hasattr(self, "alternates"): + self.alternates = {} + + def postRead(self, rawTable, font): + alternates = {} + if self.Format == 1: + input = _getGlyphsFromCoverageTable(rawTable["Coverage"]) + alts = rawTable["AlternateSet"] + assert len(input) == len(alts) + for inp, alt in zip(input, alts): + alternates[inp] = alt.Alternate + else: + assert 0, "unknown format: %s" % self.Format + self.alternates = alternates + del self.Format # Don't need this anymore + + def preWrite(self, font): + self.Format = 1 + alternates = getattr(self, "alternates", None) + if alternates is None: + alternates = self.alternates = {} + items = list(alternates.items()) + for i, (glyphName, set) in enumerate(items): + items[i] = font.getGlyphID(glyphName), glyphName, set + items.sort() + cov = Coverage() + cov.glyphs = [item[1] for item in items] + alternates = [] + setList = [item[-1] for item in items] + for set in setList: + alts = AlternateSet() + alts.Alternate = set + alternates.append(alts) + # a special case to deal with the fact that several hundred Adobe Japan1-5 + # CJK fonts will overflow an offset if the coverage table isn't pushed to the end. + # Also useful in that when splitting a sub-table because of an offset overflow + # I don't need to calculate the change in the subtable offset due to the change in the coverage table size. + # Allows packing more rules in subtable. + self.sortCoverageLast = 1 + return {"Coverage": cov, "AlternateSet": alternates} + + def toXML2(self, xmlWriter, font): + items = sorted(self.alternates.items()) + for glyphName, alternates in items: + xmlWriter.begintag("AlternateSet", glyph=glyphName) + xmlWriter.newline() + for alt in alternates: + xmlWriter.simpletag("Alternate", glyph=alt) + xmlWriter.newline() + xmlWriter.endtag("AlternateSet") + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + alternates = getattr(self, "alternates", None) + if alternates is None: + alternates = {} + self.alternates = alternates + glyphName = attrs["glyph"] + set = [] + alternates[glyphName] = set + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + set.append(attrs["glyph"]) + + +class LigatureSubst(FormatSwitchingBaseTable): + def populateDefaults(self, propagator=None): + if not hasattr(self, "ligatures"): + self.ligatures = {} + + def postRead(self, rawTable, font): + ligatures = {} + if self.Format == 1: + input = _getGlyphsFromCoverageTable(rawTable["Coverage"]) + ligSets = rawTable["LigatureSet"] + assert len(input) == len(ligSets) + for i, inp in enumerate(input): + ligatures[inp] = ligSets[i].Ligature + else: + assert 0, "unknown format: %s" % self.Format + self.ligatures = ligatures + del self.Format # Don't need this anymore + + @staticmethod + def _getLigatureSortKey(components): + # Computes a key for ordering ligatures in a GSUB Type-4 lookup. + + # When building the OpenType lookup, we need to make sure that + # the longest sequence of components is listed first, so we + # use the negative length as the key for sorting. + # Note, we no longer need to worry about deterministic order because the + # ligature mapping `dict` remembers the insertion order, and this in + # turn depends on the order in which the ligatures are written in the FEA. + # Since python sort algorithm is stable, the ligatures of equal length + # will keep the relative order in which they appear in the feature file. + # For example, given the following ligatures (all starting with 'f' and + # thus belonging to the same LigatureSet): + # + # feature liga { + # sub f i by f_i; + # sub f f f by f_f_f; + # sub f f by f_f; + # sub f f i by f_f_i; + # } liga; + # + # this should sort to: f_f_f, f_f_i, f_i, f_f + # This is also what fea-rs does, see: + # https://github.com/adobe-type-tools/afdko/issues/1727 + # https://github.com/fonttools/fonttools/issues/3428 + # https://github.com/googlefonts/fontc/pull/680 + return -len(components) + + def preWrite(self, font): + self.Format = 1 + ligatures = getattr(self, "ligatures", None) + if ligatures is None: + ligatures = self.ligatures = {} + + if ligatures and isinstance(next(iter(ligatures)), tuple): + # New high-level API in v3.1 and later. Note that we just support compiling this + # for now. We don't load to this API, and don't do XML with it. + + # ligatures is map from components-sequence to lig-glyph + newLigatures = dict() + for comps in sorted(ligatures.keys(), key=self._getLigatureSortKey): + ligature = Ligature() + ligature.Component = comps[1:] + ligature.CompCount = len(comps) + ligature.LigGlyph = ligatures[comps] + newLigatures.setdefault(comps[0], []).append(ligature) + ligatures = newLigatures + + items = list(ligatures.items()) + for i, (glyphName, set) in enumerate(items): + items[i] = font.getGlyphID(glyphName), glyphName, set + items.sort() + cov = Coverage() + cov.glyphs = [item[1] for item in items] + + ligSets = [] + setList = [item[-1] for item in items] + for set in setList: + ligSet = LigatureSet() + ligs = ligSet.Ligature = [] + for lig in set: + ligs.append(lig) + ligSets.append(ligSet) + # Useful in that when splitting a sub-table because of an offset overflow + # I don't need to calculate the change in subtabl offset due to the coverage table size. + # Allows packing more rules in subtable. + self.sortCoverageLast = 1 + return {"Coverage": cov, "LigatureSet": ligSets} + + def toXML2(self, xmlWriter, font): + items = sorted(self.ligatures.items()) + for glyphName, ligSets in items: + xmlWriter.begintag("LigatureSet", glyph=glyphName) + xmlWriter.newline() + for lig in ligSets: + xmlWriter.simpletag( + "Ligature", glyph=lig.LigGlyph, components=",".join(lig.Component) + ) + xmlWriter.newline() + xmlWriter.endtag("LigatureSet") + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + ligatures = getattr(self, "ligatures", None) + if ligatures is None: + ligatures = {} + self.ligatures = ligatures + glyphName = attrs["glyph"] + ligs = [] + ligatures[glyphName] = ligs + for element in content: + if not isinstance(element, tuple): + continue + name, attrs, content = element + lig = Ligature() + lig.LigGlyph = attrs["glyph"] + components = attrs["components"] + lig.Component = components.split(",") if components else [] + lig.CompCount = len(lig.Component) + ligs.append(lig) + + +class COLR(BaseTable): + def decompile(self, reader, font): + # COLRv0 is exceptional in that LayerRecordCount appears *after* the + # LayerRecordArray it counts, but the parser logic expects Count fields + # to always precede the arrays. Here we work around this by parsing the + # LayerRecordCount before the rest of the table, and storing it in + # the reader's local state. + subReader = reader.getSubReader(offset=0) + for conv in self.getConverters(): + if conv.name != "LayerRecordCount": + subReader.advance(conv.staticSize) + continue + reader[conv.name] = conv.read(subReader, font, tableDict={}) + break + else: + raise AssertionError("LayerRecordCount converter not found") + return BaseTable.decompile(self, reader, font) + + def preWrite(self, font): + # The writer similarly assumes Count values precede the things counted, + # thus here we pre-initialize a CountReference; the actual count value + # will be set to the lenght of the array by the time this is assembled. + self.LayerRecordCount = None + return { + **self.__dict__, + "LayerRecordCount": CountReference(self.__dict__, "LayerRecordCount"), + } + + def computeClipBoxes(self, glyphSet: "_TTGlyphSet", quantization: int = 1): + if self.Version == 0: + return + + clips = {} + for rec in self.BaseGlyphList.BaseGlyphPaintRecord: + try: + clipBox = rec.Paint.computeClipBox(self, glyphSet, quantization) + except Exception as e: + from fontTools.ttLib import TTLibError + + raise TTLibError( + f"Failed to compute COLR ClipBox for {rec.BaseGlyph!r}" + ) from e + + if clipBox is not None: + clips[rec.BaseGlyph] = clipBox + + hasClipList = hasattr(self, "ClipList") and self.ClipList is not None + if not clips: + if hasClipList: + self.ClipList = None + else: + if not hasClipList: + self.ClipList = ClipList() + self.ClipList.Format = 1 + self.ClipList.clips = clips + + +class LookupList(BaseTable): + @property + def table(self): + for l in self.Lookup: + for st in l.SubTable: + if type(st).__name__.endswith("Subst"): + return "GSUB" + if type(st).__name__.endswith("Pos"): + return "GPOS" + raise ValueError + + def toXML2(self, xmlWriter, font): + if ( + not font + or "Debg" not in font + or LOOKUP_DEBUG_INFO_KEY not in font["Debg"].data + ): + return super().toXML2(xmlWriter, font) + debugData = font["Debg"].data[LOOKUP_DEBUG_INFO_KEY][self.table] + for conv in self.getConverters(): + if conv.repeat: + value = getattr(self, conv.name, []) + for lookupIndex, item in enumerate(value): + if str(lookupIndex) in debugData: + info = LookupDebugInfo(*debugData[str(lookupIndex)]) + tag = info.location + if info.name: + tag = f"{info.name}: {tag}" + if info.feature: + script, language, feature = info.feature + tag = f"{tag} in {feature} ({script}/{language})" + xmlWriter.comment(tag) + xmlWriter.newline() + + conv.xmlWrite( + xmlWriter, font, item, conv.name, [("index", lookupIndex)] + ) + else: + if conv.aux and not eval(conv.aux, None, vars(self)): + continue + value = getattr( + self, conv.name, None + ) # TODO Handle defaults instead of defaulting to None! + conv.xmlWrite(xmlWriter, font, value, conv.name, []) + + +class BaseGlyphRecordArray(BaseTable): + def preWrite(self, font): + self.BaseGlyphRecord = sorted( + self.BaseGlyphRecord, key=lambda rec: font.getGlyphID(rec.BaseGlyph) + ) + return self.__dict__.copy() + + +class BaseGlyphList(BaseTable): + def preWrite(self, font): + self.BaseGlyphPaintRecord = sorted( + self.BaseGlyphPaintRecord, key=lambda rec: font.getGlyphID(rec.BaseGlyph) + ) + return self.__dict__.copy() + + +class ClipBoxFormat(IntEnum): + Static = 1 + Variable = 2 + + def is_variable(self): + return self is self.Variable + + def as_variable(self): + return self.Variable + + +class ClipBox(getFormatSwitchingBaseTableClass("uint8")): + formatEnum = ClipBoxFormat + + def as_tuple(self): + return tuple(getattr(self, conv.name) for conv in self.getConverters()) + + def __repr__(self): + return f"{self.__class__.__name__}{self.as_tuple()}" + + +class ClipList(getFormatSwitchingBaseTableClass("uint8")): + def populateDefaults(self, propagator=None): + if not hasattr(self, "clips"): + self.clips = {} + + def postRead(self, rawTable, font): + clips = {} + glyphOrder = font.getGlyphOrder() + for i, rec in enumerate(rawTable["ClipRecord"]): + if rec.StartGlyphID > rec.EndGlyphID: + log.warning( + "invalid ClipRecord[%i].StartGlyphID (%i) > " + "EndGlyphID (%i); skipped", + i, + rec.StartGlyphID, + rec.EndGlyphID, + ) + continue + redefinedGlyphs = [] + missingGlyphs = [] + for glyphID in range(rec.StartGlyphID, rec.EndGlyphID + 1): + try: + glyph = glyphOrder[glyphID] + except IndexError: + missingGlyphs.append(glyphID) + continue + if glyph not in clips: + clips[glyph] = copy.copy(rec.ClipBox) + else: + redefinedGlyphs.append(glyphID) + if redefinedGlyphs: + log.warning( + "ClipRecord[%i] overlaps previous records; " + "ignoring redefined clip boxes for the " + "following glyph ID range: [%i-%i]", + i, + min(redefinedGlyphs), + max(redefinedGlyphs), + ) + if missingGlyphs: + log.warning( + "ClipRecord[%i] range references missing " "glyph IDs: [%i-%i]", + i, + min(missingGlyphs), + max(missingGlyphs), + ) + self.clips = clips + + def groups(self): + glyphsByClip = defaultdict(list) + uniqueClips = {} + for glyphName, clipBox in self.clips.items(): + key = clipBox.as_tuple() + glyphsByClip[key].append(glyphName) + if key not in uniqueClips: + uniqueClips[key] = clipBox + return { + frozenset(glyphs): uniqueClips[key] for key, glyphs in glyphsByClip.items() + } + + def preWrite(self, font): + if not hasattr(self, "clips"): + self.clips = {} + clipBoxRanges = {} + glyphMap = font.getReverseGlyphMap() + for glyphs, clipBox in self.groups().items(): + glyphIDs = sorted( + glyphMap[glyphName] for glyphName in glyphs if glyphName in glyphMap + ) + if not glyphIDs: + continue + last = glyphIDs[0] + ranges = [[last]] + for glyphID in glyphIDs[1:]: + if glyphID != last + 1: + ranges[-1].append(last) + ranges.append([glyphID]) + last = glyphID + ranges[-1].append(last) + for start, end in ranges: + assert (start, end) not in clipBoxRanges + clipBoxRanges[(start, end)] = clipBox + + clipRecords = [] + for (start, end), clipBox in sorted(clipBoxRanges.items()): + record = ClipRecord() + record.StartGlyphID = start + record.EndGlyphID = end + record.ClipBox = clipBox + clipRecords.append(record) + rawTable = { + "ClipCount": len(clipRecords), + "ClipRecord": clipRecords, + } + return rawTable + + def toXML(self, xmlWriter, font, attrs=None, name=None): + tableName = name if name else self.__class__.__name__ + if attrs is None: + attrs = [] + if hasattr(self, "Format"): + attrs.append(("Format", self.Format)) + xmlWriter.begintag(tableName, attrs) + xmlWriter.newline() + # sort clips alphabetically to ensure deterministic XML dump + for glyphs, clipBox in sorted( + self.groups().items(), key=lambda item: min(item[0]) + ): + xmlWriter.begintag("Clip") + xmlWriter.newline() + for glyphName in sorted(glyphs): + xmlWriter.simpletag("Glyph", value=glyphName) + xmlWriter.newline() + xmlWriter.begintag("ClipBox", [("Format", clipBox.Format)]) + xmlWriter.newline() + clipBox.toXML2(xmlWriter, font) + xmlWriter.endtag("ClipBox") + xmlWriter.newline() + xmlWriter.endtag("Clip") + xmlWriter.newline() + xmlWriter.endtag(tableName) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + clips = getattr(self, "clips", None) + if clips is None: + self.clips = clips = {} + assert name == "Clip" + glyphs = [] + clipBox = None + for elem in content: + if not isinstance(elem, tuple): + continue + name, attrs, content = elem + if name == "Glyph": + glyphs.append(attrs["value"]) + elif name == "ClipBox": + clipBox = ClipBox() + clipBox.Format = safeEval(attrs["Format"]) + for elem in content: + if not isinstance(elem, tuple): + continue + name, attrs, content = elem + clipBox.fromXML(name, attrs, content, font) + if clipBox: + for glyphName in glyphs: + clips[glyphName] = clipBox + + +class ExtendMode(IntEnum): + PAD = 0 + REPEAT = 1 + REFLECT = 2 + + +# Porter-Duff modes for COLRv1 PaintComposite: +# https://github.com/googlefonts/colr-gradients-spec/tree/off_sub_1#compositemode-enumeration +class CompositeMode(IntEnum): + CLEAR = 0 + SRC = 1 + DEST = 2 + SRC_OVER = 3 + DEST_OVER = 4 + SRC_IN = 5 + DEST_IN = 6 + SRC_OUT = 7 + DEST_OUT = 8 + SRC_ATOP = 9 + DEST_ATOP = 10 + XOR = 11 + PLUS = 12 + SCREEN = 13 + OVERLAY = 14 + DARKEN = 15 + LIGHTEN = 16 + COLOR_DODGE = 17 + COLOR_BURN = 18 + HARD_LIGHT = 19 + SOFT_LIGHT = 20 + DIFFERENCE = 21 + EXCLUSION = 22 + MULTIPLY = 23 + HSL_HUE = 24 + HSL_SATURATION = 25 + HSL_COLOR = 26 + HSL_LUMINOSITY = 27 + + +class PaintFormat(IntEnum): + PaintColrLayers = 1 + PaintSolid = 2 + PaintVarSolid = 3 + PaintLinearGradient = 4 + PaintVarLinearGradient = 5 + PaintRadialGradient = 6 + PaintVarRadialGradient = 7 + PaintSweepGradient = 8 + PaintVarSweepGradient = 9 + PaintGlyph = 10 + PaintColrGlyph = 11 + PaintTransform = 12 + PaintVarTransform = 13 + PaintTranslate = 14 + PaintVarTranslate = 15 + PaintScale = 16 + PaintVarScale = 17 + PaintScaleAroundCenter = 18 + PaintVarScaleAroundCenter = 19 + PaintScaleUniform = 20 + PaintVarScaleUniform = 21 + PaintScaleUniformAroundCenter = 22 + PaintVarScaleUniformAroundCenter = 23 + PaintRotate = 24 + PaintVarRotate = 25 + PaintRotateAroundCenter = 26 + PaintVarRotateAroundCenter = 27 + PaintSkew = 28 + PaintVarSkew = 29 + PaintSkewAroundCenter = 30 + PaintVarSkewAroundCenter = 31 + PaintComposite = 32 + + def is_variable(self): + return self.name.startswith("PaintVar") + + def as_variable(self): + if self.is_variable(): + return self + try: + return PaintFormat.__members__[f"PaintVar{self.name[5:]}"] + except KeyError: + return None + + +class Paint(getFormatSwitchingBaseTableClass("uint8")): + formatEnum = PaintFormat + + def getFormatName(self): + try: + return self.formatEnum(self.Format).name + except ValueError: + raise NotImplementedError(f"Unknown Paint format: {self.Format}") + + def toXML(self, xmlWriter, font, attrs=None, name=None): + tableName = name if name else self.__class__.__name__ + if attrs is None: + attrs = [] + attrs.append(("Format", self.Format)) + xmlWriter.begintag(tableName, attrs) + xmlWriter.comment(self.getFormatName()) + xmlWriter.newline() + self.toXML2(xmlWriter, font) + xmlWriter.endtag(tableName) + xmlWriter.newline() + + def iterPaintSubTables(self, colr: COLR) -> Iterator[BaseTable.SubTableEntry]: + if self.Format == PaintFormat.PaintColrLayers: + # https://github.com/fonttools/fonttools/issues/2438: don't die when no LayerList exists + layers = [] + if colr.LayerList is not None: + layers = colr.LayerList.Paint + yield from ( + BaseTable.SubTableEntry(name="Layers", value=v, index=i) + for i, v in enumerate( + layers[self.FirstLayerIndex : self.FirstLayerIndex + self.NumLayers] + ) + ) + return + + if self.Format == PaintFormat.PaintColrGlyph: + for record in colr.BaseGlyphList.BaseGlyphPaintRecord: + if record.BaseGlyph == self.Glyph: + yield BaseTable.SubTableEntry(name="BaseGlyph", value=record.Paint) + return + else: + raise KeyError(f"{self.Glyph!r} not in colr.BaseGlyphList") + + for conv in self.getConverters(): + if conv.tableClass is not None and issubclass(conv.tableClass, type(self)): + value = getattr(self, conv.name) + yield BaseTable.SubTableEntry(name=conv.name, value=value) + + def getChildren(self, colr) -> List["Paint"]: + # this is kept for backward compatibility (e.g. it's used by the subsetter) + return [p.value for p in self.iterPaintSubTables(colr)] + + def traverse(self, colr: COLR, callback): + """Depth-first traversal of graph rooted at self, callback on each node.""" + if not callable(callback): + raise TypeError("callback must be callable") + + for path in dfs_base_table( + self, iter_subtables_fn=lambda paint: paint.iterPaintSubTables(colr) + ): + paint = path[-1].value + callback(paint) + + def getTransform(self) -> Transform: + if self.Format == PaintFormat.PaintTransform: + t = self.Transform + return Transform(t.xx, t.yx, t.xy, t.yy, t.dx, t.dy) + elif self.Format == PaintFormat.PaintTranslate: + return Identity.translate(self.dx, self.dy) + elif self.Format == PaintFormat.PaintScale: + return Identity.scale(self.scaleX, self.scaleY) + elif self.Format == PaintFormat.PaintScaleAroundCenter: + return ( + Identity.translate(self.centerX, self.centerY) + .scale(self.scaleX, self.scaleY) + .translate(-self.centerX, -self.centerY) + ) + elif self.Format == PaintFormat.PaintScaleUniform: + return Identity.scale(self.scale) + elif self.Format == PaintFormat.PaintScaleUniformAroundCenter: + return ( + Identity.translate(self.centerX, self.centerY) + .scale(self.scale) + .translate(-self.centerX, -self.centerY) + ) + elif self.Format == PaintFormat.PaintRotate: + return Identity.rotate(radians(self.angle)) + elif self.Format == PaintFormat.PaintRotateAroundCenter: + return ( + Identity.translate(self.centerX, self.centerY) + .rotate(radians(self.angle)) + .translate(-self.centerX, -self.centerY) + ) + elif self.Format == PaintFormat.PaintSkew: + return Identity.skew(radians(-self.xSkewAngle), radians(self.ySkewAngle)) + elif self.Format == PaintFormat.PaintSkewAroundCenter: + return ( + Identity.translate(self.centerX, self.centerY) + .skew(radians(-self.xSkewAngle), radians(self.ySkewAngle)) + .translate(-self.centerX, -self.centerY) + ) + if PaintFormat(self.Format).is_variable(): + raise NotImplementedError(f"Variable Paints not supported: {self.Format}") + + return Identity + + def computeClipBox( + self, colr: COLR, glyphSet: "_TTGlyphSet", quantization: int = 1 + ) -> Optional[ClipBox]: + pen = ControlBoundsPen(glyphSet) + for path in dfs_base_table( + self, iter_subtables_fn=lambda paint: paint.iterPaintSubTables(colr) + ): + paint = path[-1].value + if paint.Format == PaintFormat.PaintGlyph: + transformation = reduce( + Transform.transform, + (st.value.getTransform() for st in path), + Identity, + ) + glyphSet[paint.Glyph].draw(TransformPen(pen, transformation)) + + if pen.bounds is None: + return None + + cb = ClipBox() + cb.Format = int(ClipBoxFormat.Static) + cb.xMin, cb.yMin, cb.xMax, cb.yMax = quantizeRect(pen.bounds, quantization) + return cb + + +# For each subtable format there is a class. However, we don't really distinguish +# between "field name" and "format name": often these are the same. Yet there's +# a whole bunch of fields with different names. The following dict is a mapping +# from "format name" to "field name". _buildClasses() uses this to create a +# subclass for each alternate field name. +# +_equivalents = { + "PatchMap": ("IFT ", "IFTX"), + "MarkArray": ("Mark1Array",), + "LangSys": ("DefaultLangSys",), + "Coverage": ( + "MarkCoverage", + "BaseCoverage", + "LigatureCoverage", + "Mark1Coverage", + "Mark2Coverage", + "BacktrackCoverage", + "InputCoverage", + "LookAheadCoverage", + "VertGlyphCoverage", + "HorizGlyphCoverage", + "TopAccentCoverage", + "ExtendedShapeCoverage", + "MathKernCoverage", + ), + "ClassDef": ( + "ClassDef1", + "ClassDef2", + "BacktrackClassDef", + "InputClassDef", + "LookAheadClassDef", + "GlyphClassDef", + "MarkAttachClassDef", + ), + "Anchor": ( + "EntryAnchor", + "ExitAnchor", + "BaseAnchor", + "LigatureAnchor", + "Mark2Anchor", + "MarkAnchor", + ), + "Device": ( + "XPlaDevice", + "YPlaDevice", + "XAdvDevice", + "YAdvDevice", + "XDeviceTable", + "YDeviceTable", + "DeviceTable", + ), + "Axis": ( + "HorizAxis", + "VertAxis", + ), + "MinMax": ("DefaultMinMax",), + "BaseCoord": ( + "MinCoord", + "MaxCoord", + ), + "JstfLangSys": ("DefJstfLangSys",), + "JstfGSUBModList": ( + "ShrinkageEnableGSUB", + "ShrinkageDisableGSUB", + "ExtensionEnableGSUB", + "ExtensionDisableGSUB", + ), + "JstfGPOSModList": ( + "ShrinkageEnableGPOS", + "ShrinkageDisableGPOS", + "ExtensionEnableGPOS", + "ExtensionDisableGPOS", + ), + "JstfMax": ( + "ShrinkageJstfMax", + "ExtensionJstfMax", + ), + "MathKern": ( + "TopRightMathKern", + "TopLeftMathKern", + "BottomRightMathKern", + "BottomLeftMathKern", + ), + "MathGlyphConstruction": ("VertGlyphConstruction", "HorizGlyphConstruction"), +} + +# +# OverFlow logic, to automatically create ExtensionLookups +# XXX This should probably move to otBase.py +# + + +def fixLookupOverFlows(ttf, overflowRecord): + """Either the offset from the LookupList to a lookup overflowed, or + an offset from a lookup to a subtable overflowed. + + The table layout is:: + + GPSO/GUSB + Script List + Feature List + LookUpList + Lookup[0] and contents + SubTable offset list + SubTable[0] and contents + ... + SubTable[n] and contents + ... + Lookup[n] and contents + SubTable offset list + SubTable[0] and contents + ... + SubTable[n] and contents + + If the offset to a lookup overflowed (SubTableIndex is None) + we must promote the *previous* lookup to an Extension type. + + If the offset from a lookup to subtable overflowed, then we must promote it + to an Extension Lookup type. + """ + ok = 0 + lookupIndex = overflowRecord.LookupListIndex + if overflowRecord.SubTableIndex is None: + lookupIndex = lookupIndex - 1 + if lookupIndex < 0: + return ok + if overflowRecord.tableType == "GSUB": + extType = 7 + elif overflowRecord.tableType == "GPOS": + extType = 9 + + lookups = ttf[overflowRecord.tableType].table.LookupList.Lookup + lookup = lookups[lookupIndex] + # If the previous lookup is an extType, look further back. Very unlikely, but possible. + while lookup.SubTable[0].__class__.LookupType == extType: + lookupIndex = lookupIndex - 1 + if lookupIndex < 0: + # Every lookup before the overflow is already an Extension lookup, so + # there is nothing left to promote. When this is a LookupList->Lookup + # offset overflow (SubTableIndex is None), the LookupList's uint16 + # offsets simply can't address all the lookups and fontTools' packer + # can't recover; warn with actionable advice. (For a subtable offset + # overflow that fell back here, SubTableIndex is set and this message + # would be misleading, so it's skipped.) + if overflowRecord.SubTableIndex is None: + log.error( + "%s LookupList offset overflowed and all lookups are already " + "Extension lookups, so the overflow can't be resolved by " + "promotion; %s.", + overflowRecord.tableType, + ( + "reduce the number of lookups" + if have_uharfbuzz + else "install uharfbuzz to enable the HarfBuzz repacker " + "(it can often pack such tables by sharing/duplicating " + "subtables), or reduce the number of lookups" + ), + ) + return ok + lookup = lookups[lookupIndex] + + for lookupIndex in range(lookupIndex, len(lookups)): + lookup = lookups[lookupIndex] + if lookup.LookupType != extType: + lookup.LookupType = extType + for si, subTable in enumerate(lookup.SubTable): + extSubTableClass = lookupTypes[overflowRecord.tableType][extType] + extSubTable = extSubTableClass() + extSubTable.Format = 1 + extSubTable.ExtSubTable = subTable + lookup.SubTable[si] = extSubTable + ok = 1 + return ok + + +def splitMultipleSubst(oldSubTable, newSubTable, overflowRecord): + ok = 1 + oldMapping = sorted(oldSubTable.mapping.items()) + oldLen = len(oldMapping) + + if overflowRecord.itemName in ["Coverage", "RangeRecord"]: + # Coverage table is written last. Overflow is to or within the + # the coverage table. We will just cut the subtable in half. + newLen = oldLen // 2 + + elif overflowRecord.itemName == "Sequence": + # We just need to back up by two items from the overflowed + # Sequence index to make sure the offset to the Coverage table + # doesn't overflow. + newLen = overflowRecord.itemIndex - 1 + + newSubTable.mapping = {} + for i in range(newLen, oldLen): + item = oldMapping[i] + key = item[0] + newSubTable.mapping[key] = item[1] + del oldSubTable.mapping[key] + + return ok + + +def splitAlternateSubst(oldSubTable, newSubTable, overflowRecord): + ok = 1 + if hasattr(oldSubTable, "sortCoverageLast"): + newSubTable.sortCoverageLast = oldSubTable.sortCoverageLast + + oldAlts = sorted(oldSubTable.alternates.items()) + oldLen = len(oldAlts) + + if overflowRecord.itemName in ["Coverage", "RangeRecord"]: + # Coverage table is written last. overflow is to or within the + # the coverage table. We will just cut the subtable in half. + newLen = oldLen // 2 + + elif overflowRecord.itemName == "AlternateSet": + # We just need to back up by two items + # from the overflowed AlternateSet index to make sure the offset + # to the Coverage table doesn't overflow. + newLen = overflowRecord.itemIndex - 1 + + newSubTable.alternates = {} + for i in range(newLen, oldLen): + item = oldAlts[i] + key = item[0] + newSubTable.alternates[key] = item[1] + del oldSubTable.alternates[key] + + return ok + + +def splitLigatureSubst(oldSubTable, newSubTable, overflowRecord): + ok = 1 + oldLigs = sorted(oldSubTable.ligatures.items()) + oldLen = len(oldLigs) + + if overflowRecord.itemName in ["Coverage", "RangeRecord"]: + # Coverage table is written last. overflow is to or within the + # the coverage table. We will just cut the subtable in half. + newLen = oldLen // 2 + + elif overflowRecord.itemName == "LigatureSet": + # We just need to back up by two items + # from the overflowed AlternateSet index to make sure the offset + # to the Coverage table doesn't overflow. + newLen = overflowRecord.itemIndex - 1 + + newSubTable.ligatures = {} + for i in range(newLen, oldLen): + item = oldLigs[i] + key = item[0] + newSubTable.ligatures[key] = item[1] + del oldSubTable.ligatures[key] + + return ok + + +def splitSinglePos(oldSubTable, newSubTable, overflowRecord): + # Only Format 2 (one Value per covered glyph) is worth splitting; a Format 1 + # subtable shares a single Value across its whole Coverage, so there is + # nothing worth splitting. + if oldSubTable.Format != 2 or len(oldSubTable.Coverage.glyphs) <= 1: + return False + + newSubTable.Format = oldSubTable.Format + newSubTable.ValueFormat = oldSubTable.ValueFormat + + coverage = oldSubTable.Coverage.glyphs + values = oldSubTable.Value + oldCount = len(coverage) // 2 + + newSubTable.Coverage = oldSubTable.Coverage.__class__() + newSubTable.Coverage.glyphs = coverage[oldCount:] + newSubTable.Value = values[oldCount:] + + oldSubTable.Coverage.glyphs = coverage[:oldCount] + oldSubTable.Value = values[:oldCount] + + oldSubTable.ValueCount = len(oldSubTable.Value) + newSubTable.ValueCount = len(newSubTable.Value) + + return True + + +def splitPairPos(oldSubTable, newSubTable, overflowRecord): + st = oldSubTable + ok = False + newSubTable.Format = oldSubTable.Format + if oldSubTable.Format == 1 and len(oldSubTable.PairSet) > 1: + for name in "ValueFormat1", "ValueFormat2": + setattr(newSubTable, name, getattr(oldSubTable, name)) + + # Move top half of coverage to new subtable + + newSubTable.Coverage = oldSubTable.Coverage.__class__() + + coverage = oldSubTable.Coverage.glyphs + records = oldSubTable.PairSet + + oldCount = len(oldSubTable.PairSet) // 2 + + oldSubTable.Coverage.glyphs = coverage[:oldCount] + oldSubTable.PairSet = records[:oldCount] + + newSubTable.Coverage.glyphs = coverage[oldCount:] + newSubTable.PairSet = records[oldCount:] + + oldSubTable.PairSetCount = len(oldSubTable.PairSet) + newSubTable.PairSetCount = len(newSubTable.PairSet) + + ok = True + + elif oldSubTable.Format == 2 and len(oldSubTable.Class1Record) > 1: + if not hasattr(oldSubTable, "Class2Count"): + oldSubTable.Class2Count = len(oldSubTable.Class1Record[0].Class2Record) + for name in "Class2Count", "ClassDef2", "ValueFormat1", "ValueFormat2": + setattr(newSubTable, name, getattr(oldSubTable, name)) + + # The two subtables will still have the same ClassDef2 and the table + # sharing will still cause the sharing to overflow. As such, disable + # sharing on the one that is serialized second (that's oldSubTable). + oldSubTable.DontShare = True + + # Move top half of class numbers to new subtable + + newSubTable.Coverage = oldSubTable.Coverage.__class__() + newSubTable.ClassDef1 = oldSubTable.ClassDef1.__class__() + + coverage = oldSubTable.Coverage.glyphs + classDefs = oldSubTable.ClassDef1.classDefs + records = oldSubTable.Class1Record + + oldCount = len(oldSubTable.Class1Record) // 2 + newGlyphs = set(k for k, v in classDefs.items() if v >= oldCount) + + oldSubTable.Coverage.glyphs = [g for g in coverage if g not in newGlyphs] + oldSubTable.ClassDef1.classDefs = { + k: v for k, v in classDefs.items() if v < oldCount + } + oldSubTable.Class1Record = records[:oldCount] + + newSubTable.Coverage.glyphs = [g for g in coverage if g in newGlyphs] + newSubTable.ClassDef1.classDefs = { + k: (v - oldCount) for k, v in classDefs.items() if v > oldCount + } + newSubTable.Class1Record = records[oldCount:] + + oldSubTable.Class1Count = len(oldSubTable.Class1Record) + newSubTable.Class1Count = len(newSubTable.Class1Record) + + ok = True + + return ok + + +def splitMarkBasePos(oldSubTable, newSubTable, overflowRecord): + # split half of the mark classes to the new subtable + classCount = oldSubTable.ClassCount + if classCount < 2: + # oh well, not much left to split... + return False + + oldClassCount = classCount // 2 + newClassCount = classCount - oldClassCount + + oldMarkCoverage, oldMarkRecords = [], [] + newMarkCoverage, newMarkRecords = [], [] + for glyphName, markRecord in zip( + oldSubTable.MarkCoverage.glyphs, oldSubTable.MarkArray.MarkRecord + ): + if markRecord.Class < oldClassCount: + oldMarkCoverage.append(glyphName) + oldMarkRecords.append(markRecord) + else: + markRecord.Class -= oldClassCount + newMarkCoverage.append(glyphName) + newMarkRecords.append(markRecord) + + oldBaseRecords, newBaseRecords = [], [] + for rec in oldSubTable.BaseArray.BaseRecord: + oldBaseRecord, newBaseRecord = rec.__class__(), rec.__class__() + oldBaseRecord.BaseAnchor = rec.BaseAnchor[:oldClassCount] + newBaseRecord.BaseAnchor = rec.BaseAnchor[oldClassCount:] + oldBaseRecords.append(oldBaseRecord) + newBaseRecords.append(newBaseRecord) + + newSubTable.Format = oldSubTable.Format + + oldSubTable.MarkCoverage.glyphs = oldMarkCoverage + newSubTable.MarkCoverage = oldSubTable.MarkCoverage.__class__() + newSubTable.MarkCoverage.glyphs = newMarkCoverage + + # share the same BaseCoverage in both halves + newSubTable.BaseCoverage = oldSubTable.BaseCoverage + + oldSubTable.ClassCount = oldClassCount + newSubTable.ClassCount = newClassCount + + oldSubTable.MarkArray.MarkRecord = oldMarkRecords + newSubTable.MarkArray = oldSubTable.MarkArray.__class__() + newSubTable.MarkArray.MarkRecord = newMarkRecords + + oldSubTable.MarkArray.MarkCount = len(oldMarkRecords) + newSubTable.MarkArray.MarkCount = len(newMarkRecords) + + oldSubTable.BaseArray.BaseRecord = oldBaseRecords + newSubTable.BaseArray = oldSubTable.BaseArray.__class__() + newSubTable.BaseArray.BaseRecord = newBaseRecords + + oldSubTable.BaseArray.BaseCount = len(oldBaseRecords) + newSubTable.BaseArray.BaseCount = len(newBaseRecords) + + return True + + +splitTable = { + "GSUB": { + # 1: splitSingleSubst, + 2: splitMultipleSubst, + 3: splitAlternateSubst, + 4: splitLigatureSubst, + # 5: splitContextSubst, + # 6: splitChainContextSubst, + # 7: splitExtensionSubst, + # 8: splitReverseChainSingleSubst, + }, + "GPOS": { + 1: splitSinglePos, + 2: splitPairPos, + # 3: splitCursivePos, + 4: splitMarkBasePos, + # 5: splitMarkLigPos, + # 6: splitMarkMarkPos, + # 7: splitContextPos, + # 8: splitChainContextPos, + # 9: splitExtensionPos, + }, +} + + +def fixSubTableOverFlows(ttf, overflowRecord): + """ + An offset has overflowed within a sub-table. We need to divide this subtable into smaller parts. + """ + table = ttf[overflowRecord.tableType].table + lookup = table.LookupList.Lookup[overflowRecord.LookupListIndex] + subIndex = overflowRecord.SubTableIndex + subtable = lookup.SubTable[subIndex] + + # First, try not sharing anything for this subtable... + if not hasattr(subtable, "DontShare"): + subtable.DontShare = True + return True + + if hasattr(subtable, "ExtSubTable"): + # We split the subtable of the Extension table, and add a new Extension table + # to contain the new subtable. + + subTableType = subtable.ExtSubTable.__class__.LookupType + extSubTable = subtable + subtable = extSubTable.ExtSubTable + newExtSubTableClass = lookupTypes[overflowRecord.tableType][ + extSubTable.__class__.LookupType + ] + newExtSubTable = newExtSubTableClass() + newExtSubTable.Format = extSubTable.Format + toInsert = newExtSubTable + + newSubTableClass = lookupTypes[overflowRecord.tableType][subTableType] + newSubTable = newSubTableClass() + newExtSubTable.ExtSubTable = newSubTable + else: + subTableType = subtable.__class__.LookupType + newSubTableClass = lookupTypes[overflowRecord.tableType][subTableType] + newSubTable = newSubTableClass() + toInsert = newSubTable + + if hasattr(lookup, "SubTableCount"): # may not be defined yet. + lookup.SubTableCount = lookup.SubTableCount + 1 + + try: + splitFunc = splitTable[overflowRecord.tableType][subTableType] + except KeyError: + log.error( + "Don't know how to split %s lookup type %s", + overflowRecord.tableType, + subTableType, + ) + return False + + ok = splitFunc(subtable, newSubTable, overflowRecord) + if ok: + lookup.SubTable.insert(subIndex + 1, toInsert) + return ok + + +# End of OverFlow logic + + +# --------------------------------------------------------------------------- +# IFT - Incremental Font Transfer tables +# --------------------------------------------------------------------------- + + +class EntryIdStringData(BaseTable): + """IFT entry ID string data block (raw bytes pool).""" + + def decompile(self, reader, font): + # This subtable is reached via an LOffset, so the reader's data buffer + # is already scoped to the bytes starting at the subtable's offset within + # the IFT table blob. Reading to the end of that buffer is correct; the + # actual bytes consumed are determined by the entryIdStringLength fields + # in the MappingEntries records. + self.data = bytes(reader.data[reader.pos :]) + + def compile(self, writer, font): + writer.writeData(self.data) + + def toXML2(self, xmlWriter, font): + xmlWriter.simpletag("data", value=self.data.hex()) + xmlWriter.newline() + + def fromXML(self, name, attrs, content, font): + if name == "data": + self.data = bytes.fromhex(attrs["value"]) + + +def _buildClasses(): + import re + from .otData import otData + + formatPat = re.compile(r"([A-Za-z0-9]+)Format(\d+)$") + namespace = globals() + + # populate module with classes + for name, fields in otData: + baseClass = BaseTable + m = formatPat.match(name) + if m: + # XxxFormatN subtable, we only add the "base" table + name = m.group(1) + # the first row of a format-switching otData table describes the Format; + # the first column defines the type of the Format field. + # Currently this can be either 'uint16' or 'uint8'. + formatType = fields[0].type + baseClass = getFormatSwitchingBaseTableClass(formatType) + if name not in namespace: + # the class doesn't exist yet, so the base implementation is used. + cls = type(name, (baseClass,), {}) + if name in ("GSUB", "GPOS"): + cls.DontShare = True + namespace[name] = cls + + # link Var{Table} <-> {Table} (e.g. ColorStop <-> VarColorStop, etc.) + for name, _ in otData: + if name.startswith("Var") and len(name) > 3 and name[3:] in namespace: + varType = namespace[name] + noVarType = namespace[name[3:]] + varType.NoVarType = noVarType + noVarType.VarType = varType + + for base, alts in _equivalents.items(): + base = namespace[base] + for alt in alts: + namespace[alt] = base + + global lookupTypes + lookupTypes = { + "GSUB": { + 1: SingleSubst, + 2: MultipleSubst, + 3: AlternateSubst, + 4: LigatureSubst, + 5: ContextSubst, + 6: ChainContextSubst, + 7: ExtensionSubst, + 8: ReverseChainSingleSubst, + }, + "GPOS": { + 1: SinglePos, + 2: PairPos, + 3: CursivePos, + 4: MarkBasePos, + 5: MarkLigPos, + 6: MarkMarkPos, + 7: ContextPos, + 8: ChainContextPos, + 9: ExtensionPos, + }, + "mort": { + 0: RearrangementMorph, + 1: ContextualMorph, + 2: LigatureMorph, + 4: NoncontextualMorph, + 5: InsertionMorph, + }, + "morx": { + 0: RearrangementMorph, + 1: ContextualMorph, + 2: LigatureMorph, + # 3: Reserved, + 4: NoncontextualMorph, + 5: InsertionMorph, + }, + } + lookupTypes["JSTF"] = lookupTypes["GPOS"] # JSTF contains GPOS + for lookupEnum in lookupTypes.values(): + for enum, cls in lookupEnum.items(): + cls.LookupType = enum + + global featureParamTypes + featureParamTypes = { + "size": FeatureParamsSize, + } + for i in range(1, 20 + 1): + featureParamTypes["ss%02d" % i] = FeatureParamsStylisticSet + for i in range(1, 99 + 1): + featureParamTypes["cv%02d" % i] = FeatureParamsCharacterVariants + + # add converters to classes + from .otConverters import buildConverters + + for name, fields in otData: + m = formatPat.match(name) + if m: + # XxxFormatN subtable, add converter to "base" table + name, format = m.groups() + format = int(format) + cls = namespace[name] + if not hasattr(cls, "converters"): + cls.converters = {} + cls.convertersByName = {} + converters, convertersByName = buildConverters(fields[1:], namespace) + cls.converters[format] = converters + cls.convertersByName[format] = convertersByName + # XXX Add staticSize? + else: + cls = namespace[name] + cls.converters, cls.convertersByName = buildConverters(fields, namespace) + # XXX Add staticSize? + + +_buildClasses() + + +def _getGlyphsFromCoverageTable(coverage): + if coverage is None: + # empty coverage table + return [] + else: + return coverage.glyphs diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otTraverse.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otTraverse.py new file mode 100644 index 0000000000000000000000000000000000000000..f0a9b7587bfa6b0e1f28b93c36ef835274cb6a24 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/otTraverse.py @@ -0,0 +1,162 @@ +"""Methods for traversing trees of otData-driven OpenType tables.""" + +from collections import deque +from typing import Callable, Deque, Iterable, List, Optional, Tuple +from .otBase import BaseTable + +__all__ = [ + "bfs_base_table", + "dfs_base_table", + "SubTablePath", +] + + +class SubTablePath(Tuple[BaseTable.SubTableEntry, ...]): + def __str__(self) -> str: + path_parts = [] + for entry in self: + path_part = entry.name + if entry.index is not None: + path_part += f"[{entry.index}]" + path_parts.append(path_part) + return ".".join(path_parts) + + +# Given f(current frontier, new entries) add new entries to frontier +AddToFrontierFn = Callable[[Deque[SubTablePath], List[SubTablePath]], None] + + +def dfs_base_table( + root: BaseTable, + root_accessor: Optional[str] = None, + skip_root: bool = False, + predicate: Optional[Callable[[SubTablePath], bool]] = None, + iter_subtables_fn: Optional[ + Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]] + ] = None, +) -> Iterable[SubTablePath]: + """Depth-first search tree of BaseTables. + + Args: + root (BaseTable): the root of the tree. + root_accessor (Optional[str]): attribute name for the root table, if any (mostly + useful for debugging). + skip_root (Optional[bool]): if True, the root itself is not visited, only its + children. + predicate (Optional[Callable[[SubTablePath], bool]]): function to filter out + paths. If True, the path is yielded and its subtables are added to the + queue. If False, the path is skipped and its subtables are not traversed. + iter_subtables_fn (Optional[Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]]]): + function to iterate over subtables of a table. If None, the default + BaseTable.iterSubTables() is used. + + Yields: + SubTablePath: tuples of BaseTable.SubTableEntry(name, table, index) namedtuples + for each of the nodes in the tree. The last entry in a path is the current + subtable, whereas preceding ones refer to its parent tables all the way up to + the root. + """ + yield from _traverse_ot_data( + root, + root_accessor, + skip_root, + predicate, + lambda frontier, new: frontier.extendleft(reversed(new)), + iter_subtables_fn, + ) + + +def bfs_base_table( + root: BaseTable, + root_accessor: Optional[str] = None, + skip_root: bool = False, + predicate: Optional[Callable[[SubTablePath], bool]] = None, + iter_subtables_fn: Optional[ + Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]] + ] = None, +) -> Iterable[SubTablePath]: + """Breadth-first search tree of BaseTables. + + Args: + root + the root of the tree. + root_accessor (Optional[str]): attribute name for the root table, if any (mostly + useful for debugging). + skip_root (Optional[bool]): if True, the root itself is not visited, only its + children. + predicate (Optional[Callable[[SubTablePath], bool]]): function to filter out + paths. If True, the path is yielded and its subtables are added to the + queue. If False, the path is skipped and its subtables are not traversed. + iter_subtables_fn (Optional[Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]]]): + function to iterate over subtables of a table. If None, the default + BaseTable.iterSubTables() is used. + + Yields: + SubTablePath: tuples of BaseTable.SubTableEntry(name, table, index) namedtuples + for each of the nodes in the tree. The last entry in a path is the current + subtable, whereas preceding ones refer to its parent tables all the way up to + the root. + """ + yield from _traverse_ot_data( + root, + root_accessor, + skip_root, + predicate, + lambda frontier, new: frontier.extend(new), + iter_subtables_fn, + ) + + +def _traverse_ot_data( + root: BaseTable, + root_accessor: Optional[str], + skip_root: bool, + predicate: Optional[Callable[[SubTablePath], bool]], + add_to_frontier_fn: AddToFrontierFn, + iter_subtables_fn: Optional[ + Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]] + ] = None, +) -> Iterable[SubTablePath]: + # no visited because general otData cannot cycle (forward-offset only) + if root_accessor is None: + root_accessor = type(root).__name__ + + if predicate is None: + + def predicate(path): + return True + + if iter_subtables_fn is None: + + def iter_subtables_fn(table): + return table.iterSubTables() + + frontier: Deque[SubTablePath] = deque() + + root_entry = BaseTable.SubTableEntry(root_accessor, root) + if not skip_root: + frontier.append((root_entry,)) + else: + add_to_frontier_fn( + frontier, + [ + (root_entry, subtable_entry) + for subtable_entry in iter_subtables_fn(root) + ], + ) + + while frontier: + # path is (value, attr_name) tuples. attr_name is attr of parent to get value + path = frontier.popleft() + current = path[-1].value + + if not predicate(path): + continue + + yield SubTablePath(path) + + new_entries = [ + path + (subtable_entry,) for subtable_entry in iter_subtables_fn(current) + ] + + add_to_frontier_fn(frontier, new_entries) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/sbixGlyph.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/sbixGlyph.py new file mode 100644 index 0000000000000000000000000000000000000000..df08eb00eab5f761836a18639e1bcf810704d86e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/sbixGlyph.py @@ -0,0 +1,148 @@ +from fontTools.misc import sstruct +from fontTools.misc.textTools import readHex, safeEval +import struct + +sbixGlyphHeaderFormat = """ + > + originOffsetX: h # The x-value of the point in the glyph relative to its + # lower-left corner which corresponds to the origin of + # the glyph on the screen, that is the point on the + # baseline at the left edge of the glyph. + originOffsetY: h # The y-value of the point in the glyph relative to its + # lower-left corner which corresponds to the origin of + # the glyph on the screen, that is the point on the + # baseline at the left edge of the glyph. + graphicType: 4s # e.g. "png " +""" + +sbixGlyphHeaderFormatSize = sstruct.calcsize(sbixGlyphHeaderFormat) + + +class Glyph(object): + def __init__( + self, + glyphName=None, + referenceGlyphName=None, + originOffsetX=0, + originOffsetY=0, + graphicType=None, + imageData=None, + rawdata=None, + gid=0, + ): + self.gid = gid + self.glyphName = glyphName + self.referenceGlyphName = referenceGlyphName + self.originOffsetX = originOffsetX + self.originOffsetY = originOffsetY + self.rawdata = rawdata + self.graphicType = graphicType + self.imageData = imageData + + # fix self.graphicType if it is null terminated or too short + if self.graphicType is not None: + if self.graphicType[-1] == "\0": + self.graphicType = self.graphicType[:-1] + if len(self.graphicType) > 4: + from fontTools import ttLib + + raise ttLib.TTLibError( + "Glyph.graphicType must not be longer than 4 characters." + ) + elif len(self.graphicType) < 4: + # pad with spaces + self.graphicType += " "[: (4 - len(self.graphicType))] + + def is_reference_type(self): + """Returns True if this glyph is a reference to another glyph's image data.""" + return self.graphicType == "dupe" or self.graphicType == "flip" + + def decompile(self, ttFont): + self.glyphName = ttFont.getGlyphName(self.gid) + if self.rawdata is None: + from fontTools import ttLib + + raise ttLib.TTLibError("No table data to decompile") + if len(self.rawdata) > 0: + if len(self.rawdata) < sbixGlyphHeaderFormatSize: + from fontTools import ttLib + + # print "Glyph %i header too short: Expected %x, got %x." % (self.gid, sbixGlyphHeaderFormatSize, len(self.rawdata)) + raise ttLib.TTLibError("Glyph header too short.") + + sstruct.unpack( + sbixGlyphHeaderFormat, self.rawdata[:sbixGlyphHeaderFormatSize], self + ) + + if self.is_reference_type(): + # this glyph is a reference to another glyph's image data + (gid,) = struct.unpack(">H", self.rawdata[sbixGlyphHeaderFormatSize:]) + self.referenceGlyphName = ttFont.getGlyphName(gid) + else: + self.imageData = self.rawdata[sbixGlyphHeaderFormatSize:] + self.referenceGlyphName = None + # clean up + del self.rawdata + del self.gid + + def compile(self, ttFont): + if self.glyphName is None: + from fontTools import ttLib + + raise ttLib.TTLibError("Can't compile Glyph without glyph name") + # TODO: if ttFont has no maxp, cmap etc., ignore glyph names and compile by index? + # (needed if you just want to compile the sbix table on its own) + self.gid = struct.pack(">H", ttFont.getGlyphID(self.glyphName)) + if self.graphicType is None: + rawdata = b"" + else: + rawdata = sstruct.pack(sbixGlyphHeaderFormat, self) + if self.is_reference_type(): + rawdata += struct.pack(">H", ttFont.getGlyphID(self.referenceGlyphName)) + else: + assert self.imageData is not None + rawdata += self.imageData + self.rawdata = rawdata + + def toXML(self, xmlWriter, ttFont): + if self.graphicType is None: + # TODO: ignore empty glyphs? + # a glyph data entry is required for each glyph, + # but empty ones can be calculated at compile time + xmlWriter.simpletag("glyph", name=self.glyphName) + xmlWriter.newline() + return + xmlWriter.begintag( + "glyph", + graphicType=self.graphicType, + name=self.glyphName, + originOffsetX=self.originOffsetX, + originOffsetY=self.originOffsetY, + ) + xmlWriter.newline() + if self.is_reference_type(): + # this glyph is a reference to another glyph id. + xmlWriter.simpletag("ref", glyphname=self.referenceGlyphName) + else: + xmlWriter.begintag("hexdata") + xmlWriter.newline() + xmlWriter.dumphex(self.imageData) + xmlWriter.endtag("hexdata") + xmlWriter.newline() + xmlWriter.endtag("glyph") + xmlWriter.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name == "ref": + # this glyph i.e. a reference to another glyph's image data. + # in this case imageData contains the glyph id of the reference glyph + # get glyph id from glyphname + glyphname = safeEval("'''" + attrs["glyphname"] + "'''") + self.imageData = struct.pack(">H", ttFont.getGlyphID(glyphname)) + self.referenceGlyphName = glyphname + elif name == "hexdata": + self.imageData = readHex(content) + else: + from fontTools import ttLib + + raise ttLib.TTLibError("can't handle '%s' element" % name) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/sbixStrike.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/sbixStrike.py new file mode 100644 index 0000000000000000000000000000000000000000..4dfba2e76e899a55b9fa88e2aaba0f5b8c5b142d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/sbixStrike.py @@ -0,0 +1,177 @@ +from fontTools.misc import sstruct +from fontTools.misc.textTools import safeEval +from .sbixGlyph import Glyph +import struct + +sbixStrikeHeaderFormat = """ + > + ppem: H # The PPEM for which this strike was designed (e.g., 9, + # 12, 24) + resolution: H # The screen resolution (in dpi) for which this strike + # was designed (e.g., 72) +""" + +sbixGlyphDataOffsetFormat = """ + > + glyphDataOffset: L # Offset from the beginning of the strike data record + # to data for the individual glyph +""" + +sbixStrikeHeaderFormatSize = sstruct.calcsize(sbixStrikeHeaderFormat) +sbixGlyphDataOffsetFormatSize = sstruct.calcsize(sbixGlyphDataOffsetFormat) + + +class Strike(object): + def __init__(self, rawdata=None, ppem=0, resolution=72): + self.data = rawdata + self.ppem = ppem + self.resolution = resolution + self.glyphs = {} + + def decompile(self, ttFont): + if self.data is None: + from fontTools import ttLib + + raise ttLib.TTLibError + if len(self.data) < sbixStrikeHeaderFormatSize: + from fontTools import ttLib + + raise ( + ttLib.TTLibError, + "Strike header too short: Expected %x, got %x.", + ) % (sbixStrikeHeaderFormatSize, len(self.data)) + + # read Strike header from raw data + sstruct.unpack( + sbixStrikeHeaderFormat, self.data[:sbixStrikeHeaderFormatSize], self + ) + + # calculate number of glyphs + (firstGlyphDataOffset,) = struct.unpack( + ">L", + self.data[ + sbixStrikeHeaderFormatSize : sbixStrikeHeaderFormatSize + + sbixGlyphDataOffsetFormatSize + ], + ) + self.numGlyphs = ( + firstGlyphDataOffset - sbixStrikeHeaderFormatSize + ) // sbixGlyphDataOffsetFormatSize - 1 + # ^ -1 because there's one more offset than glyphs + + # build offset list for single glyph data offsets + self.glyphDataOffsets = [] + for i in range( + self.numGlyphs + 1 + ): # + 1 because there's one more offset than glyphs + start = i * sbixGlyphDataOffsetFormatSize + sbixStrikeHeaderFormatSize + (current_offset,) = struct.unpack( + ">L", self.data[start : start + sbixGlyphDataOffsetFormatSize] + ) + self.glyphDataOffsets.append(current_offset) + + # iterate through offset list and slice raw data into glyph data records + for i in range(self.numGlyphs): + current_glyph = Glyph( + rawdata=self.data[ + self.glyphDataOffsets[i] : self.glyphDataOffsets[i + 1] + ], + gid=i, + ) + current_glyph.decompile(ttFont) + self.glyphs[current_glyph.glyphName] = current_glyph + del self.glyphDataOffsets + del self.numGlyphs + del self.data + + def compile(self, ttFont): + self.glyphDataOffsets = b"" + self.bitmapData = b"" + + glyphOrder = ttFont.getGlyphOrder() + + # first glyph starts right after the header + currentGlyphDataOffset = ( + sbixStrikeHeaderFormatSize + + sbixGlyphDataOffsetFormatSize * (len(glyphOrder) + 1) + ) + for glyphName in glyphOrder: + if glyphName in self.glyphs: + # we have glyph data for this glyph + current_glyph = self.glyphs[glyphName] + else: + # must add empty glyph data record for this glyph + current_glyph = Glyph(glyphName=glyphName) + current_glyph.compile(ttFont) + current_glyph.glyphDataOffset = currentGlyphDataOffset + self.bitmapData += current_glyph.rawdata + currentGlyphDataOffset += len(current_glyph.rawdata) + self.glyphDataOffsets += sstruct.pack( + sbixGlyphDataOffsetFormat, current_glyph + ) + + # add last "offset", really the end address of the last glyph data record + dummy = Glyph() + dummy.glyphDataOffset = currentGlyphDataOffset + self.glyphDataOffsets += sstruct.pack(sbixGlyphDataOffsetFormat, dummy) + + # pack header + self.data = sstruct.pack(sbixStrikeHeaderFormat, self) + # add offsets and image data after header + self.data += self.glyphDataOffsets + self.bitmapData + + def toXML(self, xmlWriter, ttFont): + xmlWriter.begintag("strike") + xmlWriter.newline() + xmlWriter.simpletag("ppem", value=self.ppem) + xmlWriter.newline() + xmlWriter.simpletag("resolution", value=self.resolution) + xmlWriter.newline() + glyphOrder = ttFont.getGlyphOrder() + for glyphName in glyphOrder: + if glyphName in self.glyphs: + self.glyphs[glyphName].toXML(xmlWriter, ttFont) + # TODO: what if there are more glyph data records than (glyf table) glyphs? + xmlWriter.endtag("strike") + xmlWriter.newline() + + def fromXML(self, name, attrs, content, ttFont): + if name in ["ppem", "resolution"]: + setattr(self, name, safeEval(attrs["value"])) + elif name == "glyph": + if "graphicType" in attrs: + myFormat = safeEval("'''" + attrs["graphicType"] + "'''") + else: + myFormat = None + if "glyphname" in attrs: + myGlyphName = safeEval("'''" + attrs["glyphname"] + "'''") + elif "name" in attrs: + myGlyphName = safeEval("'''" + attrs["name"] + "'''") + else: + from fontTools import ttLib + + raise ttLib.TTLibError("Glyph must have a glyph name.") + if "originOffsetX" in attrs: + myOffsetX = safeEval(attrs["originOffsetX"]) + else: + myOffsetX = 0 + if "originOffsetY" in attrs: + myOffsetY = safeEval(attrs["originOffsetY"]) + else: + myOffsetY = 0 + current_glyph = Glyph( + glyphName=myGlyphName, + graphicType=myFormat, + originOffsetX=myOffsetX, + originOffsetY=myOffsetY, + ) + for element in content: + if isinstance(element, tuple): + name, attrs, content = element + current_glyph.fromXML(name, attrs, content, ttFont) + current_glyph.compile(ttFont) + self.glyphs[current_glyph.glyphName] = current_glyph + else: + from fontTools import ttLib + + raise ttLib.TTLibError("can't handle '%s' element" % name) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/table_API_readme.txt b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/table_API_readme.txt new file mode 100644 index 0000000000000000000000000000000000000000..7719201a0ea2d4b8f28a3012ad63c1de8bbf10ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/table_API_readme.txt @@ -0,0 +1,91 @@ +This folder is a subpackage of ttLib. Each module here is a +specialized TT/OT table converter: they can convert raw data +to Python objects and vice versa. Usually you don't need to +use the modules directly: they are imported and used +automatically when needed by ttLib. + +If you are writing you own table converter the following is +important. + +The modules here have pretty strange names: this is due to the +fact that we need to map TT table tags (which are case sensitive) +to filenames (which on Mac and Win aren't case sensitive) as well +as to Python identifiers. The latter means it can only contain +[A-Za-z0-9_] and cannot start with a number. + +ttLib provides functions to expand a tag into the format used here: + +>>> from fontTools import ttLib +>>> ttLib.tagToIdentifier("FOO ") +'F_O_O_' +>>> ttLib.tagToIdentifier("cvt ") +'_c_v_t' +>>> ttLib.tagToIdentifier("OS/2") +'O_S_2f_2' +>>> ttLib.tagToIdentifier("glyf") +'_g_l_y_f' +>>> + +And vice versa: + +>>> ttLib.identifierToTag("F_O_O_") +'FOO ' +>>> ttLib.identifierToTag("_c_v_t") +'cvt ' +>>> ttLib.identifierToTag("O_S_2f_2") +'OS/2' +>>> ttLib.identifierToTag("_g_l_y_f") +'glyf' +>>> + +Eg. the 'glyf' table converter lives in a Python file called: + + _g_l_y_f.py + +The converter itself is a class, named "table_" + expandedtag. Eg: + + class table__g_l_y_f: + etc. + +Note that if you _do_ need to use such modules or classes manually, +there are two convenient API functions that let you find them by tag: + +>>> ttLib.getTableModule('glyf') +<module 'ttLib.tables._g_l_y_f'> +>>> ttLib.getTableClass('glyf') +<class ttLib.tables._g_l_y_f.table__g_l_y_f at 645f400> +>>> + +You must subclass from DefaultTable.DefaultTable. It provides some default +behavior, as well as a constructor method (__init__) that you don't need to +override. + +Your converter should minimally provide two methods: + +class table_F_O_O_(DefaultTable.DefaultTable): # converter for table 'FOO ' + + def decompile(self, data, ttFont): + # 'data' is the raw table data. Unpack it into a + # Python data structure. + # 'ttFont' is a ttLib.TTfile instance, enabling you to + # refer to other tables. Do ***not*** keep a reference to + # it: it will cause a circular reference (ttFont saves + # a reference to us), and that means we'll be leaking + # memory. If you need to use it in other methods, just + # pass it around as a method argument. + + def compile(self, ttFont): + # Return the raw data, as converted from the Python + # data structure. + # Again, 'ttFont' is there so you can access other tables. + # Same warning applies. + +If you want to support TTX import/export as well, you need to provide two +additional methods: + + def toXML(self, writer, ttFont): + # XXX + + def fromXML(self, (name, attrs, content), ttFont): + # XXX + diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/ttProgram.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/ttProgram.py new file mode 100644 index 0000000000000000000000000000000000000000..4b3f9dfe0538cd12875fd3a5f209efe5cc31b64f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/ttProgram.py @@ -0,0 +1,595 @@ +"""ttLib.tables.ttProgram.py -- Assembler/disassembler for TrueType bytecode programs.""" + +from __future__ import annotations + +from fontTools.misc.textTools import num2binary, binary2num, readHex, strjoin +import array +from io import StringIO +from typing import List +import re +import logging + +log = logging.getLogger(__name__) + +# fmt: off + +# first, the list of instructions that eat bytes or words from the instruction stream + +streamInstructions = [ +# +# opcode mnemonic argBits descriptive name pops pushes eats from instruction stream pushes +# + (0x40, 'NPUSHB', 0, 'PushNBytes', 0, -1), # n, b1, b2,...bn b1,b2...bn + (0x41, 'NPUSHW', 0, 'PushNWords', 0, -1), # n, w1, w2,...w w1,w2...wn + (0xb0, 'PUSHB', 3, 'PushBytes', 0, -1), # b0, b1,..bn b0, b1, ...,bn + (0xb8, 'PUSHW', 3, 'PushWords', 0, -1), # w0,w1,..wn w0 ,w1, ...wn +] + + +# next, the list of "normal" instructions + +instructions = [ +# +# opcode mnemonic argBits descriptive name pops pushes eats from instruction stream pushes +# + (0x7f, 'AA', 0, 'AdjustAngle', 1, 0), # p - + (0x64, 'ABS', 0, 'Absolute', 1, 1), # n |n| + (0x60, 'ADD', 0, 'Add', 2, 1), # n2, n1 (n1 + n2) + (0x27, 'ALIGNPTS', 0, 'AlignPts', 2, 0), # p2, p1 - + (0x3c, 'ALIGNRP', 0, 'AlignRelativePt', -1, 0), # p1, p2, ... , ploopvalue - + (0x5a, 'AND', 0, 'LogicalAnd', 2, 1), # e2, e1 b + (0x2b, 'CALL', 0, 'CallFunction', 1, 0), # f - + (0x67, 'CEILING', 0, 'Ceiling', 1, 1), # n ceil(n) + (0x25, 'CINDEX', 0, 'CopyXToTopStack', 1, 1), # k ek + (0x22, 'CLEAR', 0, 'ClearStack', -1, 0), # all items on the stack - + (0x4f, 'DEBUG', 0, 'DebugCall', 1, 0), # n - + (0x73, 'DELTAC1', 0, 'DeltaExceptionC1', -1, 0), # argn, cn, argn-1,cn-1, , arg1, c1 - + (0x74, 'DELTAC2', 0, 'DeltaExceptionC2', -1, 0), # argn, cn, argn-1,cn-1, , arg1, c1 - + (0x75, 'DELTAC3', 0, 'DeltaExceptionC3', -1, 0), # argn, cn, argn-1,cn-1, , arg1, c1 - + (0x5d, 'DELTAP1', 0, 'DeltaExceptionP1', -1, 0), # argn, pn, argn-1, pn-1, , arg1, p1 - + (0x71, 'DELTAP2', 0, 'DeltaExceptionP2', -1, 0), # argn, pn, argn-1, pn-1, , arg1, p1 - + (0x72, 'DELTAP3', 0, 'DeltaExceptionP3', -1, 0), # argn, pn, argn-1, pn-1, , arg1, p1 - + (0x24, 'DEPTH', 0, 'GetDepthStack', 0, 1), # - n + (0x62, 'DIV', 0, 'Divide', 2, 1), # n2, n1 (n1 * 64)/ n2 + (0x20, 'DUP', 0, 'DuplicateTopStack', 1, 2), # e e, e + (0x59, 'EIF', 0, 'EndIf', 0, 0), # - - + (0x1b, 'ELSE', 0, 'Else', 0, 0), # - - + (0x2d, 'ENDF', 0, 'EndFunctionDefinition', 0, 0), # - - + (0x54, 'EQ', 0, 'Equal', 2, 1), # e2, e1 b + (0x57, 'EVEN', 0, 'Even', 1, 1), # e b + (0x2c, 'FDEF', 0, 'FunctionDefinition', 1, 0), # f - + (0x4e, 'FLIPOFF', 0, 'SetAutoFlipOff', 0, 0), # - - + (0x4d, 'FLIPON', 0, 'SetAutoFlipOn', 0, 0), # - - + (0x80, 'FLIPPT', 0, 'FlipPoint', -1, 0), # p1, p2, ..., ploopvalue - + (0x82, 'FLIPRGOFF', 0, 'FlipRangeOff', 2, 0), # h, l - + (0x81, 'FLIPRGON', 0, 'FlipRangeOn', 2, 0), # h, l - + (0x66, 'FLOOR', 0, 'Floor', 1, 1), # n floor(n) + (0x46, 'GC', 1, 'GetCoordOnPVector', 1, 1), # p c + (0x88, 'GETINFO', 0, 'GetInfo', 1, 1), # selector result + (0x91, 'GETVARIATION', 0, 'GetVariation', 0, -1), # - a1,..,an + (0x0d, 'GFV', 0, 'GetFVector', 0, 2), # - px, py + (0x0c, 'GPV', 0, 'GetPVector', 0, 2), # - px, py + (0x52, 'GT', 0, 'GreaterThan', 2, 1), # e2, e1 b + (0x53, 'GTEQ', 0, 'GreaterThanOrEqual', 2, 1), # e2, e1 b + (0x89, 'IDEF', 0, 'InstructionDefinition', 1, 0), # f - + (0x58, 'IF', 0, 'If', 1, 0), # e - + (0x8e, 'INSTCTRL', 0, 'SetInstrExecControl', 2, 0), # s, v - + (0x39, 'IP', 0, 'InterpolatePts', -1, 0), # p1, p2, ... , ploopvalue - + (0x0f, 'ISECT', 0, 'MovePtToIntersect', 5, 0), # a1, a0, b1, b0, p - + (0x30, 'IUP', 1, 'InterpolateUntPts', 0, 0), # - - + (0x1c, 'JMPR', 0, 'Jump', 1, 0), # offset - + (0x79, 'JROF', 0, 'JumpRelativeOnFalse', 2, 0), # e, offset - + (0x78, 'JROT', 0, 'JumpRelativeOnTrue', 2, 0), # e, offset - + (0x2a, 'LOOPCALL', 0, 'LoopAndCallFunction', 2, 0), # f, count - + (0x50, 'LT', 0, 'LessThan', 2, 1), # e2, e1 b + (0x51, 'LTEQ', 0, 'LessThenOrEqual', 2, 1), # e2, e1 b + (0x8b, 'MAX', 0, 'Maximum', 2, 1), # e2, e1 max(e1, e2) + (0x49, 'MD', 1, 'MeasureDistance', 2, 1), # p2,p1 d + (0x2e, 'MDAP', 1, 'MoveDirectAbsPt', 1, 0), # p - + (0xc0, 'MDRP', 5, 'MoveDirectRelPt', 1, 0), # p - + (0x3e, 'MIAP', 1, 'MoveIndirectAbsPt', 2, 0), # n, p - + (0x8c, 'MIN', 0, 'Minimum', 2, 1), # e2, e1 min(e1, e2) + (0x26, 'MINDEX', 0, 'MoveXToTopStack', 1, 1), # k ek + (0xe0, 'MIRP', 5, 'MoveIndirectRelPt', 2, 0), # n, p - + (0x4b, 'MPPEM', 0, 'MeasurePixelPerEm', 0, 1), # - ppem + (0x4c, 'MPS', 0, 'MeasurePointSize', 0, 1), # - pointSize + (0x3a, 'MSIRP', 1, 'MoveStackIndirRelPt', 2, 0), # d, p - + (0x63, 'MUL', 0, 'Multiply', 2, 1), # n2, n1 (n1 * n2)/64 + (0x65, 'NEG', 0, 'Negate', 1, 1), # n -n + (0x55, 'NEQ', 0, 'NotEqual', 2, 1), # e2, e1 b + (0x5c, 'NOT', 0, 'LogicalNot', 1, 1), # e ( not e ) + (0x6c, 'NROUND', 2, 'NoRound', 1, 1), # n1 n2 + (0x56, 'ODD', 0, 'Odd', 1, 1), # e b + (0x5b, 'OR', 0, 'LogicalOr', 2, 1), # e2, e1 b + (0x21, 'POP', 0, 'PopTopStack', 1, 0), # e - + (0x45, 'RCVT', 0, 'ReadCVT', 1, 1), # location value + (0x7d, 'RDTG', 0, 'RoundDownToGrid', 0, 0), # - - + (0x7a, 'ROFF', 0, 'RoundOff', 0, 0), # - - + (0x8a, 'ROLL', 0, 'RollTopThreeStack', 3, 3), # a,b,c b,a,c + (0x68, 'ROUND', 2, 'Round', 1, 1), # n1 n2 + (0x43, 'RS', 0, 'ReadStore', 1, 1), # n v + (0x3d, 'RTDG', 0, 'RoundToDoubleGrid', 0, 0), # - - + (0x18, 'RTG', 0, 'RoundToGrid', 0, 0), # - - + (0x19, 'RTHG', 0, 'RoundToHalfGrid', 0, 0), # - - + (0x7c, 'RUTG', 0, 'RoundUpToGrid', 0, 0), # - - + (0x77, 'S45ROUND', 0, 'SuperRound45Degrees', 1, 0), # n - + (0x7e, 'SANGW', 0, 'SetAngleWeight', 1, 0), # weight - + (0x85, 'SCANCTRL', 0, 'ScanConversionControl', 1, 0), # n - + (0x8d, 'SCANTYPE', 0, 'ScanType', 1, 0), # n - + (0x48, 'SCFS', 0, 'SetCoordFromStackFP', 2, 0), # c, p - + (0x1d, 'SCVTCI', 0, 'SetCVTCutIn', 1, 0), # n - + (0x5e, 'SDB', 0, 'SetDeltaBaseInGState', 1, 0), # n - + (0x86, 'SDPVTL', 1, 'SetDualPVectorToLine', 2, 0), # p2, p1 - + (0x5f, 'SDS', 0, 'SetDeltaShiftInGState', 1, 0), # n - + (0x0b, 'SFVFS', 0, 'SetFVectorFromStack', 2, 0), # y, x - + (0x04, 'SFVTCA', 1, 'SetFVectorToAxis', 0, 0), # - - + (0x08, 'SFVTL', 1, 'SetFVectorToLine', 2, 0), # p2, p1 - + (0x0e, 'SFVTPV', 0, 'SetFVectorToPVector', 0, 0), # - - + (0x34, 'SHC', 1, 'ShiftContourByLastPt', 1, 0), # c - + (0x32, 'SHP', 1, 'ShiftPointByLastPoint', -1, 0), # p1, p2, ..., ploopvalue - + (0x38, 'SHPIX', 0, 'ShiftZoneByPixel', -1, 0), # d, p1, p2, ..., ploopvalue - + (0x36, 'SHZ', 1, 'ShiftZoneByLastPoint', 1, 0), # e - + (0x17, 'SLOOP', 0, 'SetLoopVariable', 1, 0), # n - + (0x1a, 'SMD', 0, 'SetMinimumDistance', 1, 0), # distance - + (0x0a, 'SPVFS', 0, 'SetPVectorFromStack', 2, 0), # y, x - + (0x02, 'SPVTCA', 1, 'SetPVectorToAxis', 0, 0), # - - + (0x06, 'SPVTL', 1, 'SetPVectorToLine', 2, 0), # p2, p1 - + (0x76, 'SROUND', 0, 'SuperRound', 1, 0), # n - + (0x10, 'SRP0', 0, 'SetRefPoint0', 1, 0), # p - + (0x11, 'SRP1', 0, 'SetRefPoint1', 1, 0), # p - + (0x12, 'SRP2', 0, 'SetRefPoint2', 1, 0), # p - + (0x1f, 'SSW', 0, 'SetSingleWidth', 1, 0), # n - + (0x1e, 'SSWCI', 0, 'SetSingleWidthCutIn', 1, 0), # n - + (0x61, 'SUB', 0, 'Subtract', 2, 1), # n2, n1 (n1 - n2) + (0x00, 'SVTCA', 1, 'SetFPVectorToAxis', 0, 0), # - - + (0x23, 'SWAP', 0, 'SwapTopStack', 2, 2), # e2, e1 e1, e2 + (0x13, 'SZP0', 0, 'SetZonePointer0', 1, 0), # n - + (0x14, 'SZP1', 0, 'SetZonePointer1', 1, 0), # n - + (0x15, 'SZP2', 0, 'SetZonePointer2', 1, 0), # n - + (0x16, 'SZPS', 0, 'SetZonePointerS', 1, 0), # n - + (0x29, 'UTP', 0, 'UnTouchPt', 1, 0), # p - + (0x70, 'WCVTF', 0, 'WriteCVTInFUnits', 2, 0), # n, l - + (0x44, 'WCVTP', 0, 'WriteCVTInPixels', 2, 0), # v, l - + (0x42, 'WS', 0, 'WriteStore', 2, 0), # v, l - +] + +# fmt: on + + +def bitRepr(value: int, bits: int) -> str: + s = "" + for i in range(bits): + s = "01"[value & 0x1] + s + value = value >> 1 + return s + + +_mnemonicPat = re.compile(r"[A-Z][A-Z0-9]*$") + + +def _makeDict( + instructionList: list[tuple[int, str, int, str, int, int]], +) -> tuple[dict, dict]: + opcodeDict = {} + mnemonicDict = {} + for op, mnemonic, argBits, name, pops, pushes in instructionList: + assert _mnemonicPat.match(mnemonic) + mnemonicDict[mnemonic] = op, argBits, name + if argBits: + argoffset = op + for i in range(1 << argBits): + opcodeDict[op + i] = mnemonic, argBits, argoffset, name + else: + opcodeDict[op] = mnemonic, 0, 0, name + return opcodeDict, mnemonicDict + + +streamOpcodeDict, streamMnemonicDict = _makeDict(streamInstructions) +opcodeDict, mnemonicDict = _makeDict(instructions) + + +class tt_instructions_error(Exception): + def __init__(self, error: str) -> None: + self.error = error + + def __str__(self) -> str: + return "TT instructions error: %s" % repr(self.error) + + +_comment = r"/\*.*?\*/" +_instruction = r"([A-Z][A-Z0-9]*)\s*\[(.*?)\]" +_number = r"-?[0-9]+" +_token = "(%s)|(%s)|(%s)" % (_instruction, _number, _comment) + +_tokenRE = re.compile(_token) +_whiteRE = re.compile(r"\s*") + +_pushCountPat = re.compile(r"[A-Z][A-Z0-9]*\s*\[.*?\]\s*/\* ([0-9]+).*?\*/") + +_indentRE = re.compile(r"^FDEF|IDEF|IF|ELSE\[ \]\t.+") +_unindentRE = re.compile(r"^ELSE|ENDF|EIF\[ \]\t.+") + + +def _skipWhite(data: str, pos: int) -> int: + m = _whiteRE.match(data, pos) + newPos = m.regs[0][1] + assert newPos >= pos + return newPos + + +class Program: + def __init__(self) -> None: + pass + + def fromBytecode(self, bytecode: bytes) -> None: + self.bytecode = array.array("B", bytecode) + if hasattr(self, "assembly"): + del self.assembly + + def fromAssembly(self, assembly: list[str] | str) -> None: + if isinstance(assembly, list): + self.assembly = assembly + elif isinstance(assembly, str): + self.assembly = assembly.splitlines() + else: + raise TypeError(f"expected str or List[str], got {type(assembly).__name__}") + if hasattr(self, "bytecode"): + del self.bytecode + + def getBytecode(self) -> bytes: + if not hasattr(self, "bytecode"): + self._assemble() + return self.bytecode.tobytes() + + def getAssembly(self, preserve=True) -> List[str]: + if not hasattr(self, "assembly"): + self._disassemble(preserve=preserve) + return self.assembly + + def toXML(self, writer, ttFont) -> None: + if ( + not hasattr(ttFont, "disassembleInstructions") + or ttFont.disassembleInstructions + ): + try: + assembly = self.getAssembly() + except: + import traceback + + tmp = StringIO() + traceback.print_exc(file=tmp) + msg = "An exception occurred during the decompilation of glyph program:\n\n" + msg += tmp.getvalue() + log.error(msg) + writer.begintag("bytecode") + writer.newline() + writer.comment(msg.strip()) + writer.newline() + writer.dumphex(self.getBytecode()) + writer.endtag("bytecode") + writer.newline() + else: + if not assembly: + return + writer.begintag("assembly") + writer.newline() + i = 0 + indent = 0 + nInstr = len(assembly) + while i < nInstr: + instr = assembly[i] + if _unindentRE.match(instr): + indent -= 1 + writer.write(writer.indentwhite * indent) + writer.write(instr) + writer.newline() + m = _pushCountPat.match(instr) + i = i + 1 + if m: + nValues = int(m.group(1)) + line: List[str] = [] + j = 0 + for j in range(nValues): + if j and not (j % 25): + writer.write(writer.indentwhite * indent) + writer.write(" ".join(line)) + writer.newline() + line = [] + line.append(assembly[i + j]) + writer.write(writer.indentwhite * indent) + writer.write(" ".join(line)) + writer.newline() + i = i + j + 1 + if _indentRE.match(instr): + indent += 1 + writer.endtag("assembly") + writer.newline() + else: + bytecode = self.getBytecode() + if not bytecode: + return + writer.begintag("bytecode") + writer.newline() + writer.dumphex(bytecode) + writer.endtag("bytecode") + writer.newline() + + def fromXML(self, name, attrs, content, ttFont) -> None: + if name == "assembly": + self.fromAssembly(strjoin(content)) + self._assemble() + del self.assembly + else: + assert name == "bytecode" + self.fromBytecode(readHex(content)) + + def _assemble(self) -> None: + assembly = " ".join(getattr(self, "assembly", [])) + bytecode: List[int] = [] + push = bytecode.append + lenAssembly = len(assembly) + pos = _skipWhite(assembly, 0) + while pos < lenAssembly: + m = _tokenRE.match(assembly, pos) + if m is None: + raise tt_instructions_error( + "Syntax error in TT program (%s)" % assembly[pos - 5 : pos + 15] + ) + dummy, mnemonic, arg, number, comment = m.groups() + pos = m.regs[0][1] + if comment: + pos = _skipWhite(assembly, pos) + continue + + arg = arg.strip() + if mnemonic.startswith("INSTR"): + # Unknown instruction + op = int(mnemonic[5:]) + push(op) + elif mnemonic not in ("PUSH", "NPUSHB", "NPUSHW", "PUSHB", "PUSHW"): + op, argBits, name = mnemonicDict[mnemonic] + if len(arg) != argBits: + raise tt_instructions_error( + "Incorrect number of argument bits (%s[%s])" % (mnemonic, arg) + ) + if arg: + arg = binary2num(arg) + push(op + arg) + else: + push(op) + else: + args = [] + pos = _skipWhite(assembly, pos) + while pos < lenAssembly: + m = _tokenRE.match(assembly, pos) + if m is None: + raise tt_instructions_error( + "Syntax error in TT program (%s)" % assembly[pos : pos + 15] + ) + dummy, _mnemonic, arg, number, comment = m.groups() + if number is None and comment is None: + break + pos = m.regs[0][1] + pos = _skipWhite(assembly, pos) + if comment is not None: + continue + args.append(int(number)) + nArgs = len(args) + if mnemonic == "PUSH": + # Automatically choose the most compact representation + nWords = 0 + while nArgs: + while ( + nWords < nArgs + and nWords < 255 + and not (0 <= args[nWords] <= 255) + ): + nWords += 1 + nBytes = 0 + while ( + nWords + nBytes < nArgs + and nBytes < 255 + and 0 <= args[nWords + nBytes] <= 255 + ): + nBytes += 1 + if ( + nBytes < 2 + and nWords + nBytes < 255 + and nWords + nBytes != nArgs + ): + # Will write bytes as words + nWords += nBytes + continue + + # Write words + if nWords: + if nWords <= 8: + op, argBits, name = streamMnemonicDict["PUSHW"] + op = op + nWords - 1 + push(op) + else: + op, argBits, name = streamMnemonicDict["NPUSHW"] + push(op) + push(nWords) + for value in args[:nWords]: + assert -32768 <= value < 32768, ( + "PUSH value out of range %d" % value + ) + push((value >> 8) & 0xFF) + push(value & 0xFF) + + # Write bytes + if nBytes: + pass + if nBytes <= 8: + op, argBits, name = streamMnemonicDict["PUSHB"] + op = op + nBytes - 1 + push(op) + else: + op, argBits, name = streamMnemonicDict["NPUSHB"] + push(op) + push(nBytes) + for value in args[nWords : nWords + nBytes]: + push(value) + + nTotal = nWords + nBytes + args = args[nTotal:] + nArgs -= nTotal + nWords = 0 + else: + # Write exactly what we've been asked to + words = mnemonic[-1] == "W" + op, argBits, name = streamMnemonicDict[mnemonic] + if mnemonic[0] != "N": + assert nArgs <= 8, nArgs + op = op + nArgs - 1 + push(op) + else: + assert nArgs < 256 + push(op) + push(nArgs) + if words: + for value in args: + assert -32768 <= value < 32768, ( + "PUSHW value out of range %d" % value + ) + push((value >> 8) & 0xFF) + push(value & 0xFF) + else: + for value in args: + assert 0 <= value < 256, ( + "PUSHB value out of range %d" % value + ) + push(value) + + pos = _skipWhite(assembly, pos) + + if bytecode: + assert max(bytecode) < 256 and min(bytecode) >= 0 + self.bytecode = array.array("B", bytecode) + + def _disassemble(self, preserve=False) -> None: + assembly = [] + i = 0 + bytecode = getattr(self, "bytecode", []) + numBytecode = len(bytecode) + while i < numBytecode: + op = bytecode[i] + try: + mnemonic, argBits, argoffset, name = opcodeDict[op] + except KeyError: + if op in streamOpcodeDict: + values = [] + + # Merge consecutive PUSH operations + while bytecode[i] in streamOpcodeDict: + op = bytecode[i] + mnemonic, argBits, argoffset, name = streamOpcodeDict[op] + words = mnemonic[-1] == "W" + if argBits: + nValues = op - argoffset + 1 + else: + i = i + 1 + nValues = bytecode[i] + i = i + 1 + assert nValues > 0 + if not words: + for j in range(nValues): + value = bytecode[i] + values.append(repr(value)) + i = i + 1 + else: + for j in range(nValues): + # cast to signed int16 + value = (bytecode[i] << 8) | bytecode[i + 1] + if value >= 0x8000: + value = value - 0x10000 + values.append(repr(value)) + i = i + 2 + if preserve: + break + + if not preserve: + mnemonic = "PUSH" + nValues = len(values) + if nValues == 1: + assembly.append("%s[ ] /* 1 value pushed */" % mnemonic) + else: + assembly.append( + "%s[ ] /* %s values pushed */" % (mnemonic, nValues) + ) + assembly.extend(values) + else: + assembly.append("INSTR%d[ ]" % op) + i = i + 1 + else: + if argBits: + assembly.append( + mnemonic + + "[%s] /* %s */" % (num2binary(op - argoffset, argBits), name) + ) + else: + assembly.append(mnemonic + "[ ] /* %s */" % name) + i = i + 1 + self.assembly = assembly + + def __bool__(self) -> bool: + """ + >>> p = Program() + >>> bool(p) + False + >>> bc = array.array("B", [0]) + >>> p.fromBytecode(bc) + >>> bool(p) + True + >>> p.bytecode.pop() + 0 + >>> bool(p) + False + + >>> p = Program() + >>> asm = ['SVTCA[0]'] + >>> p.fromAssembly(asm) + >>> bool(p) + True + >>> p.assembly.pop() + 'SVTCA[0]' + >>> bool(p) + False + """ + return (hasattr(self, "assembly") and len(self.assembly) > 0) or ( + hasattr(self, "bytecode") and len(self.bytecode) > 0 + ) + + __nonzero__ = __bool__ + + def __eq__(self, other) -> bool: + if type(self) != type(other): + return NotImplemented + return self.__dict__ == other.__dict__ + + def __ne__(self, other) -> bool: + result = self.__eq__(other) + return result if result is NotImplemented else not result + + +def _test(): + """ + >>> _test() + True + """ + + bc = b"""@;:9876543210/.-,+*)(\'&%$#"! \037\036\035\034\033\032\031\030\027\026\025\024\023\022\021\020\017\016\015\014\013\012\011\010\007\006\005\004\003\002\001\000,\001\260\030CXEj\260\031C`\260F#D#\020 \260FN\360M/\260\000\022\033!#\0213Y-,\001\260\030CX\260\005+\260\000\023K\260\024PX\261\000@8Y\260\006+\033!#\0213Y-,\001\260\030CXN\260\003%\020\362!\260\000\022M\033 E\260\004%\260\004%#Jad\260(RX!#\020\326\033\260\003%\020\362!\260\000\022YY-,\260\032CX!!\033\260\002%\260\002%I\260\003%\260\003%Ja d\260\020PX!!!\033\260\003%\260\003%I\260\000PX\260\000PX\270\377\3428!\033\260\0208!Y\033\260\000RX\260\0368!\033\270\377\3608!YYYY-,\001\260\030CX\260\005+\260\000\023K\260\024PX\271\000\000\377\3008Y\260\006+\033!#\0213Y-,N\001\212\020\261F\031CD\260\000\024\261\000F\342\260\000\025\271\000\000\377\3608\000\260\000<\260(+\260\002%\020\260\000<-,\001\030\260\000/\260\001\024\362\260\001\023\260\001\025M\260\000\022-,\001\260\030CX\260\005+\260\000\023\271\000\000\377\3408\260\006+\033!#\0213Y-,\001\260\030CXEdj#Edi\260\031Cd``\260F#D#\020 \260F\360/\260\000\022\033!! \212 \212RX\0213\033!!YY-,\001\261\013\012C#Ce\012-,\000\261\012\013C#C\013-,\000\260F#p\261\001F>\001\260F#p\261\002FE:\261\002\000\010\015-,\260\022+\260\002%E\260\002%Ej\260@\213`\260\002%#D!!!-,\260\023+\260\002%E\260\002%Ej\270\377\300\214`\260\002%#D!!!-,\260\000\260\022+!!!-,\260\000\260\023+!!!-,\001\260\006C\260\007Ce\012-, i\260@a\260\000\213 \261,\300\212\214\270\020\000b`+\014d#da\\X\260\003aY-,\261\000\003%EhT\260\034KPZX\260\003%E\260\003%E`h \260\004%#D\260\004%#D\033\260\003% Eh \212#D\260\003%Eh`\260\003%#DY-,\260\003% Eh \212#D\260\003%Edhe`\260\004%\260\001`#D-,\260\011CX\207!\300\033\260\022CX\207E\260\021+\260G#D\260Gz\344\033\003\212E\030i \260G#D\212\212\207 \260\240QX\260\021+\260G#D\260Gz\344\033!\260Gz\344YYY\030-, \212E#Eh`D-,EjB-,\001\030/-,\001\260\030CX\260\004%\260\004%Id#Edi\260@\213a \260\200bj\260\002%\260\002%a\214\260\031C`\260F#D!\212\020\260F\366!\033!!!!Y-,\001\260\030CX\260\002%E\260\002%Ed`j\260\003%Eja \260\004%Ej \212\213e\260\004%#D\214\260\003%#D!!\033 EjD EjDY-,\001 E\260\000U\260\030CZXEh#Ei\260@\213a \260\200bj \212#a \260\003%\213e\260\004%#D\214\260\003%#D!!\033!!\260\031+Y-,\001\212\212Ed#EdadB-,\260\004%\260\004%\260\031+\260\030CX\260\004%\260\004%\260\003%\260\033+\001\260\002%C\260@T\260\002%C\260\000TZX\260\003% E\260@aDY\260\002%C\260\000T\260\002%C\260@TZX\260\004% E\260@`DYY!!!!-,\001KRXC\260\002%E#aD\033!!Y-,\001KRXC\260\002%E#`D\033!!Y-,KRXED\033!!Y-,\001 \260\003%#I\260@`\260 c \260\000RX#\260\002%8#\260\002%e8\000\212c8\033!!!!!Y\001-,KPXED\033!!Y-,\001\260\005%\020# \212\365\000\260\001`#\355\354-,\001\260\005%\020# \212\365\000\260\001a#\355\354-,\001\260\006%\020\365\000\355\354-,F#F`\212\212F# F\212`\212a\270\377\200b# \020#\212\261KK\212pE` \260\000PX\260\001a\270\377\272\213\033\260F\214Y\260\020`h\001:-, E\260\003%FRX\260\002%F ha\260\003%\260\003%?#!8\033!\021Y-, E\260\003%FPX\260\002%F ha\260\003%\260\003%?#!8\033!\021Y-,\000\260\007C\260\006C\013-,\212\020\354-,\260\014CX!\033 F\260\000RX\270\377\3608\033\260\0208YY-, \260\000UX\270\020\000c\260\003%Ed\260\003%Eda\260\000SX\260\002\033\260@a\260\003Y%EiSXED\033!!Y\033!\260\002%E\260\002%Ead\260(QXED\033!!YY-,!!\014d#d\213\270@\000b-,!\260\200QX\014d#d\213\270 \000b\033\262\000@/+Y\260\002`-,!\260\300QX\014d#d\213\270\025Ub\033\262\000\200/+Y\260\002`-,\014d#d\213\270@\000b`#!-,KSX\260\004%\260\004%Id#Edi\260@\213a \260\200bj\260\002%\260\002%a\214\260F#D!\212\020\260F\366!\033!\212\021#\022 9/Y-,\260\002%\260\002%Id\260\300TX\270\377\3708\260\0108\033!!Y-,\260\023CX\003\033\002Y-,\260\023CX\002\033\003Y-,\260\012+#\020 <\260\027+-,\260\002%\270\377\3608\260(+\212\020# \320#\260\020+\260\005CX\300\033<Y \020\021\260\000\022\001-,KS#KQZX8\033!!Y-,\001\260\002%\020\320#\311\001\260\001\023\260\000\024\020\260\001<\260\001\026-,\001\260\000\023\260\001\260\003%I\260\003\0278\260\001\023-,KS#KQZX E\212`D\033!!Y-, 9/-""" + + p = Program() + p.fromBytecode(bc) + asm = p.getAssembly(preserve=True) + p.fromAssembly(asm) + print(bc == p.getBytecode()) + + +if __name__ == "__main__": + import sys + import doctest + + sys.exit(doctest.testmod().failed) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/ttCollection.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/ttCollection.py new file mode 100644 index 0000000000000000000000000000000000000000..ede14b6eaaebf2ff22bceb248004b6d4975b2cfd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/ttCollection.py @@ -0,0 +1,198 @@ +from fontTools.ttLib.ttFont import TTFont +from io import BytesIO +import struct +import logging +from contextlib import contextmanager +from fontTools.ttLib.sfnt import TTC_V1, TTC_V2, readTTCHeader, writeTTCHeader +from fontTools.ttLib.tables.D_S_I_G_ import table_D_S_I_G_ +from fontTools.misc.timeTools import timestampNow + +log = logging.getLogger(__name__) + + +@contextmanager +def _sharedModifiedTimestamp(fonts): + """Pin a single ``head.modified`` timestamp across an iterable of TTFonts. + + When several fonts are saved together with ``recalcTimestamp=True``, each + one restamps its own ``head`` table via ``timestampNow()``, whose + granularity is one second. If the wall clock ticks between two fonts' + ``head.compile()`` calls they get different ``modified`` values, which + defeats byte-identical table sharing (``shareTables=True``) and makes the + saved size non-deterministic. + + This reads ``timestampNow()`` once (so ``SOURCE_DATE_EPOCH`` is still + honored) and applies it to every font that would have recalculated its own + timestamp, suppressing the per-font restamp for the duration. Each font's + ``recalcTimestamp`` flag is restored on exit, even if the body raises; the + pinned ``modified`` value is left in place, matching a normal recalc save. + Fonts with ``recalcTimestamp`` falsy, or without a ``head`` table, are left + untouched (their ``head`` is not even loaded). + + See https://github.com/fonttools/fonttools/issues/4110. + """ + now = timestampNow() + restore = [] + try: + for font in fonts: + if font.recalcTimestamp and "head" in font: + # record the original flag *before* mutating, so the finally + # block restores it even if loading 'head' below raises + restore.append((font, font.recalcTimestamp)) + font["head"].modified = now + font.recalcTimestamp = False + yield now + finally: + for font, recalcTimestamp in restore: + font.recalcTimestamp = recalcTimestamp + + +class TTCollection(object): + """Object representing a TrueType Collection / OpenType Collection. + The main API is self.fonts being a list of TTFont instances. + + If shareTables is True, then different fonts in the collection + might point to the same table object if the data for the table was + the same in the font file. Note, however, that this might result + in suprises and incorrect behavior if the different fonts involved + have different GlyphOrder. Use only if you know what you are doing. + """ + + def __init__(self, file=None, shareTables=False, **kwargs): + fonts = self.fonts = [] + if file is None: + return + + assert "fontNumber" not in kwargs, kwargs + + closeStream = False + if not hasattr(file, "read"): + file = open(file, "rb") + closeStream = True + + tableCache = {} if shareTables else None + + header = readTTCHeader(file) + for i in range(header.numFonts): + font = TTFont(file, fontNumber=i, _tableCache=tableCache, **kwargs) + fonts.append(font) + + if header.Version == TTC_V2: + self.dsig: table_D_S_I_G_ | None = None + if header.ulDsigOffset != 0: + self.dsig = table_D_S_I_G_("DSIG") + file.seek(header.ulDsigOffset, 0) + self.dsig.data = file.read(header.ulDsigLength) + + # don't close file if lazy=True, as the TTFont hold a reference to the original + # file; the file will be closed once the TTFonts are closed in the + # TTCollection.close(). We still want to close the file if lazy is None or + # False, because in that case the TTFont no longer need the original file + # and we want to avoid 'ResourceWarning: unclosed file'. + if not kwargs.get("lazy") and closeStream: + file.close() + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self.close() + + def close(self): + for font in self.fonts: + font.close() + + def save(self, file, shareTables=True): + """Save the font to disk. Similarly to the constructor, + the 'file' argument can be either a pathname or a writable + file object. + """ + if not hasattr(file, "write"): + final = None + file = open(file, "wb") + else: + # assume "file" is a writable file object + # write to a temporary stream to allow saving to unseekable streams + final = file + file = BytesIO() + + tableCache = {} if shareTables else None + + # A V2 TTC will be saved if self.dsig is present, even if it is None + version = TTC_V2 if hasattr(self, "dsig") else TTC_V1 + + # Pin one 'modified' timestamp so the fonts' 'head' tables can be shared. + with _sharedModifiedTimestamp(self.fonts): + offsets_offset = writeTTCHeader(file, len(self.fonts), version=version) + offsets = [] + for font in self.fonts: + offsets.append(file.tell()) + font._save(file, tableCache=tableCache) + file.seek(0, 2) + + file.seek(offsets_offset) + file.write(struct.pack(">%dL" % len(self.fonts), *offsets)) + + if version == TTC_V2 and self.dsig is not None: + # Compile the DSIG if necessary + if hasattr(self.dsig, "data"): + data = self.dsig.data + else: + data = self.dsig.compile(None) + # Write the DSIG tag, length, and offset + # We are at the offset where the DSIG header starts + dsig_header_fields_offset = file.tell() + # The DSIG data will be written to the end of the file, go there + file.seek(0, 2) + dsig_offset = file.tell() + # Write the actual data + file.write(data) + # Go back to the DSIG header + file.seek(dsig_header_fields_offset) + # Write the tag + file.write(b"DSIG") + # Write the length and offset + file.write(struct.pack(">2L", len(data), dsig_offset)) + + if final: + final.write(file.getvalue()) + file.close() + + def saveXML(self, fileOrPath, newlinestr="\n", writeVersion=True, **kwargs): + from fontTools.misc import xmlWriter + + writer = xmlWriter.XMLWriter(fileOrPath, newlinestr=newlinestr) + + if writeVersion: + from fontTools import version + + version = ".".join(version.split(".")[:2]) + writer.begintag("ttCollection", ttLibVersion=version) + else: + writer.begintag("ttCollection") + writer.newline() + writer.newline() + + for font in self.fonts: + font._saveXML(writer, writeVersion=False, **kwargs) + writer.newline() + + writer.endtag("ttCollection") + writer.newline() + + writer.close() + + def __getitem__(self, item): + return self.fonts[item] + + def __setitem__(self, item, value): + self.fonts[item] = value + + def __delitem__(self, item): + return self.fonts[item] + + def __len__(self): + return len(self.fonts) + + def __iter__(self): + return iter(self.fonts) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/ttFont.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/ttFont.py new file mode 100644 index 0000000000000000000000000000000000000000..9576edf838214a7b9224856e94428c514e7f3cd8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/ttFont.py @@ -0,0 +1,1710 @@ +from __future__ import annotations + +import logging +import os +import traceback +from io import BytesIO, StringIO, UnsupportedOperation +from typing import TYPE_CHECKING, TypedDict, TypeVar, overload + +from fontTools.config import Config +from fontTools.misc import xmlWriter +from fontTools.misc.configTools import AbstractConfig +from fontTools.misc.loggingTools import deprecateArgument +from fontTools.misc.textTools import Tag, byteord, tostr +from fontTools.ttLib import TTLibError +from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter +from fontTools.ttLib.ttGlyphSet import ( + _TTGlyph, # noqa: F401 + _TTGlyphSet, + _TTGlyphSetCFF, + _TTGlyphSetGlyf, + _TTGlyphSetVARC, +) + +if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping + from types import ModuleType, TracebackType + from typing import Any, BinaryIO, Literal, Sequence, TextIO + + from typing_extensions import Self, Unpack + + from fontTools.ttLib.tables import ( + B_A_S_E_, + C_B_D_T_, + C_B_L_C_, + C_F_F_, + C_F_F__2, + C_O_L_R_, + C_P_A_L_, + D_S_I_G_, + E_B_D_T_, + E_B_L_C_, + E_B_S_C_, + F_F_T_M_, + G_D_E_F_, + G_P_O_S_, + G_S_U_B_, + G_V_A_R_, + H_V_A_R_, + I_F_T_, + I_F_T_X_, + J_S_T_F_, + L_T_S_H_, + M_A_T_H_, + M_V_A_R_, + S_T_A_T_, + S_V_G_, + T_S_I__0, + T_S_I__1, + T_S_I__2, + T_S_I__3, + T_S_I__5, + T_S_I_B_, + T_S_I_C_, + T_S_I_D_, + T_S_I_J_, + T_S_I_P_, + T_S_I_S_, + T_S_I_V_, + T_T_F_A_, + V_A_R_C_, + V_D_M_X_, + V_O_R_G_, + V_V_A_R_, + D__e_b_g, + F__e_a_t, + G__l_a_t, + G__l_o_c, + O_S_2f_2, + S__i_l_f, + S__i_l_l, + _a_n_k_r, + _a_v_a_r, + _b_d_a_t, + _b_g_c_l, + _b_h_e_d, + _b_l_o_c, + _b_s_l_n, + _c_i_d_g, + _c_m_a_p, + _c_v_a_r, + _c_v_t, + _f_e_a_t, + _f_p_g_m, + _f_v_a_r, + _g_a_s_p, + _g_c_i_d, + _g_l_y_f, + _g_v_a_r, + _h_d_m_x, + _h_e_a_d, + _h_h_e_a, + _h_m_t_x, + _k_e_r_n, + _l_c_a_r, + _l_o_c_a, + _l_t_a_g, + _m_a_x_p, + _m_e_t_a, + _m_o_r_t, + _m_o_r_x, + _n_a_m_e, + _o_p_b_d, + _p_o_s_t, + _p_r_e_p, + _p_r_o_p, + _s_b_i_x, + _t_r_a_k, + _v_h_e_a, + _v_m_t_x, + ) + from fontTools.ttLib.tables.DefaultTable import DefaultTable + + _VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. + +log = logging.getLogger(__name__) + + +_NumberT = TypeVar("_NumberT", bound=float) + + +class TTFont(object): + """Represents a TrueType font. + + The object manages file input and output, and offers a convenient way of + accessing tables. Tables will be only decompiled when necessary, ie. when + they're actually accessed. This means that simple operations can be extremely fast. + + Example usage: + + .. code-block:: pycon + + >>> + >> from fontTools import ttLib + >> tt = ttLib.TTFont("afont.ttf") # Load an existing font file + >> tt['maxp'].numGlyphs + 242 + >> tt['OS/2'].achVendID + 'B&H\000' + >> tt['head'].unitsPerEm + 2048 + + For details of the objects returned when accessing each table, see the + :doc:`tables </ttLib/tables>` documentation. + To add a table to the font, use the :py:func:`newTable` function: + + .. code-block:: pycon + + >>> + >> os2 = newTable("OS/2") + >> os2.version = 4 + >> # set other attributes + >> font["OS/2"] = os2 + + TrueType fonts can also be serialized to and from XML format (see also the + :doc:`ttx </ttx>` binary): + + .. code-block:: pycon + + >> + >> tt.saveXML("afont.ttx") + Dumping 'LTSH' table... + Dumping 'OS/2' table... + [...] + + >> tt2 = ttLib.TTFont() # Create a new font object + >> tt2.importXML("afont.ttx") + >> tt2['maxp'].numGlyphs + 242 + + The TTFont object may be used as a context manager; this will cause the file + reader to be closed after the context ``with`` block is exited:: + + with TTFont(filename) as f: + # Do stuff + + Args: + file: When reading a font from disk, either a pathname pointing to a file, + or a readable file object. + res_name_or_index: If running on a Macintosh, either a sfnt resource name or + an sfnt resource index number. If the index number is zero, TTLib will + autodetect whether the file is a flat file or a suitcase. (If it is a suitcase, + only the first 'sfnt' resource will be read.) + sfntVersion (str): When constructing a font object from scratch, sets the four-byte + sfnt magic number to be used. Defaults to ``\0\1\0\0`` (TrueType). To create + an OpenType file, use ``OTTO``. + flavor (str): Set this to ``woff`` when creating a WOFF file or ``woff2`` for a WOFF2 + file. + checkChecksums (int): How checksum data should be treated. Default is 0 + (no checking). Set to 1 to check and warn on wrong checksums; set to 2 to + raise an exception if any wrong checksums are found. + recalcBBoxes (bool): If true (the default), recalculates ``glyf``, ``CFF ``, + ``head`` bounding box values and ``hhea``/``vhea`` min/max values on save. + Also compiles the glyphs on importing, which saves memory consumption and + time. + ignoreDecompileErrors (bool): If true, exceptions raised during table decompilation + will be ignored, and the binary data will be returned for those tables instead. + recalcTimestamp (bool): If true (the default), sets the ``modified`` timestamp in + the ``head`` table on save. + fontNumber (int): The index of the font in a TrueType Collection file. + lazy (bool): If lazy is set to True, many data structures are loaded lazily, upon + access only. If it is set to False, many data structures are loaded immediately. + The default is ``lazy=None`` which is somewhere in between. + """ + + tables: dict[Tag, DefaultTable | GlyphOrder] + reader: SFNTReader | None + sfntVersion: str + flavor: str | None + flavorData: Any | None + lazy: bool | None + recalcBBoxes: bool + recalcTimestamp: bool + ignoreDecompileErrors: bool + cfg: AbstractConfig + glyphOrder: list[str] + _reverseGlyphOrderDict: dict[str, int] + _tableCache: MutableMapping[tuple[Tag, bytes], DefaultTable] | None + disassembleInstructions: bool + bitmapGlyphDataFormat: str + # Deprecated attributes + verbose: bool | None + quiet: bool | None + + def __init__( + self, + file: str | os.PathLike[str] | BinaryIO | None = None, + res_name_or_index: str | int | None = None, + sfntVersion: str = "\000\001\000\000", + flavor: str | None = None, + checkChecksums: int = 0, + verbose: bool | None = None, # Deprecated + recalcBBoxes: bool = True, + allowVID: Any = NotImplemented, # Deprecated/Unused + ignoreDecompileErrors: bool = False, + recalcTimestamp: bool = True, + fontNumber: int = -1, + lazy: bool | None = None, + quiet: bool | None = None, # Deprecated + _tableCache: MutableMapping[tuple[Tag, bytes], DefaultTable] | None = None, + cfg: Mapping[str, Any] | AbstractConfig = {}, + ) -> None: + # Set deprecated attributes + for name in ("verbose", "quiet"): + val = locals().get(name) + if val is not None: + deprecateArgument(name, "configure logging instead") + setattr(self, name, val) + + self.lazy = lazy + self.recalcBBoxes = recalcBBoxes + self.recalcTimestamp = recalcTimestamp + self.tables = {} + self.reader = None + self.cfg = cfg.copy() if isinstance(cfg, AbstractConfig) else Config(cfg) + self.ignoreDecompileErrors = ignoreDecompileErrors + + if not file: + self.sfntVersion = sfntVersion + self.flavor = flavor + self.flavorData = None + return + seekable = True + if not hasattr(file, "read"): + if not isinstance(file, (str, os.PathLike)): + raise TypeError( + "fileOrPath must be a file path (str or PathLike) if it isn't an object with a `read` method." + ) + closeStream = True + # assume file is a string + if res_name_or_index is not None: + # see if it contains 'sfnt' resources in the resource or data fork + from . import macUtils + + if res_name_or_index == 0: + if macUtils.getSFNTResIndices(file): + # get the first available sfnt font. + file = macUtils.SFNTResourceReader(file, 1) + else: + file = open(file, "rb") + else: + file = macUtils.SFNTResourceReader(file, res_name_or_index) + else: + file = open(file, "rb") + else: + # assume "file" is a readable file object + assert not isinstance(file, (str, os.PathLike)) + closeStream = False + # SFNTReader wants the input file to be seekable. + # SpooledTemporaryFile has no seekable() on < 3.11, but still can seek: + # https://github.com/fonttools/fonttools/issues/3052 + if hasattr(file, "seekable"): + seekable = file.seekable() + elif hasattr(file, "seek"): + try: + file.seek(0) + except UnsupportedOperation: + seekable = False + + if not self.lazy: + # read input file in memory and wrap a stream around it to allow overwriting + if seekable: + file.seek(0) + tmp = BytesIO(file.read()) + if hasattr(file, "name"): + # save reference to input file name + tmp.name = file.name + if closeStream: + file.close() + file = tmp + elif not seekable: + raise TTLibError("Input file must be seekable when lazy=True") + self._tableCache = _tableCache + self.reader = SFNTReader(file, checkChecksums, fontNumber=fontNumber) + self.sfntVersion = self.reader.sfntVersion + self.flavor = self.reader.flavor + self.flavorData = self.reader.flavorData + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """If we still have a reader object, close it.""" + if self.reader is not None: + self.reader.close() + self.reader = None + + def save( + self, file: str | os.PathLike[str] | BinaryIO, reorderTables: bool | None = True + ) -> None: + """Save the font to disk. + + Args: + file: Similarly to the constructor, can be either a pathname or a writable + binary file object. + reorderTables (Option[bool]): If true (the default), reorder the tables, + sorting them by tag (recommended by the OpenType specification). If + false, retain the original font order. If None, reorder by table + dependency (fastest). + """ + if not hasattr(file, "write"): + if self.lazy and self.reader.file.name == file: + raise TTLibError("Can't overwrite TTFont when 'lazy' attribute is True") + createStream = True + else: + # assume "file" is a writable file object + createStream = False + + tmp = BytesIO() + + writer_reordersTables = self._save(tmp) + + if not ( + reorderTables is None + or writer_reordersTables + or (reorderTables is False and self.reader is None) + ): + if reorderTables is False: + # sort tables using the original font's order + if self.reader is None: + raise TTLibError( + "The original table order is unavailable because there isn't a font to read it from." + ) + tableOrder = list(self.reader.keys()) + else: + # use the recommended order from the OpenType specification + tableOrder = None + tmp.flush() + tmp2 = BytesIO() + reorderFontTables(tmp, tmp2, tableOrder) + tmp.close() + tmp = tmp2 + + if createStream: + # "file" is a path + assert isinstance(file, (str, os.PathLike)) + with open(file, "wb") as file: + file.write(tmp.getvalue()) + else: + assert not isinstance(file, (str, os.PathLike)) + file.write(tmp.getvalue()) + + tmp.close() + + def _save( + self, + file: BinaryIO, + tableCache: MutableMapping[tuple[Tag, bytes], Any] | None = None, + ) -> bool: + """Internal function, to be shared by save() and TTCollection.save()""" + + if self.recalcTimestamp and "head" in self: + # make sure 'head' is loaded so the recalculation is actually done + self["head"] + + tags = self.keys() + tags.pop(0) # skip GlyphOrder tag + numTables = len(tags) + # write to a temporary stream to allow saving to unseekable streams + writer = SFNTWriter( + file, numTables, self.sfntVersion, self.flavor, self.flavorData + ) + + done = [] + for tag in tags: + self._writeTable(tag, writer, done, tableCache) + + writer.close() + + return writer.reordersTables() + + class XMLSavingOptions(TypedDict): + writeVersion: bool + quiet: bool | None + tables: Sequence[str | bytes] | None + skipTables: Sequence[str] | None + splitTables: bool + splitGlyphs: bool + disassembleInstructions: bool + bitmapGlyphDataFormat: str + + def saveXML( + self, + fileOrPath: str | os.PathLike[str] | BinaryIO | TextIO, + newlinestr: str = "\n", + **kwargs: Unpack[XMLSavingOptions], + ) -> None: + """Export the font as TTX (an XML-based text file), or as a series of text + files when splitTables is true. In the latter case, the 'fileOrPath' + argument should be a path to a directory. + The 'tables' argument must either be falsy (None or empty list, meaning + dump all tables) or a non-empty list of tables to dump. The 'skipTables' + argument may be a list of tables to skip, but only when 'tables' is falsy. + """ + + writer = xmlWriter.XMLWriter(fileOrPath, newlinestr=newlinestr) + self._saveXML(writer, **kwargs) + writer.close() + + def _saveXML( + self, + writer: xmlWriter.XMLWriter, + writeVersion: bool = True, + quiet: bool | None = None, # Deprecated + tables: Sequence[str | bytes] | None = None, + skipTables: Sequence[str] | None = None, + splitTables: bool = False, + splitGlyphs: bool = False, + disassembleInstructions: bool = True, + bitmapGlyphDataFormat: str = "raw", + ) -> None: + if quiet is not None: + deprecateArgument("quiet", "configure logging instead") + + self.disassembleInstructions = disassembleInstructions + self.bitmapGlyphDataFormat = bitmapGlyphDataFormat + if not tables: + tables = self.keys() + if skipTables: + tables = [tag for tag in tables if tag not in skipTables] + + if writeVersion: + from fontTools import version + + version = ".".join(version.split(".")[:2]) + writer.begintag( + "ttFont", + sfntVersion=repr(tostr(self.sfntVersion))[1:-1], + ttLibVersion=version, + ) + else: + writer.begintag("ttFont", sfntVersion=repr(tostr(self.sfntVersion))[1:-1]) + writer.newline() + + # always splitTables if splitGlyphs is enabled + splitTables = splitTables or splitGlyphs + + if not splitTables: + writer.newline() + else: + if writer.filename is None: + raise TTLibError( + "splitTables requires the file name to be a file system path, not a stream." + ) + path, ext = os.path.splitext(writer.filename) + + for tag in tables: + if splitTables: + tablePath = path + "." + tagToIdentifier(tag) + ext + tableWriter = xmlWriter.XMLWriter( + tablePath, newlinestr=writer.newlinestr + ) + tableWriter.begintag("ttFont", ttLibVersion=version) + tableWriter.newline() + tableWriter.newline() + writer.simpletag(tagToXML(tag), src=os.path.basename(tablePath)) + writer.newline() + else: + tableWriter = writer + self._tableToXML(tableWriter, tag, splitGlyphs=splitGlyphs) + if splitTables: + tableWriter.endtag("ttFont") + tableWriter.newline() + tableWriter.close() + writer.endtag("ttFont") + writer.newline() + + def _tableToXML( + self, + writer: xmlWriter.XMLWriter, + tag: str | bytes, + quiet: bool | None = None, + splitGlyphs: bool = False, + ) -> None: + if quiet is not None: + deprecateArgument("quiet", "configure logging instead") + if tag in self: + table = self[tag] + report = "Dumping '%s' table..." % tag + else: + report = "No '%s' table found." % tag + log.info(report) + if tag not in self: + return + xmlTag = tagToXML(tag) + attrs: dict[str, Any] = {} + if hasattr(table, "ERROR"): + attrs["ERROR"] = "decompilation error" + from .tables.DefaultTable import DefaultTable + + if table.__class__ == DefaultTable: + attrs["raw"] = True + writer.begintag(xmlTag, **attrs) + writer.newline() + if tag == "glyf": + table.toXML(writer, self, splitGlyphs=splitGlyphs) + else: + table.toXML(writer, self) + writer.endtag(xmlTag) + writer.newline() + writer.newline() + + def importXML( + self, fileOrPath: str | os.PathLike[str] | BinaryIO, quiet: bool | None = None + ) -> None: + """Import a TTX file (an XML-based text format), so as to recreate + a font object. + """ + if quiet is not None: + deprecateArgument("quiet", "configure logging instead") + + if "maxp" in self and "post" in self: + # Make sure the glyph order is loaded, as it otherwise gets + # lost if the XML doesn't contain the glyph order, yet does + # contain the table which was originally used to extract the + # glyph names from (ie. 'post', 'cmap' or 'CFF '). + self.getGlyphOrder() + + from fontTools.misc import xmlReader + + reader = xmlReader.XMLReader(fileOrPath, self) + reader.read() + + def isLoaded(self, tag: str | bytes) -> bool: + """Return true if the table identified by ``tag`` has been + decompiled and loaded into memory.""" + return tag in self.tables + + def has_key(self, tag: str | bytes) -> bool: + """Test if the table identified by ``tag`` is present in the font. + + As well as this method, ``tag in font`` can also be used to determine the + presence of the table.""" + if self.isLoaded(tag): + return True + elif self.reader and tag in self.reader: + return True + elif tag == "GlyphOrder": + return True + else: + return False + + __contains__ = has_key + + def keys(self) -> list[str]: + """Returns the list of tables in the font, along with the ``GlyphOrder`` pseudo-table.""" + keys = list(self.tables.keys()) + if self.reader: + for key in list(self.reader.keys()): + if key not in keys: + keys.append(key) + + if "GlyphOrder" in keys: + keys.remove("GlyphOrder") + keys = sortedTagList(keys) + return ["GlyphOrder"] + keys + + def ensureDecompiled(self, recurse: bool | None = None) -> None: + """Decompile all the tables, even if a TTFont was opened in 'lazy' mode.""" + for tag in self.keys(): + table = self[tag] + if recurse is None: + recurse = self.lazy is not False + if recurse and hasattr(table, "ensureDecompiled"): + table.ensureDecompiled(recurse=recurse) + self.lazy = False + + def __len__(self) -> int: + return len(list(self.keys())) + + @overload + def __getitem__(self, tag: Literal["BASE"]) -> B_A_S_E_.table_B_A_S_E_: ... + @overload + def __getitem__(self, tag: Literal["CBDT"]) -> C_B_D_T_.table_C_B_D_T_: ... + @overload + def __getitem__(self, tag: Literal["CBLC"]) -> C_B_L_C_.table_C_B_L_C_: ... + @overload + def __getitem__(self, tag: Literal["CFF "]) -> C_F_F_.table_C_F_F_: ... + @overload + def __getitem__(self, tag: Literal["CFF2"]) -> C_F_F__2.table_C_F_F__2: ... + @overload + def __getitem__(self, tag: Literal["COLR"]) -> C_O_L_R_.table_C_O_L_R_: ... + @overload + def __getitem__(self, tag: Literal["CPAL"]) -> C_P_A_L_.table_C_P_A_L_: ... + @overload + def __getitem__(self, tag: Literal["DSIG"]) -> D_S_I_G_.table_D_S_I_G_: ... + @overload + def __getitem__(self, tag: Literal["EBDT"]) -> E_B_D_T_.table_E_B_D_T_: ... + @overload + def __getitem__(self, tag: Literal["EBLC"]) -> E_B_L_C_.table_E_B_L_C_: ... + @overload + def __getitem__(self, tag: Literal["EBSC"]) -> E_B_S_C_.table_E_B_S_C_: ... + @overload + def __getitem__(self, tag: Literal["FFTM"]) -> F_F_T_M_.table_F_F_T_M_: ... + @overload + def __getitem__(self, tag: Literal["GDEF"]) -> G_D_E_F_.table_G_D_E_F_: ... + @overload + def __getitem__(self, tag: Literal["GPOS"]) -> G_P_O_S_.table_G_P_O_S_: ... + @overload + def __getitem__(self, tag: Literal["GSUB"]) -> G_S_U_B_.table_G_S_U_B_: ... + @overload + def __getitem__(self, tag: Literal["GVAR"]) -> G_V_A_R_.table_G_V_A_R_: ... + @overload + def __getitem__(self, tag: Literal["HVAR"]) -> H_V_A_R_.table_H_V_A_R_: ... + @overload + def __getitem__(self, tag: Literal["IFT "]) -> I_F_T_.table_I_F_T_: ... + @overload + def __getitem__(self, tag: Literal["IFTX"]) -> I_F_T_X_.table_I_F_T_X_: ... + @overload + def __getitem__(self, tag: Literal["JSTF"]) -> J_S_T_F_.table_J_S_T_F_: ... + @overload + def __getitem__(self, tag: Literal["LTSH"]) -> L_T_S_H_.table_L_T_S_H_: ... + @overload + def __getitem__(self, tag: Literal["MATH"]) -> M_A_T_H_.table_M_A_T_H_: ... + @overload + def __getitem__(self, tag: Literal["MVAR"]) -> M_V_A_R_.table_M_V_A_R_: ... + @overload + def __getitem__(self, tag: Literal["STAT"]) -> S_T_A_T_.table_S_T_A_T_: ... + @overload + def __getitem__(self, tag: Literal["SVG "]) -> S_V_G_.table_S_V_G_: ... + @overload + def __getitem__(self, tag: Literal["TSI0"]) -> T_S_I__0.table_T_S_I__0: ... + @overload + def __getitem__(self, tag: Literal["TSI1"]) -> T_S_I__1.table_T_S_I__1: ... + @overload + def __getitem__(self, tag: Literal["TSI2"]) -> T_S_I__2.table_T_S_I__2: ... + @overload + def __getitem__(self, tag: Literal["TSI3"]) -> T_S_I__3.table_T_S_I__3: ... + @overload + def __getitem__(self, tag: Literal["TSI5"]) -> T_S_I__5.table_T_S_I__5: ... + @overload + def __getitem__(self, tag: Literal["TSIB"]) -> T_S_I_B_.table_T_S_I_B_: ... + @overload + def __getitem__(self, tag: Literal["TSIC"]) -> T_S_I_C_.table_T_S_I_C_: ... + @overload + def __getitem__(self, tag: Literal["TSID"]) -> T_S_I_D_.table_T_S_I_D_: ... + @overload + def __getitem__(self, tag: Literal["TSIJ"]) -> T_S_I_J_.table_T_S_I_J_: ... + @overload + def __getitem__(self, tag: Literal["TSIP"]) -> T_S_I_P_.table_T_S_I_P_: ... + @overload + def __getitem__(self, tag: Literal["TSIS"]) -> T_S_I_S_.table_T_S_I_S_: ... + @overload + def __getitem__(self, tag: Literal["TSIV"]) -> T_S_I_V_.table_T_S_I_V_: ... + @overload + def __getitem__(self, tag: Literal["TTFA"]) -> T_T_F_A_.table_T_T_F_A_: ... + @overload + def __getitem__(self, tag: Literal["VARC"]) -> V_A_R_C_.table_V_A_R_C_: ... + @overload + def __getitem__(self, tag: Literal["VDMX"]) -> V_D_M_X_.table_V_D_M_X_: ... + @overload + def __getitem__(self, tag: Literal["VORG"]) -> V_O_R_G_.table_V_O_R_G_: ... + @overload + def __getitem__(self, tag: Literal["VVAR"]) -> V_V_A_R_.table_V_V_A_R_: ... + @overload + def __getitem__(self, tag: Literal["Debg"]) -> D__e_b_g.table_D__e_b_g: ... + @overload + def __getitem__(self, tag: Literal["Feat"]) -> F__e_a_t.table_F__e_a_t: ... + @overload + def __getitem__(self, tag: Literal["Glat"]) -> G__l_a_t.table_G__l_a_t: ... + @overload + def __getitem__(self, tag: Literal["Gloc"]) -> G__l_o_c.table_G__l_o_c: ... + @overload + def __getitem__(self, tag: Literal["OS/2"]) -> O_S_2f_2.table_O_S_2f_2: ... + @overload + def __getitem__(self, tag: Literal["Silf"]) -> S__i_l_f.table_S__i_l_f: ... + @overload + def __getitem__(self, tag: Literal["Sill"]) -> S__i_l_l.table_S__i_l_l: ... + @overload + def __getitem__(self, tag: Literal["ankr"]) -> _a_n_k_r.table__a_n_k_r: ... + @overload + def __getitem__(self, tag: Literal["avar"]) -> _a_v_a_r.table__a_v_a_r: ... + @overload + def __getitem__(self, tag: Literal["bsln"]) -> _b_s_l_n.table__b_s_l_n: ... + @overload + def __getitem__(self, tag: Literal["bdat"]) -> _b_d_a_t.table__b_d_a_t: ... + @overload + def __getitem__(self, tag: Literal["bhed"]) -> _b_h_e_d.table__b_h_e_d: ... + @overload + def __getitem__(self, tag: Literal["bgcl"]) -> _b_g_c_l.table__b_g_c_l: ... + @overload + def __getitem__(self, tag: Literal["bloc"]) -> _b_l_o_c.table__b_l_o_c: ... + @overload + def __getitem__(self, tag: Literal["cidg"]) -> _c_i_d_g.table__c_i_d_g: ... + @overload + def __getitem__(self, tag: Literal["cmap"]) -> _c_m_a_p.table__c_m_a_p: ... + @overload + def __getitem__(self, tag: Literal["cvar"]) -> _c_v_a_r.table__c_v_a_r: ... + @overload + def __getitem__(self, tag: Literal["cvt "]) -> _c_v_t.table__c_v_t: ... + @overload + def __getitem__(self, tag: Literal["feat"]) -> _f_e_a_t.table__f_e_a_t: ... + @overload + def __getitem__(self, tag: Literal["fpgm"]) -> _f_p_g_m.table__f_p_g_m: ... + @overload + def __getitem__(self, tag: Literal["fvar"]) -> _f_v_a_r.table__f_v_a_r: ... + @overload + def __getitem__(self, tag: Literal["gasp"]) -> _g_a_s_p.table__g_a_s_p: ... + @overload + def __getitem__(self, tag: Literal["gcid"]) -> _g_c_i_d.table__g_c_i_d: ... + @overload + def __getitem__(self, tag: Literal["glyf"]) -> _g_l_y_f.table__g_l_y_f: ... + @overload + def __getitem__(self, tag: Literal["gvar"]) -> _g_v_a_r.table__g_v_a_r: ... + @overload + def __getitem__(self, tag: Literal["hdmx"]) -> _h_d_m_x.table__h_d_m_x: ... + @overload + def __getitem__(self, tag: Literal["head"]) -> _h_e_a_d.table__h_e_a_d: ... + @overload + def __getitem__(self, tag: Literal["hhea"]) -> _h_h_e_a.table__h_h_e_a: ... + @overload + def __getitem__(self, tag: Literal["hmtx"]) -> _h_m_t_x.table__h_m_t_x: ... + @overload + def __getitem__(self, tag: Literal["kern"]) -> _k_e_r_n.table__k_e_r_n: ... + @overload + def __getitem__(self, tag: Literal["lcar"]) -> _l_c_a_r.table__l_c_a_r: ... + @overload + def __getitem__(self, tag: Literal["loca"]) -> _l_o_c_a.table__l_o_c_a: ... + @overload + def __getitem__(self, tag: Literal["ltag"]) -> _l_t_a_g.table__l_t_a_g: ... + @overload + def __getitem__(self, tag: Literal["maxp"]) -> _m_a_x_p.table__m_a_x_p: ... + @overload + def __getitem__(self, tag: Literal["meta"]) -> _m_e_t_a.table__m_e_t_a: ... + @overload + def __getitem__(self, tag: Literal["mort"]) -> _m_o_r_t.table__m_o_r_t: ... + @overload + def __getitem__(self, tag: Literal["morx"]) -> _m_o_r_x.table__m_o_r_x: ... + @overload + def __getitem__(self, tag: Literal["name"]) -> _n_a_m_e.table__n_a_m_e: ... + @overload + def __getitem__(self, tag: Literal["opbd"]) -> _o_p_b_d.table__o_p_b_d: ... + @overload + def __getitem__(self, tag: Literal["post"]) -> _p_o_s_t.table__p_o_s_t: ... + @overload + def __getitem__(self, tag: Literal["prep"]) -> _p_r_e_p.table__p_r_e_p: ... + @overload + def __getitem__(self, tag: Literal["prop"]) -> _p_r_o_p.table__p_r_o_p: ... + @overload + def __getitem__(self, tag: Literal["sbix"]) -> _s_b_i_x.table__s_b_i_x: ... + @overload + def __getitem__(self, tag: Literal["trak"]) -> _t_r_a_k.table__t_r_a_k: ... + @overload + def __getitem__(self, tag: Literal["vhea"]) -> _v_h_e_a.table__v_h_e_a: ... + @overload + def __getitem__(self, tag: Literal["vmtx"]) -> _v_m_t_x.table__v_m_t_x: ... + @overload + def __getitem__(self, tag: Literal["GlyphOrder"]) -> GlyphOrder: ... + @overload + def __getitem__(self, tag: str | bytes) -> DefaultTable | GlyphOrder: ... + + def __getitem__(self, tag: str | bytes) -> DefaultTable | GlyphOrder: + tag = Tag(tag) + table = self.tables.get(tag) + if table is None: + if tag == "GlyphOrder": + table = GlyphOrder(tag) + self.tables[tag] = table + elif self.reader is not None: + table = self._readTable(tag) + else: + raise KeyError("'%s' table not found" % tag) + return table + + def _readTable(self, tag: Tag) -> DefaultTable: + log.debug("Reading '%s' table from disk", tag) + assert self.reader is not None + data = self.reader[tag] + if self._tableCache is not None: + table = self._tableCache.get((tag, data)) + if table is not None: + return table + tableClass = getTableClass(tag) + table = tableClass(tag) + self.tables[tag] = table + log.debug("Decompiling '%s' table", tag) + try: + table.decompile(data, self) + except Exception: + if not self.ignoreDecompileErrors: + raise + # fall back to DefaultTable, retaining the binary table data + log.exception( + "An exception occurred during the decompilation of the '%s' table", tag + ) + from .tables.DefaultTable import DefaultTable + + file = StringIO() + traceback.print_exc(file=file) + table = DefaultTable(tag) + table.ERROR = file.getvalue() + self.tables[tag] = table + table.decompile(data, self) + if self._tableCache is not None: + self._tableCache[(tag, data)] = table + return table + + def __setitem__(self, tag: str | bytes, table: DefaultTable) -> None: + self.tables[Tag(tag)] = table + + def __delitem__(self, tag: str | bytes) -> None: + if tag not in self: + raise KeyError("'%s' table not found" % tag) + if tag in self.tables: + del self.tables[tag] + if self.reader and tag in self.reader: + del self.reader[tag] + + @overload + def get(self, tag: Literal["BASE"]) -> B_A_S_E_.table_B_A_S_E_ | None: ... + @overload + def get(self, tag: Literal["CBDT"]) -> C_B_D_T_.table_C_B_D_T_ | None: ... + @overload + def get(self, tag: Literal["CBLC"]) -> C_B_L_C_.table_C_B_L_C_ | None: ... + @overload + def get(self, tag: Literal["CFF "]) -> C_F_F_.table_C_F_F_ | None: ... + @overload + def get(self, tag: Literal["CFF2"]) -> C_F_F__2.table_C_F_F__2 | None: ... + @overload + def get(self, tag: Literal["COLR"]) -> C_O_L_R_.table_C_O_L_R_ | None: ... + @overload + def get(self, tag: Literal["CPAL"]) -> C_P_A_L_.table_C_P_A_L_ | None: ... + @overload + def get(self, tag: Literal["DSIG"]) -> D_S_I_G_.table_D_S_I_G_ | None: ... + @overload + def get(self, tag: Literal["EBDT"]) -> E_B_D_T_.table_E_B_D_T_ | None: ... + @overload + def get(self, tag: Literal["EBLC"]) -> E_B_L_C_.table_E_B_L_C_ | None: ... + @overload + def get(self, tag: Literal["EBSC"]) -> E_B_S_C_.table_E_B_S_C_ | None: ... + @overload + def get(self, tag: Literal["FFTM"]) -> F_F_T_M_.table_F_F_T_M_ | None: ... + @overload + def get(self, tag: Literal["GDEF"]) -> G_D_E_F_.table_G_D_E_F_ | None: ... + @overload + def get(self, tag: Literal["GPOS"]) -> G_P_O_S_.table_G_P_O_S_ | None: ... + @overload + def get(self, tag: Literal["GSUB"]) -> G_S_U_B_.table_G_S_U_B_ | None: ... + @overload + def get(self, tag: Literal["GVAR"]) -> G_V_A_R_.table_G_V_A_R_ | None: ... + @overload + def get(self, tag: Literal["HVAR"]) -> H_V_A_R_.table_H_V_A_R_ | None: ... + @overload + def get(self, tag: Literal["IFT "]) -> I_F_T_.table_I_F_T_ | None: ... + @overload + def get(self, tag: Literal["IFTX"]) -> I_F_T_X_.table_I_F_T_X_ | None: ... + @overload + def get(self, tag: Literal["JSTF"]) -> J_S_T_F_.table_J_S_T_F_ | None: ... + @overload + def get(self, tag: Literal["LTSH"]) -> L_T_S_H_.table_L_T_S_H_ | None: ... + @overload + def get(self, tag: Literal["MATH"]) -> M_A_T_H_.table_M_A_T_H_ | None: ... + @overload + def get(self, tag: Literal["MVAR"]) -> M_V_A_R_.table_M_V_A_R_ | None: ... + @overload + def get(self, tag: Literal["STAT"]) -> S_T_A_T_.table_S_T_A_T_ | None: ... + @overload + def get(self, tag: Literal["SVG "]) -> S_V_G_.table_S_V_G_ | None: ... + @overload + def get(self, tag: Literal["TSI0"]) -> T_S_I__0.table_T_S_I__0 | None: ... + @overload + def get(self, tag: Literal["TSI1"]) -> T_S_I__1.table_T_S_I__1 | None: ... + @overload + def get(self, tag: Literal["TSI2"]) -> T_S_I__2.table_T_S_I__2 | None: ... + @overload + def get(self, tag: Literal["TSI3"]) -> T_S_I__3.table_T_S_I__3 | None: ... + @overload + def get(self, tag: Literal["TSI5"]) -> T_S_I__5.table_T_S_I__5 | None: ... + @overload + def get(self, tag: Literal["TSIB"]) -> T_S_I_B_.table_T_S_I_B_ | None: ... + @overload + def get(self, tag: Literal["TSIC"]) -> T_S_I_C_.table_T_S_I_C_ | None: ... + @overload + def get(self, tag: Literal["TSID"]) -> T_S_I_D_.table_T_S_I_D_ | None: ... + @overload + def get(self, tag: Literal["TSIJ"]) -> T_S_I_J_.table_T_S_I_J_ | None: ... + @overload + def get(self, tag: Literal["TSIP"]) -> T_S_I_P_.table_T_S_I_P_ | None: ... + @overload + def get(self, tag: Literal["TSIS"]) -> T_S_I_S_.table_T_S_I_S_ | None: ... + @overload + def get(self, tag: Literal["TSIV"]) -> T_S_I_V_.table_T_S_I_V_ | None: ... + @overload + def get(self, tag: Literal["TTFA"]) -> T_T_F_A_.table_T_T_F_A_ | None: ... + @overload + def get(self, tag: Literal["VARC"]) -> V_A_R_C_.table_V_A_R_C_ | None: ... + @overload + def get(self, tag: Literal["VDMX"]) -> V_D_M_X_.table_V_D_M_X_ | None: ... + @overload + def get(self, tag: Literal["VORG"]) -> V_O_R_G_.table_V_O_R_G_ | None: ... + @overload + def get(self, tag: Literal["VVAR"]) -> V_V_A_R_.table_V_V_A_R_ | None: ... + @overload + def get(self, tag: Literal["Debg"]) -> D__e_b_g.table_D__e_b_g | None: ... + @overload + def get(self, tag: Literal["Feat"]) -> F__e_a_t.table_F__e_a_t | None: ... + @overload + def get(self, tag: Literal["Glat"]) -> G__l_a_t.table_G__l_a_t | None: ... + @overload + def get(self, tag: Literal["Gloc"]) -> G__l_o_c.table_G__l_o_c | None: ... + @overload + def get(self, tag: Literal["OS/2"]) -> O_S_2f_2.table_O_S_2f_2 | None: ... + @overload + def get(self, tag: Literal["Silf"]) -> S__i_l_f.table_S__i_l_f | None: ... + @overload + def get(self, tag: Literal["Sill"]) -> S__i_l_l.table_S__i_l_l | None: ... + @overload + def get(self, tag: Literal["ankr"]) -> _a_n_k_r.table__a_n_k_r | None: ... + @overload + def get(self, tag: Literal["avar"]) -> _a_v_a_r.table__a_v_a_r | None: ... + @overload + def get(self, tag: Literal["bsln"]) -> _b_s_l_n.table__b_s_l_n | None: ... + @overload + def get(self, tag: Literal["bgcl"]) -> _b_g_c_l.table__b_g_c_l | None: ... + @overload + def get(self, tag: Literal["cidg"]) -> _c_i_d_g.table__c_i_d_g | None: ... + @overload + def get(self, tag: Literal["cmap"]) -> _c_m_a_p.table__c_m_a_p | None: ... + @overload + def get(self, tag: Literal["cvar"]) -> _c_v_a_r.table__c_v_a_r | None: ... + @overload + def get(self, tag: Literal["cvt "]) -> _c_v_t.table__c_v_t | None: ... + @overload + def get(self, tag: Literal["feat"]) -> _f_e_a_t.table__f_e_a_t | None: ... + @overload + def get(self, tag: Literal["fpgm"]) -> _f_p_g_m.table__f_p_g_m | None: ... + @overload + def get(self, tag: Literal["fvar"]) -> _f_v_a_r.table__f_v_a_r | None: ... + @overload + def get(self, tag: Literal["gasp"]) -> _g_a_s_p.table__g_a_s_p | None: ... + @overload + def get(self, tag: Literal["gcid"]) -> _g_c_i_d.table__g_c_i_d | None: ... + @overload + def get(self, tag: Literal["glyf"]) -> _g_l_y_f.table__g_l_y_f | None: ... + @overload + def get(self, tag: Literal["gvar"]) -> _g_v_a_r.table__g_v_a_r | None: ... + @overload + def get(self, tag: Literal["hdmx"]) -> _h_d_m_x.table__h_d_m_x | None: ... + @overload + def get(self, tag: Literal["head"]) -> _h_e_a_d.table__h_e_a_d | None: ... + @overload + def get(self, tag: Literal["hhea"]) -> _h_h_e_a.table__h_h_e_a | None: ... + @overload + def get(self, tag: Literal["hmtx"]) -> _h_m_t_x.table__h_m_t_x | None: ... + @overload + def get(self, tag: Literal["kern"]) -> _k_e_r_n.table__k_e_r_n | None: ... + @overload + def get(self, tag: Literal["lcar"]) -> _l_c_a_r.table__l_c_a_r | None: ... + @overload + def get(self, tag: Literal["loca"]) -> _l_o_c_a.table__l_o_c_a | None: ... + @overload + def get(self, tag: Literal["ltag"]) -> _l_t_a_g.table__l_t_a_g | None: ... + @overload + def get(self, tag: Literal["maxp"]) -> _m_a_x_p.table__m_a_x_p | None: ... + @overload + def get(self, tag: Literal["meta"]) -> _m_e_t_a.table__m_e_t_a | None: ... + @overload + def get(self, tag: Literal["mort"]) -> _m_o_r_t.table__m_o_r_t | None: ... + @overload + def get(self, tag: Literal["morx"]) -> _m_o_r_x.table__m_o_r_x | None: ... + @overload + def get(self, tag: Literal["name"]) -> _n_a_m_e.table__n_a_m_e | None: ... + @overload + def get(self, tag: Literal["opbd"]) -> _o_p_b_d.table__o_p_b_d | None: ... + @overload + def get(self, tag: Literal["post"]) -> _p_o_s_t.table__p_o_s_t | None: ... + @overload + def get(self, tag: Literal["prep"]) -> _p_r_e_p.table__p_r_e_p | None: ... + @overload + def get(self, tag: Literal["prop"]) -> _p_r_o_p.table__p_r_o_p | None: ... + @overload + def get(self, tag: Literal["sbix"]) -> _s_b_i_x.table__s_b_i_x | None: ... + @overload + def get(self, tag: Literal["trak"]) -> _t_r_a_k.table__t_r_a_k | None: ... + @overload + def get(self, tag: Literal["vhea"]) -> _v_h_e_a.table__v_h_e_a | None: ... + @overload + def get(self, tag: Literal["vmtx"]) -> _v_m_t_x.table__v_m_t_x | None: ... + @overload + def get(self, tag: Literal["GlyphOrder"]) -> GlyphOrder: ... + @overload + def get(self, tag: str | bytes) -> DefaultTable | GlyphOrder | Any | None: ... + @overload + def get( + self, tag: str | bytes, default: _VT_co + ) -> DefaultTable | GlyphOrder | Any | _VT_co: ... + + def get( + self, tag: str | bytes, default: Any | None = None + ) -> DefaultTable | GlyphOrder | Any | None: + """Returns the table if it exists or (optionally) a default if it doesn't.""" + try: + return self[tag] + except KeyError: + return default + + def setGlyphOrder(self, glyphOrder: list[str]) -> None: + """Set the glyph order + + Args: + glyphOrder ([str]): List of glyph names in order. + """ + self.glyphOrder = glyphOrder + if hasattr(self, "_reverseGlyphOrderDict"): + del self._reverseGlyphOrderDict + if self.isLoaded("glyf"): + self["glyf"].setGlyphOrder(glyphOrder) + + def getGlyphOrder(self) -> list[str]: + """Returns a list of glyph names ordered by their position in the font.""" + try: + return self.glyphOrder + except AttributeError: + pass + if "CFF " in self: + cff = self["CFF "] + self.glyphOrder = cff.getGlyphOrder() + elif "post" in self: + # TrueType font + glyphOrder = self["post"].getGlyphOrder() + if glyphOrder is None: + # + # No names found in the 'post' table. + # Try to create glyph names from the unicode cmap (if available) + # in combination with the Adobe Glyph List (AGL). + # + self._getGlyphNamesFromCmap() + elif len(glyphOrder) < self["maxp"].numGlyphs: + # + # Not enough names found in the 'post' table. + # Can happen when 'post' format 1 is improperly used on a font that + # has more than 258 glyphs (the length of 'standardGlyphOrder'). + # + log.warning( + "Not enough names found in the 'post' table, generating them from cmap instead" + ) + self._getGlyphNamesFromCmap() + else: + self.glyphOrder = glyphOrder + else: + self._getGlyphNamesFromCmap() + return self.glyphOrder + + def _getGlyphNamesFromCmap(self) -> None: + # + # This is rather convoluted, but then again, it's an interesting problem: + # - we need to use the unicode values found in the cmap table to + # build glyph names (eg. because there is only a minimal post table, + # or none at all). + # - but the cmap parser also needs glyph names to work with... + # So here's what we do: + # - make up glyph names based on glyphID + # - load a temporary cmap table based on those names + # - extract the unicode values, build the "real" glyph names + # - unload the temporary cmap table + # + if self.isLoaded("cmap"): + # Bootstrapping: we're getting called by the cmap parser + # itself. This means self.tables['cmap'] contains a partially + # loaded cmap, making it impossible to get at a unicode + # subtable here. We remove the partially loaded cmap and + # restore it later. + # This only happens if the cmap table is loaded before any + # other table that does f.getGlyphOrder() or f.getGlyphName(). + cmapLoading = self.tables["cmap"] + del self.tables["cmap"] + else: + cmapLoading = None + # Make up glyph names based on glyphID, which will be used by the + # temporary cmap and by the real cmap in case we don't find a unicode + # cmap. + numGlyphs = int(self["maxp"].numGlyphs) + glyphOrder = ["glyph%.5d" % i for i in range(numGlyphs)] + glyphOrder[0] = ".notdef" + # Set the glyph order, so the cmap parser has something + # to work with (so we don't get called recursively). + self.glyphOrder = glyphOrder + + # Make up glyph names based on the reversed cmap table. Because some + # glyphs (eg. ligatures or alternates) may not be reachable via cmap, + # this naming table will usually not cover all glyphs in the font. + # If the font has no Unicode cmap table, reversecmap will be empty. + if "cmap" in self: + reversecmap = self["cmap"].buildReversedMin() + else: + reversecmap = {} + useCount = {} + for i, tempName in enumerate(glyphOrder): + if tempName in reversecmap: + # If a font maps both U+0041 LATIN CAPITAL LETTER A and + # U+0391 GREEK CAPITAL LETTER ALPHA to the same glyph, + # we prefer naming the glyph as "A". + glyphName = self._makeGlyphName(reversecmap[tempName]) + numUses = useCount[glyphName] = useCount.get(glyphName, 0) + 1 + if numUses > 1: + glyphName = "%s.alt%d" % (glyphName, numUses - 1) + glyphOrder[i] = glyphName + + if "cmap" in self: + # Delete the temporary cmap table from the cache, so it can + # be parsed again with the right names. + del self.tables["cmap"] + self.glyphOrder = glyphOrder + if cmapLoading: + # restore partially loaded cmap, so it can continue loading + # using the proper names. + self.tables["cmap"] = cmapLoading + + @staticmethod + def _makeGlyphName(codepoint: int) -> str: + from fontTools import agl # Adobe Glyph List + + if codepoint in agl.UV2AGL: + return agl.UV2AGL[codepoint] + elif codepoint <= 0xFFFF: + return "uni%04X" % codepoint + else: + return "u%X" % codepoint + + def getGlyphNames(self) -> list[str]: + """Get a list of glyph names, sorted alphabetically.""" + glyphNames = sorted(self.getGlyphOrder()) + return glyphNames + + def getGlyphNames2(self) -> list[str]: + """Get a list of glyph names, sorted alphabetically, + but not case sensitive. + """ + from fontTools.misc import textTools + + return textTools.caselessSort(self.getGlyphOrder()) + + def getGlyphName(self, glyphID: int) -> str: + """Returns the name for the glyph with the given ID. + + If no name is available, synthesises one with the form ``glyphXXXXX``` where + ```XXXXX`` is the zero-padded glyph ID. + """ + try: + return self.getGlyphOrder()[glyphID] + except IndexError: + return "glyph%.5d" % glyphID + + def getGlyphNameMany(self, lst: Sequence[int]) -> list[str]: + """Converts a list of glyph IDs into a list of glyph names.""" + glyphOrder = self.getGlyphOrder() + cnt = len(glyphOrder) + return [glyphOrder[gid] if gid < cnt else "glyph%.5d" % gid for gid in lst] + + def getGlyphID(self, glyphName: str) -> int: + """Returns the ID of the glyph with the given name.""" + try: + return self.getReverseGlyphMap()[glyphName] + except KeyError: + if glyphName[:5] == "glyph": + try: + return int(glyphName[5:]) + except (NameError, ValueError): + raise KeyError(glyphName) + raise + + def getGlyphIDMany(self, lst: Sequence[str]) -> list[int]: + """Converts a list of glyph names into a list of glyph IDs.""" + d = self.getReverseGlyphMap() + try: + return [d[glyphName] for glyphName in lst] + except KeyError: + getGlyphID = self.getGlyphID + return [getGlyphID(glyphName) for glyphName in lst] + + def getReverseGlyphMap(self, rebuild: bool = False) -> dict[str, int]: + """Returns a mapping of glyph names to glyph IDs.""" + if rebuild or not hasattr(self, "_reverseGlyphOrderDict"): + self._buildReverseGlyphOrderDict() + return self._reverseGlyphOrderDict + + def _buildReverseGlyphOrderDict(self) -> dict[str, int]: + self._reverseGlyphOrderDict = d = {} + for glyphID, glyphName in enumerate(self.getGlyphOrder()): + d[glyphName] = glyphID + return d + + def _writeTable( + self, + tag: str | bytes, + writer: SFNTWriter, + done: list[str | bytes], # Use list as original + tableCache: MutableMapping[tuple[Tag, bytes], DefaultTable] | None = None, + ) -> None: + """Internal helper function for self.save(). Keeps track of + inter-table dependencies. + """ + if tag in done: + return + tableClass = getTableClass(tag) + for masterTable in tableClass.dependencies: + if masterTable not in done: + if masterTable in self: + self._writeTable(masterTable, writer, done, tableCache) + else: + done.append(masterTable) + done.append(tag) + tabledata = self.getTableData(tag) + if tableCache is not None: + entry = tableCache.get((Tag(tag), tabledata)) + if entry is not None: + log.debug("reusing '%s' table", tag) + writer.setEntry(tag, entry) + return + log.debug("Writing '%s' table to disk", tag) + writer[tag] = tabledata + if tableCache is not None: + tableCache[(Tag(tag), tabledata)] = writer[tag] + + def getTableData(self, tag: str | bytes) -> bytes: + """Returns the binary representation of a table. + + If the table is currently loaded and in memory, the data is compiled to + binary and returned; if it is not currently loaded, the binary data is + read from the font file and returned. + """ + tag = Tag(tag) + if self.isLoaded(tag): + log.debug("Compiling '%s' table", tag) + return self.tables[tag].compile(self) + elif self.reader and tag in self.reader: + log.debug("Reading '%s' table from disk", tag) + return self.reader[tag] + else: + raise KeyError(tag) + + def getGlyphSet( + self, + preferCFF: bool = True, + location: Mapping[str, _NumberT] | None = None, + normalized: bool = False, + recalcBounds: bool = True, + ) -> _TTGlyphSet: + """Return a generic GlyphSet, which is a dict-like object + mapping glyph names to glyph objects. The returned glyph objects + have a ``.draw()`` method that supports the Pen protocol, and will + have an attribute named 'width'. + + If the font is CFF-based, the outlines will be taken from the ``CFF `` + or ``CFF2`` tables. Otherwise the outlines will be taken from the + ``glyf`` table. + + If the font contains both a ``CFF ``/``CFF2`` and a ``glyf`` table, you + can use the ``preferCFF`` argument to specify which one should be taken. + If the font contains both a ``CFF `` and a ``CFF2`` table, the latter is + taken. + + If the ``location`` parameter is set, it should be a dictionary mapping + four-letter variation tags to their float values, and the returned + glyph-set will represent an instance of a variable font at that + location. + + If the ``normalized`` variable is set to True, that location is + interpreted as in the normalized (-1..+1) space, otherwise it is in the + font's defined axes space. + """ + if location and "fvar" not in self: + location = None + if location and not normalized: + location = self.normalizeLocation(location) + glyphSet = None + if ("CFF " in self or "CFF2" in self) and (preferCFF or "glyf" not in self): + glyphSet = _TTGlyphSetCFF(self, location) + elif "glyf" in self: + glyphSet = _TTGlyphSetGlyf(self, location, recalcBounds=recalcBounds) + else: + raise TTLibError("Font contains no outlines") + if "VARC" in self: + glyphSet = _TTGlyphSetVARC(self, location, glyphSet) + return glyphSet + + def normalizeLocation(self, location: Mapping[str, float]) -> dict[str, float]: + """Normalize a ``location`` from the font's defined axes space (also + known as user space) into the normalized (-1..+1) space. It applies + ``avar`` mapping if the font contains an ``avar`` table. + + The ``location`` parameter should be a dictionary mapping four-letter + variation tags to their float values. + + Raises ``TTLibError`` if the font is not a variable font. + """ + from fontTools.varLib.models import normalizeLocation + + if "fvar" not in self: + raise TTLibError("Not a variable font") + + axes = self["fvar"].getAxes() + location = normalizeLocation(location, axes) + if "avar" in self: + location = self["avar"].renormalizeLocation(location, self) + return location + + def getBestCmap( + self, + cmapPreferences: Sequence[tuple[int, int]] = ( + (3, 10), + (0, 6), + (0, 4), + (3, 1), + (0, 3), + (0, 2), + (0, 1), + (0, 0), + ), + ) -> dict[int, str] | None: + """Returns the 'best' Unicode cmap dictionary available in the font + or ``None``, if no Unicode cmap subtable is available. + + By default it will search for the following (platformID, platEncID) + pairs in order:: + + (3, 10), # Windows Unicode full repertoire + (0, 6), # Unicode full repertoire (format 13 subtable) + (0, 4), # Unicode 2.0 full repertoire + (3, 1), # Windows Unicode BMP + (0, 3), # Unicode 2.0 BMP + (0, 2), # Unicode ISO/IEC 10646 + (0, 1), # Unicode 1.1 + (0, 0) # Unicode 1.0 + + This particular order matches what HarfBuzz uses to choose what + subtable to use by default. This order prefers the largest-repertoire + subtable, and among those, prefers the Windows-platform over the + Unicode-platform as the former has wider support. + + This order can be customized via the ``cmapPreferences`` argument. + """ + return self["cmap"].getBestCmap(cmapPreferences=cmapPreferences) + + def reorderGlyphs(self, new_glyph_order: list[str]) -> None: + from .reorderGlyphs import reorderGlyphs + + reorderGlyphs(self, new_glyph_order) + + +class GlyphOrder(object): + """A pseudo table. The glyph order isn't in the font as a separate + table, but it's nice to present it as such in the TTX format. + """ + + def __init__(self, tag: str | None = None) -> None: + pass + + def toXML(self, writer: xmlWriter.XMLWriter, ttFont: TTFont) -> None: + glyphOrder = ttFont.getGlyphOrder() + writer.comment( + "The 'id' attribute is only for humans; it is ignored when parsed." + ) + writer.newline() + for i, glyphName in enumerate(glyphOrder): + writer.simpletag("GlyphID", id=i, name=glyphName) + writer.newline() + + def fromXML( + self, name: str, attrs: dict[str, str], content: list[Any], ttFont: TTFont + ) -> None: + if not hasattr(self, "glyphOrder"): + self.glyphOrder = [] + if name == "GlyphID": + self.glyphOrder.append(attrs["name"]) + ttFont.setGlyphOrder(self.glyphOrder) + + +def getTableModule(tag: str | bytes) -> ModuleType | None: + """Fetch the packer/unpacker module for a table. + Return None when no module is found. + """ + from . import tables + + pyTag = tagToIdentifier(tag) + try: + __import__("fontTools.ttLib.tables." + pyTag) + except ImportError as err: + # If pyTag is found in the ImportError message, + # means table is not implemented. If it's not + # there, then some other module is missing, don't + # suppress the error. + if str(err).find(pyTag) >= 0: + return None + else: + raise err + else: + return getattr(tables, pyTag) + + +# Registry for custom table packer/unpacker classes. Keys are table +# tags, values are (moduleName, className) tuples. +# See registerCustomTableClass() and getCustomTableClass() +_customTableRegistry: dict[str | bytes, tuple[str, str]] = {} + + +def registerCustomTableClass( + tag: str | bytes, moduleName: str, className: str | None = None +) -> None: + """Register a custom packer/unpacker class for a table. + + The 'moduleName' must be an importable module. If no 'className' + is given, it is derived from the tag, for example it will be + ``table_C_U_S_T_`` for a 'CUST' tag. + + The registered table class should be a subclass of + :py:class:`fontTools.ttLib.tables.DefaultTable.DefaultTable` + """ + if className is None: + className = "table_" + tagToIdentifier(tag) + _customTableRegistry[tag] = (moduleName, className) + + +def unregisterCustomTableClass(tag: str | bytes) -> None: + """Unregister the custom packer/unpacker class for a table.""" + del _customTableRegistry[tag] + + +def getCustomTableClass(tag: str | bytes) -> type[DefaultTable] | None: + """Return the custom table class for tag, if one has been registered + with 'registerCustomTableClass()'. Else return None. + """ + if tag not in _customTableRegistry: + return None + import importlib + + moduleName, className = _customTableRegistry[tag] + module = importlib.import_module(moduleName) + return getattr(module, className) + + +def getTableClass(tag: str | bytes) -> type[DefaultTable]: + """Fetch the packer/unpacker class for a table.""" + tableClass = getCustomTableClass(tag) + if tableClass is not None: + return tableClass + module = getTableModule(tag) + if module is None: + from .tables.DefaultTable import DefaultTable + + return DefaultTable + pyTag = tagToIdentifier(tag) + tableClass = getattr(module, "table_" + pyTag) + return tableClass + + +def getClassTag(klass: type[DefaultTable]) -> str | bytes: + """Fetch the table tag for a class object.""" + name = klass.__name__ + assert name[:6] == "table_" + name = name[6:] # Chop 'table_' + return identifierToTag(name) + + +def newTable(tag: str | bytes) -> DefaultTable: + """Return a new instance of a table.""" + tableClass = getTableClass(tag) + return tableClass(tag) + + +def _escapechar(c: str) -> str: + """Helper function for tagToIdentifier()""" + import re + + if re.match("[a-z0-9]", c): + return "_" + c + elif re.match("[A-Z]", c): + return c + "_" + else: + return hex(byteord(c))[2:] + + +def tagToIdentifier(tag: str | bytes) -> str: + """Convert a table tag to a valid (but UGLY) python identifier, + as well as a filename that's guaranteed to be unique even on a + caseless file system. Each character is mapped to two characters. + Lowercase letters get an underscore before the letter, uppercase + letters get an underscore after the letter. Trailing spaces are + trimmed. Illegal characters are escaped as two hex bytes. If the + result starts with a number (as the result of a hex escape), an + extra underscore is prepended. Examples: + .. code-block:: pycon + + >>> + >> tagToIdentifier('glyf') + '_g_l_y_f' + >> tagToIdentifier('cvt ') + '_c_v_t' + >> tagToIdentifier('OS/2') + 'O_S_2f_2' + """ + import re + + tag = Tag(tag) + if tag == "GlyphOrder": + return tag + assert len(tag) == 4, "tag should be 4 characters long" + while len(tag) > 1 and tag[-1] == " ": + tag = tag[:-1] + ident = "" + for c in tag: + ident = ident + _escapechar(c) + if re.match("[0-9]", ident): + ident = "_" + ident + return ident + + +def identifierToTag(ident: str) -> str: + """the opposite of tagToIdentifier()""" + if ident == "GlyphOrder": + return ident + if len(ident) % 2 and ident[0] == "_": + ident = ident[1:] + assert not (len(ident) % 2) + tag = "" + for i in range(0, len(ident), 2): + if ident[i] == "_": + tag = tag + ident[i + 1] + elif ident[i + 1] == "_": + tag = tag + ident[i] + else: + # assume hex + tag = tag + chr(int(ident[i : i + 2], 16)) + # append trailing spaces + tag = tag + (4 - len(tag)) * " " + return Tag(tag) + + +def tagToXML(tag: str | bytes) -> str: + """Similarly to tagToIdentifier(), this converts a TT tag + to a valid XML element name. Since XML element names are + case sensitive, this is a fairly simple/readable translation. + """ + import re + + tag = Tag(tag) + if tag == "OS/2": + return "OS_2" + elif tag == "GlyphOrder": + return tag + if re.match("[A-Za-z_][A-Za-z_0-9]* *$", tag): + return tag.strip() + else: + return tagToIdentifier(tag) + + +def xmlToTag(tag: str) -> str: + """The opposite of tagToXML()""" + if tag == "OS_2": + return Tag("OS/2") + if len(tag) == 8: + return identifierToTag(tag) + else: + return Tag(tag + " " * (4 - len(tag))) + + +# Table order as recommended in the OpenType specification 1.4 +TTFTableOrder = [ + "head", + "hhea", + "maxp", + "OS/2", + "hmtx", + "LTSH", + "VDMX", + "hdmx", + "cmap", + "fpgm", + "prep", + "cvt ", + "loca", + "glyf", + "kern", + "name", + "post", + "gasp", + "PCLT", +] + +OTFTableOrder = ["head", "hhea", "maxp", "OS/2", "name", "cmap", "post", "CFF "] + + +def sortedTagList( + tagList: Sequence[str], tableOrder: Sequence[str] | None = None +) -> list[str]: + """Return a sorted copy of tagList, sorted according to the OpenType + specification, or according to a custom tableOrder. If given and not + None, tableOrder needs to be a list of tag names. + """ + tagList = sorted(tagList) + if tableOrder is None: + if "DSIG" in tagList: + # DSIG should be last (XXX spec reference?) + tagList.remove("DSIG") + tagList.append("DSIG") + if "CFF " in tagList: + tableOrder = OTFTableOrder + else: + tableOrder = TTFTableOrder + orderedTables = [] + for tag in tableOrder: + if tag in tagList: + orderedTables.append(tag) + tagList.remove(tag) + orderedTables.extend(tagList) + return orderedTables + + +def reorderFontTables( + inFile: BinaryIO, # Takes file-like object as per original + outFile: BinaryIO, # Takes file-like object + tableOrder: Sequence[str] | None = None, + checkChecksums: bool = False, # Keep param even if reader handles it +) -> None: + """Rewrite a font file, ordering the tables as recommended by the + OpenType specification 1.4. + """ + inFile.seek(0) + outFile.seek(0) + reader = SFNTReader(inFile, checkChecksums=checkChecksums) + writer = SFNTWriter( + outFile, + len(reader.tables), + reader.sfntVersion, + reader.flavor, + reader.flavorData, + ) + tables = list(reader.keys()) + for tag in sortedTagList(tables, tableOrder): + writer[tag] = reader[tag] + writer.close() + + +def maxPowerOfTwo(x: int) -> int: + """Return the highest exponent of two, so that + (2 ** exponent) <= x. Return 0 if x is 0. + """ + exponent = 0 + while x: + x = x >> 1 + exponent = exponent + 1 + return max(exponent - 1, 0) + + +def getSearchRange(n: int, itemSize: int = 16) -> tuple[int, int, int]: + """Calculate searchRange, entrySelector, rangeShift.""" + # itemSize defaults to 16, for backward compatibility + # with upstream fonttools. + exponent = maxPowerOfTwo(n) + searchRange = (2**exponent) * itemSize + entrySelector = exponent + rangeShift = max(0, n * itemSize - searchRange) + return searchRange, entrySelector, rangeShift diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/ttGlyphSet.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/ttGlyphSet.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9a0cb9960434d28fd98bd6bf9fdd128522d89f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/ttGlyphSet.py @@ -0,0 +1,490 @@ +"""GlyphSets returned by a TTFont.""" + +from abc import ABC, abstractmethod +from collections.abc import Mapping +from contextlib import contextmanager +from copy import copy, deepcopy +from types import SimpleNamespace +from fontTools.misc.vector import Vector +from fontTools.misc.fixedTools import otRound, fixedToFloat as fi2fl +from fontTools.misc.loggingTools import deprecateFunction +from fontTools.misc.transform import Transform, DecomposedTransform +from fontTools.pens.transformPen import TransformPen, TransformPointPen +from fontTools.pens.recordingPen import ( + DecomposingRecordingPen, + lerpRecordings, + replayRecording, +) + + +class _TTGlyphSet(Mapping): + """Generic dict-like GlyphSet class that pulls metrics from hmtx and + glyph shape from TrueType or CFF. + """ + + def __init__(self, font, location, glyphsMapping, *, recalcBounds=True): + self.recalcBounds = recalcBounds + self.font = font + self.defaultLocationNormalized = ( + {axis.axisTag: 0 for axis in self.font["fvar"].axes} + if "fvar" in self.font + else {} + ) + self.location = location if location is not None else {} + self.rawLocation = {} # VarComponent-only location + self.originalLocation = location if location is not None else {} + self.depth = 0 + self.locationStack = [] + self.rawLocationStack = [] + self.glyphsMapping = glyphsMapping + self.hMetrics = font["hmtx"].metrics + self.vMetrics = getattr(font.get("vmtx"), "metrics", None) + self.hvarTable = None + if location: + from fontTools.varLib.varStore import VarStoreInstancer + + self.hvarTable = getattr(font.get("HVAR"), "table", None) + if self.hvarTable is not None: + self.hvarInstancer = VarStoreInstancer( + self.hvarTable.VarStore, font["fvar"].axes, location + ) + # TODO VVAR, VORG + + @contextmanager + def pushLocation(self, location, reset: bool): + self.locationStack.append(self.location) + self.rawLocationStack.append(self.rawLocation) + if reset: + self.location = self.originalLocation.copy() + self.rawLocation = self.defaultLocationNormalized.copy() + else: + self.location = self.location.copy() + self.rawLocation = {} + self.location.update(location) + self.rawLocation.update(location) + + try: + yield None + finally: + self.location = self.locationStack.pop() + self.rawLocation = self.rawLocationStack.pop() + + @contextmanager + def pushDepth(self): + try: + depth = self.depth + self.depth += 1 + yield depth + finally: + self.depth -= 1 + + def __contains__(self, glyphName): + return glyphName in self.glyphsMapping + + def __iter__(self): + return iter(self.glyphsMapping.keys()) + + def __len__(self): + return len(self.glyphsMapping) + + @deprecateFunction( + "use 'glyphName in glyphSet' instead", category=DeprecationWarning + ) + def has_key(self, glyphName): + return glyphName in self.glyphsMapping + + +class _TTGlyphSetGlyf(_TTGlyphSet): + def __init__(self, font, location, recalcBounds=True): + self.glyfTable = font["glyf"] + super().__init__(font, location, self.glyfTable, recalcBounds=recalcBounds) + self.gvarTable = font.get("gvar") + + def __getitem__(self, glyphName): + return _TTGlyphGlyf(self, glyphName, recalcBounds=self.recalcBounds) + + +class _TTGlyphSetCFF(_TTGlyphSet): + def __init__(self, font, location): + tableTag = "CFF2" if "CFF2" in font else "CFF " + self.charStrings = list(font[tableTag].cff.values())[0].CharStrings + super().__init__(font, location, self.charStrings) + self.setLocation(location) + + def __getitem__(self, glyphName): + return _TTGlyphCFF(self, glyphName) + + def setLocation(self, location): + self.blender = None + if location: + # TODO Optimize by using instancer.setLocation() + + from fontTools.varLib.varStore import VarStoreInstancer + + varStore = getattr(self.charStrings, "varStore", None) + if varStore is not None: + instancer = VarStoreInstancer( + varStore.otVarStore, self.font["fvar"].axes, location + ) + self.blender = instancer.interpolateFromDeltas + else: + self.blender = None + + @contextmanager + def pushLocation(self, location, reset: bool): + self.setLocation(location) + with _TTGlyphSet.pushLocation(self, location, reset) as value: + try: + yield value + finally: + self.setLocation(self.location) + + +class _TTGlyphSetVARC(_TTGlyphSet): + def __init__(self, font, location, glyphSet): + self.glyphSet = glyphSet + super().__init__(font, location, glyphSet) + self.varcTable = font["VARC"].table + + def __getitem__(self, glyphName): + varc = self.varcTable + if glyphName not in varc.Coverage.glyphs: + return self.glyphSet[glyphName] + return _TTGlyphVARC(self, glyphName) + + +class _TTGlyph(ABC): + """Glyph object that supports the Pen protocol, meaning that it has + .draw() and .drawPoints() methods that take a pen object as their only + argument. Additionally there are 'width' and 'lsb' attributes, read from + the 'hmtx' table. + + If the font contains a 'vmtx' table, there will also be 'height' and 'tsb' + attributes. + """ + + def __init__(self, glyphSet, glyphName, *, recalcBounds=True): + self.glyphSet = glyphSet + self.name = glyphName + self.recalcBounds = recalcBounds + self.width, self.lsb = glyphSet.hMetrics[glyphName] + if glyphSet.vMetrics is not None: + self.height, self.tsb = glyphSet.vMetrics[glyphName] + else: + self.height, self.tsb = None, None + if glyphSet.location and glyphSet.hvarTable is not None: + varidx = ( + glyphSet.font.getGlyphID(glyphName) + if glyphSet.hvarTable.AdvWidthMap is None + else glyphSet.hvarTable.AdvWidthMap.mapping[glyphName] + ) + self.width += glyphSet.hvarInstancer[varidx] + # TODO: VVAR/VORG + + @abstractmethod + def draw(self, pen): + """Draw the glyph onto ``pen``. See fontTools.pens.basePen for details + how that works. + """ + raise NotImplementedError + + def drawPoints(self, pen): + """Draw the glyph onto ``pen``. See fontTools.pens.pointPen for details + how that works. + """ + from fontTools.pens.pointPen import SegmentToPointPen + + self.draw(SegmentToPointPen(pen)) + + +class _TTGlyphGlyf(_TTGlyph): + def draw(self, pen): + """Draw the glyph onto ``pen``. See fontTools.pens.basePen for details + how that works. + """ + glyph, offset = self._getGlyphAndOffset() + + with self.glyphSet.pushDepth() as depth: + if depth: + offset = 0 # Offset should only apply at top-level + + glyph.draw(pen, self.glyphSet.glyfTable, offset) + + def drawPoints(self, pen): + """Draw the glyph onto ``pen``. See fontTools.pens.pointPen for details + how that works. + """ + glyph, offset = self._getGlyphAndOffset() + + with self.glyphSet.pushDepth() as depth: + if depth: + offset = 0 # Offset should only apply at top-level + + glyph.drawPoints(pen, self.glyphSet.glyfTable, offset) + + def _getGlyphAndOffset(self): + if self.glyphSet.location and self.glyphSet.gvarTable is not None: + glyph = self._getGlyphInstance() + else: + glyph = self.glyphSet.glyfTable[self.name] + + offset = self.lsb - glyph.xMin if hasattr(glyph, "xMin") else 0 + return glyph, offset + + def _getGlyphInstance(self): + from fontTools.varLib.iup import iup_delta + from fontTools.ttLib.tables._g_l_y_f import GlyphCoordinates + from fontTools.varLib.models import supportScalar + + glyphSet = self.glyphSet + glyfTable = glyphSet.glyfTable + variations = glyphSet.gvarTable.variations[self.name] + hMetrics = glyphSet.hMetrics + vMetrics = glyphSet.vMetrics + coordinates, _ = glyfTable._getCoordinatesAndControls( + self.name, hMetrics, vMetrics + ) + origCoords, endPts = None, None + for var in variations: + scalar = supportScalar(glyphSet.location, var.axes) + if not scalar: + continue + delta = var.coordinates + if None in delta: + if origCoords is None: + origCoords, control = glyfTable._getCoordinatesAndControls( + self.name, hMetrics, vMetrics + ) + endPts = ( + control[1] if control[0] >= 1 else list(range(len(control[1]))) + ) + delta = iup_delta(delta, origCoords, endPts) + coordinates += GlyphCoordinates(delta) * scalar + + glyph = copy(glyfTable[self.name]) # Shallow copy + width, lsb, height, tsb = _setCoordinates( + glyph, coordinates, glyfTable, recalcBounds=self.recalcBounds + ) + self.lsb = lsb + self.tsb = tsb + if glyphSet.hvarTable is None: + # no HVAR: let's set metrics from the phantom points + self.width = width + self.height = height + return glyph + + +class _TTGlyphCFF(_TTGlyph): + def draw(self, pen): + """Draw the glyph onto ``pen``. See fontTools.pens.basePen for details + how that works. + """ + self.glyphSet.charStrings[self.name].draw(pen, self.glyphSet.blender) + + +def _evaluateCondition(condition, fvarAxes, location, instancer): + if condition.Format == 1: + # ConditionAxisRange + axisIndex = condition.AxisIndex + axisTag = fvarAxes[axisIndex].axisTag + axisValue = location.get(axisTag, 0) + minValue = condition.FilterRangeMinValue + maxValue = condition.FilterRangeMaxValue + return minValue <= axisValue <= maxValue + elif condition.Format == 2: + # ConditionValue + value = condition.DefaultValue + value += instancer[condition.VarIdx][0] + return value > 0 + elif condition.Format == 3: + # ConditionAnd + for subcondition in condition.ConditionTable: + if not _evaluateCondition(subcondition, fvarAxes, location, instancer): + return False + return True + elif condition.Format == 4: + # ConditionOr + for subcondition in condition.ConditionTable: + if _evaluateCondition(subcondition, fvarAxes, location, instancer): + return True + return False + elif condition.Format == 5: + # ConditionNegate + return not _evaluateCondition( + condition.conditionTable, fvarAxes, location, instancer + ) + else: + return False # Unkonwn condition format + + +class _TTGlyphVARC(_TTGlyph): + def _draw(self, pen, isPointPen): + """Draw the glyph onto ``pen``. See fontTools.pens.basePen for details + how that works. + """ + from fontTools.ttLib.tables.otTables import ( + VarComponentFlags, + NO_VARIATION_INDEX, + ) + + glyphSet = self.glyphSet + varc = glyphSet.varcTable + idx = varc.Coverage.glyphs.index(self.name) + glyph = varc.VarCompositeGlyphs.VarCompositeGlyph[idx] + + from fontTools.varLib.multiVarStore import MultiVarStoreInstancer + from fontTools.varLib.varStore import VarStoreInstancer + + fvarAxes = glyphSet.font["fvar"].axes + instancer = MultiVarStoreInstancer( + varc.MultiVarStore, fvarAxes, self.glyphSet.location + ) + + for comp in glyph.components: + if comp.flags & VarComponentFlags.HAVE_CONDITION: + condition = varc.ConditionList.ConditionTable[comp.conditionIndex] + if not _evaluateCondition( + condition, fvarAxes, self.glyphSet.location, instancer + ): + continue + + location = {} + if comp.axisIndicesIndex is not None: + axisIndices = varc.AxisIndicesList.Item[comp.axisIndicesIndex] + axisValues = Vector(comp.axisValues) + if comp.axisValuesVarIndex != NO_VARIATION_INDEX: + axisValues += fi2fl(instancer[comp.axisValuesVarIndex], 14) + assert len(axisIndices) == len(axisValues), ( + len(axisIndices), + len(axisValues), + ) + location = { + fvarAxes[i].axisTag: v for i, v in zip(axisIndices, axisValues) + } + + if comp.transformVarIndex != NO_VARIATION_INDEX: + deltas = instancer[comp.transformVarIndex] + comp = deepcopy(comp) + comp.applyTransformDeltas(deltas) + transform = comp.transform + + reset = comp.flags & VarComponentFlags.RESET_UNSPECIFIED_AXES + with self.glyphSet.glyphSet.pushLocation(location, reset): + with self.glyphSet.pushLocation(location, reset): + shouldDecompose = self.name == comp.glyphName + + if not shouldDecompose: + try: + pen.addVarComponent( + comp.glyphName, transform, self.glyphSet.rawLocation + ) + except AttributeError: + shouldDecompose = True + + if shouldDecompose: + t = transform.toTransform() + compGlyphSet = ( + self.glyphSet + if comp.glyphName != self.name + else glyphSet.glyphSet + ) + g = compGlyphSet[comp.glyphName] + if isPointPen: + tPen = TransformPointPen(pen, t) + g.drawPoints(tPen) + else: + tPen = TransformPen(pen, t) + g.draw(tPen) + + def draw(self, pen): + self._draw(pen, False) + + def drawPoints(self, pen): + self._draw(pen, True) + + +def _setCoordinates(glyph, coord, glyfTable, *, recalcBounds=True): + # Handle phantom points for (left, right, top, bottom) positions. + assert len(coord) >= 4 + leftSideX = coord[-4][0] + rightSideX = coord[-3][0] + topSideY = coord[-2][1] + bottomSideY = coord[-1][1] + + for _ in range(4): + del coord[-1] + + if glyph.isComposite(): + assert len(coord) == len(glyph.components) + glyph.components = [copy(comp) for comp in glyph.components] # Shallow copy + for p, comp in zip(coord, glyph.components): + if hasattr(comp, "x"): + comp.x, comp.y = p + elif glyph.numberOfContours == 0: + assert len(coord) == 0 + else: + assert len(coord) == len(glyph.coordinates) + glyph.coordinates = coord + + if recalcBounds: + glyph.recalcBounds(glyfTable) + + horizontalAdvanceWidth = otRound(rightSideX - leftSideX) + verticalAdvanceWidth = otRound(topSideY - bottomSideY) + leftSideBearing = otRound(glyph.xMin - leftSideX) + topSideBearing = otRound(topSideY - glyph.yMax) + return ( + horizontalAdvanceWidth, + leftSideBearing, + verticalAdvanceWidth, + topSideBearing, + ) + + +class LerpGlyphSet(Mapping): + """A glyphset that interpolates between two other glyphsets. + + Factor is typically between 0 and 1. 0 means the first glyphset, + 1 means the second glyphset, and 0.5 means the average of the + two glyphsets. Other values are possible, and can be useful to + extrapolate. Defaults to 0.5. + """ + + def __init__(self, glyphset1, glyphset2, factor=0.5): + self.glyphset1 = glyphset1 + self.glyphset2 = glyphset2 + self.factor = factor + + def __getitem__(self, glyphname): + if glyphname in self.glyphset1 and glyphname in self.glyphset2: + return LerpGlyph(glyphname, self) + raise KeyError(glyphname) + + def __contains__(self, glyphname): + return glyphname in self.glyphset1 and glyphname in self.glyphset2 + + def __iter__(self): + set1 = set(self.glyphset1) + set2 = set(self.glyphset2) + return iter(set1.intersection(set2)) + + def __len__(self): + set1 = set(self.glyphset1) + set2 = set(self.glyphset2) + return len(set1.intersection(set2)) + + +class LerpGlyph: + def __init__(self, glyphname, glyphset): + self.glyphset = glyphset + self.glyphname = glyphname + + def draw(self, pen): + recording1 = DecomposingRecordingPen(self.glyphset.glyphset1) + self.glyphset.glyphset1[self.glyphname].draw(recording1) + recording2 = DecomposingRecordingPen(self.glyphset.glyphset2) + self.glyphset.glyphset2[self.glyphname].draw(recording2) + + factor = self.glyphset.factor + + replayRecording(lerpRecordings(recording1.value, recording2.value, factor), pen) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/ttVisitor.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/ttVisitor.py new file mode 100644 index 0000000000000000000000000000000000000000..54db61b1e0b1be5e2d36fd72008230de7fc35401 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/ttVisitor.py @@ -0,0 +1,32 @@ +"""Specialization of fontTools.misc.visitor to work with TTFont.""" + +from fontTools.misc.visitor import Visitor +from fontTools.ttLib import TTFont + + +class TTVisitor(Visitor): + def visitAttr(self, obj, attr, value, *args, **kwargs): + if isinstance(value, TTFont): + return False + super().visitAttr(obj, attr, value, *args, **kwargs) + + def visit(self, obj, *args, **kwargs): + if hasattr(obj, "ensureDecompiled"): + obj.ensureDecompiled(recurse=False) + super().visit(obj, *args, **kwargs) + + +@TTVisitor.register(TTFont) +def visit(visitor, font, *args, **kwargs): + # Some objects have links back to TTFont; even though we + # have a check in visitAttr to stop them from recursing + # onto TTFont, sometimes they still do, for example when + # someone overrides visitAttr. + if hasattr(visitor, "font"): + return False + + visitor.font = font + for tag in font.keys(): + visitor.visit(font[tag], *args, **kwargs) + del visitor.font + return False diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttLib/woff2.py b/.venv/lib/python3.12/site-packages/fontTools/ttLib/woff2.py new file mode 100644 index 0000000000000000000000000000000000000000..978c853863f6e4cf446431aa89370a041c256c31 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttLib/woff2.py @@ -0,0 +1,1679 @@ +from io import BytesIO +import sys +import array +import struct +from collections import OrderedDict +from fontTools.misc import sstruct +from fontTools.misc.arrayTools import calcIntBounds +from fontTools.misc.textTools import Tag, bytechr, byteord, bytesjoin, pad +from fontTools.ttLib import ( + TTFont, + TTLibError, + getTableModule, + getTableClass, + getSearchRange, +) +from fontTools.ttLib.sfnt import ( + SFNTReader, + SFNTWriter, + DirectoryEntry, + WOFFFlavorData, + sfntDirectoryFormat, + sfntDirectorySize, + SFNTDirectoryEntry, + sfntDirectoryEntrySize, + calcChecksum, +) +from fontTools.ttLib.tables import ttProgram, _g_l_y_f +import logging + +log = logging.getLogger("fontTools.ttLib.woff2") + +haveBrotli = False +try: + try: + import brotlicffi as brotli + except ImportError: + import brotli + haveBrotli = True +except ImportError: + pass + + +class WOFF2Reader(SFNTReader): + flavor = "woff2" + + def __init__(self, file, checkChecksums=0, fontNumber=-1): + if not haveBrotli: + log.error( + "The WOFF2 decoder requires the Brotli Python extension, available at: " + "https://github.com/google/brotli" + ) + raise ImportError("No module named brotli") + + self.file = file + + signature = Tag(self.file.read(4)) + if signature != b"wOF2": + raise TTLibError("Not a WOFF2 font (bad signature)") + + self.file.seek(0) + self.DirectoryEntry = WOFF2DirectoryEntry + data = self.file.read(woff2DirectorySize) + if len(data) != woff2DirectorySize: + raise TTLibError("Not a WOFF2 font (not enough data)") + sstruct.unpack(woff2DirectoryFormat, data, self) + + self.tables = OrderedDict() + offset = 0 + for i in range(self.numTables): + entry = self.DirectoryEntry() + entry.fromFile(self.file) + tag = Tag(entry.tag) + self.tables[tag] = entry + entry.offset = offset + offset += entry.length + + totalUncompressedSize = offset + compressedData = self.file.read(self.totalCompressedSize) + decompressedData = brotli.decompress(compressedData) + if len(decompressedData) != totalUncompressedSize: + raise TTLibError( + "unexpected size for decompressed font data: expected %d, found %d" + % (totalUncompressedSize, len(decompressedData)) + ) + self.transformBuffer = BytesIO(decompressedData) + + self.file.seek(0, 2) + if self.length != self.file.tell(): + raise TTLibError("reported 'length' doesn't match the actual file size") + + self.flavorData = WOFF2FlavorData(self) + + # make empty TTFont to store data while reconstructing tables + self.ttFont = TTFont(recalcBBoxes=False, recalcTimestamp=False) + + def __getitem__(self, tag): + """Fetch the raw table data. Reconstruct transformed tables.""" + entry = self.tables[Tag(tag)] + if not hasattr(entry, "data"): + if entry.transformed: + entry.data = self.reconstructTable(tag) + else: + entry.data = entry.loadData(self.transformBuffer) + return entry.data + + def reconstructTable(self, tag): + """Reconstruct table named 'tag' from transformed data.""" + entry = self.tables[Tag(tag)] + rawData = entry.loadData(self.transformBuffer) + if tag == "glyf": + # no need to pad glyph data when reconstructing + padding = self.padding if hasattr(self, "padding") else None + data = self._reconstructGlyf(rawData, padding) + elif tag == "loca": + data = self._reconstructLoca() + elif tag == "hmtx": + data = self._reconstructHmtx(rawData) + else: + raise TTLibError("transform for table '%s' is unknown" % tag) + return data + + def _reconstructGlyf(self, data, padding=None): + """Return recostructed glyf table data, and set the corresponding loca's + locations. Optionally pad glyph offsets to the specified number of bytes. + """ + self.ttFont["loca"] = WOFF2LocaTable() + glyfTable = self.ttFont["glyf"] = WOFF2GlyfTable() + glyfTable.reconstruct(data, self.ttFont) + if padding: + glyfTable.padding = padding + data = glyfTable.compile(self.ttFont) + return data + + def _reconstructLoca(self): + """Return reconstructed loca table data.""" + if "loca" not in self.ttFont: + # make sure glyf is reconstructed first + self.tables["glyf"].data = self.reconstructTable("glyf") + locaTable = self.ttFont["loca"] + data = locaTable.compile(self.ttFont) + if len(data) != self.tables["loca"].origLength: + raise TTLibError( + "reconstructed 'loca' table doesn't match original size: " + "expected %d, found %d" % (self.tables["loca"].origLength, len(data)) + ) + return data + + def _reconstructHmtx(self, data): + """Return reconstructed hmtx table data.""" + # Before reconstructing 'hmtx' table we need to parse other tables: + # 'glyf' is required for reconstructing the sidebearings from the glyphs' + # bounding box; 'hhea' is needed for the numberOfHMetrics field. + if "glyf" in self.flavorData.transformedTables: + # transformed 'glyf' table is self-contained, thus 'loca' not needed + tableDependencies = ("maxp", "hhea", "glyf") + else: + # decompiling untransformed 'glyf' requires 'loca', which requires 'head' + tableDependencies = ("maxp", "head", "hhea", "loca", "glyf") + for tag in tableDependencies: + self._decompileTable(tag) + hmtxTable = self.ttFont["hmtx"] = WOFF2HmtxTable() + hmtxTable.reconstruct(data, self.ttFont) + data = hmtxTable.compile(self.ttFont) + return data + + def _decompileTable(self, tag): + """Decompile table data and store it inside self.ttFont.""" + data = self[tag] + if self.ttFont.isLoaded(tag): + return self.ttFont[tag] + tableClass = getTableClass(tag) + table = tableClass(tag) + self.ttFont.tables[tag] = table + table.decompile(data, self.ttFont) + + +class WOFF2Writer(SFNTWriter): + flavor = "woff2" + + def __init__( + self, + file, + numTables, + sfntVersion="\000\001\000\000", + flavor=None, + flavorData=None, + ): + if not haveBrotli: + log.error( + "The WOFF2 encoder requires the Brotli Python extension, available at: " + "https://github.com/google/brotli" + ) + raise ImportError("No module named brotli") + + self.file = file + self.numTables = numTables + self.sfntVersion = Tag(sfntVersion) + self.flavorData = WOFF2FlavorData(data=flavorData) + + self.directoryFormat = woff2DirectoryFormat + self.directorySize = woff2DirectorySize + self.DirectoryEntry = WOFF2DirectoryEntry + + self.signature = Tag("wOF2") + + self.nextTableOffset = 0 + self.transformBuffer = BytesIO() + + self.tables = OrderedDict() + + # make empty TTFont to store data while normalising and transforming tables + self.ttFont = TTFont(recalcBBoxes=False, recalcTimestamp=False) + + def __setitem__(self, tag, data): + """Associate new entry named 'tag' with raw table data.""" + if tag in self.tables: + raise TTLibError("cannot rewrite '%s' table" % tag) + if tag == "DSIG": + # always drop DSIG table, since the encoding process can invalidate it + self.numTables -= 1 + return + + entry = self.DirectoryEntry() + entry.tag = Tag(tag) + entry.flags = getKnownTagIndex(entry.tag) + # WOFF2 table data are written to disk only on close(), after all tags + # have been specified + entry.data = data + + self.tables[tag] = entry + + def close(self): + """All tags must have been specified. Now write the table data and directory.""" + if len(self.tables) != self.numTables: + raise TTLibError( + "wrong number of tables; expected %d, found %d" + % (self.numTables, len(self.tables)) + ) + + if self.sfntVersion in ("\x00\x01\x00\x00", "true"): + isTrueType = True + elif self.sfntVersion == "OTTO": + isTrueType = False + else: + raise TTLibError("Not a TrueType or OpenType font (bad sfntVersion)") + + # The WOFF2 spec no longer requires the glyph offsets to be 4-byte aligned. + # However, the reference WOFF2 implementation still fails to reconstruct + # 'unpadded' glyf tables, therefore we need to 'normalise' them. + # See: + # https://github.com/khaledhosny/ots/issues/60 + # https://github.com/google/woff2/issues/15 + if ( + isTrueType + and "glyf" in self.flavorData.transformedTables + and "glyf" in self.tables + ): + self._normaliseGlyfAndLoca(padding=4) + self._setHeadTransformFlag() + + # To pass the legacy OpenType Sanitiser currently included in browsers, + # we must sort the table directory and data alphabetically by tag. + # See: + # https://github.com/google/woff2/pull/3 + # https://lists.w3.org/Archives/Public/public-webfonts-wg/2015Mar/0000.html + # + # 2023: We rely on this in _transformTables where we expect that + # "loca" comes after "glyf" table. + self.tables = OrderedDict(sorted(self.tables.items())) + + self.totalSfntSize = self._calcSFNTChecksumsLengthsAndOffsets() + + fontData = self._transformTables() + compressedFont = brotli.compress(fontData, mode=brotli.MODE_FONT) + + self.totalCompressedSize = len(compressedFont) + self.length = self._calcTotalSize() + self.majorVersion, self.minorVersion = self._getVersion() + self.reserved = 0 + + directory = self._packTableDirectory() + self.file.seek(0) + self.file.write(pad(directory + compressedFont, size=4)) + self._writeFlavorData() + + def _normaliseGlyfAndLoca(self, padding=4): + """Recompile glyf and loca tables, aligning glyph offsets to multiples of + 'padding' size. Update the head table's 'indexToLocFormat' accordingly while + compiling loca. + """ + if self.sfntVersion == "OTTO": + return + + for tag in ("maxp", "head", "loca", "glyf", "fvar"): + if tag in self.tables: + self._decompileTable(tag) + self.ttFont["glyf"].padding = padding + for tag in ("glyf", "loca"): + self._compileTable(tag) + + def _setHeadTransformFlag(self): + """Set bit 11 of 'head' table flags to indicate that the font has undergone + a lossless modifying transform. Re-compile head table data.""" + self._decompileTable("head") + self.ttFont["head"].flags |= 1 << 11 + self._compileTable("head") + + def _decompileTable(self, tag): + """Fetch table data, decompile it, and store it inside self.ttFont.""" + tag = Tag(tag) + if tag not in self.tables: + raise TTLibError("missing required table: %s" % tag) + if self.ttFont.isLoaded(tag): + return + data = self.tables[tag].data + if tag == "loca": + tableClass = WOFF2LocaTable + elif tag == "glyf": + tableClass = WOFF2GlyfTable + elif tag == "hmtx": + tableClass = WOFF2HmtxTable + else: + tableClass = getTableClass(tag) + table = tableClass(tag) + self.ttFont.tables[tag] = table + table.decompile(data, self.ttFont) + + def _compileTable(self, tag): + """Compile table and store it in its 'data' attribute.""" + self.tables[tag].data = self.ttFont[tag].compile(self.ttFont) + + def _calcSFNTChecksumsLengthsAndOffsets(self): + """Compute the 'original' SFNT checksums, lengths and offsets for checksum + adjustment calculation. Return the total size of the uncompressed font. + """ + offset = sfntDirectorySize + sfntDirectoryEntrySize * len(self.tables) + for tag, entry in self.tables.items(): + data = entry.data + entry.origOffset = offset + entry.origLength = len(data) + if tag == "head": + entry.checkSum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:]) + else: + entry.checkSum = calcChecksum(data) + offset += (entry.origLength + 3) & ~3 + return offset + + def _transformTables(self): + """Return transformed font data.""" + transformedTables = self.flavorData.transformedTables + for tag, entry in self.tables.items(): + data = None + if tag in transformedTables: + data = self.transformTable(tag) + if data is not None: + entry.transformed = True + if data is None: + if tag == "glyf": + # Currently we always sort table tags so + # 'loca' comes after 'glyf'. + transformedTables.discard("loca") + # pass-through the table data without transformation + data = entry.data + entry.transformed = False + entry.offset = self.nextTableOffset + entry.saveData(self.transformBuffer, data) + self.nextTableOffset += entry.length + self.writeMasterChecksum() + fontData = self.transformBuffer.getvalue() + return fontData + + def transformTable(self, tag): + """Return transformed table data, or None if some pre-conditions aren't + met -- in which case, the non-transformed table data will be used. + """ + if tag == "loca": + data = b"" + elif tag == "glyf": + for tag in ("maxp", "head", "loca", "glyf"): + self._decompileTable(tag) + glyfTable = self.ttFont["glyf"] + data = glyfTable.transform(self.ttFont) + elif tag == "hmtx": + if "glyf" not in self.tables: + return + for tag in ("maxp", "head", "hhea", "loca", "glyf", "hmtx"): + self._decompileTable(tag) + hmtxTable = self.ttFont["hmtx"] + data = hmtxTable.transform(self.ttFont) # can be None + else: + raise TTLibError("Transform for table '%s' is unknown" % tag) + return data + + def _calcMasterChecksum(self): + """Calculate checkSumAdjustment.""" + checksums = [] + for tag in self.tables.keys(): + checksums.append(self.tables[tag].checkSum) + + # Create a SFNT directory for checksum calculation purposes + self.searchRange, self.entrySelector, self.rangeShift = getSearchRange( + self.numTables, 16 + ) + directory = sstruct.pack(sfntDirectoryFormat, self) + tables = sorted(self.tables.items()) + for tag, entry in tables: + sfntEntry = SFNTDirectoryEntry() + sfntEntry.tag = entry.tag + sfntEntry.checkSum = entry.checkSum + sfntEntry.offset = entry.origOffset + sfntEntry.length = entry.origLength + directory = directory + sfntEntry.toString() + + directory_end = sfntDirectorySize + len(self.tables) * sfntDirectoryEntrySize + assert directory_end == len(directory) + + checksums.append(calcChecksum(directory)) + checksum = sum(checksums) & 0xFFFFFFFF + # BiboAfba! + checksumadjustment = (0xB1B0AFBA - checksum) & 0xFFFFFFFF + return checksumadjustment + + def writeMasterChecksum(self): + """Write checkSumAdjustment to the transformBuffer.""" + checksumadjustment = self._calcMasterChecksum() + self.transformBuffer.seek(self.tables["head"].offset + 8) + self.transformBuffer.write(struct.pack(">L", checksumadjustment)) + + def _calcTotalSize(self): + """Calculate total size of WOFF2 font, including any meta- and/or private data.""" + offset = self.directorySize + for entry in self.tables.values(): + offset += len(entry.toString()) + offset += self.totalCompressedSize + offset = (offset + 3) & ~3 + offset = self._calcFlavorDataOffsetsAndSize(offset) + return offset + + def _calcFlavorDataOffsetsAndSize(self, start): + """Calculate offsets and lengths for any meta- and/or private data.""" + offset = start + data = self.flavorData + if data.metaData: + self.metaOrigLength = len(data.metaData) + self.metaOffset = offset + self.compressedMetaData = brotli.compress( + data.metaData, mode=brotli.MODE_TEXT + ) + self.metaLength = len(self.compressedMetaData) + offset += self.metaLength + else: + self.metaOffset = self.metaLength = self.metaOrigLength = 0 + self.compressedMetaData = b"" + if data.privData: + # make sure private data is padded to 4-byte boundary + offset = (offset + 3) & ~3 + self.privOffset = offset + self.privLength = len(data.privData) + offset += self.privLength + else: + self.privOffset = self.privLength = 0 + return offset + + def _getVersion(self): + """Return the WOFF2 font's (majorVersion, minorVersion) tuple.""" + data = self.flavorData + if data.majorVersion is not None and data.minorVersion is not None: + return data.majorVersion, data.minorVersion + else: + # if None, return 'fontRevision' from 'head' table + if "head" in self.tables: + return struct.unpack(">HH", self.tables["head"].data[4:8]) + else: + return 0, 0 + + def _packTableDirectory(self): + """Return WOFF2 table directory data.""" + directory = sstruct.pack(self.directoryFormat, self) + for entry in self.tables.values(): + directory = directory + entry.toString() + return directory + + def _writeFlavorData(self): + """Write metadata and/or private data using appropiate padding.""" + compressedMetaData = self.compressedMetaData + privData = self.flavorData.privData + if compressedMetaData and privData: + compressedMetaData = pad(compressedMetaData, size=4) + if compressedMetaData: + self.file.seek(self.metaOffset) + assert self.file.tell() == self.metaOffset + self.file.write(compressedMetaData) + if privData: + self.file.seek(self.privOffset) + assert self.file.tell() == self.privOffset + self.file.write(privData) + + def reordersTables(self): + return True + + +# -- woff2 directory helpers and cruft + +woff2DirectoryFormat = """ + > # big endian + signature: 4s # "wOF2" + sfntVersion: 4s + length: L # total woff2 file size + numTables: H # number of tables + reserved: H # set to 0 + totalSfntSize: L # uncompressed size + totalCompressedSize: L # compressed size + majorVersion: H # major version of WOFF file + minorVersion: H # minor version of WOFF file + metaOffset: L # offset to metadata block + metaLength: L # length of compressed metadata + metaOrigLength: L # length of uncompressed metadata + privOffset: L # offset to private data block + privLength: L # length of private data block +""" + +woff2DirectorySize = sstruct.calcsize(woff2DirectoryFormat) + +woff2KnownTags = ( + "cmap", + "head", + "hhea", + "hmtx", + "maxp", + "name", + "OS/2", + "post", + "cvt ", + "fpgm", + "glyf", + "loca", + "prep", + "CFF ", + "VORG", + "EBDT", + "EBLC", + "gasp", + "hdmx", + "kern", + "LTSH", + "PCLT", + "VDMX", + "vhea", + "vmtx", + "BASE", + "GDEF", + "GPOS", + "GSUB", + "EBSC", + "JSTF", + "MATH", + "CBDT", + "CBLC", + "COLR", + "CPAL", + "SVG ", + "sbix", + "acnt", + "avar", + "bdat", + "bloc", + "bsln", + "cvar", + "fdsc", + "feat", + "fmtx", + "fvar", + "gvar", + "hsty", + "just", + "lcar", + "mort", + "morx", + "opbd", + "prop", + "trak", + "Zapf", + "Silf", + "Glat", + "Gloc", + "Feat", + "Sill", +) + +woff2FlagsFormat = """ + > # big endian + flags: B # table type and flags +""" + +woff2FlagsSize = sstruct.calcsize(woff2FlagsFormat) + +woff2UnknownTagFormat = """ + > # big endian + tag: 4s # 4-byte tag (optional) +""" + +woff2UnknownTagSize = sstruct.calcsize(woff2UnknownTagFormat) + +woff2UnknownTagIndex = 0x3F + +woff2Base128MaxSize = 5 +woff2DirectoryEntryMaxSize = ( + woff2FlagsSize + woff2UnknownTagSize + 2 * woff2Base128MaxSize +) + +woff2TransformedTableTags = ("glyf", "loca") + +woff2GlyfTableFormat = """ + > # big endian + version: H # = 0x0000 + optionFlags: H # Bit 0: we have overlapSimpleBitmap[], Bits 1-15: reserved + numGlyphs: H # Number of glyphs + indexFormat: H # Offset format for loca table + nContourStreamSize: L # Size of nContour stream + nPointsStreamSize: L # Size of nPoints stream + flagStreamSize: L # Size of flag stream + glyphStreamSize: L # Size of glyph stream + compositeStreamSize: L # Size of composite stream + bboxStreamSize: L # Comnined size of bboxBitmap and bboxStream + instructionStreamSize: L # Size of instruction stream +""" + +woff2GlyfTableFormatSize = sstruct.calcsize(woff2GlyfTableFormat) + +bboxFormat = """ + > # big endian + xMin: h + yMin: h + xMax: h + yMax: h +""" + +woff2OverlapSimpleBitmapFlag = 0x0001 + + +def getKnownTagIndex(tag): + """Return index of 'tag' in woff2KnownTags list. Return 63 if not found.""" + try: + return woff2KnownTags.index(tag) + except ValueError: + return woff2UnknownTagIndex + + +class WOFF2DirectoryEntry(DirectoryEntry): + def fromFile(self, file): + pos = file.tell() + data = file.read(woff2DirectoryEntryMaxSize) + left = self.fromString(data) + consumed = len(data) - len(left) + file.seek(pos + consumed) + + def fromString(self, data): + if len(data) < 1: + raise TTLibError("can't read table 'flags': not enough data") + dummy, data = sstruct.unpack2(woff2FlagsFormat, data, self) + if self.flags & 0x3F == 0x3F: + # if bits [0..5] of the flags byte == 63, read a 4-byte arbitrary tag value + if len(data) < woff2UnknownTagSize: + raise TTLibError("can't read table 'tag': not enough data") + dummy, data = sstruct.unpack2(woff2UnknownTagFormat, data, self) + else: + # otherwise, tag is derived from a fixed 'Known Tags' table + self.tag = woff2KnownTags[self.flags & 0x3F] + self.tag = Tag(self.tag) + self.origLength, data = unpackBase128(data) + self.length = self.origLength + if self.transformed: + self.length, data = unpackBase128(data) + if self.tag == "loca" and self.length != 0: + raise TTLibError("the transformLength of the 'loca' table must be 0") + # return left over data + return data + + def toString(self): + data = bytechr(self.flags) + if (self.flags & 0x3F) == 0x3F: + data += struct.pack(">4s", self.tag.tobytes()) + data += packBase128(self.origLength) + if self.transformed: + data += packBase128(self.length) + return data + + @property + def transformVersion(self): + """Return bits 6-7 of table entry's flags, which indicate the preprocessing + transformation version number (between 0 and 3). + """ + return self.flags >> 6 + + @transformVersion.setter + def transformVersion(self, value): + assert 0 <= value <= 3 + self.flags |= value << 6 + + @property + def transformed(self): + """Return True if the table has any transformation, else return False.""" + # For all tables in a font, except for 'glyf' and 'loca', the transformation + # version 0 indicates the null transform (where the original table data is + # passed directly to the Brotli compressor). For 'glyf' and 'loca' tables, + # transformation version 3 indicates the null transform + if self.tag in {"glyf", "loca"}: + return self.transformVersion != 3 + else: + return self.transformVersion != 0 + + @transformed.setter + def transformed(self, booleanValue): + # here we assume that a non-null transform means version 0 for 'glyf' and + # 'loca' and 1 for every other table (e.g. hmtx); but that may change as + # new transformation formats are introduced in the future (if ever). + if self.tag in {"glyf", "loca"}: + self.transformVersion = 3 if not booleanValue else 0 + else: + self.transformVersion = int(booleanValue) + + +class WOFF2LocaTable(getTableClass("loca")): + """Same as parent class. The only difference is that it attempts to preserve + the 'indexFormat' as encoded in the WOFF2 glyf table. + """ + + def __init__(self, tag=None): + self.tableTag = Tag(tag or "loca") + + def compile(self, ttFont): + try: + max_location = max(self.locations) + except AttributeError: + self.set([]) + max_location = 0 + if "glyf" in ttFont and hasattr(ttFont["glyf"], "indexFormat"): + # copile loca using the indexFormat specified in the WOFF2 glyf table + indexFormat = ttFont["glyf"].indexFormat + if indexFormat == 0: + if max_location >= 0x20000: + raise TTLibError("indexFormat is 0 but local offsets > 0x20000") + if not all(l % 2 == 0 for l in self.locations): + raise TTLibError( + "indexFormat is 0 but local offsets not multiples of 2" + ) + locations = array.array("H") + for location in self.locations: + locations.append(location // 2) + else: + locations = array.array("I", self.locations) + if sys.byteorder != "big": + locations.byteswap() + data = locations.tobytes() + else: + # use the most compact indexFormat given the current glyph offsets + data = super(WOFF2LocaTable, self).compile(ttFont) + return data + + +class WOFF2GlyfTable(getTableClass("glyf")): + """Decoder/Encoder for WOFF2 'glyf' table transform.""" + + subStreams = ( + "nContourStream", + "nPointsStream", + "flagStream", + "glyphStream", + "compositeStream", + "bboxStream", + "instructionStream", + ) + + def __init__(self, tag=None): + self.tableTag = Tag(tag or "glyf") + + def reconstruct(self, data, ttFont): + """Decompile transformed 'glyf' data.""" + inputDataSize = len(data) + + if inputDataSize < woff2GlyfTableFormatSize: + raise TTLibError("not enough 'glyf' data") + dummy, data = sstruct.unpack2(woff2GlyfTableFormat, data, self) + offset = woff2GlyfTableFormatSize + + for stream in self.subStreams: + size = getattr(self, stream + "Size") + setattr(self, stream, data[:size]) + data = data[size:] + offset += size + + hasOverlapSimpleBitmap = self.optionFlags & woff2OverlapSimpleBitmapFlag + self.overlapSimpleBitmap = None + if hasOverlapSimpleBitmap: + overlapSimpleBitmapSize = (self.numGlyphs + 7) >> 3 + self.overlapSimpleBitmap = array.array("B", data[:overlapSimpleBitmapSize]) + offset += overlapSimpleBitmapSize + + if offset != inputDataSize: + raise TTLibError( + "incorrect size of transformed 'glyf' table: expected %d, received %d bytes" + % (offset, inputDataSize) + ) + + bboxBitmapSize = ((self.numGlyphs + 31) >> 5) << 2 + bboxBitmap = self.bboxStream[:bboxBitmapSize] + self.bboxBitmap = array.array("B", bboxBitmap) + self.bboxStream = self.bboxStream[bboxBitmapSize:] + + self.nContourStream = array.array("h", self.nContourStream) + if sys.byteorder != "big": + self.nContourStream.byteswap() + assert len(self.nContourStream) == self.numGlyphs + + if "head" in ttFont: + ttFont["head"].indexToLocFormat = self.indexFormat + try: + self.glyphOrder = ttFont.getGlyphOrder() + except: + self.glyphOrder = None + if self.glyphOrder is None: + self.glyphOrder = [".notdef"] + self.glyphOrder.extend(["glyph%.5d" % i for i in range(1, self.numGlyphs)]) + else: + if len(self.glyphOrder) != self.numGlyphs: + raise TTLibError( + "incorrect glyphOrder: expected %d glyphs, found %d" + % (len(self.glyphOrder), self.numGlyphs) + ) + + glyphs = self.glyphs = {} + for glyphID, glyphName in enumerate(self.glyphOrder): + glyph = self._decodeGlyph(glyphID) + glyphs[glyphName] = glyph + + def transform(self, ttFont): + """Return transformed 'glyf' data""" + self.numGlyphs = len(self.glyphs) + assert len(self.glyphOrder) == self.numGlyphs + if "maxp" in ttFont: + ttFont["maxp"].numGlyphs = self.numGlyphs + self.indexFormat = ttFont["head"].indexToLocFormat + + for stream in self.subStreams: + setattr(self, stream, b"") + bboxBitmapSize = ((self.numGlyphs + 31) >> 5) << 2 + self.bboxBitmap = array.array("B", [0] * bboxBitmapSize) + + self.overlapSimpleBitmap = array.array("B", [0] * ((self.numGlyphs + 7) >> 3)) + for glyphID in range(self.numGlyphs): + try: + self._encodeGlyph(glyphID) + except NotImplementedError: + return None + hasOverlapSimpleBitmap = any(self.overlapSimpleBitmap) + + self.bboxStream = self.bboxBitmap.tobytes() + self.bboxStream + for stream in self.subStreams: + setattr(self, stream + "Size", len(getattr(self, stream))) + self.version = 0 + self.optionFlags = 0 + if hasOverlapSimpleBitmap: + self.optionFlags |= woff2OverlapSimpleBitmapFlag + data = sstruct.pack(woff2GlyfTableFormat, self) + data += bytesjoin([getattr(self, s) for s in self.subStreams]) + if hasOverlapSimpleBitmap: + data += self.overlapSimpleBitmap.tobytes() + return data + + def _decodeGlyph(self, glyphID): + glyph = getTableModule("glyf").Glyph() + glyph.numberOfContours = self.nContourStream[glyphID] + if glyph.numberOfContours == 0: + return glyph + elif glyph.isComposite(): + self._decodeComponents(glyph) + else: + self._decodeCoordinates(glyph) + self._decodeOverlapSimpleFlag(glyph, glyphID) + self._decodeBBox(glyphID, glyph) + return glyph + + def _decodeComponents(self, glyph): + data = self.compositeStream + glyph.components = [] + more = 1 + haveInstructions = 0 + while more: + component = getTableModule("glyf").GlyphComponent() + more, haveInstr, data = component.decompile(data, self) + haveInstructions = haveInstructions | haveInstr + glyph.components.append(component) + self.compositeStream = data + if haveInstructions: + self._decodeInstructions(glyph) + + def _decodeCoordinates(self, glyph): + data = self.nPointsStream + endPtsOfContours = [] + endPoint = -1 + for i in range(glyph.numberOfContours): + ptsOfContour, data = unpack255UShort(data) + endPoint += ptsOfContour + endPtsOfContours.append(endPoint) + glyph.endPtsOfContours = endPtsOfContours + self.nPointsStream = data + self._decodeTriplets(glyph) + self._decodeInstructions(glyph) + + def _decodeOverlapSimpleFlag(self, glyph, glyphID): + if self.overlapSimpleBitmap is None or glyph.numberOfContours <= 0: + return + byte = glyphID >> 3 + bit = glyphID & 7 + if self.overlapSimpleBitmap[byte] & (0x80 >> bit): + glyph.flags[0] |= _g_l_y_f.flagOverlapSimple + + def _decodeInstructions(self, glyph): + glyphStream = self.glyphStream + instructionStream = self.instructionStream + instructionLength, glyphStream = unpack255UShort(glyphStream) + glyph.program = ttProgram.Program() + glyph.program.fromBytecode(instructionStream[:instructionLength]) + self.glyphStream = glyphStream + self.instructionStream = instructionStream[instructionLength:] + + def _decodeBBox(self, glyphID, glyph): + haveBBox = bool(self.bboxBitmap[glyphID >> 3] & (0x80 >> (glyphID & 7))) + if glyph.isComposite() and not haveBBox: + raise TTLibError("no bbox values for composite glyph %d" % glyphID) + if haveBBox: + dummy, self.bboxStream = sstruct.unpack2(bboxFormat, self.bboxStream, glyph) + else: + glyph.recalcBounds(self) + + def _decodeTriplets(self, glyph): + def withSign(flag, baseval): + assert 0 <= baseval and baseval < 65536, "integer overflow" + return baseval if flag & 1 else -baseval + + nPoints = glyph.endPtsOfContours[-1] + 1 + flagSize = nPoints + if flagSize > len(self.flagStream): + raise TTLibError("not enough 'flagStream' data") + flagsData = self.flagStream[:flagSize] + self.flagStream = self.flagStream[flagSize:] + flags = array.array("B", flagsData) + + triplets = array.array("B", self.glyphStream) + nTriplets = len(triplets) + assert nPoints <= nTriplets + + x = 0 + y = 0 + glyph.coordinates = getTableModule("glyf").GlyphCoordinates.zeros(nPoints) + glyph.flags = array.array("B") + tripletIndex = 0 + for i in range(nPoints): + flag = flags[i] + onCurve = not bool(flag >> 7) + flag &= 0x7F + if flag < 84: + nBytes = 1 + elif flag < 120: + nBytes = 2 + elif flag < 124: + nBytes = 3 + else: + nBytes = 4 + assert (tripletIndex + nBytes) <= nTriplets + if flag < 10: + dx = 0 + dy = withSign(flag, ((flag & 14) << 7) + triplets[tripletIndex]) + elif flag < 20: + dx = withSign(flag, (((flag - 10) & 14) << 7) + triplets[tripletIndex]) + dy = 0 + elif flag < 84: + b0 = flag - 20 + b1 = triplets[tripletIndex] + dx = withSign(flag, 1 + (b0 & 0x30) + (b1 >> 4)) + dy = withSign(flag >> 1, 1 + ((b0 & 0x0C) << 2) + (b1 & 0x0F)) + elif flag < 120: + b0 = flag - 84 + dx = withSign(flag, 1 + ((b0 // 12) << 8) + triplets[tripletIndex]) + dy = withSign( + flag >> 1, 1 + (((b0 % 12) >> 2) << 8) + triplets[tripletIndex + 1] + ) + elif flag < 124: + b2 = triplets[tripletIndex + 1] + dx = withSign(flag, (triplets[tripletIndex] << 4) + (b2 >> 4)) + dy = withSign( + flag >> 1, ((b2 & 0x0F) << 8) + triplets[tripletIndex + 2] + ) + else: + dx = withSign( + flag, (triplets[tripletIndex] << 8) + triplets[tripletIndex + 1] + ) + dy = withSign( + flag >> 1, + (triplets[tripletIndex + 2] << 8) + triplets[tripletIndex + 3], + ) + tripletIndex += nBytes + x += dx + y += dy + glyph.coordinates[i] = (x, y) + glyph.flags.append(int(onCurve)) + bytesConsumed = tripletIndex + self.glyphStream = self.glyphStream[bytesConsumed:] + + def _encodeGlyph(self, glyphID): + glyphName = self.getGlyphName(glyphID) + glyph = self[glyphName] + self.nContourStream += struct.pack(">h", glyph.numberOfContours) + if glyph.numberOfContours == 0: + return + elif glyph.isComposite(): + self._encodeComponents(glyph) + else: + self._encodeCoordinates(glyph) + self._encodeOverlapSimpleFlag(glyph, glyphID) + self._encodeBBox(glyphID, glyph) + + def _encodeComponents(self, glyph): + lastcomponent = len(glyph.components) - 1 + more = 1 + haveInstructions = 0 + for i, component in enumerate(glyph.components): + if i == lastcomponent: + haveInstructions = hasattr(glyph, "program") + more = 0 + self.compositeStream += component.compile(more, haveInstructions, self) + if haveInstructions: + self._encodeInstructions(glyph) + + def _encodeCoordinates(self, glyph): + lastEndPoint = -1 + if _g_l_y_f.flagCubic in glyph.flags: + raise NotImplementedError + for endPoint in glyph.endPtsOfContours: + ptsOfContour = endPoint - lastEndPoint + self.nPointsStream += pack255UShort(ptsOfContour) + lastEndPoint = endPoint + self._encodeTriplets(glyph) + self._encodeInstructions(glyph) + + def _encodeOverlapSimpleFlag(self, glyph, glyphID): + if glyph.numberOfContours <= 0: + return + if glyph.flags[0] & _g_l_y_f.flagOverlapSimple: + byte = glyphID >> 3 + bit = glyphID & 7 + self.overlapSimpleBitmap[byte] |= 0x80 >> bit + + def _encodeInstructions(self, glyph): + instructions = glyph.program.getBytecode() + self.glyphStream += pack255UShort(len(instructions)) + self.instructionStream += instructions + + def _encodeBBox(self, glyphID, glyph): + assert glyph.numberOfContours != 0, "empty glyph has no bbox" + if not glyph.isComposite(): + # for simple glyphs, compare the encoded bounding box info with the calculated + # values, and if they match omit the bounding box info + currentBBox = glyph.xMin, glyph.yMin, glyph.xMax, glyph.yMax + calculatedBBox = calcIntBounds(glyph.coordinates) + if currentBBox == calculatedBBox: + return + self.bboxBitmap[glyphID >> 3] |= 0x80 >> (glyphID & 7) + self.bboxStream += sstruct.pack(bboxFormat, glyph) + + def _encodeTriplets(self, glyph): + assert len(glyph.coordinates) == len(glyph.flags) + coordinates = glyph.coordinates.copy() + coordinates.absoluteToRelative() + + flags = array.array("B") + triplets = array.array("B") + for i, (x, y) in enumerate(coordinates): + onCurve = glyph.flags[i] & _g_l_y_f.flagOnCurve + absX = abs(x) + absY = abs(y) + onCurveBit = 0 if onCurve else 128 + xSignBit = 0 if (x < 0) else 1 + ySignBit = 0 if (y < 0) else 1 + xySignBits = xSignBit + 2 * ySignBit + + if x == 0 and absY < 1280: + flags.append(onCurveBit + ((absY & 0xF00) >> 7) + ySignBit) + triplets.append(absY & 0xFF) + elif y == 0 and absX < 1280: + flags.append(onCurveBit + 10 + ((absX & 0xF00) >> 7) + xSignBit) + triplets.append(absX & 0xFF) + elif absX < 65 and absY < 65: + flags.append( + onCurveBit + + 20 + + ((absX - 1) & 0x30) + + (((absY - 1) & 0x30) >> 2) + + xySignBits + ) + triplets.append((((absX - 1) & 0xF) << 4) | ((absY - 1) & 0xF)) + elif absX < 769 and absY < 769: + flags.append( + onCurveBit + + 84 + + 12 * (((absX - 1) & 0x300) >> 8) + + (((absY - 1) & 0x300) >> 6) + + xySignBits + ) + triplets.append((absX - 1) & 0xFF) + triplets.append((absY - 1) & 0xFF) + elif absX < 4096 and absY < 4096: + flags.append(onCurveBit + 120 + xySignBits) + triplets.append(absX >> 4) + triplets.append(((absX & 0xF) << 4) | (absY >> 8)) + triplets.append(absY & 0xFF) + else: + flags.append(onCurveBit + 124 + xySignBits) + triplets.append(absX >> 8) + triplets.append(absX & 0xFF) + triplets.append(absY >> 8) + triplets.append(absY & 0xFF) + + self.flagStream += flags.tobytes() + self.glyphStream += triplets.tobytes() + + +class WOFF2HmtxTable(getTableClass("hmtx")): + def __init__(self, tag=None): + self.tableTag = Tag(tag or "hmtx") + + def reconstruct(self, data, ttFont): + (flags,) = struct.unpack(">B", data[:1]) + data = data[1:] + if flags & 0b11111100 != 0: + raise TTLibError("Bits 2-7 of '%s' flags are reserved" % self.tableTag) + + # When bit 0 is _not_ set, the lsb[] array is present + hasLsbArray = flags & 1 == 0 + # When bit 1 is _not_ set, the leftSideBearing[] array is present + hasLeftSideBearingArray = flags & 2 == 0 + if hasLsbArray and hasLeftSideBearingArray: + raise TTLibError( + "either bits 0 or 1 (or both) must set in transformed '%s' flags" + % self.tableTag + ) + + glyfTable = ttFont["glyf"] + headerTable = ttFont["hhea"] + glyphOrder = glyfTable.glyphOrder + numGlyphs = len(glyphOrder) + numberOfHMetrics = min(int(headerTable.numberOfHMetrics), numGlyphs) + + assert len(data) >= 2 * numberOfHMetrics + advanceWidthArray = array.array("H", data[: 2 * numberOfHMetrics]) + if sys.byteorder != "big": + advanceWidthArray.byteswap() + data = data[2 * numberOfHMetrics :] + + if hasLsbArray: + assert len(data) >= 2 * numberOfHMetrics + lsbArray = array.array("h", data[: 2 * numberOfHMetrics]) + if sys.byteorder != "big": + lsbArray.byteswap() + data = data[2 * numberOfHMetrics :] + else: + # compute (proportional) glyphs' lsb from their xMin + lsbArray = array.array("h") + for i, glyphName in enumerate(glyphOrder): + if i >= numberOfHMetrics: + break + glyph = glyfTable[glyphName] + xMin = getattr(glyph, "xMin", 0) + lsbArray.append(xMin) + + numberOfSideBearings = numGlyphs - numberOfHMetrics + if hasLeftSideBearingArray: + assert len(data) >= 2 * numberOfSideBearings + leftSideBearingArray = array.array("h", data[: 2 * numberOfSideBearings]) + if sys.byteorder != "big": + leftSideBearingArray.byteswap() + data = data[2 * numberOfSideBearings :] + else: + # compute (monospaced) glyphs' leftSideBearing from their xMin + leftSideBearingArray = array.array("h") + for i, glyphName in enumerate(glyphOrder): + if i < numberOfHMetrics: + continue + glyph = glyfTable[glyphName] + xMin = getattr(glyph, "xMin", 0) + leftSideBearingArray.append(xMin) + + if data: + raise TTLibError("too much '%s' table data" % self.tableTag) + + self.metrics = {} + for i in range(numberOfHMetrics): + glyphName = glyphOrder[i] + advanceWidth, lsb = advanceWidthArray[i], lsbArray[i] + self.metrics[glyphName] = (advanceWidth, lsb) + lastAdvance = advanceWidthArray[-1] + for i in range(numberOfSideBearings): + glyphName = glyphOrder[i + numberOfHMetrics] + self.metrics[glyphName] = (lastAdvance, leftSideBearingArray[i]) + + def transform(self, ttFont): + glyphOrder = ttFont.getGlyphOrder() + glyf = ttFont["glyf"] + hhea = ttFont["hhea"] + numberOfHMetrics = hhea.numberOfHMetrics + + # check if any of the proportional glyphs has left sidebearings that + # differ from their xMin bounding box values. + hasLsbArray = False + for i in range(numberOfHMetrics): + glyphName = glyphOrder[i] + lsb = self.metrics[glyphName][1] + if lsb != getattr(glyf[glyphName], "xMin", 0): + hasLsbArray = True + break + + # do the same for the monospaced glyphs (if any) at the end of hmtx table + hasLeftSideBearingArray = False + for i in range(numberOfHMetrics, len(glyphOrder)): + glyphName = glyphOrder[i] + lsb = self.metrics[glyphName][1] + if lsb != getattr(glyf[glyphName], "xMin", 0): + hasLeftSideBearingArray = True + break + + # if we need to encode both sidebearings arrays, then no transformation is + # applicable, and we must use the untransformed hmtx data + if hasLsbArray and hasLeftSideBearingArray: + return + + # set bit 0 and 1 when the respective arrays are _not_ present + flags = 0 + if not hasLsbArray: + flags |= 1 << 0 + if not hasLeftSideBearingArray: + flags |= 1 << 1 + + data = struct.pack(">B", flags) + + advanceWidthArray = array.array( + "H", + [ + self.metrics[glyphName][0] + for i, glyphName in enumerate(glyphOrder) + if i < numberOfHMetrics + ], + ) + if sys.byteorder != "big": + advanceWidthArray.byteswap() + data += advanceWidthArray.tobytes() + + if hasLsbArray: + lsbArray = array.array( + "h", + [ + self.metrics[glyphName][1] + for i, glyphName in enumerate(glyphOrder) + if i < numberOfHMetrics + ], + ) + if sys.byteorder != "big": + lsbArray.byteswap() + data += lsbArray.tobytes() + + if hasLeftSideBearingArray: + leftSideBearingArray = array.array( + "h", + [ + self.metrics[glyphOrder[i]][1] + for i in range(numberOfHMetrics, len(glyphOrder)) + ], + ) + if sys.byteorder != "big": + leftSideBearingArray.byteswap() + data += leftSideBearingArray.tobytes() + + return data + + +class WOFF2FlavorData(WOFFFlavorData): + Flavor = "woff2" + + def __init__(self, reader=None, data=None, transformedTables=None): + """Data class that holds the WOFF2 header major/minor version, any + metadata or private data (as bytes strings), and the set of + table tags that have transformations applied (if reader is not None), + or will have once the WOFF2 font is compiled. + + Args: + reader: an SFNTReader (or subclass) object to read flavor data from. + data: another WOFFFlavorData object to initialise data from. + transformedTables: set of strings containing table tags to be transformed. + + Raises: + ImportError if the brotli module is not installed. + + NOTE: The 'reader' argument, on the one hand, and the 'data' and + 'transformedTables' arguments, on the other hand, are mutually exclusive. + """ + if not haveBrotli: + raise ImportError("No module named brotli") + + if reader is not None: + if data is not None: + raise TypeError("'reader' and 'data' arguments are mutually exclusive") + if transformedTables is not None: + raise TypeError( + "'reader' and 'transformedTables' arguments are mutually exclusive" + ) + + if transformedTables is not None and ( + "glyf" in transformedTables + and "loca" not in transformedTables + or "loca" in transformedTables + and "glyf" not in transformedTables + ): + raise ValueError("'glyf' and 'loca' must be transformed (or not) together") + super(WOFF2FlavorData, self).__init__(reader=reader) + if reader: + transformedTables = [ + tag for tag, entry in reader.tables.items() if entry.transformed + ] + elif data: + self.majorVersion = data.majorVersion + self.majorVersion = data.minorVersion + self.metaData = data.metaData + self.privData = data.privData + if transformedTables is None and hasattr(data, "transformedTables"): + transformedTables = data.transformedTables + + if transformedTables is None: + transformedTables = woff2TransformedTableTags + + self.transformedTables = set(transformedTables) + + def _decompress(self, rawData): + return brotli.decompress(rawData) + + +def unpackBase128(data): + r"""Read one to five bytes from UIntBase128-encoded input string, and return + a tuple containing the decoded integer plus any leftover data. + + >>> unpackBase128(b'\x3f\x00\x00') == (63, b"\x00\x00") + True + >>> unpackBase128(b'\x8f\xff\xff\xff\x7f')[0] == 4294967295 + True + >>> unpackBase128(b'\x80\x80\x3f') # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + File "<stdin>", line 1, in ? + TTLibError: UIntBase128 value must not start with leading zeros + >>> unpackBase128(b'\x8f\xff\xff\xff\xff\x7f')[0] # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + File "<stdin>", line 1, in ? + TTLibError: UIntBase128-encoded sequence is longer than 5 bytes + >>> unpackBase128(b'\x90\x80\x80\x80\x00')[0] # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + File "<stdin>", line 1, in ? + TTLibError: UIntBase128 value exceeds 2**32-1 + """ + if len(data) == 0: + raise TTLibError("not enough data to unpack UIntBase128") + result = 0 + if byteord(data[0]) == 0x80: + # font must be rejected if UIntBase128 value starts with 0x80 + raise TTLibError("UIntBase128 value must not start with leading zeros") + for i in range(woff2Base128MaxSize): + if len(data) == 0: + raise TTLibError("not enough data to unpack UIntBase128") + code = byteord(data[0]) + data = data[1:] + # if any of the top seven bits are set then we're about to overflow + if result & 0xFE000000: + raise TTLibError("UIntBase128 value exceeds 2**32-1") + # set current value = old value times 128 bitwise-or (byte bitwise-and 127) + result = (result << 7) | (code & 0x7F) + # repeat until the most significant bit of byte is false + if (code & 0x80) == 0: + # return result plus left over data + return result, data + # make sure not to exceed the size bound + raise TTLibError("UIntBase128-encoded sequence is longer than 5 bytes") + + +def base128Size(n): + """Return the length in bytes of a UIntBase128-encoded sequence with value n. + + >>> base128Size(0) + 1 + >>> base128Size(24567) + 3 + >>> base128Size(2**32-1) + 5 + """ + assert n >= 0 + size = 1 + while n >= 128: + size += 1 + n >>= 7 + return size + + +def packBase128(n): + r"""Encode unsigned integer in range 0 to 2**32-1 (inclusive) to a string of + bytes using UIntBase128 variable-length encoding. Produce the shortest possible + encoding. + + >>> packBase128(63) == b"\x3f" + True + >>> packBase128(2**32-1) == b'\x8f\xff\xff\xff\x7f' + True + """ + if n < 0 or n >= 2**32: + raise TTLibError("UIntBase128 format requires 0 <= integer <= 2**32-1") + data = b"" + size = base128Size(n) + for i in range(size): + b = (n >> (7 * (size - i - 1))) & 0x7F + if i < size - 1: + b |= 0x80 + data += struct.pack("B", b) + return data + + +def unpack255UShort(data): + """Read one to three bytes from 255UInt16-encoded input string, and return a + tuple containing the decoded integer plus any leftover data. + + >>> unpack255UShort(bytechr(252))[0] + 252 + + Note that some numbers (e.g. 506) can have multiple encodings: + >>> unpack255UShort(struct.pack("BB", 254, 0))[0] + 506 + >>> unpack255UShort(struct.pack("BB", 255, 253))[0] + 506 + >>> unpack255UShort(struct.pack("BBB", 253, 1, 250))[0] + 506 + """ + code = byteord(data[:1]) + data = data[1:] + if code == 253: + # read two more bytes as an unsigned short + if len(data) < 2: + raise TTLibError("not enough data to unpack 255UInt16") + (result,) = struct.unpack(">H", data[:2]) + data = data[2:] + elif code == 254: + # read another byte, plus 253 * 2 + if len(data) == 0: + raise TTLibError("not enough data to unpack 255UInt16") + result = byteord(data[:1]) + result += 506 + data = data[1:] + elif code == 255: + # read another byte, plus 253 + if len(data) == 0: + raise TTLibError("not enough data to unpack 255UInt16") + result = byteord(data[:1]) + result += 253 + data = data[1:] + else: + # leave as is if lower than 253 + result = code + # return result plus left over data + return result, data + + +def pack255UShort(value): + r"""Encode unsigned integer in range 0 to 65535 (inclusive) to a bytestring + using 255UInt16 variable-length encoding. + + >>> pack255UShort(252) == b'\xfc' + True + >>> pack255UShort(506) == b'\xfe\x00' + True + >>> pack255UShort(762) == b'\xfd\x02\xfa' + True + """ + if value < 0 or value > 0xFFFF: + raise TTLibError("255UInt16 format requires 0 <= integer <= 65535") + if value < 253: + return struct.pack(">B", value) + elif value < 506: + return struct.pack(">BB", 255, value - 253) + elif value < 762: + return struct.pack(">BB", 254, value - 506) + else: + return struct.pack(">BH", 253, value) + + +def compress(input_file, output_file, transform_tables=None): + """Compress OpenType font to WOFF2. + + Args: + input_file: a file path, file or file-like object (open in binary mode) + containing an OpenType font (either CFF- or TrueType-flavored). + output_file: a file path, file or file-like object where to save the + compressed WOFF2 font. + transform_tables: Optional[Iterable[str]]: a set of table tags for which + to enable preprocessing transformations. By default, only 'glyf' + and 'loca' tables are transformed. An empty set means disable all + transformations. + """ + log.info("Processing %s => %s" % (input_file, output_file)) + + font = TTFont(input_file, recalcBBoxes=False, recalcTimestamp=False) + font.flavor = "woff2" + + if transform_tables is not None: + font.flavorData = WOFF2FlavorData( + data=font.flavorData, transformedTables=transform_tables + ) + + font.save(output_file, reorderTables=False) + + +def decompress(input_file, output_file): + """Decompress WOFF2 font to OpenType font. + + Args: + input_file: a file path, file or file-like object (open in binary mode) + containing a compressed WOFF2 font. + output_file: a file path, file or file-like object where to save the + decompressed OpenType font. + """ + log.info("Processing %s => %s" % (input_file, output_file)) + + font = TTFont(input_file, recalcBBoxes=False, recalcTimestamp=False) + font.flavor = None + font.flavorData = None + font.save(output_file, reorderTables=True) + + +def main(args=None): + """Compress and decompress WOFF2 fonts""" + import argparse + from fontTools import configLogger + from fontTools.ttx import makeOutputFileName + + class _HelpAction(argparse._HelpAction): + def __call__(self, parser, namespace, values, option_string=None): + subparsers_actions = [ + action + for action in parser._actions + if isinstance(action, argparse._SubParsersAction) + ] + for subparsers_action in subparsers_actions: + for choice, subparser in subparsers_action.choices.items(): + print(subparser.format_help()) + parser.exit() + + class _NoGlyfTransformAction(argparse.Action): + def __call__(self, parser, namespace, values, option_string=None): + namespace.transform_tables.difference_update({"glyf", "loca"}) + + class _HmtxTransformAction(argparse.Action): + def __call__(self, parser, namespace, values, option_string=None): + namespace.transform_tables.add("hmtx") + + parser = argparse.ArgumentParser( + prog="fonttools ttLib.woff2", description=main.__doc__, add_help=False + ) + + parser.add_argument( + "-h", "--help", action=_HelpAction, help="show this help message and exit" + ) + + parser_group = parser.add_subparsers(title="sub-commands") + parser_compress = parser_group.add_parser( + "compress", description="Compress a TTF or OTF font to WOFF2" + ) + parser_decompress = parser_group.add_parser( + "decompress", description="Decompress a WOFF2 font to OTF" + ) + + for subparser in (parser_compress, parser_decompress): + group = subparser.add_mutually_exclusive_group(required=False) + group.add_argument( + "-v", + "--verbose", + action="store_true", + help="print more messages to console", + ) + group.add_argument( + "-q", + "--quiet", + action="store_true", + help="do not print messages to console", + ) + + parser_compress.add_argument( + "input_file", + metavar="INPUT", + help="the input OpenType font (.ttf or .otf)", + ) + parser_decompress.add_argument( + "input_file", + metavar="INPUT", + help="the input WOFF2 font", + ) + + parser_compress.add_argument( + "-o", + "--output-file", + metavar="OUTPUT", + help="the output WOFF2 font", + ) + parser_decompress.add_argument( + "-o", + "--output-file", + metavar="OUTPUT", + help="the output OpenType font", + ) + + transform_group = parser_compress.add_argument_group() + transform_group.add_argument( + "--no-glyf-transform", + dest="transform_tables", + nargs=0, + action=_NoGlyfTransformAction, + help="Do not transform glyf (and loca) tables", + ) + transform_group.add_argument( + "--hmtx-transform", + dest="transform_tables", + nargs=0, + action=_HmtxTransformAction, + help="Enable optional transformation for 'hmtx' table", + ) + + parser_compress.set_defaults( + subcommand=compress, + transform_tables={"glyf", "loca"}, + ) + parser_decompress.set_defaults(subcommand=decompress) + + options = vars(parser.parse_args(args)) + + subcommand = options.pop("subcommand", None) + if not subcommand: + parser.print_help() + return + + quiet = options.pop("quiet") + verbose = options.pop("verbose") + configLogger( + level=("ERROR" if quiet else "DEBUG" if verbose else "INFO"), + ) + + if not options["output_file"]: + if subcommand is compress: + extension = ".woff2" + elif subcommand is decompress: + # choose .ttf/.otf file extension depending on sfntVersion + with open(options["input_file"], "rb") as f: + f.seek(4) # skip 'wOF2' signature + sfntVersion = f.read(4) + assert len(sfntVersion) == 4, "not enough data" + extension = ".otf" if sfntVersion == b"OTTO" else ".ttf" + else: + raise AssertionError(subcommand) + options["output_file"] = makeOutputFileName( + options["input_file"], outputDir=None, extension=extension + ) + + try: + subcommand(**options) + except TTLibError as e: + parser.error(e) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ttx.py b/.venv/lib/python3.12/site-packages/fontTools/ttx.py new file mode 100644 index 0000000000000000000000000000000000000000..f645f6b9d17089c01235233ba3e3e68b49171c57 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ttx.py @@ -0,0 +1,478 @@ +"""\ +usage: ttx [options] inputfile1 [... inputfileN] + +TTX -- From OpenType To XML And Back + +If an input file is a TrueType or OpenType font file, it will be +decompiled to a TTX file (an XML-based text format). +If an input file is a TTX file, it will be compiled to whatever +format the data is in, a TrueType or OpenType/CFF font file. +A special input value of - means read from the standard input. + +Output files are created so they are unique: an existing file is +never overwritten. + +General options +=============== + +-h Help print this message. +--version show version and exit. +-d <outputfolder> Specify a directory where the output files are + to be created. +-o <outputfile> Specify a file to write the output to. A special + value of - would use the standard output. +-f Overwrite existing output file(s), ie. don't append + numbers. +-v Verbose: more messages will be written to stdout + about what is being done. +-q Quiet: No messages will be written to stdout about + what is being done. +-a allow virtual glyphs ID's on compile or decompile. + +Dump options +============ + +-l List table info: instead of dumping to a TTX file, list + some minimal info about each table. +-t <table> Specify a table to dump. Multiple -t options + are allowed. When no -t option is specified, all tables + will be dumped. +-x <table> Specify a table to exclude from the dump. Multiple + -x options are allowed. -t and -x are mutually exclusive. +-s Split tables: save the TTX data into separate TTX files per + table and write one small TTX file that contains references + to the individual table dumps. This file can be used as + input to ttx, as long as the table files are in the + same directory. +-g Split glyf table: Save the glyf data into separate TTX files + per glyph and write a small TTX for the glyf table which + contains references to the individual TTGlyph elements. + NOTE: specifying -g implies -s (no need for -s together + with -g) +-i Do NOT disassemble TT instructions: when this option is + given, all TrueType programs (glyph programs, the font + program and the pre-program) will be written to the TTX + file as hex data instead of assembly. This saves some time + and makes the TTX file smaller. +-z <format> Specify a bitmap data export option for EBDT: + {'raw', 'row', 'bitwise', 'extfile'} or for the CBDT: + {'raw', 'extfile'} Each option does one of the following: + + -z raw + export the bitmap data as a hex dump + -z row + export each row as hex data + -z bitwise + export each row as binary in an ASCII art style + -z extfile + export the data as external files with XML references + + If no export format is specified 'raw' format is used. +-e Don't ignore decompilation errors, but show a full traceback + and abort. +-y <number> Select font number for TrueType Collection (.ttc/.otc), + starting from 0. +--unicodedata <UnicodeData.txt> + Use custom database file to write character names in the + comments of the cmap TTX output. +--newline <value> + Control how line endings are written in the XML file. It + can be 'LF', 'CR', or 'CRLF'. If not specified, the + default platform-specific line endings are used. + +Compile options +=============== + +-m Merge with TrueType-input-file: specify a TrueType or + OpenType font file to be merged with the TTX file. This + option is only valid when at most one TTX file is specified. +-b Don't recalc glyph bounding boxes: use the values in the + TTX file as-is. +--recalc-timestamp + Set font 'modified' timestamp to current time. + By default, the modification time of the TTX file will be + used. +--no-recalc-timestamp + Keep the original font 'modified' timestamp. +--flavor <type> + Specify flavor of output font file. May be 'woff' or 'woff2'. + Note that WOFF2 requires the Brotli Python extension, + available at https://github.com/google/brotli +--with-zopfli + Use Zopfli instead of Zlib to compress WOFF. The Python + extension is available at https://pypi.python.org/pypi/zopfli +--optimize-font-speed + Enable optimizations that prioritize speed over file size. + This mainly affects how glyf t able and gvar / VARC tables are + compiled. The produced fonts will be larger, but rendering + performance will be improved with HarfBuzz and other text + layout engines. +""" + +from fontTools.ttLib import OPTIMIZE_FONT_SPEED, TTFont, TTLibError +from fontTools.misc.macCreatorType import getMacCreatorAndType +from fontTools.unicode import setUnicodeData +from fontTools.misc.textTools import Tag, tostr +from fontTools.misc.timeTools import timestampSinceEpoch +from fontTools.misc.loggingTools import Timer +from fontTools.misc.cliTools import makeOutputFileName +import os +import sys +import getopt +import re +import logging + +log = logging.getLogger("fontTools.ttx") + +opentypeheaderRE = re.compile("""sfntVersion=['"]OTTO["']""") + + +class Options(object): + listTables = False + outputDir = None + outputFile = None + overWrite = False + verbose = False + quiet = False + splitTables = False + splitGlyphs = False + disassembleInstructions = True + mergeFile = None + recalcBBoxes = True + ignoreDecompileErrors = True + bitmapGlyphDataFormat = "raw" + unicodedata = None + newlinestr = "\n" + recalcTimestamp = None + flavor = None + useZopfli = False + optimizeFontSpeed = False + + def __init__(self, rawOptions, numFiles): + self.onlyTables = [] + self.skipTables = [] + self.fontNumber = -1 + for option, value in rawOptions: + # general options + if option == "-h": + print(__doc__) + sys.exit(0) + elif option == "--version": + from fontTools import version + + print(version) + sys.exit(0) + elif option == "-d": + if not os.path.isdir(value): + raise getopt.GetoptError( + "The -d option value must be an existing directory" + ) + self.outputDir = value + elif option == "-o": + self.outputFile = value + elif option == "-f": + self.overWrite = True + elif option == "-v": + self.verbose = True + elif option == "-q": + self.quiet = True + # dump options + elif option == "-l": + self.listTables = True + elif option == "-t": + # pad with space if table tag length is less than 4 + value = value.ljust(4) + self.onlyTables.append(value) + elif option == "-x": + # pad with space if table tag length is less than 4 + value = value.ljust(4) + self.skipTables.append(value) + elif option == "-s": + self.splitTables = True + elif option == "-g": + # -g implies (and forces) splitTables + self.splitGlyphs = True + self.splitTables = True + elif option == "-i": + self.disassembleInstructions = False + elif option == "-z": + validOptions = ("raw", "row", "bitwise", "extfile") + if value not in validOptions: + raise getopt.GetoptError( + "-z does not allow %s as a format. Use %s" + % (option, validOptions) + ) + self.bitmapGlyphDataFormat = value + elif option == "-y": + self.fontNumber = int(value) + # compile options + elif option == "-m": + self.mergeFile = value + elif option == "-b": + self.recalcBBoxes = False + elif option == "-e": + self.ignoreDecompileErrors = False + elif option == "--unicodedata": + self.unicodedata = value + elif option == "--newline": + validOptions = ("LF", "CR", "CRLF") + if value == "LF": + self.newlinestr = "\n" + elif value == "CR": + self.newlinestr = "\r" + elif value == "CRLF": + self.newlinestr = "\r\n" + else: + raise getopt.GetoptError( + "Invalid choice for --newline: %r (choose from %s)" + % (value, ", ".join(map(repr, validOptions))) + ) + elif option == "--recalc-timestamp": + self.recalcTimestamp = True + elif option == "--no-recalc-timestamp": + self.recalcTimestamp = False + elif option == "--flavor": + self.flavor = value + elif option == "--with-zopfli": + self.useZopfli = True + elif option == "--optimize-font-speed": + self.optimizeFontSpeed = True + if self.verbose and self.quiet: + raise getopt.GetoptError("-q and -v options are mutually exclusive") + if self.verbose: + self.logLevel = logging.DEBUG + elif self.quiet: + self.logLevel = logging.WARNING + else: + self.logLevel = logging.INFO + if self.mergeFile and self.flavor: + raise getopt.GetoptError("-m and --flavor options are mutually exclusive") + if self.onlyTables and self.skipTables: + raise getopt.GetoptError("-t and -x options are mutually exclusive") + if self.mergeFile and numFiles > 1: + raise getopt.GetoptError( + "Must specify exactly one TTX source file when using -m" + ) + if self.flavor != "woff" and self.useZopfli: + raise getopt.GetoptError("--with-zopfli option requires --flavor 'woff'") + + +def ttList(input, output, options): + ttf = TTFont(input, fontNumber=options.fontNumber, lazy=True) + reader = ttf.reader + tags = sorted(reader.keys()) + print('Listing table info for "%s":' % input) + format = " %4s %10s %8s %8s" + print(format % ("tag ", " checksum", " length", " offset")) + print(format % ("----", "----------", "--------", "--------")) + for tag in tags: + entry = reader.tables[tag] + if ttf.flavor == "woff2": + # WOFF2 doesn't store table checksums, so they must be calculated + from fontTools.ttLib.sfnt import calcChecksum + + data = entry.loadData(reader.transformBuffer) + checkSum = calcChecksum(data) + else: + checkSum = int(entry.checkSum) + if checkSum < 0: + checkSum = checkSum + 0x100000000 + checksum = "0x%08X" % checkSum + print(format % (tag, checksum, entry.length, entry.offset)) + print() + ttf.close() + + +@Timer(log, "Done dumping TTX in %(time).3f seconds") +def ttDump(input, output, options): + input_name = input + if input == "-": + input, input_name = sys.stdin.buffer, sys.stdin.name + output_name = output + if output == "-": + output, output_name = sys.stdout, sys.stdout.name + log.info('Dumping "%s" to "%s"...', input_name, output_name) + if options.unicodedata: + setUnicodeData(options.unicodedata) + ttf = TTFont( + input, + 0, + ignoreDecompileErrors=options.ignoreDecompileErrors, + fontNumber=options.fontNumber, + ) + ttf.saveXML( + output, + tables=options.onlyTables, + skipTables=options.skipTables, + splitTables=options.splitTables, + splitGlyphs=options.splitGlyphs, + disassembleInstructions=options.disassembleInstructions, + bitmapGlyphDataFormat=options.bitmapGlyphDataFormat, + newlinestr=options.newlinestr, + ) + ttf.close() + + +@Timer(log, "Done compiling TTX in %(time).3f seconds") +def ttCompile(input, output, options): + input_name = input + if input == "-": + input, input_name = sys.stdin, sys.stdin.name + output_name = output + if output == "-": + output, output_name = sys.stdout.buffer, sys.stdout.name + log.info('Compiling "%s" to "%s"...' % (input_name, output)) + if options.useZopfli: + from fontTools.ttLib import sfnt + + sfnt.USE_ZOPFLI = True + ttf = TTFont( + options.mergeFile, + flavor=options.flavor, + recalcBBoxes=options.recalcBBoxes, + recalcTimestamp=options.recalcTimestamp, + ) + if options.optimizeFontSpeed: + ttf.cfg[OPTIMIZE_FONT_SPEED] = options.optimizeFontSpeed + ttf.importXML(input) + + if options.recalcTimestamp is None and "head" in ttf and input is not sys.stdin: + # use TTX file modification time for head "modified" timestamp + mtime = os.path.getmtime(input) + ttf["head"].modified = timestampSinceEpoch(mtime) + + ttf.save(output) + + +def guessFileType(fileName): + if fileName == "-": + header = sys.stdin.buffer.peek(256) + ext = "" + else: + base, ext = os.path.splitext(fileName) + try: + with open(fileName, "rb") as f: + header = f.read(256) + except IOError: + return None + + if header.startswith(b"\xef\xbb\xbf<?xml"): + header = header.lstrip(b"\xef\xbb\xbf") + cr, tp = getMacCreatorAndType(fileName) + if tp in ("sfnt", "FFIL"): + return "TTF" + if ext == ".dfont": + return "TTF" + head = Tag(header[:4]) + if head == "OTTO": + return "OTF" + elif head == "ttcf": + return "TTC" + elif head in ("\0\1\0\0", "true"): + return "TTF" + elif head == "wOFF": + return "WOFF" + elif head == "wOF2": + return "WOFF2" + elif head == "<?xm": + # Use 'latin1' because that can't fail. + header = tostr(header, "latin1") + if opentypeheaderRE.search(header): + return "OTX" + else: + return "TTX" + return None + + +def parseOptions(args): + rawOptions, files = getopt.gnu_getopt( + args, + "ld:o:fvqht:x:sgim:z:baey:", + [ + "unicodedata=", + "recalc-timestamp", + "no-recalc-timestamp", + "flavor=", + "version", + "with-zopfli", + "newline=", + "optimize-font-speed", + ], + ) + + options = Options(rawOptions, len(files)) + jobs = [] + + if not files: + raise getopt.GetoptError("Must specify at least one input file") + + for input in files: + if input != "-" and not os.path.isfile(input): + raise getopt.GetoptError('File not found: "%s"' % input) + tp = guessFileType(input) + if tp in ("OTF", "TTF", "TTC", "WOFF", "WOFF2"): + extension = ".ttx" + if options.listTables: + action = ttList + else: + action = ttDump + elif tp == "TTX": + extension = "." + options.flavor if options.flavor else ".ttf" + action = ttCompile + elif tp == "OTX": + extension = "." + options.flavor if options.flavor else ".otf" + action = ttCompile + else: + raise getopt.GetoptError('Unknown file type: "%s"' % input) + + if options.outputFile: + output = options.outputFile + else: + if input == "-": + raise getopt.GetoptError("Must provide -o when reading from stdin") + output = makeOutputFileName( + input, options.outputDir, extension, options.overWrite + ) + # 'touch' output file to avoid race condition in choosing file names + if action != ttList: + open(output, "a").close() + jobs.append((action, input, output)) + return jobs, options + + +def process(jobs, options): + for action, input, output in jobs: + action(input, output, options) + + +def main(args=None): + """Convert OpenType fonts to XML and back""" + from fontTools import configLogger + + if args is None: + args = sys.argv[1:] + try: + jobs, options = parseOptions(args) + except getopt.GetoptError as e: + print("%s\nERROR: %s" % (__doc__, e), file=sys.stderr) + sys.exit(2) + + configLogger(level=options.logLevel) + + try: + process(jobs, options) + except KeyboardInterrupt: + log.error("(Cancelled.)") + sys.exit(1) + except SystemExit: + raise + except TTLibError as e: + log.error(e) + sys.exit(1) + except: + log.exception("Unhandled exception has occurred") + sys.exit(1) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__init__.py b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b0e425ff06543d0cc4de40b48184ffb350596835 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__init__.py @@ -0,0 +1,2575 @@ +""" +A library for importing .ufo files and their descendants. +Refer to http://unifiedfontobject.org for the UFO specification. + +The main interfaces are the :class:`.UFOReader` and :class:`.UFOWriter` +classes, which support versions 1, 2, and 3 of the UFO specification. + +Set variables are available for external use that list the font +info attribute names for the `fontinfo.plist` formats. These are: + +- :obj:`.fontInfoAttributesVersion1` +- :obj:`.fontInfoAttributesVersion2` +- :obj:`.fontInfoAttributesVersion3` + +A set listing the `fontinfo.plist` attributes that were deprecated +in version 2 is available for external use: + +- :obj:`.deprecatedFontInfoAttributesVersion2` + +Functions that do basic validation on values for `fontinfo.plist` +are available for external use. These are + +- :func:`.validateFontInfoVersion2ValueForAttribute` +- :func:`.validateFontInfoVersion3ValueForAttribute` + +Value conversion functions are available for converting +`fontinfo.plist` values between the possible format versions. + +- :func:`.convertFontInfoValueForAttributeFromVersion1ToVersion2` +- :func:`.convertFontInfoValueForAttributeFromVersion2ToVersion1` +- :func:`.convertFontInfoValueForAttributeFromVersion2ToVersion3` +- :func:`.convertFontInfoValueForAttributeFromVersion3ToVersion2` +""" + +from __future__ import annotations + +import enum +import logging +import os +import zipfile +from collections import OrderedDict +from copy import deepcopy +from os import fsdecode +from typing import IO, TYPE_CHECKING, Any, Optional, Union, cast + +from fontTools.misc import filesystem as fs +from fontTools.misc import plistlib +from fontTools.ufoLib.converters import convertUFO1OrUFO2KerningToUFO3Kerning +from fontTools.ufoLib.errors import UFOLibError +from fontTools.ufoLib.filenames import userNameToFileName +from fontTools.ufoLib.utils import ( + BaseFormatVersion, + normalizeFormatVersion, + numberTypes, +) +from fontTools.ufoLib.validators import * + +if TYPE_CHECKING: + from logging import Logger + + from fontTools.annotations import ( + GlyphNameToFileNameFunc, + K, + KerningDict, + KerningGroups, + KerningNested, + PathOrFS, + PathStr, + UFOFormatVersionInput, + V, + ) + from fontTools.misc.filesystem._base import FS + from fontTools.ufoLib.glifLib import GlyphSet + +KerningGroupRenameMaps = dict[str, dict[str, str]] +LibDict = dict[str, Any] +LayerOrderList = Optional[list[Optional[str]]] +AttributeDataDict = dict[str, Any] +FontInfoAttributes = dict[str, AttributeDataDict] + +# client code can check this to see if the upstream `fs` package is being used +haveFS = fs._haveFS + +__all__: list[str] = [ + "haveFS", + "makeUFOPath", + "UFOLibError", + "UFOReader", + "UFOWriter", + "UFOReaderWriter", + "UFOFileStructure", + "fontInfoAttributesVersion1", + "fontInfoAttributesVersion2", + "fontInfoAttributesVersion3", + "deprecatedFontInfoAttributesVersion2", + "validateFontInfoVersion2ValueForAttribute", + "validateFontInfoVersion3ValueForAttribute", + "convertFontInfoValueForAttributeFromVersion1ToVersion2", + "convertFontInfoValueForAttributeFromVersion2ToVersion1", +] + +__version__: str = "3.0.0" + + +logger: Logger = logging.getLogger(__name__) + + +# --------- +# Constants +# --------- + +DEFAULT_GLYPHS_DIRNAME: str = "glyphs" +DATA_DIRNAME: str = "data" +IMAGES_DIRNAME: str = "images" +METAINFO_FILENAME: str = "metainfo.plist" +FONTINFO_FILENAME: str = "fontinfo.plist" +LIB_FILENAME: str = "lib.plist" +GROUPS_FILENAME: str = "groups.plist" +KERNING_FILENAME: str = "kerning.plist" +FEATURES_FILENAME: str = "features.fea" +LAYERCONTENTS_FILENAME: str = "layercontents.plist" +LAYERINFO_FILENAME: str = "layerinfo.plist" + +DEFAULT_LAYER_NAME: str = "public.default" + + +class UFOFormatVersion(BaseFormatVersion): + FORMAT_1_0 = (1, 0) + FORMAT_2_0 = (2, 0) + FORMAT_3_0 = (3, 0) + + +class UFOFileStructure(enum.Enum): + ZIP = "zip" + PACKAGE = "package" + + +# -------------- +# Shared Methods +# -------------- + + +class _UFOBaseIO: + if TYPE_CHECKING: + fs: FS + _havePreviousFile: bool + + def getFileModificationTime(self, path: PathStr) -> Optional[float]: + """ + Returns the modification time for the file at the given path, as a + floating point number giving the number of seconds since the epoch. + The path must be relative to the UFO path. + Returns None if the file does not exist. + """ + try: + dt = self.fs.getinfo(fsdecode(path), namespaces=["details"]).modified + except (fs.errors.MissingInfoNamespace, fs.errors.ResourceNotFound): + return None + else: + if dt is not None: + return dt.timestamp() + return None + + def _getPlist(self, fileName: str, default: Optional[Any] = None) -> Any: + """ + Read a property list relative to the UFO filesystem's root. + Raises UFOLibError if the file is missing and default is None, + otherwise default is returned. + + The errors that could be raised during the reading of a plist are + unpredictable and/or too large to list, so, a blind try: except: + is done. If an exception occurs, a UFOLibError will be raised. + """ + try: + with self.fs.open(fileName, "rb") as f: + return plistlib.load(f) + except fs.errors.ResourceNotFound: + if default is None: + raise UFOLibError( + "'%s' is missing on %s. This file is required" % (fileName, self.fs) + ) + else: + return default + except Exception as e: + # TODO(anthrotype): try to narrow this down a little + raise UFOLibError(f"'{fileName}' could not be read on {self.fs}: {e}") + + def _writePlist(self, fileName: str, obj: Any) -> None: + """ + Write a property list to a file relative to the UFO filesystem's root. + + Do this sort of atomically, making it harder to corrupt existing files, + for example when plistlib encounters an error halfway during write. + This also checks to see if text matches the text that is already in the + file at path. If so, the file is not rewritten so that the modification + date is preserved. + + The errors that could be raised during the writing of a plist are + unpredictable and/or too large to list, so, a blind try: except: is done. + If an exception occurs, a UFOLibError will be raised. + """ + if self._havePreviousFile: + try: + data = plistlib.dumps(obj) + except Exception as e: + raise UFOLibError( + "'%s' could not be written on %s because " + "the data is not properly formatted: %s" % (fileName, self.fs, e) + ) + if self.fs.exists(fileName) and data == self.fs.readbytes(fileName): + return + self.fs.writebytes(fileName, data) + else: + with self.fs.open(fileName, mode="wb") as fp: + try: + plistlib.dump(obj, fp) + except Exception as e: + raise UFOLibError( + "'%s' could not be written on %s because " + "the data is not properly formatted: %s" + % (fileName, self.fs, e) + ) + + +# ---------- +# UFO Reader +# ---------- + + +class UFOReader(_UFOBaseIO): + """Read the various components of a .ufo. + + Attributes: + path: An :class:`os.PathLike` object pointing to the .ufo. + validate: A boolean indicating if the data read should be + validated. Defaults to `True`. + + By default read data is validated. Set ``validate`` to + ``False`` to not validate the data. + """ + + def __init__(self, path: PathOrFS, validate: bool = True) -> None: + # Only call __fspath__ if path is not already a str or FS object + if not isinstance(path, (str, fs.base.FS)) and hasattr(path, "__fspath__"): + path = path.__fspath__() + + if isinstance(path, str): + structure = _sniffFileStructure(path) + parentFS: FS + try: + if structure is UFOFileStructure.ZIP: + parentFS = fs.zipfs.ZipFS(path, write=False, encoding="utf-8") # type: ignore[abstract] + else: + parentFS = fs.osfs.OSFS(path) + except fs.errors.CreateFailed as e: + raise UFOLibError(f"unable to open '{path}': {e}") + + if structure is UFOFileStructure.ZIP: + # .ufoz zip files must contain a single root directory, with arbitrary + # name, containing all the UFO files + rootDirs = [ + p.name + for p in parentFS.scandir("/") + # exclude macOS metadata contained in zip file + if p.is_dir and p.name != "__MACOSX" + ] + if len(rootDirs) == 1: + # 'ClosingSubFS' ensures that the parent zip file is closed when + # its root subdirectory is closed + self.fs: FS = parentFS.opendir( + rootDirs[0], factory=fs.subfs.ClosingSubFS + ) + else: + raise UFOLibError( + "Expected exactly 1 root directory, found %d" % len(rootDirs) + ) + else: + # normal UFO 'packages' are just a single folder + self.fs = parentFS + # when passed a path string, we make sure we close the newly opened fs + # upon calling UFOReader.close method or context manager's __exit__ + self._shouldClose: bool = True + self._fileStructure = structure + elif isinstance(path, fs.base.FS): + filesystem: FS = path + try: + filesystem.check() + except fs.errors.FilesystemClosed: + raise UFOLibError("the filesystem '%s' is closed" % path) + else: + self.fs = filesystem + try: + path = filesystem.getsyspath("/") + except fs.errors.NoSysPath: + # network or in-memory FS may not map to the local one + path = str(filesystem) + # when user passed an already initialized fs instance, it is her + # responsibility to close it, thus UFOReader.close/__exit__ are no-op + self._shouldClose = False + # default to a 'package' structure + self._fileStructure = UFOFileStructure.PACKAGE + else: + raise TypeError( + "Expected a path string or fs.base.FS object, found '%s'" + % type(path).__name__ + ) + self._path: str = fsdecode(path) + self._validate: bool = validate + self._upConvertedKerningData: Optional[dict[str, Any]] = None + + try: + self.readMetaInfo(validate=validate) + except UFOLibError: + self.close() + raise + + # properties + + def _get_path(self) -> str: + import warnings + + warnings.warn( + "The 'path' attribute is deprecated; use the 'fs' attribute instead", + DeprecationWarning, + stacklevel=2, + ) + return self._path + + path: property = property(_get_path, doc="The path of the UFO (DEPRECATED).") + + def _get_formatVersion(self) -> int: + import warnings + + warnings.warn( + "The 'formatVersion' attribute is deprecated; use the 'formatVersionTuple'", + DeprecationWarning, + stacklevel=2, + ) + return self._formatVersion.major + + formatVersion = property( + _get_formatVersion, + doc="The (major) format version of the UFO. DEPRECATED: Use formatVersionTuple", + ) + + @property + def formatVersionTuple(self) -> tuple[int, int]: + """The (major, minor) format version of the UFO. + This is determined by reading metainfo.plist during __init__. + """ + return self._formatVersion + + def _get_fileStructure(self) -> Any: + return self._fileStructure + + fileStructure: property = property( + _get_fileStructure, + doc=( + "The file structure of the UFO: " + "either UFOFileStructure.ZIP or UFOFileStructure.PACKAGE" + ), + ) + + # up conversion + + def _upConvertKerning(self, validate: bool) -> None: + """ + Up convert kerning and groups in UFO 1 and 2. + The data will be held internally until each bit of data + has been retrieved. The conversion of both must be done + at once, so the raw data is cached and an error is raised + if one bit of data becomes obsolete before it is called. + + ``validate`` will validate the data. + """ + if self._upConvertedKerningData: + testKerning = self._readKerning() + if testKerning != self._upConvertedKerningData["originalKerning"]: + raise UFOLibError( + "The data in kerning.plist has been modified since it was converted to UFO 3 format." + ) + testGroups = self._readGroups() + if testGroups != self._upConvertedKerningData["originalGroups"]: + raise UFOLibError( + "The data in groups.plist has been modified since it was converted to UFO 3 format." + ) + else: + groups = self._readGroups() + if validate: + invalidFormatMessage = "groups.plist is not properly formatted." + if not isinstance(groups, dict): + raise UFOLibError(invalidFormatMessage) + for groupName, glyphList in groups.items(): + if not isinstance(groupName, str): + raise UFOLibError(invalidFormatMessage) + elif not isinstance(glyphList, list): + raise UFOLibError(invalidFormatMessage) + for glyphName in glyphList: + if not isinstance(glyphName, str): + raise UFOLibError(invalidFormatMessage) + self._upConvertedKerningData = dict( + kerning={}, + originalKerning=self._readKerning(), + groups={}, + originalGroups=groups, + ) + # convert kerning and groups + kerning, groups, conversionMaps = convertUFO1OrUFO2KerningToUFO3Kerning( + self._upConvertedKerningData["originalKerning"], + deepcopy(self._upConvertedKerningData["originalGroups"]), + self.getGlyphSet(), + ) + # store + self._upConvertedKerningData["kerning"] = kerning + self._upConvertedKerningData["groups"] = groups + self._upConvertedKerningData["groupRenameMaps"] = conversionMaps + + # support methods + + def readBytesFromPath(self, path: PathStr) -> Optional[bytes]: + """ + Returns the bytes in the file at the given path. + The path must be relative to the UFO's filesystem root. + Returns None if the file does not exist. + """ + try: + return self.fs.readbytes(fsdecode(path)) + except fs.errors.ResourceNotFound: + return None + + def getReadFileForPath( + self, path: PathStr, encoding: Optional[str] = None + ) -> Optional[Union[IO[bytes], IO[str]]]: + """ + Returns a file (or file-like) object for the file at the given path. + The path must be relative to the UFO path. + Returns None if the file does not exist. + By default the file is opened in binary mode (reads bytes). + If encoding is passed, the file is opened in text mode (reads str). + + Note: The caller is responsible for closing the open file. + """ + path = fsdecode(path) + try: + if encoding is None: + return self.fs.open(path, mode="rb") + else: + return self.fs.open(path, mode="r", encoding=encoding) + except fs.errors.ResourceNotFound: + return None + + # metainfo.plist + + def _readMetaInfo(self, validate: Optional[bool] = None) -> dict[str, Any]: + """ + Read metainfo.plist and return raw data. Only used for internal operations. + + ``validate`` will validate the read data, by default it is set + to the class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + data = self._getPlist(METAINFO_FILENAME) + if validate and not isinstance(data, dict): + raise UFOLibError("metainfo.plist is not properly formatted.") + try: + formatVersionMajor = data["formatVersion"] + except KeyError: + raise UFOLibError( + f"Missing required formatVersion in '{METAINFO_FILENAME}' on {self.fs}" + ) + formatVersionMinor = data.setdefault("formatVersionMinor", 0) + + try: + formatVersion = UFOFormatVersion((formatVersionMajor, formatVersionMinor)) + except ValueError as e: + unsupportedMsg = ( + f"Unsupported UFO format ({formatVersionMajor}.{formatVersionMinor}) " + f"in '{METAINFO_FILENAME}' on {self.fs}" + ) + if validate: + from fontTools.ufoLib.errors import UnsupportedUFOFormat + + raise UnsupportedUFOFormat(unsupportedMsg) from e + + formatVersion = UFOFormatVersion.default() + logger.warning( + "%s. Assuming the latest supported version (%s). " + "Some data may be skipped or parsed incorrectly", + unsupportedMsg, + formatVersion, + ) + data["formatVersionTuple"] = formatVersion + return data + + def readMetaInfo(self, validate: Optional[bool] = None) -> None: + """ + Read metainfo.plist and set formatVersion. Only used for internal operations. + + ``validate`` will validate the read data, by default it is set + to the class's validate value, can be overridden. + """ + data = self._readMetaInfo(validate=validate) + self._formatVersion = data["formatVersionTuple"] + + # groups.plist + + def _readGroups(self) -> dict[str, list[str]]: + groups = self._getPlist(GROUPS_FILENAME, {}) + # remove any duplicate glyphs in a kerning group + for groupName, glyphList in groups.items(): + if groupName.startswith(("public.kern1.", "public.kern2.")): + groups[groupName] = list(OrderedDict.fromkeys(glyphList)) + return groups + + def readGroups(self, validate: Optional[bool] = None) -> dict[str, list[str]]: + """ + Read groups.plist. Returns a dict. + ``validate`` will validate the read data, by default it is set to the + class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + # handle up conversion + if self._formatVersion < UFOFormatVersion.FORMAT_3_0: + self._upConvertKerning(validate) + groups = cast(dict, self._upConvertedKerningData)["groups"] + # normal + else: + groups = self._readGroups() + if validate: + valid, message = groupsValidator(groups) + if not valid: + raise UFOLibError(message) + return groups + + def getKerningGroupConversionRenameMaps( + self, validate: Optional[bool] = None + ) -> KerningGroupRenameMaps: + """ + Get maps defining the renaming that was done during any + needed kerning group conversion. This method returns a + dictionary of this form:: + + { + "side1" : {"old group name" : "new group name"}, + "side2" : {"old group name" : "new group name"} + } + + When no conversion has been performed, the side1 and side2 + dictionaries will be empty. + + ``validate`` will validate the groups, by default it is set to the + class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + if self._formatVersion >= UFOFormatVersion.FORMAT_3_0: + return dict(side1={}, side2={}) + # use the public group reader to force the load and + # conversion of the data if it hasn't happened yet. + self.readGroups(validate=validate) + return cast(dict, self._upConvertedKerningData)["groupRenameMaps"] + + # fontinfo.plist + + def _readInfo(self, validate: bool) -> dict[str, Any]: + data = self._getPlist(FONTINFO_FILENAME, {}) + if validate and not isinstance(data, dict): + raise UFOLibError("fontinfo.plist is not properly formatted.") + return data + + def readInfo(self, info: Any, validate: Optional[bool] = None) -> None: + """ + Read fontinfo.plist. It requires an object that allows + setting attributes with names that follow the fontinfo.plist + version 3 specification. This will write the attributes + defined in the file into the object. + + ``validate`` will validate the read data, by default it is set to the + class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + infoDict = self._readInfo(validate) + infoDataToSet = {} + # version 1 + if self._formatVersion == UFOFormatVersion.FORMAT_1_0: + for attr in fontInfoAttributesVersion1: + value = infoDict.get(attr) + if value is not None: + infoDataToSet[attr] = value + infoDataToSet = _convertFontInfoDataVersion1ToVersion2(infoDataToSet) + infoDataToSet = _convertFontInfoDataVersion2ToVersion3(infoDataToSet) + # version 2 + elif self._formatVersion == UFOFormatVersion.FORMAT_2_0: + for attr, dataValidationDict in list( + fontInfoAttributesVersion2ValueData.items() + ): + value = infoDict.get(attr) + if value is None: + continue + infoDataToSet[attr] = value + infoDataToSet = _convertFontInfoDataVersion2ToVersion3(infoDataToSet) + # version 3.x + elif self._formatVersion.major == UFOFormatVersion.FORMAT_3_0.major: + for attr, dataValidationDict in list( + fontInfoAttributesVersion3ValueData.items() + ): + value = infoDict.get(attr) + if value is None: + continue + infoDataToSet[attr] = value + # unsupported version + else: + raise NotImplementedError(self._formatVersion) + # validate data + if validate: + infoDataToSet = validateInfoVersion3Data(infoDataToSet) + # populate the object + for attr, value in list(infoDataToSet.items()): + try: + setattr(info, attr, value) + except AttributeError: + raise UFOLibError( + "The supplied info object does not support setting a necessary attribute (%s)." + % attr + ) + + # kerning.plist + + def _readKerning(self) -> KerningNested: + data = self._getPlist(KERNING_FILENAME, {}) + return data + + def readKerning(self, validate: Optional[bool] = None) -> KerningDict: + """ + Read kerning.plist. Returns a dict. + + ``validate`` will validate the kerning data, by default it is set to the + class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + # handle up conversion + if self._formatVersion < UFOFormatVersion.FORMAT_3_0: + self._upConvertKerning(validate) + kerningNested = cast(dict, self._upConvertedKerningData)["kerning"] + # normal + else: + kerningNested = self._readKerning() + if validate: + valid, message = kerningValidator(kerningNested) + if not valid: + raise UFOLibError(message) + # flatten + kerning = {} + for left in kerningNested: + for right in kerningNested[left]: + value = kerningNested[left][right] + kerning[left, right] = value + return kerning + + # lib.plist + + def readLib(self, validate: Optional[bool] = None) -> dict[str, Any]: + """ + Read lib.plist. Returns a dict. + + ``validate`` will validate the data, by default it is set to the + class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + data = self._getPlist(LIB_FILENAME, {}) + if validate: + valid, message = fontLibValidator(data) + if not valid: + raise UFOLibError(message) + return data + + # features.fea + + def readFeatures(self) -> str: + """ + Read features.fea. Return a string. + The returned string is empty if the file is missing. + """ + try: + with self.fs.open(FEATURES_FILENAME, "r", encoding="utf-8-sig") as f: + return f.read() + except fs.errors.ResourceNotFound: + return "" + + # glyph sets & layers + + def _readLayerContents(self, validate: bool) -> list[tuple[str, str]]: + """ + Rebuild the layer contents list by checking what glyphsets + are available on disk. + + ``validate`` will validate the layer contents. + """ + if self._formatVersion < UFOFormatVersion.FORMAT_3_0: + return [(DEFAULT_LAYER_NAME, DEFAULT_GLYPHS_DIRNAME)] + contents = self._getPlist(LAYERCONTENTS_FILENAME) + if validate: + valid, error = layerContentsValidator(contents, self.fs) + if not valid: + raise UFOLibError(error) + return contents + + def getLayerNames(self, validate: Optional[bool] = None) -> list[str]: + """ + Get the ordered layer names from layercontents.plist. + + ``validate`` will validate the data, by default it is set to the + class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + layerContents = self._readLayerContents(validate) + layerNames = [layerName for layerName, directoryName in layerContents] + return layerNames + + def getDefaultLayerName(self, validate: Optional[bool] = None) -> str: + """ + Get the default layer name from layercontents.plist. + + ``validate`` will validate the data, by default it is set to the + class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + layerContents = self._readLayerContents(validate) + for layerName, layerDirectory in layerContents: + if layerDirectory == DEFAULT_GLYPHS_DIRNAME: + return layerName + # this will already have been raised during __init__ + raise UFOLibError("The default layer is not defined in layercontents.plist.") + + def getGlyphSet( + self, + layerName: Optional[str] = None, + validateRead: Optional[bool] = None, + validateWrite: Optional[bool] = None, + ) -> GlyphSet: + """ + Return the GlyphSet associated with the + glyphs directory mapped to layerName + in the UFO. If layerName is not provided, + the name retrieved with getDefaultLayerName + will be used. + + ``validateRead`` will validate the read data, by default it is set to the + class's validate value, can be overridden. + ``validateWrite`` will validate the written data, by default it is set to the + class's validate value, can be overridden. + """ + from fontTools.ufoLib.glifLib import GlyphSet + + if validateRead is None: + validateRead = self._validate + if validateWrite is None: + validateWrite = self._validate + if layerName is None: + layerName = self.getDefaultLayerName(validate=validateRead) + directory = None + layerContents = self._readLayerContents(validateRead) + for storedLayerName, storedLayerDirectory in layerContents: + if layerName == storedLayerName: + directory = storedLayerDirectory + break + if directory is None: + raise UFOLibError('No glyphs directory is mapped to "%s".' % layerName) + try: + glyphSubFS = self.fs.opendir(directory) + except fs.errors.ResourceNotFound: + raise UFOLibError(f"No '{directory}' directory for layer '{layerName}'") + return GlyphSet( + glyphSubFS, + ufoFormatVersion=self._formatVersion, + validateRead=validateRead, + validateWrite=validateWrite, + expectContentsFile=True, + ) + + def getCharacterMapping( + self, layerName: Optional[str] = None, validate: Optional[bool] = None + ) -> dict[int, list[str]]: + """ + Return a dictionary that maps unicode values (ints) to + lists of glyph names. + """ + if validate is None: + validate = self._validate + glyphSet = self.getGlyphSet( + layerName, validateRead=validate, validateWrite=True + ) + allUnicodes = glyphSet.getUnicodes() + cmap: dict[int, list[str]] = {} + for glyphName, unicodes in allUnicodes.items(): + for code in unicodes: + if code in cmap: + cmap[code].append(glyphName) + else: + cmap[code] = [glyphName] + return cmap + + # /data + + def getDataDirectoryListing(self) -> list[str]: + """ + Returns a list of all files in the data directory. + The returned paths will be relative to the UFO. + This will not list directory names, only file names. + Thus, empty directories will be skipped. + """ + try: + self._dataFS = self.fs.opendir(DATA_DIRNAME) + except fs.errors.ResourceNotFound: + return [] + except fs.errors.DirectoryExpected: + raise UFOLibError('The UFO contains a "data" file instead of a directory.') + try: + # fs Walker.files method returns "absolute" paths (in terms of the + # root of the 'data' SubFS), so we strip the leading '/' to make + # them relative + return [p.lstrip("/") for p in self._dataFS.walk.files()] + except fs.errors.ResourceError: + return [] + + def getImageDirectoryListing(self, validate: Optional[bool] = None) -> list[str]: + """ + Returns a list of all image file names in + the images directory. Each of the images will + have been verified to have the PNG signature. + + ``validate`` will validate the data, by default it is set to the + class's validate value, can be overridden. + """ + if self._formatVersion < UFOFormatVersion.FORMAT_3_0: + return [] + if validate is None: + validate = self._validate + try: + self._imagesFS = imagesFS = self.fs.opendir(IMAGES_DIRNAME) + except fs.errors.ResourceNotFound: + return [] + except fs.errors.DirectoryExpected: + raise UFOLibError( + 'The UFO contains an "images" file instead of a directory.' + ) + result = [] + for path in imagesFS.scandir("/"): + if path.is_dir: + # silently skip this as version control + # systems often have hidden directories + continue + if validate: + with imagesFS.open(path.name, "rb") as fp: + valid, error = pngValidator(fileObj=fp) + if valid: + result.append(path.name) + else: + result.append(path.name) + return result + + def readData(self, fileName: PathStr) -> bytes: + """ + Return bytes for the file named 'fileName' inside the 'data/' directory. + """ + fileName = fsdecode(fileName) + try: + try: + dataFS = self._dataFS + except AttributeError: + # in case readData is called before getDataDirectoryListing + dataFS = self.fs.opendir(DATA_DIRNAME) + data = dataFS.readbytes(fileName) + except fs.errors.ResourceNotFound: + raise UFOLibError(f"No data file named '{fileName}' on {self.fs}") + return data + + def readImage(self, fileName: PathStr, validate: Optional[bool] = None) -> bytes: + """ + Return image data for the file named fileName. + + ``validate`` will validate the data, by default it is set to the + class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + if self._formatVersion < UFOFormatVersion.FORMAT_3_0: + raise UFOLibError( + f"Reading images is not allowed in UFO {self._formatVersion.major}." + ) + fileName = fsdecode(fileName) + try: + try: + imagesFS = self._imagesFS + except AttributeError: + # in case readImage is called before getImageDirectoryListing + imagesFS = self.fs.opendir(IMAGES_DIRNAME) + data = imagesFS.readbytes(fileName) + except fs.errors.ResourceNotFound: + raise UFOLibError(f"No image file named '{fileName}' on {self.fs}") + if validate: + valid, error = pngValidator(data=data) + if not valid: + raise UFOLibError(error) + return data + + def close(self) -> None: + if self._shouldClose: + self.fs.close() + + def __enter__(self) -> UFOReader: + return self + + def __exit__(self, exc_type: Any, exc_value: Any, exc_tb: Any) -> None: + self.close() + + +# ---------- +# UFO Writer +# ---------- + + +class UFOWriter(UFOReader): + """Write the various components of a .ufo. + + Attributes: + path: An :class:`os.PathLike` object pointing to the .ufo. + formatVersion: the UFO format version as a tuple of integers (major, minor), + or as a single integer for the major digit only (minor is implied to be 0). + By default, the latest formatVersion will be used; currently it is 3.0, + which is equivalent to formatVersion=(3, 0). + fileCreator: The creator of the .ufo file. Defaults to + `com.github.fonttools.ufoLib`. + structure: The internal structure of the .ufo file: either `ZIP` or `PACKAGE`. + validate: A boolean indicating if the data read should be validated. Defaults + to `True`. + + By default, the written data will be validated before writing. Set ``validate`` to + ``False`` if you do not want to validate the data. Validation can also be overriden + on a per-method level if desired. + + Raises: + UnsupportedUFOFormat: An exception indicating that the requested UFO + formatVersion is not supported. + """ + + def __init__( + self, + path: PathOrFS, + formatVersion: UFOFormatVersionInput = None, + fileCreator: str = "com.github.fonttools.ufoLib", + structure: Optional[UFOFileStructure] = None, + validate: bool = True, + ) -> None: + try: + formatVersion = normalizeFormatVersion(formatVersion, UFOFormatVersion) + except ValueError as e: + from fontTools.ufoLib.errors import UnsupportedUFOFormat + + raise UnsupportedUFOFormat( + f"Unsupported UFO format: {formatVersion!r}" + ) from e + + if hasattr(path, "__fspath__"): # support os.PathLike objects + path = path.__fspath__() + + if isinstance(path, str): + # normalize path by removing trailing or double slashes + path = os.path.normpath(path) + havePreviousFile = os.path.exists(path) + if havePreviousFile: + # ensure we use the same structure as the destination + existingStructure = _sniffFileStructure(path) + if structure is not None: + try: + structure = UFOFileStructure(structure) + except ValueError: + raise UFOLibError( + "Invalid or unsupported structure: '%s'" % structure + ) + if structure is not existingStructure: + raise UFOLibError( + "A UFO with a different structure (%s) already exists " + "at the given path: '%s'" % (existingStructure, path) + ) + else: + structure = existingStructure + else: + # if not exists, default to 'package' structure + if structure is None: + structure = UFOFileStructure.PACKAGE + dirName = os.path.dirname(path) + if dirName and not os.path.isdir(dirName): + raise UFOLibError( + "Cannot write to '%s': directory does not exist" % path + ) + if structure is UFOFileStructure.ZIP: + if havePreviousFile: + # we can't write a zip in-place, so we have to copy its + # contents to a temporary location and work from there, then + # upon closing UFOWriter we create the final zip file + parentFS: FS = fs.tempfs.TempFS() + with fs.zipfs.ZipFS(path, encoding="utf-8") as origFS: # type: ignore[abstract] + fs.copy.copy_fs(origFS, parentFS) + # if output path is an existing zip, we require that it contains + # one, and only one, root directory (with arbitrary name), in turn + # containing all the existing UFO contents + rootDirs = [ + p.name + for p in parentFS.scandir("/") + # exclude macOS metadata contained in zip file + if p.is_dir and p.name != "__MACOSX" + ] + if len(rootDirs) != 1: + raise UFOLibError( + "Expected exactly 1 root directory, found %d" + % len(rootDirs) + ) + else: + rootDir = rootDirs[0] + else: + # if the output zip file didn't exist, we create the root folder; + # we name it the same as input 'path', but with '.ufo' extension + rootDir = os.path.splitext(os.path.basename(path))[0] + ".ufo" + parentFS = fs.zipfs.ZipFS(path, write=True, encoding="utf-8") # type: ignore[abstract] + parentFS.makedir(rootDir) + # 'ClosingSubFS' ensures that the parent filesystem is closed + # when its root subdirectory is closed + self.fs = parentFS.opendir(rootDir, factory=fs.subfs.ClosingSubFS) + else: + self.fs = fs.osfs.OSFS(path, create=True) + self._fileStructure = structure + self._havePreviousFile = havePreviousFile + self._shouldClose = True + elif isinstance(path, fs.base.FS): + filesystem: FS = path + try: + filesystem.check() + except fs.errors.FilesystemClosed: + raise UFOLibError("the filesystem '%s' is closed" % path) + else: + self.fs = filesystem + try: + path = filesystem.getsyspath("/") + except fs.errors.NoSysPath: + # network or in-memory FS may not map to the local one + path = str(filesystem) + # if passed an FS object, always use 'package' structure + if structure and structure is not UFOFileStructure.PACKAGE: + import warnings + + warnings.warn( + "The 'structure' argument is not used when input is an FS object", + UserWarning, + stacklevel=2, + ) + self._fileStructure = UFOFileStructure.PACKAGE + # if FS contains a "metainfo.plist", we consider it non-empty + self._havePreviousFile = filesystem.exists(METAINFO_FILENAME) + # the user is responsible for closing the FS object + self._shouldClose = False + else: + raise TypeError( + "Expected a path string or fs object, found %s" % type(path).__name__ + ) + + # establish some basic stuff + self._path = fsdecode(path) + self._formatVersion = formatVersion + self._fileCreator = fileCreator + self._downConversionKerningData: Optional[KerningGroupRenameMaps] = None + self._validate = validate + # if the file already exists, get the format version. + # this will be needed for up and down conversion. + previousFormatVersion = None + if self._havePreviousFile: + metaInfo = self._readMetaInfo(validate=validate) + previousFormatVersion = metaInfo["formatVersionTuple"] + # catch down conversion + if previousFormatVersion > formatVersion: + from fontTools.ufoLib.errors import UnsupportedUFOFormat + + raise UnsupportedUFOFormat( + "The UFO located at this path is a higher version " + f"({previousFormatVersion}) than the version ({formatVersion}) " + "that is trying to be written. This is not supported." + ) + # handle the layer contents + self.layerContents: Union[dict[str, str], OrderedDict[str, str]] = {} + if previousFormatVersion is not None and previousFormatVersion.major >= 3: + # already exists + self.layerContents = OrderedDict(self._readLayerContents(validate)) + else: + # previous < 3 + # imply the layer contents + if self.fs.exists(DEFAULT_GLYPHS_DIRNAME): + self.layerContents = {DEFAULT_LAYER_NAME: DEFAULT_GLYPHS_DIRNAME} + # write the new metainfo + self._writeMetaInfo() + + # properties + + def _get_fileCreator(self) -> str: + return self._fileCreator + + fileCreator: property = property( + _get_fileCreator, + doc="The file creator of the UFO. This is set into metainfo.plist during __init__.", + ) + + # support methods for file system interaction + + def copyFromReader( + self, reader: UFOReader, sourcePath: PathStr, destPath: PathStr + ) -> None: + """ + Copy the sourcePath in the provided UFOReader to destPath + in this writer. The paths must be relative. This works with + both individual files and directories. + """ + if not isinstance(reader, UFOReader): + raise UFOLibError("The reader must be an instance of UFOReader.") + sourcePath = fsdecode(sourcePath) + destPath = fsdecode(destPath) + if not reader.fs.exists(sourcePath): + raise UFOLibError( + 'The reader does not have data located at "%s".' % sourcePath + ) + if self.fs.exists(destPath): + raise UFOLibError('A file named "%s" already exists.' % destPath) + # create the destination directory if it doesn't exist + self.fs.makedirs(fs.path.dirname(destPath), recreate=True) + if reader.fs.isdir(sourcePath): + fs.copy.copy_dir(reader.fs, sourcePath, self.fs, destPath) + else: + fs.copy.copy_file(reader.fs, sourcePath, self.fs, destPath) + + def writeBytesToPath(self, path: PathStr, data: bytes) -> None: + """ + Write bytes to a path relative to the UFO filesystem's root. + If writing to an existing UFO, check to see if data matches the data + that is already in the file at path; if so, the file is not rewritten + so that the modification date is preserved. + If needed, the directory tree for the given path will be built. + """ + path = fsdecode(path) + if self._havePreviousFile: + if self.fs.isfile(path) and data == self.fs.readbytes(path): + return + try: + self.fs.writebytes(path, data) + except fs.errors.FileExpected: + raise UFOLibError("A directory exists at '%s'" % path) + except fs.errors.ResourceNotFound: + self.fs.makedirs(fs.path.dirname(path), recreate=True) + self.fs.writebytes(path, data) + + def getFileObjectForPath( + self, + path: PathStr, + mode: str = "w", + encoding: Optional[str] = None, + ) -> Optional[IO[Any]]: + """ + Returns a file (or file-like) object for the + file at the given path. The path must be relative + to the UFO path. Returns None if the file does + not exist and the mode is "r" or "rb. + An encoding may be passed if the file is opened in text mode. + + Note: The caller is responsible for closing the open file. + """ + path = fsdecode(path) + try: + return self.fs.open(path, mode=mode, encoding=encoding) + except fs.errors.ResourceNotFound as e: + m = mode[0] + if m == "r": + # XXX I think we should just let it raise. The docstring, + # however, says that this returns None if mode is 'r' + return None + elif m == "w" or m == "a" or m == "x": + self.fs.makedirs(fs.path.dirname(path), recreate=True) + return self.fs.open(path, mode=mode, encoding=encoding) + except fs.errors.ResourceError as e: + raise UFOLibError(f"unable to open '{path}' on {self.fs}: {e}") + return None + + def removePath( + self, path: PathStr, force: bool = False, removeEmptyParents: bool = True + ) -> None: + """ + Remove the file (or directory) at path. The path + must be relative to the UFO. + Raises UFOLibError if the path doesn't exist. + If force=True, ignore non-existent paths. + If the directory where 'path' is located becomes empty, it will + be automatically removed, unless 'removeEmptyParents' is False. + """ + path = fsdecode(path) + try: + self.fs.remove(path) + except fs.errors.FileExpected: + self.fs.removetree(path) + except fs.errors.ResourceNotFound: + if not force: + raise UFOLibError(f"'{path}' does not exist on {self.fs}") + if removeEmptyParents: + parent = fs.path.dirname(path) + if parent: + fs.tools.remove_empty(self.fs, parent) + + # alias kept for backward compatibility with old API + removeFileForPath = removePath + + # UFO mod time + + def setModificationTime(self) -> None: + """ + Set the UFO modification time to the current time. + This is never called automatically. It is up to the + caller to call this when finished working on the UFO. + """ + path = self._path + if path is not None and os.path.exists(path): + try: + # this may fail on some filesystems (e.g. SMB servers) + os.utime(path, None) + except OSError as e: + logger.warning("Failed to set modified time: %s", e) + + # metainfo.plist + + def _writeMetaInfo(self) -> None: + metaInfo = dict( + creator=self._fileCreator, + formatVersion=self._formatVersion.major, + ) + if self._formatVersion.minor != 0: + metaInfo["formatVersionMinor"] = self._formatVersion.minor + self._writePlist(METAINFO_FILENAME, metaInfo) + + # groups.plist + + def setKerningGroupConversionRenameMaps(self, maps: KerningGroupRenameMaps) -> None: + """ + Set maps defining the renaming that should be done + when writing groups and kerning in UFO 1 and UFO 2. + This will effectively undo the conversion done when + UFOReader reads this data. The dictionary should have + this form:: + + { + "side1" : {"group name to use when writing" : "group name in data"}, + "side2" : {"group name to use when writing" : "group name in data"} + } + + This is the same form returned by UFOReader's + getKerningGroupConversionRenameMaps method. + """ + if self._formatVersion >= UFOFormatVersion.FORMAT_3_0: + return # XXX raise an error here + # flip the dictionaries + remap = {} + for side in ("side1", "side2"): + for writeName, dataName in list(maps[side].items()): + remap[dataName] = writeName + self._downConversionKerningData = dict(groupRenameMap=remap) + + def writeGroups( + self, groups: KerningGroups, validate: Optional[bool] = None + ) -> None: + """ + Write groups.plist. This method requires a + dict of glyph groups as an argument. + + ``validate`` will validate the data, by default it is set to the + class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + # validate the data structure + if validate: + valid, message = groupsValidator(groups) + if not valid: + raise UFOLibError(message) + # down convert + if ( + self._formatVersion < UFOFormatVersion.FORMAT_3_0 + and self._downConversionKerningData is not None + ): + remap = self._downConversionKerningData["groupRenameMap"] + remappedGroups = {} + # there are some edge cases here that are ignored: + # 1. if a group is being renamed to a name that + # already exists, the existing group is always + # overwritten. (this is why there are two loops + # below.) there doesn't seem to be a logical + # solution to groups mismatching and overwriting + # with the specifiecd group seems like a better + # solution than throwing an error. + # 2. if side 1 and side 2 groups are being renamed + # to the same group name there is no check to + # ensure that the contents are identical. that + # is left up to the caller. + for name, contents in list(groups.items()): + if name in remap: + continue + remappedGroups[name] = contents + for name, contents in list(groups.items()): + if name not in remap: + continue + name = remap[name] + remappedGroups[name] = contents + groups = remappedGroups + # pack and write + groupsNew = {} + for key, value in groups.items(): + groupsNew[key] = list(value) + if groupsNew: + self._writePlist(GROUPS_FILENAME, groupsNew) + elif self._havePreviousFile: + self.removePath(GROUPS_FILENAME, force=True, removeEmptyParents=False) + + # fontinfo.plist + + def writeInfo(self, info: Any, validate: Optional[bool] = None) -> None: + """ + Write info.plist. This method requires an object + that supports getting attributes that follow the + fontinfo.plist version 2 specification. Attributes + will be taken from the given object and written + into the file. + + ``validate`` will validate the data, by default it is set to the + class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + # gather version 3 data + infoData = {} + for attr in list(fontInfoAttributesVersion3ValueData.keys()): + if hasattr(info, attr): + try: + value = getattr(info, attr) + except AttributeError: + raise UFOLibError( + "The supplied info object does not support getting a necessary attribute (%s)." + % attr + ) + if value is None: + continue + infoData[attr] = value + # down convert data if necessary and validate + if self._formatVersion == UFOFormatVersion.FORMAT_3_0: + if validate: + infoData = validateInfoVersion3Data(infoData) + elif self._formatVersion == UFOFormatVersion.FORMAT_2_0: + infoData = _convertFontInfoDataVersion3ToVersion2(infoData) + if validate: + infoData = validateInfoVersion2Data(infoData) + elif self._formatVersion == UFOFormatVersion.FORMAT_1_0: + infoData = _convertFontInfoDataVersion3ToVersion2(infoData) + if validate: + infoData = validateInfoVersion2Data(infoData) + infoData = _convertFontInfoDataVersion2ToVersion1(infoData) + # write file if there is anything to write + if infoData: + self._writePlist(FONTINFO_FILENAME, infoData) + + # kerning.plist + + def writeKerning( + self, kerning: KerningDict, validate: Optional[bool] = None + ) -> None: + """ + Write kerning.plist. This method requires a + dict of kerning pairs as an argument. + + This performs basic structural validation of the kerning, + but it does not check for compliance with the spec in + regards to conflicting pairs. The assumption is that the + kerning data being passed is standards compliant. + + ``validate`` will validate the data, by default it is set to the + class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + # validate the data structure + if validate: + invalidFormatMessage = "The kerning is not properly formatted." + if not isDictEnough(kerning): + raise UFOLibError(invalidFormatMessage) + for pair, value in list(kerning.items()): + if not isinstance(pair, (list, tuple)): + raise UFOLibError(invalidFormatMessage) + if not len(pair) == 2: + raise UFOLibError(invalidFormatMessage) + if not isinstance(pair[0], str): + raise UFOLibError(invalidFormatMessage) + if not isinstance(pair[1], str): + raise UFOLibError(invalidFormatMessage) + if not isinstance(value, numberTypes): + raise UFOLibError(invalidFormatMessage) + # down convert + if ( + self._formatVersion < UFOFormatVersion.FORMAT_3_0 + and self._downConversionKerningData is not None + ): + remap = self._downConversionKerningData["groupRenameMap"] + remappedKerning = {} + for (side1, side2), value in list(kerning.items()): + side1 = remap.get(side1, side1) + side2 = remap.get(side2, side2) + remappedKerning[side1, side2] = value + kerning = remappedKerning + # pack and write + kerningDict: KerningNested = {} + for left, right in kerning.keys(): + value = kerning[left, right] + if left not in kerningDict: + kerningDict[left] = {} + kerningDict[left][right] = value + if kerningDict: + self._writePlist(KERNING_FILENAME, kerningDict) + elif self._havePreviousFile: + self.removePath(KERNING_FILENAME, force=True, removeEmptyParents=False) + + # lib.plist + + def writeLib(self, libDict: LibDict, validate: Optional[bool] = None) -> None: + """ + Write lib.plist. This method requires a + lib dict as an argument. + + ``validate`` will validate the data, by default it is set to the + class's validate value, can be overridden. + """ + if validate is None: + validate = self._validate + if validate: + valid, message = fontLibValidator(libDict) + if not valid: + raise UFOLibError(message) + if libDict: + self._writePlist(LIB_FILENAME, libDict) + elif self._havePreviousFile: + self.removePath(LIB_FILENAME, force=True, removeEmptyParents=False) + + # features.fea + + def writeFeatures(self, features: str, validate: Optional[bool] = None) -> None: + """ + Write features.fea. This method requires a + features string as an argument. + """ + if validate is None: + validate = self._validate + if self._formatVersion == UFOFormatVersion.FORMAT_1_0: + raise UFOLibError("features.fea is not allowed in UFO Format Version 1.") + if validate: + if not isinstance(features, str): + raise UFOLibError("The features are not text.") + if features: + self.writeBytesToPath(FEATURES_FILENAME, features.encode("utf8")) + elif self._havePreviousFile: + self.removePath(FEATURES_FILENAME, force=True, removeEmptyParents=False) + + # glyph sets & layers + + def writeLayerContents( + self, layerOrder: LayerOrderList = None, validate: Optional[bool] = None + ) -> None: + """ + Write the layercontents.plist file. This method *must* be called + after all glyph sets have been written. + """ + if validate is None: + validate = self._validate + if self._formatVersion < UFOFormatVersion.FORMAT_3_0: + return + if layerOrder is not None: + newOrder: list[Optional[str]] = [] + for layerName in layerOrder: + if layerName is None: + layerName = DEFAULT_LAYER_NAME + newOrder.append(layerName) + layerOrder = newOrder + else: + layerOrder = list(self.layerContents.keys()) + if validate and set(layerOrder) != set(self.layerContents.keys()): + raise UFOLibError( + "The layer order content does not match the glyph sets that have been created." + ) + layerContents = [ + (layerName, self.layerContents[layerName]) + for layerName in layerOrder + if layerName is not None + ] + self._writePlist(LAYERCONTENTS_FILENAME, layerContents) + + def _findDirectoryForLayerName(self, layerName: Optional[str]) -> str: + foundDirectory = None + for existingLayerName, directoryName in list(self.layerContents.items()): + if layerName is None and directoryName == DEFAULT_GLYPHS_DIRNAME: + foundDirectory = directoryName + break + elif existingLayerName == layerName: + foundDirectory = directoryName + break + if not foundDirectory: + raise UFOLibError( + "Could not locate a glyph set directory for the layer named %s." + % layerName + ) + return foundDirectory + + def getGlyphSet( # type: ignore[override] + self, + layerName: Optional[str] = None, + defaultLayer: bool = True, + glyphNameToFileNameFunc: GlyphNameToFileNameFunc = None, + validateRead: Optional[bool] = None, + validateWrite: Optional[bool] = None, + expectContentsFile: bool = False, + ) -> GlyphSet: + """ + Return the GlyphSet object associated with the + appropriate glyph directory in the .ufo. + If layerName is None, the default glyph set + will be used. The defaultLayer flag indicates + that the layer should be saved into the default + glyphs directory. + + ``validateRead`` will validate the read data, by default it is set to the + class's validate value, can be overridden. + ``validateWrte`` will validate the written data, by default it is set to the + class's validate value, can be overridden. + ``expectContentsFile`` will raise a GlifLibError if a contents.plist file is + not found on the glyph set file system. This should be set to ``True`` if you + are reading an existing UFO and ``False`` if you use ``getGlyphSet`` to create + a fresh glyph set. + """ + if validateRead is None: + validateRead = self._validate + if validateWrite is None: + validateWrite = self._validate + # only default can be written in < 3 + if self._formatVersion < UFOFormatVersion.FORMAT_3_0 and ( + not defaultLayer or layerName is not None + ): + raise UFOLibError( + f"Only the default layer can be writen in UFO {self._formatVersion.major}." + ) + # locate a layer name when None has been given + if layerName is None and defaultLayer: + for existingLayerName, directory in self.layerContents.items(): + if directory == DEFAULT_GLYPHS_DIRNAME: + layerName = existingLayerName + if layerName is None: + layerName = DEFAULT_LAYER_NAME + elif layerName is None and not defaultLayer: + raise UFOLibError("A layer name must be provided for non-default layers.") + # move along to format specific writing + if self._formatVersion < UFOFormatVersion.FORMAT_3_0: + return self._getDefaultGlyphSet( + validateRead, + validateWrite, + glyphNameToFileNameFunc=glyphNameToFileNameFunc, + expectContentsFile=expectContentsFile, + ) + elif self._formatVersion.major == UFOFormatVersion.FORMAT_3_0.major: + return self._getGlyphSetFormatVersion3( + validateRead, + validateWrite, + layerName=layerName, + defaultLayer=defaultLayer, + glyphNameToFileNameFunc=glyphNameToFileNameFunc, + expectContentsFile=expectContentsFile, + ) + else: + raise NotImplementedError(self._formatVersion) + + def _getDefaultGlyphSet( + self, + validateRead: bool, + validateWrite: bool, + glyphNameToFileNameFunc: GlyphNameToFileNameFunc = None, + expectContentsFile: bool = False, + ) -> GlyphSet: + from fontTools.ufoLib.glifLib import GlyphSet + + glyphSubFS = self.fs.makedir(DEFAULT_GLYPHS_DIRNAME, recreate=True) + return GlyphSet( + glyphSubFS, + glyphNameToFileNameFunc=glyphNameToFileNameFunc, + ufoFormatVersion=self._formatVersion, + validateRead=validateRead, + validateWrite=validateWrite, + expectContentsFile=expectContentsFile, + ) + + def _getGlyphSetFormatVersion3( + self, + validateRead: bool, + validateWrite: bool, + layerName: Optional[str] = None, + defaultLayer: bool = True, + glyphNameToFileNameFunc: GlyphNameToFileNameFunc = None, + expectContentsFile: bool = False, + ) -> GlyphSet: + from fontTools.ufoLib.glifLib import GlyphSet + + # if the default flag is on, make sure that the default in the file + # matches the default being written. also make sure that this layer + # name is not already linked to a non-default layer. + if defaultLayer: + for existingLayerName, directory in self.layerContents.items(): + if directory == DEFAULT_GLYPHS_DIRNAME: + if existingLayerName != layerName: + raise UFOLibError( + "Another layer ('%s') is already mapped to the default directory." + % existingLayerName + ) + elif existingLayerName == layerName: + raise UFOLibError( + "The layer name is already mapped to a non-default layer." + ) + + # handle layerName is None to avoid MyPy errors + if layerName is None: + raise TypeError("'leyerName' cannot be None.") + + # get an existing directory name + if layerName in self.layerContents: + directory = self.layerContents[layerName] + # get a new directory name + else: + if defaultLayer: + directory = DEFAULT_GLYPHS_DIRNAME + else: + # not caching this could be slightly expensive, + # but caching it will be cumbersome + existing = {d.lower() for d in self.layerContents.values()} + directory = userNameToFileName( + layerName, existing=existing, prefix="glyphs." + ) + # make the directory + glyphSubFS = self.fs.makedir(directory, recreate=True) + # store the mapping + self.layerContents[layerName] = directory + # load the glyph set + return GlyphSet( + glyphSubFS, + glyphNameToFileNameFunc=glyphNameToFileNameFunc, + ufoFormatVersion=self._formatVersion, + validateRead=validateRead, + validateWrite=validateWrite, + expectContentsFile=expectContentsFile, + ) + + def renameGlyphSet( + self, + layerName: Optional[str], + newLayerName: Optional[str], + defaultLayer: bool = False, + ) -> None: + """ + Rename a glyph set. + + Note: if a GlyphSet object has already been retrieved for + layerName, it is up to the caller to inform that object that + the directory it represents has changed. + """ + if self._formatVersion < UFOFormatVersion.FORMAT_3_0: + # ignore renaming glyph sets for UFO1 UFO2 + # just write the data from the default layer + return + # the new and old names can be the same + # as long as the default is being switched + if layerName is not None and layerName == newLayerName: + # if the default is off and the layer is already not the default, skip + if ( + self.layerContents[layerName] != DEFAULT_GLYPHS_DIRNAME + and not defaultLayer + ): + return + # if the default is on and the layer is already the default, skip + if self.layerContents[layerName] == DEFAULT_GLYPHS_DIRNAME and defaultLayer: + return + else: + # make sure the new layer name doesn't already exist + if newLayerName is None: + newLayerName = DEFAULT_LAYER_NAME + if newLayerName in self.layerContents: + raise UFOLibError("A layer named %s already exists." % newLayerName) + # make sure the default layer doesn't already exist + if defaultLayer and DEFAULT_GLYPHS_DIRNAME in self.layerContents.values(): + raise UFOLibError("A default layer already exists.") + # get the paths + oldDirectory = self._findDirectoryForLayerName(layerName) + if defaultLayer: + newDirectory = DEFAULT_GLYPHS_DIRNAME + else: + existing = {name.lower() for name in self.layerContents.values()} + newDirectory = userNameToFileName( + newLayerName, existing=existing, prefix="glyphs." + ) + # update the internal mapping + if layerName is not None: + del self.layerContents[layerName] + self.layerContents[newLayerName] = newDirectory + # do the file system copy + self.fs.movedir(oldDirectory, newDirectory, create=True) + + def deleteGlyphSet(self, layerName: Optional[str]) -> None: + """ + Remove the glyph set matching layerName. + """ + if self._formatVersion < UFOFormatVersion.FORMAT_3_0: + # ignore deleting glyph sets for UFO1 UFO2 as there are no layers + # just write the data from the default layer + return + foundDirectory = self._findDirectoryForLayerName(layerName) + self.removePath(foundDirectory, removeEmptyParents=False) + if layerName is not None: + del self.layerContents[layerName] + + def writeData(self, fileName: PathStr, data: bytes) -> None: + """ + Write data to fileName in the 'data' directory. + The data must be a bytes string. + """ + self.writeBytesToPath(f"{DATA_DIRNAME}/{fsdecode(fileName)}", data) + + def removeData(self, fileName: PathStr) -> None: + """ + Remove the file named fileName from the data directory. + """ + self.removePath(f"{DATA_DIRNAME}/{fsdecode(fileName)}") + + # /images + + def writeImage( + self, + fileName: PathStr, + data: bytes, + validate: Optional[bool] = None, + ) -> None: + """ + Write data to fileName in the images directory. + The data must be a valid PNG. + """ + if validate is None: + validate = self._validate + if self._formatVersion < UFOFormatVersion.FORMAT_3_0: + raise UFOLibError( + f"Images are not allowed in UFO {self._formatVersion.major}." + ) + fileName = fsdecode(fileName) + if validate: + valid, error = pngValidator(data=data) + if not valid: + raise UFOLibError(error) + self.writeBytesToPath(f"{IMAGES_DIRNAME}/{fileName}", data) + + def removeImage( + self, + fileName: PathStr, + validate: Optional[bool] = None, + ) -> None: # XXX remove unused 'validate'? + """ + Remove the file named fileName from the + images directory. + """ + if self._formatVersion < UFOFormatVersion.FORMAT_3_0: + raise UFOLibError( + f"Images are not allowed in UFO {self._formatVersion.major}." + ) + self.removePath(f"{IMAGES_DIRNAME}/{fsdecode(fileName)}") + + def copyImageFromReader( + self, + reader: UFOReader, + sourceFileName: PathStr, + destFileName: PathStr, + validate: Optional[bool] = None, + ) -> None: + """ + Copy the sourceFileName in the provided UFOReader to destFileName + in this writer. This uses the most memory efficient method possible + for copying the data possible. + """ + if validate is None: + validate = self._validate + if self._formatVersion < UFOFormatVersion.FORMAT_3_0: + raise UFOLibError( + f"Images are not allowed in UFO {self._formatVersion.major}." + ) + sourcePath = f"{IMAGES_DIRNAME}/{fsdecode(sourceFileName)}" + destPath = f"{IMAGES_DIRNAME}/{fsdecode(destFileName)}" + self.copyFromReader(reader, sourcePath, destPath) + + def close(self) -> None: + if self._havePreviousFile and self._fileStructure is UFOFileStructure.ZIP: + # if we are updating an existing zip file, we can now compress the + # contents of the temporary filesystem in the destination path + rootDir = os.path.splitext(os.path.basename(self._path))[0] + ".ufo" + with fs.zipfs.ZipFS(self._path, write=True, encoding="utf-8") as destFS: # type: ignore[abstract] + fs.copy.copy_fs(self.fs, destFS.makedir(rootDir)) + super().close() + + +# just an alias, makes it more explicit +UFOReaderWriter = UFOWriter + + +# ---------------- +# Helper Functions +# ---------------- + + +def _sniffFileStructure(ufo_path: PathStr) -> UFOFileStructure: + """Return UFOFileStructure.ZIP if the UFO at path 'ufo_path' (str) + is a zip file, else return UFOFileStructure.PACKAGE if 'ufo_path' is a + directory. + Raise UFOLibError if it is a file with unknown structure, or if the path + does not exist. + """ + if zipfile.is_zipfile(ufo_path): + return UFOFileStructure.ZIP + elif os.path.isdir(ufo_path): + return UFOFileStructure.PACKAGE + elif os.path.isfile(ufo_path): + raise UFOLibError( + "The specified UFO does not have a known structure: '%s'" % ufo_path + ) + else: + raise UFOLibError("No such file or directory: '%s'" % ufo_path) + + +def makeUFOPath(path: PathStr) -> str: + """ + Return a .ufo pathname. + + >>> makeUFOPath("directory/something.ext") == ( + ... os.path.join('directory', 'something.ufo')) + True + >>> makeUFOPath("directory/something.another.thing.ext") == ( + ... os.path.join('directory', 'something.another.thing.ufo')) + True + """ + dir, name = os.path.split(path) + name = ".".join([".".join(name.split(".")[:-1]), "ufo"]) + return os.path.join(dir, name) + + +# ---------------------- +# fontinfo.plist Support +# ---------------------- + +# Version Validators + +# There is no version 1 validator and there shouldn't be. +# The version 1 spec was very loose and there were numerous +# cases of invalid values. + + +def validateFontInfoVersion2ValueForAttribute(attr: str, value: Any) -> bool: + """ + This performs very basic validation of the value for attribute + following the UFO 2 fontinfo.plist specification. The results + of this should not be interpretted as *correct* for the font + that they are part of. This merely indicates that the value + is of the proper type and, where the specification defines + a set range of possible values for an attribute, that the + value is in the accepted range. + """ + dataValidationDict = fontInfoAttributesVersion2ValueData[attr] + valueType = dataValidationDict.get("type") + validator = dataValidationDict.get("valueValidator", genericTypeValidator) + valueOptions = dataValidationDict.get("valueOptions") + # have specific options for the validator + if valueOptions is not None: + isValidValue = validator(value, valueOptions) + # no specific options + else: + if validator == genericTypeValidator: + isValidValue = validator(value, valueType) + else: + isValidValue = validator(value) + return isValidValue + + +def validateInfoVersion2Data(infoData: dict[str, Any]) -> dict[str, Any]: + """ + This performs very basic validation of the value for infoData + following the UFO 2 fontinfo.plist specification. The results + of this should not be interpretted as *correct* for the font + that they are part of. This merely indicates that the values + are of the proper type and, where the specification defines + a set range of possible values for an attribute, that the + value is in the accepted range. + """ + validInfoData = {} + for attr, value in list(infoData.items()): + isValidValue = validateFontInfoVersion2ValueForAttribute(attr, value) + if not isValidValue: + raise UFOLibError(f"Invalid value for attribute {attr} ({value!r}).") + else: + validInfoData[attr] = value + return validInfoData + + +def validateFontInfoVersion3ValueForAttribute(attr: str, value: Any) -> bool: + """ + This performs very basic validation of the value for attribute + following the UFO 3 fontinfo.plist specification. The results + of this should not be interpretted as *correct* for the font + that they are part of. This merely indicates that the value + is of the proper type and, where the specification defines + a set range of possible values for an attribute, that the + value is in the accepted range. + """ + dataValidationDict = fontInfoAttributesVersion3ValueData[attr] + valueType = dataValidationDict.get("type") + validator = dataValidationDict.get("valueValidator", genericTypeValidator) + valueOptions = dataValidationDict.get("valueOptions") + # have specific options for the validator + if valueOptions is not None: + isValidValue = validator(value, valueOptions) + # no specific options + else: + if validator == genericTypeValidator: + isValidValue = validator(value, valueType) + else: + isValidValue = validator(value) + return isValidValue + + +def validateInfoVersion3Data(infoData: dict[str, Any]) -> dict[str, Any]: + """ + This performs very basic validation of the value for infoData + following the UFO 3 fontinfo.plist specification. The results + of this should not be interpretted as *correct* for the font + that they are part of. This merely indicates that the values + are of the proper type and, where the specification defines + a set range of possible values for an attribute, that the + value is in the accepted range. + """ + validInfoData = {} + for attr, value in list(infoData.items()): + isValidValue = validateFontInfoVersion3ValueForAttribute(attr, value) + if not isValidValue: + raise UFOLibError(f"Invalid value for attribute {attr} ({value!r}).") + else: + validInfoData[attr] = value + return validInfoData + + +# Value Options + +fontInfoOpenTypeHeadFlagsOptions: list[int] = list(range(0, 15)) +fontInfoOpenTypeOS2SelectionOptions: list[int] = [1, 2, 3, 4, 7, 8, 9] +fontInfoOpenTypeOS2UnicodeRangesOptions: list[int] = list(range(0, 128)) +fontInfoOpenTypeOS2CodePageRangesOptions: list[int] = list(range(0, 64)) +fontInfoOpenTypeOS2TypeOptions: list[int] = [0, 1, 2, 3, 8, 9] + +# Version Attribute Definitions +# This defines the attributes, types and, in some +# cases the possible values, that can exist is +# fontinfo.plist. + +fontInfoAttributesVersion1: set[str] = { + "familyName", + "styleName", + "fullName", + "fontName", + "menuName", + "fontStyle", + "note", + "versionMajor", + "versionMinor", + "year", + "copyright", + "notice", + "trademark", + "license", + "licenseURL", + "createdBy", + "designer", + "designerURL", + "vendorURL", + "unitsPerEm", + "ascender", + "descender", + "capHeight", + "xHeight", + "defaultWidth", + "slantAngle", + "italicAngle", + "widthName", + "weightName", + "weightValue", + "fondName", + "otFamilyName", + "otStyleName", + "otMacName", + "msCharSet", + "fondID", + "uniqueID", + "ttVendor", + "ttUniqueID", + "ttVersion", +} + +fontInfoAttributesVersion2ValueData: FontInfoAttributes = { + "familyName": dict(type=str), + "styleName": dict(type=str), + "styleMapFamilyName": dict(type=str), + "styleMapStyleName": dict( + type=str, valueValidator=fontInfoStyleMapStyleNameValidator + ), + "versionMajor": dict(type=int), + "versionMinor": dict(type=int), + "year": dict(type=int), + "copyright": dict(type=str), + "trademark": dict(type=str), + "unitsPerEm": dict(type=(int, float)), + "descender": dict(type=(int, float)), + "xHeight": dict(type=(int, float)), + "capHeight": dict(type=(int, float)), + "ascender": dict(type=(int, float)), + "italicAngle": dict(type=(float, int)), + "note": dict(type=str), + "openTypeHeadCreated": dict( + type=str, valueValidator=fontInfoOpenTypeHeadCreatedValidator + ), + "openTypeHeadLowestRecPPEM": dict(type=(int, float)), + "openTypeHeadFlags": dict( + type="integerList", + valueValidator=genericIntListValidator, + valueOptions=fontInfoOpenTypeHeadFlagsOptions, + ), + "openTypeHheaAscender": dict(type=(int, float)), + "openTypeHheaDescender": dict(type=(int, float)), + "openTypeHheaLineGap": dict(type=(int, float)), + "openTypeHheaCaretSlopeRise": dict(type=int), + "openTypeHheaCaretSlopeRun": dict(type=int), + "openTypeHheaCaretOffset": dict(type=(int, float)), + "openTypeNameDesigner": dict(type=str), + "openTypeNameDesignerURL": dict(type=str), + "openTypeNameManufacturer": dict(type=str), + "openTypeNameManufacturerURL": dict(type=str), + "openTypeNameLicense": dict(type=str), + "openTypeNameLicenseURL": dict(type=str), + "openTypeNameVersion": dict(type=str), + "openTypeNameUniqueID": dict(type=str), + "openTypeNameDescription": dict(type=str), + "openTypeNamePreferredFamilyName": dict(type=str), + "openTypeNamePreferredSubfamilyName": dict(type=str), + "openTypeNameCompatibleFullName": dict(type=str), + "openTypeNameSampleText": dict(type=str), + "openTypeNameWWSFamilyName": dict(type=str), + "openTypeNameWWSSubfamilyName": dict(type=str), + "openTypeOS2WidthClass": dict( + type=int, valueValidator=fontInfoOpenTypeOS2WidthClassValidator + ), + "openTypeOS2WeightClass": dict( + type=int, valueValidator=fontInfoOpenTypeOS2WeightClassValidator + ), + "openTypeOS2Selection": dict( + type="integerList", + valueValidator=genericIntListValidator, + valueOptions=fontInfoOpenTypeOS2SelectionOptions, + ), + "openTypeOS2VendorID": dict(type=str), + "openTypeOS2Panose": dict( + type="integerList", valueValidator=fontInfoVersion2OpenTypeOS2PanoseValidator + ), + "openTypeOS2FamilyClass": dict( + type="integerList", valueValidator=fontInfoOpenTypeOS2FamilyClassValidator + ), + "openTypeOS2UnicodeRanges": dict( + type="integerList", + valueValidator=genericIntListValidator, + valueOptions=fontInfoOpenTypeOS2UnicodeRangesOptions, + ), + "openTypeOS2CodePageRanges": dict( + type="integerList", + valueValidator=genericIntListValidator, + valueOptions=fontInfoOpenTypeOS2CodePageRangesOptions, + ), + "openTypeOS2TypoAscender": dict(type=(int, float)), + "openTypeOS2TypoDescender": dict(type=(int, float)), + "openTypeOS2TypoLineGap": dict(type=(int, float)), + "openTypeOS2WinAscent": dict(type=(int, float)), + "openTypeOS2WinDescent": dict(type=(int, float)), + "openTypeOS2Type": dict( + type="integerList", + valueValidator=genericIntListValidator, + valueOptions=fontInfoOpenTypeOS2TypeOptions, + ), + "openTypeOS2SubscriptXSize": dict(type=(int, float)), + "openTypeOS2SubscriptYSize": dict(type=(int, float)), + "openTypeOS2SubscriptXOffset": dict(type=(int, float)), + "openTypeOS2SubscriptYOffset": dict(type=(int, float)), + "openTypeOS2SuperscriptXSize": dict(type=(int, float)), + "openTypeOS2SuperscriptYSize": dict(type=(int, float)), + "openTypeOS2SuperscriptXOffset": dict(type=(int, float)), + "openTypeOS2SuperscriptYOffset": dict(type=(int, float)), + "openTypeOS2StrikeoutSize": dict(type=(int, float)), + "openTypeOS2StrikeoutPosition": dict(type=(int, float)), + "openTypeVheaVertTypoAscender": dict(type=(int, float)), + "openTypeVheaVertTypoDescender": dict(type=(int, float)), + "openTypeVheaVertTypoLineGap": dict(type=(int, float)), + "openTypeVheaCaretSlopeRise": dict(type=int), + "openTypeVheaCaretSlopeRun": dict(type=int), + "openTypeVheaCaretOffset": dict(type=(int, float)), + "postscriptFontName": dict(type=str), + "postscriptFullName": dict(type=str), + "postscriptSlantAngle": dict(type=(float, int)), + "postscriptUniqueID": dict(type=int), + "postscriptUnderlineThickness": dict(type=(int, float)), + "postscriptUnderlinePosition": dict(type=(int, float)), + "postscriptIsFixedPitch": dict(type=bool), + "postscriptBlueValues": dict( + type="integerList", valueValidator=fontInfoPostscriptBluesValidator + ), + "postscriptOtherBlues": dict( + type="integerList", valueValidator=fontInfoPostscriptOtherBluesValidator + ), + "postscriptFamilyBlues": dict( + type="integerList", valueValidator=fontInfoPostscriptBluesValidator + ), + "postscriptFamilyOtherBlues": dict( + type="integerList", valueValidator=fontInfoPostscriptOtherBluesValidator + ), + "postscriptStemSnapH": dict( + type="integerList", valueValidator=fontInfoPostscriptStemsValidator + ), + "postscriptStemSnapV": dict( + type="integerList", valueValidator=fontInfoPostscriptStemsValidator + ), + "postscriptBlueFuzz": dict(type=(int, float)), + "postscriptBlueShift": dict(type=(int, float)), + "postscriptBlueScale": dict(type=(float, int)), + "postscriptForceBold": dict(type=bool), + "postscriptDefaultWidthX": dict(type=(int, float)), + "postscriptNominalWidthX": dict(type=(int, float)), + "postscriptWeightName": dict(type=str), + "postscriptDefaultCharacter": dict(type=str), + "postscriptWindowsCharacterSet": dict( + type=int, valueValidator=fontInfoPostscriptWindowsCharacterSetValidator + ), + "macintoshFONDFamilyID": dict(type=int), + "macintoshFONDName": dict(type=str), +} +fontInfoAttributesVersion2: set[str] = set(fontInfoAttributesVersion2ValueData.keys()) + +fontInfoAttributesVersion3ValueData: FontInfoAttributes = deepcopy( + fontInfoAttributesVersion2ValueData +) +fontInfoAttributesVersion3ValueData.update( + { + "versionMinor": dict(type=int, valueValidator=genericNonNegativeIntValidator), + "unitsPerEm": dict( + type=(int, float), valueValidator=genericNonNegativeNumberValidator + ), + "openTypeHeadLowestRecPPEM": dict( + type=int, valueValidator=genericNonNegativeNumberValidator + ), + "openTypeHheaAscender": dict(type=int), + "openTypeHheaDescender": dict(type=int), + "openTypeHheaLineGap": dict(type=int), + "openTypeHheaCaretOffset": dict(type=int), + "openTypeOS2Panose": dict( + type="integerList", + valueValidator=fontInfoVersion3OpenTypeOS2PanoseValidator, + ), + "openTypeOS2TypoAscender": dict(type=int), + "openTypeOS2TypoDescender": dict(type=int), + "openTypeOS2TypoLineGap": dict(type=int), + "openTypeOS2WinAscent": dict( + type=int, valueValidator=genericNonNegativeNumberValidator + ), + "openTypeOS2WinDescent": dict( + type=int, valueValidator=genericNonNegativeNumberValidator + ), + "openTypeOS2SubscriptXSize": dict(type=int), + "openTypeOS2SubscriptYSize": dict(type=int), + "openTypeOS2SubscriptXOffset": dict(type=int), + "openTypeOS2SubscriptYOffset": dict(type=int), + "openTypeOS2SuperscriptXSize": dict(type=int), + "openTypeOS2SuperscriptYSize": dict(type=int), + "openTypeOS2SuperscriptXOffset": dict(type=int), + "openTypeOS2SuperscriptYOffset": dict(type=int), + "openTypeOS2StrikeoutSize": dict(type=int), + "openTypeOS2StrikeoutPosition": dict(type=int), + "openTypeGaspRangeRecords": dict( + type="dictList", valueValidator=fontInfoOpenTypeGaspRangeRecordsValidator + ), + "openTypeNameRecords": dict( + type="dictList", valueValidator=fontInfoOpenTypeNameRecordsValidator + ), + "openTypeVheaVertTypoAscender": dict(type=int), + "openTypeVheaVertTypoDescender": dict(type=int), + "openTypeVheaVertTypoLineGap": dict(type=int), + "openTypeVheaCaretOffset": dict(type=int), + "woffMajorVersion": dict( + type=int, valueValidator=genericNonNegativeIntValidator + ), + "woffMinorVersion": dict( + type=int, valueValidator=genericNonNegativeIntValidator + ), + "woffMetadataUniqueID": dict( + type=dict, valueValidator=fontInfoWOFFMetadataUniqueIDValidator + ), + "woffMetadataVendor": dict( + type=dict, valueValidator=fontInfoWOFFMetadataVendorValidator + ), + "woffMetadataCredits": dict( + type=dict, valueValidator=fontInfoWOFFMetadataCreditsValidator + ), + "woffMetadataDescription": dict( + type=dict, valueValidator=fontInfoWOFFMetadataDescriptionValidator + ), + "woffMetadataLicense": dict( + type=dict, valueValidator=fontInfoWOFFMetadataLicenseValidator + ), + "woffMetadataCopyright": dict( + type=dict, valueValidator=fontInfoWOFFMetadataCopyrightValidator + ), + "woffMetadataTrademark": dict( + type=dict, valueValidator=fontInfoWOFFMetadataTrademarkValidator + ), + "woffMetadataLicensee": dict( + type=dict, valueValidator=fontInfoWOFFMetadataLicenseeValidator + ), + "woffMetadataExtensions": dict( + type=list, valueValidator=fontInfoWOFFMetadataExtensionsValidator + ), + "guidelines": dict(type=list, valueValidator=guidelinesValidator), + } +) +fontInfoAttributesVersion3: set[str] = set(fontInfoAttributesVersion3ValueData.keys()) + +# insert the type validator for all attrs that +# have no defined validator. +for attr, dataDict in list(fontInfoAttributesVersion2ValueData.items()): + if "valueValidator" not in dataDict: + dataDict["valueValidator"] = genericTypeValidator + +for attr, dataDict in list(fontInfoAttributesVersion3ValueData.items()): + if "valueValidator" not in dataDict: + dataDict["valueValidator"] = genericTypeValidator + +# Version Conversion Support +# These are used from converting from version 1 +# to version 2 or vice-versa. + + +def _flipDict(d: dict[K, V]) -> dict[V, K]: + flipped = {} + for key, value in list(d.items()): + flipped[value] = key + return flipped + + +fontInfoAttributesVersion1To2: dict[str, str] = { + "menuName": "styleMapFamilyName", + "designer": "openTypeNameDesigner", + "designerURL": "openTypeNameDesignerURL", + "createdBy": "openTypeNameManufacturer", + "vendorURL": "openTypeNameManufacturerURL", + "license": "openTypeNameLicense", + "licenseURL": "openTypeNameLicenseURL", + "ttVersion": "openTypeNameVersion", + "ttUniqueID": "openTypeNameUniqueID", + "notice": "openTypeNameDescription", + "otFamilyName": "openTypeNamePreferredFamilyName", + "otStyleName": "openTypeNamePreferredSubfamilyName", + "otMacName": "openTypeNameCompatibleFullName", + "weightName": "postscriptWeightName", + "weightValue": "openTypeOS2WeightClass", + "ttVendor": "openTypeOS2VendorID", + "uniqueID": "postscriptUniqueID", + "fontName": "postscriptFontName", + "fondID": "macintoshFONDFamilyID", + "fondName": "macintoshFONDName", + "defaultWidth": "postscriptDefaultWidthX", + "slantAngle": "postscriptSlantAngle", + "fullName": "postscriptFullName", + # require special value conversion + "fontStyle": "styleMapStyleName", + "widthName": "openTypeOS2WidthClass", + "msCharSet": "postscriptWindowsCharacterSet", +} +fontInfoAttributesVersion2To1 = _flipDict(fontInfoAttributesVersion1To2) +deprecatedFontInfoAttributesVersion2 = set(fontInfoAttributesVersion1To2.keys()) + +_fontStyle1To2: dict[int, str] = { + 64: "regular", + 1: "italic", + 32: "bold", + 33: "bold italic", +} +_fontStyle2To1: dict[str, int] = _flipDict(_fontStyle1To2) +# Some UFO 1 files have 0 +_fontStyle1To2[0] = "regular" + +_widthName1To2: dict[str, int] = { + "Ultra-condensed": 1, + "Extra-condensed": 2, + "Condensed": 3, + "Semi-condensed": 4, + "Medium (normal)": 5, + "Semi-expanded": 6, + "Expanded": 7, + "Extra-expanded": 8, + "Ultra-expanded": 9, +} +_widthName2To1: dict[int, str] = _flipDict(_widthName1To2) +# FontLab's default width value is "Normal". +# Many format version 1 UFOs will have this. +_widthName1To2["Normal"] = 5 +# FontLab has an "All" width value. In UFO 1 +# move this up to "Normal". +_widthName1To2["All"] = 5 +# "medium" appears in a lot of UFO 1 files. +_widthName1To2["medium"] = 5 +# "Medium" appears in a lot of UFO 1 files. +_widthName1To2["Medium"] = 5 + +_msCharSet1To2: dict[int, int] = { + 0: 1, + 1: 2, + 2: 3, + 77: 4, + 128: 5, + 129: 6, + 130: 7, + 134: 8, + 136: 9, + 161: 10, + 162: 11, + 163: 12, + 177: 13, + 178: 14, + 186: 15, + 200: 16, + 204: 17, + 222: 18, + 238: 19, + 255: 20, +} +_msCharSet2To1: dict[int, int] = _flipDict(_msCharSet1To2) + +# 1 <-> 2 + + +def convertFontInfoValueForAttributeFromVersion1ToVersion2( + attr: str, value: Any +) -> tuple[str, Any]: + """ + Convert value from version 1 to version 2 format. + Returns the new attribute name and the converted value. + If the value is None, None will be returned for the new value. + """ + # convert floats to ints if possible + if isinstance(value, float): + if int(value) == value: + value = int(value) + if value is not None: + if attr == "fontStyle": + v: Optional[Union[str, int]] = _fontStyle1To2.get(value) + if v is None: + raise UFOLibError( + f"Cannot convert value ({value!r}) for attribute {attr}." + ) + value = v + elif attr == "widthName": + v = _widthName1To2.get(value) + if v is None: + raise UFOLibError( + f"Cannot convert value ({value!r}) for attribute {attr}." + ) + value = v + elif attr == "msCharSet": + v = _msCharSet1To2.get(value) + if v is None: + raise UFOLibError( + f"Cannot convert value ({value!r}) for attribute {attr}." + ) + value = v + attr = fontInfoAttributesVersion1To2.get(attr, attr) + return attr, value + + +def convertFontInfoValueForAttributeFromVersion2ToVersion1( + attr: str, value: Any +) -> tuple[str, Any]: + """ + Convert value from version 2 to version 1 format. + Returns the new attribute name and the converted value. + If the value is None, None will be returned for the new value. + """ + if value is not None: + if attr == "styleMapStyleName": + value = _fontStyle2To1.get(value) + elif attr == "openTypeOS2WidthClass": + value = _widthName2To1.get(value) + elif attr == "postscriptWindowsCharacterSet": + value = _msCharSet2To1.get(value) + attr = fontInfoAttributesVersion2To1.get(attr, attr) + return attr, value + + +def _convertFontInfoDataVersion1ToVersion2(data: dict[str, Any]) -> dict[str, Any]: + converted = {} + for attr, value in list(data.items()): + # FontLab gives -1 for the weightValue + # for fonts wil no defined value. Many + # format version 1 UFOs will have this. + if attr == "weightValue" and value == -1: + continue + newAttr, newValue = convertFontInfoValueForAttributeFromVersion1ToVersion2( + attr, value + ) + # skip if the attribute is not part of version 2 + if newAttr not in fontInfoAttributesVersion2: + continue + # catch values that can't be converted + if value is None: + raise UFOLibError( + f"Cannot convert value ({value!r}) for attribute {newAttr}." + ) + # store + converted[newAttr] = newValue + return converted + + +def _convertFontInfoDataVersion2ToVersion1(data: dict[str, Any]) -> dict[str, Any]: + converted = {} + for attr, value in list(data.items()): + newAttr, newValue = convertFontInfoValueForAttributeFromVersion2ToVersion1( + attr, value + ) + # only take attributes that are registered for version 1 + if newAttr not in fontInfoAttributesVersion1: + continue + # catch values that can't be converted + if value is None: + raise UFOLibError( + f"Cannot convert value ({value!r}) for attribute {newAttr}." + ) + # store + converted[newAttr] = newValue + return converted + + +# 2 <-> 3 + +_ufo2To3NonNegativeInt: set[str] = { + "versionMinor", + "openTypeHeadLowestRecPPEM", + "openTypeOS2WinAscent", + "openTypeOS2WinDescent", +} +_ufo2To3NonNegativeIntOrFloat: set[str] = { + "unitsPerEm", +} +_ufo2To3FloatToInt: set[str] = { + "openTypeHeadLowestRecPPEM", + "openTypeHheaAscender", + "openTypeHheaDescender", + "openTypeHheaLineGap", + "openTypeHheaCaretOffset", + "openTypeOS2TypoAscender", + "openTypeOS2TypoDescender", + "openTypeOS2TypoLineGap", + "openTypeOS2WinAscent", + "openTypeOS2WinDescent", + "openTypeOS2SubscriptXSize", + "openTypeOS2SubscriptYSize", + "openTypeOS2SubscriptXOffset", + "openTypeOS2SubscriptYOffset", + "openTypeOS2SuperscriptXSize", + "openTypeOS2SuperscriptYSize", + "openTypeOS2SuperscriptXOffset", + "openTypeOS2SuperscriptYOffset", + "openTypeOS2StrikeoutSize", + "openTypeOS2StrikeoutPosition", + "openTypeVheaVertTypoAscender", + "openTypeVheaVertTypoDescender", + "openTypeVheaVertTypoLineGap", + "openTypeVheaCaretOffset", +} + + +def convertFontInfoValueForAttributeFromVersion2ToVersion3( + attr: str, value: Any +) -> tuple[str, Any]: + """ + Convert value from version 2 to version 3 format. + Returns the new attribute name and the converted value. + If the value is None, None will be returned for the new value. + """ + if attr in _ufo2To3FloatToInt: + try: + value = round(value) + except (ValueError, TypeError): + raise UFOLibError("Could not convert value for %s." % attr) + if attr in _ufo2To3NonNegativeInt: + try: + value = int(abs(value)) + except (ValueError, TypeError): + raise UFOLibError("Could not convert value for %s." % attr) + elif attr in _ufo2To3NonNegativeIntOrFloat: + try: + v = float(abs(value)) + except (ValueError, TypeError): + raise UFOLibError("Could not convert value for %s." % attr) + if v == int(v): + v = int(v) + if v != value: + value = v + return attr, value + + +def convertFontInfoValueForAttributeFromVersion3ToVersion2( + attr: str, value: Any +) -> tuple[str, Any]: + """ + Convert value from version 3 to version 2 format. + Returns the new attribute name and the converted value. + If the value is None, None will be returned for the new value. + """ + return attr, value + + +def _convertFontInfoDataVersion3ToVersion2(data: dict[str, Any]) -> dict[str, Any]: + converted = {} + for attr, value in list(data.items()): + newAttr, newValue = convertFontInfoValueForAttributeFromVersion3ToVersion2( + attr, value + ) + if newAttr not in fontInfoAttributesVersion2: + continue + converted[newAttr] = newValue + return converted + + +def _convertFontInfoDataVersion2ToVersion3(data: dict[str, Any]) -> dict[str, Any]: + converted = {} + for attr, value in list(data.items()): + attr, value = convertFontInfoValueForAttributeFromVersion2ToVersion3( + attr, value + ) + converted[attr] = value + return converted + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62f7a34f3102c3408b4afdaf6823bce0f3386d90 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/converters.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/converters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c208f7ff1469b5eaa1e01f560b2da5b69f936498 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/converters.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/errors.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/errors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cec67cb46e5baddb19e0d6ba609408834e1ff38 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/errors.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/etree.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/etree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baaa1ef6d539abbaf0ae6e228c226d473b7a1e11 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/etree.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/filenames.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/filenames.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82b15a72d483474ab63dde014e7c9ecfe33fa1ff Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/filenames.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/glifLib.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/glifLib.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdcd04eefed478327d865715d5a647bb438d51f6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/glifLib.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/kerning.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/kerning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..454f232fb8297bc07f43e9992dc60bf755896c72 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/kerning.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/plistlib.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/plistlib.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdb74716b7f776220c80854d6b50271819e5a016 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/plistlib.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/pointPen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/pointPen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc149c2c9e4c3dc541413f83ad2be66973a7484e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/pointPen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..feed29f2121e7eea495d11d3a2a8a586d2e9a857 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/validators.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/validators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f61d0741e89ae6a122bdbbda7cc6d6bd5246930 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/__pycache__/validators.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/converters.py b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/converters.py new file mode 100644 index 0000000000000000000000000000000000000000..94a229f48d2f89bf0fc51b3b1a2a0f083b97f81d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/converters.py @@ -0,0 +1,407 @@ +from __future__ import annotations + +from typing import Mapping, Any +from collections.abc import Container + +from fontTools.annotations import KerningNested + +""" +Functions for converting UFO1 or UFO2 files into UFO3 format. + +Currently provides functionality for converting kerning rules +and kerning groups. Conversion is only supported _from_ UFO1 +or UFO2, and _to_ UFO3. +""" + +# adapted from the UFO spec + + +def convertUFO1OrUFO2KerningToUFO3Kerning( + kerning: KerningNested, groups: dict[str, list[str]], glyphSet: Container[str] = () +) -> tuple[KerningNested, dict[str, list[str]], dict[str, dict[str, str]]]: + """Convert kerning data in UFO1 or UFO2 syntax into UFO3 syntax. + + Args: + kerning: + A dictionary containing the kerning rules defined in + the UFO font, as used in :class:`.UFOReader` objects. + groups: + A dictionary containing the groups defined in the UFO + font, as used in :class:`.UFOReader` objects. + glyphSet: + Optional; a set of glyph objects to skip (default: None). + + Returns: + 1. A dictionary representing the converted kerning data. + 2. A copy of the groups dictionary, with all groups renamed to UFO3 syntax. + 3. A dictionary containing the mapping of old group names to new group names. + + """ + # gather known kerning groups based on the prefixes + firstReferencedGroups, secondReferencedGroups = findKnownKerningGroups(groups) + # Make lists of groups referenced in kerning pairs. + for first, seconds in list(kerning.items()): + if first in groups and first not in glyphSet: + if not first.startswith("public.kern1."): + firstReferencedGroups.add(first) + for second in list(seconds.keys()): + if second in groups and second not in glyphSet: + if not second.startswith("public.kern2."): + secondReferencedGroups.add(second) + # Create new names for these groups. + firstRenamedGroups: dict[str, str] = {} + for first in firstReferencedGroups: + # Make a list of existing group names. + existingGroupNames = list(groups.keys()) + list(firstRenamedGroups.keys()) + # Remove the old prefix from the name + newName = first.replace("@MMK_L_", "") + # Add the new prefix to the name. + newName = "public.kern1." + newName + # Make a unique group name. + newName = makeUniqueGroupName(newName, existingGroupNames) + # Store for use later. + firstRenamedGroups[first] = newName + secondRenamedGroups: dict[str, str] = {} + for second in secondReferencedGroups: + # Make a list of existing group names. + existingGroupNames = list(groups.keys()) + list(secondRenamedGroups.keys()) + # Remove the old prefix from the name + newName = second.replace("@MMK_R_", "") + # Add the new prefix to the name. + newName = "public.kern2." + newName + # Make a unique group name. + newName = makeUniqueGroupName(newName, existingGroupNames) + # Store for use later. + secondRenamedGroups[second] = newName + # Populate the new group names into the kerning dictionary as needed. + newKerning = {} + for first, seconds in list(kerning.items()): + first = firstRenamedGroups.get(first, first) + newSeconds = {} + for second, value in list(seconds.items()): + second = secondRenamedGroups.get(second, second) + newSeconds[second] = value + newKerning[first] = newSeconds + # Make copies of the referenced groups and store them + # under the new names in the overall groups dictionary. + allRenamedGroups = list(firstRenamedGroups.items()) + allRenamedGroups += list(secondRenamedGroups.items()) + for oldName, newName in allRenamedGroups: + group = list(groups[oldName]) + groups[newName] = group + # Return the kerning and the groups. + return newKerning, groups, dict(side1=firstRenamedGroups, side2=secondRenamedGroups) + + +def findKnownKerningGroups(groups: Mapping[str, Any]) -> tuple[set[str], set[str]]: + """Find all kerning groups in a UFO1 or UFO2 font that use known prefixes. + + In some cases, not all kerning groups will be referenced + by the kerning pairs in a UFO. The algorithm for locating + groups in :func:`convertUFO1OrUFO2KerningToUFO3Kerning` will + miss these unreferenced groups. By scanning for known prefixes, + this function will catch all of the prefixed groups. + + The prefixes and sides by this function are: + + @MMK_L_ - side 1 + @MMK_R_ - side 2 + + as defined in the UFO1 specification. + + Args: + groups: + A dictionary containing the groups defined in the UFO + font, as read by :class:`.UFOReader`. + + Returns: + Two sets; the first containing the names of all + first-side kerning groups identified in the ``groups`` + dictionary, and the second containing the names of all + second-side kerning groups identified. + + "First-side" and "second-side" are with respect to the + writing direction of the script. + + Example:: + + >>> testGroups = { + ... "@MMK_L_1" : None, + ... "@MMK_L_2" : None, + ... "@MMK_L_3" : None, + ... "@MMK_R_1" : None, + ... "@MMK_R_2" : None, + ... "@MMK_R_3" : None, + ... "@MMK_l_1" : None, + ... "@MMK_r_1" : None, + ... "@MMK_X_1" : None, + ... "foo" : None, + ... } + >>> first, second = findKnownKerningGroups(testGroups) + >>> sorted(first) == ['@MMK_L_1', '@MMK_L_2', '@MMK_L_3'] + True + >>> sorted(second) == ['@MMK_R_1', '@MMK_R_2', '@MMK_R_3'] + True + """ + knownFirstGroupPrefixes = ["@MMK_L_"] + knownSecondGroupPrefixes = ["@MMK_R_"] + firstGroups = set() + secondGroups = set() + for groupName in list(groups.keys()): + for firstPrefix in knownFirstGroupPrefixes: + if groupName.startswith(firstPrefix): + firstGroups.add(groupName) + break + for secondPrefix in knownSecondGroupPrefixes: + if groupName.startswith(secondPrefix): + secondGroups.add(groupName) + break + return firstGroups, secondGroups + + +def makeUniqueGroupName(name: str, groupNames: list[str], counter: int = 0) -> str: + """Make a kerning group name that will be unique within the set of group names. + + If the requested kerning group name already exists within the set, this + will return a new name by adding an incremented counter to the end + of the requested name. + + Args: + name: + The requested kerning group name. + groupNames: + A list of the existing kerning group names. + counter: + Optional; a counter of group names already seen (default: 0). If + :attr:`.counter` is not provided, the function will recurse, + incrementing the value of :attr:`.counter` until it finds the + first unused ``name+counter`` combination, and return that result. + + Returns: + A unique kerning group name composed of the requested name suffixed + by the smallest available integer counter. + """ + # Add a number to the name if the counter is higher than zero. + newName = name + if counter > 0: + newName = "%s%d" % (newName, counter) + # If the new name is in the existing group names, recurse. + if newName in groupNames: + return makeUniqueGroupName(name, groupNames, counter + 1) + # Otherwise send back the new name. + return newName + + +def test(): + """ + Tests for :func:`.convertUFO1OrUFO2KerningToUFO3Kerning`. + + No known prefixes. + + >>> testKerning = { + ... "A" : { + ... "A" : 1, + ... "B" : 2, + ... "CGroup" : 3, + ... "DGroup" : 4 + ... }, + ... "BGroup" : { + ... "A" : 5, + ... "B" : 6, + ... "CGroup" : 7, + ... "DGroup" : 8 + ... }, + ... "CGroup" : { + ... "A" : 9, + ... "B" : 10, + ... "CGroup" : 11, + ... "DGroup" : 12 + ... }, + ... } + >>> testGroups = { + ... "BGroup" : ["B"], + ... "CGroup" : ["C"], + ... "DGroup" : ["D"], + ... } + >>> kerning, groups, maps = convertUFO1OrUFO2KerningToUFO3Kerning( + ... testKerning, testGroups, []) + >>> expected = { + ... "A" : { + ... "A": 1, + ... "B": 2, + ... "public.kern2.CGroup": 3, + ... "public.kern2.DGroup": 4 + ... }, + ... "public.kern1.BGroup": { + ... "A": 5, + ... "B": 6, + ... "public.kern2.CGroup": 7, + ... "public.kern2.DGroup": 8 + ... }, + ... "public.kern1.CGroup": { + ... "A": 9, + ... "B": 10, + ... "public.kern2.CGroup": 11, + ... "public.kern2.DGroup": 12 + ... } + ... } + >>> kerning == expected + True + >>> expected = { + ... "BGroup": ["B"], + ... "CGroup": ["C"], + ... "DGroup": ["D"], + ... "public.kern1.BGroup": ["B"], + ... "public.kern1.CGroup": ["C"], + ... "public.kern2.CGroup": ["C"], + ... "public.kern2.DGroup": ["D"], + ... } + >>> groups == expected + True + + Known prefixes. + + >>> testKerning = { + ... "A" : { + ... "A" : 1, + ... "B" : 2, + ... "@MMK_R_CGroup" : 3, + ... "@MMK_R_DGroup" : 4 + ... }, + ... "@MMK_L_BGroup" : { + ... "A" : 5, + ... "B" : 6, + ... "@MMK_R_CGroup" : 7, + ... "@MMK_R_DGroup" : 8 + ... }, + ... "@MMK_L_CGroup" : { + ... "A" : 9, + ... "B" : 10, + ... "@MMK_R_CGroup" : 11, + ... "@MMK_R_DGroup" : 12 + ... }, + ... } + >>> testGroups = { + ... "@MMK_L_BGroup" : ["B"], + ... "@MMK_L_CGroup" : ["C"], + ... "@MMK_L_XGroup" : ["X"], + ... "@MMK_R_CGroup" : ["C"], + ... "@MMK_R_DGroup" : ["D"], + ... "@MMK_R_XGroup" : ["X"], + ... } + >>> kerning, groups, maps = convertUFO1OrUFO2KerningToUFO3Kerning( + ... testKerning, testGroups, []) + >>> expected = { + ... "A" : { + ... "A": 1, + ... "B": 2, + ... "public.kern2.CGroup": 3, + ... "public.kern2.DGroup": 4 + ... }, + ... "public.kern1.BGroup": { + ... "A": 5, + ... "B": 6, + ... "public.kern2.CGroup": 7, + ... "public.kern2.DGroup": 8 + ... }, + ... "public.kern1.CGroup": { + ... "A": 9, + ... "B": 10, + ... "public.kern2.CGroup": 11, + ... "public.kern2.DGroup": 12 + ... } + ... } + >>> kerning == expected + True + >>> expected = { + ... "@MMK_L_BGroup": ["B"], + ... "@MMK_L_CGroup": ["C"], + ... "@MMK_L_XGroup": ["X"], + ... "@MMK_R_CGroup": ["C"], + ... "@MMK_R_DGroup": ["D"], + ... "@MMK_R_XGroup": ["X"], + ... "public.kern1.BGroup": ["B"], + ... "public.kern1.CGroup": ["C"], + ... "public.kern1.XGroup": ["X"], + ... "public.kern2.CGroup": ["C"], + ... "public.kern2.DGroup": ["D"], + ... "public.kern2.XGroup": ["X"], + ... } + >>> groups == expected + True + + >>> from .validators import kerningValidator + >>> kerningValidator(kerning) + (True, None) + + Mixture of known prefixes and groups without prefixes. + + >>> testKerning = { + ... "A" : { + ... "A" : 1, + ... "B" : 2, + ... "@MMK_R_CGroup" : 3, + ... "DGroup" : 4 + ... }, + ... "BGroup" : { + ... "A" : 5, + ... "B" : 6, + ... "@MMK_R_CGroup" : 7, + ... "DGroup" : 8 + ... }, + ... "@MMK_L_CGroup" : { + ... "A" : 9, + ... "B" : 10, + ... "@MMK_R_CGroup" : 11, + ... "DGroup" : 12 + ... }, + ... } + >>> testGroups = { + ... "BGroup" : ["B"], + ... "@MMK_L_CGroup" : ["C"], + ... "@MMK_R_CGroup" : ["C"], + ... "DGroup" : ["D"], + ... } + >>> kerning, groups, maps = convertUFO1OrUFO2KerningToUFO3Kerning( + ... testKerning, testGroups, []) + >>> expected = { + ... "A" : { + ... "A": 1, + ... "B": 2, + ... "public.kern2.CGroup": 3, + ... "public.kern2.DGroup": 4 + ... }, + ... "public.kern1.BGroup": { + ... "A": 5, + ... "B": 6, + ... "public.kern2.CGroup": 7, + ... "public.kern2.DGroup": 8 + ... }, + ... "public.kern1.CGroup": { + ... "A": 9, + ... "B": 10, + ... "public.kern2.CGroup": 11, + ... "public.kern2.DGroup": 12 + ... } + ... } + >>> kerning == expected + True + >>> expected = { + ... "BGroup": ["B"], + ... "@MMK_L_CGroup": ["C"], + ... "@MMK_R_CGroup": ["C"], + ... "DGroup": ["D"], + ... "public.kern1.BGroup": ["B"], + ... "public.kern1.CGroup": ["C"], + ... "public.kern2.CGroup": ["C"], + ... "public.kern2.DGroup": ["D"], + ... } + >>> groups == expected + True + """ + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/errors.py b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..c7596c55d0405fa98cd80f8907b628f141d2545a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/errors.py @@ -0,0 +1,30 @@ +from __future__ import annotations + + +class UFOLibError(Exception): + pass + + +class UnsupportedUFOFormat(UFOLibError): + pass + + +class GlifLibError(UFOLibError): + """An error raised by glifLib. + + This class is a loose backport of PEP 678, adding a :attr:`.note` + attribute that can hold additional context for errors encountered. + + It will be maintained until only Python 3.11-and-later are supported. + """ + + def _add_note(self, note: str) -> None: + # Loose backport of PEP 678 until we only support Python 3.11+, used for + # adding additional context to errors. + # TODO: Replace with https://docs.python.org/3.11/library/exceptions.html#BaseException.add_note + message, *rest = self.args + self.args = ((message + "\n" + note), *rest) + + +class UnsupportedGLIFFormat(GlifLibError): + pass diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/etree.py b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/etree.py new file mode 100644 index 0000000000000000000000000000000000000000..07b924ac8523c0680b175f0269c42fa1959abc47 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/etree.py @@ -0,0 +1,6 @@ +"""DEPRECATED - This module is kept here only as a backward compatibility shim +for the old ufoLib.etree module, which was moved to :mod:`fontTools.misc.etree`. +Please use the latter instead. +""" + +from fontTools.misc.etree import * diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/filenames.py b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/filenames.py new file mode 100644 index 0000000000000000000000000000000000000000..6a4090a75536a0dc1e3d7b7e096982d3e6287726 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/filenames.py @@ -0,0 +1,356 @@ +from __future__ import annotations + +from collections.abc import Iterable + +""" +Convert user-provided internal UFO names to spec-compliant filenames. + +This module implements the algorithm for converting between a "user name" - +something that a user can choose arbitrarily inside a font editor - and a file +name suitable for use in a wide range of operating systems and filesystems. + +The `UFO 3 specification <http://unifiedfontobject.org/versions/ufo3/conventions/>`_ +provides an example of an algorithm for such conversion, which avoids illegal +characters, reserved file names, ambiguity between upper- and lower-case +characters, and clashes with existing files. + +This code was originally copied from +`ufoLib <https://github.com/unified-font-object/ufoLib/blob/8747da7/Lib/ufoLib/filenames.py>`_ +by Tal Leming and is copyright (c) 2005-2016, The RoboFab Developers: + +- Erik van Blokland +- Tal Leming +- Just van Rossum +""" + +# Restrictions are taken mostly from +# https://docs.microsoft.com/en-gb/windows/win32/fileio/naming-a-file#naming-conventions. +# +# 1. Integer value zero, sometimes referred to as the ASCII NUL character. +# 2. Characters whose integer representations are in the range 1 to 31, +# inclusive. +# 3. Various characters that (mostly) Windows and POSIX-y filesystems don't +# allow, plus "(" and ")", as per the specification. +illegalCharacters: set[str] = { + "\x00", + "\x01", + "\x02", + "\x03", + "\x04", + "\x05", + "\x06", + "\x07", + "\x08", + "\t", + "\n", + "\x0b", + "\x0c", + "\r", + "\x0e", + "\x0f", + "\x10", + "\x11", + "\x12", + "\x13", + "\x14", + "\x15", + "\x16", + "\x17", + "\x18", + "\x19", + "\x1a", + "\x1b", + "\x1c", + "\x1d", + "\x1e", + "\x1f", + '"', + "*", + "+", + "/", + ":", + "<", + ">", + "?", + "[", + "\\", + "]", + "(", + ")", + "|", + "\x7f", +} +reservedFileNames: set[str] = { + "aux", + "clock$", + "com1", + "com2", + "com3", + "com4", + "com5", + "com6", + "com7", + "com8", + "com9", + "con", + "lpt1", + "lpt2", + "lpt3", + "lpt4", + "lpt5", + "lpt6", + "lpt7", + "lpt8", + "lpt9", + "nul", + "prn", +} +maxFileNameLength: int = 255 + + +class NameTranslationError(Exception): + pass + + +def userNameToFileName( + userName: str, existing: Iterable[str] = (), prefix: str = "", suffix: str = "" +) -> str: + """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 string + 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 + + +def handleClash1( + userName: str, existing: Iterable[str] = [], prefix: str = "", suffix: str = "" +) -> str: + """A helper function that resolves collisions with existing names when choosing a filename. + + This function attempts to append an unused integer counter to the filename. + + 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. + + >>> 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 + + +def handleClash2( + existing: Iterable[str] = [], prefix: str = "", suffix: str = "" +) -> str: + """A helper function that resolves collisions with existing names when choosing a filename. + + This function is a fallback to :func:`handleClash1`. It attempts to append an unused integer counter to the filename. + + 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:: + + >>> 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 + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/glifLib.py b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/glifLib.py new file mode 100644 index 0000000000000000000000000000000000000000..c9929b2f69bcd7c5e93e4c65e24361e87d9d534a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/glifLib.py @@ -0,0 +1,2123 @@ +""" +Generic module for reading and writing the .glif format. + +More info about the .glif format (GLyphInterchangeFormat) can be found here: + + http://unifiedfontobject.org + +The main class in this module is :class:`GlyphSet`. It manages a set of .glif files +in a folder. It offers two ways to read glyph data, and one way to write +glyph data. See the class doc string for details. +""" + +from __future__ import annotations + +import logging +from collections import OrderedDict +from typing import TYPE_CHECKING, Any, Optional, Union, cast +from warnings import warn + +import fontTools.misc.filesystem as fs +from fontTools.misc import etree, plistlib +from fontTools.misc.textTools import tobytes +from fontTools.pens.pointPen import AbstractPointPen, PointToSegmentPen +from fontTools.ufoLib import UFOFormatVersion, _UFOBaseIO +from fontTools.ufoLib.errors import GlifLibError +from fontTools.ufoLib.filenames import userNameToFileName +from fontTools.ufoLib.utils import ( + BaseFormatVersion, + normalizeFormatVersion, + numberTypes, +) +from fontTools.ufoLib.validators import ( + anchorsValidator, + colorValidator, + genericTypeValidator, + glyphLibValidator, + guidelinesValidator, + identifierValidator, + imageValidator, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Set + from logging import Logger + + from fontTools.annotations import ( + ElementType, + FormatVersion, + FormatVersions, + GLIFFormatVersionInput, + GlyphNameToFileNameFunc, + IntFloat, + PathOrFS, + UFOFormatVersionInput, + ) + from fontTools.misc.filesystem._base import FS + + +__all__: list[str] = [ + "GlyphSet", + "GlifLibError", + "readGlyphFromString", + "writeGlyphToString", + "glyphNameToFileName", +] + +logger: Logger = logging.getLogger(__name__) + + +# --------- +# Constants +# --------- + +CONTENTS_FILENAME = "contents.plist" +LAYERINFO_FILENAME = "layerinfo.plist" + + +class GLIFFormatVersion(BaseFormatVersion): + """Class representing the versions of the .glif format supported by the UFO version in use. + + For a given :mod:`fontTools.ufoLib.UFOFormatVersion`, the :func:`supported_versions` method will + return the supported versions of the GLIF file format. If the UFO version is unspecified, the + :func:`supported_versions` method will return all available GLIF format versions. + """ + + FORMAT_1_0 = (1, 0) + FORMAT_2_0 = (2, 0) + + @classmethod + def default( + cls, ufoFormatVersion: Optional[UFOFormatVersion] = None + ) -> GLIFFormatVersion: + if ufoFormatVersion is not None: + return max(cls.supported_versions(ufoFormatVersion)) + return super().default() + + @classmethod + def supported_versions( + cls, ufoFormatVersion: Optional[UFOFormatVersion] = None + ) -> frozenset[GLIFFormatVersion]: + if ufoFormatVersion is None: + # if ufo format unspecified, return all the supported GLIF formats + return super().supported_versions() + # else only return the GLIF formats supported by the given UFO format + versions = {cls.FORMAT_1_0} + if ufoFormatVersion >= UFOFormatVersion.FORMAT_3_0: + versions.add(cls.FORMAT_2_0) + return frozenset(versions) + + +# ------------ +# Simple Glyph +# ------------ + + +class Glyph: + """ + Minimal glyph object. It has no glyph attributes until either + the draw() or the drawPoints() method has been called. + """ + + def __init__(self, glyphName: str, glyphSet: GlyphSet) -> None: + self.glyphName: str = glyphName + self.glyphSet: GlyphSet = glyphSet + + def draw(self, pen: Any, outputImpliedClosingLine: bool = False) -> None: + """ + Draw this glyph onto a *FontTools* Pen. + """ + pointPen = PointToSegmentPen( + pen, outputImpliedClosingLine=outputImpliedClosingLine + ) + self.drawPoints(pointPen) + + def drawPoints(self, pointPen: AbstractPointPen) -> None: + """ + Draw this glyph onto a PointPen. + """ + self.glyphSet.readGlyph(self.glyphName, self, pointPen) + + +# --------- +# Glyph Set +# --------- + + +class GlyphSet(_UFOBaseIO): + """ + GlyphSet manages a set of .glif files inside one directory. + + GlyphSet's constructor takes a path to an existing directory as it's + first argument. Reading glyph data can either be done through the + readGlyph() method, or by using GlyphSet's dictionary interface, where + the keys are glyph names and the values are (very) simple glyph objects. + + To write a glyph to the glyph set, you use the writeGlyph() method. + The simple glyph objects returned through the dict interface do not + support writing, they are just a convenient way to get at the glyph data. + """ + + glyphClass = Glyph + + def __init__( + self, + path: PathOrFS, + glyphNameToFileNameFunc: GlyphNameToFileNameFunc = None, + ufoFormatVersion: UFOFormatVersionInput = None, + validateRead: bool = True, + validateWrite: bool = True, + expectContentsFile: bool = False, + ) -> None: + """ + 'path' should be a path (string) to an existing local directory, or + an instance of fs.base.FS class. + + The optional 'glyphNameToFileNameFunc' argument must be a callback + function that takes two arguments: a glyph name and a list of all + existing filenames (if any exist). It should return a file name + (including the .glif extension). The glyphNameToFileName function + is called whenever a file name is created for a given glyph name. + + ``validateRead`` will validate read operations. Its default is ``True``. + ``validateWrite`` will validate write operations. Its default is ``True``. + ``expectContentsFile`` will raise a GlifLibError if a contents.plist file is + not found on the glyph set file system. This should be set to ``True`` if you + are reading an existing UFO and ``False`` if you create a fresh glyph set. + """ + try: + ufoFormatVersion = normalizeFormatVersion( + ufoFormatVersion, UFOFormatVersion + ) + except ValueError as e: + from fontTools.ufoLib.errors import UnsupportedUFOFormat + + raise UnsupportedUFOFormat( + f"Unsupported UFO format: {ufoFormatVersion!r}" + ) from e + + if hasattr(path, "__fspath__"): # support os.PathLike objects + path = path.__fspath__() + + if isinstance(path, str): + try: + filesystem: FS = fs.osfs.OSFS(path) + except fs.errors.CreateFailed: + raise GlifLibError("No glyphs directory '%s'" % path) + self._shouldClose: bool = True + elif isinstance(path, fs.base.FS): + filesystem = path + try: + filesystem.check() + except fs.errors.FilesystemClosed: + raise GlifLibError("the filesystem '%s' is closed" % filesystem) + self._shouldClose = False + else: + raise TypeError( + "Expected a path string or fs object, found %s" % type(path).__name__ + ) + try: + path = filesystem.getsyspath("/") + except fs.errors.NoSysPath: + # network or in-memory FS may not map to the local one + path = str(filesystem) + # 'dirName' is kept for backward compatibility only, but it's DEPRECATED + # as it's not guaranteed that it maps to an existing OSFS directory. + # Client could use the FS api via the `self.fs` attribute instead. + self.dirName: str = fs.path.basename(path) + self.fs: FS = filesystem + # if glyphSet contains no 'contents.plist', we consider it empty + self._havePreviousFile: bool = filesystem.exists(CONTENTS_FILENAME) + if expectContentsFile and not self._havePreviousFile: + raise GlifLibError(f"{CONTENTS_FILENAME} is missing.") + # attribute kept for backward compatibility + self.ufoFormatVersion: int = ufoFormatVersion.major + self.ufoFormatVersionTuple: UFOFormatVersion = ufoFormatVersion + if glyphNameToFileNameFunc is None: + glyphNameToFileNameFunc = glyphNameToFileName + self.glyphNameToFileName: Callable[[str, set[str]], str] = ( + glyphNameToFileNameFunc + ) + self._validateRead: bool = validateRead + self._validateWrite: bool = validateWrite + self._existingFileNames: set[str] | None = None + self._reverseContents: Optional[dict[str, str]] = None + + self.rebuildContents() + + def rebuildContents(self, validateRead: bool = False) -> None: + """ + Rebuild the contents dict by loading contents.plist. + + ``validateRead`` will validate the data, by default it is set to the + class's ``validateRead`` value, can be overridden. + """ + if validateRead is None: + validateRead = self._validateRead + contents = self._getPlist(CONTENTS_FILENAME, {}) + # validate the contents + if validateRead: + invalidFormat = False + if not isinstance(contents, dict): + invalidFormat = True + else: + for name, fileName in contents.items(): + if not isinstance(name, str): + invalidFormat = True + if not isinstance(fileName, str): + invalidFormat = True + elif not self.fs.exists(fileName): + raise GlifLibError( + "%s references a file that does not exist: %s" + % (CONTENTS_FILENAME, fileName) + ) + if invalidFormat: + raise GlifLibError("%s is not properly formatted" % CONTENTS_FILENAME) + self.contents: dict[str, str] = contents + self._existingFileNames = None + self._reverseContents = None + + def getReverseContents(self) -> dict[str, str]: + """ + Return a reversed dict of self.contents, mapping file names to + glyph names. This is primarily an aid for custom glyph name to file + name schemes that want to make sure they don't generate duplicate + file names. The file names are converted to lowercase so we can + reliably check for duplicates that only differ in case, which is + important for case-insensitive file systems. + """ + if self._reverseContents is None: + d = {} + for k, v in self.contents.items(): + d[v.lower()] = k + self._reverseContents = d + return self._reverseContents + + def writeContents(self) -> None: + """ + Write the contents.plist file out to disk. Call this method when + you're done writing glyphs. + """ + self._writePlist(CONTENTS_FILENAME, self.contents) + + # layer info + + def readLayerInfo(self, info: Any, validateRead: Optional[bool] = None) -> None: + """ + ``validateRead`` will validate the data, by default it is set to the + class's ``validateRead`` value, can be overridden. + """ + if validateRead is None: + validateRead = self._validateRead + infoDict = self._getPlist(LAYERINFO_FILENAME, {}) + if validateRead: + if not isinstance(infoDict, dict): + raise GlifLibError("layerinfo.plist is not properly formatted.") + infoDict = validateLayerInfoVersion3Data(infoDict) + # populate the object + for attr, value in infoDict.items(): + try: + setattr(info, attr, value) + except AttributeError: + raise GlifLibError( + "The supplied layer info object does not support setting a necessary attribute (%s)." + % attr + ) + + def writeLayerInfo(self, info: Any, validateWrite: Optional[bool] = None) -> None: + """ + ``validateWrite`` will validate the data, by default it is set to the + class's ``validateWrite`` value, can be overridden. + """ + if validateWrite is None: + validateWrite = self._validateWrite + if self.ufoFormatVersionTuple.major < 3: + raise GlifLibError( + "layerinfo.plist is not allowed in UFO %d." + % self.ufoFormatVersionTuple.major + ) + # gather data + infoData = {} + for attr in layerInfoVersion3ValueData.keys(): + if hasattr(info, attr): + try: + value = getattr(info, attr) + except AttributeError: + raise GlifLibError( + "The supplied info object does not support getting a necessary attribute (%s)." + % attr + ) + if value is None or (attr == "lib" and not value): + continue + infoData[attr] = value + if infoData: + # validate + if validateWrite: + infoData = validateLayerInfoVersion3Data(infoData) + # write file + self._writePlist(LAYERINFO_FILENAME, infoData) + elif self._havePreviousFile and self.fs.exists(LAYERINFO_FILENAME): + # data empty, remove existing file + self.fs.remove(LAYERINFO_FILENAME) + + def getGLIF(self, glyphName: str) -> bytes: + """ + Get the raw GLIF text for a given glyph name. This only works + for GLIF files that are already on disk. + + This method is useful in situations when the raw XML needs to be + read from a glyph set for a particular glyph before fully parsing + it into an object structure via the readGlyph method. + + Raises KeyError if 'glyphName' is not in contents.plist, or + GlifLibError if the file associated with can't be found. + """ + fileName = self.contents[glyphName] + try: + return self.fs.readbytes(fileName) + except fs.errors.ResourceNotFound: + raise GlifLibError( + "The file '%s' associated with glyph '%s' in contents.plist " + "does not exist on %s" % (fileName, glyphName, self.fs) + ) + + def getGLIFModificationTime(self, glyphName: str) -> Optional[float]: + """ + Returns the modification time for the GLIF file with 'glyphName', as + a floating point number giving the number of seconds since the epoch. + Return None if the associated file does not exist or the underlying + filesystem does not support getting modified times. + Raises KeyError if the glyphName is not in contents.plist. + """ + fileName = self.contents[glyphName] + return self.getFileModificationTime(fileName) + + # reading/writing API + + def readGlyph( + self, + glyphName: str, + glyphObject: Optional[Any] = None, + pointPen: Optional[AbstractPointPen] = None, + validate: Optional[bool] = None, + ) -> None: + """ + Read a .glif file for 'glyphName' from the glyph set. The + 'glyphObject' argument can be any kind of object (even None); + the readGlyph() method will attempt to set the following + attributes on it: + + width + the advance width of the glyph + height + the advance height of the glyph + unicodes + a list of unicode values for this glyph + note + a string + lib + a dictionary containing custom data + image + a dictionary containing image data + guidelines + a list of guideline data dictionaries + anchors + a list of anchor data dictionaries + + All attributes are optional, in two ways: + + 1) An attribute *won't* be set if the .glif file doesn't + contain data for it. 'glyphObject' will have to deal + with default values itself. + 2) If setting the attribute fails with an AttributeError + (for example if the 'glyphObject' attribute is read- + only), readGlyph() will not propagate that exception, + but ignore that attribute. + + To retrieve outline information, you need to pass an object + conforming to the PointPen protocol as the 'pointPen' argument. + This argument may be None if you don't need the outline data. + + readGlyph() will raise KeyError if the glyph is not present in + the glyph set. + + ``validate`` will validate the data, by default it is set to the + class's ``validateRead`` value, can be overridden. + """ + if validate is None: + validate = self._validateRead + text = self.getGLIF(glyphName) + try: + tree = _glifTreeFromString(text) + formatVersions = GLIFFormatVersion.supported_versions( + self.ufoFormatVersionTuple + ) + _readGlyphFromTree( + tree, + glyphObject, + pointPen, + formatVersions=formatVersions, + validate=validate, + ) + except GlifLibError as glifLibError: + # Re-raise with a note that gives extra context, describing where + # the error occurred. + fileName = self.contents[glyphName] + try: + glifLocation = f"'{self.fs.getsyspath(fileName)}'" + except fs.errors.NoSysPath: + # Network or in-memory FS may not map to a local path, so use + # the best string representation we have. + glifLocation = f"'{fileName}' from '{str(self.fs)}'" + + glifLibError._add_note( + f"The issue is in glyph '{glyphName}', located in {glifLocation}." + ) + raise + + def writeGlyph( + self, + glyphName: str, + glyphObject: Optional[Any] = None, + drawPointsFunc: Optional[Callable[[AbstractPointPen], None]] = None, + formatVersion: GLIFFormatVersionInput = None, + validate: Optional[bool] = None, + ) -> None: + """ + Write a .glif file for 'glyphName' to the glyph set. The + 'glyphObject' argument can be any kind of object (even None); + the writeGlyph() method will attempt to get the following + attributes from it: + + width + the advance width of the glyph + height + the advance height of the glyph + unicodes + a list of unicode values for this glyph + note + a string + lib + a dictionary containing custom data + image + a dictionary containing image data + guidelines + a list of guideline data dictionaries + anchors + a list of anchor data dictionaries + + All attributes are optional: if 'glyphObject' doesn't + have the attribute, it will simply be skipped. + + To write outline data to the .glif file, writeGlyph() needs + a function (any callable object actually) that will take one + argument: an object that conforms to the PointPen protocol. + The function will be called by writeGlyph(); it has to call the + proper PointPen methods to transfer the outline to the .glif file. + + The GLIF format version will be chosen based on the ufoFormatVersion + passed during the creation of this object. If a particular format + version is desired, it can be passed with the formatVersion argument. + The formatVersion argument accepts either a tuple of integers for + (major, minor), or a single integer for the major digit only (with + minor digit implied as 0). + + An UnsupportedGLIFFormat exception is raised if the requested GLIF + formatVersion is not supported. + + ``validate`` will validate the data, by default it is set to the + class's ``validateWrite`` value, can be overridden. + """ + if formatVersion is None: + formatVersion = GLIFFormatVersion.default(self.ufoFormatVersionTuple) + else: + try: + formatVersion = normalizeFormatVersion(formatVersion, GLIFFormatVersion) + except ValueError as e: + from fontTools.ufoLib.errors import UnsupportedGLIFFormat + + raise UnsupportedGLIFFormat( + f"Unsupported GLIF format version: {formatVersion!r}" + ) from e + if formatVersion not in GLIFFormatVersion.supported_versions( + self.ufoFormatVersionTuple + ): + from fontTools.ufoLib.errors import UnsupportedGLIFFormat + + raise UnsupportedGLIFFormat( + f"Unsupported GLIF format version ({formatVersion!s}) " + f"for UFO format version {self.ufoFormatVersionTuple!s}." + ) + if validate is None: + validate = self._validateWrite + fileName = self.contents.get(glyphName) + if fileName is None: + if self._existingFileNames is None: + self._existingFileNames = { + fileName.lower() for fileName in self.contents.values() + } + fileName = self.glyphNameToFileName(glyphName, self._existingFileNames) + self.contents[glyphName] = fileName + self._existingFileNames.add(fileName.lower()) + if self._reverseContents is not None: + self._reverseContents[fileName.lower()] = glyphName + data = _writeGlyphToBytes( + glyphName, + glyphObject, + drawPointsFunc, + formatVersion=formatVersion, + validate=validate, + ) + if ( + self._havePreviousFile + and self.fs.exists(fileName) + and data == self.fs.readbytes(fileName) + ): + return + self.fs.writebytes(fileName, data) + + def deleteGlyph(self, glyphName: str) -> None: + """Permanently delete the glyph from the glyph set on disk. Will + raise KeyError if the glyph is not present in the glyph set. + """ + fileName = self.contents[glyphName] + self.fs.remove(fileName) + if self._existingFileNames is not None: + self._existingFileNames.remove(fileName.lower()) + if self._reverseContents is not None: + del self._reverseContents[fileName.lower()] + del self.contents[glyphName] + + # dict-like support + + def keys(self) -> list[str]: + return list(self.contents.keys()) + + def has_key(self, glyphName: str) -> bool: + return glyphName in self.contents + + __contains__ = has_key + + def __len__(self) -> int: + return len(self.contents) + + def __getitem__(self, glyphName: str) -> Any: + if glyphName not in self.contents: + raise KeyError(glyphName) + return self.glyphClass(glyphName, self) + + # quickly fetch unicode values + + def getUnicodes( + self, glyphNames: Optional[Iterable[str]] = None + ) -> dict[str, list[int]]: + """ + Return a dictionary that maps glyph names to lists containing + the unicode value[s] for that glyph, if any. This parses the .glif + files partially, so it is a lot faster than parsing all files completely. + By default this checks all glyphs, but a subset can be passed with glyphNames. + """ + unicodes = {} + if glyphNames is None: + glyphNames = self.contents.keys() + for glyphName in glyphNames: + text = self.getGLIF(glyphName) + unicodes[glyphName] = _fetchUnicodes(text) + return unicodes + + def getComponentReferences( + self, glyphNames: Optional[Iterable[str]] = None + ) -> dict[str, list[str]]: + """ + Return a dictionary that maps glyph names to lists containing the + base glyph name of components in the glyph. This parses the .glif + files partially, so it is a lot faster than parsing all files completely. + By default this checks all glyphs, but a subset can be passed with glyphNames. + """ + components = {} + if glyphNames is None: + glyphNames = self.contents.keys() + for glyphName in glyphNames: + text = self.getGLIF(glyphName) + components[glyphName] = _fetchComponentBases(text) + return components + + def getImageReferences( + self, glyphNames: Optional[Iterable[str]] = None + ) -> dict[str, Optional[str]]: + """ + Return a dictionary that maps glyph names to the file name of the image + referenced by the glyph. This parses the .glif files partially, so it is a + lot faster than parsing all files completely. + By default this checks all glyphs, but a subset can be passed with glyphNames. + """ + images = {} + if glyphNames is None: + glyphNames = self.contents.keys() + for glyphName in glyphNames: + text = self.getGLIF(glyphName) + images[glyphName] = _fetchImageFileName(text) + return images + + def close(self) -> None: + if self._shouldClose: + self.fs.close() + + def __enter__(self) -> GlyphSet: + return self + + def __exit__(self, exc_type: Any, exc_value: Any, exc_tb: Any) -> None: + self.close() + + +# ----------------------- +# Glyph Name to File Name +# ----------------------- + + +def glyphNameToFileName(glyphName: str, existingFileNames: Optional[set[str]]) -> str: + """ + Wrapper around the userNameToFileName function in filenames.py + + Note that existingFileNames should be a set for large glyphsets + or performance will suffer. + """ + if existingFileNames is None: + existingFileNames = set() + return userNameToFileName(glyphName, existing=existingFileNames, suffix=".glif") + + +# ----------------------- +# GLIF To and From String +# ----------------------- + + +def readGlyphFromString( + aString: Union[str, bytes], + glyphObject: Optional[Any] = None, + pointPen: Optional[Any] = None, + formatVersions: FormatVersions = None, + validate: bool = True, +) -> None: + """ + Read .glif data from a string into a glyph object. + + The 'glyphObject' argument can be any kind of object (even None); + the readGlyphFromString() method will attempt to set the following + attributes on it: + + width + the advance width of the glyph + height + the advance height of the glyph + unicodes + a list of unicode values for this glyph + note + a string + lib + a dictionary containing custom data + image + a dictionary containing image data + guidelines + a list of guideline data dictionaries + anchors + a list of anchor data dictionaries + + All attributes are optional, in two ways: + + 1) An attribute *won't* be set if the .glif file doesn't + contain data for it. 'glyphObject' will have to deal + with default values itself. + 2) If setting the attribute fails with an AttributeError + (for example if the 'glyphObject' attribute is read- + only), readGlyphFromString() will not propagate that + exception, but ignore that attribute. + + To retrieve outline information, you need to pass an object + conforming to the PointPen protocol as the 'pointPen' argument. + This argument may be None if you don't need the outline data. + + The formatVersions optional argument define the GLIF format versions + that are allowed to be read. + The type is Optional[Iterable[tuple[int, int], int]]. It can contain + either integers (for the major versions to be allowed, with minor + digits defaulting to 0), or tuples of integers to specify both + (major, minor) versions. + By default when formatVersions is None all the GLIF format versions + currently defined are allowed to be read. + + ``validate`` will validate the read data. It is set to ``True`` by default. + """ + tree = _glifTreeFromString(aString) + + if formatVersions is None: + validFormatVersions: Set[GLIFFormatVersion] = ( + GLIFFormatVersion.supported_versions() + ) + else: + validFormatVersions, invalidFormatVersions = set(), set() + for v in formatVersions: + try: + formatVersion = normalizeFormatVersion(v, GLIFFormatVersion) + except ValueError: + invalidFormatVersions.add(v) + else: + validFormatVersions.add(formatVersion) + if not validFormatVersions: + raise ValueError( + "None of the requested GLIF formatVersions are supported: " + f"{formatVersions!r}" + ) + + _readGlyphFromTree( + tree, + glyphObject, + pointPen, + formatVersions=validFormatVersions, + validate=validate, + ) + + +def _writeGlyphToBytes( + glyphName: str, + glyphObject: Optional[Any] = None, + drawPointsFunc: Optional[Callable[[Any], None]] = None, + writer: Optional[Any] = None, + formatVersion: Optional[FormatVersion] = None, + validate: bool = True, +) -> bytes: + """Return .glif data for a glyph as a UTF-8 encoded bytes string.""" + try: + formatVersion = normalizeFormatVersion(formatVersion, GLIFFormatVersion) + except ValueError: + from fontTools.ufoLib.errors import UnsupportedGLIFFormat + + raise UnsupportedGLIFFormat( + "Unsupported GLIF format version: {formatVersion!r}" + ) + # start + if validate and not isinstance(glyphName, str): + raise GlifLibError("The glyph name is not properly formatted.") + if validate and len(glyphName) == 0: + raise GlifLibError("The glyph name is empty.") + glyphAttrs = OrderedDict( + [("name", glyphName), ("format", repr(formatVersion.major))] + ) + if formatVersion.minor != 0: + glyphAttrs["formatMinor"] = repr(formatVersion.minor) + root = etree.Element("glyph", glyphAttrs) + identifiers: set[str] = set() + # advance + _writeAdvance(glyphObject, root, validate) + # unicodes + if getattr(glyphObject, "unicodes", None): + _writeUnicodes(glyphObject, root, validate) + # note + if getattr(glyphObject, "note", None): + _writeNote(glyphObject, root, validate) + # image + if formatVersion.major >= 2 and getattr(glyphObject, "image", None): + _writeImage(glyphObject, root, validate) + # guidelines + if formatVersion.major >= 2 and getattr(glyphObject, "guidelines", None): + _writeGuidelines(glyphObject, root, identifiers, validate) + # anchors + anchors = getattr(glyphObject, "anchors", None) + if formatVersion.major >= 2 and anchors: + _writeAnchors(glyphObject, root, identifiers, validate) + # outline + if drawPointsFunc is not None: + outline = etree.SubElement(root, "outline") + pen = GLIFPointPen(outline, identifiers=identifiers, validate=validate) + drawPointsFunc(pen) + if formatVersion.major == 1 and anchors: + _writeAnchorsFormat1(pen, anchors, validate) + # prevent lxml from writing self-closing tags + if not len(outline): + outline.text = "\n " + # lib + if getattr(glyphObject, "lib", None): + _writeLib(glyphObject, root, validate) + # return the text + data = etree.tostring( + root, encoding="UTF-8", xml_declaration=True, pretty_print=True + ) + return data + + +def writeGlyphToString( + glyphName: str, + glyphObject: Optional[Any] = None, + drawPointsFunc: Optional[Callable[[Any], None]] = None, + formatVersion: Optional[FormatVersion] = None, + validate: bool = True, +) -> str: + """ + Return .glif data for a glyph as a string. The XML declaration's + encoding is always set to "UTF-8". + The 'glyphObject' argument can be any kind of object (even None); + the writeGlyphToString() method will attempt to get the following + attributes from it: + + width + the advance width of the glyph + height + the advance height of the glyph + unicodes + a list of unicode values for this glyph + note + a string + lib + a dictionary containing custom data + image + a dictionary containing image data + guidelines + a list of guideline data dictionaries + anchors + a list of anchor data dictionaries + + All attributes are optional: if 'glyphObject' doesn't + have the attribute, it will simply be skipped. + + To write outline data to the .glif file, writeGlyphToString() needs + a function (any callable object actually) that will take one + argument: an object that conforms to the PointPen protocol. + The function will be called by writeGlyphToString(); it has to call the + proper PointPen methods to transfer the outline to the .glif file. + + The GLIF format version can be specified with the formatVersion argument. + This accepts either a tuple of integers for (major, minor), or a single + integer for the major digit only (with minor digit implied as 0). + By default when formatVesion is None the latest GLIF format version will + be used; currently it's 2.0, which is equivalent to formatVersion=(2, 0). + + An UnsupportedGLIFFormat exception is raised if the requested UFO + formatVersion is not supported. + + ``validate`` will validate the written data. It is set to ``True`` by default. + """ + data = _writeGlyphToBytes( + glyphName, + glyphObject=glyphObject, + drawPointsFunc=drawPointsFunc, + formatVersion=formatVersion, + validate=validate, + ) + return data.decode("utf-8") + + +def _writeAdvance(glyphObject: Any, element: ElementType, validate: bool) -> None: + width = getattr(glyphObject, "width", None) + if width is not None: + if validate and not isinstance(width, numberTypes): + raise GlifLibError("width attribute must be int or float") + if width == 0: + width = None + height = getattr(glyphObject, "height", None) + if height is not None: + if validate and not isinstance(height, numberTypes): + raise GlifLibError("height attribute must be int or float") + if height == 0: + height = None + if width is not None and height is not None: + etree.SubElement( + element, + "advance", + OrderedDict([("height", repr(height)), ("width", repr(width))]), + ) + elif width is not None: + etree.SubElement(element, "advance", dict(width=repr(width))) + elif height is not None: + etree.SubElement(element, "advance", dict(height=repr(height))) + + +def _writeUnicodes(glyphObject: Any, element: ElementType, validate: bool) -> None: + unicodes = getattr(glyphObject, "unicodes", []) + if validate and isinstance(unicodes, int): + unicodes = [unicodes] + seen = set() + for code in unicodes: + if validate and not isinstance(code, int): + raise GlifLibError("unicode values must be int") + if code in seen: + continue + seen.add(code) + hexCode = "%04X" % code + etree.SubElement(element, "unicode", dict(hex=hexCode)) + + +def _writeNote(glyphObject: Any, element: ElementType, validate: bool) -> None: + note = getattr(glyphObject, "note", None) + if validate and not isinstance(note, str): + raise GlifLibError("note attribute must be str") + if isinstance(note, str): + note = note.strip() + note = "\n" + note + "\n" + etree.SubElement(element, "note").text = note + + +def _writeImage(glyphObject: Any, element: ElementType, validate: bool) -> None: + image = getattr(glyphObject, "image", None) + if image is None: + return + + if validate and not imageValidator(image): + raise GlifLibError( + "image attribute must be a dict or dict-like object with the proper structure." + ) + attrs = OrderedDict([("fileName", image["fileName"])]) + for attr, default in _transformationInfo: + value = image.get(attr, default) + if value != default: + attrs[attr] = repr(value) + color = image.get("color") + if color is not None: + attrs["color"] = color + etree.SubElement(element, "image", attrs) + + +def _writeGuidelines( + glyphObject: Any, element: ElementType, identifiers: set[str], validate: bool +) -> None: + guidelines = getattr(glyphObject, "guidelines", []) + if validate and not guidelinesValidator(guidelines): + raise GlifLibError("guidelines attribute does not have the proper structure.") + for guideline in guidelines: + attrs = OrderedDict() + x = guideline.get("x") + if x is not None: + attrs["x"] = repr(x) + y = guideline.get("y") + if y is not None: + attrs["y"] = repr(y) + angle = guideline.get("angle") + if angle is not None: + attrs["angle"] = repr(angle) + name = guideline.get("name") + if name is not None: + attrs["name"] = name + color = guideline.get("color") + if color is not None: + attrs["color"] = color + identifier = guideline.get("identifier") + if identifier is not None: + if validate and identifier in identifiers: + raise GlifLibError("identifier used more than once: %s" % identifier) + attrs["identifier"] = identifier + identifiers.add(identifier) + etree.SubElement(element, "guideline", attrs) + + +def _writeAnchorsFormat1(pen: Any, anchors: Any, validate: bool) -> None: + if validate and not anchorsValidator(anchors): + raise GlifLibError("anchors attribute does not have the proper structure.") + for anchor in anchors: + attrs = {} + x = anchor["x"] + attrs["x"] = repr(x) + y = anchor["y"] + attrs["y"] = repr(y) + name = anchor.get("name") + if name is not None: + attrs["name"] = name + pen.beginPath() + pen.addPoint((x, y), segmentType="move", name=name) + pen.endPath() + + +def _writeAnchors( + glyphObject: Any, + element: ElementType, + identifiers: set[str], + validate: bool, +) -> None: + anchors = getattr(glyphObject, "anchors", []) + if validate and not anchorsValidator(anchors): + raise GlifLibError("anchors attribute does not have the proper structure.") + for anchor in anchors: + attrs = OrderedDict() + x = anchor["x"] + attrs["x"] = repr(x) + y = anchor["y"] + attrs["y"] = repr(y) + name = anchor.get("name") + if name is not None: + attrs["name"] = name + color = anchor.get("color") + if color is not None: + attrs["color"] = color + identifier = anchor.get("identifier") + if identifier is not None: + if validate and identifier in identifiers: + raise GlifLibError("identifier used more than once: %s" % identifier) + attrs["identifier"] = identifier + identifiers.add(identifier) + etree.SubElement(element, "anchor", attrs) + + +def _writeLib(glyphObject: Any, element: ElementType, validate: bool) -> None: + lib = getattr(glyphObject, "lib", None) + if not lib: + # don't write empty lib + return + if validate: + valid, message = glyphLibValidator(lib) + if not valid: + raise GlifLibError(message) + if not isinstance(lib, dict): + lib = dict(lib) + # plist inside GLIF begins with 2 levels of indentation + e = plistlib.totree(lib, indent_level=2) + etree.SubElement(element, "lib").append(e) + + +# ----------------------- +# layerinfo.plist Support +# ----------------------- + +layerInfoVersion3ValueData = { + "color": dict(type=str, valueValidator=colorValidator), + "lib": dict(type=dict, valueValidator=genericTypeValidator), +} + + +def validateLayerInfoVersion3ValueForAttribute(attr: str, value: Any) -> bool: + """ + This performs very basic validation of the value for attribute + following the UFO 3 fontinfo.plist specification. The results + of this should not be interpretted as *correct* for the font + that they are part of. This merely indicates that the value + is of the proper type and, where the specification defines + a set range of possible values for an attribute, that the + value is in the accepted range. + """ + if attr not in layerInfoVersion3ValueData: + return False + dataValidationDict = layerInfoVersion3ValueData[attr] + valueType = dataValidationDict.get("type") + validator = dataValidationDict.get("valueValidator") + valueOptions = dataValidationDict.get("valueOptions") + # have specific options for the validator + assert callable(validator) + if valueOptions is not None: + isValidValue = validator(value, valueOptions) + # no specific options + else: + if validator == genericTypeValidator: + isValidValue = validator(value, valueType) + else: + isValidValue = validator(value) + return isValidValue + + +def validateLayerInfoVersion3Data(infoData: dict[str, Any]) -> dict[str, Any]: + """ + This performs very basic validation of the value for infoData + following the UFO 3 layerinfo.plist specification. The results + of this should not be interpretted as *correct* for the font + that they are part of. This merely indicates that the values + are of the proper type and, where the specification defines + a set range of possible values for an attribute, that the + value is in the accepted range. + """ + for attr, value in infoData.items(): + if attr not in layerInfoVersion3ValueData: + raise GlifLibError("Unknown attribute %s." % attr) + isValidValue = validateLayerInfoVersion3ValueForAttribute(attr, value) + if not isValidValue: + raise GlifLibError(f"Invalid value for attribute {attr} ({value!r}).") + return infoData + + +# ----------------- +# GLIF Tree Support +# ----------------- + + +def _glifTreeFromFile(aFile: Union[str, bytes, int]) -> ElementType: + if etree._have_lxml: + tree = etree.parse(aFile, parser=etree.XMLParser(remove_comments=True)) + else: + tree = etree.parse(aFile) + root = tree.getroot() + if root.tag != "glyph": + raise GlifLibError("The GLIF is not properly formatted.") + if root.text and root.text.strip() != "": + raise GlifLibError("Invalid GLIF structure.") + return root + + +def _glifTreeFromString(aString: Union[str, bytes]) -> ElementType: + data = tobytes(aString, encoding="utf-8") + try: + if etree._have_lxml: + root = etree.fromstring(data, parser=etree.XMLParser(remove_comments=True)) + else: + root = etree.fromstring(data) + except Exception as etree_exception: + raise GlifLibError("GLIF contains invalid XML.") from etree_exception + + if root.tag != "glyph": + raise GlifLibError("The GLIF is not properly formatted.") + if root.text and root.text.strip() != "": + raise GlifLibError("Invalid GLIF structure.") + return root + + +def _readGlyphFromTree( + tree: ElementType, + glyphObject: Optional[Any] = None, + pointPen: Optional[AbstractPointPen] = None, + formatVersions: Set[GLIFFormatVersion] = GLIFFormatVersion.supported_versions(), + validate: bool = True, +) -> None: + # check the format version + formatVersionMajor = tree.get("format") + if formatVersionMajor is None: + if validate: + raise GlifLibError("Unspecified format version in GLIF.") + formatVersionMajor = 0 + formatVersionMinor = tree.get("formatMinor", 0) + try: + formatVersion = GLIFFormatVersion( + (int(formatVersionMajor), int(formatVersionMinor)) + ) + except ValueError as e: + msg = "Unsupported GLIF format: %s.%s" % ( + formatVersionMajor, + formatVersionMinor, + ) + if validate: + from fontTools.ufoLib.errors import UnsupportedGLIFFormat + + raise UnsupportedGLIFFormat(msg) from e + # warn but continue using the latest supported format + formatVersion = GLIFFormatVersion.default() + logger.warning( + "%s. Assuming the latest supported version (%s). " + "Some data may be skipped or parsed incorrectly.", + msg, + formatVersion, + ) + + if validate and formatVersion not in formatVersions: + raise GlifLibError(f"Forbidden GLIF format version: {formatVersion!s}") + + try: + readGlyphFromTree = _READ_GLYPH_FROM_TREE_FUNCS[formatVersion] + except KeyError: + raise NotImplementedError(formatVersion) + + readGlyphFromTree( + tree=tree, + glyphObject=glyphObject, + pointPen=pointPen, + validate=validate, + formatMinor=formatVersion.minor, + ) + + +def _readGlyphFromTreeFormat1( + tree: ElementType, + glyphObject: Optional[Any] = None, + pointPen: Optional[AbstractPointPen] = None, + validate: bool = False, + **kwargs: Any, +) -> None: + # get the name + _readName(glyphObject, tree, validate) + # populate the sub elements + unicodes = [] + haveSeenAdvance = haveSeenOutline = haveSeenLib = haveSeenNote = False + for element in tree: + if element.tag == "outline": + if validate: + if haveSeenOutline: + raise GlifLibError("The outline element occurs more than once.") + if element.attrib: + raise GlifLibError( + "The outline element contains unknown attributes." + ) + if element.text and element.text.strip() != "": + raise GlifLibError("Invalid outline structure.") + haveSeenOutline = True + buildOutlineFormat1(glyphObject, pointPen, element, validate) + elif glyphObject is None: + # Skip remaining elements if no glyphObject, but outline is still + # processed above to allow drawing via pointPen without a glyphObject. + continue + elif element.tag == "advance": + if validate and haveSeenAdvance: + raise GlifLibError("The advance element occurs more than once.") + haveSeenAdvance = True + _readAdvance(glyphObject, element) + elif element.tag == "unicode": + v = element.get("hex") + if v is None: + raise GlifLibError( + "A unicode element is missing its required hex attribute." + ) + try: + v = int(v, 16) + if v not in unicodes: + unicodes.append(v) + except ValueError: + raise GlifLibError( + "Illegal value for hex attribute of unicode element." + ) + elif element.tag == "note": + if validate and haveSeenNote: + raise GlifLibError("The note element occurs more than once.") + haveSeenNote = True + _readNote(glyphObject, element) + elif element.tag == "lib": + if validate and haveSeenLib: + raise GlifLibError("The lib element occurs more than once.") + haveSeenLib = True + _readLib(glyphObject, element, validate) + else: + raise GlifLibError("Unknown element in GLIF: %s" % element) + # set the collected unicodes + if unicodes: + _relaxedSetattr(glyphObject, "unicodes", unicodes) + + +def _readGlyphFromTreeFormat2( + tree: ElementType, + glyphObject: Optional[Any] = None, + pointPen: Optional[AbstractPointPen] = None, + validate: bool = False, + formatMinor: int = 0, +) -> None: + # get the name + _readName(glyphObject, tree, validate) + # populate the sub elements + unicodes = [] + guidelines = [] + anchors = [] + haveSeenAdvance = haveSeenImage = haveSeenOutline = haveSeenLib = haveSeenNote = ( + False + ) + identifiers: set[str] = set() + for element in tree: + if element.tag == "outline": + if validate: + if haveSeenOutline: + raise GlifLibError("The outline element occurs more than once.") + if element.attrib: + raise GlifLibError( + "The outline element contains unknown attributes." + ) + if element.text and element.text.strip() != "": + raise GlifLibError("Invalid outline structure.") + haveSeenOutline = True + if pointPen is not None: + buildOutlineFormat2( + glyphObject, pointPen, element, identifiers, validate + ) + elif glyphObject is None: + # Skip remaining elements if no glyphObject, but outline is still + # processed above to allow drawing via pointPen without a glyphObject. + continue + elif element.tag == "advance": + if validate and haveSeenAdvance: + raise GlifLibError("The advance element occurs more than once.") + haveSeenAdvance = True + _readAdvance(glyphObject, element) + elif element.tag == "unicode": + v = element.get("hex") + if v is None: + raise GlifLibError( + "A unicode element is missing its required hex attribute." + ) + try: + v = int(v, 16) + if v not in unicodes: + unicodes.append(v) + except ValueError: + raise GlifLibError( + "Illegal value for hex attribute of unicode element." + ) + elif element.tag == "guideline": + if validate and len(element): + raise GlifLibError("Unknown children in guideline element.") + attrib = dict(element.attrib) + for attr in ("x", "y", "angle"): + if attr in attrib: + attrib[attr] = _number(attrib[attr]) + guidelines.append(attrib) + elif element.tag == "anchor": + if validate and len(element): + raise GlifLibError("Unknown children in anchor element.") + attrib = dict(element.attrib) + for attr in ("x", "y"): + if attr in element.attrib: + attrib[attr] = _number(attrib[attr]) + anchors.append(attrib) + elif element.tag == "image": + if validate: + if haveSeenImage: + raise GlifLibError("The image element occurs more than once.") + if len(element): + raise GlifLibError("Unknown children in image element.") + haveSeenImage = True + _readImage(glyphObject, element, validate) + elif element.tag == "note": + if validate and haveSeenNote: + raise GlifLibError("The note element occurs more than once.") + haveSeenNote = True + _readNote(glyphObject, element) + elif element.tag == "lib": + if validate and haveSeenLib: + raise GlifLibError("The lib element occurs more than once.") + haveSeenLib = True + _readLib(glyphObject, element, validate) + else: + raise GlifLibError("Unknown element in GLIF: %s" % element) + # set the collected unicodes + if unicodes: + _relaxedSetattr(glyphObject, "unicodes", unicodes) + # set the collected guidelines + if guidelines: + if validate and not guidelinesValidator(guidelines, identifiers): + raise GlifLibError("The guidelines are improperly formatted.") + _relaxedSetattr(glyphObject, "guidelines", guidelines) + # set the collected anchors + if anchors: + if validate and not anchorsValidator(anchors, identifiers): + raise GlifLibError("The anchors are improperly formatted.") + _relaxedSetattr(glyphObject, "anchors", anchors) + + +_READ_GLYPH_FROM_TREE_FUNCS: dict[GLIFFormatVersion, Callable[..., Any]] = { + GLIFFormatVersion.FORMAT_1_0: _readGlyphFromTreeFormat1, + GLIFFormatVersion.FORMAT_2_0: _readGlyphFromTreeFormat2, +} + + +def _readName(glyphObject: Optional[Any], root: ElementType, validate: bool) -> None: + glyphName = root.get("name") + if validate and not glyphName: + raise GlifLibError("Empty glyph name in GLIF.") + if glyphName and glyphObject is not None: + _relaxedSetattr(glyphObject, "name", glyphName) + + +def _readAdvance(glyphObject: Optional[Any], advance: ElementType) -> None: + width = _number(advance.get("width", 0)) + _relaxedSetattr(glyphObject, "width", width) + height = _number(advance.get("height", 0)) + _relaxedSetattr(glyphObject, "height", height) + + +def _readNote(glyphObject: Optional[Any], note: ElementType) -> None: + if note.text is None: + return + lines = note.text.split("\n") + note = "\n".join(line.strip() for line in lines if line.strip()) + _relaxedSetattr(glyphObject, "note", note) + + +def _readLib(glyphObject: Optional[Any], lib: ElementType, validate: bool) -> None: + assert len(lib) == 1 + child = lib[0] + plist = plistlib.fromtree(child) + if validate: + valid, message = glyphLibValidator(plist) + if not valid: + raise GlifLibError(message) + _relaxedSetattr(glyphObject, "lib", plist) + + +def _readImage(glyphObject: Optional[Any], image: ElementType, validate: bool) -> None: + imageData = dict(image.attrib) + for attr, default in _transformationInfo: + value = imageData.get(attr, default) + imageData[attr] = _number(value) + if validate and not imageValidator(imageData): + raise GlifLibError("The image element is not properly formatted.") + _relaxedSetattr(glyphObject, "image", imageData) + + +# ---------------- +# GLIF to PointPen +# ---------------- + +contourAttributesFormat2: set[str] = {"identifier"} +componentAttributesFormat1: set[str] = { + "base", + "xScale", + "xyScale", + "yxScale", + "yScale", + "xOffset", + "yOffset", +} +componentAttributesFormat2: set[str] = componentAttributesFormat1 | {"identifier"} +pointAttributesFormat1: set[str] = {"x", "y", "type", "smooth", "name"} +pointAttributesFormat2: set[str] = pointAttributesFormat1 | {"identifier"} +pointSmoothOptions: set[str] = {"no", "yes"} +pointTypeOptions: set[str] = {"move", "line", "offcurve", "curve", "qcurve"} + +# format 1 + + +def buildOutlineFormat1( + glyphObject: Any, + pen: Optional[AbstractPointPen], + outline: Iterable[ElementType], + validate: bool, +) -> None: + anchors = [] + for element in outline: + if element.tag == "contour": + if len(element) == 1: + point = element[0] + if point.tag == "point": + anchor = _buildAnchorFormat1(point, validate) + if anchor is not None: + anchors.append(anchor) + continue + if pen is not None: + _buildOutlineContourFormat1(pen, element, validate) + elif element.tag == "component": + if pen is not None: + _buildOutlineComponentFormat1(pen, element, validate) + else: + raise GlifLibError("Unknown element in outline element: %s" % element) + if glyphObject is not None and anchors: + if validate and not anchorsValidator(anchors): + raise GlifLibError("GLIF 1 anchors are not properly formatted.") + _relaxedSetattr(glyphObject, "anchors", anchors) + + +def _buildAnchorFormat1(point: ElementType, validate: bool) -> Optional[dict[str, Any]]: + if point.get("type") != "move": + return None + name = point.get("name") + if name is None: + return None + x = point.get("x") + y = point.get("y") + if validate and x is None: + raise GlifLibError("Required x attribute is missing in point element.") + assert x is not None + if validate and y is None: + raise GlifLibError("Required y attribute is missing in point element.") + assert y is not None + x = _number(x) + y = _number(y) + anchor = dict(x=x, y=y, name=name) + return anchor + + +def _buildOutlineContourFormat1( + pen: AbstractPointPen, contour: ElementType, validate: bool +) -> None: + if validate and contour.attrib: + raise GlifLibError("Unknown attributes in contour element.") + pen.beginPath() + if len(contour): + massaged = _validateAndMassagePointStructures( + contour, + pointAttributesFormat1, + openContourOffCurveLeniency=True, + validate=validate, + ) + _buildOutlinePointsFormat1(pen, massaged) + pen.endPath() + + +def _buildOutlinePointsFormat1( + pen: AbstractPointPen, contour: list[dict[str, Any]] +) -> None: + for point in contour: + x = point["x"] + y = point["y"] + segmentType = point["segmentType"] + smooth = point["smooth"] + name = point["name"] + pen.addPoint((x, y), segmentType=segmentType, smooth=smooth, name=name) + + +def _buildOutlineComponentFormat1( + pen: AbstractPointPen, component: ElementType, validate: bool +) -> None: + if validate: + if len(component): + raise GlifLibError("Unknown child elements of component element.") + for attr in component.attrib.keys(): + if attr not in componentAttributesFormat1: + raise GlifLibError("Unknown attribute in component element: %s" % attr) + baseGlyphName = component.get("base") + if validate and baseGlyphName is None: + raise GlifLibError("The base attribute is not defined in the component.") + assert baseGlyphName is not None + transformation = tuple( + _number(component.get(attr) or default) for attr, default in _transformationInfo + ) + transformation = cast( + tuple[float, float, float, float, float, float], transformation + ) + pen.addComponent(baseGlyphName, transformation) + + +# format 2 + + +def buildOutlineFormat2( + glyphObject: Any, + pen: AbstractPointPen, + outline: Iterable[ElementType], + identifiers: set[str], + validate: bool, +) -> None: + for element in outline: + if element.tag == "contour": + _buildOutlineContourFormat2(pen, element, identifiers, validate) + elif element.tag == "component": + _buildOutlineComponentFormat2(pen, element, identifiers, validate) + else: + raise GlifLibError("Unknown element in outline element: %s" % element.tag) + + +def _buildOutlineContourFormat2( + pen: AbstractPointPen, contour: ElementType, identifiers: set[str], validate: bool +) -> None: + if validate: + for attr in contour.attrib.keys(): + if attr not in contourAttributesFormat2: + raise GlifLibError("Unknown attribute in contour element: %s" % attr) + identifier = contour.get("identifier") + if identifier is not None: + if validate: + if identifier in identifiers: + raise GlifLibError( + "The identifier %s is used more than once." % identifier + ) + if not identifierValidator(identifier): + raise GlifLibError( + "The contour identifier %s is not valid." % identifier + ) + identifiers.add(identifier) + try: + pen.beginPath(identifier=identifier) + except TypeError: + pen.beginPath() + warn( + "The beginPath method needs an identifier kwarg. The contour's identifier value has been discarded.", + DeprecationWarning, + ) + if len(contour): + massaged = _validateAndMassagePointStructures( + contour, pointAttributesFormat2, validate=validate + ) + _buildOutlinePointsFormat2(pen, massaged, identifiers, validate) + pen.endPath() + + +def _buildOutlinePointsFormat2( + pen: AbstractPointPen, + contour: list[dict[str, Any]], + identifiers: set[str], + validate: bool, +) -> None: + for point in contour: + x = point["x"] + y = point["y"] + segmentType = point["segmentType"] + smooth = point["smooth"] + name = point["name"] + identifier = point.get("identifier") + if identifier is not None: + if validate: + if identifier in identifiers: + raise GlifLibError( + "The identifier %s is used more than once." % identifier + ) + if not identifierValidator(identifier): + raise GlifLibError("The identifier %s is not valid." % identifier) + identifiers.add(identifier) + try: + pen.addPoint( + (x, y), + segmentType=segmentType, + smooth=smooth, + name=name, + identifier=identifier, + ) + except TypeError: + pen.addPoint((x, y), segmentType=segmentType, smooth=smooth, name=name) + warn( + "The addPoint method needs an identifier kwarg. The point's identifier value has been discarded.", + DeprecationWarning, + ) + + +def _buildOutlineComponentFormat2( + pen: AbstractPointPen, component: ElementType, identifiers: set[str], validate: bool +) -> None: + if validate: + if len(component): + raise GlifLibError("Unknown child elements of component element.") + for attr in component.attrib.keys(): + if attr not in componentAttributesFormat2: + raise GlifLibError("Unknown attribute in component element: %s" % attr) + baseGlyphName = component.get("base") + if validate and baseGlyphName is None: + raise GlifLibError("The base attribute is not defined in the component.") + assert baseGlyphName is not None + transformation = tuple( + _number(component.get(attr) or default) for attr, default in _transformationInfo + ) + transformation = cast( + tuple[float, float, float, float, float, float], transformation + ) + identifier = component.get("identifier") + if identifier is not None: + if validate: + if identifier in identifiers: + raise GlifLibError( + "The identifier %s is used more than once." % identifier + ) + if validate and not identifierValidator(identifier): + raise GlifLibError("The identifier %s is not valid." % identifier) + identifiers.add(identifier) + try: + pen.addComponent(baseGlyphName, transformation, identifier=identifier) + except TypeError: + pen.addComponent(baseGlyphName, transformation) + warn( + "The addComponent method needs an identifier kwarg. The component's identifier value has been discarded.", + DeprecationWarning, + ) + + +# all formats + + +def _validateAndMassagePointStructures( + contour, pointAttributes, openContourOffCurveLeniency=False, validate=True +): + if not len(contour): + return + # store some data for later validation + lastOnCurvePoint = None + haveOffCurvePoint = False + # validate and massage the individual point elements + massaged = [] + for index, element in enumerate(contour): + # not <point> + if element.tag != "point": + raise GlifLibError( + "Unknown child element (%s) of contour element." % element.tag + ) + point = dict(element.attrib) + massaged.append(point) + if validate: + # unknown attributes + for attr in point.keys(): + if attr not in pointAttributes: + raise GlifLibError("Unknown attribute in point element: %s" % attr) + # search for unknown children + if len(element): + raise GlifLibError("Unknown child elements in point element.") + # x and y are required + for attr in ("x", "y"): + try: + point[attr] = _number(point[attr]) + except KeyError as e: + raise GlifLibError( + f"Required {attr} attribute is missing in point element." + ) from e + # segment type + pointType = point.pop("type", "offcurve") + if validate and pointType not in pointTypeOptions: + raise GlifLibError("Unknown point type: %s" % pointType) + if pointType == "offcurve": + pointType = None + point["segmentType"] = pointType + if pointType is None: + haveOffCurvePoint = True + else: + lastOnCurvePoint = index + # move can only occur as the first point + if validate and pointType == "move" and index != 0: + raise GlifLibError( + "A move point occurs after the first point in the contour." + ) + # smooth is optional + smooth = point.get("smooth", "no") + if validate and smooth is not None: + if smooth not in pointSmoothOptions: + raise GlifLibError("Unknown point smooth value: %s" % smooth) + smooth = smooth == "yes" + point["smooth"] = smooth + # smooth can only be applied to curve and qcurve + if validate and smooth and pointType is None: + raise GlifLibError("smooth attribute set in an offcurve point.") + # name is optional + if "name" not in element.attrib: + point["name"] = None + if openContourOffCurveLeniency: + # remove offcurves that precede a move. this is technically illegal, + # but we let it slide because there are fonts out there in the wild like this. + if massaged[0]["segmentType"] == "move": + count = 0 + for point in reversed(massaged): + if point["segmentType"] is None: + count += 1 + else: + break + if count: + massaged = massaged[:-count] + # validate the off-curves in the segments + if validate and haveOffCurvePoint and lastOnCurvePoint is not None: + # we only care about how many offCurves there are before an onCurve + # filter out the trailing offCurves + offCurvesCount = len(massaged) - 1 - lastOnCurvePoint + for point in massaged: + segmentType = point["segmentType"] + if segmentType is None: + offCurvesCount += 1 + else: + if offCurvesCount: + # move and line can't be preceded by off-curves + if segmentType == "move": + # this will have been filtered out already + raise GlifLibError("move can not have an offcurve.") + elif segmentType == "line": + raise GlifLibError("line can not have an offcurve.") + elif segmentType == "curve": + if offCurvesCount > 2: + raise GlifLibError("Too many offcurves defined for curve.") + elif segmentType == "qcurve": + pass + else: + # unknown segment type. it'll be caught later. + pass + offCurvesCount = 0 + return massaged + + +# --------------------- +# Misc Helper Functions +# --------------------- + + +def _relaxedSetattr(object: Any, attr: str, value: Any) -> None: + try: + setattr(object, attr, value) + except AttributeError: + pass + + +def _number(s: Union[str, int, float]) -> IntFloat: + """ + Given a numeric string, return an integer or a float, whichever + the string indicates. _number("1") will return the integer 1, + _number("1.0") will return the float 1.0. + + >>> _number("1") + 1 + >>> _number("1.0") + 1.0 + >>> _number("a") # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + GlifLibError: Could not convert a to an int or float. + """ + try: + n: IntFloat = int(s) + return n + except ValueError: + pass + try: + n = float(s) + return n + except ValueError: + raise GlifLibError("Could not convert %s to an int or float." % s) + + +# -------------------- +# Rapid Value Fetching +# -------------------- + +# base + + +class _DoneParsing(Exception): + pass + + +class _BaseParser: + def __init__(self) -> None: + self._elementStack: list[str] = [] + + def parse(self, text: bytes): + from xml.parsers.expat import ParserCreate + + parser = ParserCreate() + parser.StartElementHandler = self.startElementHandler + parser.EndElementHandler = self.endElementHandler + parser.Parse(text, True) + + def startElementHandler(self, name: str, attrs: Any) -> None: + self._elementStack.append(name) + + def endElementHandler(self, name: str) -> None: + other = self._elementStack.pop(-1) + assert other == name + + +# unicodes + + +def _fetchUnicodes(glif: bytes) -> list[int]: + """ + Get a list of unicodes listed in glif. + """ + parser = _FetchUnicodesParser() + parser.parse(glif) + return parser.unicodes + + +class _FetchUnicodesParser(_BaseParser): + def __init__(self) -> None: + self.unicodes: list[int] = [] + super().__init__() + + def startElementHandler(self, name: str, attrs: dict[str, str]) -> None: + if ( + name == "unicode" + and self._elementStack + and self._elementStack[-1] == "glyph" + ): + value = attrs.get("hex") + if value is not None: + try: + intValue = int(value, 16) + if intValue not in self.unicodes: + self.unicodes.append(intValue) + except ValueError: + pass + super().startElementHandler(name, attrs) + + +# image + + +def _fetchImageFileName(glif: bytes) -> Optional[str]: + """ + The image file name (if any) from glif. + """ + parser = _FetchImageFileNameParser() + try: + parser.parse(glif) + except _DoneParsing: + pass + return parser.fileName + + +class _FetchImageFileNameParser(_BaseParser): + def __init__(self) -> None: + self.fileName: Optional[str] = None + super().__init__() + + def startElementHandler(self, name: str, attrs: dict[str, str]) -> None: + if name == "image" and self._elementStack and self._elementStack[-1] == "glyph": + self.fileName = attrs.get("fileName") + raise _DoneParsing + super().startElementHandler(name, attrs) + + +# component references + + +def _fetchComponentBases(glif: bytes) -> list[str]: + """ + Get a list of component base glyphs listed in glif. + """ + parser = _FetchComponentBasesParser() + try: + parser.parse(glif) + except _DoneParsing: + pass + return list(parser.bases) + + +class _FetchComponentBasesParser(_BaseParser): + def __init__(self) -> None: + self.bases: list[str] = [] + super().__init__() + + def startElementHandler(self, name: str, attrs: dict[str, str]) -> None: + if ( + name == "component" + and self._elementStack + and self._elementStack[-1] == "outline" + ): + base = attrs.get("base") + if base is not None: + self.bases.append(base) + super().startElementHandler(name, attrs) + + def endElementHandler(self, name: str) -> None: + if name == "outline": + raise _DoneParsing + super().endElementHandler(name) + + +# -------------- +# GLIF Point Pen +# -------------- + +_transformationInfo: list[tuple[str, int]] = [ + # field name, default value + ("xScale", 1), + ("xyScale", 0), + ("yxScale", 0), + ("yScale", 1), + ("xOffset", 0), + ("yOffset", 0), +] + + +class GLIFPointPen(AbstractPointPen): + """ + Helper class using the PointPen protocol to write the <outline> + part of .glif files. + """ + + def __init__( + self, + element: ElementType, + formatVersion: Optional[FormatVersion] = None, + identifiers: Optional[set[str]] = None, + validate: bool = True, + ) -> None: + if identifiers is None: + identifiers = set() + self.formatVersion = normalizeFormatVersion(formatVersion, GLIFFormatVersion) + self.identifiers = identifiers + self.outline = element + self.contour = None + self.prevOffCurveCount = 0 + self.prevPointTypes: list[str] = [] + self.validate = validate + + def beginPath(self, identifier=None, **kwargs): + attrs = OrderedDict() + if identifier is not None and self.formatVersion.major >= 2: + if self.validate: + if identifier in self.identifiers: + raise GlifLibError( + "identifier used more than once: %s" % identifier + ) + if not identifierValidator(identifier): + raise GlifLibError( + "identifier not formatted properly: %s" % identifier + ) + attrs["identifier"] = identifier + self.identifiers.add(identifier) + self.contour = etree.SubElement(self.outline, "contour", attrs) + self.prevOffCurveCount = 0 + + def endPath(self): + if self.prevPointTypes and self.prevPointTypes[0] == "move": + if self.validate and self.prevPointTypes[-1] == "offcurve": + raise GlifLibError("open contour has loose offcurve point") + # prevent lxml from writing self-closing tags + if not len(self.contour): + self.contour.text = "\n " + self.contour = None + self.prevPointType = None + self.prevOffCurveCount = 0 + self.prevPointTypes = [] + + def addPoint( + self, pt, segmentType=None, smooth=None, name=None, identifier=None, **kwargs + ): + attrs = OrderedDict() + # coordinates + if pt is not None: + if self.validate: + for coord in pt: + if not isinstance(coord, numberTypes): + raise GlifLibError("coordinates must be int or float") + attrs["x"] = repr(pt[0]) + attrs["y"] = repr(pt[1]) + # segment type + if segmentType == "offcurve": + segmentType = None + if self.validate: + if segmentType == "move" and self.prevPointTypes: + raise GlifLibError( + "move occurs after a point has already been added to the contour." + ) + if ( + segmentType in ("move", "line") + and self.prevPointTypes + and self.prevPointTypes[-1] == "offcurve" + ): + raise GlifLibError("offcurve occurs before %s point." % segmentType) + if segmentType == "curve" and self.prevOffCurveCount > 2: + raise GlifLibError("too many offcurve points before curve point.") + if segmentType is not None: + attrs["type"] = segmentType + else: + segmentType = "offcurve" + if segmentType == "offcurve": + self.prevOffCurveCount += 1 + else: + self.prevOffCurveCount = 0 + self.prevPointTypes.append(segmentType) + # smooth + if smooth: + if self.validate and segmentType == "offcurve": + raise GlifLibError("can't set smooth in an offcurve point.") + attrs["smooth"] = "yes" + # name + if name is not None: + attrs["name"] = name + # identifier + if identifier is not None and self.formatVersion.major >= 2: + if self.validate: + if identifier in self.identifiers: + raise GlifLibError( + "identifier used more than once: %s" % identifier + ) + if not identifierValidator(identifier): + raise GlifLibError( + "identifier not formatted properly: %s" % identifier + ) + attrs["identifier"] = identifier + self.identifiers.add(identifier) + etree.SubElement(self.contour, "point", attrs) + + def addComponent(self, glyphName, transformation, identifier=None, **kwargs): + attrs = OrderedDict([("base", glyphName)]) + for (attr, default), value in zip(_transformationInfo, transformation): + if self.validate and not isinstance(value, numberTypes): + raise GlifLibError("transformation values must be int or float") + if value != default: + attrs[attr] = repr(value) + if identifier is not None and self.formatVersion.major >= 2: + if self.validate: + if identifier in self.identifiers: + raise GlifLibError( + "identifier used more than once: %s" % identifier + ) + if self.validate and not identifierValidator(identifier): + raise GlifLibError( + "identifier not formatted properly: %s" % identifier + ) + attrs["identifier"] = identifier + self.identifiers.add(identifier) + etree.SubElement(self.outline, "component", attrs) + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/kerning.py b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/kerning.py new file mode 100644 index 0000000000000000000000000000000000000000..7b86c1ab3dd1fa124e2633b2a473062ada78ac0d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/kerning.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +from typing import Optional + +from fontTools.annotations import KerningPair, KerningDict, KerningGroups, IntFloat + +StrDict = dict[str, str] + + +def lookupKerningValue( + pair: KerningPair, + kerning: KerningDict, + groups: KerningGroups, + fallback: IntFloat = 0, + glyphToFirstGroup: Optional[StrDict] = None, + glyphToSecondGroup: Optional[StrDict] = None, +) -> IntFloat: + """Retrieve the kerning value (if any) between a pair of elements. + + The elements can be either individual glyphs (by name) or kerning + groups (by name), or any combination of the two. + + Providing the two glyph-to-group mappings accelerates group-lookups. + These can be built manually, or with :py:func:`glyphsToGroups`. + + Args: + pair: + A tuple, in logical order (first, second) with respect + to the reading direction, to query the font for kerning + information on. Each element in the tuple can be either + a glyph name or a kerning group name. + kerning: + A dictionary of kerning pairs. + groups: + A dictionary mapping each group name to its glyph names. + fallback: + The fallback value to return if no kern is found between + the elements in ``pair``. Defaults to 0. + glyphToFirstGroup: + A dictionary mapping glyph names to the first-glyph kerning + groups to which they belong. Defaults to ``None``. + glyphToSecondGroup: + A dictionary mapping glyph names to the second-glyph kerning + groups to which they belong. Defaults to ``None``. + + Returns: + The kerning value between the element pair. If no kerning for + the pair is found, the fallback value is returned. + + Note: This function expects the ``kerning`` argument to be a flat + dictionary of kerning pairs, not the nested structure used in a + kerning.plist file. + + Examples:: + + >>> groups = { + ... "public.kern1.O" : ["O", "D", "Q"], + ... "public.kern2.E" : ["E", "F"] + ... } + >>> kerning = { + ... ("public.kern1.O", "public.kern2.E") : -100, + ... ("public.kern1.O", "F") : -200, + ... ("D", "F") : -300 + ... } + >>> lookupKerningValue(("D", "F"), kerning, groups) + -300 + >>> lookupKerningValue(("O", "F"), kerning, groups) + -200 + >>> lookupKerningValue(("O", "E"), kerning, groups) + -100 + >>> lookupKerningValue(("O", "O"), kerning, groups) + 0 + >>> lookupKerningValue(("E", "E"), kerning, groups) + 0 + >>> lookupKerningValue(("E", "O"), kerning, groups) + 0 + >>> lookupKerningValue(("X", "X"), kerning, groups) + 0 + >>> lookupKerningValue(("public.kern1.O", "public.kern2.E"), + ... kerning, groups) + -100 + >>> lookupKerningValue(("public.kern1.O", "F"), kerning, groups) + -200 + >>> lookupKerningValue(("O", "public.kern2.E"), kerning, groups) + -100 + >>> lookupKerningValue(("public.kern1.X", "public.kern2.X"), kerning, groups) + 0 + >>> glyphToFirstGroup, glyphToSecondGroup = glyphsToGroups(groups) + >>> lookupKerningValue(("O", "E"), kerning, groups, glyphToFirstGroup=glyphToFirstGroup, glyphToSecondGroup=glyphToSecondGroup) + -100 + """ + # quickly check to see if the pair is in the kerning dictionary + if pair in kerning: + return kerning[pair] + # ensure both or no glyph-to-group mappings are provided + if (glyphToFirstGroup is None) != (glyphToSecondGroup is None): + raise ValueError( + "Must provide both 'glyphToFirstGroup' and 'glyphToSecondGroup', or neither." + ) + # create glyph to group mapping + if glyphToFirstGroup is None or glyphToSecondGroup is None: + glyphToFirstGroup, glyphToSecondGroup = glyphsToGroups(groups) + # get group names and make sure first and second are glyph names + first, second = pair + firstGroup = secondGroup = None + if first.startswith("public.kern1."): + firstGroup = first + firstGlyph = None + else: + firstGroup = glyphToFirstGroup.get(first) + firstGlyph = first + if second.startswith("public.kern2."): + secondGroup = second + secondGlyph = None + else: + secondGroup = glyphToSecondGroup.get(second) + secondGlyph = second + # make an ordered list of pairs to look up + pairs = [ + (a, b) + for a in (firstGlyph, firstGroup) + for b in (secondGlyph, secondGroup) + if a is not None and b is not None + ] + # look up the pairs and return any matches + for pair in pairs: + if pair in kerning: + return kerning[pair] + # use the fallback value + return fallback + + +def glyphsToGroups(groups: KerningGroups) -> tuple[StrDict, StrDict]: + """Build dictionaries mapping glyph names to their kerning groups. + + This is a reverse-mapping of the UFO kerning groups data structure. + Groups are assumed to be compliant with the UFO specification; with + the current implementation, if glyphs appear in more than one group + anyway, the last group wins. + + Args: + groups: + A dictionary mapping each group name to its glyph names. + + Returns: + A tuple of two dictionaries, respectively mapping glyph names to + the first- and second-glyph kerning groups to which they belong. + + Examples:: + + >>> groups = { + ... "public.kern1.O" : ["O", "D", "Q"], + ... "public.kern2.E" : ["E", "F"] + ... } + >>> glyphsToGroups(groups) + ({'O': 'public.kern1.O', 'D': 'public.kern1.O', 'Q': 'public.kern1.O'}, {'E': 'public.kern2.E', 'F': 'public.kern2.E'}) + """ + glyphToFirstGroup = {} + glyphToSecondGroup = {} + for group, groupMembers in groups.items(): + if group.startswith("public.kern1."): + for glyph in groupMembers: + glyphToFirstGroup[glyph] = group + elif group.startswith("public.kern2."): + for glyph in groupMembers: + glyphToSecondGroup[glyph] = group + return (glyphToFirstGroup, glyphToSecondGroup) + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/plistlib.py b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/plistlib.py new file mode 100644 index 0000000000000000000000000000000000000000..0242e9d26fce6b5ec4def58ac6aee44a5738db98 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/plistlib.py @@ -0,0 +1,47 @@ +"""DEPRECATED - This module is kept here only as a backward compatibility shim +for the old `ufoLib.plistlib` module, which was moved to :class:`fontTools.misc.plistlib`. +Please use the latter instead. +""" + +from fontTools.misc.plistlib import dump, dumps, load, loads +from fontTools.misc.textTools import tobytes + +# The following functions were part of the old py2-like ufoLib.plistlib API. +# They are kept only for backward compatiblity. +from fontTools.ufoLib.utils import deprecated + + +@deprecated("Use 'fontTools.misc.plistlib.load' instead") +def readPlist(path_or_file): + did_open = False + if isinstance(path_or_file, str): + path_or_file = open(path_or_file, "rb") + did_open = True + try: + return load(path_or_file, use_builtin_types=False) + finally: + if did_open: + path_or_file.close() + + +@deprecated("Use 'fontTools.misc.plistlib.dump' instead") +def writePlist(value, path_or_file): + did_open = False + if isinstance(path_or_file, str): + path_or_file = open(path_or_file, "wb") + did_open = True + try: + dump(value, path_or_file, use_builtin_types=False) + finally: + if did_open: + path_or_file.close() + + +@deprecated("Use 'fontTools.misc.plistlib.loads' instead") +def readPlistFromString(data): + return loads(tobytes(data, encoding="utf-8"), use_builtin_types=False) + + +@deprecated("Use 'fontTools.misc.plistlib.dumps' instead") +def writePlistToString(value): + return dumps(value, use_builtin_types=False) diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/pointPen.py b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/pointPen.py new file mode 100644 index 0000000000000000000000000000000000000000..4a8126cd6481a39b5bfeec7348c8efd168118236 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/pointPen.py @@ -0,0 +1,6 @@ +"""DEPRECATED - This module is kept here only as a backward compatibility shim +for the old `ufoLib.pointPen` module, which was moved to :class:`fontTools.pens.pointPen`. +Please use the latter instead. +""" + +from fontTools.pens.pointPen import * diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/utils.py b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3930d8931da14db0815d885028304d3905c0d680 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/utils.py @@ -0,0 +1,107 @@ +"""This module contains miscellaneous helpers. + +It is not considered part of the public ufoLib API. It does, however, +define the :py:obj:`.deprecated` decorator that is used elsewhere in +the module. +""" + +from __future__ import annotations + +from typing import Optional, Type, TypeVar, Union, cast +from collections.abc import Callable +import enum +import functools +import warnings + +F = TypeVar("F", bound=Callable[..., object]) +FormatVersion = TypeVar("FormatVersion", bound="BaseFormatVersion") +FormatVersionInput = Optional[Union[int, tuple[int, int], FormatVersion]] + +numberTypes = (int, float) + + +def deprecated(msg: str = "") -> Callable[[F], F]: + """Decorator factory to mark functions as deprecated with given message. + + >>> @deprecated("Enough!") + ... def some_function(): + ... "I just print 'hello world'." + ... print("hello world") + >>> some_function() + hello world + >>> some_function.__doc__ == "I just print 'hello world'." + True + """ + + def deprecated_decorator(func: F) -> F: + @functools.wraps(func) + def wrapper(*args, **kwargs): + warnings.warn( + f"{func.__name__} function is a deprecated. {msg}", + category=DeprecationWarning, + stacklevel=2, + ) + return func(*args, **kwargs) + + return cast(F, wrapper) + + return deprecated_decorator + + +def normalizeFormatVersion( + value: FormatVersionInput, cls: Type[FormatVersion] +) -> FormatVersion: + # Needed for type safety of UFOFormatVersion and GLIFFormatVersion input + if value is None: + return cls.default() + if isinstance(value, cls): + return value + if isinstance(value, int): + return cls((value, 0)) + if isinstance(value, tuple) and len(value) == 2: + return cls(value) + raise ValueError(f"Unsupported format version: {value!r}") + + +# Base class for UFOFormatVersion and GLIFFormatVersion +class BaseFormatVersion(tuple[int, int], enum.Enum): + value: tuple[int, int] + + def __new__(cls: Type[FormatVersion], value: tuple[int, int]) -> BaseFormatVersion: + return super().__new__(cls, value) + + @property + def major(self) -> int: + return self.value[0] + + @property + def minor(self) -> int: + return self.value[1] + + @classmethod + def _missing_(cls, value: object) -> BaseFormatVersion: + # allow to initialize a version enum from a single (major) integer + if isinstance(value, int): + return cls((value, 0)) + # or from None to obtain the current default version + if value is None: + return cls.default() + raise ValueError(f"{value!r} is not a valid {cls.__name__}") + + def __str__(self) -> str: + return f"{self.major}.{self.minor}" + + @classmethod + def default(cls: Type[FormatVersion]) -> FormatVersion: + # get the latest defined version (i.e. the max of all versions) + return max(cls.__members__.values()) + + @classmethod + def supported_versions(cls: Type[FormatVersion]) -> frozenset[FormatVersion]: + return frozenset(cls.__members__.values()) + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/.venv/lib/python3.12/site-packages/fontTools/ufoLib/validators.py b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..baed5688d040eaa96382ffb0c0a98cdf930ff6a7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/ufoLib/validators.py @@ -0,0 +1,1197 @@ +"""Various low level data validators.""" + +from __future__ import annotations + +import calendar +from collections.abc import Mapping, Sequence +from io import open + +import fontTools.misc.filesystem as fs +from typing import Any, Type, Optional, Union + +from fontTools.annotations import IntFloat +from fontTools.ufoLib.utils import numberTypes + +GenericDict = dict[str, tuple[Union[type, tuple[Type[Any], ...]], bool]] + +# ------- +# Generic +# ------- + + +def isDictEnough(value: Any) -> bool: + """ + Some objects will likely come in that aren't + dicts but are dict-ish enough. + """ + if isinstance(value, Mapping): + return True + for attr in ("keys", "values", "items"): + if not hasattr(value, attr): + return False + return True + + +def genericTypeValidator(value: Any, typ: Type[Any]) -> bool: + """ + Generic. (Added at version 2.) + """ + return isinstance(value, typ) + + +def genericIntListValidator(values: Any, validValues: Sequence[int]) -> bool: + """ + Generic. (Added at version 2.) + """ + if not isinstance(values, (list, tuple)): + return False + valuesSet = set(values) + validValuesSet = set(validValues) + if valuesSet - validValuesSet: + return False + for value in values: + if not isinstance(value, int): + return False + return True + + +def genericNonNegativeIntValidator(value: Any) -> bool: + """ + Generic. (Added at version 3.) + """ + if not isinstance(value, int): + return False + if value < 0: + return False + return True + + +def genericNonNegativeNumberValidator(value: Any) -> bool: + """ + Generic. (Added at version 3.) + """ + if not isinstance(value, numberTypes): + return False + if value < 0: + return False + return True + + +def genericDictValidator(value: Any, prototype: GenericDict) -> bool: + """ + Generic. (Added at version 3.) + """ + # not a dict + if not isinstance(value, Mapping): + return False + # missing required keys + for key, (typ, required) in prototype.items(): + if not required: + continue + if key not in value: + return False + # unknown keys + for key in value.keys(): + if key not in prototype: + return False + # incorrect types + for key, v in value.items(): + prototypeType, required = prototype[key] + if v is None and not required: + continue + if not isinstance(v, prototypeType): + return False + return True + + +# -------------- +# fontinfo.plist +# -------------- + +# Data Validators + + +def fontInfoStyleMapStyleNameValidator(value: Any) -> bool: + """ + Version 2+. + """ + options = ["regular", "italic", "bold", "bold italic"] + return value in options + + +def fontInfoOpenTypeGaspRangeRecordsValidator(value: Any) -> bool: + """ + Version 3+. + """ + if not isinstance(value, list): + return False + if len(value) == 0: + return True + validBehaviors = [0, 1, 2, 3] + dictPrototype: GenericDict = dict( + rangeMaxPPEM=(int, True), rangeGaspBehavior=(list, True) + ) + ppemOrder = [] + for rangeRecord in value: + if not genericDictValidator(rangeRecord, dictPrototype): + return False + ppem = rangeRecord["rangeMaxPPEM"] + behavior = rangeRecord["rangeGaspBehavior"] + ppemValidity = genericNonNegativeIntValidator(ppem) + if not ppemValidity: + return False + behaviorValidity = genericIntListValidator(behavior, validBehaviors) + if not behaviorValidity: + return False + ppemOrder.append(ppem) + if ppemOrder != sorted(ppemOrder): + return False + return True + + +def fontInfoOpenTypeHeadCreatedValidator(value: Any) -> bool: + """ + Version 2+. + """ + # format: 0000/00/00 00:00:00 + if not isinstance(value, str): + return False + # basic formatting + if not len(value) == 19: + return False + if value.count(" ") != 1: + return False + strDate, strTime = value.split(" ") + if strDate.count("/") != 2: + return False + if strTime.count(":") != 2: + return False + # date + strYear, strMonth, strDay = strDate.split("/") + if len(strYear) != 4: + return False + if len(strMonth) != 2: + return False + if len(strDay) != 2: + return False + try: + intYear = int(strYear) + intMonth = int(strMonth) + intDay = int(strDay) + except ValueError: + return False + if intMonth < 1 or intMonth > 12: + return False + monthMaxDay = calendar.monthrange(intYear, intMonth)[1] + if intDay < 1 or intDay > monthMaxDay: + return False + # time + strHour, strMinute, strSecond = strTime.split(":") + if len(strHour) != 2: + return False + if len(strMinute) != 2: + return False + if len(strSecond) != 2: + return False + try: + intHour = int(strHour) + intMinute = int(strMinute) + intSecond = int(strSecond) + except ValueError: + return False + if intHour < 0 or intHour > 23: + return False + if intMinute < 0 or intMinute > 59: + return False + if intSecond < 0 or intSecond > 59: + return False + # fallback + return True + + +def fontInfoOpenTypeNameRecordsValidator(value: Any) -> bool: + """ + Version 3+. + """ + if not isinstance(value, list): + return False + dictPrototype: GenericDict = dict( + nameID=(int, True), + platformID=(int, True), + encodingID=(int, True), + languageID=(int, True), + string=(str, True), + ) + for nameRecord in value: + if not genericDictValidator(nameRecord, dictPrototype): + return False + return True + + +def fontInfoOpenTypeOS2WeightClassValidator(value: Any) -> bool: + """ + Version 2+. + """ + if not isinstance(value, int): + return False + if value < 0: + return False + return True + + +def fontInfoOpenTypeOS2WidthClassValidator(value: Any) -> bool: + """ + Version 2+. + """ + if not isinstance(value, int): + return False + if value < 1: + return False + if value > 9: + return False + return True + + +def fontInfoVersion2OpenTypeOS2PanoseValidator(values: Any) -> bool: + """ + Version 2. + """ + if not isinstance(values, (list, tuple)): + return False + if len(values) != 10: + return False + for value in values: + if not isinstance(value, int): + return False + # XXX further validation? + return True + + +def fontInfoVersion3OpenTypeOS2PanoseValidator(values: Any) -> bool: + """ + Version 3+. + """ + if not isinstance(values, (list, tuple)): + return False + if len(values) != 10: + return False + for value in values: + if not isinstance(value, int): + return False + if value < 0: + return False + # XXX further validation? + return True + + +def fontInfoOpenTypeOS2FamilyClassValidator(values: Any) -> bool: + """ + Version 2+. + """ + if not isinstance(values, (list, tuple)): + return False + if len(values) != 2: + return False + for value in values: + if not isinstance(value, int): + return False + classID, subclassID = values + if classID < 0 or classID > 14: + return False + if subclassID < 0 or subclassID > 15: + return False + return True + + +def fontInfoPostscriptBluesValidator(values: Any) -> bool: + """ + Version 2+. + """ + if not isinstance(values, (list, tuple)): + return False + if len(values) > 14: + return False + if len(values) % 2: + return False + for value in values: + if not isinstance(value, numberTypes): + return False + return True + + +def fontInfoPostscriptOtherBluesValidator(values: Any) -> bool: + """ + Version 2+. + """ + if not isinstance(values, (list, tuple)): + return False + if len(values) > 10: + return False + if len(values) % 2: + return False + for value in values: + if not isinstance(value, numberTypes): + return False + return True + + +def fontInfoPostscriptStemsValidator(values: Any) -> bool: + """ + Version 2+. + """ + if not isinstance(values, (list, tuple)): + return False + if len(values) > 12: + return False + for value in values: + if not isinstance(value, numberTypes): + return False + return True + + +def fontInfoPostscriptWindowsCharacterSetValidator(value: Any) -> bool: + """ + Version 2+. + """ + validValues = list(range(1, 21)) + if value not in validValues: + return False + return True + + +def fontInfoWOFFMetadataUniqueIDValidator(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = dict(id=(str, True)) + if not genericDictValidator(value, dictPrototype): + return False + return True + + +def fontInfoWOFFMetadataVendorValidator(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = { + "name": (str, True), + "url": (str, False), + "dir": (str, False), + "class": (str, False), + } + if not genericDictValidator(value, dictPrototype): + return False + if "dir" in value and value.get("dir") not in ("ltr", "rtl"): + return False + return True + + +def fontInfoWOFFMetadataCreditsValidator(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = dict(credits=(list, True)) + if not genericDictValidator(value, dictPrototype): + return False + if not len(value["credits"]): + return False + dictPrototype = { + "name": (str, True), + "url": (str, False), + "role": (str, False), + "dir": (str, False), + "class": (str, False), + } + for credit in value["credits"]: + if not genericDictValidator(credit, dictPrototype): + return False + if "dir" in credit and credit.get("dir") not in ("ltr", "rtl"): + return False + return True + + +def fontInfoWOFFMetadataDescriptionValidator(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = dict(url=(str, False), text=(list, True)) + if not genericDictValidator(value, dictPrototype): + return False + for text in value["text"]: + if not fontInfoWOFFMetadataTextValue(text): + return False + return True + + +def fontInfoWOFFMetadataLicenseValidator(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = dict( + url=(str, False), text=(list, False), id=(str, False) + ) + if not genericDictValidator(value, dictPrototype): + return False + if "text" in value: + for text in value["text"]: + if not fontInfoWOFFMetadataTextValue(text): + return False + return True + + +def fontInfoWOFFMetadataTrademarkValidator(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = dict(text=(list, True)) + if not genericDictValidator(value, dictPrototype): + return False + for text in value["text"]: + if not fontInfoWOFFMetadataTextValue(text): + return False + return True + + +def fontInfoWOFFMetadataCopyrightValidator(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = dict(text=(list, True)) + if not genericDictValidator(value, dictPrototype): + return False + for text in value["text"]: + if not fontInfoWOFFMetadataTextValue(text): + return False + return True + + +def fontInfoWOFFMetadataLicenseeValidator(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = { + "name": (str, True), + "dir": (str, False), + "class": (str, False), + } + if not genericDictValidator(value, dictPrototype): + return False + if "dir" in value and value.get("dir") not in ("ltr", "rtl"): + return False + return True + + +def fontInfoWOFFMetadataTextValue(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = { + "text": (str, True), + "language": (str, False), + "dir": (str, False), + "class": (str, False), + } + if not genericDictValidator(value, dictPrototype): + return False + if "dir" in value and value.get("dir") not in ("ltr", "rtl"): + return False + return True + + +def fontInfoWOFFMetadataExtensionsValidator(value: Any) -> bool: + """ + Version 3+. + """ + if not isinstance(value, list): + return False + if not value: + return False + for extension in value: + if not fontInfoWOFFMetadataExtensionValidator(extension): + return False + return True + + +def fontInfoWOFFMetadataExtensionValidator(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = dict( + names=(list, False), items=(list, True), id=(str, False) + ) + if not genericDictValidator(value, dictPrototype): + return False + if "names" in value: + for name in value["names"]: + if not fontInfoWOFFMetadataExtensionNameValidator(name): + return False + for item in value["items"]: + if not fontInfoWOFFMetadataExtensionItemValidator(item): + return False + return True + + +def fontInfoWOFFMetadataExtensionItemValidator(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = dict( + id=(str, False), names=(list, True), values=(list, True) + ) + if not genericDictValidator(value, dictPrototype): + return False + for name in value["names"]: + if not fontInfoWOFFMetadataExtensionNameValidator(name): + return False + for val in value["values"]: + if not fontInfoWOFFMetadataExtensionValueValidator(val): + return False + return True + + +def fontInfoWOFFMetadataExtensionNameValidator(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = { + "text": (str, True), + "language": (str, False), + "dir": (str, False), + "class": (str, False), + } + if not genericDictValidator(value, dictPrototype): + return False + if "dir" in value and value.get("dir") not in ("ltr", "rtl"): + return False + return True + + +def fontInfoWOFFMetadataExtensionValueValidator(value: Any) -> bool: + """ + Version 3+. + """ + dictPrototype: GenericDict = { + "text": (str, True), + "language": (str, False), + "dir": (str, False), + "class": (str, False), + } + if not genericDictValidator(value, dictPrototype): + return False + if "dir" in value and value.get("dir") not in ("ltr", "rtl"): + return False + return True + + +# ---------- +# Guidelines +# ---------- + + +def guidelinesValidator(value: Any, identifiers: Optional[set[str]] = None) -> bool: + """ + Version 3+. + """ + if not isinstance(value, list): + return False + if identifiers is None: + identifiers = set() + for guide in value: + if not guidelineValidator(guide): + return False + identifier = guide.get("identifier") + if identifier is not None: + if identifier in identifiers: + return False + identifiers.add(identifier) + return True + + +_guidelineDictPrototype: GenericDict = dict( + x=((int, float), False), + y=((int, float), False), + angle=((int, float), False), + name=(str, False), + color=(str, False), + identifier=(str, False), +) + + +def guidelineValidator(value: Any) -> bool: + """ + Version 3+. + """ + if not genericDictValidator(value, _guidelineDictPrototype): + return False + + angle = value.get("angle") + # angle must be between 0 and 360 + if angle is not None: + if angle < 0: + return False + if angle > 360: + return False + # identifier must be 1 or more characters + identifier = value.get("identifier") + if identifier is not None and not identifierValidator(identifier): + return False + # color must follow the proper format + color = value.get("color") + if color is not None and not colorValidator(color): + return False + return True + + +# ------- +# Anchors +# ------- + + +def anchorsValidator(value: Any, identifiers: Optional[set[str]] = None) -> bool: + """ + Version 3+. + """ + if not isinstance(value, list): + return False + if identifiers is None: + identifiers = set() + for anchor in value: + if not anchorValidator(anchor): + return False + identifier = anchor.get("identifier") + if identifier is not None: + if identifier in identifiers: + return False + identifiers.add(identifier) + return True + + +_anchorDictPrototype: GenericDict = dict( + x=((int, float), False), + y=((int, float), False), + name=(str, False), + color=(str, False), + identifier=(str, False), +) + + +def anchorValidator(value: Any) -> bool: + """ + Version 3+. + """ + if not genericDictValidator(value, _anchorDictPrototype): + return False + x = value.get("x") + y = value.get("y") + # x and y must be present + if x is None or y is None: + return False + # identifier must be 1 or more characters + identifier = value.get("identifier") + if identifier is not None and not identifierValidator(identifier): + return False + # color must follow the proper format + color = value.get("color") + if color is not None and not colorValidator(color): + return False + return True + + +# ---------- +# Identifier +# ---------- + + +def identifierValidator(value: Any) -> bool: + """ + Version 3+. + + >>> identifierValidator("a") + True + >>> identifierValidator("") + False + >>> identifierValidator("a" * 101) + False + """ + validCharactersMin = 0x20 + validCharactersMax = 0x7E + if not isinstance(value, str): + return False + if not value: + return False + if len(value) > 100: + return False + for c in value: + i = ord(c) + if i < validCharactersMin or i > validCharactersMax: + return False + return True + + +# ----- +# Color +# ----- + + +def colorValidator(value: Any) -> bool: + """ + Version 3+. + + >>> colorValidator("0,0,0,0") + True + >>> colorValidator(".5,.5,.5,.5") + True + >>> colorValidator("0.5,0.5,0.5,0.5") + True + >>> colorValidator("1,1,1,1") + True + + >>> colorValidator("2,0,0,0") + False + >>> colorValidator("0,2,0,0") + False + >>> colorValidator("0,0,2,0") + False + >>> colorValidator("0,0,0,2") + False + + >>> colorValidator("1r,1,1,1") + False + >>> colorValidator("1,1g,1,1") + False + >>> colorValidator("1,1,1b,1") + False + >>> colorValidator("1,1,1,1a") + False + + >>> colorValidator("1 1 1 1") + False + >>> colorValidator("1 1,1,1") + False + >>> colorValidator("1,1 1,1") + False + >>> colorValidator("1,1,1 1") + False + + >>> colorValidator("1, 1, 1, 1") + True + """ + if not isinstance(value, str): + return False + parts = value.split(",") + if len(parts) != 4: + return False + for part in parts: + part = part.strip() + converted = False + number: IntFloat + try: + number = int(part) + converted = True + except ValueError: + pass + if not converted: + try: + number = float(part) + converted = True + except ValueError: + pass + if not converted: + return False + if not 0 <= number <= 1: + return False + return True + + +# ----- +# image +# ----- + +pngSignature: bytes = b"\x89PNG\r\n\x1a\n" + +_imageDictPrototype: GenericDict = dict( + fileName=(str, True), + xScale=((int, float), False), + xyScale=((int, float), False), + yxScale=((int, float), False), + yScale=((int, float), False), + xOffset=((int, float), False), + yOffset=((int, float), False), + color=(str, False), +) + + +def imageValidator(value): + """ + Version 3+. + """ + if not genericDictValidator(value, _imageDictPrototype): + return False + # fileName must be one or more characters + if not value["fileName"]: + return False + # color must follow the proper format + color = value.get("color") + if color is not None and not colorValidator(color): + return False + return True + + +def pngValidator( + path: Optional[str] = None, + data: Optional[bytes] = None, + fileObj: Optional[Any] = None, +) -> tuple[bool, Any]: + """ + Version 3+. + + This checks the signature of the image data. + """ + assert path is not None or data is not None or fileObj is not None + if path is not None: + with open(path, "rb") as f: + signature = f.read(8) + elif data is not None: + signature = data[:8] + elif fileObj is not None: + pos = fileObj.tell() + signature = fileObj.read(8) + fileObj.seek(pos) + if signature != pngSignature: + return False, "Image does not begin with the PNG signature." + return True, None + + +# ------------------- +# layercontents.plist +# ------------------- + + +def layerContentsValidator( + value: Any, ufoPathOrFileSystem: Union[str, fs.base.FS] +) -> tuple[bool, Optional[str]]: + """ + Check the validity of layercontents.plist. + Version 3+. + """ + if isinstance(ufoPathOrFileSystem, fs.base.FS): + fileSystem = ufoPathOrFileSystem + else: + fileSystem = fs.osfs.OSFS(ufoPathOrFileSystem) + + bogusFileMessage = "layercontents.plist in not in the correct format." + # file isn't in the right format + if not isinstance(value, list): + return False, bogusFileMessage + # work through each entry + usedLayerNames = set() + usedDirectories = set() + contents = {} + for entry in value: + # layer entry in the incorrect format + if not isinstance(entry, list): + return False, bogusFileMessage + if not len(entry) == 2: + return False, bogusFileMessage + for i in entry: + if not isinstance(i, str): + return False, bogusFileMessage + layerName, directoryName = entry + # check directory naming + if directoryName != "glyphs": + if not directoryName.startswith("glyphs."): + return ( + False, + "Invalid directory name (%s) in layercontents.plist." + % directoryName, + ) + if len(layerName) == 0: + return False, "Empty layer name in layercontents.plist." + # directory doesn't exist + if not fileSystem.exists(directoryName): + return False, "A glyphset does not exist at %s." % directoryName + # default layer name + if layerName == "public.default" and directoryName != "glyphs": + return ( + False, + "The name public.default is being used by a layer that is not the default.", + ) + # check usage + if layerName in usedLayerNames: + return ( + False, + "The layer name %s is used by more than one layer." % layerName, + ) + usedLayerNames.add(layerName) + if directoryName in usedDirectories: + return ( + False, + "The directory %s is used by more than one layer." % directoryName, + ) + usedDirectories.add(directoryName) + # store + contents[layerName] = directoryName + # missing default layer + foundDefault = "glyphs" in contents.values() + if not foundDefault: + return False, "The required default glyph set is not in the UFO." + return True, None + + +# ------------ +# groups.plist +# ------------ + + +def groupsValidator(value: Any) -> tuple[bool, Optional[str]]: + """ + Check the validity of the groups. + Version 3+ (though it's backwards compatible with UFO 1 and UFO 2). + + >>> groups = {"A" : ["A", "A"], "A2" : ["A"]} + >>> groupsValidator(groups) + (True, None) + + >>> groups = {"" : ["A"]} + >>> valid, msg = groupsValidator(groups) + >>> valid + False + >>> print(msg) + A group has an empty name. + + >>> groups = {"public.awesome" : ["A"]} + >>> groupsValidator(groups) + (True, None) + + >>> groups = {"public.kern1." : ["A"]} + >>> valid, msg = groupsValidator(groups) + >>> valid + False + >>> print(msg) + The group data contains a kerning group with an incomplete name. + >>> groups = {"public.kern2." : ["A"]} + >>> valid, msg = groupsValidator(groups) + >>> valid + False + >>> print(msg) + The group data contains a kerning group with an incomplete name. + + >>> groups = {"public.kern1.A" : ["A"], "public.kern2.A" : ["A"]} + >>> groupsValidator(groups) + (True, None) + + >>> groups = {"public.kern1.A1" : ["A"], "public.kern1.A2" : ["A"]} + >>> valid, msg = groupsValidator(groups) + >>> valid + False + >>> print(msg) + The glyph "A" occurs in too many kerning groups. + """ + bogusFormatMessage = "The group data is not in the correct format." + if not isDictEnough(value): + return False, bogusFormatMessage + firstSideMapping: dict[str, str] = {} + secondSideMapping: dict[str, str] = {} + for groupName, glyphList in value.items(): + if not isinstance(groupName, (str)): + return False, bogusFormatMessage + if not isinstance(glyphList, (list, tuple)): + return False, bogusFormatMessage + if not groupName: + return False, "A group has an empty name." + if groupName.startswith("public."): + if not groupName.startswith("public.kern1.") and not groupName.startswith( + "public.kern2." + ): + # unknown public.* name. silently skip. + continue + else: + if len("public.kernN.") == len(groupName): + return ( + False, + "The group data contains a kerning group with an incomplete name.", + ) + if groupName.startswith("public.kern1."): + d = firstSideMapping + else: + d = secondSideMapping + for glyphName in glyphList: + if not isinstance(glyphName, str): + return ( + False, + "The group data %s contains an invalid member." % groupName, + ) + if glyphName in d: + return ( + False, + 'The glyph "%s" occurs in too many kerning groups.' % glyphName, + ) + d[glyphName] = groupName + return True, None + + +# ------------- +# kerning.plist +# ------------- + + +def kerningValidator(data: Any) -> tuple[bool, Optional[str]]: + """ + Check the validity of the kerning data structure. + Version 3+ (though it's backwards compatible with UFO 1 and UFO 2). + + >>> kerning = {"A" : {"B" : 100}} + >>> kerningValidator(kerning) + (True, None) + + >>> kerning = {"A" : ["B"]} + >>> valid, msg = kerningValidator(kerning) + >>> valid + False + >>> print(msg) + The kerning data is not in the correct format. + + >>> kerning = {"A" : {"B" : "100"}} + >>> valid, msg = kerningValidator(kerning) + >>> valid + False + >>> print(msg) + The kerning data is not in the correct format. + """ + bogusFormatMessage = "The kerning data is not in the correct format." + if not isinstance(data, Mapping): + return False, bogusFormatMessage + for first, secondDict in data.items(): + if not isinstance(first, str): + return False, bogusFormatMessage + elif not isinstance(secondDict, Mapping): + return False, bogusFormatMessage + for second, value in secondDict.items(): + if not isinstance(second, str): + return False, bogusFormatMessage + elif not isinstance(value, numberTypes): + return False, bogusFormatMessage + return True, None + + +# ------------- +# lib.plist/lib +# ------------- + +_bogusLibFormatMessage = "The lib data is not in the correct format: %s" + + +def fontLibValidator(value: Any) -> tuple[bool, Optional[str]]: + """ + Check the validity of the lib. + Version 3+ (though it's backwards compatible with UFO 1 and UFO 2). + + >>> lib = {"foo" : "bar"} + >>> fontLibValidator(lib) + (True, None) + + >>> lib = {"public.awesome" : "hello"} + >>> fontLibValidator(lib) + (True, None) + + >>> lib = {"public.glyphOrder" : ["A", "C", "B"]} + >>> fontLibValidator(lib) + (True, None) + + >>> lib = "hello" + >>> valid, msg = fontLibValidator(lib) + >>> valid + False + >>> print(msg) # doctest: +ELLIPSIS + The lib data is not in the correct format: expected a dictionary, ... + + >>> lib = {1: "hello"} + >>> valid, msg = fontLibValidator(lib) + >>> valid + False + >>> print(msg) + The lib key is not properly formatted: expected str, found int: 1 + + >>> lib = {"public.glyphOrder" : "hello"} + >>> valid, msg = fontLibValidator(lib) + >>> valid + False + >>> print(msg) # doctest: +ELLIPSIS + public.glyphOrder is not properly formatted: expected list or tuple,... + + >>> lib = {"public.glyphOrder" : ["A", 1, "B"]} + >>> valid, msg = fontLibValidator(lib) + >>> valid + False + >>> print(msg) # doctest: +ELLIPSIS + public.glyphOrder is not properly formatted: expected str,... + """ + if not isDictEnough(value): + reason = "expected a dictionary, found %s" % type(value).__name__ + return False, _bogusLibFormatMessage % reason + for key, value in value.items(): + if not isinstance(key, str): + return False, ( + "The lib key is not properly formatted: expected str, found %s: %r" + % (type(key).__name__, key) + ) + # public.glyphOrder + if key == "public.glyphOrder": + bogusGlyphOrderMessage = "public.glyphOrder is not properly formatted: %s" + if not isinstance(value, (list, tuple)): + reason = "expected list or tuple, found %s" % type(value).__name__ + return False, bogusGlyphOrderMessage % reason + for glyphName in value: + if not isinstance(glyphName, str): + reason = "expected str, found %s" % type(glyphName).__name__ + return False, bogusGlyphOrderMessage % reason + return True, None + + +# -------- +# GLIF lib +# -------- + + +def glyphLibValidator(value: Any) -> tuple[bool, Optional[str]]: + """ + Check the validity of the lib. + Version 3+ (though it's backwards compatible with UFO 1 and UFO 2). + + >>> lib = {"foo" : "bar"} + >>> glyphLibValidator(lib) + (True, None) + + >>> lib = {"public.awesome" : "hello"} + >>> glyphLibValidator(lib) + (True, None) + + >>> lib = {"public.markColor" : "1,0,0,0.5"} + >>> glyphLibValidator(lib) + (True, None) + + >>> lib = {"public.markColor" : 1} + >>> valid, msg = glyphLibValidator(lib) + >>> valid + False + >>> print(msg) + public.markColor is not properly formatted. + """ + if not isDictEnough(value): + reason = "expected a dictionary, found %s" % type(value).__name__ + return False, _bogusLibFormatMessage % reason + for key, value in value.items(): + if not isinstance(key, str): + reason = "key (%s) should be a string" % key + return False, _bogusLibFormatMessage % reason + # public.markColor + if key == "public.markColor": + if not colorValidator(value): + return False, "public.markColor is not properly formatted." + return True, None + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicode.py b/.venv/lib/python3.12/site-packages/fontTools/unicode.py new file mode 100644 index 0000000000000000000000000000000000000000..a9ffeefac1c9e553c53bc12346e49e7ece8d364a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/unicode.py @@ -0,0 +1,50 @@ +def _makeunicodes(f): + lines = iter(f.readlines()) + unicodes = {} + for line in lines: + if not line: + continue + num, name = line.split(";")[:2] + if name[0] == "<": + continue # "<control>", etc. + num = int(num, 16) + unicodes[num] = name + return unicodes + + +class _UnicodeCustom(object): + def __init__(self, f): + if isinstance(f, str): + with open(f) as fd: + codes = _makeunicodes(fd) + else: + codes = _makeunicodes(f) + self.codes = codes + + def __getitem__(self, charCode): + try: + return self.codes[charCode] + except KeyError: + return "????" + + +class _UnicodeBuiltin(object): + def __getitem__(self, charCode): + try: + # use unicodedata backport to python2, if available: + # https://github.com/mikekap/unicodedata2 + import unicodedata2 as unicodedata + except ImportError: + import unicodedata + try: + return unicodedata.name(chr(charCode)) + except ValueError: + return "????" + + +Unicode = _UnicodeBuiltin() + + +def setUnicodeData(f): + global Unicode + Unicode = _UnicodeCustom(f) diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicodedata/Blocks.py b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/Blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..c333c4ee3bfdd4d20e5b89854bac3ba35769b975 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/Blocks.py @@ -0,0 +1,817 @@ +# -*- coding: utf-8 -*- +# +# NOTE: This file was auto-generated with MetaTools/buildUCD.py. +# Source: https://unicode.org/Public/UNIDATA/Blocks.txt +# License: http://unicode.org/copyright.html#License +# +# Blocks-17.0.0.txt +# Date: 2025-08-01 +# © 2025 Unicode®, Inc. +# Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. in the U.S. and other countries. +# For terms of use and license, see https://www.unicode.org/terms_of_use.html +# +# Unicode Character Database +# For documentation, see https://www.unicode.org/reports/tr44/ +# +# Format: +# Start Code..End Code; Block Name + +RANGES = [ + 0x0000, # .. 0x007F ; Basic Latin + 0x0080, # .. 0x00FF ; Latin-1 Supplement + 0x0100, # .. 0x017F ; Latin Extended-A + 0x0180, # .. 0x024F ; Latin Extended-B + 0x0250, # .. 0x02AF ; IPA Extensions + 0x02B0, # .. 0x02FF ; Spacing Modifier Letters + 0x0300, # .. 0x036F ; Combining Diacritical Marks + 0x0370, # .. 0x03FF ; Greek and Coptic + 0x0400, # .. 0x04FF ; Cyrillic + 0x0500, # .. 0x052F ; Cyrillic Supplement + 0x0530, # .. 0x058F ; Armenian + 0x0590, # .. 0x05FF ; Hebrew + 0x0600, # .. 0x06FF ; Arabic + 0x0700, # .. 0x074F ; Syriac + 0x0750, # .. 0x077F ; Arabic Supplement + 0x0780, # .. 0x07BF ; Thaana + 0x07C0, # .. 0x07FF ; NKo + 0x0800, # .. 0x083F ; Samaritan + 0x0840, # .. 0x085F ; Mandaic + 0x0860, # .. 0x086F ; Syriac Supplement + 0x0870, # .. 0x089F ; Arabic Extended-B + 0x08A0, # .. 0x08FF ; Arabic Extended-A + 0x0900, # .. 0x097F ; Devanagari + 0x0980, # .. 0x09FF ; Bengali + 0x0A00, # .. 0x0A7F ; Gurmukhi + 0x0A80, # .. 0x0AFF ; Gujarati + 0x0B00, # .. 0x0B7F ; Oriya + 0x0B80, # .. 0x0BFF ; Tamil + 0x0C00, # .. 0x0C7F ; Telugu + 0x0C80, # .. 0x0CFF ; Kannada + 0x0D00, # .. 0x0D7F ; Malayalam + 0x0D80, # .. 0x0DFF ; Sinhala + 0x0E00, # .. 0x0E7F ; Thai + 0x0E80, # .. 0x0EFF ; Lao + 0x0F00, # .. 0x0FFF ; Tibetan + 0x1000, # .. 0x109F ; Myanmar + 0x10A0, # .. 0x10FF ; Georgian + 0x1100, # .. 0x11FF ; Hangul Jamo + 0x1200, # .. 0x137F ; Ethiopic + 0x1380, # .. 0x139F ; Ethiopic Supplement + 0x13A0, # .. 0x13FF ; Cherokee + 0x1400, # .. 0x167F ; Unified Canadian Aboriginal Syllabics + 0x1680, # .. 0x169F ; Ogham + 0x16A0, # .. 0x16FF ; Runic + 0x1700, # .. 0x171F ; Tagalog + 0x1720, # .. 0x173F ; Hanunoo + 0x1740, # .. 0x175F ; Buhid + 0x1760, # .. 0x177F ; Tagbanwa + 0x1780, # .. 0x17FF ; Khmer + 0x1800, # .. 0x18AF ; Mongolian + 0x18B0, # .. 0x18FF ; Unified Canadian Aboriginal Syllabics Extended + 0x1900, # .. 0x194F ; Limbu + 0x1950, # .. 0x197F ; Tai Le + 0x1980, # .. 0x19DF ; New Tai Lue + 0x19E0, # .. 0x19FF ; Khmer Symbols + 0x1A00, # .. 0x1A1F ; Buginese + 0x1A20, # .. 0x1AAF ; Tai Tham + 0x1AB0, # .. 0x1AFF ; Combining Diacritical Marks Extended + 0x1B00, # .. 0x1B7F ; Balinese + 0x1B80, # .. 0x1BBF ; Sundanese + 0x1BC0, # .. 0x1BFF ; Batak + 0x1C00, # .. 0x1C4F ; Lepcha + 0x1C50, # .. 0x1C7F ; Ol Chiki + 0x1C80, # .. 0x1C8F ; Cyrillic Extended-C + 0x1C90, # .. 0x1CBF ; Georgian Extended + 0x1CC0, # .. 0x1CCF ; Sundanese Supplement + 0x1CD0, # .. 0x1CFF ; Vedic Extensions + 0x1D00, # .. 0x1D7F ; Phonetic Extensions + 0x1D80, # .. 0x1DBF ; Phonetic Extensions Supplement + 0x1DC0, # .. 0x1DFF ; Combining Diacritical Marks Supplement + 0x1E00, # .. 0x1EFF ; Latin Extended Additional + 0x1F00, # .. 0x1FFF ; Greek Extended + 0x2000, # .. 0x206F ; General Punctuation + 0x2070, # .. 0x209F ; Superscripts and Subscripts + 0x20A0, # .. 0x20CF ; Currency Symbols + 0x20D0, # .. 0x20FF ; Combining Diacritical Marks for Symbols + 0x2100, # .. 0x214F ; Letterlike Symbols + 0x2150, # .. 0x218F ; Number Forms + 0x2190, # .. 0x21FF ; Arrows + 0x2200, # .. 0x22FF ; Mathematical Operators + 0x2300, # .. 0x23FF ; Miscellaneous Technical + 0x2400, # .. 0x243F ; Control Pictures + 0x2440, # .. 0x245F ; Optical Character Recognition + 0x2460, # .. 0x24FF ; Enclosed Alphanumerics + 0x2500, # .. 0x257F ; Box Drawing + 0x2580, # .. 0x259F ; Block Elements + 0x25A0, # .. 0x25FF ; Geometric Shapes + 0x2600, # .. 0x26FF ; Miscellaneous Symbols + 0x2700, # .. 0x27BF ; Dingbats + 0x27C0, # .. 0x27EF ; Miscellaneous Mathematical Symbols-A + 0x27F0, # .. 0x27FF ; Supplemental Arrows-A + 0x2800, # .. 0x28FF ; Braille Patterns + 0x2900, # .. 0x297F ; Supplemental Arrows-B + 0x2980, # .. 0x29FF ; Miscellaneous Mathematical Symbols-B + 0x2A00, # .. 0x2AFF ; Supplemental Mathematical Operators + 0x2B00, # .. 0x2BFF ; Miscellaneous Symbols and Arrows + 0x2C00, # .. 0x2C5F ; Glagolitic + 0x2C60, # .. 0x2C7F ; Latin Extended-C + 0x2C80, # .. 0x2CFF ; Coptic + 0x2D00, # .. 0x2D2F ; Georgian Supplement + 0x2D30, # .. 0x2D7F ; Tifinagh + 0x2D80, # .. 0x2DDF ; Ethiopic Extended + 0x2DE0, # .. 0x2DFF ; Cyrillic Extended-A + 0x2E00, # .. 0x2E7F ; Supplemental Punctuation + 0x2E80, # .. 0x2EFF ; CJK Radicals Supplement + 0x2F00, # .. 0x2FDF ; Kangxi Radicals + 0x2FE0, # .. 0x2FEF ; No_Block + 0x2FF0, # .. 0x2FFF ; Ideographic Description Characters + 0x3000, # .. 0x303F ; CJK Symbols and Punctuation + 0x3040, # .. 0x309F ; Hiragana + 0x30A0, # .. 0x30FF ; Katakana + 0x3100, # .. 0x312F ; Bopomofo + 0x3130, # .. 0x318F ; Hangul Compatibility Jamo + 0x3190, # .. 0x319F ; Kanbun + 0x31A0, # .. 0x31BF ; Bopomofo Extended + 0x31C0, # .. 0x31EF ; CJK Strokes + 0x31F0, # .. 0x31FF ; Katakana Phonetic Extensions + 0x3200, # .. 0x32FF ; Enclosed CJK Letters and Months + 0x3300, # .. 0x33FF ; CJK Compatibility + 0x3400, # .. 0x4DBF ; CJK Unified Ideographs Extension A + 0x4DC0, # .. 0x4DFF ; Yijing Hexagram Symbols + 0x4E00, # .. 0x9FFF ; CJK Unified Ideographs + 0xA000, # .. 0xA48F ; Yi Syllables + 0xA490, # .. 0xA4CF ; Yi Radicals + 0xA4D0, # .. 0xA4FF ; Lisu + 0xA500, # .. 0xA63F ; Vai + 0xA640, # .. 0xA69F ; Cyrillic Extended-B + 0xA6A0, # .. 0xA6FF ; Bamum + 0xA700, # .. 0xA71F ; Modifier Tone Letters + 0xA720, # .. 0xA7FF ; Latin Extended-D + 0xA800, # .. 0xA82F ; Syloti Nagri + 0xA830, # .. 0xA83F ; Common Indic Number Forms + 0xA840, # .. 0xA87F ; Phags-pa + 0xA880, # .. 0xA8DF ; Saurashtra + 0xA8E0, # .. 0xA8FF ; Devanagari Extended + 0xA900, # .. 0xA92F ; Kayah Li + 0xA930, # .. 0xA95F ; Rejang + 0xA960, # .. 0xA97F ; Hangul Jamo Extended-A + 0xA980, # .. 0xA9DF ; Javanese + 0xA9E0, # .. 0xA9FF ; Myanmar Extended-B + 0xAA00, # .. 0xAA5F ; Cham + 0xAA60, # .. 0xAA7F ; Myanmar Extended-A + 0xAA80, # .. 0xAADF ; Tai Viet + 0xAAE0, # .. 0xAAFF ; Meetei Mayek Extensions + 0xAB00, # .. 0xAB2F ; Ethiopic Extended-A + 0xAB30, # .. 0xAB6F ; Latin Extended-E + 0xAB70, # .. 0xABBF ; Cherokee Supplement + 0xABC0, # .. 0xABFF ; Meetei Mayek + 0xAC00, # .. 0xD7AF ; Hangul Syllables + 0xD7B0, # .. 0xD7FF ; Hangul Jamo Extended-B + 0xD800, # .. 0xDB7F ; High Surrogates + 0xDB80, # .. 0xDBFF ; High Private Use Surrogates + 0xDC00, # .. 0xDFFF ; Low Surrogates + 0xE000, # .. 0xF8FF ; Private Use Area + 0xF900, # .. 0xFAFF ; CJK Compatibility Ideographs + 0xFB00, # .. 0xFB4F ; Alphabetic Presentation Forms + 0xFB50, # .. 0xFDFF ; Arabic Presentation Forms-A + 0xFE00, # .. 0xFE0F ; Variation Selectors + 0xFE10, # .. 0xFE1F ; Vertical Forms + 0xFE20, # .. 0xFE2F ; Combining Half Marks + 0xFE30, # .. 0xFE4F ; CJK Compatibility Forms + 0xFE50, # .. 0xFE6F ; Small Form Variants + 0xFE70, # .. 0xFEFF ; Arabic Presentation Forms-B + 0xFF00, # .. 0xFFEF ; Halfwidth and Fullwidth Forms + 0xFFF0, # .. 0xFFFF ; Specials + 0x10000, # .. 0x1007F ; Linear B Syllabary + 0x10080, # .. 0x100FF ; Linear B Ideograms + 0x10100, # .. 0x1013F ; Aegean Numbers + 0x10140, # .. 0x1018F ; Ancient Greek Numbers + 0x10190, # .. 0x101CF ; Ancient Symbols + 0x101D0, # .. 0x101FF ; Phaistos Disc + 0x10200, # .. 0x1027F ; No_Block + 0x10280, # .. 0x1029F ; Lycian + 0x102A0, # .. 0x102DF ; Carian + 0x102E0, # .. 0x102FF ; Coptic Epact Numbers + 0x10300, # .. 0x1032F ; Old Italic + 0x10330, # .. 0x1034F ; Gothic + 0x10350, # .. 0x1037F ; Old Permic + 0x10380, # .. 0x1039F ; Ugaritic + 0x103A0, # .. 0x103DF ; Old Persian + 0x103E0, # .. 0x103FF ; No_Block + 0x10400, # .. 0x1044F ; Deseret + 0x10450, # .. 0x1047F ; Shavian + 0x10480, # .. 0x104AF ; Osmanya + 0x104B0, # .. 0x104FF ; Osage + 0x10500, # .. 0x1052F ; Elbasan + 0x10530, # .. 0x1056F ; Caucasian Albanian + 0x10570, # .. 0x105BF ; Vithkuqi + 0x105C0, # .. 0x105FF ; Todhri + 0x10600, # .. 0x1077F ; Linear A + 0x10780, # .. 0x107BF ; Latin Extended-F + 0x107C0, # .. 0x107FF ; No_Block + 0x10800, # .. 0x1083F ; Cypriot Syllabary + 0x10840, # .. 0x1085F ; Imperial Aramaic + 0x10860, # .. 0x1087F ; Palmyrene + 0x10880, # .. 0x108AF ; Nabataean + 0x108B0, # .. 0x108DF ; No_Block + 0x108E0, # .. 0x108FF ; Hatran + 0x10900, # .. 0x1091F ; Phoenician + 0x10920, # .. 0x1093F ; Lydian + 0x10940, # .. 0x1095F ; Sidetic + 0x10960, # .. 0x1097F ; No_Block + 0x10980, # .. 0x1099F ; Meroitic Hieroglyphs + 0x109A0, # .. 0x109FF ; Meroitic Cursive + 0x10A00, # .. 0x10A5F ; Kharoshthi + 0x10A60, # .. 0x10A7F ; Old South Arabian + 0x10A80, # .. 0x10A9F ; Old North Arabian + 0x10AA0, # .. 0x10ABF ; No_Block + 0x10AC0, # .. 0x10AFF ; Manichaean + 0x10B00, # .. 0x10B3F ; Avestan + 0x10B40, # .. 0x10B5F ; Inscriptional Parthian + 0x10B60, # .. 0x10B7F ; Inscriptional Pahlavi + 0x10B80, # .. 0x10BAF ; Psalter Pahlavi + 0x10BB0, # .. 0x10BFF ; No_Block + 0x10C00, # .. 0x10C4F ; Old Turkic + 0x10C50, # .. 0x10C7F ; No_Block + 0x10C80, # .. 0x10CFF ; Old Hungarian + 0x10D00, # .. 0x10D3F ; Hanifi Rohingya + 0x10D40, # .. 0x10D8F ; Garay + 0x10D90, # .. 0x10E5F ; No_Block + 0x10E60, # .. 0x10E7F ; Rumi Numeral Symbols + 0x10E80, # .. 0x10EBF ; Yezidi + 0x10EC0, # .. 0x10EFF ; Arabic Extended-C + 0x10F00, # .. 0x10F2F ; Old Sogdian + 0x10F30, # .. 0x10F6F ; Sogdian + 0x10F70, # .. 0x10FAF ; Old Uyghur + 0x10FB0, # .. 0x10FDF ; Chorasmian + 0x10FE0, # .. 0x10FFF ; Elymaic + 0x11000, # .. 0x1107F ; Brahmi + 0x11080, # .. 0x110CF ; Kaithi + 0x110D0, # .. 0x110FF ; Sora Sompeng + 0x11100, # .. 0x1114F ; Chakma + 0x11150, # .. 0x1117F ; Mahajani + 0x11180, # .. 0x111DF ; Sharada + 0x111E0, # .. 0x111FF ; Sinhala Archaic Numbers + 0x11200, # .. 0x1124F ; Khojki + 0x11250, # .. 0x1127F ; No_Block + 0x11280, # .. 0x112AF ; Multani + 0x112B0, # .. 0x112FF ; Khudawadi + 0x11300, # .. 0x1137F ; Grantha + 0x11380, # .. 0x113FF ; Tulu-Tigalari + 0x11400, # .. 0x1147F ; Newa + 0x11480, # .. 0x114DF ; Tirhuta + 0x114E0, # .. 0x1157F ; No_Block + 0x11580, # .. 0x115FF ; Siddham + 0x11600, # .. 0x1165F ; Modi + 0x11660, # .. 0x1167F ; Mongolian Supplement + 0x11680, # .. 0x116CF ; Takri + 0x116D0, # .. 0x116FF ; Myanmar Extended-C + 0x11700, # .. 0x1174F ; Ahom + 0x11750, # .. 0x117FF ; No_Block + 0x11800, # .. 0x1184F ; Dogra + 0x11850, # .. 0x1189F ; No_Block + 0x118A0, # .. 0x118FF ; Warang Citi + 0x11900, # .. 0x1195F ; Dives Akuru + 0x11960, # .. 0x1199F ; No_Block + 0x119A0, # .. 0x119FF ; Nandinagari + 0x11A00, # .. 0x11A4F ; Zanabazar Square + 0x11A50, # .. 0x11AAF ; Soyombo + 0x11AB0, # .. 0x11ABF ; Unified Canadian Aboriginal Syllabics Extended-A + 0x11AC0, # .. 0x11AFF ; Pau Cin Hau + 0x11B00, # .. 0x11B5F ; Devanagari Extended-A + 0x11B60, # .. 0x11B7F ; Sharada Supplement + 0x11B80, # .. 0x11BBF ; No_Block + 0x11BC0, # .. 0x11BFF ; Sunuwar + 0x11C00, # .. 0x11C6F ; Bhaiksuki + 0x11C70, # .. 0x11CBF ; Marchen + 0x11CC0, # .. 0x11CFF ; No_Block + 0x11D00, # .. 0x11D5F ; Masaram Gondi + 0x11D60, # .. 0x11DAF ; Gunjala Gondi + 0x11DB0, # .. 0x11DEF ; Tolong Siki + 0x11DF0, # .. 0x11EDF ; No_Block + 0x11EE0, # .. 0x11EFF ; Makasar + 0x11F00, # .. 0x11F5F ; Kawi + 0x11F60, # .. 0x11FAF ; No_Block + 0x11FB0, # .. 0x11FBF ; Lisu Supplement + 0x11FC0, # .. 0x11FFF ; Tamil Supplement + 0x12000, # .. 0x123FF ; Cuneiform + 0x12400, # .. 0x1247F ; Cuneiform Numbers and Punctuation + 0x12480, # .. 0x1254F ; Early Dynastic Cuneiform + 0x12550, # .. 0x12F8F ; No_Block + 0x12F90, # .. 0x12FFF ; Cypro-Minoan + 0x13000, # .. 0x1342F ; Egyptian Hieroglyphs + 0x13430, # .. 0x1345F ; Egyptian Hieroglyph Format Controls + 0x13460, # .. 0x143FF ; Egyptian Hieroglyphs Extended-A + 0x14400, # .. 0x1467F ; Anatolian Hieroglyphs + 0x14680, # .. 0x160FF ; No_Block + 0x16100, # .. 0x1613F ; Gurung Khema + 0x16140, # .. 0x167FF ; No_Block + 0x16800, # .. 0x16A3F ; Bamum Supplement + 0x16A40, # .. 0x16A6F ; Mro + 0x16A70, # .. 0x16ACF ; Tangsa + 0x16AD0, # .. 0x16AFF ; Bassa Vah + 0x16B00, # .. 0x16B8F ; Pahawh Hmong + 0x16B90, # .. 0x16D3F ; No_Block + 0x16D40, # .. 0x16D7F ; Kirat Rai + 0x16D80, # .. 0x16E3F ; No_Block + 0x16E40, # .. 0x16E9F ; Medefaidrin + 0x16EA0, # .. 0x16EDF ; Beria Erfe + 0x16EE0, # .. 0x16EFF ; No_Block + 0x16F00, # .. 0x16F9F ; Miao + 0x16FA0, # .. 0x16FDF ; No_Block + 0x16FE0, # .. 0x16FFF ; Ideographic Symbols and Punctuation + 0x17000, # .. 0x187FF ; Tangut + 0x18800, # .. 0x18AFF ; Tangut Components + 0x18B00, # .. 0x18CFF ; Khitan Small Script + 0x18D00, # .. 0x18D7F ; Tangut Supplement + 0x18D80, # .. 0x18DFF ; Tangut Components Supplement + 0x18E00, # .. 0x1AFEF ; No_Block + 0x1AFF0, # .. 0x1AFFF ; Kana Extended-B + 0x1B000, # .. 0x1B0FF ; Kana Supplement + 0x1B100, # .. 0x1B12F ; Kana Extended-A + 0x1B130, # .. 0x1B16F ; Small Kana Extension + 0x1B170, # .. 0x1B2FF ; Nushu + 0x1B300, # .. 0x1BBFF ; No_Block + 0x1BC00, # .. 0x1BC9F ; Duployan + 0x1BCA0, # .. 0x1BCAF ; Shorthand Format Controls + 0x1BCB0, # .. 0x1CBFF ; No_Block + 0x1CC00, # .. 0x1CEBF ; Symbols for Legacy Computing Supplement + 0x1CEC0, # .. 0x1CEFF ; Miscellaneous Symbols Supplement + 0x1CF00, # .. 0x1CFCF ; Znamenny Musical Notation + 0x1CFD0, # .. 0x1CFFF ; No_Block + 0x1D000, # .. 0x1D0FF ; Byzantine Musical Symbols + 0x1D100, # .. 0x1D1FF ; Musical Symbols + 0x1D200, # .. 0x1D24F ; Ancient Greek Musical Notation + 0x1D250, # .. 0x1D2BF ; No_Block + 0x1D2C0, # .. 0x1D2DF ; Kaktovik Numerals + 0x1D2E0, # .. 0x1D2FF ; Mayan Numerals + 0x1D300, # .. 0x1D35F ; Tai Xuan Jing Symbols + 0x1D360, # .. 0x1D37F ; Counting Rod Numerals + 0x1D380, # .. 0x1D3FF ; No_Block + 0x1D400, # .. 0x1D7FF ; Mathematical Alphanumeric Symbols + 0x1D800, # .. 0x1DAAF ; Sutton SignWriting + 0x1DAB0, # .. 0x1DEFF ; No_Block + 0x1DF00, # .. 0x1DFFF ; Latin Extended-G + 0x1E000, # .. 0x1E02F ; Glagolitic Supplement + 0x1E030, # .. 0x1E08F ; Cyrillic Extended-D + 0x1E090, # .. 0x1E0FF ; No_Block + 0x1E100, # .. 0x1E14F ; Nyiakeng Puachue Hmong + 0x1E150, # .. 0x1E28F ; No_Block + 0x1E290, # .. 0x1E2BF ; Toto + 0x1E2C0, # .. 0x1E2FF ; Wancho + 0x1E300, # .. 0x1E4CF ; No_Block + 0x1E4D0, # .. 0x1E4FF ; Nag Mundari + 0x1E500, # .. 0x1E5CF ; No_Block + 0x1E5D0, # .. 0x1E5FF ; Ol Onal + 0x1E600, # .. 0x1E6BF ; No_Block + 0x1E6C0, # .. 0x1E6FF ; Tai Yo + 0x1E700, # .. 0x1E7DF ; No_Block + 0x1E7E0, # .. 0x1E7FF ; Ethiopic Extended-B + 0x1E800, # .. 0x1E8DF ; Mende Kikakui + 0x1E8E0, # .. 0x1E8FF ; No_Block + 0x1E900, # .. 0x1E95F ; Adlam + 0x1E960, # .. 0x1EC6F ; No_Block + 0x1EC70, # .. 0x1ECBF ; Indic Siyaq Numbers + 0x1ECC0, # .. 0x1ECFF ; No_Block + 0x1ED00, # .. 0x1ED4F ; Ottoman Siyaq Numbers + 0x1ED50, # .. 0x1EDFF ; No_Block + 0x1EE00, # .. 0x1EEFF ; Arabic Mathematical Alphabetic Symbols + 0x1EF00, # .. 0x1EFFF ; No_Block + 0x1F000, # .. 0x1F02F ; Mahjong Tiles + 0x1F030, # .. 0x1F09F ; Domino Tiles + 0x1F0A0, # .. 0x1F0FF ; Playing Cards + 0x1F100, # .. 0x1F1FF ; Enclosed Alphanumeric Supplement + 0x1F200, # .. 0x1F2FF ; Enclosed Ideographic Supplement + 0x1F300, # .. 0x1F5FF ; Miscellaneous Symbols and Pictographs + 0x1F600, # .. 0x1F64F ; Emoticons + 0x1F650, # .. 0x1F67F ; Ornamental Dingbats + 0x1F680, # .. 0x1F6FF ; Transport and Map Symbols + 0x1F700, # .. 0x1F77F ; Alchemical Symbols + 0x1F780, # .. 0x1F7FF ; Geometric Shapes Extended + 0x1F800, # .. 0x1F8FF ; Supplemental Arrows-C + 0x1F900, # .. 0x1F9FF ; Supplemental Symbols and Pictographs + 0x1FA00, # .. 0x1FA6F ; Chess Symbols + 0x1FA70, # .. 0x1FAFF ; Symbols and Pictographs Extended-A + 0x1FB00, # .. 0x1FBFF ; Symbols for Legacy Computing + 0x1FC00, # .. 0x1FFFF ; No_Block + 0x20000, # .. 0x2A6DF ; CJK Unified Ideographs Extension B + 0x2A6E0, # .. 0x2A6FF ; No_Block + 0x2A700, # .. 0x2B73F ; CJK Unified Ideographs Extension C + 0x2B740, # .. 0x2B81F ; CJK Unified Ideographs Extension D + 0x2B820, # .. 0x2CEAF ; CJK Unified Ideographs Extension E + 0x2CEB0, # .. 0x2EBEF ; CJK Unified Ideographs Extension F + 0x2EBF0, # .. 0x2EE5F ; CJK Unified Ideographs Extension I + 0x2EE60, # .. 0x2F7FF ; No_Block + 0x2F800, # .. 0x2FA1F ; CJK Compatibility Ideographs Supplement + 0x2FA20, # .. 0x2FFFF ; No_Block + 0x30000, # .. 0x3134F ; CJK Unified Ideographs Extension G + 0x31350, # .. 0x323AF ; CJK Unified Ideographs Extension H + 0x323B0, # .. 0x3347F ; CJK Unified Ideographs Extension J + 0x33480, # .. 0xDFFFF ; No_Block + 0xE0000, # .. 0xE007F ; Tags + 0xE0080, # .. 0xE00FF ; No_Block + 0xE0100, # .. 0xE01EF ; Variation Selectors Supplement + 0xE01F0, # .. 0xEFFFF ; No_Block + 0xF0000, # .. 0xFFFFF ; Supplementary Private Use Area-A + 0x100000, # .. 0x10FFFF ; Supplementary Private Use Area-B +] + +VALUES = [ + "Basic Latin", # 0000..007F + "Latin-1 Supplement", # 0080..00FF + "Latin Extended-A", # 0100..017F + "Latin Extended-B", # 0180..024F + "IPA Extensions", # 0250..02AF + "Spacing Modifier Letters", # 02B0..02FF + "Combining Diacritical Marks", # 0300..036F + "Greek and Coptic", # 0370..03FF + "Cyrillic", # 0400..04FF + "Cyrillic Supplement", # 0500..052F + "Armenian", # 0530..058F + "Hebrew", # 0590..05FF + "Arabic", # 0600..06FF + "Syriac", # 0700..074F + "Arabic Supplement", # 0750..077F + "Thaana", # 0780..07BF + "NKo", # 07C0..07FF + "Samaritan", # 0800..083F + "Mandaic", # 0840..085F + "Syriac Supplement", # 0860..086F + "Arabic Extended-B", # 0870..089F + "Arabic Extended-A", # 08A0..08FF + "Devanagari", # 0900..097F + "Bengali", # 0980..09FF + "Gurmukhi", # 0A00..0A7F + "Gujarati", # 0A80..0AFF + "Oriya", # 0B00..0B7F + "Tamil", # 0B80..0BFF + "Telugu", # 0C00..0C7F + "Kannada", # 0C80..0CFF + "Malayalam", # 0D00..0D7F + "Sinhala", # 0D80..0DFF + "Thai", # 0E00..0E7F + "Lao", # 0E80..0EFF + "Tibetan", # 0F00..0FFF + "Myanmar", # 1000..109F + "Georgian", # 10A0..10FF + "Hangul Jamo", # 1100..11FF + "Ethiopic", # 1200..137F + "Ethiopic Supplement", # 1380..139F + "Cherokee", # 13A0..13FF + "Unified Canadian Aboriginal Syllabics", # 1400..167F + "Ogham", # 1680..169F + "Runic", # 16A0..16FF + "Tagalog", # 1700..171F + "Hanunoo", # 1720..173F + "Buhid", # 1740..175F + "Tagbanwa", # 1760..177F + "Khmer", # 1780..17FF + "Mongolian", # 1800..18AF + "Unified Canadian Aboriginal Syllabics Extended", # 18B0..18FF + "Limbu", # 1900..194F + "Tai Le", # 1950..197F + "New Tai Lue", # 1980..19DF + "Khmer Symbols", # 19E0..19FF + "Buginese", # 1A00..1A1F + "Tai Tham", # 1A20..1AAF + "Combining Diacritical Marks Extended", # 1AB0..1AFF + "Balinese", # 1B00..1B7F + "Sundanese", # 1B80..1BBF + "Batak", # 1BC0..1BFF + "Lepcha", # 1C00..1C4F + "Ol Chiki", # 1C50..1C7F + "Cyrillic Extended-C", # 1C80..1C8F + "Georgian Extended", # 1C90..1CBF + "Sundanese Supplement", # 1CC0..1CCF + "Vedic Extensions", # 1CD0..1CFF + "Phonetic Extensions", # 1D00..1D7F + "Phonetic Extensions Supplement", # 1D80..1DBF + "Combining Diacritical Marks Supplement", # 1DC0..1DFF + "Latin Extended Additional", # 1E00..1EFF + "Greek Extended", # 1F00..1FFF + "General Punctuation", # 2000..206F + "Superscripts and Subscripts", # 2070..209F + "Currency Symbols", # 20A0..20CF + "Combining Diacritical Marks for Symbols", # 20D0..20FF + "Letterlike Symbols", # 2100..214F + "Number Forms", # 2150..218F + "Arrows", # 2190..21FF + "Mathematical Operators", # 2200..22FF + "Miscellaneous Technical", # 2300..23FF + "Control Pictures", # 2400..243F + "Optical Character Recognition", # 2440..245F + "Enclosed Alphanumerics", # 2460..24FF + "Box Drawing", # 2500..257F + "Block Elements", # 2580..259F + "Geometric Shapes", # 25A0..25FF + "Miscellaneous Symbols", # 2600..26FF + "Dingbats", # 2700..27BF + "Miscellaneous Mathematical Symbols-A", # 27C0..27EF + "Supplemental Arrows-A", # 27F0..27FF + "Braille Patterns", # 2800..28FF + "Supplemental Arrows-B", # 2900..297F + "Miscellaneous Mathematical Symbols-B", # 2980..29FF + "Supplemental Mathematical Operators", # 2A00..2AFF + "Miscellaneous Symbols and Arrows", # 2B00..2BFF + "Glagolitic", # 2C00..2C5F + "Latin Extended-C", # 2C60..2C7F + "Coptic", # 2C80..2CFF + "Georgian Supplement", # 2D00..2D2F + "Tifinagh", # 2D30..2D7F + "Ethiopic Extended", # 2D80..2DDF + "Cyrillic Extended-A", # 2DE0..2DFF + "Supplemental Punctuation", # 2E00..2E7F + "CJK Radicals Supplement", # 2E80..2EFF + "Kangxi Radicals", # 2F00..2FDF + "No_Block", # 2FE0..2FEF + "Ideographic Description Characters", # 2FF0..2FFF + "CJK Symbols and Punctuation", # 3000..303F + "Hiragana", # 3040..309F + "Katakana", # 30A0..30FF + "Bopomofo", # 3100..312F + "Hangul Compatibility Jamo", # 3130..318F + "Kanbun", # 3190..319F + "Bopomofo Extended", # 31A0..31BF + "CJK Strokes", # 31C0..31EF + "Katakana Phonetic Extensions", # 31F0..31FF + "Enclosed CJK Letters and Months", # 3200..32FF + "CJK Compatibility", # 3300..33FF + "CJK Unified Ideographs Extension A", # 3400..4DBF + "Yijing Hexagram Symbols", # 4DC0..4DFF + "CJK Unified Ideographs", # 4E00..9FFF + "Yi Syllables", # A000..A48F + "Yi Radicals", # A490..A4CF + "Lisu", # A4D0..A4FF + "Vai", # A500..A63F + "Cyrillic Extended-B", # A640..A69F + "Bamum", # A6A0..A6FF + "Modifier Tone Letters", # A700..A71F + "Latin Extended-D", # A720..A7FF + "Syloti Nagri", # A800..A82F + "Common Indic Number Forms", # A830..A83F + "Phags-pa", # A840..A87F + "Saurashtra", # A880..A8DF + "Devanagari Extended", # A8E0..A8FF + "Kayah Li", # A900..A92F + "Rejang", # A930..A95F + "Hangul Jamo Extended-A", # A960..A97F + "Javanese", # A980..A9DF + "Myanmar Extended-B", # A9E0..A9FF + "Cham", # AA00..AA5F + "Myanmar Extended-A", # AA60..AA7F + "Tai Viet", # AA80..AADF + "Meetei Mayek Extensions", # AAE0..AAFF + "Ethiopic Extended-A", # AB00..AB2F + "Latin Extended-E", # AB30..AB6F + "Cherokee Supplement", # AB70..ABBF + "Meetei Mayek", # ABC0..ABFF + "Hangul Syllables", # AC00..D7AF + "Hangul Jamo Extended-B", # D7B0..D7FF + "High Surrogates", # D800..DB7F + "High Private Use Surrogates", # DB80..DBFF + "Low Surrogates", # DC00..DFFF + "Private Use Area", # E000..F8FF + "CJK Compatibility Ideographs", # F900..FAFF + "Alphabetic Presentation Forms", # FB00..FB4F + "Arabic Presentation Forms-A", # FB50..FDFF + "Variation Selectors", # FE00..FE0F + "Vertical Forms", # FE10..FE1F + "Combining Half Marks", # FE20..FE2F + "CJK Compatibility Forms", # FE30..FE4F + "Small Form Variants", # FE50..FE6F + "Arabic Presentation Forms-B", # FE70..FEFF + "Halfwidth and Fullwidth Forms", # FF00..FFEF + "Specials", # FFF0..FFFF + "Linear B Syllabary", # 10000..1007F + "Linear B Ideograms", # 10080..100FF + "Aegean Numbers", # 10100..1013F + "Ancient Greek Numbers", # 10140..1018F + "Ancient Symbols", # 10190..101CF + "Phaistos Disc", # 101D0..101FF + "No_Block", # 10200..1027F + "Lycian", # 10280..1029F + "Carian", # 102A0..102DF + "Coptic Epact Numbers", # 102E0..102FF + "Old Italic", # 10300..1032F + "Gothic", # 10330..1034F + "Old Permic", # 10350..1037F + "Ugaritic", # 10380..1039F + "Old Persian", # 103A0..103DF + "No_Block", # 103E0..103FF + "Deseret", # 10400..1044F + "Shavian", # 10450..1047F + "Osmanya", # 10480..104AF + "Osage", # 104B0..104FF + "Elbasan", # 10500..1052F + "Caucasian Albanian", # 10530..1056F + "Vithkuqi", # 10570..105BF + "Todhri", # 105C0..105FF + "Linear A", # 10600..1077F + "Latin Extended-F", # 10780..107BF + "No_Block", # 107C0..107FF + "Cypriot Syllabary", # 10800..1083F + "Imperial Aramaic", # 10840..1085F + "Palmyrene", # 10860..1087F + "Nabataean", # 10880..108AF + "No_Block", # 108B0..108DF + "Hatran", # 108E0..108FF + "Phoenician", # 10900..1091F + "Lydian", # 10920..1093F + "Sidetic", # 10940..1095F + "No_Block", # 10960..1097F + "Meroitic Hieroglyphs", # 10980..1099F + "Meroitic Cursive", # 109A0..109FF + "Kharoshthi", # 10A00..10A5F + "Old South Arabian", # 10A60..10A7F + "Old North Arabian", # 10A80..10A9F + "No_Block", # 10AA0..10ABF + "Manichaean", # 10AC0..10AFF + "Avestan", # 10B00..10B3F + "Inscriptional Parthian", # 10B40..10B5F + "Inscriptional Pahlavi", # 10B60..10B7F + "Psalter Pahlavi", # 10B80..10BAF + "No_Block", # 10BB0..10BFF + "Old Turkic", # 10C00..10C4F + "No_Block", # 10C50..10C7F + "Old Hungarian", # 10C80..10CFF + "Hanifi Rohingya", # 10D00..10D3F + "Garay", # 10D40..10D8F + "No_Block", # 10D90..10E5F + "Rumi Numeral Symbols", # 10E60..10E7F + "Yezidi", # 10E80..10EBF + "Arabic Extended-C", # 10EC0..10EFF + "Old Sogdian", # 10F00..10F2F + "Sogdian", # 10F30..10F6F + "Old Uyghur", # 10F70..10FAF + "Chorasmian", # 10FB0..10FDF + "Elymaic", # 10FE0..10FFF + "Brahmi", # 11000..1107F + "Kaithi", # 11080..110CF + "Sora Sompeng", # 110D0..110FF + "Chakma", # 11100..1114F + "Mahajani", # 11150..1117F + "Sharada", # 11180..111DF + "Sinhala Archaic Numbers", # 111E0..111FF + "Khojki", # 11200..1124F + "No_Block", # 11250..1127F + "Multani", # 11280..112AF + "Khudawadi", # 112B0..112FF + "Grantha", # 11300..1137F + "Tulu-Tigalari", # 11380..113FF + "Newa", # 11400..1147F + "Tirhuta", # 11480..114DF + "No_Block", # 114E0..1157F + "Siddham", # 11580..115FF + "Modi", # 11600..1165F + "Mongolian Supplement", # 11660..1167F + "Takri", # 11680..116CF + "Myanmar Extended-C", # 116D0..116FF + "Ahom", # 11700..1174F + "No_Block", # 11750..117FF + "Dogra", # 11800..1184F + "No_Block", # 11850..1189F + "Warang Citi", # 118A0..118FF + "Dives Akuru", # 11900..1195F + "No_Block", # 11960..1199F + "Nandinagari", # 119A0..119FF + "Zanabazar Square", # 11A00..11A4F + "Soyombo", # 11A50..11AAF + "Unified Canadian Aboriginal Syllabics Extended-A", # 11AB0..11ABF + "Pau Cin Hau", # 11AC0..11AFF + "Devanagari Extended-A", # 11B00..11B5F + "Sharada Supplement", # 11B60..11B7F + "No_Block", # 11B80..11BBF + "Sunuwar", # 11BC0..11BFF + "Bhaiksuki", # 11C00..11C6F + "Marchen", # 11C70..11CBF + "No_Block", # 11CC0..11CFF + "Masaram Gondi", # 11D00..11D5F + "Gunjala Gondi", # 11D60..11DAF + "Tolong Siki", # 11DB0..11DEF + "No_Block", # 11DF0..11EDF + "Makasar", # 11EE0..11EFF + "Kawi", # 11F00..11F5F + "No_Block", # 11F60..11FAF + "Lisu Supplement", # 11FB0..11FBF + "Tamil Supplement", # 11FC0..11FFF + "Cuneiform", # 12000..123FF + "Cuneiform Numbers and Punctuation", # 12400..1247F + "Early Dynastic Cuneiform", # 12480..1254F + "No_Block", # 12550..12F8F + "Cypro-Minoan", # 12F90..12FFF + "Egyptian Hieroglyphs", # 13000..1342F + "Egyptian Hieroglyph Format Controls", # 13430..1345F + "Egyptian Hieroglyphs Extended-A", # 13460..143FF + "Anatolian Hieroglyphs", # 14400..1467F + "No_Block", # 14680..160FF + "Gurung Khema", # 16100..1613F + "No_Block", # 16140..167FF + "Bamum Supplement", # 16800..16A3F + "Mro", # 16A40..16A6F + "Tangsa", # 16A70..16ACF + "Bassa Vah", # 16AD0..16AFF + "Pahawh Hmong", # 16B00..16B8F + "No_Block", # 16B90..16D3F + "Kirat Rai", # 16D40..16D7F + "No_Block", # 16D80..16E3F + "Medefaidrin", # 16E40..16E9F + "Beria Erfe", # 16EA0..16EDF + "No_Block", # 16EE0..16EFF + "Miao", # 16F00..16F9F + "No_Block", # 16FA0..16FDF + "Ideographic Symbols and Punctuation", # 16FE0..16FFF + "Tangut", # 17000..187FF + "Tangut Components", # 18800..18AFF + "Khitan Small Script", # 18B00..18CFF + "Tangut Supplement", # 18D00..18D7F + "Tangut Components Supplement", # 18D80..18DFF + "No_Block", # 18E00..1AFEF + "Kana Extended-B", # 1AFF0..1AFFF + "Kana Supplement", # 1B000..1B0FF + "Kana Extended-A", # 1B100..1B12F + "Small Kana Extension", # 1B130..1B16F + "Nushu", # 1B170..1B2FF + "No_Block", # 1B300..1BBFF + "Duployan", # 1BC00..1BC9F + "Shorthand Format Controls", # 1BCA0..1BCAF + "No_Block", # 1BCB0..1CBFF + "Symbols for Legacy Computing Supplement", # 1CC00..1CEBF + "Miscellaneous Symbols Supplement", # 1CEC0..1CEFF + "Znamenny Musical Notation", # 1CF00..1CFCF + "No_Block", # 1CFD0..1CFFF + "Byzantine Musical Symbols", # 1D000..1D0FF + "Musical Symbols", # 1D100..1D1FF + "Ancient Greek Musical Notation", # 1D200..1D24F + "No_Block", # 1D250..1D2BF + "Kaktovik Numerals", # 1D2C0..1D2DF + "Mayan Numerals", # 1D2E0..1D2FF + "Tai Xuan Jing Symbols", # 1D300..1D35F + "Counting Rod Numerals", # 1D360..1D37F + "No_Block", # 1D380..1D3FF + "Mathematical Alphanumeric Symbols", # 1D400..1D7FF + "Sutton SignWriting", # 1D800..1DAAF + "No_Block", # 1DAB0..1DEFF + "Latin Extended-G", # 1DF00..1DFFF + "Glagolitic Supplement", # 1E000..1E02F + "Cyrillic Extended-D", # 1E030..1E08F + "No_Block", # 1E090..1E0FF + "Nyiakeng Puachue Hmong", # 1E100..1E14F + "No_Block", # 1E150..1E28F + "Toto", # 1E290..1E2BF + "Wancho", # 1E2C0..1E2FF + "No_Block", # 1E300..1E4CF + "Nag Mundari", # 1E4D0..1E4FF + "No_Block", # 1E500..1E5CF + "Ol Onal", # 1E5D0..1E5FF + "No_Block", # 1E600..1E6BF + "Tai Yo", # 1E6C0..1E6FF + "No_Block", # 1E700..1E7DF + "Ethiopic Extended-B", # 1E7E0..1E7FF + "Mende Kikakui", # 1E800..1E8DF + "No_Block", # 1E8E0..1E8FF + "Adlam", # 1E900..1E95F + "No_Block", # 1E960..1EC6F + "Indic Siyaq Numbers", # 1EC70..1ECBF + "No_Block", # 1ECC0..1ECFF + "Ottoman Siyaq Numbers", # 1ED00..1ED4F + "No_Block", # 1ED50..1EDFF + "Arabic Mathematical Alphabetic Symbols", # 1EE00..1EEFF + "No_Block", # 1EF00..1EFFF + "Mahjong Tiles", # 1F000..1F02F + "Domino Tiles", # 1F030..1F09F + "Playing Cards", # 1F0A0..1F0FF + "Enclosed Alphanumeric Supplement", # 1F100..1F1FF + "Enclosed Ideographic Supplement", # 1F200..1F2FF + "Miscellaneous Symbols and Pictographs", # 1F300..1F5FF + "Emoticons", # 1F600..1F64F + "Ornamental Dingbats", # 1F650..1F67F + "Transport and Map Symbols", # 1F680..1F6FF + "Alchemical Symbols", # 1F700..1F77F + "Geometric Shapes Extended", # 1F780..1F7FF + "Supplemental Arrows-C", # 1F800..1F8FF + "Supplemental Symbols and Pictographs", # 1F900..1F9FF + "Chess Symbols", # 1FA00..1FA6F + "Symbols and Pictographs Extended-A", # 1FA70..1FAFF + "Symbols for Legacy Computing", # 1FB00..1FBFF + "No_Block", # 1FC00..1FFFF + "CJK Unified Ideographs Extension B", # 20000..2A6DF + "No_Block", # 2A6E0..2A6FF + "CJK Unified Ideographs Extension C", # 2A700..2B73F + "CJK Unified Ideographs Extension D", # 2B740..2B81F + "CJK Unified Ideographs Extension E", # 2B820..2CEAF + "CJK Unified Ideographs Extension F", # 2CEB0..2EBEF + "CJK Unified Ideographs Extension I", # 2EBF0..2EE5F + "No_Block", # 2EE60..2F7FF + "CJK Compatibility Ideographs Supplement", # 2F800..2FA1F + "No_Block", # 2FA20..2FFFF + "CJK Unified Ideographs Extension G", # 30000..3134F + "CJK Unified Ideographs Extension H", # 31350..323AF + "CJK Unified Ideographs Extension J", # 323B0..3347F + "No_Block", # 33480..DFFFF + "Tags", # E0000..E007F + "No_Block", # E0080..E00FF + "Variation Selectors Supplement", # E0100..E01EF + "No_Block", # E01F0..EFFFF + "Supplementary Private Use Area-A", # F0000..FFFFF + "Supplementary Private Use Area-B", # 100000..10FFFF +] diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicodedata/Mirrored.py b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/Mirrored.py new file mode 100644 index 0000000000000000000000000000000000000000..75b51a901230cce5d3886a6497dbb13da51c86b7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/Mirrored.py @@ -0,0 +1,446 @@ +# -*- coding: utf-8 -*- +# +# NOTE: The mappings in this file were generated from the command line: +# cat BidiMirroring.txt | grep "^[0-9A-F]" | sed "s/;//" | awk '{print " 0x"$1": 0x"$2","}' +# +# Source: http://www.unicode.org/Public/UNIDATA/BidiMirroring.txt +# License: http://unicode.org/copyright.html#License +# +# BidiMirroring-16.0.0.txt +# Date: 2024-01-30 +# © 2024 Unicode®, Inc. +# Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. in the U.S. and other countries. +# For terms of use and license, see https://www.unicode.org/terms_of_use.html +# +# Unicode Character Database +# For documentation, see https://www.unicode.org/reports/tr44/ +MIRRORED = { + 0x0028: 0x0029, + 0x0029: 0x0028, + 0x003C: 0x003E, + 0x003E: 0x003C, + 0x005B: 0x005D, + 0x005D: 0x005B, + 0x007B: 0x007D, + 0x007D: 0x007B, + 0x00AB: 0x00BB, + 0x00BB: 0x00AB, + 0x0F3A: 0x0F3B, + 0x0F3B: 0x0F3A, + 0x0F3C: 0x0F3D, + 0x0F3D: 0x0F3C, + 0x169B: 0x169C, + 0x169C: 0x169B, + 0x2039: 0x203A, + 0x203A: 0x2039, + 0x2045: 0x2046, + 0x2046: 0x2045, + 0x207D: 0x207E, + 0x207E: 0x207D, + 0x208D: 0x208E, + 0x208E: 0x208D, + 0x2208: 0x220B, + 0x2209: 0x220C, + 0x220A: 0x220D, + 0x220B: 0x2208, + 0x220C: 0x2209, + 0x220D: 0x220A, + 0x2215: 0x29F5, + 0x221F: 0x2BFE, + 0x2220: 0x29A3, + 0x2221: 0x299B, + 0x2222: 0x29A0, + 0x2224: 0x2AEE, + 0x223C: 0x223D, + 0x223D: 0x223C, + 0x2243: 0x22CD, + 0x2245: 0x224C, + 0x224C: 0x2245, + 0x2252: 0x2253, + 0x2253: 0x2252, + 0x2254: 0x2255, + 0x2255: 0x2254, + 0x2264: 0x2265, + 0x2265: 0x2264, + 0x2266: 0x2267, + 0x2267: 0x2266, + 0x2268: 0x2269, + 0x2269: 0x2268, + 0x226A: 0x226B, + 0x226B: 0x226A, + 0x226E: 0x226F, + 0x226F: 0x226E, + 0x2270: 0x2271, + 0x2271: 0x2270, + 0x2272: 0x2273, + 0x2273: 0x2272, + 0x2274: 0x2275, + 0x2275: 0x2274, + 0x2276: 0x2277, + 0x2277: 0x2276, + 0x2278: 0x2279, + 0x2279: 0x2278, + 0x227A: 0x227B, + 0x227B: 0x227A, + 0x227C: 0x227D, + 0x227D: 0x227C, + 0x227E: 0x227F, + 0x227F: 0x227E, + 0x2280: 0x2281, + 0x2281: 0x2280, + 0x2282: 0x2283, + 0x2283: 0x2282, + 0x2284: 0x2285, + 0x2285: 0x2284, + 0x2286: 0x2287, + 0x2287: 0x2286, + 0x2288: 0x2289, + 0x2289: 0x2288, + 0x228A: 0x228B, + 0x228B: 0x228A, + 0x228F: 0x2290, + 0x2290: 0x228F, + 0x2291: 0x2292, + 0x2292: 0x2291, + 0x2298: 0x29B8, + 0x22A2: 0x22A3, + 0x22A3: 0x22A2, + 0x22A6: 0x2ADE, + 0x22A8: 0x2AE4, + 0x22A9: 0x2AE3, + 0x22AB: 0x2AE5, + 0x22B0: 0x22B1, + 0x22B1: 0x22B0, + 0x22B2: 0x22B3, + 0x22B3: 0x22B2, + 0x22B4: 0x22B5, + 0x22B5: 0x22B4, + 0x22B6: 0x22B7, + 0x22B7: 0x22B6, + 0x22B8: 0x27DC, + 0x22C9: 0x22CA, + 0x22CA: 0x22C9, + 0x22CB: 0x22CC, + 0x22CC: 0x22CB, + 0x22CD: 0x2243, + 0x22D0: 0x22D1, + 0x22D1: 0x22D0, + 0x22D6: 0x22D7, + 0x22D7: 0x22D6, + 0x22D8: 0x22D9, + 0x22D9: 0x22D8, + 0x22DA: 0x22DB, + 0x22DB: 0x22DA, + 0x22DC: 0x22DD, + 0x22DD: 0x22DC, + 0x22DE: 0x22DF, + 0x22DF: 0x22DE, + 0x22E0: 0x22E1, + 0x22E1: 0x22E0, + 0x22E2: 0x22E3, + 0x22E3: 0x22E2, + 0x22E4: 0x22E5, + 0x22E5: 0x22E4, + 0x22E6: 0x22E7, + 0x22E7: 0x22E6, + 0x22E8: 0x22E9, + 0x22E9: 0x22E8, + 0x22EA: 0x22EB, + 0x22EB: 0x22EA, + 0x22EC: 0x22ED, + 0x22ED: 0x22EC, + 0x22F0: 0x22F1, + 0x22F1: 0x22F0, + 0x22F2: 0x22FA, + 0x22F3: 0x22FB, + 0x22F4: 0x22FC, + 0x22F6: 0x22FD, + 0x22F7: 0x22FE, + 0x22FA: 0x22F2, + 0x22FB: 0x22F3, + 0x22FC: 0x22F4, + 0x22FD: 0x22F6, + 0x22FE: 0x22F7, + 0x2308: 0x2309, + 0x2309: 0x2308, + 0x230A: 0x230B, + 0x230B: 0x230A, + 0x2329: 0x232A, + 0x232A: 0x2329, + 0x2768: 0x2769, + 0x2769: 0x2768, + 0x276A: 0x276B, + 0x276B: 0x276A, + 0x276C: 0x276D, + 0x276D: 0x276C, + 0x276E: 0x276F, + 0x276F: 0x276E, + 0x2770: 0x2771, + 0x2771: 0x2770, + 0x2772: 0x2773, + 0x2773: 0x2772, + 0x2774: 0x2775, + 0x2775: 0x2774, + 0x27C3: 0x27C4, + 0x27C4: 0x27C3, + 0x27C5: 0x27C6, + 0x27C6: 0x27C5, + 0x27C8: 0x27C9, + 0x27C9: 0x27C8, + 0x27CB: 0x27CD, + 0x27CD: 0x27CB, + 0x27D5: 0x27D6, + 0x27D6: 0x27D5, + 0x27DC: 0x22B8, + 0x27DD: 0x27DE, + 0x27DE: 0x27DD, + 0x27E2: 0x27E3, + 0x27E3: 0x27E2, + 0x27E4: 0x27E5, + 0x27E5: 0x27E4, + 0x27E6: 0x27E7, + 0x27E7: 0x27E6, + 0x27E8: 0x27E9, + 0x27E9: 0x27E8, + 0x27EA: 0x27EB, + 0x27EB: 0x27EA, + 0x27EC: 0x27ED, + 0x27ED: 0x27EC, + 0x27EE: 0x27EF, + 0x27EF: 0x27EE, + 0x2983: 0x2984, + 0x2984: 0x2983, + 0x2985: 0x2986, + 0x2986: 0x2985, + 0x2987: 0x2988, + 0x2988: 0x2987, + 0x2989: 0x298A, + 0x298A: 0x2989, + 0x298B: 0x298C, + 0x298C: 0x298B, + 0x298D: 0x2990, + 0x298E: 0x298F, + 0x298F: 0x298E, + 0x2990: 0x298D, + 0x2991: 0x2992, + 0x2992: 0x2991, + 0x2993: 0x2994, + 0x2994: 0x2993, + 0x2995: 0x2996, + 0x2996: 0x2995, + 0x2997: 0x2998, + 0x2998: 0x2997, + 0x299B: 0x2221, + 0x29A0: 0x2222, + 0x29A3: 0x2220, + 0x29A4: 0x29A5, + 0x29A5: 0x29A4, + 0x29A8: 0x29A9, + 0x29A9: 0x29A8, + 0x29AA: 0x29AB, + 0x29AB: 0x29AA, + 0x29AC: 0x29AD, + 0x29AD: 0x29AC, + 0x29AE: 0x29AF, + 0x29AF: 0x29AE, + 0x29B8: 0x2298, + 0x29C0: 0x29C1, + 0x29C1: 0x29C0, + 0x29C4: 0x29C5, + 0x29C5: 0x29C4, + 0x29CF: 0x29D0, + 0x29D0: 0x29CF, + 0x29D1: 0x29D2, + 0x29D2: 0x29D1, + 0x29D4: 0x29D5, + 0x29D5: 0x29D4, + 0x29D8: 0x29D9, + 0x29D9: 0x29D8, + 0x29DA: 0x29DB, + 0x29DB: 0x29DA, + 0x29E8: 0x29E9, + 0x29E9: 0x29E8, + 0x29F5: 0x2215, + 0x29F8: 0x29F9, + 0x29F9: 0x29F8, + 0x29FC: 0x29FD, + 0x29FD: 0x29FC, + 0x2A2B: 0x2A2C, + 0x2A2C: 0x2A2B, + 0x2A2D: 0x2A2E, + 0x2A2E: 0x2A2D, + 0x2A34: 0x2A35, + 0x2A35: 0x2A34, + 0x2A3C: 0x2A3D, + 0x2A3D: 0x2A3C, + 0x2A64: 0x2A65, + 0x2A65: 0x2A64, + 0x2A79: 0x2A7A, + 0x2A7A: 0x2A79, + 0x2A7B: 0x2A7C, + 0x2A7C: 0x2A7B, + 0x2A7D: 0x2A7E, + 0x2A7E: 0x2A7D, + 0x2A7F: 0x2A80, + 0x2A80: 0x2A7F, + 0x2A81: 0x2A82, + 0x2A82: 0x2A81, + 0x2A83: 0x2A84, + 0x2A84: 0x2A83, + 0x2A85: 0x2A86, + 0x2A86: 0x2A85, + 0x2A87: 0x2A88, + 0x2A88: 0x2A87, + 0x2A89: 0x2A8A, + 0x2A8A: 0x2A89, + 0x2A8B: 0x2A8C, + 0x2A8C: 0x2A8B, + 0x2A8D: 0x2A8E, + 0x2A8E: 0x2A8D, + 0x2A8F: 0x2A90, + 0x2A90: 0x2A8F, + 0x2A91: 0x2A92, + 0x2A92: 0x2A91, + 0x2A93: 0x2A94, + 0x2A94: 0x2A93, + 0x2A95: 0x2A96, + 0x2A96: 0x2A95, + 0x2A97: 0x2A98, + 0x2A98: 0x2A97, + 0x2A99: 0x2A9A, + 0x2A9A: 0x2A99, + 0x2A9B: 0x2A9C, + 0x2A9C: 0x2A9B, + 0x2A9D: 0x2A9E, + 0x2A9E: 0x2A9D, + 0x2A9F: 0x2AA0, + 0x2AA0: 0x2A9F, + 0x2AA1: 0x2AA2, + 0x2AA2: 0x2AA1, + 0x2AA6: 0x2AA7, + 0x2AA7: 0x2AA6, + 0x2AA8: 0x2AA9, + 0x2AA9: 0x2AA8, + 0x2AAA: 0x2AAB, + 0x2AAB: 0x2AAA, + 0x2AAC: 0x2AAD, + 0x2AAD: 0x2AAC, + 0x2AAF: 0x2AB0, + 0x2AB0: 0x2AAF, + 0x2AB1: 0x2AB2, + 0x2AB2: 0x2AB1, + 0x2AB3: 0x2AB4, + 0x2AB4: 0x2AB3, + 0x2AB5: 0x2AB6, + 0x2AB6: 0x2AB5, + 0x2AB7: 0x2AB8, + 0x2AB8: 0x2AB7, + 0x2AB9: 0x2ABA, + 0x2ABA: 0x2AB9, + 0x2ABB: 0x2ABC, + 0x2ABC: 0x2ABB, + 0x2ABD: 0x2ABE, + 0x2ABE: 0x2ABD, + 0x2ABF: 0x2AC0, + 0x2AC0: 0x2ABF, + 0x2AC1: 0x2AC2, + 0x2AC2: 0x2AC1, + 0x2AC3: 0x2AC4, + 0x2AC4: 0x2AC3, + 0x2AC5: 0x2AC6, + 0x2AC6: 0x2AC5, + 0x2AC7: 0x2AC8, + 0x2AC8: 0x2AC7, + 0x2AC9: 0x2ACA, + 0x2ACA: 0x2AC9, + 0x2ACB: 0x2ACC, + 0x2ACC: 0x2ACB, + 0x2ACD: 0x2ACE, + 0x2ACE: 0x2ACD, + 0x2ACF: 0x2AD0, + 0x2AD0: 0x2ACF, + 0x2AD1: 0x2AD2, + 0x2AD2: 0x2AD1, + 0x2AD3: 0x2AD4, + 0x2AD4: 0x2AD3, + 0x2AD5: 0x2AD6, + 0x2AD6: 0x2AD5, + 0x2ADE: 0x22A6, + 0x2AE3: 0x22A9, + 0x2AE4: 0x22A8, + 0x2AE5: 0x22AB, + 0x2AEC: 0x2AED, + 0x2AED: 0x2AEC, + 0x2AEE: 0x2224, + 0x2AF7: 0x2AF8, + 0x2AF8: 0x2AF7, + 0x2AF9: 0x2AFA, + 0x2AFA: 0x2AF9, + 0x2BFE: 0x221F, + 0x2E02: 0x2E03, + 0x2E03: 0x2E02, + 0x2E04: 0x2E05, + 0x2E05: 0x2E04, + 0x2E09: 0x2E0A, + 0x2E0A: 0x2E09, + 0x2E0C: 0x2E0D, + 0x2E0D: 0x2E0C, + 0x2E1C: 0x2E1D, + 0x2E1D: 0x2E1C, + 0x2E20: 0x2E21, + 0x2E21: 0x2E20, + 0x2E22: 0x2E23, + 0x2E23: 0x2E22, + 0x2E24: 0x2E25, + 0x2E25: 0x2E24, + 0x2E26: 0x2E27, + 0x2E27: 0x2E26, + 0x2E28: 0x2E29, + 0x2E29: 0x2E28, + 0x2E55: 0x2E56, + 0x2E56: 0x2E55, + 0x2E57: 0x2E58, + 0x2E58: 0x2E57, + 0x2E59: 0x2E5A, + 0x2E5A: 0x2E59, + 0x2E5B: 0x2E5C, + 0x2E5C: 0x2E5B, + 0x3008: 0x3009, + 0x3009: 0x3008, + 0x300A: 0x300B, + 0x300B: 0x300A, + 0x300C: 0x300D, + 0x300D: 0x300C, + 0x300E: 0x300F, + 0x300F: 0x300E, + 0x3010: 0x3011, + 0x3011: 0x3010, + 0x3014: 0x3015, + 0x3015: 0x3014, + 0x3016: 0x3017, + 0x3017: 0x3016, + 0x3018: 0x3019, + 0x3019: 0x3018, + 0x301A: 0x301B, + 0x301B: 0x301A, + 0xFE59: 0xFE5A, + 0xFE5A: 0xFE59, + 0xFE5B: 0xFE5C, + 0xFE5C: 0xFE5B, + 0xFE5D: 0xFE5E, + 0xFE5E: 0xFE5D, + 0xFE64: 0xFE65, + 0xFE65: 0xFE64, + 0xFF08: 0xFF09, + 0xFF09: 0xFF08, + 0xFF1C: 0xFF1E, + 0xFF1E: 0xFF1C, + 0xFF3B: 0xFF3D, + 0xFF3D: 0xFF3B, + 0xFF5B: 0xFF5D, + 0xFF5D: 0xFF5B, + 0xFF5F: 0xFF60, + 0xFF60: 0xFF5F, + 0xFF62: 0xFF63, + 0xFF63: 0xFF62, +} diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicodedata/OTTags.py b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/OTTags.py new file mode 100644 index 0000000000000000000000000000000000000000..859a3bcdcf29bcdda827edad766ffeab2f0b636a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/OTTags.py @@ -0,0 +1,50 @@ +# Data updated to OpenType 1.8.2 as of January 2018. + +# Complete list of OpenType script tags at: +# https://www.microsoft.com/typography/otspec/scripttags.htm + +# Most of the script tags are the same as the ISO 15924 tag but lowercased, +# so we only have to handle the exceptional cases: +# - KATAKANA and HIRAGANA both map to 'kana'; +# - spaces at the end are preserved, unlike ISO 15924; +# - we map special script codes for Inherited, Common and Unknown to DFLT. + +DEFAULT_SCRIPT = "DFLT" + +SCRIPT_ALIASES = { + "jamo": "hang", +} + +SCRIPT_EXCEPTIONS = { + "Hira": "kana", + "Hrkt": "kana", + "Laoo": "lao ", + "Yiii": "yi ", + "Nkoo": "nko ", + "Vaii": "vai ", + "Zmth": "math", + "Zinh": DEFAULT_SCRIPT, + "Zyyy": DEFAULT_SCRIPT, + "Zzzz": DEFAULT_SCRIPT, +} + +SCRIPT_EXCEPTIONS_REVERSED = { + "math": "Zmth", +} + +NEW_SCRIPT_TAGS = { + "Beng": ("bng2",), + "Deva": ("dev2",), + "Gujr": ("gjr2",), + "Guru": ("gur2",), + "Knda": ("knd2",), + "Mlym": ("mlm2",), + "Orya": ("ory2",), + "Taml": ("tml2",), + "Telu": ("tel2",), + "Mymr": ("mym2",), +} + +NEW_SCRIPT_TAGS_REVERSED = { + value: key for key, values in NEW_SCRIPT_TAGS.items() for value in values +} diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicodedata/ScriptExtensions.py b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/ScriptExtensions.py new file mode 100644 index 0000000000000000000000000000000000000000..ec2dbac16fa45de8aec3f05a0f5dead90555b222 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/ScriptExtensions.py @@ -0,0 +1,832 @@ +# -*- coding: utf-8 -*- +# +# NOTE: This file was auto-generated with MetaTools/buildUCD.py. +# Source: https://unicode.org/Public/UNIDATA/ScriptExtensions.txt +# License: http://unicode.org/copyright.html#License +# +# ScriptExtensions-17.0.0.txt +# Date: 2025-08-01, 21:42:00 GMT +# © 2025 Unicode®, Inc. +# Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. in the U.S. and other countries. +# For terms of use and license, see https://www.unicode.org/terms_of_use.html +# +# Unicode Character Database +# For documentation, see https://www.unicode.org/reports/tr44/ +# +# The Script_Extensions property indicates which characters are commonly used +# with more than one script, but with a limited number of scripts. +# For each code point, there is one or more property values. Each such value is a Script property value. +# For more information, see: +# UAX #24, Unicode Script Property: https://www.unicode.org/reports/tr24/ +# Especially the sections: +# https://www.unicode.org/reports/tr24/#Assignment_Script_Values +# https://www.unicode.org/reports/tr24/#Assignment_ScriptX_Values +# +# Each Script_Extensions value in this file consists of a set +# of one or more abbreviated Script property values. The ordering of the +# values in that set is not material, but for stability in presentation +# it is given here as alphabetical. +# +# All code points not explicitly listed for Script_Extensions +# have as their value the corresponding Script property value. +# +# @missing: 0000..10FFFF; <script> + +RANGES = [ + 0x0000, # .. 0x00B6 ; None + 0x00B7, # .. 0x00B7 ; {'Avst', 'Cari', 'Copt', 'Dupl', 'Elba', 'Geor', 'Glag', 'Gong', 'Goth', 'Grek', 'Hani', 'Latn', 'Lydi', 'Mahj', 'Perm', 'Shaw'} + 0x00B8, # .. 0x02BB ; None + 0x02BC, # .. 0x02BC ; {'Beng', 'Cyrl', 'Deva', 'Latn', 'Lisu', 'Thai', 'Toto'} + 0x02BD, # .. 0x02C6 ; None + 0x02C7, # .. 0x02C7 ; {'Bopo', 'Latn'} + 0x02C8, # .. 0x02C8 ; None + 0x02C9, # .. 0x02CB ; {'Bopo', 'Latn'} + 0x02CC, # .. 0x02CC ; None + 0x02CD, # .. 0x02CD ; {'Latn', 'Lisu'} + 0x02CE, # .. 0x02D6 ; None + 0x02D7, # .. 0x02D7 ; {'Latn', 'Thai'} + 0x02D8, # .. 0x02D8 ; None + 0x02D9, # .. 0x02D9 ; {'Bopo', 'Latn'} + 0x02DA, # .. 0x02FF ; None + 0x0300, # .. 0x0300 ; {'Cher', 'Copt', 'Cyrl', 'Grek', 'Latn', 'Perm', 'Sunu', 'Tale'} + 0x0301, # .. 0x0301 ; {'Cher', 'Cyrl', 'Grek', 'Latn', 'Osge', 'Sunu', 'Tale', 'Todr'} + 0x0302, # .. 0x0302 ; {'Cher', 'Cyrl', 'Latn', 'Tfng'} + 0x0303, # .. 0x0303 ; {'Glag', 'Latn', 'Sunu', 'Syrc', 'Thai'} + 0x0304, # .. 0x0304 ; {'Aghb', 'Cher', 'Copt', 'Cyrl', 'Goth', 'Grek', 'Latn', 'Osge', 'Syrc', 'Tfng', 'Todr'} + 0x0305, # .. 0x0305 ; {'Copt', 'Elba', 'Glag', 'Goth', 'Kana', 'Latn'} + 0x0306, # .. 0x0306 ; {'Cyrl', 'Grek', 'Latn', 'Perm', 'Tfng'} + 0x0307, # .. 0x0307 ; {'Copt', 'Dupl', 'Hebr', 'Latn', 'Perm', 'Syrc', 'Tale', 'Tfng', 'Todr'} + 0x0308, # .. 0x0308 ; {'Armn', 'Cyrl', 'Dupl', 'Goth', 'Grek', 'Hebr', 'Latn', 'Perm', 'Syrc', 'Tale', 'Tfng'} + 0x0309, # .. 0x0309 ; {'Latn', 'Tfng'} + 0x030A, # .. 0x030A ; {'Dupl', 'Latn', 'Syrc'} + 0x030B, # .. 0x030B ; {'Cher', 'Cyrl', 'Latn', 'Osge'} + 0x030C, # .. 0x030C ; {'Cher', 'Latn', 'Tale'} + 0x030D, # .. 0x030D ; {'Latn', 'Sunu'} + 0x030E, # .. 0x030E ; {'Ethi', 'Latn'} + 0x030F, # .. 0x030F ; None + 0x0310, # .. 0x0310 ; {'Latn', 'Sunu'} + 0x0311, # .. 0x0311 ; {'Cyrl', 'Latn', 'Todr'} + 0x0312, # .. 0x0312 ; None + 0x0313, # .. 0x0313 ; {'Grek', 'Latn', 'Perm', 'Todr'} + 0x0314, # .. 0x0322 ; None + 0x0323, # .. 0x0323 ; {'Cher', 'Dupl', 'Kana', 'Latn', 'Syrc', 'Tfng'} + 0x0324, # .. 0x0324 ; {'Cher', 'Dupl', 'Latn', 'Syrc'} + 0x0325, # .. 0x0325 ; {'Latn', 'Syrc'} + 0x0326, # .. 0x032C ; None + 0x032D, # .. 0x032D ; {'Latn', 'Sunu', 'Syrc'} + 0x032E, # .. 0x032E ; {'Latn', 'Syrc'} + 0x032F, # .. 0x032F ; None + 0x0330, # .. 0x0330 ; {'Cher', 'Latn', 'Syrc'} + 0x0331, # .. 0x0331 ; {'Aghb', 'Cher', 'Goth', 'Latn', 'Sunu', 'Syrc', 'Thai'} + 0x0332, # .. 0x0341 ; None + 0x0342, # .. 0x0342 ; {'Grek'} + 0x0343, # .. 0x0344 ; None + 0x0345, # .. 0x0345 ; {'Grek'} + 0x0346, # .. 0x0357 ; None + 0x0358, # .. 0x0358 ; {'Latn', 'Osge'} + 0x0359, # .. 0x035D ; None + 0x035E, # .. 0x035E ; {'Aghb', 'Latn', 'Todr'} + 0x035F, # .. 0x0362 ; None + 0x0363, # .. 0x036F ; {'Latn'} + 0x0370, # .. 0x0373 ; None + 0x0374, # .. 0x0375 ; {'Copt', 'Grek'} + 0x0376, # .. 0x0482 ; None + 0x0483, # .. 0x0483 ; {'Cyrl', 'Perm'} + 0x0484, # .. 0x0484 ; {'Cyrl', 'Glag'} + 0x0485, # .. 0x0486 ; {'Cyrl', 'Latn'} + 0x0487, # .. 0x0487 ; {'Cyrl', 'Glag'} + 0x0488, # .. 0x0588 ; None + 0x0589, # .. 0x0589 ; {'Armn', 'Geor', 'Glag'} + 0x058A, # .. 0x060B ; None + 0x060C, # .. 0x060C ; {'Arab', 'Gara', 'Nkoo', 'Rohg', 'Syrc', 'Thaa', 'Yezi'} + 0x060D, # .. 0x061A ; None + 0x061B, # .. 0x061B ; {'Arab', 'Gara', 'Nkoo', 'Rohg', 'Syrc', 'Thaa', 'Yezi'} + 0x061C, # .. 0x061C ; {'Arab', 'Syrc', 'Thaa'} + 0x061D, # .. 0x061E ; None + 0x061F, # .. 0x061F ; {'Adlm', 'Arab', 'Gara', 'Nkoo', 'Rohg', 'Syrc', 'Thaa', 'Yezi'} + 0x0620, # .. 0x063F ; None + 0x0640, # .. 0x0640 ; {'Adlm', 'Arab', 'Mand', 'Mani', 'Ougr', 'Phlp', 'Rohg', 'Sogd', 'Syrc'} + 0x0641, # .. 0x064A ; None + 0x064B, # .. 0x0655 ; {'Arab', 'Syrc'} + 0x0656, # .. 0x065F ; None + 0x0660, # .. 0x0669 ; {'Arab', 'Thaa', 'Yezi'} + 0x066A, # .. 0x066F ; None + 0x0670, # .. 0x0670 ; {'Arab', 'Syrc'} + 0x0671, # .. 0x06D3 ; None + 0x06D4, # .. 0x06D4 ; {'Arab', 'Rohg'} + 0x06D5, # .. 0x0950 ; None + 0x0951, # .. 0x0951 ; {'Beng', 'Deva', 'Gran', 'Gujr', 'Guru', 'Knda', 'Latn', 'Mlym', 'Nand', 'Newa', 'Orya', 'Shrd', 'Taml', 'Telu', 'Tirh'} + 0x0952, # .. 0x0952 ; {'Beng', 'Deva', 'Gran', 'Gujr', 'Guru', 'Knda', 'Latn', 'Mlym', 'Newa', 'Orya', 'Taml', 'Telu', 'Tirh'} + 0x0953, # .. 0x0963 ; None + 0x0964, # .. 0x0964 ; {'Beng', 'Deva', 'Dogr', 'Gong', 'Gonm', 'Gran', 'Gujr', 'Guru', 'Knda', 'Mahj', 'Mlym', 'Nand', 'Onao', 'Orya', 'Sind', 'Sinh', 'Sylo', 'Takr', 'Taml', 'Telu', 'Tirh'} + 0x0965, # .. 0x0965 ; {'Beng', 'Deva', 'Dogr', 'Gong', 'Gonm', 'Gran', 'Gujr', 'Gukh', 'Guru', 'Knda', 'Limb', 'Mahj', 'Mlym', 'Nand', 'Onao', 'Orya', 'Sind', 'Sinh', 'Sylo', 'Takr', 'Taml', 'Telu', 'Tirh'} + 0x0966, # .. 0x096F ; {'Deva', 'Dogr', 'Kthi', 'Mahj'} + 0x0970, # .. 0x09E5 ; None + 0x09E6, # .. 0x09EF ; {'Beng', 'Cakm', 'Sylo'} + 0x09F0, # .. 0x0A65 ; None + 0x0A66, # .. 0x0A6F ; {'Guru', 'Mult'} + 0x0A70, # .. 0x0AE5 ; None + 0x0AE6, # .. 0x0AEF ; {'Gujr', 'Khoj'} + 0x0AF0, # .. 0x0BE5 ; None + 0x0BE6, # .. 0x0BF3 ; {'Gran', 'Taml'} + 0x0BF4, # .. 0x0CE5 ; None + 0x0CE6, # .. 0x0CEF ; {'Knda', 'Nand', 'Tutg'} + 0x0CF0, # .. 0x103F ; None + 0x1040, # .. 0x1049 ; {'Cakm', 'Mymr', 'Tale'} + 0x104A, # .. 0x10FA ; None + 0x10FB, # .. 0x10FB ; {'Geor', 'Glag', 'Latn'} + 0x10FC, # .. 0x16EA ; None + 0x16EB, # .. 0x16ED ; {'Runr'} + 0x16EE, # .. 0x1734 ; None + 0x1735, # .. 0x1736 ; {'Buhd', 'Hano', 'Tagb', 'Tglg'} + 0x1737, # .. 0x1801 ; None + 0x1802, # .. 0x1803 ; {'Mong', 'Phag'} + 0x1804, # .. 0x1804 ; None + 0x1805, # .. 0x1805 ; {'Mong', 'Phag'} + 0x1806, # .. 0x1CCF ; None + 0x1CD0, # .. 0x1CD0 ; {'Beng', 'Deva', 'Gran', 'Knda'} + 0x1CD1, # .. 0x1CD1 ; {'Deva'} + 0x1CD2, # .. 0x1CD2 ; {'Beng', 'Deva', 'Gran', 'Knda'} + 0x1CD3, # .. 0x1CD3 ; {'Deva', 'Gran', 'Knda'} + 0x1CD4, # .. 0x1CD4 ; {'Deva'} + 0x1CD5, # .. 0x1CD5 ; {'Beng', 'Deva', 'Newa', 'Telu', 'Tirh'} + 0x1CD6, # .. 0x1CD6 ; {'Beng', 'Deva', 'Telu'} + 0x1CD7, # .. 0x1CD7 ; {'Deva', 'Newa', 'Shrd'} + 0x1CD8, # .. 0x1CD8 ; {'Beng', 'Deva', 'Newa', 'Telu'} + 0x1CD9, # .. 0x1CD9 ; {'Deva', 'Shrd'} + 0x1CDA, # .. 0x1CDA ; {'Deva', 'Knda', 'Mlym', 'Orya', 'Taml', 'Telu'} + 0x1CDB, # .. 0x1CDB ; {'Deva'} + 0x1CDC, # .. 0x1CDD ; {'Deva', 'Shrd'} + 0x1CDE, # .. 0x1CDF ; {'Deva'} + 0x1CE0, # .. 0x1CE0 ; {'Deva', 'Shrd'} + 0x1CE1, # .. 0x1CE1 ; {'Beng', 'Deva'} + 0x1CE2, # .. 0x1CE2 ; {'Deva', 'Newa', 'Tirh'} + 0x1CE3, # .. 0x1CE8 ; {'Deva'} + 0x1CE9, # .. 0x1CE9 ; {'Deva', 'Nand', 'Newa'} + 0x1CEA, # .. 0x1CEA ; {'Beng', 'Deva', 'Shrd'} + 0x1CEB, # .. 0x1CEB ; {'Deva', 'Newa'} + 0x1CEC, # .. 0x1CEC ; {'Deva'} + 0x1CED, # .. 0x1CED ; {'Beng', 'Deva', 'Newa', 'Shrd'} + 0x1CEE, # .. 0x1CF1 ; {'Deva'} + 0x1CF2, # .. 0x1CF2 ; {'Beng', 'Deva', 'Gran', 'Knda', 'Mlym', 'Nand', 'Orya', 'Sinh', 'Telu', 'Tirh', 'Tutg'} + 0x1CF3, # .. 0x1CF3 ; {'Deva', 'Gran'} + 0x1CF4, # .. 0x1CF4 ; {'Deva', 'Gran', 'Knda', 'Tutg'} + 0x1CF5, # .. 0x1CF6 ; {'Beng', 'Deva'} + 0x1CF7, # .. 0x1CF7 ; {'Beng'} + 0x1CF8, # .. 0x1CF9 ; {'Deva', 'Gran'} + 0x1CFA, # .. 0x1CFA ; {'Nand'} + 0x1CFB, # .. 0x1DBF ; None + 0x1DC0, # .. 0x1DC1 ; {'Grek'} + 0x1DC2, # .. 0x1DF7 ; None + 0x1DF8, # .. 0x1DF8 ; {'Cyrl', 'Latn', 'Syrc'} + 0x1DF9, # .. 0x1DF9 ; None + 0x1DFA, # .. 0x1DFA ; {'Syrc'} + 0x1DFB, # .. 0x202E ; None + 0x202F, # .. 0x202F ; {'Latn', 'Mong', 'Phag'} + 0x2030, # .. 0x204E ; None + 0x204F, # .. 0x204F ; {'Adlm', 'Arab'} + 0x2050, # .. 0x2059 ; None + 0x205A, # .. 0x205A ; {'Cari', 'Geor', 'Glag', 'Hung', 'Lyci', 'Orkh'} + 0x205B, # .. 0x205C ; None + 0x205D, # .. 0x205D ; {'Cari', 'Grek', 'Hung', 'Mero'} + 0x205E, # .. 0x20EF ; None + 0x20F0, # .. 0x20F0 ; {'Deva', 'Gran', 'Latn'} + 0x20F1, # .. 0x2E16 ; None + 0x2E17, # .. 0x2E17 ; {'Copt', 'Latn'} + 0x2E18, # .. 0x2E2F ; None + 0x2E30, # .. 0x2E30 ; {'Avst', 'Orkh'} + 0x2E31, # .. 0x2E31 ; {'Avst', 'Cari', 'Geor', 'Hung', 'Kthi', 'Lydi', 'Samr'} + 0x2E32, # .. 0x2E3B ; None + 0x2E3C, # .. 0x2E3C ; {'Dupl'} + 0x2E3D, # .. 0x2E40 ; None + 0x2E41, # .. 0x2E41 ; {'Adlm', 'Arab', 'Hung'} + 0x2E42, # .. 0x2E42 ; None + 0x2E43, # .. 0x2E43 ; {'Cyrl', 'Glag'} + 0x2E44, # .. 0x2FEF ; None + 0x2FF0, # .. 0x2FFF ; {'Hani', 'Tang'} + 0x3000, # .. 0x3000 ; None + 0x3001, # .. 0x3001 ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana', 'Mong', 'Yiii'} + 0x3002, # .. 0x3002 ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana', 'Mong', 'Phag', 'Yiii'} + 0x3003, # .. 0x3003 ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana'} + 0x3004, # .. 0x3005 ; None + 0x3006, # .. 0x3006 ; {'Hani'} + 0x3007, # .. 0x3007 ; None + 0x3008, # .. 0x3009 ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana', 'Mong', 'Tibt', 'Yiii'} + 0x300A, # .. 0x300B ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana', 'Lisu', 'Mong', 'Tibt', 'Yiii'} + 0x300C, # .. 0x3011 ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana', 'Yiii'} + 0x3012, # .. 0x3012 ; None + 0x3013, # .. 0x3013 ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana'} + 0x3014, # .. 0x301B ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana', 'Yiii'} + 0x301C, # .. 0x301F ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana'} + 0x3020, # .. 0x3029 ; None + 0x302A, # .. 0x302D ; {'Bopo', 'Hani'} + 0x302E, # .. 0x302F ; None + 0x3030, # .. 0x3030 ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana'} + 0x3031, # .. 0x3035 ; {'Hira', 'Kana'} + 0x3036, # .. 0x3036 ; None + 0x3037, # .. 0x3037 ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana'} + 0x3038, # .. 0x303B ; None + 0x303C, # .. 0x303D ; {'Hani', 'Hira', 'Kana'} + 0x303E, # .. 0x303F ; {'Hani'} + 0x3040, # .. 0x3098 ; None + 0x3099, # .. 0x309C ; {'Hira', 'Kana'} + 0x309D, # .. 0x309F ; None + 0x30A0, # .. 0x30A0 ; {'Hira', 'Kana'} + 0x30A1, # .. 0x30FA ; None + 0x30FB, # .. 0x30FB ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana', 'Yiii'} + 0x30FC, # .. 0x30FC ; {'Hira', 'Kana'} + 0x30FD, # .. 0x318F ; None + 0x3190, # .. 0x319F ; {'Hani'} + 0x31A0, # .. 0x31BF ; None + 0x31C0, # .. 0x31E5 ; {'Hani'} + 0x31E6, # .. 0x31EE ; None + 0x31EF, # .. 0x31EF ; {'Hani', 'Tang'} + 0x31F0, # .. 0x321F ; None + 0x3220, # .. 0x3247 ; {'Hani'} + 0x3248, # .. 0x327F ; None + 0x3280, # .. 0x32B0 ; {'Hani'} + 0x32B1, # .. 0x32BF ; None + 0x32C0, # .. 0x32CB ; {'Hani'} + 0x32CC, # .. 0x32FE ; None + 0x32FF, # .. 0x32FF ; {'Hani'} + 0x3300, # .. 0x3357 ; None + 0x3358, # .. 0x3370 ; {'Hani'} + 0x3371, # .. 0x337A ; None + 0x337B, # .. 0x337F ; {'Hani'} + 0x3380, # .. 0x33DF ; None + 0x33E0, # .. 0x33FE ; {'Hani'} + 0x33FF, # .. 0xA66E ; None + 0xA66F, # .. 0xA66F ; {'Cyrl', 'Glag'} + 0xA670, # .. 0xA6FF ; None + 0xA700, # .. 0xA707 ; {'Hani', 'Latn'} + 0xA708, # .. 0xA82F ; None + 0xA830, # .. 0xA832 ; {'Deva', 'Dogr', 'Gujr', 'Guru', 'Khoj', 'Knda', 'Kthi', 'Mahj', 'Mlym', 'Modi', 'Nand', 'Shrd', 'Sind', 'Takr', 'Tirh', 'Tutg'} + 0xA833, # .. 0xA835 ; {'Deva', 'Dogr', 'Gujr', 'Guru', 'Khoj', 'Knda', 'Kthi', 'Mahj', 'Modi', 'Nand', 'Shrd', 'Sind', 'Takr', 'Tirh', 'Tutg'} + 0xA836, # .. 0xA837 ; {'Deva', 'Dogr', 'Gujr', 'Guru', 'Khoj', 'Kthi', 'Mahj', 'Modi', 'Sind', 'Takr', 'Tirh'} + 0xA838, # .. 0xA838 ; {'Deva', 'Dogr', 'Gujr', 'Guru', 'Khoj', 'Kthi', 'Mahj', 'Modi', 'Shrd', 'Sind', 'Takr', 'Tirh'} + 0xA839, # .. 0xA839 ; {'Deva', 'Dogr', 'Gujr', 'Guru', 'Khoj', 'Kthi', 'Mahj', 'Modi', 'Sind', 'Takr', 'Tirh'} + 0xA83A, # .. 0xA8F0 ; None + 0xA8F1, # .. 0xA8F1 ; {'Beng', 'Deva', 'Tutg'} + 0xA8F2, # .. 0xA8F2 ; None + 0xA8F3, # .. 0xA8F3 ; {'Deva', 'Taml'} + 0xA8F4, # .. 0xA92D ; None + 0xA92E, # .. 0xA92E ; {'Kali', 'Latn', 'Mymr'} + 0xA92F, # .. 0xA9CE ; None + 0xA9CF, # .. 0xA9CF ; {'Bugi', 'Java'} + 0xA9D0, # .. 0xFD3D ; None + 0xFD3E, # .. 0xFD3F ; {'Arab', 'Nkoo'} + 0xFD40, # .. 0xFDF1 ; None + 0xFDF2, # .. 0xFDF2 ; {'Arab', 'Thaa'} + 0xFDF3, # .. 0xFDFC ; None + 0xFDFD, # .. 0xFDFD ; {'Arab', 'Thaa'} + 0xFDFE, # .. 0xFE44 ; None + 0xFE45, # .. 0xFE46 ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana'} + 0xFE47, # .. 0xFF60 ; None + 0xFF61, # .. 0xFF65 ; {'Bopo', 'Hang', 'Hani', 'Hira', 'Kana', 'Yiii'} + 0xFF66, # .. 0xFF6F ; None + 0xFF70, # .. 0xFF70 ; {'Hira', 'Kana'} + 0xFF71, # .. 0xFF9D ; None + 0xFF9E, # .. 0xFF9F ; {'Hira', 'Kana'} + 0xFFA0, # .. 0x100FF ; None + 0x10100, # .. 0x10101 ; {'Cpmn', 'Cprt', 'Linb'} + 0x10102, # .. 0x10102 ; {'Cprt', 'Linb'} + 0x10103, # .. 0x10106 ; None + 0x10107, # .. 0x10133 ; {'Cprt', 'Lina', 'Linb'} + 0x10134, # .. 0x10136 ; None + 0x10137, # .. 0x1013F ; {'Cprt', 'Linb'} + 0x10140, # .. 0x102DF ; None + 0x102E0, # .. 0x102FB ; {'Arab', 'Copt'} + 0x102FC, # .. 0x10AF1 ; None + 0x10AF2, # .. 0x10AF2 ; {'Mani', 'Ougr'} + 0x10AF3, # .. 0x11300 ; None + 0x11301, # .. 0x11301 ; {'Gran', 'Taml'} + 0x11302, # .. 0x11302 ; None + 0x11303, # .. 0x11303 ; {'Gran', 'Taml'} + 0x11304, # .. 0x1133A ; None + 0x1133B, # .. 0x1133C ; {'Gran', 'Taml'} + 0x1133D, # .. 0x11FCF ; None + 0x11FD0, # .. 0x11FD1 ; {'Gran', 'Taml'} + 0x11FD2, # .. 0x11FD2 ; None + 0x11FD3, # .. 0x11FD3 ; {'Gran', 'Taml'} + 0x11FD4, # .. 0x1BC9F ; None + 0x1BCA0, # .. 0x1BCA3 ; {'Dupl'} + 0x1BCA4, # .. 0x1D35F ; None + 0x1D360, # .. 0x1D371 ; {'Hani'} + 0x1D372, # .. 0x1F24F ; None + 0x1F250, # .. 0x1F251 ; {'Hani'} + 0x1F252, # .. 0x10FFFF ; None +] + +VALUES = [ + None, # 0000..00B6 + { + "Avst", + "Cari", + "Copt", + "Dupl", + "Elba", + "Geor", + "Glag", + "Gong", + "Goth", + "Grek", + "Hani", + "Latn", + "Lydi", + "Mahj", + "Perm", + "Shaw", + }, # 00B7..00B7 + None, # 00B8..02BB + {"Beng", "Cyrl", "Deva", "Latn", "Lisu", "Thai", "Toto"}, # 02BC..02BC + None, # 02BD..02C6 + {"Bopo", "Latn"}, # 02C7..02C7 + None, # 02C8..02C8 + {"Bopo", "Latn"}, # 02C9..02CB + None, # 02CC..02CC + {"Latn", "Lisu"}, # 02CD..02CD + None, # 02CE..02D6 + {"Latn", "Thai"}, # 02D7..02D7 + None, # 02D8..02D8 + {"Bopo", "Latn"}, # 02D9..02D9 + None, # 02DA..02FF + {"Cher", "Copt", "Cyrl", "Grek", "Latn", "Perm", "Sunu", "Tale"}, # 0300..0300 + {"Cher", "Cyrl", "Grek", "Latn", "Osge", "Sunu", "Tale", "Todr"}, # 0301..0301 + {"Cher", "Cyrl", "Latn", "Tfng"}, # 0302..0302 + {"Glag", "Latn", "Sunu", "Syrc", "Thai"}, # 0303..0303 + { + "Aghb", + "Cher", + "Copt", + "Cyrl", + "Goth", + "Grek", + "Latn", + "Osge", + "Syrc", + "Tfng", + "Todr", + }, # 0304..0304 + {"Copt", "Elba", "Glag", "Goth", "Kana", "Latn"}, # 0305..0305 + {"Cyrl", "Grek", "Latn", "Perm", "Tfng"}, # 0306..0306 + { + "Copt", + "Dupl", + "Hebr", + "Latn", + "Perm", + "Syrc", + "Tale", + "Tfng", + "Todr", + }, # 0307..0307 + { + "Armn", + "Cyrl", + "Dupl", + "Goth", + "Grek", + "Hebr", + "Latn", + "Perm", + "Syrc", + "Tale", + "Tfng", + }, # 0308..0308 + {"Latn", "Tfng"}, # 0309..0309 + {"Dupl", "Latn", "Syrc"}, # 030A..030A + {"Cher", "Cyrl", "Latn", "Osge"}, # 030B..030B + {"Cher", "Latn", "Tale"}, # 030C..030C + {"Latn", "Sunu"}, # 030D..030D + {"Ethi", "Latn"}, # 030E..030E + None, # 030F..030F + {"Latn", "Sunu"}, # 0310..0310 + {"Cyrl", "Latn", "Todr"}, # 0311..0311 + None, # 0312..0312 + {"Grek", "Latn", "Perm", "Todr"}, # 0313..0313 + None, # 0314..0322 + {"Cher", "Dupl", "Kana", "Latn", "Syrc", "Tfng"}, # 0323..0323 + {"Cher", "Dupl", "Latn", "Syrc"}, # 0324..0324 + {"Latn", "Syrc"}, # 0325..0325 + None, # 0326..032C + {"Latn", "Sunu", "Syrc"}, # 032D..032D + {"Latn", "Syrc"}, # 032E..032E + None, # 032F..032F + {"Cher", "Latn", "Syrc"}, # 0330..0330 + {"Aghb", "Cher", "Goth", "Latn", "Sunu", "Syrc", "Thai"}, # 0331..0331 + None, # 0332..0341 + {"Grek"}, # 0342..0342 + None, # 0343..0344 + {"Grek"}, # 0345..0345 + None, # 0346..0357 + {"Latn", "Osge"}, # 0358..0358 + None, # 0359..035D + {"Aghb", "Latn", "Todr"}, # 035E..035E + None, # 035F..0362 + {"Latn"}, # 0363..036F + None, # 0370..0373 + {"Copt", "Grek"}, # 0374..0375 + None, # 0376..0482 + {"Cyrl", "Perm"}, # 0483..0483 + {"Cyrl", "Glag"}, # 0484..0484 + {"Cyrl", "Latn"}, # 0485..0486 + {"Cyrl", "Glag"}, # 0487..0487 + None, # 0488..0588 + {"Armn", "Geor", "Glag"}, # 0589..0589 + None, # 058A..060B + {"Arab", "Gara", "Nkoo", "Rohg", "Syrc", "Thaa", "Yezi"}, # 060C..060C + None, # 060D..061A + {"Arab", "Gara", "Nkoo", "Rohg", "Syrc", "Thaa", "Yezi"}, # 061B..061B + {"Arab", "Syrc", "Thaa"}, # 061C..061C + None, # 061D..061E + {"Adlm", "Arab", "Gara", "Nkoo", "Rohg", "Syrc", "Thaa", "Yezi"}, # 061F..061F + None, # 0620..063F + { + "Adlm", + "Arab", + "Mand", + "Mani", + "Ougr", + "Phlp", + "Rohg", + "Sogd", + "Syrc", + }, # 0640..0640 + None, # 0641..064A + {"Arab", "Syrc"}, # 064B..0655 + None, # 0656..065F + {"Arab", "Thaa", "Yezi"}, # 0660..0669 + None, # 066A..066F + {"Arab", "Syrc"}, # 0670..0670 + None, # 0671..06D3 + {"Arab", "Rohg"}, # 06D4..06D4 + None, # 06D5..0950 + { + "Beng", + "Deva", + "Gran", + "Gujr", + "Guru", + "Knda", + "Latn", + "Mlym", + "Nand", + "Newa", + "Orya", + "Shrd", + "Taml", + "Telu", + "Tirh", + }, # 0951..0951 + { + "Beng", + "Deva", + "Gran", + "Gujr", + "Guru", + "Knda", + "Latn", + "Mlym", + "Newa", + "Orya", + "Taml", + "Telu", + "Tirh", + }, # 0952..0952 + None, # 0953..0963 + { + "Beng", + "Deva", + "Dogr", + "Gong", + "Gonm", + "Gran", + "Gujr", + "Guru", + "Knda", + "Mahj", + "Mlym", + "Nand", + "Onao", + "Orya", + "Sind", + "Sinh", + "Sylo", + "Takr", + "Taml", + "Telu", + "Tirh", + }, # 0964..0964 + { + "Beng", + "Deva", + "Dogr", + "Gong", + "Gonm", + "Gran", + "Gujr", + "Gukh", + "Guru", + "Knda", + "Limb", + "Mahj", + "Mlym", + "Nand", + "Onao", + "Orya", + "Sind", + "Sinh", + "Sylo", + "Takr", + "Taml", + "Telu", + "Tirh", + }, # 0965..0965 + {"Deva", "Dogr", "Kthi", "Mahj"}, # 0966..096F + None, # 0970..09E5 + {"Beng", "Cakm", "Sylo"}, # 09E6..09EF + None, # 09F0..0A65 + {"Guru", "Mult"}, # 0A66..0A6F + None, # 0A70..0AE5 + {"Gujr", "Khoj"}, # 0AE6..0AEF + None, # 0AF0..0BE5 + {"Gran", "Taml"}, # 0BE6..0BF3 + None, # 0BF4..0CE5 + {"Knda", "Nand", "Tutg"}, # 0CE6..0CEF + None, # 0CF0..103F + {"Cakm", "Mymr", "Tale"}, # 1040..1049 + None, # 104A..10FA + {"Geor", "Glag", "Latn"}, # 10FB..10FB + None, # 10FC..16EA + {"Runr"}, # 16EB..16ED + None, # 16EE..1734 + {"Buhd", "Hano", "Tagb", "Tglg"}, # 1735..1736 + None, # 1737..1801 + {"Mong", "Phag"}, # 1802..1803 + None, # 1804..1804 + {"Mong", "Phag"}, # 1805..1805 + None, # 1806..1CCF + {"Beng", "Deva", "Gran", "Knda"}, # 1CD0..1CD0 + {"Deva"}, # 1CD1..1CD1 + {"Beng", "Deva", "Gran", "Knda"}, # 1CD2..1CD2 + {"Deva", "Gran", "Knda"}, # 1CD3..1CD3 + {"Deva"}, # 1CD4..1CD4 + {"Beng", "Deva", "Newa", "Telu", "Tirh"}, # 1CD5..1CD5 + {"Beng", "Deva", "Telu"}, # 1CD6..1CD6 + {"Deva", "Newa", "Shrd"}, # 1CD7..1CD7 + {"Beng", "Deva", "Newa", "Telu"}, # 1CD8..1CD8 + {"Deva", "Shrd"}, # 1CD9..1CD9 + {"Deva", "Knda", "Mlym", "Orya", "Taml", "Telu"}, # 1CDA..1CDA + {"Deva"}, # 1CDB..1CDB + {"Deva", "Shrd"}, # 1CDC..1CDD + {"Deva"}, # 1CDE..1CDF + {"Deva", "Shrd"}, # 1CE0..1CE0 + {"Beng", "Deva"}, # 1CE1..1CE1 + {"Deva", "Newa", "Tirh"}, # 1CE2..1CE2 + {"Deva"}, # 1CE3..1CE8 + {"Deva", "Nand", "Newa"}, # 1CE9..1CE9 + {"Beng", "Deva", "Shrd"}, # 1CEA..1CEA + {"Deva", "Newa"}, # 1CEB..1CEB + {"Deva"}, # 1CEC..1CEC + {"Beng", "Deva", "Newa", "Shrd"}, # 1CED..1CED + {"Deva"}, # 1CEE..1CF1 + { + "Beng", + "Deva", + "Gran", + "Knda", + "Mlym", + "Nand", + "Orya", + "Sinh", + "Telu", + "Tirh", + "Tutg", + }, # 1CF2..1CF2 + {"Deva", "Gran"}, # 1CF3..1CF3 + {"Deva", "Gran", "Knda", "Tutg"}, # 1CF4..1CF4 + {"Beng", "Deva"}, # 1CF5..1CF6 + {"Beng"}, # 1CF7..1CF7 + {"Deva", "Gran"}, # 1CF8..1CF9 + {"Nand"}, # 1CFA..1CFA + None, # 1CFB..1DBF + {"Grek"}, # 1DC0..1DC1 + None, # 1DC2..1DF7 + {"Cyrl", "Latn", "Syrc"}, # 1DF8..1DF8 + None, # 1DF9..1DF9 + {"Syrc"}, # 1DFA..1DFA + None, # 1DFB..202E + {"Latn", "Mong", "Phag"}, # 202F..202F + None, # 2030..204E + {"Adlm", "Arab"}, # 204F..204F + None, # 2050..2059 + {"Cari", "Geor", "Glag", "Hung", "Lyci", "Orkh"}, # 205A..205A + None, # 205B..205C + {"Cari", "Grek", "Hung", "Mero"}, # 205D..205D + None, # 205E..20EF + {"Deva", "Gran", "Latn"}, # 20F0..20F0 + None, # 20F1..2E16 + {"Copt", "Latn"}, # 2E17..2E17 + None, # 2E18..2E2F + {"Avst", "Orkh"}, # 2E30..2E30 + {"Avst", "Cari", "Geor", "Hung", "Kthi", "Lydi", "Samr"}, # 2E31..2E31 + None, # 2E32..2E3B + {"Dupl"}, # 2E3C..2E3C + None, # 2E3D..2E40 + {"Adlm", "Arab", "Hung"}, # 2E41..2E41 + None, # 2E42..2E42 + {"Cyrl", "Glag"}, # 2E43..2E43 + None, # 2E44..2FEF + {"Hani", "Tang"}, # 2FF0..2FFF + None, # 3000..3000 + {"Bopo", "Hang", "Hani", "Hira", "Kana", "Mong", "Yiii"}, # 3001..3001 + {"Bopo", "Hang", "Hani", "Hira", "Kana", "Mong", "Phag", "Yiii"}, # 3002..3002 + {"Bopo", "Hang", "Hani", "Hira", "Kana"}, # 3003..3003 + None, # 3004..3005 + {"Hani"}, # 3006..3006 + None, # 3007..3007 + {"Bopo", "Hang", "Hani", "Hira", "Kana", "Mong", "Tibt", "Yiii"}, # 3008..3009 + { + "Bopo", + "Hang", + "Hani", + "Hira", + "Kana", + "Lisu", + "Mong", + "Tibt", + "Yiii", + }, # 300A..300B + {"Bopo", "Hang", "Hani", "Hira", "Kana", "Yiii"}, # 300C..3011 + None, # 3012..3012 + {"Bopo", "Hang", "Hani", "Hira", "Kana"}, # 3013..3013 + {"Bopo", "Hang", "Hani", "Hira", "Kana", "Yiii"}, # 3014..301B + {"Bopo", "Hang", "Hani", "Hira", "Kana"}, # 301C..301F + None, # 3020..3029 + {"Bopo", "Hani"}, # 302A..302D + None, # 302E..302F + {"Bopo", "Hang", "Hani", "Hira", "Kana"}, # 3030..3030 + {"Hira", "Kana"}, # 3031..3035 + None, # 3036..3036 + {"Bopo", "Hang", "Hani", "Hira", "Kana"}, # 3037..3037 + None, # 3038..303B + {"Hani", "Hira", "Kana"}, # 303C..303D + {"Hani"}, # 303E..303F + None, # 3040..3098 + {"Hira", "Kana"}, # 3099..309C + None, # 309D..309F + {"Hira", "Kana"}, # 30A0..30A0 + None, # 30A1..30FA + {"Bopo", "Hang", "Hani", "Hira", "Kana", "Yiii"}, # 30FB..30FB + {"Hira", "Kana"}, # 30FC..30FC + None, # 30FD..318F + {"Hani"}, # 3190..319F + None, # 31A0..31BF + {"Hani"}, # 31C0..31E5 + None, # 31E6..31EE + {"Hani", "Tang"}, # 31EF..31EF + None, # 31F0..321F + {"Hani"}, # 3220..3247 + None, # 3248..327F + {"Hani"}, # 3280..32B0 + None, # 32B1..32BF + {"Hani"}, # 32C0..32CB + None, # 32CC..32FE + {"Hani"}, # 32FF..32FF + None, # 3300..3357 + {"Hani"}, # 3358..3370 + None, # 3371..337A + {"Hani"}, # 337B..337F + None, # 3380..33DF + {"Hani"}, # 33E0..33FE + None, # 33FF..A66E + {"Cyrl", "Glag"}, # A66F..A66F + None, # A670..A6FF + {"Hani", "Latn"}, # A700..A707 + None, # A708..A82F + { + "Deva", + "Dogr", + "Gujr", + "Guru", + "Khoj", + "Knda", + "Kthi", + "Mahj", + "Mlym", + "Modi", + "Nand", + "Shrd", + "Sind", + "Takr", + "Tirh", + "Tutg", + }, # A830..A832 + { + "Deva", + "Dogr", + "Gujr", + "Guru", + "Khoj", + "Knda", + "Kthi", + "Mahj", + "Modi", + "Nand", + "Shrd", + "Sind", + "Takr", + "Tirh", + "Tutg", + }, # A833..A835 + { + "Deva", + "Dogr", + "Gujr", + "Guru", + "Khoj", + "Kthi", + "Mahj", + "Modi", + "Sind", + "Takr", + "Tirh", + }, # A836..A837 + { + "Deva", + "Dogr", + "Gujr", + "Guru", + "Khoj", + "Kthi", + "Mahj", + "Modi", + "Shrd", + "Sind", + "Takr", + "Tirh", + }, # A838..A838 + { + "Deva", + "Dogr", + "Gujr", + "Guru", + "Khoj", + "Kthi", + "Mahj", + "Modi", + "Sind", + "Takr", + "Tirh", + }, # A839..A839 + None, # A83A..A8F0 + {"Beng", "Deva", "Tutg"}, # A8F1..A8F1 + None, # A8F2..A8F2 + {"Deva", "Taml"}, # A8F3..A8F3 + None, # A8F4..A92D + {"Kali", "Latn", "Mymr"}, # A92E..A92E + None, # A92F..A9CE + {"Bugi", "Java"}, # A9CF..A9CF + None, # A9D0..FD3D + {"Arab", "Nkoo"}, # FD3E..FD3F + None, # FD40..FDF1 + {"Arab", "Thaa"}, # FDF2..FDF2 + None, # FDF3..FDFC + {"Arab", "Thaa"}, # FDFD..FDFD + None, # FDFE..FE44 + {"Bopo", "Hang", "Hani", "Hira", "Kana"}, # FE45..FE46 + None, # FE47..FF60 + {"Bopo", "Hang", "Hani", "Hira", "Kana", "Yiii"}, # FF61..FF65 + None, # FF66..FF6F + {"Hira", "Kana"}, # FF70..FF70 + None, # FF71..FF9D + {"Hira", "Kana"}, # FF9E..FF9F + None, # FFA0..100FF + {"Cpmn", "Cprt", "Linb"}, # 10100..10101 + {"Cprt", "Linb"}, # 10102..10102 + None, # 10103..10106 + {"Cprt", "Lina", "Linb"}, # 10107..10133 + None, # 10134..10136 + {"Cprt", "Linb"}, # 10137..1013F + None, # 10140..102DF + {"Arab", "Copt"}, # 102E0..102FB + None, # 102FC..10AF1 + {"Mani", "Ougr"}, # 10AF2..10AF2 + None, # 10AF3..11300 + {"Gran", "Taml"}, # 11301..11301 + None, # 11302..11302 + {"Gran", "Taml"}, # 11303..11303 + None, # 11304..1133A + {"Gran", "Taml"}, # 1133B..1133C + None, # 1133D..11FCF + {"Gran", "Taml"}, # 11FD0..11FD1 + None, # 11FD2..11FD2 + {"Gran", "Taml"}, # 11FD3..11FD3 + None, # 11FD4..1BC9F + {"Dupl"}, # 1BCA0..1BCA3 + None, # 1BCA4..1D35F + {"Hani"}, # 1D360..1D371 + None, # 1D372..1F24F + {"Hani"}, # 1F250..1F251 + None, # 1F252..10FFFF +] diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicodedata/Scripts.py b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/Scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..dac10667b423a6a6681e0a67234de37db00611b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/Scripts.py @@ -0,0 +1,3639 @@ +# -*- coding: utf-8 -*- +# +# NOTE: This file was auto-generated with MetaTools/buildUCD.py. +# Source: https://unicode.org/Public/UNIDATA/Scripts.txt +# License: http://unicode.org/copyright.html#License +# +# Scripts-17.0.0.txt +# Date: 2025-07-24, 13:28:55 GMT +# © 2025 Unicode®, Inc. +# Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. in the U.S. and other countries. +# For terms of use and license, see https://www.unicode.org/terms_of_use.html +# +# Unicode Character Database +# For documentation, see https://www.unicode.org/reports/tr44/ +# For more information, see: +# UAX #24, Unicode Script Property: https://www.unicode.org/reports/tr24/ +# Especially the sections: +# https://www.unicode.org/reports/tr24/#Assignment_Script_Values +# https://www.unicode.org/reports/tr24/#Assignment_ScriptX_Values +# + +RANGES = [ + 0x0000, # .. 0x0040 ; Common + 0x0041, # .. 0x005A ; Latin + 0x005B, # .. 0x0060 ; Common + 0x0061, # .. 0x007A ; Latin + 0x007B, # .. 0x00A9 ; Common + 0x00AA, # .. 0x00AA ; Latin + 0x00AB, # .. 0x00B9 ; Common + 0x00BA, # .. 0x00BA ; Latin + 0x00BB, # .. 0x00BF ; Common + 0x00C0, # .. 0x00D6 ; Latin + 0x00D7, # .. 0x00D7 ; Common + 0x00D8, # .. 0x00F6 ; Latin + 0x00F7, # .. 0x00F7 ; Common + 0x00F8, # .. 0x02B8 ; Latin + 0x02B9, # .. 0x02DF ; Common + 0x02E0, # .. 0x02E4 ; Latin + 0x02E5, # .. 0x02E9 ; Common + 0x02EA, # .. 0x02EB ; Bopomofo + 0x02EC, # .. 0x02FF ; Common + 0x0300, # .. 0x036F ; Inherited + 0x0370, # .. 0x0373 ; Greek + 0x0374, # .. 0x0374 ; Common + 0x0375, # .. 0x0377 ; Greek + 0x0378, # .. 0x0379 ; Unknown + 0x037A, # .. 0x037D ; Greek + 0x037E, # .. 0x037E ; Common + 0x037F, # .. 0x037F ; Greek + 0x0380, # .. 0x0383 ; Unknown + 0x0384, # .. 0x0384 ; Greek + 0x0385, # .. 0x0385 ; Common + 0x0386, # .. 0x0386 ; Greek + 0x0387, # .. 0x0387 ; Common + 0x0388, # .. 0x038A ; Greek + 0x038B, # .. 0x038B ; Unknown + 0x038C, # .. 0x038C ; Greek + 0x038D, # .. 0x038D ; Unknown + 0x038E, # .. 0x03A1 ; Greek + 0x03A2, # .. 0x03A2 ; Unknown + 0x03A3, # .. 0x03E1 ; Greek + 0x03E2, # .. 0x03EF ; Coptic + 0x03F0, # .. 0x03FF ; Greek + 0x0400, # .. 0x0484 ; Cyrillic + 0x0485, # .. 0x0486 ; Inherited + 0x0487, # .. 0x052F ; Cyrillic + 0x0530, # .. 0x0530 ; Unknown + 0x0531, # .. 0x0556 ; Armenian + 0x0557, # .. 0x0558 ; Unknown + 0x0559, # .. 0x058A ; Armenian + 0x058B, # .. 0x058C ; Unknown + 0x058D, # .. 0x058F ; Armenian + 0x0590, # .. 0x0590 ; Unknown + 0x0591, # .. 0x05C7 ; Hebrew + 0x05C8, # .. 0x05CF ; Unknown + 0x05D0, # .. 0x05EA ; Hebrew + 0x05EB, # .. 0x05EE ; Unknown + 0x05EF, # .. 0x05F4 ; Hebrew + 0x05F5, # .. 0x05FF ; Unknown + 0x0600, # .. 0x0604 ; Arabic + 0x0605, # .. 0x0605 ; Common + 0x0606, # .. 0x060B ; Arabic + 0x060C, # .. 0x060C ; Common + 0x060D, # .. 0x061A ; Arabic + 0x061B, # .. 0x061B ; Common + 0x061C, # .. 0x061E ; Arabic + 0x061F, # .. 0x061F ; Common + 0x0620, # .. 0x063F ; Arabic + 0x0640, # .. 0x0640 ; Common + 0x0641, # .. 0x064A ; Arabic + 0x064B, # .. 0x0655 ; Inherited + 0x0656, # .. 0x066F ; Arabic + 0x0670, # .. 0x0670 ; Inherited + 0x0671, # .. 0x06DC ; Arabic + 0x06DD, # .. 0x06DD ; Common + 0x06DE, # .. 0x06FF ; Arabic + 0x0700, # .. 0x070D ; Syriac + 0x070E, # .. 0x070E ; Unknown + 0x070F, # .. 0x074A ; Syriac + 0x074B, # .. 0x074C ; Unknown + 0x074D, # .. 0x074F ; Syriac + 0x0750, # .. 0x077F ; Arabic + 0x0780, # .. 0x07B1 ; Thaana + 0x07B2, # .. 0x07BF ; Unknown + 0x07C0, # .. 0x07FA ; Nko + 0x07FB, # .. 0x07FC ; Unknown + 0x07FD, # .. 0x07FF ; Nko + 0x0800, # .. 0x082D ; Samaritan + 0x082E, # .. 0x082F ; Unknown + 0x0830, # .. 0x083E ; Samaritan + 0x083F, # .. 0x083F ; Unknown + 0x0840, # .. 0x085B ; Mandaic + 0x085C, # .. 0x085D ; Unknown + 0x085E, # .. 0x085E ; Mandaic + 0x085F, # .. 0x085F ; Unknown + 0x0860, # .. 0x086A ; Syriac + 0x086B, # .. 0x086F ; Unknown + 0x0870, # .. 0x0891 ; Arabic + 0x0892, # .. 0x0896 ; Unknown + 0x0897, # .. 0x08E1 ; Arabic + 0x08E2, # .. 0x08E2 ; Common + 0x08E3, # .. 0x08FF ; Arabic + 0x0900, # .. 0x0950 ; Devanagari + 0x0951, # .. 0x0954 ; Inherited + 0x0955, # .. 0x0963 ; Devanagari + 0x0964, # .. 0x0965 ; Common + 0x0966, # .. 0x097F ; Devanagari + 0x0980, # .. 0x0983 ; Bengali + 0x0984, # .. 0x0984 ; Unknown + 0x0985, # .. 0x098C ; Bengali + 0x098D, # .. 0x098E ; Unknown + 0x098F, # .. 0x0990 ; Bengali + 0x0991, # .. 0x0992 ; Unknown + 0x0993, # .. 0x09A8 ; Bengali + 0x09A9, # .. 0x09A9 ; Unknown + 0x09AA, # .. 0x09B0 ; Bengali + 0x09B1, # .. 0x09B1 ; Unknown + 0x09B2, # .. 0x09B2 ; Bengali + 0x09B3, # .. 0x09B5 ; Unknown + 0x09B6, # .. 0x09B9 ; Bengali + 0x09BA, # .. 0x09BB ; Unknown + 0x09BC, # .. 0x09C4 ; Bengali + 0x09C5, # .. 0x09C6 ; Unknown + 0x09C7, # .. 0x09C8 ; Bengali + 0x09C9, # .. 0x09CA ; Unknown + 0x09CB, # .. 0x09CE ; Bengali + 0x09CF, # .. 0x09D6 ; Unknown + 0x09D7, # .. 0x09D7 ; Bengali + 0x09D8, # .. 0x09DB ; Unknown + 0x09DC, # .. 0x09DD ; Bengali + 0x09DE, # .. 0x09DE ; Unknown + 0x09DF, # .. 0x09E3 ; Bengali + 0x09E4, # .. 0x09E5 ; Unknown + 0x09E6, # .. 0x09FE ; Bengali + 0x09FF, # .. 0x0A00 ; Unknown + 0x0A01, # .. 0x0A03 ; Gurmukhi + 0x0A04, # .. 0x0A04 ; Unknown + 0x0A05, # .. 0x0A0A ; Gurmukhi + 0x0A0B, # .. 0x0A0E ; Unknown + 0x0A0F, # .. 0x0A10 ; Gurmukhi + 0x0A11, # .. 0x0A12 ; Unknown + 0x0A13, # .. 0x0A28 ; Gurmukhi + 0x0A29, # .. 0x0A29 ; Unknown + 0x0A2A, # .. 0x0A30 ; Gurmukhi + 0x0A31, # .. 0x0A31 ; Unknown + 0x0A32, # .. 0x0A33 ; Gurmukhi + 0x0A34, # .. 0x0A34 ; Unknown + 0x0A35, # .. 0x0A36 ; Gurmukhi + 0x0A37, # .. 0x0A37 ; Unknown + 0x0A38, # .. 0x0A39 ; Gurmukhi + 0x0A3A, # .. 0x0A3B ; Unknown + 0x0A3C, # .. 0x0A3C ; Gurmukhi + 0x0A3D, # .. 0x0A3D ; Unknown + 0x0A3E, # .. 0x0A42 ; Gurmukhi + 0x0A43, # .. 0x0A46 ; Unknown + 0x0A47, # .. 0x0A48 ; Gurmukhi + 0x0A49, # .. 0x0A4A ; Unknown + 0x0A4B, # .. 0x0A4D ; Gurmukhi + 0x0A4E, # .. 0x0A50 ; Unknown + 0x0A51, # .. 0x0A51 ; Gurmukhi + 0x0A52, # .. 0x0A58 ; Unknown + 0x0A59, # .. 0x0A5C ; Gurmukhi + 0x0A5D, # .. 0x0A5D ; Unknown + 0x0A5E, # .. 0x0A5E ; Gurmukhi + 0x0A5F, # .. 0x0A65 ; Unknown + 0x0A66, # .. 0x0A76 ; Gurmukhi + 0x0A77, # .. 0x0A80 ; Unknown + 0x0A81, # .. 0x0A83 ; Gujarati + 0x0A84, # .. 0x0A84 ; Unknown + 0x0A85, # .. 0x0A8D ; Gujarati + 0x0A8E, # .. 0x0A8E ; Unknown + 0x0A8F, # .. 0x0A91 ; Gujarati + 0x0A92, # .. 0x0A92 ; Unknown + 0x0A93, # .. 0x0AA8 ; Gujarati + 0x0AA9, # .. 0x0AA9 ; Unknown + 0x0AAA, # .. 0x0AB0 ; Gujarati + 0x0AB1, # .. 0x0AB1 ; Unknown + 0x0AB2, # .. 0x0AB3 ; Gujarati + 0x0AB4, # .. 0x0AB4 ; Unknown + 0x0AB5, # .. 0x0AB9 ; Gujarati + 0x0ABA, # .. 0x0ABB ; Unknown + 0x0ABC, # .. 0x0AC5 ; Gujarati + 0x0AC6, # .. 0x0AC6 ; Unknown + 0x0AC7, # .. 0x0AC9 ; Gujarati + 0x0ACA, # .. 0x0ACA ; Unknown + 0x0ACB, # .. 0x0ACD ; Gujarati + 0x0ACE, # .. 0x0ACF ; Unknown + 0x0AD0, # .. 0x0AD0 ; Gujarati + 0x0AD1, # .. 0x0ADF ; Unknown + 0x0AE0, # .. 0x0AE3 ; Gujarati + 0x0AE4, # .. 0x0AE5 ; Unknown + 0x0AE6, # .. 0x0AF1 ; Gujarati + 0x0AF2, # .. 0x0AF8 ; Unknown + 0x0AF9, # .. 0x0AFF ; Gujarati + 0x0B00, # .. 0x0B00 ; Unknown + 0x0B01, # .. 0x0B03 ; Oriya + 0x0B04, # .. 0x0B04 ; Unknown + 0x0B05, # .. 0x0B0C ; Oriya + 0x0B0D, # .. 0x0B0E ; Unknown + 0x0B0F, # .. 0x0B10 ; Oriya + 0x0B11, # .. 0x0B12 ; Unknown + 0x0B13, # .. 0x0B28 ; Oriya + 0x0B29, # .. 0x0B29 ; Unknown + 0x0B2A, # .. 0x0B30 ; Oriya + 0x0B31, # .. 0x0B31 ; Unknown + 0x0B32, # .. 0x0B33 ; Oriya + 0x0B34, # .. 0x0B34 ; Unknown + 0x0B35, # .. 0x0B39 ; Oriya + 0x0B3A, # .. 0x0B3B ; Unknown + 0x0B3C, # .. 0x0B44 ; Oriya + 0x0B45, # .. 0x0B46 ; Unknown + 0x0B47, # .. 0x0B48 ; Oriya + 0x0B49, # .. 0x0B4A ; Unknown + 0x0B4B, # .. 0x0B4D ; Oriya + 0x0B4E, # .. 0x0B54 ; Unknown + 0x0B55, # .. 0x0B57 ; Oriya + 0x0B58, # .. 0x0B5B ; Unknown + 0x0B5C, # .. 0x0B5D ; Oriya + 0x0B5E, # .. 0x0B5E ; Unknown + 0x0B5F, # .. 0x0B63 ; Oriya + 0x0B64, # .. 0x0B65 ; Unknown + 0x0B66, # .. 0x0B77 ; Oriya + 0x0B78, # .. 0x0B81 ; Unknown + 0x0B82, # .. 0x0B83 ; Tamil + 0x0B84, # .. 0x0B84 ; Unknown + 0x0B85, # .. 0x0B8A ; Tamil + 0x0B8B, # .. 0x0B8D ; Unknown + 0x0B8E, # .. 0x0B90 ; Tamil + 0x0B91, # .. 0x0B91 ; Unknown + 0x0B92, # .. 0x0B95 ; Tamil + 0x0B96, # .. 0x0B98 ; Unknown + 0x0B99, # .. 0x0B9A ; Tamil + 0x0B9B, # .. 0x0B9B ; Unknown + 0x0B9C, # .. 0x0B9C ; Tamil + 0x0B9D, # .. 0x0B9D ; Unknown + 0x0B9E, # .. 0x0B9F ; Tamil + 0x0BA0, # .. 0x0BA2 ; Unknown + 0x0BA3, # .. 0x0BA4 ; Tamil + 0x0BA5, # .. 0x0BA7 ; Unknown + 0x0BA8, # .. 0x0BAA ; Tamil + 0x0BAB, # .. 0x0BAD ; Unknown + 0x0BAE, # .. 0x0BB9 ; Tamil + 0x0BBA, # .. 0x0BBD ; Unknown + 0x0BBE, # .. 0x0BC2 ; Tamil + 0x0BC3, # .. 0x0BC5 ; Unknown + 0x0BC6, # .. 0x0BC8 ; Tamil + 0x0BC9, # .. 0x0BC9 ; Unknown + 0x0BCA, # .. 0x0BCD ; Tamil + 0x0BCE, # .. 0x0BCF ; Unknown + 0x0BD0, # .. 0x0BD0 ; Tamil + 0x0BD1, # .. 0x0BD6 ; Unknown + 0x0BD7, # .. 0x0BD7 ; Tamil + 0x0BD8, # .. 0x0BE5 ; Unknown + 0x0BE6, # .. 0x0BFA ; Tamil + 0x0BFB, # .. 0x0BFF ; Unknown + 0x0C00, # .. 0x0C0C ; Telugu + 0x0C0D, # .. 0x0C0D ; Unknown + 0x0C0E, # .. 0x0C10 ; Telugu + 0x0C11, # .. 0x0C11 ; Unknown + 0x0C12, # .. 0x0C28 ; Telugu + 0x0C29, # .. 0x0C29 ; Unknown + 0x0C2A, # .. 0x0C39 ; Telugu + 0x0C3A, # .. 0x0C3B ; Unknown + 0x0C3C, # .. 0x0C44 ; Telugu + 0x0C45, # .. 0x0C45 ; Unknown + 0x0C46, # .. 0x0C48 ; Telugu + 0x0C49, # .. 0x0C49 ; Unknown + 0x0C4A, # .. 0x0C4D ; Telugu + 0x0C4E, # .. 0x0C54 ; Unknown + 0x0C55, # .. 0x0C56 ; Telugu + 0x0C57, # .. 0x0C57 ; Unknown + 0x0C58, # .. 0x0C5A ; Telugu + 0x0C5B, # .. 0x0C5B ; Unknown + 0x0C5C, # .. 0x0C5D ; Telugu + 0x0C5E, # .. 0x0C5F ; Unknown + 0x0C60, # .. 0x0C63 ; Telugu + 0x0C64, # .. 0x0C65 ; Unknown + 0x0C66, # .. 0x0C6F ; Telugu + 0x0C70, # .. 0x0C76 ; Unknown + 0x0C77, # .. 0x0C7F ; Telugu + 0x0C80, # .. 0x0C8C ; Kannada + 0x0C8D, # .. 0x0C8D ; Unknown + 0x0C8E, # .. 0x0C90 ; Kannada + 0x0C91, # .. 0x0C91 ; Unknown + 0x0C92, # .. 0x0CA8 ; Kannada + 0x0CA9, # .. 0x0CA9 ; Unknown + 0x0CAA, # .. 0x0CB3 ; Kannada + 0x0CB4, # .. 0x0CB4 ; Unknown + 0x0CB5, # .. 0x0CB9 ; Kannada + 0x0CBA, # .. 0x0CBB ; Unknown + 0x0CBC, # .. 0x0CC4 ; Kannada + 0x0CC5, # .. 0x0CC5 ; Unknown + 0x0CC6, # .. 0x0CC8 ; Kannada + 0x0CC9, # .. 0x0CC9 ; Unknown + 0x0CCA, # .. 0x0CCD ; Kannada + 0x0CCE, # .. 0x0CD4 ; Unknown + 0x0CD5, # .. 0x0CD6 ; Kannada + 0x0CD7, # .. 0x0CDB ; Unknown + 0x0CDC, # .. 0x0CDE ; Kannada + 0x0CDF, # .. 0x0CDF ; Unknown + 0x0CE0, # .. 0x0CE3 ; Kannada + 0x0CE4, # .. 0x0CE5 ; Unknown + 0x0CE6, # .. 0x0CEF ; Kannada + 0x0CF0, # .. 0x0CF0 ; Unknown + 0x0CF1, # .. 0x0CF3 ; Kannada + 0x0CF4, # .. 0x0CFF ; Unknown + 0x0D00, # .. 0x0D0C ; Malayalam + 0x0D0D, # .. 0x0D0D ; Unknown + 0x0D0E, # .. 0x0D10 ; Malayalam + 0x0D11, # .. 0x0D11 ; Unknown + 0x0D12, # .. 0x0D44 ; Malayalam + 0x0D45, # .. 0x0D45 ; Unknown + 0x0D46, # .. 0x0D48 ; Malayalam + 0x0D49, # .. 0x0D49 ; Unknown + 0x0D4A, # .. 0x0D4F ; Malayalam + 0x0D50, # .. 0x0D53 ; Unknown + 0x0D54, # .. 0x0D63 ; Malayalam + 0x0D64, # .. 0x0D65 ; Unknown + 0x0D66, # .. 0x0D7F ; Malayalam + 0x0D80, # .. 0x0D80 ; Unknown + 0x0D81, # .. 0x0D83 ; Sinhala + 0x0D84, # .. 0x0D84 ; Unknown + 0x0D85, # .. 0x0D96 ; Sinhala + 0x0D97, # .. 0x0D99 ; Unknown + 0x0D9A, # .. 0x0DB1 ; Sinhala + 0x0DB2, # .. 0x0DB2 ; Unknown + 0x0DB3, # .. 0x0DBB ; Sinhala + 0x0DBC, # .. 0x0DBC ; Unknown + 0x0DBD, # .. 0x0DBD ; Sinhala + 0x0DBE, # .. 0x0DBF ; Unknown + 0x0DC0, # .. 0x0DC6 ; Sinhala + 0x0DC7, # .. 0x0DC9 ; Unknown + 0x0DCA, # .. 0x0DCA ; Sinhala + 0x0DCB, # .. 0x0DCE ; Unknown + 0x0DCF, # .. 0x0DD4 ; Sinhala + 0x0DD5, # .. 0x0DD5 ; Unknown + 0x0DD6, # .. 0x0DD6 ; Sinhala + 0x0DD7, # .. 0x0DD7 ; Unknown + 0x0DD8, # .. 0x0DDF ; Sinhala + 0x0DE0, # .. 0x0DE5 ; Unknown + 0x0DE6, # .. 0x0DEF ; Sinhala + 0x0DF0, # .. 0x0DF1 ; Unknown + 0x0DF2, # .. 0x0DF4 ; Sinhala + 0x0DF5, # .. 0x0E00 ; Unknown + 0x0E01, # .. 0x0E3A ; Thai + 0x0E3B, # .. 0x0E3E ; Unknown + 0x0E3F, # .. 0x0E3F ; Common + 0x0E40, # .. 0x0E5B ; Thai + 0x0E5C, # .. 0x0E80 ; Unknown + 0x0E81, # .. 0x0E82 ; Lao + 0x0E83, # .. 0x0E83 ; Unknown + 0x0E84, # .. 0x0E84 ; Lao + 0x0E85, # .. 0x0E85 ; Unknown + 0x0E86, # .. 0x0E8A ; Lao + 0x0E8B, # .. 0x0E8B ; Unknown + 0x0E8C, # .. 0x0EA3 ; Lao + 0x0EA4, # .. 0x0EA4 ; Unknown + 0x0EA5, # .. 0x0EA5 ; Lao + 0x0EA6, # .. 0x0EA6 ; Unknown + 0x0EA7, # .. 0x0EBD ; Lao + 0x0EBE, # .. 0x0EBF ; Unknown + 0x0EC0, # .. 0x0EC4 ; Lao + 0x0EC5, # .. 0x0EC5 ; Unknown + 0x0EC6, # .. 0x0EC6 ; Lao + 0x0EC7, # .. 0x0EC7 ; Unknown + 0x0EC8, # .. 0x0ECE ; Lao + 0x0ECF, # .. 0x0ECF ; Unknown + 0x0ED0, # .. 0x0ED9 ; Lao + 0x0EDA, # .. 0x0EDB ; Unknown + 0x0EDC, # .. 0x0EDF ; Lao + 0x0EE0, # .. 0x0EFF ; Unknown + 0x0F00, # .. 0x0F47 ; Tibetan + 0x0F48, # .. 0x0F48 ; Unknown + 0x0F49, # .. 0x0F6C ; Tibetan + 0x0F6D, # .. 0x0F70 ; Unknown + 0x0F71, # .. 0x0F97 ; Tibetan + 0x0F98, # .. 0x0F98 ; Unknown + 0x0F99, # .. 0x0FBC ; Tibetan + 0x0FBD, # .. 0x0FBD ; Unknown + 0x0FBE, # .. 0x0FCC ; Tibetan + 0x0FCD, # .. 0x0FCD ; Unknown + 0x0FCE, # .. 0x0FD4 ; Tibetan + 0x0FD5, # .. 0x0FD8 ; Common + 0x0FD9, # .. 0x0FDA ; Tibetan + 0x0FDB, # .. 0x0FFF ; Unknown + 0x1000, # .. 0x109F ; Myanmar + 0x10A0, # .. 0x10C5 ; Georgian + 0x10C6, # .. 0x10C6 ; Unknown + 0x10C7, # .. 0x10C7 ; Georgian + 0x10C8, # .. 0x10CC ; Unknown + 0x10CD, # .. 0x10CD ; Georgian + 0x10CE, # .. 0x10CF ; Unknown + 0x10D0, # .. 0x10FA ; Georgian + 0x10FB, # .. 0x10FB ; Common + 0x10FC, # .. 0x10FF ; Georgian + 0x1100, # .. 0x11FF ; Hangul + 0x1200, # .. 0x1248 ; Ethiopic + 0x1249, # .. 0x1249 ; Unknown + 0x124A, # .. 0x124D ; Ethiopic + 0x124E, # .. 0x124F ; Unknown + 0x1250, # .. 0x1256 ; Ethiopic + 0x1257, # .. 0x1257 ; Unknown + 0x1258, # .. 0x1258 ; Ethiopic + 0x1259, # .. 0x1259 ; Unknown + 0x125A, # .. 0x125D ; Ethiopic + 0x125E, # .. 0x125F ; Unknown + 0x1260, # .. 0x1288 ; Ethiopic + 0x1289, # .. 0x1289 ; Unknown + 0x128A, # .. 0x128D ; Ethiopic + 0x128E, # .. 0x128F ; Unknown + 0x1290, # .. 0x12B0 ; Ethiopic + 0x12B1, # .. 0x12B1 ; Unknown + 0x12B2, # .. 0x12B5 ; Ethiopic + 0x12B6, # .. 0x12B7 ; Unknown + 0x12B8, # .. 0x12BE ; Ethiopic + 0x12BF, # .. 0x12BF ; Unknown + 0x12C0, # .. 0x12C0 ; Ethiopic + 0x12C1, # .. 0x12C1 ; Unknown + 0x12C2, # .. 0x12C5 ; Ethiopic + 0x12C6, # .. 0x12C7 ; Unknown + 0x12C8, # .. 0x12D6 ; Ethiopic + 0x12D7, # .. 0x12D7 ; Unknown + 0x12D8, # .. 0x1310 ; Ethiopic + 0x1311, # .. 0x1311 ; Unknown + 0x1312, # .. 0x1315 ; Ethiopic + 0x1316, # .. 0x1317 ; Unknown + 0x1318, # .. 0x135A ; Ethiopic + 0x135B, # .. 0x135C ; Unknown + 0x135D, # .. 0x137C ; Ethiopic + 0x137D, # .. 0x137F ; Unknown + 0x1380, # .. 0x1399 ; Ethiopic + 0x139A, # .. 0x139F ; Unknown + 0x13A0, # .. 0x13F5 ; Cherokee + 0x13F6, # .. 0x13F7 ; Unknown + 0x13F8, # .. 0x13FD ; Cherokee + 0x13FE, # .. 0x13FF ; Unknown + 0x1400, # .. 0x167F ; Canadian_Aboriginal + 0x1680, # .. 0x169C ; Ogham + 0x169D, # .. 0x169F ; Unknown + 0x16A0, # .. 0x16EA ; Runic + 0x16EB, # .. 0x16ED ; Common + 0x16EE, # .. 0x16F8 ; Runic + 0x16F9, # .. 0x16FF ; Unknown + 0x1700, # .. 0x1715 ; Tagalog + 0x1716, # .. 0x171E ; Unknown + 0x171F, # .. 0x171F ; Tagalog + 0x1720, # .. 0x1734 ; Hanunoo + 0x1735, # .. 0x1736 ; Common + 0x1737, # .. 0x173F ; Unknown + 0x1740, # .. 0x1753 ; Buhid + 0x1754, # .. 0x175F ; Unknown + 0x1760, # .. 0x176C ; Tagbanwa + 0x176D, # .. 0x176D ; Unknown + 0x176E, # .. 0x1770 ; Tagbanwa + 0x1771, # .. 0x1771 ; Unknown + 0x1772, # .. 0x1773 ; Tagbanwa + 0x1774, # .. 0x177F ; Unknown + 0x1780, # .. 0x17DD ; Khmer + 0x17DE, # .. 0x17DF ; Unknown + 0x17E0, # .. 0x17E9 ; Khmer + 0x17EA, # .. 0x17EF ; Unknown + 0x17F0, # .. 0x17F9 ; Khmer + 0x17FA, # .. 0x17FF ; Unknown + 0x1800, # .. 0x1801 ; Mongolian + 0x1802, # .. 0x1803 ; Common + 0x1804, # .. 0x1804 ; Mongolian + 0x1805, # .. 0x1805 ; Common + 0x1806, # .. 0x1819 ; Mongolian + 0x181A, # .. 0x181F ; Unknown + 0x1820, # .. 0x1878 ; Mongolian + 0x1879, # .. 0x187F ; Unknown + 0x1880, # .. 0x18AA ; Mongolian + 0x18AB, # .. 0x18AF ; Unknown + 0x18B0, # .. 0x18F5 ; Canadian_Aboriginal + 0x18F6, # .. 0x18FF ; Unknown + 0x1900, # .. 0x191E ; Limbu + 0x191F, # .. 0x191F ; Unknown + 0x1920, # .. 0x192B ; Limbu + 0x192C, # .. 0x192F ; Unknown + 0x1930, # .. 0x193B ; Limbu + 0x193C, # .. 0x193F ; Unknown + 0x1940, # .. 0x1940 ; Limbu + 0x1941, # .. 0x1943 ; Unknown + 0x1944, # .. 0x194F ; Limbu + 0x1950, # .. 0x196D ; Tai_Le + 0x196E, # .. 0x196F ; Unknown + 0x1970, # .. 0x1974 ; Tai_Le + 0x1975, # .. 0x197F ; Unknown + 0x1980, # .. 0x19AB ; New_Tai_Lue + 0x19AC, # .. 0x19AF ; Unknown + 0x19B0, # .. 0x19C9 ; New_Tai_Lue + 0x19CA, # .. 0x19CF ; Unknown + 0x19D0, # .. 0x19DA ; New_Tai_Lue + 0x19DB, # .. 0x19DD ; Unknown + 0x19DE, # .. 0x19DF ; New_Tai_Lue + 0x19E0, # .. 0x19FF ; Khmer + 0x1A00, # .. 0x1A1B ; Buginese + 0x1A1C, # .. 0x1A1D ; Unknown + 0x1A1E, # .. 0x1A1F ; Buginese + 0x1A20, # .. 0x1A5E ; Tai_Tham + 0x1A5F, # .. 0x1A5F ; Unknown + 0x1A60, # .. 0x1A7C ; Tai_Tham + 0x1A7D, # .. 0x1A7E ; Unknown + 0x1A7F, # .. 0x1A89 ; Tai_Tham + 0x1A8A, # .. 0x1A8F ; Unknown + 0x1A90, # .. 0x1A99 ; Tai_Tham + 0x1A9A, # .. 0x1A9F ; Unknown + 0x1AA0, # .. 0x1AAD ; Tai_Tham + 0x1AAE, # .. 0x1AAF ; Unknown + 0x1AB0, # .. 0x1ADD ; Inherited + 0x1ADE, # .. 0x1ADF ; Unknown + 0x1AE0, # .. 0x1AEB ; Inherited + 0x1AEC, # .. 0x1AFF ; Unknown + 0x1B00, # .. 0x1B4C ; Balinese + 0x1B4D, # .. 0x1B4D ; Unknown + 0x1B4E, # .. 0x1B7F ; Balinese + 0x1B80, # .. 0x1BBF ; Sundanese + 0x1BC0, # .. 0x1BF3 ; Batak + 0x1BF4, # .. 0x1BFB ; Unknown + 0x1BFC, # .. 0x1BFF ; Batak + 0x1C00, # .. 0x1C37 ; Lepcha + 0x1C38, # .. 0x1C3A ; Unknown + 0x1C3B, # .. 0x1C49 ; Lepcha + 0x1C4A, # .. 0x1C4C ; Unknown + 0x1C4D, # .. 0x1C4F ; Lepcha + 0x1C50, # .. 0x1C7F ; Ol_Chiki + 0x1C80, # .. 0x1C8A ; Cyrillic + 0x1C8B, # .. 0x1C8F ; Unknown + 0x1C90, # .. 0x1CBA ; Georgian + 0x1CBB, # .. 0x1CBC ; Unknown + 0x1CBD, # .. 0x1CBF ; Georgian + 0x1CC0, # .. 0x1CC7 ; Sundanese + 0x1CC8, # .. 0x1CCF ; Unknown + 0x1CD0, # .. 0x1CD2 ; Inherited + 0x1CD3, # .. 0x1CD3 ; Common + 0x1CD4, # .. 0x1CE0 ; Inherited + 0x1CE1, # .. 0x1CE1 ; Common + 0x1CE2, # .. 0x1CE8 ; Inherited + 0x1CE9, # .. 0x1CEC ; Common + 0x1CED, # .. 0x1CED ; Inherited + 0x1CEE, # .. 0x1CF3 ; Common + 0x1CF4, # .. 0x1CF4 ; Inherited + 0x1CF5, # .. 0x1CF7 ; Common + 0x1CF8, # .. 0x1CF9 ; Inherited + 0x1CFA, # .. 0x1CFA ; Common + 0x1CFB, # .. 0x1CFF ; Unknown + 0x1D00, # .. 0x1D25 ; Latin + 0x1D26, # .. 0x1D2A ; Greek + 0x1D2B, # .. 0x1D2B ; Cyrillic + 0x1D2C, # .. 0x1D5C ; Latin + 0x1D5D, # .. 0x1D61 ; Greek + 0x1D62, # .. 0x1D65 ; Latin + 0x1D66, # .. 0x1D6A ; Greek + 0x1D6B, # .. 0x1D77 ; Latin + 0x1D78, # .. 0x1D78 ; Cyrillic + 0x1D79, # .. 0x1DBE ; Latin + 0x1DBF, # .. 0x1DBF ; Greek + 0x1DC0, # .. 0x1DFF ; Inherited + 0x1E00, # .. 0x1EFF ; Latin + 0x1F00, # .. 0x1F15 ; Greek + 0x1F16, # .. 0x1F17 ; Unknown + 0x1F18, # .. 0x1F1D ; Greek + 0x1F1E, # .. 0x1F1F ; Unknown + 0x1F20, # .. 0x1F45 ; Greek + 0x1F46, # .. 0x1F47 ; Unknown + 0x1F48, # .. 0x1F4D ; Greek + 0x1F4E, # .. 0x1F4F ; Unknown + 0x1F50, # .. 0x1F57 ; Greek + 0x1F58, # .. 0x1F58 ; Unknown + 0x1F59, # .. 0x1F59 ; Greek + 0x1F5A, # .. 0x1F5A ; Unknown + 0x1F5B, # .. 0x1F5B ; Greek + 0x1F5C, # .. 0x1F5C ; Unknown + 0x1F5D, # .. 0x1F5D ; Greek + 0x1F5E, # .. 0x1F5E ; Unknown + 0x1F5F, # .. 0x1F7D ; Greek + 0x1F7E, # .. 0x1F7F ; Unknown + 0x1F80, # .. 0x1FB4 ; Greek + 0x1FB5, # .. 0x1FB5 ; Unknown + 0x1FB6, # .. 0x1FC4 ; Greek + 0x1FC5, # .. 0x1FC5 ; Unknown + 0x1FC6, # .. 0x1FD3 ; Greek + 0x1FD4, # .. 0x1FD5 ; Unknown + 0x1FD6, # .. 0x1FDB ; Greek + 0x1FDC, # .. 0x1FDC ; Unknown + 0x1FDD, # .. 0x1FEF ; Greek + 0x1FF0, # .. 0x1FF1 ; Unknown + 0x1FF2, # .. 0x1FF4 ; Greek + 0x1FF5, # .. 0x1FF5 ; Unknown + 0x1FF6, # .. 0x1FFE ; Greek + 0x1FFF, # .. 0x1FFF ; Unknown + 0x2000, # .. 0x200B ; Common + 0x200C, # .. 0x200D ; Inherited + 0x200E, # .. 0x2064 ; Common + 0x2065, # .. 0x2065 ; Unknown + 0x2066, # .. 0x2070 ; Common + 0x2071, # .. 0x2071 ; Latin + 0x2072, # .. 0x2073 ; Unknown + 0x2074, # .. 0x207E ; Common + 0x207F, # .. 0x207F ; Latin + 0x2080, # .. 0x208E ; Common + 0x208F, # .. 0x208F ; Unknown + 0x2090, # .. 0x209C ; Latin + 0x209D, # .. 0x209F ; Unknown + 0x20A0, # .. 0x20C1 ; Common + 0x20C2, # .. 0x20CF ; Unknown + 0x20D0, # .. 0x20F0 ; Inherited + 0x20F1, # .. 0x20FF ; Unknown + 0x2100, # .. 0x2125 ; Common + 0x2126, # .. 0x2126 ; Greek + 0x2127, # .. 0x2129 ; Common + 0x212A, # .. 0x212B ; Latin + 0x212C, # .. 0x2131 ; Common + 0x2132, # .. 0x2132 ; Latin + 0x2133, # .. 0x214D ; Common + 0x214E, # .. 0x214E ; Latin + 0x214F, # .. 0x215F ; Common + 0x2160, # .. 0x2188 ; Latin + 0x2189, # .. 0x218B ; Common + 0x218C, # .. 0x218F ; Unknown + 0x2190, # .. 0x2429 ; Common + 0x242A, # .. 0x243F ; Unknown + 0x2440, # .. 0x244A ; Common + 0x244B, # .. 0x245F ; Unknown + 0x2460, # .. 0x27FF ; Common + 0x2800, # .. 0x28FF ; Braille + 0x2900, # .. 0x2B73 ; Common + 0x2B74, # .. 0x2B75 ; Unknown + 0x2B76, # .. 0x2BFF ; Common + 0x2C00, # .. 0x2C5F ; Glagolitic + 0x2C60, # .. 0x2C7F ; Latin + 0x2C80, # .. 0x2CF3 ; Coptic + 0x2CF4, # .. 0x2CF8 ; Unknown + 0x2CF9, # .. 0x2CFF ; Coptic + 0x2D00, # .. 0x2D25 ; Georgian + 0x2D26, # .. 0x2D26 ; Unknown + 0x2D27, # .. 0x2D27 ; Georgian + 0x2D28, # .. 0x2D2C ; Unknown + 0x2D2D, # .. 0x2D2D ; Georgian + 0x2D2E, # .. 0x2D2F ; Unknown + 0x2D30, # .. 0x2D67 ; Tifinagh + 0x2D68, # .. 0x2D6E ; Unknown + 0x2D6F, # .. 0x2D70 ; Tifinagh + 0x2D71, # .. 0x2D7E ; Unknown + 0x2D7F, # .. 0x2D7F ; Tifinagh + 0x2D80, # .. 0x2D96 ; Ethiopic + 0x2D97, # .. 0x2D9F ; Unknown + 0x2DA0, # .. 0x2DA6 ; Ethiopic + 0x2DA7, # .. 0x2DA7 ; Unknown + 0x2DA8, # .. 0x2DAE ; Ethiopic + 0x2DAF, # .. 0x2DAF ; Unknown + 0x2DB0, # .. 0x2DB6 ; Ethiopic + 0x2DB7, # .. 0x2DB7 ; Unknown + 0x2DB8, # .. 0x2DBE ; Ethiopic + 0x2DBF, # .. 0x2DBF ; Unknown + 0x2DC0, # .. 0x2DC6 ; Ethiopic + 0x2DC7, # .. 0x2DC7 ; Unknown + 0x2DC8, # .. 0x2DCE ; Ethiopic + 0x2DCF, # .. 0x2DCF ; Unknown + 0x2DD0, # .. 0x2DD6 ; Ethiopic + 0x2DD7, # .. 0x2DD7 ; Unknown + 0x2DD8, # .. 0x2DDE ; Ethiopic + 0x2DDF, # .. 0x2DDF ; Unknown + 0x2DE0, # .. 0x2DFF ; Cyrillic + 0x2E00, # .. 0x2E5D ; Common + 0x2E5E, # .. 0x2E7F ; Unknown + 0x2E80, # .. 0x2E99 ; Han + 0x2E9A, # .. 0x2E9A ; Unknown + 0x2E9B, # .. 0x2EF3 ; Han + 0x2EF4, # .. 0x2EFF ; Unknown + 0x2F00, # .. 0x2FD5 ; Han + 0x2FD6, # .. 0x2FEF ; Unknown + 0x2FF0, # .. 0x3004 ; Common + 0x3005, # .. 0x3005 ; Han + 0x3006, # .. 0x3006 ; Common + 0x3007, # .. 0x3007 ; Han + 0x3008, # .. 0x3020 ; Common + 0x3021, # .. 0x3029 ; Han + 0x302A, # .. 0x302D ; Inherited + 0x302E, # .. 0x302F ; Hangul + 0x3030, # .. 0x3037 ; Common + 0x3038, # .. 0x303B ; Han + 0x303C, # .. 0x303F ; Common + 0x3040, # .. 0x3040 ; Unknown + 0x3041, # .. 0x3096 ; Hiragana + 0x3097, # .. 0x3098 ; Unknown + 0x3099, # .. 0x309A ; Inherited + 0x309B, # .. 0x309C ; Common + 0x309D, # .. 0x309F ; Hiragana + 0x30A0, # .. 0x30A0 ; Common + 0x30A1, # .. 0x30FA ; Katakana + 0x30FB, # .. 0x30FC ; Common + 0x30FD, # .. 0x30FF ; Katakana + 0x3100, # .. 0x3104 ; Unknown + 0x3105, # .. 0x312F ; Bopomofo + 0x3130, # .. 0x3130 ; Unknown + 0x3131, # .. 0x318E ; Hangul + 0x318F, # .. 0x318F ; Unknown + 0x3190, # .. 0x319F ; Common + 0x31A0, # .. 0x31BF ; Bopomofo + 0x31C0, # .. 0x31E5 ; Common + 0x31E6, # .. 0x31EE ; Unknown + 0x31EF, # .. 0x31EF ; Common + 0x31F0, # .. 0x31FF ; Katakana + 0x3200, # .. 0x321E ; Hangul + 0x321F, # .. 0x321F ; Unknown + 0x3220, # .. 0x325F ; Common + 0x3260, # .. 0x327E ; Hangul + 0x327F, # .. 0x32CF ; Common + 0x32D0, # .. 0x32FE ; Katakana + 0x32FF, # .. 0x32FF ; Common + 0x3300, # .. 0x3357 ; Katakana + 0x3358, # .. 0x33FF ; Common + 0x3400, # .. 0x4DBF ; Han + 0x4DC0, # .. 0x4DFF ; Common + 0x4E00, # .. 0x9FFF ; Han + 0xA000, # .. 0xA48C ; Yi + 0xA48D, # .. 0xA48F ; Unknown + 0xA490, # .. 0xA4C6 ; Yi + 0xA4C7, # .. 0xA4CF ; Unknown + 0xA4D0, # .. 0xA4FF ; Lisu + 0xA500, # .. 0xA62B ; Vai + 0xA62C, # .. 0xA63F ; Unknown + 0xA640, # .. 0xA69F ; Cyrillic + 0xA6A0, # .. 0xA6F7 ; Bamum + 0xA6F8, # .. 0xA6FF ; Unknown + 0xA700, # .. 0xA721 ; Common + 0xA722, # .. 0xA787 ; Latin + 0xA788, # .. 0xA78A ; Common + 0xA78B, # .. 0xA7DC ; Latin + 0xA7DD, # .. 0xA7F0 ; Unknown + 0xA7F1, # .. 0xA7FF ; Latin + 0xA800, # .. 0xA82C ; Syloti_Nagri + 0xA82D, # .. 0xA82F ; Unknown + 0xA830, # .. 0xA839 ; Common + 0xA83A, # .. 0xA83F ; Unknown + 0xA840, # .. 0xA877 ; Phags_Pa + 0xA878, # .. 0xA87F ; Unknown + 0xA880, # .. 0xA8C5 ; Saurashtra + 0xA8C6, # .. 0xA8CD ; Unknown + 0xA8CE, # .. 0xA8D9 ; Saurashtra + 0xA8DA, # .. 0xA8DF ; Unknown + 0xA8E0, # .. 0xA8FF ; Devanagari + 0xA900, # .. 0xA92D ; Kayah_Li + 0xA92E, # .. 0xA92E ; Common + 0xA92F, # .. 0xA92F ; Kayah_Li + 0xA930, # .. 0xA953 ; Rejang + 0xA954, # .. 0xA95E ; Unknown + 0xA95F, # .. 0xA95F ; Rejang + 0xA960, # .. 0xA97C ; Hangul + 0xA97D, # .. 0xA97F ; Unknown + 0xA980, # .. 0xA9CD ; Javanese + 0xA9CE, # .. 0xA9CE ; Unknown + 0xA9CF, # .. 0xA9CF ; Common + 0xA9D0, # .. 0xA9D9 ; Javanese + 0xA9DA, # .. 0xA9DD ; Unknown + 0xA9DE, # .. 0xA9DF ; Javanese + 0xA9E0, # .. 0xA9FE ; Myanmar + 0xA9FF, # .. 0xA9FF ; Unknown + 0xAA00, # .. 0xAA36 ; Cham + 0xAA37, # .. 0xAA3F ; Unknown + 0xAA40, # .. 0xAA4D ; Cham + 0xAA4E, # .. 0xAA4F ; Unknown + 0xAA50, # .. 0xAA59 ; Cham + 0xAA5A, # .. 0xAA5B ; Unknown + 0xAA5C, # .. 0xAA5F ; Cham + 0xAA60, # .. 0xAA7F ; Myanmar + 0xAA80, # .. 0xAAC2 ; Tai_Viet + 0xAAC3, # .. 0xAADA ; Unknown + 0xAADB, # .. 0xAADF ; Tai_Viet + 0xAAE0, # .. 0xAAF6 ; Meetei_Mayek + 0xAAF7, # .. 0xAB00 ; Unknown + 0xAB01, # .. 0xAB06 ; Ethiopic + 0xAB07, # .. 0xAB08 ; Unknown + 0xAB09, # .. 0xAB0E ; Ethiopic + 0xAB0F, # .. 0xAB10 ; Unknown + 0xAB11, # .. 0xAB16 ; Ethiopic + 0xAB17, # .. 0xAB1F ; Unknown + 0xAB20, # .. 0xAB26 ; Ethiopic + 0xAB27, # .. 0xAB27 ; Unknown + 0xAB28, # .. 0xAB2E ; Ethiopic + 0xAB2F, # .. 0xAB2F ; Unknown + 0xAB30, # .. 0xAB5A ; Latin + 0xAB5B, # .. 0xAB5B ; Common + 0xAB5C, # .. 0xAB64 ; Latin + 0xAB65, # .. 0xAB65 ; Greek + 0xAB66, # .. 0xAB69 ; Latin + 0xAB6A, # .. 0xAB6B ; Common + 0xAB6C, # .. 0xAB6F ; Unknown + 0xAB70, # .. 0xABBF ; Cherokee + 0xABC0, # .. 0xABED ; Meetei_Mayek + 0xABEE, # .. 0xABEF ; Unknown + 0xABF0, # .. 0xABF9 ; Meetei_Mayek + 0xABFA, # .. 0xABFF ; Unknown + 0xAC00, # .. 0xD7A3 ; Hangul + 0xD7A4, # .. 0xD7AF ; Unknown + 0xD7B0, # .. 0xD7C6 ; Hangul + 0xD7C7, # .. 0xD7CA ; Unknown + 0xD7CB, # .. 0xD7FB ; Hangul + 0xD7FC, # .. 0xF8FF ; Unknown + 0xF900, # .. 0xFA6D ; Han + 0xFA6E, # .. 0xFA6F ; Unknown + 0xFA70, # .. 0xFAD9 ; Han + 0xFADA, # .. 0xFAFF ; Unknown + 0xFB00, # .. 0xFB06 ; Latin + 0xFB07, # .. 0xFB12 ; Unknown + 0xFB13, # .. 0xFB17 ; Armenian + 0xFB18, # .. 0xFB1C ; Unknown + 0xFB1D, # .. 0xFB36 ; Hebrew + 0xFB37, # .. 0xFB37 ; Unknown + 0xFB38, # .. 0xFB3C ; Hebrew + 0xFB3D, # .. 0xFB3D ; Unknown + 0xFB3E, # .. 0xFB3E ; Hebrew + 0xFB3F, # .. 0xFB3F ; Unknown + 0xFB40, # .. 0xFB41 ; Hebrew + 0xFB42, # .. 0xFB42 ; Unknown + 0xFB43, # .. 0xFB44 ; Hebrew + 0xFB45, # .. 0xFB45 ; Unknown + 0xFB46, # .. 0xFB4F ; Hebrew + 0xFB50, # .. 0xFD3D ; Arabic + 0xFD3E, # .. 0xFD3F ; Common + 0xFD40, # .. 0xFDCF ; Arabic + 0xFDD0, # .. 0xFDEF ; Unknown + 0xFDF0, # .. 0xFDFF ; Arabic + 0xFE00, # .. 0xFE0F ; Inherited + 0xFE10, # .. 0xFE19 ; Common + 0xFE1A, # .. 0xFE1F ; Unknown + 0xFE20, # .. 0xFE2D ; Inherited + 0xFE2E, # .. 0xFE2F ; Cyrillic + 0xFE30, # .. 0xFE52 ; Common + 0xFE53, # .. 0xFE53 ; Unknown + 0xFE54, # .. 0xFE66 ; Common + 0xFE67, # .. 0xFE67 ; Unknown + 0xFE68, # .. 0xFE6B ; Common + 0xFE6C, # .. 0xFE6F ; Unknown + 0xFE70, # .. 0xFE74 ; Arabic + 0xFE75, # .. 0xFE75 ; Unknown + 0xFE76, # .. 0xFEFC ; Arabic + 0xFEFD, # .. 0xFEFE ; Unknown + 0xFEFF, # .. 0xFEFF ; Common + 0xFF00, # .. 0xFF00 ; Unknown + 0xFF01, # .. 0xFF20 ; Common + 0xFF21, # .. 0xFF3A ; Latin + 0xFF3B, # .. 0xFF40 ; Common + 0xFF41, # .. 0xFF5A ; Latin + 0xFF5B, # .. 0xFF65 ; Common + 0xFF66, # .. 0xFF6F ; Katakana + 0xFF70, # .. 0xFF70 ; Common + 0xFF71, # .. 0xFF9D ; Katakana + 0xFF9E, # .. 0xFF9F ; Common + 0xFFA0, # .. 0xFFBE ; Hangul + 0xFFBF, # .. 0xFFC1 ; Unknown + 0xFFC2, # .. 0xFFC7 ; Hangul + 0xFFC8, # .. 0xFFC9 ; Unknown + 0xFFCA, # .. 0xFFCF ; Hangul + 0xFFD0, # .. 0xFFD1 ; Unknown + 0xFFD2, # .. 0xFFD7 ; Hangul + 0xFFD8, # .. 0xFFD9 ; Unknown + 0xFFDA, # .. 0xFFDC ; Hangul + 0xFFDD, # .. 0xFFDF ; Unknown + 0xFFE0, # .. 0xFFE6 ; Common + 0xFFE7, # .. 0xFFE7 ; Unknown + 0xFFE8, # .. 0xFFEE ; Common + 0xFFEF, # .. 0xFFF8 ; Unknown + 0xFFF9, # .. 0xFFFD ; Common + 0xFFFE, # .. 0xFFFF ; Unknown + 0x10000, # .. 0x1000B ; Linear_B + 0x1000C, # .. 0x1000C ; Unknown + 0x1000D, # .. 0x10026 ; Linear_B + 0x10027, # .. 0x10027 ; Unknown + 0x10028, # .. 0x1003A ; Linear_B + 0x1003B, # .. 0x1003B ; Unknown + 0x1003C, # .. 0x1003D ; Linear_B + 0x1003E, # .. 0x1003E ; Unknown + 0x1003F, # .. 0x1004D ; Linear_B + 0x1004E, # .. 0x1004F ; Unknown + 0x10050, # .. 0x1005D ; Linear_B + 0x1005E, # .. 0x1007F ; Unknown + 0x10080, # .. 0x100FA ; Linear_B + 0x100FB, # .. 0x100FF ; Unknown + 0x10100, # .. 0x10102 ; Common + 0x10103, # .. 0x10106 ; Unknown + 0x10107, # .. 0x10133 ; Common + 0x10134, # .. 0x10136 ; Unknown + 0x10137, # .. 0x1013F ; Common + 0x10140, # .. 0x1018E ; Greek + 0x1018F, # .. 0x1018F ; Unknown + 0x10190, # .. 0x1019C ; Common + 0x1019D, # .. 0x1019F ; Unknown + 0x101A0, # .. 0x101A0 ; Greek + 0x101A1, # .. 0x101CF ; Unknown + 0x101D0, # .. 0x101FC ; Common + 0x101FD, # .. 0x101FD ; Inherited + 0x101FE, # .. 0x1027F ; Unknown + 0x10280, # .. 0x1029C ; Lycian + 0x1029D, # .. 0x1029F ; Unknown + 0x102A0, # .. 0x102D0 ; Carian + 0x102D1, # .. 0x102DF ; Unknown + 0x102E0, # .. 0x102E0 ; Inherited + 0x102E1, # .. 0x102FB ; Common + 0x102FC, # .. 0x102FF ; Unknown + 0x10300, # .. 0x10323 ; Old_Italic + 0x10324, # .. 0x1032C ; Unknown + 0x1032D, # .. 0x1032F ; Old_Italic + 0x10330, # .. 0x1034A ; Gothic + 0x1034B, # .. 0x1034F ; Unknown + 0x10350, # .. 0x1037A ; Old_Permic + 0x1037B, # .. 0x1037F ; Unknown + 0x10380, # .. 0x1039D ; Ugaritic + 0x1039E, # .. 0x1039E ; Unknown + 0x1039F, # .. 0x1039F ; Ugaritic + 0x103A0, # .. 0x103C3 ; Old_Persian + 0x103C4, # .. 0x103C7 ; Unknown + 0x103C8, # .. 0x103D5 ; Old_Persian + 0x103D6, # .. 0x103FF ; Unknown + 0x10400, # .. 0x1044F ; Deseret + 0x10450, # .. 0x1047F ; Shavian + 0x10480, # .. 0x1049D ; Osmanya + 0x1049E, # .. 0x1049F ; Unknown + 0x104A0, # .. 0x104A9 ; Osmanya + 0x104AA, # .. 0x104AF ; Unknown + 0x104B0, # .. 0x104D3 ; Osage + 0x104D4, # .. 0x104D7 ; Unknown + 0x104D8, # .. 0x104FB ; Osage + 0x104FC, # .. 0x104FF ; Unknown + 0x10500, # .. 0x10527 ; Elbasan + 0x10528, # .. 0x1052F ; Unknown + 0x10530, # .. 0x10563 ; Caucasian_Albanian + 0x10564, # .. 0x1056E ; Unknown + 0x1056F, # .. 0x1056F ; Caucasian_Albanian + 0x10570, # .. 0x1057A ; Vithkuqi + 0x1057B, # .. 0x1057B ; Unknown + 0x1057C, # .. 0x1058A ; Vithkuqi + 0x1058B, # .. 0x1058B ; Unknown + 0x1058C, # .. 0x10592 ; Vithkuqi + 0x10593, # .. 0x10593 ; Unknown + 0x10594, # .. 0x10595 ; Vithkuqi + 0x10596, # .. 0x10596 ; Unknown + 0x10597, # .. 0x105A1 ; Vithkuqi + 0x105A2, # .. 0x105A2 ; Unknown + 0x105A3, # .. 0x105B1 ; Vithkuqi + 0x105B2, # .. 0x105B2 ; Unknown + 0x105B3, # .. 0x105B9 ; Vithkuqi + 0x105BA, # .. 0x105BA ; Unknown + 0x105BB, # .. 0x105BC ; Vithkuqi + 0x105BD, # .. 0x105BF ; Unknown + 0x105C0, # .. 0x105F3 ; Todhri + 0x105F4, # .. 0x105FF ; Unknown + 0x10600, # .. 0x10736 ; Linear_A + 0x10737, # .. 0x1073F ; Unknown + 0x10740, # .. 0x10755 ; Linear_A + 0x10756, # .. 0x1075F ; Unknown + 0x10760, # .. 0x10767 ; Linear_A + 0x10768, # .. 0x1077F ; Unknown + 0x10780, # .. 0x10785 ; Latin + 0x10786, # .. 0x10786 ; Unknown + 0x10787, # .. 0x107B0 ; Latin + 0x107B1, # .. 0x107B1 ; Unknown + 0x107B2, # .. 0x107BA ; Latin + 0x107BB, # .. 0x107FF ; Unknown + 0x10800, # .. 0x10805 ; Cypriot + 0x10806, # .. 0x10807 ; Unknown + 0x10808, # .. 0x10808 ; Cypriot + 0x10809, # .. 0x10809 ; Unknown + 0x1080A, # .. 0x10835 ; Cypriot + 0x10836, # .. 0x10836 ; Unknown + 0x10837, # .. 0x10838 ; Cypriot + 0x10839, # .. 0x1083B ; Unknown + 0x1083C, # .. 0x1083C ; Cypriot + 0x1083D, # .. 0x1083E ; Unknown + 0x1083F, # .. 0x1083F ; Cypriot + 0x10840, # .. 0x10855 ; Imperial_Aramaic + 0x10856, # .. 0x10856 ; Unknown + 0x10857, # .. 0x1085F ; Imperial_Aramaic + 0x10860, # .. 0x1087F ; Palmyrene + 0x10880, # .. 0x1089E ; Nabataean + 0x1089F, # .. 0x108A6 ; Unknown + 0x108A7, # .. 0x108AF ; Nabataean + 0x108B0, # .. 0x108DF ; Unknown + 0x108E0, # .. 0x108F2 ; Hatran + 0x108F3, # .. 0x108F3 ; Unknown + 0x108F4, # .. 0x108F5 ; Hatran + 0x108F6, # .. 0x108FA ; Unknown + 0x108FB, # .. 0x108FF ; Hatran + 0x10900, # .. 0x1091B ; Phoenician + 0x1091C, # .. 0x1091E ; Unknown + 0x1091F, # .. 0x1091F ; Phoenician + 0x10920, # .. 0x10939 ; Lydian + 0x1093A, # .. 0x1093E ; Unknown + 0x1093F, # .. 0x1093F ; Lydian + 0x10940, # .. 0x10959 ; Sidetic + 0x1095A, # .. 0x1097F ; Unknown + 0x10980, # .. 0x1099F ; Meroitic_Hieroglyphs + 0x109A0, # .. 0x109B7 ; Meroitic_Cursive + 0x109B8, # .. 0x109BB ; Unknown + 0x109BC, # .. 0x109CF ; Meroitic_Cursive + 0x109D0, # .. 0x109D1 ; Unknown + 0x109D2, # .. 0x109FF ; Meroitic_Cursive + 0x10A00, # .. 0x10A03 ; Kharoshthi + 0x10A04, # .. 0x10A04 ; Unknown + 0x10A05, # .. 0x10A06 ; Kharoshthi + 0x10A07, # .. 0x10A0B ; Unknown + 0x10A0C, # .. 0x10A13 ; Kharoshthi + 0x10A14, # .. 0x10A14 ; Unknown + 0x10A15, # .. 0x10A17 ; Kharoshthi + 0x10A18, # .. 0x10A18 ; Unknown + 0x10A19, # .. 0x10A35 ; Kharoshthi + 0x10A36, # .. 0x10A37 ; Unknown + 0x10A38, # .. 0x10A3A ; Kharoshthi + 0x10A3B, # .. 0x10A3E ; Unknown + 0x10A3F, # .. 0x10A48 ; Kharoshthi + 0x10A49, # .. 0x10A4F ; Unknown + 0x10A50, # .. 0x10A58 ; Kharoshthi + 0x10A59, # .. 0x10A5F ; Unknown + 0x10A60, # .. 0x10A7F ; Old_South_Arabian + 0x10A80, # .. 0x10A9F ; Old_North_Arabian + 0x10AA0, # .. 0x10ABF ; Unknown + 0x10AC0, # .. 0x10AE6 ; Manichaean + 0x10AE7, # .. 0x10AEA ; Unknown + 0x10AEB, # .. 0x10AF6 ; Manichaean + 0x10AF7, # .. 0x10AFF ; Unknown + 0x10B00, # .. 0x10B35 ; Avestan + 0x10B36, # .. 0x10B38 ; Unknown + 0x10B39, # .. 0x10B3F ; Avestan + 0x10B40, # .. 0x10B55 ; Inscriptional_Parthian + 0x10B56, # .. 0x10B57 ; Unknown + 0x10B58, # .. 0x10B5F ; Inscriptional_Parthian + 0x10B60, # .. 0x10B72 ; Inscriptional_Pahlavi + 0x10B73, # .. 0x10B77 ; Unknown + 0x10B78, # .. 0x10B7F ; Inscriptional_Pahlavi + 0x10B80, # .. 0x10B91 ; Psalter_Pahlavi + 0x10B92, # .. 0x10B98 ; Unknown + 0x10B99, # .. 0x10B9C ; Psalter_Pahlavi + 0x10B9D, # .. 0x10BA8 ; Unknown + 0x10BA9, # .. 0x10BAF ; Psalter_Pahlavi + 0x10BB0, # .. 0x10BFF ; Unknown + 0x10C00, # .. 0x10C48 ; Old_Turkic + 0x10C49, # .. 0x10C7F ; Unknown + 0x10C80, # .. 0x10CB2 ; Old_Hungarian + 0x10CB3, # .. 0x10CBF ; Unknown + 0x10CC0, # .. 0x10CF2 ; Old_Hungarian + 0x10CF3, # .. 0x10CF9 ; Unknown + 0x10CFA, # .. 0x10CFF ; Old_Hungarian + 0x10D00, # .. 0x10D27 ; Hanifi_Rohingya + 0x10D28, # .. 0x10D2F ; Unknown + 0x10D30, # .. 0x10D39 ; Hanifi_Rohingya + 0x10D3A, # .. 0x10D3F ; Unknown + 0x10D40, # .. 0x10D65 ; Garay + 0x10D66, # .. 0x10D68 ; Unknown + 0x10D69, # .. 0x10D85 ; Garay + 0x10D86, # .. 0x10D8D ; Unknown + 0x10D8E, # .. 0x10D8F ; Garay + 0x10D90, # .. 0x10E5F ; Unknown + 0x10E60, # .. 0x10E7E ; Arabic + 0x10E7F, # .. 0x10E7F ; Unknown + 0x10E80, # .. 0x10EA9 ; Yezidi + 0x10EAA, # .. 0x10EAA ; Unknown + 0x10EAB, # .. 0x10EAD ; Yezidi + 0x10EAE, # .. 0x10EAF ; Unknown + 0x10EB0, # .. 0x10EB1 ; Yezidi + 0x10EB2, # .. 0x10EC1 ; Unknown + 0x10EC2, # .. 0x10EC7 ; Arabic + 0x10EC8, # .. 0x10ECF ; Unknown + 0x10ED0, # .. 0x10ED8 ; Arabic + 0x10ED9, # .. 0x10EF9 ; Unknown + 0x10EFA, # .. 0x10EFF ; Arabic + 0x10F00, # .. 0x10F27 ; Old_Sogdian + 0x10F28, # .. 0x10F2F ; Unknown + 0x10F30, # .. 0x10F59 ; Sogdian + 0x10F5A, # .. 0x10F6F ; Unknown + 0x10F70, # .. 0x10F89 ; Old_Uyghur + 0x10F8A, # .. 0x10FAF ; Unknown + 0x10FB0, # .. 0x10FCB ; Chorasmian + 0x10FCC, # .. 0x10FDF ; Unknown + 0x10FE0, # .. 0x10FF6 ; Elymaic + 0x10FF7, # .. 0x10FFF ; Unknown + 0x11000, # .. 0x1104D ; Brahmi + 0x1104E, # .. 0x11051 ; Unknown + 0x11052, # .. 0x11075 ; Brahmi + 0x11076, # .. 0x1107E ; Unknown + 0x1107F, # .. 0x1107F ; Brahmi + 0x11080, # .. 0x110C2 ; Kaithi + 0x110C3, # .. 0x110CC ; Unknown + 0x110CD, # .. 0x110CD ; Kaithi + 0x110CE, # .. 0x110CF ; Unknown + 0x110D0, # .. 0x110E8 ; Sora_Sompeng + 0x110E9, # .. 0x110EF ; Unknown + 0x110F0, # .. 0x110F9 ; Sora_Sompeng + 0x110FA, # .. 0x110FF ; Unknown + 0x11100, # .. 0x11134 ; Chakma + 0x11135, # .. 0x11135 ; Unknown + 0x11136, # .. 0x11147 ; Chakma + 0x11148, # .. 0x1114F ; Unknown + 0x11150, # .. 0x11176 ; Mahajani + 0x11177, # .. 0x1117F ; Unknown + 0x11180, # .. 0x111DF ; Sharada + 0x111E0, # .. 0x111E0 ; Unknown + 0x111E1, # .. 0x111F4 ; Sinhala + 0x111F5, # .. 0x111FF ; Unknown + 0x11200, # .. 0x11211 ; Khojki + 0x11212, # .. 0x11212 ; Unknown + 0x11213, # .. 0x11241 ; Khojki + 0x11242, # .. 0x1127F ; Unknown + 0x11280, # .. 0x11286 ; Multani + 0x11287, # .. 0x11287 ; Unknown + 0x11288, # .. 0x11288 ; Multani + 0x11289, # .. 0x11289 ; Unknown + 0x1128A, # .. 0x1128D ; Multani + 0x1128E, # .. 0x1128E ; Unknown + 0x1128F, # .. 0x1129D ; Multani + 0x1129E, # .. 0x1129E ; Unknown + 0x1129F, # .. 0x112A9 ; Multani + 0x112AA, # .. 0x112AF ; Unknown + 0x112B0, # .. 0x112EA ; Khudawadi + 0x112EB, # .. 0x112EF ; Unknown + 0x112F0, # .. 0x112F9 ; Khudawadi + 0x112FA, # .. 0x112FF ; Unknown + 0x11300, # .. 0x11303 ; Grantha + 0x11304, # .. 0x11304 ; Unknown + 0x11305, # .. 0x1130C ; Grantha + 0x1130D, # .. 0x1130E ; Unknown + 0x1130F, # .. 0x11310 ; Grantha + 0x11311, # .. 0x11312 ; Unknown + 0x11313, # .. 0x11328 ; Grantha + 0x11329, # .. 0x11329 ; Unknown + 0x1132A, # .. 0x11330 ; Grantha + 0x11331, # .. 0x11331 ; Unknown + 0x11332, # .. 0x11333 ; Grantha + 0x11334, # .. 0x11334 ; Unknown + 0x11335, # .. 0x11339 ; Grantha + 0x1133A, # .. 0x1133A ; Unknown + 0x1133B, # .. 0x1133B ; Inherited + 0x1133C, # .. 0x11344 ; Grantha + 0x11345, # .. 0x11346 ; Unknown + 0x11347, # .. 0x11348 ; Grantha + 0x11349, # .. 0x1134A ; Unknown + 0x1134B, # .. 0x1134D ; Grantha + 0x1134E, # .. 0x1134F ; Unknown + 0x11350, # .. 0x11350 ; Grantha + 0x11351, # .. 0x11356 ; Unknown + 0x11357, # .. 0x11357 ; Grantha + 0x11358, # .. 0x1135C ; Unknown + 0x1135D, # .. 0x11363 ; Grantha + 0x11364, # .. 0x11365 ; Unknown + 0x11366, # .. 0x1136C ; Grantha + 0x1136D, # .. 0x1136F ; Unknown + 0x11370, # .. 0x11374 ; Grantha + 0x11375, # .. 0x1137F ; Unknown + 0x11380, # .. 0x11389 ; Tulu_Tigalari + 0x1138A, # .. 0x1138A ; Unknown + 0x1138B, # .. 0x1138B ; Tulu_Tigalari + 0x1138C, # .. 0x1138D ; Unknown + 0x1138E, # .. 0x1138E ; Tulu_Tigalari + 0x1138F, # .. 0x1138F ; Unknown + 0x11390, # .. 0x113B5 ; Tulu_Tigalari + 0x113B6, # .. 0x113B6 ; Unknown + 0x113B7, # .. 0x113C0 ; Tulu_Tigalari + 0x113C1, # .. 0x113C1 ; Unknown + 0x113C2, # .. 0x113C2 ; Tulu_Tigalari + 0x113C3, # .. 0x113C4 ; Unknown + 0x113C5, # .. 0x113C5 ; Tulu_Tigalari + 0x113C6, # .. 0x113C6 ; Unknown + 0x113C7, # .. 0x113CA ; Tulu_Tigalari + 0x113CB, # .. 0x113CB ; Unknown + 0x113CC, # .. 0x113D5 ; Tulu_Tigalari + 0x113D6, # .. 0x113D6 ; Unknown + 0x113D7, # .. 0x113D8 ; Tulu_Tigalari + 0x113D9, # .. 0x113E0 ; Unknown + 0x113E1, # .. 0x113E2 ; Tulu_Tigalari + 0x113E3, # .. 0x113FF ; Unknown + 0x11400, # .. 0x1145B ; Newa + 0x1145C, # .. 0x1145C ; Unknown + 0x1145D, # .. 0x11461 ; Newa + 0x11462, # .. 0x1147F ; Unknown + 0x11480, # .. 0x114C7 ; Tirhuta + 0x114C8, # .. 0x114CF ; Unknown + 0x114D0, # .. 0x114D9 ; Tirhuta + 0x114DA, # .. 0x1157F ; Unknown + 0x11580, # .. 0x115B5 ; Siddham + 0x115B6, # .. 0x115B7 ; Unknown + 0x115B8, # .. 0x115DD ; Siddham + 0x115DE, # .. 0x115FF ; Unknown + 0x11600, # .. 0x11644 ; Modi + 0x11645, # .. 0x1164F ; Unknown + 0x11650, # .. 0x11659 ; Modi + 0x1165A, # .. 0x1165F ; Unknown + 0x11660, # .. 0x1166C ; Mongolian + 0x1166D, # .. 0x1167F ; Unknown + 0x11680, # .. 0x116B9 ; Takri + 0x116BA, # .. 0x116BF ; Unknown + 0x116C0, # .. 0x116C9 ; Takri + 0x116CA, # .. 0x116CF ; Unknown + 0x116D0, # .. 0x116E3 ; Myanmar + 0x116E4, # .. 0x116FF ; Unknown + 0x11700, # .. 0x1171A ; Ahom + 0x1171B, # .. 0x1171C ; Unknown + 0x1171D, # .. 0x1172B ; Ahom + 0x1172C, # .. 0x1172F ; Unknown + 0x11730, # .. 0x11746 ; Ahom + 0x11747, # .. 0x117FF ; Unknown + 0x11800, # .. 0x1183B ; Dogra + 0x1183C, # .. 0x1189F ; Unknown + 0x118A0, # .. 0x118F2 ; Warang_Citi + 0x118F3, # .. 0x118FE ; Unknown + 0x118FF, # .. 0x118FF ; Warang_Citi + 0x11900, # .. 0x11906 ; Dives_Akuru + 0x11907, # .. 0x11908 ; Unknown + 0x11909, # .. 0x11909 ; Dives_Akuru + 0x1190A, # .. 0x1190B ; Unknown + 0x1190C, # .. 0x11913 ; Dives_Akuru + 0x11914, # .. 0x11914 ; Unknown + 0x11915, # .. 0x11916 ; Dives_Akuru + 0x11917, # .. 0x11917 ; Unknown + 0x11918, # .. 0x11935 ; Dives_Akuru + 0x11936, # .. 0x11936 ; Unknown + 0x11937, # .. 0x11938 ; Dives_Akuru + 0x11939, # .. 0x1193A ; Unknown + 0x1193B, # .. 0x11946 ; Dives_Akuru + 0x11947, # .. 0x1194F ; Unknown + 0x11950, # .. 0x11959 ; Dives_Akuru + 0x1195A, # .. 0x1199F ; Unknown + 0x119A0, # .. 0x119A7 ; Nandinagari + 0x119A8, # .. 0x119A9 ; Unknown + 0x119AA, # .. 0x119D7 ; Nandinagari + 0x119D8, # .. 0x119D9 ; Unknown + 0x119DA, # .. 0x119E4 ; Nandinagari + 0x119E5, # .. 0x119FF ; Unknown + 0x11A00, # .. 0x11A47 ; Zanabazar_Square + 0x11A48, # .. 0x11A4F ; Unknown + 0x11A50, # .. 0x11AA2 ; Soyombo + 0x11AA3, # .. 0x11AAF ; Unknown + 0x11AB0, # .. 0x11ABF ; Canadian_Aboriginal + 0x11AC0, # .. 0x11AF8 ; Pau_Cin_Hau + 0x11AF9, # .. 0x11AFF ; Unknown + 0x11B00, # .. 0x11B09 ; Devanagari + 0x11B0A, # .. 0x11B5F ; Unknown + 0x11B60, # .. 0x11B67 ; Sharada + 0x11B68, # .. 0x11BBF ; Unknown + 0x11BC0, # .. 0x11BE1 ; Sunuwar + 0x11BE2, # .. 0x11BEF ; Unknown + 0x11BF0, # .. 0x11BF9 ; Sunuwar + 0x11BFA, # .. 0x11BFF ; Unknown + 0x11C00, # .. 0x11C08 ; Bhaiksuki + 0x11C09, # .. 0x11C09 ; Unknown + 0x11C0A, # .. 0x11C36 ; Bhaiksuki + 0x11C37, # .. 0x11C37 ; Unknown + 0x11C38, # .. 0x11C45 ; Bhaiksuki + 0x11C46, # .. 0x11C4F ; Unknown + 0x11C50, # .. 0x11C6C ; Bhaiksuki + 0x11C6D, # .. 0x11C6F ; Unknown + 0x11C70, # .. 0x11C8F ; Marchen + 0x11C90, # .. 0x11C91 ; Unknown + 0x11C92, # .. 0x11CA7 ; Marchen + 0x11CA8, # .. 0x11CA8 ; Unknown + 0x11CA9, # .. 0x11CB6 ; Marchen + 0x11CB7, # .. 0x11CFF ; Unknown + 0x11D00, # .. 0x11D06 ; Masaram_Gondi + 0x11D07, # .. 0x11D07 ; Unknown + 0x11D08, # .. 0x11D09 ; Masaram_Gondi + 0x11D0A, # .. 0x11D0A ; Unknown + 0x11D0B, # .. 0x11D36 ; Masaram_Gondi + 0x11D37, # .. 0x11D39 ; Unknown + 0x11D3A, # .. 0x11D3A ; Masaram_Gondi + 0x11D3B, # .. 0x11D3B ; Unknown + 0x11D3C, # .. 0x11D3D ; Masaram_Gondi + 0x11D3E, # .. 0x11D3E ; Unknown + 0x11D3F, # .. 0x11D47 ; Masaram_Gondi + 0x11D48, # .. 0x11D4F ; Unknown + 0x11D50, # .. 0x11D59 ; Masaram_Gondi + 0x11D5A, # .. 0x11D5F ; Unknown + 0x11D60, # .. 0x11D65 ; Gunjala_Gondi + 0x11D66, # .. 0x11D66 ; Unknown + 0x11D67, # .. 0x11D68 ; Gunjala_Gondi + 0x11D69, # .. 0x11D69 ; Unknown + 0x11D6A, # .. 0x11D8E ; Gunjala_Gondi + 0x11D8F, # .. 0x11D8F ; Unknown + 0x11D90, # .. 0x11D91 ; Gunjala_Gondi + 0x11D92, # .. 0x11D92 ; Unknown + 0x11D93, # .. 0x11D98 ; Gunjala_Gondi + 0x11D99, # .. 0x11D9F ; Unknown + 0x11DA0, # .. 0x11DA9 ; Gunjala_Gondi + 0x11DAA, # .. 0x11DAF ; Unknown + 0x11DB0, # .. 0x11DDB ; Tolong_Siki + 0x11DDC, # .. 0x11DDF ; Unknown + 0x11DE0, # .. 0x11DE9 ; Tolong_Siki + 0x11DEA, # .. 0x11EDF ; Unknown + 0x11EE0, # .. 0x11EF8 ; Makasar + 0x11EF9, # .. 0x11EFF ; Unknown + 0x11F00, # .. 0x11F10 ; Kawi + 0x11F11, # .. 0x11F11 ; Unknown + 0x11F12, # .. 0x11F3A ; Kawi + 0x11F3B, # .. 0x11F3D ; Unknown + 0x11F3E, # .. 0x11F5A ; Kawi + 0x11F5B, # .. 0x11FAF ; Unknown + 0x11FB0, # .. 0x11FB0 ; Lisu + 0x11FB1, # .. 0x11FBF ; Unknown + 0x11FC0, # .. 0x11FF1 ; Tamil + 0x11FF2, # .. 0x11FFE ; Unknown + 0x11FFF, # .. 0x11FFF ; Tamil + 0x12000, # .. 0x12399 ; Cuneiform + 0x1239A, # .. 0x123FF ; Unknown + 0x12400, # .. 0x1246E ; Cuneiform + 0x1246F, # .. 0x1246F ; Unknown + 0x12470, # .. 0x12474 ; Cuneiform + 0x12475, # .. 0x1247F ; Unknown + 0x12480, # .. 0x12543 ; Cuneiform + 0x12544, # .. 0x12F8F ; Unknown + 0x12F90, # .. 0x12FF2 ; Cypro_Minoan + 0x12FF3, # .. 0x12FFF ; Unknown + 0x13000, # .. 0x13455 ; Egyptian_Hieroglyphs + 0x13456, # .. 0x1345F ; Unknown + 0x13460, # .. 0x143FA ; Egyptian_Hieroglyphs + 0x143FB, # .. 0x143FF ; Unknown + 0x14400, # .. 0x14646 ; Anatolian_Hieroglyphs + 0x14647, # .. 0x160FF ; Unknown + 0x16100, # .. 0x16139 ; Gurung_Khema + 0x1613A, # .. 0x167FF ; Unknown + 0x16800, # .. 0x16A38 ; Bamum + 0x16A39, # .. 0x16A3F ; Unknown + 0x16A40, # .. 0x16A5E ; Mro + 0x16A5F, # .. 0x16A5F ; Unknown + 0x16A60, # .. 0x16A69 ; Mro + 0x16A6A, # .. 0x16A6D ; Unknown + 0x16A6E, # .. 0x16A6F ; Mro + 0x16A70, # .. 0x16ABE ; Tangsa + 0x16ABF, # .. 0x16ABF ; Unknown + 0x16AC0, # .. 0x16AC9 ; Tangsa + 0x16ACA, # .. 0x16ACF ; Unknown + 0x16AD0, # .. 0x16AED ; Bassa_Vah + 0x16AEE, # .. 0x16AEF ; Unknown + 0x16AF0, # .. 0x16AF5 ; Bassa_Vah + 0x16AF6, # .. 0x16AFF ; Unknown + 0x16B00, # .. 0x16B45 ; Pahawh_Hmong + 0x16B46, # .. 0x16B4F ; Unknown + 0x16B50, # .. 0x16B59 ; Pahawh_Hmong + 0x16B5A, # .. 0x16B5A ; Unknown + 0x16B5B, # .. 0x16B61 ; Pahawh_Hmong + 0x16B62, # .. 0x16B62 ; Unknown + 0x16B63, # .. 0x16B77 ; Pahawh_Hmong + 0x16B78, # .. 0x16B7C ; Unknown + 0x16B7D, # .. 0x16B8F ; Pahawh_Hmong + 0x16B90, # .. 0x16D3F ; Unknown + 0x16D40, # .. 0x16D79 ; Kirat_Rai + 0x16D7A, # .. 0x16E3F ; Unknown + 0x16E40, # .. 0x16E9A ; Medefaidrin + 0x16E9B, # .. 0x16E9F ; Unknown + 0x16EA0, # .. 0x16EB8 ; Beria_Erfe + 0x16EB9, # .. 0x16EBA ; Unknown + 0x16EBB, # .. 0x16ED3 ; Beria_Erfe + 0x16ED4, # .. 0x16EFF ; Unknown + 0x16F00, # .. 0x16F4A ; Miao + 0x16F4B, # .. 0x16F4E ; Unknown + 0x16F4F, # .. 0x16F87 ; Miao + 0x16F88, # .. 0x16F8E ; Unknown + 0x16F8F, # .. 0x16F9F ; Miao + 0x16FA0, # .. 0x16FDF ; Unknown + 0x16FE0, # .. 0x16FE0 ; Tangut + 0x16FE1, # .. 0x16FE1 ; Nushu + 0x16FE2, # .. 0x16FE3 ; Han + 0x16FE4, # .. 0x16FE4 ; Khitan_Small_Script + 0x16FE5, # .. 0x16FEF ; Unknown + 0x16FF0, # .. 0x16FF6 ; Han + 0x16FF7, # .. 0x16FFF ; Unknown + 0x17000, # .. 0x18AFF ; Tangut + 0x18B00, # .. 0x18CD5 ; Khitan_Small_Script + 0x18CD6, # .. 0x18CFE ; Unknown + 0x18CFF, # .. 0x18CFF ; Khitan_Small_Script + 0x18D00, # .. 0x18D1E ; Tangut + 0x18D1F, # .. 0x18D7F ; Unknown + 0x18D80, # .. 0x18DF2 ; Tangut + 0x18DF3, # .. 0x1AFEF ; Unknown + 0x1AFF0, # .. 0x1AFF3 ; Katakana + 0x1AFF4, # .. 0x1AFF4 ; Unknown + 0x1AFF5, # .. 0x1AFFB ; Katakana + 0x1AFFC, # .. 0x1AFFC ; Unknown + 0x1AFFD, # .. 0x1AFFE ; Katakana + 0x1AFFF, # .. 0x1AFFF ; Unknown + 0x1B000, # .. 0x1B000 ; Katakana + 0x1B001, # .. 0x1B11F ; Hiragana + 0x1B120, # .. 0x1B122 ; Katakana + 0x1B123, # .. 0x1B131 ; Unknown + 0x1B132, # .. 0x1B132 ; Hiragana + 0x1B133, # .. 0x1B14F ; Unknown + 0x1B150, # .. 0x1B152 ; Hiragana + 0x1B153, # .. 0x1B154 ; Unknown + 0x1B155, # .. 0x1B155 ; Katakana + 0x1B156, # .. 0x1B163 ; Unknown + 0x1B164, # .. 0x1B167 ; Katakana + 0x1B168, # .. 0x1B16F ; Unknown + 0x1B170, # .. 0x1B2FB ; Nushu + 0x1B2FC, # .. 0x1BBFF ; Unknown + 0x1BC00, # .. 0x1BC6A ; Duployan + 0x1BC6B, # .. 0x1BC6F ; Unknown + 0x1BC70, # .. 0x1BC7C ; Duployan + 0x1BC7D, # .. 0x1BC7F ; Unknown + 0x1BC80, # .. 0x1BC88 ; Duployan + 0x1BC89, # .. 0x1BC8F ; Unknown + 0x1BC90, # .. 0x1BC99 ; Duployan + 0x1BC9A, # .. 0x1BC9B ; Unknown + 0x1BC9C, # .. 0x1BC9F ; Duployan + 0x1BCA0, # .. 0x1BCA3 ; Common + 0x1BCA4, # .. 0x1CBFF ; Unknown + 0x1CC00, # .. 0x1CCFC ; Common + 0x1CCFD, # .. 0x1CCFF ; Unknown + 0x1CD00, # .. 0x1CEB3 ; Common + 0x1CEB4, # .. 0x1CEB9 ; Unknown + 0x1CEBA, # .. 0x1CED0 ; Common + 0x1CED1, # .. 0x1CEDF ; Unknown + 0x1CEE0, # .. 0x1CEF0 ; Common + 0x1CEF1, # .. 0x1CEFF ; Unknown + 0x1CF00, # .. 0x1CF2D ; Inherited + 0x1CF2E, # .. 0x1CF2F ; Unknown + 0x1CF30, # .. 0x1CF46 ; Inherited + 0x1CF47, # .. 0x1CF4F ; Unknown + 0x1CF50, # .. 0x1CFC3 ; Common + 0x1CFC4, # .. 0x1CFFF ; Unknown + 0x1D000, # .. 0x1D0F5 ; Common + 0x1D0F6, # .. 0x1D0FF ; Unknown + 0x1D100, # .. 0x1D126 ; Common + 0x1D127, # .. 0x1D128 ; Unknown + 0x1D129, # .. 0x1D166 ; Common + 0x1D167, # .. 0x1D169 ; Inherited + 0x1D16A, # .. 0x1D17A ; Common + 0x1D17B, # .. 0x1D182 ; Inherited + 0x1D183, # .. 0x1D184 ; Common + 0x1D185, # .. 0x1D18B ; Inherited + 0x1D18C, # .. 0x1D1A9 ; Common + 0x1D1AA, # .. 0x1D1AD ; Inherited + 0x1D1AE, # .. 0x1D1EA ; Common + 0x1D1EB, # .. 0x1D1FF ; Unknown + 0x1D200, # .. 0x1D245 ; Greek + 0x1D246, # .. 0x1D2BF ; Unknown + 0x1D2C0, # .. 0x1D2D3 ; Common + 0x1D2D4, # .. 0x1D2DF ; Unknown + 0x1D2E0, # .. 0x1D2F3 ; Common + 0x1D2F4, # .. 0x1D2FF ; Unknown + 0x1D300, # .. 0x1D356 ; Common + 0x1D357, # .. 0x1D35F ; Unknown + 0x1D360, # .. 0x1D378 ; Common + 0x1D379, # .. 0x1D3FF ; Unknown + 0x1D400, # .. 0x1D454 ; Common + 0x1D455, # .. 0x1D455 ; Unknown + 0x1D456, # .. 0x1D49C ; Common + 0x1D49D, # .. 0x1D49D ; Unknown + 0x1D49E, # .. 0x1D49F ; Common + 0x1D4A0, # .. 0x1D4A1 ; Unknown + 0x1D4A2, # .. 0x1D4A2 ; Common + 0x1D4A3, # .. 0x1D4A4 ; Unknown + 0x1D4A5, # .. 0x1D4A6 ; Common + 0x1D4A7, # .. 0x1D4A8 ; Unknown + 0x1D4A9, # .. 0x1D4AC ; Common + 0x1D4AD, # .. 0x1D4AD ; Unknown + 0x1D4AE, # .. 0x1D4B9 ; Common + 0x1D4BA, # .. 0x1D4BA ; Unknown + 0x1D4BB, # .. 0x1D4BB ; Common + 0x1D4BC, # .. 0x1D4BC ; Unknown + 0x1D4BD, # .. 0x1D4C3 ; Common + 0x1D4C4, # .. 0x1D4C4 ; Unknown + 0x1D4C5, # .. 0x1D505 ; Common + 0x1D506, # .. 0x1D506 ; Unknown + 0x1D507, # .. 0x1D50A ; Common + 0x1D50B, # .. 0x1D50C ; Unknown + 0x1D50D, # .. 0x1D514 ; Common + 0x1D515, # .. 0x1D515 ; Unknown + 0x1D516, # .. 0x1D51C ; Common + 0x1D51D, # .. 0x1D51D ; Unknown + 0x1D51E, # .. 0x1D539 ; Common + 0x1D53A, # .. 0x1D53A ; Unknown + 0x1D53B, # .. 0x1D53E ; Common + 0x1D53F, # .. 0x1D53F ; Unknown + 0x1D540, # .. 0x1D544 ; Common + 0x1D545, # .. 0x1D545 ; Unknown + 0x1D546, # .. 0x1D546 ; Common + 0x1D547, # .. 0x1D549 ; Unknown + 0x1D54A, # .. 0x1D550 ; Common + 0x1D551, # .. 0x1D551 ; Unknown + 0x1D552, # .. 0x1D6A5 ; Common + 0x1D6A6, # .. 0x1D6A7 ; Unknown + 0x1D6A8, # .. 0x1D7CB ; Common + 0x1D7CC, # .. 0x1D7CD ; Unknown + 0x1D7CE, # .. 0x1D7FF ; Common + 0x1D800, # .. 0x1DA8B ; SignWriting + 0x1DA8C, # .. 0x1DA9A ; Unknown + 0x1DA9B, # .. 0x1DA9F ; SignWriting + 0x1DAA0, # .. 0x1DAA0 ; Unknown + 0x1DAA1, # .. 0x1DAAF ; SignWriting + 0x1DAB0, # .. 0x1DEFF ; Unknown + 0x1DF00, # .. 0x1DF1E ; Latin + 0x1DF1F, # .. 0x1DF24 ; Unknown + 0x1DF25, # .. 0x1DF2A ; Latin + 0x1DF2B, # .. 0x1DFFF ; Unknown + 0x1E000, # .. 0x1E006 ; Glagolitic + 0x1E007, # .. 0x1E007 ; Unknown + 0x1E008, # .. 0x1E018 ; Glagolitic + 0x1E019, # .. 0x1E01A ; Unknown + 0x1E01B, # .. 0x1E021 ; Glagolitic + 0x1E022, # .. 0x1E022 ; Unknown + 0x1E023, # .. 0x1E024 ; Glagolitic + 0x1E025, # .. 0x1E025 ; Unknown + 0x1E026, # .. 0x1E02A ; Glagolitic + 0x1E02B, # .. 0x1E02F ; Unknown + 0x1E030, # .. 0x1E06D ; Cyrillic + 0x1E06E, # .. 0x1E08E ; Unknown + 0x1E08F, # .. 0x1E08F ; Cyrillic + 0x1E090, # .. 0x1E0FF ; Unknown + 0x1E100, # .. 0x1E12C ; Nyiakeng_Puachue_Hmong + 0x1E12D, # .. 0x1E12F ; Unknown + 0x1E130, # .. 0x1E13D ; Nyiakeng_Puachue_Hmong + 0x1E13E, # .. 0x1E13F ; Unknown + 0x1E140, # .. 0x1E149 ; Nyiakeng_Puachue_Hmong + 0x1E14A, # .. 0x1E14D ; Unknown + 0x1E14E, # .. 0x1E14F ; Nyiakeng_Puachue_Hmong + 0x1E150, # .. 0x1E28F ; Unknown + 0x1E290, # .. 0x1E2AE ; Toto + 0x1E2AF, # .. 0x1E2BF ; Unknown + 0x1E2C0, # .. 0x1E2F9 ; Wancho + 0x1E2FA, # .. 0x1E2FE ; Unknown + 0x1E2FF, # .. 0x1E2FF ; Wancho + 0x1E300, # .. 0x1E4CF ; Unknown + 0x1E4D0, # .. 0x1E4F9 ; Nag_Mundari + 0x1E4FA, # .. 0x1E5CF ; Unknown + 0x1E5D0, # .. 0x1E5FA ; Ol_Onal + 0x1E5FB, # .. 0x1E5FE ; Unknown + 0x1E5FF, # .. 0x1E5FF ; Ol_Onal + 0x1E600, # .. 0x1E6BF ; Unknown + 0x1E6C0, # .. 0x1E6DE ; Tai_Yo + 0x1E6DF, # .. 0x1E6DF ; Unknown + 0x1E6E0, # .. 0x1E6F5 ; Tai_Yo + 0x1E6F6, # .. 0x1E6FD ; Unknown + 0x1E6FE, # .. 0x1E6FF ; Tai_Yo + 0x1E700, # .. 0x1E7DF ; Unknown + 0x1E7E0, # .. 0x1E7E6 ; Ethiopic + 0x1E7E7, # .. 0x1E7E7 ; Unknown + 0x1E7E8, # .. 0x1E7EB ; Ethiopic + 0x1E7EC, # .. 0x1E7EC ; Unknown + 0x1E7ED, # .. 0x1E7EE ; Ethiopic + 0x1E7EF, # .. 0x1E7EF ; Unknown + 0x1E7F0, # .. 0x1E7FE ; Ethiopic + 0x1E7FF, # .. 0x1E7FF ; Unknown + 0x1E800, # .. 0x1E8C4 ; Mende_Kikakui + 0x1E8C5, # .. 0x1E8C6 ; Unknown + 0x1E8C7, # .. 0x1E8D6 ; Mende_Kikakui + 0x1E8D7, # .. 0x1E8FF ; Unknown + 0x1E900, # .. 0x1E94B ; Adlam + 0x1E94C, # .. 0x1E94F ; Unknown + 0x1E950, # .. 0x1E959 ; Adlam + 0x1E95A, # .. 0x1E95D ; Unknown + 0x1E95E, # .. 0x1E95F ; Adlam + 0x1E960, # .. 0x1EC70 ; Unknown + 0x1EC71, # .. 0x1ECB4 ; Common + 0x1ECB5, # .. 0x1ED00 ; Unknown + 0x1ED01, # .. 0x1ED3D ; Common + 0x1ED3E, # .. 0x1EDFF ; Unknown + 0x1EE00, # .. 0x1EE03 ; Arabic + 0x1EE04, # .. 0x1EE04 ; Unknown + 0x1EE05, # .. 0x1EE1F ; Arabic + 0x1EE20, # .. 0x1EE20 ; Unknown + 0x1EE21, # .. 0x1EE22 ; Arabic + 0x1EE23, # .. 0x1EE23 ; Unknown + 0x1EE24, # .. 0x1EE24 ; Arabic + 0x1EE25, # .. 0x1EE26 ; Unknown + 0x1EE27, # .. 0x1EE27 ; Arabic + 0x1EE28, # .. 0x1EE28 ; Unknown + 0x1EE29, # .. 0x1EE32 ; Arabic + 0x1EE33, # .. 0x1EE33 ; Unknown + 0x1EE34, # .. 0x1EE37 ; Arabic + 0x1EE38, # .. 0x1EE38 ; Unknown + 0x1EE39, # .. 0x1EE39 ; Arabic + 0x1EE3A, # .. 0x1EE3A ; Unknown + 0x1EE3B, # .. 0x1EE3B ; Arabic + 0x1EE3C, # .. 0x1EE41 ; Unknown + 0x1EE42, # .. 0x1EE42 ; Arabic + 0x1EE43, # .. 0x1EE46 ; Unknown + 0x1EE47, # .. 0x1EE47 ; Arabic + 0x1EE48, # .. 0x1EE48 ; Unknown + 0x1EE49, # .. 0x1EE49 ; Arabic + 0x1EE4A, # .. 0x1EE4A ; Unknown + 0x1EE4B, # .. 0x1EE4B ; Arabic + 0x1EE4C, # .. 0x1EE4C ; Unknown + 0x1EE4D, # .. 0x1EE4F ; Arabic + 0x1EE50, # .. 0x1EE50 ; Unknown + 0x1EE51, # .. 0x1EE52 ; Arabic + 0x1EE53, # .. 0x1EE53 ; Unknown + 0x1EE54, # .. 0x1EE54 ; Arabic + 0x1EE55, # .. 0x1EE56 ; Unknown + 0x1EE57, # .. 0x1EE57 ; Arabic + 0x1EE58, # .. 0x1EE58 ; Unknown + 0x1EE59, # .. 0x1EE59 ; Arabic + 0x1EE5A, # .. 0x1EE5A ; Unknown + 0x1EE5B, # .. 0x1EE5B ; Arabic + 0x1EE5C, # .. 0x1EE5C ; Unknown + 0x1EE5D, # .. 0x1EE5D ; Arabic + 0x1EE5E, # .. 0x1EE5E ; Unknown + 0x1EE5F, # .. 0x1EE5F ; Arabic + 0x1EE60, # .. 0x1EE60 ; Unknown + 0x1EE61, # .. 0x1EE62 ; Arabic + 0x1EE63, # .. 0x1EE63 ; Unknown + 0x1EE64, # .. 0x1EE64 ; Arabic + 0x1EE65, # .. 0x1EE66 ; Unknown + 0x1EE67, # .. 0x1EE6A ; Arabic + 0x1EE6B, # .. 0x1EE6B ; Unknown + 0x1EE6C, # .. 0x1EE72 ; Arabic + 0x1EE73, # .. 0x1EE73 ; Unknown + 0x1EE74, # .. 0x1EE77 ; Arabic + 0x1EE78, # .. 0x1EE78 ; Unknown + 0x1EE79, # .. 0x1EE7C ; Arabic + 0x1EE7D, # .. 0x1EE7D ; Unknown + 0x1EE7E, # .. 0x1EE7E ; Arabic + 0x1EE7F, # .. 0x1EE7F ; Unknown + 0x1EE80, # .. 0x1EE89 ; Arabic + 0x1EE8A, # .. 0x1EE8A ; Unknown + 0x1EE8B, # .. 0x1EE9B ; Arabic + 0x1EE9C, # .. 0x1EEA0 ; Unknown + 0x1EEA1, # .. 0x1EEA3 ; Arabic + 0x1EEA4, # .. 0x1EEA4 ; Unknown + 0x1EEA5, # .. 0x1EEA9 ; Arabic + 0x1EEAA, # .. 0x1EEAA ; Unknown + 0x1EEAB, # .. 0x1EEBB ; Arabic + 0x1EEBC, # .. 0x1EEEF ; Unknown + 0x1EEF0, # .. 0x1EEF1 ; Arabic + 0x1EEF2, # .. 0x1EFFF ; Unknown + 0x1F000, # .. 0x1F02B ; Common + 0x1F02C, # .. 0x1F02F ; Unknown + 0x1F030, # .. 0x1F093 ; Common + 0x1F094, # .. 0x1F09F ; Unknown + 0x1F0A0, # .. 0x1F0AE ; Common + 0x1F0AF, # .. 0x1F0B0 ; Unknown + 0x1F0B1, # .. 0x1F0BF ; Common + 0x1F0C0, # .. 0x1F0C0 ; Unknown + 0x1F0C1, # .. 0x1F0CF ; Common + 0x1F0D0, # .. 0x1F0D0 ; Unknown + 0x1F0D1, # .. 0x1F0F5 ; Common + 0x1F0F6, # .. 0x1F0FF ; Unknown + 0x1F100, # .. 0x1F1AD ; Common + 0x1F1AE, # .. 0x1F1E5 ; Unknown + 0x1F1E6, # .. 0x1F1FF ; Common + 0x1F200, # .. 0x1F200 ; Hiragana + 0x1F201, # .. 0x1F202 ; Common + 0x1F203, # .. 0x1F20F ; Unknown + 0x1F210, # .. 0x1F23B ; Common + 0x1F23C, # .. 0x1F23F ; Unknown + 0x1F240, # .. 0x1F248 ; Common + 0x1F249, # .. 0x1F24F ; Unknown + 0x1F250, # .. 0x1F251 ; Common + 0x1F252, # .. 0x1F25F ; Unknown + 0x1F260, # .. 0x1F265 ; Common + 0x1F266, # .. 0x1F2FF ; Unknown + 0x1F300, # .. 0x1F6D8 ; Common + 0x1F6D9, # .. 0x1F6DB ; Unknown + 0x1F6DC, # .. 0x1F6EC ; Common + 0x1F6ED, # .. 0x1F6EF ; Unknown + 0x1F6F0, # .. 0x1F6FC ; Common + 0x1F6FD, # .. 0x1F6FF ; Unknown + 0x1F700, # .. 0x1F7D9 ; Common + 0x1F7DA, # .. 0x1F7DF ; Unknown + 0x1F7E0, # .. 0x1F7EB ; Common + 0x1F7EC, # .. 0x1F7EF ; Unknown + 0x1F7F0, # .. 0x1F7F0 ; Common + 0x1F7F1, # .. 0x1F7FF ; Unknown + 0x1F800, # .. 0x1F80B ; Common + 0x1F80C, # .. 0x1F80F ; Unknown + 0x1F810, # .. 0x1F847 ; Common + 0x1F848, # .. 0x1F84F ; Unknown + 0x1F850, # .. 0x1F859 ; Common + 0x1F85A, # .. 0x1F85F ; Unknown + 0x1F860, # .. 0x1F887 ; Common + 0x1F888, # .. 0x1F88F ; Unknown + 0x1F890, # .. 0x1F8AD ; Common + 0x1F8AE, # .. 0x1F8AF ; Unknown + 0x1F8B0, # .. 0x1F8BB ; Common + 0x1F8BC, # .. 0x1F8BF ; Unknown + 0x1F8C0, # .. 0x1F8C1 ; Common + 0x1F8C2, # .. 0x1F8CF ; Unknown + 0x1F8D0, # .. 0x1F8D8 ; Common + 0x1F8D9, # .. 0x1F8FF ; Unknown + 0x1F900, # .. 0x1FA57 ; Common + 0x1FA58, # .. 0x1FA5F ; Unknown + 0x1FA60, # .. 0x1FA6D ; Common + 0x1FA6E, # .. 0x1FA6F ; Unknown + 0x1FA70, # .. 0x1FA7C ; Common + 0x1FA7D, # .. 0x1FA7F ; Unknown + 0x1FA80, # .. 0x1FA8A ; Common + 0x1FA8B, # .. 0x1FA8D ; Unknown + 0x1FA8E, # .. 0x1FAC6 ; Common + 0x1FAC7, # .. 0x1FAC7 ; Unknown + 0x1FAC8, # .. 0x1FAC8 ; Common + 0x1FAC9, # .. 0x1FACC ; Unknown + 0x1FACD, # .. 0x1FADC ; Common + 0x1FADD, # .. 0x1FADE ; Unknown + 0x1FADF, # .. 0x1FAEA ; Common + 0x1FAEB, # .. 0x1FAEE ; Unknown + 0x1FAEF, # .. 0x1FAF8 ; Common + 0x1FAF9, # .. 0x1FAFF ; Unknown + 0x1FB00, # .. 0x1FB92 ; Common + 0x1FB93, # .. 0x1FB93 ; Unknown + 0x1FB94, # .. 0x1FBFA ; Common + 0x1FBFB, # .. 0x1FFFF ; Unknown + 0x20000, # .. 0x2A6DF ; Han + 0x2A6E0, # .. 0x2A6FF ; Unknown + 0x2A700, # .. 0x2B81D ; Han + 0x2B81E, # .. 0x2B81F ; Unknown + 0x2B820, # .. 0x2CEAD ; Han + 0x2CEAE, # .. 0x2CEAF ; Unknown + 0x2CEB0, # .. 0x2EBE0 ; Han + 0x2EBE1, # .. 0x2EBEF ; Unknown + 0x2EBF0, # .. 0x2EE5D ; Han + 0x2EE5E, # .. 0x2F7FF ; Unknown + 0x2F800, # .. 0x2FA1D ; Han + 0x2FA1E, # .. 0x2FFFF ; Unknown + 0x30000, # .. 0x3134A ; Han + 0x3134B, # .. 0x3134F ; Unknown + 0x31350, # .. 0x33479 ; Han + 0x3347A, # .. 0xE0000 ; Unknown + 0xE0001, # .. 0xE0001 ; Common + 0xE0002, # .. 0xE001F ; Unknown + 0xE0020, # .. 0xE007F ; Common + 0xE0080, # .. 0xE00FF ; Unknown + 0xE0100, # .. 0xE01EF ; Inherited + 0xE01F0, # .. 0x10FFFF ; Unknown +] + +VALUES = [ + "Zyyy", # 0000..0040 ; Common + "Latn", # 0041..005A ; Latin + "Zyyy", # 005B..0060 ; Common + "Latn", # 0061..007A ; Latin + "Zyyy", # 007B..00A9 ; Common + "Latn", # 00AA..00AA ; Latin + "Zyyy", # 00AB..00B9 ; Common + "Latn", # 00BA..00BA ; Latin + "Zyyy", # 00BB..00BF ; Common + "Latn", # 00C0..00D6 ; Latin + "Zyyy", # 00D7..00D7 ; Common + "Latn", # 00D8..00F6 ; Latin + "Zyyy", # 00F7..00F7 ; Common + "Latn", # 00F8..02B8 ; Latin + "Zyyy", # 02B9..02DF ; Common + "Latn", # 02E0..02E4 ; Latin + "Zyyy", # 02E5..02E9 ; Common + "Bopo", # 02EA..02EB ; Bopomofo + "Zyyy", # 02EC..02FF ; Common + "Zinh", # 0300..036F ; Inherited + "Grek", # 0370..0373 ; Greek + "Zyyy", # 0374..0374 ; Common + "Grek", # 0375..0377 ; Greek + "Zzzz", # 0378..0379 ; Unknown + "Grek", # 037A..037D ; Greek + "Zyyy", # 037E..037E ; Common + "Grek", # 037F..037F ; Greek + "Zzzz", # 0380..0383 ; Unknown + "Grek", # 0384..0384 ; Greek + "Zyyy", # 0385..0385 ; Common + "Grek", # 0386..0386 ; Greek + "Zyyy", # 0387..0387 ; Common + "Grek", # 0388..038A ; Greek + "Zzzz", # 038B..038B ; Unknown + "Grek", # 038C..038C ; Greek + "Zzzz", # 038D..038D ; Unknown + "Grek", # 038E..03A1 ; Greek + "Zzzz", # 03A2..03A2 ; Unknown + "Grek", # 03A3..03E1 ; Greek + "Copt", # 03E2..03EF ; Coptic + "Grek", # 03F0..03FF ; Greek + "Cyrl", # 0400..0484 ; Cyrillic + "Zinh", # 0485..0486 ; Inherited + "Cyrl", # 0487..052F ; Cyrillic + "Zzzz", # 0530..0530 ; Unknown + "Armn", # 0531..0556 ; Armenian + "Zzzz", # 0557..0558 ; Unknown + "Armn", # 0559..058A ; Armenian + "Zzzz", # 058B..058C ; Unknown + "Armn", # 058D..058F ; Armenian + "Zzzz", # 0590..0590 ; Unknown + "Hebr", # 0591..05C7 ; Hebrew + "Zzzz", # 05C8..05CF ; Unknown + "Hebr", # 05D0..05EA ; Hebrew + "Zzzz", # 05EB..05EE ; Unknown + "Hebr", # 05EF..05F4 ; Hebrew + "Zzzz", # 05F5..05FF ; Unknown + "Arab", # 0600..0604 ; Arabic + "Zyyy", # 0605..0605 ; Common + "Arab", # 0606..060B ; Arabic + "Zyyy", # 060C..060C ; Common + "Arab", # 060D..061A ; Arabic + "Zyyy", # 061B..061B ; Common + "Arab", # 061C..061E ; Arabic + "Zyyy", # 061F..061F ; Common + "Arab", # 0620..063F ; Arabic + "Zyyy", # 0640..0640 ; Common + "Arab", # 0641..064A ; Arabic + "Zinh", # 064B..0655 ; Inherited + "Arab", # 0656..066F ; Arabic + "Zinh", # 0670..0670 ; Inherited + "Arab", # 0671..06DC ; Arabic + "Zyyy", # 06DD..06DD ; Common + "Arab", # 06DE..06FF ; Arabic + "Syrc", # 0700..070D ; Syriac + "Zzzz", # 070E..070E ; Unknown + "Syrc", # 070F..074A ; Syriac + "Zzzz", # 074B..074C ; Unknown + "Syrc", # 074D..074F ; Syriac + "Arab", # 0750..077F ; Arabic + "Thaa", # 0780..07B1 ; Thaana + "Zzzz", # 07B2..07BF ; Unknown + "Nkoo", # 07C0..07FA ; Nko + "Zzzz", # 07FB..07FC ; Unknown + "Nkoo", # 07FD..07FF ; Nko + "Samr", # 0800..082D ; Samaritan + "Zzzz", # 082E..082F ; Unknown + "Samr", # 0830..083E ; Samaritan + "Zzzz", # 083F..083F ; Unknown + "Mand", # 0840..085B ; Mandaic + "Zzzz", # 085C..085D ; Unknown + "Mand", # 085E..085E ; Mandaic + "Zzzz", # 085F..085F ; Unknown + "Syrc", # 0860..086A ; Syriac + "Zzzz", # 086B..086F ; Unknown + "Arab", # 0870..0891 ; Arabic + "Zzzz", # 0892..0896 ; Unknown + "Arab", # 0897..08E1 ; Arabic + "Zyyy", # 08E2..08E2 ; Common + "Arab", # 08E3..08FF ; Arabic + "Deva", # 0900..0950 ; Devanagari + "Zinh", # 0951..0954 ; Inherited + "Deva", # 0955..0963 ; Devanagari + "Zyyy", # 0964..0965 ; Common + "Deva", # 0966..097F ; Devanagari + "Beng", # 0980..0983 ; Bengali + "Zzzz", # 0984..0984 ; Unknown + "Beng", # 0985..098C ; Bengali + "Zzzz", # 098D..098E ; Unknown + "Beng", # 098F..0990 ; Bengali + "Zzzz", # 0991..0992 ; Unknown + "Beng", # 0993..09A8 ; Bengali + "Zzzz", # 09A9..09A9 ; Unknown + "Beng", # 09AA..09B0 ; Bengali + "Zzzz", # 09B1..09B1 ; Unknown + "Beng", # 09B2..09B2 ; Bengali + "Zzzz", # 09B3..09B5 ; Unknown + "Beng", # 09B6..09B9 ; Bengali + "Zzzz", # 09BA..09BB ; Unknown + "Beng", # 09BC..09C4 ; Bengali + "Zzzz", # 09C5..09C6 ; Unknown + "Beng", # 09C7..09C8 ; Bengali + "Zzzz", # 09C9..09CA ; Unknown + "Beng", # 09CB..09CE ; Bengali + "Zzzz", # 09CF..09D6 ; Unknown + "Beng", # 09D7..09D7 ; Bengali + "Zzzz", # 09D8..09DB ; Unknown + "Beng", # 09DC..09DD ; Bengali + "Zzzz", # 09DE..09DE ; Unknown + "Beng", # 09DF..09E3 ; Bengali + "Zzzz", # 09E4..09E5 ; Unknown + "Beng", # 09E6..09FE ; Bengali + "Zzzz", # 09FF..0A00 ; Unknown + "Guru", # 0A01..0A03 ; Gurmukhi + "Zzzz", # 0A04..0A04 ; Unknown + "Guru", # 0A05..0A0A ; Gurmukhi + "Zzzz", # 0A0B..0A0E ; Unknown + "Guru", # 0A0F..0A10 ; Gurmukhi + "Zzzz", # 0A11..0A12 ; Unknown + "Guru", # 0A13..0A28 ; Gurmukhi + "Zzzz", # 0A29..0A29 ; Unknown + "Guru", # 0A2A..0A30 ; Gurmukhi + "Zzzz", # 0A31..0A31 ; Unknown + "Guru", # 0A32..0A33 ; Gurmukhi + "Zzzz", # 0A34..0A34 ; Unknown + "Guru", # 0A35..0A36 ; Gurmukhi + "Zzzz", # 0A37..0A37 ; Unknown + "Guru", # 0A38..0A39 ; Gurmukhi + "Zzzz", # 0A3A..0A3B ; Unknown + "Guru", # 0A3C..0A3C ; Gurmukhi + "Zzzz", # 0A3D..0A3D ; Unknown + "Guru", # 0A3E..0A42 ; Gurmukhi + "Zzzz", # 0A43..0A46 ; Unknown + "Guru", # 0A47..0A48 ; Gurmukhi + "Zzzz", # 0A49..0A4A ; Unknown + "Guru", # 0A4B..0A4D ; Gurmukhi + "Zzzz", # 0A4E..0A50 ; Unknown + "Guru", # 0A51..0A51 ; Gurmukhi + "Zzzz", # 0A52..0A58 ; Unknown + "Guru", # 0A59..0A5C ; Gurmukhi + "Zzzz", # 0A5D..0A5D ; Unknown + "Guru", # 0A5E..0A5E ; Gurmukhi + "Zzzz", # 0A5F..0A65 ; Unknown + "Guru", # 0A66..0A76 ; Gurmukhi + "Zzzz", # 0A77..0A80 ; Unknown + "Gujr", # 0A81..0A83 ; Gujarati + "Zzzz", # 0A84..0A84 ; Unknown + "Gujr", # 0A85..0A8D ; Gujarati + "Zzzz", # 0A8E..0A8E ; Unknown + "Gujr", # 0A8F..0A91 ; Gujarati + "Zzzz", # 0A92..0A92 ; Unknown + "Gujr", # 0A93..0AA8 ; Gujarati + "Zzzz", # 0AA9..0AA9 ; Unknown + "Gujr", # 0AAA..0AB0 ; Gujarati + "Zzzz", # 0AB1..0AB1 ; Unknown + "Gujr", # 0AB2..0AB3 ; Gujarati + "Zzzz", # 0AB4..0AB4 ; Unknown + "Gujr", # 0AB5..0AB9 ; Gujarati + "Zzzz", # 0ABA..0ABB ; Unknown + "Gujr", # 0ABC..0AC5 ; Gujarati + "Zzzz", # 0AC6..0AC6 ; Unknown + "Gujr", # 0AC7..0AC9 ; Gujarati + "Zzzz", # 0ACA..0ACA ; Unknown + "Gujr", # 0ACB..0ACD ; Gujarati + "Zzzz", # 0ACE..0ACF ; Unknown + "Gujr", # 0AD0..0AD0 ; Gujarati + "Zzzz", # 0AD1..0ADF ; Unknown + "Gujr", # 0AE0..0AE3 ; Gujarati + "Zzzz", # 0AE4..0AE5 ; Unknown + "Gujr", # 0AE6..0AF1 ; Gujarati + "Zzzz", # 0AF2..0AF8 ; Unknown + "Gujr", # 0AF9..0AFF ; Gujarati + "Zzzz", # 0B00..0B00 ; Unknown + "Orya", # 0B01..0B03 ; Oriya + "Zzzz", # 0B04..0B04 ; Unknown + "Orya", # 0B05..0B0C ; Oriya + "Zzzz", # 0B0D..0B0E ; Unknown + "Orya", # 0B0F..0B10 ; Oriya + "Zzzz", # 0B11..0B12 ; Unknown + "Orya", # 0B13..0B28 ; Oriya + "Zzzz", # 0B29..0B29 ; Unknown + "Orya", # 0B2A..0B30 ; Oriya + "Zzzz", # 0B31..0B31 ; Unknown + "Orya", # 0B32..0B33 ; Oriya + "Zzzz", # 0B34..0B34 ; Unknown + "Orya", # 0B35..0B39 ; Oriya + "Zzzz", # 0B3A..0B3B ; Unknown + "Orya", # 0B3C..0B44 ; Oriya + "Zzzz", # 0B45..0B46 ; Unknown + "Orya", # 0B47..0B48 ; Oriya + "Zzzz", # 0B49..0B4A ; Unknown + "Orya", # 0B4B..0B4D ; Oriya + "Zzzz", # 0B4E..0B54 ; Unknown + "Orya", # 0B55..0B57 ; Oriya + "Zzzz", # 0B58..0B5B ; Unknown + "Orya", # 0B5C..0B5D ; Oriya + "Zzzz", # 0B5E..0B5E ; Unknown + "Orya", # 0B5F..0B63 ; Oriya + "Zzzz", # 0B64..0B65 ; Unknown + "Orya", # 0B66..0B77 ; Oriya + "Zzzz", # 0B78..0B81 ; Unknown + "Taml", # 0B82..0B83 ; Tamil + "Zzzz", # 0B84..0B84 ; Unknown + "Taml", # 0B85..0B8A ; Tamil + "Zzzz", # 0B8B..0B8D ; Unknown + "Taml", # 0B8E..0B90 ; Tamil + "Zzzz", # 0B91..0B91 ; Unknown + "Taml", # 0B92..0B95 ; Tamil + "Zzzz", # 0B96..0B98 ; Unknown + "Taml", # 0B99..0B9A ; Tamil + "Zzzz", # 0B9B..0B9B ; Unknown + "Taml", # 0B9C..0B9C ; Tamil + "Zzzz", # 0B9D..0B9D ; Unknown + "Taml", # 0B9E..0B9F ; Tamil + "Zzzz", # 0BA0..0BA2 ; Unknown + "Taml", # 0BA3..0BA4 ; Tamil + "Zzzz", # 0BA5..0BA7 ; Unknown + "Taml", # 0BA8..0BAA ; Tamil + "Zzzz", # 0BAB..0BAD ; Unknown + "Taml", # 0BAE..0BB9 ; Tamil + "Zzzz", # 0BBA..0BBD ; Unknown + "Taml", # 0BBE..0BC2 ; Tamil + "Zzzz", # 0BC3..0BC5 ; Unknown + "Taml", # 0BC6..0BC8 ; Tamil + "Zzzz", # 0BC9..0BC9 ; Unknown + "Taml", # 0BCA..0BCD ; Tamil + "Zzzz", # 0BCE..0BCF ; Unknown + "Taml", # 0BD0..0BD0 ; Tamil + "Zzzz", # 0BD1..0BD6 ; Unknown + "Taml", # 0BD7..0BD7 ; Tamil + "Zzzz", # 0BD8..0BE5 ; Unknown + "Taml", # 0BE6..0BFA ; Tamil + "Zzzz", # 0BFB..0BFF ; Unknown + "Telu", # 0C00..0C0C ; Telugu + "Zzzz", # 0C0D..0C0D ; Unknown + "Telu", # 0C0E..0C10 ; Telugu + "Zzzz", # 0C11..0C11 ; Unknown + "Telu", # 0C12..0C28 ; Telugu + "Zzzz", # 0C29..0C29 ; Unknown + "Telu", # 0C2A..0C39 ; Telugu + "Zzzz", # 0C3A..0C3B ; Unknown + "Telu", # 0C3C..0C44 ; Telugu + "Zzzz", # 0C45..0C45 ; Unknown + "Telu", # 0C46..0C48 ; Telugu + "Zzzz", # 0C49..0C49 ; Unknown + "Telu", # 0C4A..0C4D ; Telugu + "Zzzz", # 0C4E..0C54 ; Unknown + "Telu", # 0C55..0C56 ; Telugu + "Zzzz", # 0C57..0C57 ; Unknown + "Telu", # 0C58..0C5A ; Telugu + "Zzzz", # 0C5B..0C5B ; Unknown + "Telu", # 0C5C..0C5D ; Telugu + "Zzzz", # 0C5E..0C5F ; Unknown + "Telu", # 0C60..0C63 ; Telugu + "Zzzz", # 0C64..0C65 ; Unknown + "Telu", # 0C66..0C6F ; Telugu + "Zzzz", # 0C70..0C76 ; Unknown + "Telu", # 0C77..0C7F ; Telugu + "Knda", # 0C80..0C8C ; Kannada + "Zzzz", # 0C8D..0C8D ; Unknown + "Knda", # 0C8E..0C90 ; Kannada + "Zzzz", # 0C91..0C91 ; Unknown + "Knda", # 0C92..0CA8 ; Kannada + "Zzzz", # 0CA9..0CA9 ; Unknown + "Knda", # 0CAA..0CB3 ; Kannada + "Zzzz", # 0CB4..0CB4 ; Unknown + "Knda", # 0CB5..0CB9 ; Kannada + "Zzzz", # 0CBA..0CBB ; Unknown + "Knda", # 0CBC..0CC4 ; Kannada + "Zzzz", # 0CC5..0CC5 ; Unknown + "Knda", # 0CC6..0CC8 ; Kannada + "Zzzz", # 0CC9..0CC9 ; Unknown + "Knda", # 0CCA..0CCD ; Kannada + "Zzzz", # 0CCE..0CD4 ; Unknown + "Knda", # 0CD5..0CD6 ; Kannada + "Zzzz", # 0CD7..0CDB ; Unknown + "Knda", # 0CDC..0CDE ; Kannada + "Zzzz", # 0CDF..0CDF ; Unknown + "Knda", # 0CE0..0CE3 ; Kannada + "Zzzz", # 0CE4..0CE5 ; Unknown + "Knda", # 0CE6..0CEF ; Kannada + "Zzzz", # 0CF0..0CF0 ; Unknown + "Knda", # 0CF1..0CF3 ; Kannada + "Zzzz", # 0CF4..0CFF ; Unknown + "Mlym", # 0D00..0D0C ; Malayalam + "Zzzz", # 0D0D..0D0D ; Unknown + "Mlym", # 0D0E..0D10 ; Malayalam + "Zzzz", # 0D11..0D11 ; Unknown + "Mlym", # 0D12..0D44 ; Malayalam + "Zzzz", # 0D45..0D45 ; Unknown + "Mlym", # 0D46..0D48 ; Malayalam + "Zzzz", # 0D49..0D49 ; Unknown + "Mlym", # 0D4A..0D4F ; Malayalam + "Zzzz", # 0D50..0D53 ; Unknown + "Mlym", # 0D54..0D63 ; Malayalam + "Zzzz", # 0D64..0D65 ; Unknown + "Mlym", # 0D66..0D7F ; Malayalam + "Zzzz", # 0D80..0D80 ; Unknown + "Sinh", # 0D81..0D83 ; Sinhala + "Zzzz", # 0D84..0D84 ; Unknown + "Sinh", # 0D85..0D96 ; Sinhala + "Zzzz", # 0D97..0D99 ; Unknown + "Sinh", # 0D9A..0DB1 ; Sinhala + "Zzzz", # 0DB2..0DB2 ; Unknown + "Sinh", # 0DB3..0DBB ; Sinhala + "Zzzz", # 0DBC..0DBC ; Unknown + "Sinh", # 0DBD..0DBD ; Sinhala + "Zzzz", # 0DBE..0DBF ; Unknown + "Sinh", # 0DC0..0DC6 ; Sinhala + "Zzzz", # 0DC7..0DC9 ; Unknown + "Sinh", # 0DCA..0DCA ; Sinhala + "Zzzz", # 0DCB..0DCE ; Unknown + "Sinh", # 0DCF..0DD4 ; Sinhala + "Zzzz", # 0DD5..0DD5 ; Unknown + "Sinh", # 0DD6..0DD6 ; Sinhala + "Zzzz", # 0DD7..0DD7 ; Unknown + "Sinh", # 0DD8..0DDF ; Sinhala + "Zzzz", # 0DE0..0DE5 ; Unknown + "Sinh", # 0DE6..0DEF ; Sinhala + "Zzzz", # 0DF0..0DF1 ; Unknown + "Sinh", # 0DF2..0DF4 ; Sinhala + "Zzzz", # 0DF5..0E00 ; Unknown + "Thai", # 0E01..0E3A ; Thai + "Zzzz", # 0E3B..0E3E ; Unknown + "Zyyy", # 0E3F..0E3F ; Common + "Thai", # 0E40..0E5B ; Thai + "Zzzz", # 0E5C..0E80 ; Unknown + "Laoo", # 0E81..0E82 ; Lao + "Zzzz", # 0E83..0E83 ; Unknown + "Laoo", # 0E84..0E84 ; Lao + "Zzzz", # 0E85..0E85 ; Unknown + "Laoo", # 0E86..0E8A ; Lao + "Zzzz", # 0E8B..0E8B ; Unknown + "Laoo", # 0E8C..0EA3 ; Lao + "Zzzz", # 0EA4..0EA4 ; Unknown + "Laoo", # 0EA5..0EA5 ; Lao + "Zzzz", # 0EA6..0EA6 ; Unknown + "Laoo", # 0EA7..0EBD ; Lao + "Zzzz", # 0EBE..0EBF ; Unknown + "Laoo", # 0EC0..0EC4 ; Lao + "Zzzz", # 0EC5..0EC5 ; Unknown + "Laoo", # 0EC6..0EC6 ; Lao + "Zzzz", # 0EC7..0EC7 ; Unknown + "Laoo", # 0EC8..0ECE ; Lao + "Zzzz", # 0ECF..0ECF ; Unknown + "Laoo", # 0ED0..0ED9 ; Lao + "Zzzz", # 0EDA..0EDB ; Unknown + "Laoo", # 0EDC..0EDF ; Lao + "Zzzz", # 0EE0..0EFF ; Unknown + "Tibt", # 0F00..0F47 ; Tibetan + "Zzzz", # 0F48..0F48 ; Unknown + "Tibt", # 0F49..0F6C ; Tibetan + "Zzzz", # 0F6D..0F70 ; Unknown + "Tibt", # 0F71..0F97 ; Tibetan + "Zzzz", # 0F98..0F98 ; Unknown + "Tibt", # 0F99..0FBC ; Tibetan + "Zzzz", # 0FBD..0FBD ; Unknown + "Tibt", # 0FBE..0FCC ; Tibetan + "Zzzz", # 0FCD..0FCD ; Unknown + "Tibt", # 0FCE..0FD4 ; Tibetan + "Zyyy", # 0FD5..0FD8 ; Common + "Tibt", # 0FD9..0FDA ; Tibetan + "Zzzz", # 0FDB..0FFF ; Unknown + "Mymr", # 1000..109F ; Myanmar + "Geor", # 10A0..10C5 ; Georgian + "Zzzz", # 10C6..10C6 ; Unknown + "Geor", # 10C7..10C7 ; Georgian + "Zzzz", # 10C8..10CC ; Unknown + "Geor", # 10CD..10CD ; Georgian + "Zzzz", # 10CE..10CF ; Unknown + "Geor", # 10D0..10FA ; Georgian + "Zyyy", # 10FB..10FB ; Common + "Geor", # 10FC..10FF ; Georgian + "Hang", # 1100..11FF ; Hangul + "Ethi", # 1200..1248 ; Ethiopic + "Zzzz", # 1249..1249 ; Unknown + "Ethi", # 124A..124D ; Ethiopic + "Zzzz", # 124E..124F ; Unknown + "Ethi", # 1250..1256 ; Ethiopic + "Zzzz", # 1257..1257 ; Unknown + "Ethi", # 1258..1258 ; Ethiopic + "Zzzz", # 1259..1259 ; Unknown + "Ethi", # 125A..125D ; Ethiopic + "Zzzz", # 125E..125F ; Unknown + "Ethi", # 1260..1288 ; Ethiopic + "Zzzz", # 1289..1289 ; Unknown + "Ethi", # 128A..128D ; Ethiopic + "Zzzz", # 128E..128F ; Unknown + "Ethi", # 1290..12B0 ; Ethiopic + "Zzzz", # 12B1..12B1 ; Unknown + "Ethi", # 12B2..12B5 ; Ethiopic + "Zzzz", # 12B6..12B7 ; Unknown + "Ethi", # 12B8..12BE ; Ethiopic + "Zzzz", # 12BF..12BF ; Unknown + "Ethi", # 12C0..12C0 ; Ethiopic + "Zzzz", # 12C1..12C1 ; Unknown + "Ethi", # 12C2..12C5 ; Ethiopic + "Zzzz", # 12C6..12C7 ; Unknown + "Ethi", # 12C8..12D6 ; Ethiopic + "Zzzz", # 12D7..12D7 ; Unknown + "Ethi", # 12D8..1310 ; Ethiopic + "Zzzz", # 1311..1311 ; Unknown + "Ethi", # 1312..1315 ; Ethiopic + "Zzzz", # 1316..1317 ; Unknown + "Ethi", # 1318..135A ; Ethiopic + "Zzzz", # 135B..135C ; Unknown + "Ethi", # 135D..137C ; Ethiopic + "Zzzz", # 137D..137F ; Unknown + "Ethi", # 1380..1399 ; Ethiopic + "Zzzz", # 139A..139F ; Unknown + "Cher", # 13A0..13F5 ; Cherokee + "Zzzz", # 13F6..13F7 ; Unknown + "Cher", # 13F8..13FD ; Cherokee + "Zzzz", # 13FE..13FF ; Unknown + "Cans", # 1400..167F ; Canadian_Aboriginal + "Ogam", # 1680..169C ; Ogham + "Zzzz", # 169D..169F ; Unknown + "Runr", # 16A0..16EA ; Runic + "Zyyy", # 16EB..16ED ; Common + "Runr", # 16EE..16F8 ; Runic + "Zzzz", # 16F9..16FF ; Unknown + "Tglg", # 1700..1715 ; Tagalog + "Zzzz", # 1716..171E ; Unknown + "Tglg", # 171F..171F ; Tagalog + "Hano", # 1720..1734 ; Hanunoo + "Zyyy", # 1735..1736 ; Common + "Zzzz", # 1737..173F ; Unknown + "Buhd", # 1740..1753 ; Buhid + "Zzzz", # 1754..175F ; Unknown + "Tagb", # 1760..176C ; Tagbanwa + "Zzzz", # 176D..176D ; Unknown + "Tagb", # 176E..1770 ; Tagbanwa + "Zzzz", # 1771..1771 ; Unknown + "Tagb", # 1772..1773 ; Tagbanwa + "Zzzz", # 1774..177F ; Unknown + "Khmr", # 1780..17DD ; Khmer + "Zzzz", # 17DE..17DF ; Unknown + "Khmr", # 17E0..17E9 ; Khmer + "Zzzz", # 17EA..17EF ; Unknown + "Khmr", # 17F0..17F9 ; Khmer + "Zzzz", # 17FA..17FF ; Unknown + "Mong", # 1800..1801 ; Mongolian + "Zyyy", # 1802..1803 ; Common + "Mong", # 1804..1804 ; Mongolian + "Zyyy", # 1805..1805 ; Common + "Mong", # 1806..1819 ; Mongolian + "Zzzz", # 181A..181F ; Unknown + "Mong", # 1820..1878 ; Mongolian + "Zzzz", # 1879..187F ; Unknown + "Mong", # 1880..18AA ; Mongolian + "Zzzz", # 18AB..18AF ; Unknown + "Cans", # 18B0..18F5 ; Canadian_Aboriginal + "Zzzz", # 18F6..18FF ; Unknown + "Limb", # 1900..191E ; Limbu + "Zzzz", # 191F..191F ; Unknown + "Limb", # 1920..192B ; Limbu + "Zzzz", # 192C..192F ; Unknown + "Limb", # 1930..193B ; Limbu + "Zzzz", # 193C..193F ; Unknown + "Limb", # 1940..1940 ; Limbu + "Zzzz", # 1941..1943 ; Unknown + "Limb", # 1944..194F ; Limbu + "Tale", # 1950..196D ; Tai_Le + "Zzzz", # 196E..196F ; Unknown + "Tale", # 1970..1974 ; Tai_Le + "Zzzz", # 1975..197F ; Unknown + "Talu", # 1980..19AB ; New_Tai_Lue + "Zzzz", # 19AC..19AF ; Unknown + "Talu", # 19B0..19C9 ; New_Tai_Lue + "Zzzz", # 19CA..19CF ; Unknown + "Talu", # 19D0..19DA ; New_Tai_Lue + "Zzzz", # 19DB..19DD ; Unknown + "Talu", # 19DE..19DF ; New_Tai_Lue + "Khmr", # 19E0..19FF ; Khmer + "Bugi", # 1A00..1A1B ; Buginese + "Zzzz", # 1A1C..1A1D ; Unknown + "Bugi", # 1A1E..1A1F ; Buginese + "Lana", # 1A20..1A5E ; Tai_Tham + "Zzzz", # 1A5F..1A5F ; Unknown + "Lana", # 1A60..1A7C ; Tai_Tham + "Zzzz", # 1A7D..1A7E ; Unknown + "Lana", # 1A7F..1A89 ; Tai_Tham + "Zzzz", # 1A8A..1A8F ; Unknown + "Lana", # 1A90..1A99 ; Tai_Tham + "Zzzz", # 1A9A..1A9F ; Unknown + "Lana", # 1AA0..1AAD ; Tai_Tham + "Zzzz", # 1AAE..1AAF ; Unknown + "Zinh", # 1AB0..1ADD ; Inherited + "Zzzz", # 1ADE..1ADF ; Unknown + "Zinh", # 1AE0..1AEB ; Inherited + "Zzzz", # 1AEC..1AFF ; Unknown + "Bali", # 1B00..1B4C ; Balinese + "Zzzz", # 1B4D..1B4D ; Unknown + "Bali", # 1B4E..1B7F ; Balinese + "Sund", # 1B80..1BBF ; Sundanese + "Batk", # 1BC0..1BF3 ; Batak + "Zzzz", # 1BF4..1BFB ; Unknown + "Batk", # 1BFC..1BFF ; Batak + "Lepc", # 1C00..1C37 ; Lepcha + "Zzzz", # 1C38..1C3A ; Unknown + "Lepc", # 1C3B..1C49 ; Lepcha + "Zzzz", # 1C4A..1C4C ; Unknown + "Lepc", # 1C4D..1C4F ; Lepcha + "Olck", # 1C50..1C7F ; Ol_Chiki + "Cyrl", # 1C80..1C8A ; Cyrillic + "Zzzz", # 1C8B..1C8F ; Unknown + "Geor", # 1C90..1CBA ; Georgian + "Zzzz", # 1CBB..1CBC ; Unknown + "Geor", # 1CBD..1CBF ; Georgian + "Sund", # 1CC0..1CC7 ; Sundanese + "Zzzz", # 1CC8..1CCF ; Unknown + "Zinh", # 1CD0..1CD2 ; Inherited + "Zyyy", # 1CD3..1CD3 ; Common + "Zinh", # 1CD4..1CE0 ; Inherited + "Zyyy", # 1CE1..1CE1 ; Common + "Zinh", # 1CE2..1CE8 ; Inherited + "Zyyy", # 1CE9..1CEC ; Common + "Zinh", # 1CED..1CED ; Inherited + "Zyyy", # 1CEE..1CF3 ; Common + "Zinh", # 1CF4..1CF4 ; Inherited + "Zyyy", # 1CF5..1CF7 ; Common + "Zinh", # 1CF8..1CF9 ; Inherited + "Zyyy", # 1CFA..1CFA ; Common + "Zzzz", # 1CFB..1CFF ; Unknown + "Latn", # 1D00..1D25 ; Latin + "Grek", # 1D26..1D2A ; Greek + "Cyrl", # 1D2B..1D2B ; Cyrillic + "Latn", # 1D2C..1D5C ; Latin + "Grek", # 1D5D..1D61 ; Greek + "Latn", # 1D62..1D65 ; Latin + "Grek", # 1D66..1D6A ; Greek + "Latn", # 1D6B..1D77 ; Latin + "Cyrl", # 1D78..1D78 ; Cyrillic + "Latn", # 1D79..1DBE ; Latin + "Grek", # 1DBF..1DBF ; Greek + "Zinh", # 1DC0..1DFF ; Inherited + "Latn", # 1E00..1EFF ; Latin + "Grek", # 1F00..1F15 ; Greek + "Zzzz", # 1F16..1F17 ; Unknown + "Grek", # 1F18..1F1D ; Greek + "Zzzz", # 1F1E..1F1F ; Unknown + "Grek", # 1F20..1F45 ; Greek + "Zzzz", # 1F46..1F47 ; Unknown + "Grek", # 1F48..1F4D ; Greek + "Zzzz", # 1F4E..1F4F ; Unknown + "Grek", # 1F50..1F57 ; Greek + "Zzzz", # 1F58..1F58 ; Unknown + "Grek", # 1F59..1F59 ; Greek + "Zzzz", # 1F5A..1F5A ; Unknown + "Grek", # 1F5B..1F5B ; Greek + "Zzzz", # 1F5C..1F5C ; Unknown + "Grek", # 1F5D..1F5D ; Greek + "Zzzz", # 1F5E..1F5E ; Unknown + "Grek", # 1F5F..1F7D ; Greek + "Zzzz", # 1F7E..1F7F ; Unknown + "Grek", # 1F80..1FB4 ; Greek + "Zzzz", # 1FB5..1FB5 ; Unknown + "Grek", # 1FB6..1FC4 ; Greek + "Zzzz", # 1FC5..1FC5 ; Unknown + "Grek", # 1FC6..1FD3 ; Greek + "Zzzz", # 1FD4..1FD5 ; Unknown + "Grek", # 1FD6..1FDB ; Greek + "Zzzz", # 1FDC..1FDC ; Unknown + "Grek", # 1FDD..1FEF ; Greek + "Zzzz", # 1FF0..1FF1 ; Unknown + "Grek", # 1FF2..1FF4 ; Greek + "Zzzz", # 1FF5..1FF5 ; Unknown + "Grek", # 1FF6..1FFE ; Greek + "Zzzz", # 1FFF..1FFF ; Unknown + "Zyyy", # 2000..200B ; Common + "Zinh", # 200C..200D ; Inherited + "Zyyy", # 200E..2064 ; Common + "Zzzz", # 2065..2065 ; Unknown + "Zyyy", # 2066..2070 ; Common + "Latn", # 2071..2071 ; Latin + "Zzzz", # 2072..2073 ; Unknown + "Zyyy", # 2074..207E ; Common + "Latn", # 207F..207F ; Latin + "Zyyy", # 2080..208E ; Common + "Zzzz", # 208F..208F ; Unknown + "Latn", # 2090..209C ; Latin + "Zzzz", # 209D..209F ; Unknown + "Zyyy", # 20A0..20C1 ; Common + "Zzzz", # 20C2..20CF ; Unknown + "Zinh", # 20D0..20F0 ; Inherited + "Zzzz", # 20F1..20FF ; Unknown + "Zyyy", # 2100..2125 ; Common + "Grek", # 2126..2126 ; Greek + "Zyyy", # 2127..2129 ; Common + "Latn", # 212A..212B ; Latin + "Zyyy", # 212C..2131 ; Common + "Latn", # 2132..2132 ; Latin + "Zyyy", # 2133..214D ; Common + "Latn", # 214E..214E ; Latin + "Zyyy", # 214F..215F ; Common + "Latn", # 2160..2188 ; Latin + "Zyyy", # 2189..218B ; Common + "Zzzz", # 218C..218F ; Unknown + "Zyyy", # 2190..2429 ; Common + "Zzzz", # 242A..243F ; Unknown + "Zyyy", # 2440..244A ; Common + "Zzzz", # 244B..245F ; Unknown + "Zyyy", # 2460..27FF ; Common + "Brai", # 2800..28FF ; Braille + "Zyyy", # 2900..2B73 ; Common + "Zzzz", # 2B74..2B75 ; Unknown + "Zyyy", # 2B76..2BFF ; Common + "Glag", # 2C00..2C5F ; Glagolitic + "Latn", # 2C60..2C7F ; Latin + "Copt", # 2C80..2CF3 ; Coptic + "Zzzz", # 2CF4..2CF8 ; Unknown + "Copt", # 2CF9..2CFF ; Coptic + "Geor", # 2D00..2D25 ; Georgian + "Zzzz", # 2D26..2D26 ; Unknown + "Geor", # 2D27..2D27 ; Georgian + "Zzzz", # 2D28..2D2C ; Unknown + "Geor", # 2D2D..2D2D ; Georgian + "Zzzz", # 2D2E..2D2F ; Unknown + "Tfng", # 2D30..2D67 ; Tifinagh + "Zzzz", # 2D68..2D6E ; Unknown + "Tfng", # 2D6F..2D70 ; Tifinagh + "Zzzz", # 2D71..2D7E ; Unknown + "Tfng", # 2D7F..2D7F ; Tifinagh + "Ethi", # 2D80..2D96 ; Ethiopic + "Zzzz", # 2D97..2D9F ; Unknown + "Ethi", # 2DA0..2DA6 ; Ethiopic + "Zzzz", # 2DA7..2DA7 ; Unknown + "Ethi", # 2DA8..2DAE ; Ethiopic + "Zzzz", # 2DAF..2DAF ; Unknown + "Ethi", # 2DB0..2DB6 ; Ethiopic + "Zzzz", # 2DB7..2DB7 ; Unknown + "Ethi", # 2DB8..2DBE ; Ethiopic + "Zzzz", # 2DBF..2DBF ; Unknown + "Ethi", # 2DC0..2DC6 ; Ethiopic + "Zzzz", # 2DC7..2DC7 ; Unknown + "Ethi", # 2DC8..2DCE ; Ethiopic + "Zzzz", # 2DCF..2DCF ; Unknown + "Ethi", # 2DD0..2DD6 ; Ethiopic + "Zzzz", # 2DD7..2DD7 ; Unknown + "Ethi", # 2DD8..2DDE ; Ethiopic + "Zzzz", # 2DDF..2DDF ; Unknown + "Cyrl", # 2DE0..2DFF ; Cyrillic + "Zyyy", # 2E00..2E5D ; Common + "Zzzz", # 2E5E..2E7F ; Unknown + "Hani", # 2E80..2E99 ; Han + "Zzzz", # 2E9A..2E9A ; Unknown + "Hani", # 2E9B..2EF3 ; Han + "Zzzz", # 2EF4..2EFF ; Unknown + "Hani", # 2F00..2FD5 ; Han + "Zzzz", # 2FD6..2FEF ; Unknown + "Zyyy", # 2FF0..3004 ; Common + "Hani", # 3005..3005 ; Han + "Zyyy", # 3006..3006 ; Common + "Hani", # 3007..3007 ; Han + "Zyyy", # 3008..3020 ; Common + "Hani", # 3021..3029 ; Han + "Zinh", # 302A..302D ; Inherited + "Hang", # 302E..302F ; Hangul + "Zyyy", # 3030..3037 ; Common + "Hani", # 3038..303B ; Han + "Zyyy", # 303C..303F ; Common + "Zzzz", # 3040..3040 ; Unknown + "Hira", # 3041..3096 ; Hiragana + "Zzzz", # 3097..3098 ; Unknown + "Zinh", # 3099..309A ; Inherited + "Zyyy", # 309B..309C ; Common + "Hira", # 309D..309F ; Hiragana + "Zyyy", # 30A0..30A0 ; Common + "Kana", # 30A1..30FA ; Katakana + "Zyyy", # 30FB..30FC ; Common + "Kana", # 30FD..30FF ; Katakana + "Zzzz", # 3100..3104 ; Unknown + "Bopo", # 3105..312F ; Bopomofo + "Zzzz", # 3130..3130 ; Unknown + "Hang", # 3131..318E ; Hangul + "Zzzz", # 318F..318F ; Unknown + "Zyyy", # 3190..319F ; Common + "Bopo", # 31A0..31BF ; Bopomofo + "Zyyy", # 31C0..31E5 ; Common + "Zzzz", # 31E6..31EE ; Unknown + "Zyyy", # 31EF..31EF ; Common + "Kana", # 31F0..31FF ; Katakana + "Hang", # 3200..321E ; Hangul + "Zzzz", # 321F..321F ; Unknown + "Zyyy", # 3220..325F ; Common + "Hang", # 3260..327E ; Hangul + "Zyyy", # 327F..32CF ; Common + "Kana", # 32D0..32FE ; Katakana + "Zyyy", # 32FF..32FF ; Common + "Kana", # 3300..3357 ; Katakana + "Zyyy", # 3358..33FF ; Common + "Hani", # 3400..4DBF ; Han + "Zyyy", # 4DC0..4DFF ; Common + "Hani", # 4E00..9FFF ; Han + "Yiii", # A000..A48C ; Yi + "Zzzz", # A48D..A48F ; Unknown + "Yiii", # A490..A4C6 ; Yi + "Zzzz", # A4C7..A4CF ; Unknown + "Lisu", # A4D0..A4FF ; Lisu + "Vaii", # A500..A62B ; Vai + "Zzzz", # A62C..A63F ; Unknown + "Cyrl", # A640..A69F ; Cyrillic + "Bamu", # A6A0..A6F7 ; Bamum + "Zzzz", # A6F8..A6FF ; Unknown + "Zyyy", # A700..A721 ; Common + "Latn", # A722..A787 ; Latin + "Zyyy", # A788..A78A ; Common + "Latn", # A78B..A7DC ; Latin + "Zzzz", # A7DD..A7F0 ; Unknown + "Latn", # A7F1..A7FF ; Latin + "Sylo", # A800..A82C ; Syloti_Nagri + "Zzzz", # A82D..A82F ; Unknown + "Zyyy", # A830..A839 ; Common + "Zzzz", # A83A..A83F ; Unknown + "Phag", # A840..A877 ; Phags_Pa + "Zzzz", # A878..A87F ; Unknown + "Saur", # A880..A8C5 ; Saurashtra + "Zzzz", # A8C6..A8CD ; Unknown + "Saur", # A8CE..A8D9 ; Saurashtra + "Zzzz", # A8DA..A8DF ; Unknown + "Deva", # A8E0..A8FF ; Devanagari + "Kali", # A900..A92D ; Kayah_Li + "Zyyy", # A92E..A92E ; Common + "Kali", # A92F..A92F ; Kayah_Li + "Rjng", # A930..A953 ; Rejang + "Zzzz", # A954..A95E ; Unknown + "Rjng", # A95F..A95F ; Rejang + "Hang", # A960..A97C ; Hangul + "Zzzz", # A97D..A97F ; Unknown + "Java", # A980..A9CD ; Javanese + "Zzzz", # A9CE..A9CE ; Unknown + "Zyyy", # A9CF..A9CF ; Common + "Java", # A9D0..A9D9 ; Javanese + "Zzzz", # A9DA..A9DD ; Unknown + "Java", # A9DE..A9DF ; Javanese + "Mymr", # A9E0..A9FE ; Myanmar + "Zzzz", # A9FF..A9FF ; Unknown + "Cham", # AA00..AA36 ; Cham + "Zzzz", # AA37..AA3F ; Unknown + "Cham", # AA40..AA4D ; Cham + "Zzzz", # AA4E..AA4F ; Unknown + "Cham", # AA50..AA59 ; Cham + "Zzzz", # AA5A..AA5B ; Unknown + "Cham", # AA5C..AA5F ; Cham + "Mymr", # AA60..AA7F ; Myanmar + "Tavt", # AA80..AAC2 ; Tai_Viet + "Zzzz", # AAC3..AADA ; Unknown + "Tavt", # AADB..AADF ; Tai_Viet + "Mtei", # AAE0..AAF6 ; Meetei_Mayek + "Zzzz", # AAF7..AB00 ; Unknown + "Ethi", # AB01..AB06 ; Ethiopic + "Zzzz", # AB07..AB08 ; Unknown + "Ethi", # AB09..AB0E ; Ethiopic + "Zzzz", # AB0F..AB10 ; Unknown + "Ethi", # AB11..AB16 ; Ethiopic + "Zzzz", # AB17..AB1F ; Unknown + "Ethi", # AB20..AB26 ; Ethiopic + "Zzzz", # AB27..AB27 ; Unknown + "Ethi", # AB28..AB2E ; Ethiopic + "Zzzz", # AB2F..AB2F ; Unknown + "Latn", # AB30..AB5A ; Latin + "Zyyy", # AB5B..AB5B ; Common + "Latn", # AB5C..AB64 ; Latin + "Grek", # AB65..AB65 ; Greek + "Latn", # AB66..AB69 ; Latin + "Zyyy", # AB6A..AB6B ; Common + "Zzzz", # AB6C..AB6F ; Unknown + "Cher", # AB70..ABBF ; Cherokee + "Mtei", # ABC0..ABED ; Meetei_Mayek + "Zzzz", # ABEE..ABEF ; Unknown + "Mtei", # ABF0..ABF9 ; Meetei_Mayek + "Zzzz", # ABFA..ABFF ; Unknown + "Hang", # AC00..D7A3 ; Hangul + "Zzzz", # D7A4..D7AF ; Unknown + "Hang", # D7B0..D7C6 ; Hangul + "Zzzz", # D7C7..D7CA ; Unknown + "Hang", # D7CB..D7FB ; Hangul + "Zzzz", # D7FC..F8FF ; Unknown + "Hani", # F900..FA6D ; Han + "Zzzz", # FA6E..FA6F ; Unknown + "Hani", # FA70..FAD9 ; Han + "Zzzz", # FADA..FAFF ; Unknown + "Latn", # FB00..FB06 ; Latin + "Zzzz", # FB07..FB12 ; Unknown + "Armn", # FB13..FB17 ; Armenian + "Zzzz", # FB18..FB1C ; Unknown + "Hebr", # FB1D..FB36 ; Hebrew + "Zzzz", # FB37..FB37 ; Unknown + "Hebr", # FB38..FB3C ; Hebrew + "Zzzz", # FB3D..FB3D ; Unknown + "Hebr", # FB3E..FB3E ; Hebrew + "Zzzz", # FB3F..FB3F ; Unknown + "Hebr", # FB40..FB41 ; Hebrew + "Zzzz", # FB42..FB42 ; Unknown + "Hebr", # FB43..FB44 ; Hebrew + "Zzzz", # FB45..FB45 ; Unknown + "Hebr", # FB46..FB4F ; Hebrew + "Arab", # FB50..FD3D ; Arabic + "Zyyy", # FD3E..FD3F ; Common + "Arab", # FD40..FDCF ; Arabic + "Zzzz", # FDD0..FDEF ; Unknown + "Arab", # FDF0..FDFF ; Arabic + "Zinh", # FE00..FE0F ; Inherited + "Zyyy", # FE10..FE19 ; Common + "Zzzz", # FE1A..FE1F ; Unknown + "Zinh", # FE20..FE2D ; Inherited + "Cyrl", # FE2E..FE2F ; Cyrillic + "Zyyy", # FE30..FE52 ; Common + "Zzzz", # FE53..FE53 ; Unknown + "Zyyy", # FE54..FE66 ; Common + "Zzzz", # FE67..FE67 ; Unknown + "Zyyy", # FE68..FE6B ; Common + "Zzzz", # FE6C..FE6F ; Unknown + "Arab", # FE70..FE74 ; Arabic + "Zzzz", # FE75..FE75 ; Unknown + "Arab", # FE76..FEFC ; Arabic + "Zzzz", # FEFD..FEFE ; Unknown + "Zyyy", # FEFF..FEFF ; Common + "Zzzz", # FF00..FF00 ; Unknown + "Zyyy", # FF01..FF20 ; Common + "Latn", # FF21..FF3A ; Latin + "Zyyy", # FF3B..FF40 ; Common + "Latn", # FF41..FF5A ; Latin + "Zyyy", # FF5B..FF65 ; Common + "Kana", # FF66..FF6F ; Katakana + "Zyyy", # FF70..FF70 ; Common + "Kana", # FF71..FF9D ; Katakana + "Zyyy", # FF9E..FF9F ; Common + "Hang", # FFA0..FFBE ; Hangul + "Zzzz", # FFBF..FFC1 ; Unknown + "Hang", # FFC2..FFC7 ; Hangul + "Zzzz", # FFC8..FFC9 ; Unknown + "Hang", # FFCA..FFCF ; Hangul + "Zzzz", # FFD0..FFD1 ; Unknown + "Hang", # FFD2..FFD7 ; Hangul + "Zzzz", # FFD8..FFD9 ; Unknown + "Hang", # FFDA..FFDC ; Hangul + "Zzzz", # FFDD..FFDF ; Unknown + "Zyyy", # FFE0..FFE6 ; Common + "Zzzz", # FFE7..FFE7 ; Unknown + "Zyyy", # FFE8..FFEE ; Common + "Zzzz", # FFEF..FFF8 ; Unknown + "Zyyy", # FFF9..FFFD ; Common + "Zzzz", # FFFE..FFFF ; Unknown + "Linb", # 10000..1000B ; Linear_B + "Zzzz", # 1000C..1000C ; Unknown + "Linb", # 1000D..10026 ; Linear_B + "Zzzz", # 10027..10027 ; Unknown + "Linb", # 10028..1003A ; Linear_B + "Zzzz", # 1003B..1003B ; Unknown + "Linb", # 1003C..1003D ; Linear_B + "Zzzz", # 1003E..1003E ; Unknown + "Linb", # 1003F..1004D ; Linear_B + "Zzzz", # 1004E..1004F ; Unknown + "Linb", # 10050..1005D ; Linear_B + "Zzzz", # 1005E..1007F ; Unknown + "Linb", # 10080..100FA ; Linear_B + "Zzzz", # 100FB..100FF ; Unknown + "Zyyy", # 10100..10102 ; Common + "Zzzz", # 10103..10106 ; Unknown + "Zyyy", # 10107..10133 ; Common + "Zzzz", # 10134..10136 ; Unknown + "Zyyy", # 10137..1013F ; Common + "Grek", # 10140..1018E ; Greek + "Zzzz", # 1018F..1018F ; Unknown + "Zyyy", # 10190..1019C ; Common + "Zzzz", # 1019D..1019F ; Unknown + "Grek", # 101A0..101A0 ; Greek + "Zzzz", # 101A1..101CF ; Unknown + "Zyyy", # 101D0..101FC ; Common + "Zinh", # 101FD..101FD ; Inherited + "Zzzz", # 101FE..1027F ; Unknown + "Lyci", # 10280..1029C ; Lycian + "Zzzz", # 1029D..1029F ; Unknown + "Cari", # 102A0..102D0 ; Carian + "Zzzz", # 102D1..102DF ; Unknown + "Zinh", # 102E0..102E0 ; Inherited + "Zyyy", # 102E1..102FB ; Common + "Zzzz", # 102FC..102FF ; Unknown + "Ital", # 10300..10323 ; Old_Italic + "Zzzz", # 10324..1032C ; Unknown + "Ital", # 1032D..1032F ; Old_Italic + "Goth", # 10330..1034A ; Gothic + "Zzzz", # 1034B..1034F ; Unknown + "Perm", # 10350..1037A ; Old_Permic + "Zzzz", # 1037B..1037F ; Unknown + "Ugar", # 10380..1039D ; Ugaritic + "Zzzz", # 1039E..1039E ; Unknown + "Ugar", # 1039F..1039F ; Ugaritic + "Xpeo", # 103A0..103C3 ; Old_Persian + "Zzzz", # 103C4..103C7 ; Unknown + "Xpeo", # 103C8..103D5 ; Old_Persian + "Zzzz", # 103D6..103FF ; Unknown + "Dsrt", # 10400..1044F ; Deseret + "Shaw", # 10450..1047F ; Shavian + "Osma", # 10480..1049D ; Osmanya + "Zzzz", # 1049E..1049F ; Unknown + "Osma", # 104A0..104A9 ; Osmanya + "Zzzz", # 104AA..104AF ; Unknown + "Osge", # 104B0..104D3 ; Osage + "Zzzz", # 104D4..104D7 ; Unknown + "Osge", # 104D8..104FB ; Osage + "Zzzz", # 104FC..104FF ; Unknown + "Elba", # 10500..10527 ; Elbasan + "Zzzz", # 10528..1052F ; Unknown + "Aghb", # 10530..10563 ; Caucasian_Albanian + "Zzzz", # 10564..1056E ; Unknown + "Aghb", # 1056F..1056F ; Caucasian_Albanian + "Vith", # 10570..1057A ; Vithkuqi + "Zzzz", # 1057B..1057B ; Unknown + "Vith", # 1057C..1058A ; Vithkuqi + "Zzzz", # 1058B..1058B ; Unknown + "Vith", # 1058C..10592 ; Vithkuqi + "Zzzz", # 10593..10593 ; Unknown + "Vith", # 10594..10595 ; Vithkuqi + "Zzzz", # 10596..10596 ; Unknown + "Vith", # 10597..105A1 ; Vithkuqi + "Zzzz", # 105A2..105A2 ; Unknown + "Vith", # 105A3..105B1 ; Vithkuqi + "Zzzz", # 105B2..105B2 ; Unknown + "Vith", # 105B3..105B9 ; Vithkuqi + "Zzzz", # 105BA..105BA ; Unknown + "Vith", # 105BB..105BC ; Vithkuqi + "Zzzz", # 105BD..105BF ; Unknown + "Todr", # 105C0..105F3 ; Todhri + "Zzzz", # 105F4..105FF ; Unknown + "Lina", # 10600..10736 ; Linear_A + "Zzzz", # 10737..1073F ; Unknown + "Lina", # 10740..10755 ; Linear_A + "Zzzz", # 10756..1075F ; Unknown + "Lina", # 10760..10767 ; Linear_A + "Zzzz", # 10768..1077F ; Unknown + "Latn", # 10780..10785 ; Latin + "Zzzz", # 10786..10786 ; Unknown + "Latn", # 10787..107B0 ; Latin + "Zzzz", # 107B1..107B1 ; Unknown + "Latn", # 107B2..107BA ; Latin + "Zzzz", # 107BB..107FF ; Unknown + "Cprt", # 10800..10805 ; Cypriot + "Zzzz", # 10806..10807 ; Unknown + "Cprt", # 10808..10808 ; Cypriot + "Zzzz", # 10809..10809 ; Unknown + "Cprt", # 1080A..10835 ; Cypriot + "Zzzz", # 10836..10836 ; Unknown + "Cprt", # 10837..10838 ; Cypriot + "Zzzz", # 10839..1083B ; Unknown + "Cprt", # 1083C..1083C ; Cypriot + "Zzzz", # 1083D..1083E ; Unknown + "Cprt", # 1083F..1083F ; Cypriot + "Armi", # 10840..10855 ; Imperial_Aramaic + "Zzzz", # 10856..10856 ; Unknown + "Armi", # 10857..1085F ; Imperial_Aramaic + "Palm", # 10860..1087F ; Palmyrene + "Nbat", # 10880..1089E ; Nabataean + "Zzzz", # 1089F..108A6 ; Unknown + "Nbat", # 108A7..108AF ; Nabataean + "Zzzz", # 108B0..108DF ; Unknown + "Hatr", # 108E0..108F2 ; Hatran + "Zzzz", # 108F3..108F3 ; Unknown + "Hatr", # 108F4..108F5 ; Hatran + "Zzzz", # 108F6..108FA ; Unknown + "Hatr", # 108FB..108FF ; Hatran + "Phnx", # 10900..1091B ; Phoenician + "Zzzz", # 1091C..1091E ; Unknown + "Phnx", # 1091F..1091F ; Phoenician + "Lydi", # 10920..10939 ; Lydian + "Zzzz", # 1093A..1093E ; Unknown + "Lydi", # 1093F..1093F ; Lydian + "Sidt", # 10940..10959 ; Sidetic + "Zzzz", # 1095A..1097F ; Unknown + "Mero", # 10980..1099F ; Meroitic_Hieroglyphs + "Merc", # 109A0..109B7 ; Meroitic_Cursive + "Zzzz", # 109B8..109BB ; Unknown + "Merc", # 109BC..109CF ; Meroitic_Cursive + "Zzzz", # 109D0..109D1 ; Unknown + "Merc", # 109D2..109FF ; Meroitic_Cursive + "Khar", # 10A00..10A03 ; Kharoshthi + "Zzzz", # 10A04..10A04 ; Unknown + "Khar", # 10A05..10A06 ; Kharoshthi + "Zzzz", # 10A07..10A0B ; Unknown + "Khar", # 10A0C..10A13 ; Kharoshthi + "Zzzz", # 10A14..10A14 ; Unknown + "Khar", # 10A15..10A17 ; Kharoshthi + "Zzzz", # 10A18..10A18 ; Unknown + "Khar", # 10A19..10A35 ; Kharoshthi + "Zzzz", # 10A36..10A37 ; Unknown + "Khar", # 10A38..10A3A ; Kharoshthi + "Zzzz", # 10A3B..10A3E ; Unknown + "Khar", # 10A3F..10A48 ; Kharoshthi + "Zzzz", # 10A49..10A4F ; Unknown + "Khar", # 10A50..10A58 ; Kharoshthi + "Zzzz", # 10A59..10A5F ; Unknown + "Sarb", # 10A60..10A7F ; Old_South_Arabian + "Narb", # 10A80..10A9F ; Old_North_Arabian + "Zzzz", # 10AA0..10ABF ; Unknown + "Mani", # 10AC0..10AE6 ; Manichaean + "Zzzz", # 10AE7..10AEA ; Unknown + "Mani", # 10AEB..10AF6 ; Manichaean + "Zzzz", # 10AF7..10AFF ; Unknown + "Avst", # 10B00..10B35 ; Avestan + "Zzzz", # 10B36..10B38 ; Unknown + "Avst", # 10B39..10B3F ; Avestan + "Prti", # 10B40..10B55 ; Inscriptional_Parthian + "Zzzz", # 10B56..10B57 ; Unknown + "Prti", # 10B58..10B5F ; Inscriptional_Parthian + "Phli", # 10B60..10B72 ; Inscriptional_Pahlavi + "Zzzz", # 10B73..10B77 ; Unknown + "Phli", # 10B78..10B7F ; Inscriptional_Pahlavi + "Phlp", # 10B80..10B91 ; Psalter_Pahlavi + "Zzzz", # 10B92..10B98 ; Unknown + "Phlp", # 10B99..10B9C ; Psalter_Pahlavi + "Zzzz", # 10B9D..10BA8 ; Unknown + "Phlp", # 10BA9..10BAF ; Psalter_Pahlavi + "Zzzz", # 10BB0..10BFF ; Unknown + "Orkh", # 10C00..10C48 ; Old_Turkic + "Zzzz", # 10C49..10C7F ; Unknown + "Hung", # 10C80..10CB2 ; Old_Hungarian + "Zzzz", # 10CB3..10CBF ; Unknown + "Hung", # 10CC0..10CF2 ; Old_Hungarian + "Zzzz", # 10CF3..10CF9 ; Unknown + "Hung", # 10CFA..10CFF ; Old_Hungarian + "Rohg", # 10D00..10D27 ; Hanifi_Rohingya + "Zzzz", # 10D28..10D2F ; Unknown + "Rohg", # 10D30..10D39 ; Hanifi_Rohingya + "Zzzz", # 10D3A..10D3F ; Unknown + "Gara", # 10D40..10D65 ; Garay + "Zzzz", # 10D66..10D68 ; Unknown + "Gara", # 10D69..10D85 ; Garay + "Zzzz", # 10D86..10D8D ; Unknown + "Gara", # 10D8E..10D8F ; Garay + "Zzzz", # 10D90..10E5F ; Unknown + "Arab", # 10E60..10E7E ; Arabic + "Zzzz", # 10E7F..10E7F ; Unknown + "Yezi", # 10E80..10EA9 ; Yezidi + "Zzzz", # 10EAA..10EAA ; Unknown + "Yezi", # 10EAB..10EAD ; Yezidi + "Zzzz", # 10EAE..10EAF ; Unknown + "Yezi", # 10EB0..10EB1 ; Yezidi + "Zzzz", # 10EB2..10EC1 ; Unknown + "Arab", # 10EC2..10EC7 ; Arabic + "Zzzz", # 10EC8..10ECF ; Unknown + "Arab", # 10ED0..10ED8 ; Arabic + "Zzzz", # 10ED9..10EF9 ; Unknown + "Arab", # 10EFA..10EFF ; Arabic + "Sogo", # 10F00..10F27 ; Old_Sogdian + "Zzzz", # 10F28..10F2F ; Unknown + "Sogd", # 10F30..10F59 ; Sogdian + "Zzzz", # 10F5A..10F6F ; Unknown + "Ougr", # 10F70..10F89 ; Old_Uyghur + "Zzzz", # 10F8A..10FAF ; Unknown + "Chrs", # 10FB0..10FCB ; Chorasmian + "Zzzz", # 10FCC..10FDF ; Unknown + "Elym", # 10FE0..10FF6 ; Elymaic + "Zzzz", # 10FF7..10FFF ; Unknown + "Brah", # 11000..1104D ; Brahmi + "Zzzz", # 1104E..11051 ; Unknown + "Brah", # 11052..11075 ; Brahmi + "Zzzz", # 11076..1107E ; Unknown + "Brah", # 1107F..1107F ; Brahmi + "Kthi", # 11080..110C2 ; Kaithi + "Zzzz", # 110C3..110CC ; Unknown + "Kthi", # 110CD..110CD ; Kaithi + "Zzzz", # 110CE..110CF ; Unknown + "Sora", # 110D0..110E8 ; Sora_Sompeng + "Zzzz", # 110E9..110EF ; Unknown + "Sora", # 110F0..110F9 ; Sora_Sompeng + "Zzzz", # 110FA..110FF ; Unknown + "Cakm", # 11100..11134 ; Chakma + "Zzzz", # 11135..11135 ; Unknown + "Cakm", # 11136..11147 ; Chakma + "Zzzz", # 11148..1114F ; Unknown + "Mahj", # 11150..11176 ; Mahajani + "Zzzz", # 11177..1117F ; Unknown + "Shrd", # 11180..111DF ; Sharada + "Zzzz", # 111E0..111E0 ; Unknown + "Sinh", # 111E1..111F4 ; Sinhala + "Zzzz", # 111F5..111FF ; Unknown + "Khoj", # 11200..11211 ; Khojki + "Zzzz", # 11212..11212 ; Unknown + "Khoj", # 11213..11241 ; Khojki + "Zzzz", # 11242..1127F ; Unknown + "Mult", # 11280..11286 ; Multani + "Zzzz", # 11287..11287 ; Unknown + "Mult", # 11288..11288 ; Multani + "Zzzz", # 11289..11289 ; Unknown + "Mult", # 1128A..1128D ; Multani + "Zzzz", # 1128E..1128E ; Unknown + "Mult", # 1128F..1129D ; Multani + "Zzzz", # 1129E..1129E ; Unknown + "Mult", # 1129F..112A9 ; Multani + "Zzzz", # 112AA..112AF ; Unknown + "Sind", # 112B0..112EA ; Khudawadi + "Zzzz", # 112EB..112EF ; Unknown + "Sind", # 112F0..112F9 ; Khudawadi + "Zzzz", # 112FA..112FF ; Unknown + "Gran", # 11300..11303 ; Grantha + "Zzzz", # 11304..11304 ; Unknown + "Gran", # 11305..1130C ; Grantha + "Zzzz", # 1130D..1130E ; Unknown + "Gran", # 1130F..11310 ; Grantha + "Zzzz", # 11311..11312 ; Unknown + "Gran", # 11313..11328 ; Grantha + "Zzzz", # 11329..11329 ; Unknown + "Gran", # 1132A..11330 ; Grantha + "Zzzz", # 11331..11331 ; Unknown + "Gran", # 11332..11333 ; Grantha + "Zzzz", # 11334..11334 ; Unknown + "Gran", # 11335..11339 ; Grantha + "Zzzz", # 1133A..1133A ; Unknown + "Zinh", # 1133B..1133B ; Inherited + "Gran", # 1133C..11344 ; Grantha + "Zzzz", # 11345..11346 ; Unknown + "Gran", # 11347..11348 ; Grantha + "Zzzz", # 11349..1134A ; Unknown + "Gran", # 1134B..1134D ; Grantha + "Zzzz", # 1134E..1134F ; Unknown + "Gran", # 11350..11350 ; Grantha + "Zzzz", # 11351..11356 ; Unknown + "Gran", # 11357..11357 ; Grantha + "Zzzz", # 11358..1135C ; Unknown + "Gran", # 1135D..11363 ; Grantha + "Zzzz", # 11364..11365 ; Unknown + "Gran", # 11366..1136C ; Grantha + "Zzzz", # 1136D..1136F ; Unknown + "Gran", # 11370..11374 ; Grantha + "Zzzz", # 11375..1137F ; Unknown + "Tutg", # 11380..11389 ; Tulu_Tigalari + "Zzzz", # 1138A..1138A ; Unknown + "Tutg", # 1138B..1138B ; Tulu_Tigalari + "Zzzz", # 1138C..1138D ; Unknown + "Tutg", # 1138E..1138E ; Tulu_Tigalari + "Zzzz", # 1138F..1138F ; Unknown + "Tutg", # 11390..113B5 ; Tulu_Tigalari + "Zzzz", # 113B6..113B6 ; Unknown + "Tutg", # 113B7..113C0 ; Tulu_Tigalari + "Zzzz", # 113C1..113C1 ; Unknown + "Tutg", # 113C2..113C2 ; Tulu_Tigalari + "Zzzz", # 113C3..113C4 ; Unknown + "Tutg", # 113C5..113C5 ; Tulu_Tigalari + "Zzzz", # 113C6..113C6 ; Unknown + "Tutg", # 113C7..113CA ; Tulu_Tigalari + "Zzzz", # 113CB..113CB ; Unknown + "Tutg", # 113CC..113D5 ; Tulu_Tigalari + "Zzzz", # 113D6..113D6 ; Unknown + "Tutg", # 113D7..113D8 ; Tulu_Tigalari + "Zzzz", # 113D9..113E0 ; Unknown + "Tutg", # 113E1..113E2 ; Tulu_Tigalari + "Zzzz", # 113E3..113FF ; Unknown + "Newa", # 11400..1145B ; Newa + "Zzzz", # 1145C..1145C ; Unknown + "Newa", # 1145D..11461 ; Newa + "Zzzz", # 11462..1147F ; Unknown + "Tirh", # 11480..114C7 ; Tirhuta + "Zzzz", # 114C8..114CF ; Unknown + "Tirh", # 114D0..114D9 ; Tirhuta + "Zzzz", # 114DA..1157F ; Unknown + "Sidd", # 11580..115B5 ; Siddham + "Zzzz", # 115B6..115B7 ; Unknown + "Sidd", # 115B8..115DD ; Siddham + "Zzzz", # 115DE..115FF ; Unknown + "Modi", # 11600..11644 ; Modi + "Zzzz", # 11645..1164F ; Unknown + "Modi", # 11650..11659 ; Modi + "Zzzz", # 1165A..1165F ; Unknown + "Mong", # 11660..1166C ; Mongolian + "Zzzz", # 1166D..1167F ; Unknown + "Takr", # 11680..116B9 ; Takri + "Zzzz", # 116BA..116BF ; Unknown + "Takr", # 116C0..116C9 ; Takri + "Zzzz", # 116CA..116CF ; Unknown + "Mymr", # 116D0..116E3 ; Myanmar + "Zzzz", # 116E4..116FF ; Unknown + "Ahom", # 11700..1171A ; Ahom + "Zzzz", # 1171B..1171C ; Unknown + "Ahom", # 1171D..1172B ; Ahom + "Zzzz", # 1172C..1172F ; Unknown + "Ahom", # 11730..11746 ; Ahom + "Zzzz", # 11747..117FF ; Unknown + "Dogr", # 11800..1183B ; Dogra + "Zzzz", # 1183C..1189F ; Unknown + "Wara", # 118A0..118F2 ; Warang_Citi + "Zzzz", # 118F3..118FE ; Unknown + "Wara", # 118FF..118FF ; Warang_Citi + "Diak", # 11900..11906 ; Dives_Akuru + "Zzzz", # 11907..11908 ; Unknown + "Diak", # 11909..11909 ; Dives_Akuru + "Zzzz", # 1190A..1190B ; Unknown + "Diak", # 1190C..11913 ; Dives_Akuru + "Zzzz", # 11914..11914 ; Unknown + "Diak", # 11915..11916 ; Dives_Akuru + "Zzzz", # 11917..11917 ; Unknown + "Diak", # 11918..11935 ; Dives_Akuru + "Zzzz", # 11936..11936 ; Unknown + "Diak", # 11937..11938 ; Dives_Akuru + "Zzzz", # 11939..1193A ; Unknown + "Diak", # 1193B..11946 ; Dives_Akuru + "Zzzz", # 11947..1194F ; Unknown + "Diak", # 11950..11959 ; Dives_Akuru + "Zzzz", # 1195A..1199F ; Unknown + "Nand", # 119A0..119A7 ; Nandinagari + "Zzzz", # 119A8..119A9 ; Unknown + "Nand", # 119AA..119D7 ; Nandinagari + "Zzzz", # 119D8..119D9 ; Unknown + "Nand", # 119DA..119E4 ; Nandinagari + "Zzzz", # 119E5..119FF ; Unknown + "Zanb", # 11A00..11A47 ; Zanabazar_Square + "Zzzz", # 11A48..11A4F ; Unknown + "Soyo", # 11A50..11AA2 ; Soyombo + "Zzzz", # 11AA3..11AAF ; Unknown + "Cans", # 11AB0..11ABF ; Canadian_Aboriginal + "Pauc", # 11AC0..11AF8 ; Pau_Cin_Hau + "Zzzz", # 11AF9..11AFF ; Unknown + "Deva", # 11B00..11B09 ; Devanagari + "Zzzz", # 11B0A..11B5F ; Unknown + "Shrd", # 11B60..11B67 ; Sharada + "Zzzz", # 11B68..11BBF ; Unknown + "Sunu", # 11BC0..11BE1 ; Sunuwar + "Zzzz", # 11BE2..11BEF ; Unknown + "Sunu", # 11BF0..11BF9 ; Sunuwar + "Zzzz", # 11BFA..11BFF ; Unknown + "Bhks", # 11C00..11C08 ; Bhaiksuki + "Zzzz", # 11C09..11C09 ; Unknown + "Bhks", # 11C0A..11C36 ; Bhaiksuki + "Zzzz", # 11C37..11C37 ; Unknown + "Bhks", # 11C38..11C45 ; Bhaiksuki + "Zzzz", # 11C46..11C4F ; Unknown + "Bhks", # 11C50..11C6C ; Bhaiksuki + "Zzzz", # 11C6D..11C6F ; Unknown + "Marc", # 11C70..11C8F ; Marchen + "Zzzz", # 11C90..11C91 ; Unknown + "Marc", # 11C92..11CA7 ; Marchen + "Zzzz", # 11CA8..11CA8 ; Unknown + "Marc", # 11CA9..11CB6 ; Marchen + "Zzzz", # 11CB7..11CFF ; Unknown + "Gonm", # 11D00..11D06 ; Masaram_Gondi + "Zzzz", # 11D07..11D07 ; Unknown + "Gonm", # 11D08..11D09 ; Masaram_Gondi + "Zzzz", # 11D0A..11D0A ; Unknown + "Gonm", # 11D0B..11D36 ; Masaram_Gondi + "Zzzz", # 11D37..11D39 ; Unknown + "Gonm", # 11D3A..11D3A ; Masaram_Gondi + "Zzzz", # 11D3B..11D3B ; Unknown + "Gonm", # 11D3C..11D3D ; Masaram_Gondi + "Zzzz", # 11D3E..11D3E ; Unknown + "Gonm", # 11D3F..11D47 ; Masaram_Gondi + "Zzzz", # 11D48..11D4F ; Unknown + "Gonm", # 11D50..11D59 ; Masaram_Gondi + "Zzzz", # 11D5A..11D5F ; Unknown + "Gong", # 11D60..11D65 ; Gunjala_Gondi + "Zzzz", # 11D66..11D66 ; Unknown + "Gong", # 11D67..11D68 ; Gunjala_Gondi + "Zzzz", # 11D69..11D69 ; Unknown + "Gong", # 11D6A..11D8E ; Gunjala_Gondi + "Zzzz", # 11D8F..11D8F ; Unknown + "Gong", # 11D90..11D91 ; Gunjala_Gondi + "Zzzz", # 11D92..11D92 ; Unknown + "Gong", # 11D93..11D98 ; Gunjala_Gondi + "Zzzz", # 11D99..11D9F ; Unknown + "Gong", # 11DA0..11DA9 ; Gunjala_Gondi + "Zzzz", # 11DAA..11DAF ; Unknown + "Tols", # 11DB0..11DDB ; Tolong_Siki + "Zzzz", # 11DDC..11DDF ; Unknown + "Tols", # 11DE0..11DE9 ; Tolong_Siki + "Zzzz", # 11DEA..11EDF ; Unknown + "Maka", # 11EE0..11EF8 ; Makasar + "Zzzz", # 11EF9..11EFF ; Unknown + "Kawi", # 11F00..11F10 ; Kawi + "Zzzz", # 11F11..11F11 ; Unknown + "Kawi", # 11F12..11F3A ; Kawi + "Zzzz", # 11F3B..11F3D ; Unknown + "Kawi", # 11F3E..11F5A ; Kawi + "Zzzz", # 11F5B..11FAF ; Unknown + "Lisu", # 11FB0..11FB0 ; Lisu + "Zzzz", # 11FB1..11FBF ; Unknown + "Taml", # 11FC0..11FF1 ; Tamil + "Zzzz", # 11FF2..11FFE ; Unknown + "Taml", # 11FFF..11FFF ; Tamil + "Xsux", # 12000..12399 ; Cuneiform + "Zzzz", # 1239A..123FF ; Unknown + "Xsux", # 12400..1246E ; Cuneiform + "Zzzz", # 1246F..1246F ; Unknown + "Xsux", # 12470..12474 ; Cuneiform + "Zzzz", # 12475..1247F ; Unknown + "Xsux", # 12480..12543 ; Cuneiform + "Zzzz", # 12544..12F8F ; Unknown + "Cpmn", # 12F90..12FF2 ; Cypro_Minoan + "Zzzz", # 12FF3..12FFF ; Unknown + "Egyp", # 13000..13455 ; Egyptian_Hieroglyphs + "Zzzz", # 13456..1345F ; Unknown + "Egyp", # 13460..143FA ; Egyptian_Hieroglyphs + "Zzzz", # 143FB..143FF ; Unknown + "Hluw", # 14400..14646 ; Anatolian_Hieroglyphs + "Zzzz", # 14647..160FF ; Unknown + "Gukh", # 16100..16139 ; Gurung_Khema + "Zzzz", # 1613A..167FF ; Unknown + "Bamu", # 16800..16A38 ; Bamum + "Zzzz", # 16A39..16A3F ; Unknown + "Mroo", # 16A40..16A5E ; Mro + "Zzzz", # 16A5F..16A5F ; Unknown + "Mroo", # 16A60..16A69 ; Mro + "Zzzz", # 16A6A..16A6D ; Unknown + "Mroo", # 16A6E..16A6F ; Mro + "Tnsa", # 16A70..16ABE ; Tangsa + "Zzzz", # 16ABF..16ABF ; Unknown + "Tnsa", # 16AC0..16AC9 ; Tangsa + "Zzzz", # 16ACA..16ACF ; Unknown + "Bass", # 16AD0..16AED ; Bassa_Vah + "Zzzz", # 16AEE..16AEF ; Unknown + "Bass", # 16AF0..16AF5 ; Bassa_Vah + "Zzzz", # 16AF6..16AFF ; Unknown + "Hmng", # 16B00..16B45 ; Pahawh_Hmong + "Zzzz", # 16B46..16B4F ; Unknown + "Hmng", # 16B50..16B59 ; Pahawh_Hmong + "Zzzz", # 16B5A..16B5A ; Unknown + "Hmng", # 16B5B..16B61 ; Pahawh_Hmong + "Zzzz", # 16B62..16B62 ; Unknown + "Hmng", # 16B63..16B77 ; Pahawh_Hmong + "Zzzz", # 16B78..16B7C ; Unknown + "Hmng", # 16B7D..16B8F ; Pahawh_Hmong + "Zzzz", # 16B90..16D3F ; Unknown + "Krai", # 16D40..16D79 ; Kirat_Rai + "Zzzz", # 16D7A..16E3F ; Unknown + "Medf", # 16E40..16E9A ; Medefaidrin + "Zzzz", # 16E9B..16E9F ; Unknown + "Berf", # 16EA0..16EB8 ; Beria_Erfe + "Zzzz", # 16EB9..16EBA ; Unknown + "Berf", # 16EBB..16ED3 ; Beria_Erfe + "Zzzz", # 16ED4..16EFF ; Unknown + "Plrd", # 16F00..16F4A ; Miao + "Zzzz", # 16F4B..16F4E ; Unknown + "Plrd", # 16F4F..16F87 ; Miao + "Zzzz", # 16F88..16F8E ; Unknown + "Plrd", # 16F8F..16F9F ; Miao + "Zzzz", # 16FA0..16FDF ; Unknown + "Tang", # 16FE0..16FE0 ; Tangut + "Nshu", # 16FE1..16FE1 ; Nushu + "Hani", # 16FE2..16FE3 ; Han + "Kits", # 16FE4..16FE4 ; Khitan_Small_Script + "Zzzz", # 16FE5..16FEF ; Unknown + "Hani", # 16FF0..16FF6 ; Han + "Zzzz", # 16FF7..16FFF ; Unknown + "Tang", # 17000..18AFF ; Tangut + "Kits", # 18B00..18CD5 ; Khitan_Small_Script + "Zzzz", # 18CD6..18CFE ; Unknown + "Kits", # 18CFF..18CFF ; Khitan_Small_Script + "Tang", # 18D00..18D1E ; Tangut + "Zzzz", # 18D1F..18D7F ; Unknown + "Tang", # 18D80..18DF2 ; Tangut + "Zzzz", # 18DF3..1AFEF ; Unknown + "Kana", # 1AFF0..1AFF3 ; Katakana + "Zzzz", # 1AFF4..1AFF4 ; Unknown + "Kana", # 1AFF5..1AFFB ; Katakana + "Zzzz", # 1AFFC..1AFFC ; Unknown + "Kana", # 1AFFD..1AFFE ; Katakana + "Zzzz", # 1AFFF..1AFFF ; Unknown + "Kana", # 1B000..1B000 ; Katakana + "Hira", # 1B001..1B11F ; Hiragana + "Kana", # 1B120..1B122 ; Katakana + "Zzzz", # 1B123..1B131 ; Unknown + "Hira", # 1B132..1B132 ; Hiragana + "Zzzz", # 1B133..1B14F ; Unknown + "Hira", # 1B150..1B152 ; Hiragana + "Zzzz", # 1B153..1B154 ; Unknown + "Kana", # 1B155..1B155 ; Katakana + "Zzzz", # 1B156..1B163 ; Unknown + "Kana", # 1B164..1B167 ; Katakana + "Zzzz", # 1B168..1B16F ; Unknown + "Nshu", # 1B170..1B2FB ; Nushu + "Zzzz", # 1B2FC..1BBFF ; Unknown + "Dupl", # 1BC00..1BC6A ; Duployan + "Zzzz", # 1BC6B..1BC6F ; Unknown + "Dupl", # 1BC70..1BC7C ; Duployan + "Zzzz", # 1BC7D..1BC7F ; Unknown + "Dupl", # 1BC80..1BC88 ; Duployan + "Zzzz", # 1BC89..1BC8F ; Unknown + "Dupl", # 1BC90..1BC99 ; Duployan + "Zzzz", # 1BC9A..1BC9B ; Unknown + "Dupl", # 1BC9C..1BC9F ; Duployan + "Zyyy", # 1BCA0..1BCA3 ; Common + "Zzzz", # 1BCA4..1CBFF ; Unknown + "Zyyy", # 1CC00..1CCFC ; Common + "Zzzz", # 1CCFD..1CCFF ; Unknown + "Zyyy", # 1CD00..1CEB3 ; Common + "Zzzz", # 1CEB4..1CEB9 ; Unknown + "Zyyy", # 1CEBA..1CED0 ; Common + "Zzzz", # 1CED1..1CEDF ; Unknown + "Zyyy", # 1CEE0..1CEF0 ; Common + "Zzzz", # 1CEF1..1CEFF ; Unknown + "Zinh", # 1CF00..1CF2D ; Inherited + "Zzzz", # 1CF2E..1CF2F ; Unknown + "Zinh", # 1CF30..1CF46 ; Inherited + "Zzzz", # 1CF47..1CF4F ; Unknown + "Zyyy", # 1CF50..1CFC3 ; Common + "Zzzz", # 1CFC4..1CFFF ; Unknown + "Zyyy", # 1D000..1D0F5 ; Common + "Zzzz", # 1D0F6..1D0FF ; Unknown + "Zyyy", # 1D100..1D126 ; Common + "Zzzz", # 1D127..1D128 ; Unknown + "Zyyy", # 1D129..1D166 ; Common + "Zinh", # 1D167..1D169 ; Inherited + "Zyyy", # 1D16A..1D17A ; Common + "Zinh", # 1D17B..1D182 ; Inherited + "Zyyy", # 1D183..1D184 ; Common + "Zinh", # 1D185..1D18B ; Inherited + "Zyyy", # 1D18C..1D1A9 ; Common + "Zinh", # 1D1AA..1D1AD ; Inherited + "Zyyy", # 1D1AE..1D1EA ; Common + "Zzzz", # 1D1EB..1D1FF ; Unknown + "Grek", # 1D200..1D245 ; Greek + "Zzzz", # 1D246..1D2BF ; Unknown + "Zyyy", # 1D2C0..1D2D3 ; Common + "Zzzz", # 1D2D4..1D2DF ; Unknown + "Zyyy", # 1D2E0..1D2F3 ; Common + "Zzzz", # 1D2F4..1D2FF ; Unknown + "Zyyy", # 1D300..1D356 ; Common + "Zzzz", # 1D357..1D35F ; Unknown + "Zyyy", # 1D360..1D378 ; Common + "Zzzz", # 1D379..1D3FF ; Unknown + "Zyyy", # 1D400..1D454 ; Common + "Zzzz", # 1D455..1D455 ; Unknown + "Zyyy", # 1D456..1D49C ; Common + "Zzzz", # 1D49D..1D49D ; Unknown + "Zyyy", # 1D49E..1D49F ; Common + "Zzzz", # 1D4A0..1D4A1 ; Unknown + "Zyyy", # 1D4A2..1D4A2 ; Common + "Zzzz", # 1D4A3..1D4A4 ; Unknown + "Zyyy", # 1D4A5..1D4A6 ; Common + "Zzzz", # 1D4A7..1D4A8 ; Unknown + "Zyyy", # 1D4A9..1D4AC ; Common + "Zzzz", # 1D4AD..1D4AD ; Unknown + "Zyyy", # 1D4AE..1D4B9 ; Common + "Zzzz", # 1D4BA..1D4BA ; Unknown + "Zyyy", # 1D4BB..1D4BB ; Common + "Zzzz", # 1D4BC..1D4BC ; Unknown + "Zyyy", # 1D4BD..1D4C3 ; Common + "Zzzz", # 1D4C4..1D4C4 ; Unknown + "Zyyy", # 1D4C5..1D505 ; Common + "Zzzz", # 1D506..1D506 ; Unknown + "Zyyy", # 1D507..1D50A ; Common + "Zzzz", # 1D50B..1D50C ; Unknown + "Zyyy", # 1D50D..1D514 ; Common + "Zzzz", # 1D515..1D515 ; Unknown + "Zyyy", # 1D516..1D51C ; Common + "Zzzz", # 1D51D..1D51D ; Unknown + "Zyyy", # 1D51E..1D539 ; Common + "Zzzz", # 1D53A..1D53A ; Unknown + "Zyyy", # 1D53B..1D53E ; Common + "Zzzz", # 1D53F..1D53F ; Unknown + "Zyyy", # 1D540..1D544 ; Common + "Zzzz", # 1D545..1D545 ; Unknown + "Zyyy", # 1D546..1D546 ; Common + "Zzzz", # 1D547..1D549 ; Unknown + "Zyyy", # 1D54A..1D550 ; Common + "Zzzz", # 1D551..1D551 ; Unknown + "Zyyy", # 1D552..1D6A5 ; Common + "Zzzz", # 1D6A6..1D6A7 ; Unknown + "Zyyy", # 1D6A8..1D7CB ; Common + "Zzzz", # 1D7CC..1D7CD ; Unknown + "Zyyy", # 1D7CE..1D7FF ; Common + "Sgnw", # 1D800..1DA8B ; SignWriting + "Zzzz", # 1DA8C..1DA9A ; Unknown + "Sgnw", # 1DA9B..1DA9F ; SignWriting + "Zzzz", # 1DAA0..1DAA0 ; Unknown + "Sgnw", # 1DAA1..1DAAF ; SignWriting + "Zzzz", # 1DAB0..1DEFF ; Unknown + "Latn", # 1DF00..1DF1E ; Latin + "Zzzz", # 1DF1F..1DF24 ; Unknown + "Latn", # 1DF25..1DF2A ; Latin + "Zzzz", # 1DF2B..1DFFF ; Unknown + "Glag", # 1E000..1E006 ; Glagolitic + "Zzzz", # 1E007..1E007 ; Unknown + "Glag", # 1E008..1E018 ; Glagolitic + "Zzzz", # 1E019..1E01A ; Unknown + "Glag", # 1E01B..1E021 ; Glagolitic + "Zzzz", # 1E022..1E022 ; Unknown + "Glag", # 1E023..1E024 ; Glagolitic + "Zzzz", # 1E025..1E025 ; Unknown + "Glag", # 1E026..1E02A ; Glagolitic + "Zzzz", # 1E02B..1E02F ; Unknown + "Cyrl", # 1E030..1E06D ; Cyrillic + "Zzzz", # 1E06E..1E08E ; Unknown + "Cyrl", # 1E08F..1E08F ; Cyrillic + "Zzzz", # 1E090..1E0FF ; Unknown + "Hmnp", # 1E100..1E12C ; Nyiakeng_Puachue_Hmong + "Zzzz", # 1E12D..1E12F ; Unknown + "Hmnp", # 1E130..1E13D ; Nyiakeng_Puachue_Hmong + "Zzzz", # 1E13E..1E13F ; Unknown + "Hmnp", # 1E140..1E149 ; Nyiakeng_Puachue_Hmong + "Zzzz", # 1E14A..1E14D ; Unknown + "Hmnp", # 1E14E..1E14F ; Nyiakeng_Puachue_Hmong + "Zzzz", # 1E150..1E28F ; Unknown + "Toto", # 1E290..1E2AE ; Toto + "Zzzz", # 1E2AF..1E2BF ; Unknown + "Wcho", # 1E2C0..1E2F9 ; Wancho + "Zzzz", # 1E2FA..1E2FE ; Unknown + "Wcho", # 1E2FF..1E2FF ; Wancho + "Zzzz", # 1E300..1E4CF ; Unknown + "Nagm", # 1E4D0..1E4F9 ; Nag_Mundari + "Zzzz", # 1E4FA..1E5CF ; Unknown + "Onao", # 1E5D0..1E5FA ; Ol_Onal + "Zzzz", # 1E5FB..1E5FE ; Unknown + "Onao", # 1E5FF..1E5FF ; Ol_Onal + "Zzzz", # 1E600..1E6BF ; Unknown + "Tayo", # 1E6C0..1E6DE ; Tai_Yo + "Zzzz", # 1E6DF..1E6DF ; Unknown + "Tayo", # 1E6E0..1E6F5 ; Tai_Yo + "Zzzz", # 1E6F6..1E6FD ; Unknown + "Tayo", # 1E6FE..1E6FF ; Tai_Yo + "Zzzz", # 1E700..1E7DF ; Unknown + "Ethi", # 1E7E0..1E7E6 ; Ethiopic + "Zzzz", # 1E7E7..1E7E7 ; Unknown + "Ethi", # 1E7E8..1E7EB ; Ethiopic + "Zzzz", # 1E7EC..1E7EC ; Unknown + "Ethi", # 1E7ED..1E7EE ; Ethiopic + "Zzzz", # 1E7EF..1E7EF ; Unknown + "Ethi", # 1E7F0..1E7FE ; Ethiopic + "Zzzz", # 1E7FF..1E7FF ; Unknown + "Mend", # 1E800..1E8C4 ; Mende_Kikakui + "Zzzz", # 1E8C5..1E8C6 ; Unknown + "Mend", # 1E8C7..1E8D6 ; Mende_Kikakui + "Zzzz", # 1E8D7..1E8FF ; Unknown + "Adlm", # 1E900..1E94B ; Adlam + "Zzzz", # 1E94C..1E94F ; Unknown + "Adlm", # 1E950..1E959 ; Adlam + "Zzzz", # 1E95A..1E95D ; Unknown + "Adlm", # 1E95E..1E95F ; Adlam + "Zzzz", # 1E960..1EC70 ; Unknown + "Zyyy", # 1EC71..1ECB4 ; Common + "Zzzz", # 1ECB5..1ED00 ; Unknown + "Zyyy", # 1ED01..1ED3D ; Common + "Zzzz", # 1ED3E..1EDFF ; Unknown + "Arab", # 1EE00..1EE03 ; Arabic + "Zzzz", # 1EE04..1EE04 ; Unknown + "Arab", # 1EE05..1EE1F ; Arabic + "Zzzz", # 1EE20..1EE20 ; Unknown + "Arab", # 1EE21..1EE22 ; Arabic + "Zzzz", # 1EE23..1EE23 ; Unknown + "Arab", # 1EE24..1EE24 ; Arabic + "Zzzz", # 1EE25..1EE26 ; Unknown + "Arab", # 1EE27..1EE27 ; Arabic + "Zzzz", # 1EE28..1EE28 ; Unknown + "Arab", # 1EE29..1EE32 ; Arabic + "Zzzz", # 1EE33..1EE33 ; Unknown + "Arab", # 1EE34..1EE37 ; Arabic + "Zzzz", # 1EE38..1EE38 ; Unknown + "Arab", # 1EE39..1EE39 ; Arabic + "Zzzz", # 1EE3A..1EE3A ; Unknown + "Arab", # 1EE3B..1EE3B ; Arabic + "Zzzz", # 1EE3C..1EE41 ; Unknown + "Arab", # 1EE42..1EE42 ; Arabic + "Zzzz", # 1EE43..1EE46 ; Unknown + "Arab", # 1EE47..1EE47 ; Arabic + "Zzzz", # 1EE48..1EE48 ; Unknown + "Arab", # 1EE49..1EE49 ; Arabic + "Zzzz", # 1EE4A..1EE4A ; Unknown + "Arab", # 1EE4B..1EE4B ; Arabic + "Zzzz", # 1EE4C..1EE4C ; Unknown + "Arab", # 1EE4D..1EE4F ; Arabic + "Zzzz", # 1EE50..1EE50 ; Unknown + "Arab", # 1EE51..1EE52 ; Arabic + "Zzzz", # 1EE53..1EE53 ; Unknown + "Arab", # 1EE54..1EE54 ; Arabic + "Zzzz", # 1EE55..1EE56 ; Unknown + "Arab", # 1EE57..1EE57 ; Arabic + "Zzzz", # 1EE58..1EE58 ; Unknown + "Arab", # 1EE59..1EE59 ; Arabic + "Zzzz", # 1EE5A..1EE5A ; Unknown + "Arab", # 1EE5B..1EE5B ; Arabic + "Zzzz", # 1EE5C..1EE5C ; Unknown + "Arab", # 1EE5D..1EE5D ; Arabic + "Zzzz", # 1EE5E..1EE5E ; Unknown + "Arab", # 1EE5F..1EE5F ; Arabic + "Zzzz", # 1EE60..1EE60 ; Unknown + "Arab", # 1EE61..1EE62 ; Arabic + "Zzzz", # 1EE63..1EE63 ; Unknown + "Arab", # 1EE64..1EE64 ; Arabic + "Zzzz", # 1EE65..1EE66 ; Unknown + "Arab", # 1EE67..1EE6A ; Arabic + "Zzzz", # 1EE6B..1EE6B ; Unknown + "Arab", # 1EE6C..1EE72 ; Arabic + "Zzzz", # 1EE73..1EE73 ; Unknown + "Arab", # 1EE74..1EE77 ; Arabic + "Zzzz", # 1EE78..1EE78 ; Unknown + "Arab", # 1EE79..1EE7C ; Arabic + "Zzzz", # 1EE7D..1EE7D ; Unknown + "Arab", # 1EE7E..1EE7E ; Arabic + "Zzzz", # 1EE7F..1EE7F ; Unknown + "Arab", # 1EE80..1EE89 ; Arabic + "Zzzz", # 1EE8A..1EE8A ; Unknown + "Arab", # 1EE8B..1EE9B ; Arabic + "Zzzz", # 1EE9C..1EEA0 ; Unknown + "Arab", # 1EEA1..1EEA3 ; Arabic + "Zzzz", # 1EEA4..1EEA4 ; Unknown + "Arab", # 1EEA5..1EEA9 ; Arabic + "Zzzz", # 1EEAA..1EEAA ; Unknown + "Arab", # 1EEAB..1EEBB ; Arabic + "Zzzz", # 1EEBC..1EEEF ; Unknown + "Arab", # 1EEF0..1EEF1 ; Arabic + "Zzzz", # 1EEF2..1EFFF ; Unknown + "Zyyy", # 1F000..1F02B ; Common + "Zzzz", # 1F02C..1F02F ; Unknown + "Zyyy", # 1F030..1F093 ; Common + "Zzzz", # 1F094..1F09F ; Unknown + "Zyyy", # 1F0A0..1F0AE ; Common + "Zzzz", # 1F0AF..1F0B0 ; Unknown + "Zyyy", # 1F0B1..1F0BF ; Common + "Zzzz", # 1F0C0..1F0C0 ; Unknown + "Zyyy", # 1F0C1..1F0CF ; Common + "Zzzz", # 1F0D0..1F0D0 ; Unknown + "Zyyy", # 1F0D1..1F0F5 ; Common + "Zzzz", # 1F0F6..1F0FF ; Unknown + "Zyyy", # 1F100..1F1AD ; Common + "Zzzz", # 1F1AE..1F1E5 ; Unknown + "Zyyy", # 1F1E6..1F1FF ; Common + "Hira", # 1F200..1F200 ; Hiragana + "Zyyy", # 1F201..1F202 ; Common + "Zzzz", # 1F203..1F20F ; Unknown + "Zyyy", # 1F210..1F23B ; Common + "Zzzz", # 1F23C..1F23F ; Unknown + "Zyyy", # 1F240..1F248 ; Common + "Zzzz", # 1F249..1F24F ; Unknown + "Zyyy", # 1F250..1F251 ; Common + "Zzzz", # 1F252..1F25F ; Unknown + "Zyyy", # 1F260..1F265 ; Common + "Zzzz", # 1F266..1F2FF ; Unknown + "Zyyy", # 1F300..1F6D8 ; Common + "Zzzz", # 1F6D9..1F6DB ; Unknown + "Zyyy", # 1F6DC..1F6EC ; Common + "Zzzz", # 1F6ED..1F6EF ; Unknown + "Zyyy", # 1F6F0..1F6FC ; Common + "Zzzz", # 1F6FD..1F6FF ; Unknown + "Zyyy", # 1F700..1F7D9 ; Common + "Zzzz", # 1F7DA..1F7DF ; Unknown + "Zyyy", # 1F7E0..1F7EB ; Common + "Zzzz", # 1F7EC..1F7EF ; Unknown + "Zyyy", # 1F7F0..1F7F0 ; Common + "Zzzz", # 1F7F1..1F7FF ; Unknown + "Zyyy", # 1F800..1F80B ; Common + "Zzzz", # 1F80C..1F80F ; Unknown + "Zyyy", # 1F810..1F847 ; Common + "Zzzz", # 1F848..1F84F ; Unknown + "Zyyy", # 1F850..1F859 ; Common + "Zzzz", # 1F85A..1F85F ; Unknown + "Zyyy", # 1F860..1F887 ; Common + "Zzzz", # 1F888..1F88F ; Unknown + "Zyyy", # 1F890..1F8AD ; Common + "Zzzz", # 1F8AE..1F8AF ; Unknown + "Zyyy", # 1F8B0..1F8BB ; Common + "Zzzz", # 1F8BC..1F8BF ; Unknown + "Zyyy", # 1F8C0..1F8C1 ; Common + "Zzzz", # 1F8C2..1F8CF ; Unknown + "Zyyy", # 1F8D0..1F8D8 ; Common + "Zzzz", # 1F8D9..1F8FF ; Unknown + "Zyyy", # 1F900..1FA57 ; Common + "Zzzz", # 1FA58..1FA5F ; Unknown + "Zyyy", # 1FA60..1FA6D ; Common + "Zzzz", # 1FA6E..1FA6F ; Unknown + "Zyyy", # 1FA70..1FA7C ; Common + "Zzzz", # 1FA7D..1FA7F ; Unknown + "Zyyy", # 1FA80..1FA8A ; Common + "Zzzz", # 1FA8B..1FA8D ; Unknown + "Zyyy", # 1FA8E..1FAC6 ; Common + "Zzzz", # 1FAC7..1FAC7 ; Unknown + "Zyyy", # 1FAC8..1FAC8 ; Common + "Zzzz", # 1FAC9..1FACC ; Unknown + "Zyyy", # 1FACD..1FADC ; Common + "Zzzz", # 1FADD..1FADE ; Unknown + "Zyyy", # 1FADF..1FAEA ; Common + "Zzzz", # 1FAEB..1FAEE ; Unknown + "Zyyy", # 1FAEF..1FAF8 ; Common + "Zzzz", # 1FAF9..1FAFF ; Unknown + "Zyyy", # 1FB00..1FB92 ; Common + "Zzzz", # 1FB93..1FB93 ; Unknown + "Zyyy", # 1FB94..1FBFA ; Common + "Zzzz", # 1FBFB..1FFFF ; Unknown + "Hani", # 20000..2A6DF ; Han + "Zzzz", # 2A6E0..2A6FF ; Unknown + "Hani", # 2A700..2B81D ; Han + "Zzzz", # 2B81E..2B81F ; Unknown + "Hani", # 2B820..2CEAD ; Han + "Zzzz", # 2CEAE..2CEAF ; Unknown + "Hani", # 2CEB0..2EBE0 ; Han + "Zzzz", # 2EBE1..2EBEF ; Unknown + "Hani", # 2EBF0..2EE5D ; Han + "Zzzz", # 2EE5E..2F7FF ; Unknown + "Hani", # 2F800..2FA1D ; Han + "Zzzz", # 2FA1E..2FFFF ; Unknown + "Hani", # 30000..3134A ; Han + "Zzzz", # 3134B..3134F ; Unknown + "Hani", # 31350..33479 ; Han + "Zzzz", # 3347A..E0000 ; Unknown + "Zyyy", # E0001..E0001 ; Common + "Zzzz", # E0002..E001F ; Unknown + "Zyyy", # E0020..E007F ; Common + "Zzzz", # E0080..E00FF ; Unknown + "Zinh", # E0100..E01EF ; Inherited + "Zzzz", # E01F0..10FFFF ; Unknown +] + +NAMES = { + "Adlm": "Adlam", + "Aghb": "Caucasian_Albanian", + "Ahom": "Ahom", + "Arab": "Arabic", + "Armi": "Imperial_Aramaic", + "Armn": "Armenian", + "Avst": "Avestan", + "Bali": "Balinese", + "Bamu": "Bamum", + "Bass": "Bassa_Vah", + "Batk": "Batak", + "Beng": "Bengali", + "Berf": "Beria_Erfe", + "Bhks": "Bhaiksuki", + "Bopo": "Bopomofo", + "Brah": "Brahmi", + "Brai": "Braille", + "Bugi": "Buginese", + "Buhd": "Buhid", + "Cakm": "Chakma", + "Cans": "Canadian_Aboriginal", + "Cari": "Carian", + "Cham": "Cham", + "Cher": "Cherokee", + "Chrs": "Chorasmian", + "Copt": "Coptic", + "Cpmn": "Cypro_Minoan", + "Cprt": "Cypriot", + "Cyrl": "Cyrillic", + "Deva": "Devanagari", + "Diak": "Dives_Akuru", + "Dogr": "Dogra", + "Dsrt": "Deseret", + "Dupl": "Duployan", + "Egyp": "Egyptian_Hieroglyphs", + "Elba": "Elbasan", + "Elym": "Elymaic", + "Ethi": "Ethiopic", + "Gara": "Garay", + "Geor": "Georgian", + "Glag": "Glagolitic", + "Gong": "Gunjala_Gondi", + "Gonm": "Masaram_Gondi", + "Goth": "Gothic", + "Gran": "Grantha", + "Grek": "Greek", + "Gujr": "Gujarati", + "Gukh": "Gurung_Khema", + "Guru": "Gurmukhi", + "Hang": "Hangul", + "Hani": "Han", + "Hano": "Hanunoo", + "Hatr": "Hatran", + "Hebr": "Hebrew", + "Hira": "Hiragana", + "Hluw": "Anatolian_Hieroglyphs", + "Hmng": "Pahawh_Hmong", + "Hmnp": "Nyiakeng_Puachue_Hmong", + "Hrkt": "Katakana_Or_Hiragana", + "Hung": "Old_Hungarian", + "Ital": "Old_Italic", + "Java": "Javanese", + "Kali": "Kayah_Li", + "Kana": "Katakana", + "Kawi": "Kawi", + "Khar": "Kharoshthi", + "Khmr": "Khmer", + "Khoj": "Khojki", + "Kits": "Khitan_Small_Script", + "Knda": "Kannada", + "Krai": "Kirat_Rai", + "Kthi": "Kaithi", + "Lana": "Tai_Tham", + "Laoo": "Lao", + "Latn": "Latin", + "Lepc": "Lepcha", + "Limb": "Limbu", + "Lina": "Linear_A", + "Linb": "Linear_B", + "Lisu": "Lisu", + "Lyci": "Lycian", + "Lydi": "Lydian", + "Mahj": "Mahajani", + "Maka": "Makasar", + "Mand": "Mandaic", + "Mani": "Manichaean", + "Marc": "Marchen", + "Medf": "Medefaidrin", + "Mend": "Mende_Kikakui", + "Merc": "Meroitic_Cursive", + "Mero": "Meroitic_Hieroglyphs", + "Mlym": "Malayalam", + "Modi": "Modi", + "Mong": "Mongolian", + "Mroo": "Mro", + "Mtei": "Meetei_Mayek", + "Mult": "Multani", + "Mymr": "Myanmar", + "Nagm": "Nag_Mundari", + "Nand": "Nandinagari", + "Narb": "Old_North_Arabian", + "Nbat": "Nabataean", + "Newa": "Newa", + "Nkoo": "Nko", + "Nshu": "Nushu", + "Ogam": "Ogham", + "Olck": "Ol_Chiki", + "Onao": "Ol_Onal", + "Orkh": "Old_Turkic", + "Orya": "Oriya", + "Osge": "Osage", + "Osma": "Osmanya", + "Ougr": "Old_Uyghur", + "Palm": "Palmyrene", + "Pauc": "Pau_Cin_Hau", + "Perm": "Old_Permic", + "Phag": "Phags_Pa", + "Phli": "Inscriptional_Pahlavi", + "Phlp": "Psalter_Pahlavi", + "Phnx": "Phoenician", + "Plrd": "Miao", + "Prti": "Inscriptional_Parthian", + "Rjng": "Rejang", + "Rohg": "Hanifi_Rohingya", + "Runr": "Runic", + "Samr": "Samaritan", + "Sarb": "Old_South_Arabian", + "Saur": "Saurashtra", + "Sgnw": "SignWriting", + "Shaw": "Shavian", + "Shrd": "Sharada", + "Sidd": "Siddham", + "Sidt": "Sidetic", + "Sind": "Khudawadi", + "Sinh": "Sinhala", + "Sogd": "Sogdian", + "Sogo": "Old_Sogdian", + "Sora": "Sora_Sompeng", + "Soyo": "Soyombo", + "Sund": "Sundanese", + "Sunu": "Sunuwar", + "Sylo": "Syloti_Nagri", + "Syrc": "Syriac", + "Tagb": "Tagbanwa", + "Takr": "Takri", + "Tale": "Tai_Le", + "Talu": "New_Tai_Lue", + "Taml": "Tamil", + "Tang": "Tangut", + "Tavt": "Tai_Viet", + "Tayo": "Tai_Yo", + "Telu": "Telugu", + "Tfng": "Tifinagh", + "Tglg": "Tagalog", + "Thaa": "Thaana", + "Thai": "Thai", + "Tibt": "Tibetan", + "Tirh": "Tirhuta", + "Tnsa": "Tangsa", + "Todr": "Todhri", + "Tols": "Tolong_Siki", + "Toto": "Toto", + "Tutg": "Tulu_Tigalari", + "Ugar": "Ugaritic", + "Vaii": "Vai", + "Vith": "Vithkuqi", + "Wara": "Warang_Citi", + "Wcho": "Wancho", + "Xpeo": "Old_Persian", + "Xsux": "Cuneiform", + "Yezi": "Yezidi", + "Yiii": "Yi", + "Zanb": "Zanabazar_Square", + "Zinh": "Inherited", + "Zyyy": "Common", + "Zzzz": "Unknown", +} diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__init__.py b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef73951297bd96b18074039185f09fc6ee28637d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__init__.py @@ -0,0 +1,305 @@ +from __future__ import annotations + +from fontTools.misc.textTools import byteord, tostr + +import re +from bisect import bisect_right +from typing import Literal, TypeVar, overload + +try: + # use unicodedata backport compatible with python2: + # https://github.com/fonttools/unicodedata2 + from unicodedata2 import * +except ImportError: # pragma: no cover + # fall back to built-in unicodedata (possibly outdated) + from unicodedata import * + +from . import Blocks, Mirrored, Scripts, ScriptExtensions, OTTags + +__all__ = [ + # names from built-in unicodedata module + "lookup", + "name", + "decimal", + "digit", + "numeric", + "category", + "bidirectional", + "combining", + "east_asian_width", + "mirrored", + "decomposition", + "normalize", + "unidata_version", + "ucd_3_2_0", + # additonal functions + "block", + "script", + "script_extension", + "script_name", + "script_code", + "script_horizontal_direction", + "ot_tags_from_script", + "ot_tag_to_script", +] + + +def mirrored(code): + """If code (unicode codepoint) has a mirrored version returns it, otherwise None.""" + return Mirrored.MIRRORED.get(code) + + +def script(char): + """Return the four-letter script code assigned to the Unicode character + 'char' as string. + + >>> script("a") + 'Latn' + >>> script(",") + 'Zyyy' + >>> script(chr(0x10FFFF)) + 'Zzzz' + """ + code = byteord(char) + # 'bisect_right(a, x, lo=0, hi=len(a))' returns an insertion point which + # comes after (to the right of) any existing entries of x in a, and it + # partitions array a into two halves so that, for the left side + # all(val <= x for val in a[lo:i]), and for the right side + # all(val > x for val in a[i:hi]). + # Our 'SCRIPT_RANGES' is a sorted list of ranges (only their starting + # breakpoints); we want to use `bisect_right` to look up the range that + # contains the given codepoint: i.e. whose start is less than or equal + # to the codepoint. Thus, we subtract -1 from the index returned. + i = bisect_right(Scripts.RANGES, code) + return Scripts.VALUES[i - 1] + + +def script_extension(char): + """Return the script extension property assigned to the Unicode character + 'char' as a set of string. + + >>> script_extension("a") == {'Latn'} + True + >>> script_extension(chr(0x060C)) == {'Nkoo', 'Arab', 'Rohg', 'Thaa', 'Syrc', 'Gara', 'Yezi'} + True + >>> script_extension(chr(0x10FFFF)) == {'Zzzz'} + True + """ + code = byteord(char) + i = bisect_right(ScriptExtensions.RANGES, code) + value = ScriptExtensions.VALUES[i - 1] + if value is None: + # code points not explicitly listed for Script Extensions + # have as their value the corresponding Script property value + return {script(char)} + return value + + +def script_name(code, default=KeyError): + """Return the long, human-readable script name given a four-letter + Unicode script code. + + If no matching name is found, a KeyError is raised by default. + + You can use the 'default' argument to return a fallback value (e.g. + 'Unknown' or None) instead of throwing an error. + """ + try: + return str(Scripts.NAMES[code].replace("_", " ")) + except KeyError: + if isinstance(default, type) and issubclass(default, KeyError): + raise + return default + + +_normalize_re = re.compile(r"[-_ ]+") + + +def _normalize_property_name(string): + """Remove case, strip space, '-' and '_' for loose matching.""" + return _normalize_re.sub("", string).lower() + + +_SCRIPT_CODES = {_normalize_property_name(v): k for k, v in Scripts.NAMES.items()} + + +def script_code(script_name, default=KeyError): + """Returns the four-letter Unicode script code from its long name + + If no matching script code is found, a KeyError is raised by default. + + You can use the 'default' argument to return a fallback string (e.g. + 'Zzzz' or None) instead of throwing an error. + """ + normalized_name = _normalize_property_name(script_name) + try: + return _SCRIPT_CODES[normalized_name] + except KeyError: + if isinstance(default, type) and issubclass(default, KeyError): + raise + return default + + +# The data on script direction is taken from Harfbuzz source code: +# https://github.com/harfbuzz/harfbuzz/blob/3.2.0/src/hb-common.cc#L514-L613 +# This in turn references the following "Script_Metadata" document: +# https://docs.google.com/spreadsheets/d/1Y90M0Ie3MUJ6UVCRDOypOtijlMDLNNyyLk36T6iMu0o +RTL_SCRIPTS = { + # Unicode-1.1 additions + "Arab", # Arabic + "Hebr", # Hebrew + # Unicode-3.0 additions + "Syrc", # Syriac + "Thaa", # Thaana + # Unicode-4.0 additions + "Cprt", # Cypriot + # Unicode-4.1 additions + "Khar", # Kharoshthi + # Unicode-5.0 additions + "Phnx", # Phoenician + "Nkoo", # Nko + # Unicode-5.1 additions + "Lydi", # Lydian + # Unicode-5.2 additions + "Avst", # Avestan + "Armi", # Imperial Aramaic + "Phli", # Inscriptional Pahlavi + "Prti", # Inscriptional Parthian + "Sarb", # Old South Arabian + "Orkh", # Old Turkic + "Samr", # Samaritan + # Unicode-6.0 additions + "Mand", # Mandaic + # Unicode-6.1 additions + "Merc", # Meroitic Cursive + "Mero", # Meroitic Hieroglyphs + # Unicode-7.0 additions + "Mani", # Manichaean + "Mend", # Mende Kikakui + "Nbat", # Nabataean + "Narb", # Old North Arabian + "Palm", # Palmyrene + "Phlp", # Psalter Pahlavi + # Unicode-8.0 additions + "Hatr", # Hatran + "Hung", # Old Hungarian + # Unicode-9.0 additions + "Adlm", # Adlam + # Unicode-11.0 additions + "Rohg", # Hanifi Rohingya + "Sogo", # Old Sogdian + "Sogd", # Sogdian + # Unicode-12.0 additions + "Elym", # Elymaic + # Unicode-13.0 additions + "Chrs", # Chorasmian + "Yezi", # Yezidi + # Unicode-14.0 additions + "Ougr", # Old Uyghur + # Unicode-16.0 additions + "Gara", # Garay + # Unicode-17.0 additions + "Sidt", # Sidetic +} + + +HorizDirection = Literal["RTL", "LTR"] +T = TypeVar("T") + + +@overload +def script_horizontal_direction(script_code: str, default: T) -> HorizDirection | T: ... + + +@overload +def script_horizontal_direction( + script_code: str, default: type[KeyError] = KeyError +) -> HorizDirection: ... + + +def script_horizontal_direction( + script_code: str, default: T | type[KeyError] = KeyError +) -> HorizDirection | T: + """Return "RTL" for scripts that contain right-to-left characters + according to the Bidi_Class property. Otherwise return "LTR". + """ + if script_code not in Scripts.NAMES: + if isinstance(default, type) and issubclass(default, KeyError): + raise default(script_code) + return default + return "RTL" if script_code in RTL_SCRIPTS else "LTR" + + +def block(char): + """Return the block property assigned to the Unicode character 'char' + as a string. + + >>> block("a") + 'Basic Latin' + >>> block(chr(0x060C)) + 'Arabic' + >>> block(chr(0xEFFFF)) + 'No_Block' + """ + code = byteord(char) + i = bisect_right(Blocks.RANGES, code) + return Blocks.VALUES[i - 1] + + +def ot_tags_from_script(script_code): + """Return a list of OpenType script tags associated with a given + Unicode script code. + Return ['DFLT'] script tag for invalid/unknown script codes. + """ + if script_code in OTTags.SCRIPT_EXCEPTIONS: + return [OTTags.SCRIPT_EXCEPTIONS[script_code]] + + if script_code not in Scripts.NAMES: + return [OTTags.DEFAULT_SCRIPT] + + script_tags = [script_code[0].lower() + script_code[1:]] + if script_code in OTTags.NEW_SCRIPT_TAGS: + script_tags.extend(OTTags.NEW_SCRIPT_TAGS[script_code]) + script_tags.reverse() # last in, first out + + return script_tags + + +def ot_tag_to_script(tag): + """Return the Unicode script code for the given OpenType script tag, or + None for "DFLT" tag or if there is no Unicode script associated with it. + Raises ValueError if the tag is invalid. + """ + tag = tostr(tag).strip() + if not tag or " " in tag or len(tag) > 4: + raise ValueError("invalid OpenType tag: %r" % tag) + + if tag in OTTags.SCRIPT_ALIASES: + tag = OTTags.SCRIPT_ALIASES[tag] + + while len(tag) != 4: + tag += str(" ") # pad with spaces + + if tag == OTTags.DEFAULT_SCRIPT: + # it's unclear which Unicode script the "DFLT" OpenType tag maps to, + # so here we return None + return None + + if tag in OTTags.NEW_SCRIPT_TAGS_REVERSED: + return OTTags.NEW_SCRIPT_TAGS_REVERSED[tag] + + if tag in OTTags.SCRIPT_EXCEPTIONS_REVERSED: + return OTTags.SCRIPT_EXCEPTIONS_REVERSED[tag] + + # This side of the conversion is fully algorithmic + + # Any spaces at the end of the tag are replaced by repeating the last + # letter. Eg 'nko ' -> 'Nkoo'. + # Change first char to uppercase + script_code = tag[0].upper() + tag[1] + for i in range(2, 4): + script_code += script_code[i - 1] if tag[i] == " " else tag[i] + + if script_code not in Scripts.NAMES: + return None + return script_code diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/Blocks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/Blocks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a52a20a7d08cb9dc857eb311f5d1a0375390577 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/Blocks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/Mirrored.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/Mirrored.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7941e9bf27671a4e2c7913ad67a6957258b0792b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/Mirrored.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/OTTags.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/OTTags.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30aafb79ca02c2e98ded728da9facc8db4be368a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/OTTags.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/ScriptExtensions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/ScriptExtensions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa1a1dfc721c3c0463f2e23d2b6a3999e2ab5bb3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/ScriptExtensions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/Scripts.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/Scripts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..741605f71852dd4646ed4b7895c9d3aecb87039f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/Scripts.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b12a1cb917492ab33135a3368a970597a80b550 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/unicodedata/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__init__.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b29b44719dc742ec92ac78fc2e5fd292fc48066 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/__init__.py @@ -0,0 +1,1581 @@ +""" +Module for dealing with 'gvar'-style font variations, also known as run-time +interpolation. + +The ideas here are very similar to MutatorMath. There is even code to read +MutatorMath .designspace files in the varLib.designspace module. + +For now, if you run this file on a designspace file, it tries to find +ttf-interpolatable files for the masters and build a variable-font from +them. Such ttf-interpolatable and designspace files can be generated from +a Glyphs source, eg., using noto-source as an example: + + .. code-block:: sh + + $ fontmake -o ttf-interpolatable -g NotoSansArabic-MM.glyphs + +Then you can make a variable-font this way: + + .. code-block:: sh + + $ fonttools varLib master_ufo/NotoSansArabic.designspace + +API *will* change in near future. +""" + +from typing import List +from fontTools.misc.vector import Vector +from fontTools.misc.roundTools import noRound, otRound +from fontTools.misc.fixedTools import floatToFixed as fl2fi +from fontTools.misc.textTools import Tag, tostr +from fontTools.ttLib import TTFont, newTable +from fontTools.ttLib.tables._f_v_a_r import Axis, NamedInstance +from fontTools.ttLib.tables._g_l_y_f import ( + GlyphCoordinates, + dropImpliedOnCurvePoints, + USE_MY_METRICS, +) +from fontTools.ttLib.tables.ttProgram import Program +from fontTools.ttLib.tables.TupleVariation import TupleVariation +from fontTools.ttLib.tables import otTables as ot +from fontTools.ttLib.tables.otBase import OTTableWriter +from fontTools.varLib import builder, models, varStore +from fontTools.varLib.merger import VariationMerger, COLRVariationMerger +from fontTools.varLib.mvar import MVAR_ENTRIES +from fontTools.varLib.iup import iup_delta_optimize +from fontTools.varLib.featureVars import addFeatureVariations +from fontTools.designspaceLib import DesignSpaceDocument, InstanceDescriptor +from fontTools.designspaceLib.split import splitInterpolable, splitVariableFonts +from fontTools.varLib.stat import buildVFStatTable +from fontTools.colorLib.builder import buildColrV1 +from fontTools.colorLib.unbuilder import unbuildColrV1 +from functools import partial +from collections import OrderedDict, defaultdict, namedtuple +import os.path +import logging +from copy import deepcopy +from pprint import pformat +from re import fullmatch +from .errors import VarLibError, VarLibValidationError + +log = logging.getLogger("fontTools.varLib") + +# This is a lib key for the designspace document. The value should be +# a comma-separated list of OpenType feature tag(s), to be used as the +# FeatureVariations feature. +# If present, the DesignSpace <rules processing="..."> flag is ignored. +FEAVAR_FEATURETAG_LIB_KEY = "com.github.fonttools.varLib.featureVarsFeatureTag" + +# +# Creation routines +# + + +def _add_fvar(font, axes, instances: List[InstanceDescriptor]): + """ + Add 'fvar' table to font. + + axes is an ordered dictionary of DesignspaceAxis objects. + + instances is list of dictionary objects with 'location', 'stylename', + and possibly 'postscriptfontname' entries. + """ + + assert axes + assert isinstance(axes, OrderedDict) + + log.info("Generating fvar") + + fvar = newTable("fvar") + nameTable = font["name"] + + # if there are not currently any mac names don't add them here, that's inconsistent + # https://github.com/fonttools/fonttools/issues/683 + macNames = any(nr.platformID == 1 for nr in getattr(nameTable, "names", ())) + + # we have all the best ways to express mac names + platforms = ((3, 1, 0x409),) + if macNames: + platforms = ((1, 0, 0),) + platforms + + for a in axes.values(): + axis = Axis() + axis.axisTag = Tag(a.tag) + # TODO Skip axes that have no variation. + axis.minValue, axis.defaultValue, axis.maxValue = ( + a.minimum, + a.default, + a.maximum, + ) + axis.axisNameID = nameTable.addMultilingualName( + a.labelNames, font, minNameID=256, mac=macNames + ) + axis.flags = int(a.hidden) + fvar.axes.append(axis) + + default_coordinates = {axis.axisTag: axis.defaultValue for axis in fvar.axes} + + for instance in instances: + # Filter out discrete axis locations + coordinates = { + name: value for name, value in instance.location.items() if name in axes + } + + if "en" not in instance.localisedStyleName: + if not instance.styleName: + raise VarLibValidationError( + f"Instance at location '{coordinates}' must have a default English " + "style name ('stylename' attribute on the instance element or a " + "stylename element with an 'xml:lang=\"en\"' attribute)." + ) + localisedStyleName = dict(instance.localisedStyleName) + localisedStyleName["en"] = tostr(instance.styleName) + else: + localisedStyleName = instance.localisedStyleName + + psname = instance.postScriptFontName + + inst = NamedInstance() + inst.coordinates = { + axes[k].tag: axes[k].map_backward(v) for k, v in coordinates.items() + } + + subfamilyNameID = nameTable.findMultilingualName( + localisedStyleName, windows=True, mac=macNames + ) + if subfamilyNameID in {2, 17} and inst.coordinates == default_coordinates: + # Instances can only reuse an existing name ID 2 or 17 if they are at the + # default location across all axes, see: + # https://github.com/fonttools/fonttools/issues/3825. + inst.subfamilyNameID = subfamilyNameID + else: + inst.subfamilyNameID = nameTable.addMultilingualName( + localisedStyleName, windows=True, mac=macNames, minNameID=256 + ) + + if psname is not None: + psname = tostr(psname) + inst.postscriptNameID = nameTable.addName(psname, platforms=platforms) + fvar.instances.append(inst) + + assert "fvar" not in font + font["fvar"] = fvar + + return fvar + + +def _add_avar(font, axes, mappings, axisTags): + """ + Add 'avar' table to font. + + axes is an ordered dictionary of AxisDescriptor objects. + """ + + assert axes + assert isinstance(axes, OrderedDict) + + log.info("Generating avar") + + avar = newTable("avar") + + interesting = False + vals_triples = {} + for axis in axes.values(): + axis_map = axis.get_validated_map() + + # Currently, some rasterizers require that the default value maps + # (-1 to -1, 0 to 0, and 1 to 1) be present for all the segment + # maps, even when the default normalization mapping for the axis + # was not modified. + # https://github.com/googlei18n/fontmake/issues/295 + # https://github.com/fonttools/fonttools/issues/1011 + # TODO(anthrotype) revert this (and 19c4b37) when issue is fixed + curve = avar.segments[axis.tag] = {-1.0: -1.0, 0.0: 0.0, 1.0: 1.0} + + keys_triple = (axis.minimum, axis.default, axis.maximum) + vals_triple = tuple(axis.map_forward(v) for v in keys_triple) + vals_triples[axis.tag] = vals_triple + if not axis_map: + continue + + # The validated view removes repeated pairs while preserving legal + # duplicate output values. + items = sorted(axis_map) + keys = [item[0] for item in items] + vals = [item[1] for item in items] + + # Current avar requirements. We don't have to enforce + # these on the designer and can deduce some ourselves, + # but for now just enforce them. + if axis.minimum != min(keys): + raise VarLibValidationError( + f"Axis '{axis.name}': there must be a mapping for the axis minimum " + f"value {axis.minimum} and it must be the lowest input mapping value." + ) + if axis.maximum != max(keys): + raise VarLibValidationError( + f"Axis '{axis.name}': there must be a mapping for the axis maximum " + f"value {axis.maximum} and it must be the highest input mapping value." + ) + if axis.default not in keys: + raise VarLibValidationError( + f"Axis '{axis.name}': there must be a mapping for the axis default " + f"value {axis.default}." + ) + # Ascending values + if sorted(vals) != vals: + raise VarLibValidationError( + f"Axis '{axis.name}': mapping output values must be in ascending order." + ) + + keys = [models.normalizeValue(v, keys_triple) for v in keys] + vals = [models.normalizeValue(v, vals_triple) for v in vals] + + if all(k == v for k, v in zip(keys, vals)): + continue + interesting = True + + curve.update(zip(keys, vals)) + + assert 0.0 in curve and curve[0.0] == 0.0 + assert -1.0 not in curve or curve[-1.0] == -1.0 + assert +1.0 not in curve or curve[+1.0] == +1.0 + # curve.update({-1.0: -1.0, 0.0: 0.0, 1.0: 1.0}) + + if mappings: + interesting = True + + inputLocations = [ + { + axes[name].tag: models.normalizeValue(v, vals_triples[axes[name].tag]) + for name, v in mapping.inputLocation.items() + } + for mapping in mappings + ] + outputLocations = [ + { + axes[name].tag: models.normalizeValue(v, vals_triples[axes[name].tag]) + for name, v in mapping.outputLocation.items() + } + for mapping in mappings + ] + assert len(inputLocations) == len(outputLocations) + + # If base-master is missing, insert it at zero location. + if not any(all(v == 0 for k, v in loc.items()) for loc in inputLocations): + inputLocations.insert(0, {}) + outputLocations.insert(0, {}) + + model = models.VariationModel(inputLocations, axisTags) + storeBuilder = varStore.OnlineVarStoreBuilder(axisTags) + storeBuilder.setModel(model) + varIdxes = {} + for tag in axisTags: + masterValues = [] + for vo, vi in zip(outputLocations, inputLocations): + if tag not in vo: + masterValues.append(0) + continue + v = vo[tag] - vi.get(tag, 0) + masterValues.append(fl2fi(v, 14)) + varIdxes[tag] = storeBuilder.storeMasters(masterValues)[1] + + store = storeBuilder.finish() + optimized = store.optimize() + varIdxes = {axis: optimized[value] for axis, value in varIdxes.items()} + + varIdxMap = builder.buildDeltaSetIndexMap(varIdxes[t] for t in axisTags) + + avar.majorVersion = 2 + avar.table = ot.avar() + avar.table.VarIdxMap = varIdxMap + avar.table.VarStore = store + + assert "avar" not in font + if not interesting: + log.info("No need for avar") + avar = None + else: + font["avar"] = avar + + return avar + + +def _add_stat(font): + # Note: this function only gets called by old code that calls `build()` + # directly. Newer code that wants to benefit from STAT data from the + # designspace should call `build_many()` + + if "STAT" in font: + return + + from ..otlLib.builder import buildStatTable + + fvarTable = font["fvar"] + axes = [dict(tag=a.axisTag, name=a.axisNameID) for a in fvarTable.axes] + buildStatTable(font, axes) + + +_MasterData = namedtuple("_MasterData", ["glyf", "hMetrics", "vMetrics"]) + + +def _add_gvar(font, masterModel, master_ttfs, tolerance=0.5, optimize=True): + if tolerance < 0: + raise ValueError("`tolerance` must be a positive number.") + + log.info("Generating gvar") + assert "gvar" not in font + gvar = font["gvar"] = newTable("gvar") + glyf = font["glyf"] + defaultMasterIndex = masterModel.reverseMapping[0] + + master_datas = [ + _MasterData( + m["glyf"], m["hmtx"].metrics, getattr(m.get("vmtx"), "metrics", None) + ) + for m in master_ttfs + ] + + for glyph in font.getGlyphOrder(): + log.debug("building gvar for glyph '%s'", glyph) + + allData = [ + m.glyf._getCoordinatesAndControls(glyph, m.hMetrics, m.vMetrics) + for m in master_datas + ] + + if allData[defaultMasterIndex][1].numberOfContours != 0: + # If the default master is not empty, interpret empty non-default masters + # as missing glyphs from a sparse master + allData = [ + d if d is not None and d[1].numberOfContours != 0 else None + for d in allData + ] + + model, allData = masterModel.getSubModel(allData) + + allCoords = [d[0] for d in allData] + allControls = [d[1] for d in allData] + control = allControls[0] + if not models.allEqual(allControls): + log.warning("glyph %s has incompatible masters; skipping" % glyph) + continue + del allControls + + # Update gvar + gvar.variations[glyph] = [] + deltas = model.getDeltas( + allCoords, round=partial(GlyphCoordinates.__round__, round=round) + ) + supports = model.supports + assert len(deltas) == len(supports) + + # Prepare for IUP optimization + origCoords = deltas[0] + endPts = control.endPts + + for i, (delta, support) in enumerate(zip(deltas[1:], supports[1:])): + if all(v == 0 for v in delta.array): + continue + var = TupleVariation(support, delta) + if optimize: + var.optimize(origCoords, endPts, tolerance=tolerance) + gvar.variations[glyph].append(var) + + +def _remove_TTHinting(font): + for tag in ("cvar", "cvt ", "fpgm", "prep"): + if tag in font: + del font[tag] + maxp = font["maxp"] + for attr in ( + "maxTwilightPoints", + "maxStorage", + "maxFunctionDefs", + "maxInstructionDefs", + "maxStackElements", + "maxSizeOfInstructions", + ): + setattr(maxp, attr, 0) + maxp.maxZones = 1 + font["glyf"].removeHinting() + # TODO: Modify gasp table to deactivate gridfitting for all ranges? + + +def _merge_TTHinting(font, masterModel, master_ttfs): + log.info("Merging TT hinting") + assert "cvar" not in font + + # Check that the existing hinting is compatible + + # fpgm and prep table + + for tag in ("fpgm", "prep"): + all_pgms = [m[tag].program for m in master_ttfs if tag in m] + if not all_pgms: + continue + font_pgm = getattr(font.get(tag), "program", None) + if any(pgm != font_pgm for pgm in all_pgms): + log.warning( + "Masters have incompatible %s tables, hinting is discarded." % tag + ) + _remove_TTHinting(font) + return + + # glyf table + + font_glyf = font["glyf"] + master_glyfs = [m["glyf"] for m in master_ttfs] + for name, glyph in font_glyf.glyphs.items(): + all_pgms = [getattr(glyf.get(name), "program", None) for glyf in master_glyfs] + if not any(all_pgms): + continue + glyph.expand(font_glyf) + font_pgm = getattr(glyph, "program", None) + if any(pgm != font_pgm for pgm in all_pgms if pgm): + log.warning( + "Masters have incompatible glyph programs in glyph '%s', hinting is discarded." + % name + ) + # TODO Only drop hinting from this glyph. + _remove_TTHinting(font) + return + + # cvt table + + all_cvs = [Vector(m["cvt "].values) if "cvt " in m else None for m in master_ttfs] + + nonNone_cvs = models.nonNone(all_cvs) + if not nonNone_cvs: + # There is no cvt table to make a cvar table from, we're done here. + return + + if not models.allEqual(len(c) for c in nonNone_cvs): + log.warning("Masters have incompatible cvt tables, hinting is discarded.") + _remove_TTHinting(font) + return + + variations = [] + deltas, supports = masterModel.getDeltasAndSupports( + all_cvs, round=round + ) # builtin round calls into Vector.__round__, which uses builtin round as we like + for i, (delta, support) in enumerate(zip(deltas[1:], supports[1:])): + if all(v == 0 for v in delta): + continue + var = TupleVariation(support, delta) + variations.append(var) + + # We can build the cvar table now. + if variations: + cvar = font["cvar"] = newTable("cvar") + cvar.version = 1 + cvar.variations = variations + + +def _has_inconsistent_use_my_metrics_flag( + master_glyf, glyph_name, flagged_components, expected_num_components +) -> bool: + master_glyph = master_glyf.get(glyph_name) + # 'sparse' glyph master doesn't contribute. Besides when components don't match + # the VF build is going to fail anyway, so be lenient here. + if ( + master_glyph is not None + and master_glyph.isComposite() + and len(master_glyph.components) == expected_num_components + ): + for i, base_glyph in flagged_components: + comp = master_glyph.components[i] + if comp.glyphName != base_glyph: + break + if not (comp.flags & USE_MY_METRICS): + return True + return False + + +def _unset_inconsistent_use_my_metrics_flags(vf, master_fonts): + """Clear USE_MY_METRICS on composite components if inconsistent across masters. + + If a composite glyph's component has USE_MY_METRICS set differently among + the masters, the flag is removed from the variable font's glyf table so that + advance widths are not determined by that single component's phantom points. + """ + glyf = vf["glyf"] + master_glyfs = [m["glyf"] for m in master_fonts if "glyf" in m] + if not master_glyfs: + # Should not happen: at least the base master (as copied into vf) has glyf + return + + for glyph_name in glyf.keys(): + glyph = glyf[glyph_name] + if not glyph.isComposite(): + continue + + # collect indices of component(s) that carry the USE_MY_METRICS flag. + # This is supposed to be 1 component per composite, but you never know. + flagged_components = [ + (i, comp.glyphName) + for i, comp in enumerate(glyph.components) + if (comp.flags & USE_MY_METRICS) + ] + if not flagged_components: + # Nothing to fix + continue + + # Verify that for all master glyf tables that contribute this glyph, the + # corresponding component (same glyphName and index) also carries USE_MY_METRICS + # and unset the flag if not. + expected_num_components = len(glyph.components) + if any( + _has_inconsistent_use_my_metrics_flag( + master_glyf, glyph_name, flagged_components, expected_num_components + ) + for master_glyf in master_glyfs + ): + comp_names = [name for _, name in flagged_components] + log.info( + "Composite glyph '%s' has inconsistent USE_MY_METRICS flags across " + "masters; clearing the flag on component%s %s", + glyph_name, + "s" if len(comp_names) > 1 else "", + comp_names if len(comp_names) > 1 else comp_names[0], + ) + for i, _ in flagged_components: + glyph.components[i].flags &= ~USE_MY_METRICS + + +_MetricsFields = namedtuple( + "_MetricsFields", + [ + "tableTag", + "metricsTag", + "sb1", + "sb2", + "advMapping", + "vOrigMapping", + "phantomIndex", + ], +) + +HVAR_FIELDS = _MetricsFields( + tableTag="HVAR", + metricsTag="hmtx", + sb1="LsbMap", + sb2="RsbMap", + advMapping="AdvWidthMap", + vOrigMapping=None, + phantomIndex=0, +) + +VVAR_FIELDS = _MetricsFields( + tableTag="VVAR", + metricsTag="vmtx", + sb1="TsbMap", + sb2="BsbMap", + advMapping="AdvHeightMap", + vOrigMapping="VOrgMap", + phantomIndex=1, +) + + +def _add_HVAR(font, masterModel, master_ttfs, axisTags): + getAdvanceMetrics = partial( + _get_advance_metrics, font, masterModel, master_ttfs, axisTags, HVAR_FIELDS + ) + _add_VHVAR(font, axisTags, HVAR_FIELDS, getAdvanceMetrics) + + +def _add_VVAR(font, masterModel, master_ttfs, axisTags): + getAdvanceMetrics = partial( + _get_advance_metrics, font, masterModel, master_ttfs, axisTags, VVAR_FIELDS + ) + _add_VHVAR(font, axisTags, VVAR_FIELDS, getAdvanceMetrics) + + +def _add_VHVAR(font, axisTags, tableFields, getAdvanceMetrics): + tableTag = tableFields.tableTag + assert tableTag not in font + glyphOrder = font.getGlyphOrder() + log.info("Generating " + tableTag) + VHVAR = newTable(tableTag) + tableClass = getattr(ot, tableTag) + vhvar = VHVAR.table = tableClass() + vhvar.Version = 0x00010000 + + vhAdvanceDeltasAndSupports, vOrigDeltasAndSupports = getAdvanceMetrics() + + if vOrigDeltasAndSupports: + singleModel = False + else: + singleModel = models.allEqual( + id(v[1]) for v in vhAdvanceDeltasAndSupports.values() + ) + + directStore = None + if singleModel: + # Build direct mapping + supports = next(iter(vhAdvanceDeltasAndSupports.values()))[1][1:] + varTupleList = builder.buildVarRegionList(supports, axisTags) + varTupleIndexes = list(range(len(supports))) + varData = builder.buildVarData(varTupleIndexes, [], optimize=False) + for glyphName in glyphOrder: + varData.addItem(vhAdvanceDeltasAndSupports[glyphName][0], round=noRound) + varData.optimize() + directStore = builder.buildVarStore(varTupleList, [varData]) + # remove unused regions from VarRegionList + directStore.prune_regions() + + # Build optimized indirect mapping + storeBuilder = varStore.OnlineVarStoreBuilder(axisTags) + advMapping = {} + for glyphName in glyphOrder: + deltas, supports = vhAdvanceDeltasAndSupports[glyphName] + storeBuilder.setSupports(supports) + advMapping[glyphName] = storeBuilder.storeDeltas(deltas, round=noRound) + + if vOrigDeltasAndSupports: + vOrigMap = {} + for glyphName in glyphOrder: + deltas, supports = vOrigDeltasAndSupports[glyphName] + storeBuilder.setSupports(supports) + vOrigMap[glyphName] = storeBuilder.storeDeltas(deltas, round=noRound) + + indirectStore = storeBuilder.finish() + mapping2 = indirectStore.optimize(use_NO_VARIATION_INDEX=False) + advMapping = [mapping2[advMapping[g]] for g in glyphOrder] + advanceMapping = builder.buildVarIdxMap(advMapping, glyphOrder) + + if vOrigDeltasAndSupports: + vOrigMap = [mapping2[vOrigMap[g]] for g in glyphOrder] + + useDirect = False + vOrigMapping = None + if directStore: + # Compile both, see which is more compact + + writer = OTTableWriter() + directStore.compile(writer, font) + directSize = len(writer.getAllData()) + + writer = OTTableWriter() + indirectStore.compile(writer, font) + advanceMapping.compile(writer, font) + indirectSize = len(writer.getAllData()) + + useDirect = directSize < indirectSize + + if useDirect: + metricsStore = directStore + advanceMapping = None + else: + metricsStore = indirectStore + if vOrigDeltasAndSupports: + vOrigMapping = builder.buildVarIdxMap(vOrigMap, glyphOrder) + + vhvar.VarStore = metricsStore + setattr(vhvar, tableFields.advMapping, advanceMapping) + if vOrigMapping is not None: + setattr(vhvar, tableFields.vOrigMapping, vOrigMapping) + setattr(vhvar, tableFields.sb1, None) + setattr(vhvar, tableFields.sb2, None) + + font[tableTag] = VHVAR + return + + +def _get_advance_metrics(font, masterModel, master_ttfs, axisTags, tableFields): + tableTag = tableFields.tableTag + glyphOrder = font.getGlyphOrder() + + # Build list of source font advance widths for each glyph + metricsTag = tableFields.metricsTag + advMetricses = [m[metricsTag].metrics for m in master_ttfs] + + # Build list of source font vertical origin coords for each glyph + if tableTag == "VVAR" and "VORG" in master_ttfs[0]: + vOrigMetricses = [m["VORG"].VOriginRecords for m in master_ttfs] + defaultYOrigs = [m["VORG"].defaultVertOriginY for m in master_ttfs] + vOrigMetricses = list(zip(vOrigMetricses, defaultYOrigs)) + else: + vOrigMetricses = None + + vhAdvanceDeltasAndSupports = {} + vOrigDeltasAndSupports = {} + # HACK: we treat width 65535 as a sentinel value to signal that a glyph + # from a non-default master should not participate in computing {H,V}VAR, + # as if it were missing. Allows to variate other glyph-related data independently + # from glyph metrics + sparse_advance = 0xFFFF + for glyph in glyphOrder: + vhAdvances = [ + ( + metrics[glyph][0] + if glyph in metrics and metrics[glyph][0] != sparse_advance + else None + ) + for metrics in advMetricses + ] + vhAdvanceDeltasAndSupports[glyph] = masterModel.getDeltasAndSupports( + vhAdvances, round=round + ) + + if vOrigMetricses: + for glyph in glyphOrder: + # We need to supply a vOrigs tuple with non-None default values + # for each glyph. vOrigMetricses contains values only for those + # glyphs which have a non-default vOrig. + vOrigs = [ + metrics[glyph] if glyph in metrics else defaultVOrig + for metrics, defaultVOrig in vOrigMetricses + ] + vOrigDeltasAndSupports[glyph] = masterModel.getDeltasAndSupports( + vOrigs, round=round + ) + + return vhAdvanceDeltasAndSupports, vOrigDeltasAndSupports + + +def _add_MVAR(font, masterModel, master_ttfs, axisTags): + log.info("Generating MVAR") + + store_builder = varStore.OnlineVarStoreBuilder(axisTags) + + records = [] + lastTableTag = None + fontTable = None + tables = None + # HACK: we need to special-case post.underlineThickness and .underlinePosition + # and unilaterally/arbitrarily define a sentinel value to distinguish the case + # when a post table is present in a given master simply because that's where + # the glyph names in TrueType must be stored, but the underline values are not + # meant to be used for building MVAR's deltas. The value of -0x8000 (-32768) + # the minimum FWord (int16) value, was chosen for its unlikelyhood to appear + # in real-world underline position/thickness values. + specialTags = {"unds": -0x8000, "undo": -0x8000} + + for tag, (tableTag, itemName) in sorted(MVAR_ENTRIES.items(), key=lambda kv: kv[1]): + # For each tag, fetch the associated table from all fonts (or not when we are + # still looking at a tag from the same tables) and set up the variation model + # for them. + if tableTag != lastTableTag: + tables = fontTable = None + if tableTag in font: + fontTable = font[tableTag] + tables = [] + for master in master_ttfs: + if tableTag not in master or ( + tag in specialTags + and getattr(master[tableTag], itemName) == specialTags[tag] + ): + tables.append(None) + else: + tables.append(master[tableTag]) + model, tables = masterModel.getSubModel(tables) + store_builder.setModel(model) + lastTableTag = tableTag + + if tables is None: # Tag not applicable to the master font. + continue + + # TODO support gasp entries + + master_values = [getattr(table, itemName) for table in tables] + if models.allEqual(master_values): + base, varIdx = master_values[0], None + else: + base, varIdx = store_builder.storeMasters(master_values) + setattr(fontTable, itemName, base) + + if varIdx is None: + continue + log.info(" %s: %s.%s %s", tag, tableTag, itemName, master_values) + rec = ot.MetricsValueRecord() + rec.ValueTag = tag + rec.VarIdx = varIdx + records.append(rec) + + assert "MVAR" not in font + if records: + store = store_builder.finish() + # Optimize + mapping = store.optimize() + for rec in records: + rec.VarIdx = mapping[rec.VarIdx] + + MVAR = font["MVAR"] = newTable("MVAR") + mvar = MVAR.table = ot.MVAR() + mvar.Version = 0x00010000 + mvar.Reserved = 0 + mvar.VarStore = store + # XXX these should not be hard-coded but computed automatically + mvar.ValueRecordSize = 8 + mvar.ValueRecordCount = len(records) + mvar.ValueRecord = sorted(records, key=lambda r: r.ValueTag) + + +def _add_BASE(font, masterModel, master_ttfs, axisTags): + log.info("Generating BASE") + + merger = VariationMerger(masterModel, axisTags, font) + merger.mergeTables(font, master_ttfs, ["BASE"]) + store = merger.store_builder.finish() + + if not store: + return + base = font["BASE"].table + assert base.Version == 0x00010000 + base.Version = 0x00010001 + base.VarStore = store + + +def _merge_OTL(font, model, master_fonts, axisTags): + otl_tags = ["GSUB", "GDEF", "GPOS"] + if not any(tag in font for tag in otl_tags): + return + + log.info("Merging OpenType Layout tables") + merger = VariationMerger(model, axisTags, font) + + merger.mergeTables(font, master_fonts, otl_tags) + store = merger.store_builder.finish() + if not store: + return + try: + GDEF = font["GDEF"].table + assert GDEF.Version <= 0x00010002 + except KeyError: + GDEFTable = font["GDEF"] = newTable("GDEF") + GDEF = GDEFTable.table = ot.GDEF() + GDEF.GlyphClassDef = None + GDEF.AttachList = None + GDEF.LigCaretList = None + GDEF.MarkAttachClassDef = None + GDEF.MarkGlyphSetsDef = None + + GDEF.Version = 0x00010003 + GDEF.VarStore = store + + # Optimize + varidx_map = store.optimize() + GDEF.remap_device_varidxes(varidx_map) + if "GPOS" in font: + font["GPOS"].table.remap_device_varidxes(varidx_map) + + +def _add_GSUB_feature_variations( + font, axes, internal_axis_supports, rules, featureTags +): + def normalize(name, value): + return models.normalizeLocation({name: value}, internal_axis_supports)[name] + + log.info("Generating GSUB FeatureVariations") + + axis_tags = {name: axis.tag for name, axis in axes.items()} + + conditional_subs = [] + for rule in rules: + region = [] + for conditions in rule.conditionSets: + space = {} + for condition in conditions: + axis_name = condition["name"] + if condition["minimum"] is not None: + minimum = normalize(axis_name, condition["minimum"]) + else: + minimum = -1.0 + if condition["maximum"] is not None: + maximum = normalize(axis_name, condition["maximum"]) + else: + maximum = 1.0 + tag = axis_tags[axis_name] + space[tag] = (minimum, maximum) + region.append(space) + + subs = {k: v for k, v in rule.subs} + + conditional_subs.append((region, subs)) + + addFeatureVariations(font, conditional_subs, featureTags) + + +_DesignSpaceData = namedtuple( + "_DesignSpaceData", + [ + "axes", + "axisMappings", + "internal_axis_supports", + "base_idx", + "normalized_master_locs", + "masters", + "instances", + "rules", + "rulesProcessingLast", + "lib", + ], +) + + +def _add_CFF2(varFont, model, master_fonts): + from .cff import merge_region_fonts + + glyphOrder = varFont.getGlyphOrder() + if "CFF2" not in varFont: + from fontTools.cffLib.CFFToCFF2 import convertCFFToCFF2 + + convertCFFToCFF2(varFont) + + ordered_fonts_list = model.reorderMasters(master_fonts, model.reverseMapping) + # re-ordering the master list simplifies building the CFF2 data item lists. + merge_region_fonts(varFont, model, ordered_fonts_list, glyphOrder) + + +def _add_COLR(font, model, master_fonts, axisTags, colr_layer_reuse=True): + merger = COLRVariationMerger( + model, axisTags, font, allowLayerReuse=colr_layer_reuse + ) + merger.mergeTables(font, master_fonts) + store = merger.store_builder.finish() + + colr = font["COLR"].table + if store: + mapping = store.optimize() + colr.VarStore = store + varIdxes = [mapping[v] for v in merger.varIdxes] + colr.VarIndexMap = builder.buildDeltaSetIndexMap(varIdxes) + + +def load_designspace(designspace, log_enabled=True, *, require_sources=True): + # TODO: remove this and always assume 'designspace' is a DesignSpaceDocument, + # never a file path, as that's already handled by caller + if hasattr(designspace, "sources"): # Assume a DesignspaceDocument + ds = designspace + else: # Assume a file path + ds = DesignSpaceDocument.fromfile(designspace) + + masters = ds.sources + if require_sources and not masters: + raise VarLibValidationError("Designspace must have at least one source.") + instances = ds.instances + + # TODO: Use fontTools.designspaceLib.tagForAxisName instead. + standard_axis_map = OrderedDict( + [ + ("weight", ("wght", {"en": "Weight"})), + ("width", ("wdth", {"en": "Width"})), + ("slant", ("slnt", {"en": "Slant"})), + ("optical", ("opsz", {"en": "Optical Size"})), + ("italic", ("ital", {"en": "Italic"})), + ] + ) + + # Setup axes + if not ds.axes: + raise VarLibValidationError(f"Designspace must have at least one axis.") + + axes = OrderedDict() + for axis_index, axis in enumerate(ds.axes): + axis_name = axis.name + if not axis_name: + if not axis.tag: + raise VarLibValidationError(f"Axis at index {axis_index} needs a tag.") + axis_name = axis.name = axis.tag + + if axis_name in standard_axis_map: + if axis.tag is None: + axis.tag = standard_axis_map[axis_name][0] + if not axis.labelNames: + axis.labelNames.update(standard_axis_map[axis_name][1]) + else: + if not axis.tag: + raise VarLibValidationError(f"Axis at index {axis_index} needs a tag.") + if not axis.labelNames: + axis.labelNames["en"] = tostr(axis_name) + + axes[axis_name] = axis + if log_enabled: + log.info("Axes:\n%s", pformat([axis.asdict() for axis in axes.values()])) + + axisMappings = ds.axisMappings + if axisMappings and log_enabled: + log.info("Mappings:\n%s", pformat(axisMappings)) + + # Check all master and instance locations are valid and fill in defaults + for obj in masters + instances: + obj_name = obj.name or obj.styleName or "" + loc = obj.getFullDesignLocation(ds) + obj.designLocation = loc + if loc is None: + raise VarLibValidationError( + f"Source or instance '{obj_name}' has no location." + ) + for axis_name in loc.keys(): + if axis_name not in axes: + raise VarLibValidationError( + f"Location axis '{axis_name}' unknown for '{obj_name}'." + ) + for axis_name, axis in axes.items(): + v = axis.map_backward(loc[axis_name]) + if not (axis.minimum <= v <= axis.maximum): + raise VarLibValidationError( + f"Source or instance '{obj_name}' has out-of-range location " + f"for axis '{axis_name}': is mapped to {v} but must be in " + f"mapped range [{axis.minimum}..{axis.maximum}] (NOTE: all " + "values are in user-space)." + ) + + # Normalize master locations + + internal_master_locs = [o.getFullDesignLocation(ds) for o in masters] + if log_enabled: + log.info("Internal master locations:\n%s", pformat(internal_master_locs)) + + # TODO This mapping should ideally be moved closer to logic in _add_fvar/avar + internal_axis_supports = {} + for axis in axes.values(): + triple = (axis.minimum, axis.default, axis.maximum) + internal_axis_supports[axis.name] = [axis.map_forward(v) for v in triple] + if log_enabled: + log.info("Internal axis supports:\n%s", pformat(internal_axis_supports)) + + normalized_master_locs = [ + models.normalizeLocation(m, internal_axis_supports) + for m in internal_master_locs + ] + if log_enabled: + log.info("Normalized master locations:\n%s", pformat(normalized_master_locs)) + + # Find base master + base_idx = None + for i, m in enumerate(normalized_master_locs): + if all(v == 0 for v in m.values()): + if base_idx is not None: + raise VarLibValidationError( + "More than one base master found in Designspace." + ) + base_idx = i + if require_sources and base_idx is None: + raise VarLibValidationError( + "Base master not found; no master at default location?" + ) + if log_enabled: + log.info("Index of base master: %s", base_idx) + + return _DesignSpaceData( + axes, + axisMappings, + internal_axis_supports, + base_idx, + normalized_master_locs, + masters, + instances, + ds.rules, + ds.rulesProcessingLast, + ds.lib, + ) + + +# https://docs.microsoft.com/en-us/typography/opentype/spec/os2#uswidthclass +WDTH_VALUE_TO_OS2_WIDTH_CLASS = { + 50: 1, + 62.5: 2, + 75: 3, + 87.5: 4, + 100: 5, + 112.5: 6, + 125: 7, + 150: 8, + 200: 9, +} + + +def set_default_weight_width_slant(font, location): + if "OS/2" in font: + if "wght" in location: + weight_class = otRound(max(1, min(location["wght"], 1000))) + if font["OS/2"].usWeightClass != weight_class: + log.info("Setting OS/2.usWeightClass = %s", weight_class) + font["OS/2"].usWeightClass = weight_class + + if "wdth" in location: + # map 'wdth' axis (50..200) to OS/2.usWidthClass (1..9), rounding to closest + widthValue = min(max(location["wdth"], 50), 200) + widthClass = otRound( + models.piecewiseLinearMap(widthValue, WDTH_VALUE_TO_OS2_WIDTH_CLASS) + ) + if font["OS/2"].usWidthClass != widthClass: + log.info("Setting OS/2.usWidthClass = %s", widthClass) + font["OS/2"].usWidthClass = widthClass + + if "slnt" in location and "post" in font: + italicAngle = max(-90, min(location["slnt"], 90)) + if font["post"].italicAngle != italicAngle: + log.info("Setting post.italicAngle = %s", italicAngle) + font["post"].italicAngle = italicAngle + + +def drop_implied_oncurve_points(*masters: TTFont) -> int: + """Drop impliable on-curve points from all the simple glyphs in masters. + + In TrueType glyf outlines, on-curve points can be implied when they are located + exactly at the midpoint of the line connecting two consecutive off-curve points. + + The input masters' glyf tables are assumed to contain same-named glyphs that are + interpolatable. Oncurve points are only dropped if they can be implied for all + the masters. The fonts are modified in-place. + + Args: + masters: The TTFont(s) to modify + + Returns: + The total number of points that were dropped if any. + + Reference: + https://developer.apple.com/fonts/TrueType-Reference-Manual/RM01/Chap1.html + """ + + glyph_masters = defaultdict(list) + # multiple DS source may point to the same TTFont object and we want to + # avoid processing the same glyph twice as they are modified in-place + for font in {id(m): m for m in masters}.values(): + glyf = font["glyf"] + for glyphName in glyf.keys(): + glyph_masters[glyphName].append(glyf[glyphName]) + count = 0 + for glyphName, glyphs in glyph_masters.items(): + try: + dropped = dropImpliedOnCurvePoints(*glyphs) + except ValueError as e: + # we don't fail for incompatible glyphs in _add_gvar so we shouldn't here + log.warning("Failed to drop implied oncurves for %r: %s", glyphName, e) + else: + count += len(dropped) + return count + + +def build_many( + designspace: DesignSpaceDocument, + master_finder=lambda s: s, + exclude=[], + optimize=True, + skip_vf=lambda vf_name: False, + colr_layer_reuse=True, + drop_implied_oncurves=False, +): + """ + Build variable fonts from a designspace file, version 5 which can define + several VFs, or version 4 which has implicitly one VF covering the whole doc. + + If master_finder is set, it should be a callable that takes master + filename as found in designspace file and map it to master font + binary as to be opened (eg. .ttf or .otf). + + skip_vf can be used to skip building some of the variable fonts defined in + the input designspace. It's a predicate that takes as argument the name + of the variable font and returns `bool`. + + Always returns a Dict[str, TTFont] keyed by VariableFontDescriptor.name + """ + res = {} + # varLib.build (used further below) by default only builds an incomplete 'STAT' + # with an empty AxisValueArray--unless the VF inherited 'STAT' from its base master. + # Designspace version 5 can also be used to define 'STAT' labels or customize + # axes ordering, etc. To avoid overwriting a pre-existing 'STAT' or redoing the + # same work twice, here we check if designspace contains any 'STAT' info before + # proceeding to call buildVFStatTable for each VF. + # https://github.com/fonttools/fonttools/pull/3024 + # https://github.com/fonttools/fonttools/issues/3045 + doBuildStatFromDSv5 = ( + "STAT" not in exclude + and designspace.formatTuple >= (5, 0) + and ( + any(a.axisLabels or a.axisOrdering is not None for a in designspace.axes) + or designspace.locationLabels + ) + ) + for _location, subDoc in splitInterpolable(designspace): + for name, vfDoc in splitVariableFonts(subDoc): + if skip_vf(name): + log.debug(f"Skipping variable TTF font: {name}") + continue + vf = build( + vfDoc, + master_finder, + exclude=exclude, + optimize=optimize, + colr_layer_reuse=colr_layer_reuse, + drop_implied_oncurves=drop_implied_oncurves, + )[0] + if doBuildStatFromDSv5: + buildVFStatTable(vf, designspace, name) + res[name] = vf + return res + + +def build( + designspace, + master_finder=lambda s: s, + exclude=[], + optimize=True, + colr_layer_reuse=True, + drop_implied_oncurves=False, +): + """ + Build variation font from a designspace file. + + If master_finder is set, it should be a callable that takes master + filename as found in designspace file and map it to master font + binary as to be opened (eg. .ttf or .otf). + """ + if hasattr(designspace, "sources"): # Assume a DesignspaceDocument + pass + else: # Assume a file path + designspace = DesignSpaceDocument.fromfile(designspace) + + ds = load_designspace(designspace) + log.info("Building variable font") + + log.info("Loading master fonts") + master_fonts = load_masters(designspace, master_finder) + + # TODO: 'master_ttfs' is unused except for return value, remove later + master_ttfs = [] + for master in master_fonts: + try: + master_ttfs.append(master.reader.file.name) + except AttributeError: + master_ttfs.append(None) # in-memory fonts have no path + + if drop_implied_oncurves and "glyf" in master_fonts[ds.base_idx]: + drop_count = drop_implied_oncurve_points(*master_fonts) + log.info( + "Dropped %s on-curve points from simple glyphs in the 'glyf' table", + drop_count, + ) + + # Copy the base master to work from it + vf = deepcopy(master_fonts[ds.base_idx]) + + if "DSIG" in vf: + del vf["DSIG"] + + # Clear USE_MY_METRICS composite flags if set inconsistently across masters. + if "glyf" in vf: + _unset_inconsistent_use_my_metrics_flags(vf, master_fonts) + + # TODO append masters as named-instances as well; needs .designspace change. + fvar = _add_fvar(vf, ds.axes, ds.instances) + if "STAT" not in exclude: + _add_stat(vf) + + # Map from axis names to axis tags... + normalized_master_locs = [ + {ds.axes[k].tag: v for k, v in loc.items()} for loc in ds.normalized_master_locs + ] + # From here on, we use fvar axes only + axisTags = [axis.axisTag for axis in fvar.axes] + + # Assume single-model for now. + model = models.VariationModel(normalized_master_locs, axisOrder=axisTags) + assert 0 == model.mapping[ds.base_idx] + + log.info("Building variations tables") + if "avar" not in exclude: + _add_avar(vf, ds.axes, ds.axisMappings, axisTags) + if "BASE" not in exclude and "BASE" in vf: + _add_BASE(vf, model, master_fonts, axisTags) + if "MVAR" not in exclude: + _add_MVAR(vf, model, master_fonts, axisTags) + if "HVAR" not in exclude: + _add_HVAR(vf, model, master_fonts, axisTags) + if "VVAR" not in exclude and "vmtx" in vf: + _add_VVAR(vf, model, master_fonts, axisTags) + if "GDEF" not in exclude or "GPOS" not in exclude: + _merge_OTL(vf, model, master_fonts, axisTags) + if "gvar" not in exclude and "glyf" in vf: + _add_gvar(vf, model, master_fonts, optimize=optimize) + if "cvar" not in exclude and "glyf" in vf: + _merge_TTHinting(vf, model, master_fonts) + if "GSUB" not in exclude and ds.rules: + featureTags = _feature_variations_tags(ds) + _add_GSUB_feature_variations( + vf, ds.axes, ds.internal_axis_supports, ds.rules, featureTags + ) + if "CFF2" not in exclude and ("CFF " in vf or "CFF2" in vf): + _add_CFF2(vf, model, master_fonts) + if "post" in vf: + # set 'post' to format 2 to keep the glyph names dropped from CFF2 + post = vf["post"] + if post.formatType != 2.0: + post.formatType = 2.0 + post.extraNames = [] + post.mapping = {} + if "COLR" not in exclude and "COLR" in vf and vf["COLR"].version > 0: + _add_COLR(vf, model, master_fonts, axisTags, colr_layer_reuse) + + set_default_weight_width_slant( + vf, location={axis.axisTag: axis.defaultValue for axis in vf["fvar"].axes} + ) + + for tag in exclude: + if tag in vf: + del vf[tag] + + # TODO: Only return vf for 4.0+, the rest is unused. + return vf, model, master_ttfs + + +def _open_font(path, master_finder=lambda s: s): + # load TTFont masters from given 'path': this can be either a .TTX or an + # OpenType binary font; or if neither of these, try use the 'master_finder' + # callable to resolve the path to a valid .TTX or OpenType font binary. + from fontTools.ttx import guessFileType + + master_path = os.path.normpath(path) + tp = guessFileType(master_path) + if tp is None: + # not an OpenType binary/ttx, fall back to the master finder. + master_path = master_finder(master_path) + tp = guessFileType(master_path) + if tp in ("TTX", "OTX"): + font = TTFont() + font.importXML(master_path) + elif tp in ("TTF", "OTF", "WOFF", "WOFF2"): + font = TTFont(master_path) + else: + raise VarLibValidationError("Invalid master path: %r" % master_path) + return font + + +def load_masters(designspace, master_finder=lambda s: s): + """Ensure that all SourceDescriptor.font attributes have an appropriate TTFont + object loaded, or else open TTFont objects from the SourceDescriptor.path + attributes. + + The paths can point to either an OpenType font, a TTX file, or a UFO. In the + latter case, use the provided master_finder callable to map from UFO paths to + the respective master font binaries (e.g. .ttf, .otf or .ttx). + + Return list of master TTFont objects in the same order they are listed in the + DesignSpaceDocument. + """ + for master in designspace.sources: + # If a SourceDescriptor has a layer name, demand that the compiled TTFont + # be supplied by the caller. This spares us from modifying MasterFinder. + if master.layerName and master.font is None: + raise VarLibValidationError( + f"Designspace source '{master.name or '<Unknown>'}' specified a " + "layer name but lacks the required TTFont object in the 'font' " + "attribute." + ) + + return designspace.loadSourceFonts(_open_font, master_finder=master_finder) + + +class MasterFinder(object): + def __init__(self, template): + self.template = template + + def __call__(self, src_path): + fullname = os.path.abspath(src_path) + dirname, basename = os.path.split(fullname) + stem, ext = os.path.splitext(basename) + path = self.template.format( + fullname=fullname, + dirname=dirname, + basename=basename, + stem=stem, + ext=ext, + ) + return os.path.normpath(path) + + +def _feature_variations_tags(ds): + raw_tags = ds.lib.get( + FEAVAR_FEATURETAG_LIB_KEY, + "rclt" if ds.rulesProcessingLast else "rvrn", + ) + return sorted({t.strip() for t in raw_tags.split(",")}) + + +def addGSUBFeatureVariations(vf, designspace, featureTags=(), *, log_enabled=False): + """Add GSUB FeatureVariations table to variable font, based on DesignSpace rules. + + Args: + vf: A TTFont object representing the variable font. + designspace: A DesignSpaceDocument object. + featureTags: Optional feature tag(s) to use for the FeatureVariations records. + If unset, the key 'com.github.fonttools.varLib.featureVarsFeatureTag' is + looked up in the DS <lib> and used; otherwise the default is 'rclt' if + the <rules processing="last"> attribute is set, else 'rvrn'. + See <https://fonttools.readthedocs.io/en/latest/designspaceLib/xml.html#rules-element> + log_enabled: If True, log info about DS axes and sources. Default is False, as + the same info may have already been logged as part of varLib.build. + """ + ds = load_designspace(designspace, log_enabled=log_enabled) + if not ds.rules: + return + if not featureTags: + featureTags = _feature_variations_tags(ds) + _add_GSUB_feature_variations( + vf, ds.axes, ds.internal_axis_supports, ds.rules, featureTags + ) + + +def main(args=None): + """Build variable fonts from a designspace file and masters""" + from argparse import ArgumentParser + from fontTools import configLogger + + parser = ArgumentParser(prog="varLib", description=main.__doc__) + parser.add_argument("designspace") + output_group = parser.add_mutually_exclusive_group() + output_group.add_argument( + "-o", metavar="OUTPUTFILE", dest="outfile", default=None, help="output file" + ) + output_group.add_argument( + "-d", + "--output-dir", + metavar="OUTPUTDIR", + default=None, + help="output dir (default: same as input designspace file)", + ) + parser.add_argument( + "-x", + metavar="TAG", + dest="exclude", + action="append", + default=[], + help="exclude table", + ) + parser.add_argument( + "--disable-iup", + dest="optimize", + action="store_false", + help="do not perform IUP optimization", + ) + parser.add_argument( + "--no-colr-layer-reuse", + dest="colr_layer_reuse", + action="store_false", + help="do not rebuild variable COLR table to optimize COLR layer reuse", + ) + parser.add_argument( + "--drop-implied-oncurves", + action="store_true", + help=( + "drop on-curve points that can be implied when exactly in the middle of " + "two off-curve points (only applies to TrueType fonts)" + ), + ) + parser.add_argument( + "--master-finder", + default="master_ttf_interpolatable/{stem}.ttf", + help=( + "templated string used for finding binary font " + "files given the source file names defined in the " + "designspace document. The following special strings " + "are defined: {fullname} is the absolute source file " + "name; {basename} is the file name without its " + "directory; {stem} is the basename without the file " + "extension; {ext} is the source file extension; " + "{dirname} is the directory of the absolute file " + 'name. The default value is "%(default)s".' + ), + ) + parser.add_argument( + "--variable-fonts", + default=".*", + metavar="VF_NAME", + help=( + "Filter the list of variable fonts produced from the input " + "Designspace v5 file. By default all listed variable fonts are " + "generated. To generate a specific variable font (or variable fonts) " + 'that match a given "name" attribute, you can pass as argument ' + "the full name or a regular expression. E.g.: --variable-fonts " + '"MyFontVF_WeightOnly"; or --variable-fonts "MyFontVFItalic_.*".' + ), + ) + logging_group = parser.add_mutually_exclusive_group(required=False) + logging_group.add_argument( + "-v", "--verbose", action="store_true", help="Run more verbosely." + ) + logging_group.add_argument( + "-q", "--quiet", action="store_true", help="Turn verbosity off." + ) + options = parser.parse_args(args) + + configLogger( + level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO") + ) + + designspace_filename = options.designspace + designspace = DesignSpaceDocument.fromfile(designspace_filename) + + vf_descriptors = designspace.getVariableFonts() + if not vf_descriptors: + parser.error(f"No variable fonts in given designspace {designspace.path!r}") + + vfs_to_build = [] + for vf in vf_descriptors: + # Skip variable fonts that do not match the user's inclusion regex if given. + if not fullmatch(options.variable_fonts, vf.name): + continue + vfs_to_build.append(vf) + + if not vfs_to_build: + parser.error(f"No variable fonts matching {options.variable_fonts!r}") + + if options.outfile is not None and len(vfs_to_build) > 1: + parser.error( + "can't specify -o because there are multiple VFs to build; " + "use --output-dir, or select a single VF with --variable-fonts" + ) + + output_dir = options.output_dir + if output_dir is None: + output_dir = os.path.dirname(designspace_filename) + + vf_name_to_output_path = {} + if len(vfs_to_build) == 1 and options.outfile is not None: + vf_name_to_output_path[vfs_to_build[0].name] = options.outfile + else: + for vf in vfs_to_build: + if vf.filename is not None: + # Only use basename to prevent path traversal attacks + filename = os.path.basename(vf.filename) + else: + # vf.name comes straight from the designspace and is equally + # attacker-controlled, so basename it too + filename = os.path.basename(vf.name) + ".{ext}" + vf_name_to_output_path[vf.name] = os.path.join(output_dir, filename) + + vf_names_to_build = {vf.name for vf in vfs_to_build} + finder = MasterFinder(options.master_finder) + + vfs = build_many( + designspace, + finder, + exclude=options.exclude, + optimize=options.optimize, + skip_vf=lambda name: name not in vf_names_to_build, + colr_layer_reuse=options.colr_layer_reuse, + drop_implied_oncurves=options.drop_implied_oncurves, + ) + + for vf_name, vf in vfs.items(): + ext = "otf" if vf.sfntVersion == "OTTO" else "ttf" + output_path = vf_name_to_output_path[vf_name].format(ext=ext) + output_dir = os.path.dirname(output_path) + if output_dir: + os.makedirs(output_dir, exist_ok=True) + log.info("Saving variation font %s", output_path) + vf.save(output_path) + + +if __name__ == "__main__": + import sys + + if len(sys.argv) > 1: + sys.exit(main()) + import doctest + + sys.exit(doctest.testmod().failed) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__main__.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..b222c81e1889eab05871979aa6a8f2195b00f127 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/__main__.py @@ -0,0 +1,5 @@ +import sys +from fontTools.varLib import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9634c1e6f7db4684ac902bec798a45a7f74d5813 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00a50c710e12ffba2aacd777ef4edb14e16de627 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/__main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/avarPlanner.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/avarPlanner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a66ca765bd896410d0ca0bc453909638880da5a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/avarPlanner.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/builder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/builder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c2ad6c3259e366bb490c6bd07f043677af30176 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/builder.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/cff.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/cff.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..764653f2330a86533918603909dff5c590a8602c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/cff.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/errors.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/errors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f7b649953a69ec9f90987106428723c2e739293 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/errors.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/featureVars.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/featureVars.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6200aa9756ceba9ff93fc8bc4107b554f9ad217d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/featureVars.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/hvar.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/hvar.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6eaaa71c521f697f028490dd490c273fdd889e91 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/hvar.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatable.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d3bfbba34aff74cc30553d9274381a86c9a02bc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatable.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatableHelpers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatableHelpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9dc60afc569e00a1d022cdb78818a75610a770a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatableHelpers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatablePlot.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatablePlot.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05956414f5bd5a1f06eb3e7f0176cbe74df97d15 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatablePlot.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatableTestContourOrder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatableTestContourOrder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0615fa31b94c541a40f8e68ea4c1800d8c35772 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatableTestContourOrder.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatableTestStartingPoint.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatableTestStartingPoint.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83952c22313a4160308e702e22928249a64cf3e4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolatableTestStartingPoint.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolate_layout.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolate_layout.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c6b9cfad529732def4dea1c6687fb86609f4d33 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/interpolate_layout.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/iup.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/iup.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c000c0250ead8c3f03573cb8cd392dba065613d0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/iup.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/merger.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/merger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a12428c918b08613e0da3718b75097ca419c2f6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/merger.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/models.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbd0185d1fbf8d72ba47182fc91d151fea39c2c4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/models.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/multiVarStore.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/multiVarStore.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ce939dfb83b3ba882edb32b139a42f59b59ede1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/multiVarStore.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/mutator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/mutator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07a583bc4496bf5f7e723e95ffdc389fdbc8ee44 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/mutator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/mvar.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/mvar.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d4522ffe0bae1a2baf38105dd51123de48cccee Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/mvar.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/plot.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/plot.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5529302effe010cca7e4235932a8051ba9224e5d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/plot.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/stat.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/stat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48743b7975f659b90da76d480deb28f87f2d012f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/stat.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/varStore.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/varStore.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..335303b21be1a3bf73ee168da0b07ee58bf4bc45 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/__pycache__/varStore.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__init__.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__main__.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..1bb27dbfd53902914177ee7fb24a21402b9ae3d3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__main__.py @@ -0,0 +1,72 @@ +import logging + +log = logging.getLogger("fontTools.varLib.avar") + + +def main(args=None): + from fontTools.ttLib import TTFont + from fontTools.misc.cliTools import makeOutputFileName + from fontTools import configLogger + import argparse + import sys + + print( + "WARNING: This script is deprecated. Use `fonttools varLib.avar.build` " + "or `fonttools varLib.avar.unbuild` instead.\n", + file=sys.stderr, + ) + + if args is None: + args = sys.argv[1:] + + parser = argparse.ArgumentParser( + "fonttools varLib.avar", + description="Add `avar` table from designspace file to variable font.", + ) + parser.add_argument("font", metavar="varfont.ttf", help="Variable-font file.") + parser.add_argument( + "designspace", + metavar="family.designspace", + help="Designspace file.", + nargs="?", + default=None, + ) + parser.add_argument( + "-o", + "--output-file", + type=str, + help="Output font file name.", + ) + parser.add_argument( + "-v", "--verbose", action="store_true", help="Run more verbosely." + ) + + options = parser.parse_args(args) + + configLogger(level=("INFO" if options.verbose else "WARNING")) + + font = TTFont(options.font) + + if options.designspace is None: + from .unbuild import unbuild + + unbuild(font) + return 0 + + from .build import build + + build(font, options.designspace) + + if options.output_file is None: + outfile = makeOutputFileName(options.font, overWrite=True, suffix=".avar") + else: + outfile = options.output_file + if outfile: + log.info("Saving %s", outfile) + font.save(outfile) + + +if __name__ == "__main__": + import sys + + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c75e5b93787ccbfe345c2b7b650728a7590b8cb8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33c2a703c06b4bb929a2c7c74ec21cd67dec0945 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/__main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/build.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/build.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a34c9492bdec31747184f12ffa65a43efdc88123 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/build.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/map.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/map.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0199ea78b15b0eb7bd99ca63de5b581406b422ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/map.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/plan.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/plan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5496f9bae0ac7a61c8e66b6b0f5002ac82ffbbf4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/plan.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/unbuild.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/unbuild.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d177802ec49e0c3d9d12d7d0a8d803d355ff05f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/__pycache__/unbuild.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/build.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/build.py new file mode 100644 index 0000000000000000000000000000000000000000..d9706705db819c7f02b16995765679bde47de40d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/build.py @@ -0,0 +1,79 @@ +from fontTools.varLib import _add_fvar, _add_avar, load_designspace +from fontTools.ttLib import newTable +import logging + +log = logging.getLogger("fontTools.varLib.avar") + + +def build(font, designspace_file): + ds = load_designspace(designspace_file, require_sources=False) + + if not "fvar" in font: + if "name" not in font: + font["name"] = newTable("name") + _add_fvar(font, ds.axes, ds.instances) + + axisTags = [a.axisTag for a in font["fvar"].axes] + + if "avar" in font: + log.warning("avar table already present, overwriting.") + del font["avar"] + + _add_avar(font, ds.axes, ds.axisMappings, axisTags) + + +def main(args=None): + """Add `avar` table from designspace file to variable font.""" + + from fontTools.ttLib import TTFont + from fontTools.misc.cliTools import makeOutputFileName + from fontTools import configLogger + import argparse + + if args is None: + import sys + + args = sys.argv[1:] + + parser = argparse.ArgumentParser( + "fonttools varLib.avar.build", + description="Add `avar` table from designspace file to variable font.", + ) + parser.add_argument("font", metavar="varfont.ttf", help="Variable-font file.") + parser.add_argument( + "designspace", + metavar="family.designspace", + help="Designspace file.", + default=None, + ) + parser.add_argument( + "-o", + "--output-file", + type=str, + help="Output font file name.", + ) + parser.add_argument( + "-v", "--verbose", action="store_true", help="Run more verbosely." + ) + + options = parser.parse_args(args) + + configLogger(level=("INFO" if options.verbose else "WARNING")) + + font = TTFont(options.font) + + build(font, options.designspace) + + if options.output_file is None: + outfile = makeOutputFileName(options.font, overWrite=True, suffix=".avar") + else: + outfile = options.output_file + if outfile: + log.info("Saving %s", outfile) + font.save(outfile) + + +if __name__ == "__main__": + import sys + + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/map.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/map.py new file mode 100644 index 0000000000000000000000000000000000000000..a5331f109b8ce9606bb9b99f59819e5dcb7f3402 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/map.py @@ -0,0 +1,124 @@ +from fontTools.varLib.models import normalizeValue + + +def _denormalize(v, triplet): + if v >= 0: + return triplet[1] + v * (triplet[2] - triplet[1]) + else: + return triplet[1] + v * (triplet[1] - triplet[0]) + + +def map( + font, location, *, inputNormalized=False, outputNormalized=False, dropZeroes=False +): + if "fvar" not in font: + return None + + fvar = font["fvar"] + axes = {a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in fvar.axes} + unknownAxes = sorted(tag for tag in location if tag not in axes) + if unknownAxes: + raise ValueError(f"Unknown axis tag(s): {', '.join(unknownAxes)}") + + if not inputNormalized: + location = { + tag: normalizeValue(value, axes[tag]) for tag, value in location.items() + } + + if "avar" in font: + location = font["avar"].renormalizeLocation(location, font, dropZeroes) + + if not outputNormalized: + location = { + tag: _denormalize(value, axes[tag]) for tag, value in location.items() + } + + return location + + +def main(args=None): + """Map variation coordinates through the `avar` table.""" + + from fontTools.ttLib import TTFont + import argparse + + if args is None: + import sys + + args = sys.argv[1:] + + parser = argparse.ArgumentParser( + "fonttools varLib.avar.map", + description="Map variation coordinates through the `avar` table.", + ) + parser.add_argument("font", metavar="varfont.ttf", help="Variable-font file.") + parser.add_argument( + "coords", + metavar="[AXIS=value...]", + help="Coordinates to map, e.g. 'wght=700 wdth=75'.", + nargs="*", + default=None, + ) + parser.add_argument( + "-f", action="store_true", help="Do not omit axes at default location." + ) + parser.add_argument( + "-i", action="store_true", help="Input coordinates are normalized (-1..1)." + ) + parser.add_argument( + "-o", action="store_true", help="Output coordinates as normalized (-1..1)." + ) + + options = parser.parse_args(args) + + if not options.coords: + parser.error( + "No coordinates provided. Please specify at least one axis coordinate (e.g., wght=500)" + ) + + if options.font.endswith(".designspace"): + from .build import build + + font = TTFont() + build(font, options.font) + else: + font = TTFont(options.font) + if "fvar" not in font: + parser.error(f"Font '{options.font}' does not contain an 'fvar' table.") + + location = {} + for item in options.coords: + tag, sep, value = item.partition("=") + if not sep or not tag or not value: + parser.error( + f"Invalid coordinate {item!r}. Expected AXIS=value, e.g. wght=500" + ) + try: + location[tag] = float(value) + except ValueError: + parser.error( + f"Invalid coordinate value in {item!r}. Expected a number after '='" + ) + + try: + mapped = map( + font, + location, + inputNormalized=options.i, + outputNormalized=options.o, + dropZeroes=not options.f, + ) + except ValueError as e: + parser.error(str(e)) + assert mapped is not None + + for tag in mapped: + v = mapped[tag] + v = int(v) if v == int(v) else v + print(f"{tag}={v:g}") + + +if __name__ == "__main__": + import sys + + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/plan.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/plan.py new file mode 100644 index 0000000000000000000000000000000000000000..c211dd24626560f2a60386391098e427b616aa6f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/plan.py @@ -0,0 +1,1004 @@ +from fontTools.ttLib import newTable +from fontTools.ttLib.tables._f_v_a_r import Axis as fvarAxis +from fontTools.pens.areaPen import AreaPen +from fontTools.pens.basePen import NullPen +from fontTools.pens.statisticsPen import StatisticsPen +from fontTools.varLib.models import piecewiseLinearMap, normalizeValue +from fontTools.misc.cliTools import makeOutputFileName +import math +import logging +from pprint import pformat + +__all__ = [ + "planWeightAxis", + "planWidthAxis", + "planSlantAxis", + "planOpticalSizeAxis", + "planAxis", + "sanitizeWeight", + "sanitizeWidth", + "sanitizeSlant", + "measureWeight", + "measureWidth", + "measureSlant", + "normalizeLinear", + "normalizeLog", + "normalizeDegrees", + "interpolateLinear", + "interpolateLog", + "processAxis", + "makeDesignspaceSnippet", + "addEmptyAvar", + "main", +] + +log = logging.getLogger("fontTools.varLib.avar.plan") + +WEIGHTS = [ + 50, + 100, + 150, + 200, + 250, + 300, + 350, + 400, + 450, + 500, + 550, + 600, + 650, + 700, + 750, + 800, + 850, + 900, + 950, +] + +WIDTHS = [ + 25.0, + 37.5, + 50.0, + 62.5, + 75.0, + 87.5, + 100.0, + 112.5, + 125.0, + 137.5, + 150.0, + 162.5, + 175.0, + 187.5, + 200.0, +] + +SLANTS = list(math.degrees(math.atan(d / 20.0)) for d in range(-20, 21)) + +SIZES = [ + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 14, + 18, + 24, + 30, + 36, + 48, + 60, + 72, + 96, + 120, + 144, + 192, + 240, + 288, +] + + +SAMPLES = 8 + + +def normalizeLinear(value, rangeMin, rangeMax): + """Linearly normalize value in [rangeMin, rangeMax] to [0, 1], with extrapolation.""" + return (value - rangeMin) / (rangeMax - rangeMin) + + +def interpolateLinear(t, a, b): + """Linear interpolation between a and b, with t typically in [0, 1].""" + return a + t * (b - a) + + +def normalizeLog(value, rangeMin, rangeMax): + """Logarithmically normalize value in [rangeMin, rangeMax] to [0, 1], with extrapolation.""" + logMin = math.log(rangeMin) + logMax = math.log(rangeMax) + return (math.log(value) - logMin) / (logMax - logMin) + + +def interpolateLog(t, a, b): + """Logarithmic interpolation between a and b, with t typically in [0, 1].""" + logA = math.log(a) + logB = math.log(b) + return math.exp(logA + t * (logB - logA)) + + +def normalizeDegrees(value, rangeMin, rangeMax): + """Angularly normalize value in [rangeMin, rangeMax] to [0, 1], with extrapolation.""" + tanMin = math.tan(math.radians(rangeMin)) + tanMax = math.tan(math.radians(rangeMax)) + return (math.tan(math.radians(value)) - tanMin) / (tanMax - tanMin) + + +def measureWeight(glyphset, glyphs=None): + """Measure the perceptual average weight of the given glyphs.""" + if isinstance(glyphs, dict): + frequencies = glyphs + else: + frequencies = {g: 1 for g in glyphs} + + wght_sum = wdth_sum = 0 + for glyph_name in glyphs: + if frequencies is not None: + frequency = frequencies.get(glyph_name, 0) + if frequency == 0: + continue + else: + frequency = 1 + + glyph = glyphset[glyph_name] + + pen = AreaPen(glyphset=glyphset) + glyph.draw(pen) + + mult = glyph.width * frequency + wght_sum += mult * abs(pen.value) + wdth_sum += mult + + return wght_sum / wdth_sum + + +def measureWidth(glyphset, glyphs=None): + """Measure the average width of the given glyphs.""" + if isinstance(glyphs, dict): + frequencies = glyphs + else: + frequencies = {g: 1 for g in glyphs} + + wdth_sum = 0 + freq_sum = 0 + for glyph_name in glyphs: + if frequencies is not None: + frequency = frequencies.get(glyph_name, 0) + if frequency == 0: + continue + else: + frequency = 1 + + glyph = glyphset[glyph_name] + + pen = NullPen() + glyph.draw(pen) + + wdth_sum += glyph.width * frequency + freq_sum += frequency + + return wdth_sum / freq_sum + + +def measureSlant(glyphset, glyphs=None): + """Measure the perceptual average slant angle of the given glyphs.""" + if isinstance(glyphs, dict): + frequencies = glyphs + else: + frequencies = {g: 1 for g in glyphs} + + slnt_sum = 0 + freq_sum = 0 + for glyph_name in glyphs: + if frequencies is not None: + frequency = frequencies.get(glyph_name, 0) + if frequency == 0: + continue + else: + frequency = 1 + + glyph = glyphset[glyph_name] + + pen = StatisticsPen(glyphset=glyphset) + glyph.draw(pen) + + mult = glyph.width * frequency + slnt_sum += mult * pen.slant + freq_sum += mult + + return -math.degrees(math.atan(slnt_sum / freq_sum)) + + +def sanitizeWidth(userTriple, designTriple, pins, measurements): + """Sanitize the width axis limits.""" + + minVal, defaultVal, maxVal = ( + measurements[designTriple[0]], + measurements[designTriple[1]], + measurements[designTriple[2]], + ) + + calculatedMinVal = userTriple[1] * (minVal / defaultVal) + calculatedMaxVal = userTriple[1] * (maxVal / defaultVal) + + log.info("Original width axis limits: %g:%g:%g", *userTriple) + log.info( + "Calculated width axis limits: %g:%g:%g", + calculatedMinVal, + userTriple[1], + calculatedMaxVal, + ) + + if ( + abs(calculatedMinVal - userTriple[0]) / userTriple[1] > 0.05 + or abs(calculatedMaxVal - userTriple[2]) / userTriple[1] > 0.05 + ): + log.warning("Calculated width axis min/max do not match user input.") + log.warning( + " Current width axis limits: %g:%g:%g", + *userTriple, + ) + log.warning( + " Suggested width axis limits: %g:%g:%g", + calculatedMinVal, + userTriple[1], + calculatedMaxVal, + ) + + return False + + return True + + +def sanitizeWeight(userTriple, designTriple, pins, measurements): + """Sanitize the weight axis limits.""" + + if len(set(userTriple)) < 3: + return True + + minVal, defaultVal, maxVal = ( + measurements[designTriple[0]], + measurements[designTriple[1]], + measurements[designTriple[2]], + ) + + logMin = math.log(minVal) + logDefault = math.log(defaultVal) + logMax = math.log(maxVal) + + t = (userTriple[1] - userTriple[0]) / (userTriple[2] - userTriple[0]) + y = math.exp(logMin + t * (logMax - logMin)) + t = (y - minVal) / (maxVal - minVal) + calculatedDefaultVal = userTriple[0] + t * (userTriple[2] - userTriple[0]) + + log.info("Original weight axis limits: %g:%g:%g", *userTriple) + log.info( + "Calculated weight axis limits: %g:%g:%g", + userTriple[0], + calculatedDefaultVal, + userTriple[2], + ) + + if abs(calculatedDefaultVal - userTriple[1]) / userTriple[1] > 0.05: + log.warning("Calculated weight axis default does not match user input.") + + log.warning( + " Current weight axis limits: %g:%g:%g", + *userTriple, + ) + + log.warning( + " Suggested weight axis limits, changing default: %g:%g:%g", + userTriple[0], + calculatedDefaultVal, + userTriple[2], + ) + + t = (userTriple[2] - userTriple[0]) / (userTriple[1] - userTriple[0]) + y = math.exp(logMin + t * (logDefault - logMin)) + t = (y - minVal) / (defaultVal - minVal) + calculatedMaxVal = userTriple[0] + t * (userTriple[1] - userTriple[0]) + log.warning( + " Suggested weight axis limits, changing maximum: %g:%g:%g", + userTriple[0], + userTriple[1], + calculatedMaxVal, + ) + + t = (userTriple[0] - userTriple[2]) / (userTriple[1] - userTriple[2]) + y = math.exp(logMax + t * (logDefault - logMax)) + t = (y - maxVal) / (defaultVal - maxVal) + calculatedMinVal = userTriple[2] + t * (userTriple[1] - userTriple[2]) + log.warning( + " Suggested weight axis limits, changing minimum: %g:%g:%g", + calculatedMinVal, + userTriple[1], + userTriple[2], + ) + + return False + + return True + + +def sanitizeSlant(userTriple, designTriple, pins, measurements): + """Sanitize the slant axis limits.""" + + log.info("Original slant axis limits: %g:%g:%g", *userTriple) + log.info( + "Calculated slant axis limits: %g:%g:%g", + measurements[designTriple[0]], + measurements[designTriple[1]], + measurements[designTriple[2]], + ) + + if ( + abs(measurements[designTriple[0]] - userTriple[0]) > 1 + or abs(measurements[designTriple[1]] - userTriple[1]) > 1 + or abs(measurements[designTriple[2]] - userTriple[2]) > 1 + ): + log.warning("Calculated slant axis min/default/max do not match user input.") + log.warning( + " Current slant axis limits: %g:%g:%g", + *userTriple, + ) + log.warning( + " Suggested slant axis limits: %g:%g:%g", + measurements[designTriple[0]], + measurements[designTriple[1]], + measurements[designTriple[2]], + ) + + return False + + return True + + +def planAxis( + measureFunc, + normalizeFunc, + interpolateFunc, + glyphSetFunc, + axisTag, + axisLimits, + values, + samples=None, + glyphs=None, + designLimits=None, + pins=None, + sanitizeFunc=None, +): + """Plan an axis. + + measureFunc: callable that takes a glyphset and an optional + list of glyphnames, and returns the glyphset-wide measurement + to be used for the axis. + + normalizeFunc: callable that takes a measurement and a minimum + and maximum, and normalizes the measurement into the range 0..1, + possibly extrapolating too. + + interpolateFunc: callable that takes a normalized t value, and a + minimum and maximum, and returns the interpolated value, + possibly extrapolating too. + + glyphSetFunc: callable that takes a variations "location" dictionary, + and returns a glyphset. + + axisTag: the axis tag string. + + axisLimits: a triple of minimum, default, and maximum values for + the axis. Or an `fvar` Axis object. + + values: a list of output values to map for this axis. + + samples: the number of samples to use when sampling. Default 8. + + glyphs: a list of glyph names to use when sampling. Defaults to None, + which will process all glyphs. + + designLimits: an optional triple of minimum, default, and maximum values + represenging the "design" limits for the axis. If not provided, the + axisLimits will be used. + + pins: an optional dictionary of before/after mapping entries to pin in + the output. + + sanitizeFunc: an optional callable to call to sanitize the axis limits. + """ + + if isinstance(axisLimits, fvarAxis): + axisLimits = (axisLimits.minValue, axisLimits.defaultValue, axisLimits.maxValue) + minValue, defaultValue, maxValue = axisLimits + + if samples is None: + samples = SAMPLES + if glyphs is None: + glyphs = glyphSetFunc({}).keys() + if pins is None: + pins = {} + else: + pins = pins.copy() + + log.info( + "Axis limits min %g / default %g / max %g", minValue, defaultValue, maxValue + ) + triple = (minValue, defaultValue, maxValue) + + if designLimits is not None: + log.info("Axis design-limits min %g / default %g / max %g", *designLimits) + else: + designLimits = triple + + if pins: + log.info("Pins %s", sorted(pins.items())) + pins.update( + { + minValue: designLimits[0], + defaultValue: designLimits[1], + maxValue: designLimits[2], + } + ) + + out = {} + outNormalized = {} + + axisMeasurements = {} + for value in sorted({minValue, defaultValue, maxValue} | set(pins.keys())): + glyphset = glyphSetFunc(location={axisTag: value}) + designValue = pins[value] + axisMeasurements[designValue] = measureFunc(glyphset, glyphs) + + if sanitizeFunc is not None: + log.info("Sanitizing axis limit values for the `%s` axis.", axisTag) + sanitizeFunc(triple, designLimits, pins, axisMeasurements) + + log.debug("Calculated average value:\n%s", pformat(axisMeasurements)) + + for (rangeMin, targetMin), (rangeMax, targetMax) in zip( + list(sorted(pins.items()))[:-1], + list(sorted(pins.items()))[1:], + ): + targetValues = {w for w in values if rangeMin < w < rangeMax} + if not targetValues: + continue + + normalizedMin = normalizeValue(rangeMin, triple) + normalizedMax = normalizeValue(rangeMax, triple) + normalizedTargetMin = normalizeValue(targetMin, designLimits) + normalizedTargetMax = normalizeValue(targetMax, designLimits) + + log.info("Planning target values %s.", sorted(targetValues)) + log.info("Sampling %u points in range %g,%g.", samples, rangeMin, rangeMax) + valueMeasurements = axisMeasurements.copy() + for sample in range(1, samples + 1): + value = rangeMin + (rangeMax - rangeMin) * sample / (samples + 1) + log.debug("Sampling value %g.", value) + glyphset = glyphSetFunc(location={axisTag: value}) + designValue = piecewiseLinearMap(value, pins) + valueMeasurements[designValue] = measureFunc(glyphset, glyphs) + log.debug("Sampled average value:\n%s", pformat(valueMeasurements)) + + measurementValue = {} + for value in sorted(valueMeasurements): + measurementValue[valueMeasurements[value]] = value + + out[rangeMin] = targetMin + outNormalized[normalizedMin] = normalizedTargetMin + for value in sorted(targetValues): + t = normalizeFunc(value, rangeMin, rangeMax) + targetMeasurement = interpolateFunc( + t, valueMeasurements[targetMin], valueMeasurements[targetMax] + ) + targetValue = piecewiseLinearMap(targetMeasurement, measurementValue) + log.debug("Planned mapping value %g to %g." % (value, targetValue)) + out[value] = targetValue + valueNormalized = normalizedMin + (value - rangeMin) / ( + rangeMax - rangeMin + ) * (normalizedMax - normalizedMin) + outNormalized[valueNormalized] = normalizedTargetMin + ( + targetValue - targetMin + ) / (targetMax - targetMin) * (normalizedTargetMax - normalizedTargetMin) + out[rangeMax] = targetMax + outNormalized[normalizedMax] = normalizedTargetMax + + log.info("Planned mapping for the `%s` axis:\n%s", axisTag, pformat(out)) + log.info( + "Planned normalized mapping for the `%s` axis:\n%s", + axisTag, + pformat(outNormalized), + ) + + if all(abs(k - v) < 0.01 for k, v in outNormalized.items()): + log.info("Detected identity mapping for the `%s` axis. Dropping.", axisTag) + out = {} + outNormalized = {} + + return out, outNormalized + + +def planWeightAxis( + glyphSetFunc, + axisLimits, + weights=None, + samples=None, + glyphs=None, + designLimits=None, + pins=None, + sanitize=False, +): + """Plan a weight (`wght`) axis. + + weights: A list of weight values to plan for. If None, the default + values are used. + + This function simply calls planAxis with values=weights, and the appropriate + arguments. See documenation for planAxis for more information. + """ + + if weights is None: + weights = WEIGHTS + + return planAxis( + measureWeight, + normalizeLinear, + interpolateLog, + glyphSetFunc, + "wght", + axisLimits, + values=weights, + samples=samples, + glyphs=glyphs, + designLimits=designLimits, + pins=pins, + sanitizeFunc=sanitizeWeight if sanitize else None, + ) + + +def planWidthAxis( + glyphSetFunc, + axisLimits, + widths=None, + samples=None, + glyphs=None, + designLimits=None, + pins=None, + sanitize=False, +): + """Plan a width (`wdth`) axis. + + widths: A list of width values (percentages) to plan for. If None, the default + values are used. + + This function simply calls planAxis with values=widths, and the appropriate + arguments. See documenation for planAxis for more information. + """ + + if widths is None: + widths = WIDTHS + + return planAxis( + measureWidth, + normalizeLinear, + interpolateLinear, + glyphSetFunc, + "wdth", + axisLimits, + values=widths, + samples=samples, + glyphs=glyphs, + designLimits=designLimits, + pins=pins, + sanitizeFunc=sanitizeWidth if sanitize else None, + ) + + +def planSlantAxis( + glyphSetFunc, + axisLimits, + slants=None, + samples=None, + glyphs=None, + designLimits=None, + pins=None, + sanitize=False, +): + """Plan a slant (`slnt`) axis. + + slants: A list slant angles to plan for. If None, the default + values are used. + + This function simply calls planAxis with values=slants, and the appropriate + arguments. See documenation for planAxis for more information. + """ + + if slants is None: + slants = SLANTS + + return planAxis( + measureSlant, + normalizeDegrees, + interpolateLinear, + glyphSetFunc, + "slnt", + axisLimits, + values=slants, + samples=samples, + glyphs=glyphs, + designLimits=designLimits, + pins=pins, + sanitizeFunc=sanitizeSlant if sanitize else None, + ) + + +def planOpticalSizeAxis( + glyphSetFunc, + axisLimits, + sizes=None, + samples=None, + glyphs=None, + designLimits=None, + pins=None, + sanitize=False, +): + """Plan a optical-size (`opsz`) axis. + + sizes: A list of optical size values to plan for. If None, the default + values are used. + + This function simply calls planAxis with values=sizes, and the appropriate + arguments. See documenation for planAxis for more information. + """ + + if sizes is None: + sizes = SIZES + + return planAxis( + measureWeight, + normalizeLog, + interpolateLog, + glyphSetFunc, + "opsz", + axisLimits, + values=sizes, + samples=samples, + glyphs=glyphs, + designLimits=designLimits, + pins=pins, + ) + + +def makeDesignspaceSnippet(axisTag, axisName, axisLimit, mapping): + """Make a designspace snippet for a single axis.""" + + designspaceSnippet = ( + ' <axis tag="%s" name="%s" minimum="%g" default="%g" maximum="%g"' + % ((axisTag, axisName) + axisLimit) + ) + if mapping: + designspaceSnippet += ">\n" + else: + designspaceSnippet += "/>" + + for key, value in mapping.items(): + designspaceSnippet += ' <map input="%g" output="%g"/>\n' % (key, value) + + if mapping: + designspaceSnippet += " </axis>" + + return designspaceSnippet + + +def addEmptyAvar(font): + """Add an empty `avar` table to the font.""" + font["avar"] = avar = newTable("avar") + for axis in font["fvar"].axes: + avar.segments[axis.axisTag] = {} + + +def processAxis( + font, + planFunc, + axisTag, + axisName, + values, + samples=None, + glyphs=None, + designLimits=None, + pins=None, + sanitize=False, + plot=False, +): + """Process a single axis.""" + + axisLimits = None + for axis in font["fvar"].axes: + if axis.axisTag == axisTag: + axisLimits = axis + break + if axisLimits is None: + return "" + axisLimits = (axisLimits.minValue, axisLimits.defaultValue, axisLimits.maxValue) + + log.info("Planning %s axis.", axisName) + + if "avar" in font: + existingMapping = font["avar"].segments[axisTag] + font["avar"].segments[axisTag] = {} + else: + existingMapping = None + + if values is not None and isinstance(values, str): + values = [float(w) for w in values.split()] + + if designLimits is not None and isinstance(designLimits, str): + designLimits = [float(d) for d in designLimits.split(":")] + assert ( + len(designLimits) == 3 + and designLimits[0] <= designLimits[1] <= designLimits[2] + ) + else: + designLimits = None + + if pins is not None and isinstance(pins, str): + newPins = {} + for pin in pins.split(): + before, after = pin.split(":") + newPins[float(before)] = float(after) + pins = newPins + del newPins + + mapping, mappingNormalized = planFunc( + font.getGlyphSet, + axisLimits, + values, + samples=samples, + glyphs=glyphs, + designLimits=designLimits, + pins=pins, + sanitize=sanitize, + ) + + if plot: + from matplotlib import pyplot + + pyplot.plot( + sorted(mappingNormalized), + [mappingNormalized[k] for k in sorted(mappingNormalized)], + ) + pyplot.show() + + if existingMapping is not None: + log.info("Existing %s mapping:\n%s", axisName, pformat(existingMapping)) + + if mapping: + if "avar" not in font: + addEmptyAvar(font) + font["avar"].segments[axisTag] = mappingNormalized + else: + if "avar" in font: + font["avar"].segments[axisTag] = {} + + designspaceSnippet = makeDesignspaceSnippet( + axisTag, + axisName, + axisLimits, + mapping, + ) + return designspaceSnippet + + +def main(args=None): + """Plan the standard axis mappings for a variable font""" + + if args is None: + import sys + + args = sys.argv[1:] + + from fontTools import configLogger + from fontTools.ttLib import TTFont + import argparse + + parser = argparse.ArgumentParser( + "fonttools varLib.avar.plan", + description="Plan `avar` table for variable font", + ) + parser.add_argument("font", metavar="varfont.ttf", help="Variable-font file.") + parser.add_argument( + "-o", + "--output-file", + type=str, + help="Output font file name.", + ) + parser.add_argument( + "--weights", type=str, help="Space-separate list of weights to generate." + ) + parser.add_argument( + "--widths", type=str, help="Space-separate list of widths to generate." + ) + parser.add_argument( + "--slants", type=str, help="Space-separate list of slants to generate." + ) + parser.add_argument( + "--sizes", type=str, help="Space-separate list of optical-sizes to generate." + ) + parser.add_argument("--samples", type=int, help="Number of samples.") + parser.add_argument( + "-s", "--sanitize", action="store_true", help="Sanitize axis limits" + ) + parser.add_argument( + "-g", + "--glyphs", + type=str, + help="Space-separate list of glyphs to use for sampling.", + ) + parser.add_argument( + "--weight-design-limits", + type=str, + help="min:default:max in design units for the `wght` axis.", + ) + parser.add_argument( + "--width-design-limits", + type=str, + help="min:default:max in design units for the `wdth` axis.", + ) + parser.add_argument( + "--slant-design-limits", + type=str, + help="min:default:max in design units for the `slnt` axis.", + ) + parser.add_argument( + "--optical-size-design-limits", + type=str, + help="min:default:max in design units for the `opsz` axis.", + ) + parser.add_argument( + "--weight-pins", + type=str, + help="Space-separate list of before:after pins for the `wght` axis.", + ) + parser.add_argument( + "--width-pins", + type=str, + help="Space-separate list of before:after pins for the `wdth` axis.", + ) + parser.add_argument( + "--slant-pins", + type=str, + help="Space-separate list of before:after pins for the `slnt` axis.", + ) + parser.add_argument( + "--optical-size-pins", + type=str, + help="Space-separate list of before:after pins for the `opsz` axis.", + ) + parser.add_argument( + "-p", "--plot", action="store_true", help="Plot the resulting mapping." + ) + + logging_group = parser.add_mutually_exclusive_group(required=False) + logging_group.add_argument( + "-v", "--verbose", action="store_true", help="Run more verbosely." + ) + logging_group.add_argument( + "-q", "--quiet", action="store_true", help="Turn verbosity off." + ) + + options = parser.parse_args(args) + + configLogger( + level=("DEBUG" if options.verbose else "WARNING" if options.quiet else "INFO") + ) + + font = TTFont(options.font) + if not "fvar" in font: + log.error("Not a variable font.") + return 1 + + if options.glyphs is not None: + glyphs = options.glyphs.split() + if ":" in options.glyphs: + glyphs = {} + for g in options.glyphs.split(): + if ":" in g: + glyph, frequency = g.split(":") + glyphs[glyph] = float(frequency) + else: + glyphs[g] = 1.0 + else: + glyphs = None + + designspaceSnippets = [] + + designspaceSnippets.append( + processAxis( + font, + planWeightAxis, + "wght", + "Weight", + values=options.weights, + samples=options.samples, + glyphs=glyphs, + designLimits=options.weight_design_limits, + pins=options.weight_pins, + sanitize=options.sanitize, + plot=options.plot, + ) + ) + designspaceSnippets.append( + processAxis( + font, + planWidthAxis, + "wdth", + "Width", + values=options.widths, + samples=options.samples, + glyphs=glyphs, + designLimits=options.width_design_limits, + pins=options.width_pins, + sanitize=options.sanitize, + plot=options.plot, + ) + ) + designspaceSnippets.append( + processAxis( + font, + planSlantAxis, + "slnt", + "Slant", + values=options.slants, + samples=options.samples, + glyphs=glyphs, + designLimits=options.slant_design_limits, + pins=options.slant_pins, + sanitize=options.sanitize, + plot=options.plot, + ) + ) + designspaceSnippets.append( + processAxis( + font, + planOpticalSizeAxis, + "opsz", + "OpticalSize", + values=options.sizes, + samples=options.samples, + glyphs=glyphs, + designLimits=options.optical_size_design_limits, + pins=options.optical_size_pins, + sanitize=options.sanitize, + plot=options.plot, + ) + ) + + log.info("Designspace snippet:") + for snippet in designspaceSnippets: + if snippet: + print(snippet) + + if options.output_file is None: + outfile = makeOutputFileName(options.font, overWrite=True, suffix=".avar") + else: + outfile = options.output_file + if outfile: + log.info("Saving %s", outfile) + font.save(outfile) + + +if __name__ == "__main__": + import sys + + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/unbuild.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/unbuild.py new file mode 100644 index 0000000000000000000000000000000000000000..ddf677902cea837c5cbf3ba37a6b3f0847e72bbc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/avar/unbuild.py @@ -0,0 +1,274 @@ +from fontTools.varLib.models import VariationModel +from fontTools.varLib.varStore import VarStoreInstancer +from fontTools.misc.fixedTools import fixedToFloat as fi2fl +from itertools import product +import sys + + +def _denormalize(v, axis): + if v >= 0: + return axis.defaultValue + v * (axis.maxValue - axis.defaultValue) + else: + return axis.defaultValue + v * (axis.defaultValue - axis.minValue) + + +def _pruneLocations(locations, poles, axisTags): + # Now we have all the input locations, find which ones are + # not needed and remove them. + + # Note: This algorithm is heavily tied to how VariationModel + # is implemented. It assumes that input was extracted from + # VariationModel-generated object, like an ItemVariationStore + # created by fontmake using varLib.models.VariationModel. + # Some CoPilot blabbering: + # I *think* I can prove that this algorithm is correct, but + # I'm not 100% sure. It's possible that there are edge cases + # where this algorithm will fail. I'm not sure how to prove + # that it's correct, but I'm also not sure how to prove that + # it's incorrect. I'm not sure how to write a test case that + # would prove that it's incorrect. I'm not sure how to write + # a test case that would prove that it's correct. + + model = VariationModel(locations, axisTags) + modelMapping = model.mapping + modelSupports = model.supports + pins = {tuple(k.items()): None for k in poles} + for location in poles: + i = locations.index(location) + i = modelMapping[i] + support = modelSupports[i] + supportAxes = set(support.keys()) + for axisTag, (minV, _, maxV) in support.items(): + for v in (minV, maxV): + if v in (-1, 0, 1): + continue + for pin in pins.keys(): + pinLocation = dict(pin) + pinAxes = set(pinLocation.keys()) + if pinAxes != supportAxes: + continue + if axisTag not in pinAxes: + continue + if pinLocation[axisTag] == v: + break + else: + # No pin found. Go through the previous masters + # and find a suitable pin. Going backwards is + # better because it can find a pin that is close + # to the pole in more dimensions, and reducing + # the total number of pins needed. + for candidateIdx in range(i - 1, -1, -1): + candidate = modelSupports[candidateIdx] + candidateAxes = set(candidate.keys()) + if candidateAxes != supportAxes: + continue + if axisTag not in candidateAxes: + continue + candidate = { + k: defaultV for k, (_, defaultV, _) in candidate.items() + } + if candidate[axisTag] == v: + pins[tuple(candidate.items())] = None + break + else: + assert False, "No pin found" + return [dict(t) for t in pins.keys()] + + +def mappings_from_avar(font, denormalize=True): + fvarAxes = font["fvar"].axes + axisMap = {a.axisTag: a for a in fvarAxes} + axisTags = [a.axisTag for a in fvarAxes] + axisIndexes = {a.axisTag: i for i, a in enumerate(fvarAxes)} + if "avar" not in font: + return {}, [] + avar = font["avar"] + axisMaps = { + tag: seg + for tag, seg in avar.segments.items() + if seg and seg != {-1: -1, 0: 0, 1: 1} + } + mappings = [] + + if getattr(avar, "majorVersion", 1) == 2: + varStore = avar.table.VarStore + regions = varStore.VarRegionList.Region + + # Find all the input locations; this finds "poles", that are + # locations of the peaks, and "corners", that are locations + # of the corners of the regions. These two sets of locations + # together constitute inputLocations to consider. + + poles = {(): None} # Just using it as an ordered set + inputLocations = set({()}) + for varData in varStore.VarData: + regionIndices = varData.VarRegionIndex + for regionIndex in regionIndices: + peakLocation = [] + corners = [] + region = regions[regionIndex] + for axisIndex, axis in enumerate(region.VarRegionAxis): + if axis.PeakCoord == 0: + continue + axisTag = axisTags[axisIndex] + peakLocation.append((axisTag, axis.PeakCoord)) + corner = [] + if axis.StartCoord != 0: + corner.append((axisTag, axis.StartCoord)) + if axis.EndCoord != 0: + corner.append((axisTag, axis.EndCoord)) + corners.append(corner) + corners = set(product(*corners)) + peakLocation = tuple(peakLocation) + poles[peakLocation] = None + inputLocations.add(peakLocation) + inputLocations.update(corners) + + # Sort them by number of axes, then by axis order + inputLocations = [ + dict(t) + for t in sorted( + inputLocations, + key=lambda t: (len(t), tuple(axisIndexes[tag] for tag, _ in t)), + ) + ] + poles = [dict(t) for t in poles.keys()] + inputLocations = _pruneLocations(inputLocations, list(poles), axisTags) + + # Find the output locations, at input locations + varIdxMap = avar.table.VarIdxMap + instancer = VarStoreInstancer(varStore, fvarAxes) + for location in inputLocations: + instancer.setLocation(location) + outputLocation = {} + for axisIndex, axisTag in enumerate(axisTags): + varIdx = axisIndex + if varIdxMap is not None: + varIdx = varIdxMap[varIdx] + delta = instancer[varIdx] + if delta != 0: + v = location.get(axisTag, 0) + v = v + fi2fl(delta, 14) + # See https://github.com/fonttools/fonttools/pull/3598#issuecomment-2266082009 + # v = max(-1, min(1, v)) + outputLocation[axisTag] = v + mappings.append((location, outputLocation)) + + # Remove base master we added, if it maps to the default location + assert mappings[0][0] == {} + if mappings[0][1] == {}: + mappings.pop(0) + + if denormalize: + for tag, seg in axisMaps.items(): + if tag not in axisMap: + raise ValueError(f"Unknown axis tag {tag}") + denorm = lambda v: _denormalize(v, axisMap[tag]) + axisMaps[tag] = {denorm(k): denorm(v) for k, v in seg.items()} + + for i, (inputLoc, outputLoc) in enumerate(mappings): + inputLoc = { + tag: _denormalize(val, axisMap[tag]) for tag, val in inputLoc.items() + } + outputLoc = { + tag: _denormalize(val, axisMap[tag]) for tag, val in outputLoc.items() + } + mappings[i] = (inputLoc, outputLoc) + + return axisMaps, mappings + + +def unbuild(font, f=sys.stdout): + fvar = font["fvar"] + axes = fvar.axes + segments, mappings = mappings_from_avar(font) + + if "name" in font: + name = font["name"] + axisNames = { + axis.axisTag: name.getDebugName(axis.axisNameID) or axis.axisTag + for axis in axes + } + else: + axisNames = {a.axisTag: a.axisTag for a in axes} + + print("<?xml version='1.0' encoding='UTF-8'?>", file=f) + print('<designspace format="5.1">', file=f) + print(" <axes>", file=f) + for axis in axes: + + axisName = axisNames[axis.axisTag] + + triplet = (axis.minValue, axis.defaultValue, axis.maxValue) + triplet = [int(v) if v == int(v) else v for v in triplet] + + axisMap = segments.get(axis.axisTag) + closing = "/>" if axisMap is None else ">" + + print( + f' <axis tag="{axis.axisTag}" name="{axisName}" minimum="{triplet[0]}" maximum="{triplet[2]}" default="{triplet[1]}"{closing}', + file=f, + ) + if axisMap is not None: + for k in sorted(axisMap.keys()): + v = axisMap[k] + k = int(k) if k == int(k) else k + v = int(v) if v == int(v) else v + print(f' <map input="{k}" output="{v}"/>', file=f) + print(" </axis>", file=f) + if mappings: + print(" <mappings>", file=f) + for inputLoc, outputLoc in mappings: + print(" <mapping>", file=f) + print(" <input>", file=f) + for tag in sorted(inputLoc.keys()): + v = inputLoc[tag] + v = int(v) if v == int(v) else v + print( + f' <dimension name="{axisNames[tag]}" xvalue="{v}"/>', + file=f, + ) + print(" </input>", file=f) + print(" <output>", file=f) + for tag in sorted(outputLoc.keys()): + v = outputLoc[tag] + v = int(v) if v == int(v) else v + print( + f' <dimension name="{axisNames[tag]}" xvalue="{v}"/>', + file=f, + ) + print(" </output>", file=f) + print(" </mapping>", file=f) + print(" </mappings>", file=f) + print(" </axes>", file=f) + print("</designspace>", file=f) + + +def main(args=None): + """Print `avar` table as a designspace snippet.""" + + if args is None: + args = sys.argv[1:] + + from fontTools.ttLib import TTFont + import argparse + + parser = argparse.ArgumentParser( + "fonttools varLib.avar.unbuild", + description="Print `avar` table as a designspace snippet.", + ) + parser.add_argument("font", metavar="varfont.ttf", help="Variable-font file.") + options = parser.parse_args(args) + + font = TTFont(options.font) + if "fvar" not in font: + print("Not a variable font.", file=sys.stderr) + return 1 + + unbuild(font) + + +if __name__ == "__main__": + import sys + + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/avarPlanner.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/avarPlanner.py new file mode 100644 index 0000000000000000000000000000000000000000..1fc63b1c1b32cc04151c06708d28cb3d75f0b978 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/avarPlanner.py @@ -0,0 +1,8 @@ +def main(args=None): + from .avar.plan import main + + main(args) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/builder.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..456c34c4dd903d1ba7704c46bfb8e2af212cd0a4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/builder.py @@ -0,0 +1,215 @@ +from fontTools import ttLib +from fontTools.ttLib.tables import otTables as ot + +# VariationStore + + +def buildVarRegionAxis(axisSupport): + self = ot.VarRegionAxis() + self.StartCoord, self.PeakCoord, self.EndCoord = [float(v) for v in axisSupport] + return self + + +def buildSparseVarRegionAxis(axisIndex, axisSupport): + self = ot.SparseVarRegionAxis() + self.AxisIndex = axisIndex + self.StartCoord, self.PeakCoord, self.EndCoord = [float(v) for v in axisSupport] + return self + + +def buildVarRegion(support, axisTags): + assert all(tag in axisTags for tag in support.keys()), ( + "Unknown axis tag found.", + support, + axisTags, + ) + self = ot.VarRegion() + self.VarRegionAxis = [] + for tag in axisTags: + self.VarRegionAxis.append(buildVarRegionAxis(support.get(tag, (0, 0, 0)))) + return self + + +def buildSparseVarRegion(support, axisTags): + assert all(tag in axisTags for tag in support.keys()), ( + "Unknown axis tag found.", + support, + axisTags, + ) + self = ot.SparseVarRegion() + self.SparseVarRegionAxis = [] + for i, tag in enumerate(axisTags): + if tag not in support: + continue + self.SparseVarRegionAxis.append( + buildSparseVarRegionAxis(i, support.get(tag, (0, 0, 0))) + ) + self.SparseRegionCount = len(self.SparseVarRegionAxis) + return self + + +def buildVarRegionList(supports, axisTags): + self = ot.VarRegionList() + self.RegionAxisCount = len(axisTags) + self.Region = [] + for support in supports: + self.Region.append(buildVarRegion(support, axisTags)) + self.RegionCount = len(self.Region) + return self + + +def buildSparseVarRegionList(supports, axisTags): + self = ot.SparseVarRegionList() + self.RegionAxisCount = len(axisTags) + self.Region = [] + for support in supports: + self.Region.append(buildSparseVarRegion(support, axisTags)) + self.RegionCount = len(self.Region) + return self + + +def _reorderItem(lst, mapping): + return [lst[i] for i in mapping] + + +def VarData_calculateNumShorts(self, optimize=False): + count = self.VarRegionCount + items = self.Item + bit_lengths = [0] * count + for item in items: + # The "+ (i < -1)" magic is to handle two's-compliment. + # That is, we want to get back 7 for -128, whereas + # bit_length() returns 8. Similarly for -65536. + # The reason "i < -1" is used instead of "i < 0" is that + # the latter would make it return 0 for "-1" instead of 1. + bl = [(i + (i < -1)).bit_length() for i in item] + bit_lengths = [max(*pair) for pair in zip(bl, bit_lengths)] + # The addition of 8, instead of seven, is to account for the sign bit. + # This "((b + 8) >> 3) if b else 0" when combined with the above + # "(i + (i < -1)).bit_length()" is a faster way to compute byte-lengths + # conforming to: + # + # byte_length = (0 if i == 0 else + # 1 if -128 <= i < 128 else + # 2 if -65536 <= i < 65536 else + # ...) + byte_lengths = [((b + 8) >> 3) if b else 0 for b in bit_lengths] + + # https://github.com/fonttools/fonttools/issues/2279 + longWords = any(b > 2 for b in byte_lengths) + + if optimize: + # Reorder columns such that wider columns come before narrower columns + mapping = [] + mapping.extend(i for i, b in enumerate(byte_lengths) if b > 2) + mapping.extend(i for i, b in enumerate(byte_lengths) if b == 2) + mapping.extend(i for i, b in enumerate(byte_lengths) if b == 1) + + byte_lengths = _reorderItem(byte_lengths, mapping) + self.VarRegionIndex = _reorderItem(self.VarRegionIndex, mapping) + self.VarRegionCount = len(self.VarRegionIndex) + for i in range(len(items)): + items[i] = _reorderItem(items[i], mapping) + + if longWords: + self.NumShorts = ( + max((i for i, b in enumerate(byte_lengths) if b > 2), default=-1) + 1 + ) + self.NumShorts |= 0x8000 + else: + self.NumShorts = ( + max((i for i, b in enumerate(byte_lengths) if b > 1), default=-1) + 1 + ) + + self.VarRegionCount = len(self.VarRegionIndex) + return self + + +ot.VarData.calculateNumShorts = VarData_calculateNumShorts + + +def VarData_CalculateNumShorts(self, optimize=True): + """Deprecated name for VarData_calculateNumShorts() which + defaults to optimize=True. Use varData.calculateNumShorts() + or varData.optimize().""" + return VarData_calculateNumShorts(self, optimize=optimize) + + +def VarData_optimize(self): + return VarData_calculateNumShorts(self, optimize=True) + + +ot.VarData.optimize = VarData_optimize + + +def buildVarData(varRegionIndices, items, optimize=True): + self = ot.VarData() + self.VarRegionIndex = list(varRegionIndices) + regionCount = self.VarRegionCount = len(self.VarRegionIndex) + records = self.Item = [] + if items: + for item in items: + assert len(item) == regionCount + records.append(list(item)) + self.ItemCount = len(self.Item) + self.calculateNumShorts(optimize=optimize) + return self + + +def buildVarStore(varRegionList, varDataList): + self = ot.VarStore() + self.Format = 1 + self.VarRegionList = varRegionList + self.VarData = list(varDataList) + self.VarDataCount = len(self.VarData) + return self + + +def buildMultiVarData(varRegionIndices, items): + self = ot.MultiVarData() + self.Format = 1 + self.VarRegionIndex = list(varRegionIndices) + regionCount = self.VarRegionCount = len(self.VarRegionIndex) + records = self.Item = [] + if items: + for item in items: + assert len(item) == regionCount + records.append(list(item)) + self.ItemCount = len(self.Item) + return self + + +def buildMultiVarStore(varRegionList, multiVarDataList): + self = ot.MultiVarStore() + self.Format = 1 + self.SparseVarRegionList = varRegionList + self.MultiVarData = list(multiVarDataList) + self.MultiVarDataCount = len(self.MultiVarData) + return self + + +# Variation helpers + + +def buildVarIdxMap(varIdxes, glyphOrder): + self = ot.VarIdxMap() + self.mapping = {g: v for g, v in zip(glyphOrder, varIdxes)} + return self + + +def buildDeltaSetIndexMap(varIdxes): + mapping = list(varIdxes) + if all(i == v for i, v in enumerate(mapping)): + return None + self = ot.DeltaSetIndexMap() + self.mapping = mapping + self.Format = 1 if len(mapping) > 0xFFFF else 0 + return self + + +def buildVarDevTable(varIdx): + self = ot.Device() + self.DeltaFormat = 0x8000 + self.StartSize = varIdx >> 16 + self.EndSize = varIdx & 0xFFFF + return self diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/cff.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/cff.py new file mode 100644 index 0000000000000000000000000000000000000000..4c36c96a8dda3b7d45975470e6cf87d66ce1b053 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/cff.py @@ -0,0 +1,630 @@ +from collections import namedtuple +from fontTools.cffLib import ( + maxStackLimit, + TopDictIndex, + buildOrder, + topDictOperators, + topDictOperators2, + privateDictOperators, + privateDictOperators2, + FDArrayIndex, + FontDict, + VarStoreData, +) +from io import BytesIO +from fontTools.cffLib.specializer import specializeCommands, commandsToProgram +from fontTools.ttLib import newTable +from fontTools import varLib +from fontTools.varLib.models import allEqual +from fontTools.misc.loggingTools import deprecateFunction +from fontTools.misc.roundTools import roundFunc +from fontTools.misc.psCharStrings import T2CharString, T2OutlineExtractor +from fontTools.pens.t2CharStringPen import T2CharStringPen +from functools import partial + +from .errors import ( + VarLibCFFDictMergeError, + VarLibCFFPointTypeMergeError, + VarLibCFFHintTypeMergeError, + VarLibMergeError, +) + +# Backwards compatibility +MergeDictError = VarLibCFFDictMergeError +MergeTypeError = VarLibCFFPointTypeMergeError + + +def addCFFVarStore(varFont, varModel, varDataList, masterSupports): + fvarTable = varFont["fvar"] + axisKeys = [axis.axisTag for axis in fvarTable.axes] + varTupleList = varLib.builder.buildVarRegionList(masterSupports, axisKeys) + varStoreCFFV = varLib.builder.buildVarStore(varTupleList, varDataList) + + topDict = varFont["CFF2"].cff.topDictIndex[0] + topDict.VarStore = VarStoreData(otVarStore=varStoreCFFV) + if topDict.FDArray[0].vstore is None: + fdArray = topDict.FDArray + for fontDict in fdArray: + if hasattr(fontDict, "Private"): + fontDict.Private.vstore = topDict.VarStore + + +@deprecateFunction("Use fontTools.cffLib.CFFToCFF2.convertCFFToCFF2 instead.") +def convertCFFtoCFF2(varFont): + from fontTools.cffLib.CFFToCFF2 import convertCFFToCFF2 + + return convertCFFToCFF2(varFont) + + +def conv_to_int(num): + if isinstance(num, float) and num.is_integer(): + return int(num) + return num + + +pd_blend_fields = ( + "BlueValues", + "OtherBlues", + "FamilyBlues", + "FamilyOtherBlues", + "BlueScale", + "BlueShift", + "BlueFuzz", + "StdHW", + "StdVW", + "StemSnapH", + "StemSnapV", +) + + +def get_private(regionFDArrays, fd_index, ri, fd_map): + region_fdArray = regionFDArrays[ri] + region_fd_map = fd_map[fd_index] + if ri in region_fd_map: + region_fdIndex = region_fd_map[ri] + private = region_fdArray[region_fdIndex].Private + else: + private = None + return private + + +def merge_PrivateDicts(top_dicts, vsindex_dict, var_model, fd_map): + """ + I step through the FontDicts in the FDArray of the varfont TopDict. + For each varfont FontDict: + + * step through each key in FontDict.Private. + * For each key, step through each relevant source font Private dict, and + build a list of values to blend. + + The 'relevant' source fonts are selected by first getting the right + submodel using ``vsindex_dict[vsindex]``. The indices of the + ``subModel.locations`` are mapped to source font list indices by + assuming the latter order is the same as the order of the + ``var_model.locations``. I can then get the index of each subModel + location in the list of ``var_model.locations``. + """ + + topDict = top_dicts[0] + region_top_dicts = top_dicts[1:] + if hasattr(region_top_dicts[0], "FDArray"): + regionFDArrays = [fdTopDict.FDArray for fdTopDict in region_top_dicts] + else: + regionFDArrays = [[fdTopDict] for fdTopDict in region_top_dicts] + for fd_index, font_dict in enumerate(topDict.FDArray): + private_dict = font_dict.Private + vsindex = getattr(private_dict, "vsindex", 0) + # At the moment, no PrivateDict has a vsindex key, but let's support + # how it should work. See comment at end of + # merge_charstrings() - still need to optimize use of vsindex. + sub_model, _ = vsindex_dict[vsindex] + master_indices = [] + for loc in sub_model.locations[1:]: + i = var_model.locations.index(loc) - 1 + master_indices.append(i) + pds = [private_dict] + last_pd = private_dict + for ri in master_indices: + pd = get_private(regionFDArrays, fd_index, ri, fd_map) + # If the region font doesn't have this FontDict, just reference + # the last one used. + if pd is None: + pd = last_pd + else: + last_pd = pd + pds.append(pd) + num_masters = len(pds) + for key, value in private_dict.rawDict.items(): + dataList = [] + if key not in pd_blend_fields: + continue + if isinstance(value, list): + try: + values = [pd.rawDict[key] for pd in pds] + except KeyError: + print( + "Warning: {key} in default font Private dict is " + "missing from another font, and was " + "discarded.".format(key=key) + ) + continue + try: + values = zip(*values) + except IndexError: + raise VarLibCFFDictMergeError(key, value, values) + """ + Row 0 contains the first value from each master. + Convert each row from absolute values to relative + values from the previous row. + e.g for three masters, a list of values was: + master 0 OtherBlues = [-217,-205] + master 1 OtherBlues = [-234,-222] + master 1 OtherBlues = [-188,-176] + The call to zip() converts this to: + [(-217, -234, -188), (-205, -222, -176)] + and is converted finally to: + OtherBlues = [[-217, 17.0, 46.0], [-205, 0.0, 0.0]] + """ + prev_val_list = [0] * num_masters + any_points_differ = False + for val_list in values: + rel_list = [ + (val - prev_val_list[i]) for (i, val) in enumerate(val_list) + ] + if (not any_points_differ) and not allEqual(rel_list): + any_points_differ = True + prev_val_list = val_list + deltas = sub_model.getDeltas(rel_list) + # For PrivateDict BlueValues, the default font + # values are absolute, not relative to the prior value. + deltas[0] = val_list[0] + dataList.append(deltas) + # If there are no blend values,then + # we can collapse the blend lists. + if not any_points_differ: + dataList = [data[0] for data in dataList] + else: + values = [pd.rawDict[key] for pd in pds] + if not allEqual(values): + dataList = sub_model.getDeltas(values) + else: + dataList = values[0] + + # Convert numbers with no decimal part to an int + if isinstance(dataList, list): + for i, item in enumerate(dataList): + if isinstance(item, list): + for j, jtem in enumerate(item): + dataList[i][j] = conv_to_int(jtem) + else: + dataList[i] = conv_to_int(item) + else: + dataList = conv_to_int(dataList) + + private_dict.rawDict[key] = dataList + + +def _cff_or_cff2(font): + if "CFF " in font: + return font["CFF "] + return font["CFF2"] + + +def getfd_map(varFont, fonts_list): + """Since a subset source font may have fewer FontDicts in their + FDArray than the default font, we have to match up the FontDicts in + the different fonts . We do this with the FDSelect array, and by + assuming that the same glyph will reference matching FontDicts in + each source font. We return a mapping from fdIndex in the default + font to a dictionary which maps each master list index of each + region font to the equivalent fdIndex in the region font.""" + fd_map = {} + default_font = fonts_list[0] + region_fonts = fonts_list[1:] + num_regions = len(region_fonts) + topDict = _cff_or_cff2(default_font).cff.topDictIndex[0] + if not hasattr(topDict, "FDSelect"): + # All glyphs reference only one FontDict. + # Map the FD index for regions to index 0. + fd_map[0] = {ri: 0 for ri in range(num_regions)} + return fd_map + + gname_mapping = {} + default_fdSelect = topDict.FDSelect + glyphOrder = default_font.getGlyphOrder() + for gid, fdIndex in enumerate(default_fdSelect): + gname_mapping[glyphOrder[gid]] = fdIndex + if fdIndex not in fd_map: + fd_map[fdIndex] = {} + for ri, region_font in enumerate(region_fonts): + region_glyphOrder = region_font.getGlyphOrder() + region_topDict = _cff_or_cff2(region_font).cff.topDictIndex[0] + if not hasattr(region_topDict, "FDSelect"): + # All the glyphs share the same FontDict. Pick any glyph. + default_fdIndex = gname_mapping[region_glyphOrder[0]] + fd_map[default_fdIndex][ri] = 0 + else: + region_fdSelect = region_topDict.FDSelect + for gid, fdIndex in enumerate(region_fdSelect): + default_fdIndex = gname_mapping[region_glyphOrder[gid]] + region_map = fd_map[default_fdIndex] + if ri not in region_map: + region_map[ri] = fdIndex + return fd_map + + +CVarData = namedtuple("CVarData", "varDataList masterSupports vsindex_dict") + + +def merge_region_fonts(varFont, model, ordered_fonts_list, glyphOrder): + topDict = varFont["CFF2"].cff.topDictIndex[0] + top_dicts = [topDict] + [ + _cff_or_cff2(ttFont).cff.topDictIndex[0] for ttFont in ordered_fonts_list[1:] + ] + num_masters = len(model.mapping) + cvData = merge_charstrings(glyphOrder, num_masters, top_dicts, model) + fd_map = getfd_map(varFont, ordered_fonts_list) + merge_PrivateDicts(top_dicts, cvData.vsindex_dict, model, fd_map) + addCFFVarStore(varFont, model, cvData.varDataList, cvData.masterSupports) + + +def _get_cs(charstrings, glyphName, filterEmpty=False): + if glyphName not in charstrings: + return None + cs = charstrings[glyphName] + + if filterEmpty: + cs.decompile() + if cs.program == []: # CFF2 empty charstring + return None + elif ( + len(cs.program) <= 2 + and cs.program[-1] == "endchar" + and (len(cs.program) == 1 or type(cs.program[0]) in (int, float)) + ): # CFF1 empty charstring + return None + + return cs + + +def _add_new_vsindex( + model, key, masterSupports, vsindex_dict, vsindex_by_key, varDataList +): + varTupleIndexes = [] + for support in model.supports[1:]: + if support not in masterSupports: + masterSupports.append(support) + varTupleIndexes.append(masterSupports.index(support)) + var_data = varLib.builder.buildVarData(varTupleIndexes, None, False) + vsindex = len(vsindex_dict) + vsindex_by_key[key] = vsindex + vsindex_dict[vsindex] = (model, [key]) + varDataList.append(var_data) + return vsindex + + +def merge_charstrings(glyphOrder, num_masters, top_dicts, masterModel): + vsindex_dict = {} + vsindex_by_key = {} + varDataList = [] + masterSupports = [] + default_charstrings = top_dicts[0].CharStrings + for gid, gname in enumerate(glyphOrder): + # interpret empty non-default masters as missing glyphs from a sparse master + all_cs = [ + _get_cs(td.CharStrings, gname, i != 0) for i, td in enumerate(top_dicts) + ] + model, model_cs = masterModel.getSubModel(all_cs) + # create the first pass CFF2 charstring, from + # the default charstring. + default_charstring = model_cs[0] + var_pen = CFF2CharStringMergePen([], gname, num_masters, 0) + # We need to override outlineExtractor because these + # charstrings do have widths in the 'program'; we need to drop these + # values rather than post assertion error for them. + default_charstring.outlineExtractor = MergeOutlineExtractor + default_charstring.draw(var_pen) + + # Add the coordinates from all the other regions to the + # blend lists in the CFF2 charstring. + region_cs = model_cs[1:] + for region_idx, region_charstring in enumerate(region_cs, start=1): + var_pen.restart(region_idx) + region_charstring.outlineExtractor = MergeOutlineExtractor + region_charstring.draw(var_pen) + + # Collapse each coordinate list to a blend operator and its args. + new_cs = var_pen.getCharString( + private=default_charstring.private, + globalSubrs=default_charstring.globalSubrs, + var_model=model, + optimize=True, + ) + default_charstrings[gname] = new_cs + + if not region_cs: + continue + + if (not var_pen.seen_moveto) or ("blend" not in new_cs.program): + # If this is not a marking glyph, or if there are no blend + # arguments, then we can use vsindex 0. No need to + # check if we need a new vsindex. + continue + + # If the charstring required a new model, create + # a VarData table to go with, and set vsindex. + key = tuple(v is not None for v in all_cs) + try: + vsindex = vsindex_by_key[key] + except KeyError: + vsindex = _add_new_vsindex( + model, key, masterSupports, vsindex_dict, vsindex_by_key, varDataList + ) + # We do not need to check for an existing new_cs.private.vsindex, + # as we know it doesn't exist yet. + if vsindex != 0: + new_cs.program[:0] = [vsindex, "vsindex"] + + # If there is no variation in any of the charstrings, then vsindex_dict + # never gets built. This could still be needed if there is variation + # in the PrivatDict, so we will build the default data for vsindex = 0. + if not vsindex_dict: + key = (True,) * num_masters + _add_new_vsindex( + masterModel, key, masterSupports, vsindex_dict, vsindex_by_key, varDataList + ) + cvData = CVarData( + varDataList=varDataList, + masterSupports=masterSupports, + vsindex_dict=vsindex_dict, + ) + # XXX To do: optimize use of vsindex between the PrivateDicts and + # charstrings + return cvData + + +class CFFToCFF2OutlineExtractor(T2OutlineExtractor): + """This class is used to remove the initial width from the CFF + charstring without trying to add the width to self.nominalWidthX, + which is None.""" + + def popallWidth(self, evenOdd=0): + args = self.popall() + if not self.gotWidth: + if evenOdd ^ (len(args) % 2): + args = args[1:] + self.width = self.defaultWidthX + self.gotWidth = 1 + return args + + +class MergeOutlineExtractor(CFFToCFF2OutlineExtractor): + """Used to extract the charstring commands - including hints - from a + CFF charstring in order to merge it as another set of region data + into a CFF2 variable font charstring.""" + + def __init__( + self, + pen, + localSubrs, + globalSubrs, + nominalWidthX, + defaultWidthX, + private=None, + blender=None, + ): + super().__init__( + pen, localSubrs, globalSubrs, nominalWidthX, defaultWidthX, private, blender + ) + + def countHints(self): + args = self.popallWidth() + self.hintCount = self.hintCount + len(args) // 2 + return args + + def _hint_op(self, type, args): + self.pen.add_hint(type, args) + + def op_hstem(self, index): + args = self.countHints() + self._hint_op("hstem", args) + + def op_vstem(self, index): + args = self.countHints() + self._hint_op("vstem", args) + + def op_hstemhm(self, index): + args = self.countHints() + self._hint_op("hstemhm", args) + + def op_vstemhm(self, index): + args = self.countHints() + self._hint_op("vstemhm", args) + + def _get_hintmask(self, index): + if not self.hintMaskBytes: + args = self.countHints() + if args: + self._hint_op("vstemhm", args) + self.hintMaskBytes = (self.hintCount + 7) // 8 + hintMaskBytes, index = self.callingStack[-1].getBytes(index, self.hintMaskBytes) + return index, hintMaskBytes + + def op_hintmask(self, index): + index, hintMaskBytes = self._get_hintmask(index) + self.pen.add_hintmask("hintmask", [hintMaskBytes]) + return hintMaskBytes, index + + def op_cntrmask(self, index): + index, hintMaskBytes = self._get_hintmask(index) + self.pen.add_hintmask("cntrmask", [hintMaskBytes]) + return hintMaskBytes, index + + +class CFF2CharStringMergePen(T2CharStringPen): + """Pen to merge Type 2 CharStrings.""" + + def __init__( + self, default_commands, glyphName, num_masters, master_idx, roundTolerance=0.01 + ): + # For roundTolerance see https://github.com/fonttools/fonttools/issues/2838 + super().__init__( + width=None, glyphSet=None, CFF2=True, roundTolerance=roundTolerance + ) + self.pt_index = 0 + self._commands = default_commands + self.m_index = master_idx + self.num_masters = num_masters + self.prev_move_idx = 0 + self.seen_moveto = False + self.glyphName = glyphName + self.round = roundFunc(roundTolerance, round=round) + + def add_point(self, point_type, pt_coords): + if self.m_index == 0: + self._commands.append([point_type, [pt_coords]]) + else: + cmd = self._commands[self.pt_index] + if cmd[0] != point_type: + raise VarLibCFFPointTypeMergeError( + point_type, self.pt_index, len(cmd[1]), cmd[0], self.glyphName + ) + cmd[1].append(pt_coords) + self.pt_index += 1 + + def add_hint(self, hint_type, args): + if self.m_index == 0: + self._commands.append([hint_type, [args]]) + else: + cmd = self._commands[self.pt_index] + if cmd[0] != hint_type: + raise VarLibCFFHintTypeMergeError( + hint_type, self.pt_index, len(cmd[1]), cmd[0], self.glyphName + ) + cmd[1].append(args) + self.pt_index += 1 + + def add_hintmask(self, hint_type, abs_args): + # For hintmask, fonttools.cffLib.specializer.py expects + # each of these to be represented by two sequential commands: + # first holding only the operator name, with an empty arg list, + # second with an empty string as the op name, and the mask arg list. + if self.m_index == 0: + self._commands.append([hint_type, []]) + self._commands.append(["", [abs_args]]) + else: + cmd = self._commands[self.pt_index] + if cmd[0] != hint_type: + raise VarLibCFFHintTypeMergeError( + hint_type, self.pt_index, len(cmd[1]), cmd[0], self.glyphName + ) + self.pt_index += 1 + cmd = self._commands[self.pt_index] + cmd[1].append(abs_args) + self.pt_index += 1 + + def _moveTo(self, pt): + if not self.seen_moveto: + self.seen_moveto = True + pt_coords = self._p(pt) + self.add_point("rmoveto", pt_coords) + # I set prev_move_idx here because add_point() + # can change self.pt_index. + self.prev_move_idx = self.pt_index - 1 + + def _lineTo(self, pt): + pt_coords = self._p(pt) + self.add_point("rlineto", pt_coords) + + def _curveToOne(self, pt1, pt2, pt3): + _p = self._p + pt_coords = _p(pt1) + _p(pt2) + _p(pt3) + self.add_point("rrcurveto", pt_coords) + + def _closePath(self): + pass + + def _endPath(self): + pass + + def restart(self, region_idx): + self.pt_index = 0 + self.m_index = region_idx + self._p0 = (0, 0) + + def getCommands(self): + return self._commands + + def reorder_blend_args(self, commands, get_delta_func): + """ + We first re-order the master coordinate values. + For a moveto to lineto, the args are now arranged as:: + + [ [master_0 x,y], [master_1 x,y], [master_2 x,y] ] + + We re-arrange this to:: + + [ [master_0 x, master_1 x, master_2 x], + [master_0 y, master_1 y, master_2 y] + ] + + If the master values are all the same, we collapse the list to + as single value instead of a list. + + We then convert this to:: + + [ [master_0 x] + [x delta tuple] + [numBlends=1] + [master_0 y] + [y delta tuple] + [numBlends=1] + ] + """ + for cmd in commands: + # arg[i] is the set of arguments for this operator from master i. + args = cmd[1] + m_args = zip(*args) + # m_args[n] is now all num_master args for the i'th argument + # for this operation. + cmd[1] = list(m_args) + lastOp = None + for cmd in commands: + op = cmd[0] + # masks are represented by two cmd's: first has only op names, + # second has only args. + if lastOp in ["hintmask", "cntrmask"]: + coord = list(cmd[1]) + if not allEqual(coord): + raise VarLibMergeError( + "Hintmask values cannot differ between source fonts." + ) + cmd[1] = [coord[0][0]] + else: + coords = cmd[1] + new_coords = [] + for coord in coords: + if allEqual(coord): + new_coords.append(coord[0]) + else: + # convert to deltas + deltas = get_delta_func(coord)[1:] + coord = [coord[0]] + deltas + coord.append(1) + new_coords.append(coord) + cmd[1] = new_coords + lastOp = op + return commands + + def getCharString( + self, private=None, globalSubrs=None, var_model=None, optimize=True + ): + commands = self._commands + commands = self.reorder_blend_args( + commands, partial(var_model.getDeltas, round=self.round) + ) + if optimize: + commands = specializeCommands( + commands, generalizeFirst=False, maxstack=maxStackLimit + ) + program = commandsToProgram(commands) + charString = T2CharString( + program=program, private=private, globalSubrs=globalSubrs + ) + return charString diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/errors.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..4f30f901babed2b985ae5c333420b6a9e7a3baa8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/errors.py @@ -0,0 +1,219 @@ +import textwrap + + +class VarLibError(Exception): + """Base exception for the varLib module.""" + + +class VarLibValidationError(VarLibError): + """Raised when input data is invalid from varLib's point of view.""" + + +class VarLibMergeError(VarLibError): + """Raised when input data cannot be merged into a variable font.""" + + def __init__(self, merger=None, **kwargs): + self.merger = merger + if not kwargs: + kwargs = {} + if "stack" in kwargs: + self.stack = kwargs["stack"] + del kwargs["stack"] + else: + self.stack = [] + self.cause = kwargs + + @property + def reason(self): + return self.__doc__ + + def _master_name(self, ix): + if self.merger is not None: + ttf = self.merger.ttfs[ix] + if "name" in ttf and ttf["name"].getBestFullName(): + return ttf["name"].getBestFullName() + elif hasattr(ttf.reader, "file") and hasattr(ttf.reader.file, "name"): + return ttf.reader.file.name + return f"master number {ix}" + + @property + def offender(self): + if "expected" in self.cause and "got" in self.cause: + index = [x == self.cause["expected"] for x in self.cause["got"]].index( + False + ) + master_name = self._master_name(index) + if "location" in self.cause: + master_name = f"{master_name} ({self.cause['location']})" + return index, master_name + return None, None + + @property + def details(self): + if "expected" in self.cause and "got" in self.cause: + offender_index, offender = self.offender + got = self.cause["got"][offender_index] + return f"Expected to see {self.stack[0]}=={self.cause['expected']!r}, instead saw {got!r}\n" + return "" + + def __str__(self): + offender_index, offender = self.offender + location = "" + if offender: + location = f"\n\nThe problem is likely to be in {offender}:\n" + context = "".join(reversed(self.stack)) + basic = textwrap.fill( + f"Couldn't merge the fonts, because {self.reason}. " + f"This happened while performing the following operation: {context}", + width=78, + ) + return "\n\n" + basic + location + self.details + + +class ShouldBeConstant(VarLibMergeError): + """some values were different, but should have been the same""" + + @property + def details(self): + basic_message = super().details + + if self.stack[0] != ".FeatureCount" or self.merger is None: + return basic_message + + assert self.stack[0] == ".FeatureCount" + offender_index, _ = self.offender + bad_ttf = self.merger.ttfs[offender_index] + good_ttf = next( + ttf + for ttf in self.merger.ttfs + if self.stack[-1] in ttf + and ttf[self.stack[-1]].table.FeatureList.FeatureCount + == self.cause["expected"] + ) + + good_features = [ + x.FeatureTag + for x in good_ttf[self.stack[-1]].table.FeatureList.FeatureRecord + ] + bad_features = [ + x.FeatureTag + for x in bad_ttf[self.stack[-1]].table.FeatureList.FeatureRecord + ] + return basic_message + ( + "\nIncompatible features between masters.\n" + f"Expected: {', '.join(good_features)}.\n" + f"Got: {', '.join(bad_features)}.\n" + ) + + +class FoundANone(VarLibMergeError): + """one of the values in a list was empty when it shouldn't have been""" + + @property + def offender(self): + index = [x is None for x in self.cause["got"]].index(True) + return index, self._master_name(index) + + @property + def details(self): + cause, stack = self.cause, self.stack + return f"{stack[0]}=={cause['got']}\n" + + +class NotANone(VarLibMergeError): + """one of the values in a list was not empty when it should have been""" + + @property + def offender(self): + index = [x is not None for x in self.cause["got"]].index(True) + return index, self._master_name(index) + + @property + def details(self): + cause, stack = self.cause, self.stack + return f"{stack[0]}=={cause['got']}\n" + + +class MismatchedTypes(VarLibMergeError): + """data had inconsistent types""" + + +class LengthsDiffer(VarLibMergeError): + """a list of objects had inconsistent lengths""" + + +class KeysDiffer(VarLibMergeError): + """a list of objects had different keys""" + + +class InconsistentGlyphOrder(VarLibMergeError): + """the glyph order was inconsistent between masters""" + + +class InconsistentExtensions(VarLibMergeError): + """the masters use extension lookups in inconsistent ways""" + + +class UnsupportedFormat(VarLibMergeError): + """an OpenType subtable (%s) had a format I didn't expect""" + + def __init__(self, merger=None, **kwargs): + super().__init__(merger, **kwargs) + if not self.stack: + self.stack = [".Format"] + + @property + def reason(self): + s = self.__doc__ % self.cause["subtable"] + if "value" in self.cause: + s += f" ({self.cause['value']!r})" + return s + + +class InconsistentFormats(UnsupportedFormat): + """an OpenType subtable (%s) had inconsistent formats between masters""" + + +class VarLibCFFMergeError(VarLibError): + pass + + +class VarLibCFFDictMergeError(VarLibCFFMergeError): + """Raised when a CFF PrivateDict cannot be merged.""" + + def __init__(self, key, value, values): + error_msg = ( + f"For the Private Dict key '{key}', the default font value list:" + f"\n\t{value}\nhad a different number of values than a region font:" + ) + for region_value in values: + error_msg += f"\n\t{region_value}" + self.args = (error_msg,) + + +class VarLibCFFPointTypeMergeError(VarLibCFFMergeError): + """Raised when a CFF glyph cannot be merged because of point type differences.""" + + def __init__(self, point_type, pt_index, m_index, default_type, glyph_name): + error_msg = ( + f"Glyph '{glyph_name}': '{point_type}' at point index {pt_index} in " + f"master index {m_index} differs from the default font point type " + f"'{default_type}'" + ) + self.args = (error_msg,) + + +class VarLibCFFHintTypeMergeError(VarLibCFFMergeError): + """Raised when a CFF glyph cannot be merged because of hint type differences.""" + + def __init__(self, hint_type, cmd_index, m_index, default_type, glyph_name): + error_msg = ( + f"Glyph '{glyph_name}': '{hint_type}' at index {cmd_index} in " + f"master index {m_index} differs from the default font hint type " + f"'{default_type}'" + ) + self.args = (error_msg,) + + +class VariationModelError(VarLibError): + """Raised when a variation model is faulty.""" diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/featureVars.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/featureVars.py new file mode 100644 index 0000000000000000000000000000000000000000..40ad9dfca6c56f26aa767a454c3f5ed0b4cdb28a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/featureVars.py @@ -0,0 +1,703 @@ +"""Module to build FeatureVariation tables: +https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#featurevariations-table + +NOTE: The API is experimental and subject to change. +""" + +from fontTools.misc.dictTools import hashdict +from fontTools.misc.intTools import bit_count +from fontTools.ttLib import newTable +from fontTools.ttLib.tables import otTables as ot +from fontTools.ttLib.ttVisitor import TTVisitor +from fontTools.otlLib.builder import buildLookup, buildSingleSubstSubtable +from collections import OrderedDict + +from .errors import VarLibError, VarLibValidationError + + +def addFeatureVariations(font, conditionalSubstitutions, featureTag="rvrn"): + """Add conditional substitutions to a Variable Font. + + The `conditionalSubstitutions` argument is a list of (Region, Substitutions) + tuples. + + A Region is a list of Boxes. A Box is a dict mapping axisTags to + (minValue, maxValue) tuples. Irrelevant axes may be omitted and they are + interpretted as extending to end of axis in each direction. A Box represents + an orthogonal 'rectangular' subset of an N-dimensional design space. + A Region represents a more complex subset of an N-dimensional design space, + ie. the union of all the Boxes in the Region. + For efficiency, Boxes within a Region should ideally not overlap, but + functionality is not compromised if they do. + + The minimum and maximum values are expressed in normalized coordinates. + + A Substitution is a dict mapping source glyph names to substitute glyph names. + + Example: + + # >>> f = TTFont(srcPath) + # >>> condSubst = [ + # ... # A list of (Region, Substitution) tuples. + # ... ([{"wdth": (0.5, 1.0)}], {"cent": "cent.rvrn"}), + # ... ([{"wght": (0.5, 1.0)}], {"dollar": "dollar.rvrn"}), + # ... ] + # >>> addFeatureVariations(f, condSubst) + # >>> f.save(dstPath) + + The `featureTag` parameter takes either a str or a iterable of str (the single str + is kept for backwards compatibility), and defines which feature(s) will be + associated with the feature variations. + Note, if this is "rvrn", then the substitution lookup will be inserted at the + beginning of the lookup list so that it is processed before others, otherwise + for any other feature tags it will be appended last. + """ + + # process first when "rvrn" is the only listed tag + featureTags = [featureTag] if isinstance(featureTag, str) else sorted(featureTag) + processLast = "rvrn" not in featureTags or len(featureTags) > 1 + + _checkSubstitutionGlyphsExist( + glyphNames=set(font.getGlyphOrder()), + substitutions=conditionalSubstitutions, + ) + + substitutions = overlayFeatureVariations(conditionalSubstitutions) + + # turn substitution dicts into tuples of tuples, so they are hashable + conditionalSubstitutions, allSubstitutions = makeSubstitutionsHashable( + substitutions + ) + if "GSUB" not in font: + font["GSUB"] = buildGSUB() + else: + existingTags = _existingVariableFeatures(font["GSUB"].table).intersection( + featureTags + ) + if existingTags: + raise VarLibError( + f"FeatureVariations already exist for feature tag(s): {existingTags}" + ) + + # setup lookups + lookupMap = buildSubstitutionLookups( + font["GSUB"].table, allSubstitutions, processLast + ) + + # addFeatureVariationsRaw takes a list of + # ( {condition}, [ lookup indices ] ) + # so rearrange our lookups to match + conditionsAndLookups = [] + for conditionSet, substitutions in conditionalSubstitutions: + conditionsAndLookups.append( + (conditionSet, [lookupMap[s] for s in substitutions]) + ) + + addFeatureVariationsRaw(font, font["GSUB"].table, conditionsAndLookups, featureTags) + + # Update OS/2.usMaxContext in case the font didn't have features before, but + # does now, if the OS/2 table exists. The table may be required, but + # fontTools needs to be able to deal with non-standard fonts. Since feature + # variations are always 1:1 mappings, we can set the value to at least 1 + # instead of recomputing it with `otlLib.maxContextCalc.maxCtxFont()`. + if (os2 := font.get("OS/2")) is not None: + os2.usMaxContext = max(1, os2.usMaxContext) + + +def _existingVariableFeatures(table): + existingFeatureVarsTags = set() + if hasattr(table, "FeatureVariations") and table.FeatureVariations is not None: + features = table.FeatureList.FeatureRecord + for fvr in table.FeatureVariations.FeatureVariationRecord: + for ftsr in fvr.FeatureTableSubstitution.SubstitutionRecord: + existingFeatureVarsTags.add(features[ftsr.FeatureIndex].FeatureTag) + return existingFeatureVarsTags + + +def _checkSubstitutionGlyphsExist(glyphNames, substitutions): + referencedGlyphNames = set() + for _, substitution in substitutions: + referencedGlyphNames |= substitution.keys() + referencedGlyphNames |= set(substitution.values()) + missing = referencedGlyphNames - glyphNames + if missing: + raise VarLibValidationError( + "Missing glyphs are referenced in conditional substitution rules:" + f" {', '.join(missing)}" + ) + + +def overlayFeatureVariations(conditionalSubstitutions): + """Compute overlaps between all conditional substitutions. + + The `conditionalSubstitutions` argument is a list of (Region, Substitutions) + tuples. + + A Region is a list of Boxes. A Box is a dict mapping axisTags to + (minValue, maxValue) tuples. Irrelevant axes may be omitted and they are + interpretted as extending to end of axis in each direction. A Box represents + an orthogonal 'rectangular' subset of an N-dimensional design space. + A Region represents a more complex subset of an N-dimensional design space, + ie. the union of all the Boxes in the Region. + For efficiency, Boxes within a Region should ideally not overlap, but + functionality is not compromised if they do. + + The minimum and maximum values are expressed in normalized coordinates. + + A Substitution is a dict mapping source glyph names to substitute glyph names. + + Returns data is in similar but different format. Overlaps of distinct + substitution Boxes (*not* Regions) are explicitly listed as distinct rules, + and rules with the same Box merged. The more specific rules appear earlier + in the resulting list. Moreover, instead of just a dictionary of substitutions, + a list of dictionaries is returned for substitutions corresponding to each + unique space, with each dictionary being identical to one of the input + substitution dictionaries. These dictionaries are not merged to allow data + sharing when they are converted into font tables. + + Example:: + + >>> condSubst = [ + ... # A list of (Region, Substitution) tuples. + ... ([{"wght": (0.5, 1.0)}], {"dollar": "dollar.rvrn"}), + ... ([{"wght": (0.5, 1.0)}], {"dollar": "dollar.rvrn"}), + ... ([{"wdth": (0.5, 1.0)}], {"cent": "cent.rvrn"}), + ... ([{"wght": (0.5, 1.0), "wdth": (-1, 1.0)}], {"dollar": "dollar.rvrn"}), + ... ] + >>> from pprint import pprint + >>> pprint(overlayFeatureVariations(condSubst)) + [({'wdth': (0.5, 1.0), 'wght': (0.5, 1.0)}, + [{'dollar': 'dollar.rvrn'}, {'cent': 'cent.rvrn'}]), + ({'wdth': (0.5, 1.0)}, [{'cent': 'cent.rvrn'}]), + ({'wght': (0.5, 1.0)}, [{'dollar': 'dollar.rvrn'}])] + + """ + + # Merge same-substitutions rules, as this creates fewer number oflookups. + merged = OrderedDict() + for value, key in conditionalSubstitutions: + key = hashdict(key) + if key in merged: + merged[key].extend(value) + else: + merged[key] = value + conditionalSubstitutions = [(v, dict(k)) for k, v in merged.items()] + del merged + + # Merge same-region rules, as this is cheaper. + # Also convert boxes to hashdict() + # + # Reversing is such that earlier entries win in case of conflicting substitution + # rules for the same region. + merged = OrderedDict() + for key, value in reversed(conditionalSubstitutions): + key = tuple( + sorted( + (hashdict(cleanupBox(k)) for k in key), + key=lambda d: tuple(sorted(d.items())), + ) + ) + if key in merged: + merged[key].update(value) + else: + merged[key] = dict(value) + conditionalSubstitutions = list(reversed(merged.items())) + del merged + + # Overlay + # + # Rank is the bit-set of the index of all contributing layers. + initMapInit = ((hashdict(), 0),) # Initializer representing the entire space + boxMap = OrderedDict(initMapInit) # Map from Box to Rank + for i, (currRegion, _) in enumerate(conditionalSubstitutions): + newMap = OrderedDict(initMapInit) + currRank = 1 << i + for box, rank in boxMap.items(): + for currBox in currRegion: + intersection, remainder = overlayBox(currBox, box) + if intersection is not None: + intersection = hashdict(intersection) + newMap[intersection] = newMap.get(intersection, 0) | rank | currRank + if remainder is not None: + remainder = hashdict(remainder) + newMap[remainder] = newMap.get(remainder, 0) | rank + boxMap = newMap + + # Generate output + items = [] + for box, rank in sorted( + boxMap.items(), key=(lambda BoxAndRank: -bit_count(BoxAndRank[1])) + ): + # Skip any box that doesn't have any substitution. + if rank == 0: + continue + substsList = [] + i = 0 + while rank: + if rank & 1: + substsList.append(conditionalSubstitutions[i][1]) + rank >>= 1 + i += 1 + items.append((dict(box), substsList)) + return items + + +# +# Terminology: +# +# A 'Box' is a dict representing an orthogonal "rectangular" bit of N-dimensional space. +# The keys in the dict are axis tags, the values are (minValue, maxValue) tuples. +# Missing dimensions (keys) are substituted by the default min and max values +# from the corresponding axes. +# + + +def overlayBox(top, bot): + """Overlays ``top`` box on top of ``bot`` box. + + Returns two items: + + * Box for intersection of ``top`` and ``bot``, or None if they don't intersect. + * Box for remainder of ``bot``. Remainder box might not be exact (since the + remainder might not be a simple box), but is inclusive of the exact + remainder. + """ + + # Intersection + intersection = {} + intersection.update(top) + intersection.update(bot) + for axisTag in set(top) & set(bot): + min1, max1 = top[axisTag] + min2, max2 = bot[axisTag] + minimum = max(min1, min2) + maximum = min(max1, max2) + if not minimum < maximum: + return None, bot # Do not intersect + intersection[axisTag] = minimum, maximum + + # Remainder + # + # Remainder is empty if bot's each axis range lies within that of intersection. + # + # Remainder is shrank if bot's each, except for exactly one, axis range lies + # within that of intersection, and that one axis, it extrudes out of the + # intersection only on one side. + # + # Bot is returned in full as remainder otherwise, as true remainder is not + # representable as a single box. + + remainder = dict(bot) + extruding = False + fullyInside = True + for axisTag in top: + if axisTag in bot: + continue + extruding = True + fullyInside = False + break + for axisTag in bot: + if axisTag not in top: + continue # Axis range lies fully within + min1, max1 = intersection[axisTag] + min2, max2 = bot[axisTag] + if min1 <= min2 and max2 <= max1: + continue # Axis range lies fully within + + # Bot's range doesn't fully lie within that of top's for this axis. + # We know they intersect, so it cannot lie fully without either; so they + # overlap. + + # If we have had an overlapping axis before, remainder is not + # representable as a box, so return full bottom and go home. + if extruding: + return intersection, bot + extruding = True + fullyInside = False + + # Otherwise, cut remainder on this axis and continue. + if min1 <= min2: + # Right side survives. + minimum = max(max1, min2) + maximum = max2 + elif max2 <= max1: + # Left side survives. + minimum = min2 + maximum = min(min1, max2) + else: + # Remainder leaks out from both sides. Can't cut either. + return intersection, bot + + remainder[axisTag] = minimum, maximum + + if fullyInside: + # bot is fully within intersection. Remainder is empty. + return intersection, None + + return intersection, remainder + + +def cleanupBox(box): + """Return a sparse copy of `box`, without redundant (default) values. + + >>> cleanupBox({}) + {} + >>> cleanupBox({'wdth': (0.0, 1.0)}) + {'wdth': (0.0, 1.0)} + >>> cleanupBox({'wdth': (-1.0, 1.0)}) + {} + + """ + return {tag: limit for tag, limit in box.items() if limit != (-1.0, 1.0)} + + +# +# Low level implementation +# + + +def addFeatureVariationsRaw(font, table, conditionalSubstitutions, featureTag="rvrn"): + """Low level implementation of addFeatureVariations that directly + models the possibilities of the FeatureVariations table.""" + + featureTags = [featureTag] if isinstance(featureTag, str) else sorted(featureTag) + processLast = "rvrn" not in featureTags or len(featureTags) > 1 + + # + # if a <featureTag> feature is not present: + # make empty <featureTag> feature + # sort features, get <featureTag> feature index + # add <featureTag> feature to all scripts + # if a <featureTag> feature is present: + # reuse <featureTag> feature index + # make lookups + # add feature variations + # + if table.Version < 0x00010001: + table.Version = 0x00010001 # allow table.FeatureVariations + + varFeatureIndices = set() + + existingTags = { + feature.FeatureTag + for feature in table.FeatureList.FeatureRecord + if feature.FeatureTag in featureTags + } + + newTags = set(featureTags) - existingTags + if newTags: + varFeatures = [] + for featureTag in sorted(newTags): + varFeature = buildFeatureRecord(featureTag, []) + table.FeatureList.FeatureRecord.append(varFeature) + varFeatures.append(varFeature) + table.FeatureList.FeatureCount = len(table.FeatureList.FeatureRecord) + + sortFeatureList(table) + + for varFeature in varFeatures: + varFeatureIndex = table.FeatureList.FeatureRecord.index(varFeature) + + for scriptRecord in table.ScriptList.ScriptRecord: + if scriptRecord.Script.DefaultLangSys is None: + # We need to have a default LangSys to attach variations to. + langSys = ot.LangSys() + langSys.LookupOrder = None + langSys.ReqFeatureIndex = 0xFFFF + langSys.FeatureIndex = [] + langSys.FeatureCount = 0 + scriptRecord.Script.DefaultLangSys = langSys + langSystems = [lsr.LangSys for lsr in scriptRecord.Script.LangSysRecord] + for langSys in [scriptRecord.Script.DefaultLangSys] + langSystems: + langSys.FeatureIndex.append(varFeatureIndex) + langSys.FeatureCount = len(langSys.FeatureIndex) + varFeatureIndices.add(varFeatureIndex) + + if existingTags: + # indices may have changed if we inserted new features and sorted feature list + # so we must do this after the above + varFeatureIndices.update( + index + for index, feature in enumerate(table.FeatureList.FeatureRecord) + if feature.FeatureTag in existingTags + ) + + axisIndices = { + axis.axisTag: axisIndex for axisIndex, axis in enumerate(font["fvar"].axes) + } + + hasFeatureVariations = ( + hasattr(table, "FeatureVariations") and table.FeatureVariations is not None + ) + + featureVariationRecords = [] + for conditionSet, lookupIndices in conditionalSubstitutions: + conditionTable = [] + for axisTag, (minValue, maxValue) in sorted(conditionSet.items()): + if minValue > maxValue: + raise VarLibValidationError( + "A condition set has a minimum value above the maximum value." + ) + ct = buildConditionTable(axisIndices[axisTag], minValue, maxValue) + conditionTable.append(ct) + records = [] + for varFeatureIndex in sorted(varFeatureIndices): + existingLookupIndices = table.FeatureList.FeatureRecord[ + varFeatureIndex + ].Feature.LookupListIndex + combinedLookupIndices = ( + existingLookupIndices + lookupIndices + if processLast + else lookupIndices + existingLookupIndices + ) + + records.append( + buildFeatureTableSubstitutionRecord( + varFeatureIndex, combinedLookupIndices + ) + ) + if hasFeatureVariations and ( + fvr := findFeatureVariationRecord(table.FeatureVariations, conditionTable) + ): + fvr.FeatureTableSubstitution.SubstitutionRecord.extend(records) + fvr.FeatureTableSubstitution.SubstitutionCount = len( + fvr.FeatureTableSubstitution.SubstitutionRecord + ) + else: + featureVariationRecords.append( + buildFeatureVariationRecord(conditionTable, records) + ) + + if hasFeatureVariations: + if table.FeatureVariations.Version != 0x00010000: + raise VarLibError( + "Unsupported FeatureVariations table version: " + f"0x{table.FeatureVariations.Version:08x} (expected 0x00010000)." + ) + table.FeatureVariations.FeatureVariationRecord.extend(featureVariationRecords) + table.FeatureVariations.FeatureVariationCount = len( + table.FeatureVariations.FeatureVariationRecord + ) + else: + table.FeatureVariations = buildFeatureVariations(featureVariationRecords) + + +# +# Building GSUB/FeatureVariations internals +# + + +def buildGSUB(): + """Build a GSUB table from scratch.""" + fontTable = newTable("GSUB") + gsub = fontTable.table = ot.GSUB() + gsub.Version = 0x00010001 # allow gsub.FeatureVariations + + gsub.ScriptList = ot.ScriptList() + gsub.ScriptList.ScriptRecord = [] + gsub.FeatureList = ot.FeatureList() + gsub.FeatureList.FeatureRecord = [] + gsub.LookupList = ot.LookupList() + gsub.LookupList.Lookup = [] + + srec = ot.ScriptRecord() + srec.ScriptTag = "DFLT" + srec.Script = ot.Script() + srec.Script.DefaultLangSys = None + srec.Script.LangSysRecord = [] + srec.Script.LangSysCount = 0 + + langrec = ot.LangSysRecord() + langrec.LangSys = ot.LangSys() + langrec.LangSys.ReqFeatureIndex = 0xFFFF + langrec.LangSys.FeatureIndex = [] + srec.Script.DefaultLangSys = langrec.LangSys + + gsub.ScriptList.ScriptRecord.append(srec) + gsub.ScriptList.ScriptCount = 1 + gsub.FeatureVariations = None + + return fontTable + + +def makeSubstitutionsHashable(conditionalSubstitutions): + """Turn all the substitution dictionaries in sorted tuples of tuples so + they are hashable, to detect duplicates so we don't write out redundant + data.""" + allSubstitutions = set() + condSubst = [] + for conditionSet, substitutionMaps in conditionalSubstitutions: + substitutions = [] + for substitutionMap in substitutionMaps: + subst = tuple(sorted(substitutionMap.items())) + substitutions.append(subst) + allSubstitutions.add(subst) + condSubst.append((conditionSet, substitutions)) + return condSubst, sorted(allSubstitutions) + + +class ShifterVisitor(TTVisitor): + def __init__(self, shift): + self.shift = shift + + +@ShifterVisitor.register_attr(ot.Feature, "LookupListIndex") # GSUB/GPOS +def visit(visitor, obj, attr, value): + shift = visitor.shift + value = [l + shift for l in value] + setattr(obj, attr, value) + + +@ShifterVisitor.register_attr( + (ot.SubstLookupRecord, ot.PosLookupRecord), "LookupListIndex" +) +def visit(visitor, obj, attr, value): + setattr(obj, attr, visitor.shift + value) + + +def buildSubstitutionLookups(gsub, allSubstitutions, processLast=False): + """Build the lookups for the glyph substitutions, return a dict mapping + the substitution to lookup indices.""" + + # Insert lookups at the beginning of the lookup vector + # https://github.com/googlefonts/fontmake/issues/950 + + firstIndex = len(gsub.LookupList.Lookup) if processLast else 0 + lookupMap = {} + for i, substitutionMap in enumerate(allSubstitutions): + lookupMap[substitutionMap] = firstIndex + i + + if not processLast: + # Shift all lookup indices in gsub by len(allSubstitutions) + shift = len(allSubstitutions) + visitor = ShifterVisitor(shift) + visitor.visit(gsub.FeatureList.FeatureRecord) + visitor.visit(gsub.LookupList.Lookup) + + for i, subst in enumerate(allSubstitutions): + substMap = dict(subst) + lookup = buildLookup([buildSingleSubstSubtable(substMap)]) + if processLast: + gsub.LookupList.Lookup.append(lookup) + else: + gsub.LookupList.Lookup.insert(i, lookup) + assert gsub.LookupList.Lookup[lookupMap[subst]] is lookup + gsub.LookupList.LookupCount = len(gsub.LookupList.Lookup) + return lookupMap + + +def buildFeatureVariations(featureVariationRecords): + """Build the FeatureVariations subtable.""" + fv = ot.FeatureVariations() + fv.Version = 0x00010000 + fv.FeatureVariationRecord = featureVariationRecords + fv.FeatureVariationCount = len(featureVariationRecords) + return fv + + +def buildFeatureRecord(featureTag, lookupListIndices): + """Build a FeatureRecord.""" + fr = ot.FeatureRecord() + fr.FeatureTag = featureTag + fr.Feature = ot.Feature() + fr.Feature.LookupListIndex = lookupListIndices + fr.Feature.populateDefaults() + return fr + + +def buildFeatureVariationRecord(conditionTable, substitutionRecords): + """Build a FeatureVariationRecord.""" + fvr = ot.FeatureVariationRecord() + if len(conditionTable) != 0: + fvr.ConditionSet = ot.ConditionSet() + fvr.ConditionSet.ConditionTable = conditionTable + fvr.ConditionSet.ConditionCount = len(conditionTable) + else: + fvr.ConditionSet = None + fvr.FeatureTableSubstitution = ot.FeatureTableSubstitution() + fvr.FeatureTableSubstitution.Version = 0x00010000 + fvr.FeatureTableSubstitution.SubstitutionRecord = substitutionRecords + fvr.FeatureTableSubstitution.SubstitutionCount = len(substitutionRecords) + return fvr + + +def buildFeatureTableSubstitutionRecord(featureIndex, lookupListIndices): + """Build a FeatureTableSubstitutionRecord.""" + ftsr = ot.FeatureTableSubstitutionRecord() + ftsr.FeatureIndex = featureIndex + ftsr.Feature = ot.Feature() + ftsr.Feature.LookupListIndex = lookupListIndices + ftsr.Feature.LookupCount = len(lookupListIndices) + return ftsr + + +def buildConditionTable(axisIndex, filterRangeMinValue, filterRangeMaxValue): + """Build a ConditionTable.""" + ct = ot.ConditionTable() + ct.Format = 1 + ct.AxisIndex = axisIndex + ct.FilterRangeMinValue = filterRangeMinValue + ct.FilterRangeMaxValue = filterRangeMaxValue + return ct + + +def findFeatureVariationRecord(featureVariations, conditionTable): + """Find a FeatureVariationRecord that has the same conditionTable.""" + if featureVariations.Version != 0x00010000: + raise VarLibError( + "Unsupported FeatureVariations table version: " + f"0x{featureVariations.Version:08x} (expected 0x00010000)." + ) + + for fvr in featureVariations.FeatureVariationRecord: + if conditionTable == fvr.ConditionSet.ConditionTable: + return fvr + + return None + + +def sortFeatureList(table): + """Sort the feature list by feature tag, and remap the feature indices + elsewhere. This is needed after the feature list has been modified. + """ + # decorate, sort, undecorate, because we need to make an index remapping table + tagIndexFea = [ + (fea.FeatureTag, index, fea) + for index, fea in enumerate(table.FeatureList.FeatureRecord) + ] + tagIndexFea.sort() + table.FeatureList.FeatureRecord = [fea for tag, index, fea in tagIndexFea] + featureRemap = dict( + zip([index for tag, index, fea in tagIndexFea], range(len(tagIndexFea))) + ) + + # Remap the feature indices + remapFeatures(table, featureRemap) + + +def remapFeatures(table, featureRemap): + """Go through the scripts list, and remap feature indices.""" + for scriptIndex, script in enumerate(table.ScriptList.ScriptRecord): + defaultLangSys = script.Script.DefaultLangSys + if defaultLangSys is not None: + _remapLangSys(defaultLangSys, featureRemap) + for langSysRecordIndex, langSysRec in enumerate(script.Script.LangSysRecord): + langSys = langSysRec.LangSys + _remapLangSys(langSys, featureRemap) + + if hasattr(table, "FeatureVariations") and table.FeatureVariations is not None: + for fvr in table.FeatureVariations.FeatureVariationRecord: + for ftsr in fvr.FeatureTableSubstitution.SubstitutionRecord: + ftsr.FeatureIndex = featureRemap[ftsr.FeatureIndex] + + +def _remapLangSys(langSys, featureRemap): + if langSys.ReqFeatureIndex != 0xFFFF: + langSys.ReqFeatureIndex = featureRemap[langSys.ReqFeatureIndex] + langSys.FeatureIndex = [featureRemap[index] for index in langSys.FeatureIndex] + + +if __name__ == "__main__": + import doctest, sys + + sys.exit(doctest.testmod().failed) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/hvar.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/hvar.py new file mode 100644 index 0000000000000000000000000000000000000000..14b662ebf72f11a7981da23c65144080896e642b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/hvar.py @@ -0,0 +1,113 @@ +from fontTools.misc.roundTools import noRound +from fontTools.ttLib import TTFont, newTable +from fontTools.ttLib.tables import otTables as ot +from fontTools.ttLib.tables.otBase import OTTableWriter +from fontTools.varLib import HVAR_FIELDS, VVAR_FIELDS, _add_VHVAR +from fontTools.varLib import builder, models, varStore +from fontTools.misc.fixedTools import fixedToFloat as fi2fl +from fontTools.misc.cliTools import makeOutputFileName +from functools import partial +import logging + +log = logging.getLogger("fontTools.varLib.avar") + + +def _get_advance_metrics(font, axisTags, tableFields): + # There's two ways we can go from here: + # 1. For each glyph, at each master peak, compute the value of the + # advance width at that peak. Then pass these all to a VariationModel + # builder to compute back the deltas. + # 2. For each master peak, pull out the deltas of the advance width directly, + # and feed these to the VarStoreBuilder, forgoing the remodeling step. + # We'll go with the second option, as it's simpler, faster, and more direct. + gvar = font["gvar"] + vhAdvanceDeltasAndSupports = {} + glyphOrder = font.getGlyphOrder() + phantomIndex = tableFields.phantomIndex + for glyphName in glyphOrder: + supports = [] + deltas = [] + variations = gvar.variations.get(glyphName, []) + + for tv in variations: + supports.append(tv.axes) + phantoms = tv.coordinates[-4:] + phantoms = phantoms[phantomIndex * 2 : phantomIndex * 2 + 2] + assert len(phantoms) == 2 + phantoms[0] = phantoms[0][phantomIndex] if phantoms[0] is not None else 0 + phantoms[1] = phantoms[1][phantomIndex] if phantoms[1] is not None else 0 + deltas.append(phantoms[1] - phantoms[0]) + + vhAdvanceDeltasAndSupports[glyphName] = (deltas, supports) + + vOrigDeltasAndSupports = None # TODO + + return vhAdvanceDeltasAndSupports, vOrigDeltasAndSupports + + +def add_HVAR(font): + if "HVAR" in font: + del font["HVAR"] + axisTags = [axis.axisTag for axis in font["fvar"].axes] + getAdvanceMetrics = partial(_get_advance_metrics, font, axisTags, HVAR_FIELDS) + _add_VHVAR(font, axisTags, HVAR_FIELDS, getAdvanceMetrics) + + +def add_VVAR(font): + if "VVAR" in font: + del font["VVAR"] + getAdvanceMetrics = partial(_get_advance_metrics, font, axisTags, VVAR_FIELDS) + axisTags = [axis.axisTag for axis in font["fvar"].axes] + _add_VHVAR(font, axisTags, VVAR_FIELDS, getAdvanceMetrics) + + +def main(args=None): + """Add `HVAR` table to variable font.""" + + if args is None: + import sys + + args = sys.argv[1:] + + from fontTools import configLogger + from fontTools.designspaceLib import DesignSpaceDocument + import argparse + + parser = argparse.ArgumentParser( + "fonttools varLib.hvar", + description="Add `HVAR` table from to variable font.", + ) + parser.add_argument("font", metavar="varfont.ttf", help="Variable-font file.") + parser.add_argument( + "-o", + "--output-file", + type=str, + help="Output font file name.", + ) + + options = parser.parse_args(args) + + configLogger(level="WARNING") + + font = TTFont(options.font) + if not "fvar" in font: + log.error("Not a variable font.") + return 1 + + add_HVAR(font) + if "vmtx" in font: + add_VVAR(font) + + if options.output_file is None: + outfile = makeOutputFileName(options.font, overWrite=True, suffix=".hvar") + else: + outfile = options.output_file + if outfile: + log.info("Saving %s", outfile) + font.save(outfile) + + +if __name__ == "__main__": + import sys + + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__init__.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de344957362cde7710fa9419efe0d7ab643fde24 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__init__.py @@ -0,0 +1,3001 @@ +"""Partially instantiate a variable font. + +The module exports an `instantiateVariableFont` function and CLI that allow to +create full instances (i.e. static fonts) from variable fonts, as well as "partial" +variable fonts that only contain a subset of the original variation space. + +For example, if you wish to pin the width axis to a given location while also +restricting the weight axis to 400..700 range, you can do: + +.. code-block:: sh + + $ fonttools varLib.instancer ./NotoSans-VF.ttf wdth=85 wght=400:700 + +See `fonttools varLib.instancer --help` for more info on the CLI options. + +The module's entry point is the `instantiateVariableFont` function, which takes +a TTFont object and a dict specifying either axis coodinates or (min, max) ranges, +and returns a new TTFont representing either a partial VF, or full instance if all +the VF axes were given an explicit coordinate. + +E.g. here's how to pin the wght axis at a given location in a wght+wdth variable +font, keeping only the deltas associated with the wdth axis: +.. code-block:: pycon + + >>> + >> from fontTools import ttLib + >> from fontTools.varLib import instancer + >> varfont = ttLib.TTFont("path/to/MyVariableFont.ttf") + >> [a.axisTag for a in varfont["fvar"].axes] # the varfont's current axes + ['wght', 'wdth'] + >> partial = instancer.instantiateVariableFont(varfont, {"wght": 300}) + >> [a.axisTag for a in partial["fvar"].axes] # axes left after pinning 'wght' + ['wdth'] + +If the input location specifies all the axes, the resulting instance is no longer +'variable' (same as using fontools varLib.mutator): +.. code-block:: pycon + + >>> + >> instance = instancer.instantiateVariableFont( + ... varfont, {"wght": 700, "wdth": 67.5} + ... ) + >> "fvar" not in instance + True + +If one just want to drop an axis at the default location, without knowing in +advance what the default value for that axis is, one can pass a `None` value: +.. code-block:: pycon + + >>> + >> instance = instancer.instantiateVariableFont(varfont, {"wght": None}) + >> len(varfont["fvar"].axes) + 1 + +From the console script, this is equivalent to passing `wght=drop` as input. + +This module is similar to fontTools.varLib.mutator, which it's intended to supersede. +Note that, unlike varLib.mutator, when an axis is not mentioned in the input +location, by default the varLib.instancer will keep the axis and the corresponding +deltas, whereas mutator implicitly drops the axis at its default coordinate. +To obtain the same behavior as mutator, pass the `static=True` parameter or +the `--static` CLI option. + +The module supports all the following "levels" of instancing, which can of +course be combined: + +L1 + dropping one or more axes while leaving the default tables unmodified; + .. code-block:: pycon + + >>> + >> font = instancer.instantiateVariableFont(varfont, {"wght": None}) + +L2 + dropping one or more axes while pinning them at non-default locations; + .. code-block:: pycon + + >>> + >> font = instancer.instantiateVariableFont(varfont, {"wght": 700}) + +L3 + restricting the range of variation of one or more axes, by setting either + a new minimum or maximum, potentially -- though not necessarily -- dropping + entire regions of variations that fall completely outside this new range. + .. code-block:: pycon + + >>> + >> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300)}) + +L4 + moving the default location of an axis, by specifying (min,defalt,max) values: + .. code-block:: pycon + + >>> + >> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300, 700)}) + +Both TrueType-flavored (glyf+gvar) variable and CFF2 variable fonts are supported. +""" + +from fontTools.misc.fixedTools import ( + floatToFixedToFloat, + strToFixedToFloat, + otRound, +) +from fontTools.varLib.models import normalizeValue, piecewiseLinearMap, VariationModel +from fontTools.ttLib import TTFont, newTable +from fontTools.ttLib.tables.TupleVariation import TupleVariation +from fontTools.ttLib.tables import _g_l_y_f +from fontTools import varLib + +# we import the `subset` module because we use the `prune_lookups` method on the GSUB +# table class, and that method is only defined dynamically upon importing `subset` +from fontTools import subset # noqa: F401 +from fontTools.cffLib import privateDictOperators2 +from fontTools.cffLib.specializer import ( + programToCommands, + commandsToProgram, + specializeCommands, + generalizeCommands, +) +from fontTools.cffLib.CFF2ToCFF import convertCFF2ToCFF +from fontTools.varLib import builder +from fontTools.varLib.mvar import MVAR_ENTRIES +from fontTools.varLib.merger import MutatorMerger +from fontTools.varLib.instancer import names +from fontTools.varLib.varStore import NO_VARIATION_INDEX +from .featureVars import instantiateFeatureVariations +from fontTools.misc.cliTools import makeOutputFileName +from fontTools.varLib.instancer import solver +from fontTools.ttLib.tables.otTables import VarComponentFlags +import collections +import dataclasses +from contextlib import contextmanager +from copy import deepcopy +from enum import IntEnum +import logging +import os +import re +import io +from typing import Dict, Iterable, Mapping, Optional, Sequence, Tuple, Union +import warnings + +log = logging.getLogger("fontTools.varLib.instancer") + + +def AxisRange(minimum, maximum): + warnings.warn( + "AxisRange is deprecated; use AxisTriple instead", + DeprecationWarning, + stacklevel=2, + ) + return AxisTriple(minimum, None, maximum) + + +def NormalizedAxisRange(minimum, maximum): + warnings.warn( + "NormalizedAxisRange is deprecated; use AxisTriple instead", + DeprecationWarning, + stacklevel=2, + ) + return NormalizedAxisTriple(minimum, None, maximum) + + +@dataclasses.dataclass(frozen=True, order=True, repr=False) +class AxisTriple(Sequence): + """A triple of (min, default, max) axis values. + + Any of the values can be None, in which case the limitRangeAndPopulateDefaults() + method can be used to fill in the missing values based on the fvar axis values. + """ + + minimum: Optional[float] + default: Optional[float] + maximum: Optional[float] + + def __post_init__(self): + if self.default is None and self.minimum == self.maximum: + object.__setattr__(self, "default", self.minimum) + if ( + ( + self.minimum is not None + and self.default is not None + and self.minimum > self.default + ) + or ( + self.default is not None + and self.maximum is not None + and self.default > self.maximum + ) + or ( + self.minimum is not None + and self.maximum is not None + and self.minimum > self.maximum + ) + ): + raise ValueError( + f"{type(self).__name__} minimum ({self.minimum}), default ({self.default}), maximum ({self.maximum}) must be in sorted order" + ) + + def __getitem__(self, i): + fields = dataclasses.fields(self) + return getattr(self, fields[i].name) + + def __len__(self): + return len(dataclasses.fields(self)) + + def _replace(self, **kwargs): + return dataclasses.replace(self, **kwargs) + + def __repr__(self): + return ( + f"({', '.join(format(v, 'g') if v is not None else 'None' for v in self)})" + ) + + @classmethod + def expand( + cls, + v: Union[ + "AxisTriple", + float, # pin axis at single value, same as min==default==max + Tuple[float, float], # (min, max), restrict axis and keep default + Tuple[float, float, float], # (min, default, max) + ], + ) -> "AxisTriple": + """Convert a single value or a tuple into an AxisTriple. + + If the input is a single value, it is interpreted as a pin at that value. + If the input is a tuple, it is interpreted as (min, max) or (min, default, max). + """ + if isinstance(v, cls): + return v + if isinstance(v, (int, float)): + return cls(v, v, v) + try: + n = len(v) + except TypeError as e: + raise ValueError( + f"expected float, 2- or 3-tuple of floats; got {type(v)}: {v!r}" + ) from e + default = None + if n == 2: + minimum, maximum = v + elif n >= 3: + return cls(*v) + else: + raise ValueError(f"expected sequence of 2 or 3; got {n}: {v!r}") + return cls(minimum, default, maximum) + + def limitRangeAndPopulateDefaults(self, fvarTriple) -> "AxisTriple": + """Return a new AxisTriple with the default value filled in. + + Set default to fvar axis default if the latter is within the min/max range, + otherwise set default to the min or max value, whichever is closer to the + fvar axis default. + If the default value is already set, return self. + """ + minimum = self.minimum + if minimum is None: + minimum = fvarTriple[0] + default = self.default + if default is None: + default = fvarTriple[1] + maximum = self.maximum + if maximum is None: + maximum = fvarTriple[2] + + minimum = max(minimum, fvarTriple[0]) + maximum = max(maximum, fvarTriple[0]) + minimum = min(minimum, fvarTriple[2]) + maximum = min(maximum, fvarTriple[2]) + default = max(minimum, min(maximum, default)) + + return AxisTriple(minimum, default, maximum) + + +@dataclasses.dataclass(frozen=True, order=True, repr=False) +class NormalizedAxisTriple(AxisTriple): + """A triple of (min, default, max) normalized axis values.""" + + minimum: float + default: float + maximum: float + + def __post_init__(self): + if self.default is None: + object.__setattr__(self, "default", max(self.minimum, min(self.maximum, 0))) + if not (-1.0 <= self.minimum <= self.default <= self.maximum <= 1.0): + raise ValueError( + "Normalized axis values not in -1..+1 range; got " + f"minimum={self.minimum:g}, default={self.default:g}, maximum={self.maximum:g})" + ) + + +@dataclasses.dataclass(frozen=True, order=True, repr=False) +class NormalizedAxisTripleAndDistances(AxisTriple): + """A triple of (min, default, max) normalized axis values, + with distances between min and default, and default and max, + in the *pre-normalized* space.""" + + minimum: float + default: float + maximum: float + distanceNegative: Optional[float] = 1 + distancePositive: Optional[float] = 1 + + def __post_init__(self): + if self.default is None: + object.__setattr__(self, "default", max(self.minimum, min(self.maximum, 0))) + if not (-1.0 <= self.minimum <= self.default <= self.maximum <= 1.0): + raise ValueError( + "Normalized axis values not in -1..+1 range; got " + f"minimum={self.minimum:g}, default={self.default:g}, maximum={self.maximum:g})" + ) + + def reverse_negate(self): + v = self + return self.__class__(-v[2], -v[1], -v[0], v[4], v[3]) + + def renormalizeValue(self, v, extrapolate=True): + """Renormalizes a normalized value v to the range of this axis, + considering the pre-normalized distances as well as the new + axis limits.""" + + lower, default, upper, distanceNegative, distancePositive = self + assert lower <= default <= upper + + if not extrapolate: + v = max(lower, min(upper, v)) + + if v == default: + return 0 + + if default < 0: + return -self.reverse_negate().renormalizeValue(-v, extrapolate=extrapolate) + + # default >= 0 and v != default + + if v > default: + return (v - default) / (upper - default) + + # v < default + + if lower >= 0: + return (v - default) / (default - lower) + + # lower < 0 and v < default + + totalDistance = distanceNegative * -lower + distancePositive * default + + if v >= 0: + vDistance = (default - v) * distancePositive + else: + vDistance = -v * distanceNegative + distancePositive * default + + return -vDistance / totalDistance + + +class _BaseAxisLimits(Mapping[str, AxisTriple]): + def __getitem__(self, key: str) -> AxisTriple: + return self._data[key] + + def __iter__(self) -> Iterable[str]: + return iter(self._data) + + def __len__(self) -> int: + return len(self._data) + + def __repr__(self) -> str: + return f"{type(self).__name__}({self._data!r})" + + def __str__(self) -> str: + return str(self._data) + + def defaultLocation(self) -> Dict[str, float]: + """Return a dict of default axis values.""" + return {k: v.default for k, v in self.items()} + + def pinnedLocation(self) -> Dict[str, float]: + """Return a location dict with only the pinned axes.""" + return {k: v.default for k, v in self.items() if v.minimum == v.maximum} + + +class AxisLimits(_BaseAxisLimits): + """Maps axis tags (str) to AxisTriple values.""" + + def __init__(self, *args, **kwargs): + self._data = data = {} + for k, v in dict(*args, **kwargs).items(): + if v is None: + # will be filled in by limitAxesAndPopulateDefaults + data[k] = v + else: + try: + triple = AxisTriple.expand(v) + except ValueError as e: + raise ValueError(f"Invalid axis limits for {k!r}: {v!r}") from e + data[k] = triple + + def limitAxesAndPopulateDefaults(self, varfont) -> "AxisLimits": + """Return a new AxisLimits with defaults filled in from fvar table. + + If all axis limits already have defaults, return self. + """ + fvar = varfont["fvar"] + fvarTriples = { + a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in fvar.axes + } + newLimits = {} + for axisTag, triple in self.items(): + fvarTriple = fvarTriples[axisTag] + default = fvarTriple[1] + if triple is None: + newLimits[axisTag] = AxisTriple(default, default, default) + else: + newLimits[axisTag] = triple.limitRangeAndPopulateDefaults(fvarTriple) + return type(self)(newLimits) + + def normalize(self, varfont, usingAvar=True) -> "NormalizedAxisLimits": + """Return a new NormalizedAxisLimits with normalized -1..0..+1 values. + + If usingAvar is True, the avar table is used to warp the default normalization. + """ + fvar = varfont["fvar"] + badLimits = set(self.keys()).difference(a.axisTag for a in fvar.axes) + if badLimits: + raise ValueError("Cannot limit: {} not present in fvar".format(badLimits)) + + axes = { + a.axisTag: (a.minValue, a.defaultValue, a.maxValue) + for a in fvar.axes + if a.axisTag in self + } + + if usingAvar and "avar" in varfont: + avar = varfont["avar"] + + if getattr(avar, "majorVersion", 1) >= 2 and set( + self.pinnedLocation() + ).issuperset(a.axisTag for a in fvar.axes): + # Full instancing of avar2 font (all axes pinned). + # Use avar table to normalize location and return. + location = self.pinnedLocation() + location = { + tag: normalize(value, axes[tag], None) + for tag, value in location.items() + } + return NormalizedAxisLimits( + **avar.renormalizeLocation(location, varfont, dropZeroes=False) + ) + # else: partial instancing of an avar2 font falls through to the + # standard v1 normalization below, which yields intermediate-space + # limits (post-avar v1, pre-avar v2); the avar v2 offset + # compensation in the instancer handles the rest. + + # Note: normalized values are intentionally NOT quantized here; the + # F2Dot14 quantization happens once, after the avar v1 mapping (in + # renormalizeAxisLimits), so pre-map rounding doesn't compound drift. + normalizedLimits = {} + + for axis_tag, fvarTriple in axes.items(): + minUser, defaultUser, maxUser = fvarTriple + distanceNegative = defaultUser - minUser + distancePositive = maxUser - defaultUser + + if self[axis_tag] is None: # Drop + normalizedLimits[axis_tag] = NormalizedAxisTripleAndDistances( + 0, 0, 0, distanceNegative, distancePositive + ) + continue + + minV, defaultV, maxV = self[axis_tag] + + if defaultV is None: + defaultV = fvarTriple[1] + + normalizedLimits[axis_tag] = NormalizedAxisTripleAndDistances( + *(normalizeValue(v, fvarTriple) for v in (minV, defaultV, maxV)), + distanceNegative, + distancePositive, + ) + + if usingAvar and "avar" in varfont: + normalizedLimits = varfont["avar"].renormalizeAxisLimits( + normalizedLimits, varfont + ) + else: + # Quantize to F2Dot14, to avoid surprise interpolations. + normalizedLimits = { + tag: tuple(floatToFixedToFloat(v, 14) for v in tuple(triple)[:3]) + + tuple(triple)[3:] + for tag, triple in normalizedLimits.items() + } + + return NormalizedAxisLimits(normalizedLimits) + + +class NormalizedAxisLimits(_BaseAxisLimits): + """Maps axis tags (str) to NormalizedAxisTriple values.""" + + def __init__(self, *args, **kwargs): + self._data = data = {} + for k, v in dict(*args, **kwargs).items(): + try: + triple = NormalizedAxisTripleAndDistances.expand(v) + except ValueError as e: + raise ValueError(f"Invalid axis limits for {k!r}: {v!r}") from e + data[k] = triple + + +class OverlapMode(IntEnum): + KEEP_AND_DONT_SET_FLAGS = 0 + KEEP_AND_SET_FLAGS = 1 + REMOVE = 2 + REMOVE_AND_IGNORE_ERRORS = 3 + + +def instantiateVARC(varfont, axisLimits): + log.info("Instantiating VARC tables") + + # TODO(behdad) My confidence in this function is rather low; + # It needs more testing. Specially with partial-instancing, + # I don't think it currently works. + + varc = varfont["VARC"].table + fvarAxes = varfont["fvar"].axes if "fvar" in varfont else [] + + location = axisLimits.pinnedLocation() + axisMap = [i for i, axis in enumerate(fvarAxes) if axis.axisTag not in location] + reverseAxisMap = {i: j for j, i in enumerate(axisMap)} + + if varc.AxisIndicesList: + axisIndicesList = varc.AxisIndicesList.Item + for i, axisIndices in enumerate(axisIndicesList): + if any(fvarAxes[j].axisTag in axisLimits for j in axisIndices): + raise NotImplementedError( + "Instancing across VarComponent axes is not supported." + ) + axisIndicesList[i] = [reverseAxisMap[j] for j in axisIndices] + + store = varc.MultiVarStore + if store: + for region in store.SparseVarRegionList.Region: + newRegionAxis = [] + for regionRecord in region.SparseVarRegionAxis: + tag = fvarAxes[regionRecord.AxisIndex].axisTag + if tag in axisLimits: + raise NotImplementedError( + "Instancing across VarComponent axes is not supported." + ) + regionRecord.AxisIndex = reverseAxisMap[regionRecord.AxisIndex] + + +def instantiateTupleVariationStore( + variations, axisLimits, origCoords=None, endPts=None +): + """Instantiate TupleVariation list at the given location, or limit axes' min/max. + + The 'variations' list of TupleVariation objects is modified in-place. + The 'axisLimits' (dict) maps axis tags (str) to NormalizedAxisTriple namedtuples + specifying (minimum, default, maximum) in the -1,0,+1 normalized space. Pinned axes + have minimum == default == maximum. + + A 'full' instance (i.e. static font) is produced when all the axes are pinned to + single coordinates; a 'partial' instance (i.e. a less variable font) is produced + when some of the axes are omitted, or restricted with a new range. + + Tuples that do not participate are kept as they are. Those that have 0 influence + at the given location are removed from the variation store. + Those that are fully instantiated (i.e. all their axes are being pinned) are also + removed from the variation store, their scaled deltas accummulated and returned, so + that they can be added by the caller to the default instance's coordinates. + Tuples that are only partially instantiated (i.e. not all the axes that they + participate in are being pinned) are kept in the store, and their deltas multiplied + by the scalar support of the axes to be pinned at the desired location. + + Args: + variations: List[TupleVariation] from either 'gvar' or 'cvar'. + axisLimits: NormalizedAxisLimits: map from axis tags to (min, default, max) + normalized coordinates for the full or partial instance. + origCoords: GlyphCoordinates: default instance's coordinates for computing 'gvar' + inferred points (cf. table__g_l_y_f._getCoordinatesAndControls). + endPts: List[int]: indices of contour end points, for inferring 'gvar' deltas. + + Returns: + List[float]: the overall delta adjustment after applicable deltas were summed. + """ + + newVariations = changeTupleVariationsAxisLimits(variations, axisLimits) + + mergedVariations = collections.OrderedDict() + for var in newVariations: + # compute inferred deltas only for gvar ('origCoords' is None for cvar) + if origCoords is not None: + var.calcInferredDeltas(origCoords, endPts) + + # merge TupleVariations with overlapping "tents" + axes = frozenset(var.axes.items()) + if axes in mergedVariations: + mergedVariations[axes] += var + else: + mergedVariations[axes] = var + + # drop TupleVariation if all axes have been pinned (var.axes.items() is empty); + # its deltas will be added to the default instance's coordinates + defaultVar = mergedVariations.pop(frozenset(), None) + + for var in mergedVariations.values(): + var.roundDeltas() + variations[:] = list(mergedVariations.values()) + + return defaultVar.coordinates if defaultVar is not None else [] + + +def changeTupleVariationsAxisLimits(variations, axisLimits): + for axisTag, axisLimit in sorted(axisLimits.items()): + newVariations = [] + for var in variations: + newVariations.extend(changeTupleVariationAxisLimit(var, axisTag, axisLimit)) + variations = newVariations + return variations + + +def changeTupleVariationAxisLimit(var, axisTag, axisLimit): + assert isinstance(axisLimit, NormalizedAxisTripleAndDistances) + + # Skip when current axis is missing or peaks at 0 (i.e. doesn't participate) + lower, peak, upper = var.axes.get(axisTag, (-1, 0, 1)) + if peak == 0: + # explicitly defined, no-op axes can be omitted + # https://github.com/fonttools/fonttools/issues/3453 + if axisTag in var.axes: + del var.axes[axisTag] + return [var] + # Drop if the var 'tent' isn't well-formed + if not (lower <= peak <= upper) or (lower < 0 and upper > 0): + return [] + + if axisTag not in var.axes: + return [var] + + tent = var.axes[axisTag] + + solutions = solver.rebaseTent(tent, axisLimit) + + out = [] + for scalar, tent in solutions: + newVar = ( + TupleVariation(var.axes, var.coordinates) if len(solutions) > 1 else var + ) + if tent is None: + newVar.axes.pop(axisTag) + else: + assert tent[1] != 0, tent + newVar.axes[axisTag] = tent + newVar *= scalar + out.append(newVar) + + return out + + +def instantiateCFF2( + varfont, + axisLimits, + *, + round=round, + specialize=True, + generalize=False, + downgrade=False, + reachableRanges=None, +): + # The algorithm here is rather simple: + # + # Take all blend operations and store their deltas in the (otherwise empty) + # CFF2 VarStore. Then, instantiate the VarStore with the given axis limits, + # and read back the new deltas. This is done for both the CharStrings and + # the Private dicts. + # + # Then prune unused things and possibly drop the VarStore if it's empty. + # + # If the downgrade parameter is True, no actual downgrading is done, but + # the function returns True if the VarStore was empty after instantiation, + # and hence a downgrade to CFF is possible. In all other cases it returns + # False. + + log.info("Instantiating CFF2 table") + + fvarAxes = varfont["fvar"].axes + + cff = varfont["CFF2"].cff + topDict = cff.topDictIndex[0] + varStore = getattr(topDict, "VarStore", None) + if varStore is not None: + varStore = varStore.otVarStore + if not varStore: + if downgrade: + from fontTools.cffLib.CFF2ToCFF import convertCFF2ToCFF + + convertCFF2ToCFF(varfont) + return + + cff.desubroutinize() + + def getNumRegions(vsindex): + return varStore.VarData[vsindex if vsindex is not None else 0].VarRegionCount + + charStrings = topDict.CharStrings.values() + + # Gather all unique private dicts + uniquePrivateDicts = set() + privateDicts = [] + for fd in topDict.FDArray: + if fd.Private not in uniquePrivateDicts: + uniquePrivateDicts.add(fd.Private) + privateDicts.append(fd.Private) + + allCommands = [] + allCommandPrivates = [] + for cs in charStrings: + assert cs.private.vstore.otVarStore is varStore # Or in many places!! + commands = programToCommands(cs.program, getNumRegions=getNumRegions) + if generalize: + commands = generalizeCommands(commands) + if specialize: + commands = specializeCommands(commands, generalizeFirst=not generalize) + allCommands.append(commands) + allCommandPrivates.append(cs.private) + + def storeBlendsToVarStore(arg): + if not isinstance(arg, list): + return + + if any(isinstance(subarg, list) for subarg in arg[:-1]): + raise NotImplementedError("Nested blend lists not supported (yet)") + + count = arg[-1] + assert (len(arg) - 1) % count == 0 + nRegions = (len(arg) - 1) // count - 1 + assert nRegions == getNumRegions(vsindex) + for i in range(count, len(arg) - 1, nRegions): + deltas = arg[i : i + nRegions] + assert len(deltas) == nRegions + varData = varStore.VarData[vsindex] + varData.Item.append(deltas) + varData.ItemCount += 1 + + def fetchBlendsFromVarStore(arg): + if not isinstance(arg, list): + return [arg] + + if any(isinstance(subarg, list) for subarg in arg[:-1]): + raise NotImplementedError("Nested blend lists not supported (yet)") + + count = arg[-1] + assert (len(arg) - 1) % count == 0 + numRegions = getNumRegions(vsindex) + newDefaults = [] + newDeltas = [] + for i in range(count): + defaultValue = arg[i] + + major = vsindex + minor = varDataCursor[major] + varDataCursor[major] += 1 + + defaultValue += round(defaultDeltas[major][minor]) + newDefaults.append(defaultValue) + + varData = varStore.VarData[major] + deltas = varData.Item[minor] + assert len(deltas) == numRegions + newDeltas.extend(deltas) + + if not numRegions: + return newDefaults # No deltas, just return the defaults + + return [newDefaults + newDeltas + [count]] + + # Check VarData's are empty + for varData in varStore.VarData: + assert varData.Item == [] + assert varData.ItemCount == 0 + + # Add charstring blend lists to VarStore so we can instantiate them + for commands, private in zip(allCommands, allCommandPrivates): + vsindex = getattr(private, "vsindex", 0) + for command in commands: + if command[0] == "vsindex": + vsindex = command[1][0] + continue + for arg in command[1]: + storeBlendsToVarStore(arg) + + # Add private blend lists to VarStore so we can instantiate values + for private in privateDicts: + vsindex = getattr(private, "vsindex", 0) + for opcode, name, arg_type, default, converter in privateDictOperators2: + if arg_type not in ("number", "delta", "array") or name == "vsindex": + continue + if not hasattr(private, name): + continue + + values = getattr(private, name) + if arg_type == "number": + values = [values] + + for value in values: + if not isinstance(value, list): + continue + + assert len(value) % (getNumRegions(vsindex) + 1) == 0 + count = len(value) // (getNumRegions(vsindex) + 1) + storeBlendsToVarStore(value + [count]) + + # Instantiate VarStore + defaultDeltas = instantiateItemVariationStore( + varStore, fvarAxes, axisLimits, hierarchical=True + ) + + # Optionally cull dead regions (for avar2 partial instancing) + if reachableRanges: + _cullItemVariationStore(varStore, fvarAxes, reachableRanges) + + # Read back new charstring blends from the instantiated VarStore + varDataCursor = [0] * len(varStore.VarData) + for commands, private in zip(allCommands, allCommandPrivates): + vsindex = getattr(private, "vsindex", 0) + for command in commands: + if command[0] == "vsindex": + vsindex = command[1][0] + continue + newArgs = [] + for arg in command[1]: + newArgs.extend(fetchBlendsFromVarStore(arg)) + command[1][:] = newArgs + + # Read back new private blends from the instantiated VarStore + for private in privateDicts: + vsindex = getattr(private, "vsindex", 0) + for opcode, name, arg_type, default, converter in privateDictOperators2: + if arg_type not in ("number", "delta", "array") or name == "vsindex": + continue + if not hasattr(private, name): + continue + + values = getattr(private, name) + if arg_type == "number": + values = [values] + + newValues = [] + for value in values: + if not isinstance(value, list): + newValues.append(value) + continue + + value.append(1) + value = fetchBlendsFromVarStore(value) + newValues.extend(v[:-1] if isinstance(v, list) else v for v in value) + + if arg_type == "number": + newValues = newValues[0] + + setattr(private, name, newValues) + + # Empty out the VarStore + for i, varData in enumerate(varStore.VarData): + assert varDataCursor[i] == varData.ItemCount, ( + varDataCursor[i], + varData.ItemCount, + ) + varData.Item = [] + varData.ItemCount = 0 + + # Collect surviving vsindexes + usedVsindex = set( + i for i in range(len(varStore.VarData)) if varStore.VarData[i].VarRegionCount + ) + # Remove vsindex commands that are no longer needed + for commands, private in zip(allCommands, allCommandPrivates): + if not any(isinstance(arg, list) for command in commands for arg in command[1]): + commands[:] = [command for command in commands if command[0] != "vsindex"] + + # Remove unused VarData and update vsindex values + vsindexMapping = {v: i for i, v in enumerate(sorted(usedVsindex))} + varStore.VarData = [ + varData for i, varData in enumerate(varStore.VarData) if i in usedVsindex + ] + varStore.VarDataCount = len(varStore.VarData) + for commands in allCommands: + for command in commands: + if command[0] == "vsindex": + command[1][0] = vsindexMapping[command[1][0]] + for private in privateDicts: + if hasattr(private, "vsindex"): + if private.vsindex in vsindexMapping: + private.vsindex = vsindexMapping[private.vsindex] + else: + # The referenced VarData lost all its regions; the dict's + # blends have dissolved into plain values. + del private.vsindex + + # Remove initial vsindex commands that are implied + for commands, private in zip(allCommands, allCommandPrivates): + vsindex = getattr(private, "vsindex", 0) + if commands and commands[0] == ("vsindex", [vsindex]): + commands.pop(0) + + # Ship the charstrings! + for cs, commands in zip(charStrings, allCommands): + cs.program = commandsToProgram(commands) + + # Remove empty VarStore + if not varStore.VarData: + if "VarStore" in topDict.rawDict: + del topDict.rawDict["VarStore"] + del topDict.VarStore + del topDict.CharStrings.varStore + for private in privateDicts: + del private.vstore + + if downgrade: + return True + + return False + + +def _instantiateGvarGlyph( + glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=True +): + coordinates, ctrl = glyf._getCoordinatesAndControls(glyphname, hMetrics, vMetrics) + endPts = ctrl.endPts + + # Not every glyph may have variations + tupleVarStore = gvar.variations.get(glyphname) + + if tupleVarStore: + defaultDeltas = instantiateTupleVariationStore( + tupleVarStore, axisLimits, coordinates, endPts + ) + + if defaultDeltas: + coordinates += _g_l_y_f.GlyphCoordinates(defaultDeltas) + + # _setCoordinates also sets the hmtx/vmtx advance widths and sidebearings from + # the four phantom points and glyph bounding boxes. + # We call it unconditionally even if a glyph has no variations or no deltas are + # applied at this location, in case the glyph's xMin and in turn its sidebearing + # have changed. E.g. a composite glyph has no deltas for the component's (x, y) + # offset nor for the 4 phantom points (e.g. it's monospaced). Thus its entry in + # gvar table is empty; however, the composite's base glyph may have deltas + # applied, hence the composite's bbox and left/top sidebearings may need updating + # in the instanced font. + glyf._setCoordinates(glyphname, coordinates, hMetrics, vMetrics) + + if not tupleVarStore: + if glyphname in gvar.variations: + del gvar.variations[glyphname] + return + + if optimize: + # IUP semantics depend on point equality, and so round prior to + # optimization to ensure that comparisons that happen now will be the + # same as those that happen at render time. This is especially needed + # when floating point deltas have been applied to the default position. + # See https://github.com/fonttools/fonttools/issues/3634 + # Rounding must happen only after calculating glyf metrics above, to + # preserve backwards compatibility. + # See 0010a3cd9aa25f84a3a6250dafb119743d32aa40 + coordinates.toInt() + for var in tupleVarStore: + var.optimize(coordinates, endPts) + + +def instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True): + """Remove? + https://github.com/fonttools/fonttools/pull/2266""" + gvar = varfont["gvar"] + glyf = varfont["glyf"] + hMetrics = varfont["hmtx"].metrics + vMetrics = getattr(varfont.get("vmtx"), "metrics", None) + _instantiateGvarGlyph( + glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize + ) + + +def instantiateGvar(varfont, axisLimits, optimize=True): + log.info("Instantiating glyf/gvar tables") + + gvar = varfont["gvar"] + glyf = varfont["glyf"] + hMetrics = varfont["hmtx"].metrics + vMetrics = getattr(varfont.get("vmtx"), "metrics", None) + # Get list of glyph names sorted by component depth. + # If a composite glyph is processed before its base glyph, the bounds may + # be calculated incorrectly because deltas haven't been applied to the + # base glyph yet. + glyphnames = sorted( + glyf.glyphOrder, + key=lambda name: ( + ( + glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth + if glyf[name].isComposite() + else 0 + ), + name, + ), + ) + for glyphname in glyphnames: + _instantiateGvarGlyph( + glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize + ) + + if not gvar.variations: + del varfont["gvar"] + + +def setCvarDeltas(cvt, deltas): + for i, delta in enumerate(deltas): + if delta: + cvt[i] += otRound(delta) + + +def instantiateCvar(varfont, axisLimits): + log.info("Instantiating cvt/cvar tables") + + cvar = varfont["cvar"] + + defaultDeltas = instantiateTupleVariationStore(cvar.variations, axisLimits) + + if defaultDeltas: + setCvarDeltas(varfont["cvt "], defaultDeltas) + + if not cvar.variations: + del varfont["cvar"] + + +def setMvarDeltas(varfont, deltas): + mvar = varfont["MVAR"].table + records = mvar.ValueRecord + for rec in records: + mvarTag = rec.ValueTag + if mvarTag not in MVAR_ENTRIES: + continue + tableTag, itemName = MVAR_ENTRIES[mvarTag] + delta = deltas[rec.VarIdx] + if delta != 0: + setattr( + varfont[tableTag], + itemName, + getattr(varfont[tableTag], itemName) + otRound(delta), + ) + + +@contextmanager +def verticalMetricsKeptInSync(varfont): + """Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing. + + When applying MVAR deltas to the OS/2 table, if the ascender, descender and + line gap change but they were the same as the respective hhea metrics in the + original font, this context manager ensures that hhea metrcs also get updated + accordingly. + The MVAR spec only has tags for the OS/2 metrics, but it is common in fonts + to have the hhea metrics be equal to those for compat reasons. + + https://learn.microsoft.com/en-us/typography/opentype/spec/mvar + https://googlefonts.github.io/gf-guide/metrics.html#7-hhea-and-typo-metrics-should-be-equal + https://github.com/fonttools/fonttools/issues/3297 + """ + current_os2_vmetrics = [ + getattr(varfont["OS/2"], attr) + for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap") + ] + metrics_are_synced = current_os2_vmetrics == [ + getattr(varfont["hhea"], attr) for attr in ("ascender", "descender", "lineGap") + ] + + yield metrics_are_synced + + if metrics_are_synced: + new_os2_vmetrics = [ + getattr(varfont["OS/2"], attr) + for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap") + ] + if current_os2_vmetrics != new_os2_vmetrics: + for attr, value in zip( + ("ascender", "descender", "lineGap"), new_os2_vmetrics + ): + setattr(varfont["hhea"], attr, value) + + +def instantiateMVAR(varfont, axisLimits): + log.info("Instantiating MVAR table") + + mvar = varfont["MVAR"].table + fvarAxes = varfont["fvar"].axes + varStore = mvar.VarStore + defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits) + + with verticalMetricsKeptInSync(varfont): + setMvarDeltas(varfont, defaultDeltas) + + if varStore.VarRegionList.Region: + varIndexMapping = varStore.optimize() + for rec in mvar.ValueRecord: + rec.VarIdx = varIndexMapping[rec.VarIdx] + else: + del varfont["MVAR"] + + +def _remapVarIdxMap(table, attrName, varIndexMapping, glyphOrder): + oldMapping = getattr(table, attrName).mapping + newMapping = [varIndexMapping[oldMapping[glyphName]] for glyphName in glyphOrder] + setattr(table, attrName, builder.buildVarIdxMap(newMapping, glyphOrder)) + + +# TODO(anthrotype) Add support for HVAR/VVAR in CFF2 +def _instantiateVHVAR(varfont, axisLimits, tableFields, *, round=round): + location = axisLimits.pinnedLocation() + tableTag = tableFields.tableTag + fvarAxes = varfont["fvar"].axes + + log.info("Instantiating %s table", tableTag) + vhvar = varfont[tableTag].table + varStore = vhvar.VarStore + + if "glyf" in varfont: + # Deltas from gvar table have already been applied to the hmtx/vmtx. For full + # instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return + if set(location).issuperset(axis.axisTag for axis in fvarAxes): + log.info("Dropping %s table", tableTag) + del varfont[tableTag] + return + + defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits) + + if "glyf" not in varfont: + # CFF2 fonts need hmtx/vmtx updated here. For glyf fonts, the instantiateGvar + # function already updated the hmtx/vmtx from phantom points. Maybe remove + # that and do it here for both CFF2 and glyf fonts? + # + # Specially, if a font has glyf but not gvar, the hmtx/vmtx will not have been + # updated by instantiateGvar. Though one can call that a faulty font. + metricsTag = "vmtx" if tableTag == "VVAR" else "hmtx" + if metricsTag in varfont: + advMapping = getattr(vhvar, tableFields.advMapping) + metricsTable = varfont[metricsTag] + metrics = metricsTable.metrics + for glyphName, (advanceWidth, sb) in metrics.items(): + if advMapping: + varIdx = advMapping.mapping[glyphName] + else: + varIdx = varfont.getGlyphID(glyphName) + delta = round(defaultDeltas[varIdx]) + metrics[glyphName] = (max(0, advanceWidth + delta), sb) + + if ( + tableTag == "VVAR" + and getattr(vhvar, tableFields.vOrigMapping) is not None + ): + log.warning( + "VORG table not yet updated to reflect changes in VVAR table" + ) + + # For full instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return + if set(location).issuperset(axis.axisTag for axis in fvarAxes): + log.info("Dropping %s table", tableTag) + del varfont[tableTag] + return + + if varStore.VarRegionList.Region: + # Only re-optimize VarStore if the HVAR/VVAR already uses indirect AdvWidthMap + # or AdvHeightMap. If a direct, implicit glyphID->VariationIndex mapping is + # used for advances, skip re-optimizing and maintain original VariationIndex. + if getattr(vhvar, tableFields.advMapping): + varIndexMapping = varStore.optimize(use_NO_VARIATION_INDEX=False) + glyphOrder = varfont.getGlyphOrder() + _remapVarIdxMap(vhvar, tableFields.advMapping, varIndexMapping, glyphOrder) + if getattr(vhvar, tableFields.sb1): # left or top sidebearings + _remapVarIdxMap(vhvar, tableFields.sb1, varIndexMapping, glyphOrder) + if getattr(vhvar, tableFields.sb2): # right or bottom sidebearings + _remapVarIdxMap(vhvar, tableFields.sb2, varIndexMapping, glyphOrder) + if tableTag == "VVAR" and getattr(vhvar, tableFields.vOrigMapping): + _remapVarIdxMap( + vhvar, tableFields.vOrigMapping, varIndexMapping, glyphOrder + ) + + +def instantiateHVAR(varfont, axisLimits): + return _instantiateVHVAR(varfont, axisLimits, varLib.HVAR_FIELDS) + + +def instantiateVVAR(varfont, axisLimits): + return _instantiateVHVAR(varfont, axisLimits, varLib.VVAR_FIELDS) + + +class _TupleVarStoreAdapter(object): + def __init__(self, regions, axisOrder, tupleVarData, itemCounts): + self.regions = regions + self.axisOrder = axisOrder + self.tupleVarData = tupleVarData + self.itemCounts = itemCounts + + @classmethod + def fromItemVarStore(cls, itemVarStore, fvarAxes): + axisOrder = [axis.axisTag for axis in fvarAxes] + regions = [ + region.get_support(fvarAxes) for region in itemVarStore.VarRegionList.Region + ] + tupleVarData = [] + itemCounts = [] + for varData in itemVarStore.VarData: + variations = [] + varDataRegions = (regions[i] for i in varData.VarRegionIndex) + for axes, coordinates in zip(varDataRegions, zip(*varData.Item)): + variations.append(TupleVariation(axes, list(coordinates))) + tupleVarData.append(variations) + itemCounts.append(varData.ItemCount) + return cls(regions, axisOrder, tupleVarData, itemCounts) + + def rebuildRegions(self): + # Collect the set of all unique region axes from the current TupleVariations. + # We use an OrderedDict to de-duplicate regions while keeping the order. + uniqueRegions = collections.OrderedDict.fromkeys( + ( + frozenset(var.axes.items()) + for variations in self.tupleVarData + for var in variations + ) + ) + # Maintain the original order for the regions that pre-existed, appending + # the new regions at the end of the region list. + newRegions = [] + for region in self.regions: + regionAxes = frozenset(region.items()) + if regionAxes in uniqueRegions: + newRegions.append(region) + del uniqueRegions[regionAxes] + if uniqueRegions: + newRegions.extend(dict(region) for region in uniqueRegions) + self.regions = newRegions + + def instantiate(self, axisLimits): + defaultDeltaArray = [] + for variations, itemCount in zip(self.tupleVarData, self.itemCounts): + defaultDeltas = instantiateTupleVariationStore(variations, axisLimits) + if not defaultDeltas: + defaultDeltas = [0] * itemCount + defaultDeltaArray.append(defaultDeltas) + + # rebuild regions whose axes were dropped or limited + self.rebuildRegions() + + pinnedAxes = set(axisLimits.pinnedLocation()) + self.axisOrder = [ + axisTag for axisTag in self.axisOrder if axisTag not in pinnedAxes + ] + + return defaultDeltaArray + + def asItemVarStore(self): + regionOrder = [frozenset(axes.items()) for axes in self.regions] + varDatas = [] + for variations, itemCount in zip(self.tupleVarData, self.itemCounts): + if variations: + assert len(variations[0].coordinates) == itemCount + varRegionIndices = [ + regionOrder.index(frozenset(var.axes.items())) for var in variations + ] + varDataItems = list(zip(*(var.coordinates for var in variations))) + varDatas.append( + builder.buildVarData(varRegionIndices, varDataItems, optimize=False) + ) + else: + varDatas.append( + builder.buildVarData([], [[] for _ in range(itemCount)]) + ) + regionList = builder.buildVarRegionList(self.regions, self.axisOrder) + itemVarStore = builder.buildVarStore(regionList, varDatas) + # remove unused regions from VarRegionList + itemVarStore.prune_regions() + return itemVarStore + + +def instantiateItemVariationStore( + itemVarStore, fvarAxes, axisLimits, hierarchical=False +): + """Compute deltas at partial location, and update varStore in-place. + + Remove regions in which all axes were instanced, or fall outside the new axis + limits. Scale the deltas of the remaining regions where only some of the axes + were instanced. + + The number of VarData subtables, and the number of items within each, are + not modified, in order to keep the existing VariationIndex valid. + One may call VarStore.optimize() method after this to further optimize those. + + Args: + varStore: An otTables.VarStore object (Item Variation Store) + fvarAxes: list of fvar's Axis objects + axisLimits: NormalizedAxisLimits: mapping axis tags to normalized + min/default/max axis coordinates. May not specify coordinates/ranges for + all the fvar axes. + + Returns: + defaultDeltas: to be added to the default instance, of type dict of floats + keyed by VariationIndex compound values: i.e. (outer << 16) + inner. + """ + tupleVarStore = _TupleVarStoreAdapter.fromItemVarStore(itemVarStore, fvarAxes) + defaultDeltaArray = tupleVarStore.instantiate(axisLimits) + newItemVarStore = tupleVarStore.asItemVarStore() + + itemVarStore.VarRegionList = newItemVarStore.VarRegionList + if not hasattr(itemVarStore, "VarDataCount"): # Happens fromXML + itemVarStore.VarDataCount = len(newItemVarStore.VarData) + assert itemVarStore.VarDataCount == newItemVarStore.VarDataCount + itemVarStore.VarData = newItemVarStore.VarData + + if not hierarchical: + defaultDeltas = { + ((major << 16) + minor): delta + for major, deltas in enumerate(defaultDeltaArray) + for minor, delta in enumerate(deltas) + } + defaultDeltas[itemVarStore.NO_VARIATION_INDEX] = 0 + else: + defaultDeltas = {0xFFFF: {0xFFFF: 0}} # NO_VARIATION_INDEX + for major, deltas in enumerate(defaultDeltaArray): + defaultDeltasForMajor = defaultDeltas.setdefault(major, {}) + for minor, delta in enumerate(deltas): + defaultDeltasForMajor[minor] = delta + return defaultDeltas + + +def _instantiateBASE(varfont, axisLimits): + if "BASE" not in varfont: + return + + base = varfont["BASE"].table + varStore = getattr(base, "VarStore", None) + if varStore is None: + return + + log.info("Instantiating BASE table") + + fvarAxes = varfont["fvar"].axes + defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits) + + merger = MutatorMerger( + varfont, defaultDeltas, deleteVariations=(not varStore.VarRegionList.Region) + ) + merger.mergeTables(varfont, [varfont], ["BASE"]) + + if varStore.VarRegionList.Region: + base.remap_device_varidxes(varStore.optimize()) + else: + # Downgrade BASE, it no longer references an ItemVariationStore. + del base.VarStore + base.Version = 0x00010000 + + +def instantiateOTL(varfont, axisLimits): + # TODO(anthrotype) Support partial instancing of JSTF table + _instantiateBASE(varfont, axisLimits) + + if ( + "GDEF" not in varfont + or varfont["GDEF"].table.Version < 0x00010003 + or not varfont["GDEF"].table.VarStore + ): + return + + if "GPOS" in varfont: + msg = "Instantiating GDEF and GPOS tables" + else: + msg = "Instantiating GDEF table" + log.info(msg) + + gdef = varfont["GDEF"].table + varStore = gdef.VarStore + fvarAxes = varfont["fvar"].axes + + defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits) + + # When VF are built, big lookups may overflow and be broken into multiple + # subtables. MutatorMerger (which inherits from AligningMerger) reattaches + # them upon instancing, in case they can now fit a single subtable (if not, + # they will be split again upon compilation). + # This 'merger' also works as a 'visitor' that traverses the OTL tables and + # calls specific methods when instances of a given type are found. + # Specifically, it adds default deltas to GPOS Anchors/ValueRecords and GDEF + # LigatureCarets, and optionally deletes all VariationIndex tables if the + # VarStore is fully instanced. + merger = MutatorMerger( + varfont, defaultDeltas, deleteVariations=(not varStore.VarRegionList.Region) + ) + merger.mergeTables(varfont, [varfont], ["GDEF", "GPOS"]) + + if varStore.VarRegionList.Region: + varIndexMapping = varStore.optimize() + gdef.remap_device_varidxes(varIndexMapping) + if "GPOS" in varfont: + varfont["GPOS"].table.remap_device_varidxes(varIndexMapping) + else: + # Downgrade GDEF. + del gdef.VarStore + gdef.Version = 0x00010002 + if gdef.MarkGlyphSetsDef is None: + del gdef.MarkGlyphSetsDef + gdef.Version = 0x00010000 + + if not ( + gdef.LigCaretList + or gdef.MarkAttachClassDef + or gdef.GlyphClassDef + or gdef.AttachList + or (gdef.Version >= 0x00010002 and gdef.MarkGlyphSetsDef) + ): + del varfont["GDEF"] + + +def _isValidAvarSegmentMap(axisTag, segmentMap): + if not segmentMap: + return True + if not {(-1.0, -1.0), (0, 0), (1.0, 1.0)}.issubset(segmentMap.items()): + log.warning( + f"Invalid avar SegmentMap record for axis '{axisTag}': does not " + "include all required value maps {-1.0: -1.0, 0: 0, 1.0: 1.0}" + ) + return False + previousValue = None + for fromCoord, toCoord in sorted(segmentMap.items()): + if previousValue is not None and previousValue > toCoord: + log.warning( + f"Invalid avar AxisValueMap({fromCoord}, {toCoord}) record " + f"for axis '{axisTag}': the toCoordinate value must be >= to " + f"the toCoordinate value of the preceding record ({previousValue})." + ) + return False + previousValue = toCoord + return True + + +def downgradeCFF2ToCFF(varfont): + # Save these properties + recalcTimestamp = varfont.recalcTimestamp + recalcBBoxes = varfont.recalcBBoxes + + # Disable them + varfont.recalcTimestamp = False + varfont.recalcBBoxes = False + + # Save to memory, reload, downgrade and save again, reload. + # We do this dance because the convertCFF2ToCFF changes glyph + # names, so following save would fail if any other table was + # loaded and referencing glyph names. + # + # The second save+load is unfortunate but also necessary. + + stream = io.BytesIO() + log.info("Saving CFF2 font to memory for downgrade") + varfont.save(stream) + stream.seek(0) + varfont = TTFont(stream, recalcTimestamp=False, recalcBBoxes=False) + + convertCFF2ToCFF(varfont) + + stream = io.BytesIO() + log.info("Saving downgraded CFF font to memory") + varfont.save(stream) + stream.seek(0) + varfont = TTFont(stream, recalcTimestamp=False, recalcBBoxes=False) + + # Uncomment, to see test all tables can be loaded. This fails without + # the extra save+load above. + """ + for tag in varfont.keys(): + print("Loading", tag) + varfont[tag] + """ + + # Restore them + varfont.recalcTimestamp = recalcTimestamp + varfont.recalcBBoxes = recalcBBoxes + + return varfont + + +def instantiateAvar(varfont, axisLimits, normalizedLimits=None, oldIntermediates=None): + # 'axisLimits' dict must contain user-space (non-normalized) coordinates. + + if normalizedLimits is None: + normalizedLimits = axisLimits.normalize(varfont) + + avar = varfont["avar"] + + segments = avar.segments + + # Capture the OLD avar v1 segment maps before the renormalization below + # overwrites avar.segments; _instantiateAvarV2 needs them to collect the + # interior breakpoints used for exact offset compensation. + oldSegments = {tag: dict(mapping) for tag, mapping in segments.items()} + + # An avar version 2 font is never downgraded to version 1: even with a + # NULL/empty VarStore, partial instancing takes the avar2 path (offset + # compensation creates delta rows on demand), which keeps the other + # variation tables in old coordinate space and the instance bit-exact. + version = getattr(avar, "majorVersion", 1) + isAvar2 = version >= 2 + + # Drop the table if we instantiate all the axes. An avar2 VarStore may + # drive axes that have no v1 segment map (segments can even be empty), + # so for those fonts require ALL fvar axes to be pinned, not merely all + # segment-mapped ones — otherwise we'd delete live avar2 variation data. + pinnedAxes = set(axisLimits.pinnedLocation()) + if pinnedAxes.issuperset(axis.axisTag for axis in varfont["fvar"].axes) or ( + not isAvar2 and pinnedAxes.issuperset(segments) + ): + log.info("Dropping avar table") + del varfont["avar"] + return + + # For avar2: need old intermediate values BEFORE modifying avar v1. + if isAvar2 and oldIntermediates is None: + oldIntermediates = _computeOldIntermediates(varfont, axisLimits) + + log.info("Instantiating avar table") + if isAvar2: + # For avar2 partial instancing, keep identity segments for pinned axes + # that will be hidden in fvar. compile() needs segment entries for all + # fvar axes. Self-contained axes' segments will be removed later when + # they're removed from fvar. + for axis in pinnedAxes: + if axis in segments: + segments[axis] = {-1.0: -1.0, 0.0: 0.0, 1.0: 1.0} + else: + for axis in pinnedAxes: + if axis in segments: + del segments[axis] + + # Standard avar v1 instancing (unchanged). + normalizedRanges = axisLimits.normalize(varfont, usingAvar=False) + newSegments = {} + for axisTag, mapping in segments.items(): + if not _isValidAvarSegmentMap(axisTag, mapping): + continue + if mapping and axisTag in normalizedRanges: + axisRange = normalizedRanges[axisTag] + mappedMin = floatToFixedToFloat( + piecewiseLinearMap(axisRange.minimum, mapping), 14 + ) + mappedDef = floatToFixedToFloat( + piecewiseLinearMap(axisRange.default, mapping), 14 + ) + mappedMax = floatToFixedToFloat( + piecewiseLinearMap(axisRange.maximum, mapping), 14 + ) + mappedAxisLimit = NormalizedAxisTripleAndDistances( + mappedMin, + mappedDef, + mappedMax, + axisRange.distanceNegative, + axisRange.distancePositive, + ) + newMapping = {} + for fromCoord, toCoord in mapping.items(): + if fromCoord < axisRange.minimum or fromCoord > axisRange.maximum: + continue + fromCoord = axisRange.renormalizeValue(fromCoord) + + assert mappedMin <= toCoord <= mappedMax + toCoord = mappedAxisLimit.renormalizeValue(toCoord) + + fromCoord = floatToFixedToFloat(fromCoord, 14) + toCoord = floatToFixedToFloat(toCoord, 14) + newMapping[fromCoord] = toCoord + newMapping.update({-1.0: -1.0, 0.0: 0.0, 1.0: 1.0}) + newSegments[axisTag] = newMapping + else: + newSegments[axisTag] = mapping + avar.segments = newSegments + + if version == 1: + return {} + + assert version == 2 + + return _instantiateAvarV2( + varfont, axisLimits, normalizedLimits, oldIntermediates, oldSegments + ) + + +def _computeOldIntermediates(varfont, axisLimits): + """Compute old intermediate axis values before avar v1 modification. + + For each axis in axisLimits, computes the old intermediate coordinate + values (post-fvar normalization + avar v1 mapping) at the new min, + default, and max user-space values. + + Returns: + dict mapping axis tags to (a_i, d_i, b_i) tuples where: + - a_i = old intermediate value at the new minimum + - d_i = old intermediate value at the new default + - b_i = old intermediate value at the new maximum + All values are in normalized coordinate space [-1, +1]. + """ + fvar = varfont["fvar"] + avar = varfont["avar"] + avarSegments = avar.segments + + result = {} + for axis in fvar.axes: + tag = axis.axisTag + if tag not in axisLimits: + continue + + triple = axisLimits[tag] + minV = triple.minimum + defV = triple.default if triple.default is not None else axis.defaultValue + maxV = triple.maximum + + # Normalize using old fvar, map through old avar v1 segment map, + # quantize to F2Dot14 — all via the module's normalize() helper so + # the rounding behavior lives in a single place. + oldFvarTriple = (axis.minValue, axis.defaultValue, axis.maxValue) + avarMapping = avarSegments.get(tag, None) + result[tag] = tuple( + normalize(v, oldFvarTriple, avarMapping) for v in (minV, defV, maxV) + ) + + return result + + +# Threshold, in F2Dot14 units, above which a restricted avar2 axis's residual +# offset-compensation error triggers a warning. The quantization floor is ~2 and +# small residuals (a few units) are common and imperceptible for real avar v1 +# maps; only a clearly larger residual — a steep retained segment that cannot be +# reproduced bit-exactly — is worth flagging (see _estimateAvar2OffsetError). +_AVAR2_OFFSET_WARN_THRESHOLD = 8 + + +def _estimateAvar2OffsetError(oldSeg, newSeg, oldFvarTriple, newTriple, offsetByZ): + """Estimate the residual offset-compensation error for one restricted axis. + + Returns the max |old-avar1-final - (new-avar1 + offset)| over the retained + user range, in F2Dot14 units. offset(z) is the piecewise-linear function + through the offsetByZ knots (what the 1-D VariationModel reproduces). The + residual is dominated by F2Dot14 requantization of a steep retained avar v1 + segment (e.g. a moved default compressing part of the axis into a narrow z + band); offset compensation cannot remove it. Used only to decide which + encoding ships and whether to warn. + + Sampled on a uniform grid augmented with the user-space preimages of every + kink of the residual (old/new avar v1 breakpoints and offset(z) knots), so + the worst kink cannot fall between uniform samples. The pointwise F2Dot14 + rounding makes this an estimate rather than an exact bound, but every + piecewise-linear extremum is visited. + """ + lo, _, hi = newTriple + samples = 257 + us = {lo + (hi - lo) * i / (samples - 1) for i in range(samples)} + denormOld = {-1.0: oldFvarTriple[0], 0.0: oldFvarTriple[1], 1.0: oldFvarTriple[2]} + denormNew = {-1.0: newTriple[0], 0.0: newTriple[1], 1.0: newTriple[2]} + if oldSeg: + us.update(piecewiseLinearMap(n, denormOld) for n in oldSeg) + zToNorm = None + if newSeg: + us.update(piecewiseLinearMap(n, denormNew) for n in newSeg) + # Inverse of newSeg, to pull offset(z) knots back to normalized space. + # (For a non-strictly-monotone map this picks one preimage, which is + # fine: the uniform grid still covers the rest.) + zToNorm = {v: k for k, v in newSeg.items()} + for z in offsetByZ: + n = piecewiseLinearMap(z, zToNorm) if zToNorm else z + us.add(piecewiseLinearMap(n, denormNew)) + + maxErr = 0 + for u in us: + if not (lo <= u <= hi): + continue + nOld = normalizeValue(u, oldFvarTriple) + oldFinal = piecewiseLinearMap(nOld, oldSeg) if oldSeg else nOld + nNew = normalizeValue(u, newTriple) + z = piecewiseLinearMap(nNew, newSeg) if newSeg else nNew + newFinal = z + piecewiseLinearMap(z, offsetByZ) + maxErr = max(maxErr, abs(otRound(oldFinal * 16384) - otRound(newFinal * 16384))) + return maxErr + + +def _effectiveAvar2VarIdx(varStore, varIdxMap, axisIdx): + """The varIdx an axis actually resolves to in the avar2 VarStore. + + Entries (or the implicit identity mapping) that point outside the store + behave as "no variation" at runtime, so report them as + NO_VARIATION_INDEX; this also covers a NULL VarStore. + """ + varIdx = varIdxMap[axisIdx] if varIdxMap is not None else axisIdx + if varIdx == NO_VARIATION_INDEX or varStore is None: + return NO_VARIATION_INDEX + outer, inner = varIdx >> 16, varIdx & 0xFFFF + if outer >= len(varStore.VarData) or inner >= varStore.VarData[outer].ItemCount: + return NO_VARIATION_INDEX + return varIdx + + +def _instantiateAvarV2( + varfont, axisLimits, normalizedLimits, oldIntermediates, oldSegments=None +): + """Instance avar v2 IVS: rebase regions + add offset compensation. + + This implements the offset compensation approach from the design doc: + 1. Rebase IVS regions to new intermediate coordinate space (via rebaseTent) + 2. Detect self-contained pinned axes (whose final coord is constant) + 3. Add offset compensation entries (empty-region bias + tent deltas) + for non-self-contained axes so final coordinates remain in old space + 4. Self-contained axes are skipped — their contributions will be folded + into gvar/HVAR/etc. by the caller + + Returns: + dict: {axisTag: finalCoord} for self-contained pinned axes that can be + removed from fvar. finalCoord is in old-space normalized coordinates. + """ + avar = varfont["avar"] + fvarAxes = varfont["fvar"].axes + varStore = avar.table.VarStore + varIdxMap = getattr(avar.table, "VarIdxMap", None) + oldSegments = oldSegments or {} + + # A compiled DeltaSetIndexMap may be stored truncated (trailing duplicate + # entries are trimmed; reads clamp to the last entry). We write into the + # mapping by axis index below, so pad it back to full length first, with + # the same value clamping would have produced for each index. + if varIdxMap is not None and len(varIdxMap.mapping) < len(fvarAxes): + mapping = varIdxMap.mapping + fill = mapping[-1] if mapping else NO_VARIATION_INDEX + mapping.extend([fill] * (len(fvarAxes) - len(mapping))) + + # Normalize mapping entries that don't resolve to a real store row (out + # of range, or a NULL VarStore) to NO_VARIATION_INDEX, mirroring runtime + # behavior. A version 2 font is never downgraded: with a NULL VarStore we + # start from an empty store and offset compensation creates delta rows on + # demand. + numAxes = len(fvarAxes) + rawMapping = [varIdxMap[i] if varIdxMap is not None else i for i in range(numAxes)] + effectiveMapping = [ + _effectiveAvar2VarIdx(varStore, varIdxMap, i) for i in range(numAxes) + ] + if effectiveMapping != rawMapping: + if varIdxMap is None: + varIdxMap = builder.buildDeltaSetIndexMap(effectiveMapping) + avar.table.VarIdxMap = varIdxMap + else: + varIdxMap.mapping = effectiveMapping + if varStore is None: + varStore = builder.buildVarStore( + builder.buildVarRegionList([], [a.axisTag for a in fvarAxes]), [] + ) + avar.table.VarStore = varStore + + # Step 1: Convert IVS to TupleVariation representation and rebase + tupleVarStore = _TupleVarStoreAdapter.fromItemVarStore(varStore, fvarAxes) + + # Save original axis order (instantiate() will remove pinned axes) + originalAxisOrder = list(tupleVarStore.axisOrder) + + # Rebase regions for restricted/pinned axes + defaultDeltaArray = tupleVarStore.instantiate(normalizedLimits) + + # Restore full axis order — for avar2 we keep all fvar axes + tupleVarStore.axisOrder = originalAxisOrder + + # Step 1.5: Detect self-contained pinned axes. + # A pinned axis is self-contained if its final coordinate doesn't vary + # with any remaining axes. After IVS rebasing, check if any remaining + # TupleVariation has a non-zero delta at the axis's inner position. + selfContainedAxes = {} + pinnedLocation = axisLimits.pinnedLocation() + + for axisIdx, axis in enumerate(fvarAxes): + tag = axis.axisTag + if tag not in pinnedLocation: + continue + + # Get this axis's varIdx + if varIdxMap is not None: + varIdx = varIdxMap[axisIdx] + else: + varIdx = axisIdx + + if varIdx == NO_VARIATION_INDEX: + # No IVS entry → final coord = intermediate coord (self-contained) + a_i, d_i, b_i = oldIntermediates[tag] + finalInt = otRound(d_i * 16384) + finalInt = min(max(finalInt, -(1 << 14)), 1 << 14) + selfContainedAxes[tag] = finalInt / 16384.0 + continue + + outer = varIdx >> 16 + inner = varIdx & 0xFFFF + + if outer >= len(tupleVarStore.tupleVarData): + continue + + # Check if any remaining TupleVariation has a non-zero delta + hasDelta = any( + tv.coordinates[inner] != 0 for tv in tupleVarStore.tupleVarData[outer] + ) + + if not hasDelta: + # Self-contained: final coord = intermediate + defaultDelta + a_i, d_i, b_i = oldIntermediates[tag] + d_int = otRound(d_i * 16384) + defaultDelta = defaultDeltaArray[outer][inner] + finalInt = d_int + otRound(defaultDelta) + finalInt = min(max(finalInt, -(1 << 14)), 1 << 14) + selfContainedAxes[tag] = finalInt / 16384.0 + + if selfContainedAxes: + log.info( + "Self-contained pinned axes (removable): %s", + {tag: round(v, 6) for tag, v in selfContainedAxes.items()}, + ) + + # Step 1.75: Privatize shared varIdx delta rows before adding offset + # compensation. avar2's VarIdxMap may map several fvar axes to the SAME + # IVS delta row (as the parametric test font does: e.g. GRAD and XOPQ can + # share one varIdx). Writing one axis's offset-compensation deltas into a + # shared row would corrupt every OTHER axis that reads that row. So give + # each offset-receiving axis whose row is shared its own private copy of + # the row (identical contents, preserving the rebased delta), then repoint + # its VarIdxMap entry. Sharers keep the clean row; offsets land privately. + def _axisVarIdx(i): + return varIdxMap[i] if varIdxMap is not None else i + + varIdxRefCount = collections.Counter(_axisVarIdx(i) for i in range(len(fvarAxes))) + for axisIdx, axis in enumerate(fvarAxes): + tag = axis.axisTag + # Only axes that will receive offset compensation (restricted or + # non-self-contained pinned) can contaminate a shared row. + if tag not in axisLimits or tag in selfContainedAxes: + continue + varIdx = _axisVarIdx(axisIdx) + if varIdx == NO_VARIATION_INDEX: + continue # gets a fresh, private VarData in the offset loop below + if varIdxRefCount[varIdx] <= 1: + continue # sole owner: safe to write offsets in place + # Shared: duplicate this axis's item (row) within its VarData so it has + # a private inner index. Copy the value from every TupleVariation so the + # rebased delta is preserved; extend defaultDeltaArray in tandem. + outer = varIdx >> 16 + inner = varIdx & 0xFFFF + newInner = tupleVarStore.itemCounts[outer] + for tv in tupleVarStore.tupleVarData[outer]: + tv.coordinates.append(tv.coordinates[inner]) + tupleVarStore.itemCounts[outer] += 1 + defaultDeltaArray[outer].append(defaultDeltaArray[outer][inner]) + newVarIdx = (outer << 16) | newInner + # A shared varIdx implies an explicit VarIdxMap (implicit identity maps + # every axis to a distinct varIdx, so we could not be here otherwise). + assert varIdxMap is not None + varIdxMap.mapping[axisIdx] = newVarIdx + varIdxRefCount[varIdx] -= 1 + varIdxRefCount[newVarIdx] += 1 + + # Step 2: Add offset compensation TupleVariations + processedVarIdxes = set() + approxWarn = {} # {axisTag: residual F2Dot14 error} for axes we can't make exact + for axisIdx, axis in enumerate(fvarAxes): + tag = axis.axisTag + + # Determine this axis's varIdx + if varIdxMap is not None: + varIdx = varIdxMap[axisIdx] + else: + varIdx = axisIdx + + if tag in axisLimits: + if tag in selfContainedAxes: + # Self-contained pinned axis: skip offset compensation. + # Its contribution will be folded into gvar/HVAR/etc. instead. + continue + + # This axis is being restricted or pinned (non-self-contained) + a_i, d_i, b_i = oldIntermediates[tag] + isPinned = axisLimits[tag].minimum == axisLimits[tag].maximum + + if varIdx == NO_VARIATION_INDEX: + # This axis has no existing avar2 mapping. Create a new + # VarData with one item to hold the offset compensation. + outer = len(tupleVarStore.tupleVarData) + inner = 0 + tupleVarStore.tupleVarData.append([]) + tupleVarStore.itemCounts.append(1) + defaultDeltaArray.append([0]) + + varIdx = (outer << 16) | inner + + # Update VarIdxMap + if varIdxMap is None: + # Identity mapping for all axes, except this one + mapping = list(range(len(fvarAxes))) + mapping[axisIdx] = varIdx + varIdxMap = builder.buildDeltaSetIndexMap(mapping) + avar.table.VarIdxMap = varIdxMap + else: + varIdxMap.mapping[axisIdx] = varIdx + + outer = varIdx >> 16 + inner = varIdx & 0xFFFF + itemCount = tupleVarStore.itemCounts[outer] + defaultDelta = defaultDeltaArray[outer][inner] + + # Offset compensation encodes, as avar2 deltas on axis `tag`, the + # piecewise-linear function offset(z) = inv_renorm(z) - z, where + # inv_renorm maps a new intermediate coordinate z back to the old + # intermediate coordinate. It is known at these breakpoints in the + # new intermediate space: + # z = -1 -> a_i + 1 (new minimum) + # z = 0 -> d_i (new default) + # z = +1 -> b_i - 1 (new maximum) + # If the axis default MOVED, inv_renorm also kinks where the OLD + # default lands in the new space (old intermediate crosses 0), at + # z = z_old -> -z_old + # Omitting that breakpoint (as a plain two-tent encoding does) makes + # interior coordinates wrong. Feed all breakpoints to a VariationModel + # to synthesize the correct tents; this reduces to the two classic + # tents when the default is unchanged (z_old == 0). + offsetByZ = {-1.0: a_i + 1.0, 0.0: d_i, 1.0: b_i - 1.0} + if not isPinned: + newSeg = avar.segments.get(tag) + newLimit = axisLimits[tag] + # default may be unpopulated (2-tuple limits): means unchanged. + newDefault = ( + newLimit.default + if newLimit.default is not None + else axis.defaultValue + ) + newTriple = (newLimit.minimum, newDefault, newLimit.maximum) + # Moved-default kink: where the OLD default lands in new space. + zOldNorm = normalizeValue(axis.defaultValue, newTriple) + zOld = piecewiseLinearMap(zOldNorm, newSeg) if newSeg else zOldNorm + zOld = floatToFixedToFloat(zOld, 14) + if -1.0 < zOld < 1.0 and zOld not in offsetByZ: + offsetByZ[zOld] = -zOld + + # Interior avar v1 breakpoints inside the retained range each put + # a kink in offset(z). Sampling only {-1, 0, +1, z_old} would + # linearly interpolate across those kinks (approximate, worst + # under a moved default on an asymmetric axis). The retained + # (renormalized) avar v1 map keeps exactly the in-range old + # breakpoints, and z(u) kinks at each retained breakpoint's + # output coordinate; add that z with its old intermediate value + # so the model reproduces offset(z) at every kink. Iterating the + # retained map lands each sample on the F2Dot14-quantized kink. + oldSeg = oldSegments.get(tag) + oldFvarTriple = (axis.minValue, axis.defaultValue, axis.maxValue) + withBreakpoints = dict(offsetByZ) + if oldSeg and newSeg: + denormNew = { + -1.0: newTriple[0], + 0.0: newTriple[1], + 1.0: newTriple[2], + } + for fromCoordNew, z in newSeg.items(): + if fromCoordNew in (-1.0, 0.0, 1.0): + continue # anchors already seeded + z = floatToFixedToFloat(z, 14) + if not (-1.0 < z < 1.0) or z in withBreakpoints: + continue + user = piecewiseLinearMap(fromCoordNew, denormNew) + nOld = normalizeValue(user, oldFvarTriple) + xOld = piecewiseLinearMap(nOld, oldSeg) + withBreakpoints[z] = floatToFixedToFloat(xOld, 14) - z + + # Extra tents cost F2Dot14 rounding, so for a steep segment they + # can add more quantization noise than the structural error they + # remove. Keep the interior breakpoints only when they do not + # increase the estimated residual; this makes the collection a + # strict (never-worse) improvement over the {-1,0,+1,z_old} + # anchors. Warn when even the better choice is not bit-exact + # (a steep retained segment we cannot reproduce in F2Dot14). + errAnchors = _estimateAvar2OffsetError( + oldSeg, newSeg, oldFvarTriple, newTriple, offsetByZ + ) + if len(withBreakpoints) == len(offsetByZ): + # Collection added no breakpoints (the common case): + # the two encodings are identical, skip the second pass. + approxErr = errAnchors + else: + errWith = _estimateAvar2OffsetError( + oldSeg, newSeg, oldFvarTriple, newTriple, withBreakpoints + ) + if errWith <= errAnchors: + offsetByZ = withBreakpoints + approxErr = errWith + else: + approxErr = errAnchors + if approxErr > _AVAR2_OFFSET_WARN_THRESHOLD: + approxWarn[tag] = approxErr + + if isPinned: + # Pinned axis has zero range: only the constant bias applies. + bias = otRound(d_i * 16384) + otRound(defaultDelta) + if bias != 0: + coords = [0] * itemCount + coords[inner] = bias + tupleVarStore.tupleVarData[outer].append(TupleVariation({}, coords)) + else: + zs = sorted(offsetByZ) + model = VariationModel([{tag: z} for z in zs], axisOrder=[tag]) + deltas = model.getDeltas([offsetByZ[z] for z in zs]) + for delta, support in zip(deltas, model.supports): + di = otRound(delta * 16384) + if not support: + # Base (empty) region: fold in the rebased default delta. + di += otRound(defaultDelta) + if di != 0: + coords = [0] * itemCount + coords[inner] = di + tupleVarStore.tupleVarData[outer].append( + TupleVariation(dict(support), coords) + ) + else: + # Free or private axis — not being restricted. + # If it has a non-zero default delta (from rebasing restricted axes' + # contributions), add it back as a bias. The standard instancing + # subtracts default deltas, but for avar2 we must preserve them. + # Skip if this varIdx was already processed (multiple axes can + # share the same varIdx entry). + if varIdx == NO_VARIATION_INDEX: + continue + if varIdx in processedVarIdxes: + continue + processedVarIdxes.add(varIdx) + outer = varIdx >> 16 + inner = varIdx & 0xFFFF + if outer >= len(defaultDeltaArray): + continue + defaultDelta = defaultDeltaArray[outer][inner] + if otRound(defaultDelta) != 0: + itemCount = tupleVarStore.itemCounts[outer] + coords = [0] * itemCount + coords[inner] = otRound(defaultDelta) + tupleVarStore.tupleVarData[outer].append(TupleVariation({}, coords)) + + if approxWarn: + log.warning( + "avar2 partial instancing is approximate (not bit-exact) for " + "axes %s: the avar v1 segment map has interior breakpoint(s) in the " + "retained range that, after a moved/edge default, require a steep " + "F2Dot14 segment the offset compensation cannot fully reproduce. " + "Max residual: %s F2Dot14 units.", + ", ".join(sorted(approxWarn)), + {tag: approxWarn[tag] for tag in sorted(approxWarn)}, + ) + + # Step 3: Remove self-contained axes from axis order. + # The VarRegionList must match the post-removal fvar axis count. + # After instancing, no TupleVariation references self-contained axes. + if selfContainedAxes: + tupleVarStore.axisOrder = [ + tag for tag in tupleVarStore.axisOrder if tag not in selfContainedAxes + ] + + # Step 4: Rebuild regions and convert back to IVS + tupleVarStore.rebuildRegions() + newVarStore = tupleVarStore.asItemVarStore() + + # Step 5: Optimize the VarStore (merge regions, remove zero deltas) + varIdxMapping = newVarStore.optimize(use_NO_VARIATION_INDEX=False) + if varIdxMap is not None: + varIdxMap.mapping = [ + varIdxMapping.get(varIdx, varIdx) for varIdx in varIdxMap.mapping + ] + elif varIdxMapping: + # optimize() remapped indices but we had no VarIdxMap (implicit + # identity). Create one if the mapping is no longer identity. + varIdxMap = builder.buildDeltaSetIndexMap( + varIdxMapping.get(i, i) for i in range(len(fvarAxes)) + ) + if varIdxMap is not None: + avar.table.VarIdxMap = varIdxMap + avar.table.VarStore = newVarStore + + return selfContainedAxes + + +def _isTupleVariationDead(tv, reachableRanges): + """Check if a TupleVariation is dead (unreachable) given reachable axis ranges.""" + for tag, (lo, hi) in reachableRanges.items(): + if tag not in tv.axes: + continue + start, peak, end = tv.axes[tag] + # Region is dead if entirely outside reachable range. Strict + # comparisons: supportScalar returns 1 (not 0) at v == peak, so a + # tent whose peak sits exactly on the reachable boundary (peak == + # start == hi, or peak == end == lo) is still live there. + if hi < start or lo > end: + return True + return False + + +def _cullItemVariationStore(varStore, fvarAxes, reachableRanges): + """Remove dead regions from an ItemVariationStore via TupleVariation culling. + + Converts to TupleVariations, removes dead ones, converts back. + Returns the number of removed regions. + """ + tupleVarStore = _TupleVarStoreAdapter.fromItemVarStore(varStore, fvarAxes) + totalCulled = 0 + for tvList in tupleVarStore.tupleVarData: + before = len(tvList) + tvList[:] = [ + tv for tv in tvList if not _isTupleVariationDead(tv, reachableRanges) + ] + totalCulled += before - len(tvList) + if totalCulled: + tupleVarStore.rebuildRegions() + newVarStore = tupleVarStore.asItemVarStore() + varStore.VarRegionList = newVarStore.VarRegionList + varStore.VarData = newVarStore.VarData + return totalCulled + + +def _cullVariationsForAvar2(varfont, reachableRanges): + """Cull dead variations outside reachable old-space final-coord ranges. + + After avar2 partial instancing with offset compensation, variation tables + remain in old-space final coordinates. Some regions may be unreachable + because the restricted axis range maps to a narrower final-coord range. + + For gvar/cvar: removes TupleVariations whose axis regions lie entirely + outside the reachable range. + For IVS-based tables (HVAR, VVAR, MVAR, GDEF): removes dead region + columns from the ItemVariationStore. + + Args: + varfont: The font being instanced. + reachableRanges: dict mapping axis tags to (lo, hi) tuples representing + the reachable range of old-space final coordinates for that axis. + """ + fvarAxes = varfont["fvar"].axes + + if "gvar" in varfont: + gvar = varfont["gvar"] + totalCulled = 0 + totalTotal = 0 + + for glyphName in gvar.variations: + variations = gvar.variations[glyphName] + newVariations = [] + for tv in variations: + totalTotal += 1 + if _isTupleVariationDead(tv, reachableRanges): + totalCulled += 1 + else: + newVariations.append(tv) + gvar.variations[glyphName] = newVariations + + if totalCulled: + log.info( + "avar2 gvar culling: removed %d / %d TupleVariations (%.1f%%)", + totalCulled, + totalTotal, + 100 * totalCulled / totalTotal if totalTotal else 0, + ) + + if "cvar" in varfont: + cvar = varfont["cvar"] + before = len(cvar.variations) + cvar.variations = [ + tv + for tv in cvar.variations + if not _isTupleVariationDead(tv, reachableRanges) + ] + culled = before - len(cvar.variations) + if culled: + log.info( + "avar2 cvar culling: removed %d / %d TupleVariations (%.1f%%)", + culled, + before, + 100 * culled / before if before else 0, + ) + + # Cull all IVS-based tables. A fixed tag list (like the rest of the + # instancer uses) rather than probing every table in the font, which + # would force-decompile unrelated tables for nothing. + # TODO: VARC's MultiVarStore is not culled here (different structure). + for tag in ("HVAR", "VVAR", "MVAR", "GDEF", "BASE", "COLR"): + if tag not in varfont: + continue + table = varfont[tag] + table = getattr(table, "table", table) + vs = getattr(table, "VarStore", None) + if vs is None: + continue + removed = _cullItemVariationStore(vs, fvarAxes, reachableRanges) + if removed: + log.info( + "avar2 %s culling: removed %d dead region references", + tag, + removed, + ) + + # CFF2: cull via populate/cull/depopulate cycle (blend operators encode + # region counts, so the VarStore can't be culled without updating them). + if "CFF2" in varfont: + cff = varfont["CFF2"].cff + topDict = cff.topDictIndex[0] + if getattr(topDict, "VarStore", None) and topDict.VarStore.otVarStore: + instantiateCFF2( + varfont, + NormalizedAxisLimits({}), + reachableRanges=reachableRanges, + ) + + +def _computeReachableRangesForAvar2(varfont, axisLimits, reachableRanges): + """Compute reachable old-space final-coord ranges using getExtremes. + + For axes not already in reachableRanges (i.e., axes with IVS entries + rather than NO_VARIATION_INDEX), compute conservative bounds on the + reachable old-space final coordinate using getExtremes on the instanced + avar v2 VarStore. + + This is critical for parametric fonts where gvar references private axes + driven by public axes through avar2. Restricting wght narrows the + reachable range of XOPQ, YOPQ, etc. + + Must be called AFTER _instantiateFvarForAvar2 has updated fvar and + VarIdxMap so that axes and VarStore match. + """ + avar = varfont["avar"] + fvarAxes = varfont["fvar"].axes + varStore = getattr(avar.table, "VarStore", None) + if varStore is None: + return + varIdxMap = getattr(avar.table, "VarIdxMap", None) + + # Private axes (originally hidden, not user-restricted) always have + # intermediate coordinate = 0. Any VarStore region referencing them + # as input gets scalar = 0 at intermediate = 0. Tell getExtremes + # by pinning them at (0, 0, 0) so it correctly zeros out those regions. + privateAxisLimits = {} + for axis in fvarAxes: + if axis.flags & 0x1 and axis.axisTag not in axisLimits: + privateAxisLimits[axis.axisTag] = (0, 0, 0) + + for axisIdx, axis in enumerate(fvarAxes): + tag = axis.axisTag + if tag in reachableRanges: + continue # Already computed (NO_VARIATION_INDEX, exact) + + if varIdxMap is not None: + varIdx = varIdxMap[axisIdx] + else: + varIdx = axisIdx + + if varIdx == NO_VARIATION_INDEX: + continue + + # Private axes have no identity term (intermediate always 0, + # final = delta only). Public axes have identity + delta. + private = axis.flags & 0x1 + identityAxisIndex = None if private else axisIdx + + # Pass privateAxisLimits so getExtremes correctly zeros out + # regions referencing private axes (whose intermediate is always 0). + minV, maxV = varStore.getExtremes( + varIdx, fvarAxes, privateAxisLimits, identityAxisIndex + ) + + lo = min(+1, max(-1, minV / 16384)) + hi = min(+1, max(-1, maxV / 16384)) + assert lo <= hi + reachableRanges[tag] = (lo, hi) + + log.info( + "avar2 getExtremes range for %s: [%.4f, %.4f]", + tag, + lo, + hi, + ) + + +def _instantiateFvarForAvar2(varfont, axisLimits, selfContainedAxes=None): + """Update fvar for avar2 partial instancing. + + Self-contained pinned axes (in selfContainedAxes dict) are removed from fvar + and their contributions folded into variation tables. Non-self-contained pinned + axes are kept as hidden axes. Restricted axes have their ranges updated. + """ + fvar = varfont["fvar"] + pinnedLocation = axisLimits.pinnedLocation() + if selfContainedAxes is None: + selfContainedAxes = {} + + log.info("Instantiating fvar table (avar2 mode)") + + # Track removed axis indices for VarIdxMap update + removedAxisIndices = set() + originalAxisCount = len(fvar.axes) + + axes = [] + for axisIdx, axis in enumerate(fvar.axes): + tag = axis.axisTag + if tag in selfContainedAxes: + # Self-contained pinned axis: remove from fvar + removedAxisIndices.add(axisIdx) + continue + if tag in axisLimits: + triple = axisLimits[tag] + defV = triple.default if triple.default is not None else axis.defaultValue + axis.minValue = triple.minimum + axis.defaultValue = defV + axis.maxValue = triple.maximum + if tag in pinnedLocation: + # Non-self-contained pinned: keep as hidden + axis.flags |= 0x0001 # HIDDEN_AXIS + axes.append(axis) + fvar.axes = axes + + # Update avar for removed axes + if removedAxisIndices and "avar" in varfont: + avar = varfont["avar"] + + # Remove segment maps for removed axes + for tag in selfContainedAxes: + avar.segments.pop(tag, None) + + # Update VarIdxMap to reflect new axis positions + if getattr(avar, "majorVersion", 1) >= 2: + varIdxMap = getattr(avar.table, "VarIdxMap", None) + if varIdxMap is not None: + varIdxMap.mapping = [ + varIdxMap.mapping[i] + for i in range(len(varIdxMap.mapping)) + if i not in removedAxisIndices + ] + else: + # Implicit identity mapping: axis i → varIdx i. + # After removing axes, need explicit mapping if non-identity. + varIdxMap = builder.buildDeltaSetIndexMap( + i for i in range(originalAxisCount) if i not in removedAxisIndices + ) + if varIdxMap is not None: + avar.table.VarIdxMap = varIdxMap + + # Filter named instances: keep those within the new ranges + instances = [] + for instance in fvar.instances: + # Check that pinned axis values match + if any( + instance.coordinates.get(tag) != value + for tag, value in pinnedLocation.items() + ): + continue + if not isInstanceWithinAxisRanges(instance.coordinates, axisLimits): + continue + # Remove coordinates for removed axes + for tag in selfContainedAxes: + instance.coordinates.pop(tag, None) + instances.append(instance) + fvar.instances = instances + + +def isInstanceWithinAxisRanges(location, axisRanges): + for axisTag, coord in location.items(): + if axisTag in axisRanges: + axisRange = axisRanges[axisTag] + if coord < axisRange.minimum or coord > axisRange.maximum: + return False + return True + + +def instantiateFvar(varfont, axisLimits): + # 'axisLimits' dict must contain user-space (non-normalized) coordinates + + location = axisLimits.pinnedLocation() + + fvar = varfont["fvar"] + + # drop table if we instantiate all the axes + if set(location).issuperset(axis.axisTag for axis in fvar.axes): + log.info("Dropping fvar table") + del varfont["fvar"] + return + + log.info("Instantiating fvar table") + + axes = [] + for axis in fvar.axes: + axisTag = axis.axisTag + if axisTag in location: + continue + if axisTag in axisLimits: + triple = axisLimits[axisTag] + if triple.default is None: + triple = (triple.minimum, axis.defaultValue, triple.maximum) + axis.minValue, axis.defaultValue, axis.maxValue = triple + axes.append(axis) + fvar.axes = axes + + # only keep NamedInstances whose coordinates == pinned axis location + instances = [] + for instance in fvar.instances: + if any(instance.coordinates[axis] != value for axis, value in location.items()): + continue + for axisTag in location: + del instance.coordinates[axisTag] + if not isInstanceWithinAxisRanges(instance.coordinates, axisLimits): + continue + instances.append(instance) + fvar.instances = instances + + +def instantiateSTAT(varfont, axisLimits): + # 'axisLimits' dict must contain user-space (non-normalized) coordinates + + stat = varfont["STAT"].table + if not stat.DesignAxisRecord or not ( + stat.AxisValueArray and stat.AxisValueArray.AxisValue + ): + return # STAT table empty, nothing to do + + log.info("Instantiating STAT table") + newAxisValueTables = axisValuesFromAxisLimits(stat, axisLimits) + stat.AxisValueCount = len(newAxisValueTables) + if stat.AxisValueCount: + stat.AxisValueArray.AxisValue = newAxisValueTables + else: + stat.AxisValueArray = None + + +def axisValuesFromAxisLimits(stat, axisLimits): + def isAxisValueOutsideLimits(axisTag, axisValue): + if axisTag in axisLimits: + triple = axisLimits[axisTag] + if axisValue < triple.minimum or axisValue > triple.maximum: + return True + return False + + # only keep AxisValues whose axis is not pinned nor restricted, or is pinned at the + # exact (nominal) value, or is restricted but the value is within the new range + designAxes = stat.DesignAxisRecord.Axis + newAxisValueTables = [] + for axisValueTable in stat.AxisValueArray.AxisValue: + axisValueFormat = axisValueTable.Format + if axisValueFormat in (1, 2, 3): + axisTag = designAxes[axisValueTable.AxisIndex].AxisTag + if axisValueFormat == 2: + axisValue = axisValueTable.NominalValue + else: + axisValue = axisValueTable.Value + if isAxisValueOutsideLimits(axisTag, axisValue): + continue + elif axisValueFormat == 4: + # drop 'non-analytic' AxisValue if _any_ AxisValueRecord doesn't match + # the pinned location or is outside range + dropAxisValueTable = False + for rec in axisValueTable.AxisValueRecord: + axisTag = designAxes[rec.AxisIndex].AxisTag + axisValue = rec.Value + if isAxisValueOutsideLimits(axisTag, axisValue): + dropAxisValueTable = True + break + if dropAxisValueTable: + continue + else: + log.warning("Unknown AxisValue table format (%s); ignored", axisValueFormat) + newAxisValueTables.append(axisValueTable) + return newAxisValueTables + + +def setMacOverlapFlags(glyfTable): + flagOverlapCompound = _g_l_y_f.OVERLAP_COMPOUND + flagOverlapSimple = _g_l_y_f.flagOverlapSimple + for glyphName in glyfTable.keys(): + glyph = glyfTable[glyphName] + # Set OVERLAP_COMPOUND bit for compound glyphs + if glyph.isComposite(): + glyph.components[0].flags |= flagOverlapCompound + # Set OVERLAP_SIMPLE bit for simple glyphs + elif glyph.numberOfContours > 0: + glyph.flags[0] |= flagOverlapSimple + + +def normalize(value, triple, avarMapping=None): + value = normalizeValue(value, triple) + if avarMapping: + value = piecewiseLinearMap(value, avarMapping) + # Quantize to F2Dot14, to avoid surprise interpolations. + return floatToFixedToFloat(value, 14) + + +def _instantiateVariationTables(varfont, limits, optimize, downgradeCFF2): + """Instantiate all variation-carrying tables at the given limits. + + Returns the new value of the downgradeCFF2 flag (instantiateCFF2 reports + whether a downgrade to CFF is actually possible, i.e. nothing varies). + """ + if "VARC" in varfont: + instantiateVARC(varfont, limits) + + if "CFF2" in varfont: + downgradeCFF2 = instantiateCFF2(varfont, limits, downgrade=downgradeCFF2) + + if "gvar" in varfont: + instantiateGvar(varfont, limits, optimize=optimize) + + if "cvar" in varfont: + instantiateCvar(varfont, limits) + + if "MVAR" in varfont: + instantiateMVAR(varfont, limits) + + if "HVAR" in varfont: + instantiateHVAR(varfont, limits) + + if "VVAR" in varfont: + instantiateVVAR(varfont, limits) + + instantiateOTL(varfont, limits) + + instantiateFeatureVariations(varfont, limits) + + return downgradeCFF2 + + +def sanityCheckVariableTables(varfont): + if "fvar" not in varfont: + raise ValueError("Missing required table fvar") + if "gvar" in varfont: + if "glyf" not in varfont: + raise ValueError("Can't have gvar without glyf") + + +def instantiateVariableFont( + varfont, + axisLimits, + inplace=False, + optimize=True, + overlap=OverlapMode.KEEP_AND_SET_FLAGS, + updateFontNames=False, + *, + downgradeCFF2=False, + static=False, +): + """Instantiate variable font, either fully or partially. + + Depending on whether the `axisLimits` dictionary references all or some of the + input varfont's axes, the output font will either be a full instance (static + font) or a variable font with possibly less variation data. + + Args: + varfont: a TTFont instance, which must contain at least an 'fvar' table. + axisLimits: a dict keyed by axis tags (str) containing the coordinates (float) + along one or more axes where the desired instance will be located. + If the value is `None`, the default coordinate as per 'fvar' table for + that axis is used. + The limit values can also be (min, max) tuples for restricting an + axis's variation range. The default axis value must be included in + the new range. + inplace (bool): whether to modify input TTFont object in-place instead of + returning a distinct object. + optimize (bool): if False, do not perform IUP-delta optimization on the + remaining 'gvar' table's deltas. Possibly faster, and might work around + rendering issues in some buggy environments, at the cost of a slightly + larger file size. + overlap (OverlapMode): variable fonts usually contain overlapping contours, and + some font rendering engines on Apple platforms require that the + `OVERLAP_SIMPLE` and `OVERLAP_COMPOUND` flags in the 'glyf' table be set to + force rendering using a non-zero fill rule. Thus we always set these flags + on all glyphs to maximise cross-compatibility of the generated instance. + You can disable this by passing OverlapMode.KEEP_AND_DONT_SET_FLAGS. + If you want to remove the overlaps altogether and merge overlapping + contours and components, you can pass OverlapMode.REMOVE (or + REMOVE_AND_IGNORE_ERRORS to not hard-fail on tricky glyphs). Note that this + requires the skia-pathops package (available to pip install). + The overlap parameter only has effect when generating full static instances. + updateFontNames (bool): if True, update the instantiated font's name table using + the Axis Value Tables from the STAT table. The name table and the style bits + in the head and OS/2 table will be updated so they conform to the R/I/B/BI + model. If the STAT table is missing or an Axis Value table is missing for + a given axis coordinate, a ValueError will be raised. + downgradeCFF2 (bool): if True, downgrade the CFF2 table to CFF table when possible + ie. full instancing of all axes. This is useful for compatibility with older + software that does not support CFF2. Defaults to False. Note that this + operation also removes overlaps within glyph shapes, as CFF does not support + overlaps but CFF2 does. + static (bool): if True, generate a full instance (static font) instead of a partial + instance (variable font). + """ + # 'overlap' used to be bool and is now enum; for backward compat keep accepting bool + overlap = OverlapMode(int(overlap)) + + sanityCheckVariableTables(varfont) + + if static: + unspecified = [] + for axis in varfont["fvar"].axes: + if axis.axisTag not in axisLimits: + axisLimits[axis.axisTag] = None + unspecified.append(axis.axisTag) + if unspecified: + log.info("Pinning unspecified axes to default: %s", unspecified) + + axisLimits = AxisLimits(axisLimits).limitAxesAndPopulateDefaults(varfont) + + log.info("Restricted limits: %s", axisLimits) + + normalizedLimits = axisLimits.normalize(varfont) + + log.info("Normalized limits: %s", normalizedLimits) + + if not inplace: + varfont = deepcopy(varfont) + + if "DSIG" in varfont: + del varfont["DSIG"] + + if updateFontNames: + log.info("Updating name table") + names.updateNameTable(varfont, axisLimits) + + # Detect avar2 partial instancing: avar version 2, and not all fvar axes + # are pinned. In this mode, variation tables (gvar, HVAR, etc.) are kept + # in the old final-coordinate space, and the avar v2 offset compensation + # ensures the correct old-space final coordinates are produced. A version + # 2 font is never downgraded to v1 — even with a NULL/empty VarStore, the + # avar2 path applies (offset compensation creates rows on demand). + _isAvar2PartialInstancing = ( + "avar" in varfont + and getattr(varfont["avar"], "majorVersion", 1) >= 2 + and not set(axisLimits.pinnedLocation()).issuperset( + a.axisTag for a in varfont["fvar"].axes + ) + ) + + if _isAvar2PartialInstancing: + log.info( + "avar2 partial instancing: keeping variation tables in old " + "coordinate space" + ) + if downgradeCFF2: + # The result of avar2 partial instancing is still variable, so a + # downgrade to CFF is never possible. + log.warning("downgradeCFF2 is ignored for avar2 partial instancing") + downgradeCFF2 = False + else: + downgradeCFF2 = _instantiateVariationTables( + varfont, normalizedLimits, optimize, downgradeCFF2 + ) + + # For avar2 partial instancing, compute old intermediate values BEFORE + # avar instancing modifies the segments. Used for both NO_VARIATION_INDEX + # reachable ranges and offset compensation in _instantiateAvarV2. + reachableRanges = {} + oldIntermediates = None + if _isAvar2PartialInstancing: + oldIntermediates = _computeOldIntermediates(varfont, axisLimits) + + # For NO_VARIATION_INDEX axes (no IVS delta), the final coord equals + # the intermediate coord, so the reachable range is [a_i, b_i]. + avar = varfont["avar"] + varStore = getattr(avar.table, "VarStore", None) + varIdxMap = getattr(avar.table, "VarIdxMap", None) + fvarAxes = varfont["fvar"].axes + + for axisIdx, axis in enumerate(fvarAxes): + tag = axis.axisTag + if tag not in axisLimits: + continue + triple = axisLimits[tag] + if triple.minimum == triple.maximum: + continue # Pinned axis, not restricted + if tag not in oldIntermediates: + continue + + if ( + _effectiveAvar2VarIdx(varStore, varIdxMap, axisIdx) + == NO_VARIATION_INDEX + ): + a_i, d_i, b_i = oldIntermediates[tag] + reachableRanges[tag] = (min(a_i, b_i), max(a_i, b_i)) + + selfContainedAxes = {} + if "avar" in varfont: + selfContainedAxes = ( + instantiateAvar(varfont, axisLimits, normalizedLimits, oldIntermediates) + or {} + ) + + # For avar2 partial instancing, run variation instancing for + # self-contained pinned axes (those that can be removed from fvar). + # These axes have a constant old-space final coordinate, so we can + # fold their contributions into gvar/HVAR/etc. at that coordinate. + if _isAvar2PartialInstancing and selfContainedAxes: + scLimits = NormalizedAxisLimits( + { + tag: NormalizedAxisTripleAndDistances(v, v, v) + for tag, v in selfContainedAxes.items() + } + ) + log.info( + "Instancing variation tables for self-contained axes: %s", + list(selfContainedAxes), + ) + + downgradeCFF2 = _instantiateVariationTables( + varfont, scLimits, optimize, downgradeCFF2 + ) + + with names.pruningUnusedNames(varfont): + if "STAT" in varfont: + instantiateSTAT(varfont, axisLimits) + + if _isAvar2PartialInstancing: + _instantiateFvarForAvar2(varfont, axisLimits, selfContainedAxes) + else: + instantiateFvar(varfont, axisLimits) + + # Cull dead gvar/cvar regions outside reachable old-space final-coord + # ranges. Must be after _instantiateFvarForAvar2 so fvar and VarStore + # axis orders match for getExtremes. + if _isAvar2PartialInstancing: + # Extend reachable ranges for axes with IVS entries (conservative + # bounds via getExtremes on the instanced avar v2 VarStore). + _computeReachableRangesForAvar2(varfont, axisLimits, reachableRanges) + + if reachableRanges: + _cullVariationsForAvar2(varfont, reachableRanges) + + if "OS/2" in varfont: + varfont["OS/2"].recalcAvgCharWidth(varfont) + + varLib.set_default_weight_width_slant( + varfont, location=axisLimits.defaultLocation() + ) + + if updateFontNames: + # Set Regular/Italic/Bold/Bold Italic bits as appropriate, after the + # name table has been updated. + setRibbiBits(varfont) + + if downgradeCFF2: + origVarfont = varfont + varfont = downgradeCFF2ToCFF(varfont) + if inplace: + origVarfont.__dict__ = varfont.__dict__.copy() + + if "fvar" not in varfont: + if overlap == OverlapMode.KEEP_AND_SET_FLAGS: + if "glyf" in varfont: + setMacOverlapFlags(varfont["glyf"]) + elif overlap in (OverlapMode.REMOVE, OverlapMode.REMOVE_AND_IGNORE_ERRORS): + from fontTools.ttLib.removeOverlaps import removeOverlaps + + log.info("Removing glyph outlines overlaps") + removeOverlaps( + varfont, + ignoreErrors=(overlap == OverlapMode.REMOVE_AND_IGNORE_ERRORS), + ) + + return varfont + + +def setRibbiBits(font): + """Set the `head.macStyle` and `OS/2.fsSelection` style bits + appropriately.""" + + english_ribbi_style = font["name"].getName(names.NameID.SUBFAMILY_NAME, 3, 1, 0x409) + if english_ribbi_style is None: + return + + styleMapStyleName = english_ribbi_style.toStr().lower() + if styleMapStyleName not in {"regular", "bold", "italic", "bold italic"}: + return + + if styleMapStyleName == "bold": + font["head"].macStyle = 0b01 + elif styleMapStyleName == "bold italic": + font["head"].macStyle = 0b11 + elif styleMapStyleName == "italic": + font["head"].macStyle = 0b10 + + selection = font["OS/2"].fsSelection + # First clear... + selection &= ~(1 << 0) + selection &= ~(1 << 5) + selection &= ~(1 << 6) + # ...then re-set the bits. + if styleMapStyleName == "regular": + selection |= 1 << 6 + elif styleMapStyleName == "bold": + selection |= 1 << 5 + elif styleMapStyleName == "italic": + selection |= 1 << 0 + elif styleMapStyleName == "bold italic": + selection |= 1 << 0 + selection |= 1 << 5 + font["OS/2"].fsSelection = selection + + +def parseLimits(limits: Iterable[str]) -> Dict[str, Optional[AxisTriple]]: + result = {} + for limitString in limits: + match = re.match( + r"^(\w{1,4})=(?:(drop)|(?:([^:]*)(?:[:]([^:]*))?(?:[:]([^:]*))?))$", + limitString, + ) + if not match: + raise ValueError("invalid location format: %r" % limitString) + tag = match.group(1).ljust(4) + + if match.group(2): # 'drop' + result[tag] = None + continue + + triple = match.group(3, 4, 5) + + if triple[1] is None: # "value" syntax + triple = (triple[0], triple[0], triple[0]) + elif triple[2] is None: # "min:max" syntax + triple = (triple[0], None, triple[1]) + + triple = tuple(float(v) if v else None for v in triple) + + result[tag] = AxisTriple(*triple) + + return result + + +def parseArgs(args): + """Parse argv. + + Returns: + 3-tuple (infile, axisLimits, options) + axisLimits is either a Dict[str, Optional[float]], for pinning variation axes + to specific coordinates along those axes (with `None` as a placeholder for an + axis' default value); or a Dict[str, Tuple(float, float)], meaning limit this + axis to min/max range. + Axes locations are in user-space coordinates, as defined in the "fvar" table. + """ + from fontTools import configLogger + import argparse + + parser = argparse.ArgumentParser( + "fonttools varLib.instancer", + description="Partially instantiate a variable font", + ) + parser.add_argument("input", metavar="INPUT.ttf", help="Input variable TTF file.") + parser.add_argument( + "locargs", + metavar="AXIS=LOC", + nargs="*", + help="List of space separated locations. A location consists of " + "the tag of a variation axis, followed by '=' and the literal, " + "string 'drop', or colon-separated list of one to three values, " + "each of which is the empty string, or a number. " + "E.g.: wdth=100 or wght=75.0:125.0 or wght=100:400:700 or wght=:500: " + "or wght=drop", + ) + parser.add_argument( + "-o", + "--output", + metavar="OUTPUT.ttf", + default=None, + help="Output instance TTF file (default: INPUT-instance.ttf).", + ) + parser.add_argument( + "--static", + dest="static", + action="store_true", + help="Make a static font: pin unspecified axes to their default location.", + ) + parser.add_argument( + "--no-optimize", + dest="optimize", + action="store_false", + help="Don't perform IUP optimization on the remaining gvar TupleVariations", + ) + parser.add_argument( + "--no-overlap-flag", + dest="overlap", + action="store_false", + help="Don't set OVERLAP_SIMPLE/OVERLAP_COMPOUND glyf flags (only applicable " + "when generating a full instance)", + ) + parser.add_argument( + "--remove-overlaps", + dest="remove_overlaps", + action="store_true", + help="Merge overlapping contours and components (only applicable " + "when generating a full instance). Requires skia-pathops", + ) + parser.add_argument( + "--ignore-overlap-errors", + dest="ignore_overlap_errors", + action="store_true", + help="Don't crash if the remove-overlaps operation fails for some glyphs.", + ) + parser.add_argument( + "--update-name-table", + action="store_true", + help="Update the instantiated font's `name` table. Input font must have " + "a STAT table with Axis Value Tables", + ) + parser.add_argument( + "--downgrade-cff2", + action="store_true", + help="If all axes are pinned, downgrade CFF2 to CFF table format", + ) + parser.add_argument( + "--no-recalc-timestamp", + dest="recalc_timestamp", + action="store_false", + help="Don't set the output font's timestamp to the current time.", + ) + parser.add_argument( + "--no-recalc-bounds", + dest="recalc_bounds", + action="store_false", + help="Don't recalculate font bounding boxes", + ) + loggingGroup = parser.add_mutually_exclusive_group(required=False) + loggingGroup.add_argument( + "-v", "--verbose", action="store_true", help="Run more verbosely." + ) + loggingGroup.add_argument( + "-q", "--quiet", action="store_true", help="Turn verbosity off." + ) + options = parser.parse_args(args) + + if options.remove_overlaps: + if options.ignore_overlap_errors: + options.overlap = OverlapMode.REMOVE_AND_IGNORE_ERRORS + else: + options.overlap = OverlapMode.REMOVE + else: + options.overlap = OverlapMode(int(options.overlap)) + + infile = options.input + if not os.path.isfile(infile): + parser.error("No such file '{}'".format(infile)) + + configLogger( + level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO") + ) + + try: + axisLimits = parseLimits(options.locargs) + except ValueError as e: + parser.error(str(e)) + + if len(axisLimits) != len(options.locargs): + parser.error("Specified multiple limits for the same axis") + + return (infile, axisLimits, options) + + +def main(args=None): + """Partially instantiate a variable font""" + infile, axisLimits, options = parseArgs(args) + log.info("Restricting axes: %s", axisLimits) + + log.info("Loading variable font") + varfont = TTFont( + infile, + recalcTimestamp=options.recalc_timestamp, + recalcBBoxes=options.recalc_bounds, + ) + + isFullInstance = options.static or { + axisTag + for axisTag, limit in axisLimits.items() + if limit is None or limit[0] == limit[2] + }.issuperset(axis.axisTag for axis in varfont["fvar"].axes) + + varfont = instantiateVariableFont( + varfont, + axisLimits, + inplace=True, + optimize=options.optimize, + overlap=options.overlap, + updateFontNames=options.update_name_table, + downgradeCFF2=options.downgrade_cff2, + static=options.static, + ) + + suffix = "-instance" if isFullInstance else "-partial" + outfile = ( + makeOutputFileName(infile, overWrite=True, suffix=suffix) + if not options.output + else options.output + ) + + log.info( + "Saving %s font %s", + "instance" if isFullInstance else "partial variable", + outfile, + ) + varfont.save(outfile) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__main__.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..64ffff2b9fdf58d8a557de7c1ae631b5c6fb4b6f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__main__.py @@ -0,0 +1,5 @@ +import sys +from fontTools.varLib.instancer import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68cbeb55a1f5d8ebd7709a99aabc1f3c9dcdd3ad --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/__init__.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09202c827639f7ec981baee36e035697f80721326cac1e3acde39c0285b4f367 +size 115471 diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aaac04ca4b0af6c4b815c45e18a47e24720f3947 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/__main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/featureVars.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/featureVars.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4467f340af7ee1b46d5a9ac4f34cdc494a97a698 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/featureVars.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/names.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/names.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3307bed64adb364ca6ccd69dda3959108d8dc2f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/names.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/solver.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/solver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e794e2500024168f3d907f89c3cf13ce485e9b7c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/solver.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/featureVars.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/featureVars.py new file mode 100644 index 0000000000000000000000000000000000000000..c647b77cb1ece35f226873a4ddd0c4dce33d8590 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/featureVars.py @@ -0,0 +1,189 @@ +from fontTools.ttLib.tables import otTables as ot +from copy import deepcopy +import logging + +log = logging.getLogger("fontTools.varLib.instancer") + + +def _featureVariationRecordIsUnique(rec, seen): + conditionSet = [] + conditionSets = ( + rec.ConditionSet.ConditionTable if rec.ConditionSet is not None else [] + ) + for cond in conditionSets: + if cond.Format != 1: + # can't tell whether this is duplicate, assume is unique + return True + conditionSet.append( + (cond.AxisIndex, cond.FilterRangeMinValue, cond.FilterRangeMaxValue) + ) + # besides the set of conditions, we also include the FeatureTableSubstitution + # version to identify unique FeatureVariationRecords, even though only one + # version is currently defined. It's theoretically possible that multiple + # records with same conditions but different substitution table version be + # present in the same font for backward compatibility. + recordKey = frozenset([rec.FeatureTableSubstitution.Version] + conditionSet) + if recordKey in seen: + return False + else: + seen.add(recordKey) # side effect + return True + + +def _limitFeatureVariationConditionRange(condition, axisLimit): + minValue = condition.FilterRangeMinValue + maxValue = condition.FilterRangeMaxValue + + if ( + minValue > maxValue + or minValue > axisLimit.maximum + or maxValue < axisLimit.minimum + ): + # condition invalid or out of range + return + + return tuple( + axisLimit.renormalizeValue(v, extrapolate=False) for v in (minValue, maxValue) + ) + + +def _instantiateFeatureVariationRecord( + record, recIdx, axisLimits, fvarAxes, axisIndexMap +): + applies = True + shouldKeep = False + newConditions = [] + from fontTools.varLib.instancer import NormalizedAxisTripleAndDistances + + default_triple = NormalizedAxisTripleAndDistances(-1, 0, +1) + if record.ConditionSet is None: + record.ConditionSet = ot.ConditionSet() + record.ConditionSet.ConditionTable = [] + record.ConditionSet.ConditionCount = 0 + for i, condition in enumerate(record.ConditionSet.ConditionTable): + if condition.Format == 1: + axisIdx = condition.AxisIndex + axisTag = fvarAxes[axisIdx].axisTag + + minValue = condition.FilterRangeMinValue + maxValue = condition.FilterRangeMaxValue + triple = axisLimits.get(axisTag, default_triple) + + if not (minValue <= triple.default <= maxValue): + applies = False + + # if condition not met, remove entire record + if triple.minimum > maxValue or triple.maximum < minValue: + newConditions = None + break + + if axisTag in axisIndexMap: + # remap axis index + condition.AxisIndex = axisIndexMap[axisTag] + + # remap condition limits + newRange = _limitFeatureVariationConditionRange(condition, triple) + if newRange: + # keep condition with updated limits + minimum, maximum = newRange + condition.FilterRangeMinValue = minimum + condition.FilterRangeMaxValue = maximum + shouldKeep = True + if minimum != -1 or maximum != +1: + newConditions.append(condition) + else: + # condition out of range, remove entire record + newConditions = None + break + + else: + log.warning( + "Condition table {0} of FeatureVariationRecord {1} has " + "unsupported format ({2}); ignored".format(i, recIdx, condition.Format) + ) + applies = False + newConditions.append(condition) + + if newConditions is not None and shouldKeep: + record.ConditionSet.ConditionTable = newConditions + if not newConditions: + record.ConditionSet = None + shouldKeep = True + else: + shouldKeep = False + + # Does this *always* apply? + universal = shouldKeep and not newConditions + + return applies, shouldKeep, universal + + +def _instantiateFeatureVariations(table, fvarAxes, axisLimits): + pinnedAxes = set(axisLimits.pinnedLocation()) + axisOrder = [axis.axisTag for axis in fvarAxes if axis.axisTag not in pinnedAxes] + axisIndexMap = {axisTag: axisOrder.index(axisTag) for axisTag in axisOrder} + + featureVariationApplied = False + uniqueRecords = set() + newRecords = [] + defaultsSubsts = None + + for i, record in enumerate(table.FeatureVariations.FeatureVariationRecord): + applies, shouldKeep, universal = _instantiateFeatureVariationRecord( + record, i, axisLimits, fvarAxes, axisIndexMap + ) + + if shouldKeep and _featureVariationRecordIsUnique(record, uniqueRecords): + newRecords.append(record) + + if applies and not featureVariationApplied: + assert record.FeatureTableSubstitution.Version == 0x00010000 + defaultsSubsts = deepcopy(record.FeatureTableSubstitution) + for default, rec in zip( + defaultsSubsts.SubstitutionRecord, + record.FeatureTableSubstitution.SubstitutionRecord, + ): + default.Feature = deepcopy( + table.FeatureList.FeatureRecord[rec.FeatureIndex].Feature + ) + table.FeatureList.FeatureRecord[rec.FeatureIndex].Feature = deepcopy( + rec.Feature + ) + # Set variations only once + featureVariationApplied = True + + # Further records don't have a chance to apply after a universal record + if universal: + break + + # Insert a catch-all record to reinstate the old features if necessary + if featureVariationApplied and newRecords and not universal: + defaultRecord = ot.FeatureVariationRecord() + defaultRecord.ConditionSet = ot.ConditionSet() + defaultRecord.ConditionSet.ConditionTable = [] + defaultRecord.ConditionSet.ConditionCount = 0 + defaultRecord.FeatureTableSubstitution = defaultsSubsts + + newRecords.append(defaultRecord) + + if newRecords: + table.FeatureVariations.FeatureVariationRecord = newRecords + table.FeatureVariations.FeatureVariationCount = len(newRecords) + else: + del table.FeatureVariations + # downgrade table version if there are no FeatureVariations left + table.Version = 0x00010000 + + +def instantiateFeatureVariations(varfont, axisLimits): + for tableTag in ("GPOS", "GSUB"): + if tableTag not in varfont or not getattr( + varfont[tableTag].table, "FeatureVariations", None + ): + continue + log.info("Instantiating FeatureVariations of %s table", tableTag) + _instantiateFeatureVariations( + varfont[tableTag].table, varfont["fvar"].axes, axisLimits + ) + # remove unreferenced lookups + varfont[tableTag].prune_lookups() diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/names.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/names.py new file mode 100644 index 0000000000000000000000000000000000000000..f9454688e06597b8eb984b658cd0d5d19eece601 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/names.py @@ -0,0 +1,388 @@ +"""Helpers for instantiating name table records.""" + +from contextlib import contextmanager +from copy import deepcopy +from enum import IntEnum +import re + + +class NameID(IntEnum): + FAMILY_NAME = 1 + SUBFAMILY_NAME = 2 + UNIQUE_FONT_IDENTIFIER = 3 + FULL_FONT_NAME = 4 + VERSION_STRING = 5 + POSTSCRIPT_NAME = 6 + TYPOGRAPHIC_FAMILY_NAME = 16 + TYPOGRAPHIC_SUBFAMILY_NAME = 17 + VARIATIONS_POSTSCRIPT_NAME_PREFIX = 25 + + +ELIDABLE_AXIS_VALUE_NAME = 2 + + +def getVariationNameIDs(varfont): + used = [] + if "fvar" in varfont: + fvar = varfont["fvar"] + for axis in fvar.axes: + used.append(axis.axisNameID) + for instance in fvar.instances: + used.append(instance.subfamilyNameID) + if instance.postscriptNameID != 0xFFFF: + used.append(instance.postscriptNameID) + if "STAT" in varfont: + stat = varfont["STAT"].table + for axis in stat.DesignAxisRecord.Axis if stat.DesignAxisRecord else (): + used.append(axis.AxisNameID) + for value in stat.AxisValueArray.AxisValue if stat.AxisValueArray else (): + used.append(value.ValueNameID) + elidedFallbackNameID = getattr(stat, "ElidedFallbackNameID", None) + if elidedFallbackNameID is not None: + used.append(elidedFallbackNameID) + # nameIDs <= 255 are reserved by OT spec so we don't touch them + return {nameID for nameID in used if nameID > 255} + + +@contextmanager +def pruningUnusedNames(varfont): + from . import log + + origNameIDs = getVariationNameIDs(varfont) + + yield + + log.info("Pruning name table") + exclude = origNameIDs - getVariationNameIDs(varfont) + varfont["name"].names[:] = [ + record for record in varfont["name"].names if record.nameID not in exclude + ] + if "ltag" in varfont: + # Drop the whole 'ltag' table if all the language-dependent Unicode name + # records that reference it have been dropped. + # TODO: Only prune unused ltag tags, renumerating langIDs accordingly. + # Note ltag can also be used by feat or morx tables, so check those too. + if not any( + record + for record in varfont["name"].names + if record.platformID == 0 and record.langID != 0xFFFF + ): + del varfont["ltag"] + + +def updateNameTable(varfont, axisLimits): + """Update instatiated variable font's name table using STAT AxisValues. + + Raises ValueError if the STAT table is missing or an Axis Value table is + missing for requested axis locations. + + First, collect all STAT AxisValues that match the new default axis locations + (excluding "elided" ones); concatenate the strings in design axis order, + while giving priority to "synthetic" values (Format 4), to form the + typographic subfamily name associated with the new default instance. + Finally, update all related records in the name table, making sure that + legacy family/sub-family names conform to the the R/I/B/BI (Regular, Italic, + Bold, Bold Italic) naming model. + + Example: Updating a partial variable font: + | >>> ttFont = TTFont("OpenSans[wdth,wght].ttf") + | >>> updateNameTable(ttFont, {"wght": (400, 900), "wdth": 75}) + + The name table records will be updated in the following manner: + NameID 1 familyName: "Open Sans" --> "Open Sans Condensed" + NameID 2 subFamilyName: "Regular" --> "Regular" + NameID 3 Unique font identifier: "3.000;GOOG;OpenSans-Regular" --> \ + "3.000;GOOG;OpenSans-Condensed" + NameID 4 Full font name: "Open Sans Regular" --> "Open Sans Condensed" + NameID 6 PostScript name: "OpenSans-Regular" --> "OpenSans-Condensed" + NameID 16 Typographic Family name: None --> "Open Sans" + NameID 17 Typographic Subfamily name: None --> "Condensed" + + References: + https://docs.microsoft.com/en-us/typography/opentype/spec/stat + https://docs.microsoft.com/en-us/typography/opentype/spec/name#name-ids + """ + from . import AxisLimits, axisValuesFromAxisLimits + + if "STAT" not in varfont: + raise ValueError("Cannot update name table since there is no STAT table.") + stat = varfont["STAT"].table + if not stat.AxisValueArray: + raise ValueError("Cannot update name table since there are no STAT Axis Values") + fvar = varfont["fvar"] + + # The updated name table will reflect the new 'zero origin' of the font. + # If we're instantiating a partial font, we will populate the unpinned + # axes with their default axis values from fvar. + axisLimits = AxisLimits(axisLimits).limitAxesAndPopulateDefaults(varfont) + partialDefaults = axisLimits.defaultLocation() + fvarDefaults = {a.axisTag: a.defaultValue for a in fvar.axes} + defaultAxisCoords = AxisLimits({**fvarDefaults, **partialDefaults}) + assert all(v.minimum == v.maximum for v in defaultAxisCoords.values()) + + axisValueTables = axisValuesFromAxisLimits(stat, defaultAxisCoords) + checkAxisValuesExist(stat, axisValueTables, defaultAxisCoords.pinnedLocation()) + + # ignore "elidable" axis values, should be omitted in application font menus. + axisValueTables = [ + v for v in axisValueTables if not v.Flags & ELIDABLE_AXIS_VALUE_NAME + ] + axisValueTables = _sortAxisValues(axisValueTables) + _updateNameRecords(varfont, axisValueTables) + + +def checkAxisValuesExist(stat, axisValues, axisCoords): + seen = set() + designAxes = stat.DesignAxisRecord.Axis + hasValues = set() + for value in stat.AxisValueArray.AxisValue: + if value.Format in (1, 2, 3): + hasValues.add(designAxes[value.AxisIndex].AxisTag) + elif value.Format == 4: + for rec in value.AxisValueRecord: + hasValues.add(designAxes[rec.AxisIndex].AxisTag) + + for axisValueTable in axisValues: + axisValueFormat = axisValueTable.Format + if axisValueTable.Format in (1, 2, 3): + axisTag = designAxes[axisValueTable.AxisIndex].AxisTag + if axisValueFormat == 2: + axisValue = axisValueTable.NominalValue + else: + axisValue = axisValueTable.Value + if axisTag in axisCoords and axisValue == axisCoords[axisTag]: + seen.add(axisTag) + elif axisValueTable.Format == 4: + for rec in axisValueTable.AxisValueRecord: + axisTag = designAxes[rec.AxisIndex].AxisTag + if axisTag in axisCoords and rec.Value == axisCoords[axisTag]: + seen.add(axisTag) + + missingAxes = (set(axisCoords) - seen) & hasValues + if missingAxes: + missing = ", ".join(f"'{i}': {axisCoords[i]}" for i in missingAxes) + raise ValueError(f"Cannot find Axis Values {{{missing}}}") + + +def _sortAxisValues(axisValues): + # Sort by axis index, remove duplicates and ensure that format 4 AxisValues + # are dominant. + # The MS Spec states: "if a format 1, format 2 or format 3 table has a + # (nominal) value used in a format 4 table that also has values for + # other axes, the format 4 table, being the more specific match, is used", + # https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-value-table-format-4 + results = [] + seenAxes = set() + # Sort format 4 axes so the tables with the most AxisValueRecords are first + format4 = sorted( + [v for v in axisValues if v.Format == 4], + key=lambda v: len(v.AxisValueRecord), + reverse=True, + ) + + for val in format4: + axisIndexes = set(r.AxisIndex for r in val.AxisValueRecord) + minIndex = min(axisIndexes) + if not seenAxes & axisIndexes: + seenAxes |= axisIndexes + results.append((minIndex, val)) + + for val in axisValues: + if val in format4: + continue + axisIndex = val.AxisIndex + if axisIndex not in seenAxes: + seenAxes.add(axisIndex) + results.append((axisIndex, val)) + + return [axisValue for _, axisValue in sorted(results)] + + +def _updateNameRecords(varfont, axisValues): + # Update nametable based on the axisValues using the R/I/B/BI model. + nametable = varfont["name"] + stat = varfont["STAT"].table + + axisValueNameIDs = [a.ValueNameID for a in axisValues] + ribbiNameIDs = [n for n in axisValueNameIDs if _isRibbi(nametable, n)] + nonRibbiNameIDs = [n for n in axisValueNameIDs if n not in ribbiNameIDs] + elidedNameID = stat.ElidedFallbackNameID + elidedNameIsRibbi = _isRibbi(nametable, elidedNameID) + + getName = nametable.getName + platforms = set((r.platformID, r.platEncID, r.langID) for r in nametable.names) + for platform in platforms: + if not all(getName(i, *platform) for i in (1, 2, elidedNameID)): + # Since no family name and subfamily name records were found, + # we cannot update this set of name Records. + continue + + subFamilyName = " ".join( + getName(n, *platform).toUnicode() for n in ribbiNameIDs + ) + if nonRibbiNameIDs: + typoSubFamilyName = " ".join( + getName(n, *platform).toUnicode() for n in axisValueNameIDs + ) + else: + typoSubFamilyName = None + + # If neither subFamilyName and typographic SubFamilyName exist, + # we will use the STAT's elidedFallbackName + if not typoSubFamilyName and not subFamilyName: + if elidedNameIsRibbi: + subFamilyName = getName(elidedNameID, *platform).toUnicode() + else: + typoSubFamilyName = getName(elidedNameID, *platform).toUnicode() + + familyNameSuffix = " ".join( + getName(n, *platform).toUnicode() for n in nonRibbiNameIDs + ) + + _updateNameTableStyleRecords( + varfont, + familyNameSuffix, + subFamilyName, + typoSubFamilyName, + *platform, + ) + + +def _isRibbi(nametable, nameID): + englishRecord = nametable.getName(nameID, 3, 1, 0x409) + return ( + True + if englishRecord is not None + and englishRecord.toUnicode() in ("Regular", "Italic", "Bold", "Bold Italic") + else False + ) + + +def _updateNameTableStyleRecords( + varfont, + familyNameSuffix, + subFamilyName, + typoSubFamilyName, + platformID=3, + platEncID=1, + langID=0x409, +): + # TODO (Marc F) It may be nice to make this part a standalone + # font renamer in the future. + nametable = varfont["name"] + platform = (platformID, platEncID, langID) + + currentFamilyName = nametable.getName( + NameID.TYPOGRAPHIC_FAMILY_NAME, *platform + ) or nametable.getName(NameID.FAMILY_NAME, *platform) + + currentStyleName = nametable.getName( + NameID.TYPOGRAPHIC_SUBFAMILY_NAME, *platform + ) or nametable.getName(NameID.SUBFAMILY_NAME, *platform) + + if not all([currentFamilyName, currentStyleName]): + raise ValueError(f"Missing required NameIDs 1 and 2 for platform {platform}") + + currentFamilyName = currentFamilyName.toUnicode() + currentStyleName = currentStyleName.toUnicode() + + nameIDs = { + NameID.FAMILY_NAME: currentFamilyName, + NameID.SUBFAMILY_NAME: subFamilyName or "Regular", + } + if typoSubFamilyName: + nameIDs[NameID.FAMILY_NAME] = f"{currentFamilyName} {familyNameSuffix}".strip() + nameIDs[NameID.TYPOGRAPHIC_FAMILY_NAME] = currentFamilyName + nameIDs[NameID.TYPOGRAPHIC_SUBFAMILY_NAME] = typoSubFamilyName + else: + # Remove previous Typographic Family and SubFamily names since they're + # no longer required + for nameID in ( + NameID.TYPOGRAPHIC_FAMILY_NAME, + NameID.TYPOGRAPHIC_SUBFAMILY_NAME, + ): + nametable.removeNames(nameID=nameID) + + newFamilyName = ( + nameIDs.get(NameID.TYPOGRAPHIC_FAMILY_NAME) or nameIDs[NameID.FAMILY_NAME] + ) + newStyleName = ( + nameIDs.get(NameID.TYPOGRAPHIC_SUBFAMILY_NAME) or nameIDs[NameID.SUBFAMILY_NAME] + ) + + nameIDs[NameID.FULL_FONT_NAME] = f"{newFamilyName} {newStyleName}" + nameIDs[NameID.POSTSCRIPT_NAME] = _updatePSNameRecord( + varfont, newFamilyName, newStyleName, platform + ) + + uniqueID = _updateUniqueIdNameRecord(varfont, nameIDs, platform) + if uniqueID: + nameIDs[NameID.UNIQUE_FONT_IDENTIFIER] = uniqueID + + for nameID, string in nameIDs.items(): + assert string, nameID + nametable.setName(string, nameID, *platform) + + if "fvar" not in varfont: + nametable.removeNames(NameID.VARIATIONS_POSTSCRIPT_NAME_PREFIX) + + +def _updatePSNameRecord(varfont, familyName, styleName, platform): + # Implementation based on Adobe Technical Note #5902 : + # https://wwwimages2.adobe.com/content/dam/acom/en/devnet/font/pdfs/5902.AdobePSNameGeneration.pdf + nametable = varfont["name"] + + family_prefix = nametable.getName( + NameID.VARIATIONS_POSTSCRIPT_NAME_PREFIX, *platform + ) + if family_prefix: + family_prefix = family_prefix.toUnicode() + else: + family_prefix = familyName + + psName = f"{family_prefix}-{styleName}" + # Remove any characters other than uppercase Latin letters, lowercase + # Latin letters, digits and hyphens. + psName = re.sub(r"[^A-Za-z0-9-]", r"", psName) + + if len(psName) > 127: + # Abbreviating the stylename so it fits within 127 characters whilst + # conforming to every vendor's specification is too complex. Instead + # we simply truncate the psname and add the required "..." + return f"{psName[:124]}..." + return psName + + +def _updateUniqueIdNameRecord(varfont, nameIDs, platform): + nametable = varfont["name"] + currentRecord = nametable.getName(NameID.UNIQUE_FONT_IDENTIFIER, *platform) + if not currentRecord: + return None + + # Check if full name and postscript name are a substring of currentRecord + for nameID in (NameID.FULL_FONT_NAME, NameID.POSTSCRIPT_NAME): + nameRecord = nametable.getName(nameID, *platform) + if not nameRecord: + continue + if nameRecord.toUnicode() in currentRecord.toUnicode(): + return currentRecord.toUnicode().replace( + nameRecord.toUnicode(), nameIDs[nameRecord.nameID] + ) + + # Create a new string since we couldn't find any substrings. + fontVersion = _fontVersion(varfont, platform) + achVendID = varfont["OS/2"].achVendID + # Remove non-ASCII characers and trailing spaces + vendor = re.sub(r"[^\x00-\x7F]", "", achVendID).strip() + psName = nameIDs[NameID.POSTSCRIPT_NAME] + return f"{fontVersion};{vendor};{psName}" + + +def _fontVersion(font, platform=(3, 1, 0x409)): + nameRecord = font["name"].getName(NameID.VERSION_STRING, *platform) + if nameRecord is None: + return f'{font["head"].fontRevision:.3f}' + # "Version 1.101; ttfautohint (v1.8.1.43-b0c9)" --> "1.101" + # Also works fine with inputs "Version 1.101" or "1.101" etc + versionNumber = nameRecord.toUnicode().split(";")[0] + return versionNumber.lstrip("Version ").strip() diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/solver.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/solver.py new file mode 100644 index 0000000000000000000000000000000000000000..ba5231b796795259f9b7a471242e142d48623b0e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/solver.py @@ -0,0 +1,309 @@ +from fontTools.varLib.models import supportScalar +from fontTools.misc.fixedTools import MAX_F2DOT14 +from functools import lru_cache + +__all__ = ["rebaseTent"] + +EPSILON = 1 / (1 << 14) + + +def _reverse_negate(v): + return (-v[2], -v[1], -v[0]) + + +def _solve(tent, axisLimit, negative=False): + axisMin, axisDef, axisMax, _distanceNegative, _distancePositive = axisLimit + lower, peak, upper = tent + + # Mirror the problem such that axisDef <= peak + if axisDef > peak: + return [ + (scalar, _reverse_negate(t) if t is not None else None) + for scalar, t in _solve( + _reverse_negate(tent), + axisLimit.reverse_negate(), + not negative, + ) + ] + # axisDef <= peak + + # case 1: The whole deltaset falls outside the new limit; we can drop it + # + # peak + # 1.........................................o.......... + # / \ + # / \ + # / \ + # / \ + # 0---|-----------|----------|-------- o o----1 + # axisMin axisDef axisMax lower upper + # + if axisMax <= lower and axisMax < peak: + return [] # No overlap + + # case 2: Only the peak and outermost bound fall outside the new limit; + # we keep the deltaset, update peak and outermost bound and and scale deltas + # by the scalar value for the restricted axis at the new limit, and solve + # recursively. + # + # |peak + # 1...............................|.o.......... + # |/ \ + # / \ + # /| \ + # / | \ + # 0--------------------------- o | o----1 + # lower | upper + # | + # axisMax + # + # Convert to: + # + # 1............................................ + # | + # o peak + # /| + # /x| + # 0--------------------------- o o upper ----1 + # lower | + # | + # axisMax + if axisMax < peak: + mult = supportScalar({"tag": axisMax}, {"tag": tent}) + tent = (lower, axisMax, axisMax) + return [(scalar * mult, t) for scalar, t in _solve(tent, axisLimit)] + + # lower <= axisDef <= peak <= axisMax + + gain = supportScalar({"tag": axisDef}, {"tag": tent}) + out = [(gain, None)] + + # First, the positive side + + # outGain is the scalar of axisMax at the tent. + outGain = supportScalar({"tag": axisMax}, {"tag": tent}) + + # Case 3a: Gain is more than outGain. The tent down-slope crosses + # the axis into negative. We have to split it into multiples. + # + # | peak | + # 1...................|.o.....|.............. + # |/x\_ | + # gain................+....+_.|.............. + # /| |y\| + # ................../.|....|..+_......outGain + # / | | | \ + # 0---|-----------o | | | o----------1 + # axisMin lower | | | upper + # | | | + # axisDef | axisMax + # | + # crossing + if gain >= outGain: + # Note that this is the branch taken if both gain and outGain are 0. + + # Crossing point on the axis. + crossing = peak + (1 - gain) * (upper - peak) + + loc = (max(lower, axisDef), peak, crossing) + scalar = 1 + + # The part before the crossing point. + out.append((scalar - gain, loc)) + + # The part after the crossing point may use one or two tents, + # depending on whether upper is before axisMax or not, in one + # case we need to keep it down to eternity. + + # Case 3a1, similar to case 1neg; just one tent needed, as in + # the drawing above. + if upper >= axisMax: + loc = (crossing, axisMax, axisMax) + scalar = outGain + + out.append((scalar - gain, loc)) + + # Case 3a2: Similar to case 2neg; two tents needed, to keep + # down to eternity. + # + # | peak | + # 1...................|.o................|... + # |/ \_ | + # gain................+....+_............|... + # /| | \xxxxxxxxxxy| + # / | | \_xxxxxyyyy| + # / | | \xxyyyyyy| + # 0---|-----------o | | o-------|--1 + # axisMin lower | | upper | + # | | | + # axisDef | axisMax + # | + # crossing + else: + # A tent's peak cannot fall on axis default. Nudge it. + if upper == axisDef: + upper += EPSILON + + # Downslope. + loc1 = (crossing, upper, axisMax) + scalar1 = 0 + + # Eternity justify. + loc2 = (upper, axisMax, axisMax) + scalar2 = 0 + + out.append((scalar1 - gain, loc1)) + out.append((scalar2 - gain, loc2)) + + else: + # Special-case if peak is at axisMax. + if axisMax == peak: + upper = peak + + # Case 3: + # We keep delta as is and only scale the axis upper to achieve + # the desired new tent if feasible. + # + # peak + # 1.....................o.................... + # / \_| + # ..................../....+_.........outGain + # / | \ + # gain..............+......|..+_............. + # /| | | \ + # 0---|-----------o | | | o----------1 + # axisMin lower| | | upper + # | | newUpper + # axisDef axisMax + # + newUpper = peak + (1 - gain) * (upper - peak) + assert axisMax <= newUpper # Because outGain > gain + # Disabled because ots doesn't like us: + # https://github.com/fonttools/fonttools/issues/3350 + if False and newUpper <= axisDef + (axisMax - axisDef) * 2: + upper = newUpper + if not negative and axisDef + (axisMax - axisDef) * MAX_F2DOT14 < upper: + # we clamp +2.0 to the max F2Dot14 (~1.99994) for convenience + upper = axisDef + (axisMax - axisDef) * MAX_F2DOT14 + assert peak < upper + + loc = (max(axisDef, lower), peak, upper) + scalar = 1 + + out.append((scalar - gain, loc)) + + # Case 4: New limit doesn't fit; we need to chop into two tents, + # because the shape of a triangle with part of one side cut off + # cannot be represented as a triangle itself. + # + # | peak | + # 1.........|......o.|.................... + # ..........|...../x\|.............outGain + # | |xxy|\_ + # | /xxxy| \_ + # | |xxxxy| \_ + # | /xxxxy| \_ + # 0---|-----|-oxxxxxx| o----------1 + # axisMin | lower | upper + # | | + # axisDef axisMax + # + else: + loc1 = (max(axisDef, lower), peak, axisMax) + scalar1 = 1 + + loc2 = (peak, axisMax, axisMax) + scalar2 = outGain + + out.append((scalar1 - gain, loc1)) + # Don't add a dirac delta! + if peak < axisMax: + out.append((scalar2 - gain, loc2)) + + # Now, the negative side + + # Case 1neg: Lower extends beyond axisMin: we chop. Simple. + # + # | |peak + # 1..................|...|.o................. + # | |/ \ + # gain...............|...+...\............... + # |x_/| \ + # |/ | \ + # _/| | \ + # 0---------------o | | o----------1 + # lower | | upper + # | | + # axisMin axisDef + # + if lower <= axisMin: + loc = (axisMin, axisMin, axisDef) + scalar = supportScalar({"tag": axisMin}, {"tag": tent}) + + out.append((scalar - gain, loc)) + + # Case 2neg: Lower is betwen axisMin and axisDef: we add two + # tents to keep it down all the way to eternity. + # + # | |peak + # 1...|...............|.o................. + # | |/ \ + # gain|...............+...\............... + # |yxxxxxxxxxxxxx/| \ + # |yyyyyyxxxxxxx/ | \ + # |yyyyyyyyyyyx/ | \ + # 0---|-----------o | o----------1 + # axisMin lower | upper + # | + # axisDef + # + else: + # A tent's peak cannot fall on axis default. Nudge it. + if lower == axisDef: + lower -= EPSILON + + # Downslope. + loc1 = (axisMin, lower, axisDef) + scalar1 = 0 + + # Eternity justify. + loc2 = (axisMin, axisMin, lower) + scalar2 = 0 + + out.append((scalar1 - gain, loc1)) + out.append((scalar2 - gain, loc2)) + + return out + + +@lru_cache(128) +def rebaseTent(tent, axisLimit): + """Given a tuple (lower,peak,upper) "tent" and new axis limits + (axisMin,axisDefault,axisMax), solves how to represent the tent + under the new axis configuration. All values are in normalized + -1,0,+1 coordinate system. Tent values can be outside this range. + + Return value is a list of tuples. Each tuple is of the form + (scalar,tent), where scalar is a multipler to multiply any + delta-sets by, and tent is a new tent for that output delta-set. + If tent value is None, that is a special deltaset that should + be always-enabled (called "gain").""" + + axisMin, axisDef, axisMax, _distanceNegative, _distancePositive = axisLimit + assert -1 <= axisMin <= axisDef <= axisMax <= +1 + + lower, peak, upper = tent + assert -2 <= lower <= peak <= upper <= +2 + + assert peak != 0 + + sols = _solve(tent, axisLimit) + + n = lambda v: axisLimit.renormalizeValue(v) + sols = [ + (scalar, (n(v[0]), n(v[1]), n(v[2])) if v is not None else None) + for scalar, v in sols + if scalar + ] + + return sols diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatable.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatable.py new file mode 100644 index 0000000000000000000000000000000000000000..5f376f7d8aa80bafacac80ec492b815c4bc6d65d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatable.py @@ -0,0 +1,1214 @@ +""" +Tool to find wrong contour order between different masters, and +other interpolatability (or lack thereof) issues. + +Call as: +$ fonttools varLib.interpolatable font1 font2 ... +""" + +from .interpolatableHelpers import * +from .interpolatableTestContourOrder import test_contour_order +from .interpolatableTestStartingPoint import test_starting_point +from fontTools.pens.recordingPen import ( + RecordingPen, + DecomposingRecordingPen, + lerpRecordings, +) +from fontTools.pens.transformPen import TransformPen +from fontTools.pens.statisticsPen import StatisticsPen, StatisticsControlPen +from fontTools.pens.momentsPen import OpenContourError +from fontTools.varLib.models import piecewiseLinearMap, normalizeLocation +from fontTools.misc.fixedTools import floatToFixedToStr +from fontTools.misc.transform import Transform +from collections import defaultdict +from types import SimpleNamespace +from functools import wraps +from pprint import pformat +from math import sqrt, atan2, pi +import logging +import os + +log = logging.getLogger("fontTools.varLib.interpolatable") + +DEFAULT_TOLERANCE = 0.95 +DEFAULT_KINKINESS = 0.5 +DEFAULT_KINKINESS_LENGTH = 0.002 # ratio of UPEM +DEFAULT_UPEM = 1000 + + +class Glyph: + ITEMS = ( + "recordings", + "greenStats", + "controlStats", + "greenVectors", + "controlVectors", + "nodeTypes", + "isomorphisms", + "points", + "openContours", + ) + + def __init__(self, glyphname, glyphset): + self.name = glyphname + for item in self.ITEMS: + setattr(self, item, []) + self._populate(glyphset) + + def _fill_in(self, ix): + for item in self.ITEMS: + if len(getattr(self, item)) == ix: + getattr(self, item).append(None) + + def _populate(self, glyphset): + glyph = glyphset[self.name] + self.doesnt_exist = glyph is None + if self.doesnt_exist: + return + + perContourPen = PerContourOrComponentPen(RecordingPen, glyphset=glyphset) + try: + glyph.draw(perContourPen, outputImpliedClosingLine=True) + except TypeError: + glyph.draw(perContourPen) + self.recordings = perContourPen.value + del perContourPen + + for ix, contour in enumerate(self.recordings): + nodeTypes = [op for op, arg in contour.value] + self.nodeTypes.append(nodeTypes) + + greenStats = StatisticsPen(glyphset=glyphset) + controlStats = StatisticsControlPen(glyphset=glyphset) + try: + contour.replay(greenStats) + contour.replay(controlStats) + self.openContours.append(False) + except OpenContourError as e: + self.openContours.append(True) + self._fill_in(ix) + continue + self.greenStats.append(greenStats) + self.controlStats.append(controlStats) + self.greenVectors.append(contour_vector_from_stats(greenStats)) + self.controlVectors.append(contour_vector_from_stats(controlStats)) + + # Check starting point + if nodeTypes[0] == "addComponent": + self._fill_in(ix) + continue + + assert nodeTypes[0] == "moveTo" + assert nodeTypes[-1] in ("closePath", "endPath") + points = SimpleRecordingPointPen() + converter = SegmentToPointPen(points, False) + contour.replay(converter) + # points.value is a list of pt,bool where bool is true if on-curve and false if off-curve; + # now check all rotations and mirror-rotations of the contour and build list of isomorphic + # possible starting points. + self.points.append(points.value) + + isomorphisms = [] + self.isomorphisms.append(isomorphisms) + + # Add rotations + add_isomorphisms(points.value, isomorphisms, False) + # Add mirrored rotations + add_isomorphisms(points.value, isomorphisms, True) + + def draw(self, pen, contour_idx=None): + if contour_idx is None: + for contour in self.recordings: + contour.draw(pen) + else: + self.recordings[contour_idx].draw(pen) + + +def test_gen( + glyphsets, + glyphs=None, + names=None, + ignore_missing=False, + *, + locations=None, + tolerance=DEFAULT_TOLERANCE, + kinkiness=DEFAULT_KINKINESS, + upem=DEFAULT_UPEM, + show_all=False, + discrete_axes=[], +): + if tolerance >= 10: + tolerance *= 0.01 + assert 0 <= tolerance <= 1 + if kinkiness >= 10: + kinkiness *= 0.01 + assert 0 <= kinkiness + + names = names or [repr(g) for g in glyphsets] + + if glyphs is None: + # `glyphs = glyphsets[0].keys()` is faster, certainly, but doesn't allow for sparse TTFs/OTFs given out of order + # ... risks the sparse master being the first one, and only processing a subset of the glyphs + glyphs = {g for glyphset in glyphsets for g in glyphset.keys()} + + parents, order = find_parents_and_order( + glyphsets, locations, discrete_axes=discrete_axes + ) + + def grand_parent(i, glyphname): + if i is None: + return None + i = parents[i] + if i is None: + return None + while parents[i] is not None and glyphsets[i][glyphname] is None: + i = parents[i] + return i + + for glyph_name in glyphs: + log.info("Testing glyph %s", glyph_name) + allGlyphs = [Glyph(glyph_name, glyphset) for glyphset in glyphsets] + if len([1 for glyph in allGlyphs if not glyph.doesnt_exist]) <= 1: + continue + for master_idx, (glyph, glyphset, name) in enumerate( + zip(allGlyphs, glyphsets, names) + ): + if glyph.doesnt_exist: + if not ignore_missing: + yield ( + glyph_name, + { + "type": InterpolatableProblem.MISSING, + "master": name, + "master_idx": master_idx, + }, + ) + continue + + has_open = False + for ix, open in enumerate(glyph.openContours): + if not open: + continue + has_open = True + yield ( + glyph_name, + { + "type": InterpolatableProblem.OPEN_PATH, + "master": name, + "master_idx": master_idx, + "contour": ix, + }, + ) + if has_open: + continue + + matchings = [None] * len(glyphsets) + + for m1idx in order: + glyph1 = allGlyphs[m1idx] + if glyph1 is None or not glyph1.nodeTypes: + continue + m0idx = grand_parent(m1idx, glyph_name) + if m0idx is None: + continue + glyph0 = allGlyphs[m0idx] + if glyph0 is None or not glyph0.nodeTypes: + continue + + # + # Basic compatibility checks + # + + m0 = glyph0.nodeTypes + m1 = glyph1.nodeTypes + if len(m0) != len(m1): + yield ( + glyph_name, + { + "type": InterpolatableProblem.PATH_COUNT, + "master_1": names[m0idx], + "master_2": names[m1idx], + "master_1_idx": m0idx, + "master_2_idx": m1idx, + "value_1": len(m0), + "value_2": len(m1), + }, + ) + continue + + if m0 != m1: + for pathIx, (nodes1, nodes2) in enumerate(zip(m0, m1)): + if nodes1 == nodes2: + continue + if len(nodes1) != len(nodes2): + yield ( + glyph_name, + { + "type": InterpolatableProblem.NODE_COUNT, + "path": pathIx, + "master_1": names[m0idx], + "master_2": names[m1idx], + "master_1_idx": m0idx, + "master_2_idx": m1idx, + "value_1": len(nodes1), + "value_2": len(nodes2), + }, + ) + continue + for nodeIx, (n1, n2) in enumerate(zip(nodes1, nodes2)): + if n1 != n2: + yield ( + glyph_name, + { + "type": InterpolatableProblem.NODE_INCOMPATIBILITY, + "path": pathIx, + "node": nodeIx, + "master_1": names[m0idx], + "master_2": names[m1idx], + "master_1_idx": m0idx, + "master_2_idx": m1idx, + "value_1": n1, + "value_2": n2, + }, + ) + continue + + # + # InterpolatableProblem.CONTOUR_ORDER check + # + + this_tolerance, matching = test_contour_order(glyph0, glyph1) + if this_tolerance < tolerance: + yield ( + glyph_name, + { + "type": InterpolatableProblem.CONTOUR_ORDER, + "master_1": names[m0idx], + "master_2": names[m1idx], + "master_1_idx": m0idx, + "master_2_idx": m1idx, + "value_1": list(range(len(matching))), + "value_2": matching, + "tolerance": this_tolerance, + }, + ) + matchings[m1idx] = matching + + # + # wrong-start-point / weight check + # + + m0Isomorphisms = glyph0.isomorphisms + m1Isomorphisms = glyph1.isomorphisms + m0Vectors = glyph0.greenVectors + m1Vectors = glyph1.greenVectors + recording0 = glyph0.recordings + recording1 = glyph1.recordings + + # If contour-order is wrong, adjust it + matching = matchings[m1idx] + if ( + matching is not None and m1Isomorphisms + ): # m1 is empty for composite glyphs + m1Isomorphisms = [m1Isomorphisms[i] for i in matching] + m1Vectors = [m1Vectors[i] for i in matching] + recording1 = [recording1[i] for i in matching] + + midRecording = [] + for c0, c1 in zip(recording0, recording1): + try: + r = RecordingPen() + r.value = list(lerpRecordings(c0.value, c1.value)) + midRecording.append(r) + except ValueError: + # Mismatch because of the reordering above + midRecording.append(None) + + for ix, (contour0, contour1) in enumerate( + zip(m0Isomorphisms, m1Isomorphisms) + ): + if ( + contour0 is None + or contour1 is None + or len(contour0) == 0 + or len(contour0) != len(contour1) + ): + # We already reported this; or nothing to do; or not compatible + # after reordering above. + continue + + this_tolerance, proposed_point, reverse = test_starting_point( + glyph0, glyph1, ix, tolerance, matching + ) + + if this_tolerance < tolerance: + yield ( + glyph_name, + { + "type": InterpolatableProblem.WRONG_START_POINT, + "contour": ix, + "master_1": names[m0idx], + "master_2": names[m1idx], + "master_1_idx": m0idx, + "master_2_idx": m1idx, + "value_1": 0, + "value_2": proposed_point, + "reversed": reverse, + "tolerance": this_tolerance, + }, + ) + + # Weight check. + # + # If contour could be mid-interpolated, and the two + # contours have the same area sign, proceeed. + # + # The sign difference can happen if it's a weirdo + # self-intersecting contour; ignore it. + contour = midRecording[ix] + + if contour and (m0Vectors[ix][0] < 0) == (m1Vectors[ix][0] < 0): + midStats = StatisticsPen(glyphset=None) + contour.replay(midStats) + + midVector = contour_vector_from_stats(midStats) + + m0Vec = m0Vectors[ix] + m1Vec = m1Vectors[ix] + size0 = m0Vec[0] * m0Vec[0] + size1 = m1Vec[0] * m1Vec[0] + midSize = midVector[0] * midVector[0] + + for overweight, problem_type in enumerate( + ( + InterpolatableProblem.UNDERWEIGHT, + InterpolatableProblem.OVERWEIGHT, + ) + ): + if overweight: + expectedSize = max(size0, size1) + continue # disabled + else: + expectedSize = sqrt(size0 * size1) + + log.debug( + "%s: actual size %g; threshold size %g, master sizes: %g, %g", + problem_type, + midSize, + expectedSize, + size0, + size1, + ) + + if ( + not overweight and expectedSize * tolerance > midSize + 1e-5 + ) or (overweight and 1e-5 + expectedSize / tolerance < midSize): + try: + if overweight: + this_tolerance = expectedSize / midSize + else: + this_tolerance = midSize / expectedSize + except ZeroDivisionError: + this_tolerance = 0 + log.debug("tolerance %g", this_tolerance) + yield ( + glyph_name, + { + "type": problem_type, + "contour": ix, + "master_1": names[m0idx], + "master_2": names[m1idx], + "master_1_idx": m0idx, + "master_2_idx": m1idx, + "tolerance": this_tolerance, + }, + ) + + # + # "kink" detector + # + m0 = glyph0.points + m1 = glyph1.points + + # If contour-order is wrong, adjust it + if matchings[m1idx] is not None and m1: # m1 is empty for composite glyphs + m1 = [m1[i] for i in matchings[m1idx]] + + t = 0.1 # ~sin(radian(6)) for tolerance 0.95 + deviation_threshold = ( + upem * DEFAULT_KINKINESS_LENGTH * DEFAULT_KINKINESS / kinkiness + ) + + for ix, (contour0, contour1) in enumerate(zip(m0, m1)): + if ( + contour0 is None + or contour1 is None + or len(contour0) == 0 + or len(contour0) != len(contour1) + ): + # We already reported this; or nothing to do; or not compatible + # after reordering above. + continue + + # Walk the contour, keeping track of three consecutive points, with + # middle one being an on-curve. If the three are co-linear then + # check for kinky-ness. + for i in range(len(contour0)): + pt0 = contour0[i] + pt1 = contour1[i] + if not pt0[1] or not pt1[1]: + # Skip off-curves + continue + pt0_prev = contour0[i - 1] + pt1_prev = contour1[i - 1] + pt0_next = contour0[(i + 1) % len(contour0)] + pt1_next = contour1[(i + 1) % len(contour1)] + + if pt0_prev[1] and pt1_prev[1]: + # At least one off-curve is required + continue + if pt0_next[1] and pt1_next[1]: + # At least one off-curve is required + continue + + pt0 = complex(*pt0[0]) + pt1 = complex(*pt1[0]) + pt0_prev = complex(*pt0_prev[0]) + pt1_prev = complex(*pt1_prev[0]) + pt0_next = complex(*pt0_next[0]) + pt1_next = complex(*pt1_next[0]) + + # We have three consecutive points. Check whether + # they are colinear. + d0_prev = pt0 - pt0_prev + d0_next = pt0_next - pt0 + d1_prev = pt1 - pt1_prev + d1_next = pt1_next - pt1 + + sin0 = d0_prev.real * d0_next.imag - d0_prev.imag * d0_next.real + sin1 = d1_prev.real * d1_next.imag - d1_prev.imag * d1_next.real + try: + sin0 /= abs(d0_prev) * abs(d0_next) + sin1 /= abs(d1_prev) * abs(d1_next) + except ZeroDivisionError: + continue + + if abs(sin0) > t or abs(sin1) > t: + # Not colinear / not smooth. + continue + + # Check the mid-point is actually, well, in the middle. + dot0 = d0_prev.real * d0_next.real + d0_prev.imag * d0_next.imag + dot1 = d1_prev.real * d1_next.real + d1_prev.imag * d1_next.imag + if dot0 < 0 or dot1 < 0: + # Sharp corner. + continue + + # Fine, if handle ratios are similar... + r0 = abs(d0_prev) / (abs(d0_prev) + abs(d0_next)) + r1 = abs(d1_prev) / (abs(d1_prev) + abs(d1_next)) + r_diff = abs(r0 - r1) + if abs(r_diff) < t: + # Smooth enough. + continue + + mid = (pt0 + pt1) / 2 + mid_prev = (pt0_prev + pt1_prev) / 2 + mid_next = (pt0_next + pt1_next) / 2 + + mid_d0 = mid - mid_prev + mid_d1 = mid_next - mid + + sin_mid = mid_d0.real * mid_d1.imag - mid_d0.imag * mid_d1.real + try: + sin_mid /= abs(mid_d0) * abs(mid_d1) + except ZeroDivisionError: + continue + + # ...or if the angles are similar. + if abs(sin_mid) * (tolerance * kinkiness) <= t: + # Smooth enough. + continue + + # How visible is the kink? + + cross = sin_mid * abs(mid_d0) * abs(mid_d1) + arc_len = abs(mid_d0 + mid_d1) + deviation = abs(cross / arc_len) + if deviation < deviation_threshold: + continue + deviation_ratio = deviation / arc_len + if deviation_ratio > t: + continue + + this_tolerance = t / (abs(sin_mid) * kinkiness) + + log.debug( + "kink: deviation %g; deviation_ratio %g; sin_mid %g; r_diff %g", + deviation, + deviation_ratio, + sin_mid, + r_diff, + ) + log.debug("tolerance %g", this_tolerance) + yield ( + glyph_name, + { + "type": InterpolatableProblem.KINK, + "contour": ix, + "master_1": names[m0idx], + "master_2": names[m1idx], + "master_1_idx": m0idx, + "master_2_idx": m1idx, + "value": i, + "tolerance": this_tolerance, + }, + ) + + # + # --show-all + # + + if show_all: + yield ( + glyph_name, + { + "type": InterpolatableProblem.NOTHING, + "master_1": names[m0idx], + "master_2": names[m1idx], + "master_1_idx": m0idx, + "master_2_idx": m1idx, + }, + ) + + +@wraps(test_gen) +def test(*args, **kwargs): + problems = defaultdict(list) + for glyphname, problem in test_gen(*args, **kwargs): + problems[glyphname].append(problem) + return problems + + +def recursivelyAddGlyph(glyphname, glyphset, ttGlyphSet, glyf): + if glyphname in glyphset: + return + glyphset[glyphname] = ttGlyphSet[glyphname] + + for component in getattr(glyf[glyphname], "components", []): + recursivelyAddGlyph(component.glyphName, glyphset, ttGlyphSet, glyf) + + +def ensure_parent_dir(path): + dirname = os.path.dirname(path) + if dirname: + os.makedirs(dirname, exist_ok=True) + return path + + +def main(args=None): + """Test for interpolatability issues between fonts""" + import argparse + import sys + + parser = argparse.ArgumentParser( + "fonttools varLib.interpolatable", + description=main.__doc__, + ) + parser.add_argument( + "--glyphs", + action="store", + help="Space-separate name of glyphs to check", + ) + parser.add_argument( + "--show-all", + action="store_true", + help="Show all glyph pairs, even if no problems are found", + ) + parser.add_argument( + "--tolerance", + action="store", + type=float, + help="Error tolerance. Between 0 and 1. Default %s" % DEFAULT_TOLERANCE, + ) + parser.add_argument( + "--kinkiness", + action="store", + type=float, + help="How aggressively report kinks. Default %s" % DEFAULT_KINKINESS, + ) + parser.add_argument( + "--json", + action="store_true", + help="Output report in JSON format", + ) + parser.add_argument( + "--pdf", + action="store", + help="Output report in PDF format", + ) + parser.add_argument( + "--ps", + action="store", + help="Output report in PostScript format", + ) + parser.add_argument( + "--html", + action="store", + help="Output report in HTML format", + ) + parser.add_argument( + "--quiet", + action="store_true", + help="Only exit with code 1 or 0, no output", + ) + parser.add_argument( + "--output", + action="store", + help="Output file for the problem report; Default: stdout", + ) + parser.add_argument( + "--ignore-missing", + action="store_true", + help="Will not report glyphs missing from sparse masters as errors", + ) + parser.add_argument( + "inputs", + metavar="FILE", + type=str, + nargs="+", + help="Input a single variable font / DesignSpace / Glyphs file, or multiple TTF/UFO files", + ) + parser.add_argument( + "--name", + metavar="NAME", + type=str, + action="append", + help="Name of the master to use in the report. If not provided, all are used.", + ) + parser.add_argument("-v", "--verbose", action="store_true", help="Run verbosely.") + parser.add_argument("--debug", action="store_true", help="Run with debug output.") + + args = parser.parse_args(args) + + from fontTools import configLogger + + configLogger(level=("INFO" if args.verbose else "WARNING")) + if args.debug: + configLogger(level="DEBUG") + + glyphs = args.glyphs.split() if args.glyphs else None + + from os.path import basename + + fonts = [] + names = [] + locations = [] + discrete_axes = set() + upem = DEFAULT_UPEM + + original_args_inputs = tuple(args.inputs) + + if len(args.inputs) == 1: + designspace = None + if args.inputs[0].endswith(".designspace"): + from fontTools.designspaceLib import DesignSpaceDocument + + designspace = DesignSpaceDocument.fromfile(args.inputs[0]) + args.inputs = [master.path for master in designspace.sources] + locations = [master.location for master in designspace.sources] + discrete_axes = { + a.name for a in designspace.axes if not hasattr(a, "minimum") + } + axis_triples = { + a.name: (a.minimum, a.default, a.maximum) + for a in designspace.axes + if a.name not in discrete_axes + } + axis_mappings = {a.name: a.map for a in designspace.axes} + axis_triples = { + k: tuple(piecewiseLinearMap(v, dict(axis_mappings[k])) for v in vv) + for k, vv in axis_triples.items() + } + + elif args.inputs[0].endswith((".glyphs", ".glyphspackage")): + from glyphsLib import GSFont, to_designspace + + gsfont = GSFont(args.inputs[0]) + upem = gsfont.upm + designspace = to_designspace(gsfont) + fonts = [source.font for source in designspace.sources] + names = ["%s-%s" % (f.info.familyName, f.info.styleName) for f in fonts] + args.inputs = [] + locations = [master.location for master in designspace.sources] + axis_triples = { + a.name: (a.minimum, a.default, a.maximum) for a in designspace.axes + } + axis_mappings = {a.name: a.map for a in designspace.axes} + axis_triples = { + k: tuple(piecewiseLinearMap(v, dict(axis_mappings[k])) for v in vv) + for k, vv in axis_triples.items() + } + + elif args.inputs[0].endswith(".ttf") or args.inputs[0].endswith(".otf"): + from fontTools.ttLib import TTFont + + # Is variable font? + + font = TTFont(args.inputs[0]) + upem = font["head"].unitsPerEm + + fvar = font["fvar"] + axisMapping = {} + for axis in fvar.axes: + axisMapping[axis.axisTag] = { + -1: axis.minValue, + 0: axis.defaultValue, + 1: axis.maxValue, + } + normalized = False + if "avar" in font: + avar = font["avar"] + if getattr(avar.table, "VarStore", None): + axisMapping = {tag: {-1: -1, 0: 0, 1: 1} for tag in axisMapping} + normalized = True + else: + for axisTag, segments in avar.segments.items(): + fvarMapping = axisMapping[axisTag].copy() + for location, value in segments.items(): + axisMapping[axisTag][value] = piecewiseLinearMap( + location, fvarMapping + ) + + # Gather all glyphs at their "master" locations + ttGlyphSets = {} + glyphsets = defaultdict(dict) + + if "gvar" in font: + gvar = font["gvar"] + glyf = font["glyf"] + + if glyphs is None: + glyphs = sorted(gvar.variations.keys()) + for glyphname in glyphs: + for var in gvar.variations[glyphname]: + locDict = {} + loc = [] + for tag, val in sorted(var.axes.items()): + locDict[tag] = val[1] + loc.append((tag, val[1])) + + locTuple = tuple(loc) + if locTuple not in ttGlyphSets: + ttGlyphSets[locTuple] = font.getGlyphSet( + location=locDict, normalized=True, recalcBounds=False + ) + + recursivelyAddGlyph( + glyphname, glyphsets[locTuple], ttGlyphSets[locTuple], glyf + ) + + elif "CFF2" in font: + fvarAxes = font["fvar"].axes + cff2 = font["CFF2"].cff.topDictIndex[0] + charstrings = cff2.CharStrings + + if glyphs is None: + glyphs = sorted(charstrings.keys()) + for glyphname in glyphs: + cs = charstrings[glyphname] + private = cs.private + + # Extract vsindex for the glyph + vsindices = {getattr(private, "vsindex", 0)} + vsindex = getattr(private, "vsindex", 0) + last_op = 0 + # The spec says vsindex can only appear once and must be the first + # operator in the charstring, but we support multiple. + # https://github.com/harfbuzz/boring-expansion-spec/issues/158 + for op in cs.program: + if op == "blend": + vsindices.add(vsindex) + elif op == "vsindex": + assert isinstance(last_op, int) + vsindex = last_op + last_op = op + + if not hasattr(private, "vstore"): + continue + + varStore = private.vstore.otVarStore + for vsindex in vsindices: + varData = varStore.VarData[vsindex] + for regionIndex in varData.VarRegionIndex: + region = varStore.VarRegionList.Region[regionIndex] + + locDict = {} + loc = [] + for axisIndex, axis in enumerate(region.VarRegionAxis): + tag = fvarAxes[axisIndex].axisTag + val = axis.PeakCoord + locDict[tag] = val + loc.append((tag, val)) + + locTuple = tuple(loc) + if locTuple not in ttGlyphSets: + ttGlyphSets[locTuple] = font.getGlyphSet( + location=locDict, + normalized=True, + recalcBounds=False, + ) + + glyphset = glyphsets[locTuple] + glyphset[glyphname] = ttGlyphSets[locTuple][glyphname] + + names = ["''"] + fonts = [font.getGlyphSet()] + locations = [{}] + axis_triples = {a: (-1, 0, +1) for a in sorted(axisMapping.keys())} + for locTuple in sorted(glyphsets.keys(), key=lambda v: (len(v), v)): + name = ( + "'" + + " ".join( + "%s=%s" + % ( + k, + floatToFixedToStr( + piecewiseLinearMap(v, axisMapping[k]), 14 + ), + ) + for k, v in locTuple + ) + + "'" + ) + if normalized: + name += " (normalized)" + names.append(name) + fonts.append(glyphsets[locTuple]) + locations.append(dict(locTuple)) + + args.ignore_missing = True + args.inputs = [] + + if not locations: + locations = [{} for _ in fonts] + + for filename in args.inputs: + if filename.endswith(".ufo"): + from fontTools.ufoLib import UFOReader + + font = UFOReader(filename) + info = SimpleNamespace() + font.readInfo(info) + upem = info.unitsPerEm + fonts.append(font) + else: + from fontTools.ttLib import TTFont + + font = TTFont(filename) + upem = font["head"].unitsPerEm + fonts.append(font) + + names.append(basename(filename).rsplit(".", 1)[0]) + + if len(fonts) < 2: + log.warning("Font file does not seem to be variable. Nothing to check.") + return + + glyphsets = [] + for font in fonts: + if hasattr(font, "getGlyphSet"): + glyphset = font.getGlyphSet() + else: + glyphset = font + glyphsets.append({k: glyphset[k] for k in glyphset.keys()}) + + if args.name: + accepted_names = set(args.name) + glyphsets = [ + glyphset + for name, glyphset in zip(names, glyphsets) + if name in accepted_names + ] + locations = [ + location + for name, location in zip(names, locations) + if name in accepted_names + ] + names = [name for name in names if name in accepted_names] + + if not glyphs: + glyphs = sorted(set([gn for glyphset in glyphsets for gn in glyphset.keys()])) + + glyphsSet = set(glyphs) + for glyphset in glyphsets: + glyphSetGlyphNames = set(glyphset.keys()) + diff = glyphsSet - glyphSetGlyphNames + if diff: + for gn in diff: + glyphset[gn] = None + + # Normalize locations + locations = [ + { + **normalizeLocation(loc, axis_triples), + **{k: v for k, v in loc.items() if k in discrete_axes}, + } + for loc in locations + ] + tolerance = args.tolerance or DEFAULT_TOLERANCE + kinkiness = args.kinkiness if args.kinkiness is not None else DEFAULT_KINKINESS + + try: + log.info("Running on %d glyphsets", len(glyphsets)) + log.info("Locations: %s", pformat(locations)) + problems_gen = test_gen( + glyphsets, + glyphs=glyphs, + names=names, + locations=locations, + upem=upem, + ignore_missing=args.ignore_missing, + tolerance=tolerance, + kinkiness=kinkiness, + show_all=args.show_all, + discrete_axes=discrete_axes, + ) + problems = defaultdict(list) + + f = ( + sys.stdout + if args.output is None + else open(ensure_parent_dir(args.output), "w") + ) + + if not args.quiet: + if args.json: + import json + + for glyphname, problem in problems_gen: + problems[glyphname].append(problem) + + print(json.dumps(problems), file=f) + else: + last_glyphname = None + for glyphname, p in problems_gen: + problems[glyphname].append(p) + + if glyphname != last_glyphname: + print(f"Glyph {glyphname} was not compatible:", file=f) + last_glyphname = glyphname + last_master_idxs = None + + master_idxs = ( + (p["master_idx"],) + if "master_idx" in p + else (p["master_1_idx"], p["master_2_idx"]) + ) + if master_idxs != last_master_idxs: + master_names = ( + (p["master"],) + if "master" in p + else (p["master_1"], p["master_2"]) + ) + print(f" Masters: %s:" % ", ".join(master_names), file=f) + last_master_idxs = master_idxs + + if p["type"] == InterpolatableProblem.MISSING: + print( + " Glyph was missing in master %s" % p["master"], file=f + ) + elif p["type"] == InterpolatableProblem.OPEN_PATH: + print( + " Glyph has an open path in master %s" % p["master"], + file=f, + ) + elif p["type"] == InterpolatableProblem.PATH_COUNT: + print( + " Path count differs: %i in %s, %i in %s" + % ( + p["value_1"], + p["master_1"], + p["value_2"], + p["master_2"], + ), + file=f, + ) + elif p["type"] == InterpolatableProblem.NODE_COUNT: + print( + " Node count differs in path %i: %i in %s, %i in %s" + % ( + p["path"], + p["value_1"], + p["master_1"], + p["value_2"], + p["master_2"], + ), + file=f, + ) + elif p["type"] == InterpolatableProblem.NODE_INCOMPATIBILITY: + print( + " Node %d incompatible in path %i: %s in %s, %s in %s" + % ( + p["node"], + p["path"], + p["value_1"], + p["master_1"], + p["value_2"], + p["master_2"], + ), + file=f, + ) + elif p["type"] == InterpolatableProblem.CONTOUR_ORDER: + print( + " Contour order differs: %s in %s, %s in %s" + % ( + p["value_1"], + p["master_1"], + p["value_2"], + p["master_2"], + ), + file=f, + ) + elif p["type"] == InterpolatableProblem.WRONG_START_POINT: + print( + " Contour %d start point differs: %s in %s, %s in %s; reversed: %s" + % ( + p["contour"], + p["value_1"], + p["master_1"], + p["value_2"], + p["master_2"], + p["reversed"], + ), + file=f, + ) + elif p["type"] == InterpolatableProblem.UNDERWEIGHT: + print( + " Contour %d interpolation is underweight: %s, %s" + % ( + p["contour"], + p["master_1"], + p["master_2"], + ), + file=f, + ) + elif p["type"] == InterpolatableProblem.OVERWEIGHT: + print( + " Contour %d interpolation is overweight: %s, %s" + % ( + p["contour"], + p["master_1"], + p["master_2"], + ), + file=f, + ) + elif p["type"] == InterpolatableProblem.KINK: + print( + " Contour %d has a kink at %s: %s, %s" + % ( + p["contour"], + p["value"], + p["master_1"], + p["master_2"], + ), + file=f, + ) + elif p["type"] == InterpolatableProblem.NOTHING: + print( + " Showing %s and %s" + % ( + p["master_1"], + p["master_2"], + ), + file=f, + ) + else: + for glyphname, problem in problems_gen: + problems[glyphname].append(problem) + + problems = sort_problems(problems) + + for p in "ps", "pdf": + arg = getattr(args, p) + if arg is None: + continue + log.info("Writing %s to %s", p.upper(), arg) + from .interpolatablePlot import InterpolatablePS, InterpolatablePDF + + PlotterClass = InterpolatablePS if p == "ps" else InterpolatablePDF + + with PlotterClass( + ensure_parent_dir(arg), glyphsets=glyphsets, names=names + ) as doc: + doc.add_title_page( + original_args_inputs, tolerance=tolerance, kinkiness=kinkiness + ) + if problems: + doc.add_summary(problems) + doc.add_problems(problems) + if not problems and not args.quiet: + doc.draw_cupcake() + if problems: + doc.add_index() + doc.add_table_of_contents() + + if args.html: + log.info("Writing HTML to %s", args.html) + from .interpolatablePlot import InterpolatableSVG + + svgs = [] + glyph_starts = {} + with InterpolatableSVG(svgs, glyphsets=glyphsets, names=names) as svg: + svg.add_title_page( + original_args_inputs, + show_tolerance=False, + tolerance=tolerance, + kinkiness=kinkiness, + ) + for glyph, glyph_problems in problems.items(): + glyph_starts[len(svgs)] = glyph + svg.add_problems( + {glyph: glyph_problems}, + show_tolerance=False, + show_page_number=False, + ) + if not problems and not args.quiet: + svg.draw_cupcake() + + import base64 + import html + + with open(ensure_parent_dir(args.html), "wb") as f: + f.write(b"<!DOCTYPE html>\n") + f.write( + b'<html><body align="center" style="font-family: sans-serif; text-color: #222">\n' + ) + f.write(b"<title>fonttools varLib.interpolatable report</title>\n") + for i, svg in enumerate(svgs): + if i in glyph_starts: + f.write( + f"<h1>Glyph {html.escape(glyph_starts[i])}</h1>\n".encode( + "utf-8" + ) + ) + f.write("<img src='data:image/svg+xml;base64,".encode("utf-8")) + f.write(base64.b64encode(svg)) + f.write(b"' />\n") + f.write(b"<hr>\n") + f.write(b"</body></html>\n") + + except Exception as e: + e.args += original_args_inputs + log.error(e) + raise + + if problems: + return problems + + +if __name__ == "__main__": + import sys + + problems = main() + sys.exit(int(bool(problems))) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatableHelpers.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatableHelpers.py new file mode 100644 index 0000000000000000000000000000000000000000..bbe072c83cf65a6ecf503e6b4ba9ad58453b3808 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatableHelpers.py @@ -0,0 +1,360 @@ +from fontTools.ttLib.ttGlyphSet import LerpGlyphSet +from fontTools.pens.basePen import AbstractPen, BasePen, DecomposingPen +from fontTools.pens.pointPen import AbstractPointPen, SegmentToPointPen +from fontTools.pens.recordingPen import RecordingPen, DecomposingRecordingPen +from fontTools.misc.transform import Transform +from collections import defaultdict, deque +from math import sqrt, copysign, atan2, pi +import itertools + +import logging + +log = logging.getLogger("fontTools.varLib.interpolatable") + + +class InterpolatableProblem: + NOTHING = "nothing" + MISSING = "missing" + OPEN_PATH = "open_path" + PATH_COUNT = "path_count" + NODE_COUNT = "node_count" + NODE_INCOMPATIBILITY = "node_incompatibility" + CONTOUR_ORDER = "contour_order" + WRONG_START_POINT = "wrong_start_point" + KINK = "kink" + UNDERWEIGHT = "underweight" + OVERWEIGHT = "overweight" + + severity = { + MISSING: 1, + OPEN_PATH: 2, + PATH_COUNT: 3, + NODE_COUNT: 4, + NODE_INCOMPATIBILITY: 5, + CONTOUR_ORDER: 6, + WRONG_START_POINT: 7, + KINK: 8, + UNDERWEIGHT: 9, + OVERWEIGHT: 10, + NOTHING: 11, + } + + +def sort_problems(problems): + """Sort problem groups by their most severe problem type.""" + return dict( + sorted( + problems.items(), + key=lambda _: -min( + ( + (InterpolatableProblem.severity[p["type"]] + p.get("tolerance", 0)) + for p in _[1] + ), + ), + reverse=True, + ) + ) + + +def rot_list(l, k): + """Rotate list by k items forward. Ie. item at position 0 will be + at position k in returned list. Negative k is allowed.""" + return l[-k:] + l[:-k] + + +class PerContourPen(BasePen): + def __init__(self, Pen, glyphset=None): + BasePen.__init__(self, glyphset) + self._Pen = Pen + self._pen = None + self.value = [] + + def _moveTo(self, p0): + self._newItem() + self._pen.moveTo(p0) + + def _lineTo(self, p1): + self._pen.lineTo(p1) + + def _qCurveToOne(self, p1, p2): + self._pen.qCurveTo(p1, p2) + + def _curveToOne(self, p1, p2, p3): + self._pen.curveTo(p1, p2, p3) + + def _closePath(self): + self._pen.closePath() + self._pen = None + + def _endPath(self): + self._pen.endPath() + self._pen = None + + def _newItem(self): + self._pen = pen = self._Pen() + self.value.append(pen) + + +class PerContourOrComponentPen(PerContourPen): + def addComponent(self, glyphName, transformation): + self._newItem() + self.value[-1].addComponent(glyphName, transformation) + + +class SimpleRecordingPointPen(AbstractPointPen): + def __init__(self): + self.value = [] + + def beginPath(self, identifier=None, **kwargs): + pass + + def endPath(self) -> None: + pass + + def addPoint(self, pt, segmentType=None): + self.value.append((pt, False if segmentType is None else True)) + + +def vdiff_hypot2(v0, v1): + s = 0 + for x0, x1 in zip(v0, v1): + d = x1 - x0 + s += d * d + return s + + +def vdiff_hypot2_complex(v0, v1): + s = 0 + for x0, x1 in zip(v0, v1): + d = x1 - x0 + s += d.real * d.real + d.imag * d.imag + # This does the same but seems to be slower: + # s += (d * d.conjugate()).real + return s + + +def matching_cost(G, matching): + return sum(G[i][j] for i, j in enumerate(matching)) + + +def min_cost_perfect_bipartite_matching_scipy(G): + n = len(G) + rows, cols = linear_sum_assignment(G) + assert (rows == list(range(n))).all() + # Convert numpy array and integer to Python types, + # to ensure that this is JSON-serializable. + cols = list(int(e) for e in cols) + return list(cols), matching_cost(G, cols) + + +def min_cost_perfect_bipartite_matching_munkres(G): + n = len(G) + cols = [None] * n + for row, col in Munkres().compute(G): + cols[row] = col + return cols, matching_cost(G, cols) + + +def min_cost_perfect_bipartite_matching_bruteforce(G): + n = len(G) + + if n > 6: + raise Exception("Install Python module 'munkres' or 'scipy >= 0.17.0'") + + # Otherwise just brute-force + permutations = itertools.permutations(range(n)) + best = list(next(permutations)) + best_cost = matching_cost(G, best) + for p in permutations: + cost = matching_cost(G, p) + if cost < best_cost: + best, best_cost = list(p), cost + return best, best_cost + + +# Prefer `scipy.optimize.linear_sum_assignment` for performance. +# `Munkres` is also supported as a fallback for minimalistic systems +# where installing SciPy is not feasible. +try: + from scipy.optimize import linear_sum_assignment + + min_cost_perfect_bipartite_matching = min_cost_perfect_bipartite_matching_scipy +except ImportError: + try: + from munkres import Munkres + + min_cost_perfect_bipartite_matching = ( + min_cost_perfect_bipartite_matching_munkres + ) + except ImportError: + min_cost_perfect_bipartite_matching = ( + min_cost_perfect_bipartite_matching_bruteforce + ) + + +def contour_vector_from_stats(stats): + # Don't change the order of items here. + # It's okay to add to the end, but otherwise, other + # code depends on it. Search for "covariance". + size = sqrt(abs(stats.area)) + return ( + copysign((size), stats.area), + stats.meanX, + stats.meanY, + stats.stddevX * 2, + stats.stddevY * 2, + stats.correlation * size, + ) + + +def matching_for_vectors(m0, m1): + n = len(m0) + + costs = [[vdiff_hypot2(v0, v1) for v1 in m1] for v0 in m0] + ( + matching, + matching_cost, + ) = min_cost_perfect_bipartite_matching(costs) + identity_cost = sum(costs[i][i] for i in range(n)) + return matching, matching_cost, identity_cost + + +def points_characteristic_bits(points): + bits = 0 + for pt, b in reversed(points): + bits = (bits << 1) | b + return bits + + +_NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR = 4 + + +def points_complex_vector(points): + vector = [] + if not points: + return vector + points = [complex(*pt) for pt, _ in points] + n = len(points) + assert _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR == 4 + points.extend(points[: _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR - 1]) + while len(points) < _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR: + points.extend(points[: _NUM_ITEMS_PER_POINTS_COMPLEX_VECTOR - 1]) + for i in range(n): + # The weights are magic numbers. + + # The point itself + p0 = points[i] + vector.append(p0) + + # The vector to the next point + p1 = points[i + 1] + d0 = p1 - p0 + vector.append(d0 * 3) + + # The turn vector + p2 = points[i + 2] + d1 = p2 - p1 + vector.append(d1 - d0) + + # The angle to the next point, as a cross product; + # Square root of, to match dimentionality of distance. + cross = d0.real * d1.imag - d0.imag * d1.real + cross = copysign(sqrt(abs(cross)), cross) + vector.append(cross * 4) + + return vector + + +def add_isomorphisms(points, isomorphisms, reverse): + reference_bits = points_characteristic_bits(points) + n = len(points) + + # if points[0][0] == points[-1][0]: + # abort + + if reverse: + points = points[::-1] + bits = points_characteristic_bits(points) + else: + bits = reference_bits + + vector = points_complex_vector(points) + + assert len(vector) % n == 0 + mult = len(vector) // n + mask = (1 << n) - 1 + + for i in range(n): + b = ((bits << (n - i)) & mask) | (bits >> i) + if b == reference_bits: + isomorphisms.append( + (rot_list(vector, -i * mult), n - 1 - i if reverse else i, reverse) + ) + + +def find_parents_and_order(glyphsets, locations, *, discrete_axes=set()): + parents = [None] + list(range(len(glyphsets) - 1)) + order = list(range(len(glyphsets))) + if locations: + # Order base master first + bases = [ + i + for i, l in enumerate(locations) + if all(v == 0 for k, v in l.items() if k not in discrete_axes) + ] + if bases: + log.info("Found %s base masters: %s", len(bases), bases) + else: + log.warning("No base master location found") + + # Form a minimum spanning tree of the locations + try: + from scipy.sparse.csgraph import minimum_spanning_tree + + graph = [[0] * len(locations) for _ in range(len(locations))] + axes = set() + for l in locations: + axes.update(l.keys()) + axes = sorted(axes) + vectors = [tuple(l.get(k, 0) for k in axes) for l in locations] + for i, j in itertools.combinations(range(len(locations)), 2): + i_discrete_location = { + k: v for k, v in zip(axes, vectors[i]) if k in discrete_axes + } + j_discrete_location = { + k: v for k, v in zip(axes, vectors[j]) if k in discrete_axes + } + if i_discrete_location != j_discrete_location: + continue + graph[i][j] = vdiff_hypot2(vectors[i], vectors[j]) + + tree = minimum_spanning_tree(graph, overwrite=True) + rows, cols = tree.nonzero() + graph = defaultdict(set) + for row, col in zip(rows, cols): + graph[row].add(col) + graph[col].add(row) + + # Traverse graph from the base and assign parents + parents = [None] * len(locations) + order = [] + visited = set() + queue = deque(bases) + while queue: + i = queue.popleft() + visited.add(i) + order.append(i) + for j in sorted(graph[i]): + if j not in visited: + parents[j] = i + queue.append(j) + assert len(order) == len( + parents + ), "Not all masters are reachable; report an issue" + + except ImportError: + pass + + log.info("Parents: %s", parents) + log.info("Order: %s", order) + return parents, order diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatablePlot.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatablePlot.py new file mode 100644 index 0000000000000000000000000000000000000000..6685cd763a0c126c544145cea46193142a56b68d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatablePlot.py @@ -0,0 +1,1264 @@ +from .interpolatableHelpers import * +from fontTools.ttLib import TTFont +from fontTools.ttLib.ttGlyphSet import LerpGlyphSet +from fontTools.pens.recordingPen import ( + RecordingPen, + DecomposingRecordingPen, + RecordingPointPen, +) +from fontTools.pens.boundsPen import ControlBoundsPen +from fontTools.pens.cairoPen import CairoPen +from fontTools.pens.pointPen import ( + SegmentToPointPen, + PointToSegmentPen, + ReverseContourPointPen, +) +from itertools import cycle +from io import BytesIO +import cairo +import math +import os +import logging + +log = logging.getLogger("fontTools.varLib.interpolatable") + + +class OverridingDict(dict): + def __init__(self, parent_dict): + self.parent_dict = parent_dict + + def __missing__(self, key): + return self.parent_dict[key] + + +class InterpolatablePlot: + width = 8.5 * 72 + height = 11 * 72 + pad = 0.1 * 72 + title_font_size = 24 + font_size = 16 + page_number = 1 + head_color = (0.3, 0.3, 0.3) + label_color = (0.2, 0.2, 0.2) + border_color = (0.9, 0.9, 0.9) + border_width = 0.5 + fill_color = (0.8, 0.8, 0.8) + stroke_color = (0.1, 0.1, 0.1) + stroke_width = 1 + oncurve_node_color = (0, 0.8, 0, 0.7) + oncurve_node_diameter = 6 + offcurve_node_color = (0, 0.5, 0, 0.7) + offcurve_node_diameter = 4 + handle_color = (0, 0.5, 0, 0.7) + handle_width = 0.5 + corrected_start_point_color = (0, 0.9, 0, 0.7) + corrected_start_point_size = 7 + wrong_start_point_color = (1, 0, 0, 0.7) + start_point_color = (0, 0, 1, 0.7) + start_arrow_length = 9 + kink_point_size = 7 + kink_point_color = (1, 0, 1, 0.7) + kink_circle_size = 15 + kink_circle_stroke_width = 1 + kink_circle_color = (1, 0, 1, 0.7) + contour_colors = ((1, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 0), (1, 0, 1), (0, 1, 1)) + contour_alpha = 0.5 + weight_issue_contour_color = (0, 0, 0, 0.4) + no_issues_label = "Your font's good! Have a cupcake..." + no_issues_label_color = (0, 0.5, 0) + cupcake_color = (0.3, 0, 0.3) + cupcake = r""" + ,@. + ,@.@@,. + ,@@,.@@@. @.@@@,. + ,@@. @@@. @@. @@,. + ,@@@.@,.@. @. @@@@,.@.@@,. + ,@@.@. @@.@@. @,. .@' @' @@, + ,@@. @. .@@.@@@. @@' @, +,@. @@. @, +@. @,@@,. , .@@, +@,. .@,@@,. .@@,. , .@@, @, @, +@. .@. @ @@,. , @ + @,.@@. @,. @@,. @. @,. @' + @@||@,. @'@,. @@,. @@ @,. @'@@, @' + \\@@@@' @,. @'@@@@' @@,. @@@' //@@@' + |||||||| @@,. @@' ||||||| |@@@|@|| || + \\\\\\\ ||@@@|| ||||||| ||||||| // + ||||||| |||||| |||||| |||||| || + \\\\\\ |||||| |||||| |||||| // + |||||| ||||| ||||| ||||| || + \\\\\ ||||| ||||| ||||| // + ||||| |||| ||||| |||| || + \\\\ |||| |||| |||| // + |||||||||||||||||||||||| +""" + emoticon_color = (0, 0.3, 0.3) + shrug = r"""\_(")_/""" + underweight = r""" + o +/|\ +/ \ +""" + overweight = r""" + o +/O\ +/ \ +""" + yay = r""" \o/ """ + + def __init__(self, out, glyphsets, names=None, **kwargs): + self.out = out + self.glyphsets = glyphsets + self.names = names or [repr(g) for g in glyphsets] + self.toc = {} + + for k, v in kwargs.items(): + if not hasattr(self, k): + raise TypeError("Unknown keyword argument: %s" % k) + setattr(self, k, v) + + self.panel_width = self.width / 2 - self.pad * 3 + self.panel_height = ( + self.height / 2 - self.pad * 6 - self.font_size * 2 - self.title_font_size + ) + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + pass + + def show_page(self): + self.page_number += 1 + + def add_title_page( + self, files, *, show_tolerance=True, tolerance=None, kinkiness=None + ): + pad = self.pad + width = self.width - 3 * self.pad + x = y = pad + + self.draw_label( + "Problem report for:", + x=x, + y=y, + bold=True, + width=width, + font_size=self.title_font_size, + ) + y += self.title_font_size + + import hashlib + + for file in files: + base_file = os.path.basename(file) + y += self.font_size + self.pad + self.draw_label(base_file, x=x, y=y, bold=True, width=width) + y += self.font_size + self.pad + + try: + with open(file, "rb") as f: + h = hashlib.sha1(f.read()).hexdigest() + self.draw_label("sha1: %s" % h, x=x + pad, y=y, width=width) + y += self.font_size + except IsADirectoryError: + pass + + if file.endswith(".ttf"): + ttFont = TTFont(file) + name = ttFont["name"] if "name" in ttFont else None + if name: + for what, nameIDs in ( + ("Family name", (21, 16, 1)), + ("Version", (5,)), + ): + n = name.getFirstDebugName(nameIDs) + if n is None: + continue + self.draw_label( + "%s: %s" % (what, n), x=x + pad, y=y, width=width + ) + y += self.font_size + self.pad + elif file.endswith((".glyphs", ".glyphspackage")): + from glyphsLib import GSFont + + f = GSFont(file) + for what, field in ( + ("Family name", "familyName"), + ("VersionMajor", "versionMajor"), + ("VersionMinor", "_versionMinor"), + ): + self.draw_label( + "%s: %s" % (what, getattr(f, field)), + x=x + pad, + y=y, + width=width, + ) + y += self.font_size + self.pad + + self.draw_legend( + show_tolerance=show_tolerance, tolerance=tolerance, kinkiness=kinkiness + ) + self.show_page() + + def draw_legend(self, *, show_tolerance=True, tolerance=None, kinkiness=None): + cr = cairo.Context(self.surface) + + x = self.pad + y = self.height - self.pad - self.font_size * 2 + width = self.width - 2 * self.pad + + xx = x + self.pad * 2 + xxx = x + self.pad * 4 + + if show_tolerance: + self.draw_label( + "Tolerance: badness; closer to zero the worse", x=xxx, y=y, width=width + ) + y -= self.pad + self.font_size + + self.draw_label("Underweight contours", x=xxx, y=y, width=width) + cr.rectangle(xx - self.pad * 0.7, y, 1.5 * self.pad, self.font_size) + cr.set_source_rgb(*self.fill_color) + cr.fill_preserve() + if self.stroke_color: + cr.set_source_rgb(*self.stroke_color) + cr.set_line_width(self.stroke_width) + cr.stroke_preserve() + cr.set_source_rgba(*self.weight_issue_contour_color) + cr.fill() + y -= self.pad + self.font_size + + self.draw_label( + "Colored contours: contours with the wrong order", x=xxx, y=y, width=width + ) + cr.rectangle(xx - self.pad * 0.7, y, 1.5 * self.pad, self.font_size) + if self.fill_color: + cr.set_source_rgb(*self.fill_color) + cr.fill_preserve() + if self.stroke_color: + cr.set_source_rgb(*self.stroke_color) + cr.set_line_width(self.stroke_width) + cr.stroke_preserve() + cr.set_source_rgba(*self.contour_colors[0], self.contour_alpha) + cr.fill() + y -= self.pad + self.font_size + + self.draw_label("Kink artifact", x=xxx, y=y, width=width) + self.draw_circle( + cr, + x=xx, + y=y + self.font_size * 0.5, + diameter=self.kink_circle_size, + stroke_width=self.kink_circle_stroke_width, + color=self.kink_circle_color, + ) + y -= self.pad + self.font_size + + self.draw_label("Point causing kink in the contour", x=xxx, y=y, width=width) + self.draw_dot( + cr, + x=xx, + y=y + self.font_size * 0.5, + diameter=self.kink_point_size, + color=self.kink_point_color, + ) + y -= self.pad + self.font_size + + self.draw_label("Suggested new contour start point", x=xxx, y=y, width=width) + self.draw_dot( + cr, + x=xx, + y=y + self.font_size * 0.5, + diameter=self.corrected_start_point_size, + color=self.corrected_start_point_color, + ) + y -= self.pad + self.font_size + + self.draw_label( + "Contour start point in contours with wrong direction", + x=xxx, + y=y, + width=width, + ) + self.draw_arrow( + cr, + x=xx - self.start_arrow_length * 0.3, + y=y + self.font_size * 0.5, + color=self.wrong_start_point_color, + ) + y -= self.pad + self.font_size + + self.draw_label( + "Contour start point when the first two points overlap", + x=xxx, + y=y, + width=width, + ) + self.draw_dot( + cr, + x=xx, + y=y + self.font_size * 0.5, + diameter=self.corrected_start_point_size, + color=self.start_point_color, + ) + y -= self.pad + self.font_size + + self.draw_label("Contour start point and direction", x=xxx, y=y, width=width) + self.draw_arrow( + cr, + x=xx - self.start_arrow_length * 0.3, + y=y + self.font_size * 0.5, + color=self.start_point_color, + ) + y -= self.pad + self.font_size + + self.draw_label("Legend:", x=x, y=y, width=width, bold=True) + y -= self.pad + self.font_size + + if kinkiness is not None: + self.draw_label( + "Kink-reporting aggressiveness: %g" % kinkiness, + x=xxx, + y=y, + width=width, + ) + y -= self.pad + self.font_size + + if tolerance is not None: + self.draw_label( + "Error tolerance: %g" % tolerance, + x=xxx, + y=y, + width=width, + ) + y -= self.pad + self.font_size + + self.draw_label("Parameters:", x=x, y=y, width=width, bold=True) + y -= self.pad + self.font_size + + def add_summary(self, problems): + pad = self.pad + width = self.width - 3 * self.pad + height = self.height - 2 * self.pad + x = y = pad + + self.draw_label( + "Summary of problems", + x=x, + y=y, + bold=True, + width=width, + font_size=self.title_font_size, + ) + y += self.title_font_size + + glyphs_per_problem = defaultdict(set) + for glyphname, glyph_problems in sorted(problems.items()): + for problem in glyph_problems: + glyphs_per_problem[problem["type"]].add(glyphname) + + if InterpolatableProblem.NOTHING in glyphs_per_problem: + del glyphs_per_problem[InterpolatableProblem.NOTHING] + + for problem_type in sorted( + glyphs_per_problem, key=lambda x: InterpolatableProblem.severity[x] + ): + y += self.font_size + self.draw_label( + "%s: %d" % (problem_type, len(glyphs_per_problem[problem_type])), + x=x, + y=y, + width=width, + bold=True, + ) + y += self.font_size + + for glyphname in sorted(glyphs_per_problem[problem_type]): + if y + self.font_size > height: + self.show_page() + y = self.font_size + pad + self.draw_label(glyphname, x=x + 2 * pad, y=y, width=width - 2 * pad) + y += self.font_size + + self.show_page() + + def _add_listing(self, title, items): + pad = self.pad + width = self.width - 2 * self.pad + height = self.height - 2 * self.pad + x = y = pad + + self.draw_label( + title, x=x, y=y, bold=True, width=width, font_size=self.title_font_size + ) + y += self.title_font_size + self.pad + + last_glyphname = None + for page_no, (glyphname, problems) in items: + if glyphname == last_glyphname: + continue + last_glyphname = glyphname + if y + self.font_size > height: + self.show_page() + y = self.font_size + pad + self.draw_label(glyphname, x=x + 5 * pad, y=y, width=width - 2 * pad) + self.draw_label(str(page_no), x=x, y=y, width=4 * pad, align=1) + y += self.font_size + + self.show_page() + + def add_table_of_contents(self): + self._add_listing("Table of contents", sorted(self.toc.items())) + + def add_index(self): + self._add_listing("Index", sorted(self.toc.items(), key=lambda x: x[1][0])) + + def add_problems(self, problems, *, show_tolerance=True, show_page_number=True): + for glyph, glyph_problems in problems.items(): + last_masters = None + current_glyph_problems = [] + for p in glyph_problems: + masters = ( + p["master_idx"] + if "master_idx" in p + else (p["master_1_idx"], p["master_2_idx"]) + ) + if masters == last_masters: + current_glyph_problems.append(p) + continue + # Flush + if current_glyph_problems: + self.add_problem( + glyph, + current_glyph_problems, + show_tolerance=show_tolerance, + show_page_number=show_page_number, + ) + self.show_page() + current_glyph_problems = [] + last_masters = masters + current_glyph_problems.append(p) + if current_glyph_problems: + self.add_problem( + glyph, + current_glyph_problems, + show_tolerance=show_tolerance, + show_page_number=show_page_number, + ) + self.show_page() + + def add_problem( + self, glyphname, problems, *, show_tolerance=True, show_page_number=True + ): + if type(problems) not in (list, tuple): + problems = [problems] + + self.toc[self.page_number] = (glyphname, problems) + + problem_type = problems[0]["type"] + problem_types = set(problem["type"] for problem in problems) + if not all(pt == problem_type for pt in problem_types): + problem_type = ", ".join(sorted({problem["type"] for problem in problems})) + + log.info("Drawing %s: %s", glyphname, problem_type) + + master_keys = ( + ("master_idx",) + if "master_idx" in problems[0] + else ("master_1_idx", "master_2_idx") + ) + master_indices = [problems[0][k] for k in master_keys] + + if problem_type == InterpolatableProblem.MISSING: + sample_glyph = next( + i for i, m in enumerate(self.glyphsets) if m[glyphname] is not None + ) + master_indices.insert(0, sample_glyph) + + x = self.pad + y = self.pad + + self.draw_label( + "Glyph name: " + glyphname, + x=x, + y=y, + color=self.head_color, + align=0, + bold=True, + font_size=self.title_font_size, + ) + tolerance = min(p.get("tolerance", 1) for p in problems) + if tolerance < 1 and show_tolerance: + self.draw_label( + "tolerance: %.2f" % tolerance, + x=x, + y=y, + width=self.width - 2 * self.pad, + align=1, + bold=True, + ) + y += self.title_font_size + self.pad + self.draw_label( + "Problems: " + problem_type, + x=x, + y=y, + width=self.width - 2 * self.pad, + color=self.head_color, + bold=True, + ) + y += self.font_size + self.pad * 2 + + scales = [] + for which, master_idx in enumerate(master_indices): + glyphset = self.glyphsets[master_idx] + name = self.names[master_idx] + + self.draw_label( + name, + x=x, + y=y, + color=self.label_color, + width=self.panel_width, + align=0.5, + ) + y += self.font_size + self.pad + + if glyphset[glyphname] is not None: + scales.append( + self.draw_glyph(glyphset, glyphname, problems, which, x=x, y=y) + ) + else: + self.draw_emoticon(self.shrug, x=x, y=y) + y += self.panel_height + self.font_size + self.pad + + if any( + pt + in ( + InterpolatableProblem.NOTHING, + InterpolatableProblem.WRONG_START_POINT, + InterpolatableProblem.CONTOUR_ORDER, + InterpolatableProblem.KINK, + InterpolatableProblem.UNDERWEIGHT, + InterpolatableProblem.OVERWEIGHT, + ) + for pt in problem_types + ): + x = self.pad + self.panel_width + self.pad + y = self.pad + y += self.title_font_size + self.pad * 2 + y += self.font_size + self.pad + + glyphset1 = self.glyphsets[master_indices[0]] + glyphset2 = self.glyphsets[master_indices[1]] + + # Draw the mid-way of the two masters + + self.draw_label( + "midway interpolation", + x=x, + y=y, + color=self.head_color, + width=self.panel_width, + align=0.5, + ) + y += self.font_size + self.pad + + midway_glyphset = LerpGlyphSet(glyphset1, glyphset2) + self.draw_glyph( + midway_glyphset, + glyphname, + [{"type": "midway"}] + + [ + p + for p in problems + if p["type"] + in ( + InterpolatableProblem.KINK, + InterpolatableProblem.UNDERWEIGHT, + InterpolatableProblem.OVERWEIGHT, + ) + ], + None, + x=x, + y=y, + scale=min(scales), + ) + + y += self.panel_height + self.font_size + self.pad + + if any( + pt + in ( + InterpolatableProblem.WRONG_START_POINT, + InterpolatableProblem.CONTOUR_ORDER, + InterpolatableProblem.KINK, + ) + for pt in problem_types + ): + # Draw the proposed fix + + self.draw_label( + "proposed fix", + x=x, + y=y, + color=self.head_color, + width=self.panel_width, + align=0.5, + ) + y += self.font_size + self.pad + + overriding1 = OverridingDict(glyphset1) + overriding2 = OverridingDict(glyphset2) + perContourPen1 = PerContourOrComponentPen( + RecordingPen, glyphset=overriding1 + ) + perContourPen2 = PerContourOrComponentPen( + RecordingPen, glyphset=overriding2 + ) + glyphset1[glyphname].draw(perContourPen1) + glyphset2[glyphname].draw(perContourPen2) + + for problem in problems: + if problem["type"] == InterpolatableProblem.CONTOUR_ORDER: + fixed_contours = [ + perContourPen2.value[i] for i in problems[0]["value_2"] + ] + perContourPen2.value = fixed_contours + + for problem in problems: + if problem["type"] == InterpolatableProblem.WRONG_START_POINT: + # Save the wrong contours + wrongContour1 = perContourPen1.value[problem["contour"]] + wrongContour2 = perContourPen2.value[problem["contour"]] + + # Convert the wrong contours to point pens + points1 = RecordingPointPen() + converter = SegmentToPointPen(points1, False) + wrongContour1.replay(converter) + points2 = RecordingPointPen() + converter = SegmentToPointPen(points2, False) + wrongContour2.replay(converter) + + proposed_start = problem["value_2"] + + # See if we need reversing; fragile but worth a try + if problem["reversed"]: + new_points2 = RecordingPointPen() + reversedPen = ReverseContourPointPen(new_points2) + points2.replay(reversedPen) + points2 = new_points2 + proposed_start = len(points2.value) - 2 - proposed_start + + # Rotate points2 so that the first point is the same as in points1 + beginPath = points2.value[:1] + endPath = points2.value[-1:] + pts = points2.value[1:-1] + pts = pts[proposed_start:] + pts[:proposed_start] + points2.value = beginPath + pts + endPath + + # Convert the point pens back to segment pens + segment1 = RecordingPen() + converter = PointToSegmentPen(segment1, True) + points1.replay(converter) + segment2 = RecordingPen() + converter = PointToSegmentPen(segment2, True) + points2.replay(converter) + + # Replace the wrong contours + wrongContour1.value = segment1.value + wrongContour2.value = segment2.value + perContourPen1.value[problem["contour"]] = wrongContour1 + perContourPen2.value[problem["contour"]] = wrongContour2 + + for problem in problems: + # If we have a kink, try to fix it. + if problem["type"] == InterpolatableProblem.KINK: + # Save the wrong contours + wrongContour1 = perContourPen1.value[problem["contour"]] + wrongContour2 = perContourPen2.value[problem["contour"]] + + # Convert the wrong contours to point pens + points1 = RecordingPointPen() + converter = SegmentToPointPen(points1, False) + wrongContour1.replay(converter) + points2 = RecordingPointPen() + converter = SegmentToPointPen(points2, False) + wrongContour2.replay(converter) + + i = problem["value"] + + # Position points to be around the same ratio + # beginPath / endPath dance + j = i + 1 + pt0 = points1.value[j][1][0] + pt1 = points2.value[j][1][0] + j_prev = (i - 1) % (len(points1.value) - 2) + 1 + pt0_prev = points1.value[j_prev][1][0] + pt1_prev = points2.value[j_prev][1][0] + j_next = (i + 1) % (len(points1.value) - 2) + 1 + pt0_next = points1.value[j_next][1][0] + pt1_next = points2.value[j_next][1][0] + + pt0 = complex(*pt0) + pt1 = complex(*pt1) + pt0_prev = complex(*pt0_prev) + pt1_prev = complex(*pt1_prev) + pt0_next = complex(*pt0_next) + pt1_next = complex(*pt1_next) + + # Find the ratio of the distance between the points + r0 = abs(pt0 - pt0_prev) / abs(pt0_next - pt0_prev) + r1 = abs(pt1 - pt1_prev) / abs(pt1_next - pt1_prev) + r_mid = (r0 + r1) / 2 + + pt0 = pt0_prev + r_mid * (pt0_next - pt0_prev) + pt1 = pt1_prev + r_mid * (pt1_next - pt1_prev) + + points1.value[j] = ( + points1.value[j][0], + (((pt0.real, pt0.imag),) + points1.value[j][1][1:]), + points1.value[j][2], + ) + points2.value[j] = ( + points2.value[j][0], + (((pt1.real, pt1.imag),) + points2.value[j][1][1:]), + points2.value[j][2], + ) + + # Convert the point pens back to segment pens + segment1 = RecordingPen() + converter = PointToSegmentPen(segment1, True) + points1.replay(converter) + segment2 = RecordingPen() + converter = PointToSegmentPen(segment2, True) + points2.replay(converter) + + # Replace the wrong contours + wrongContour1.value = segment1.value + wrongContour2.value = segment2.value + + # Assemble + fixed1 = RecordingPen() + fixed2 = RecordingPen() + for contour in perContourPen1.value: + fixed1.value.extend(contour.value) + for contour in perContourPen2.value: + fixed2.value.extend(contour.value) + fixed1.draw = fixed1.replay + fixed2.draw = fixed2.replay + + overriding1[glyphname] = fixed1 + overriding2[glyphname] = fixed2 + + try: + midway_glyphset = LerpGlyphSet(overriding1, overriding2) + self.draw_glyph( + midway_glyphset, + glyphname, + {"type": "fixed"}, + None, + x=x, + y=y, + scale=min(scales), + ) + except ValueError: + self.draw_emoticon(self.shrug, x=x, y=y) + y += self.panel_height + self.pad + + else: + emoticon = self.shrug + if InterpolatableProblem.UNDERWEIGHT in problem_types: + emoticon = self.underweight + elif InterpolatableProblem.OVERWEIGHT in problem_types: + emoticon = self.overweight + elif InterpolatableProblem.NOTHING in problem_types: + emoticon = self.yay + self.draw_emoticon(emoticon, x=x, y=y) + + if show_page_number: + self.draw_label( + str(self.page_number), + x=0, + y=self.height - self.font_size - self.pad, + width=self.width, + color=self.head_color, + align=0.5, + ) + + def draw_label( + self, + label, + *, + x=0, + y=0, + color=(0, 0, 0), + align=0, + bold=False, + width=None, + height=None, + font_size=None, + ): + if width is None: + width = self.width + if height is None: + height = self.height + if font_size is None: + font_size = self.font_size + cr = cairo.Context(self.surface) + cr.select_font_face( + "@cairo:", + cairo.FONT_SLANT_NORMAL, + cairo.FONT_WEIGHT_BOLD if bold else cairo.FONT_WEIGHT_NORMAL, + ) + cr.set_font_size(font_size) + font_extents = cr.font_extents() + font_size = font_size * font_size / font_extents[2] + cr.set_font_size(font_size) + font_extents = cr.font_extents() + + cr.set_source_rgb(*color) + + extents = cr.text_extents(label) + if extents.width > width: + # Shrink + font_size *= width / extents.width + cr.set_font_size(font_size) + font_extents = cr.font_extents() + extents = cr.text_extents(label) + + # Center + label_x = x + (width - extents.width) * align + label_y = y + font_extents[0] + cr.move_to(label_x, label_y) + cr.show_text(label) + + def draw_glyph(self, glyphset, glyphname, problems, which, *, x=0, y=0, scale=None): + if type(problems) not in (list, tuple): + problems = [problems] + + midway = any(problem["type"] == "midway" for problem in problems) + problem_type = problems[0]["type"] + problem_types = set(problem["type"] for problem in problems) + if not all(pt == problem_type for pt in problem_types): + problem_type = "mixed" + glyph = glyphset[glyphname] + + recording = RecordingPen() + glyph.draw(recording) + decomposedRecording = DecomposingRecordingPen(glyphset) + glyph.draw(decomposedRecording) + + boundsPen = ControlBoundsPen(glyphset) + decomposedRecording.replay(boundsPen) + bounds = boundsPen.bounds + if bounds is None: + bounds = (0, 0, 0, 0) + + glyph_width = bounds[2] - bounds[0] + glyph_height = bounds[3] - bounds[1] + + if glyph_width: + if scale is None: + scale = self.panel_width / glyph_width + else: + scale = min(scale, self.panel_width / glyph_width) + if glyph_height: + if scale is None: + scale = self.panel_height / glyph_height + else: + scale = min(scale, self.panel_height / glyph_height) + if scale is None: + scale = 1 + + cr = cairo.Context(self.surface) + cr.translate(x, y) + # Center + cr.translate( + (self.panel_width - glyph_width * scale) / 2, + (self.panel_height - glyph_height * scale) / 2, + ) + cr.scale(scale, -scale) + cr.translate(-bounds[0], -bounds[3]) + + if self.border_color: + cr.set_source_rgb(*self.border_color) + cr.rectangle(bounds[0], bounds[1], glyph_width, glyph_height) + cr.set_line_width(self.border_width / scale) + cr.stroke() + + if self.fill_color or self.stroke_color: + pen = CairoPen(glyphset, cr) + decomposedRecording.replay(pen) + + if self.fill_color and problem_type != InterpolatableProblem.OPEN_PATH: + cr.set_source_rgb(*self.fill_color) + cr.fill_preserve() + + if self.stroke_color: + cr.set_source_rgb(*self.stroke_color) + cr.set_line_width(self.stroke_width / scale) + cr.stroke_preserve() + + cr.new_path() + + if ( + InterpolatableProblem.UNDERWEIGHT in problem_types + or InterpolatableProblem.OVERWEIGHT in problem_types + ): + perContourPen = PerContourOrComponentPen(RecordingPen, glyphset=glyphset) + recording.replay(perContourPen) + for problem in problems: + if problem["type"] in ( + InterpolatableProblem.UNDERWEIGHT, + InterpolatableProblem.OVERWEIGHT, + ): + contour = perContourPen.value[problem["contour"]] + contour.replay(CairoPen(glyphset, cr)) + cr.set_source_rgba(*self.weight_issue_contour_color) + cr.fill() + + if any( + t in problem_types + for t in { + InterpolatableProblem.NOTHING, + InterpolatableProblem.NODE_COUNT, + InterpolatableProblem.NODE_INCOMPATIBILITY, + } + ): + cr.set_line_cap(cairo.LINE_CAP_ROUND) + + # Oncurve nodes + for segment, args in decomposedRecording.value: + if not args: + continue + x, y = args[-1] + cr.move_to(x, y) + cr.line_to(x, y) + cr.set_source_rgba(*self.oncurve_node_color) + cr.set_line_width(self.oncurve_node_diameter / scale) + cr.stroke() + + # Offcurve nodes + for segment, args in decomposedRecording.value: + if not args: + continue + for x, y in args[:-1]: + cr.move_to(x, y) + cr.line_to(x, y) + cr.set_source_rgba(*self.offcurve_node_color) + cr.set_line_width(self.offcurve_node_diameter / scale) + cr.stroke() + + # Handles + for segment, args in decomposedRecording.value: + if not args: + pass + elif segment in ("moveTo", "lineTo"): + cr.move_to(*args[0]) + elif segment == "qCurveTo": + for x, y in args: + cr.line_to(x, y) + cr.new_sub_path() + cr.move_to(*args[-1]) + elif segment == "curveTo": + cr.line_to(*args[0]) + cr.new_sub_path() + cr.move_to(*args[1]) + cr.line_to(*args[2]) + cr.new_sub_path() + cr.move_to(*args[-1]) + else: + continue + + cr.set_source_rgba(*self.handle_color) + cr.set_line_width(self.handle_width / scale) + cr.stroke() + + matching = None + for problem in problems: + if problem["type"] == InterpolatableProblem.CONTOUR_ORDER: + matching = problem["value_2"] + colors = cycle(self.contour_colors) + perContourPen = PerContourOrComponentPen( + RecordingPen, glyphset=glyphset + ) + recording.replay(perContourPen) + for i, contour in enumerate(perContourPen.value): + if matching[i] == i: + continue + color = next(colors) + contour.replay(CairoPen(glyphset, cr)) + cr.set_source_rgba(*color, self.contour_alpha) + cr.fill() + + for problem in problems: + if problem["type"] in ( + InterpolatableProblem.NOTHING, + InterpolatableProblem.WRONG_START_POINT, + ): + idx = problem.get("contour") + + # Draw suggested point + if idx is not None and which == 1 and "value_2" in problem: + perContourPen = PerContourOrComponentPen( + RecordingPen, glyphset=glyphset + ) + decomposedRecording.replay(perContourPen) + points = SimpleRecordingPointPen() + converter = SegmentToPointPen(points, False) + perContourPen.value[ + idx if matching is None else matching[idx] + ].replay(converter) + targetPoint = points.value[problem["value_2"]][0] + cr.save() + cr.translate(*targetPoint) + cr.scale(1 / scale, 1 / scale) + self.draw_dot( + cr, + diameter=self.corrected_start_point_size, + color=self.corrected_start_point_color, + ) + cr.restore() + + # Draw start-point arrow + if which == 0 or not problem.get("reversed"): + color = self.start_point_color + else: + color = self.wrong_start_point_color + first_pt = None + i = 0 + cr.save() + for segment, args in decomposedRecording.value: + if segment == "moveTo": + first_pt = args[0] + continue + if first_pt is None: + continue + if segment == "closePath": + second_pt = first_pt + else: + second_pt = args[0] + + if idx is None or i == idx: + cr.save() + first_pt = complex(*first_pt) + second_pt = complex(*second_pt) + length = abs(second_pt - first_pt) + cr.translate(first_pt.real, first_pt.imag) + if length: + # Draw arrowhead + cr.rotate( + math.atan2( + second_pt.imag - first_pt.imag, + second_pt.real - first_pt.real, + ) + ) + cr.scale(1 / scale, 1 / scale) + self.draw_arrow(cr, color=color) + else: + # Draw circle + cr.scale(1 / scale, 1 / scale) + self.draw_dot( + cr, + diameter=self.corrected_start_point_size, + color=color, + ) + cr.restore() + + if idx is not None: + break + + first_pt = None + i += 1 + + cr.restore() + + if problem["type"] == InterpolatableProblem.KINK: + idx = problem.get("contour") + perContourPen = PerContourOrComponentPen( + RecordingPen, glyphset=glyphset + ) + decomposedRecording.replay(perContourPen) + points = SimpleRecordingPointPen() + converter = SegmentToPointPen(points, False) + perContourPen.value[idx if matching is None else matching[idx]].replay( + converter + ) + + targetPoint = points.value[problem["value"]][0] + cr.save() + cr.translate(*targetPoint) + cr.scale(1 / scale, 1 / scale) + if midway: + self.draw_circle( + cr, + diameter=self.kink_circle_size, + stroke_width=self.kink_circle_stroke_width, + color=self.kink_circle_color, + ) + else: + self.draw_dot( + cr, + diameter=self.kink_point_size, + color=self.kink_point_color, + ) + cr.restore() + + return scale + + def draw_dot(self, cr, *, x=0, y=0, color=(0, 0, 0), diameter=10): + cr.save() + cr.set_line_width(diameter) + cr.set_line_cap(cairo.LINE_CAP_ROUND) + cr.move_to(x, y) + cr.line_to(x, y) + if len(color) == 3: + color = color + (1,) + cr.set_source_rgba(*color) + cr.stroke() + cr.restore() + + def draw_circle( + self, cr, *, x=0, y=0, color=(0, 0, 0), diameter=10, stroke_width=1 + ): + cr.save() + cr.set_line_width(stroke_width) + cr.set_line_cap(cairo.LINE_CAP_SQUARE) + cr.arc(x, y, diameter / 2, 0, 2 * math.pi) + if len(color) == 3: + color = color + (1,) + cr.set_source_rgba(*color) + cr.stroke() + cr.restore() + + def draw_arrow(self, cr, *, x=0, y=0, color=(0, 0, 0)): + cr.save() + if len(color) == 3: + color = color + (1,) + cr.set_source_rgba(*color) + cr.translate(self.start_arrow_length + x, y) + cr.move_to(0, 0) + cr.line_to( + -self.start_arrow_length, + -self.start_arrow_length * 0.4, + ) + cr.line_to( + -self.start_arrow_length, + self.start_arrow_length * 0.4, + ) + cr.close_path() + cr.fill() + cr.restore() + + def draw_text(self, text, *, x=0, y=0, color=(0, 0, 0), width=None, height=None): + if width is None: + width = self.width + if height is None: + height = self.height + + text = text.splitlines() + cr = cairo.Context(self.surface) + cr.set_source_rgb(*color) + cr.set_font_size(self.font_size) + cr.select_font_face( + "@cairo:monospace", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL + ) + text_width = 0 + text_height = 0 + font_extents = cr.font_extents() + font_font_size = font_extents[2] + font_ascent = font_extents[0] + for line in text: + extents = cr.text_extents(line) + text_width = max(text_width, extents.x_advance) + text_height += font_font_size + if not text_width: + return + cr.translate(x, y) + scale = min(width / text_width, height / text_height) + # center + cr.translate( + (width - text_width * scale) / 2, (height - text_height * scale) / 2 + ) + cr.scale(scale, scale) + + cr.translate(0, font_ascent) + for line in text: + cr.move_to(0, 0) + cr.show_text(line) + cr.translate(0, font_font_size) + + def draw_cupcake(self): + self.draw_label( + self.no_issues_label, + x=self.pad, + y=self.pad, + color=self.no_issues_label_color, + width=self.width - 2 * self.pad, + align=0.5, + bold=True, + font_size=self.title_font_size, + ) + + self.draw_text( + self.cupcake, + x=self.pad, + y=self.pad + self.font_size, + width=self.width - 2 * self.pad, + height=self.height - 2 * self.pad - self.font_size, + color=self.cupcake_color, + ) + + def draw_emoticon(self, emoticon, x=0, y=0): + self.draw_text( + emoticon, + x=x, + y=y, + color=self.emoticon_color, + width=self.panel_width, + height=self.panel_height, + ) + + +class InterpolatablePostscriptLike(InterpolatablePlot): + def __exit__(self, type, value, traceback): + self.surface.finish() + + def show_page(self): + super().show_page() + self.surface.show_page() + + +class InterpolatablePS(InterpolatablePostscriptLike): + def __enter__(self): + self.surface = cairo.PSSurface(self.out, self.width, self.height) + return self + + +class InterpolatablePDF(InterpolatablePostscriptLike): + def __enter__(self): + self.surface = cairo.PDFSurface(self.out, self.width, self.height) + self.surface.set_metadata( + cairo.PDF_METADATA_CREATOR, "fonttools varLib.interpolatable" + ) + self.surface.set_metadata(cairo.PDF_METADATA_CREATE_DATE, "") + return self + + +class InterpolatableSVG(InterpolatablePlot): + def __enter__(self): + self.sink = BytesIO() + self.surface = cairo.SVGSurface(self.sink, self.width, self.height) + return self + + def __exit__(self, type, value, traceback): + if self.surface is not None: + self.show_page() + + def show_page(self): + super().show_page() + self.surface.finish() + self.out.append(self.sink.getvalue()) + self.sink = BytesIO() + self.surface = cairo.SVGSurface(self.sink, self.width, self.height) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatableTestContourOrder.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatableTestContourOrder.py new file mode 100644 index 0000000000000000000000000000000000000000..f593e2bd4dbcd08dd6f8a9aad88d541a33c8009f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatableTestContourOrder.py @@ -0,0 +1,81 @@ +from .interpolatableHelpers import * +import logging + +log = logging.getLogger("fontTools.varLib.interpolatable") + + +def test_contour_order(glyph0, glyph1): + # We try matching both the StatisticsControlPen vector + # and the StatisticsPen vector. + # + # If either method found an identity matching, accept it. + # This is crucial for fonts like Kablammo[MORF].ttf and + # Nabla[EDPT,EHLT].ttf, since they really confuse the + # StatisticsPen vector because of their area=0 contours. + + n = len(glyph0.controlVectors) + matching = None + matching_cost = 0 + identity_cost = 0 + done = n <= 1 + if not done: + m0Control = glyph0.controlVectors + m1Control = glyph1.controlVectors + ( + matching_control, + matching_cost_control, + identity_cost_control, + ) = matching_for_vectors(m0Control, m1Control) + done = matching_cost_control == identity_cost_control + if not done: + m0Green = glyph0.greenVectors + m1Green = glyph1.greenVectors + ( + matching_green, + matching_cost_green, + identity_cost_green, + ) = matching_for_vectors(m0Green, m1Green) + done = matching_cost_green == identity_cost_green + + if not done: + # See if reversing contours in one master helps. + # That's a common problem. Then the wrong_start_point + # test will fix them. + # + # Reverse the sign of the area (0); the rest stay the same. + m1ControlReversed = [(-m[0],) + m[1:] for m in m1Control] + ( + matching_control_reversed, + matching_cost_control_reversed, + identity_cost_control_reversed, + ) = matching_for_vectors(m0Control, m1ControlReversed) + done = matching_cost_control_reversed == identity_cost_control_reversed + if not done: + m1GreenReversed = [(-m[0],) + m[1:] for m in m1Green] + ( + matching_green_reversed, + matching_cost_green_reversed, + identity_cost_green_reversed, + ) = matching_for_vectors(m0Green, m1GreenReversed) + done = matching_cost_green_reversed == identity_cost_green_reversed + + if not done: + # Otherwise, use the best of the two matchings. + if ( + matching_cost_control * identity_cost_green + < matching_cost_green * identity_cost_control + ): + matching = matching_control + matching_cost = matching_cost_control + identity_cost = identity_cost_control + else: + matching = matching_green + matching_cost = matching_cost_green + identity_cost = identity_cost_green + + this_tolerance = matching_cost / identity_cost if identity_cost else 1 + log.debug( + "test-contour-order: tolerance %g", + this_tolerance, + ) + return this_tolerance, matching diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatableTestStartingPoint.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatableTestStartingPoint.py new file mode 100644 index 0000000000000000000000000000000000000000..6c619ebe689ba3982a3eb7ea1b14d670c8f5536c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolatableTestStartingPoint.py @@ -0,0 +1,109 @@ +from .interpolatableHelpers import * + + +def test_starting_point(glyph0, glyph1, ix, tolerance, matching): + if matching is None: + matching = list(range(len(glyph0.isomorphisms))) + contour0 = glyph0.isomorphisms[ix] + contour1 = glyph1.isomorphisms[matching[ix]] + m0Vectors = glyph0.greenVectors + m1Vectors = [glyph1.greenVectors[i] for i in matching] + + c0 = contour0[0] + # Next few lines duplicated below. + costs = [vdiff_hypot2_complex(c0[0], c1[0]) for c1 in contour1] + min_cost_idx, min_cost = min(enumerate(costs), key=lambda x: x[1]) + first_cost = costs[0] + proposed_point = contour1[min_cost_idx][1] + reverse = contour1[min_cost_idx][2] + + if min_cost < first_cost * tolerance: + # c0 is the first isomorphism of the m0 master + # contour1 is list of all isomorphisms of the m1 master + # + # If the two shapes are both circle-ish and slightly + # rotated, we detect wrong start point. This is for + # example the case hundreds of times in + # RobotoSerif-Italic[GRAD,opsz,wdth,wght].ttf + # + # If the proposed point is only one off from the first + # point (and not reversed), try harder: + # + # Find the major eigenvector of the covariance matrix, + # and rotate the contours by that angle. Then find the + # closest point again. If it matches this time, let it + # pass. + + num_points = len(glyph1.points[ix]) + leeway = 3 + if not reverse and ( + proposed_point <= leeway or proposed_point >= num_points - leeway + ): + # Try harder + + # Recover the covariance matrix from the GreenVectors. + # This is a 2x2 matrix. + transforms = [] + for vector in (m0Vectors[ix], m1Vectors[ix]): + # meanX = vector[1] + # meanY = vector[2] + stddevX = vector[3] * 0.5 + stddevY = vector[4] * 0.5 + correlation = vector[5] + if correlation: + correlation /= abs(vector[0]) + + # https://cookierobotics.com/007/ + a = stddevX * stddevX # VarianceX + c = stddevY * stddevY # VarianceY + b = correlation * stddevX * stddevY # Covariance + + delta = (((a - c) * 0.5) ** 2 + b * b) ** 0.5 + lambda1 = (a + c) * 0.5 + delta # Major eigenvalue + lambda2 = (a + c) * 0.5 - delta # Minor eigenvalue + theta = atan2(lambda1 - a, b) if b != 0 else (pi * 0.5 if a < c else 0) + trans = Transform() + # Don't translate here. We are working on the complex-vector + # that includes more than just the points. It's horrible what + # we are doing anyway... + # trans = trans.translate(meanX, meanY) + trans = trans.rotate(theta) + if lambda2 < 0: + lambda2 = 0 + trans = trans.scale(sqrt(lambda1), sqrt(lambda2)) + transforms.append(trans) + + trans = transforms[0] + new_c0 = ( + [complex(*trans.transformPoint((pt.real, pt.imag))) for pt in c0[0]], + ) + c0[1:] + trans = transforms[1] + new_contour1 = [] + for c1 in contour1: + new_c1 = ( + [ + complex(*trans.transformPoint((pt.real, pt.imag))) + for pt in c1[0] + ], + ) + c1[1:] + new_contour1.append(new_c1) + + # Next few lines duplicate from above. + costs = [ + vdiff_hypot2_complex(new_c0[0], new_c1[0]) for new_c1 in new_contour1 + ] + min_cost_idx, min_cost = min(enumerate(costs), key=lambda x: x[1]) + first_cost = costs[0] + if min_cost < first_cost * tolerance: + # Don't report this + # min_cost = first_cost + # reverse = False + # proposed_point = 0 # new_contour1[min_cost_idx][1] + pass + + this_tolerance = min_cost / first_cost if first_cost else 1 + log.debug( + "test-starting-point: tolerance %g", + this_tolerance, + ) + return this_tolerance, proposed_point, reverse diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolate_layout.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolate_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..798b29590d31ded570e4974e227e0973d1546e72 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/interpolate_layout.py @@ -0,0 +1,124 @@ +""" +Interpolate OpenType Layout tables (GDEF / GPOS / GSUB). +""" + +from fontTools.ttLib import TTFont +from fontTools.varLib import models, VarLibError, load_designspace, load_masters +from fontTools.varLib.merger import InstancerMerger +import os.path +import logging +from copy import deepcopy +from pprint import pformat + +log = logging.getLogger("fontTools.varLib.interpolate_layout") + + +def interpolate_layout(designspace, loc, master_finder=lambda s: s, mapped=False): + """ + Interpolate GPOS from a designspace file and location. + + If master_finder is set, it should be a callable that takes master + filename as found in designspace file and map it to master font + binary as to be opened (eg. .ttf or .otf). + + If mapped is False (default), then location is mapped using the + map element of the axes in designspace file. If mapped is True, + it is assumed that location is in designspace's internal space and + no mapping is performed. + """ + if hasattr(designspace, "sources"): # Assume a DesignspaceDocument + pass + else: # Assume a file path + from fontTools.designspaceLib import DesignSpaceDocument + + designspace = DesignSpaceDocument.fromfile(designspace) + + ds = load_designspace(designspace) + log.info("Building interpolated font") + + log.info("Loading master fonts") + master_fonts = load_masters(designspace, master_finder) + font = deepcopy(master_fonts[ds.base_idx]) + + log.info("Location: %s", pformat(loc)) + if not mapped: + loc = {name: ds.axes[name].map_forward(v) for name, v in loc.items()} + log.info("Internal location: %s", pformat(loc)) + loc = models.normalizeLocation(loc, ds.internal_axis_supports) + log.info("Normalized location: %s", pformat(loc)) + + # Assume single-model for now. + model = models.VariationModel(ds.normalized_master_locs) + assert 0 == model.mapping[ds.base_idx] + + merger = InstancerMerger(font, model, loc) + + log.info("Building interpolated tables") + # TODO GSUB/GDEF + merger.mergeTables(font, master_fonts, ["GPOS"]) + return font + + +def main(args=None): + """Interpolate GDEF/GPOS/GSUB tables for a point on a designspace""" + from fontTools import configLogger + import argparse + import sys + + parser = argparse.ArgumentParser( + "fonttools varLib.interpolate_layout", + description=main.__doc__, + ) + parser.add_argument( + "designspace_filename", metavar="DESIGNSPACE", help="Input TTF files" + ) + parser.add_argument( + "locations", + metavar="LOCATION", + type=str, + nargs="+", + help="Axis locations (e.g. wdth=120", + ) + parser.add_argument( + "-o", + "--output", + metavar="OUTPUT", + help="Output font file (defaults to <designspacename>-instance.ttf)", + ) + parser.add_argument( + "-l", + "--loglevel", + metavar="LEVEL", + default="INFO", + help="Logging level (defaults to INFO)", + ) + + args = parser.parse_args(args) + + if not args.output: + args.output = os.path.splitext(args.designspace_filename)[0] + "-instance.ttf" + + configLogger(level=args.loglevel) + + finder = lambda s: s.replace("master_ufo", "master_ttf_interpolatable").replace( + ".ufo", ".ttf" + ) + + loc = {} + for arg in args.locations: + tag, val = arg.split("=") + loc[tag] = float(val) + + font = interpolate_layout(args.designspace_filename, loc, finder) + log.info("Saving font %s", args.output) + font.save(args.output) + + +if __name__ == "__main__": + import sys + + if len(sys.argv) > 1: + sys.exit(main()) + import doctest + + sys.exit(doctest.testmod().failed) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/iup.c b/.venv/lib/python3.12/site-packages/fontTools/varLib/iup.c new file mode 100644 index 0000000000000000000000000000000000000000..a2fdf5b29646994f0043cde2c3607db830a4c2c1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/iup.c @@ -0,0 +1,24658 @@ +/* Generated by Cython 3.3.0 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "name": "fontTools.varLib.iup", + "sources": [ + "Lib/fontTools/varLib/iup.py" + ] + }, + "module_name": "fontTools.varLib.iup" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +/* InitLimitedAPI */ +#if defined(Py_LIMITED_API) + #if !defined(CYTHON_LIMITED_API) + #define CYTHON_LIMITED_API 1 + #endif +#elif defined(CYTHON_LIMITED_API) + #ifdef _MSC_VER + #pragma message ("Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead.") + #else + #warning Limited API usage is enabled with 'CYTHON_LIMITED_API' but 'Py_LIMITED_API' does not define a Python target version. Consider setting 'Py_LIMITED_API' instead. + #endif +#endif + +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x03090000 + #error Cython requires Python 3.9+. +#elif defined(Py_LIMITED_API) && (Py_LIMITED_API & 0xFFFF0000) > (PY_VERSION_HEX & 0xFFFF0000) + #error 'Py_LIMITED_API' can only select past Python X.Y versions, not future ones. +#else +#define __PYX_ABI_VERSION "3_3_0" +#define CYTHON_HEX_VERSION 0x030300F0 +#define CYTHON_FUTURE_DIVISION 1 +/* CModulePreamble */ +#include <stddef.h> +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifdef __has_builtin + #define __Pyx_has_cbuiltin(name) __has_builtin(name) +#else + #define __Pyx_has_cbuiltin(name) (0) +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX +#if defined(CYTHON_LIMITED_API) + #ifdef Py_LIMITED_API + #undef __PYX_LIMITED_VERSION_HEX + #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API + #if Py_LIMITED_API < 0x03090000 + #error "Cython 3.3 requires the Python Limited API version to be 3.9 or greater." + #endif + #endif + #if defined(GRAALVM_PYTHON) || defined(PYPY_VERSION) + #ifdef _MSC_VER + #pragma message ("Py_LIMITED_API is defined on PyPy or GraalPy. This takes precedence over Cython's specialized\ + code for PyPy and GraalPy and is unlikely to work.") + #else + #warning "Py_LIMITED_API is defined on PyPy or GraalPy. This takes precedence over Cython's specialized\ + code for PyPy and GraalPy and is unlikely to work." + #endif + #endif + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 1 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 1 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #endif + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_VECTORCALL + #define CYTHON_VECTORCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) + #ifndef CYTHON_VECTORCALL_TPNEW + #define CYTHON_VECTORCALL_TPNEW (CYTHON_VECTORCALL && __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (__PYX_LIMITED_VERSION_HEX >= 0x030F0000 && PY_VERSION_HEX > 0x030F00A8) + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND (__PYX_LIMITED_VERSION_HEX >= 0x030A0000) + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #ifndef CYTHON_USE_OWN_PREP_RERAISE_STAR + #define CYTHON_USE_OWN_PREP_RERAISE_STAR 1 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 1 + #endif + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 + #if __PYX_LIMITED_VERSION_HEX < 0x030E0000 + #undef CYTHON_OPAQUE_OBJECTS + #define CYTHON_OPAQUE_OBJECTS 0 + #elif !defined(CYTHON_OPAQUE_OBJECTS) + #define CYTHON_OPAQUE_OBJECTS (__PYX_LIMITED_VERSION_HEX >= 0x030F0000) + #endif +#elif defined(GRAALVM_PYTHON) + /* For very preliminary testing purposes. Most variables are set the same as PyPy. + The existence of this section does not imply that anything works or is even tested */ + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 1 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #endif + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #ifndef CYTHON_VECTORCALL + #define CYTHON_VECTORCALL 1 + #endif + #if CYTHON_USE_TYPE_SPECS && PY_VERSION_HEX < 0x030E0000 + #undef CYTHON_VECTORCALL_TPNEW + #define CYTHON_VECTORCALL_TPNEW 0 + #elif !defined(CYTHON_VECTORCALL_TPNEW) + #define CYTHON_VECTORCALL_TPNEW CYTHON_VECTORCALL + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #ifndef CYTHON_USE_OWN_PREP_RERAISE_STAR + #define CYTHON_USE_OWN_PREP_RERAISE_STAR 1 + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 + #undef CYTHON_OPAQUE_OBJECTS + #define CYTHON_OPAQUE_OBJECTS 0 +#elif defined(PYPY_VERSION) + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #ifndef CYTHON_VECTORCALL + #define CYTHON_VECTORCALL 1 + #endif + #if CYTHON_USE_TYPE_SPECS && PY_VERSION_HEX < 0x030E0000 + #undef CYTHON_VECTORCALL_TPNEW + #define CYTHON_VECTORCALL_TPNEW 0 + #elif !defined(CYTHON_VECTORCALL_TPNEW) + #define CYTHON_VECTORCALL_TPNEW (PYPY_VERSION_NUM >= 0x07030800 && CYTHON_VECTORCALL) + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PYPY_VERSION_NUM >= 0x07030C00) + #endif + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC (PYPY_VERSION_NUM >= 0x07031100) + #endif + #ifndef CYTHON_USE_OWN_PREP_RERAISE_STAR + #define CYTHON_USE_OWN_PREP_RERAISE_STAR 1 + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 + #undef CYTHON_OPAQUE_OBJECTS + #define CYTHON_OPAQUE_OBJECTS 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #ifdef Py_GIL_DISABLED + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 1 + #else + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #endif + #if PY_VERSION_HEX < 0x030A0000 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #elif !defined(CYTHON_USE_TYPE_SLOTS) + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #ifndef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #ifndef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #elif !defined(CYTHON_USE_PYLIST_INTERNALS) + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #elif !defined(CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS) + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #elif !defined(CYTHON_FAST_GIL) + #define CYTHON_FAST_GIL (PY_VERSION_HEX < 0x030C00A6) + #endif + #ifndef CYTHON_VECTORCALL + #define CYTHON_VECTORCALL 1 + #endif + #if CYTHON_USE_TYPE_SPECS && PY_VERSION_HEX < 0x030E0000 + #undef CYTHON_VECTORCALL_TPNEW + #define CYTHON_VECTORCALL_TPNEW 0 + #elif !defined(CYTHON_VECTORCALL_TPNEW) + #define CYTHON_VECTORCALL_TPNEW CYTHON_VECTORCALL + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #ifndef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING (PY_VERSION_HEX >= 0x030d00B1) + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #elif !defined(CYTHON_USE_DICT_VERSIONS) + #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5 && !CYTHON_USE_MODULE_STATE) + #endif + #ifndef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif + #ifndef CYTHON_USE_OWN_PREP_RERAISE_STAR + #define CYTHON_USE_OWN_PREP_RERAISE_STAR (PY_VERSION_HEX < 0x030C00B2) + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS (!CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif + #if defined(CYTHON_IMMORTAL_CONSTANTS) && PY_VERSION_HEX < 0x030C0000 + #undef CYTHON_IMMORTAL_CONSTANTS + #define CYTHON_IMMORTAL_CONSTANTS 0 // definitely won't work + #elif !defined(CYTHON_IMMORTAL_CONSTANTS) + #define CYTHON_IMMORTAL_CONSTANTS (PY_VERSION_HEX >= 0x030C0000 && !CYTHON_USE_MODULE_STATE && CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif + #ifndef CYTHON_OPAQUE_OBJECTS + #define CYTHON_OPAQUE_OBJECTS 0 + #endif +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(maybe_unused) + #define CYTHON_UNUSED [[maybe_unused]] + #endif + #endif + #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L + #define CYTHON_UNUSED [[maybe_unused]] + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_UNUSED_VAR +# if defined(__cplusplus) + template<class T> void CYTHON_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR + #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_USE_CPP_STD_MOVE + #if defined(__cplusplus) && (\ + __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) + #define CYTHON_USE_CPP_STD_MOVE 1 + #else + #define CYTHON_USE_CPP_STD_MOVE 0 + #endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#include <stdint.h> +typedef uintptr_t __pyx_uintptr_t; +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif +#ifdef Py_UNREACHABLE + #define __Pyx_UNREACHABLE() Py_UNREACHABLE() +#elif __Pyx_has_cbuiltin(__builtin_unreachable) + #define __Pyx_UNREACHABLE() __builtin_unreachable() +#elif defined(__clang__) || defined(__INTEL_COMPILER) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))) + #define __Pyx_UNREACHABLE() __builtin_unreachable() +#elif defined(_MSC_VER) + #define __Pyx_UNREACHABLE() __assume(0) +#else + #define __Pyx_UNREACHABLE() Py_FatalError("Unreachable C code path reached") +#endif +#ifndef Py_UNREACHABLE + #define Py_UNREACHABLE() __Pyx_UNREACHABLE() +#endif +#ifdef __cplusplus + template <typename T> + struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; + #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL<type>::value) +#else + #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) +#endif +#if CYTHON_COMPILING_IN_PYPY == 1 + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX < 0x030A0000) +#else + #define __PYX_NEED_TP_PRINT_SLOT 0 +#endif +#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +#define __Pyx_PyErr_FetchException(petype, peval, petb) PyErr_Fetch(petype, peval, petb) +#define __Pyx_PyErr_RestoreException(etype, eval, etb) PyErr_Restore(etype, eval, etb) +#else +#define __Pyx_PyErr_FetchException(petype, peval, petb) *(petype)=NULL; *(peval)=PyErr_GetRaisedException(); *(petb)=NULL +#define __Pyx_PyErr_RestoreException(etype, eval, etb) PyErr_SetRaisedException(eval) +#endif + +/* CInitCode */ +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #elif defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +/* PythonCompatibility */ +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#define __Pyx_BUILTIN_MODULE_NAME "builtins" +#define __Pyx_DefaultClassType PyType_Type +#if CYTHON_COMPILING_IN_LIMITED_API + #ifndef CO_OPTIMIZED + static int CO_OPTIMIZED; + #endif + #ifndef CO_NEWLOCALS + static int CO_NEWLOCALS; + #endif + #ifndef CO_VARARGS + static int CO_VARARGS; + #endif + #ifndef CO_VARKEYWORDS + static int CO_VARKEYWORDS; + #endif + #ifndef CO_ASYNC_GENERATOR + static int CO_ASYNC_GENERATOR; + #endif + #ifndef CO_GENERATOR + static int CO_GENERATOR; + #endif + #ifndef CO_COROUTINE + static int CO_COROUTINE; + #endif +#else + #ifndef CO_COROUTINE + #define CO_COROUTINE 0x80 + #endif + #ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x200 + #endif +#endif +static int __Pyx_init_co_variables(void); +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) + #define __Pyx_Py_Is(x, y) Py_Is(x, y) +#else + #define __Pyx_Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) + #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) +#else + #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) + #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) +#else + #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) + #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) +#else + #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) +#endif +#define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) +#else + #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static unsigned long __Pyx_Runtime_TPFLAGS_SEQUENCE; +static unsigned long __Pyx_Runtime_TPFLAGS_MAPPING; +#else +#define __Pyx_Runtime_TPFLAGS_SEQUENCE Py_TPFLAGS_SEQUENCE +#define __Pyx_Runtime_TPFLAGS_MAPPING Py_TPFLAGS_MAPPING +#endif +static int __Pyx_init_tpflags_variables(void); +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef Py_TPFLAGS_SEQUENCE + #define Py_TPFLAGS_SEQUENCE (CYTHON_COMPILING_IN_LIMITED_API ? 0 : 1 << 5) +#endif +#ifndef Py_TPFLAGS_MAPPING + #define Py_TPFLAGS_MAPPING (CYTHON_COMPILING_IN_LIMITED_API ? 0 : 1 << 6) +#endif +#ifndef Py_TPFLAGS_IMMUTABLETYPE + #define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8) +#endif +#ifndef Py_TPFLAGS_DISALLOW_INSTANTIATION + #define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7) +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#if !defined(METH_FASTCALL) || CYTHON_COMPILING_IN_PYPY + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #if PY_VERSION_HEX >= 0x030d00A4 + # define __Pyx_PyCFunctionFast PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords PyCFunctionFastWithKeywords + #else + # define __Pyx_PyCFunctionFast _PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords + #endif +#endif +#if CYTHON_VECTORCALL + #define __Pyx_METH_FASTCALL METH_FASTCALL + #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast + #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords +#else + #define __Pyx_METH_FASTCALL METH_VARARGS + #define __Pyx_PyCFunction_FastCall PyCFunction + #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords +#endif +#if CYTHON_VECTORCALL + #define __pyx_vectorcallfunc vectorcallfunc + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET + #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) +#else + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) +#endif +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) +#define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) +#elif !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) +#endif +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) +static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { + return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; +} +#endif +static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void (*cfunc)(void)) { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; +#else + return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +#endif +} +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) +#else + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) +#endif +#if CYTHON_COMPILING_IN_PYPY + typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); +#else + #define __Pyx_PyCMethod PyCMethod +#endif +#ifndef METH_METHOD + #define METH_METHOD 0x200 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) +#elif CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) GraalPyFrame_SetLineNumber((frame), (lineno)) +#elif CYTHON_COMPILING_IN_GRAAL + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) _PyFrame_SetLineNumber((frame), (lineno)) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyThreadState_Current PyThreadState_Get() +#elif !CYTHON_FAST_THREAD_STATE + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#endif +#if CYTHON_OPAQUE_OBJECTS && CYTHON_COMPILING_IN_LIMITED_API + #define __PYX_SHARED_SIZEOF(T) -((int)sizeof(T)) + #define __PYX_SHARED_RELATIVE_OFFSET Py_RELATIVE_OFFSET + #define CYTHON_OPAQUE_SHARED_TYPES 1 +#else + #define __PYX_SHARED_SIZEOF(T) sizeof(T) + #define __PYX_SHARED_RELATIVE_OFFSET 0 + #define CYTHON_OPAQUE_SHARED_TYPES 0 +#endif +#if CYTHON_USE_MODULE_STATE +static CYTHON_INLINE void *__Pyx__PyModule_GetState(PyObject *op) +{ + void *result; + result = PyModule_GetState(op); + if (!result) + Py_FatalError("Couldn't find the module state"); + return result; +} +#define __Pyx_PyModule_GetState(o) (__pyx_mstatetype *)__Pyx__PyModule_GetState(o) +#else +#define __Pyx_PyModule_GetState(op) ((void)op,__pyx_mstate_global) +#endif +#define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE((PyObject *) obj), name, func_ctype) +#define __Pyx_PyObject_TryGetSlot(obj, name, func_ctype) __Pyx_PyType_TryGetSlot(Py_TYPE(obj), name, func_ctype) +#define __Pyx_PyObject_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#define __Pyx_PyObject_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype) __Pyx_PyType_GetSlot(type, name, func_ctype) + #define __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) (((type)->sub) ? ((type)->sub->name) : NULL) + #define __Pyx_PyType_TryGetSubSlot(type, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) +#else + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype)\ + ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000 ||\ + (PyType_GetFlags(type) & Py_TPFLAGS_HEAPTYPE) || __Pyx_get_runtime_version() >= 0x030A0000) ?\ + __Pyx_PyType_GetSlot(type, name, func_ctype) : NULL) + #define __Pyx_PyType_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSlot(obj, name, func_ctype) + #define __Pyx_PyType_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSlot(obj, name, func_ctype) +#endif +#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) +#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { + PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); + if (res == NULL && PyErr_Occurred()) { + PyErr_WriteUnraisable(NULL); + } + return res; +} +#elif !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000 +#define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#else +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { +#if CYTHON_COMPILING_IN_PYPY + return PyDict_GetItem(dict, name); +#else + PyDictEntry *ep; + PyDictObject *mp = (PyDictObject*) dict; + long hash = ((PyStringObject *) name)->ob_shash; + assert(hash != -1); + ep = (mp->ma_lookup)(mp, name, hash); + if (ep == NULL) { + return NULL; + } + return ep->me_value; +#endif +} +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#endif +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) + #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) +#else + #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) + #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) +#endif +#define __Pyx_PyObject_GetIterNextFunc(iterator) __Pyx_PyObject_GetSlot(iterator, tp_iternext, iternextfunc) +#if CYTHON_USE_TYPE_SPECS +#define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ + PyTypeObject *type = Py_TYPE((PyObject*)obj);\ + assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ + PyObject_GC_Del(obj);\ + Py_DECREF(type);\ +} +#else +#define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) + #define __Pyx_PyUnicode_KIND_04(u) __Pyx_PyUnicode_KIND(u) + #define __Pyx_PyUnicode_DATA(u) ((void*)u) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) +#else + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif + static CYTHON_INLINE int __Pyx_PyUnicode_KIND_04(PyObject *o) { + return __Pyx_PyUnicode_KIND(o) - (int) !!PyUnicode_IS_ASCII(o); + } +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #if !defined(PyUnicode_DecodeUnicodeEscape) + #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) + #endif + #if !defined(PyUnicode_Contains) + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) + #endif + #if !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) + #endif + #if !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) + #endif +#endif +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && PyUnstable_Object_IsUniquelyReferenced(obj)) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#elif CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#else + #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) Py_IS_TYPE(obj, &PySet_Type) +#endif +enum __Pyx_ReferenceSharing { + __Pyx_ReferenceSharing_DefinitelyUnique, // We created it so we know it's unshared - no need to check + __Pyx_ReferenceSharing_OwnStrongReference, + __Pyx_ReferenceSharing_FunctionArgument, + __Pyx_ReferenceSharing_SharedReference, // Never trust it to be unshared because it's a global or similar +}; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && PY_VERSION_HEX >= 0x030E0000 +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing)\ + (sharing == __Pyx_ReferenceSharing_DefinitelyUnique ? 1 :\ + (sharing == __Pyx_ReferenceSharing_FunctionArgument ? PyUnstable_Object_IsUniqueReferencedTemporary(o) :\ + (sharing == __Pyx_ReferenceSharing_OwnStrongReference ? PyUnstable_Object_IsUniquelyReferenced(o) : 0))) +#elif (CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)sharing), Py_REFCNT(o) == 1) +#else +#define __Pyx_IS_UNIQUELY_REFERENCED(o, sharing) (((void)o), ((void)sharing), 0) +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #if CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRef(o, i) (likely((i) >= 0) ? PySequence_GetItem(o, i) : (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) + #else + #define __Pyx_PyList_GetItemRef(o, i) PySequence_ITEM(o, i) + #endif +#elif CYTHON_COMPILING_IN_LIMITED_API || !(CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE) + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_XNewRef(PyList_GetItem(o, i)) +#else + #define __Pyx_PyList_GetItemRef(o, i) (likely(__Pyx_is_valid_index(i, PyList_GET_SIZE(o))) ?\ + __Pyx_NewRef(PyList_GET_ITEM(o, i)) : (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +#endif +#if CYTHON_AVOID_BORROWED_REFS || CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyList_GET_ITEM_REF(o, i, unsafe_shared) ((void)(unsafe_shared),\ + __Pyx_PyList_GetItemRef(o, i)) +#elif CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GET_ITEM_REF(o, i, unsafe_shared) (\ + __Pyx_IS_UNIQUELY_REFERENCED(o, unsafe_shared) ?\ + __Pyx_NewRef(PyList_GET_ITEM(o, i)) : __Pyx_PyList_GetItemRef(o, i)) + #else + #define __Pyx_PyList_GET_ITEM_REF(o, i, unsafe_shared) (\ + __Pyx_IS_UNIQUELY_REFERENCED(o, unsafe_shared) ?\ + __Pyx_XNewRef(PyList_GetItem(o, i)) : __Pyx_PyList_GetItemRef(o, i)) + #endif +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GET_ITEM_REF(o, i, unsafe_shared) ((void)(unsafe_shared),\ + __Pyx_NewRef(PyList_GET_ITEM(o, i))) +#else + #define __Pyx_PyList_GET_ITEM_REF(o, i, unsafe_shared) ((void)(unsafe_shared),\ + __Pyx_XNewRef(PyList_GetItem(o, i))) +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyDict_GetItemRef(dict, key, result) PyDict_GetItemRef(dict, key, result) +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyObject_GetItem(dict, key); + if (*result == NULL) { + if (PyErr_ExceptionMatches(PyExc_KeyError)) { + PyErr_Clear(); + return 0; + } + return -1; + } + return 1; +} +#else +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyDict_GetItemWithError(dict, key); + if (*result == NULL) { + return PyErr_Occurred() ? -1 : 0; + } + Py_INCREF(*result); + return 1; +} +#endif +#if defined(CYTHON_DEBUG_VISIT_CONST) && CYTHON_DEBUG_VISIT_CONST + #define __Pyx_VISIT_CONST(obj) Py_VISIT(obj) +#else + #define __Pyx_VISIT_CONST(obj) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GET_ITEM(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GET_ITEM(o, i) +#else + #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GetItem(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GetItem(o, i) +#endif +#if CYTHON_ASSUME_SAFE_SIZE + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) + #define __Pyx_PyDict_GET_SIZE(o) PyDict_GET_SIZE(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GET_LENGTH(o) +#else + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) + #define __Pyx_PyDict_GET_SIZE(o) PyDict_Size(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GetLength(o) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_InternFromString) + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) +#endif +#define __Pyx_PyLong_FromHash_t PyLong_FromSsize_t +#define __Pyx_PyLong_AsHash_t __Pyx_PyIndex_AsSsize_t +#if __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + #define __Pyx_PySendResult PySendResult +#else + typedef enum { + PYGEN_RETURN = 0, + PYGEN_ERROR = -1, + PYGEN_NEXT = 1, + } __Pyx_PySendResult; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030A00A3 + typedef __Pyx_PySendResult (*__Pyx_pyiter_sendfunc)(PyObject *iter, PyObject *value, PyObject **result); +#else + #define __Pyx_pyiter_sendfunc sendfunc +#endif +#if !CYTHON_USE_AM_SEND +#define __PYX_HAS_PY_AM_SEND 0 +#elif __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#define __PYX_HAS_PY_AM_SEND 1 +#else +#define __PYX_HAS_PY_AM_SEND 2 // our own backported implementation +#endif +#if __PYX_HAS_PY_AM_SEND < 2 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods +#else + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + __Pyx_pyiter_sendfunc am_send; + } __Pyx_PyAsyncMethodsStruct; + #define __Pyx_SlotTpAsAsync(s) ((PyAsyncMethods*)(s)) +#endif +#if CYTHON_USE_AM_SEND && PY_VERSION_HEX < 0x030A00F0 + #define __Pyx_TPFLAGS_HAVE_AM_SEND (1UL << 21) +#else + #define __Pyx_TPFLAGS_HAVE_AM_SEND (0) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030A0000 +#ifdef __cplusplus +extern "C" +#endif +PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize); +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_init_co_variable(PyObject *inspect, const char* name, int *write_to) { + int value; + PyObject *py_value = PyObject_GetAttrString(inspect, name); + if (!py_value) return 0; + value = (int) PyLong_AsLong(py_value); + Py_DECREF(py_value); + *write_to = value; + return value != -1 || !PyErr_Occurred(); +} +static int __Pyx_init_co_variables(void) { + PyObject *inspect; + int result; + inspect = PyImport_ImportModule("inspect"); + result = +#if !defined(CO_OPTIMIZED) + __Pyx_init_co_variable(inspect, "CO_OPTIMIZED", &CO_OPTIMIZED) && +#endif +#if !defined(CO_NEWLOCALS) + __Pyx_init_co_variable(inspect, "CO_NEWLOCALS", &CO_NEWLOCALS) && +#endif +#if !defined(CO_VARARGS) + __Pyx_init_co_variable(inspect, "CO_VARARGS", &CO_VARARGS) && +#endif +#if !defined(CO_VARKEYWORDS) + __Pyx_init_co_variable(inspect, "CO_VARKEYWORDS", &CO_VARKEYWORDS) && +#endif +#if !defined(CO_ASYNC_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_ASYNC_GENERATOR", &CO_ASYNC_GENERATOR) && +#endif +#if !defined(CO_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_GENERATOR", &CO_GENERATOR) && +#endif +#if !defined(CO_COROUTINE) + __Pyx_init_co_variable(inspect, "CO_COROUTINE", &CO_COROUTINE) && +#endif + 1; + Py_DECREF(inspect); + return result ? 0 : -1; +} +static int __Pyx_init_tpflags_bitcount(unsigned long flag) { + int count = 0; + while (flag) { + count += (int) (flag & 1); + flag >>= 1; + } + return count; +} +static int __Pyx_init_tpflags_variables(void) { + if (__Pyx_Runtime_TPFLAGS_SEQUENCE != 0 && __Pyx_Runtime_TPFLAGS_MAPPING != 0) { + return 0; + } + PyObject *collections_abc = PyImport_ImportModule("collections.abc"); + if (!collections_abc) return -1; + int result = 0; + PyObject *sequence = NULL, *mapping = NULL; +#if __PYX_LIMITED_VERSION_HEX >= 0x030D0000 + if (PyObject_GetOptionalAttrString(collections_abc, "Sequence", &sequence) != 1) goto fail; + if (PyObject_GetOptionalAttrString(collections_abc, "Mapping", &mapping) != 1) goto fail; +#else + sequence = PyObject_GetAttrString(collections_abc, "Sequence"); + if (!sequence) goto fail_attr_lookup; + mapping = PyObject_GetAttrString(collections_abc, "Mapping"); + if (!mapping) goto fail_attr_lookup; +#endif + if (!PyType_Check(sequence) || !PyType_Check(mapping)) goto fail; + { + unsigned long sequence_flags = PyType_GetFlags((PyTypeObject*)sequence); + unsigned long mapping_flags = PyType_GetFlags((PyTypeObject*)mapping); + unsigned long mutual_flags = sequence_flags & mapping_flags; + sequence_flags = sequence_flags ^ mutual_flags; + mapping_flags = mapping_flags ^ mutual_flags; + if (__Pyx_Runtime_TPFLAGS_SEQUENCE == 0 && __Pyx_init_tpflags_bitcount(sequence_flags) == 1) { + __Pyx_Runtime_TPFLAGS_SEQUENCE = sequence_flags; + } + if (__Pyx_Runtime_TPFLAGS_MAPPING == 0 && __Pyx_init_tpflags_bitcount(mapping_flags) == 1) { + __Pyx_Runtime_TPFLAGS_MAPPING = mapping_flags; + } + } + cleanup: + Py_XDECREF(mapping); + Py_XDECREF(sequence); + Py_DECREF(collections_abc); + return result; +#if __PYX_LIMITED_VERSION_HEX < 0x030D0000 + fail_attr_lookup: + if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } +#endif + fail: + result = PyErr_Occurred() ? -1 : 0; + goto cleanup; +} +#else +static int __Pyx_init_co_variables(void) { + return 0; // It's a limited API-only feature +} +static int __Pyx_init_tpflags_variables(void) { + return 0; // It's a limited API-only feature +} +#endif + +/* MathInitCode */ +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #ifndef _USE_MATH_DEFINES + #define _USE_MATH_DEFINES + #endif +#endif +#include <math.h> +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#ifndef CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#define CYTHON_CLINE_IN_TRACEBACK_RUNTIME 0 +#endif +#ifndef CYTHON_CLINE_IN_TRACEBACK +#define CYTHON_CLINE_IN_TRACEBACK CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#endif +#if CYTHON_CLINE_IN_TRACEBACK +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; __pyx_clineno = __LINE__; (void) __pyx_clineno; } +#else +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; (void) __pyx_clineno; } +#endif +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#define __PYX_HAVE__fontTools__varLib__iup +#define __PYX_HAVE_API__fontTools__varLib__iup +/* Early includes */ +#ifdef _OPENMP +#include <omp.h> +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#ifdef CYTHON_FREETHREADING_COMPATIBLE +#if CYTHON_FREETHREADING_COMPATIBLE +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_NOT_USED +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_USED +#endif +#else +#define __Pyx_FREETHREADING_COMPATIBLE Py_MOD_GIL_USED +#endif +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include <cstdlib> + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AS_STRING(s) +#else + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AsString(s) +#endif +#define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +static CYTHON_INLINE PyObject *__Pyx_NewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_NewRef) + return Py_NewRef(obj); +#else + Py_INCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_XNewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_XNewRef) + return Py_XNewRef(obj); +#else + Py_XINCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b); +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x); +#define __Pyx_PyObject_RichCompareBool(a,b,cmp) __Pyx_PyObject_IsTrueAndDecref(PyObject_RichCompare((a),(b),(cmp))) +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __Pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AS_DOUBLE(x) +#define __Pyx_PyFloat_IsNonZero(x) (PyFloat_AS_DOUBLE(x) != 0.0) +#else +#define __Pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AsDouble(x) +#define __Pyx_PyFloat_IsNonZero(x) PyObject_IsTrue(x) +#endif +#define __Pyx_PyFloat_AsFloat(x) ((float) __Pyx_PyFloat_AsDouble(x)) +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_VERSION_HEX >= 0x030C00A7 + #ifndef _PyLong_SIGN_MASK + #define _PyLong_SIGN_MASK 3 + #endif + #ifndef _PyLong_NON_SIZE_BITS + #define _PyLong_NON_SIZE_BITS 3 + #endif + #define __Pyx_PyLong_SignBits(x) ((int) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK)) + #define __Pyx_PyLong_Sign(x) (1 - __Pyx_PyLong_SignBits(x)) + #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_SignBits(x) & 2) != 0) + #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) + #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_SignBits(x) & 1) + #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_SignBits(x) == 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_SignedDigitCount(x)\ + (((Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) + #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) + #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) + #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) + #else + #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_CompactValue(x) (((Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) + #endif + static CYTHON_INLINE Py_ssize_t __Pyx_PyLong_CompareSignAndSize(PyObject *a, PyObject *b) { + uintptr_t tag_a = ((PyLongObject*)a)->long_value.lv_tag; + uintptr_t tag_b = ((PyLongObject*)b)->long_value.lv_tag; + if (tag_a == tag_b) return 0; + int sign_a = (int) (tag_a & _PyLong_SIGN_MASK); + int sign_b = (int) (tag_b & _PyLong_SIGN_MASK); + if (sign_a > sign_b) return -1; + if (sign_a < sign_b) return 1; + Py_ssize_t size_a = (Py_ssize_t) (tag_a >> _PyLong_NON_SIZE_BITS); + Py_ssize_t size_b = (Py_ssize_t) (tag_b >> _PyLong_NON_SIZE_BITS); + return (1 - sign_a) * (size_a - size_b); + } + typedef Py_ssize_t __Pyx_compact_pylong; + typedef size_t __Pyx_compact_upylong; + #else + #define __Pyx_PyLong_Sign(x) ((int) ((Py_SIZE(x) == 0) ? 0 : (Py_SIZE(x) < 0) ? -1 : 1)) + #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) + #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) + #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) + #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) + #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) + #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) + #define __Pyx_PyLong_CompactValue(x)\ + ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) + #define __Pyx_PyLong_CompareSignAndSize(a, b) (Py_SIZE(a) - Py_SIZE(b)) + typedef sdigit __Pyx_compact_pylong; + typedef digit __Pyx_compact_upylong; + #endif + #if PY_VERSION_HEX >= 0x030C00A5 + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) + #else + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) + #endif + #define __Pyx_PyLong_IsNonZero(x) (!__Pyx_PyLong_IsZero(x)) +#else + #define __Pyx_PyLong_IsNonZero(x) PyObject_IsTrue(x) +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#elif __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeASCII(c_str, size, NULL) +#else + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +/* PretendToInitialize */ +#ifdef __cplusplus +#if __cplusplus > 201103L +#include <type_traits> +#endif +template <typename T> +static void __Pyx_pretend_to_initialize(T* ptr) { +#if __cplusplus > 201103L + if ((std::is_trivially_default_constructible<T>::value)) +#endif + *ptr = T(); + (void)ptr; +} +#else +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } +#endif + + +#if !CYTHON_USE_MODULE_STATE +static PyObject *__pyx_m = NULL; +#endif +static const char * const __pyx_cfilenm = __FILE__; + +/* #### Code section: filename_table ### */ + +static const char* const __pyx_f[] = { + "Lib/fontTools/varLib/iup.py", +}; +/* #### Code section: utility_code_proto_before_types ### */ +/* Atomics.proto (used by UnpackUnboundCMethod) */ +#include <pythread.h> +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS +#define __PYX_GET_CYTHON_COMPILING_IN_CPYTHON_FREETHREADING() CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __pyx_atomic_int_type int +#define __pyx_nonatomic_int_type int +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__)) + #include <stdatomic.h> +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ + (defined(_MSC_VER) && _MSC_VER >= 1700))) + #include <atomic> +#endif +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type atomic_int + #define __pyx_atomic_ptr_type atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) atomic_fetch_add_explicit(value, 1, memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) atomic_fetch_add_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) atomic_fetch_sub_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) atomic_load(value) + #define __pyx_atomic_store(value, new_value) atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) atomic_load_explicit(value, memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) atomic_load_explicit(value, memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ +\ + (defined(_MSC_VER) && _MSC_VER >= 1700)) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type std::atomic_int + #define __pyx_atomic_ptr_type std::atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) std::atomic_fetch_sub_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) std::atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) std::atomic_load(value) + #define __pyx_atomic_store(value, new_value) std::atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) std::atomic_load_explicit(value, std::memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) std::atomic_load_explicit(value, std::memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) std::atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #define __pyx_atomic_pointer_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C++ atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C++ atomics" + #endif +#elif CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\ + (__GNUC_MINOR__ > 1 ||\ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2)))) + #define __pyx_atomic_ptr_type void* + #define __pyx_nonatomic_ptr_type void* + #define __pyx_atomic_incr_relaxed(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_incr_acq_rel(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_acq_rel(value) __sync_fetch_and_sub(value, 1) + #define __pyx_atomic_sub(value, arg) __sync_fetch_and_sub(value, arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_store(value, new_value) __sync_lock_test_and_set(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_load_acquire(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) __sync_lock_test_and_set(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_nonatomic_ptr_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && defined(_MSC_VER) + #include <intrin.h> + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type long + #define __pyx_atomic_ptr_type void* + #undef __pyx_nonatomic_int_type + #define __pyx_nonatomic_int_type long + #define __pyx_nonatomic_ptr_type void* + #pragma intrinsic (_InterlockedExchangeAdd, _InterlockedExchange, _InterlockedCompareExchange, _InterlockedCompareExchangePointer, _InterlockedExchangePointer) + #define __pyx_atomic_incr_relaxed(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_incr_acq_rel(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_decr_acq_rel(value) _InterlockedExchangeAdd(value, -1) + #define __pyx_atomic_sub(value, arg) _InterlockedExchangeAdd(value, -arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = _InterlockedCompareExchange(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) _InterlockedExchangeAdd(value, 0) + #define __pyx_atomic_store(value, new_value) _InterlockedExchange(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) *(void * volatile *)value + #define __pyx_atomic_pointer_load_acquire(value) _InterlockedCompareExchangePointer(value, 0, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) _InterlockedExchangePointer(value, (__pyx_atomic_ptr_type)new_value) + static CYTHON_INLINE int __pyx_atomic_pointer_cmp_exchange(__pyx_atomic_ptr_type* value, __pyx_nonatomic_ptr_type* expected, __pyx_nonatomic_ptr_type desired) { + __pyx_atomic_ptr_type old = _InterlockedCompareExchangePointer(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #ifdef __PYX_DEBUG_ATOMICS + #pragma message ("Using MSVC atomics") + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif + +/* CriticalSectionsDefinition.proto (used by CriticalSections) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection void* +#define __Pyx_PyCriticalSection2 void* +#define __Pyx_PyCriticalSection_End(cs) +#define __Pyx_PyCriticalSection2_End(cs) +#else +#define __Pyx_PyCriticalSection PyCriticalSection +#define __Pyx_PyCriticalSection2 PyCriticalSection2 +#define __Pyx_PyCriticalSection_End PyCriticalSection_End +#define __Pyx_PyCriticalSection2_End PyCriticalSection2_End +#endif + +/* CriticalSections.proto (used by ParseKeywordsImpl) */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection_Begin(cs, arg) (void)(cs) +#define __Pyx_PyCriticalSection2_Begin(cs, arg1, arg2) (void)(cs) +#else +#define __Pyx_PyCriticalSection_Begin PyCriticalSection_Begin +#define __Pyx_PyCriticalSection2_Begin PyCriticalSection2_Begin +#endif +#if PY_VERSION_HEX < 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_BEGIN_CRITICAL_SECTION(o) { +#define __Pyx_END_CRITICAL_SECTION() } +#else +#define __Pyx_BEGIN_CRITICAL_SECTION Py_BEGIN_CRITICAL_SECTION +#define __Pyx_END_CRITICAL_SECTION Py_END_CRITICAL_SECTION +#endif + +/* IncludeStructmemberH.proto (used by CythonFunctionShared) */ +#include <structmember.h> + +/* #### Code section: numeric_typedefs ### */ +/* #### Code section: complex_type_declarations ### */ +/* #### Code section: type_declarations ### */ + +/*--- Type declarations ---*/ +struct __pyx_defaults; +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between; +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr; +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize; +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr; +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr; + +/* "fontTools/varLib/iup.py":292 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * i=cython.int, + * j=cython.int, +*/ +struct __pyx_defaults { + PyObject_HEAD + PyObject *arg0; +}; + + +/* "fontTools/varLib/iup.py":168 + * + * + * @cython.cfunc # <<<<<<<<<<<<<< + * @cython.inline + * @cython.locals( +*/ +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between { + PyObject_HEAD + PyObject *__pyx_v_tolerance; +}; + + +/* "fontTools/varLib/iup.py":196 + * + * return all( + * abs(complex(x - p, y - q)) <= tolerance # <<<<<<<<<<<<<< + * for (x, y), (p, q) in zip(deltas, interp) + * ) +*/ +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr { + PyObject_HEAD + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *__pyx_outer_scope; + PyObject *__pyx_genexpr_arg_0; + int __pyx_v_i; + int __pyx_v_j; + double __pyx_v_p; + double __pyx_v_q; + double __pyx_v_x; + double __pyx_v_y; +}; + + +/* "fontTools/varLib/iup.py":362 + * + * + * def iup_contour_optimize( # <<<<<<<<<<<<<< + * deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0.0 + * ) -> _DeltaOrNoneSegment: +*/ +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize { + PyObject_HEAD + PyObject *__pyx_v_d0; + PyObject *__pyx_v_tolerance; +}; + + +/* "fontTools/varLib/iup.py":377 + * + * # If all are within tolerance distance of 0, encode nothing: + * if all(abs(complex(*p)) <= tolerance for p in deltas): # <<<<<<<<<<<<<< + * return [None] * n + * +*/ +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr { + PyObject_HEAD + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *__pyx_outer_scope; + PyObject *__pyx_genexpr_arg_0; + PyObject *__pyx_v_p; +}; + + +/* "fontTools/varLib/iup.py":386 + * # If all deltas are exactly the same, return just one (the first one): + * d0 = deltas[0] + * if all(d0 == d for d in deltas): # <<<<<<<<<<<<<< + * return [d0] + [None] * (n - 1) + * +*/ +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr { + PyObject_HEAD + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *__pyx_outer_scope; + PyObject *__pyx_genexpr_arg_0; + PyObject *__pyx_v_d; +}; + +/* #### Code section: utility_code_proto ### */ + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, Py_ssize_t); + void (*DECREF)(void*, PyObject*, Py_ssize_t); + void (*GOTREF)(void*, PyObject*, Py_ssize_t); + void (*GIVEREF)(void*, PyObject*, Py_ssize_t); + void* (*SetupContext)(const char*, Py_ssize_t, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContextNogil() + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_Py_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; Py_XDECREF(tmp);\ + } while (0) +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* FastTypeChecks.proto (used by GivenExceptionMatches) */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); +#define __Pyx_PyAnySet_Check(obj) __Pyx_TypeCheck2(obj, &PySet_Type, &PyFrozenSet_Type) +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) +#define __Pyx_PyAnySet_Check(obj) PyAnySet_Check(obj) +#endif + +/* PyThreadStateGet.proto (used by PyErrFetchRestore) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#if PY_VERSION_HEX >= 0x030C00A6 +#define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) +#else +#define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) +#endif +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) +#define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() +#endif + +/* PyErrFetchRestore.proto (used by GivenExceptionMatches) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* GivenExceptionMatches.proto (used by PyErrExceptionMatches) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2) { + return PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2); +} +#endif +#define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) + +/* PyErrExceptionMatches.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* PyObjectGetAttrStr.proto (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* PyObjectGetAttrStrNoError.proto (used by GetBuiltinName) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* GetBuiltinName.proto */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* CopyObjectArray.proto (used by TupleOrListFromArrayImpl) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length); +#endif + +/* TupleOrListFromArrayImpl.proto (used by TupleFromArray) */ +#if PY_VERSION_HEX >= 0x030F0000 && !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyTuple_FromArray(src, n) PyTuple_FromArray(src, ((n)<0) ? 0 : (n)) +#else +CYTHON_UNUSED static PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); +#endif + +/* TupleFromArray.proto */ + + +/* FormatTypeName.proto (used by pybuiltin_invalid) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%N" +#define __Pyx_PyType_GetFullyQualifiedName(tp) Py_NewRef((PyObject*)tp) +#define __Pyx_DECREF_TypeName(obj) Py_DECREF(obj) +#elif CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%U" +#define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) +static __Pyx_TypeName __Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp); +#else // !LIMITED_API +typedef const char *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%.200s" +#define __Pyx_PyType_GetFullyQualifiedName(tp) ((tp)->tp_name) +#define __Pyx_DECREF_TypeName(obj) +#endif + +/* pybuiltin_invalid.export */ +static void __Pyx_PyBuiltin_Invalid(PyObject *obj, const char *builtin_type_name, const char *argname); + +/* pyint_simplify.proto */ +static CYTHON_INLINE int __Pyx_PyInt_FromNumber(PyObject **number_var, const char *argname, int accept_none); + +/* SetItemInt.proto */ +#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, wraparound, boundscheck, unsafe_shared) :\ + __Pyx_SetItemInt_Generic(o, to_py_func(i), v)) +static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int wraparound, int boundscheck, int unsafe_shared); + +/* PyFrozenDict.proto (used by GetItemInt) */ +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyFrozenDict_TypePtr ((PyTypeObject*) __pyx_mstate_global->__Pyx_PyFrozenDictType) +#define __Pyx_PyFrozenDict_New(it) __Pyx__PyFrozenDict_New(__pyx_mstate_global->__Pyx_PyFrozenDictType, it) +static CYTHON_INLINE PyObject* __Pyx__PyFrozenDict_New(PyObject* frozendict_type, PyObject* it); +#define __Pyx_PyFrozenDict_NewEmpty() __Pyx_PyFrozenDict_New(NULL) +#define __Pyx_PyFrozenDict_Check(obj) PyObject_TypeCheck((obj), __Pyx_PyFrozenDict_TypePtr) +#define __Pyx_PyFrozenDict_CheckExact(obj) Py_IS_TYPE((obj), __Pyx_PyFrozenDict_TypePtr) +#define __Pyx_PyAnyDict_Check(obj) __Pyx__PyAnyDict_Check(obj, __Pyx_PyFrozenDict_TypePtr) +static CYTHON_INLINE int __Pyx__PyAnyDict_Check(PyObject *obj, PyTypeObject* frozendict_type) { + return PyObject_TypeCheck(obj, &PyDict_Type) || PyObject_TypeCheck(obj, frozendict_type); +} +#define __Pyx_PyAnyDict_CheckExact(obj) __Pyx__PyAnyDict_CheckExact(obj, __Pyx_PyFrozenDict_TypePtr) +static CYTHON_INLINE int __Pyx__PyAnyDict_CheckExact(PyObject *obj, PyTypeObject* frozendict_type) { + return Py_IS_TYPE(obj, &PyDict_Type) || Py_IS_TYPE(obj, frozendict_type); +} +#elif PY_VERSION_HEX >= 0x030f00a6 ||\ + (defined(PyFrozenDict_Check) && defined(PyAnyDict_Check) && defined(PyFrozenDict_New)) +#define __Pyx_PyFrozenDict_TypePtr (&PyFrozenDict_Type) +#define __Pyx_PyFrozenDict_New(it) PyFrozenDict_New(it) +#define __Pyx_PyFrozenDict_NewEmpty() PyFrozenDict_New(NULL) +#define __Pyx_PyFrozenDict_Check(obj) PyFrozenDict_Check(obj) +#define __Pyx_PyFrozenDict_CheckExact(obj) PyFrozenDict_CheckExact(obj) +#define __Pyx_PyAnyDict_Check(obj) PyAnyDict_Check(obj) +#define __Pyx_PyAnyDict_CheckExact(obj) PyAnyDict_CheckExact(obj) +#else +#define __Pyx_PyFrozenDict_TypePtr (&PyDict_Type) +static CYTHON_INLINE PyObject* __Pyx_PyFrozenDict_New(PyObject* it) { + if (!it) { + return PyDict_New(); + } else if (PyDict_Check(it)) { + return PyDict_Copy(it); + } else { + PyObject *dict = PyDict_New(); + if (!dict) return NULL; + PyObject *result = PyNumber_InPlaceOr(dict, it); + Py_DECREF(dict); + return result; + } +} +#define __Pyx_PyFrozenDict_NewEmpty() PyDict_New() +#define __Pyx_PyFrozenDict_Check(obj) PyDict_Check(obj) +#define __Pyx_PyFrozenDict_CheckExact(obj) PyDict_CheckExact(obj) +#define __Pyx_PyAnyDict_Check(obj) PyDict_Check(obj) +#define __Pyx_PyAnyDict_CheckExact(obj) PyDict_CheckExact(obj) +#endif + +/* GetItemInt.proto */ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + __Pyx_GetItemInt_Generic(o, to_py_func(i))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, wraparound, boundscheck, has_gil, unsafe_shared)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, unsafe_shared) :\ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared); + +/* ListExtend.proto */ +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030d0000) && !defined(PyList_Extend) +static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v); +#else +#define __Pyx_PyList_Extend(L, v) PyList_Extend(L, v) +#endif + +/* ListAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x); +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +/* PyObjectCall.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* IncludeStringH.proto (used by PyObjectCompare) */ +#include <string.h> + +/* PyObjectCompare.proto (used by UnicodeEquals) */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_str_str(PyObject *op1, PyObject *op2, int pyop); + +/* UnicodeEquals.proto (used by fastcall) */ +#define __Pyx_PyUnicode_Equals(s1, s2) __Pyx_PyObject_CompareBoolEq_str_str(s1, s2, Py_EQ) + +/* fastcall.proto */ +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_PySequence_ITEM(args, i) +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_NewRef(__Pyx_PyTuple_GET_ITEM(args, i)) +#else + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_XNewRef(PyTuple_GetItem(args, i)) +#endif +#define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) +#define __Pyx_KwValues_VARARGS(args, nargs) NULL +#define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) +#define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) +#if CYTHON_VECTORCALL + #define __Pyx_ArgRef_FASTCALL(args, i) __Pyx_NewRef(args[i]) + #define __Pyx_NumKwargs_FASTCALL(kwds) __Pyx_PyTuple_GET_SIZE(kwds) + #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) + static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL + CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); + #else + #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) + #endif +#else + #define __Pyx_ArgRef_FASTCALL __Pyx_ArgRef_VARARGS + #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS +#endif +#if CYTHON_VECTORCALL_TPNEW + #if !CYTHON_VECTORCALL + #error Enabling CYTHON_VECTORCALL_TPNEW without CYTHON_VECTORCALL is not supported + #endif + #define __Pyx_ArgRef_FASTCALL_TPNEW __Pyx_ArgRef_FASTCALL + #define __Pyx_NumKwargs_FASTCALL_TPNEW __Pyx_NumKwargs_FASTCALL + #define __Pyx_KwValues_FASTCALL_TPNEW __Pyx_KwValues_FASTCALL + #define __Pyx_GetKwValue_FASTCALL_TPNEW __Pyx_GetKwValue_FASTCALL + #define __Pyx_KwargsAsDict_FASTCALL_TPNEW __Pyx_KwargsAsDict_FASTCALL +#else + #define __Pyx_ArgRef_FASTCALL_TPNEW __Pyx_ArgRef_VARARGS + #define __Pyx_NumKwargs_FASTCALL_TPNEW __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL_TPNEW __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL_TPNEW __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL_TPNEW __Pyx_KwargsAsDict_VARARGS +#endif +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) +#if CYTHON_VECTORCALL +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(args + start, stop - start) +#else +#define __Pyx_ArgsSlice_FASTCALL __Pyx_ArgsSlice_VARARGS +#endif + +/* py_dict_items.proto (used by OwnedDictNext) */ +#define __Pyx_PyDict_items_TypePtr (&PyDictKeys_Type) +#define __Pyx_PyDict_items_Check(obj) PyObject_TypeCheck((obj), __Pyx_PyDictItems_TypePtr) +#define __Pyx_PyDict_items_CheckExact(obj) Py_IS_TYPE((obj), __Pyx_PyDictItems_TypePtr) +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); + +/* CallCFunction.proto (used by CallUnboundCMethod0) */ +#define __Pyx_CallCFunction(cfunc, self, args)\ + ((PyCFunction)(void(*)(void))(cfunc)->func)(self, args) +#define __Pyx_CallCFunctionWithKeywords(cfunc, self, args, kwargs)\ + ((PyCFunctionWithKeywords)(void(*)(void))(cfunc)->func)(self, args, kwargs) +#define __Pyx_CallCFunctionFast(cfunc, self, args, nargs)\ + ((__Pyx_PyCFunctionFast)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs) +#define __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, nargs, kwnames)\ + ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs, kwnames) + +/* PyObjectCallMethO.proto (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectFastCall.proto (used by PyObjectCallOneArg) */ +#define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject * const*args, size_t nargsf, PyObject *kwargs); + +/* PyObjectCallOneArg.proto (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* UnpackUnboundCMethod_decl.proto (used by UnpackUnboundCMethod) */ +typedef struct { + PyObject *type; + PyObject **method_name; + PyCFunction func; + PyObject *method; + int flag; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && CYTHON_ATOMICS + __pyx_atomic_int_type initialized; +#endif +} __Pyx_CachedCFunction; + +/* IgnoreException.proto (used by UnpackUnboundCMethod_impl) */ +static CYTHON_INLINE int __Pyx_IgnoreGivenException(PyObject *given_exception, PyObject *ignorable_exception); +#define __Pyx_IgnoreException(ignorable_exception) __Pyx_IgnoreGivenException(NULL, ignorable_exception) + +/* UnpackUnboundCMethod_impl.export */ +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target); + +/* UnpackUnboundCMethod.proto (used by CallUnboundCMethod0) */ +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +static CYTHON_INLINE int __Pyx_CachedCFunction_GetAndSetInitializing(__Pyx_CachedCFunction *cfunc) { +#if !CYTHON_ATOMICS + return 1; +#else + __pyx_nonatomic_int_type expected = 0; + if (__pyx_atomic_int_cmp_exchange(&cfunc->initialized, &expected, 1)) { + return 0; + } + return expected; +#endif +} +static CYTHON_INLINE void __Pyx_CachedCFunction_SetFinishedInitializing(__Pyx_CachedCFunction *cfunc) { +#if CYTHON_ATOMICS + __pyx_atomic_store(&cfunc->initialized, 2); +#endif +} +#else +#define __Pyx_CachedCFunction_GetAndSetInitializing(cfunc) 2 +#define __Pyx_CachedCFunction_SetFinishedInitializing(cfunc) +#endif + +/* CallUnboundCMethod0.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#else +#define __Pyx_CallUnboundCMethod0(cfunc, self) __Pyx__CallUnboundCMethod0(cfunc, self) +#endif + +/* py_dict_values.proto (used by OwnedDictNext) */ +#define __Pyx_PyDict_values_TypePtr (&PyDictKeys_Type) +#define __Pyx_PyDict_values_Check(obj) PyObject_TypeCheck((obj), __Pyx_PyDictValues_TypePtr) +#define __Pyx_PyDict_values_CheckExact(obj) Py_IS_TYPE((obj), __Pyx_PyDictValues_TypePtr) +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d); + +/* OwnedDictNext.proto (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue); +#else +CYTHON_INLINE +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue); +#endif + +/* RaiseDoubleKeywords.proto (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywordsImpl.export */ +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name +); +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* CallUnboundCMethod2.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2); +#else +#define __Pyx_CallUnboundCMethod2(cfunc, self, arg1, arg2) __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2) +#endif + +/* ParseKeywords.proto */ +static CYTHON_INLINE int __Pyx_ParseKeywords( + PyObject *kwds, PyObject *const *kwvalues, PyObject ** const argnames[], + PyObject *kwds2, PyObject *values[], + Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* RaiseArgTupleInvalid.export */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* AssertionsEnabled.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX >= 0x030C0000 + static int __pyx_assertions_enabled_flag; + #define __pyx_assertions_enabled() (__pyx_assertions_enabled_flag) + #if __clang__ || __GNUC__ + __attribute__((no_sanitize("thread"))) + #endif + static int __Pyx_init_assertions_enabled(void) { + PyObject *builtins, *debug, *debug_str; + int flag; + builtins = PyEval_GetBuiltins(); + if (!builtins) goto bad; + debug_str = PyUnicode_FromStringAndSize("__debug__", 9); + if (!debug_str) goto bad; + debug = PyObject_GetItem(builtins, debug_str); + Py_DECREF(debug_str); + if (!debug) goto bad; + flag = PyObject_IsTrue(debug); + Py_DECREF(debug); + if (flag == -1) goto bad; + __pyx_assertions_enabled_flag = flag; + return 0; + bad: + __pyx_assertions_enabled_flag = 1; + return -1; + } +#else + #define __Pyx_init_assertions_enabled() (0) + #define __pyx_assertions_enabled() (!Py_OptimizeFlag) +#endif + +/* PyAssertionError_Check.proto */ +#define __Pyx_PyExc_AssertionError_Check(obj) __Pyx_TypeCheck(obj, PyExc_AssertionError) + +/* RaiseException.export */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +/* PySequenceContains.proto */ +static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) { + int result = PySequence_Contains(seq, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +/* PyLongBinop.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static CYTHON_INLINE PyObject* __Pyx_PyLong_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); +#else +#define __Pyx_PyLong_AddObjC(op1, op2, intval, inplace, zerodivision_check)\ + (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) +#endif + +/* ListCompAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x); +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +/* IterNextPlain.proto (used by IterNext) */ +static CYTHON_INLINE PyObject *__Pyx_PyIter_Next_Plain(PyObject *iterator); +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject *__Pyx_GetBuiltinNext_LimitedAPI(void); +#endif + +/* RaiseErrorWithObjectType.proto (used by IterNext) */ +#define __Pyx_RaiseTypeErrorWithObjectType(message, obj) __Pyx_RaiseErrorWithObjectType(PyExc_TypeError, message, obj) +#define __Pyx_RaiseErrorWithObjectType(exc_type, message, obj) __Pyx_RaiseErrorWithType(exc_type, message, Py_TYPE(obj)) +CYTHON_UNUSED +static void __Pyx_RaiseErrorWithType(PyObject* exc_type, const char* message, PyTypeObject *type_obj); + +/* IterNext.proto */ +#define __Pyx_PyIter_Next(obj) __Pyx_PyIter_Next2(obj, NULL) +static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject *, PyObject *); + +/* PyLongCompare.proto */ +static CYTHON_INLINE int __Pyx_PyLong_BoolNeObjC(PyObject *op1, PyObject *op2, long intval, long inplace); + +/* SliceObject.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); + +/* ObjectGetItem.proto */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject *key); +#else +#define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) +#endif + +/* RaiseErrorWithObjectTypes.proto (used by PyNumberBinop) */ +#define __Pyx_RaiseErrorWithObjectTypes1(exc_type, message, arg, obj1, obj2) __Pyx_RaiseErrorWithTypes1(exc_type, message, arg, Py_TYPE(obj1), Py_TYPE(obj2)) +#define __Pyx_RaiseTypeErrorWithObjectTypes(message, obj1, obj2) __Pyx_RaiseTypeErrorWithTypes(message, Py_TYPE(obj1), Py_TYPE(obj2)) +#define __Pyx_RaiseTypeErrorWithTypes(message, type_obj1, type_obj2) __Pyx_RaiseErrorWithTypes1(PyExc_TypeError, "%.1s" message, "", type_obj1, type_obj2) +CYTHON_UNUSED +static void __Pyx_RaiseErrorWithTypes1(PyObject* exc_type, const char *message, const char *arg, PyTypeObject *type_obj1, PyTypeObject *type_obj2); + +/* PyNumberBinop.proto */ +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyNumber_Subtract_object_object(op1, op2) PyNumber_Subtract(op1, op2) +#define __Pyx_PyNumber_InPlaceSubtract_object_object(op1, op2) PyNumber_InPlaceSubtract(op1, op2) +#else +#define __Pyx_PyNumber_Subtract_object_object(op1, op2) __Pyx__PyNumber_Subtract_object_object(op1, op2, 0) +#define __Pyx_PyNumber_InPlaceSubtract_object_object(op1, op2) __Pyx__PyNumber_Subtract_object_object(op1, op2, 1) +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Subtract_object_object(PyObject *op1, PyObject *op2, int inplace); +#endif + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolGt_object_int(PyObject *op1, PyObject *op2, int pyop); + +/* PyLongBinop.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static CYTHON_INLINE PyObject* __Pyx_PyLong_SubtractObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); +#else +#define __Pyx_PyLong_SubtractObjC(op1, op2, intval, inplace, zerodivision_check)\ + (inplace ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2)) +#endif + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolNe_object_int(PyObject *op1, PyObject *op2, int pyop); + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_int_object(PyObject *op1, PyObject *op2, int pyop); + +/* PyDictVersioning.proto (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __Pyx_XNewRef(__pyx_dict_cached_value);\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_mstate_global->__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* RaiseUnboundLocalError.proto */ +static void __Pyx_RaiseUnboundLocalError(const char *varname); + +/* RaiseTooManyValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +/* RaiseNeedMoreValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +/* IterFinish.proto */ +static CYTHON_INLINE int __Pyx_IterFinish(void); + +/* UnpackItemEndCheck.proto */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); + +/* py_abs.proto */ +#if CYTHON_USE_PYLONG_INTERNALS +static PyObject *__Pyx_PyLong_AbsNeg(PyObject *num); +#define __Pyx_PyNumber_Absolute(x)\ + ((likely(PyLong_CheckExact(x))) ?\ + (likely(__Pyx_PyLong_IsNonNeg(x)) ? __Pyx_NewRef(x) : __Pyx_PyLong_AbsNeg(x)) :\ + PyNumber_Absolute(x)) +#else +#define __Pyx_PyNumber_Absolute(x) PyNumber_Absolute(x) +#endif + +/* RaiseClosureNameError.proto */ +static void __Pyx_RaiseClosureNameError(const char *varname); + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolLe_object_object(PyObject *op1, PyObject *op2, int pyop); + +/* GetException.proto (used by pep479) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* pep479.proto */ +static void __Pyx_Generator_Replace_StopIteration(int in_async_gen); + +/* PyRange_Check.proto */ +#if CYTHON_COMPILING_IN_PYPY && !defined(PyRange_Check) + #define PyRange_Check(obj) __Pyx_TypeCheck((obj), &PyRange_Type) +#endif + +/* PyNumberBinop.proto */ +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyNumber_Subtract_int_int(op1, op2) PyNumber_Subtract(op1, op2) +#define __Pyx_PyNumber_InPlaceSubtract_int_int(op1, op2) PyNumber_InPlaceSubtract(op1, op2) +#else +#define __Pyx_PyNumber_Subtract_int_int(op1, op2) __Pyx__PyNumber_Subtract_int_int(op1, op2, 0) +#define __Pyx_PyNumber_InPlaceSubtract_int_int(op1, op2) __Pyx__PyNumber_Subtract_int_int(op1, op2, 1) +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Subtract_int_int(PyObject *op1, PyObject *op2, int inplace); +#endif + +/* IncludeStdlibH.proto */ +#include <stdlib.h> + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolGt_float_object(PyObject *op1, PyObject *op2, int pyop); + +/* PyNumberBinop.proto */ +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyNumber_Subtract_float_object(op1, op2) PyNumber_Subtract(op1, op2) +#define __Pyx_PyNumber_InPlaceSubtract_float_object(op1, op2) PyNumber_InPlaceSubtract(op1, op2) +#else +#define __Pyx_PyNumber_Subtract_float_object(op1, op2) __Pyx__PyNumber_Subtract_float_object(op1, op2, 0) +#define __Pyx_PyNumber_InPlaceSubtract_float_object(op1, op2) __Pyx__PyNumber_Subtract_float_object(op1, op2, 1) +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Subtract_float_object(PyObject *op1, PyObject *op2, int inplace); +#endif + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolLe_object_float(PyObject *op1, PyObject *op2, int pyop); + +/* PyNumberBinop.proto */ +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyNumber_Add_float_object(op1, op2) PyNumber_Add(op1, op2) +#define __Pyx_PyNumber_InPlaceAdd_float_object(op1, op2) PyNumber_InPlaceAdd(op1, op2) +#else +#define __Pyx_PyNumber_Add_float_object(op1, op2) __Pyx__PyNumber_Add_float_object(op1, op2, 0) +#define __Pyx_PyNumber_InPlaceAdd_float_object(op1, op2) __Pyx__PyNumber_Add_float_object(op1, op2, 1) +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Add_float_object(PyObject *op1, PyObject *op2, int inplace); +#endif + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolLe_float_object(PyObject *op1, PyObject *op2, int pyop); + +/* PyObjectCompare.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CompareLt_object_float(PyObject *op1, PyObject *op2, int pyop); + +/* PyObjectCompare.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CompareLt_float_object(PyObject *op1, PyObject *op2, int pyop); + +/* ArgTypeTestError.export */ +static void __Pyx_ArgTypeError(PyObject *obj, PyTypeObject *type, const char *name, int exact); + +/* ArgTypeTest.proto */ +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolLt_object_object(PyObject *op1, PyObject *op2, int pyop); + +/* DictGetItem.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key); +#define __Pyx_PyObject_Dict_GetItem(obj, name)\ + (likely(__Pyx_PyAnyDict_CheckExact(obj)) ?\ + __Pyx_PyDict_GetItem(obj, name) : PyObject_GetItem(obj, name)) +#else +#define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) +#define __Pyx_PyObject_Dict_GetItem(obj, name) PyObject_GetItem(obj, name) +#endif + +/* pyfrozenset_new.proto (used by PySetContains) */ +static PyObject* __Pyx_PyFrozenSet_New(PyObject* it); + +/* PySetContains.proto */ +static CYTHON_INLINE int __Pyx_PySet_ContainsTF(PyObject* key, PyObject* set, int eq); + +/* PyNumberBinop.proto */ +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyNumber_Subtract_int_object(op1, op2) PyNumber_Subtract(op1, op2) +#define __Pyx_PyNumber_InPlaceSubtract_int_object(op1, op2) PyNumber_InPlaceSubtract(op1, op2) +#else +#define __Pyx_PyNumber_Subtract_int_object(op1, op2) __Pyx__PyNumber_Subtract_int_object(op1, op2, 0) +#define __Pyx_PyNumber_InPlaceSubtract_int_object(op1, op2) __Pyx__PyNumber_Subtract_int_object(op1, op2, 1) +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Subtract_int_object(PyObject *op1, PyObject *op2, int inplace); +#endif + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolGt_int_object(PyObject *op1, PyObject *op2, int pyop); + +/* TupleOrListFromArrayImpl.proto (used by ListFromArray) */ +CYTHON_UNUSED static PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); + +/* ListFromArray.proto (used by SliceTupleAndList) */ + + +/* SliceTupleAndList.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_GetSlice(PyObject* src, Py_ssize_t start, Py_ssize_t stop); +static CYTHON_INLINE PyObject* __Pyx_PyTuple_GetSlice(PyObject* src, Py_ssize_t start, Py_ssize_t stop); +#else +#define __Pyx_PyList_GetSlice(seq, start, stop) PySequence_GetSlice(seq, start, stop) +#define __Pyx_PyTuple_GetSlice(seq, start, stop) PySequence_GetSlice(seq, start, stop) +#endif + +/* set_iter.proto */ +static CYTHON_INLINE PyObject* __Pyx_set_iterator(PyObject* iterable, int is_set, + Py_ssize_t* p_orig_length, int* p_source_is_set); +static CYTHON_INLINE int __Pyx_set_iter_next( + PyObject* iter_obj, Py_ssize_t orig_length, + Py_ssize_t* ppos, PyObject **value, + int source_is_set); + +/* PyNumberBinop.proto */ +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyNumber_Add_object_int(op1, op2) PyNumber_Add(op1, op2) +#define __Pyx_PyNumber_InPlaceAdd_object_int(op1, op2) PyNumber_InPlaceAdd(op1, op2) +#else +#define __Pyx_PyNumber_Add_object_int(op1, op2) __Pyx__PyNumber_Add_object_int(op1, op2, 0) +#define __Pyx_PyNumber_InPlaceAdd_object_int(op1, op2) __Pyx__PyNumber_Add_object_int(op1, op2, 1) +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Add_object_int(PyObject *op1, PyObject *op2, int inplace); +#endif + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_object_object(PyObject *op1, PyObject *op2, int pyop); + +/* PyLongCompare.proto */ +static CYTHON_INLINE int __Pyx_PyLong_BoolEqObjC(PyObject *op1, PyObject *op2, long intval, long inplace); + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolGe_object_int(PyObject *op1, PyObject *op2, int pyop); + +/* py_set_remove.proto */ +static CYTHON_INLINE int __Pyx_PySet_Remove(PyObject *set, PyObject *key); + +/* ListCompAppendAndDecref.proto */ +static CYTHON_INLINE int __Pyx_ListComp_AppendAndDecref(PyObject* list, PyObject* x); + +/* PyNumberBinop.proto */ +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_PyNumber_Add_object_object(op1, op2) PyNumber_Add(op1, op2) +#define __Pyx_PyNumber_InPlaceAdd_object_object(op1, op2) PyNumber_InPlaceAdd(op1, op2) +#else +#define __Pyx_PyNumber_Add_object_object(op1, op2) __Pyx__PyNumber_Add_object_object(op1, op2, 0) +#define __Pyx_PyNumber_InPlaceAdd_object_object(op1, op2) __Pyx__PyNumber_Add_object_object(op1, op2, 1) +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Add_object_object(PyObject *op1, PyObject *op2, int inplace); +#endif + +/* PyObjectCompare.proto */ +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_object_int(PyObject *op1, PyObject *op2, int pyop); + +/* AllocateExtensionType.proto */ +static PyObject *__Pyx_AllocateExtensionType(PyTypeObject *t, int is_final); + +/* CallSlotAsVectorcall.proto */ +#if CYTHON_VECTORCALL_TPNEW +typedef PyObject * (*__Pyx_tpnewvectorcallfunc)(PyTypeObject* o, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames); +static PyObject * __Pyx_CallTpnewAsVectorcall(__Pyx_tpnewvectorcallfunc f, PyTypeObject* o, PyObject *a, PyObject *k); +#endif + +/* CallNewInitFromVectorcall.proto */ +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__Pyx_CallNewInitFromVectorcall(PyTypeObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#endif + +/* CallTypeTraverse.proto */ +#if !CYTHON_USE_TYPE_SPECS +#define __Pyx_call_type_traverse(o, always_call, visit, arg) 0 +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg); +#endif + +/* CheckTypeForFreelists.proto */ +#if CYTHON_USE_FREELISTS +#if CYTHON_USE_TYPE_SPECS +#define __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(t, expected_tp, expected_size) ((int) ((t) == (expected_tp))) +#define __PYX_CHECK_TYPE_FOR_FREELIST_FLAGS Py_TPFLAGS_IS_ABSTRACT +#else +#define __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(t, expected_tp, expected_size) ((int) ((t)->tp_basicsize == (expected_size))) +#define __PYX_CHECK_TYPE_FOR_FREELIST_FLAGS (Py_TPFLAGS_IS_ABSTRACT | Py_TPFLAGS_HEAPTYPE) +#endif +#define __PYX_CHECK_TYPE_FOR_FREELISTS(t, expected_tp, expected_size)\ + (__PYX_CHECK_FINAL_TYPE_FOR_FREELISTS((t), (expected_tp), (expected_size)) &\ + (int) (!__Pyx_PyType_HasFeature((t), __PYX_CHECK_TYPE_FOR_FREELIST_FLAGS))) +#endif + +/* PyObjectCallMethod0.proto (used by PyType_Ready) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* GetTypeDictOffset.proto (used by ValidateBasesTuple) */ +#if !CYTHON_USE_TYPE_SLOTS +CYTHON_UNUSED static Py_ssize_t __Pyx_GetTypeDictOffset(PyObject *tp, int require_cython_valid_result); +#endif + +/* RaiseErrorWithObjectType1.proto (used by ValidateBasesTuple) */ +#define __Pyx_RaiseTypeErrorWithObjectType1(message, arg, obj) __Pyx_RaiseErrorWithObjectType1(PyExc_TypeError, message, arg, obj) +#define __Pyx_RaiseErrorWithObjectType1(exc_type, message, arg, obj) __Pyx_RaiseErrorWithType1(exc_type, message, arg, Py_TYPE(obj)) +CYTHON_UNUSED +static void __Pyx_RaiseErrorWithType1(PyObject* exc_type, const char* message, const char *arg, PyTypeObject *type_obj); + +/* ValidateBasesTuple.proto (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, int has_dictoffset, PyObject *bases); +#endif + +/* PyType_Ready.export */ +CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); + +/* HasAttr.proto (used by ImportImpl) */ +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_HasAttr(o, n) PyObject_HasAttrWithError(o, n) +#else +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); +#endif + +/* ImportImpl.export */ +static PyObject *__Pyx__Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, PyObject *moddict, int level); + +/* Import.proto */ +static CYTHON_INLINE PyObject *__Pyx_Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, int level); + +/* ImportFrom.export */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +/* dict_setdefault.proto (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value); + +/* AddModuleRef.proto (used by FetchSharedCythonModule) */ +#if ((CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && PY_VERSION_HEX < 0x030F00a3) ||\ + __PYX_LIMITED_VERSION_HEX < 0x030d0000) + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name); +#else + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#endif + +/* FetchSharedCythonModule.proto (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void); + +/* VerifyCachedType.proto (used by FetchCommonType) */ +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t expected_basicsize); + +/* FetchCommonType.proto (used by CommonTypesMetaclass) */ +static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases); + +/* CommonTypesMetaclass.proto (used by CythonFunctionShared) */ +static int __pyx_CommonTypesMetaclass_init(PyObject *module); +#define __Pyx_CommonTypesMetaclass_USED + +/* CythonFunctionPerModule.proto (used by CythonFunctionShared) */ +#define __Pyx_CyFunction_USED +#if CYTHON_OPAQUE_SHARED_TYPES +#define __Pyx_as_CyFunctionObject(o) ((__pyx_CyFunctionObject *)PyObject_GetTypeData((o), __pyx_mstate_global->__pyx_CyFunctionType)) +#else +#define __Pyx_as_CyFunctionObject(o) ((__pyx_CyFunctionObject *)o) +#endif +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CYFUNCTION_COROUTINE 0x08 +#define __Pyx_CyFunction_GetClosure(f)\ + ((__Pyx_as_CyFunctionObject(f))->func_closure) +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx__CyFunction_GetClassObj(f)\ + ((f)->func_classobj) +#else + #define __Pyx__CyFunction_GetClassObj(f)\ + ((PyObject*) ((PyCMethodObject *) (f))->mm_class) +#endif +#define __Pyx_CyFunction_GetClassObj(f)\ + __Pyx__CyFunction_GetClassObj(__Pyx_as_CyFunctionObject(f)) +#define __Pyx_CyFunction_SetClassObj(f, classobj)\ + __Pyx__CyFunction_SetClassObj(__Pyx_as_CyFunctionObject(f), (classobj)) +#define __Pyx_CyFunction_Defaults(type, f)\ + ((type *)((__Pyx_as_CyFunctionObject(f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ + (__Pyx_as_CyFunctionObject(f))->defaults_getter = (g) +typedef struct { +#if CYTHON_COMPILING_IN_LIMITED_API +#if !CYTHON_OPAQUE_OBJECTS + PyObject_HEAD +#endif + PyMethodDef *func_methoddef; + PyObject *func_module; +#else + PyCMethodObject func; +#endif +#if (CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY) && CYTHON_VECTORCALL + __pyx_vectorcallfunc func_vectorcall; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_weakreflist; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_dict; +#endif + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_classobj; +#endif + PyObject *defaults; + int flags; + PyObject *defaults_tuple; + PyObject *defaults_kwdict; + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; +#if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + PyObject *func_is_coroutine; +#endif +} __pyx_CyFunctionObject; +#undef __Pyx_CyOrPyCFunction_Check +#define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_mstate_global->__pyx_CyFunctionType) +#define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_mstate_global->__pyx_CyFunctionType, &PyCFunction_Type) +#define __Pyx_CyFunction_CheckExact(obj) Py_IS_TYPE(obj, __pyx_mstate_global->__pyx_CyFunctionType) +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)); +#undef __Pyx_IsSameCFunction +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, + PyTypeObject *defaults_type); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __pyx_CyFunction_init(PyObject *module); +#if CYTHON_VECTORCALL +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY +#define __Pyx_CyFunction_func_vectorcall(f) ((f)->func_vectorcall) +#else +#define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) +#endif +#endif + +/* PyMethodNew.proto (used by CythonFunctionShared) */ +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ); + +/* PyVectorcallFastCallDict.proto (used by CythonFunctionShared) */ +#if CYTHON_VECTORCALL +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); +#endif + +/* CythonFunctionShared.proto (used by CythonFunction) */ +static PyObject *__Pyx_CyFunction_Init(PyObject *op_in, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +#if CYTHON_VECTORCALL +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#endif + +/* CythonFunction.export */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +static PyTypeObject *__Pyx_Get_CyFunction_Type(void); + +/* CLineInTraceback.proto (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#else +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#endif + +/* CodeObjectCache.proto (used by AddTraceback) */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject __Pyx_CachedCodeObjectType; +#else +typedef PyCodeObject __Pyx_CachedCodeObjectType; +#endif +typedef struct { + __Pyx_CachedCodeObjectType* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_int_type accessor_count; + #endif +}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object); + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* GCCDiagnostics.proto */ +#if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *); + +/* PyObjectVectorcallKwds.proto (used by PyObjectVectorcallMethodKwds) */ +#if CYTHON_VECTORCALL +#define __Pyx_Object_VectorcallKwds PyObject_Vectorcall +CYTHON_UNUSED static int __Pyx_CheckVectorcallKwarg(PyObject *kwnames, Py_ssize_t i); +#else +#define __Pyx_Object_VectorcallKwds __Pyx_PyObject_FastCallDict +CYTHON_UNUSED static PyObject *__Pyx_MakeKwargDict(PyObject **keys, PyObject **values, Py_ssize_t n); +CYTHON_UNUSED static int __Pyx_CheckVectorcallKwarg(PyObject **kwnames, Py_ssize_t i); +#endif + +/* PyObjectVectorcallMethodKwds.proto (used by CIntToPy) */ +#if CYTHON_VECTORCALL +#define __Pyx_Object_VectorcallMethodKwds PyObject_VectorcallMethod +#else +static PyObject *__Pyx_Object_VectorcallMethodKwds(PyObject *name, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#endif + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *); + +/* GetRuntimeVersion.proto */ +#if __PYX_LIMITED_VERSION_HEX < 0x030b0000 +static unsigned long __Pyx_cached_runtime_version = 0; +static void __Pyx_init_runtime_version(void); +#else +#define __Pyx_init_runtime_version() +#endif +static unsigned long __Pyx_get_runtime_version(void); + +/* GetTopmostException.proto (used by SaveResetException) */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); +#endif + +/* SaveResetException.proto (used by CoroutineBase) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +#else +#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) +#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) +#endif + +/* SwapException.proto (used by CoroutineBase) */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* PyObjectCallMethod1.proto (used by CoroutineBase) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); + +/* PyObjectCallNoArg.proto (used by CoroutineBase) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); + +/* ReturnWithStopIteration.proto (used by CoroutineBase) */ +static CYTHON_INLINE void __Pyx_ReturnWithStopIteration(PyObject* value, int async, int iternext); + +/* CoroutineBase.proto (used by Generator) */ +struct __pyx_CoroutineObject; +typedef PyObject *(*__pyx_coroutine_body_t)(struct __pyx_CoroutineObject *, PyThreadState *, PyObject *); +#if CYTHON_USE_EXC_INFO_STACK +#define __Pyx_ExcInfoStruct _PyErr_StackItem +#else +typedef struct { + PyObject *exc_type; + PyObject *exc_value; + PyObject *exc_traceback; +} __Pyx_ExcInfoStruct; +#endif +typedef struct __pyx_CoroutineObject { + PyObject_HEAD + __pyx_coroutine_body_t body; + PyObject *closure; + __Pyx_ExcInfoStruct gi_exc_state; +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *gi_weakreflist; +#endif + PyObject *classobj; + PyObject *yieldfrom; + __Pyx_pyiter_sendfunc yieldfrom_am_send; + PyObject *gi_name; + PyObject *gi_qualname; + PyObject *gi_modulename; + PyObject *gi_code; + PyObject *gi_frame; +#if CYTHON_USE_SYS_MONITORING && (CYTHON_PROFILE || CYTHON_TRACE) + PyMonitoringState __pyx_pymonitoring_state[__Pyx_MonitoringEventTypes_CyGen_count]; + uint64_t __pyx_pymonitoring_version; +#endif + int resume_label; + char is_running; +} __pyx_CoroutineObject; +static __pyx_CoroutineObject *__Pyx__Coroutine_New( + PyTypeObject *type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, + PyObject *name, PyObject *qualname, PyObject *module_name); +static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( + __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, + PyObject *name, PyObject *qualname, PyObject *module_name); +static CYTHON_INLINE void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *self); +static int __Pyx_Coroutine_clear(PyObject *self); +static __Pyx_PySendResult __Pyx_Coroutine_AmSend(PyObject *self, PyObject *value, PyObject **retval); +static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value); +static __Pyx_PySendResult __Pyx_Coroutine_Close(PyObject *self, PyObject **retval); +static PyObject *__Pyx_Coroutine_Throw(PyObject *gen, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + PyObject *args +#else + PyObject *const *args, Py_ssize_t nargs +#endif + ); +#if CYTHON_USE_EXC_INFO_STACK +#define __Pyx_Coroutine_SwapException(self) +#define __Pyx_Coroutine_ResetAndClearException(self) __Pyx_Coroutine_ExceptionClear(&(self)->gi_exc_state) +#else +#define __Pyx_Coroutine_SwapException(self) {\ + __Pyx_ExceptionSwap(&(self)->gi_exc_state.exc_type, &(self)->gi_exc_state.exc_value, &(self)->gi_exc_state.exc_traceback);\ + __Pyx_Coroutine_ResetFrameBackpointer(&(self)->gi_exc_state);\ + } +#define __Pyx_Coroutine_ResetAndClearException(self) {\ + __Pyx_ExceptionReset((self)->gi_exc_state.exc_type, (self)->gi_exc_state.exc_value, (self)->gi_exc_state.exc_traceback);\ + (self)->gi_exc_state.exc_type = (self)->gi_exc_state.exc_value = (self)->gi_exc_state.exc_traceback = NULL;\ + } +#endif +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ + __Pyx_PyGen__FetchStopIterationValue(__pyx_tstate, pvalue) +#else +#define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ + __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, pvalue) +#endif +static int __Pyx_PyGen__FetchStopIterationValue(PyThreadState *tstate, PyObject **pvalue); +static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state); +static char __Pyx_Coroutine_test_and_set_is_running(__pyx_CoroutineObject *gen); +static void __Pyx_Coroutine_unset_is_running(__pyx_CoroutineObject *gen); +static char __Pyx_Coroutine_get_is_running(__pyx_CoroutineObject *gen); +static PyObject *__Pyx_Coroutine_get_is_running_getter(PyObject *gen, void *closure); +#if __PYX_HAS_PY_AM_SEND == 2 +static void __Pyx_SetBackportTypeAmSend(PyTypeObject *type, __Pyx_PyAsyncMethodsStruct *static_amsend_methods, __Pyx_pyiter_sendfunc am_send); +#endif +static PyObject *__Pyx_Coroutine_fail_reduce_ex(PyObject *self, PyObject *arg); + +/* Generator.proto */ +#define __Pyx_Generator_USED +#define __Pyx_Generator_CheckExact(obj) Py_IS_TYPE(obj, __pyx_mstate_global->__pyx_GeneratorType) +#define __Pyx_Generator_New(body, code, closure, name, qualname, module_name)\ + __Pyx__Coroutine_New(__pyx_mstate_global->__pyx_GeneratorType, body, code, closure, name, qualname, module_name) +static PyObject *__Pyx_Generator_Next(PyObject *self); +static int __pyx_Generator_init(PyObject *module); +static CYTHON_INLINE PyObject *__Pyx_Generator_GetInlinedResult(PyObject *self); + +/* CheckBinaryVersion.proto */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); + +/* DecompressString.proto */ +static PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo); + +/* DecompressString_LZSS.proto */ +static PyObject *__Pyx_DecompressString_LZSS(const char *s, size_t compressed_length, size_t uncompressed_length); + +/* MultiPhaseInitModuleState.proto */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +#include <stdlib.h> +static PyObject *__Pyx_State_FindModule(void*); +static int __Pyx_State_AddModule(PyObject* module, void*); +static int __Pyx_State_RemoveModule(void*); +#elif CYTHON_USE_MODULE_STATE +#define __Pyx_State_FindModule PyState_FindModule +#define __Pyx_State_AddModule PyState_AddModule +#define __Pyx_State_RemoveModule PyState_RemoveModule +#endif + +/* #### Code section: module_declarations ### */ +/* CythonABIVersion.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API + #if CYTHON_VECTORCALL + #define __PYX_VECTORCALL_ABI_SUFFIX "_vectorcall" + #else + #define __PYX_VECTORCALL_ABI_SUFFIX + #endif + #define __PYX_LIMITED_ABI_SUFFIX "limited" __PYX_VECTORCALL_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#else + #define __PYX_LIMITED_ABI_SUFFIX +#endif +#if __PYX_HAS_PY_AM_SEND == 1 + #define __PYX_AM_SEND_ABI_SUFFIX +#elif __PYX_HAS_PY_AM_SEND == 2 + #define __PYX_AM_SEND_ABI_SUFFIX "amsendbackport" +#else + #define __PYX_AM_SEND_ABI_SUFFIX "noamsend" +#endif +#ifndef __PYX_MONITORING_ABI_SUFFIX + #define __PYX_MONITORING_ABI_SUFFIX +#endif +#if CYTHON_USE_TP_FINALIZE + #define __PYX_TP_FINALIZE_ABI_SUFFIX +#else + #define __PYX_TP_FINALIZE_ABI_SUFFIX "nofinalize" +#endif +#if CYTHON_USE_FREELISTS || !defined(__Pyx_AsyncGen_USED) + #define __PYX_FREELISTS_ABI_SUFFIX +#else + #define __PYX_FREELISTS_ABI_SUFFIX "nofreelists" +#endif +#if CYTHON_OPAQUE_OBJECTS && CYTHON_COMPILING_IN_LIMITED_API + #define __PYX_OPAQUE_OBJECTS_ABI_SUFFIX "opaque" +#else + #define __PYX_OPAQUE_OBJECTS_ABI_SUFFIX +#endif +#define CYTHON_ABI __PYX_ABI_VERSION __PYX_LIMITED_ABI_SUFFIX __PYX_MONITORING_ABI_SUFFIX __PYX_TP_FINALIZE_ABI_SUFFIX __PYX_FREELISTS_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX __PYX_OPAQUE_OBJECTS_ABI_SUFFIX +#define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI +#define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." + + +/* Module declarations from "cython" */ + +/* Module declarations from "fontTools.varLib.iup" */ +static PyObject *__pyx_f_9fontTools_6varLib_3iup_iup_segment(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *); /*proto*/ +static CYTHON_INLINE int __pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyObject *, PyObject *, int, int, PyObject *); /*proto*/ +/* #### Code section: typeinfo ### */ +/* #### Code section: before_global_var ### */ +#define __Pyx_MODULE_NAME "fontTools.varLib.iup" +extern int __pyx_module_is_main_fontTools__varLib__iup; +int __pyx_module_is_main_fontTools__varLib__iup = 0; + +/* Implementation of "fontTools.varLib.iup" */ +/* #### Code section: global_var ### */ +static PyObject *__pyx_builtin_zip; +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_max; +/* #### Code section: string_decls ### */ +/* #### Code section: decls ### */ +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_iup_contour(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords); /* proto */ +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_2iup_delta(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords, PyObject *__pyx_v_ends); /* proto */ +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_18can_iup_in_between_genexpr(PyObject *__pyx_self, PyObject *__pyx_genexpr_arg_0); /* proto */ +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_4_iup_contour_bound_forced_set(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords, PyObject *__pyx_v_tolerance); /* proto */ +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_16__defaults__(CYTHON_UNUSED PyObject *__pyx_self); /* proto */ +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_6_iup_contour_optimize_dp(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords, PyObject *__pyx_v_forced, double __pyx_v_tolerance, PyObject *__pyx_v_lookback); /* proto */ +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_8_rot_list(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_l, PyObject *__pyx_v_k); /* proto */ +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_10_rot_set(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_s, PyObject *__pyx_v_k, PyObject *__pyx_v_n); /* proto */ +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_20iup_contour_optimize_genexpr(PyObject *__pyx_self, PyObject *__pyx_genexpr_arg_0); /* proto */ +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_20iup_contour_optimize_3genexpr(PyObject *__pyx_self, PyObject *__pyx_genexpr_arg_0); /* proto */ +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_12iup_contour_optimize(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords, PyObject *__pyx_v_tolerance); /* proto */ +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_14iup_delta_optimize(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords, PyObject *__pyx_v_ends, PyObject *__pyx_v_tolerance); /* proto */ +static PyObject *__pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_defaults(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +static PyObject *__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_defaults(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_6varLib_3iup___pyx_defaults(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +#endif +#if !CYTHON_VECTORCALL_TPNEW +#define __pyx_tp_new_9fontTools_6varLib_3iup___pyx_defaults __pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_defaults +#endif +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_defaults(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames); /*proto*/ +#endif +static PyObject *__pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +static PyObject *__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +#endif +#if !CYTHON_VECTORCALL_TPNEW +#define __pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between __pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between +#endif +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames); /*proto*/ +#endif +static PyObject *__pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +static PyObject *__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +#endif +#if !CYTHON_VECTORCALL_TPNEW +#define __pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr __pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr +#endif +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames); /*proto*/ +#endif +static PyObject *__pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +static PyObject *__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +#endif +#if !CYTHON_VECTORCALL_TPNEW +#define __pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize __pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize +#endif +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames); /*proto*/ +#endif +static PyObject *__pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +static PyObject *__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +#endif +#if !CYTHON_VECTORCALL_TPNEW +#define __pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr __pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr +#endif +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames); /*proto*/ +#endif +static PyObject *__pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +static PyObject *__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +); /*proto*/ +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +#endif +#if !CYTHON_VECTORCALL_TPNEW +#define __pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr __pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr +#endif +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames); /*proto*/ +#endif +/* #### Code section: late_includes ### */ +/* #### Code section: module_state ### */ +/* SmallCodeConfig */ +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif + +#ifdef __cplusplus +namespace { + #endif + typedef struct { + PyObject *__pyx_d; + PyObject *__pyx_b; + PyObject *__pyx_cython_runtime; + PyObject *__pyx_empty_tuple; + PyObject *__pyx_empty_bytes; + PyObject *__pyx_empty_unicode; + PyObject *__pyx_type_9fontTools_6varLib_3iup___pyx_defaults; + PyObject *__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between; + PyObject *__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr; + PyObject *__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize; + PyObject *__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr; + PyObject *__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr; + PyTypeObject *__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults; + PyTypeObject *__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between; + PyTypeObject *__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr; + PyTypeObject *__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize; + PyTypeObject *__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr; + PyTypeObject *__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_items; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_pop; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_values; + PyObject *__pyx_tuple[4]; + PyObject *__pyx_codeobj_tab[11]; + PyObject *__pyx_string_tab[128]; + PyObject *__pyx_number_tab[8]; +/* #### Code section: module_state_contents ### */ +/* PyFrozenDict.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API +PyObject *__Pyx_PyFrozenDictType; +#endif + +/* IterNextPlain.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +PyObject *__Pyx_GetBuiltinNext_LimitedAPI_cache; +#endif + + +#if CYTHON_USE_FREELISTS +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between[8]; +int __pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between; +#endif + +#if CYTHON_USE_FREELISTS +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr *__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr[8]; +int __pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr; +#endif + +#if CYTHON_USE_FREELISTS +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize[8]; +int __pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize; +#endif + +#if CYTHON_USE_FREELISTS +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr *__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr[8]; +int __pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr; +#endif + +#if CYTHON_USE_FREELISTS +struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr *__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr[8]; +int __pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr; +#endif +/* CommonTypesMetaclass.module_state_decls */ +PyTypeObject *__pyx_CommonTypesMetaclassType; + +/* CachedMethodType.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API +PyObject *__Pyx_CachedMethodType; +#endif + +/* CythonFunctionPerModule.module_state_decls */ +PyTypeObject *__pyx_CyFunctionType; + +/* CodeObjectCache.module_state_decls */ +struct __Pyx_CodeObjectCache __pyx_code_cache; + +/* Generator.module_state_decls */ +PyTypeObject *__pyx_GeneratorType; + +/* #### Code section: module_state_end ### */ +} __pyx_mstatetype; +#ifdef __cplusplus +} /* anonymous namespace */ +#endif + +#if CYTHON_USE_MODULE_STATE +#ifdef __cplusplus +namespace { +extern struct PyModuleDef __pyx_moduledef; +} /* anonymous namespace */ +#else +static struct PyModuleDef __pyx_moduledef; +#endif + +#define __pyx_mstate_global (__Pyx_PyModule_GetState(__Pyx_State_FindModule(&__pyx_moduledef))) + +#define __pyx_m (__Pyx_State_FindModule(&__pyx_moduledef)) +#else +static __pyx_mstatetype __pyx_mstate_global_static = +#ifdef __cplusplus + {}; +#else + {0}; +#endif +static __pyx_mstatetype * const __pyx_mstate_global = &__pyx_mstate_global_static; +#endif +/* #### Code section: constant_name_defines ### */ +#define __pyx_kp_u__2 __pyx_string_tab[0] +#define __pyx_kp_u_ __pyx_string_tab[1] +#define __pyx_kp_u_Lib_fontTools_varLib_iup_py __pyx_string_tab[2] +#define __pyx_kp_u_Note_that_Cython_is_deliberately __pyx_string_tab[3] +#define __pyx_kp_u_add_note __pyx_string_tab[4] +#define __pyx_kp_u_disable __pyx_string_tab[5] +#define __pyx_kp_u_enable __pyx_string_tab[6] +#define __pyx_kp_u_gc __pyx_string_tab[7] +#define __pyx_kp_u_isenabled __pyx_string_tab[8] +#define __pyx_n_u_COMPILED __pyx_string_tab[9] +#define __pyx_n_u_Integral __pyx_string_tab[10] +#define __pyx_n_u_MAX_LOOKBACK __pyx_string_tab[11] +#define __pyx_n_u_Real __pyx_string_tab[12] +#define __pyx_n_u_Sequence __pyx_string_tab[13] +#define __pyx_n_u_Tuple __pyx_string_tab[14] +#define __pyx_n_u_Union __pyx_string_tab[15] +#define __pyx_n_u_Delta __pyx_string_tab[16] +#define __pyx_n_u_DeltaOrNone __pyx_string_tab[17] +#define __pyx_n_u_DeltaOrNoneSegment __pyx_string_tab[18] +#define __pyx_n_u_DeltaSegment __pyx_string_tab[19] +#define __pyx_n_u_Endpoints __pyx_string_tab[20] +#define __pyx_n_u_Point __pyx_string_tab[21] +#define __pyx_n_u_PointSegment __pyx_string_tab[22] +#define __pyx_n_u_Pyx_PyDict_NextRef __pyx_string_tab[23] +#define __pyx_n_u_annotate __pyx_string_tab[24] +#define __pyx_n_u_class_getitem __pyx_string_tab[25] +#define __pyx_n_u_func __pyx_string_tab[26] +#define __pyx_n_u_main __pyx_string_tab[27] +#define __pyx_n_u_module __pyx_string_tab[28] +#define __pyx_n_u_name __pyx_string_tab[29] +#define __pyx_n_u_qualname __pyx_string_tab[30] +#define __pyx_n_u_test __pyx_string_tab[31] +#define __pyx_n_u_is_coroutine __pyx_string_tab[32] +#define __pyx_n_u_iup_contour_bound_forced_set __pyx_string_tab[33] +#define __pyx_n_u_iup_contour_optimize_dp __pyx_string_tab[34] +#define __pyx_n_u_rot_list __pyx_string_tab[35] +#define __pyx_n_u_rot_set __pyx_string_tab[36] +#define __pyx_n_u_asyncio_coroutines __pyx_string_tab[37] +#define __pyx_n_u_best_cost __pyx_string_tab[38] +#define __pyx_n_u_best_j __pyx_string_tab[39] +#define __pyx_n_u_best_sol __pyx_string_tab[40] +#define __pyx_n_u_c __pyx_string_tab[41] +#define __pyx_n_u_c1 __pyx_string_tab[42] +#define __pyx_n_u_c2 __pyx_string_tab[43] +#define __pyx_n_u_can_iup_in_between_locals_genexp __pyx_string_tab[44] +#define __pyx_n_u_chain __pyx_string_tab[45] +#define __pyx_n_u_cj __pyx_string_tab[46] +#define __pyx_n_u_cline_in_traceback __pyx_string_tab[47] +#define __pyx_n_u_close __pyx_string_tab[48] +#define __pyx_n_u_contour __pyx_string_tab[49] +#define __pyx_n_u_coords __pyx_string_tab[50] +#define __pyx_n_u_cost __pyx_string_tab[51] +#define __pyx_n_u_costs __pyx_string_tab[52] +#define __pyx_n_u_d __pyx_string_tab[53] +#define __pyx_n_u_d0 __pyx_string_tab[54] +#define __pyx_n_u_d1 __pyx_string_tab[55] +#define __pyx_n_u_d2 __pyx_string_tab[56] +#define __pyx_n_u_deltas __pyx_string_tab[57] +#define __pyx_n_u_dj __pyx_string_tab[58] +#define __pyx_n_u_end __pyx_string_tab[59] +#define __pyx_n_u_ends __pyx_string_tab[60] +#define __pyx_n_u_enumerate __pyx_string_tab[61] +#define __pyx_n_u_fontTools_varLib_iup __pyx_string_tab[62] +#define __pyx_n_u_force __pyx_string_tab[63] +#define __pyx_n_u_forced __pyx_string_tab[64] +#define __pyx_n_u_genexpr __pyx_string_tab[65] +#define __pyx_n_u_i __pyx_string_tab[66] +#define __pyx_n_u_i1 __pyx_string_tab[67] +#define __pyx_n_u_i2 __pyx_string_tab[68] +#define __pyx_n_u_indices __pyx_string_tab[69] +#define __pyx_n_u_int __pyx_string_tab[70] +#define __pyx_n_u_it __pyx_string_tab[71] +#define __pyx_n_u_items __pyx_string_tab[72] +#define __pyx_n_u_iup_contour __pyx_string_tab[73] +#define __pyx_n_u_iup_contour_optimize __pyx_string_tab[74] +#define __pyx_n_u_iup_contour_optimize_locals_gene __pyx_string_tab[75] +#define __pyx_n_u_iup_delta __pyx_string_tab[76] +#define __pyx_n_u_iup_delta_optimize __pyx_string_tab[77] +#define __pyx_n_u_j __pyx_string_tab[78] +#define __pyx_n_u_k __pyx_string_tab[79] +#define __pyx_n_u_l __pyx_string_tab[80] +#define __pyx_n_u_lc __pyx_string_tab[81] +#define __pyx_n_u_lcj __pyx_string_tab[82] +#define __pyx_n_u_ld __pyx_string_tab[83] +#define __pyx_n_u_ldj __pyx_string_tab[84] +#define __pyx_n_u_list __pyx_string_tab[85] +#define __pyx_n_u_lookback __pyx_string_tab[86] +#define __pyx_n_u_max __pyx_string_tab[87] +#define __pyx_n_u_n __pyx_string_tab[88] +#define __pyx_n_u_nc __pyx_string_tab[89] +#define __pyx_n_u_ncj __pyx_string_tab[90] +#define __pyx_n_u_nd __pyx_string_tab[91] +#define __pyx_n_u_ndj __pyx_string_tab[92] +#define __pyx_n_u_next __pyx_string_tab[93] +#define __pyx_n_u_numbers __pyx_string_tab[94] +#define __pyx_n_u_out __pyx_string_tab[95] +#define __pyx_n_u_p __pyx_string_tab[96] +#define __pyx_n_u_pop __pyx_string_tab[97] +#define __pyx_n_u_q __pyx_string_tab[98] +#define __pyx_n_u_return __pyx_string_tab[99] +#define __pyx_n_u_ri1 __pyx_string_tab[100] +#define __pyx_n_u_ri2 __pyx_string_tab[101] +#define __pyx_n_u_s __pyx_string_tab[102] +#define __pyx_n_u_send __pyx_string_tab[103] +#define __pyx_n_u_set __pyx_string_tab[104] +#define __pyx_n_u_setdefault __pyx_string_tab[105] +#define __pyx_n_u_solution __pyx_string_tab[106] +#define __pyx_n_u_start __pyx_string_tab[107] +#define __pyx_n_u_throw __pyx_string_tab[108] +#define __pyx_n_u_tolerance __pyx_string_tab[109] +#define __pyx_n_u_typing __pyx_string_tab[110] +#define __pyx_n_u_v __pyx_string_tab[111] +#define __pyx_n_u_value __pyx_string_tab[112] +#define __pyx_n_u_values __pyx_string_tab[113] +#define __pyx_n_u_x __pyx_string_tab[114] +#define __pyx_n_u_y __pyx_string_tab[115] +#define __pyx_n_u_zip __pyx_string_tab[116] +#define __pyx_kp_b_iso88591_q_5_Cq_D_RuJcQSST_1A_5_2Rs_Bc_2 __pyx_string_tab[117] +#define __pyx_kp_b_iso88591_Q_1A_A_q_r_A_q_q_a_q_Bay_A_881 __pyx_string_tab[118] +#define __pyx_kp_b_iso88591_a_5_Cq_D_RuJcQSST_1A_5_2Rs_Bc_2 __pyx_string_tab[119] +#define __pyx_kp_b_iso88591_q_a_1A_y_1_1_Q_c_c_U_3a_E_Bc_1 __pyx_string_tab[120] +#define __pyx_kp_b_iso88591_Q_3axs_Qa_1A_U_3axr_T_E_q_D_ar __pyx_string_tab[121] +#define __pyx_kp_b_iso88591_a __pyx_string_tab[122] +#define __pyx_kp_b_iso88591_A __pyx_string_tab[123] +#define __pyx_kp_b_iso88591_1 __pyx_string_tab[124] +#define __pyx_kp_b_iso88591_t1_q_2Rr_Bb_E __pyx_string_tab[125] +#define __pyx_kp_b_iso88591_1A_t1_q_1ARr_b_Bb __pyx_string_tab[126] +#define __pyx_kp_b_iso88591_55Gq_3axs_Qa_uG1_q_1A_ar_S_Yaxs __pyx_string_tab[127] +#define __pyx_float_0_0 __pyx_number_tab[0] +#define __pyx_int_0 __pyx_number_tab[1] +#define __pyx_int_neg_1 __pyx_number_tab[2] +#define __pyx_int_1 __pyx_number_tab[3] +#define __pyx_int_2 __pyx_number_tab[4] +#define __pyx_int_3 __pyx_number_tab[5] +#define __pyx_int_4 __pyx_number_tab[6] +#define __pyx_int_8 __pyx_number_tab[7] +/* #### Code section: module_state_clear ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_clear(PyObject *m) { + __pyx_mstatetype *clear_module_state = __Pyx_PyModule_GetState(m); + if (!clear_module_state) return 0; + Py_CLEAR(clear_module_state->__pyx_d); + Py_CLEAR(clear_module_state->__pyx_b); + Py_CLEAR(clear_module_state->__pyx_cython_runtime); + Py_CLEAR(clear_module_state->__pyx_empty_tuple); + Py_CLEAR(clear_module_state->__pyx_empty_bytes); + Py_CLEAR(clear_module_state->__pyx_empty_unicode); + #if CYTHON_PEP489_MULTI_PHASE_INIT + __Pyx_State_RemoveModule(NULL); + #endif + Py_CLEAR(clear_module_state->__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults); + Py_CLEAR(clear_module_state->__pyx_type_9fontTools_6varLib_3iup___pyx_defaults); + Py_CLEAR(clear_module_state->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between); + Py_CLEAR(clear_module_state->__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between); + Py_CLEAR(clear_module_state->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr); + Py_CLEAR(clear_module_state->__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr); + Py_CLEAR(clear_module_state->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize); + Py_CLEAR(clear_module_state->__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize); + Py_CLEAR(clear_module_state->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr); + Py_CLEAR(clear_module_state->__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr); + Py_CLEAR(clear_module_state->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr); + Py_CLEAR(clear_module_state->__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr); + Py_CLEAR(clear_module_state->__pyx_umethod_PyDict_Type_items.method); + Py_CLEAR(clear_module_state->__pyx_umethod_PyDict_Type_pop.method); + Py_CLEAR(clear_module_state->__pyx_umethod_PyDict_Type_values.method); + for (int i=0; i<4; ++i) { Py_CLEAR(clear_module_state->__pyx_tuple[i]); } + for (int i=0; i<11; ++i) { Py_CLEAR(clear_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<128; ++i) { Py_CLEAR(clear_module_state->__pyx_string_tab[i]); } + for (int i=0; i<8; ++i) { Py_CLEAR(clear_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_clear_contents ### */ +/* CommonTypesMetaclass.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionPerModule.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_CyFunctionType); + +/* Generator.module_state_clear */ +Py_CLEAR(clear_module_state->__pyx_GeneratorType); + +/* #### Code section: module_state_clear_end ### */ +return 0; +} +#endif +/* #### Code section: module_state_traverse ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { + __pyx_mstatetype *traverse_module_state = __Pyx_PyModule_GetState(m); + if (!traverse_module_state) return 0; + Py_VISIT(traverse_module_state->__pyx_d); + Py_VISIT(traverse_module_state->__pyx_b); + Py_VISIT(traverse_module_state->__pyx_cython_runtime); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_tuple); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_bytes); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_unicode); + Py_VISIT(traverse_module_state->__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults); + Py_VISIT(traverse_module_state->__pyx_type_9fontTools_6varLib_3iup___pyx_defaults); + Py_VISIT(traverse_module_state->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between); + Py_VISIT(traverse_module_state->__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between); + Py_VISIT(traverse_module_state->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr); + Py_VISIT(traverse_module_state->__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr); + Py_VISIT(traverse_module_state->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize); + Py_VISIT(traverse_module_state->__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize); + Py_VISIT(traverse_module_state->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr); + Py_VISIT(traverse_module_state->__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr); + Py_VISIT(traverse_module_state->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr); + Py_VISIT(traverse_module_state->__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr); + Py_VISIT(traverse_module_state->__pyx_umethod_PyDict_Type_items.method); + Py_VISIT(traverse_module_state->__pyx_umethod_PyDict_Type_pop.method); + Py_VISIT(traverse_module_state->__pyx_umethod_PyDict_Type_values.method); + for (int i=0; i<4; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_tuple[i]); } + for (int i=0; i<11; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<128; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_string_tab[i]); } + for (int i=0; i<8; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_number_tab[i]); } +/* #### Code section: module_state_traverse_contents ### */ +/* CommonTypesMetaclass.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CommonTypesMetaclassType); + +/* CythonFunctionPerModule.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_CyFunctionType); + +/* Generator.module_state_traverse */ +Py_VISIT(traverse_module_state->__pyx_GeneratorType); + +/* #### Code section: module_state_traverse_end ### */ +return 0; +} +#endif +/* #### Code section: module_code ### */ + +/* "fontTools/varLib/iup.py":27 + * + * + * @cython.cfunc # <<<<<<<<<<<<<< + * @cython.locals( + * j=cython.int, +*/ + +static PyObject *__pyx_f_9fontTools_6varLib_3iup_iup_segment(PyObject *__pyx_v_coords, PyObject *__pyx_v_rc1, PyObject *__pyx_v_rd1, PyObject *__pyx_v_rc2, PyObject *__pyx_v_rd2) { + int __pyx_v_j; + int __pyx_v_n; + double __pyx_v_x1; + double __pyx_v_x2; + double __pyx_v_d1; + double __pyx_v_d2; + double __pyx_v_scale; + double __pyx_v_x; + double __pyx_v_d; + PyObject *__pyx_v_out_arrays = NULL; + PyObject *__pyx_v_out = NULL; + PyObject *__pyx_v_pair = NULL; + double __pyx_v_nudge; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + double __pyx_t_5; + double __pyx_t_6; + double __pyx_t_7; + double __pyx_t_8; + int __pyx_t_9; + Py_ssize_t __pyx_t_10; + PyObject *__pyx_t_11 = NULL; + int __pyx_t_12; + PyObject *(*__pyx_t_13)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("iup_segment", 0); + + /* "fontTools/varLib/iup.py":48 + * # rc1 = reference coord 1 + * # rd1 = reference delta 1 + * out_arrays = [None, None] # <<<<<<<<<<<<<< + * for j in 0, 1: + * out_arrays[j] = out = [] +*/ + __pyx_t_1 = PyList_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 48, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyList_SET_ITEM(__pyx_t_1, 0, Py_None) != (0)) __PYX_ERR(0, 48, __pyx_L1_error); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyList_SET_ITEM(__pyx_t_1, 1, Py_None) != (0)) __PYX_ERR(0, 48, __pyx_L1_error); + __pyx_v_out_arrays = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "fontTools/varLib/iup.py":49 + * # rd1 = reference delta 1 + * out_arrays = [None, None] + * for j in 0, 1: # <<<<<<<<<<<<<< + * out_arrays[j] = out = [] + * x1, x2, d1, d2 = rc1[j], rc2[j], rd1[j], rd2[j] +*/ + __pyx_t_1 = __pyx_mstate_global->__pyx_tuple[0]; __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= 2) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2)); + #else + __pyx_t_3 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_2); + #endif + ++__pyx_t_2; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_PyInt_FromNumber(&__pyx_t_3, NULL, 1) < (0)) __PYX_ERR(0, 49, __pyx_L1_error) + __pyx_t_4 = __Pyx_PyLong_As_int(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_j = __pyx_t_4; + + /* "fontTools/varLib/iup.py":50 + * out_arrays = [None, None] + * for j in 0, 1: + * out_arrays[j] = out = [] # <<<<<<<<<<<<<< + * x1, x2, d1, d2 = rc1[j], rc2[j], rd1[j], rd2[j] + * +*/ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 50, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (unlikely((__Pyx_SetItemInt(__pyx_v_out_arrays, __pyx_v_j, __pyx_t_3, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference) < 0))) __PYX_ERR(0, 50, __pyx_L1_error) + __Pyx_INCREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_out, __pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":51 + * for j in 0, 1: + * out_arrays[j] = out = [] + * x1, x2, d1, d2 = rc1[j], rc2[j], rd1[j], rd2[j] # <<<<<<<<<<<<<< + * + * if x1 == x2: +*/ + __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_rc1, __pyx_v_j, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 51, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_5 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 51, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_rc2, __pyx_v_j, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 51, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = __Pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_6 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 51, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_rd1, __pyx_v_j, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 51, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = __Pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_7 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 51, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_rd2, __pyx_v_j, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 51, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = __Pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_8 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 51, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_x1 = __pyx_t_5; + __pyx_v_x2 = __pyx_t_6; + __pyx_v_d1 = __pyx_t_7; + __pyx_v_d2 = __pyx_t_8; + + /* "fontTools/varLib/iup.py":53 + * x1, x2, d1, d2 = rc1[j], rc2[j], rd1[j], rd2[j] + * + * if x1 == x2: # <<<<<<<<<<<<<< + * n = len(coords) + * if d1 == d2: +*/ + __pyx_t_9 = (__pyx_v_x1 == __pyx_v_x2); + + if (__pyx_t_9) { + + + /* "fontTools/varLib/iup.py":54 + * + * if x1 == x2: + * n = len(coords) # <<<<<<<<<<<<<< + * if d1 == d2: + * out.extend([d1] * n) +*/ + __pyx_t_10 = PyObject_Length(__pyx_v_coords); if (unlikely(__pyx_t_10 == ((Py_ssize_t)-1))) __PYX_ERR(0, 54, __pyx_L1_error) + __pyx_v_n = __pyx_t_10; + + /* "fontTools/varLib/iup.py":55 + * if x1 == x2: + * n = len(coords) + * if d1 == d2: # <<<<<<<<<<<<<< + * out.extend([d1] * n) + * else: +*/ + __pyx_t_9 = (__pyx_v_d1 == __pyx_v_d2); + + if (__pyx_t_9) { + + + /* "fontTools/varLib/iup.py":56 + * n = len(coords) + * if d1 == d2: + * out.extend([d1] * n) # <<<<<<<<<<<<<< + * else: + * out.extend([0] * n) +*/ + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_d1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_11 = PyList_New(1 * ((__pyx_v_n<0) ? 0:__pyx_v_n)); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_n; __pyx_temp++) { + __Pyx_INCREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + if (__Pyx_PyList_SET_ITEM(__pyx_t_11, __pyx_temp, __pyx_t_3) != (0)) __PYX_ERR(0, 56, __pyx_L1_error); + } + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_12 = __Pyx_PyList_Extend(__pyx_v_out, __pyx_t_11); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 56, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + + + /* "fontTools/varLib/iup.py":55 + * if x1 == x2: + * n = len(coords) + * if d1 == d2: # <<<<<<<<<<<<<< + * out.extend([d1] * n) + * else: +*/ + goto __pyx_L6; + } + + /* "fontTools/varLib/iup.py":58 + * out.extend([d1] * n) + * else: + * out.extend([0] * n) # <<<<<<<<<<<<<< + * continue + * +*/ + /*else*/ { + __pyx_t_11 = PyList_New(1 * ((__pyx_v_n<0) ? 0:__pyx_v_n)); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 58, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_v_n; __pyx_temp++) { + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_0); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_0); + if (__Pyx_PyList_SET_ITEM(__pyx_t_11, __pyx_temp, __pyx_mstate_global->__pyx_int_0) != (0)) __PYX_ERR(0, 58, __pyx_L1_error); + } + } + __pyx_t_12 = __Pyx_PyList_Extend(__pyx_v_out, __pyx_t_11); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 58, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + + } + __pyx_L6:; + + /* "fontTools/varLib/iup.py":59 + * else: + * out.extend([0] * n) + * continue # <<<<<<<<<<<<<< + * + * if x1 > x2: +*/ + goto __pyx_L3_continue; + + /* "fontTools/varLib/iup.py":53 + * x1, x2, d1, d2 = rc1[j], rc2[j], rd1[j], rd2[j] + * + * if x1 == x2: # <<<<<<<<<<<<<< + * n = len(coords) + * if d1 == d2: +*/ + } + + /* "fontTools/varLib/iup.py":61 + * continue + * + * if x1 > x2: # <<<<<<<<<<<<<< + * x1, x2 = x2, x1 + * d1, d2 = d2, d1 +*/ + __pyx_t_9 = (__pyx_v_x1 > __pyx_v_x2); + + if (__pyx_t_9) { + + + /* "fontTools/varLib/iup.py":62 + * + * if x1 > x2: + * x1, x2 = x2, x1 # <<<<<<<<<<<<<< + * d1, d2 = d2, d1 + * +*/ + __pyx_t_8 = __pyx_v_x2; + + __pyx_t_7 = __pyx_v_x1; + + __pyx_v_x1 = __pyx_t_8; + __pyx_v_x2 = __pyx_t_7; + + /* "fontTools/varLib/iup.py":63 + * if x1 > x2: + * x1, x2 = x2, x1 + * d1, d2 = d2, d1 # <<<<<<<<<<<<<< + * + * # x1 < x2 +*/ + __pyx_t_7 = __pyx_v_d2; + + __pyx_t_8 = __pyx_v_d1; + + __pyx_v_d1 = __pyx_t_7; + __pyx_v_d2 = __pyx_t_8; + + /* "fontTools/varLib/iup.py":61 + * continue + * + * if x1 > x2: # <<<<<<<<<<<<<< + * x1, x2 = x2, x1 + * d1, d2 = d2, d1 +*/ + } + + /* "fontTools/varLib/iup.py":66 + * + * # x1 < x2 + * scale = (d2 - d1) / (x2 - x1) # <<<<<<<<<<<<<< + * for pair in coords: + * x = pair[j] +*/ + __pyx_t_8 = (__pyx_v_d2 - __pyx_v_d1); + + __pyx_t_7 = (__pyx_v_x2 - __pyx_v_x1); + + if (unlikely(__pyx_t_7 == 0)) { + PyErr_SetString(PyExc_ZeroDivisionError, "float division"); + __PYX_ERR(0, 66, __pyx_L1_error) + } + __pyx_v_scale = (__pyx_t_8 / __pyx_t_7); + + + + /* "fontTools/varLib/iup.py":67 + * # x1 < x2 + * scale = (d2 - d1) / (x2 - x1) + * for pair in coords: # <<<<<<<<<<<<<< + * x = pair[j] + * +*/ + if (likely(PyList_CheckExact(__pyx_v_coords)) || PyTuple_CheckExact(__pyx_v_coords)) { + __pyx_t_11 = __pyx_v_coords; __Pyx_INCREF(__pyx_t_11); + __pyx_t_10 = 0; + __pyx_t_13 = NULL; + } else { + __pyx_t_10 = -1; __pyx_t_11 = PyObject_GetIter(__pyx_v_coords); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 67, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_13 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_11); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 67, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_13)) { + if (likely(PyList_CheckExact(__pyx_t_11))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_11); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 67, __pyx_L1_error) + #endif + if (__pyx_t_10 >= __pyx_temp) break; + } + __pyx_t_3 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_11, __pyx_t_10, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_10; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_11); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 67, __pyx_L1_error) + #endif + if (__pyx_t_10 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_11, __pyx_t_10)); + #else + __pyx_t_3 = __Pyx_PySequence_ITEM(__pyx_t_11, __pyx_t_10); + #endif + ++__pyx_t_10; + } + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 67, __pyx_L1_error) + } else { + __pyx_t_3 = __pyx_t_13(__pyx_t_11); + if (unlikely(!__pyx_t_3)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 67, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_pair, __pyx_t_3); + __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":68 + * scale = (d2 - d1) / (x2 - x1) + * for pair in coords: + * x = pair[j] # <<<<<<<<<<<<<< + * + * if x <= x1: +*/ + __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_pair, __pyx_v_j, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 68, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = __Pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_7 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 68, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_x = __pyx_t_7; + + /* "fontTools/varLib/iup.py":70 + * x = pair[j] + * + * if x <= x1: # <<<<<<<<<<<<<< + * d = d1 + * elif x >= x2: +*/ + __pyx_t_9 = (__pyx_v_x <= __pyx_v_x1); + + if (__pyx_t_9) { + + + /* "fontTools/varLib/iup.py":71 + * + * if x <= x1: + * d = d1 # <<<<<<<<<<<<<< + * elif x >= x2: + * d = d2 +*/ + __pyx_v_d = __pyx_v_d1; + + /* "fontTools/varLib/iup.py":70 + * x = pair[j] + * + * if x <= x1: # <<<<<<<<<<<<<< + * d = d1 + * elif x >= x2: +*/ + goto __pyx_L10; + } + + /* "fontTools/varLib/iup.py":72 + * if x <= x1: + * d = d1 + * elif x >= x2: # <<<<<<<<<<<<<< + * d = d2 + * else: +*/ + __pyx_t_9 = (__pyx_v_x >= __pyx_v_x2); + + if (__pyx_t_9) { + + + /* "fontTools/varLib/iup.py":73 + * d = d1 + * elif x >= x2: + * d = d2 # <<<<<<<<<<<<<< + * else: + * # Interpolate +*/ + __pyx_v_d = __pyx_v_d2; + + /* "fontTools/varLib/iup.py":72 + * if x <= x1: + * d = d1 + * elif x >= x2: # <<<<<<<<<<<<<< + * d = d2 + * else: +*/ + goto __pyx_L10; + } + + /* "fontTools/varLib/iup.py":82 + * # - https://godbolt.org/z/YsP4T3TqK, + * # - https://github.com/fonttools/fonttools/issues/3703 + * nudge = (x - x1) * scale # <<<<<<<<<<<<<< + * d = d1 + nudge + * +*/ + /*else*/ { + __pyx_v_nudge = ((__pyx_v_x - __pyx_v_x1) * __pyx_v_scale); + + /* "fontTools/varLib/iup.py":83 + * # - https://github.com/fonttools/fonttools/issues/3703 + * nudge = (x - x1) * scale + * d = d1 + nudge # <<<<<<<<<<<<<< + * + * out.append(d) +*/ + __pyx_v_d = (__pyx_v_d1 + __pyx_v_nudge); + } + __pyx_L10:; + + /* "fontTools/varLib/iup.py":85 + * d = d1 + nudge + * + * out.append(d) # <<<<<<<<<<<<<< + * + * return zip(*out_arrays) +*/ + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_d); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 85, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_12 = __Pyx_PyList_Append(__pyx_v_out, __pyx_t_3); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 85, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + + /* "fontTools/varLib/iup.py":67 + * # x1 < x2 + * scale = (d2 - d1) / (x2 - x1) + * for pair in coords: # <<<<<<<<<<<<<< + * x = pair[j] + * +*/ + } + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + + /* "fontTools/varLib/iup.py":49 + * # rd1 = reference delta 1 + * out_arrays = [None, None] + * for j in 0, 1: # <<<<<<<<<<<<<< + * out_arrays[j] = out = [] + * x1, x2, d1, d2 = rc1[j], rc2[j], rd1[j], rd2[j] +*/ + __pyx_L3_continue:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "fontTools/varLib/iup.py":87 + * out.append(d) + * + * return zip(*out_arrays) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_1 = PySequence_Tuple(__pyx_v_out_arrays); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 87, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_11 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_1, NULL); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 87, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __pyx_r = __pyx_t_11; + } + __Pyx_XDECREF(__pyx_temp); + } + __pyx_t_11 = 0; + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":27 + * + * + * @cython.cfunc # <<<<<<<<<<<<<< + * @cython.locals( + * j=cython.int, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_AddTraceback("fontTools.varLib.iup.iup_segment", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + + + + + + + + + + __Pyx_XDECREF(__pyx_v_out_arrays); + __Pyx_XDECREF(__pyx_v_out); + __Pyx_XDECREF(__pyx_v_pair); + + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/varLib/iup.py":90 + * + * + * def iup_contour(deltas: _DeltaOrNoneSegment, coords: _PointSegment) -> _DeltaSegment: # <<<<<<<<<<<<<< + * """For the contour given in `coords`, interpolate any missing + * delta values in delta vector `deltas`. +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_1iup_contour(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_6varLib_3iup_iup_contour, "iup_contour(deltas: _DeltaOrNoneSegment, coords: _PointSegment) -> _DeltaSegment\n\nFor the contour given in `coords`, interpolate any missing\ndelta values in delta vector `deltas`.\n\nReturns fully filled-out delta vector."); +static PyMethodDef __pyx_mdef_9fontTools_6varLib_3iup_1iup_contour = {"iup_contour", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_6varLib_3iup_1iup_contour, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_6varLib_3iup_iup_contour}; +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_1iup_contour(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_deltas = 0; + PyObject *__pyx_v_coords = 0; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("iup_contour (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_deltas,&__pyx_mstate_global->__pyx_n_u_coords,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 90, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 90, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 90, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "iup_contour", 0) < (0)) __PYX_ERR(0, 90, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("iup_contour", 1, 2, 2, i); __PYX_ERR(0, 90, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 2)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 90, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 90, __pyx_L3_error) + } + __pyx_v_deltas = values[0]; + __pyx_v_coords = values[1]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("iup_contour", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 90, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.varLib.iup.iup_contour", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9fontTools_6varLib_3iup_iup_contour(__pyx_self, __pyx_v_deltas, __pyx_v_coords); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_iup_contour(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords) { + PyObject *__pyx_v_n = NULL; + PyObject *__pyx_v_indices = NULL; + PyObject *__pyx_v_out = NULL; + PyObject *__pyx_v_it = NULL; + PyObject *__pyx_v_start = NULL; + PyObject *__pyx_v_i1 = NULL; + PyObject *__pyx_v_i2 = NULL; + PyObject *__pyx_v_ri1 = NULL; + PyObject *__pyx_v_ri2 = NULL; + PyObject *__pyx_v_end = NULL; + PyObject *__pyx_7genexpr__pyx_v_i = NULL; + PyObject *__pyx_7genexpr__pyx_v_v = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *(*__pyx_t_7)(PyObject *); + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_t_12; + PyObject *__pyx_t_13 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("iup_contour", 0); + + /* "fontTools/varLib/iup.py":96 + * Returns fully filled-out delta vector.""" + * + * assert len(deltas) == len(coords) # <<<<<<<<<<<<<< + * if None not in deltas: + * return deltas +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_1 = PyObject_Length(__pyx_v_deltas); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 96, __pyx_L1_error) + __pyx_t_2 = PyObject_Length(__pyx_v_coords); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 96, __pyx_L1_error) + __pyx_t_3 = (__pyx_t_1 == __pyx_t_2); + + + + if (unlikely(!__pyx_t_3)) { + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_AssertionError))), 0, 0, 0); + __PYX_ERR(0, 96, __pyx_L1_error) + } + + } + #else + if ((1)); else __PYX_ERR(0, 96, __pyx_L1_error) + #endif + + /* "fontTools/varLib/iup.py":97 + * + * assert len(deltas) == len(coords) + * if None not in deltas: # <<<<<<<<<<<<<< + * return deltas + * +*/ + __pyx_t_3 = (__Pyx_PySequence_ContainsTF(Py_None, __pyx_v_deltas, Py_NE)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 97, __pyx_L1_error) + if (__pyx_t_3) { + + + /* "fontTools/varLib/iup.py":98 + * assert len(deltas) == len(coords) + * if None not in deltas: + * return deltas # <<<<<<<<<<<<<< + * + * n = len(deltas) +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(__pyx_v_deltas); + __pyx_r = __pyx_v_deltas; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":97 + * + * assert len(deltas) == len(coords) + * if None not in deltas: # <<<<<<<<<<<<<< + * return deltas + * +*/ + } + + /* "fontTools/varLib/iup.py":100 + * return deltas + * + * n = len(deltas) # <<<<<<<<<<<<<< + * # indices of points with explicit deltas + * indices = [i for i, v in enumerate(deltas) if v is not None] +*/ + __pyx_t_2 = PyObject_Length(__pyx_v_deltas); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 100, __pyx_L1_error) + __pyx_t_4 = PyLong_FromSsize_t(__pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + + if (__Pyx_PyInt_FromNumber(&__pyx_t_4, NULL, 0) < (0)) __PYX_ERR(0, 100, __pyx_L1_error) + __pyx_v_n = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":102 + * n = len(deltas) + * # indices of points with explicit deltas + * indices = [i for i, v in enumerate(deltas) if v is not None] # <<<<<<<<<<<<<< + * if not indices: + * # All deltas are None. Return 0,0 for all. +*/ + { /* enter inner scope */ + __pyx_t_4 = PyList_New(0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 102, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_0); + __pyx_t_5 = __pyx_mstate_global->__pyx_int_0; + if (likely(PyList_CheckExact(__pyx_v_deltas)) || PyTuple_CheckExact(__pyx_v_deltas)) { + __pyx_t_6 = __pyx_v_deltas; __Pyx_INCREF(__pyx_t_6); + __pyx_t_2 = 0; + __pyx_t_7 = NULL; + } else { + __pyx_t_2 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_v_deltas); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 102, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 102, __pyx_L6_error) + } + for (;;) { + if (likely(!__pyx_t_7)) { + if (likely(PyList_CheckExact(__pyx_t_6))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 102, __pyx_L6_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + __pyx_t_8 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_6, __pyx_t_2, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_2; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 102, __pyx_L6_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_8 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_2)); + #else + __pyx_t_8 = __Pyx_PySequence_ITEM(__pyx_t_6, __pyx_t_2); + #endif + ++__pyx_t_2; + } + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 102, __pyx_L6_error) + } else { + __pyx_t_8 = __pyx_t_7(__pyx_t_6); + if (unlikely(!__pyx_t_8)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 102, __pyx_L6_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XDECREF_SET(__pyx_7genexpr__pyx_v_v, __pyx_t_8); + __pyx_t_8 = 0; + __Pyx_INCREF(__pyx_t_5); + __Pyx_XDECREF_SET(__pyx_7genexpr__pyx_v_i, __pyx_t_5); + __pyx_t_8 = __Pyx_PyLong_AddObjC(__pyx_t_5, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 102, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_5); + __pyx_t_5 = __pyx_t_8; + __pyx_t_8 = 0; + __pyx_t_3 = (__pyx_7genexpr__pyx_v_v != Py_None); + if (__pyx_t_3) { + + if (unlikely(__Pyx_ListComp_Append(__pyx_t_4, __pyx_7genexpr__pyx_v_i))) __PYX_ERR(0, 102, __pyx_L6_error) + } + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_i); __pyx_7genexpr__pyx_v_i = 0; + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_v); __pyx_7genexpr__pyx_v_v = 0; + goto __pyx_L11_exit_scope; + __pyx_L6_error:; + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_i); __pyx_7genexpr__pyx_v_i = 0; + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_v); __pyx_7genexpr__pyx_v_v = 0; + goto __pyx_L1_error; + __pyx_L11_exit_scope:; + } /* exit inner scope */ + __pyx_v_indices = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":103 + * # indices of points with explicit deltas + * indices = [i for i, v in enumerate(deltas) if v is not None] + * if not indices: # <<<<<<<<<<<<<< + * # All deltas are None. Return 0,0 for all. + * return [(0, 0)] * n +*/ + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_v_indices); + if (unlikely(((!CYTHON_ASSUME_SAFE_SIZE) && __pyx_temp < 0))) __PYX_ERR(0, 103, __pyx_L1_error) + __pyx_t_3 = (__pyx_temp != 0); + } + + __pyx_t_9 = (!__pyx_t_3); + + + if (__pyx_t_9) { + + + /* "fontTools/varLib/iup.py":105 + * if not indices: + * # All deltas are None. Return 0,0 for all. + * return [(0, 0)] * n # <<<<<<<<<<<<<< + * + * out = [] +*/ + __pyx_t_4 = PyList_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_mstate_global->__pyx_tuple[1]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[1]); + if (__Pyx_PyList_SET_ITEM(__pyx_t_4, 0, __pyx_mstate_global->__pyx_tuple[1]) != (0)) __PYX_ERR(0, 105, __pyx_L1_error); + { PyObject* __pyx_temp = PyNumber_InPlaceMultiply(__pyx_t_4, __pyx_v_n); if (unlikely(!__pyx_temp)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_temp); + __Pyx_DECREF(__pyx_t_4); + __pyx_t_4 = __pyx_temp; + } + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __pyx_r = __pyx_t_4; + } + __Pyx_XDECREF(__pyx_temp); + } + __pyx_t_4 = 0; + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":103 + * # indices of points with explicit deltas + * indices = [i for i, v in enumerate(deltas) if v is not None] + * if not indices: # <<<<<<<<<<<<<< + * # All deltas are None. Return 0,0 for all. + * return [(0, 0)] * n +*/ + } + + /* "fontTools/varLib/iup.py":107 + * return [(0, 0)] * n + * + * out = [] # <<<<<<<<<<<<<< + * it = iter(indices) + * start = next(it) +*/ + __pyx_t_4 = PyList_New(0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_v_out = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":108 + * + * out = [] + * it = iter(indices) # <<<<<<<<<<<<<< + * start = next(it) + * if start != 0: +*/ + __pyx_t_4 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_v_it = __pyx_t_4; + __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":109 + * out = [] + * it = iter(indices) + * start = next(it) # <<<<<<<<<<<<<< + * if start != 0: + * # Initial segment that wraps around +*/ + __pyx_t_4 = __Pyx_PyIter_Next(__pyx_v_it); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 109, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_v_start = __pyx_t_4; + __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":110 + * it = iter(indices) + * start = next(it) + * if start != 0: # <<<<<<<<<<<<<< + * # Initial segment that wraps around + * i1, i2, ri1, ri2 = 0, start, start, indices[-1] +*/ + __pyx_t_9 = (__Pyx_PyLong_BoolNeObjC(__pyx_v_start, __pyx_mstate_global->__pyx_int_0, 0, 0)); if (unlikely((__pyx_t_9 < 0))) __PYX_ERR(0, 110, __pyx_L1_error) + if (__pyx_t_9) { + + + /* "fontTools/varLib/iup.py":112 + * if start != 0: + * # Initial segment that wraps around + * i1, i2, ri1, ri2 = 0, start, start, indices[-1] # <<<<<<<<<<<<<< + * out.extend( + * iup_segment( +*/ + __pyx_t_4 = __pyx_mstate_global->__pyx_int_0; + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = __pyx_v_start; + __Pyx_INCREF(__pyx_t_5); + __pyx_t_6 = __pyx_v_start; + __Pyx_INCREF(__pyx_t_6); + __pyx_t_8 = __Pyx_GetItemInt_List(__pyx_v_indices, -1L, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_v_i1 = __pyx_t_4; + __pyx_t_4 = 0; + __pyx_v_i2 = __pyx_t_5; + __pyx_t_5 = 0; + __pyx_v_ri1 = __pyx_t_6; + __pyx_t_6 = 0; + __pyx_v_ri2 = __pyx_t_8; + __pyx_t_8 = 0; + + /* "fontTools/varLib/iup.py":115 + * out.extend( + * iup_segment( + * coords[i1:i2], coords[ri1], deltas[ri1], coords[ri2], deltas[ri2] # <<<<<<<<<<<<<< + * ) + * ) +*/ + __pyx_t_8 = __Pyx_PyObject_GetSlice(__pyx_v_coords, 0, 0, &__pyx_v_i1, &__pyx_v_i2, NULL, 0, 0, 1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_6 = __Pyx_PyObject_GetItem(__pyx_v_coords, __pyx_v_ri1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_v_ri1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetItem(__pyx_v_coords, __pyx_v_ri2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_10 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_v_ri2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + + /* "fontTools/varLib/iup.py":114 + * i1, i2, ri1, ri2 = 0, start, start, indices[-1] + * out.extend( + * iup_segment( # <<<<<<<<<<<<<< + * coords[i1:i2], coords[ri1], deltas[ri1], coords[ri2], deltas[ri2] + * ) +*/ + __pyx_t_11 = __pyx_f_9fontTools_6varLib_3iup_iup_segment(__pyx_t_8, __pyx_t_6, __pyx_t_5, __pyx_t_4, __pyx_t_10); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 114, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + + /* "fontTools/varLib/iup.py":113 + * # Initial segment that wraps around + * i1, i2, ri1, ri2 = 0, start, start, indices[-1] + * out.extend( # <<<<<<<<<<<<<< + * iup_segment( + * coords[i1:i2], coords[ri1], deltas[ri1], coords[ri2], deltas[ri2] +*/ + __pyx_t_12 = __Pyx_PyList_Extend(__pyx_v_out, __pyx_t_11); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 113, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + + + /* "fontTools/varLib/iup.py":110 + * it = iter(indices) + * start = next(it) + * if start != 0: # <<<<<<<<<<<<<< + * # Initial segment that wraps around + * i1, i2, ri1, ri2 = 0, start, start, indices[-1] +*/ + } + + /* "fontTools/varLib/iup.py":118 + * ) + * ) + * out.append(deltas[start]) # <<<<<<<<<<<<<< + * for end in it: + * if end - start > 1: +*/ + __pyx_t_11 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_v_start); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 118, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_12 = __Pyx_PyList_Append(__pyx_v_out, __pyx_t_11); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 118, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + + + /* "fontTools/varLib/iup.py":119 + * ) + * out.append(deltas[start]) + * for end in it: # <<<<<<<<<<<<<< + * if end - start > 1: + * i1, i2, ri1, ri2 = start + 1, end, start, end +*/ + if (likely(PyList_CheckExact(__pyx_v_it)) || PyTuple_CheckExact(__pyx_v_it)) { + __pyx_t_11 = __pyx_v_it; __Pyx_INCREF(__pyx_t_11); + __pyx_t_2 = 0; + __pyx_t_7 = NULL; + } else { + __pyx_t_2 = -1; __pyx_t_11 = PyObject_GetIter(__pyx_v_it); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 119, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_7 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_11); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 119, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_7)) { + if (likely(PyList_CheckExact(__pyx_t_11))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_11); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 119, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + __pyx_t_10 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_11, __pyx_t_2, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_2; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_11); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 119, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_10 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_11, __pyx_t_2)); + #else + __pyx_t_10 = __Pyx_PySequence_ITEM(__pyx_t_11, __pyx_t_2); + #endif + ++__pyx_t_2; + } + if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 119, __pyx_L1_error) + } else { + __pyx_t_10 = __pyx_t_7(__pyx_t_11); + if (unlikely(!__pyx_t_10)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 119, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_10); + __Pyx_XDECREF_SET(__pyx_v_end, __pyx_t_10); + __pyx_t_10 = 0; + + /* "fontTools/varLib/iup.py":120 + * out.append(deltas[start]) + * for end in it: + * if end - start > 1: # <<<<<<<<<<<<<< + * i1, i2, ri1, ri2 = start + 1, end, start, end + * out.extend( +*/ + __pyx_t_10 = __Pyx_PyNumber_Subtract_object_object(__pyx_v_end, __pyx_v_start); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 120, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_9 = __Pyx_PyObject_CompareBoolGt_object_int(__pyx_t_10, __pyx_mstate_global->__pyx_int_1, Py_GT); if (unlikely((__pyx_t_9 < 0))) __PYX_ERR(0, 120, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (__pyx_t_9) { + + + /* "fontTools/varLib/iup.py":121 + * for end in it: + * if end - start > 1: + * i1, i2, ri1, ri2 = start + 1, end, start, end # <<<<<<<<<<<<<< + * out.extend( + * iup_segment( +*/ + __pyx_t_10 = __Pyx_PyLong_AddObjC(__pyx_v_start, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 121, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_4 = __pyx_v_end; + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = __pyx_v_start; + __Pyx_INCREF(__pyx_t_5); + __pyx_t_6 = __pyx_v_end; + __Pyx_INCREF(__pyx_t_6); + __Pyx_XDECREF_SET(__pyx_v_i1, __pyx_t_10); + __pyx_t_10 = 0; + __Pyx_XDECREF_SET(__pyx_v_i2, __pyx_t_4); + __pyx_t_4 = 0; + __Pyx_XDECREF_SET(__pyx_v_ri1, __pyx_t_5); + __pyx_t_5 = 0; + __Pyx_XDECREF_SET(__pyx_v_ri2, __pyx_t_6); + __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":124 + * out.extend( + * iup_segment( + * coords[i1:i2], coords[ri1], deltas[ri1], coords[ri2], deltas[ri2] # <<<<<<<<<<<<<< + * ) + * ) +*/ + __pyx_t_6 = __Pyx_PyObject_GetSlice(__pyx_v_coords, 0, 0, &__pyx_v_i1, &__pyx_v_i2, NULL, 0, 0, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_coords, __pyx_v_ri1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_v_ri1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_10 = __Pyx_PyObject_GetItem(__pyx_v_coords, __pyx_v_ri2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_8 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_v_ri2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 124, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + + /* "fontTools/varLib/iup.py":123 + * i1, i2, ri1, ri2 = start + 1, end, start, end + * out.extend( + * iup_segment( # <<<<<<<<<<<<<< + * coords[i1:i2], coords[ri1], deltas[ri1], coords[ri2], deltas[ri2] + * ) +*/ + __pyx_t_13 = __pyx_f_9fontTools_6varLib_3iup_iup_segment(__pyx_t_6, __pyx_t_5, __pyx_t_4, __pyx_t_10, __pyx_t_8); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 123, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "fontTools/varLib/iup.py":122 + * if end - start > 1: + * i1, i2, ri1, ri2 = start + 1, end, start, end + * out.extend( # <<<<<<<<<<<<<< + * iup_segment( + * coords[i1:i2], coords[ri1], deltas[ri1], coords[ri2], deltas[ri2] +*/ + __pyx_t_12 = __Pyx_PyList_Extend(__pyx_v_out, __pyx_t_13); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 122, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + + + /* "fontTools/varLib/iup.py":120 + * out.append(deltas[start]) + * for end in it: + * if end - start > 1: # <<<<<<<<<<<<<< + * i1, i2, ri1, ri2 = start + 1, end, start, end + * out.extend( +*/ + } + + /* "fontTools/varLib/iup.py":127 + * ) + * ) + * out.append(deltas[end]) # <<<<<<<<<<<<<< + * start = end + * if start != n - 1: +*/ + __pyx_t_13 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_v_end); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + __pyx_t_12 = __Pyx_PyList_Append(__pyx_v_out, __pyx_t_13); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + + + /* "fontTools/varLib/iup.py":128 + * ) + * out.append(deltas[end]) + * start = end # <<<<<<<<<<<<<< + * if start != n - 1: + * # Final segment that wraps around +*/ + __Pyx_INCREF(__pyx_v_end); + __Pyx_DECREF_SET(__pyx_v_start, __pyx_v_end); + + /* "fontTools/varLib/iup.py":119 + * ) + * out.append(deltas[start]) + * for end in it: # <<<<<<<<<<<<<< + * if end - start > 1: + * i1, i2, ri1, ri2 = start + 1, end, start, end +*/ + } + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + + /* "fontTools/varLib/iup.py":129 + * out.append(deltas[end]) + * start = end + * if start != n - 1: # <<<<<<<<<<<<<< + * # Final segment that wraps around + * i1, i2, ri1, ri2 = start + 1, n, start, indices[0] +*/ + __pyx_t_11 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 129, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_9 = __Pyx_PyObject_CompareBoolNe_object_int(__pyx_v_start, __pyx_t_11, Py_NE); if (unlikely((__pyx_t_9 < 0))) __PYX_ERR(0, 129, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + if (__pyx_t_9) { + + + /* "fontTools/varLib/iup.py":131 + * if start != n - 1: + * # Final segment that wraps around + * i1, i2, ri1, ri2 = start + 1, n, start, indices[0] # <<<<<<<<<<<<<< + * out.extend( + * iup_segment( +*/ + __pyx_t_11 = __Pyx_PyLong_AddObjC(__pyx_v_start, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 131, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_13 = __pyx_v_n; + __Pyx_INCREF(__pyx_t_13); + __pyx_t_8 = __pyx_v_start; + __Pyx_INCREF(__pyx_t_8); + __pyx_t_10 = __Pyx_GetItemInt_List(__pyx_v_indices, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 131, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_XDECREF_SET(__pyx_v_i1, __pyx_t_11); + __pyx_t_11 = 0; + __Pyx_XDECREF_SET(__pyx_v_i2, __pyx_t_13); + __pyx_t_13 = 0; + __Pyx_XDECREF_SET(__pyx_v_ri1, __pyx_t_8); + __pyx_t_8 = 0; + __Pyx_XDECREF_SET(__pyx_v_ri2, __pyx_t_10); + __pyx_t_10 = 0; + + /* "fontTools/varLib/iup.py":134 + * out.extend( + * iup_segment( + * coords[i1:i2], coords[ri1], deltas[ri1], coords[ri2], deltas[ri2] # <<<<<<<<<<<<<< + * ) + * ) +*/ + __pyx_t_10 = __Pyx_PyObject_GetSlice(__pyx_v_coords, 0, 0, &__pyx_v_i1, &__pyx_v_i2, NULL, 0, 0, 1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_8 = __Pyx_PyObject_GetItem(__pyx_v_coords, __pyx_v_ri1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_13 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_v_ri1); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + __pyx_t_11 = __Pyx_PyObject_GetItem(__pyx_v_coords, __pyx_v_ri2); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_4 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_v_ri2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + + /* "fontTools/varLib/iup.py":133 + * i1, i2, ri1, ri2 = start + 1, n, start, indices[0] + * out.extend( + * iup_segment( # <<<<<<<<<<<<<< + * coords[i1:i2], coords[ri1], deltas[ri1], coords[ri2], deltas[ri2] + * ) +*/ + __pyx_t_5 = __pyx_f_9fontTools_6varLib_3iup_iup_segment(__pyx_t_10, __pyx_t_8, __pyx_t_13, __pyx_t_11, __pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 133, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":132 + * # Final segment that wraps around + * i1, i2, ri1, ri2 = start + 1, n, start, indices[0] + * out.extend( # <<<<<<<<<<<<<< + * iup_segment( + * coords[i1:i2], coords[ri1], deltas[ri1], coords[ri2], deltas[ri2] +*/ + __pyx_t_12 = __Pyx_PyList_Extend(__pyx_v_out, __pyx_t_5); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + + /* "fontTools/varLib/iup.py":129 + * out.append(deltas[end]) + * start = end + * if start != n - 1: # <<<<<<<<<<<<<< + * # Final segment that wraps around + * i1, i2, ri1, ri2 = start + 1, n, start, indices[0] +*/ + } + + /* "fontTools/varLib/iup.py":138 + * ) + * + * assert len(deltas) == len(out), (len(deltas), len(out)) # <<<<<<<<<<<<<< + * return out + * +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_2 = PyObject_Length(__pyx_v_deltas); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 138, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyList_GET_SIZE(__pyx_v_out); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 138, __pyx_L1_error) + __pyx_t_9 = (__pyx_t_2 == __pyx_t_1); + + + + if (unlikely(!__pyx_t_9)) { + __pyx_t_1 = PyObject_Length(__pyx_v_deltas); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 138, __pyx_L1_error) + __pyx_t_5 = PyLong_FromSsize_t(__pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + __pyx_t_1 = __Pyx_PyList_GET_SIZE(__pyx_v_out); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 138, __pyx_L1_error) + __pyx_t_4 = PyLong_FromSsize_t(__pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + + __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_5) != (0)) __PYX_ERR(0, 138, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_11, 1, __pyx_t_4) != (0)) __PYX_ERR(0, 138, __pyx_L1_error); + __pyx_t_5 = 0; + __pyx_t_4 = 0; + { + PyObject* __pyx_temp[1] = {__pyx_t_11}; + __pyx_t_4 = __Pyx_PyTuple_FromArray(__pyx_temp, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_AssertionError))), __pyx_t_4, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 138, __pyx_L1_error) + } + + } + #else + if ((1)); else __PYX_ERR(0, 138, __pyx_L1_error) + #endif + + /* "fontTools/varLib/iup.py":139 + * + * assert len(deltas) == len(out), (len(deltas), len(out)) + * return out # <<<<<<<<<<<<<< + * + * +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(__pyx_v_out); + __pyx_r = __pyx_v_out; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":90 + * + * + * def iup_contour(deltas: _DeltaOrNoneSegment, coords: _PointSegment) -> _DeltaSegment: # <<<<<<<<<<<<<< + * """For the contour given in `coords`, interpolate any missing + * delta values in delta vector `deltas`. +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_XDECREF(__pyx_t_13); + __Pyx_AddTraceback("fontTools.varLib.iup.iup_contour", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_n); + __Pyx_XDECREF(__pyx_v_indices); + __Pyx_XDECREF(__pyx_v_out); + __Pyx_XDECREF(__pyx_v_it); + __Pyx_XDECREF(__pyx_v_start); + __Pyx_XDECREF(__pyx_v_i1); + __Pyx_XDECREF(__pyx_v_i2); + __Pyx_XDECREF(__pyx_v_ri1); + __Pyx_XDECREF(__pyx_v_ri2); + __Pyx_XDECREF(__pyx_v_end); + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_i); + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_v); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/varLib/iup.py":142 + * + * + * def iup_delta( # <<<<<<<<<<<<<< + * deltas: _DeltaOrNoneSegment, coords: _PointSegment, ends: _Endpoints + * ) -> _DeltaSegment: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_3iup_delta(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_6varLib_3iup_2iup_delta, "iup_delta(deltas: _DeltaOrNoneSegment, coords: _PointSegment, ends: _Endpoints) -> _DeltaSegment\n\nFor the outline given in `coords`, with contour endpoints given\nin sorted increasing order in `ends`, interpolate any missing\ndelta values in delta vector `deltas`.\n\nReturns fully filled-out delta vector."); +static PyMethodDef __pyx_mdef_9fontTools_6varLib_3iup_3iup_delta = {"iup_delta", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_6varLib_3iup_3iup_delta, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_6varLib_3iup_2iup_delta}; +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_3iup_delta(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_deltas = 0; + PyObject *__pyx_v_coords = 0; + PyObject *__pyx_v_ends = 0; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("iup_delta (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_deltas,&__pyx_mstate_global->__pyx_n_u_coords,&__pyx_mstate_global->__pyx_n_u_ends,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 142, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 142, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 142, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 142, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "iup_delta", 0) < (0)) __PYX_ERR(0, 142, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("iup_delta", 1, 3, 3, i); __PYX_ERR(0, 142, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 142, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 142, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 142, __pyx_L3_error) + } + __pyx_v_deltas = values[0]; + __pyx_v_coords = values[1]; + __pyx_v_ends = values[2]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("iup_delta", 1, 3, 3, __pyx_nargs); __PYX_ERR(0, 142, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.varLib.iup.iup_delta", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9fontTools_6varLib_3iup_2iup_delta(__pyx_self, __pyx_v_deltas, __pyx_v_coords, __pyx_v_ends); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_2iup_delta(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords, PyObject *__pyx_v_ends) { + PyObject *__pyx_v_n = NULL; + PyObject *__pyx_v_out = NULL; + PyObject *__pyx_v_start = NULL; + PyObject *__pyx_v_end = NULL; + PyObject *__pyx_v_contour = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + Py_ssize_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *(*__pyx_t_9)(PyObject *); + PyObject *__pyx_t_10 = NULL; + size_t __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("iup_delta", 0); + __Pyx_INCREF(__pyx_v_ends); + + /* "fontTools/varLib/iup.py":151 + * Returns fully filled-out delta vector.""" + * + * assert sorted(ends) == ends and len(coords) == (ends[-1] + 1 if ends else 0) + 4 # <<<<<<<<<<<<<< + * n = len(coords) + * ends = ends + [n - 4, n - 3, n - 2, n - 1] +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_2 = PySequence_List(__pyx_v_ends); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (unlikely((PyList_Sort(__pyx_t_2) < 0))) __PYX_ERR(0, 151, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyObject_RichCompareBool(__pyx_t_2, __pyx_v_ends, Py_EQ); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_3) { + + } else { + + __pyx_t_1 = __pyx_t_3; + + goto __pyx_L3_bool_binop_done; + } + __pyx_t_4 = PyObject_Length(__pyx_v_coords); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-1))) __PYX_ERR(0, 151, __pyx_L1_error) + __pyx_t_2 = PyLong_FromSsize_t(__pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_ends); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 151, __pyx_L1_error) + if (__pyx_t_3) { + __pyx_t_6 = __Pyx_GetItemInt(__pyx_v_ends, -1L, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyLong_AddObjC(__pyx_t_6, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_5 = __pyx_t_7; + __pyx_t_7 = 0; + } else { + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_0); + __pyx_t_5 = __pyx_mstate_global->__pyx_int_0; + } + + __pyx_t_7 = __Pyx_PyLong_AddObjC(__pyx_t_5, __pyx_mstate_global->__pyx_int_4, 4, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_3 = __Pyx_PyObject_CompareBoolEq_int_object(__pyx_t_2, __pyx_t_7, Py_EQ); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + __pyx_t_1 = __pyx_t_3; + + __pyx_L3_bool_binop_done:; + if (unlikely(!__pyx_t_1)) { + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_AssertionError))), 0, 0, 0); + __PYX_ERR(0, 151, __pyx_L1_error) + } + + } + #else + if ((1)); else __PYX_ERR(0, 151, __pyx_L1_error) + #endif + + /* "fontTools/varLib/iup.py":152 + * + * assert sorted(ends) == ends and len(coords) == (ends[-1] + 1 if ends else 0) + 4 + * n = len(coords) # <<<<<<<<<<<<<< + * ends = ends + [n - 4, n - 3, n - 2, n - 1] + * out = [] +*/ + __pyx_t_4 = PyObject_Length(__pyx_v_coords); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-1))) __PYX_ERR(0, 152, __pyx_L1_error) + __pyx_t_7 = PyLong_FromSsize_t(__pyx_t_4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 152, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + + if (__Pyx_PyInt_FromNumber(&__pyx_t_7, NULL, 0) < (0)) __PYX_ERR(0, 152, __pyx_L1_error) + __pyx_v_n = ((PyObject*)__pyx_t_7); + __pyx_t_7 = 0; + + /* "fontTools/varLib/iup.py":153 + * assert sorted(ends) == ends and len(coords) == (ends[-1] + 1 if ends else 0) + 4 + * n = len(coords) + * ends = ends + [n - 4, n - 3, n - 2, n - 1] # <<<<<<<<<<<<<< + * out = [] + * start = 0 +*/ + __pyx_t_7 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_4, 4, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 153, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_3, 3, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 153, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_2, 2, 0, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 153, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 153, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = PyList_New(4); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 153, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GIVEREF(__pyx_t_7); + if (__Pyx_PyList_SET_ITEM(__pyx_t_8, 0, __pyx_t_7) != (0)) __PYX_ERR(0, 153, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_2); + if (__Pyx_PyList_SET_ITEM(__pyx_t_8, 1, __pyx_t_2) != (0)) __PYX_ERR(0, 153, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyList_SET_ITEM(__pyx_t_8, 2, __pyx_t_5) != (0)) __PYX_ERR(0, 153, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_6); + if (__Pyx_PyList_SET_ITEM(__pyx_t_8, 3, __pyx_t_6) != (0)) __PYX_ERR(0, 153, __pyx_L1_error); + __pyx_t_7 = 0; + __pyx_t_2 = 0; + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_t_6 = PyNumber_Add(__pyx_v_ends, __pyx_t_8); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 153, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF_SET(__pyx_v_ends, __pyx_t_6); + __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":154 + * n = len(coords) + * ends = ends + [n - 4, n - 3, n - 2, n - 1] + * out = [] # <<<<<<<<<<<<<< + * start = 0 + * for end in ends: +*/ + __pyx_t_6 = PyList_New(0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 154, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_v_out = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":155 + * ends = ends + [n - 4, n - 3, n - 2, n - 1] + * out = [] + * start = 0 # <<<<<<<<<<<<<< + * for end in ends: + * end += 1 +*/ + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_0); + __pyx_v_start = __pyx_mstate_global->__pyx_int_0; + + /* "fontTools/varLib/iup.py":156 + * out = [] + * start = 0 + * for end in ends: # <<<<<<<<<<<<<< + * end += 1 + * contour = iup_contour(deltas[start:end], coords[start:end]) +*/ + if (likely(PyList_CheckExact(__pyx_v_ends)) || PyTuple_CheckExact(__pyx_v_ends)) { + __pyx_t_6 = __pyx_v_ends; __Pyx_INCREF(__pyx_t_6); + __pyx_t_4 = 0; + __pyx_t_9 = NULL; + } else { + __pyx_t_4 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_v_ends); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 156, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_9 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_6); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 156, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_9)) { + if (likely(PyList_CheckExact(__pyx_t_6))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 156, __pyx_L1_error) + #endif + if (__pyx_t_4 >= __pyx_temp) break; + } + __pyx_t_8 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_6, __pyx_t_4, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_4; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 156, __pyx_L1_error) + #endif + if (__pyx_t_4 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_8 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_4)); + #else + __pyx_t_8 = __Pyx_PySequence_ITEM(__pyx_t_6, __pyx_t_4); + #endif + ++__pyx_t_4; + } + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 156, __pyx_L1_error) + } else { + __pyx_t_8 = __pyx_t_9(__pyx_t_6); + if (unlikely(!__pyx_t_8)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 156, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XDECREF_SET(__pyx_v_end, __pyx_t_8); + __pyx_t_8 = 0; + + /* "fontTools/varLib/iup.py":157 + * start = 0 + * for end in ends: + * end += 1 # <<<<<<<<<<<<<< + * contour = iup_contour(deltas[start:end], coords[start:end]) + * out.extend(contour) +*/ + __pyx_t_8 = __Pyx_PyLong_AddObjC(__pyx_v_end, __pyx_mstate_global->__pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 157, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF_SET(__pyx_v_end, __pyx_t_8); + __pyx_t_8 = 0; + + /* "fontTools/varLib/iup.py":158 + * for end in ends: + * end += 1 + * contour = iup_contour(deltas[start:end], coords[start:end]) # <<<<<<<<<<<<<< + * out.extend(contour) + * start = end +*/ + __pyx_t_5 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_iup_contour); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = __Pyx_PyObject_GetSlice(__pyx_v_deltas, 0, 0, &__pyx_v_start, &__pyx_v_end, NULL, 0, 0, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_10 = __Pyx_PyObject_GetSlice(__pyx_v_coords, 0, 0, &__pyx_v_start, &__pyx_v_end, NULL, 0, 0, 1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); + assert(__pyx_t_5); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_2, __pyx__function); + __pyx_t_11 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_5, __pyx_t_7, __pyx_t_10}; + __pyx_t_8 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_2, __pyx_callargs+__pyx_t_11, (3-__pyx_t_11) | (__pyx_t_11*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 158, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + } + __Pyx_XDECREF_SET(__pyx_v_contour, __pyx_t_8); + __pyx_t_8 = 0; + + /* "fontTools/varLib/iup.py":159 + * end += 1 + * contour = iup_contour(deltas[start:end], coords[start:end]) + * out.extend(contour) # <<<<<<<<<<<<<< + * start = end + * +*/ + __pyx_t_12 = __Pyx_PyList_Extend(__pyx_v_out, __pyx_v_contour); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 159, __pyx_L1_error) + + + /* "fontTools/varLib/iup.py":160 + * contour = iup_contour(deltas[start:end], coords[start:end]) + * out.extend(contour) + * start = end # <<<<<<<<<<<<<< + * + * return out +*/ + __Pyx_INCREF(__pyx_v_end); + __Pyx_DECREF_SET(__pyx_v_start, __pyx_v_end); + + /* "fontTools/varLib/iup.py":156 + * out = [] + * start = 0 + * for end in ends: # <<<<<<<<<<<<<< + * end += 1 + * contour = iup_contour(deltas[start:end], coords[start:end]) +*/ + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":162 + * start = end + * + * return out # <<<<<<<<<<<<<< + * + * +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(__pyx_v_out); + __pyx_r = __pyx_v_out; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":142 + * + * + * def iup_delta( # <<<<<<<<<<<<<< + * deltas: _DeltaOrNoneSegment, coords: _PointSegment, ends: _Endpoints + * ) -> _DeltaSegment: +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("fontTools.varLib.iup.iup_delta", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_n); + __Pyx_XDECREF(__pyx_v_out); + __Pyx_XDECREF(__pyx_v_start); + __Pyx_XDECREF(__pyx_v_end); + __Pyx_XDECREF(__pyx_v_contour); + __Pyx_XDECREF(__pyx_v_ends); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static PyObject *__pyx_gb_9fontTools_6varLib_3iup_18can_iup_in_between_2generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ + +/* "fontTools/varLib/iup.py":196 + * + * return all( + * abs(complex(x - p, y - q)) <= tolerance # <<<<<<<<<<<<<< + * for (x, y), (p, q) in zip(deltas, interp) + * ) +*/ + +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_18can_iup_in_between_genexpr(PyObject *__pyx_self, PyObject *__pyx_genexpr_arg_0) { + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr *__pyx_cur_scope; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("genexpr", 0); + __pyx_cur_scope = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr *)__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(__pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (unlikely(!__pyx_cur_scope)) { + __pyx_cur_scope = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr *)Py_None); + __Pyx_INCREF(Py_None); + __PYX_ERR(0, 196, __pyx_L1_error) + } else { + __Pyx_GOTREF((PyObject *)__pyx_cur_scope); + } + __pyx_cur_scope->__pyx_outer_scope = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *) __pyx_self; + __Pyx_INCREF((PyObject *)__pyx_cur_scope->__pyx_outer_scope); + __Pyx_GIVEREF((PyObject *)__pyx_cur_scope->__pyx_outer_scope); + __pyx_cur_scope->__pyx_genexpr_arg_0 = __pyx_genexpr_arg_0; + __Pyx_INCREF(__pyx_cur_scope->__pyx_genexpr_arg_0); + __Pyx_GIVEREF(__pyx_cur_scope->__pyx_genexpr_arg_0); + { + __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_9fontTools_6varLib_3iup_18can_iup_in_between_2generator, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[0]), (PyObject *) __pyx_cur_scope, __pyx_mstate_global->__pyx_n_u_genexpr, __pyx_mstate_global->__pyx_n_u_can_iup_in_between_locals_genexp, __pyx_mstate_global->__pyx_n_u_fontTools_varLib_iup); if (unlikely(!gen)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_DECREF(__pyx_cur_scope); + __Pyx_RefNannyFinishContext(); + return (PyObject *) gen; + } + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("fontTools.varLib.iup.can_iup_in_between.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_DECREF((PyObject *)__pyx_cur_scope); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_gb_9fontTools_6varLib_3iup_18can_iup_in_between_2generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ +{ + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr *__pyx_cur_scope = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr *)__pyx_generator->closure); + PyObject *__pyx_r = NULL; + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *(*__pyx_t_3)(PyObject *); + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + double __pyx_t_11; + double __pyx_t_12; + size_t __pyx_t_13; + int __pyx_t_14; + int __pyx_t_15; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("genexpr", 0); + switch (__pyx_generator->resume_label) { + case 0: goto __pyx_L3_first_run; + default: /* CPython raises the right error here */ + __Pyx_RefNannyFinishContext(); + return NULL; + } + __pyx_L3_first_run:; + if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 196, __pyx_L1_error) + + /* "fontTools/varLib/iup.py":197 + * return all( + * abs(complex(x - p, y - q)) <= tolerance + * for (x, y), (p, q) in zip(deltas, interp) # <<<<<<<<<<<<<< + * ) + * +*/ + if (unlikely(!__pyx_cur_scope->__pyx_genexpr_arg_0)) { __Pyx_RaiseUnboundLocalError(".0"); __PYX_ERR(0, 197, __pyx_L1_error) } + if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_genexpr_arg_0)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_genexpr_arg_0)) { + __pyx_t_1 = __pyx_cur_scope->__pyx_genexpr_arg_0; __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = 0; + __pyx_t_3 = NULL; + } else { + __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_cur_scope->__pyx_genexpr_arg_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 197, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_3)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 197, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + __pyx_t_4 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_1, __pyx_t_2, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_2; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 197, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2)); + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_2); + #endif + ++__pyx_t_2; + } + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 197, __pyx_L1_error) + } else { + __pyx_t_4 = __pyx_t_3(__pyx_t_1); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 197, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_4); + if ((likely(PyTuple_CheckExact(__pyx_t_4))) || (PyList_CheckExact(__pyx_t_4))) { + PyObject* sequence = __pyx_t_4; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 197, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_5); + __pyx_t_6 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_6); + } else { + __pyx_t_5 = __Pyx_PyList_GET_ITEM_REF(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyList_GET_ITEM_REF(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_6); + } + #else + __pyx_t_5 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #endif + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_7 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_8 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_7); + index = 0; __pyx_t_5 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_5)) goto __pyx_L6_unpacking_failed; + __Pyx_GOTREF(__pyx_t_5); + index = 1; __pyx_t_6 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_6)) goto __pyx_L6_unpacking_failed; + __Pyx_GOTREF(__pyx_t_6); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 2) < (0)) __PYX_ERR(0, 197, __pyx_L1_error) + __pyx_t_8 = NULL; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L7_unpacking_done; + __pyx_L6_unpacking_failed:; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 197, __pyx_L1_error) + __pyx_L7_unpacking_done:; + } + if ((likely(PyTuple_CheckExact(__pyx_t_5))) || (PyList_CheckExact(__pyx_t_5))) { + PyObject* sequence = __pyx_t_5; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 197, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_7 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_7); + __pyx_t_9 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_9); + } else { + __pyx_t_7 = __Pyx_PyList_GET_ITEM_REF(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_7); + __pyx_t_9 = __Pyx_PyList_GET_ITEM_REF(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_9); + } + #else + __pyx_t_7 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + #endif + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_10 = PyObject_GetIter(__pyx_t_5); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_8 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_10); + index = 0; __pyx_t_7 = __pyx_t_8(__pyx_t_10); if (unlikely(!__pyx_t_7)) goto __pyx_L8_unpacking_failed; + __Pyx_GOTREF(__pyx_t_7); + index = 1; __pyx_t_9 = __pyx_t_8(__pyx_t_10); if (unlikely(!__pyx_t_9)) goto __pyx_L8_unpacking_failed; + __Pyx_GOTREF(__pyx_t_9); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_10), 2) < (0)) __PYX_ERR(0, 197, __pyx_L1_error) + __pyx_t_8 = NULL; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + goto __pyx_L9_unpacking_done; + __pyx_L8_unpacking_failed:; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_8 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 197, __pyx_L1_error) + __pyx_L9_unpacking_done:; + } + __pyx_t_11 = __Pyx_PyFloat_AsDouble(__pyx_t_7); if (unlikely((__pyx_t_11 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_12 = __Pyx_PyFloat_AsDouble(__pyx_t_9); if (unlikely((__pyx_t_12 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_cur_scope->__pyx_v_x = __pyx_t_11; + __pyx_cur_scope->__pyx_v_y = __pyx_t_12; + if ((likely(PyTuple_CheckExact(__pyx_t_6))) || (PyList_CheckExact(__pyx_t_6))) { + PyObject* sequence = __pyx_t_6; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 197, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_9 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_9); + __pyx_t_7 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_7); + } else { + __pyx_t_9 = __Pyx_PyList_GET_ITEM_REF(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_9); + __pyx_t_7 = __Pyx_PyList_GET_ITEM_REF(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_7); + } + #else + __pyx_t_9 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_7 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + #endif + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_10 = PyObject_GetIter(__pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_8 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_10); + index = 0; __pyx_t_9 = __pyx_t_8(__pyx_t_10); if (unlikely(!__pyx_t_9)) goto __pyx_L10_unpacking_failed; + __Pyx_GOTREF(__pyx_t_9); + index = 1; __pyx_t_7 = __pyx_t_8(__pyx_t_10); if (unlikely(!__pyx_t_7)) goto __pyx_L10_unpacking_failed; + __Pyx_GOTREF(__pyx_t_7); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_10), 2) < (0)) __PYX_ERR(0, 197, __pyx_L1_error) + __pyx_t_8 = NULL; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + goto __pyx_L11_unpacking_done; + __pyx_L10_unpacking_failed:; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_8 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 197, __pyx_L1_error) + __pyx_L11_unpacking_done:; + } + __pyx_t_12 = __Pyx_PyFloat_AsDouble(__pyx_t_9); if (unlikely((__pyx_t_12 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_11 = __Pyx_PyFloat_AsDouble(__pyx_t_7); if (unlikely((__pyx_t_11 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_cur_scope->__pyx_v_p = __pyx_t_12; + __pyx_cur_scope->__pyx_v_q = __pyx_t_11; + + /* "fontTools/varLib/iup.py":196 + * + * return all( + * abs(complex(x - p, y - q)) <= tolerance # <<<<<<<<<<<<<< + * for (x, y), (p, q) in zip(deltas, interp) + * ) +*/ + __pyx_t_6 = NULL; + __pyx_t_5 = PyFloat_FromDouble((__pyx_cur_scope->__pyx_v_x - __pyx_cur_scope->__pyx_v_p)); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = PyFloat_FromDouble((__pyx_cur_scope->__pyx_v_y - __pyx_cur_scope->__pyx_v_q)); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_13 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_6, __pyx_t_5, __pyx_t_7}; + __pyx_t_4 = __Pyx_PyObject_FastCall((PyObject*)(&PyComplex_Type), __pyx_callargs+__pyx_t_13, (3-__pyx_t_13) | (__pyx_t_13*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __pyx_t_7 = __Pyx_PyNumber_Absolute(__pyx_t_4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_tolerance)) { __Pyx_RaiseClosureNameError("tolerance"); __PYX_ERR(0, 196, __pyx_L1_error) } + __pyx_t_14 = __Pyx_PyObject_CompareBoolLe_object_object(__pyx_t_7, __pyx_cur_scope->__pyx_outer_scope->__pyx_v_tolerance, Py_LE); if (unlikely((__pyx_t_14 < 0))) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_15 = (!__pyx_t_14); + + + if (__pyx_t_15) { + + + /* "fontTools/varLib/iup.py":195 + * deltas = deltas[i + 1 : j] + * + * return all( # <<<<<<<<<<<<<< + * abs(complex(x - p, y - q)) <= tolerance + * for (x, y), (p, q) in zip(deltas, interp) +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(Py_False); + __pyx_r = Py_False; + } + __Pyx_XDECREF(__pyx_temp); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":196 + * + * return all( + * abs(complex(x - p, y - q)) <= tolerance # <<<<<<<<<<<<<< + * for (x, y), (p, q) in zip(deltas, interp) + * ) +*/ + } + + /* "fontTools/varLib/iup.py":197 + * return all( + * abs(complex(x - p, y - q)) <= tolerance + * for (x, y), (p, q) in zip(deltas, interp) # <<<<<<<<<<<<<< + * ) + * +*/ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + /*else*/ { + + /* "fontTools/varLib/iup.py":196 + * + * return all( + * abs(complex(x - p, y - q)) <= tolerance # <<<<<<<<<<<<<< + * for (x, y), (p, q) in zip(deltas, interp) + * ) +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(Py_True); + __pyx_r = Py_True; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + } + CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + if (__Pyx_PyErr_Occurred()) { + __Pyx_Generator_Replace_StopIteration(0); + __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + #if !CYTHON_USE_EXC_INFO_STACK + __Pyx_Coroutine_ResetAndClearException(__pyx_generator); + #endif + __pyx_generator->resume_label = -1; + __Pyx_Coroutine_clear((PyObject*)__pyx_generator); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/varLib/iup.py":168 + * + * + * @cython.cfunc # <<<<<<<<<<<<<< + * @cython.inline + * @cython.locals( +*/ + +static CYTHON_INLINE int __pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords, int __pyx_v_i, int __pyx_v_j, PyObject *__pyx_v_tolerance) { + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *__pyx_cur_scope; + PyObject *__pyx_v_interp = NULL; + PyObject *__pyx_gb_9fontTools_6varLib_3iup_18can_iup_in_between_2generator = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + size_t __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("can_iup_in_between", 0); + __pyx_cur_scope = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *)__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(__pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (unlikely(!__pyx_cur_scope)) { + __pyx_cur_scope = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *)Py_None); + __Pyx_INCREF(Py_None); + __PYX_ERR(0, 168, __pyx_L1_error) + } else { + __Pyx_GOTREF((PyObject *)__pyx_cur_scope); + } + __pyx_cur_scope->__pyx_v_tolerance = __pyx_v_tolerance; + __Pyx_INCREF(__pyx_cur_scope->__pyx_v_tolerance); + __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_tolerance); + __Pyx_INCREF(__pyx_v_deltas); + + /* "fontTools/varLib/iup.py":191 + * provided error tolerance.""" + * + * assert j - i >= 2 # <<<<<<<<<<<<<< + * interp = iup_segment(coords[i + 1 : j], coords[i], deltas[i], coords[j], deltas[j]) + * deltas = deltas[i + 1 : j] +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_1 = ((__pyx_v_j - __pyx_v_i) >= 2); + + if (unlikely(!__pyx_t_1)) { + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_AssertionError))), 0, 0, 0); + __PYX_ERR(0, 191, __pyx_L1_error) + } + + } + #else + if ((1)); else __PYX_ERR(0, 191, __pyx_L1_error) + #endif + + /* "fontTools/varLib/iup.py":192 + * + * assert j - i >= 2 + * interp = iup_segment(coords[i + 1 : j], coords[i], deltas[i], coords[j], deltas[j]) # <<<<<<<<<<<<<< + * deltas = deltas[i + 1 : j] + * +*/ + __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_v_coords, (__pyx_v_i + 1), __pyx_v_j, NULL, NULL, NULL, 1, 1, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 192, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_coords, __pyx_v_i, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 192, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_deltas, __pyx_v_i, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 192, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_coords, __pyx_v_j, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 192, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_GetItemInt(__pyx_v_deltas, __pyx_v_j, int, 1, __Pyx_PyLong_From_int, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 192, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __pyx_f_9fontTools_6varLib_3iup_iup_segment(__pyx_t_2, __pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 192, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_v_interp = __pyx_t_7; + __pyx_t_7 = 0; + + /* "fontTools/varLib/iup.py":193 + * assert j - i >= 2 + * interp = iup_segment(coords[i + 1 : j], coords[i], deltas[i], coords[j], deltas[j]) + * deltas = deltas[i + 1 : j] # <<<<<<<<<<<<<< + * + * return all( +*/ + __pyx_t_7 = __Pyx_PyObject_GetSlice(__pyx_v_deltas, (__pyx_v_i + 1), __pyx_v_j, NULL, NULL, NULL, 1, 1, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 193, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF_SET(__pyx_v_deltas, __pyx_t_7); + __pyx_t_7 = 0; + + /* "fontTools/varLib/iup.py":197 + * return all( + * abs(complex(x - p, y - q)) <= tolerance + * for (x, y), (p, q) in zip(deltas, interp) # <<<<<<<<<<<<<< + * ) + * +*/ + __pyx_t_6 = NULL; + __pyx_t_8 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_6, __pyx_v_deltas, __pyx_v_interp}; + __pyx_t_7 = __Pyx_PyObject_FastCall((PyObject*)__pyx_builtin_zip, __pyx_callargs+__pyx_t_8, (3-__pyx_t_8) | (__pyx_t_8*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 197, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + } + + /* "fontTools/varLib/iup.py":196 + * + * return all( + * abs(complex(x - p, y - q)) <= tolerance # <<<<<<<<<<<<<< + * for (x, y), (p, q) in zip(deltas, interp) + * ) +*/ + __pyx_t_6 = __pyx_pf_9fontTools_6varLib_3iup_18can_iup_in_between_genexpr(((PyObject*)__pyx_cur_scope), __pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_Generator_GetInlinedResult(__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_9 = __Pyx_PyLong_As_int(__pyx_t_7); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + { + __pyx_r = __pyx_t_9; + } + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":168 + * + * + * @cython.cfunc # <<<<<<<<<<<<<< + * @cython.inline + * @cython.locals( +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("fontTools.varLib.iup.can_iup_in_between", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_interp); + __Pyx_XDECREF(__pyx_gb_9fontTools_6varLib_3iup_18can_iup_in_between_2generator); + __Pyx_XDECREF(__pyx_v_deltas); + __Pyx_DECREF((PyObject *)__pyx_cur_scope); + + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/varLib/iup.py":201 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * cj=cython.double, + * dj=cython.double, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_5_iup_contour_bound_forced_set(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_6varLib_3iup_4_iup_contour_bound_forced_set, "_iup_contour_bound_forced_set(deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0) -> set\n\nThe forced set is a conservative set of points on the contour that must be encoded\nexplicitly (ie. cannot be interpolated). Calculating this set allows for significantly\nspeeding up the dynamic-programming, as well as resolve circularity in DP.\n\nThe set is precise; that is, if an index is in the returned set, then there is no way\nthat IUP can generate delta for that point, given `coords` and `deltas`."); +static PyMethodDef __pyx_mdef_9fontTools_6varLib_3iup_5_iup_contour_bound_forced_set = {"_iup_contour_bound_forced_set", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_6varLib_3iup_5_iup_contour_bound_forced_set, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_6varLib_3iup_4_iup_contour_bound_forced_set}; +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_5_iup_contour_bound_forced_set(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_deltas = 0; + PyObject *__pyx_v_coords = 0; + PyObject *__pyx_v_tolerance = 0; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_iup_contour_bound_forced_set (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_deltas,&__pyx_mstate_global->__pyx_n_u_coords,&__pyx_mstate_global->__pyx_n_u_tolerance,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 201, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 201, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 201, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 201, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "_iup_contour_bound_forced_set", 0) < (0)) __PYX_ERR(0, 201, __pyx_L3_error) + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)((PyObject*)__pyx_mstate_global->__pyx_int_0))); + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("_iup_contour_bound_forced_set", 0, 2, 3, i); __PYX_ERR(0, 201, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 201, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 201, __pyx_L3_error) + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 201, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)((PyObject*)__pyx_mstate_global->__pyx_int_0))); + } + __pyx_v_deltas = values[0]; + __pyx_v_coords = values[1]; + __pyx_v_tolerance = values[2]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_iup_contour_bound_forced_set", 0, 2, 3, __pyx_nargs); __PYX_ERR(0, 201, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.varLib.iup._iup_contour_bound_forced_set", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9fontTools_6varLib_3iup_4_iup_contour_bound_forced_set(__pyx_self, __pyx_v_deltas, __pyx_v_coords, __pyx_v_tolerance); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_4_iup_contour_bound_forced_set(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords, PyObject *__pyx_v_tolerance) { + double __pyx_v_cj; + double __pyx_v_dj; + double __pyx_v_lcj; + double __pyx_v_ldj; + double __pyx_v_ncj; + double __pyx_v_ndj; + int __pyx_v_force; + PyObject *__pyx_v_forced = 0; + PyObject *__pyx_v_n = NULL; + PyObject *__pyx_v_i = NULL; + PyObject *__pyx_v_ld = NULL; + PyObject *__pyx_v_lc = NULL; + PyObject *__pyx_v_d = NULL; + PyObject *__pyx_v_c = NULL; + PyObject *__pyx_v_nd = NULL; + PyObject *__pyx_v_nc = NULL; + long __pyx_v_j; + double __pyx_v_c1; + double __pyx_v_c2; + double __pyx_v_d1; + double __pyx_v_d2; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + long __pyx_t_10; + double __pyx_t_11; + double __pyx_t_12; + int __pyx_t_13; + double __pyx_t_14; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + int __pyx_t_17; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_iup_contour_bound_forced_set", 0); + + /* "fontTools/varLib/iup.py":221 + * that IUP can generate delta for that point, given `coords` and `deltas`. + * """ + * assert len(deltas) == len(coords) # <<<<<<<<<<<<<< + * + * n = len(deltas) +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_1 = PyObject_Length(__pyx_v_deltas); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 221, __pyx_L1_error) + __pyx_t_2 = PyObject_Length(__pyx_v_coords); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 221, __pyx_L1_error) + __pyx_t_3 = (__pyx_t_1 == __pyx_t_2); + + + + if (unlikely(!__pyx_t_3)) { + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_AssertionError))), 0, 0, 0); + __PYX_ERR(0, 221, __pyx_L1_error) + } + + } + #else + if ((1)); else __PYX_ERR(0, 221, __pyx_L1_error) + #endif + + /* "fontTools/varLib/iup.py":223 + * assert len(deltas) == len(coords) + * + * n = len(deltas) # <<<<<<<<<<<<<< + * forced = set() + * # Track "last" and "next" points on the contour as we sweep. +*/ + __pyx_t_2 = PyObject_Length(__pyx_v_deltas); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 223, __pyx_L1_error) + __pyx_t_4 = PyLong_FromSsize_t(__pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 223, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + + if (__Pyx_PyInt_FromNumber(&__pyx_t_4, NULL, 0) < (0)) __PYX_ERR(0, 223, __pyx_L1_error) + __pyx_v_n = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":224 + * + * n = len(deltas) + * forced = set() # <<<<<<<<<<<<<< + * # Track "last" and "next" points on the contour as we sweep. + * for i in range(len(deltas) - 1, -1, -1): +*/ + __pyx_t_4 = PySet_New(0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 224, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_v_forced = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":226 + * forced = set() + * # Track "last" and "next" points on the contour as we sweep. + * for i in range(len(deltas) - 1, -1, -1): # <<<<<<<<<<<<<< + * ld, lc = deltas[i - 1], coords[i - 1] + * d, c = deltas[i], coords[i] +*/ + __pyx_t_5 = NULL; + __pyx_t_2 = PyObject_Length(__pyx_v_deltas); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 226, __pyx_L1_error) + __pyx_t_6 = PyLong_FromSsize_t((__pyx_t_2 - 1)); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 226, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + + __pyx_t_7 = 1; + { + PyObject *__pyx_callargs[4] = {__pyx_t_5, __pyx_t_6, __pyx_mstate_global->__pyx_int_neg_1, __pyx_mstate_global->__pyx_int_neg_1}; + __pyx_t_4 = __Pyx_PyObject_FastCall((PyObject*)(&PyRange_Type), __pyx_callargs+__pyx_t_7, (4-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 226, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __pyx_t_6 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 226, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_6); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 226, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + for (;;) { + { + __pyx_t_4 = __pyx_t_8(__pyx_t_6); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 226, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_PyInt_FromNumber(&__pyx_t_4, NULL, 1) < (0)) __PYX_ERR(0, 226, __pyx_L1_error) + __Pyx_XDECREF_SET(__pyx_v_i, ((PyObject*)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":227 + * # Track "last" and "next" points on the contour as we sweep. + * for i in range(len(deltas) - 1, -1, -1): + * ld, lc = deltas[i - 1], coords[i - 1] # <<<<<<<<<<<<<< + * d, c = deltas[i], coords[i] + * nd, nc = deltas[i - n + 1], coords[i - n + 1] +*/ + __pyx_t_4 = __Pyx_PyLong_SubtractObjC(__pyx_v_i, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 227, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 227, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyLong_SubtractObjC(__pyx_v_i, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 227, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_9 = __Pyx_PyObject_GetItem(__pyx_v_coords, __pyx_t_4); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 227, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF_SET(__pyx_v_ld, __pyx_t_5); + __pyx_t_5 = 0; + __Pyx_XDECREF_SET(__pyx_v_lc, __pyx_t_9); + __pyx_t_9 = 0; + + /* "fontTools/varLib/iup.py":228 + * for i in range(len(deltas) - 1, -1, -1): + * ld, lc = deltas[i - 1], coords[i - 1] + * d, c = deltas[i], coords[i] # <<<<<<<<<<<<<< + * nd, nc = deltas[i - n + 1], coords[i - n + 1] + * +*/ + __pyx_t_9 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_v_i); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 228, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_coords, __pyx_v_i); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 228, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_XDECREF_SET(__pyx_v_d, __pyx_t_9); + __pyx_t_9 = 0; + __Pyx_XDECREF_SET(__pyx_v_c, __pyx_t_5); + __pyx_t_5 = 0; + + /* "fontTools/varLib/iup.py":229 + * ld, lc = deltas[i - 1], coords[i - 1] + * d, c = deltas[i], coords[i] + * nd, nc = deltas[i - n + 1], coords[i - n + 1] # <<<<<<<<<<<<<< + * + * for j in (0, 1): # For X and for Y +*/ + __pyx_t_5 = __Pyx_PyNumber_Subtract_int_int(__pyx_v_i, __pyx_v_n); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 229, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_9 = __Pyx_PyLong_AddObjC(__pyx_t_5, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 229, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_t_9); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 229, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyNumber_Subtract_int_int(__pyx_v_i, __pyx_v_n); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 229, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_4 = __Pyx_PyLong_AddObjC(__pyx_t_9, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 229, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_9 = __Pyx_PyObject_GetItem(__pyx_v_coords, __pyx_t_4); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 229, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF_SET(__pyx_v_nd, __pyx_t_5); + __pyx_t_5 = 0; + __Pyx_XDECREF_SET(__pyx_v_nc, __pyx_t_9); + __pyx_t_9 = 0; + + /* "fontTools/varLib/iup.py":231 + * nd, nc = deltas[i - n + 1], coords[i - n + 1] + * + * for j in (0, 1): # For X and for Y # <<<<<<<<<<<<<< + * cj = c[j] + * dj = d[j] +*/ + __pyx_t_9 = __pyx_mstate_global->__pyx_tuple[0]; __Pyx_INCREF(__pyx_t_9); + __pyx_t_2 = 0; + for (;;) { + if (__pyx_t_2 >= 2) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_5 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_2)); + #else + __pyx_t_5 = __Pyx_PySequence_ITEM(__pyx_t_9, __pyx_t_2); + #endif + ++__pyx_t_2; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 231, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (__Pyx_PyInt_FromNumber(&__pyx_t_5, NULL, 1) < (0)) __PYX_ERR(0, 231, __pyx_L1_error) + __pyx_t_10 = __Pyx_PyLong_As_long(__pyx_t_5); if (unlikely((__pyx_t_10 == (long)-1) && PyErr_Occurred())) __PYX_ERR(0, 231, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_j = __pyx_t_10; + + /* "fontTools/varLib/iup.py":232 + * + * for j in (0, 1): # For X and for Y + * cj = c[j] # <<<<<<<<<<<<<< + * dj = d[j] + * lcj = lc[j] +*/ + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_c, __pyx_v_j, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 232, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_11 = __Pyx_PyFloat_AsDouble(__pyx_t_5); if (unlikely((__pyx_t_11 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 232, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_cj = __pyx_t_11; + + /* "fontTools/varLib/iup.py":233 + * for j in (0, 1): # For X and for Y + * cj = c[j] + * dj = d[j] # <<<<<<<<<<<<<< + * lcj = lc[j] + * ldj = ld[j] +*/ + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_d, __pyx_v_j, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 233, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_11 = __Pyx_PyFloat_AsDouble(__pyx_t_5); if (unlikely((__pyx_t_11 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 233, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_dj = __pyx_t_11; + + /* "fontTools/varLib/iup.py":234 + * cj = c[j] + * dj = d[j] + * lcj = lc[j] # <<<<<<<<<<<<<< + * ldj = ld[j] + * ncj = nc[j] +*/ + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_lc, __pyx_v_j, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 234, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_11 = __Pyx_PyFloat_AsDouble(__pyx_t_5); if (unlikely((__pyx_t_11 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 234, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_lcj = __pyx_t_11; + + /* "fontTools/varLib/iup.py":235 + * dj = d[j] + * lcj = lc[j] + * ldj = ld[j] # <<<<<<<<<<<<<< + * ncj = nc[j] + * ndj = nd[j] +*/ + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_ld, __pyx_v_j, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 235, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_11 = __Pyx_PyFloat_AsDouble(__pyx_t_5); if (unlikely((__pyx_t_11 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 235, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_ldj = __pyx_t_11; + + /* "fontTools/varLib/iup.py":236 + * lcj = lc[j] + * ldj = ld[j] + * ncj = nc[j] # <<<<<<<<<<<<<< + * ndj = nd[j] + * +*/ + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_nc, __pyx_v_j, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 236, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_11 = __Pyx_PyFloat_AsDouble(__pyx_t_5); if (unlikely((__pyx_t_11 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 236, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_ncj = __pyx_t_11; + + /* "fontTools/varLib/iup.py":237 + * ldj = ld[j] + * ncj = nc[j] + * ndj = nd[j] # <<<<<<<<<<<<<< + * + * if lcj <= ncj: +*/ + __pyx_t_5 = __Pyx_GetItemInt(__pyx_v_nd, __pyx_v_j, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_OwnStrongReference); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 237, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_11 = __Pyx_PyFloat_AsDouble(__pyx_t_5); if (unlikely((__pyx_t_11 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 237, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_ndj = __pyx_t_11; + + /* "fontTools/varLib/iup.py":239 + * ndj = nd[j] + * + * if lcj <= ncj: # <<<<<<<<<<<<<< + * c1, c2 = lcj, ncj + * d1, d2 = ldj, ndj +*/ + __pyx_t_3 = (__pyx_v_lcj <= __pyx_v_ncj); + + if (__pyx_t_3) { + + + /* "fontTools/varLib/iup.py":240 + * + * if lcj <= ncj: + * c1, c2 = lcj, ncj # <<<<<<<<<<<<<< + * d1, d2 = ldj, ndj + * else: +*/ + __pyx_t_11 = __pyx_v_lcj; + + __pyx_t_12 = __pyx_v_ncj; + + __pyx_v_c1 = __pyx_t_11; + __pyx_v_c2 = __pyx_t_12; + + /* "fontTools/varLib/iup.py":241 + * if lcj <= ncj: + * c1, c2 = lcj, ncj + * d1, d2 = ldj, ndj # <<<<<<<<<<<<<< + * else: + * c1, c2 = ncj, lcj +*/ + __pyx_t_12 = __pyx_v_ldj; + + __pyx_t_11 = __pyx_v_ndj; + + __pyx_v_d1 = __pyx_t_12; + __pyx_v_d2 = __pyx_t_11; + + /* "fontTools/varLib/iup.py":239 + * ndj = nd[j] + * + * if lcj <= ncj: # <<<<<<<<<<<<<< + * c1, c2 = lcj, ncj + * d1, d2 = ldj, ndj +*/ + goto __pyx_L7; + } + + /* "fontTools/varLib/iup.py":243 + * d1, d2 = ldj, ndj + * else: + * c1, c2 = ncj, lcj # <<<<<<<<<<<<<< + * d1, d2 = ndj, ldj + * +*/ + /*else*/ { + __pyx_t_11 = __pyx_v_ncj; + + __pyx_t_12 = __pyx_v_lcj; + + __pyx_v_c1 = __pyx_t_11; + __pyx_v_c2 = __pyx_t_12; + + /* "fontTools/varLib/iup.py":244 + * else: + * c1, c2 = ncj, lcj + * d1, d2 = ndj, ldj # <<<<<<<<<<<<<< + * + * force = False +*/ + __pyx_t_12 = __pyx_v_ndj; + + __pyx_t_11 = __pyx_v_ldj; + + __pyx_v_d1 = __pyx_t_12; + __pyx_v_d2 = __pyx_t_11; + } + __pyx_L7:; + + /* "fontTools/varLib/iup.py":246 + * d1, d2 = ndj, ldj + * + * force = False # <<<<<<<<<<<<<< + * + * # If the two coordinates are the same, then the interpolation +*/ + __pyx_v_force = 0; + + /* "fontTools/varLib/iup.py":253 + * # + * # This test has to be before the next one. + * if c1 == c2: # <<<<<<<<<<<<<< + * if abs(d1 - d2) > tolerance and abs(dj) > tolerance: + * force = True +*/ + __pyx_t_3 = (__pyx_v_c1 == __pyx_v_c2); + + if (__pyx_t_3) { + + + /* "fontTools/varLib/iup.py":254 + * # This test has to be before the next one. + * if c1 == c2: + * if abs(d1 - d2) > tolerance and abs(dj) > tolerance: # <<<<<<<<<<<<<< + * force = True + * +*/ + __pyx_t_11 = fabs((__pyx_v_d1 - __pyx_v_d2)); + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_11); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 254, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + __pyx_t_13 = __Pyx_PyObject_CompareBoolGt_float_object(__pyx_t_5, __pyx_v_tolerance, Py_GT); if (unlikely((__pyx_t_13 < 0))) __PYX_ERR(0, 254, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_13) { + + } else { + + __pyx_t_3 = __pyx_t_13; + + goto __pyx_L10_bool_binop_done; + } + __pyx_t_11 = fabs(__pyx_v_dj); + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_11); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 254, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + __pyx_t_13 = __Pyx_PyObject_CompareBoolGt_float_object(__pyx_t_5, __pyx_v_tolerance, Py_GT); if (unlikely((__pyx_t_13 < 0))) __PYX_ERR(0, 254, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + __pyx_t_3 = __pyx_t_13; + + __pyx_L10_bool_binop_done:; + if (__pyx_t_3) { + + + /* "fontTools/varLib/iup.py":255 + * if c1 == c2: + * if abs(d1 - d2) > tolerance and abs(dj) > tolerance: + * force = True # <<<<<<<<<<<<<< + * + * # If coordinate for current point is between coordinate of adjacent +*/ + __pyx_v_force = 1; + + /* "fontTools/varLib/iup.py":254 + * # This test has to be before the next one. + * if c1 == c2: + * if abs(d1 - d2) > tolerance and abs(dj) > tolerance: # <<<<<<<<<<<<<< + * force = True + * +*/ + } + + /* "fontTools/varLib/iup.py":253 + * # + * # This test has to be before the next one. + * if c1 == c2: # <<<<<<<<<<<<<< + * if abs(d1 - d2) > tolerance and abs(dj) > tolerance: + * force = True +*/ + goto __pyx_L8; + } + + /* "fontTools/varLib/iup.py":262 + * # allowance), then there is no way that current point can be IUP-ed. + * # Mark it forced. + * elif c1 <= cj <= c2: # and c1 != c2 # <<<<<<<<<<<<<< + * if not (min(d1, d2) - tolerance <= dj <= max(d1, d2) + tolerance): + * force = True +*/ + __pyx_t_3 = (__pyx_v_c1 <= __pyx_v_cj); + if (__pyx_t_3) { + __pyx_t_3 = (__pyx_v_cj <= __pyx_v_c2); + } + if (__pyx_t_3) { + + + /* "fontTools/varLib/iup.py":263 + * # Mark it forced. + * elif c1 <= cj <= c2: # and c1 != c2 + * if not (min(d1, d2) - tolerance <= dj <= max(d1, d2) + tolerance): # <<<<<<<<<<<<<< + * force = True + * +*/ + + __pyx_t_11 = __pyx_v_d2; + + __pyx_t_12 = __pyx_v_d1; + __pyx_t_3 = (__pyx_t_11 < __pyx_t_12); + + if (__pyx_t_3) { + + __pyx_t_14 = __pyx_t_11; + } else { + + __pyx_t_14 = __pyx_t_12; + } + + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_14); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 263, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + __pyx_t_4 = __Pyx_PyNumber_Subtract_float_object(__pyx_t_5, __pyx_v_tolerance); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 263, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyFloat_FromDouble(__pyx_v_dj); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 263, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_CompareBoolLe_object_float(__pyx_t_4, __pyx_t_5, Py_LE); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 263, __pyx_L1_error) + if (__pyx_t_3) { + + __pyx_t_14 = __pyx_v_d2; + + __pyx_t_11 = __pyx_v_d1; + __pyx_t_13 = (__pyx_t_14 > __pyx_t_11); + + if (__pyx_t_13) { + + __pyx_t_12 = __pyx_t_14; + } else { + + __pyx_t_12 = __pyx_t_11; + } + + __pyx_t_15 = PyFloat_FromDouble(__pyx_t_12); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 263, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + + __pyx_t_16 = __Pyx_PyNumber_Add_float_object(__pyx_t_15, __pyx_v_tolerance); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 263, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_16); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_3 = __Pyx_PyObject_CompareBoolLe_float_object(__pyx_t_5, __pyx_t_16, Py_LE); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 263, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_13 = (!__pyx_t_3); + + + if (__pyx_t_13) { + + + /* "fontTools/varLib/iup.py":264 + * elif c1 <= cj <= c2: # and c1 != c2 + * if not (min(d1, d2) - tolerance <= dj <= max(d1, d2) + tolerance): + * force = True # <<<<<<<<<<<<<< + * + * # Otherwise, the delta should either match the closest, or have the +*/ + __pyx_v_force = 1; + + /* "fontTools/varLib/iup.py":263 + * # Mark it forced. + * elif c1 <= cj <= c2: # and c1 != c2 + * if not (min(d1, d2) - tolerance <= dj <= max(d1, d2) + tolerance): # <<<<<<<<<<<<<< + * force = True + * +*/ + } + + /* "fontTools/varLib/iup.py":262 + * # allowance), then there is no way that current point can be IUP-ed. + * # Mark it forced. + * elif c1 <= cj <= c2: # and c1 != c2 # <<<<<<<<<<<<<< + * if not (min(d1, d2) - tolerance <= dj <= max(d1, d2) + tolerance): + * force = True +*/ + goto __pyx_L8; + } + + /* "fontTools/varLib/iup.py":269 + * # same sign as the interpolation of the two deltas. + * else: # cj < c1 or c2 < cj + * if d1 != d2: # <<<<<<<<<<<<<< + * if cj < c1: + * if ( +*/ + /*else*/ { + __pyx_t_13 = (__pyx_v_d1 != __pyx_v_d2); + + if (__pyx_t_13) { + + + /* "fontTools/varLib/iup.py":270 + * else: # cj < c1 or c2 < cj + * if d1 != d2: + * if cj < c1: # <<<<<<<<<<<<<< + * if ( + * abs(dj) > tolerance +*/ + __pyx_t_13 = (__pyx_v_cj < __pyx_v_c1); + + if (__pyx_t_13) { + + + /* "fontTools/varLib/iup.py":272 + * if cj < c1: + * if ( + * abs(dj) > tolerance # <<<<<<<<<<<<<< + * and abs(dj - d1) > tolerance + * and ((dj - tolerance < d1) != (d1 < d2)) +*/ + __pyx_t_12 = fabs(__pyx_v_dj); + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_12); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 272, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + __pyx_t_3 = __Pyx_PyObject_CompareBoolGt_float_object(__pyx_t_5, __pyx_v_tolerance, Py_GT); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 272, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_3) { + + } else { + + __pyx_t_13 = __pyx_t_3; + + goto __pyx_L16_bool_binop_done; + } + + /* "fontTools/varLib/iup.py":273 + * if ( + * abs(dj) > tolerance + * and abs(dj - d1) > tolerance # <<<<<<<<<<<<<< + * and ((dj - tolerance < d1) != (d1 < d2)) + * ): +*/ + __pyx_t_12 = fabs((__pyx_v_dj - __pyx_v_d1)); + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_12); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 273, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + __pyx_t_3 = __Pyx_PyObject_CompareBoolGt_float_object(__pyx_t_5, __pyx_v_tolerance, Py_GT); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 273, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_3) { + + } else { + + __pyx_t_13 = __pyx_t_3; + + goto __pyx_L16_bool_binop_done; + } + + /* "fontTools/varLib/iup.py":274 + * abs(dj) > tolerance + * and abs(dj - d1) > tolerance + * and ((dj - tolerance < d1) != (d1 < d2)) # <<<<<<<<<<<<<< + * ): + * force = True +*/ + __pyx_t_5 = PyFloat_FromDouble(__pyx_v_dj); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 274, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyNumber_Subtract_float_object(__pyx_t_5, __pyx_v_tolerance); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 274, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyFloat_FromDouble(__pyx_v_d1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 274, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_16 = __Pyx_PyObject_CompareLt_object_float(__pyx_t_4, __pyx_t_5, Py_LT); __Pyx_XGOTREF(__pyx_t_16); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 274, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyBool_FromLong((__pyx_v_d1 < __pyx_v_d2)); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 274, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_RichCompareBool(__pyx_t_16, __pyx_t_5, Py_NE); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 274, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + __pyx_t_13 = __pyx_t_3; + + __pyx_L16_bool_binop_done:; + + /* "fontTools/varLib/iup.py":271 + * if d1 != d2: + * if cj < c1: + * if ( # <<<<<<<<<<<<<< + * abs(dj) > tolerance + * and abs(dj - d1) > tolerance +*/ + if (__pyx_t_13) { + + + /* "fontTools/varLib/iup.py":276 + * and ((dj - tolerance < d1) != (d1 < d2)) + * ): + * force = True # <<<<<<<<<<<<<< + * else: # c2 < cj + * if ( +*/ + __pyx_v_force = 1; + + /* "fontTools/varLib/iup.py":271 + * if d1 != d2: + * if cj < c1: + * if ( # <<<<<<<<<<<<<< + * abs(dj) > tolerance + * and abs(dj - d1) > tolerance +*/ + } + + /* "fontTools/varLib/iup.py":270 + * else: # cj < c1 or c2 < cj + * if d1 != d2: + * if cj < c1: # <<<<<<<<<<<<<< + * if ( + * abs(dj) > tolerance +*/ + goto __pyx_L14; + } + + /* "fontTools/varLib/iup.py":278 + * force = True + * else: # c2 < cj + * if ( # <<<<<<<<<<<<<< + * abs(dj) > tolerance + * and abs(dj - d2) > tolerance +*/ + /*else*/ { + + /* "fontTools/varLib/iup.py":279 + * else: # c2 < cj + * if ( + * abs(dj) > tolerance # <<<<<<<<<<<<<< + * and abs(dj - d2) > tolerance + * and ((d2 < dj + tolerance) != (d1 < d2)) +*/ + __pyx_t_12 = fabs(__pyx_v_dj); + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_12); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 279, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + __pyx_t_3 = __Pyx_PyObject_CompareBoolGt_float_object(__pyx_t_5, __pyx_v_tolerance, Py_GT); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 279, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_3) { + + } else { + + __pyx_t_13 = __pyx_t_3; + + goto __pyx_L20_bool_binop_done; + } + + /* "fontTools/varLib/iup.py":280 + * if ( + * abs(dj) > tolerance + * and abs(dj - d2) > tolerance # <<<<<<<<<<<<<< + * and ((d2 < dj + tolerance) != (d1 < d2)) + * ): +*/ + __pyx_t_12 = fabs((__pyx_v_dj - __pyx_v_d2)); + __pyx_t_5 = PyFloat_FromDouble(__pyx_t_12); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 280, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + __pyx_t_3 = __Pyx_PyObject_CompareBoolGt_float_object(__pyx_t_5, __pyx_v_tolerance, Py_GT); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 280, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_3) { + + } else { + + __pyx_t_13 = __pyx_t_3; + + goto __pyx_L20_bool_binop_done; + } + + /* "fontTools/varLib/iup.py":281 + * abs(dj) > tolerance + * and abs(dj - d2) > tolerance + * and ((d2 < dj + tolerance) != (d1 < d2)) # <<<<<<<<<<<<<< + * ): + * force = True +*/ + __pyx_t_5 = PyFloat_FromDouble(__pyx_v_d2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 281, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_16 = PyFloat_FromDouble(__pyx_v_dj); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 281, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_16); + __pyx_t_4 = __Pyx_PyNumber_Add_float_object(__pyx_t_16, __pyx_v_tolerance); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 281, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + __pyx_t_16 = __Pyx_PyObject_CompareLt_float_object(__pyx_t_5, __pyx_t_4, Py_LT); __Pyx_XGOTREF(__pyx_t_16); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 281, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyBool_FromLong((__pyx_v_d1 < __pyx_v_d2)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 281, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_RichCompareBool(__pyx_t_16, __pyx_t_4, Py_NE); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 281, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + __pyx_t_13 = __pyx_t_3; + + __pyx_L20_bool_binop_done:; + + /* "fontTools/varLib/iup.py":278 + * force = True + * else: # c2 < cj + * if ( # <<<<<<<<<<<<<< + * abs(dj) > tolerance + * and abs(dj - d2) > tolerance +*/ + if (__pyx_t_13) { + + + /* "fontTools/varLib/iup.py":283 + * and ((d2 < dj + tolerance) != (d1 < d2)) + * ): + * force = True # <<<<<<<<<<<<<< + * + * if force: +*/ + __pyx_v_force = 1; + + /* "fontTools/varLib/iup.py":278 + * force = True + * else: # c2 < cj + * if ( # <<<<<<<<<<<<<< + * abs(dj) > tolerance + * and abs(dj - d2) > tolerance +*/ + } + } + __pyx_L14:; + + /* "fontTools/varLib/iup.py":269 + * # same sign as the interpolation of the two deltas. + * else: # cj < c1 or c2 < cj + * if d1 != d2: # <<<<<<<<<<<<<< + * if cj < c1: + * if ( +*/ + } + } + __pyx_L8:; + + /* "fontTools/varLib/iup.py":285 + * force = True + * + * if force: # <<<<<<<<<<<<<< + * forced.add(i) + * break +*/ + __pyx_t_13 = (__pyx_v_force != 0); + + if (__pyx_t_13) { + + + /* "fontTools/varLib/iup.py":286 + * + * if force: + * forced.add(i) # <<<<<<<<<<<<<< + * break + * +*/ + __pyx_t_17 = PySet_Add(__pyx_v_forced, __pyx_v_i); if (unlikely(__pyx_t_17 == ((int)-1))) __PYX_ERR(0, 286, __pyx_L1_error) + + + /* "fontTools/varLib/iup.py":287 + * if force: + * forced.add(i) + * break # <<<<<<<<<<<<<< + * + * return forced +*/ + goto __pyx_L6_break; + + /* "fontTools/varLib/iup.py":285 + * force = True + * + * if force: # <<<<<<<<<<<<<< + * forced.add(i) + * break +*/ + } + + /* "fontTools/varLib/iup.py":231 + * nd, nc = deltas[i - n + 1], coords[i - n + 1] + * + * for j in (0, 1): # For X and for Y # <<<<<<<<<<<<<< + * cj = c[j] + * dj = d[j] +*/ + } + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L24_for_end; + __pyx_L6_break:; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L24_for_end; + __pyx_L24_for_end:; + + /* "fontTools/varLib/iup.py":226 + * forced = set() + * # Track "last" and "next" points on the contour as we sweep. + * for i in range(len(deltas) - 1, -1, -1): # <<<<<<<<<<<<<< + * ld, lc = deltas[i - 1], coords[i - 1] + * d, c = deltas[i], coords[i] +*/ + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":289 + * break + * + * return forced # <<<<<<<<<<<<<< + * + * +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(__pyx_v_forced); + __pyx_r = __pyx_v_forced; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":201 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * cj=cython.double, + * dj=cython.double, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_XDECREF(__pyx_t_16); + __Pyx_AddTraceback("fontTools.varLib.iup._iup_contour_bound_forced_set", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + + + + + + + + __Pyx_XDECREF(__pyx_v_forced); + __Pyx_XDECREF(__pyx_v_n); + __Pyx_XDECREF(__pyx_v_i); + __Pyx_XDECREF(__pyx_v_ld); + __Pyx_XDECREF(__pyx_v_lc); + __Pyx_XDECREF(__pyx_v_d); + __Pyx_XDECREF(__pyx_v_c); + __Pyx_XDECREF(__pyx_v_nd); + __Pyx_XDECREF(__pyx_v_nc); + + + + + + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/varLib/iup.py":292 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * i=cython.int, + * j=cython.int, +*/ + +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_16__defaults__(CYTHON_UNUSED PyObject *__pyx_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__defaults__", 0); + + /* "fontTools/varLib/iup.py":305 + * coords: _PointSegment, + * forced=set(), + * tolerance: Real = 0, # <<<<<<<<<<<<<< + * lookback: Integral = None, + * ): +*/ + __pyx_t_1 = PyFloat_FromDouble(((double)0.0)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 305, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + + /* "fontTools/varLib/iup.py":292 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * i=cython.int, + * j=cython.int, +*/ + __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 292, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__Pyx_CyFunction_Defaults(struct __pyx_defaults, __pyx_self)->arg0); + __Pyx_GIVEREF(__Pyx_CyFunction_Defaults(struct __pyx_defaults, __pyx_self)->arg0); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 0, __Pyx_CyFunction_Defaults(struct __pyx_defaults, __pyx_self)->arg0) != (0)) __PYX_ERR(0, 292, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1) != (0)) __PYX_ERR(0, 292, __pyx_L1_error); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 2, Py_None) != (0)) __PYX_ERR(0, 292, __pyx_L1_error); + __pyx_t_1 = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 292, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_2); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2) != (0)) __PYX_ERR(0, 292, __pyx_L1_error); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, Py_None) != (0)) __PYX_ERR(0, 292, __pyx_L1_error); + __pyx_t_2 = 0; + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __pyx_r = __pyx_t_1; + } + __Pyx_XDECREF(__pyx_temp); + } + __pyx_t_1 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("fontTools.varLib.iup.__defaults__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_7_iup_contour_optimize_dp(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_6varLib_3iup_6_iup_contour_optimize_dp, "_iup_contour_optimize_dp(deltas: _DeltaSegment, coords: _PointSegment, set forced=set(), double tolerance: Real = 0, lookback: Integral = None)\n\nStraightforward Dynamic-Programming. For each index i, find least-costly encoding of\npoints 0 to i where i is explicitly encoded. We find this by considering all previous\nexplicit points j and check whether interpolation can fill points between j and i.\n\nNote that solution always encodes last point explicitly. Higher-level is responsible\nfor removing that restriction.\n\nAs major speedup, we stop looking further whenever we see a \"forced\" point."); +static PyMethodDef __pyx_mdef_9fontTools_6varLib_3iup_7_iup_contour_optimize_dp = {"_iup_contour_optimize_dp", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_6varLib_3iup_7_iup_contour_optimize_dp, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_6varLib_3iup_6_iup_contour_optimize_dp}; +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_7_iup_contour_optimize_dp(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_deltas = 0; + PyObject *__pyx_v_coords = 0; + PyObject *__pyx_v_forced = 0; + double __pyx_v_tolerance; + PyObject *__pyx_v_lookback = 0; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[5] = {0,0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_iup_contour_optimize_dp (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_deltas,&__pyx_mstate_global->__pyx_n_u_coords,&__pyx_mstate_global->__pyx_n_u_forced,&__pyx_mstate_global->__pyx_n_u_tolerance,&__pyx_mstate_global->__pyx_n_u_lookback,0}; + struct __pyx_defaults *__pyx_dynamic_args = __Pyx_CyFunction_Defaults(struct __pyx_defaults, __pyx_self); + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 292, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 292, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 292, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 292, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 292, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 292, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "_iup_contour_optimize_dp", 0) < (0)) __PYX_ERR(0, 292, __pyx_L3_error) + if (!values[2]) values[2] = __Pyx_NewRef(__pyx_dynamic_args->arg0); + + /* "fontTools/varLib/iup.py":306 + * forced=set(), + * tolerance: Real = 0, + * lookback: Integral = None, # <<<<<<<<<<<<<< + * ): + * """Straightforward Dynamic-Programming. For each index i, find least-costly encoding of +*/ + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)Py_None)); + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("_iup_contour_optimize_dp", 0, 2, 5, i); __PYX_ERR(0, 292, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 292, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 292, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 292, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 292, __pyx_L3_error) + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 292, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + if (!values[2]) values[2] = __Pyx_NewRef(__pyx_dynamic_args->arg0); + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)Py_None)); + } + __pyx_v_deltas = values[0]; + __pyx_v_coords = values[1]; + __pyx_v_forced = ((PyObject*)values[2]); + if (values[3]) { + __pyx_v_tolerance = __Pyx_PyFloat_AsDouble(values[3]); if (unlikely((__pyx_v_tolerance == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 305, __pyx_L3_error) + } else { + __pyx_v_tolerance = ((double)((double)0.0)); + } + __pyx_v_lookback = values[4]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_iup_contour_optimize_dp", 0, 2, 5, __pyx_nargs); __PYX_ERR(0, 292, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.varLib.iup._iup_contour_optimize_dp", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_forced), (&PySet_Type), 1, "forced", 1))) __PYX_ERR(0, 304, __pyx_L1_error) + __pyx_r = __pyx_pf_9fontTools_6varLib_3iup_6_iup_contour_optimize_dp(__pyx_self, __pyx_v_deltas, __pyx_v_coords, __pyx_v_forced, __pyx_v_tolerance, __pyx_v_lookback); + + /* "fontTools/varLib/iup.py":292 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * i=cython.int, + * j=cython.int, +*/ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_6_iup_contour_optimize_dp(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords, PyObject *__pyx_v_forced, double __pyx_v_tolerance, PyObject *__pyx_v_lookback) { + int __pyx_v_i; + int __pyx_v_j; + double __pyx_v_best_cost; + double __pyx_v_cost; + Py_ssize_t __pyx_v_n; + PyObject *__pyx_v_costs = NULL; + PyObject *__pyx_v_chain = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + double __pyx_t_8; + long __pyx_t_9; + Py_ssize_t __pyx_t_10; + Py_ssize_t __pyx_t_11; + int __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_iup_contour_optimize_dp", 0); + __Pyx_INCREF(__pyx_v_lookback); + + /* "fontTools/varLib/iup.py":317 + * As major speedup, we stop looking further whenever we see a "forced" point.""" + * + * n = len(deltas) # <<<<<<<<<<<<<< + * if lookback is None: + * lookback = n +*/ + __pyx_t_1 = PyObject_Length(__pyx_v_deltas); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 317, __pyx_L1_error) + __pyx_v_n = __pyx_t_1; + + /* "fontTools/varLib/iup.py":318 + * + * n = len(deltas) + * if lookback is None: # <<<<<<<<<<<<<< + * lookback = n + * lookback = min(lookback, MAX_LOOKBACK) +*/ + __pyx_t_2 = (__pyx_v_lookback == Py_None); + if (__pyx_t_2) { + + + /* "fontTools/varLib/iup.py":319 + * n = len(deltas) + * if lookback is None: + * lookback = n # <<<<<<<<<<<<<< + * lookback = min(lookback, MAX_LOOKBACK) + * costs = {-1: 0} +*/ + __pyx_t_3 = PyLong_FromSsize_t(__pyx_v_n); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 319, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_lookback, __pyx_t_3); + __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":318 + * + * n = len(deltas) + * if lookback is None: # <<<<<<<<<<<<<< + * lookback = n + * lookback = min(lookback, MAX_LOOKBACK) +*/ + } + + /* "fontTools/varLib/iup.py":320 + * if lookback is None: + * lookback = n + * lookback = min(lookback, MAX_LOOKBACK) # <<<<<<<<<<<<<< + * costs = {-1: 0} + * chain = {-1: None} +*/ + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_MAX_LOOKBACK); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 320, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_lookback); + __pyx_t_4 = __pyx_v_lookback; + __pyx_t_2 = __Pyx_PyObject_CompareBoolLt_object_object(__pyx_t_3, __pyx_t_4, Py_LT); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 320, __pyx_L1_error) + if (__pyx_t_2) { + __Pyx_INCREF(__pyx_t_3); + __pyx_t_5 = __pyx_t_3; + } else { + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = __pyx_t_4; + } + + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __pyx_t_5; + __Pyx_INCREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF_SET(__pyx_v_lookback, __pyx_t_3); + __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":321 + * lookback = n + * lookback = min(lookback, MAX_LOOKBACK) + * costs = {-1: 0} # <<<<<<<<<<<<<< + * chain = {-1: None} + * for i in range(0, n): +*/ + __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 321, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_mstate_global->__pyx_int_neg_1, __pyx_mstate_global->__pyx_int_0) < (0)) __PYX_ERR(0, 321, __pyx_L1_error) + __pyx_v_costs = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":322 + * lookback = min(lookback, MAX_LOOKBACK) + * costs = {-1: 0} + * chain = {-1: None} # <<<<<<<<<<<<<< + * for i in range(0, n): + * best_cost = costs[i - 1] + 1 +*/ + __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 322, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_mstate_global->__pyx_int_neg_1, Py_None) < (0)) __PYX_ERR(0, 322, __pyx_L1_error) + __pyx_v_chain = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":323 + * costs = {-1: 0} + * chain = {-1: None} + * for i in range(0, n): # <<<<<<<<<<<<<< + * best_cost = costs[i - 1] + 1 + * +*/ + + __pyx_t_1 = __pyx_v_n; + __pyx_t_6 = __pyx_t_1; + + for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { + __pyx_v_i = __pyx_t_7; + + /* "fontTools/varLib/iup.py":324 + * chain = {-1: None} + * for i in range(0, n): + * best_cost = costs[i - 1] + 1 # <<<<<<<<<<<<<< + * + * costs[i] = best_cost +*/ + __pyx_t_3 = __Pyx_PyLong_From_long((__pyx_v_i - 1)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 324, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyDict_GetItem(__pyx_v_costs, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 324, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyLong_AddObjC(__pyx_t_5, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 324, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_8 = __Pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_8 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 324, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_best_cost = __pyx_t_8; + + /* "fontTools/varLib/iup.py":326 + * best_cost = costs[i - 1] + 1 + * + * costs[i] = best_cost # <<<<<<<<<<<<<< + * chain[i] = i - 1 + * +*/ + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_best_cost); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 326, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyLong_From_int(__pyx_v_i); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 326, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (unlikely((PyDict_SetItem(__pyx_v_costs, __pyx_t_5, __pyx_t_3) < 0))) __PYX_ERR(0, 326, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":327 + * + * costs[i] = best_cost + * chain[i] = i - 1 # <<<<<<<<<<<<<< + * + * if i - 1 in forced: +*/ + __pyx_t_3 = __Pyx_PyLong_From_long((__pyx_v_i - 1)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyLong_From_int(__pyx_v_i); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (unlikely((PyDict_SetItem(__pyx_v_chain, __pyx_t_5, __pyx_t_3) < 0))) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":329 + * chain[i] = i - 1 + * + * if i - 1 in forced: # <<<<<<<<<<<<<< + * continue + * +*/ + __pyx_t_3 = __Pyx_PyLong_From_long((__pyx_v_i - 1)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 329, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (unlikely(__pyx_v_forced == Py_None)) { + PyErr_SetString(PyExc_TypeError, "\047NoneType\047 object is not iterable"); + __PYX_ERR(0, 329, __pyx_L1_error) + } + __pyx_t_2 = (__Pyx_PySet_ContainsTF(__pyx_t_3, __pyx_v_forced, Py_EQ)); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 329, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_2) { + + + /* "fontTools/varLib/iup.py":330 + * + * if i - 1 in forced: + * continue # <<<<<<<<<<<<<< + * + * for j in range(i - 2, max(i - lookback, -2), -1): +*/ + goto __pyx_L4_continue; + + /* "fontTools/varLib/iup.py":329 + * chain[i] = i - 1 + * + * if i - 1 in forced: # <<<<<<<<<<<<<< + * continue + * +*/ + } + + /* "fontTools/varLib/iup.py":332 + * continue + * + * for j in range(i - 2, max(i - lookback, -2), -1): # <<<<<<<<<<<<<< + * cost = costs[j] + 1 + * +*/ + + __pyx_t_9 = -2L; + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_i); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 332, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyNumber_Subtract_int_object(__pyx_t_3, __pyx_v_lookback); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 332, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyLong_From_long(__pyx_t_9); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 332, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_CompareBoolGt_int_object(__pyx_t_4, __pyx_t_5, Py_GT); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 332, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_2) { + __pyx_t_4 = __Pyx_PyLong_From_long(__pyx_t_9); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 332, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __pyx_t_4; + __pyx_t_4 = 0; + } else { + __Pyx_INCREF(__pyx_t_5); + __pyx_t_3 = __pyx_t_5; + } + + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 332, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_11 = __pyx_t_10; + + for (__pyx_t_12 = (__pyx_v_i - 2); __pyx_t_12 > __pyx_t_11; __pyx_t_12-=1) { + __pyx_v_j = __pyx_t_12; + + /* "fontTools/varLib/iup.py":333 + * + * for j in range(i - 2, max(i - lookback, -2), -1): + * cost = costs[j] + 1 # <<<<<<<<<<<<<< + * + * if cost < best_cost and can_iup_in_between(deltas, coords, j, i, tolerance): +*/ + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_j); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 333, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyDict_GetItem(__pyx_v_costs, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 333, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyLong_AddObjC(__pyx_t_5, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 333, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_8 = __Pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely((__pyx_t_8 == (double)-1) && PyErr_Occurred())) __PYX_ERR(0, 333, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_cost = __pyx_t_8; + + /* "fontTools/varLib/iup.py":335 + * cost = costs[j] + 1 + * + * if cost < best_cost and can_iup_in_between(deltas, coords, j, i, tolerance): # <<<<<<<<<<<<<< + * costs[i] = best_cost = cost + * chain[i] = j +*/ + __pyx_t_13 = (__pyx_v_cost < __pyx_v_best_cost); + + if (__pyx_t_13) { + + } else { + + __pyx_t_2 = __pyx_t_13; + + goto __pyx_L10_bool_binop_done; + } + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_tolerance); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 335, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_14 = __pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(__pyx_v_deltas, __pyx_v_coords, __pyx_v_j, __pyx_v_i, __pyx_t_3); if (unlikely(__pyx_t_14 == ((int)-1) && PyErr_Occurred())) __PYX_ERR(0, 335, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_13 = (__pyx_t_14 != 0); + + + + __pyx_t_2 = __pyx_t_13; + + __pyx_L10_bool_binop_done:; + if (__pyx_t_2) { + + + /* "fontTools/varLib/iup.py":336 + * + * if cost < best_cost and can_iup_in_between(deltas, coords, j, i, tolerance): + * costs[i] = best_cost = cost # <<<<<<<<<<<<<< + * chain[i] = j + * +*/ + __pyx_t_3 = PyFloat_FromDouble(__pyx_v_cost); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 336, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyLong_From_int(__pyx_v_i); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 336, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (unlikely((PyDict_SetItem(__pyx_v_costs, __pyx_t_5, __pyx_t_3) < 0))) __PYX_ERR(0, 336, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_best_cost = __pyx_v_cost; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":337 + * if cost < best_cost and can_iup_in_between(deltas, coords, j, i, tolerance): + * costs[i] = best_cost = cost + * chain[i] = j # <<<<<<<<<<<<<< + * + * if j in forced: +*/ + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_j); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 337, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyLong_From_int(__pyx_v_i); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 337, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (unlikely((PyDict_SetItem(__pyx_v_chain, __pyx_t_5, __pyx_t_3) < 0))) __PYX_ERR(0, 337, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":335 + * cost = costs[j] + 1 + * + * if cost < best_cost and can_iup_in_between(deltas, coords, j, i, tolerance): # <<<<<<<<<<<<<< + * costs[i] = best_cost = cost + * chain[i] = j +*/ + } + + /* "fontTools/varLib/iup.py":339 + * chain[i] = j + * + * if j in forced: # <<<<<<<<<<<<<< + * break + * +*/ + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_j); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 339, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (unlikely(__pyx_v_forced == Py_None)) { + PyErr_SetString(PyExc_TypeError, "\047NoneType\047 object is not iterable"); + __PYX_ERR(0, 339, __pyx_L1_error) + } + __pyx_t_2 = (__Pyx_PySet_ContainsTF(__pyx_t_3, __pyx_v_forced, Py_EQ)); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 339, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_2) { + + + /* "fontTools/varLib/iup.py":340 + * + * if j in forced: + * break # <<<<<<<<<<<<<< + * + * return chain, costs +*/ + goto __pyx_L8_break; + + /* "fontTools/varLib/iup.py":339 + * chain[i] = j + * + * if j in forced: # <<<<<<<<<<<<<< + * break + * +*/ + } + } + __pyx_L8_break:; + + + __pyx_L4_continue:; + } + + + /* "fontTools/varLib/iup.py":342 + * break + * + * return chain, costs # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 342, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_chain); + __Pyx_GIVEREF(__pyx_v_chain); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_chain) != (0)) __PYX_ERR(0, 342, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_costs); + __Pyx_GIVEREF(__pyx_v_costs); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_costs) != (0)) __PYX_ERR(0, 342, __pyx_L1_error); + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __pyx_r = __pyx_t_3; + } + __Pyx_XDECREF(__pyx_temp); + } + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":292 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * i=cython.int, + * j=cython.int, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("fontTools.varLib.iup._iup_contour_optimize_dp", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + + + + + + __Pyx_XDECREF(__pyx_v_costs); + __Pyx_XDECREF(__pyx_v_chain); + __Pyx_XDECREF(__pyx_v_lookback); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/varLib/iup.py":345 + * + * + * def _rot_list(l: list, k: int): # <<<<<<<<<<<<<< + * """Rotate list by k items forward. Ie. item at position 0 will be + * at position k in returned list. Negative k is allowed.""" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_9_rot_list(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_6varLib_3iup_8_rot_list, "_rot_list(list l: list, int k: int)\n\nRotate list by k items forward. Ie. item at position 0 will be\nat position k in returned list. Negative k is allowed."); +static PyMethodDef __pyx_mdef_9fontTools_6varLib_3iup_9_rot_list = {"_rot_list", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_6varLib_3iup_9_rot_list, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_6varLib_3iup_8_rot_list}; +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_9_rot_list(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_l = 0; + PyObject *__pyx_v_k = 0; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_rot_list (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_l,&__pyx_mstate_global->__pyx_n_u_k,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 345, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 345, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 345, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "_rot_list", 0) < (0)) __PYX_ERR(0, 345, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("_rot_list", 1, 2, 2, i); __PYX_ERR(0, 345, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 2)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 345, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 345, __pyx_L3_error) + } + __pyx_v_l = ((PyObject*)values[0]); + if (__Pyx_PyInt_FromNumber(&values[1], "k", 0) < (0)) __PYX_ERR(0, 345, __pyx_L3_error) + __pyx_v_k = ((PyObject*)values[1]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_rot_list", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 345, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.varLib.iup._rot_list", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_l), (&PyList_Type), 0, "l", 2))) __PYX_ERR(0, 345, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_k), (&PyLong_Type), 0, "k", 2))) __PYX_ERR(0, 345, __pyx_L1_error) + __pyx_r = __pyx_pf_9fontTools_6varLib_3iup_8_rot_list(__pyx_self, __pyx_v_l, __pyx_v_k); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_8_rot_list(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_l, PyObject *__pyx_v_k) { + PyObject *__pyx_v_n = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_rot_list", 0); + __Pyx_INCREF(__pyx_v_k); + + /* "fontTools/varLib/iup.py":348 + * """Rotate list by k items forward. Ie. item at position 0 will be + * at position k in returned list. Negative k is allowed.""" + * n = len(l) # <<<<<<<<<<<<<< + * k %= n + * if not k: +*/ + __pyx_t_1 = __Pyx_PyList_GET_SIZE(__pyx_v_l); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 348, __pyx_L1_error) + __pyx_t_2 = PyLong_FromSsize_t(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 348, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + + if (__Pyx_PyInt_FromNumber(&__pyx_t_2, NULL, 0) < (0)) __PYX_ERR(0, 348, __pyx_L1_error) + __pyx_v_n = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "fontTools/varLib/iup.py":349 + * at position k in returned list. Negative k is allowed.""" + * n = len(l) + * k %= n # <<<<<<<<<<<<<< + * if not k: + * return l +*/ + __pyx_t_2 = PyNumber_InPlaceRemainder(__pyx_v_k, __pyx_v_n); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 349, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF_SET(__pyx_v_k, ((PyObject*)__pyx_t_2)); + __pyx_t_2 = 0; + + /* "fontTools/varLib/iup.py":350 + * n = len(l) + * k %= n + * if not k: # <<<<<<<<<<<<<< + * return l + * return l[n - k :] + l[: n - k] +*/ + { + Py_ssize_t __pyx_temp = __Pyx_PyLong_IsNonZero(__pyx_v_k); + if (unlikely(((!CYTHON_USE_PYLONG_INTERNALS) && __pyx_temp < 0))) __PYX_ERR(0, 350, __pyx_L1_error) + __pyx_t_3 = (__pyx_temp != 0); + } + + __pyx_t_4 = (!__pyx_t_3); + + + if (__pyx_t_4) { + + + /* "fontTools/varLib/iup.py":351 + * k %= n + * if not k: + * return l # <<<<<<<<<<<<<< + * return l[n - k :] + l[: n - k] + * +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(__pyx_v_l); + __pyx_r = __pyx_v_l; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":350 + * n = len(l) + * k %= n + * if not k: # <<<<<<<<<<<<<< + * return l + * return l[n - k :] + l[: n - k] +*/ + } + + /* "fontTools/varLib/iup.py":352 + * if not k: + * return l + * return l[n - k :] + l[: n - k] # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_2 = __Pyx_PyNumber_Subtract_int_int(__pyx_v_n, __pyx_v_k); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 352, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = (__pyx_t_2 == ((PyObject*)Py_None)); + if (__pyx_t_4) { + + __pyx_t_1 = 0; + } else { + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_2); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 352, __pyx_L1_error) + __pyx_t_1 = __pyx_t_5; + } + + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyList_GetSlice(__pyx_v_l, __pyx_t_1, PY_SSIZE_T_MAX); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 352, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + + __pyx_t_6 = __Pyx_PyNumber_Subtract_int_int(__pyx_v_n, __pyx_v_k); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 352, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = (__pyx_t_6 == ((PyObject*)Py_None)); + if (__pyx_t_4) { + + __pyx_t_1 = PY_SSIZE_T_MAX; + } else { + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_6); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 352, __pyx_L1_error) + __pyx_t_1 = __pyx_t_5; + } + + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyList_GetSlice(__pyx_v_l, 0, __pyx_t_1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 352, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + + __pyx_t_7 = PyNumber_Add(__pyx_t_2, __pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 352, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __pyx_r = __pyx_t_7; + } + __Pyx_XDECREF(__pyx_temp); + } + __pyx_t_7 = 0; + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":345 + * + * + * def _rot_list(l: list, k: int): # <<<<<<<<<<<<<< + * """Rotate list by k items forward. Ie. item at position 0 will be + * at position k in returned list. Negative k is allowed.""" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("fontTools.varLib.iup._rot_list", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_n); + __Pyx_XDECREF(__pyx_v_k); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/varLib/iup.py":355 + * + * + * def _rot_set(s: set, k: int, n: int): # <<<<<<<<<<<<<< + * k %= n + * if not k: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_11_rot_set(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_6varLib_3iup_10_rot_set, "_rot_set(set s: set, int k: int, int n: int)"); +static PyMethodDef __pyx_mdef_9fontTools_6varLib_3iup_11_rot_set = {"_rot_set", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_6varLib_3iup_11_rot_set, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_6varLib_3iup_10_rot_set}; +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_11_rot_set(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_s = 0; + PyObject *__pyx_v_k = 0; + PyObject *__pyx_v_n = 0; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_rot_set (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_s,&__pyx_mstate_global->__pyx_n_u_k,&__pyx_mstate_global->__pyx_n_u_n,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 355, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 355, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 355, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 355, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "_rot_set", 0) < (0)) __PYX_ERR(0, 355, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("_rot_set", 1, 3, 3, i); __PYX_ERR(0, 355, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 355, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 355, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 355, __pyx_L3_error) + } + __pyx_v_s = ((PyObject*)values[0]); + if (__Pyx_PyInt_FromNumber(&values[1], "k", 0) < (0)) __PYX_ERR(0, 355, __pyx_L3_error) + __pyx_v_k = ((PyObject*)values[1]); + if (__Pyx_PyInt_FromNumber(&values[2], "n", 0) < (0)) __PYX_ERR(0, 355, __pyx_L3_error) + __pyx_v_n = ((PyObject*)values[2]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_rot_set", 1, 3, 3, __pyx_nargs); __PYX_ERR(0, 355, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.varLib.iup._rot_set", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_s), (&PySet_Type), 0, "s", 2))) __PYX_ERR(0, 355, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_k), (&PyLong_Type), 0, "k", 2))) __PYX_ERR(0, 355, __pyx_L1_error) + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_n), (&PyLong_Type), 0, "n", 2))) __PYX_ERR(0, 355, __pyx_L1_error) + __pyx_r = __pyx_pf_9fontTools_6varLib_3iup_10_rot_set(__pyx_self, __pyx_v_s, __pyx_v_k, __pyx_v_n); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_10_rot_set(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_s, PyObject *__pyx_v_k, PyObject *__pyx_v_n) { + PyObject *__pyx_8genexpr2__pyx_v_v = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + int __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_rot_set", 0); + __Pyx_INCREF(__pyx_v_k); + + /* "fontTools/varLib/iup.py":356 + * + * def _rot_set(s: set, k: int, n: int): + * k %= n # <<<<<<<<<<<<<< + * if not k: + * return s +*/ + __pyx_t_1 = PyNumber_InPlaceRemainder(__pyx_v_k, __pyx_v_n); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 356, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF_SET(__pyx_v_k, ((PyObject*)__pyx_t_1)); + __pyx_t_1 = 0; + + /* "fontTools/varLib/iup.py":357 + * def _rot_set(s: set, k: int, n: int): + * k %= n + * if not k: # <<<<<<<<<<<<<< + * return s + * return {(v + k) % n for v in s} +*/ + { + Py_ssize_t __pyx_temp = __Pyx_PyLong_IsNonZero(__pyx_v_k); + if (unlikely(((!CYTHON_USE_PYLONG_INTERNALS) && __pyx_temp < 0))) __PYX_ERR(0, 357, __pyx_L1_error) + __pyx_t_2 = (__pyx_temp != 0); + } + + __pyx_t_3 = (!__pyx_t_2); + + + if (__pyx_t_3) { + + + /* "fontTools/varLib/iup.py":358 + * k %= n + * if not k: + * return s # <<<<<<<<<<<<<< + * return {(v + k) % n for v in s} + * +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(__pyx_v_s); + __pyx_r = __pyx_v_s; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":357 + * def _rot_set(s: set, k: int, n: int): + * k %= n + * if not k: # <<<<<<<<<<<<<< + * return s + * return {(v + k) % n for v in s} +*/ + } + + /* "fontTools/varLib/iup.py":359 + * if not k: + * return s + * return {(v + k) % n for v in s} # <<<<<<<<<<<<<< + * + * +*/ + { /* enter inner scope */ + __pyx_t_1 = PySet_New(NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 359, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = 0; + __pyx_t_8 = __Pyx_set_iterator(__pyx_v_s, 1, (&__pyx_t_6), (&__pyx_t_7)); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 359, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_4); + __pyx_t_4 = __pyx_t_8; + __pyx_t_8 = 0; + while (1) { + __pyx_t_9 = __Pyx_set_iter_next(__pyx_t_4, __pyx_t_6, &__pyx_t_5, &__pyx_t_8, __pyx_t_7); + if (unlikely(__pyx_t_9 == 0)) break; + if (unlikely(__pyx_t_9 == -1)) __PYX_ERR(0, 359, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XDECREF_SET(__pyx_8genexpr2__pyx_v_v, __pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyNumber_Add_object_int(__pyx_8genexpr2__pyx_v_v, __pyx_v_k); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 359, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_10 = PyNumber_Remainder(__pyx_t_8, __pyx_v_n); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 359, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(PySet_Add(__pyx_t_1, __pyx_t_10))) __PYX_ERR(0, 359, __pyx_L6_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_v); __pyx_8genexpr2__pyx_v_v = 0; + goto __pyx_L9_exit_scope; + __pyx_L6_error:; + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_v); __pyx_8genexpr2__pyx_v_v = 0; + goto __pyx_L1_error; + __pyx_L9_exit_scope:; + } /* exit inner scope */ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __pyx_r = __pyx_t_1; + } + __Pyx_XDECREF(__pyx_temp); + } + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":355 + * + * + * def _rot_set(s: set, k: int, n: int): # <<<<<<<<<<<<<< + * k %= n + * if not k: +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("fontTools.varLib.iup._rot_set", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_v); + __Pyx_XDECREF(__pyx_v_k); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/varLib/iup.py":362 + * + * + * def iup_contour_optimize( # <<<<<<<<<<<<<< + * deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0.0 + * ) -> _DeltaOrNoneSegment: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_13iup_contour_optimize(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_6varLib_3iup_12iup_contour_optimize, "iup_contour_optimize(deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0.0) -> _DeltaOrNoneSegment\n\nFor contour with coordinates `coords`, optimize a set of delta\nvalues `deltas` within error `tolerance`.\n\nReturns delta vector that has most number of None items instead of\nthe input delta."); +static PyMethodDef __pyx_mdef_9fontTools_6varLib_3iup_13iup_contour_optimize = {"iup_contour_optimize", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_6varLib_3iup_13iup_contour_optimize, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_6varLib_3iup_12iup_contour_optimize}; +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_13iup_contour_optimize(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_deltas = 0; + PyObject *__pyx_v_coords = 0; + PyObject *__pyx_v_tolerance = 0; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("iup_contour_optimize (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_deltas,&__pyx_mstate_global->__pyx_n_u_coords,&__pyx_mstate_global->__pyx_n_u_tolerance,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 362, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 362, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 362, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 362, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "iup_contour_optimize", 0) < (0)) __PYX_ERR(0, 362, __pyx_L3_error) + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)((PyObject*)__pyx_mstate_global->__pyx_float_0_0))); + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("iup_contour_optimize", 0, 2, 3, i); __PYX_ERR(0, 362, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 362, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 362, __pyx_L3_error) + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 362, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)((PyObject*)__pyx_mstate_global->__pyx_float_0_0))); + } + __pyx_v_deltas = values[0]; + __pyx_v_coords = values[1]; + __pyx_v_tolerance = values[2]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("iup_contour_optimize", 0, 2, 3, __pyx_nargs); __PYX_ERR(0, 362, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.varLib.iup.iup_contour_optimize", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9fontTools_6varLib_3iup_12iup_contour_optimize(__pyx_self, __pyx_v_deltas, __pyx_v_coords, __pyx_v_tolerance); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static PyObject *__pyx_gb_9fontTools_6varLib_3iup_20iup_contour_optimize_2generator1(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ + +/* "fontTools/varLib/iup.py":377 + * + * # If all are within tolerance distance of 0, encode nothing: + * if all(abs(complex(*p)) <= tolerance for p in deltas): # <<<<<<<<<<<<<< + * return [None] * n + * +*/ + +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_20iup_contour_optimize_genexpr(PyObject *__pyx_self, PyObject *__pyx_genexpr_arg_0) { + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr *__pyx_cur_scope; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("genexpr", 0); + __pyx_cur_scope = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr *)__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(__pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (unlikely(!__pyx_cur_scope)) { + __pyx_cur_scope = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr *)Py_None); + __Pyx_INCREF(Py_None); + __PYX_ERR(0, 377, __pyx_L1_error) + } else { + __Pyx_GOTREF((PyObject *)__pyx_cur_scope); + } + __pyx_cur_scope->__pyx_outer_scope = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *) __pyx_self; + __Pyx_INCREF((PyObject *)__pyx_cur_scope->__pyx_outer_scope); + __Pyx_GIVEREF((PyObject *)__pyx_cur_scope->__pyx_outer_scope); + __pyx_cur_scope->__pyx_genexpr_arg_0 = __pyx_genexpr_arg_0; + __Pyx_INCREF(__pyx_cur_scope->__pyx_genexpr_arg_0); + __Pyx_GIVEREF(__pyx_cur_scope->__pyx_genexpr_arg_0); + { + __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_9fontTools_6varLib_3iup_20iup_contour_optimize_2generator1, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[1]), (PyObject *) __pyx_cur_scope, __pyx_mstate_global->__pyx_n_u_genexpr, __pyx_mstate_global->__pyx_n_u_iup_contour_optimize_locals_gene, __pyx_mstate_global->__pyx_n_u_fontTools_varLib_iup); if (unlikely(!gen)) __PYX_ERR(0, 377, __pyx_L1_error) + __Pyx_DECREF(__pyx_cur_scope); + __Pyx_RefNannyFinishContext(); + return (PyObject *) gen; + } + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("fontTools.varLib.iup.iup_contour_optimize.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_DECREF((PyObject *)__pyx_cur_scope); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_gb_9fontTools_6varLib_3iup_20iup_contour_optimize_2generator1(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ +{ + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr *__pyx_cur_scope = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr *)__pyx_generator->closure); + PyObject *__pyx_r = NULL; + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *(*__pyx_t_3)(PyObject *); + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("genexpr", 0); + switch (__pyx_generator->resume_label) { + case 0: goto __pyx_L3_first_run; + default: /* CPython raises the right error here */ + __Pyx_RefNannyFinishContext(); + return NULL; + } + __pyx_L3_first_run:; + if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 377, __pyx_L1_error) + if (unlikely(!__pyx_cur_scope->__pyx_genexpr_arg_0)) { __Pyx_RaiseUnboundLocalError(".0"); __PYX_ERR(0, 377, __pyx_L1_error) } + if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_genexpr_arg_0)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_genexpr_arg_0)) { + __pyx_t_1 = __pyx_cur_scope->__pyx_genexpr_arg_0; __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = 0; + __pyx_t_3 = NULL; + } else { + __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_cur_scope->__pyx_genexpr_arg_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 377, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 377, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_3)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 377, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + __pyx_t_4 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_1, __pyx_t_2, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_2; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 377, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2)); + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_2); + #endif + ++__pyx_t_2; + } + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 377, __pyx_L1_error) + } else { + __pyx_t_4 = __pyx_t_3(__pyx_t_1); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 377, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_p); + __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_p, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_cur_scope->__pyx_v_p); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 377, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)(&PyComplex_Type)), __pyx_t_4, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 377, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyNumber_Absolute(__pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 377, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_tolerance)) { __Pyx_RaiseClosureNameError("tolerance"); __PYX_ERR(0, 377, __pyx_L1_error) } + __pyx_t_6 = __Pyx_PyObject_CompareBoolLe_object_object(__pyx_t_4, __pyx_cur_scope->__pyx_outer_scope->__pyx_v_tolerance, Py_LE); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(0, 377, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_7 = (!__pyx_t_6); + + + if (__pyx_t_7) { + + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(Py_False); + __pyx_r = Py_False; + } + __Pyx_XDECREF(__pyx_temp); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L0; + } + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + /*else*/ { + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(Py_True); + __pyx_r = Py_True; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + } + CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + if (__Pyx_PyErr_Occurred()) { + __Pyx_Generator_Replace_StopIteration(0); + __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + #if !CYTHON_USE_EXC_INFO_STACK + __Pyx_Coroutine_ResetAndClearException(__pyx_generator); + #endif + __pyx_generator->resume_label = -1; + __Pyx_Coroutine_clear((PyObject*)__pyx_generator); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static PyObject *__pyx_gb_9fontTools_6varLib_3iup_20iup_contour_optimize_5generator2(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ + +/* "fontTools/varLib/iup.py":386 + * # If all deltas are exactly the same, return just one (the first one): + * d0 = deltas[0] + * if all(d0 == d for d in deltas): # <<<<<<<<<<<<<< + * return [d0] + [None] * (n - 1) + * +*/ + +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_20iup_contour_optimize_3genexpr(PyObject *__pyx_self, PyObject *__pyx_genexpr_arg_0) { + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr *__pyx_cur_scope; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("genexpr", 0); + __pyx_cur_scope = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr *)__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(__pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (unlikely(!__pyx_cur_scope)) { + __pyx_cur_scope = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr *)Py_None); + __Pyx_INCREF(Py_None); + __PYX_ERR(0, 386, __pyx_L1_error) + } else { + __Pyx_GOTREF((PyObject *)__pyx_cur_scope); + } + __pyx_cur_scope->__pyx_outer_scope = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *) __pyx_self; + __Pyx_INCREF((PyObject *)__pyx_cur_scope->__pyx_outer_scope); + __Pyx_GIVEREF((PyObject *)__pyx_cur_scope->__pyx_outer_scope); + __pyx_cur_scope->__pyx_genexpr_arg_0 = __pyx_genexpr_arg_0; + __Pyx_INCREF(__pyx_cur_scope->__pyx_genexpr_arg_0); + __Pyx_GIVEREF(__pyx_cur_scope->__pyx_genexpr_arg_0); + { + __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_9fontTools_6varLib_3iup_20iup_contour_optimize_5generator2, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[2]), (PyObject *) __pyx_cur_scope, __pyx_mstate_global->__pyx_n_u_genexpr, __pyx_mstate_global->__pyx_n_u_iup_contour_optimize_locals_gene, __pyx_mstate_global->__pyx_n_u_fontTools_varLib_iup); if (unlikely(!gen)) __PYX_ERR(0, 386, __pyx_L1_error) + __Pyx_DECREF(__pyx_cur_scope); + __Pyx_RefNannyFinishContext(); + return (PyObject *) gen; + } + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("fontTools.varLib.iup.iup_contour_optimize.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_DECREF((PyObject *)__pyx_cur_scope); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_gb_9fontTools_6varLib_3iup_20iup_contour_optimize_5generator2(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ +{ + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr *__pyx_cur_scope = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr *)__pyx_generator->closure); + PyObject *__pyx_r = NULL; + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *(*__pyx_t_3)(PyObject *); + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("genexpr", 0); + switch (__pyx_generator->resume_label) { + case 0: goto __pyx_L3_first_run; + default: /* CPython raises the right error here */ + __Pyx_RefNannyFinishContext(); + return NULL; + } + __pyx_L3_first_run:; + if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 386, __pyx_L1_error) + if (unlikely(!__pyx_cur_scope->__pyx_genexpr_arg_0)) { __Pyx_RaiseUnboundLocalError(".0"); __PYX_ERR(0, 386, __pyx_L1_error) } + if (likely(PyList_CheckExact(__pyx_cur_scope->__pyx_genexpr_arg_0)) || PyTuple_CheckExact(__pyx_cur_scope->__pyx_genexpr_arg_0)) { + __pyx_t_1 = __pyx_cur_scope->__pyx_genexpr_arg_0; __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = 0; + __pyx_t_3 = NULL; + } else { + __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_cur_scope->__pyx_genexpr_arg_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 386, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 386, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_3)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 386, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + __pyx_t_4 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_1, __pyx_t_2, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_2; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 386, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2)); + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_2); + #endif + ++__pyx_t_2; + } + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 386, __pyx_L1_error) + } else { + __pyx_t_4 = __pyx_t_3(__pyx_t_1); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 386, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_d); + __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_d, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_d0)) { __Pyx_RaiseClosureNameError("d0"); __PYX_ERR(0, 386, __pyx_L1_error) } + __pyx_t_5 = __Pyx_PyObject_CompareBoolEq_object_object(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_d0, __pyx_cur_scope->__pyx_v_d, Py_EQ); if (unlikely((__pyx_t_5 < 0))) __PYX_ERR(0, 386, __pyx_L1_error) + __pyx_t_6 = (!__pyx_t_5); + + + if (__pyx_t_6) { + + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(Py_False); + __pyx_r = Py_False; + } + __Pyx_XDECREF(__pyx_temp); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L0; + } + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + /*else*/ { + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(Py_True); + __pyx_r = Py_True; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + } + CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + if (__Pyx_PyErr_Occurred()) { + __Pyx_Generator_Replace_StopIteration(0); + __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + #if !CYTHON_USE_EXC_INFO_STACK + __Pyx_Coroutine_ResetAndClearException(__pyx_generator); + #endif + __pyx_generator->resume_label = -1; + __Pyx_Coroutine_clear((PyObject*)__pyx_generator); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/varLib/iup.py":362 + * + * + * def iup_contour_optimize( # <<<<<<<<<<<<<< + * deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0.0 + * ) -> _DeltaOrNoneSegment: +*/ + +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_12iup_contour_optimize(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords, PyObject *__pyx_v_tolerance) { + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *__pyx_cur_scope; + PyObject *__pyx_v_n = NULL; + PyObject *__pyx_v_forced = NULL; + PyObject *__pyx_v_k = NULL; + PyObject *__pyx_v_chain = NULL; + PyObject *__pyx_v_costs = NULL; + PyObject *__pyx_v_solution = NULL; + PyObject *__pyx_v_i = NULL; + PyObject *__pyx_v_best_sol = NULL; + PyObject *__pyx_v_best_cost = NULL; + PyObject *__pyx_v_start = NULL; + PyObject *__pyx_v_cost = NULL; + PyObject *__pyx_gb_9fontTools_6varLib_3iup_20iup_contour_optimize_2generator1 = 0; + PyObject *__pyx_gb_9fontTools_6varLib_3iup_20iup_contour_optimize_5generator2 = 0; + PyObject *__pyx_8genexpr5__pyx_v_i = NULL; + PyObject *__pyx_8genexpr6__pyx_v_i = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *(*__pyx_t_8)(PyObject *); + int __pyx_t_9; + PyObject *(*__pyx_t_10)(PyObject *); + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("iup_contour_optimize", 0); + __pyx_cur_scope = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *)__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(__pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (unlikely(!__pyx_cur_scope)) { + __pyx_cur_scope = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *)Py_None); + __Pyx_INCREF(Py_None); + __PYX_ERR(0, 362, __pyx_L1_error) + } else { + __Pyx_GOTREF((PyObject *)__pyx_cur_scope); + } + __pyx_cur_scope->__pyx_v_tolerance = __pyx_v_tolerance; + __Pyx_INCREF(__pyx_cur_scope->__pyx_v_tolerance); + __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_tolerance); + __Pyx_INCREF(__pyx_v_deltas); + __Pyx_INCREF(__pyx_v_coords); + + /* "fontTools/varLib/iup.py":372 + * """ + * + * n = len(deltas) # <<<<<<<<<<<<<< + * + * # Get the easy cases out of the way: +*/ + __pyx_t_1 = PyObject_Length(__pyx_v_deltas); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 372, __pyx_L1_error) + __pyx_t_2 = PyLong_FromSsize_t(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 372, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + + if (__Pyx_PyInt_FromNumber(&__pyx_t_2, NULL, 0) < (0)) __PYX_ERR(0, 372, __pyx_L1_error) + __pyx_v_n = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "fontTools/varLib/iup.py":377 + * + * # If all are within tolerance distance of 0, encode nothing: + * if all(abs(complex(*p)) <= tolerance for p in deltas): # <<<<<<<<<<<<<< + * return [None] * n + * +*/ + __pyx_t_2 = __pyx_pf_9fontTools_6varLib_3iup_20iup_contour_optimize_genexpr(((PyObject*)__pyx_cur_scope), __pyx_v_deltas); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 377, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_Generator_GetInlinedResult(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 377, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 377, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_4) { + + + /* "fontTools/varLib/iup.py":378 + * # If all are within tolerance distance of 0, encode nothing: + * if all(abs(complex(*p)) <= tolerance for p in deltas): + * return [None] * n # <<<<<<<<<<<<<< + * + * # If there's exactly one point, return it: +*/ + __pyx_t_3 = PyList_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 378, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyList_SET_ITEM(__pyx_t_3, 0, Py_None) != (0)) __PYX_ERR(0, 378, __pyx_L1_error); + { PyObject* __pyx_temp = PyNumber_InPlaceMultiply(__pyx_t_3, __pyx_v_n); if (unlikely(!__pyx_temp)) __PYX_ERR(0, 378, __pyx_L1_error) + __Pyx_GOTREF(__pyx_temp); + __Pyx_DECREF(__pyx_t_3); + __pyx_t_3 = __pyx_temp; + } + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __pyx_r = __pyx_t_3; + } + __Pyx_XDECREF(__pyx_temp); + } + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":377 + * + * # If all are within tolerance distance of 0, encode nothing: + * if all(abs(complex(*p)) <= tolerance for p in deltas): # <<<<<<<<<<<<<< + * return [None] * n + * +*/ + } + + /* "fontTools/varLib/iup.py":381 + * + * # If there's exactly one point, return it: + * if n == 1: # <<<<<<<<<<<<<< + * return deltas + * +*/ + __pyx_t_4 = (__Pyx_PyLong_BoolEqObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_1, 1, 0)); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 381, __pyx_L1_error) + if (__pyx_t_4) { + + + /* "fontTools/varLib/iup.py":382 + * # If there's exactly one point, return it: + * if n == 1: + * return deltas # <<<<<<<<<<<<<< + * + * # If all deltas are exactly the same, return just one (the first one): +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(__pyx_v_deltas); + __pyx_r = __pyx_v_deltas; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":381 + * + * # If there's exactly one point, return it: + * if n == 1: # <<<<<<<<<<<<<< + * return deltas + * +*/ + } + + /* "fontTools/varLib/iup.py":385 + * + * # If all deltas are exactly the same, return just one (the first one): + * d0 = deltas[0] # <<<<<<<<<<<<<< + * if all(d0 == d for d in deltas): + * return [d0] + [None] * (n - 1) +*/ + __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_deltas, 0, long, 1, __Pyx_PyLong_From_long, 0, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 385, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __pyx_cur_scope->__pyx_v_d0 = __pyx_t_3; + __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":386 + * # If all deltas are exactly the same, return just one (the first one): + * d0 = deltas[0] + * if all(d0 == d for d in deltas): # <<<<<<<<<<<<<< + * return [d0] + [None] * (n - 1) + * +*/ + __pyx_t_3 = __pyx_pf_9fontTools_6varLib_3iup_20iup_contour_optimize_3genexpr(((PyObject*)__pyx_cur_scope), __pyx_v_deltas); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 386, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_Generator_GetInlinedResult(__pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 386, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 386, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_4) { + + + /* "fontTools/varLib/iup.py":387 + * d0 = deltas[0] + * if all(d0 == d for d in deltas): + * return [d0] + [None] * (n - 1) # <<<<<<<<<<<<<< + * + * # Else, solve the general problem using Dynamic Programming. +*/ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 387, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_cur_scope->__pyx_v_d0); + __Pyx_GIVEREF(__pyx_cur_scope->__pyx_v_d0); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 0, __pyx_cur_scope->__pyx_v_d0) != (0)) __PYX_ERR(0, 387, __pyx_L1_error); + __pyx_t_3 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 387, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = PyList_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 387, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyList_SET_ITEM(__pyx_t_5, 0, Py_None) != (0)) __PYX_ERR(0, 387, __pyx_L1_error); + { PyObject* __pyx_temp = PyNumber_InPlaceMultiply(__pyx_t_5, __pyx_t_3); if (unlikely(!__pyx_temp)) __PYX_ERR(0, 387, __pyx_L1_error) + __Pyx_GOTREF(__pyx_temp); + __Pyx_DECREF(__pyx_t_5); + __pyx_t_5 = __pyx_temp; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Add(__pyx_t_2, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 387, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __pyx_r = __pyx_t_3; + } + __Pyx_XDECREF(__pyx_temp); + } + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":386 + * # If all deltas are exactly the same, return just one (the first one): + * d0 = deltas[0] + * if all(d0 == d for d in deltas): # <<<<<<<<<<<<<< + * return [d0] + [None] * (n - 1) + * +*/ + } + + /* "fontTools/varLib/iup.py":391 + * # Else, solve the general problem using Dynamic Programming. + * + * forced = _iup_contour_bound_forced_set(deltas, coords, tolerance) # <<<<<<<<<<<<<< + * # The _iup_contour_optimize_dp() routine returns the optimal encoding + * # solution given the constraint that the last point is always encoded. +*/ + __pyx_t_5 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_iup_contour_bound_forced_set); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 391, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); + assert(__pyx_t_5); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_2, __pyx__function); + __pyx_t_6 = 0; + } + #endif + { + PyObject *__pyx_callargs[4] = {__pyx_t_5, __pyx_v_deltas, __pyx_v_coords, __pyx_cur_scope->__pyx_v_tolerance}; + __pyx_t_3 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_2, __pyx_callargs+__pyx_t_6, (4-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 391, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_v_forced = __pyx_t_3; + __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":400 + * # if the font size changes (reduced); that would mean the forced-set + * # has members it should not have. + * if forced: # <<<<<<<<<<<<<< + * # Forced set is non-empty: rotate the contour start point + * # such that the last point in the list is a forced point. +*/ + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_forced); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 400, __pyx_L1_error) + if (__pyx_t_4) { + + + /* "fontTools/varLib/iup.py":403 + * # Forced set is non-empty: rotate the contour start point + * # such that the last point in the list is a forced point. + * k = (n - 1) - max(forced) # <<<<<<<<<<<<<< + * assert k >= 0 + * +*/ + __pyx_t_3 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = NULL; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_v_forced}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)__pyx_builtin_max, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_5 = __Pyx_PyNumber_Subtract_int_object(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 403, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_k = __pyx_t_5; + __pyx_t_5 = 0; + + /* "fontTools/varLib/iup.py":404 + * # such that the last point in the list is a forced point. + * k = (n - 1) - max(forced) + * assert k >= 0 # <<<<<<<<<<<<<< + * + * deltas = _rot_list(deltas, k) +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_4 = __Pyx_PyObject_CompareBoolGe_object_int(__pyx_v_k, __pyx_mstate_global->__pyx_int_0, Py_GE); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 404, __pyx_L1_error) + if (unlikely(!__pyx_t_4)) { + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_AssertionError))), 0, 0, 0); + __PYX_ERR(0, 404, __pyx_L1_error) + } + + } + #else + if ((1)); else __PYX_ERR(0, 404, __pyx_L1_error) + #endif + + /* "fontTools/varLib/iup.py":406 + * assert k >= 0 + * + * deltas = _rot_list(deltas, k) # <<<<<<<<<<<<<< + * coords = _rot_list(coords, k) + * forced = _rot_set(forced, k, n) +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_rot_list); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 406, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_3, __pyx__function); + __pyx_t_6 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_2, __pyx_v_deltas, __pyx_v_k}; + __pyx_t_5 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_3, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 406, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_DECREF_SET(__pyx_v_deltas, __pyx_t_5); + __pyx_t_5 = 0; + + /* "fontTools/varLib/iup.py":407 + * + * deltas = _rot_list(deltas, k) + * coords = _rot_list(coords, k) # <<<<<<<<<<<<<< + * forced = _rot_set(forced, k, n) + * +*/ + __pyx_t_3 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_rot_list); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 407, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + assert(__pyx_t_3); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_2, __pyx__function); + __pyx_t_6 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_3, __pyx_v_coords, __pyx_v_k}; + __pyx_t_5 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_2, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 407, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_DECREF_SET(__pyx_v_coords, __pyx_t_5); + __pyx_t_5 = 0; + + /* "fontTools/varLib/iup.py":408 + * deltas = _rot_list(deltas, k) + * coords = _rot_list(coords, k) + * forced = _rot_set(forced, k, n) # <<<<<<<<<<<<<< + * + * # Debugging: Pass a set() instead of forced variable to the next call +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_rot_set); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 408, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_3, __pyx__function); + __pyx_t_6 = 0; + } + #endif + { + PyObject *__pyx_callargs[4] = {__pyx_t_2, __pyx_v_forced, __pyx_v_k, __pyx_v_n}; + __pyx_t_5 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_3, __pyx_callargs+__pyx_t_6, (4-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 408, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_DECREF_SET(__pyx_v_forced, __pyx_t_5); + __pyx_t_5 = 0; + + /* "fontTools/varLib/iup.py":412 + * # Debugging: Pass a set() instead of forced variable to the next call + * # to exercise forced-set computation for under-counting. + * chain, costs = _iup_contour_optimize_dp(deltas, coords, forced, tolerance) # <<<<<<<<<<<<<< + * + * # Assemble solution. +*/ + __pyx_t_3 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_iup_contour_optimize_dp); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 412, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + assert(__pyx_t_3); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_2, __pyx__function); + __pyx_t_6 = 0; + } + #endif + { + PyObject *__pyx_callargs[5] = {__pyx_t_3, __pyx_v_deltas, __pyx_v_coords, __pyx_v_forced, __pyx_cur_scope->__pyx_v_tolerance}; + __pyx_t_5 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_2, __pyx_callargs+__pyx_t_6, (5-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 412, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + if ((likely(PyTuple_CheckExact(__pyx_t_5))) || (PyList_CheckExact(__pyx_t_5))) { + PyObject* sequence = __pyx_t_5; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 412, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + } else { + __pyx_t_2 = __Pyx_PyList_GET_ITEM_REF(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 412, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyList_GET_ITEM_REF(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 412, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_3); + } + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 412, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 412, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_7 = PyObject_GetIter(__pyx_t_5); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 412, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_8 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_7); + index = 0; __pyx_t_2 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_2)) goto __pyx_L7_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_3 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_3)) goto __pyx_L7_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 2) < (0)) __PYX_ERR(0, 412, __pyx_L1_error) + __pyx_t_8 = NULL; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L8_unpacking_done; + __pyx_L7_unpacking_failed:; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 412, __pyx_L1_error) + __pyx_L8_unpacking_done:; + } + __pyx_v_chain = __pyx_t_2; + __pyx_t_2 = 0; + __pyx_v_costs = __pyx_t_3; + __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":415 + * + * # Assemble solution. + * solution = set() # <<<<<<<<<<<<<< + * i = n - 1 + * while i is not None: +*/ + __pyx_t_5 = PySet_New(0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 415, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_solution = ((PyObject*)__pyx_t_5); + __pyx_t_5 = 0; + + /* "fontTools/varLib/iup.py":416 + * # Assemble solution. + * solution = set() + * i = n - 1 # <<<<<<<<<<<<<< + * while i is not None: + * solution.add(i) +*/ + __pyx_t_5 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 416, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_v_i = __pyx_t_5; + __pyx_t_5 = 0; + + /* "fontTools/varLib/iup.py":417 + * solution = set() + * i = n - 1 + * while i is not None: # <<<<<<<<<<<<<< + * solution.add(i) + * i = chain[i] +*/ + while (1) { + __pyx_t_4 = (__pyx_v_i != Py_None); + + if (!__pyx_t_4) break; + + /* "fontTools/varLib/iup.py":418 + * i = n - 1 + * while i is not None: + * solution.add(i) # <<<<<<<<<<<<<< + * i = chain[i] + * solution.remove(-1) +*/ + __pyx_t_9 = PySet_Add(__pyx_v_solution, __pyx_v_i); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(0, 418, __pyx_L1_error) + + + /* "fontTools/varLib/iup.py":419 + * while i is not None: + * solution.add(i) + * i = chain[i] # <<<<<<<<<<<<<< + * solution.remove(-1) + * +*/ + __pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_chain, __pyx_v_i); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 419, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF_SET(__pyx_v_i, __pyx_t_5); + __pyx_t_5 = 0; + } + + /* "fontTools/varLib/iup.py":420 + * solution.add(i) + * i = chain[i] + * solution.remove(-1) # <<<<<<<<<<<<<< + * + * # if not forced <= solution: +*/ + __pyx_t_9 = __Pyx_PySet_Remove(__pyx_v_solution, __pyx_mstate_global->__pyx_int_neg_1); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(0, 420, __pyx_L1_error) + + + /* "fontTools/varLib/iup.py":426 + * # print("deltas", deltas) + * # print("len", len(deltas)) + * assert forced <= solution, (forced, solution) # <<<<<<<<<<<<<< + * + * deltas = [deltas[i] if i in solution else None for i in range(n)] +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_4 = __Pyx_PyObject_RichCompareBool(__pyx_v_forced, __pyx_v_solution, Py_LE); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 426, __pyx_L1_error) + if (unlikely(!__pyx_t_4)) { + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 426, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_forced); + __Pyx_GIVEREF(__pyx_v_forced); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_forced) != (0)) __PYX_ERR(0, 426, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_solution); + __Pyx_GIVEREF(__pyx_v_solution); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_v_solution) != (0)) __PYX_ERR(0, 426, __pyx_L1_error); + { + PyObject* __pyx_temp[1] = {__pyx_t_5}; + __pyx_t_3 = __Pyx_PyTuple_FromArray(__pyx_temp, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 426, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_AssertionError))), __pyx_t_3, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 426, __pyx_L1_error) + } + + } + #else + if ((1)); else __PYX_ERR(0, 426, __pyx_L1_error) + #endif + + /* "fontTools/varLib/iup.py":428 + * assert forced <= solution, (forced, solution) + * + * deltas = [deltas[i] if i in solution else None for i in range(n)] # <<<<<<<<<<<<<< + * + * deltas = _rot_list(deltas, -k) +*/ + { /* enter inner scope */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 428, __pyx_L13_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = NULL; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_n}; + __pyx_t_5 = __Pyx_PyObject_FastCall((PyObject*)(&PyRange_Type), __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 428, __pyx_L13_error) + __Pyx_GOTREF(__pyx_t_5); + } + __pyx_t_2 = PyObject_GetIter(__pyx_t_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 428, __pyx_L13_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_10 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 428, __pyx_L13_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + for (;;) { + { + __pyx_t_5 = __pyx_t_10(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 428, __pyx_L13_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_5); + if (__Pyx_PyInt_FromNumber(&__pyx_t_5, NULL, 1) < (0)) __PYX_ERR(0, 428, __pyx_L13_error) + __Pyx_XDECREF_SET(__pyx_8genexpr5__pyx_v_i, ((PyObject*)__pyx_t_5)); + __pyx_t_5 = 0; + __pyx_t_4 = (__Pyx_PySet_ContainsTF(__pyx_8genexpr5__pyx_v_i, __pyx_v_solution, Py_EQ)); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 428, __pyx_L13_error) + if (__pyx_t_4) { + __pyx_t_7 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_8genexpr5__pyx_v_i); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 428, __pyx_L13_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_5 = __pyx_t_7; + __pyx_t_7 = 0; + } else { + __Pyx_INCREF(Py_None); + __pyx_t_5 = Py_None; + } + + __Pyx_GIVEREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_AppendAndDecref(__pyx_t_3, __pyx_t_5))) __PYX_ERR(0, 428, __pyx_L13_error) + __pyx_t_5 = 0; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_8genexpr5__pyx_v_i); __pyx_8genexpr5__pyx_v_i = 0; + goto __pyx_L17_exit_scope; + __pyx_L13_error:; + __Pyx_XDECREF(__pyx_8genexpr5__pyx_v_i); __pyx_8genexpr5__pyx_v_i = 0; + goto __pyx_L1_error; + __pyx_L17_exit_scope:; + } /* exit inner scope */ + __Pyx_DECREF_SET(__pyx_v_deltas, __pyx_t_3); + __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":430 + * deltas = [deltas[i] if i in solution else None for i in range(n)] + * + * deltas = _rot_list(deltas, -k) # <<<<<<<<<<<<<< + * else: + * # Repeat the contour an extra time, solve the new case, then look for solutions of the +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_rot_list); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 430, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = PyNumber_Negative(__pyx_v_k); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 430, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_5); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_5, __pyx__function); + __pyx_t_6 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_2, __pyx_v_deltas, __pyx_t_7}; + __pyx_t_3 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_5, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 430, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_DECREF_SET(__pyx_v_deltas, __pyx_t_3); + __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":400 + * # if the font size changes (reduced); that would mean the forced-set + * # has members it should not have. + * if forced: # <<<<<<<<<<<<<< + * # Forced set is non-empty: rotate the contour start point + * # such that the last point in the list is a forced point. +*/ + goto __pyx_L6; + } + + /* "fontTools/varLib/iup.py":435 + * # circular n-length problem in the solution for new linear case. I cannot prove that + * # this always produces the optimal solution... + * chain, costs = _iup_contour_optimize_dp( # <<<<<<<<<<<<<< + * deltas + deltas, coords + coords, forced, tolerance, n + * ) +*/ + /*else*/ { + __pyx_t_5 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_iup_contour_optimize_dp); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 435, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + + /* "fontTools/varLib/iup.py":436 + * # this always produces the optimal solution... + * chain, costs = _iup_contour_optimize_dp( + * deltas + deltas, coords + coords, forced, tolerance, n # <<<<<<<<<<<<<< + * ) + * best_sol, best_cost = None, n + 1 +*/ + __pyx_t_2 = __Pyx_PyNumber_Add_object_object(__pyx_v_deltas, __pyx_v_deltas); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 436, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_11 = __Pyx_PyNumber_Add_object_object(__pyx_v_coords, __pyx_v_coords); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 436, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_6 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_7); + assert(__pyx_t_5); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_7, __pyx__function); + __pyx_t_6 = 0; + } + #endif + { + PyObject *__pyx_callargs[6] = {__pyx_t_5, __pyx_t_2, __pyx_t_11, __pyx_v_forced, __pyx_cur_scope->__pyx_v_tolerance, __pyx_v_n}; + __pyx_t_3 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_7, __pyx_callargs+__pyx_t_6, (6-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 435, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + if ((likely(PyTuple_CheckExact(__pyx_t_3))) || (PyList_CheckExact(__pyx_t_3))) { + PyObject* sequence = __pyx_t_3; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 435, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_7 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_7); + __pyx_t_11 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_11); + } else { + __pyx_t_7 = __Pyx_PyList_GET_ITEM_REF(sequence, 0, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 435, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_7); + __pyx_t_11 = __Pyx_PyList_GET_ITEM_REF(sequence, 1, __Pyx_ReferenceSharing_SharedReference); + if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 435, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_11); + } + #else + __pyx_t_7 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 435, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_11 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 435, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_2 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 435, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_8 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_2); + index = 0; __pyx_t_7 = __pyx_t_8(__pyx_t_2); if (unlikely(!__pyx_t_7)) goto __pyx_L18_unpacking_failed; + __Pyx_GOTREF(__pyx_t_7); + index = 1; __pyx_t_11 = __pyx_t_8(__pyx_t_2); if (unlikely(!__pyx_t_11)) goto __pyx_L18_unpacking_failed; + __Pyx_GOTREF(__pyx_t_11); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_2), 2) < (0)) __PYX_ERR(0, 435, __pyx_L1_error) + __pyx_t_8 = NULL; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L19_unpacking_done; + __pyx_L18_unpacking_failed:; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_8 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 435, __pyx_L1_error) + __pyx_L19_unpacking_done:; + } + + /* "fontTools/varLib/iup.py":435 + * # circular n-length problem in the solution for new linear case. I cannot prove that + * # this always produces the optimal solution... + * chain, costs = _iup_contour_optimize_dp( # <<<<<<<<<<<<<< + * deltas + deltas, coords + coords, forced, tolerance, n + * ) +*/ + __pyx_v_chain = __pyx_t_7; + __pyx_t_7 = 0; + __pyx_v_costs = __pyx_t_11; + __pyx_t_11 = 0; + + /* "fontTools/varLib/iup.py":438 + * deltas + deltas, coords + coords, forced, tolerance, n + * ) + * best_sol, best_cost = None, n + 1 # <<<<<<<<<<<<<< + * + * for start in range(n - 1, len(costs) - 1): +*/ + __pyx_t_3 = Py_None; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_11 = __Pyx_PyLong_AddObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 438, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_v_best_sol = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + __pyx_v_best_cost = __pyx_t_11; + __pyx_t_11 = 0; + + /* "fontTools/varLib/iup.py":440 + * best_sol, best_cost = None, n + 1 + * + * for start in range(n - 1, len(costs) - 1): # <<<<<<<<<<<<<< + * # Assemble solution. + * solution = set() +*/ + __pyx_t_3 = NULL; + __pyx_t_7 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 440, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_1 = PyObject_Length(__pyx_v_costs); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 440, __pyx_L1_error) + __pyx_t_2 = PyLong_FromSsize_t((__pyx_t_1 - 1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 440, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_3, __pyx_t_7, __pyx_t_2}; + __pyx_t_11 = __Pyx_PyObject_FastCall((PyObject*)(&PyRange_Type), __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 440, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + } + __pyx_t_2 = PyObject_GetIter(__pyx_t_11); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 440, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_10 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 440, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + for (;;) { + { + __pyx_t_11 = __pyx_t_10(__pyx_t_2); + if (unlikely(!__pyx_t_11)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 440, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_11); + if (__Pyx_PyInt_FromNumber(&__pyx_t_11, NULL, 1) < (0)) __PYX_ERR(0, 440, __pyx_L1_error) + __Pyx_XDECREF_SET(__pyx_v_start, ((PyObject*)__pyx_t_11)); + __pyx_t_11 = 0; + + /* "fontTools/varLib/iup.py":442 + * for start in range(n - 1, len(costs) - 1): + * # Assemble solution. + * solution = set() # <<<<<<<<<<<<<< + * i = start + * while i > start - n: +*/ + __pyx_t_11 = PySet_New(0); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 442, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_XDECREF_SET(__pyx_v_solution, ((PyObject*)__pyx_t_11)); + __pyx_t_11 = 0; + + /* "fontTools/varLib/iup.py":443 + * # Assemble solution. + * solution = set() + * i = start # <<<<<<<<<<<<<< + * while i > start - n: + * solution.add(i % n) +*/ + __Pyx_INCREF(__pyx_v_start); + __Pyx_XDECREF_SET(__pyx_v_i, __pyx_v_start); + + /* "fontTools/varLib/iup.py":444 + * solution = set() + * i = start + * while i > start - n: # <<<<<<<<<<<<<< + * solution.add(i % n) + * i = chain[i] +*/ + while (1) { + __pyx_t_11 = __Pyx_PyNumber_Subtract_int_int(__pyx_v_start, __pyx_v_n); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 444, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_4 = __Pyx_PyObject_CompareBoolGt_object_int(__pyx_v_i, __pyx_t_11, Py_GT); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 444, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + + if (!__pyx_t_4) break; + + /* "fontTools/varLib/iup.py":445 + * i = start + * while i > start - n: + * solution.add(i % n) # <<<<<<<<<<<<<< + * i = chain[i] + * if i == start - n: +*/ + __pyx_t_11 = PyNumber_Remainder(__pyx_v_i, __pyx_v_n); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 445, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_9 = PySet_Add(__pyx_v_solution, __pyx_t_11); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(0, 445, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + + + /* "fontTools/varLib/iup.py":446 + * while i > start - n: + * solution.add(i % n) + * i = chain[i] # <<<<<<<<<<<<<< + * if i == start - n: + * cost = costs[start] - costs[start - n] +*/ + __pyx_t_11 = __Pyx_PyObject_GetItem(__pyx_v_chain, __pyx_v_i); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 446, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF_SET(__pyx_v_i, __pyx_t_11); + __pyx_t_11 = 0; + } + + /* "fontTools/varLib/iup.py":447 + * solution.add(i % n) + * i = chain[i] + * if i == start - n: # <<<<<<<<<<<<<< + * cost = costs[start] - costs[start - n] + * if cost <= best_cost: +*/ + __pyx_t_11 = __Pyx_PyNumber_Subtract_int_int(__pyx_v_start, __pyx_v_n); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 447, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_4 = __Pyx_PyObject_CompareBoolEq_object_int(__pyx_v_i, __pyx_t_11, Py_EQ); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 447, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + if (__pyx_t_4) { + + + /* "fontTools/varLib/iup.py":448 + * i = chain[i] + * if i == start - n: + * cost = costs[start] - costs[start - n] # <<<<<<<<<<<<<< + * if cost <= best_cost: + * best_sol, best_cost = solution, cost +*/ + __pyx_t_11 = __Pyx_PyObject_GetItem(__pyx_v_costs, __pyx_v_start); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 448, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_7 = __Pyx_PyNumber_Subtract_int_int(__pyx_v_start, __pyx_v_n); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 448, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_v_costs, __pyx_t_7); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 448, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyNumber_Subtract_object_object(__pyx_t_11, __pyx_t_3); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 448, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_cost, __pyx_t_7); + __pyx_t_7 = 0; + + /* "fontTools/varLib/iup.py":449 + * if i == start - n: + * cost = costs[start] - costs[start - n] + * if cost <= best_cost: # <<<<<<<<<<<<<< + * best_sol, best_cost = solution, cost + * +*/ + __pyx_t_4 = __Pyx_PyObject_CompareBoolLe_object_object(__pyx_v_cost, __pyx_v_best_cost, Py_LE); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 449, __pyx_L1_error) + if (__pyx_t_4) { + + + /* "fontTools/varLib/iup.py":450 + * cost = costs[start] - costs[start - n] + * if cost <= best_cost: + * best_sol, best_cost = solution, cost # <<<<<<<<<<<<<< + * + * # if not forced <= best_sol: +*/ + __pyx_t_7 = __pyx_v_solution; + __Pyx_INCREF(__pyx_t_7); + __pyx_t_3 = __pyx_v_cost; + __Pyx_INCREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_best_sol, ((PyObject*)__pyx_t_7)); + __pyx_t_7 = 0; + __Pyx_DECREF_SET(__pyx_v_best_cost, __pyx_t_3); + __pyx_t_3 = 0; + + /* "fontTools/varLib/iup.py":449 + * if i == start - n: + * cost = costs[start] - costs[start - n] + * if cost <= best_cost: # <<<<<<<<<<<<<< + * best_sol, best_cost = solution, cost + * +*/ + } + + /* "fontTools/varLib/iup.py":447 + * solution.add(i % n) + * i = chain[i] + * if i == start - n: # <<<<<<<<<<<<<< + * cost = costs[start] - costs[start - n] + * if cost <= best_cost: +*/ + } + + /* "fontTools/varLib/iup.py":440 + * best_sol, best_cost = None, n + 1 + * + * for start in range(n - 1, len(costs) - 1): # <<<<<<<<<<<<<< + * # Assemble solution. + * solution = set() +*/ + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "fontTools/varLib/iup.py":456 + * # print("deltas", deltas) + * # print("len", len(deltas)) + * assert forced <= best_sol, (forced, best_sol) # <<<<<<<<<<<<<< + * + * deltas = [deltas[i] if i in best_sol else None for i in range(n)] +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_4 = __Pyx_PyObject_RichCompareBool(__pyx_v_forced, __pyx_v_best_sol, Py_LE); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 456, __pyx_L1_error) + if (unlikely(!__pyx_t_4)) { + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 456, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_forced); + __Pyx_GIVEREF(__pyx_v_forced); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_forced) != (0)) __PYX_ERR(0, 456, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_best_sol); + __Pyx_GIVEREF(__pyx_v_best_sol); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_best_sol) != (0)) __PYX_ERR(0, 456, __pyx_L1_error); + { + PyObject* __pyx_temp[1] = {__pyx_t_2}; + __pyx_t_3 = __Pyx_PyTuple_FromArray(__pyx_temp, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 456, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_AssertionError))), __pyx_t_3, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 456, __pyx_L1_error) + } + + } + #else + if ((1)); else __PYX_ERR(0, 456, __pyx_L1_error) + #endif + + /* "fontTools/varLib/iup.py":458 + * assert forced <= best_sol, (forced, best_sol) + * + * deltas = [deltas[i] if i in best_sol else None for i in range(n)] # <<<<<<<<<<<<<< + * + * return deltas +*/ + { /* enter inner scope */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 458, __pyx_L29_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_7 = NULL; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_v_n}; + __pyx_t_2 = __Pyx_PyObject_FastCall((PyObject*)(&PyRange_Type), __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 458, __pyx_L29_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_7 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 458, __pyx_L29_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_10 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_7); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 458, __pyx_L29_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + { + __pyx_t_2 = __pyx_t_10(__pyx_t_7); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 458, __pyx_L29_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_PyInt_FromNumber(&__pyx_t_2, NULL, 1) < (0)) __PYX_ERR(0, 458, __pyx_L29_error) + __Pyx_XDECREF_SET(__pyx_8genexpr6__pyx_v_i, ((PyObject*)__pyx_t_2)); + __pyx_t_2 = 0; + if (unlikely(__pyx_v_best_sol == Py_None)) { + PyErr_SetString(PyExc_TypeError, "\047NoneType\047 object is not iterable"); + __PYX_ERR(0, 458, __pyx_L29_error) + } + __pyx_t_4 = (__Pyx_PySet_ContainsTF(__pyx_8genexpr6__pyx_v_i, __pyx_v_best_sol, Py_EQ)); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 458, __pyx_L29_error) + if (__pyx_t_4) { + __pyx_t_11 = __Pyx_PyObject_GetItem(__pyx_v_deltas, __pyx_8genexpr6__pyx_v_i); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 458, __pyx_L29_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_2 = __pyx_t_11; + __pyx_t_11 = 0; + } else { + __Pyx_INCREF(Py_None); + __pyx_t_2 = Py_None; + } + + __Pyx_GIVEREF(__pyx_t_2); + if (unlikely(__Pyx_ListComp_AppendAndDecref(__pyx_t_3, __pyx_t_2))) __PYX_ERR(0, 458, __pyx_L29_error) + __pyx_t_2 = 0; + } + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_8genexpr6__pyx_v_i); __pyx_8genexpr6__pyx_v_i = 0; + goto __pyx_L33_exit_scope; + __pyx_L29_error:; + __Pyx_XDECREF(__pyx_8genexpr6__pyx_v_i); __pyx_8genexpr6__pyx_v_i = 0; + goto __pyx_L1_error; + __pyx_L33_exit_scope:; + } /* exit inner scope */ + __Pyx_DECREF_SET(__pyx_v_deltas, __pyx_t_3); + __pyx_t_3 = 0; + } + __pyx_L6:; + + /* "fontTools/varLib/iup.py":460 + * deltas = [deltas[i] if i in best_sol else None for i in range(n)] + * + * return deltas # <<<<<<<<<<<<<< + * + * +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(__pyx_v_deltas); + __pyx_r = __pyx_v_deltas; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":362 + * + * + * def iup_contour_optimize( # <<<<<<<<<<<<<< + * deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0.0 + * ) -> _DeltaOrNoneSegment: +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_AddTraceback("fontTools.varLib.iup.iup_contour_optimize", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_n); + __Pyx_XDECREF(__pyx_v_forced); + __Pyx_XDECREF(__pyx_v_k); + __Pyx_XDECREF(__pyx_v_chain); + __Pyx_XDECREF(__pyx_v_costs); + __Pyx_XDECREF(__pyx_v_solution); + __Pyx_XDECREF(__pyx_v_i); + __Pyx_XDECREF(__pyx_v_best_sol); + __Pyx_XDECREF(__pyx_v_best_cost); + __Pyx_XDECREF(__pyx_v_start); + __Pyx_XDECREF(__pyx_v_cost); + __Pyx_XDECREF(__pyx_gb_9fontTools_6varLib_3iup_20iup_contour_optimize_2generator1); + __Pyx_XDECREF(__pyx_gb_9fontTools_6varLib_3iup_20iup_contour_optimize_5generator2); + __Pyx_XDECREF(__pyx_8genexpr5__pyx_v_i); + __Pyx_XDECREF(__pyx_8genexpr6__pyx_v_i); + __Pyx_XDECREF(__pyx_v_deltas); + __Pyx_XDECREF(__pyx_v_coords); + __Pyx_DECREF((PyObject *)__pyx_cur_scope); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "fontTools/varLib/iup.py":463 + * + * + * def iup_delta_optimize( # <<<<<<<<<<<<<< + * deltas: _DeltaSegment, + * coords: _PointSegment, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_15iup_delta_optimize(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_9fontTools_6varLib_3iup_14iup_delta_optimize, "iup_delta_optimize(deltas: _DeltaSegment, coords: _PointSegment, ends: _Endpoints, tolerance: Real = 0.0) -> _DeltaOrNoneSegment\n\nFor the outline given in `coords`, with contour endpoints given\nin sorted increasing order in `ends`, optimize a set of delta\nvalues `deltas` within error `tolerance`.\n\nReturns delta vector that has most number of None items instead of\nthe input delta."); +static PyMethodDef __pyx_mdef_9fontTools_6varLib_3iup_15iup_delta_optimize = {"iup_delta_optimize", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_9fontTools_6varLib_3iup_15iup_delta_optimize, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_9fontTools_6varLib_3iup_14iup_delta_optimize}; +static PyObject *__pyx_pw_9fontTools_6varLib_3iup_15iup_delta_optimize(PyObject *__pyx_self, +#if CYTHON_VECTORCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_deltas = 0; + PyObject *__pyx_v_coords = 0; + PyObject *__pyx_v_ends = 0; + PyObject *__pyx_v_tolerance = 0; + #if !CYTHON_VECTORCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[4] = {0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("iup_delta_optimize (wrapper)", 0); + #if !CYTHON_VECTORCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_deltas,&__pyx_mstate_global->__pyx_n_u_coords,&__pyx_mstate_global->__pyx_n_u_ends,&__pyx_mstate_global->__pyx_n_u_tolerance,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) __PYX_ERR(0, 463, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 463, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 463, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 463, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 463, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "iup_delta_optimize", 0) < (0)) __PYX_ERR(0, 463, __pyx_L3_error) + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)((PyObject*)__pyx_mstate_global->__pyx_float_0_0))); + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("iup_delta_optimize", 0, 3, 4, i); __PYX_ERR(0, 463, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 463, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 463, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 463, __pyx_L3_error) + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 463, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)((PyObject*)__pyx_mstate_global->__pyx_float_0_0))); + } + __pyx_v_deltas = values[0]; + __pyx_v_coords = values[1]; + __pyx_v_ends = values[2]; + __pyx_v_tolerance = values[3]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("iup_delta_optimize", 0, 3, 4, __pyx_nargs); __PYX_ERR(0, 463, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("fontTools.varLib.iup.iup_delta_optimize", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_9fontTools_6varLib_3iup_14iup_delta_optimize(__pyx_self, __pyx_v_deltas, __pyx_v_coords, __pyx_v_ends, __pyx_v_tolerance); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_9fontTools_6varLib_3iup_14iup_delta_optimize(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_deltas, PyObject *__pyx_v_coords, PyObject *__pyx_v_ends, PyObject *__pyx_v_tolerance) { + PyObject *__pyx_v_n = NULL; + PyObject *__pyx_v_out = NULL; + PyObject *__pyx_v_start = NULL; + PyObject *__pyx_v_end = NULL; + PyObject *__pyx_v_contour = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + Py_ssize_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *(*__pyx_t_9)(PyObject *); + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + size_t __pyx_t_12; + Py_ssize_t __pyx_t_13; + int __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("iup_delta_optimize", 0); + __Pyx_INCREF(__pyx_v_ends); + + /* "fontTools/varLib/iup.py":476 + * the input delta. + * """ + * assert sorted(ends) == ends and len(coords) == (ends[-1] + 1 if ends else 0) + 4 # <<<<<<<<<<<<<< + * n = len(coords) + * ends = ends + [n - 4, n - 3, n - 2, n - 1] +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_2 = PySequence_List(__pyx_v_ends); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 476, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (unlikely((PyList_Sort(__pyx_t_2) < 0))) __PYX_ERR(0, 476, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyObject_RichCompareBool(__pyx_t_2, __pyx_v_ends, Py_EQ); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 476, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_3) { + + } else { + + __pyx_t_1 = __pyx_t_3; + + goto __pyx_L3_bool_binop_done; + } + __pyx_t_4 = PyObject_Length(__pyx_v_coords); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-1))) __PYX_ERR(0, 476, __pyx_L1_error) + __pyx_t_2 = PyLong_FromSsize_t(__pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 476, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_ends); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 476, __pyx_L1_error) + if (__pyx_t_3) { + __pyx_t_6 = __Pyx_GetItemInt(__pyx_v_ends, -1L, long, 1, __Pyx_PyLong_From_long, 1, 1, 1, __Pyx_ReferenceSharing_FunctionArgument); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 476, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyLong_AddObjC(__pyx_t_6, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 476, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_5 = __pyx_t_7; + __pyx_t_7 = 0; + } else { + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_0); + __pyx_t_5 = __pyx_mstate_global->__pyx_int_0; + } + + __pyx_t_7 = __Pyx_PyLong_AddObjC(__pyx_t_5, __pyx_mstate_global->__pyx_int_4, 4, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 476, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_3 = __Pyx_PyObject_CompareBoolEq_int_object(__pyx_t_2, __pyx_t_7, Py_EQ); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 476, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + __pyx_t_1 = __pyx_t_3; + + __pyx_L3_bool_binop_done:; + if (unlikely(!__pyx_t_1)) { + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_AssertionError))), 0, 0, 0); + __PYX_ERR(0, 476, __pyx_L1_error) + } + + } + #else + if ((1)); else __PYX_ERR(0, 476, __pyx_L1_error) + #endif + + /* "fontTools/varLib/iup.py":477 + * """ + * assert sorted(ends) == ends and len(coords) == (ends[-1] + 1 if ends else 0) + 4 + * n = len(coords) # <<<<<<<<<<<<<< + * ends = ends + [n - 4, n - 3, n - 2, n - 1] + * out = [] +*/ + __pyx_t_4 = PyObject_Length(__pyx_v_coords); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-1))) __PYX_ERR(0, 477, __pyx_L1_error) + __pyx_t_7 = PyLong_FromSsize_t(__pyx_t_4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 477, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + + if (__Pyx_PyInt_FromNumber(&__pyx_t_7, NULL, 0) < (0)) __PYX_ERR(0, 477, __pyx_L1_error) + __pyx_v_n = ((PyObject*)__pyx_t_7); + __pyx_t_7 = 0; + + /* "fontTools/varLib/iup.py":478 + * assert sorted(ends) == ends and len(coords) == (ends[-1] + 1 if ends else 0) + 4 + * n = len(coords) + * ends = ends + [n - 4, n - 3, n - 2, n - 1] # <<<<<<<<<<<<<< + * out = [] + * start = 0 +*/ + __pyx_t_7 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_4, 4, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 478, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_3, 3, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 478, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_2, 2, 0, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 478, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyLong_SubtractObjC(__pyx_v_n, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 478, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = PyList_New(4); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 478, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GIVEREF(__pyx_t_7); + if (__Pyx_PyList_SET_ITEM(__pyx_t_8, 0, __pyx_t_7) != (0)) __PYX_ERR(0, 478, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_2); + if (__Pyx_PyList_SET_ITEM(__pyx_t_8, 1, __pyx_t_2) != (0)) __PYX_ERR(0, 478, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyList_SET_ITEM(__pyx_t_8, 2, __pyx_t_5) != (0)) __PYX_ERR(0, 478, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_6); + if (__Pyx_PyList_SET_ITEM(__pyx_t_8, 3, __pyx_t_6) != (0)) __PYX_ERR(0, 478, __pyx_L1_error); + __pyx_t_7 = 0; + __pyx_t_2 = 0; + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_t_6 = PyNumber_Add(__pyx_v_ends, __pyx_t_8); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 478, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF_SET(__pyx_v_ends, __pyx_t_6); + __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":479 + * n = len(coords) + * ends = ends + [n - 4, n - 3, n - 2, n - 1] + * out = [] # <<<<<<<<<<<<<< + * start = 0 + * for end in ends: +*/ + __pyx_t_6 = PyList_New(0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 479, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_v_out = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":480 + * ends = ends + [n - 4, n - 3, n - 2, n - 1] + * out = [] + * start = 0 # <<<<<<<<<<<<<< + * for end in ends: + * contour = iup_contour_optimize( +*/ + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_0); + __pyx_v_start = __pyx_mstate_global->__pyx_int_0; + + /* "fontTools/varLib/iup.py":481 + * out = [] + * start = 0 + * for end in ends: # <<<<<<<<<<<<<< + * contour = iup_contour_optimize( + * deltas[start : end + 1], coords[start : end + 1], tolerance +*/ + if (likely(PyList_CheckExact(__pyx_v_ends)) || PyTuple_CheckExact(__pyx_v_ends)) { + __pyx_t_6 = __pyx_v_ends; __Pyx_INCREF(__pyx_t_6); + __pyx_t_4 = 0; + __pyx_t_9 = NULL; + } else { + __pyx_t_4 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_v_ends); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 481, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_9 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_6); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 481, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_9)) { + if (likely(PyList_CheckExact(__pyx_t_6))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 481, __pyx_L1_error) + #endif + if (__pyx_t_4 >= __pyx_temp) break; + } + __pyx_t_8 = __Pyx_PyList_GET_ITEM_REF(__pyx_t_6, __pyx_t_4, __Pyx_ReferenceSharing_OwnStrongReference); + ++__pyx_t_4; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 481, __pyx_L1_error) + #endif + if (__pyx_t_4 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_8 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_4)); + #else + __pyx_t_8 = __Pyx_PySequence_ITEM(__pyx_t_6, __pyx_t_4); + #endif + ++__pyx_t_4; + } + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 481, __pyx_L1_error) + } else { + __pyx_t_8 = __pyx_t_9(__pyx_t_6); + if (unlikely(!__pyx_t_8)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 481, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XDECREF_SET(__pyx_v_end, __pyx_t_8); + __pyx_t_8 = 0; + + /* "fontTools/varLib/iup.py":482 + * start = 0 + * for end in ends: + * contour = iup_contour_optimize( # <<<<<<<<<<<<<< + * deltas[start : end + 1], coords[start : end + 1], tolerance + * ) +*/ + __pyx_t_5 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_iup_contour_optimize); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 482, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + + /* "fontTools/varLib/iup.py":483 + * for end in ends: + * contour = iup_contour_optimize( + * deltas[start : end + 1], coords[start : end + 1], tolerance # <<<<<<<<<<<<<< + * ) + * assert len(contour) == end - start + 1 +*/ + __pyx_t_7 = __Pyx_PyLong_AddObjC(__pyx_v_end, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 483, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_10 = __Pyx_PyObject_GetSlice(__pyx_v_deltas, 0, 0, &__pyx_v_start, &__pyx_t_7, NULL, 0, 0, 1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 483, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyLong_AddObjC(__pyx_v_end, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 483, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_11 = __Pyx_PyObject_GetSlice(__pyx_v_coords, 0, 0, &__pyx_v_start, &__pyx_t_7, NULL, 0, 0, 1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 483, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_12 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); + assert(__pyx_t_5); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_2, __pyx__function); + __pyx_t_12 = 0; + } + #endif + { + PyObject *__pyx_callargs[4] = {__pyx_t_5, __pyx_t_10, __pyx_t_11, __pyx_v_tolerance}; + __pyx_t_8 = __Pyx_PyObject_FastCall((PyObject*)__pyx_t_2, __pyx_callargs+__pyx_t_12, (4-__pyx_t_12) | (__pyx_t_12*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 482, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + } + __Pyx_XDECREF_SET(__pyx_v_contour, __pyx_t_8); + __pyx_t_8 = 0; + + /* "fontTools/varLib/iup.py":485 + * deltas[start : end + 1], coords[start : end + 1], tolerance + * ) + * assert len(contour) == end - start + 1 # <<<<<<<<<<<<<< + * out.extend(contour) + * start = end + 1 +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_13 = PyObject_Length(__pyx_v_contour); if (unlikely(__pyx_t_13 == ((Py_ssize_t)-1))) __PYX_ERR(0, 485, __pyx_L1_error) + __pyx_t_8 = PyLong_FromSsize_t(__pyx_t_13); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 485, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + + __pyx_t_2 = __Pyx_PyNumber_Subtract_object_object(__pyx_v_end, __pyx_v_start); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 485, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_11 = __Pyx_PyLong_AddObjC(__pyx_t_2, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 485, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_1 = __Pyx_PyObject_CompareBoolEq_int_object(__pyx_t_8, __pyx_t_11, Py_EQ); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 485, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + if (unlikely(!__pyx_t_1)) { + __Pyx_Raise(((PyObject *)(((PyTypeObject*)PyExc_AssertionError))), 0, 0, 0); + __PYX_ERR(0, 485, __pyx_L1_error) + } + + } + #else + if ((1)); else __PYX_ERR(0, 485, __pyx_L1_error) + #endif + + /* "fontTools/varLib/iup.py":486 + * ) + * assert len(contour) == end - start + 1 + * out.extend(contour) # <<<<<<<<<<<<<< + * start = end + 1 + * +*/ + __pyx_t_14 = __Pyx_PyList_Extend(__pyx_v_out, __pyx_v_contour); if (unlikely(__pyx_t_14 == ((int)-1))) __PYX_ERR(0, 486, __pyx_L1_error) + + + /* "fontTools/varLib/iup.py":487 + * assert len(contour) == end - start + 1 + * out.extend(contour) + * start = end + 1 # <<<<<<<<<<<<<< + * + * return out +*/ + __pyx_t_11 = __Pyx_PyLong_AddObjC(__pyx_v_end, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 487, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF_SET(__pyx_v_start, __pyx_t_11); + __pyx_t_11 = 0; + + /* "fontTools/varLib/iup.py":481 + * out = [] + * start = 0 + * for end in ends: # <<<<<<<<<<<<<< + * contour = iup_contour_optimize( + * deltas[start : end + 1], coords[start : end + 1], tolerance +*/ + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":489 + * start = end + 1 + * + * return out # <<<<<<<<<<<<<< +*/ + { + PyObject *__pyx_temp; + { + __pyx_temp = __pyx_r; + __Pyx_INCREF(__pyx_v_out); + __pyx_r = __pyx_v_out; + } + __Pyx_XDECREF(__pyx_temp); + } + goto __pyx_L0; + + /* "fontTools/varLib/iup.py":463 + * + * + * def iup_delta_optimize( # <<<<<<<<<<<<<< + * deltas: _DeltaSegment, + * coords: _PointSegment, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_AddTraceback("fontTools.varLib.iup.iup_delta_optimize", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_n); + __Pyx_XDECREF(__pyx_v_out); + __Pyx_XDECREF(__pyx_v_start); + __Pyx_XDECREF(__pyx_v_end); + __Pyx_XDECREF(__pyx_v_contour); + __Pyx_XDECREF(__pyx_v_ends); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +/* #### Code section: module_exttypes ### */ + +static PyObject *__pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_defaults(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + CYTHON_UNUSED PyObject *const *args, CYTHON_UNUSED Py_ssize_t nargs, CYTHON_UNUSED PyObject *kwnames +#else + CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k +#endif +) { + return o; +} + +static PyObject *__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_defaults(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +) { + PyObject *o; + o = __Pyx_AllocateExtensionType(t, 1); + if (unlikely(!o)) return 0; + return __pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_defaults(o, +#if CYTHON_VECTORCALL_TPNEW + args, nargs, kwnames +#else + a, k +#endif +); +} + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_6varLib_3iup___pyx_defaults(PyTypeObject *t, PyObject *a, PyObject *k) { + return __Pyx_CallTpnewAsVectorcall(__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_defaults, t, a, k); +} +#endif + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_defaults(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames) { + if (unlikely((PyTypeObject*)t != __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults || __Pyx_PyType_HasFeature((PyTypeObject*)t, Py_TPFLAGS_IS_ABSTRACT))) { + return __Pyx_CallNewInitFromVectorcall((PyTypeObject*)t, args, nargsf, kwnames); + } + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *o = __pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_defaults((PyTypeObject*)t, args, nargs, kwnames); + return o; +} +#endif + +static void __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_defaults(PyObject *o) { + struct __pyx_defaults *p = (struct __pyx_defaults *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_defaults) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->arg0); + PyTypeObject *tp = Py_TYPE(o); + #if CYTHON_USE_TYPE_SLOTS + (*tp->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free); + if (tp_free) tp_free(o); + } + #endif + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(tp); + #endif +} + +static int __pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_defaults(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_defaults *p = (struct __pyx_defaults *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->arg0) { + e = (*v)(p->arg0, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_9fontTools_6varLib_3iup___pyx_defaults(PyObject *o) { + PyObject* tmp; + struct __pyx_defaults *p = (struct __pyx_defaults *)o; + tmp = ((PyObject*)p->arg0); + p->arg0 = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9fontTools_6varLib_3iup___pyx_defaults_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_defaults}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_defaults}, + {Py_tp_clear, (void *)__pyx_tp_clear_9fontTools_6varLib_3iup___pyx_defaults}, + {Py_tp_new, (void *)__pyx_tp_new_9fontTools_6varLib_3iup___pyx_defaults}, + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + {Py_tp_vectorcall, (void *)__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_defaults}, + #endif + #endif + {0, 0}, +}; +static PyType_Spec __pyx_type_9fontTools_6varLib_3iup___pyx_defaults_spec = { + "fontTools.varLib.iup.__pyx_defaults", + sizeof(struct __pyx_defaults), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, + __pyx_type_9fontTools_6varLib_3iup___pyx_defaults_slots, +}; +#else + +static PyTypeObject __pyx_type_9fontTools_6varLib_3iup___pyx_defaults = { + PyVarObject_HEAD_INIT(0, 0) + "fontTools.varLib.iup.""__pyx_defaults", /*tp_name*/ + sizeof(struct __pyx_defaults), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_defaults, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_defaults, /*tp_traverse*/ + __pyx_tp_clear_9fontTools_6varLib_3iup___pyx_defaults, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9fontTools_6varLib_3iup___pyx_defaults, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + __pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_defaults, /*tp_vectorcall*/ + #else + NULL, /*tp_vectorcall*/ + #endif + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyObject *__pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + CYTHON_UNUSED PyObject *const *args, CYTHON_UNUSED Py_ssize_t nargs, CYTHON_UNUSED PyObject *kwnames +#else + CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k +#endif +) { + return o; +} + +static PyObject *__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +) { + PyObject *o; + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between > 0) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(t, __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between)))) + { + o = (PyObject*)__pyx_mstate_global->__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between[--__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between]; + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(Py_TYPE(o)); + #endif + memset(o, 0, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between)); + #if CYTHON_COMPILING_IN_LIMITED_API + (void) PyObject_Init(o, t); + #else + (void) PyObject_INIT(o, t); + #endif + PyObject_GC_Track(o); + } else + #endif + { + o = __Pyx_AllocateExtensionType(t, 1); + } + if (unlikely(!o)) return 0; + return __pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(o, +#if CYTHON_VECTORCALL_TPNEW + args, nargs, kwnames +#else + a, k +#endif +); +} + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyTypeObject *t, PyObject *a, PyObject *k) { + return __Pyx_CallTpnewAsVectorcall(__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between, t, a, k); +} +#endif + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames) { + if (unlikely((PyTypeObject*)t != __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between || __Pyx_PyType_HasFeature((PyTypeObject*)t, Py_TPFLAGS_IS_ABSTRACT))) { + return __Pyx_CallNewInitFromVectorcall((PyTypeObject*)t, args, nargsf, kwnames); + } + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *o = __pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between((PyTypeObject*)t, args, nargs, kwnames); + return o; +} +#endif + +static void __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyObject *o) { + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *p = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->__pyx_v_tolerance); + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between < 8) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(Py_TYPE(o), __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between)))) + { + __pyx_mstate_global->__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between[__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between++] = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *)o); + } else + #endif + { + PyTypeObject *tp = Py_TYPE(o); + #if CYTHON_USE_TYPE_SLOTS + (*tp->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free); + if (tp_free) tp_free(o); + } + #endif + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(tp); + #endif + } +} + +static int __pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *p = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->__pyx_v_tolerance) { + e = (*v)(p->__pyx_v_tolerance, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *p = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between *)o; + tmp = ((PyObject*)p->__pyx_v_tolerance); + p->__pyx_v_tolerance = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between}, + {Py_tp_clear, (void *)__pyx_tp_clear_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between}, + {Py_tp_new, (void *)__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between}, + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + {Py_tp_vectorcall, (void *)__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between}, + #endif + #endif + {0, 0}, +}; +static PyType_Spec __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between_spec = { + "fontTools.varLib.iup.__pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between", + sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, + __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between_slots, +}; +#else + +static PyTypeObject __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between = { + PyVarObject_HEAD_INIT(0, 0) + "fontTools.varLib.iup.""__pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between", /*tp_name*/ + sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between, /*tp_traverse*/ + __pyx_tp_clear_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + __pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between, /*tp_vectorcall*/ + #else + NULL, /*tp_vectorcall*/ + #endif + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyObject *__pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + CYTHON_UNUSED PyObject *const *args, CYTHON_UNUSED Py_ssize_t nargs, CYTHON_UNUSED PyObject *kwnames +#else + CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k +#endif +) { + return o; +} + +static PyObject *__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +) { + PyObject *o; + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr > 0) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(t, __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr)))) + { + o = (PyObject*)__pyx_mstate_global->__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr[--__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr]; + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(Py_TYPE(o)); + #endif + memset(o, 0, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr)); + #if CYTHON_COMPILING_IN_LIMITED_API + (void) PyObject_Init(o, t); + #else + (void) PyObject_INIT(o, t); + #endif + PyObject_GC_Track(o); + } else + #endif + { + o = __Pyx_AllocateExtensionType(t, 1); + } + if (unlikely(!o)) return 0; + return __pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(o, +#if CYTHON_VECTORCALL_TPNEW + args, nargs, kwnames +#else + a, k +#endif +); +} + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(PyTypeObject *t, PyObject *a, PyObject *k) { + return __Pyx_CallTpnewAsVectorcall(__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr, t, a, k); +} +#endif + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames) { + if (unlikely((PyTypeObject*)t != __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr || __Pyx_PyType_HasFeature((PyTypeObject*)t, Py_TPFLAGS_IS_ABSTRACT))) { + return __Pyx_CallNewInitFromVectorcall((PyTypeObject*)t, args, nargsf, kwnames); + } + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *o = __pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr((PyTypeObject*)t, args, nargs, kwnames); + return o; +} +#endif + +static void __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(PyObject *o) { + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr *p = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->__pyx_outer_scope); + Py_CLEAR(p->__pyx_genexpr_arg_0); + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr < 8) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(Py_TYPE(o), __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr)))) + { + __pyx_mstate_global->__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr[__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr++] = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr *)o); + } else + #endif + { + PyTypeObject *tp = Py_TYPE(o); + #if CYTHON_USE_TYPE_SLOTS + (*tp->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free); + if (tp_free) tp_free(o); + } + #endif + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(tp); + #endif + } +} + +static int __pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr *p = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->__pyx_outer_scope) { + e = (*v)(((PyObject *)p->__pyx_outer_scope), a); if (e) return e; + } + if (p->__pyx_genexpr_arg_0) { + e = (*v)(p->__pyx_genexpr_arg_0, a); if (e) return e; + } + return 0; +} +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr}, + {Py_tp_new, (void *)__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr}, + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + {Py_tp_vectorcall, (void *)__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr}, + #endif + #endif + {0, 0}, +}; +static PyType_Spec __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr_spec = { + "fontTools.varLib.iup.__pyx_scope_struct_1_genexpr", + sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, + __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr_slots, +}; +#else + +static PyTypeObject __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr = { + PyVarObject_HEAD_INIT(0, 0) + "fontTools.varLib.iup.""__pyx_scope_struct_1_genexpr", /*tp_name*/ + sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + __pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr, /*tp_vectorcall*/ + #else + NULL, /*tp_vectorcall*/ + #endif + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyObject *__pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + CYTHON_UNUSED PyObject *const *args, CYTHON_UNUSED Py_ssize_t nargs, CYTHON_UNUSED PyObject *kwnames +#else + CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k +#endif +) { + return o; +} + +static PyObject *__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +) { + PyObject *o; + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize > 0) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(t, __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize)))) + { + o = (PyObject*)__pyx_mstate_global->__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize[--__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize]; + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(Py_TYPE(o)); + #endif + memset(o, 0, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize)); + #if CYTHON_COMPILING_IN_LIMITED_API + (void) PyObject_Init(o, t); + #else + (void) PyObject_INIT(o, t); + #endif + PyObject_GC_Track(o); + } else + #endif + { + o = __Pyx_AllocateExtensionType(t, 1); + } + if (unlikely(!o)) return 0; + return __pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(o, +#if CYTHON_VECTORCALL_TPNEW + args, nargs, kwnames +#else + a, k +#endif +); +} + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(PyTypeObject *t, PyObject *a, PyObject *k) { + return __Pyx_CallTpnewAsVectorcall(__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize, t, a, k); +} +#endif + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames) { + if (unlikely((PyTypeObject*)t != __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize || __Pyx_PyType_HasFeature((PyTypeObject*)t, Py_TPFLAGS_IS_ABSTRACT))) { + return __Pyx_CallNewInitFromVectorcall((PyTypeObject*)t, args, nargsf, kwnames); + } + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *o = __pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize((PyTypeObject*)t, args, nargs, kwnames); + return o; +} +#endif + +static void __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(PyObject *o) { + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *p = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->__pyx_v_d0); + Py_CLEAR(p->__pyx_v_tolerance); + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize < 8) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(Py_TYPE(o), __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize)))) + { + __pyx_mstate_global->__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize[__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize++] = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *)o); + } else + #endif + { + PyTypeObject *tp = Py_TYPE(o); + #if CYTHON_USE_TYPE_SLOTS + (*tp->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free); + if (tp_free) tp_free(o); + } + #endif + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(tp); + #endif + } +} + +static int __pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *p = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->__pyx_v_d0) { + e = (*v)(p->__pyx_v_d0, a); if (e) return e; + } + if (p->__pyx_v_tolerance) { + e = (*v)(p->__pyx_v_tolerance, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *p = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize *)o; + tmp = ((PyObject*)p->__pyx_v_d0); + p->__pyx_v_d0 = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->__pyx_v_tolerance); + p->__pyx_v_tolerance = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize}, + {Py_tp_clear, (void *)__pyx_tp_clear_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize}, + {Py_tp_new, (void *)__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize}, + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + {Py_tp_vectorcall, (void *)__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize}, + #endif + #endif + {0, 0}, +}; +static PyType_Spec __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize_spec = { + "fontTools.varLib.iup.__pyx_scope_struct_2_iup_contour_optimize", + sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, + __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize_slots, +}; +#else + +static PyTypeObject __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize = { + PyVarObject_HEAD_INIT(0, 0) + "fontTools.varLib.iup.""__pyx_scope_struct_2_iup_contour_optimize", /*tp_name*/ + sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize, /*tp_traverse*/ + __pyx_tp_clear_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + __pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize, /*tp_vectorcall*/ + #else + NULL, /*tp_vectorcall*/ + #endif + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyObject *__pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + CYTHON_UNUSED PyObject *const *args, CYTHON_UNUSED Py_ssize_t nargs, CYTHON_UNUSED PyObject *kwnames +#else + CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k +#endif +) { + return o; +} + +static PyObject *__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +) { + PyObject *o; + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr > 0) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(t, __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr)))) + { + o = (PyObject*)__pyx_mstate_global->__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr[--__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr]; + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(Py_TYPE(o)); + #endif + memset(o, 0, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr)); + #if CYTHON_COMPILING_IN_LIMITED_API + (void) PyObject_Init(o, t); + #else + (void) PyObject_INIT(o, t); + #endif + PyObject_GC_Track(o); + } else + #endif + { + o = __Pyx_AllocateExtensionType(t, 1); + } + if (unlikely(!o)) return 0; + return __pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(o, +#if CYTHON_VECTORCALL_TPNEW + args, nargs, kwnames +#else + a, k +#endif +); +} + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(PyTypeObject *t, PyObject *a, PyObject *k) { + return __Pyx_CallTpnewAsVectorcall(__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr, t, a, k); +} +#endif + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames) { + if (unlikely((PyTypeObject*)t != __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr || __Pyx_PyType_HasFeature((PyTypeObject*)t, Py_TPFLAGS_IS_ABSTRACT))) { + return __Pyx_CallNewInitFromVectorcall((PyTypeObject*)t, args, nargsf, kwnames); + } + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *o = __pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr((PyTypeObject*)t, args, nargs, kwnames); + return o; +} +#endif + +static void __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(PyObject *o) { + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr *p = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->__pyx_outer_scope); + Py_CLEAR(p->__pyx_genexpr_arg_0); + Py_CLEAR(p->__pyx_v_p); + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr < 8) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(Py_TYPE(o), __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr)))) + { + __pyx_mstate_global->__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr[__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr++] = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr *)o); + } else + #endif + { + PyTypeObject *tp = Py_TYPE(o); + #if CYTHON_USE_TYPE_SLOTS + (*tp->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free); + if (tp_free) tp_free(o); + } + #endif + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(tp); + #endif + } +} + +static int __pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr *p = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->__pyx_outer_scope) { + e = (*v)(((PyObject *)p->__pyx_outer_scope), a); if (e) return e; + } + if (p->__pyx_genexpr_arg_0) { + e = (*v)(p->__pyx_genexpr_arg_0, a); if (e) return e; + } + if (p->__pyx_v_p) { + e = (*v)(p->__pyx_v_p, a); if (e) return e; + } + return 0; +} +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr}, + {Py_tp_new, (void *)__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr}, + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + {Py_tp_vectorcall, (void *)__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr}, + #endif + #endif + {0, 0}, +}; +static PyType_Spec __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr_spec = { + "fontTools.varLib.iup.__pyx_scope_struct_3_genexpr", + sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, + __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr_slots, +}; +#else + +static PyTypeObject __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr = { + PyVarObject_HEAD_INIT(0, 0) + "fontTools.varLib.iup.""__pyx_scope_struct_3_genexpr", /*tp_name*/ + sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + __pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr, /*tp_vectorcall*/ + #else + NULL, /*tp_vectorcall*/ + #endif + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyObject *__pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(PyObject *o, +#if CYTHON_VECTORCALL_TPNEW + CYTHON_UNUSED PyObject *const *args, CYTHON_UNUSED Py_ssize_t nargs, CYTHON_UNUSED PyObject *kwnames +#else + CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k +#endif +) { + return o; +} + +static PyObject *__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(PyTypeObject *t, +#if CYTHON_VECTORCALL_TPNEW + PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames +#else + PyObject *a, PyObject *k +#endif +) { + PyObject *o; + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr > 0) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(t, __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr)))) + { + o = (PyObject*)__pyx_mstate_global->__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr[--__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr]; + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(Py_TYPE(o)); + #endif + memset(o, 0, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr)); + #if CYTHON_COMPILING_IN_LIMITED_API + (void) PyObject_Init(o, t); + #else + (void) PyObject_INIT(o, t); + #endif + PyObject_GC_Track(o); + } else + #endif + { + o = __Pyx_AllocateExtensionType(t, 1); + } + if (unlikely(!o)) return 0; + return __pyx_tp_new__initialisation_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(o, +#if CYTHON_VECTORCALL_TPNEW + args, nargs, kwnames +#else + a, k +#endif +); +} + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(PyTypeObject *t, PyObject *a, PyObject *k) { + return __Pyx_CallTpnewAsVectorcall(__pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr, t, a, k); +} +#endif + +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(PyObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames) { + if (unlikely((PyTypeObject*)t != __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr || __Pyx_PyType_HasFeature((PyTypeObject*)t, Py_TPFLAGS_IS_ABSTRACT))) { + return __Pyx_CallNewInitFromVectorcall((PyTypeObject*)t, args, nargsf, kwnames); + } + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *o = __pyx_tp_new_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr((PyTypeObject*)t, args, nargs, kwnames); + return o; +} +#endif + +static void __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(PyObject *o) { + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr *p = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(__Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->__pyx_outer_scope); + Py_CLEAR(p->__pyx_genexpr_arg_0); + Py_CLEAR(p->__pyx_v_d); + #if CYTHON_USE_FREELISTS + if (likely((int)(__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr < 8) & __PYX_CHECK_FINAL_TYPE_FOR_FREELISTS(Py_TYPE(o), __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr, sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr)))) + { + __pyx_mstate_global->__pyx_freelist_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr[__pyx_mstate_global->__pyx_freecount_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr++] = ((struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr *)o); + } else + #endif + { + PyTypeObject *tp = Py_TYPE(o); + #if CYTHON_USE_TYPE_SLOTS + (*tp->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(tp, Py_tp_free); + if (tp_free) tp_free(o); + } + #endif + #if CYTHON_USE_TYPE_SPECS + Py_DECREF(tp); + #endif + } +} + +static int __pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr *p = (struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->__pyx_outer_scope) { + e = (*v)(((PyObject *)p->__pyx_outer_scope), a); if (e) return e; + } + if (p->__pyx_genexpr_arg_0) { + e = (*v)(p->__pyx_genexpr_arg_0, a); if (e) return e; + } + if (p->__pyx_v_d) { + e = (*v)(p->__pyx_v_d, a); if (e) return e; + } + return 0; +} +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr}, + {Py_tp_new, (void *)__pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr}, + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + {Py_tp_vectorcall, (void *)__pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr}, + #endif + #endif + {0, 0}, +}; +static PyType_Spec __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr_spec = { + "fontTools.varLib.iup.__pyx_scope_struct_4_genexpr", + sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, + __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr_slots, +}; +#else + +static PyTypeObject __pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr = { + PyVarObject_HEAD_INIT(0, 0) + "fontTools.varLib.iup.""__pyx_scope_struct_4_genexpr", /*tp_name*/ + sizeof(struct __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr, /*tp_dealloc*/ + 0, /*tp_vectorcall_offset*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + 0, /*tp_doc*/ + __pyx_tp_traverse_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) && (!CYTHON_COMPILING_IN_LIMITED_API || __PYX_LIMITED_VERSION_HEX >= 0x030E0000) + #if CYTHON_VECTORCALL_TPNEW + __pyx_tp_vectorcall_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr, /*tp_vectorcall*/ + #else + NULL, /*tp_vectorcall*/ + #endif + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; +/* #### Code section: initfunc_declarations ### */ +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitAfterSharedUtility(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Global_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Variable_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Function_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Exttype___pyx_defaults(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Type_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Variable_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_Function_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate); /*proto*/ +/* #### Code section: init_module ### */ + +static int __Pyx_modinit_Global_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Global_init_code", 0); + /*--- Global init code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_Variable_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_Function_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_Exttype___pyx_defaults(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Exttype___pyx_defaults", 0); + /*--- Exttype __pyx_defaults ---*/ + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9fontTools_6varLib_3iup___pyx_defaults_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults)) __PYX_ERR(0, 292, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults = &__pyx_type_9fontTools_6varLib_3iup___pyx_defaults; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults) < (0)) __PYX_ERR(0, 292, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults->tp_dictoffset && __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults->tp_getattro = PyObject_GenericGetAttr; + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between", 0); + /*--- Exttype __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between ---*/ + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between)) __PYX_ERR(0, 168, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between = &__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between) < (0)) __PYX_ERR(0, 168, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between->tp_dictoffset && __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between->tp_getattro = PyObject_GenericGetAttr; + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr", 0); + /*--- Exttype __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr ---*/ + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr)) __PYX_ERR(0, 196, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr = &__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr) < (0)) __PYX_ERR(0, 196, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr->tp_dictoffset && __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr->tp_getattro = PyObject_GenericGetAttr; + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize", 0); + /*--- Exttype __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize ---*/ + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize)) __PYX_ERR(0, 362, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize = &__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize) < (0)) __PYX_ERR(0, 362, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize->tp_dictoffset && __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize->tp_getattro = PyObject_GenericGetAttr; + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr", 0); + /*--- Exttype __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr ---*/ + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr)) __PYX_ERR(0, 377, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr = &__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr) < (0)) __PYX_ERR(0, 377, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr->tp_dictoffset && __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr->tp_getattro = PyObject_GenericGetAttr; + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr", 0); + /*--- Exttype __pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr ---*/ + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr)) __PYX_ERR(0, 386, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr = &__pyx_type_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr) < (0)) __PYX_ERR(0, 386, __pyx_L1_error) + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount((PyObject*)__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr); + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr->tp_dictoffset && __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr->tp_getattro = PyObject_GenericGetAttr; + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_Type_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Type_import_code", 0); + /*--- Type import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_Variable_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_Function_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_Function_import_code", 0); + /*--- Function import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec_iup(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec_iup}, + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + {Py_mod_gil, __Pyx_FREETHREADING_COMPATIBLE}, + #endif + #if PY_VERSION_HEX >= 0x030C0000 && CYTHON_USE_MODULE_STATE + {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}, + #endif + {0, NULL} +}; +#endif + +#ifdef __cplusplus +namespace { + struct PyModuleDef __pyx_moduledef = + #else + static struct PyModuleDef __pyx_moduledef = + #endif + { + PyModuleDef_HEAD_INIT, + "iup", + 0, /* m_doc */ + #if CYTHON_USE_MODULE_STATE + sizeof(__pyx_mstatetype), /* m_size */ + #else + (CYTHON_PEP489_MULTI_PHASE_INIT) ? 0 : -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + #if CYTHON_USE_MODULE_STATE + __pyx_m_traverse, /* m_traverse */ + __pyx_m_clear, /* m_clear */ + NULL /* m_free */ + #else + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ + #endif + }; + #ifdef __cplusplus +} /* anonymous namespace */ +#endif + +/* PyModInitFuncType */ +#ifndef CYTHON_NO_PYINIT_EXPORT + #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#else + #ifdef __cplusplus + #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * + #else + #define __Pyx_PyMODINIT_FUNC PyObject * + #endif +#endif + +__Pyx_PyMODINIT_FUNC PyInit_iup(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit_iup(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +/* ModuleCreationPEP489 */ +#if CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x030A0000 &&\ + (defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS))) +static PY_INT64_T __Pyx_GetCurrentInterpreterId(void) { + { + PyObject *module = PyImport_ImportModule("_interpreters"); // 3.13+ I think + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_Exception)) { + goto bad; // BaseException + } + PyErr_Clear(); // just try the 3.8-3.12 version + module = PyImport_ImportModule("_xxsubinterpreters"); + if (!module) goto bad; + } + PyObject *current = PyObject_CallMethod(module, "get_current", NULL); + Py_DECREF(module); + if (!current) goto bad; + if (PyTuple_Check(current)) { + PyObject *new_current = PySequence_GetItem(current, 0); + Py_DECREF(current); + current = new_current; + if (!new_current) goto bad; + } + long long as_c_int = PyLong_AsLongLong(current); + Py_DECREF(current); + return as_c_int; + } + bad: + PySys_WriteStderr("__Pyx_GetCurrentInterpreterId failed. Try setting the C define CYTHON_PEP489_MULTI_PHASE_INIT=0\n"); + return -1; +} +#endif +#if !CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + static PY_INT64_T main_interpreter_id = -1; +#if CYTHON_COMPILING_IN_GRAAL && defined(GRAALPY_VERSION_NUM) && GRAALPY_VERSION_NUM > 0x19000000 + PY_INT64_T current_id = GraalPyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_GRAAL + PY_INT64_T current_id = PyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_LIMITED_API && (__PYX_LIMITED_VERSION_HEX < 0x030A0000 &&\ + (defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS))) + PY_INT64_T current_id = __Pyx_GetCurrentInterpreterId(); +#elif CYTHON_COMPILING_IN_LIMITED_API + PY_INT64_T current_id = PyInterpreterState_GetID(PyInterpreterState_Get()); +#else + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); +#endif + if (unlikely(current_id == -1)) { + return -1; + } + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return 0; + } else if (unlikely(main_interpreter_id != current_id)) { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +#endif +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) +{ + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { + result = PyDict_SetItemString(moddict, to_name, value); + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + CYTHON_UNUSED_VAR(def); + #if !CYTHON_USE_MODULE_STATE + if (__Pyx_check_single_interpreter()) + return NULL; + #endif + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec_iup(PyObject *__pyx_pyinit_module) +#endif +{ + int stringtab_initialized = 0; + #if CYTHON_USE_MODULE_STATE + int pystate_addmodule_run = 0; + #endif + __pyx_mstatetype *__pyx_mstate = NULL; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module 'iup' has already been imported. Re-initialisation is not supported."); + return -1; + } + #else + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_t_1 = __pyx_pyinit_module; + Py_INCREF(__pyx_t_1); + #else + __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #if CYTHON_USE_MODULE_STATE + { + int add_module_result = __Pyx_State_AddModule(__pyx_t_1, &__pyx_moduledef); + __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "iup" pseudovariable */ + if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + pystate_addmodule_run = 1; + } + #else + __pyx_m = __pyx_t_1; + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + PyUnstable_Module_SetGIL(__pyx_m, Py_MOD_GIL_USED); + #endif + __pyx_mstate = __pyx_mstate_global; + CYTHON_UNUSED_VAR(__pyx_t_1); + __pyx_mstate->__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_mstate->__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_mstate->__pyx_d); + __pyx_mstate->__pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_mstate->__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_cython_runtime = __Pyx_PyImport_AddModuleRef("cython_runtime"); if (unlikely(!__pyx_mstate->__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_mstate->__pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /* ImportRefnannyAPI */ + #if CYTHON_REFNANNY + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); + if (!__Pyx_RefNanny) { + if (PyErr_ExceptionMatches(PyExc_Exception)) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + } + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); + } + #endif + +__Pyx_RefNannySetupContext("PyInit_iup", 0); + __Pyx_init_runtime_version(); + if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_mstate->__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Library function declarations ---*/ + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + stringtab_initialized = 1; + if (__Pyx_InitGlobals() < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__pyx_module_is_main_fontTools__varLib__iup) { + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_name, __pyx_mstate_global->__pyx_n_u_main) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + } + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "fontTools.varLib.iup")) { + if (unlikely((PyDict_SetItemString(modules, "fontTools.varLib.iup", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_CreateCodeObjects(__pyx_mstate) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_Global_init_code(__pyx_mstate); + (void)__Pyx_modinit_Variable_export_code(__pyx_mstate); + (void)__Pyx_modinit_Function_export_code(__pyx_mstate); + /*--- Type init code ---*/ + if (unlikely((__Pyx_modinit_Exttype___pyx_defaults(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely((__Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct____pyx_f_9fontTools_6varLib_3iup_can_iup_in_between(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely((__Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_1_genexpr(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely((__Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_2_iup_contour_optimize(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely((__Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_3_genexpr(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely((__Pyx_modinit_Exttype___pyx_obj_9fontTools_6varLib_3iup___pyx_scope_struct_4_genexpr(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_Type_import_code(__pyx_mstate); + (void)__Pyx_modinit_Variable_import_code(__pyx_mstate); + (void)__Pyx_modinit_Function_import_code(__pyx_mstate); + if (__Pyx_InitAfterSharedUtility() < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Execution code ---*/ + + /* "fontTools/varLib/iup.py":1 + * try: # <<<<<<<<<<<<<< + * import cython + * except (AttributeError, ImportError): +*/ + { + (void)__pyx_t_1; (void)__pyx_t_2; (void)__pyx_t_3; /* mark used */ + /*try:*/ { + + /* "fontTools/varLib/iup.py":2 + * try: + * import cython # <<<<<<<<<<<<<< + * except (AttributeError, ImportError): + * # if cython not installed, use mock module with no-op decorators and types +*/ + } + } + + /* "fontTools/varLib/iup.py":6 + * # if cython not installed, use mock module with no-op decorators and types + * from fontTools.misc import cython + * COMPILED = cython.compiled # <<<<<<<<<<<<<< + * + * from typing import ( +*/ + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_COMPILED, Py_True) < (0)) __PYX_ERR(0, 6, __pyx_L1_error) + + /* "fontTools/varLib/iup.py":8 + * COMPILED = cython.compiled + * + * from typing import ( # <<<<<<<<<<<<<< + * Sequence, + * Tuple, +*/ + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_Sequence,__pyx_mstate_global->__pyx_n_u_Tuple,__pyx_mstate_global->__pyx_n_u_Union}; + __pyx_t_3 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_typing, __pyx_imported_names, 3, NULL, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 8, __pyx_L1_error) + } + __pyx_t_4 = __pyx_t_3; + __Pyx_GOTREF(__pyx_t_4); + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_Sequence,__pyx_mstate_global->__pyx_n_u_Tuple,__pyx_mstate_global->__pyx_n_u_Union}; + for (__pyx_t_5=0; __pyx_t_5 < 3; __pyx_t_5++) { + __pyx_t_6 = __Pyx_ImportFrom(__pyx_t_4, __pyx_imported_names[__pyx_t_5]); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_imported_names[__pyx_t_5], __pyx_t_6) < (0)) __PYX_ERR(0, 8, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":13 + * Union, + * ) + * from numbers import Integral, Real # <<<<<<<<<<<<<< + * + * _Point = Tuple[Real, Real] +*/ + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_Integral,__pyx_mstate_global->__pyx_n_u_Real}; + __pyx_t_3 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_numbers, __pyx_imported_names, 2, NULL, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 13, __pyx_L1_error) + } + __pyx_t_4 = __pyx_t_3; + __Pyx_GOTREF(__pyx_t_4); + { + PyObject* const __pyx_imported_names[] = {__pyx_mstate_global->__pyx_n_u_Integral,__pyx_mstate_global->__pyx_n_u_Real}; + for (__pyx_t_5=0; __pyx_t_5 < 2; __pyx_t_5++) { + __pyx_t_6 = __Pyx_ImportFrom(__pyx_t_4, __pyx_imported_names[__pyx_t_5]); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_imported_names[__pyx_t_5], __pyx_t_6) < (0)) __PYX_ERR(0, 13, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":15 + * from numbers import Integral, Real + * + * _Point = Tuple[Real, Real] # <<<<<<<<<<<<<< + * _Delta = Tuple[Real, Real] + * _PointSegment = Sequence[_Point] +*/ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_Tuple); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_Real); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_Real); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + { + PyObject* __pyx_temp[2] = {__pyx_t_6, __pyx_t_7}; + __pyx_t_8 = __Pyx_PyTuple_FromArray(__pyx_temp, 2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_PyObject_GetItem(__pyx_t_4, __pyx_t_8); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_Point, __pyx_t_7) < (0)) __PYX_ERR(0, 15, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "fontTools/varLib/iup.py":16 + * + * _Point = Tuple[Real, Real] + * _Delta = Tuple[Real, Real] # <<<<<<<<<<<<<< + * _PointSegment = Sequence[_Point] + * _DeltaSegment = Sequence[_Delta] +*/ + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_Tuple); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_Real); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_Real); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + { + PyObject* __pyx_temp[2] = {__pyx_t_8, __pyx_t_4}; + __pyx_t_6 = __Pyx_PyTuple_FromArray(__pyx_temp, 2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_GetItem(__pyx_t_7, __pyx_t_6); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_Delta, __pyx_t_4) < (0)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":17 + * _Point = Tuple[Real, Real] + * _Delta = Tuple[Real, Real] + * _PointSegment = Sequence[_Point] # <<<<<<<<<<<<<< + * _DeltaSegment = Sequence[_Delta] + * _DeltaOrNone = Union[_Delta, None] +*/ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_Sequence); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_Point); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetItem(__pyx_t_4, __pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_PointSegment, __pyx_t_7) < (0)) __PYX_ERR(0, 17, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "fontTools/varLib/iup.py":18 + * _Delta = Tuple[Real, Real] + * _PointSegment = Sequence[_Point] + * _DeltaSegment = Sequence[_Delta] # <<<<<<<<<<<<<< + * _DeltaOrNone = Union[_Delta, None] + * _DeltaOrNoneSegment = Sequence[_DeltaOrNone] +*/ + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_Sequence); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_Delta); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = __Pyx_PyObject_GetItem(__pyx_t_7, __pyx_t_6); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_DeltaSegment, __pyx_t_4) < (0)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":19 + * _PointSegment = Sequence[_Point] + * _DeltaSegment = Sequence[_Delta] + * _DeltaOrNone = Union[_Delta, None] # <<<<<<<<<<<<<< + * _DeltaOrNoneSegment = Sequence[_DeltaOrNone] + * _Endpoints = Sequence[Integral] +*/ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_Union); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 19, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_Delta); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 19, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + { + PyObject* __pyx_temp[2] = {__pyx_t_6, Py_None}; + __pyx_t_7 = __Pyx_PyTuple_FromArray(__pyx_temp, 2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 19, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_GetItem(__pyx_t_4, __pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 19, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_DeltaOrNone, __pyx_t_6) < (0)) __PYX_ERR(0, 19, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":20 + * _DeltaSegment = Sequence[_Delta] + * _DeltaOrNone = Union[_Delta, None] + * _DeltaOrNoneSegment = Sequence[_DeltaOrNone] # <<<<<<<<<<<<<< + * _Endpoints = Sequence[Integral] + * +*/ + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_Sequence); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_DeltaOrNone); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = __Pyx_PyObject_GetItem(__pyx_t_6, __pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_DeltaOrNoneSegment, __pyx_t_4) < (0)) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "fontTools/varLib/iup.py":21 + * _DeltaOrNone = Union[_Delta, None] + * _DeltaOrNoneSegment = Sequence[_DeltaOrNone] + * _Endpoints = Sequence[Integral] # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_Sequence); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_Integral); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = __Pyx_PyObject_GetItem(__pyx_t_4, __pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_Endpoints, __pyx_t_6) < (0)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":24 + * + * + * MAX_LOOKBACK = 8 # <<<<<<<<<<<<<< + * + * +*/ + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_MAX_LOOKBACK, __pyx_mstate_global->__pyx_int_8) < (0)) __PYX_ERR(0, 24, __pyx_L1_error) + + /* "fontTools/varLib/iup.py":90 + * + * + * def iup_contour(deltas: _DeltaOrNoneSegment, coords: _PointSegment) -> _DeltaSegment: # <<<<<<<<<<<<<< + * """For the contour given in `coords`, interpolate any missing + * delta values in delta vector `deltas`. +*/ + __pyx_t_6 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_deltas, __pyx_mstate_global->__pyx_n_u_DeltaOrNoneSegment) < (0)) __PYX_ERR(0, 90, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_coords, __pyx_mstate_global->__pyx_n_u_PointSegment) < (0)) __PYX_ERR(0, 90, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_return, __pyx_mstate_global->__pyx_n_u_DeltaSegment) < (0)) __PYX_ERR(0, 90, __pyx_L1_error) + __pyx_t_7 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6varLib_3iup_1iup_contour, 0, __pyx_mstate_global->__pyx_n_u_iup_contour, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_varLib_iup, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[3])); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_7); + #endif + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_7, __pyx_t_6); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_iup_contour, __pyx_t_7) < (0)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "fontTools/varLib/iup.py":142 + * + * + * def iup_delta( # <<<<<<<<<<<<<< + * deltas: _DeltaOrNoneSegment, coords: _PointSegment, ends: _Endpoints + * ) -> _DeltaSegment: +*/ + __pyx_t_7 = __Pyx_PyDict_NewPresized(4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_deltas, __pyx_mstate_global->__pyx_n_u_DeltaOrNoneSegment) < (0)) __PYX_ERR(0, 142, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_coords, __pyx_mstate_global->__pyx_n_u_PointSegment) < (0)) __PYX_ERR(0, 142, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_ends, __pyx_mstate_global->__pyx_n_u_Endpoints) < (0)) __PYX_ERR(0, 142, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_return, __pyx_mstate_global->__pyx_n_u_DeltaSegment) < (0)) __PYX_ERR(0, 142, __pyx_L1_error) + __pyx_t_6 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6varLib_3iup_3iup_delta, 0, __pyx_mstate_global->__pyx_n_u_iup_delta, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_varLib_iup, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[4])); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_6); + #endif + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_6, __pyx_t_7); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_iup_delta, __pyx_t_6) < (0)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":201 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * cj=cython.double, + * dj=cython.double, +*/ + __pyx_t_6 = __Pyx_PyDict_NewPresized(4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 201, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_deltas, __pyx_mstate_global->__pyx_n_u_DeltaSegment) < (0)) __PYX_ERR(0, 201, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_coords, __pyx_mstate_global->__pyx_n_u_PointSegment) < (0)) __PYX_ERR(0, 201, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_tolerance, __pyx_mstate_global->__pyx_n_u_Real) < (0)) __PYX_ERR(0, 201, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_return, __pyx_mstate_global->__pyx_n_u_set) < (0)) __PYX_ERR(0, 201, __pyx_L1_error) + __pyx_t_7 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6varLib_3iup_5_iup_contour_bound_forced_set, 0, __pyx_mstate_global->__pyx_n_u_iup_contour_bound_forced_set, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_varLib_iup, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[5])); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 201, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_7); + #endif + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_7, __pyx_mstate_global->__pyx_tuple[2]); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_7, __pyx_t_6); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_iup_contour_bound_forced_set, __pyx_t_7) < (0)) __PYX_ERR(0, 201, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "fontTools/varLib/iup.py":292 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * i=cython.int, + * j=cython.int, +*/ + __pyx_t_7 = __Pyx_PyDict_NewPresized(4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 292, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_deltas, __pyx_mstate_global->__pyx_n_u_DeltaSegment) < (0)) __PYX_ERR(0, 292, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_coords, __pyx_mstate_global->__pyx_n_u_PointSegment) < (0)) __PYX_ERR(0, 292, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_tolerance, __pyx_mstate_global->__pyx_n_u_Real) < (0)) __PYX_ERR(0, 292, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_lookback, __pyx_mstate_global->__pyx_n_u_Integral) < (0)) __PYX_ERR(0, 292, __pyx_L1_error) + __pyx_t_6 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6varLib_3iup_7_iup_contour_optimize_dp, 0, __pyx_mstate_global->__pyx_n_u_iup_contour_optimize_dp, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_varLib_iup, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[6])); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 292, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_6); + #endif + if (!__Pyx_CyFunction_InitDefaults(__pyx_t_6, __pyx_mstate_global->__pyx_ptype_9fontTools_6varLib_3iup___pyx_defaults)) __PYX_ERR(0, 292, __pyx_L1_error) + __pyx_t_4 = PySet_New(0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 304, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_CyFunction_Defaults(struct __pyx_defaults, __pyx_t_6)->arg0 = ((PyObject*)__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __pyx_t_4 = 0; + __Pyx_CyFunction_SetDefaultsGetter(__pyx_t_6, __pyx_pf_9fontTools_6varLib_3iup_16__defaults__); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_6, __pyx_t_7); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_iup_contour_optimize_dp, __pyx_t_6) < (0)) __PYX_ERR(0, 292, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":345 + * + * + * def _rot_list(l: list, k: int): # <<<<<<<<<<<<<< + * """Rotate list by k items forward. Ie. item at position 0 will be + * at position k in returned list. Negative k is allowed.""" +*/ + __pyx_t_6 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 345, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_l, __pyx_mstate_global->__pyx_n_u_list) < (0)) __PYX_ERR(0, 345, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_k, __pyx_mstate_global->__pyx_n_u_int) < (0)) __PYX_ERR(0, 345, __pyx_L1_error) + __pyx_t_7 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6varLib_3iup_9_rot_list, 0, __pyx_mstate_global->__pyx_n_u_rot_list, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_varLib_iup, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[7])); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 345, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_7); + #endif + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_7, __pyx_t_6); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_rot_list, __pyx_t_7) < (0)) __PYX_ERR(0, 345, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "fontTools/varLib/iup.py":355 + * + * + * def _rot_set(s: set, k: int, n: int): # <<<<<<<<<<<<<< + * k %= n + * if not k: +*/ + __pyx_t_7 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 355, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_s, __pyx_mstate_global->__pyx_n_u_set) < (0)) __PYX_ERR(0, 355, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_k, __pyx_mstate_global->__pyx_n_u_int) < (0)) __PYX_ERR(0, 355, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_n, __pyx_mstate_global->__pyx_n_u_int) < (0)) __PYX_ERR(0, 355, __pyx_L1_error) + __pyx_t_6 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6varLib_3iup_11_rot_set, 0, __pyx_mstate_global->__pyx_n_u_rot_set, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_varLib_iup, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[8])); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 355, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_6); + #endif + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_6, __pyx_t_7); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_rot_set, __pyx_t_6) < (0)) __PYX_ERR(0, 355, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":362 + * + * + * def iup_contour_optimize( # <<<<<<<<<<<<<< + * deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0.0 + * ) -> _DeltaOrNoneSegment: +*/ + __pyx_t_6 = __Pyx_PyDict_NewPresized(4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 362, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_deltas, __pyx_mstate_global->__pyx_n_u_DeltaSegment) < (0)) __PYX_ERR(0, 362, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_coords, __pyx_mstate_global->__pyx_n_u_PointSegment) < (0)) __PYX_ERR(0, 362, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_tolerance, __pyx_mstate_global->__pyx_n_u_Real) < (0)) __PYX_ERR(0, 362, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_return, __pyx_mstate_global->__pyx_n_u_DeltaOrNoneSegment) < (0)) __PYX_ERR(0, 362, __pyx_L1_error) + __pyx_t_7 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6varLib_3iup_13iup_contour_optimize, 0, __pyx_mstate_global->__pyx_n_u_iup_contour_optimize, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_varLib_iup, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[9])); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 362, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_7); + #endif + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_7, __pyx_mstate_global->__pyx_tuple[3]); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_7, __pyx_t_6); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_iup_contour_optimize, __pyx_t_7) < (0)) __PYX_ERR(0, 362, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "fontTools/varLib/iup.py":463 + * + * + * def iup_delta_optimize( # <<<<<<<<<<<<<< + * deltas: _DeltaSegment, + * coords: _PointSegment, +*/ + __pyx_t_7 = __Pyx_PyDict_NewPresized(5); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 463, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_deltas, __pyx_mstate_global->__pyx_n_u_DeltaSegment) < (0)) __PYX_ERR(0, 463, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_coords, __pyx_mstate_global->__pyx_n_u_PointSegment) < (0)) __PYX_ERR(0, 463, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_ends, __pyx_mstate_global->__pyx_n_u_Endpoints) < (0)) __PYX_ERR(0, 463, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_tolerance, __pyx_mstate_global->__pyx_n_u_Real) < (0)) __PYX_ERR(0, 463, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_return, __pyx_mstate_global->__pyx_n_u_DeltaOrNoneSegment) < (0)) __PYX_ERR(0, 463, __pyx_L1_error) + __pyx_t_6 = __Pyx_CyFunction_New(&__pyx_mdef_9fontTools_6varLib_3iup_15iup_delta_optimize, 0, __pyx_mstate_global->__pyx_n_u_iup_delta_optimize, NULL, __pyx_mstate_global->__pyx_n_u_fontTools_varLib_iup, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[10])); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 463, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030E0000 + PyUnstable_Object_EnableDeferredRefcount(__pyx_t_6); + #endif + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_6, __pyx_mstate_global->__pyx_tuple[3]); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_6, __pyx_t_7); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_iup_delta_optimize, __pyx_t_6) < (0)) __PYX_ERR(0, 463, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "fontTools/varLib/iup.py":1 + * try: # <<<<<<<<<<<<<< + * import cython + * except (AttributeError, ImportError): +*/ + __pyx_t_6 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_test, __pyx_t_6) < (0)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + if (__pyx_m) { + if (__pyx_mstate->__pyx_d && stringtab_initialized) { + __Pyx_AddTraceback("init fontTools.varLib.iup", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + #if !CYTHON_USE_MODULE_STATE + Py_CLEAR(__pyx_m); + #else + Py_DECREF(__pyx_m); + if (pystate_addmodule_run) { + PyObject *tp, *value, *tb; + __Pyx_PyErr_FetchException(&tp, &value, &tb); + __Pyx_State_RemoveModule(&__pyx_moduledef); + __Pyx_PyErr_RestoreException(tp, value, tb); + } + #endif + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init fontTools.varLib.iup"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #else + return __pyx_m; + #endif +} +/* #### Code section: pystring_table ### */ +/* #### Code section: cached_builtins ### */ + +static int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate) { + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + __pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_zip); if (!__pyx_builtin_zip) __PYX_ERR(0, 87, __pyx_L1_error) + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(0, 102, __pyx_L1_error) + __pyx_builtin_max = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_max); if (!__pyx_builtin_max) __PYX_ERR(0, 403, __pyx_L1_error) + + /* Cached unbound methods */ + __pyx_mstate->__pyx_umethod_PyDict_Type_items.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_items.method_name = &__pyx_mstate->__pyx_n_u_items; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.method_name = &__pyx_mstate->__pyx_n_u_pop; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_values.method_name = &__pyx_mstate->__pyx_n_u_values; + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cached_constants ### */ + +static int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "fontTools/varLib/iup.py":49 + * # rd1 = reference delta 1 + * out_arrays = [None, None] + * for j in 0, 1: # <<<<<<<<<<<<<< + * out_arrays[j] = out = [] + * x1, x2, d1, d2 = rc1[j], rc2[j], rd1[j], rd2[j] +*/ + { + PyObject* __pyx_temp[2] = {__pyx_mstate_global->__pyx_int_0, __pyx_mstate_global->__pyx_int_1}; + __pyx_mstate_global->__pyx_tuple[0] = __Pyx_PyTuple_FromArray(__pyx_temp, 2); if (unlikely(!__pyx_mstate_global->__pyx_tuple[0])) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[0]); + } + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[0]); + + /* "fontTools/varLib/iup.py":105 + * if not indices: + * # All deltas are None. Return 0,0 for all. + * return [(0, 0)] * n # <<<<<<<<<<<<<< + * + * out = [] +*/ + { + PyObject* __pyx_temp[2] = {__pyx_mstate_global->__pyx_int_0, __pyx_mstate_global->__pyx_int_0}; + __pyx_mstate_global->__pyx_tuple[1] = __Pyx_PyTuple_FromArray(__pyx_temp, 2); if (unlikely(!__pyx_mstate_global->__pyx_tuple[1])) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[1]); + } + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[1]); + + /* "fontTools/varLib/iup.py":201 + * + * + * @cython.locals( # <<<<<<<<<<<<<< + * cj=cython.double, + * dj=cython.double, +*/ + { + PyObject* __pyx_temp[1] = {((PyObject*)__pyx_mstate_global->__pyx_int_0)}; + __pyx_mstate_global->__pyx_tuple[2] = __Pyx_PyTuple_FromArray(__pyx_temp, 1); if (unlikely(!__pyx_mstate_global->__pyx_tuple[2])) __PYX_ERR(0, 201, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[2]); + } + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[2]); + + /* "fontTools/varLib/iup.py":362 + * + * + * def iup_contour_optimize( # <<<<<<<<<<<<<< + * deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0.0 + * ) -> _DeltaOrNoneSegment: +*/ + { + PyObject* __pyx_temp[1] = {((PyObject*)__pyx_mstate_global->__pyx_float_0_0)}; + __pyx_mstate_global->__pyx_tuple[3] = __Pyx_PyTuple_FromArray(__pyx_temp, 1); if (unlikely(!__pyx_mstate_global->__pyx_tuple[3])) __PYX_ERR(0, 362, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[3]); + } + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[3]); + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_tuple; + for (Py_ssize_t i=0; i<4; ++i) { + #if PY_VERSION_HEX >= 0x030F0000 + PyUnstable_SetImmortal(table[i]); + #elif CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if ((PY_SSIZE_T_MAX <= _Py_IMMORTAL_REFCNT_LOCAL)) break; + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], ((Py_ssize_t)_Py_IMMORTAL_REFCNT_LOCAL + 1)); + } + #else + if ((PY_SSIZE_T_MAX < _Py_IMMORTAL_INITIAL_REFCNT)) break; + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} +/* #### Code section: init_constants ### */ + +static int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate) { + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + CYTHON_UNUSED_VAR(__pyx_mstate); + { + const struct { const unsigned int length: 8; } str_length_index[] = {{1},{1},{27},{179},{8},{7},{6},{2},{9},{8},{8},{12},{4},{8},{5},{5},{6},{12},{19},{13},{10},{6},{13},{20},{12},{17},{8},{8},{10},{8},{12},{8},{13},{29},{24},{9},{8},{18},{9},{6},{8},{1},{2},{2},{35},{5},{2},{18},{5},{7},{6},{4},{5},{1},{2},{2},{2},{6},{2},{3},{4},{9},{20},{5},{6},{7},{1},{2},{2},{7},{3},{2},{5},{11},{20},{37},{9},{18},{1},{1},{1},{2},{3},{2},{3},{4},{8},{3},{1},{2},{3},{2},{3},{4},{7},{3},{1},{3},{1},{6},{3},{3},{1},{4},{3},{10},{8},{5},{5},{9},{6},{1},{5},{6},{1},{1},{3}}; + const struct { const unsigned int length: 10; } bytes_length_index[] = {{200},{522},{162},{242},{504},{2},{2},{2},{47},{60},{438}}; + #ifndef CYTHON_COMPRESS_STRINGS + #define CYTHON_COMPRESS_STRINGS 90 + #endif + #if (CYTHON_COMPRESS_STRINGS) == 1 /* compression: zlib (1881 bytes) */ +static const char cstring[] = "x\332\275U\315W\333\306\026\267\301\020A\014\330\306|\244\345\275\047 \241\257iK*\363Q\332\323\323\036\363\225\246I\023lH\332\267\362\031Kc\220\021\222-\215\214\235U\226Z\316r\226\263\324RK/\275d\351\245\226\376\023\370\023\336\035\t\034\222\346\235\363\272)\307H\243\321\275w~\367w\177\367j\375\347\027z\365I\3152\311\211e\031\316\223\026\262\305\206\3566\326\033\235\227\026\30129CD\336\353\2203\313\224uG\326\260\241W\261\215\0106:\262Cl]%\330\026F\246|tp\364\315\346\316\246\214LM\266q\035\253\304\221\035\267\252\032\310q\260#[5\271\352\352\006\321M\231t\032\330Y\227\237\325\344\216\345\312&\306\232L,\271\001vw\035\310\0316e\007\023\261\220\277@\246i\021Dt\313\254\200\273n\236~!k\272\r\207\350-,\274\017\221\341\340u\244i\025\260\303\232\356\240\252\201\261)\256\247\252\356\304+m\357\325oG\317^\034\354?3\t>\265\221\361[\361\217\312\213W\257\236\357\026\367\236\22712\216q\323\305\246\212O\334\206\201_\233\342\264}l\020\024__\331/-\023\337]\037\343\323\013l\222x\353\366\341\300\324\032\226n\022\247r$n\361\365\366e\345\250\323\206\377} \256\362\022\267I\031\327*\225\233\344p\005\376\242\364+\247\230\350\004_\210\215\232k\252\342~\201t3\272[\232kD\246&\272\210\356M\027\031\267k\202\0358\244\242;\025\325\262-\027\350\306\025(\047<\231\304r\355J\325rM\255R\263l\025k\025`\367\203\227V\203\350\027\372[\\\321\032\025\333\"\025C\207`b\001\206\310\351\230\252n\255\017\303:Uq\224j9$Z\324\243\253c\031\252\252\250\005\025\231Qd\200\\\305\344\022*\261\376\243a\251P\244\237\326O\261\211\333\r[=\203\204\324\272jD\020\241\2546Rq\025\251\347\252a9\370\006\222jY\266\346\210C\304\277\243i\337j\212V\320\004\335\216V\307\246\006?(\256{\021ir(\344\365X\310\353\000!J5\316\367\346`]W\364\202nj\272\212\035\250\214\0361\355\334\341\341S\224|j\357O)\t\243\010\333p1\264\255\237\033\206j\250uC3\264\272\340\325\260\254s\221\355\005j\233\246\nD\230\232\251\325!\014\201l\240\305\034`\271\321\260\032M\033\023\3276m]\261\365\0024\206\310\227\300O\3035\344\032\004\010wEW8\004\331\204\234\331\326%\261""\014 \003D\034\367I\253\205\014\027G\027\247\335y\2537\336%\303\364\224\370M\336\017S3^3\034\033\277\316$\306r4K\327\330(\333\342)\276\307\233\276\024\244\202\375\356Hw\265[\356\272\275_\257\324~\351\270\177|\022\246$o\324S\274b\230\272\357m\321\021\272L\013\264L\035\266\302v\231\312s\274\300\217\375\021\177\305\007\203Io9L\245\205\251\344\335\203\203\244\\?\267\306Q\230\316\201\327\016\333d6\317\3637\276\342\377\022\235\364\260\213\006\322\214\347\300\313\357\331\036#\020\352\215_\360K\241t\337\373\0166\225P\312\320\024\335\245h\000g+\"\217U\376s\360U\267t\223\302D\214\354z21\366\017V\014!V\223J,y=\236\030\223\336\331\336\254\027\357\211\347Io\036^&\303\324\264\207b\303(0\355\360\021\276\302\213\327Rbl\272?\365\330_\366w\202\235\256r\235\023!\204\347\304\264W\366l:\013\326*\313\262e\341,\036\213\003)K\037\260e\266\303\001\347\007\313E\260\3737_\345%\210:\221\361\332\375\205\047~3\220\272RO\272\022\340&\026(`H{\273^\025\020I\323p\273G\233a:O\367Y\222e\303t\206\216\321\222\260\311\300\013\233e\257\323\"\316%\000\370\234\377\342G\047\213\332%\331<0:\313_\006\217\002\322\335\352\215\365J=t\007\026\027\314\014\001\204\351Y\250\334\037\354w\276\313\317\374\263\340\274\227\035H9\3725\253\301F\325O\016\000\3213\372\032\\\013\254\314\034\201\237\237\372e\2779H\177\006i\003\250\244(\344\n\020Q\203\322\2430\263\310R\254\010\2666\317\206\231<=\210\350I\307\364\034\202>\212af\201\272`\"\216\304P\366\303`%\200\315Y\272\005\272S\302\374?\231\341?\016\212\177)\275[%|\331\377\362\247.\022B\230\376{\264<\023\t\232~\305J\300X\021\224\272\035\314\007\315\3568\200\270\253\327\344\r\302\353|bjZt\335\364L\334uBy\327\363C\321\206\251{\357:tT8\315\302%%Z\344\007V\022f*\315\016o\2227\346\275\206W\033B\0161\307\267`\225\2014\345\225<,B\304\013\221Ls\000h\n7\232-\002\000Q\327\003:\007Z\267Y\216}\007j\337\345\347\301\\\200\204 \266\200\345YQ\315\001\324\315\205\322\326y\252\377p;@A\273\333\3569W\253W\24503\007b\304\354G\336\274]*\203\233*C1\263\"_\310\0362\236OL=\374\240?\323\336\206\207\2746""\020\274\n\254A\355\206\364G<\335\311\215\266\243\331p\342g\303\010\356<m\262\021\310t\237\217s\304m?\347+\202\345M\257\005\0004\266\306\223\374#\313]V\205\342\037B\003\027@\264v\220\013\2248\363,]\245\2450-4%J\364~!\264\\\024\257\376\347B\244I\"\352#y\317\261\367\213\301\237w\240\177\213 \306\251\014L4q$\350\\d\346Di\214\360\307\376~0\032(\221.\227\303\374\022\023\306\2719\272G[,2\376\036\314RP\234:\230\375\320=\351\345{\345^36\234Ld\363\020\014\006P\230_\210\"\026\303\305\007\341\322\277X3rA\341\222\314G\241\343\367\200\253\274h\332pi\005:\270\314\337\002\021\233\320>\033\335j/9Xz\310\213\203\377\317\321\2016x\376\241cZ\31083\017\374/C\367\306\225W<\304\212\\\351\04720y%\016\003v\302\313\nm\023O\211{&\365^\216\273\264\n#\343\200g\373\211hH\211\301<l\207O\370\301~\3449\007~\261N\253<\331O,\366\027\267\372[O{M\030\034\037kL\204p\275\2474\0162T\334@t\037D\312\323c6\306\376\003\232j\373\016L\243\247]\345\346\320\201t;\270\226\007q\363Oxy\350*$\246\300>M\322\010]\313;\246\321\244\334\207\021\375\206m\260S\376\273\3774(\004\267\037\2550\275@#\222D\341\037\261\026\014\321\032\314\275\345`\273;\337m\366\306{\265\253\342U)\376B]\002\244V4\350og\214P\270\r\222\266\343\257@\n\2245\0171D5\036\371\227\242eg`N\202\346>\027\343\023\3062 \300|\333\317\372k\30184m\253\373\246\247\364\016\257\326\372G\245~\251,\2765\351h4m\307\237.1\303o\262\030\021\022\177\237\3116\014\224\r\256\372\013\301=\030j\311\277\226\215\364q\031Na\216&\375\007\301jP\002\320\242\222\377\005d\244\3301"; + PyObject *data = __Pyx_DecompressString(cstring, 1881, 1); + #define __Pyx_DecompressString_LZSS_UNUSED + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #elif (CYTHON_COMPRESS_STRINGS) > 0 && (CYTHON_COMPRESS_STRINGS) <= 90 /* compression: lzss (2460 bytes) */ +static const char cstring[] = "\377.?Lib/fo\377ntTools/\367var\r\001iup.\377pyNote t\377hat Cyth\377on is de\377liberate\377ly stric\367ter!\001n PE\377P-484 an\377d reject\377s subcla\377sses of \377builtin \377types. I\377f you ne\177ed to p%\000\376%\tthen se\375t\200\000e \047ann\377otation_\376<\000ing\047 di\355rb\000iv\242\000o F\377alse.add\375_%\000edisab\357leen\002\001gci\375s\004\003dCOMPI\377LEDInteg\377ralMAX_L\377OOKBACKR\377ealSeque\377nceTuple\373Unj\001Delta\375_\001\002OrNone\376\000\tSegment\374\031\003\005\005Endpoi\037nts_P\003\001\000\003\"\005\257_Pyx\001\000D\266 _\377NextRef_}_\326\004e____\253\"\377_getitem\336\r\001func\025\001ma{in\003\002odul&\002\367nam.\002qual\336\004\005testD\000is\277_corou\354 e\371_\314@\013\000ntour\377_bound_f?orced_\333 \020\n\377optimize\377_dp_rot_\343liJ\000\005\001\204@asy\337ncio.N\006sb^g\001cost\004\002j\n\002\377solcc1c2\347canr\002\260\000bet}w\207@.<loc\242@\377>.genexp\367rch\316\000cjcl\371i\321 \330\000trace\377backclos\367eco\253\002coor\363dsa\001e\001sdd0\337d1d2d\220Asd\317jend\000\000\332@um\364\217\204\002\300\204\006.\303\204\003.iup\370\346\002\352\003r\004ii1i2\177indices\244@\005i\345\"s\232(\244)\213%\000\021\302\016\350\345!\227\002\000\006_\313%jkl\377lclcjldl{dj\324!look\352\001\377maxnncnc\277jndndj\227 t\177numbers\272@\377ppopqret\377urnri1ri\3672ss\353\002tset\177default\356 \376\342@onstart\377throwtol\277erance\242\205\003v\337value\000\002sx\377yzip\200\001\330\014\375\r\000\000\330\n\013\330\004\017\377\210q\330\005\006\360\020\000\377\005\022\220\021\220&\230\003\377\2305\240\004\240C\240q\377\250\010\260\004\260D\270\002\377\270#\270R\270u\300J\377\310c\320QS\320ST\377\330\004\010\210\003\2101\210\377A\330\004\013\2105\220\002\377\220!\2202\220R\220s\377\230\"\230B\230c\240\022\377\2402\240S\250\002\250\"\375\250\036\000\n\210!\330\004\014\356\047\001\010\210\007f\000\010\022\320\177\022&\240a\330\014\0223\000\3778\2304\230r\240\024\240\337V\2501\250He\002$\270\277a\340\010\017\210sP\0009\357\230C\230tH""\000V\2502\177\250Q\330\010\013\2107e\000\3771\330\010\020\220\004\220B\327\220a\340y\0001\304\001#\240_?\260+\270Q\274\004\t\224\003\377\360\n\000\005\035\230A\330\376I\000q\220\010\230\001\360\006\377\000\005\010\200r\210\023\210\374\016\003\014\001\n\210\026\210q\220?\001\330\004\016\210a#\003T\002\377\220y\240\002\240\"\240A\377\360\010\000\005\016\320\r*\377\250!\2508\2608\2701\353\360\022?\001qG\000\t\016\210\337R\210r\220\023\204\000c\230\347\021\230!b\001\013\001A\340\010\377\021\220\031\230!\2308\240\334\245\000\000\010\021\220\030%\000(\240\367#\240QS\000\t\020\210x\377\320\027/\250q\260\010\270\357\010\300\010\310\231\001\t\027\220\276\201\000\014\210B\210b\217\000\010\375\016\004\000\007\220q\330\014\024\377\220D\230\001\230\021\330\014\337\020\220\005\220Q \001\020\220\377\007\220r\230\021\360\014\000\376E\000w\220c\230\033\240H\271\250u\002\270A\001\230\026\317 \023\377\240N\260%\260t\2705?\300\005\300Q\300a\214\010\324\000\273\n\000x\006\330\014\023\267@X\377\230W\240B\240h\250h\377\260k\300\021\340\010\022\220\367,\230f\016\000b\250\001\340\277\010\014\210I\220U\317\0002\357\230R\230s\274\001\240g\250?R\250q\340\014\032\364\000\222\000\256\305`\022\220\"\215@f\370@a\177\330\020\030\230\004\230A)\000\377r\240\021\330\020\024\220E\326\232\"\014\017\251\"F\235`A\330O\020\027\220u \000o\001e\364@\357F\260\"\260\022\000\023\2205\376\365`1\330\024\036\230l\250\347*\260A\262\200*\202e)\320)\027>\270a\310\204\001\016\346\203c\266\205\001\255 \367+\230Q\257 A\240V\250\1776\260\026\260q\270\006\202\000\372\244\204\t\001\245\204\004\360\024\000\r\016\346\365\205\001\016\017\360\205\003\366a\360\026\000\375\005\256\204\004\330\004\007\200y\220\277\003\2201\330\010\023\002\000\004\356\237\205\001:\230Q\235\204\001c\220\021\374\000\004\371\205\001\005\210U\220!\220\3613\257a\336#\361\205\0051\340\010\r\217\210Q\210e?\001\003\003\225\206\001q\337\340\010\013\2102\255\204\004A\330\373\014\r\324AE\220\025\220a\276\307`\022\2307\240\"\375@k\257\260\025\260a\215a5\356`""\023\372\312A\340\265@u\220B\220j\377\240\004\320$6\260a\260\377x\270x\300s\310#\310\377Q\330\020\025\220Q\220eo\230<\240q\003\0051\340\337D\372\337@\021\230\206\0017\220!\200\001\366\332\000\r$\223\206\n\014\2103\210\177a\210x\220s\230#\263 \333a\340\301\207\007\020\220\245 \010\210\366\323\006\220x\227\207\002T\250\021\330\377\010\014\210E\220\026\220q\377\230\002\230\"\230D\240\006\377\240a\240r\250\022\2501\376\222\207\0014\210v\220Q\220d\337\230&\240\001\240\033\014B\230\377b\240\004\240F\250!\250\3772\250R\250r\260\022\260\3751\364\003\021\220#\220Q\330O\014\021\220\021\316\207\002\000\006\014\310\204\001!A\027\001\000\006\002\r\221!t\366\"\332\204\002\257\025\230a\330\001\005\340\000\017\014\377\024\220A\360\016\000\r\020\233\210sn\002\020\023\262A\245\211\002D\377\240\002\240*\250D\260\003\373\2601\337\211\002!\330\024\034\230~)\001\022\025\220C\220v\364@\372*\0009\353\000\004\240B\240j\376$\000:\270T\300\024\300R{\300q#\003\n\000\021\024\200`\277c\230\021\330\024\027\367\211\002A\377\330\030\031\330\034\037\230q\375\240/\001a\330\034 \240\003\257\2401\240C\251 \024\261\206\001\330\377\034\"\240#\240R\240z\376\206 4\260t\2703\270b\377\300\001\340\034$\240A\340\276\023#s\250\"\250K+\013\014\366\271\213\001\020\026\375 !\2301\330\375\020\365B1\210a\230A\240\3771\320\000\020\220\010\230\010\177\240\001\330\004\t\210\021\330\204\001\307t\2101\214\212\002\263\213\001\207\204\005B\220\377b\230\004\230E\240\021\320\341\000\267\211\002\245\212\001\206\205\006%\0201\210A\332\370\211\002\0255\000\001\230\244\204\001b\240\377\001\320\000\030\320\0305\320\3775G\300q\360\014\000\005<\325l\323\205\001u\210G\220w\003\351f\375\340\364\212\001\210r\220\024\220S\357\230\005\230Y\321`x\250s?\260\"\260G\2701\246\004\206\214\001\276\343\212\001F\230!\340\004\304\214\002\t\277\210\024\210Q\210a\316\214\001D\373\220\001\220\206\001\007\200v\210S\375\220\245\211\002D\220\005\220V\230\3773\230g\240W\250G\260\3732\260\255\214\005\330\014\027\220q\375\330\242 a\220s\230%\230\377v\240Q""\240f\250F\260\377!\2606\270\026\270q\300\177\006\300f\310A\310Q\234\214\003\307w\210a\313\204\002`\000\251\215\004\013\210\2374\210r\220\026\360\212\001\202\213\001\004\357\220E\230\026A\000R\240s\357\250%\250w\257\206\001\017\210w\337\220a\330\020\033\376 \024\032\373\230!\177\000e\2406\250\021\377\250&\260\006\260a\260v\377\270V\3001\300F\310&\277\320PQ\320QR\273\214\001\014\312\306\215\0026\265\214\003\020\376\214\001\300\003\002\220\347\"\220A\360\212\001\304\0036\240\022\377\2403\240c\250\027\260\007O\260q\270\001\374\215\004\247\200$\010\367-\377g\240S\250\001\250\031\260\357#\260Q\260\276 \013\2101"; + PyObject *data = __Pyx_DecompressString_LZSS(cstring, 2460, 3193); + #define __Pyx_DecompressString_UNUSED + if (unlikely(!data)) __PYX_ERR(0, 1, __pyx_L1_error) + const char* const bytes = __Pyx_PyBytes_AsString(data); + #if !CYTHON_ASSUME_SAFE_MACROS + if (likely(bytes)); else { Py_DECREF(data); __PYX_ERR(0, 1, __pyx_L1_error) } + #endif + #else /* compression: none (3193 bytes) */ +static const char bytes[] = ".?Lib/fontTools/varLib/iup.pyNote that Cython is deliberately stricter than PEP-484 and rejects subclasses of builtin types. If you need to pass subclasses then set the \047annotation_typing\047 directive to False.add_notedisableenablegcisenabledCOMPILEDIntegralMAX_LOOKBACKRealSequenceTupleUnion_Delta_DeltaOrNone_DeltaOrNoneSegment_DeltaSegment_Endpoints_Point_PointSegment__Pyx_PyDict_NextRef__annotate____class_getitem____func____main____module____name____qualname____test___is_coroutine_iup_contour_bound_forced_set_iup_contour_optimize_dp_rot_list_rot_setasyncio.coroutinesbest_costbest_jbest_solcc1c2can_iup_in_between.<locals>.genexprchaincjcline_in_tracebackclosecontourcoordscostcostsdd0d1d2deltasdjendendsenumeratefontTools.varLib.iupforceforcedgenexprii1i2indicesintititemsiup_contouriup_contour_optimizeiup_contour_optimize.<locals>.genexpriup_deltaiup_delta_optimizejkllclcjldldjlistlookbackmaxnncncjndndjnextnumbersoutppopqreturnri1ri2ssendsetsetdefaultsolutionstartthrowtolerancetypingvvaluevaluesxyzip\200\001\330\014\r\330\014\r\330\n\013\330\004\017\210q\330\005\006\360\020\000\005\022\220\021\220&\230\003\2305\240\004\240C\240q\250\010\260\004\260D\270\002\270#\270R\270u\300J\310c\320QS\320ST\330\004\010\210\003\2101\210A\330\004\013\2105\220\002\220!\2202\220R\220s\230\"\230B\230c\240\022\2402\240S\250\002\250\"\250A\330\004\n\210!\330\004\014\210A\330\004\010\210\007\210q\330\010\022\320\022&\240a\330\014\022\220!\2208\2304\230r\240\024\240V\2501\250H\260D\270\002\270$\270a\340\010\017\210s\220!\2209\230C\230t\2402\240V\2502\250Q\330\010\013\2107\220!\2201\330\010\020\220\004\220B\220a\340\004\013\2101\200\001\330\014#\240?\260+\270Q\330\005\006\360\020\000\005\t\210\003\2101\210A\360\n\000\005\035\230A\330\010\017\210q\220\010\230\001\360\006\000\005\010\200r\210\023\210A\330\010\017\210q\360\006\000\005\n\210\026\210q\220\001\330\004\016\210a\330\010\017\210q\220\004\220B\220a\220y\240\002\240\"\240A\360\010\000\005\016\320\r*\250!\2508\2608\2701\360\022""\000\005\010\200q\360\006\000\t\016\210R\210r\220\023\220B\220c\230\021\230!\330\010\017\210r\220\023\220A\340\010\021\220\031\230!\2308\2401\330\010\021\220\031\230!\2308\2401\330\010\021\220\030\230\021\230(\240#\240Q\360\010\000\t\020\210x\320\027/\250q\260\010\270\010\300\010\310\001\360\006\000\t\027\220a\330\010\014\210B\210b\220\001\330\010\016\210b\220\007\220q\330\014\024\220D\230\001\230\021\330\014\020\220\005\220Q\220a\330\010\020\220\007\220r\230\021\360\014\000\t\020\210w\220c\230\033\240H\250A\340\010\021\220\021\220&\230\001\230\026\230r\240\023\240N\260%\260t\2705\300\005\300Q\300a\340\010\021\220\031\230!\2308\2401\240A\360\n\000\t\020\210x\320\027/\250q\330\014\023\2202\220X\230W\240B\240h\250h\260k\300\021\340\010\022\220,\230f\240B\240b\250\001\340\010\014\210I\220U\230!\2302\230R\230s\240#\240Q\240g\250R\250q\340\014\032\230!\330\014\020\220\001\330\014\022\220\"\220B\220f\230B\230a\330\020\030\230\004\230A\230R\230r\240\021\330\020\024\220E\230\021\230!\330\014\017\210r\220\023\220F\230\"\230A\330\020\027\220u\230A\230W\240B\240e\2501\250F\260\"\260A\330\020\023\2205\230\003\2301\330\024\036\230l\250*\260A\360\014\000\t\020\210w\220c\230\033\240H\250A\340\010\021\220\021\220&\230\001\230\026\230r\240\023\240N\260%\260t\2705\300\005\300Q\300a\340\004\013\2101\200\001\330\014)\320)>\270a\330\005\006\360\016\000\005\022\220\021\220&\230\003\2305\240\004\240C\240q\250\010\260\004\260D\270\002\270#\270R\270u\300J\310c\320QS\320ST\330\004\010\210\003\2101\210A\330\004\013\2105\220\002\220!\2202\220R\220s\230\"\230B\230c\240\022\2402\240S\250\002\250\"\250A\330\004\n\210!\330\004\014\210A\330\004\010\210\007\210q\330\010\017\210q\330\010\022\220+\230Q\230f\240A\240V\2506\260\026\260q\270\006\270a\330\010\013\2107\220!\2201\330\010\020\220\001\340\004\013\2101\200\001\360\024\000\r\016\330\014\r\330\016\017\330\004\017\210q\330\004\016\210a\360\026\000\005\t\210\003\2101\210A\330\004\007\200y\220\003\2201\330\010\023\2201\330\004\022\220!\220:\230Q""\330\004\016\210c\220\021\330\004\016\210c\220\021\330\004\010\210\005\210U\220!\2203\220a\330\010\024\220E\230\021\230\"\230B\230c\240\022\2401\340\010\r\210Q\210e\2201\330\010\r\210Q\210e\2202\220R\220q\340\010\013\2102\210R\210r\220\023\220A\330\014\r\340\010\014\210E\220\025\220a\220r\230\022\2307\240\"\240B\240k\260\025\260a\330\014\023\2205\230\001\230\023\230B\230a\340\014\017\210u\220B\220j\240\004\320$6\260a\260x\270x\300s\310#\310Q\330\020\025\220Q\220e\230<\240q\330\020\025\220Q\220e\2301\340\014\017\210r\220\023\220A\330\020\021\340\004\013\2107\220!\200\001\360\026\000\r$\240?\260+\270Q\330\005\006\360\020\000\005\014\2103\210a\210x\220s\230#\230Q\230a\340\004\010\210\003\2101\210A\330\004\020\220\001\340\004\010\210\005\210U\220!\2203\220a\220x\230r\240\024\240T\250\021\330\010\014\210E\220\026\220q\230\002\230\"\230D\240\006\240a\240r\250\022\2501\330\010\013\2104\210v\220Q\220d\230&\240\001\240\021\330\010\014\210E\220\026\220q\230\002\230\"\230B\230b\240\004\240F\250!\2502\250R\250r\260\022\2601\340\010\014\210E\220\021\220#\220Q\330\014\021\220\021\220!\2201\330\014\021\220\021\220!\2201\330\014\022\220\"\220A\220Q\330\014\022\220\"\220A\220Q\330\014\022\220\"\220A\220Q\330\014\022\220\"\220A\220Q\340\014\017\210t\2203\220a\330\020\024\220E\230\025\230a\330\020\024\220E\230\025\230a\340\020\024\220E\230\025\230a\330\020\024\220E\230\025\230a\340\014\024\220A\360\016\000\r\020\210s\220#\220Q\330\020\023\2203\220a\220s\230\"\230D\240\002\240*\250D\260\003\2601\260D\270\002\270!\330\024\034\230A\360\016\000\022\025\220C\220v\230Q\330\020\023\2209\230D\240\004\240B\240j\260\003\260:\270T\300\024\300R\300q\330\024\034\230A\360\n\000\021\024\2203\220c\230\021\330\024\027\220s\230\"\230A\330\030\031\330\034\037\230q\240\004\240B\240a\330\034 \240\003\2401\240C\240r\250\024\250R\250q\330\034\"\240#\240R\240z\260\022\2604\260t\2703\270b\300\001\340\034$\240A\340\030\031\330\034\037\230q\240\004\240B\240a\330\034 \240\003\2401\240C\240r\250\024\250R\250q""\330\034\"\240#\240R\240s\250\"\250K\260t\2703\270b\300\001\340\034$\240A\340\014\017\210q\330\020\026\220d\230!\2301\330\020\021\340\004\013\2101\210a\230A\2401\320\000\020\220\010\230\010\240\001\330\004\t\210\021\330\004\007\200t\2101\330\010\017\210q\330\004\013\2102\210R\210r\220\023\220B\220b\230\004\230E\240\021\320\000\021\220\031\230!\360\006\000\005\t\210\003\2101\210A\330\004\t\210\021\330\004\007\200t\2101\330\010\017\210q\330\004\013\2101\210A\210R\210r\220\025\220b\230\001\230\023\230B\230b\240\001\320\000\030\320\0305\3205G\300q\360\014\000\005\014\2103\210a\210x\220s\230#\230Q\230a\330\004\007\200u\210G\2201\330\010\017\210q\340\004\010\210\003\2101\210A\340\004\016\210a\210r\220\024\220S\230\005\230Y\240a\240x\250s\260\"\260G\2701\330\004\007\200t\2101\340\010\017\210r\220\023\220F\230!\340\004\n\210!\330\004\t\210\024\210Q\210a\330\004\014\210D\220\001\220\021\330\004\007\200v\210S\220\001\340\010\014\210D\220\005\220V\2303\230g\240W\250G\2602\260Q\330\010\013\2107\220!\330\014\027\220q\330\020\026\220a\220s\230%\230v\240Q\240f\250F\260!\2606\270\026\270q\300\006\300f\310A\310Q\360\006\000\005\010\200w\210a\210v\220Q\220a\330\004\010\210\007\210q\330\010\013\2104\210r\220\026\220r\230\021\330\014\020\220\004\220E\230\026\230v\240R\240s\250%\250w\260a\330\014\017\210w\220a\330\020\033\2301\330\024\032\230!\2303\230e\2406\250\021\250&\260\006\260a\260v\270V\3001\300F\310&\320PQ\320QR\360\006\000\t\014\2107\220!\2206\230\021\230!\330\010\020\220\001\330\004\007\200v\210S\220\002\220\"\220A\340\010\014\210D\220\005\220V\2306\240\022\2403\240c\250\027\260\007\260q\270\001\330\010\013\2107\220!\330\014\027\220q\330\020\026\220a\220s\230%\230v\240Q\240f\250F\260!\2606\270\026\270q\300\006\300f\310A\310Q\360\010\000\005\014\2103\210a\210x\220s\230#\230Q\230g\240S\250\001\250\031\260#\260Q\260a\330\004\013\2101"; + PyObject *data = NULL; + #define __Pyx_DecompressString_UNUSED + #define __Pyx_DecompressString_LZSS_UNUSED + #endif + PyObject **stringtab = __pyx_mstate->__pyx_string_tab; + Py_ssize_t pos = 0; + for (int i = 0; i < 117; i++) { + Py_ssize_t bytes_length = str_length_index[i].length; + PyObject *string = PyUnicode_DecodeUTF8(bytes + pos, bytes_length, NULL); + if (likely(string) && i >= 9) PyUnicode_InternInPlace(&string); + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + stringtab[i] = string; + pos += bytes_length; + } + for (int i = 117; i < 128; i++) { + Py_ssize_t bytes_length = bytes_length_index[i-117].length; + PyObject *string = PyBytes_FromStringAndSize(bytes + pos, bytes_length); + stringtab[i] = string; + pos += bytes_length; + if (unlikely(!string)) { + Py_XDECREF(data); + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + Py_XDECREF(data); + for (Py_ssize_t i = 0; i < 128; i++) { + if (unlikely(PyObject_Hash(stringtab[i]) == -1)) { + __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = stringtab + 117; + for (Py_ssize_t i=0; i<11; ++i) { + #if PY_VERSION_HEX >= 0x030F0000 + PyUnstable_SetImmortal(table[i]); + #elif CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if ((PY_SSIZE_T_MAX <= _Py_IMMORTAL_REFCNT_LOCAL)) break; + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], ((Py_ssize_t)_Py_IMMORTAL_REFCNT_LOCAL + 1)); + } + #else + if ((PY_SSIZE_T_MAX < _Py_IMMORTAL_INITIAL_REFCNT)) break; + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + } + { + PyObject **numbertab = __pyx_mstate->__pyx_number_tab; + double const c_constants[] = {0.0}; + for (int i = 0; i < 1; i++) { + numbertab[i] = PyFloat_FromDouble(c_constants[i]); + if (unlikely(!numbertab[i])) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + { + PyObject **numbertab = __pyx_mstate->__pyx_number_tab + 1; + int8_t const cint_constants_1[] = {0,-1,1,2,3,4,8}; + for (int i = 0; i < 7; i++) { + numbertab[i] = PyLong_FromLong(cint_constants_1[i - 0]); + if (unlikely(!numbertab[i])) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #if CYTHON_IMMORTAL_CONSTANTS + { + PyObject **table = __pyx_mstate->__pyx_number_tab; + for (Py_ssize_t i=0; i<8; ++i) { + #if PY_VERSION_HEX >= 0x030F0000 + PyUnstable_SetImmortal(table[i]); + #elif CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if ((PY_SSIZE_T_MAX <= _Py_IMMORTAL_REFCNT_LOCAL)) break; + #if PY_VERSION_HEX < 0x030E0000 + if (_Py_IsOwnedByCurrentThread(table[i]) && Py_REFCNT(table[i]) == 1) + #else + if (PyUnstable_Object_IsUniquelyReferenced(table[i])) + #endif + { + Py_SET_REFCNT(table[i], ((Py_ssize_t)_Py_IMMORTAL_REFCNT_LOCAL + 1)); + } + #else + if ((PY_SSIZE_T_MAX < _Py_IMMORTAL_INITIAL_REFCNT)) break; + Py_SET_REFCNT(table[i], _Py_IMMORTAL_INITIAL_REFCNT); + #endif + } + } + #endif + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_codeobjects ### */ +#ifdef __cplusplus +namespace { +#endif +typedef struct { + unsigned int argcount : 3; + unsigned int num_posonly_args : 1; + unsigned int num_kwonly_args : 1; + unsigned int nlocals : 5; + unsigned int flags : 10; + unsigned int first_line : 9; +} __Pyx_PyCode_New_function_description; +#ifdef __cplusplus +} /* anonymous namespace */ +#endif +/* NewCodeObj.proto */ +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +); + + +static int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate) { + PyObject* tuple_dedup_map = PyDict_New(); + if (unlikely(!tuple_dedup_map)) return -1; + { + const __Pyx_PyCode_New_function_description descr = {0, 0, 0, 6, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS|CO_GENERATOR), 196}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_i, __pyx_mstate->__pyx_n_u_j, __pyx_mstate->__pyx_n_u_x, __pyx_mstate->__pyx_n_u_y, __pyx_mstate->__pyx_n_u_p, __pyx_mstate->__pyx_n_u_q}; + __pyx_mstate_global->__pyx_codeobj_tab[0] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_varLib_iup_py, __pyx_mstate->__pyx_n_u_genexpr, __pyx_mstate->__pyx_kp_b_iso88591_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[0])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {0, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS|CO_GENERATOR), 377}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_p}; + __pyx_mstate_global->__pyx_codeobj_tab[1] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_varLib_iup_py, __pyx_mstate->__pyx_n_u_genexpr, __pyx_mstate->__pyx_kp_b_iso88591_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[1])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {0, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS|CO_GENERATOR), 386}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_d}; + __pyx_mstate_global->__pyx_codeobj_tab[2] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_varLib_iup_py, __pyx_mstate->__pyx_n_u_genexpr, __pyx_mstate->__pyx_kp_b_iso88591_a, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[2])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 14, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 90}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_deltas, __pyx_mstate->__pyx_n_u_coords, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_indices, __pyx_mstate->__pyx_n_u_out, __pyx_mstate->__pyx_n_u_it, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_i1, __pyx_mstate->__pyx_n_u_i2, __pyx_mstate->__pyx_n_u_ri1, __pyx_mstate->__pyx_n_u_ri2, __pyx_mstate->__pyx_n_u_end, __pyx_mstate->__pyx_n_u_i, __pyx_mstate->__pyx_n_u_v}; + __pyx_mstate_global->__pyx_codeobj_tab[3] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_varLib_iup_py, __pyx_mstate->__pyx_n_u_iup_contour, __pyx_mstate->__pyx_kp_b_iso88591_55Gq_3axs_Qa_uG1_q_1A_ar_S_Yaxs, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[3])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 8, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 142}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_deltas, __pyx_mstate->__pyx_n_u_coords, __pyx_mstate->__pyx_n_u_ends, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_out, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_end, __pyx_mstate->__pyx_n_u_contour}; + __pyx_mstate_global->__pyx_codeobj_tab[4] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_varLib_iup_py, __pyx_mstate->__pyx_n_u_iup_delta, __pyx_mstate->__pyx_kp_b_iso88591_a_5_Cq_D_RuJcQSST_1A_5_2Rs_Bc_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[4])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 24, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 201}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_deltas, __pyx_mstate->__pyx_n_u_coords, __pyx_mstate->__pyx_n_u_tolerance, __pyx_mstate->__pyx_n_u_cj, __pyx_mstate->__pyx_n_u_dj, __pyx_mstate->__pyx_n_u_lcj, __pyx_mstate->__pyx_n_u_ldj, __pyx_mstate->__pyx_n_u_ncj, __pyx_mstate->__pyx_n_u_ndj, __pyx_mstate->__pyx_n_u_force, __pyx_mstate->__pyx_n_u_forced, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_i, __pyx_mstate->__pyx_n_u_ld, __pyx_mstate->__pyx_n_u_lc, __pyx_mstate->__pyx_n_u_d, __pyx_mstate->__pyx_n_u_c, __pyx_mstate->__pyx_n_u_nd, __pyx_mstate->__pyx_n_u_nc, __pyx_mstate->__pyx_n_u_j, __pyx_mstate->__pyx_n_u_c1, __pyx_mstate->__pyx_n_u_c2, __pyx_mstate->__pyx_n_u_d1, __pyx_mstate->__pyx_n_u_d2}; + __pyx_mstate_global->__pyx_codeobj_tab[5] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_varLib_iup_py, __pyx_mstate->__pyx_n_u_iup_contour_bound_forced_set, __pyx_mstate->__pyx_kp_b_iso88591_Q_3axs_Qa_1A_U_3axr_T_E_q_D_ar, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[5])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {5, 0, 0, 13, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 292}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_deltas, __pyx_mstate->__pyx_n_u_coords, __pyx_mstate->__pyx_n_u_forced, __pyx_mstate->__pyx_n_u_tolerance, __pyx_mstate->__pyx_n_u_lookback, __pyx_mstate->__pyx_n_u_i, __pyx_mstate->__pyx_n_u_j, __pyx_mstate->__pyx_n_u_best_cost, __pyx_mstate->__pyx_n_u_best_j, __pyx_mstate->__pyx_n_u_cost, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_costs, __pyx_mstate->__pyx_n_u_chain}; + __pyx_mstate_global->__pyx_codeobj_tab[6] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_varLib_iup_py, __pyx_mstate->__pyx_n_u_iup_contour_optimize_dp, __pyx_mstate->__pyx_kp_b_iso88591_q_a_1A_y_1_1_Q_c_c_U_3a_E_Bc_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[6])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 345}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_l, __pyx_mstate->__pyx_n_u_k, __pyx_mstate->__pyx_n_u_n}; + __pyx_mstate_global->__pyx_codeobj_tab[7] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_varLib_iup_py, __pyx_mstate->__pyx_n_u_rot_list, __pyx_mstate->__pyx_kp_b_iso88591_1A_t1_q_1ARr_b_Bb, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[7])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 355}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_s, __pyx_mstate->__pyx_n_u_k, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_v}; + __pyx_mstate_global->__pyx_codeobj_tab[8] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_varLib_iup_py, __pyx_mstate->__pyx_n_u_rot_set, __pyx_mstate->__pyx_kp_b_iso88591_t1_q_2Rr_Bb_E, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[8])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 20, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 362}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_deltas, __pyx_mstate->__pyx_n_u_coords, __pyx_mstate->__pyx_n_u_tolerance, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_d0, __pyx_mstate->__pyx_n_u_forced, __pyx_mstate->__pyx_n_u_k, __pyx_mstate->__pyx_n_u_chain, __pyx_mstate->__pyx_n_u_costs, __pyx_mstate->__pyx_n_u_solution, __pyx_mstate->__pyx_n_u_i, __pyx_mstate->__pyx_n_u_best_sol, __pyx_mstate->__pyx_n_u_best_cost, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_cost, __pyx_mstate->__pyx_n_u_genexpr, __pyx_mstate->__pyx_n_u_genexpr, __pyx_mstate->__pyx_n_u_genexpr, __pyx_mstate->__pyx_n_u_i, __pyx_mstate->__pyx_n_u_i}; + __pyx_mstate_global->__pyx_codeobj_tab[9] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_varLib_iup_py, __pyx_mstate->__pyx_n_u_iup_contour_optimize, __pyx_mstate->__pyx_kp_b_iso88591_Q_1A_A_q_r_A_q_q_a_q_Bay_A_881, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[9])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {4, 0, 0, 9, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 463}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_deltas, __pyx_mstate->__pyx_n_u_coords, __pyx_mstate->__pyx_n_u_ends, __pyx_mstate->__pyx_n_u_tolerance, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_out, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_end, __pyx_mstate->__pyx_n_u_contour}; + __pyx_mstate_global->__pyx_codeobj_tab[10] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_Lib_fontTools_varLib_iup_py, __pyx_mstate->__pyx_n_u_iup_delta_optimize, __pyx_mstate->__pyx_kp_b_iso88591_q_5_Cq_D_RuJcQSST_1A_5_2Rs_Bc_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[10])) goto bad; + } + Py_DECREF(tuple_dedup_map); + return 0; + bad: + Py_DECREF(tuple_dedup_map); + return -1; +} +/* #### Code section: init_globals ### */ + +static int __Pyx_InitGlobals(void) { + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + /* PythonCompatibility.init */ + if (likely(__Pyx_init_co_variables() == 0 && __Pyx_init_tpflags_variables() == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* PyFrozenDict.init */ + #if CYTHON_COMPILING_IN_LIMITED_API + { + PyObject *builtins = PyEval_GetBuiltins(); // borrowed + if (likely(builtins)) { + PyObject *type_name = PyUnicode_FromStringAndSize("frozendict", sizeof("frozendict")-1); + if (likely(type_name)) { + PyObject *frozendict_type = PyObject_GetItem(builtins, type_name); + Py_DECREF(type_name); + if (!frozendict_type && PyErr_ExceptionMatches(PyExc_KeyError)) { + PyErr_Clear(); + frozendict_type = (PyObject*) &PyDict_Type; + Py_INCREF(frozendict_type); + } + __pyx_mstate_global->__Pyx_PyFrozenDictType = frozendict_type; + } + } + } // error handling follows + #endif + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* AssertionsEnabled.init */ + if (likely(__Pyx_init_assertions_enabled() == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CommonTypesMetaclass.init */ + if (likely(__pyx_CommonTypesMetaclass_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CachedMethodType.init */ + #if CYTHON_COMPILING_IN_LIMITED_API + { + PyObject *typesModule=NULL; + typesModule = PyImport_ImportModule("types"); + if (typesModule) { + __pyx_mstate_global->__Pyx_CachedMethodType = PyObject_GetAttrString(typesModule, "MethodType"); + Py_DECREF(typesModule); + } + } // error handling follows + #endif + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* Generator.init */ + if (likely(__pyx_Generator_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_after_shared_utility ### */ + +static int __Pyx_InitAfterSharedUtility(void) { + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + /* CythonFunctionPerModule.init */ + if (likely(__pyx_CyFunction_init(__pyx_m) == 0)); else + + if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cleanup_globals ### */ +/* #### Code section: cleanup_module ### */ +/* #### Code section: main_method ### */ +/* #### Code section: utility_code_pragmas ### */ +#ifdef _MSC_VER +#pragma warning( push ) +/* Warning 4127: conditional expression is constant + * Cython uses constant conditional expressions to allow in inline functions to be optimized at + * compile-time, so this warning is not useful + */ +#pragma warning( disable : 4127 ) +#endif + + + +/* #### Code section: utility_code_def ### */ + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* FastTypeChecks (used by GivenExceptionMatches) */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (cls == a || cls == b) return 1; + mro = cls->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(mro, i); + if (base == (PyObject *)a || base == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); +} +#endif + +/* PyErrFetchRestore (used by GivenExceptionMatches) */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *tmp_value; + assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); + if (value) { + #if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) + #endif + PyException_SetTraceback(value, tb); + } + tmp_value = tstate->current_exception; + tstate->current_exception = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject* exc_value; + exc_value = tstate->current_exception; + tstate->current_exception = 0; + *value = exc_value; + *type = NULL; + *tb = NULL; + if (exc_value) { + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + #if CYTHON_COMPILING_IN_CPYTHON + *tb = ((PyBaseExceptionObject*) exc_value)->traceback; + Py_XINCREF(*tb); + #else + *tb = PyException_GetTraceback(exc_value); + #endif + } +#else + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#endif +} +#endif + +/* GivenExceptionMatches (used by PyErrExceptionMatches) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + if (exc_type1) { + return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); + } else { + return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } +} +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); + for (i=0; i<n; i++) { + if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1; + } + for (i=0; i<n; i++) { + PyObject *t = PyTuple_GET_ITEM(tuple, i); + if (likely(PyExceptionClass_Check(t))) { + if (__Pyx_inner_PyErr_GivenExceptionMatches2(exc_type, NULL, t)) return 1; + } else { + } + } + return 0; +} +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject* exc_type) { + if (likely(err == exc_type)) return 1; + if (likely(PyExceptionClass_Check(err))) { + if (likely(PyExceptionClass_Check(exc_type))) { + return __Pyx_inner_PyErr_GivenExceptionMatches2(err, NULL, exc_type); + } else if (likely(PyTuple_Check(exc_type))) { + return __Pyx_PyErr_GivenExceptionMatchesTuple(err, exc_type); + } else { + } + } + return PyErr_GivenExceptionMatches(err, exc_type); +} +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *exc_type1, PyObject *exc_type2) { + assert(PyExceptionClass_Check(exc_type1)); + assert(PyExceptionClass_Check(exc_type2)); + if (likely(err == exc_type1 || err == exc_type2)) return 1; + if (likely(PyExceptionClass_Check(err))) { + return __Pyx_inner_PyErr_GivenExceptionMatches2(err, exc_type1, exc_type2); + } + return (PyErr_GivenExceptionMatches(err, exc_type1) || PyErr_GivenExceptionMatches(err, exc_type2)); +} +#endif + +/* PyErrExceptionMatches (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); + for (i=0; i<n; i++) { + if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1; + } + for (i=0; i<n; i++) { + if (__Pyx_PyErr_GivenExceptionMatches(exc_type, PyTuple_GET_ITEM(tuple, i))) return 1; + } + return 0; +} +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err) { + int result; + PyObject *exc_type; +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *current_exception = tstate->current_exception; + if (unlikely(!current_exception)) return 0; + exc_type = (PyObject*) Py_TYPE(current_exception); + if (exc_type == err) return 1; +#else + exc_type = tstate->curexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; +#endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(exc_type); + #endif + if (unlikely(PyTuple_Check(err))) { + result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + } else { + result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(exc_type); + #endif + return result; +} +#endif + +/* PyObjectGetAttrStr (used by PyObjectGetAttrStrNoError) */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* PyObjectGetAttrStrNoError (used by GetBuiltinName) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + (void) PyObject_GetOptionalAttr(obj, attr_name, &result); + return result; +#else +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +#endif +} + +/* GetBuiltinName */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_mstate_global->__pyx_b, name); + if (unlikely(!result) && !PyErr_Occurred()) { + PyErr_Format(PyExc_NameError, + "name '%U' is not defined", name); + } + return result; +} + +/* CopyObjectArray (used by TupleOrListFromArrayImpl) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} +#endif + +/* TupleOrListFromArrayImpl (used by TupleFromArray) */ +#if !(PY_VERSION_HEX >= 0x030F0000 && !CYTHON_COMPILING_IN_LIMITED_API) +CYTHON_UNUSED static PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) { + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + PyObject *res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + #if CYTHON_COMPILING_IN_CPYTHON + __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); + #else + Py_ssize_t i; + for (i = 0; i < n; i++) { + Py_INCREF(src[i]); + if (unlikely(__Pyx_PyTuple_SET_ITEM(res, i, src[i]) < (0))) { + Py_DECREF(res); + return NULL; + } + } + #endif + return res; +} +#endif + +/* FormatTypeName (used by pybuiltin_invalid) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static __Pyx_TypeName +__Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp) +{ + PyObject *module = NULL, *name = NULL, *result = NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_qualname); + #else + name = PyType_GetQualName(tp); + #endif + if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) goto bad; + module = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_module); + if (unlikely(module == NULL) || unlikely(!PyUnicode_Check(module))) goto bad; + if (PyUnicode_CompareWithASCIIString(module, "builtins") == 0) { + result = name; + name = NULL; + goto done; + } + result = PyUnicode_FromFormat("%U.%U", module, name); + if (unlikely(result == NULL)) goto bad; + done: + Py_XDECREF(name); + Py_XDECREF(module); + return result; + bad: + PyErr_Clear(); + if (name) { + result = name; + name = NULL; + } else { + result = __Pyx_NewRef(__pyx_mstate_global->__pyx_kp_u_); + } + goto done; +} +#endif + +/* pybuiltin_invalid (used by pyint_simplify) */ +static void __Pyx_PyBuiltin_Invalid(PyObject *obj, const char *builtin_type_name, const char *argname) { + __Pyx_TypeName obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!obj_type_name)) return; + #endif + if (argname) { + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected %.5s, got " __Pyx_FMT_TYPENAME ")", + argname, builtin_type_name, obj_type_name + ); + } else { + PyErr_Format(PyExc_TypeError, + "Expected %.5s, got " __Pyx_FMT_TYPENAME, + builtin_type_name, obj_type_name + ); + } + __Pyx_DECREF_TypeName(obj_type_name); +} + +/* pyint_simplify */ +static int __Pyx__PyInt_FromNumber(PyObject **number_var, const char *argname); +static CYTHON_INLINE int __Pyx_PyInt_FromNumber(PyObject **number_var, const char *argname, int accept_none) { + PyObject *number = *number_var; + if (likely((accept_none && number == Py_None) || PyLong_CheckExact(number))) { + return 0; + } + return __Pyx__PyInt_FromNumber(number_var, argname); +} +static int __Pyx__PyInt_FromNumber(PyObject **number_var, const char *argname) { + PyObject *number = *number_var; + PyObject *int_object; + if (likely(PyNumber_Check(number))) { + int_object = PyNumber_Long(number); + if (unlikely(!int_object)) goto bad; + } else { + __Pyx_PyBuiltin_Invalid(number, "int", argname); + goto bad; + } + *number_var = int_object; + Py_DECREF(number); + return 0; +bad: + *number_var = NULL; + Py_DECREF(number); + return -1; +} + +/* GettItemInt_wraparound (used by SetItemInt) */ +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY +static int __Pyx_GetItemInt_wraparound(PyObject *o, PySequenceMethods *sm, Py_ssize_t *i) { + assert(*i < 0); + if (likely(sm->sq_length)) { + Py_ssize_t l = sm->sq_length(o); + if (likely(l >= 0)) { + *i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return -1; + PyErr_Clear(); + } + } + return 0; +} +#endif + +/* SetItemInt */ +static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { + int r; + if (unlikely(!j)) return -1; + r = PyObject_SetItem(o, j, v); + Py_DECREF(j); + return r; +} +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY +static CYTHON_INLINE int __Pyx_SetItemInt_Fast_mapping(PyObject *o, objobjargproc setitem, Py_ssize_t i, PyObject *value) { + PyObject *key = PyLong_FromSsize_t(i); + if (unlikely(!key)) return -1; + int r = setitem(o, key, value); + Py_DECREF(key); + return r; +} +#endif +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE && !CYTHON_AVOID_BORROWED_REFS + if (PyList_CheckExact(o)) { + Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); + if ((CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS && !__Pyx_IS_UNIQUELY_REFERENCED(o, unsafe_shared))) { + Py_INCREF(v); + return PyList_SetItem(o, n, v); + } else if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o)))) { + PyObject* old; + Py_INCREF(v); + old = PyList_GET_ITEM(o, n); + PyList_SET_ITEM(o, n, v); + Py_DECREF(old); + return 0; + } + } else +#endif +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY + if (PyDict_CheckExact(o)) { + return __Pyx_SetItemInt_Fast_mapping(o, PyDict_Type.tp_as_mapping->mp_ass_subscript, i, v); + } else + { + PyTypeObject *obj_type = Py_TYPE(o); + int seq_or_mapping = __Pyx_PyType_GetFlags(obj_type) & (Py_TPFLAGS_SEQUENCE|Py_TPFLAGS_MAPPING); + if (seq_or_mapping != Py_TPFLAGS_SEQUENCE) { + PyMappingMethods *mm = obj_type->tp_as_mapping; + if (mm && mm->mp_ass_subscript) + return __Pyx_SetItemInt_Fast_mapping(o, mm->mp_ass_subscript, i, v); + } + PySequenceMethods *sm = obj_type->tp_as_sequence; + if (likely(sm && sm->sq_ass_item)) { + if (wraparound && (i < 0) && unlikely(__Pyx_GetItemInt_wraparound(o, sm, &i) == -1)) + return -1; + return sm->sq_ass_item(o, i, v); + } + if (seq_or_mapping == Py_TPFLAGS_SEQUENCE) { + PyMappingMethods *mm = obj_type->tp_as_mapping; + if (likely(mm && mm->mp_ass_subscript)) + return __Pyx_SetItemInt_Fast_mapping(o, mm->mp_ass_subscript, i, v); + } + } +#else + if (!PyMapping_Check(o)) { + return PySequence_SetItem(o, i, v); + } +#endif + (void)wraparound; + (void)boundscheck; + return __Pyx_SetItemInt_Generic(o, PyLong_FromSsize_t(i), v); +} + +/* PyFrozenDict (used by GetItemInt) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE PyObject* __Pyx__PyFrozenDict_New(PyObject* frozendict_type, PyObject* it) { + return PyObject_CallFunctionObjArgs(frozendict_type, it, NULL); +} +#endif + +/* GetItemInt */ +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (unlikely(!j)) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static PyObject *__Pyx_GetItemInt_Generic_size(PyObject *o, Py_ssize_t i) { + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_AVOID_BORROWED_REFS + CYTHON_UNUSED_VAR(boundscheck); + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + Py_ssize_t size = __Pyx_PyList_GET_SIZE(o); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(size < 0)) return NULL; + #endif + wrapped_i += size; + } + return __Pyx_PyList_GetItemRef(o, wrapped_i); +#elif CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + Py_ssize_t wrapped_i = i; + Py_ssize_t size = (wraparound | boundscheck) ? PyList_GET_SIZE(o) : -1; + if (wraparound & unlikely(i < 0)) { + wrapped_i += size; + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, size))) { + return __Pyx_PyList_GET_ITEM_REF(o, wrapped_i, unsafe_shared); + } + return __Pyx_GetItemInt_Generic_size(o, i); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_AVOID_BORROWED_REFS + CYTHON_UNUSED_VAR(boundscheck); + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + Py_ssize_t size = __Pyx_PyTuple_GET_SIZE(o); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(size < 0)) return NULL; + #endif + wrapped_i += size; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_COMPILING_IN_LIMITED_API + return PySequence_ITEM(o, wrapped_i); + #else + if (unlikely(wrapped_i < 0)) { + PyErr_SetString(PyExc_IndexError, "tuple index out of range"); + return NULL; + } + return PySequence_GetItem(o, wrapped_i); + #endif +#elif CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + Py_ssize_t wrapped_i = i; + Py_ssize_t size = (wraparound | boundscheck) ? PyTuple_GET_SIZE(o) : -1; + if (wraparound & unlikely(i < 0)) { + wrapped_i += size; + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, size))) { + return __Pyx_NewRef(__Pyx_PyTuple_GET_ITEM(o, wrapped_i)); + } + return __Pyx_GetItemInt_Generic_size(o, i); +#else + (void)wraparound; + (void)boundscheck; + return PySequence_GetItem(o, i); +#endif +} +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast_mapping(PyObject *o, binaryfunc getitem, Py_ssize_t i) { + PyObject *r, *key = PyLong_FromSsize_t(i); + if (unlikely(!key)) return NULL; + r = getitem(o, key); + Py_DECREF(key); + return r; +} +#endif +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck, int unsafe_shared) { + CYTHON_MAYBE_UNUSED_VAR(unsafe_shared); +#if CYTHON_ASSUME_SAFE_SIZE + if (PyList_CheckExact(o)) { + return __Pyx_GetItemInt_List_Fast(o, i, wraparound, boundscheck, unsafe_shared); + } else + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (PyTuple_CheckExact(o)) { + return __Pyx_GetItemInt_Tuple_Fast(o, i, wraparound, boundscheck, unsafe_shared); + } else + #endif +#else + if ((!wraparound || i >= 0) & PyList_CheckExact(o)) { + return boundscheck ? __Pyx_PyList_GetItemRef(o, i) : __Pyx_PyList_GET_ITEM_REF(o, i, unsafe_shared); + } else +#endif +#if CYTHON_USE_TYPE_SLOTS && !CYTHON_COMPILING_IN_PYPY + if (PyDict_CheckExact(o)) { + return __Pyx_GetItemInt_Fast_mapping(o, PyDict_Type.tp_as_mapping->mp_subscript, i); + #if defined(PyFrozenDict_CheckExact) + } else if (PyFrozenDict_CheckExact(o)) { + return __Pyx_GetItemInt_Fast_mapping(o, PyFrozenDict_Type.tp_as_mapping->mp_subscript, i); + #endif + } else + { + PyTypeObject *obj_type = Py_TYPE(o); + int seq_or_mapping = __Pyx_PyType_GetFlags(obj_type) & (Py_TPFLAGS_SEQUENCE|Py_TPFLAGS_MAPPING); + if (seq_or_mapping != Py_TPFLAGS_SEQUENCE) { + PyMappingMethods *mm = obj_type->tp_as_mapping; + if (mm && mm->mp_subscript) + return __Pyx_GetItemInt_Fast_mapping(o, mm->mp_subscript, i); + } + PySequenceMethods *sm = obj_type->tp_as_sequence; + if (likely(sm && sm->sq_item)) { + if (wraparound && (i < 0) && unlikely(__Pyx_GetItemInt_wraparound(o, sm, &i) == -1)) + return NULL; + return sm->sq_item(o, i); + } + if (seq_or_mapping == Py_TPFLAGS_SEQUENCE) { + PyMappingMethods *mm = obj_type->tp_as_mapping; + if (likely(mm && mm->mp_subscript)) + return __Pyx_GetItemInt_Fast_mapping(o, mm->mp_subscript, i); + } + } +#else + if (!PyMapping_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + (void)wraparound; + (void)boundscheck; + return __Pyx_GetItemInt_Generic_size(o, i); +} + +/* ListExtend */ +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030d0000) && !defined(PyList_Extend) +static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject* none = _PyList_Extend((PyListObject*)L, v); + if (unlikely(!none)) + return -1; + Py_DECREF(none); + return 0; +#else + return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); +#endif +} +#endif + +/* ListAppendAndDecrefInternal (used by ListAppend) */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE +static CYTHON_INLINE void __Pyx__ListComp_AppendAndDecref(PyObject* list, Py_ssize_t len, PyObject* x) { + PyList_SET_ITEM(list, len, x); + Py_SET_SIZE(list, len + 1); +} +#endif + +/* ListAppend */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + __Pyx__ListComp_AppendAndDecref(list, len, x); + return 0; + } + return PyList_Append(list, x); +} +#endif + +/* PyObjectCall */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = Py_TYPE(func)->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectCompare (used by UnicodeEquals) */ +#ifndef __Pyx_DEFINED_PyObject_CompareStrStrBoolEq +#define __Pyx_DEFINED_PyObject_CompareStrStrBoolEq +static CYTHON_INLINE int __Pyx_PyObject_CompareStrStrBoolEq(PyObject* s1, PyObject* s2) { + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + int result = PyUnicode_Equal(s1, s2); + #if !CYTHON_COMPILING_IN_CPYTHON + if (unlikely(result == -1)) return -1; + #endif + if (result == 0) goto __pyx_return_false; else goto __pyx_return_true; + #else + int result = PyUnicode_Compare(s1, s2); + if (unlikely((result == -1) && PyErr_Occurred())) return -1; + if (result == 0) goto __pyx_return_true; else goto __pyx_return_false; + #endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_str_str(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op1 == Py_None)) { + if (op2 == Py_None) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(op2 == Py_None)) { + if (op1 == Py_None) goto __pyx_return_true; else goto __pyx_return_false; + } + + if (likely(op1 != Py_None)) { + if (op1 == op2) goto __pyx_return_true; + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareStrStrBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* fastcall */ +#if CYTHON_VECTORCALL +static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) +{ + Py_ssize_t i, n = __Pyx_PyTuple_GET_SIZE(kwnames); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(n == -1)) return NULL; + #endif + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + if (s == namei) return kwvalues[i]; + } + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + int eq = __Pyx_PyUnicode_Equals(s, namei); + if (unlikely(eq != 0)) { + if (unlikely(eq < 0)) return NULL; + return kwvalues[i]; + } + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL +CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { + Py_ssize_t i, nkwargs; + PyObject *dict; +#if !CYTHON_ASSUME_SAFE_SIZE + nkwargs = PyTuple_Size(kwnames); + if (unlikely(nkwargs < 0)) return NULL; +#else + nkwargs = PyTuple_GET_SIZE(kwnames); +#endif + dict = PyDict_New(); + if (unlikely(!dict)) + return NULL; + for (i=0; i<nkwargs; i++) { +#if !CYTHON_ASSUME_SAFE_MACROS + PyObject *key = PyTuple_GetItem(kwnames, i); + if (!key) goto bad; +#else + PyObject *key = PyTuple_GET_ITEM(kwnames, i); +#endif + if (unlikely(PyDict_SetItem(dict, key, kwvalues[i]) < 0)) + goto bad; + } + return dict; +bad: + Py_DECREF(dict); + return NULL; +} +#endif +#endif + +/* PyObjectCallMethO (used by PyObjectFastCall) */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); + self = __Pyx_CyOrPyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectFastCall (used by PyObjectCallOneArg) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs) { + PyObject *argstuple; + PyObject *result = 0; + size_t i; + argstuple = PyTuple_New((Py_ssize_t)nargs); + if (unlikely(!argstuple)) return NULL; + for (i = 0; i < nargs; i++) { + Py_INCREF(args[i]); + if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) != (0)) goto bad; + } + result = __Pyx_PyObject_Call(func, argstuple, kwargs); + bad: + Py_DECREF(argstuple); + return result; +} +#endif +#if CYTHON_VECTORCALL && !(CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY) + #if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE vectorcallfunc __Pyx_PyVectorcall_Function(PyObject *callable) { + PyTypeObject *tp = Py_TYPE(callable); + #if defined(__Pyx_CyFunction_USED) + if (__Pyx_CyFunction_CheckExact(callable)) { + return __Pyx_CyFunction_func_vectorcall(callable); + } + #endif + if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) { + return NULL; + } + assert(PyCallable_Check(callable)); + Py_ssize_t offset = tp->tp_vectorcall_offset; + assert(offset > 0); + vectorcallfunc ptr; + memcpy(&ptr, (char *) callable + offset, sizeof(ptr)); + return ptr; +} + #else + #define __Pyx_PyVectorcall_Function(callable) PyVectorcall_Function(callable) + #endif +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwargs) { + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(nargsf); +#if CYTHON_COMPILING_IN_CPYTHON + if (nargs == 0 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) + return __Pyx_PyObject_CallMethO(func, NULL); + } + else if (nargs == 1 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) + return __Pyx_PyObject_CallMethO(func, args[0]); + } +#endif + if (kwargs == NULL) { + #if CYTHON_VECTORCALL + #if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + return PyObject_Vectorcall(func, args, nargsf, NULL); + #else + vectorcallfunc f = __Pyx_PyVectorcall_Function(func); + if (f) { + return f(func, args, nargsf, NULL); + } + #endif + #endif + } + if (nargs == 0) { + return __Pyx_PyObject_Call(func, __pyx_mstate_global->__pyx_empty_tuple, kwargs); + } + #if CYTHON_COMPILING_IN_LIMITED_API + return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); + #elif CYTHON_COMPILING_IN_PYPY + return PyObject_VectorcallDict(func, args, (size_t) nargs, kwargs); + #else + return PyObject_VectorcallDict(func, args, nargsf, kwargs); + #endif +} + +/* PyObjectCallOneArg (used by CallUnboundCMethod0) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *args[2] = {NULL, arg}; + return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* IgnoreException (used by UnpackUnboundCMethod_impl) */ +static CYTHON_INLINE int __Pyx_IgnoreGivenException(PyObject *given_exception, PyObject *ignorable_exception) { + if (PyErr_GivenExceptionMatches(given_exception ? given_exception : PyErr_Occurred(), ignorable_exception)) { + PyErr_Clear(); + return 1; + } + return 0; +} + +/* UnpackUnboundCMethod_impl (used by UnpackUnboundCMethod) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { + PyObject *result; + PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); + if (unlikely(!selfless_args)) return NULL; + result = PyObject_Call(method, selfless_args, kwargs); + Py_DECREF(selfless_args); + return result; +} +#else +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { + return PyObject_Vectorcall(method, args ? args+1 : NULL, nargs ? (size_t) nargs-1 : 0, kwnames); +} +#endif +static PyMethodDef __Pyx_UnboundCMethod_Def = { + "CythonUnboundCMethod", + __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_SelflessCall), +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 + METH_VARARGS | METH_KEYWORDS, +#else + METH_FASTCALL | METH_KEYWORDS, +#endif + NULL +}; +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { + PyObject *method, *result=NULL; + method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); + if (unlikely(!method)) + return -1; + result = method; +#if CYTHON_COMPILING_IN_CPYTHON + if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) + { + PyMethodDescrObject *descr = (PyMethodDescrObject*) method; + target->func = descr->d_method->ml_meth; + target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST); + } else +#endif +#if CYTHON_COMPILING_IN_PYPY +#else + if (PyCFunction_Check(method)) +#endif + { + PyObject *self; + int self_found; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + self = PyObject_GetAttrString(method, "__self__"); + if (!self && !__Pyx_IgnoreException(PyExc_AttributeError)) { + return -1; + } +#else + self = PyCFunction_GET_SELF(method); +#endif + self_found = (self && self != Py_None); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + Py_XDECREF(self); +#endif + if (self_found) { + PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); + if (unlikely(!unbound_method)) return -1; + Py_DECREF(method); + result = unbound_method; + } + } +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if (unlikely(target->method)) { + Py_DECREF(result); + } else +#endif + target->method = result; + return 0; +} + +/* CallUnboundCMethod0 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + if (likely(cfunc->flag == METH_NOARGS)) + return __Pyx_CallCFunction(cfunc, self, NULL); + if (likely(cfunc->flag == METH_FASTCALL)) + return __Pyx_CallCFunctionFast(cfunc, self, NULL, 0); + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, NULL, 0, NULL); + if (likely(cfunc->flag == (METH_VARARGS | METH_KEYWORDS))) + return __Pyx_CallCFunctionWithKeywords(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple, NULL); + if (cfunc->flag == METH_VARARGS) + return __Pyx_CallCFunction(cfunc, self, __pyx_mstate_global->__pyx_empty_tuple); + return __Pyx__CallUnboundCMethod0(cfunc, self); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod0(&tmp_cfunc, self); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod0(cfunc, self); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + PyObject *result; + if (unlikely(!cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; + result = __Pyx_PyObject_CallOneArg(cfunc->method, self); + return result; +} + +/* py_dict_items (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_items, d); +} + +/* py_dict_values (used by OwnedDictNext) */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) { + return __Pyx_CallUnboundCMethod0(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_values, d); +} + +/* OwnedDictNext (used by ParseKeywordsImpl) */ +#if CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, PyObject **ppos, PyObject **pkey, PyObject **pvalue) { + PyObject *next = NULL; + if (!*ppos) { + if (pvalue) { + PyObject *dictview = pkey ? __Pyx_PyDict_Items(p) : __Pyx_PyDict_Values(p); + if (unlikely(!dictview)) goto bad; + *ppos = PyObject_GetIter(dictview); + Py_DECREF(dictview); + } else { + *ppos = PyObject_GetIter(p); + } + if (unlikely(!*ppos)) goto bad; + } + next = PyIter_Next(*ppos); + if (!next) { + if (PyErr_Occurred()) goto bad; + return 0; + } + if (pkey && pvalue) { + *pkey = __Pyx_PySequence_ITEM(next, 0); + if (unlikely(*pkey)) goto bad; + *pvalue = __Pyx_PySequence_ITEM(next, 1); + if (unlikely(*pvalue)) goto bad; + Py_DECREF(next); + } else if (pkey) { + *pkey = next; + } else { + assert(pvalue); + *pvalue = next; + } + return 1; + bad: + Py_XDECREF(next); +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 + PyErr_FormatUnraisable("Exception ignored in __Pyx_PyDict_NextRef"); +#else + PyErr_WriteUnraisable(__pyx_mstate_global->__pyx_n_u_Pyx_PyDict_NextRef); +#endif + if (pkey) *pkey = NULL; + if (pvalue) *pvalue = NULL; + return 0; +} +#else // !CYTHON_AVOID_BORROWED_REFS +static int __Pyx_PyDict_NextRef(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { + int result = PyDict_Next(p, ppos, pkey, pvalue); + if (likely(result == 1)) { + if (pkey) Py_INCREF(*pkey); + if (pvalue) Py_INCREF(*pvalue); + } + return result; +} +#endif + +/* RaiseDoubleKeywords (used by ParseKeywordsImpl) */ +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); +} + +/* CallUnboundCMethod2 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + PyObject *args[2] = {arg1, arg2}; + if (cfunc->flag == METH_FASTCALL) { + return __Pyx_CallCFunctionFast(cfunc, self, args, 2); + } + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, 2, NULL); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod2(&tmp_cfunc, self, arg1, arg2); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2){ + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + PyObject *result = NULL; + PyObject *args = PyTuple_New(2); + if (unlikely(!args)) return NULL; + Py_INCREF(arg1); + PyTuple_SET_ITEM(args, 0, arg1); + Py_INCREF(arg2); + PyTuple_SET_ITEM(args, 1, arg2); + if (cfunc->flag & METH_KEYWORDS) + result = __Pyx_CallCFunctionWithKeywords(cfunc, self, args, NULL); + else + result = __Pyx_CallCFunction(cfunc, self, args); + Py_DECREF(args); + return result; + } +#endif + { + PyObject *args[4] = {NULL, self, arg1, arg2}; + return __Pyx_PyObject_FastCall(cfunc->method, args+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); + } +} + +/* ParseKeywordsImpl (used by ParseKeywords) */ +static int __Pyx_ValidateDuplicatePosArgs( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char* function_name) +{ + PyObject ** const *name = argnames; + while (name != first_kw_arg) { + PyObject *key = **name; + int found = PyDict_Contains(kwds, key); + if (unlikely(found)) { + if (found == 1) __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; + } + name++; + } + return 0; +bad: + return -1; +} +#if CYTHON_USE_UNICODE_INTERNALS +static CYTHON_INLINE int __Pyx_UnicodeKeywordsEqual(PyObject *s1, PyObject *s2) { + int kind; + Py_ssize_t len = PyUnicode_GET_LENGTH(s1); + if (len != PyUnicode_GET_LENGTH(s2)) return 0; + kind = PyUnicode_KIND(s1); + if (kind != PyUnicode_KIND(s2)) return 0; + const void *data1 = PyUnicode_DATA(s1); + const void *data2 = PyUnicode_DATA(s2); + return (memcmp(data1, data2, (size_t) len * (size_t) kind) == 0); +} +#endif +static int __Pyx_MatchKeywordArg_str( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + #if CYTHON_USE_UNICODE_INTERNALS + Py_hash_t key_hash = ((PyASCIIObject*)key)->hash; + if (unlikely(key_hash == -1)) { + key_hash = PyObject_Hash(key); + if (unlikely(key_hash == -1)) + goto bad; + } + #endif + name = first_kw_arg; + while (*name) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (key_hash == ((PyASCIIObject*)name_str)->hash && __Pyx_UnicodeKeywordsEqual(name_str, key)) { + *index_found = (size_t) (name - argnames); + return 1; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + *index_found = (size_t) (name - argnames); + return 1; + } + } + #endif + name++; + } + name = argnames; + while (name != first_kw_arg) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (unlikely(key_hash == ((PyASCIIObject*)name_str)->hash)) { + if (__Pyx_UnicodeKeywordsEqual(name_str, key)) + goto arg_passed_twice; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + if (unlikely(name_str == key)) goto arg_passed_twice; + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + } + #endif + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +bad: + return -1; +} +static int __Pyx_MatchKeywordArg_nostr( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + if (unlikely(!PyUnicode_Check(key))) goto invalid_keyword_type; + name = first_kw_arg; + while (*name) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (cmp == 1) { + *index_found = (size_t) (name - argnames); + return 1; + } + if (unlikely(cmp == -1)) goto bad; + name++; + } + name = argnames; + while (name != first_kw_arg) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (unlikely(cmp != 0)) { + if (cmp == 1) goto arg_passed_twice; + else goto bad; + } + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +bad: + return -1; +} +static CYTHON_INLINE int __Pyx_MatchKeywordArg( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + return likely(PyUnicode_CheckExact(key)) ? + __Pyx_MatchKeywordArg_str(key, argnames, first_kw_arg, index_found, function_name) : + __Pyx_MatchKeywordArg_nostr(key, argnames, first_kw_arg, index_found, function_name); +} +static void __Pyx_RejectUnknownKeyword( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char *function_name) +{ + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos = NULL; + #else + Py_ssize_t pos = 0; + #endif + PyObject *key = NULL; + __Pyx_BEGIN_CRITICAL_SECTION(kwds); + #if CYTHON_AVOID_BORROWED_REFS + while (__Pyx_PyDict_NextRef(kwds, &pos, &key, NULL)) + #else + (void) __Pyx_PyDict_NextRef; + while (PyDict_Next(kwds, &pos, &key, NULL)) + #endif + { + PyObject** const *name = first_kw_arg; + while (*name && (**name != key)) name++; + if (!*name) { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp != 1) { + if (cmp == 0) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + break; + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + } + __Pyx_END_CRITICAL_SECTION(); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(pos); + #endif + assert(PyErr_Occurred()); +} +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t extracted = 0; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + name = first_kw_arg; + while (*name && num_kwargs > extracted) { + PyObject * key = **name; + PyObject *value; + int found = 0; + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + found = PyDict_GetItemRef(kwds, key, &value); + #else + value = PyDict_GetItemWithError(kwds, key); + if (value) { + Py_INCREF(value); + found = 1; + } else { + if (unlikely(PyErr_Occurred())) goto bad; + } + #endif + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + extracted++; + } + name++; + } + if (num_kwargs > extracted) { + if (ignore_unknown_kwargs) { + if (unlikely(__Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name) == -1)) + goto bad; + } else { + __Pyx_RejectUnknownKeyword(kwds, argnames, first_kw_arg, function_name); + goto bad; + } + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t len; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + if (PyDict_Update(kwds2, kwds) < 0) goto bad; + name = first_kw_arg; + while (*name) { + PyObject *key = **name; + PyObject *value; +#if !CYTHON_COMPILING_IN_LIMITED_API && (PY_VERSION_HEX >= 0x030d00A2 || defined(PyDict_Pop)) + int found = PyDict_Pop(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int found = PyDict_GetItemRef(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + if (unlikely(PyDict_DelItem(kwds2, key) < 0)) goto bad; + } +#else + #if CYTHON_COMPILING_IN_CPYTHON + value = _PyDict_Pop(kwds2, key, kwds2); + #else + value = __Pyx_CallUnboundCMethod2(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_pop, kwds2, key, kwds2); + #endif + if (value == kwds2) { + Py_DECREF(value); + } else { + if (unlikely(!value)) goto bad; + values[name-argnames] = value; + } +#endif + name++; + } + len = PyDict_Size(kwds2); + if (len > 0) { + return __Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name); + } else if (unlikely(len == -1)) { + goto bad; + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject *key = NULL; + PyObject** const * name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + for (Py_ssize_t pos = 0; pos < num_kwargs; pos++) { +#if CYTHON_AVOID_BORROWED_REFS + key = __Pyx_PySequence_ITEM(kwds, pos); +#else + key = __Pyx_PyTuple_GET_ITEM(kwds, pos); +#endif +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!key)) goto bad; +#endif + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + PyObject *value = kwvalues[pos]; + values[name-argnames] = __Pyx_NewRef(value); + } else { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp == 1) { + PyObject *value = kwvalues[pos]; + values[index_found] = __Pyx_NewRef(value); + } else { + if (unlikely(cmp == -1)) goto bad; + if (kwds2) { + PyObject *value = kwvalues[pos]; + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else if (!ignore_unknown_kwargs) { + goto invalid_keyword; + } + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + key = NULL; + #endif + } + return 0; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + goto bad; +bad: + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(key); + #endif + return -1; +} + +/* ParseKeywords */ +static int __Pyx_ParseKeywords( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + if (CYTHON_VECTORCALL && likely(PyTuple_Check(kwds))) + return __Pyx_ParseKeywordsTuple(kwds, kwvalues, argnames, kwds2, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); + else if (kwds2) + return __Pyx_ParseKeywordDictToDict(kwds, argnames, kwds2, values, num_pos_args, function_name); + else + return __Pyx_ParseKeywordDict(kwds, argnames, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); +} + +/* RaiseArgTupleInvalid */ +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +/* RaiseException */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { + instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyException_SetTraceback(value, tb); +#elif CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} + +/* PyLongBinop */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_Fallback___Pyx_PyLong_AddObjC(PyObject *op1, PyObject *op2, int inplace) { + return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); +} +#if CYTHON_USE_PYLONG_INTERNALS +static PyObject* __Pyx_Unpacked___Pyx_PyLong_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(inplace); + CYTHON_UNUSED_VAR(zerodivision_check); + const long b = intval; + long a; + const PY_LONG_LONG llb = intval; + PY_LONG_LONG lla; + if (unlikely(__Pyx_PyLong_IsZero(op1))) { + return __Pyx_NewRef(op2); + } + const int is_positive = __Pyx_PyLong_IsPos(op1); + const digit* digits = __Pyx_PyLong_Digits(op1); + const Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (likely(size == 1)) { + a = (long) digits[0]; + if (!is_positive) a *= -1; + } else { + if (size == 2 && 8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + if (!is_positive) a *= -1; + goto calculate_long; + } else if (size == 2 && 8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + if (!is_positive) lla *= -1; + goto calculate_long_long; + } else + if (size == 3 && 8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + if (!is_positive) a *= -1; + goto calculate_long; + } else if (size == 3 && 8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + if (!is_positive) lla *= -1; + goto calculate_long_long; + } else + if (size == 4 && 8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + if (!is_positive) a *= -1; + goto calculate_long; + } else if (size == 4 && 8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + if (!is_positive) lla *= -1; + goto calculate_long_long; + } else + {} + return PyLong_Type.tp_as_number->nb_add(op1, op2); + } + calculate_long: + { + long x; + x = a + b; + return PyLong_FromLong(x); + } + calculate_long_long: + { + PY_LONG_LONG llx; + llx = lla + llb; + return PyLong_FromLongLong(llx); + } + +} +#endif +static PyObject* __Pyx_Float___Pyx_PyLong_AddObjC(PyObject *float_val, long intval, int zerodivision_check) { + CYTHON_UNUSED_VAR(zerodivision_check); + const long b = intval; + double a = __Pyx_PyFloat_AS_DOUBLE(float_val); + double result; + + result = ((double)a) + (double)b; + return PyFloat_FromDouble(result); +} +static CYTHON_INLINE PyObject* __Pyx_PyLong_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_UNUSED_VAR(zerodivision_check); + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + return __Pyx_Unpacked___Pyx_PyLong_AddObjC(op1, op2, intval, inplace, zerodivision_check); + } + #endif + if (PyFloat_CheckExact(op1)) { + return __Pyx_Float___Pyx_PyLong_AddObjC(op1, intval, zerodivision_check); + } + return __Pyx_Fallback___Pyx_PyLong_AddObjC(op1, op2, inplace); +} +#endif + +/* ListCompAppend */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + __Pyx__ListComp_AppendAndDecref(list, len, x); + return 0; + } + return PyList_Append(list, x); +} +#endif + +/* IterNextPlain (used by IterNext) */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject *__Pyx_GetBuiltinNext_LimitedAPI(void) { + if (unlikely(!__pyx_mstate_global->__Pyx_GetBuiltinNext_LimitedAPI_cache)) + __pyx_mstate_global->__Pyx_GetBuiltinNext_LimitedAPI_cache = __Pyx_GetBuiltinName(__pyx_mstate_global->__pyx_n_u_next); + return __pyx_mstate_global->__Pyx_GetBuiltinNext_LimitedAPI_cache; +} +#endif +static CYTHON_INLINE PyObject *__Pyx_PyIter_Next_Plain(PyObject *iterator) { +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + PyObject *result; + PyObject *next = __Pyx_GetBuiltinNext_LimitedAPI(); + if (unlikely(!next)) return NULL; + result = PyObject_CallFunctionObjArgs(next, iterator, NULL); + return result; +#else + (void)__Pyx_GetBuiltinName; // only for early limited API + iternextfunc iternext = __Pyx_PyObject_GetIterNextFunc(iterator); + assert(iternext); + return iternext(iterator); +#endif +} + +/* RaiseErrorWithObjectType (used by IterNext) */ +static void __Pyx_RaiseErrorWithType(PyObject* exc_type, const char* message, PyTypeObject *type_obj) { + __Pyx_TypeName type_name = __Pyx_PyType_GetFullyQualifiedName(type_obj); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!type_name)) return; + #endif + PyErr_Format(exc_type, message, type_name); + __Pyx_DECREF_TypeName(type_name); +} + +/* IterNext */ +static PyObject *__Pyx_PyIter_Next2Default(PyObject* defval) { + PyObject* exc_type; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + exc_type = __Pyx_PyErr_CurrentExceptionType(); + if (unlikely(exc_type)) { + if (!defval || unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) + return NULL; + __Pyx_PyErr_Clear(); + Py_INCREF(defval); + return defval; + } + if (defval) { + Py_INCREF(defval); + return defval; + } + __Pyx_PyErr_SetNone(PyExc_StopIteration); + return NULL; +} +static void __Pyx_PyIter_Next_ErrorNoIterator(PyObject *iterator) { + __Pyx_RaiseTypeErrorWithObjectType( + __Pyx_FMT_TYPENAME " object is not an iterator", iterator); +} +static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject* iterator, PyObject* defval) { + PyObject* next; +#if !CYTHON_COMPILING_IN_LIMITED_API + iternextfunc iternext = __Pyx_PyObject_TryGetSlot(iterator, tp_iternext, iternextfunc); + if (likely(iternext)) { + next = iternext(iterator); + if (likely(next)) + return next; + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000 + if (unlikely(iternext == &_PyObject_NextNotImplemented)) + return NULL; + #endif + } else if (CYTHON_USE_TYPE_SLOTS) { + __Pyx_PyIter_Next_ErrorNoIterator(iterator); + return NULL; + } else +#endif + if (unlikely(!PyIter_Check(iterator))) { + __Pyx_PyIter_Next_ErrorNoIterator(iterator); + return NULL; + } else { + next = defval ? PyIter_Next(iterator) : __Pyx_PyIter_Next_Plain(iterator); + if (likely(next)) + return next; + } + return __Pyx_PyIter_Next2Default(defval); +} + +/* PyLongCompare */ +static CYTHON_INLINE int __Pyx_PyLong_BoolNeObjC(PyObject *op1, PyObject *op2, long intval, long inplace) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_UNUSED_VAR(inplace); + if (op1 == op2) { + return 0; + } + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + int unequal; + unsigned long uintval; + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + const digit* digits = __Pyx_PyLong_Digits(op1); + if (intval == 0) { + return (__Pyx_PyLong_IsZero(op1) != 1); + } else if (intval < 0) { + if (__Pyx_PyLong_IsNonNeg(op1)) + return 1; + intval = -intval; + } else { + if (__Pyx_PyLong_IsNeg(op1)) + return 1; + } + uintval = (unsigned long) intval; +#if PyLong_SHIFT * 4 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 4)) { + unequal = (size != 5) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[4] != ((uintval >> (4 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 3 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 3)) { + unequal = (size != 4) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 2 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 2)) { + unequal = (size != 3) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 1 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 1)) { + unequal = (size != 2) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif + unequal = (size != 1) || (((unsigned long) digits[0]) != (uintval & (unsigned long) PyLong_MASK)); + return (unequal != 0); + } + #endif + if (PyFloat_CheckExact(op1)) { + const long b = intval; + double a = __Pyx_PyFloat_AS_DOUBLE(op1); + return ((double)a != (double)b); + } + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_NE); +} + +/* SliceObject */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice(PyObject* obj, + Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { +#if CYTHON_USE_TYPE_SLOTS + PyMappingMethods* mp = Py_TYPE(obj)->tp_as_mapping; + if (likely(mp && mp->mp_subscript)) +#else + if ((1)) +#endif + { + PyObject* result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; + } else { + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyLong_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; + } + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyLong_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } +#if CYTHON_USE_TYPE_SLOTS + result = mp->mp_subscript(obj, py_slice); +#else + result = PyObject_GetItem(obj, py_slice); +#endif + if (!_py_slice) { + Py_DECREF(py_slice); + } + return result; + } else { + __Pyx_RaiseTypeErrorWithObjectType( + "'" __Pyx_FMT_TYPENAME "' object is unsliceable", obj); + } +bad: + return NULL; +} + +/* ObjectGetItem */ +#if CYTHON_USE_TYPE_SLOTS +static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject *index) { + PyObject *runerr = NULL; + Py_ssize_t key_value; + key_value = __Pyx_PyIndex_AsSsize_t(index); + if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { + return __Pyx_GetItemInt_Fast(obj, key_value, 1, 1, 1); + } + if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { + PyErr_Clear(); + __Pyx_RaiseErrorWithObjectType( + PyExc_IndexError, + "cannot fit '" __Pyx_FMT_TYPENAME "' into an index-sized integer", + index); + } + return NULL; +} +static PyObject *__Pyx_PyObject_GetItem_Slow(PyObject *obj, PyObject *key) { + if (likely(PyType_Check(obj))) { + if ((PyTypeObject*)obj == &PyType_Type) { + return Py_GenericAlias(obj, key); + } + PyObject *meth = __Pyx_PyObject_GetAttrStrNoError(obj, __pyx_mstate_global->__pyx_n_u_class_getitem); + if (!meth) { + if (PyErr_Occurred()) { + return NULL; + } + } else { + PyObject *result = __Pyx_PyObject_CallOneArg(meth, key); + Py_DECREF(meth); + return result; + } + } + __Pyx_RaiseTypeErrorWithObjectType( + "'" __Pyx_FMT_TYPENAME "' object is not subscriptable", obj); + return NULL; +} +static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject *key) { + PyTypeObject *tp = Py_TYPE(obj); + PyMappingMethods *mm = tp->tp_as_mapping; + PySequenceMethods *sm = tp->tp_as_sequence; + if (likely(mm && mm->mp_subscript)) { + return mm->mp_subscript(obj, key); + } + if (likely(sm && sm->sq_item)) { + return __Pyx_PyObject_GetIndex(obj, key); + } + return __Pyx_PyObject_GetItem_Slow(obj, key); +} +#endif + +/* RaiseErrorWithObjectTypes (used by PyNumberBinop) */ +static void __Pyx_RaiseErrorWithTypes1(PyObject* exc_type, const char *message, const char *arg, PyTypeObject *type_obj1, PyTypeObject *type_obj2) { + __Pyx_TypeName type_name1 = __Pyx_PyType_GetFullyQualifiedName(type_obj1); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!type_name1)) return; + #endif + __Pyx_TypeName type_name2 = __Pyx_PyType_GetFullyQualifiedName(type_obj2); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!type_name2)) goto type2_failed; + #endif + PyErr_Format(exc_type, message, arg, type_name1, type_name2); + __Pyx_DECREF_TypeName(type_name2); +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +type2_failed: +#endif + __Pyx_DECREF_TypeName(type_name1); +} + +/* PyNumberBinop */ +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API) +#if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#ifndef __Pyx_DEFINED_BinopTypeError +#define __Pyx_DEFINED_BinopTypeError +static void __Pyx_BinopTypeError(PyObject *op1, PyObject *op2, const char* op, int inplace) { + char opname[4] = {op[0], op[1], 0, 0}; + if (inplace) { + opname[op[1] ? 2 : 1] = '='; + } + __Pyx_RaiseErrorWithObjectTypes1( + PyExc_TypeError, + "unsupported operand type(s) for %.3s: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", + opname, op1, op2); +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyNumber_Subtract_xfloat_object +#define __Pyx_DEFINED_PyNumber_Subtract_xfloat_object +static PyObject* __Pyx_PyNumber_Subtract_xfloat_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyLong_CheckExact(op2)) { + double int_op2; + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t compact_op2 = __Pyx_PyLong_CompactValue(op2); + if (compact_op2 == 0) return __Pyx_NewRef(op1); + int_op2 = (double) compact_op2; + } else + #endif + { + int_op2 = PyLong_AsDouble(op2); + if (unlikely((int_op2 == -1.) && PyErr_Occurred())) return NULL; + #if !CYTHON_USE_PYLONG_INTERNALS + if (int_op2 == 0.) return __Pyx_NewRef(op1); + #endif + } + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op1 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(float_op1 - int_op2); + } + if (PyLong_Check(op2)) { + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(&PyFloat_Type, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + return slot_func(op1, op2); + } + } + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "-", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2); + #endif +} +#endif +#ifndef __Pyx_DEFINED_PyNumber_Subtract_xint_object +#define __Pyx_DEFINED_PyNumber_Subtract_xint_object +static PyObject* __Pyx_PyNumber_Subtract_xint_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyFloat_CheckExact(op2)) { + double int_op1; + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t compact_op1 = __Pyx_PyLong_CompactValue(op1); + int_op1 = (double) compact_op1; + } else + #endif + { + int_op1 = PyLong_AsDouble(op1); + if (unlikely((int_op1 == -1.) && PyErr_Occurred())) return NULL; + } + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op2 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(int_op1 - float_op2); + } + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "-", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2); + #endif +} +#endif +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Subtract_object_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyFloat_CheckExact(op1)) { + if (PyFloat_CheckExact(op2)) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op2 == -1.) && PyErr_Occurred())) return NULL; + #endif + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op1 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(float_op1 - float_op2); + } + return __Pyx_PyNumber_Subtract_xfloat_object(op1, op2, inplace); + } + if (PyLong_CheckExact(op1)) { + if (PyLong_CheckExact(op2)) { + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t int_op1 = __Pyx_PyLong_CompactValue(op1); + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t int_op2 = __Pyx_PyLong_CompactValue(op2); + if (int_op2 == 0) return __Pyx_NewRef(op1); + return PyLong_FromSsize_t(int_op1 - int_op2); + } + } + else if (__Pyx_PyLong_IsZero(op2)) return __Pyx_NewRef(op1); + #endif + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(&PyLong_Type, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + return slot_func(op1, op2); + } + } + return __Pyx_PyNumber_Subtract_xint_object(op1, op2, inplace); + } + return (inplace) ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2); +} +#endif + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolGt +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolGt +static int __Pyx_PyObject_CompareFloatIntBoolGt(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 > ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 > 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_true; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign2 > 0) goto __pyx_return_false; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 > 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 > ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_false; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_true; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_GT); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolGt +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolGt +static int __Pyx_PyObject_CompareIntIntBoolGt(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_false; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + if (cmp < 0) goto __pyx_return_false; else goto __pyx_return_true; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 > iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 > overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_GT); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolGt_object_int(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op2 == Py_None)) { + goto __pyx_richcmp; + } + if (op1 == op2) goto __pyx_return_false; + if (PyFloat_CheckExact(op1)) { + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareFloatIntBoolGt(op1, op2); + } + goto __pyx_richcmp; + } + if (likely(PyLong_CheckExact(op1))) { + if (op1 == op2) goto __pyx_return_false; + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareIntIntBoolGt(op1, op2); + } + goto __pyx_richcmp; + } + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_GT); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* PyLongBinop */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_Fallback___Pyx_PyLong_SubtractObjC(PyObject *op1, PyObject *op2, int inplace) { + return (inplace ? PyNumber_InPlaceSubtract : PyNumber_Subtract)(op1, op2); +} +#if CYTHON_USE_PYLONG_INTERNALS +static PyObject* __Pyx_Unpacked___Pyx_PyLong_SubtractObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(inplace); + CYTHON_UNUSED_VAR(zerodivision_check); + const long b = intval; + long a; + const PY_LONG_LONG llb = intval; + PY_LONG_LONG lla; + if (unlikely(__Pyx_PyLong_IsZero(op1))) { + return PyLong_FromLong(-intval); + } + const int is_positive = __Pyx_PyLong_IsPos(op1); + const digit* digits = __Pyx_PyLong_Digits(op1); + const Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (likely(size == 1)) { + a = (long) digits[0]; + if (!is_positive) a *= -1; + } else { + if (size == 2 && 8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + if (!is_positive) a *= -1; + goto calculate_long; + } else if (size == 2 && 8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + if (!is_positive) lla *= -1; + goto calculate_long_long; + } else + if (size == 3 && 8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + if (!is_positive) a *= -1; + goto calculate_long; + } else if (size == 3 && 8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + if (!is_positive) lla *= -1; + goto calculate_long_long; + } else + if (size == 4 && 8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + if (!is_positive) a *= -1; + goto calculate_long; + } else if (size == 4 && 8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + if (!is_positive) lla *= -1; + goto calculate_long_long; + } else + {} + return PyLong_Type.tp_as_number->nb_subtract(op1, op2); + } + calculate_long: + { + long x; + x = a - b; + return PyLong_FromLong(x); + } + calculate_long_long: + { + PY_LONG_LONG llx; + llx = lla - llb; + return PyLong_FromLongLong(llx); + } + +} +#endif +static PyObject* __Pyx_Float___Pyx_PyLong_SubtractObjC(PyObject *float_val, long intval, int zerodivision_check) { + CYTHON_UNUSED_VAR(zerodivision_check); + const long b = intval; + double a = __Pyx_PyFloat_AS_DOUBLE(float_val); + double result; + + result = ((double)a) - (double)b; + return PyFloat_FromDouble(result); +} +static CYTHON_INLINE PyObject* __Pyx_PyLong_SubtractObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_UNUSED_VAR(zerodivision_check); + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + return __Pyx_Unpacked___Pyx_PyLong_SubtractObjC(op1, op2, intval, inplace, zerodivision_check); + } + #endif + if (PyFloat_CheckExact(op1)) { + return __Pyx_Float___Pyx_PyLong_SubtractObjC(op1, intval, zerodivision_check); + } + return __Pyx_Fallback___Pyx_PyLong_SubtractObjC(op1, op2, inplace); +} +#endif + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolNe +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolNe +static int __Pyx_PyObject_CompareFloatIntBoolNe(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 != ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 != 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_true; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } else { + if (sign2 > 0) goto __pyx_return_true; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 != 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 != ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_true; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_NE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolNe +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolNe +static int __Pyx_PyObject_CompareIntIntBoolNe(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_false; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + goto __pyx_return_true; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 != iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 != overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_NE); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolNe_object_int(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op2 == Py_None)) { + if (op1 == Py_None) goto __pyx_return_false; else goto __pyx_richcmp; + } + if (op1 == op2) goto __pyx_return_false; + if (PyFloat_CheckExact(op1)) { + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareFloatIntBoolNe(op1, op2); + } + goto __pyx_richcmp; + } + if (likely(PyLong_CheckExact(op1))) { + if (op1 == op2) goto __pyx_return_false; + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareIntIntBoolNe(op1, op2); + } + goto __pyx_richcmp; + } + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_NE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareIntFloatBoolEq +#define __Pyx_DEFINED_PyObject_CompareIntFloatBoolEq +static int __Pyx_PyObject_CompareIntFloatBoolEq(PyObject *op1, PyObject *op2) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t iop1 = __Pyx_PyLong_CompactValue(op1); + if (((double)iop1) == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op2))) { + if (0.0 == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign1 = __Pyx_PyLong_Sign(op1); + if (float_op2 >= 0.) { + if (sign1 < 0) goto __pyx_return_false; + if (float_op2 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign1 > 0) goto __pyx_return_false; + if (float_op2 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op2))) { + if (0.0 == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow1; + long iop1 = PyLong_AsLongAndOverflow(op1, &overflow1); + if (likely(!overflow1)) { + if ((long long) iop1 >= (1LL << 53)) { + overflow1 = 1; + } else if ((long long) iop1 <= - (1LL << 53)) { + overflow1 = -1; + } else { + if (((double) iop1) == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow1 < 0) { + if (float_op2 > ((double) (1LL << 53))) goto __pyx_return_false; + } else { + if (float_op2 < - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolEq +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolEq +static int __Pyx_PyObject_CompareIntIntBoolEq(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_true; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + goto __pyx_return_false; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 == iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 == overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_int_object(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op1 == Py_None)) { + if (op2 == Py_None) goto __pyx_return_true; else goto __pyx_richcmp; + } + if (op1 == op2) goto __pyx_return_true; + if (likely(op1 != Py_None)) { + if (op1 == op2) goto __pyx_return_true; + if (likely(PyLong_CheckExact(op2))) { + return __Pyx_PyObject_CompareIntIntBoolEq(op1, op2); + } + if (PyFloat_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntFloatBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* PyDictVersioning (used by GetModuleGlobalName) */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!__pyx_m)) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_NameError); + return NULL; + } + result = PyObject_GetAttr(__pyx_m, name); + if (likely(result)) { + return result; + } + if (!__Pyx_IgnoreException(PyExc_Exception)) { + return NULL; // BaseException + } +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + if (unlikely(__Pyx_PyDict_GetItemRef(__pyx_mstate_global->__pyx_d, name, &result) == -1)) { + if (!__Pyx_IgnoreException(PyExc_Exception)) { + return NULL; // BaseException + } + } + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return result; + } +#else + result = _PyDict_GetItem_KnownHash(__pyx_mstate_global->__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyObject *exc = PyErr_Occurred(); + if (unlikely(exc) && !__Pyx_IgnoreGivenException(exc, PyExc_Exception)) { + return NULL; // BaseException + } +#endif + return __Pyx_GetBuiltinName(name); +} + +/* RaiseUnboundLocalError */ +static void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +/* RaiseTooManyValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +/* RaiseNeedMoreValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +/* IterFinish */ +static CYTHON_INLINE int __Pyx_IterFinish(void) { + PyObject* exc_type; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + exc_type = __Pyx_PyErr_CurrentExceptionType(); + if (unlikely(exc_type)) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) + return -1; + __Pyx_PyErr_Clear(); + return 0; + } + return 0; +} + +/* UnpackItemEndCheck */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } + return __Pyx_IterFinish(); +} + +/* py_abs */ +#if CYTHON_USE_PYLONG_INTERNALS +static PyObject *__Pyx_PyLong_AbsNeg(PyObject *n) { +#if PY_VERSION_HEX >= 0x030C00A7 + if (likely(__Pyx_PyLong_IsCompact(n))) { + return PyLong_FromSize_t(__Pyx_PyLong_CompactValueUnsigned(n)); + } +#else + if (likely(Py_SIZE(n) == -1)) { + return PyLong_FromUnsignedLong(__Pyx_PyLong_Digits(n)[0]); + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON + { + PyObject *copy = _PyLong_Copy((PyLongObject*)n); + if (likely(copy)) { + #if PY_VERSION_HEX >= 0x030C00A7 + ((PyLongObject*)copy)->long_value.lv_tag ^= ((PyLongObject*)copy)->long_value.lv_tag & _PyLong_SIGN_MASK; + #else + Py_SET_SIZE(copy, -Py_SIZE(copy)); + #endif + } + return copy; + } +#else + return PyNumber_Negative(n); +#endif +} +#endif + +/* RaiseClosureNameError */ +static void __Pyx_RaiseClosureNameError(const char *varname) { + PyErr_Format(PyExc_NameError, "free variable '%s' referenced before assignment in enclosing scope", varname); +} + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareStrStrBoolLe +#define __Pyx_DEFINED_PyObject_CompareStrStrBoolLe +static CYTHON_INLINE int __Pyx_PyObject_CompareStrStrBoolLe(PyObject* s1, PyObject* s2) { + int result = PyUnicode_Compare(s1, s2); + if (unlikely((result == -1) && PyErr_Occurred())) return -1; + if (result <= 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyBytesPyBytesBoolLe +#define __Pyx_DEFINED_PyObject_ComparePyBytesPyBytesBoolLe +static CYTHON_INLINE int __Pyx_PyObject_ComparePyBytesPyBytesBoolLe(PyObject* s1, PyObject* s2) { + Py_ssize_t cmp; + Py_ssize_t length1, length2, short_length; + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + length1 = __Pyx_PyBytes_GET_SIZE(s1); + length2 = __Pyx_PyBytes_GET_SIZE(s2); + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + #else + char *ps1, *ps2; + if (unlikely(PyBytes_AsStringAndSize(s1, &ps1, &length1) == -1)) return -1; + if (unlikely(PyBytes_AsStringAndSize(s2, &ps2, &length2) == -1)) return -1; + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + #endif + cmp = (Py_ssize_t) ((const unsigned char*) ps1)[0] - (Py_ssize_t) ((const unsigned char*) ps2)[0]; + if (cmp == 0 && short_length > 1) { + cmp = memcmp(ps1, ps2, (size_t)short_length); + } + if (cmp == 0) cmp = (length1 - length2); + if (cmp <= 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyBytesPyByteArrayBoolLe +#define __Pyx_DEFINED_PyObject_ComparePyBytesPyByteArrayBoolLe +static CYTHON_INLINE int __Pyx_PyObject_ComparePyBytesPyByteArrayBoolLe(PyObject* s1, PyObject* s2) { + Py_ssize_t cmp; + Py_ssize_t length1, length2, short_length; + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + length1 = __Pyx_PyBytes_GET_SIZE(s1); + length2 = __Pyx_PyByteArray_GET_SIZE(s2); + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyByteArray_AS_STRING(s2); + #else + char *ps1, *ps2; + if (unlikely(PyBytes_AsStringAndSize(s1, &ps1, &length1) == -1)) return -1; + ps2 = __Pyx_PyByteArray_AsString(s2); if (unlikely(!ps2)) return -1; + length2 = __Pyx_PyByteArray_GET_SIZE(s2); if (unlikely(length2 == -1)) return -1; + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + #endif + cmp = (Py_ssize_t) ((const unsigned char*) ps1)[0] - (Py_ssize_t) ((const unsigned char*) ps2)[0]; + if (cmp == 0 && short_length > 1) { + cmp = memcmp(ps1, ps2, (size_t)short_length); + } + if (cmp == 0) cmp = (length1 - length2); + if (cmp <= 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyByteArrayPyBytesBoolLe +#define __Pyx_DEFINED_PyObject_ComparePyByteArrayPyBytesBoolLe +static CYTHON_INLINE int __Pyx_PyObject_ComparePyByteArrayPyBytesBoolLe(PyObject* s1, PyObject* s2) { + Py_ssize_t cmp; + Py_ssize_t length1, length2, short_length; + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + length1 = __Pyx_PyByteArray_GET_SIZE(s1); + length2 = __Pyx_PyBytes_GET_SIZE(s2); + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + ps1 = PyByteArray_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + #else + char *ps1, *ps2; + ps1 = __Pyx_PyByteArray_AsString(s1); if (unlikely(!ps1)) return -1; + length1 = __Pyx_PyByteArray_GET_SIZE(s1); if (unlikely(length1 == -1)) return -1; + if (unlikely(PyBytes_AsStringAndSize(s2, &ps2, &length2) == -1)) return -1; + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + #endif + cmp = (Py_ssize_t) ((const unsigned char*) ps1)[0] - (Py_ssize_t) ((const unsigned char*) ps2)[0]; + if (cmp == 0 && short_length > 1) { + cmp = memcmp(ps1, ps2, (size_t)short_length); + } + if (cmp == 0) cmp = (length1 - length2); + if (cmp <= 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyByteArrayPyByteArrayBoolLe +#define __Pyx_DEFINED_PyObject_ComparePyByteArrayPyByteArrayBoolLe +static CYTHON_INLINE int __Pyx_PyObject_ComparePyByteArrayPyByteArrayBoolLe(PyObject* s1, PyObject* s2) { + Py_ssize_t cmp; + Py_ssize_t length1, length2, short_length; + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + length1 = __Pyx_PyByteArray_GET_SIZE(s1); + length2 = __Pyx_PyByteArray_GET_SIZE(s2); + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + ps1 = PyByteArray_AS_STRING(s1); + ps2 = PyByteArray_AS_STRING(s2); + #else + char *ps1, *ps2; + ps1 = __Pyx_PyByteArray_AsString(s1); if (unlikely(!ps1)) return -1; + length1 = __Pyx_PyByteArray_GET_SIZE(s1); if (unlikely(length1 == -1)) return -1; + ps2 = __Pyx_PyByteArray_AsString(s2); if (unlikely(!ps2)) return -1; + length2 = __Pyx_PyByteArray_GET_SIZE(s2); if (unlikely(length2 == -1)) return -1; + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + #endif + cmp = (Py_ssize_t) ((const unsigned char*) ps1)[0] - (Py_ssize_t) ((const unsigned char*) ps2)[0]; + if (cmp == 0 && short_length > 1) { + cmp = memcmp(ps1, ps2, (size_t)short_length); + } + if (cmp == 0) cmp = (length1 - length2); + if (cmp <= 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolLe +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolLe +static int __Pyx_PyObject_CompareFloatIntBoolLe(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 <= ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 <= 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_false; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } else { + if (sign2 > 0) goto __pyx_return_true; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 <= 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 <= ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntFloatBoolLe +#define __Pyx_DEFINED_PyObject_CompareIntFloatBoolLe +static int __Pyx_PyObject_CompareIntFloatBoolLe(PyObject *op1, PyObject *op2) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t iop1 = __Pyx_PyLong_CompactValue(op1); + if (((double)iop1) <= float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op2))) { + if (0.0 <= float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign1 = __Pyx_PyLong_Sign(op1); + if (float_op2 >= 0.) { + if (sign1 < 0) goto __pyx_return_true; + if (float_op2 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign1 > 0) goto __pyx_return_false; + if (float_op2 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } + } + #else + if (unlikely(!isfinite(float_op2))) { + if (0.0 <= float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow1; + long iop1 = PyLong_AsLongAndOverflow(op1, &overflow1); + if (likely(!overflow1)) { + if ((long long) iop1 >= (1LL << 53)) { + overflow1 = 1; + } else if ((long long) iop1 <= - (1LL << 53)) { + overflow1 = -1; + } else { + if (((double) iop1) <= float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow1 < 0) { + if (float_op2 > ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op2 < - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolLe +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolLe +static int __Pyx_PyObject_CompareIntIntBoolLe(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_true; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + if (cmp < 0) goto __pyx_return_true; else goto __pyx_return_false; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 <= iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 <= overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LE); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolLe_object_object(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (PyFloat_CheckExact(op1)) { + if (PyFloat_CheckExact(op2)) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + if (float_op1 <= float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareFloatIntBoolLe(op1, op2); + } + goto __pyx_richcmp; + } + if (PyLong_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntIntBoolLe(op1, op2); + } + if (PyFloat_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntFloatBoolLe(op1, op2); + } + goto __pyx_richcmp; + } + + if (PyUnicode_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (PyUnicode_CheckExact(op2)) { + return __Pyx_PyObject_CompareStrStrBoolLe(op1, op2); + } + goto __pyx_richcmp; + } + + #if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) + if (PyBytes_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (PyBytes_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyBytesPyBytesBoolLe(op1, op2); + } + if (PyByteArray_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyBytesPyByteArrayBoolLe(op1, op2); + } + goto __pyx_richcmp; + } + #endif + #if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) + if (PyByteArray_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (PyByteArray_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyByteArrayPyByteArrayBoolLe(op1, op2); + } + if (PyBytes_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyByteArrayPyBytesBoolLe(op1, op2); + } + goto __pyx_richcmp; + } + #endif + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* GetException (used by pep479) */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) +#endif +{ + PyObject *local_type = NULL, *local_value, *local_tb = NULL; +#if CYTHON_FAST_THREAD_STATE + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if PY_VERSION_HEX >= 0x030C0000 + local_value = tstate->current_exception; + tstate->current_exception = 0; + #else + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + #endif +#elif __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + local_value = PyErr_GetRaisedException(); +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + if (likely(local_value)) { + local_type = (PyObject*) Py_TYPE(local_value); + Py_INCREF(local_type); + local_tb = PyException_GetTraceback(local_value); + } +#else + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_FAST_THREAD_STATE + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } +#endif // __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_FAST_THREAD_STATE + #if CYTHON_USE_EXC_INFO_STACK + { + _PyErr_StackItem *exc_info = tstate->exc_info; + #if PY_VERSION_HEX >= 0x030B00a4 + tmp_value = exc_info->exc_value; + exc_info->exc_value = local_value; + tmp_type = NULL; + tmp_tb = NULL; + Py_XDECREF(local_type); + Py_XDECREF(local_tb); + #else + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = local_type; + exc_info->exc_value = local_value; + exc_info->exc_traceback = local_tb; + #endif + } + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#elif __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + PyErr_SetHandledException(local_value); + Py_XDECREF(local_value); + Py_XDECREF(local_type); + Py_XDECREF(local_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +#endif +} + +/* pep479 */ +static void __Pyx_Generator_Replace_StopIteration(int in_async_gen) { + PyObject *exc, *val, *tb, *cur_exc, *new_exc; + __Pyx_PyThreadState_declare + int is_async_stopiteration = 0; + CYTHON_MAYBE_UNUSED_VAR(in_async_gen); + __Pyx_PyThreadState_assign + cur_exc = __Pyx_PyErr_CurrentExceptionType(); + if (likely(!__Pyx_PyErr_GivenExceptionMatches(cur_exc, PyExc_StopIteration))) { + if (in_async_gen && unlikely(__Pyx_PyErr_GivenExceptionMatches(cur_exc, PyExc_StopAsyncIteration))) { + is_async_stopiteration = 1; + } else { + return; + } + } + __Pyx_GetException(&exc, &val, &tb); + Py_XDECREF(exc); + Py_XDECREF(tb); + new_exc = PyObject_CallFunction(PyExc_RuntimeError, "s", + is_async_stopiteration ? "async generator raised StopAsyncIteration" : + in_async_gen ? "async generator raised StopIteration" : + "generator raised StopIteration"); + if (!new_exc) { + Py_XDECREF(val); + return; + } + PyException_SetCause(new_exc, val); // steals ref to val + PyErr_SetObject(PyExc_RuntimeError, new_exc); + Py_DECREF(new_exc); +} + +/* PyNumberBinop */ +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API) +#if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#ifndef __Pyx_DEFINED_BinopTypeError +#define __Pyx_DEFINED_BinopTypeError +static void __Pyx_BinopTypeError(PyObject *op1, PyObject *op2, const char* op, int inplace) { + char opname[4] = {op[0], op[1], 0, 0}; + if (inplace) { + opname[op[1] ? 2 : 1] = '='; + } + __Pyx_RaiseErrorWithObjectTypes1( + PyExc_TypeError, + "unsupported operand type(s) for %.3s: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", + opname, op1, op2); +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyNumber_Subtract_xint_int +#define __Pyx_DEFINED_PyNumber_Subtract_xint_int +static PyObject* __Pyx_PyNumber_Subtract_xint_int(PyObject *op1, PyObject *op2, int inplace) { + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "-", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2); + #endif +} +#endif +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Subtract_int_int(PyObject *op1, PyObject *op2, int inplace) { + if (likely(op1 != Py_None)) { + if (likely(op2 != Py_None)) { + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t int_op1 = __Pyx_PyLong_CompactValue(op1); + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t int_op2 = __Pyx_PyLong_CompactValue(op2); + if (int_op2 == 0) return __Pyx_NewRef(op1); + return PyLong_FromSsize_t(int_op1 - int_op2); + } + } + else if (__Pyx_PyLong_IsZero(op2)) return __Pyx_NewRef(op1); + #endif + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(&PyLong_Type, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + return slot_func(op1, op2); + } + } + return __Pyx_PyNumber_Subtract_xint_int(op1, op2, inplace); + } + return (inplace) ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2); +} +#endif + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolGt +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolGt +static int __Pyx_PyObject_CompareFloatIntBoolGt(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 > ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 > 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_true; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign2 > 0) goto __pyx_return_false; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 > 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 > ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_false; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_true; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_GT); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolGt_float_object(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op1 == Py_None)) { + goto __pyx_richcmp; + } + if (likely(op1 != Py_None)) { + if (likely(PyFloat_CheckExact(op2))) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + if (float_op1 > float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareFloatIntBoolGt(op1, op2); + } + goto __pyx_richcmp; + } + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_GT); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* PyNumberBinop */ +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API) +#if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#ifndef __Pyx_DEFINED_BinopTypeError +#define __Pyx_DEFINED_BinopTypeError +static void __Pyx_BinopTypeError(PyObject *op1, PyObject *op2, const char* op, int inplace) { + char opname[4] = {op[0], op[1], 0, 0}; + if (inplace) { + opname[op[1] ? 2 : 1] = '='; + } + __Pyx_RaiseErrorWithObjectTypes1( + PyExc_TypeError, + "unsupported operand type(s) for %.3s: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", + opname, op1, op2); +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyNumber_Subtract_xfloat_object +#define __Pyx_DEFINED_PyNumber_Subtract_xfloat_object +static PyObject* __Pyx_PyNumber_Subtract_xfloat_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyLong_CheckExact(op2)) { + double int_op2; + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t compact_op2 = __Pyx_PyLong_CompactValue(op2); + if (compact_op2 == 0) return __Pyx_NewRef(op1); + int_op2 = (double) compact_op2; + } else + #endif + { + int_op2 = PyLong_AsDouble(op2); + if (unlikely((int_op2 == -1.) && PyErr_Occurred())) return NULL; + #if !CYTHON_USE_PYLONG_INTERNALS + if (int_op2 == 0.) return __Pyx_NewRef(op1); + #endif + } + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op1 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(float_op1 - int_op2); + } + if (PyLong_Check(op2)) { + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(&PyFloat_Type, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + return slot_func(op1, op2); + } + } + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "-", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2); + #endif +} +#endif +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Subtract_float_object(PyObject *op1, PyObject *op2, int inplace) { + if (likely(op1 != Py_None)) { + if (likely(PyFloat_CheckExact(op2))) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op2 == -1.) && PyErr_Occurred())) return NULL; + #endif + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op1 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(float_op1 - float_op2); + } + return __Pyx_PyNumber_Subtract_xfloat_object(op1, op2, inplace); + } + return (inplace) ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2); +} +#endif + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareIntFloatBoolLe +#define __Pyx_DEFINED_PyObject_CompareIntFloatBoolLe +static int __Pyx_PyObject_CompareIntFloatBoolLe(PyObject *op1, PyObject *op2) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t iop1 = __Pyx_PyLong_CompactValue(op1); + if (((double)iop1) <= float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op2))) { + if (0.0 <= float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign1 = __Pyx_PyLong_Sign(op1); + if (float_op2 >= 0.) { + if (sign1 < 0) goto __pyx_return_true; + if (float_op2 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign1 > 0) goto __pyx_return_false; + if (float_op2 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } + } + #else + if (unlikely(!isfinite(float_op2))) { + if (0.0 <= float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow1; + long iop1 = PyLong_AsLongAndOverflow(op1, &overflow1); + if (likely(!overflow1)) { + if ((long long) iop1 >= (1LL << 53)) { + overflow1 = 1; + } else if ((long long) iop1 <= - (1LL << 53)) { + overflow1 = -1; + } else { + if (((double) iop1) <= float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow1 < 0) { + if (float_op2 > ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op2 < - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolLe_object_float(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op2 == Py_None)) { + goto __pyx_richcmp; + } + if (likely(PyFloat_CheckExact(op1))) { + if (likely(op2 != Py_None)) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + if (float_op1 <= float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + goto __pyx_richcmp; + } + if (PyLong_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareIntFloatBoolLe(op1, op2); + } + goto __pyx_richcmp; + } + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* PyNumberBinop */ +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API) +#if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#ifndef __Pyx_DEFINED_BinopTypeError +#define __Pyx_DEFINED_BinopTypeError +static void __Pyx_BinopTypeError(PyObject *op1, PyObject *op2, const char* op, int inplace) { + char opname[4] = {op[0], op[1], 0, 0}; + if (inplace) { + opname[op[1] ? 2 : 1] = '='; + } + __Pyx_RaiseErrorWithObjectTypes1( + PyExc_TypeError, + "unsupported operand type(s) for %.3s: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", + opname, op1, op2); +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyNumber_Add_xfloat_object +#define __Pyx_DEFINED_PyNumber_Add_xfloat_object +static PyObject* __Pyx_PyNumber_Add_xfloat_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyLong_CheckExact(op2)) { + double int_op2; + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t compact_op2 = __Pyx_PyLong_CompactValue(op2); + if (compact_op2 == 0) return __Pyx_NewRef(op1); + int_op2 = (double) compact_op2; + } else + #endif + { + int_op2 = PyLong_AsDouble(op2); + if (unlikely((int_op2 == -1.) && PyErr_Occurred())) return NULL; + #if !CYTHON_USE_PYLONG_INTERNALS + if (int_op2 == 0.) return __Pyx_NewRef(op1); + #endif + } + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op1 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(float_op1 + int_op2); + } + if (PyLong_Check(op2)) { + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(&PyFloat_Type, tp_as_number, nb_add, binaryfunc); + if (likely(slot_func)) { + return slot_func(op1, op2); + } + } + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_add, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "+", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2); + #endif +} +#endif +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Add_float_object(PyObject *op1, PyObject *op2, int inplace) { + if (likely(op1 != Py_None)) { + if (likely(PyFloat_CheckExact(op2))) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op2 == -1.) && PyErr_Occurred())) return NULL; + #endif + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op1 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(float_op1 + float_op2); + } + return __Pyx_PyNumber_Add_xfloat_object(op1, op2, inplace); + } + return (inplace) ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2); +} +#endif + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolLe +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolLe +static int __Pyx_PyObject_CompareFloatIntBoolLe(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 <= ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 <= 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_false; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } else { + if (sign2 > 0) goto __pyx_return_true; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 <= 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 <= ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolLe_float_object(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op1 == Py_None)) { + goto __pyx_richcmp; + } + if (likely(op1 != Py_None)) { + if (likely(PyFloat_CheckExact(op2))) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + if (float_op1 <= float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareFloatIntBoolLe(op1, op2); + } + goto __pyx_richcmp; + } + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareIntFloatLt +#define __Pyx_DEFINED_PyObject_CompareIntFloatLt +static PyObject* __Pyx_PyObject_CompareIntFloatLt(PyObject *op1, PyObject *op2) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return NULL; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t iop1 = __Pyx_PyLong_CompactValue(op1); + if (((double)iop1) < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op2))) { + if (0.0 < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign1 = __Pyx_PyLong_Sign(op1); + if (float_op2 >= 0.) { + if (sign1 < 0) goto __pyx_return_true; + if (float_op2 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign1 > 0) goto __pyx_return_false; + if (float_op2 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } + } + #else + if (unlikely(!isfinite(float_op2))) { + if (0.0 < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow1; + long iop1 = PyLong_AsLongAndOverflow(op1, &overflow1); + if (likely(!overflow1)) { + if ((long long) iop1 >= (1LL << 53)) { + overflow1 = 1; + } else if ((long long) iop1 <= - (1LL << 53)) { + overflow1 = -1; + } else { + if (((double) iop1) < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow1 < 0) { + if (float_op2 > ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op2 < - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return PyObject_RichCompare(op1, op2, Py_LT); +__pyx_return_true: + Py_RETURN_TRUE; +__pyx_return_false: + Py_RETURN_FALSE; +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_CompareLt_object_float(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op2 == Py_None)) { + goto __pyx_richcmp; + } + if (likely(PyFloat_CheckExact(op1))) { + if (likely(op2 != Py_None)) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return NULL; + #endif + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return NULL; + #endif + if (float_op1 < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + goto __pyx_richcmp; + } + if (PyLong_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareIntFloatLt(op1, op2); + } + goto __pyx_richcmp; + } + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return PyObject_RichCompare(op1, op2, Py_LT); +__pyx_return_true: + Py_RETURN_TRUE; +__pyx_return_false: + Py_RETURN_FALSE; +} + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntLt +#define __Pyx_DEFINED_PyObject_CompareFloatIntLt +static PyObject* __Pyx_PyObject_CompareFloatIntLt(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return NULL; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 < ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 < 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_false; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } else { + if (sign2 > 0) goto __pyx_return_true; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 < 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 < ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return PyObject_RichCompare(op1, op2, Py_LT); +__pyx_return_true: + Py_RETURN_TRUE; +__pyx_return_false: + Py_RETURN_FALSE; +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_CompareLt_float_object(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op1 == Py_None)) { + goto __pyx_richcmp; + } + if (likely(op1 != Py_None)) { + if (likely(PyFloat_CheckExact(op2))) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return NULL; + #endif + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return NULL; + #endif + if (float_op1 < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareFloatIntLt(op1, op2); + } + goto __pyx_richcmp; + } + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return PyObject_RichCompare(op1, op2, Py_LT); +__pyx_return_true: + Py_RETURN_TRUE; +__pyx_return_false: + Py_RETURN_FALSE; +} + +/* ArgTypeTestError (used by ArgTypeTest) */ +static void __Pyx_ArgTypeError(PyObject *obj, PyTypeObject *type, const char *name, int exact) +{ + __Pyx_TypeName type_name; + __Pyx_TypeName obj_type_name; + PyObject *extra_info = __pyx_mstate_global->__pyx_empty_unicode; + int from_annotation_subclass = 0; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return; + } else if (exact == 2) { + if (__Pyx_TypeCheck(obj, type)) { + from_annotation_subclass = 1; + extra_info = __pyx_mstate_global->__pyx_kp_u_Note_that_Cython_is_deliberately; + } + } + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!type_name)) return; + #endif + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!obj_type_name)) goto obj_type_name_failed; + #endif + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected " __Pyx_FMT_TYPENAME ", got " __Pyx_FMT_TYPENAME ")" +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + "%s%U" +#endif + , name, type_name, obj_type_name +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + , (from_annotation_subclass ? ". " : ""), extra_info +#endif + ); +#if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + if (exact == 2 && from_annotation_subclass) { + PyObject *res; + PyObject *vargs[2]; + vargs[0] = PyErr_GetRaisedException(); + vargs[1] = extra_info; + res = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_kp_u_add_note, vargs, 2, NULL); + Py_XDECREF(res); + PyErr_SetRaisedException(vargs[0]); + } +#endif + __Pyx_DECREF_TypeName(obj_type_name); +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +obj_type_name_failed: +#endif + __Pyx_DECREF_TypeName(type_name); + return; +} + +/* ArgTypeTest */ +static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { + if (likely(Py_IS_TYPE(obj, type) | (none_allowed && (obj == Py_None)))) + return 1; + if (!exact && likely(type) && likely(__Pyx_TypeCheck(obj, type))) + return 1; + __Pyx_ArgTypeError(obj, type, name, exact); + return 0; +} + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareStrStrBoolLt +#define __Pyx_DEFINED_PyObject_CompareStrStrBoolLt +static CYTHON_INLINE int __Pyx_PyObject_CompareStrStrBoolLt(PyObject* s1, PyObject* s2) { + int result = PyUnicode_Compare(s1, s2); + if (unlikely((result == -1) && PyErr_Occurred())) return -1; + if (result < 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyBytesPyBytesBoolLt +#define __Pyx_DEFINED_PyObject_ComparePyBytesPyBytesBoolLt +static CYTHON_INLINE int __Pyx_PyObject_ComparePyBytesPyBytesBoolLt(PyObject* s1, PyObject* s2) { + Py_ssize_t cmp; + Py_ssize_t length1, length2, short_length; + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + length1 = __Pyx_PyBytes_GET_SIZE(s1); + length2 = __Pyx_PyBytes_GET_SIZE(s2); + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + #else + char *ps1, *ps2; + if (unlikely(PyBytes_AsStringAndSize(s1, &ps1, &length1) == -1)) return -1; + if (unlikely(PyBytes_AsStringAndSize(s2, &ps2, &length2) == -1)) return -1; + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + #endif + cmp = (Py_ssize_t) ((const unsigned char*) ps1)[0] - (Py_ssize_t) ((const unsigned char*) ps2)[0]; + if (cmp == 0 && short_length > 1) { + cmp = memcmp(ps1, ps2, (size_t)short_length); + } + if (cmp == 0) cmp = (length1 - length2); + if (cmp < 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyBytesPyByteArrayBoolLt +#define __Pyx_DEFINED_PyObject_ComparePyBytesPyByteArrayBoolLt +static CYTHON_INLINE int __Pyx_PyObject_ComparePyBytesPyByteArrayBoolLt(PyObject* s1, PyObject* s2) { + Py_ssize_t cmp; + Py_ssize_t length1, length2, short_length; + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + length1 = __Pyx_PyBytes_GET_SIZE(s1); + length2 = __Pyx_PyByteArray_GET_SIZE(s2); + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyByteArray_AS_STRING(s2); + #else + char *ps1, *ps2; + if (unlikely(PyBytes_AsStringAndSize(s1, &ps1, &length1) == -1)) return -1; + ps2 = __Pyx_PyByteArray_AsString(s2); if (unlikely(!ps2)) return -1; + length2 = __Pyx_PyByteArray_GET_SIZE(s2); if (unlikely(length2 == -1)) return -1; + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + #endif + cmp = (Py_ssize_t) ((const unsigned char*) ps1)[0] - (Py_ssize_t) ((const unsigned char*) ps2)[0]; + if (cmp == 0 && short_length > 1) { + cmp = memcmp(ps1, ps2, (size_t)short_length); + } + if (cmp == 0) cmp = (length1 - length2); + if (cmp < 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyByteArrayPyBytesBoolLt +#define __Pyx_DEFINED_PyObject_ComparePyByteArrayPyBytesBoolLt +static CYTHON_INLINE int __Pyx_PyObject_ComparePyByteArrayPyBytesBoolLt(PyObject* s1, PyObject* s2) { + Py_ssize_t cmp; + Py_ssize_t length1, length2, short_length; + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + length1 = __Pyx_PyByteArray_GET_SIZE(s1); + length2 = __Pyx_PyBytes_GET_SIZE(s2); + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + ps1 = PyByteArray_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + #else + char *ps1, *ps2; + ps1 = __Pyx_PyByteArray_AsString(s1); if (unlikely(!ps1)) return -1; + length1 = __Pyx_PyByteArray_GET_SIZE(s1); if (unlikely(length1 == -1)) return -1; + if (unlikely(PyBytes_AsStringAndSize(s2, &ps2, &length2) == -1)) return -1; + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + #endif + cmp = (Py_ssize_t) ((const unsigned char*) ps1)[0] - (Py_ssize_t) ((const unsigned char*) ps2)[0]; + if (cmp == 0 && short_length > 1) { + cmp = memcmp(ps1, ps2, (size_t)short_length); + } + if (cmp == 0) cmp = (length1 - length2); + if (cmp < 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyByteArrayPyByteArrayBoolLt +#define __Pyx_DEFINED_PyObject_ComparePyByteArrayPyByteArrayBoolLt +static CYTHON_INLINE int __Pyx_PyObject_ComparePyByteArrayPyByteArrayBoolLt(PyObject* s1, PyObject* s2) { + Py_ssize_t cmp; + Py_ssize_t length1, length2, short_length; + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + length1 = __Pyx_PyByteArray_GET_SIZE(s1); + length2 = __Pyx_PyByteArray_GET_SIZE(s2); + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + ps1 = PyByteArray_AS_STRING(s1); + ps2 = PyByteArray_AS_STRING(s2); + #else + char *ps1, *ps2; + ps1 = __Pyx_PyByteArray_AsString(s1); if (unlikely(!ps1)) return -1; + length1 = __Pyx_PyByteArray_GET_SIZE(s1); if (unlikely(length1 == -1)) return -1; + ps2 = __Pyx_PyByteArray_AsString(s2); if (unlikely(!ps2)) return -1; + length2 = __Pyx_PyByteArray_GET_SIZE(s2); if (unlikely(length2 == -1)) return -1; + short_length = (length1 < length2) ? length1 : length2; + if (short_length == 0) { + if (length1 == 0) goto __pyx_return_true; else goto __pyx_return_false; + } + #endif + cmp = (Py_ssize_t) ((const unsigned char*) ps1)[0] - (Py_ssize_t) ((const unsigned char*) ps2)[0]; + if (cmp == 0 && short_length > 1) { + cmp = memcmp(ps1, ps2, (size_t)short_length); + } + if (cmp == 0) cmp = (length1 - length2); + if (cmp < 0) goto __pyx_return_true; else goto __pyx_return_false; +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolLt +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolLt +static int __Pyx_PyObject_CompareFloatIntBoolLt(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 < ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 < 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_false; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } else { + if (sign2 > 0) goto __pyx_return_true; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 < 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 < ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LT); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntFloatBoolLt +#define __Pyx_DEFINED_PyObject_CompareIntFloatBoolLt +static int __Pyx_PyObject_CompareIntFloatBoolLt(PyObject *op1, PyObject *op2) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t iop1 = __Pyx_PyLong_CompactValue(op1); + if (((double)iop1) < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op2))) { + if (0.0 < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign1 = __Pyx_PyLong_Sign(op1); + if (float_op2 >= 0.) { + if (sign1 < 0) goto __pyx_return_true; + if (float_op2 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign1 > 0) goto __pyx_return_false; + if (float_op2 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } + } + #else + if (unlikely(!isfinite(float_op2))) { + if (0.0 < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow1; + long iop1 = PyLong_AsLongAndOverflow(op1, &overflow1); + if (likely(!overflow1)) { + if ((long long) iop1 >= (1LL << 53)) { + overflow1 = 1; + } else if ((long long) iop1 <= - (1LL << 53)) { + overflow1 = -1; + } else { + if (((double) iop1) < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow1 < 0) { + if (float_op2 > ((double) (1LL << 53))) goto __pyx_return_true; + } else { + if (float_op2 < - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LT); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolLt +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolLt +static int __Pyx_PyObject_CompareIntIntBoolLt(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_false; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + if (cmp < 0) goto __pyx_return_true; else goto __pyx_return_false; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 < iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 < overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LT); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolLt_object_object(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (PyFloat_CheckExact(op1)) { + if (PyFloat_CheckExact(op2)) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + if (float_op1 < float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareFloatIntBoolLt(op1, op2); + } + goto __pyx_richcmp; + } + if (PyLong_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntIntBoolLt(op1, op2); + } + if (PyFloat_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntFloatBoolLt(op1, op2); + } + goto __pyx_richcmp; + } + + if (PyUnicode_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (PyUnicode_CheckExact(op2)) { + return __Pyx_PyObject_CompareStrStrBoolLt(op1, op2); + } + goto __pyx_richcmp; + } + + #if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) + if (PyBytes_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (PyBytes_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyBytesPyBytesBoolLt(op1, op2); + } + if (PyByteArray_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyBytesPyByteArrayBoolLt(op1, op2); + } + goto __pyx_richcmp; + } + #endif + #if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) + if (PyByteArray_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_false; + if (PyByteArray_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyByteArrayPyByteArrayBoolLt(op1, op2); + } + if (PyBytes_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyByteArrayPyBytesBoolLt(op1, op2); + } + goto __pyx_richcmp; + } + #endif + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_LT); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* DictGetItem */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { + PyObject *value; + if (unlikely(__Pyx_PyDict_GetItemRef(d, key, &value) == 0)) { // no value, no error + if (unlikely(PyTuple_Check(key))) { + PyObject* args = PyTuple_Pack(1, key); + if (likely(args)) { + PyErr_SetObject(PyExc_KeyError, args); + Py_DECREF(args); + } + } else { + PyErr_SetObject(PyExc_KeyError, key); + } + } + return value; +} +#endif + +/* pyfrozenset_new (used by PySetContains) */ +static PyObject* __Pyx_PyFrozenSet_New(PyObject* it) { + PyObject* result; + if (PyFrozenSet_CheckExact(it)) { + Py_INCREF(it); + return it; + } + result = PyFrozenSet_New(it); + if (unlikely(!result)) { + return NULL; + } + if ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000) +#if CYTHON_COMPILING_IN_LIMITED_API + || likely(__Pyx_get_runtime_version() >= 0x030A0000) +#endif + ) + return result; + Py_ssize_t size = __Pyx_PySet_GET_SIZE(result); + if (likely(size > 0)) + return result; +#if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(size < 0)) { + Py_DECREF(result); + return NULL; + } +#endif + Py_DECREF(result); + return PyFrozenSet_New(NULL); +} + +/* PySetContains */ +static int __Pyx_PySet_ContainsUnhashable(PyObject *set, PyObject *key) { + int result = -1; + if (PySet_Check(key) && PyErr_ExceptionMatches(PyExc_TypeError)) { + PyObject *tmpkey; + PyErr_Clear(); + tmpkey = __Pyx_PyFrozenSet_New(key); + if (tmpkey != NULL) { + result = PySet_Contains(set, tmpkey); + Py_DECREF(tmpkey); + } + } + return result; +} +static CYTHON_INLINE int __Pyx_PySet_ContainsTF(PyObject* key, PyObject* set, int eq) { + int result = PySet_Contains(set, key); + if (unlikely(result < 0)) { + result = __Pyx_PySet_ContainsUnhashable(set, key); + } + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +/* PyNumberBinop */ +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API) +#if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#ifndef __Pyx_DEFINED_BinopTypeError +#define __Pyx_DEFINED_BinopTypeError +static void __Pyx_BinopTypeError(PyObject *op1, PyObject *op2, const char* op, int inplace) { + char opname[4] = {op[0], op[1], 0, 0}; + if (inplace) { + opname[op[1] ? 2 : 1] = '='; + } + __Pyx_RaiseErrorWithObjectTypes1( + PyExc_TypeError, + "unsupported operand type(s) for %.3s: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", + opname, op1, op2); +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyNumber_Subtract_xint_object +#define __Pyx_DEFINED_PyNumber_Subtract_xint_object +static PyObject* __Pyx_PyNumber_Subtract_xint_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyFloat_CheckExact(op2)) { + double int_op1; + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t compact_op1 = __Pyx_PyLong_CompactValue(op1); + int_op1 = (double) compact_op1; + } else + #endif + { + int_op1 = PyLong_AsDouble(op1); + if (unlikely((int_op1 == -1.) && PyErr_Occurred())) return NULL; + } + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op2 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(int_op1 - float_op2); + } + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "-", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2); + #endif +} +#endif +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Subtract_int_object(PyObject *op1, PyObject *op2, int inplace) { + if (likely(op1 != Py_None)) { + if (likely(PyLong_CheckExact(op2))) { + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t int_op1 = __Pyx_PyLong_CompactValue(op1); + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t int_op2 = __Pyx_PyLong_CompactValue(op2); + if (int_op2 == 0) return __Pyx_NewRef(op1); + return PyLong_FromSsize_t(int_op1 - int_op2); + } + } + else if (__Pyx_PyLong_IsZero(op2)) return __Pyx_NewRef(op1); + #endif + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(&PyLong_Type, tp_as_number, nb_subtract, binaryfunc); + if (likely(slot_func)) { + return slot_func(op1, op2); + } + } + return __Pyx_PyNumber_Subtract_xint_object(op1, op2, inplace); + } + return (inplace) ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2); +} +#endif + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareIntFloatBoolGt +#define __Pyx_DEFINED_PyObject_CompareIntFloatBoolGt +static int __Pyx_PyObject_CompareIntFloatBoolGt(PyObject *op1, PyObject *op2) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t iop1 = __Pyx_PyLong_CompactValue(op1); + if (((double)iop1) > float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op2))) { + if (0.0 > float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign1 = __Pyx_PyLong_Sign(op1); + if (float_op2 >= 0.) { + if (sign1 < 0) goto __pyx_return_false; + if (float_op2 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } else { + if (sign1 > 0) goto __pyx_return_true; + if (float_op2 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op2))) { + if (0.0 > float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow1; + long iop1 = PyLong_AsLongAndOverflow(op1, &overflow1); + if (likely(!overflow1)) { + if ((long long) iop1 >= (1LL << 53)) { + overflow1 = 1; + } else if ((long long) iop1 <= - (1LL << 53)) { + overflow1 = -1; + } else { + if (((double) iop1) > float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow1 < 0) { + if (float_op2 > ((double) (1LL << 53))) goto __pyx_return_false; + } else { + if (float_op2 < - ((double) (1LL << 53))) goto __pyx_return_true; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_GT); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolGt +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolGt +static int __Pyx_PyObject_CompareIntIntBoolGt(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_false; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + if (cmp < 0) goto __pyx_return_false; else goto __pyx_return_true; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 > iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 > overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_GT); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolGt_int_object(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op1 == Py_None)) { + goto __pyx_richcmp; + } + if (op1 == op2) goto __pyx_return_false; + if (likely(op1 != Py_None)) { + if (op1 == op2) goto __pyx_return_false; + if (likely(PyLong_CheckExact(op2))) { + return __Pyx_PyObject_CompareIntIntBoolGt(op1, op2); + } + if (PyFloat_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntFloatBoolGt(op1, op2); + } + goto __pyx_richcmp; + } + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_GT); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* TupleOrListFromArrayImpl (used by ListFromArray) */ +CYTHON_UNUSED static PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) { + PyObject *res = PyList_New(n); + if (unlikely(res == NULL)) return NULL; + #if CYTHON_COMPILING_IN_CPYTHON + __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); + #else + Py_ssize_t i; + for (i = 0; i < n; i++) { + Py_INCREF(src[i]); + if (unlikely(__Pyx_PyList_SET_ITEM(res, i, src[i]) < (0))) { + Py_DECREF(res); + return NULL; + } + } + #endif + return res; +} + +/* SliceTupleAndList */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_crop_slice(Py_ssize_t* _start, Py_ssize_t* _stop, Py_ssize_t* _length) { + Py_ssize_t start = *_start, stop = *_stop, length = *_length; + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + else if (stop > length) + stop = length; + *_length = stop - start; + *_start = start; + *_stop = stop; +} +static CYTHON_INLINE PyObject* __Pyx_PyTuple_GetSlice( + PyObject* src, Py_ssize_t start, Py_ssize_t stop) { + Py_ssize_t length = PyTuple_GET_SIZE(src); + __Pyx_crop_slice(&start, &stop, &length); + return __Pyx_PyTuple_FromArray(((PyTupleObject*)src)->ob_item + start, length); +} +static CYTHON_INLINE PyObject* __Pyx_PyList_GetSlice_locked( + PyObject* src, Py_ssize_t start, Py_ssize_t stop) { + Py_ssize_t length = PyList_GET_SIZE(src); + __Pyx_crop_slice(&start, &stop, &length); + if (length <= 0) { + return PyList_New(0); + } + return __Pyx_PyList_FromArray(((PyListObject*)src)->ob_item + start, length); +} +static CYTHON_INLINE PyObject* __Pyx_PyList_GetSlice( + PyObject* src, Py_ssize_t start, Py_ssize_t stop) { + PyObject *result; + __Pyx_BEGIN_CRITICAL_SECTION(src); + result = __Pyx_PyList_GetSlice_locked(src, start, stop); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +#endif // CYTHON_COMPILING_IN_CPYTHON + +/* set_iter */ +static CYTHON_INLINE PyObject* __Pyx_set_iterator(PyObject* iterable, int is_set, + Py_ssize_t* p_orig_length, int* p_source_is_set) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000 + is_set = is_set || likely(PySet_CheckExact(iterable) || PyFrozenSet_CheckExact(iterable)); + *p_source_is_set = is_set; + if (likely(is_set)) { + *p_orig_length = PySet_Size(iterable); + Py_INCREF(iterable); + return iterable; + } +#else + CYTHON_UNUSED_VAR(is_set); + *p_source_is_set = 0; +#endif + *p_orig_length = 0; + return PyObject_GetIter(iterable); +} +static CYTHON_INLINE int __Pyx_set_iter_next( + PyObject* iter_obj, Py_ssize_t orig_length, + Py_ssize_t* ppos, PyObject **value, + int source_is_set) { + if (!CYTHON_COMPILING_IN_CPYTHON || PY_VERSION_HEX >= 0x030d0000 || unlikely(!source_is_set)) { + *value = PyIter_Next(iter_obj); + if (unlikely(!*value)) { + return __Pyx_IterFinish(); + } + CYTHON_UNUSED_VAR(orig_length); + CYTHON_UNUSED_VAR(ppos); + return 1; + } +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000 + if (unlikely(PySet_GET_SIZE(iter_obj) != orig_length)) { + PyErr_SetString( + PyExc_RuntimeError, + "set changed size during iteration"); + return -1; + } + { + Py_hash_t hash; + int ret = _PySet_NextEntry(iter_obj, ppos, value, &hash); + assert (ret != -1); + if (likely(ret)) { + Py_INCREF(*value); + return 1; + } + } +#endif + return 0; +} + +/* PyNumberBinop */ +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API) +#if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#ifndef __Pyx_DEFINED_BinopTypeError +#define __Pyx_DEFINED_BinopTypeError +static void __Pyx_BinopTypeError(PyObject *op1, PyObject *op2, const char* op, int inplace) { + char opname[4] = {op[0], op[1], 0, 0}; + if (inplace) { + opname[op[1] ? 2 : 1] = '='; + } + __Pyx_RaiseErrorWithObjectTypes1( + PyExc_TypeError, + "unsupported operand type(s) for %.3s: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", + opname, op1, op2); +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyNumber_Add_xfloat_int +#define __Pyx_DEFINED_PyNumber_Add_xfloat_int +static PyObject* __Pyx_PyNumber_Add_xfloat_int(PyObject *op1, PyObject *op2, int inplace) { + if (likely(op2 != Py_None)) { + double int_op2; + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t compact_op2 = __Pyx_PyLong_CompactValue(op2); + if (compact_op2 == 0) return __Pyx_NewRef(op1); + int_op2 = (double) compact_op2; + } else + #endif + { + int_op2 = PyLong_AsDouble(op2); + if (unlikely((int_op2 == -1.) && PyErr_Occurred())) return NULL; + #if !CYTHON_USE_PYLONG_INTERNALS + if (int_op2 == 0.) return __Pyx_NewRef(op1); + #endif + } + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op1 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(float_op1 + int_op2); + } + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_add, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "+", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2); + #endif +} +#endif +#ifndef __Pyx_DEFINED_PyNumber_Add_xint_int +#define __Pyx_DEFINED_PyNumber_Add_xint_int +static PyObject* __Pyx_PyNumber_Add_xint_int(PyObject *op1, PyObject *op2, int inplace) { + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_add, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "+", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2); + #endif +} +#endif +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Add_object_int(PyObject *op1, PyObject *op2, int inplace) { + if (PyFloat_CheckExact(op1)) { + return __Pyx_PyNumber_Add_xfloat_int(op1, op2, inplace); + } + if (likely(PyLong_CheckExact(op1))) { + if (likely(op2 != Py_None)) { + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t int_op1 = __Pyx_PyLong_CompactValue(op1); + if (int_op1 == 0) return __Pyx_NewRef(op2); + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t int_op2 = __Pyx_PyLong_CompactValue(op2); + if (int_op2 == 0) return __Pyx_NewRef(op1); + return PyLong_FromSsize_t(int_op1 + int_op2); + } + } + else if (__Pyx_PyLong_IsZero(op2)) return __Pyx_NewRef(op1); + #endif + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(&PyLong_Type, tp_as_number, nb_add, binaryfunc); + if (likely(slot_func)) { + return slot_func(op1, op2); + } + } + return __Pyx_PyNumber_Add_xint_int(op1, op2, inplace); + } + return (inplace) ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2); +} +#endif + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareStrStrBoolEq +#define __Pyx_DEFINED_PyObject_CompareStrStrBoolEq +static CYTHON_INLINE int __Pyx_PyObject_CompareStrStrBoolEq(PyObject* s1, PyObject* s2) { + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + int result = PyUnicode_Equal(s1, s2); + #if !CYTHON_COMPILING_IN_CPYTHON + if (unlikely(result == -1)) return -1; + #endif + if (result == 0) goto __pyx_return_false; else goto __pyx_return_true; + #else + int result = PyUnicode_Compare(s1, s2); + if (unlikely((result == -1) && PyErr_Occurred())) return -1; + if (result == 0) goto __pyx_return_true; else goto __pyx_return_false; + #endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyBytesPyBytesBoolEq +#define __Pyx_DEFINED_PyObject_ComparePyBytesPyBytesBoolEq +static CYTHON_INLINE int __Pyx_PyObject_ComparePyBytesPyBytesBoolEq(PyObject* s1, PyObject* s2) { + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) goto __pyx_return_false; + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + #else + char *ps1, *ps2; + Py_ssize_t length, length2; + if (unlikely(PyBytes_AsStringAndSize(s1, &ps1, &length) == -1)) return -1; + if (unlikely(PyBytes_AsStringAndSize(s2, &ps2, &length2) == -1)) return -1; + if (length != length2) goto __pyx_return_false; + #endif + if (ps1[0] != ps2[0]) goto __pyx_return_false; + if (length == 1) goto __pyx_return_true; + { + int cmp; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1 = ((PyBytesObject*)s1)->ob_shash; + Py_hash_t hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) goto __pyx_return_false; +#endif + cmp = memcmp(ps1, ps2, (size_t)length); + if (cmp == 0) goto __pyx_return_true; else goto __pyx_return_false; + } +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyBytesPyByteArrayBoolEq +#define __Pyx_DEFINED_PyObject_ComparePyBytesPyByteArrayBoolEq +static CYTHON_INLINE int __Pyx_PyObject_ComparePyBytesPyByteArrayBoolEq(PyObject* s1, PyObject* s2) { + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyByteArray_GET_SIZE(s2)) goto __pyx_return_false; + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyByteArray_AS_STRING(s2); + #else + char *ps1, *ps2; + Py_ssize_t length, length2; + if (unlikely(PyBytes_AsStringAndSize(s1, &ps1, &length) == -1)) return -1; + ps2 = __Pyx_PyByteArray_AsString(s2); if (unlikely(!ps2)) return -1; + length2 = __Pyx_PyByteArray_GET_SIZE(s2); if (unlikely(length2 == -1)) return -1; + if (length != length2) goto __pyx_return_false; + #endif + if (ps1[0] != ps2[0]) goto __pyx_return_false; + if (length == 1) goto __pyx_return_true; + { + int cmp; + cmp = memcmp(ps1, ps2, (size_t)length); + if (cmp == 0) goto __pyx_return_true; else goto __pyx_return_false; + } +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyByteArrayPyBytesBoolEq +#define __Pyx_DEFINED_PyObject_ComparePyByteArrayPyBytesBoolEq +static CYTHON_INLINE int __Pyx_PyObject_ComparePyByteArrayPyBytesBoolEq(PyObject* s1, PyObject* s2) { + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + Py_ssize_t length = PyByteArray_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) goto __pyx_return_false; + ps1 = PyByteArray_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + #else + char *ps1, *ps2; + Py_ssize_t length, length2; + ps1 = __Pyx_PyByteArray_AsString(s1); if (unlikely(!ps1)) return -1; + length = __Pyx_PyByteArray_GET_SIZE(s1); if (unlikely(length == -1)) return -1; + if (unlikely(PyBytes_AsStringAndSize(s2, &ps2, &length2) == -1)) return -1; + if (length != length2) goto __pyx_return_false; + #endif + if (length == 0) goto __pyx_return_true; + if (ps1[0] != ps2[0]) goto __pyx_return_false; + if (length == 1) goto __pyx_return_true; + { + int cmp; + cmp = memcmp(ps1, ps2, (size_t)length); + if (cmp == 0) goto __pyx_return_true; else goto __pyx_return_false; + } +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) +#ifndef __Pyx_DEFINED_PyObject_ComparePyByteArrayPyByteArrayBoolEq +#define __Pyx_DEFINED_PyObject_ComparePyByteArrayPyByteArrayBoolEq +static CYTHON_INLINE int __Pyx_PyObject_ComparePyByteArrayPyByteArrayBoolEq(PyObject* s1, PyObject* s2) { + #if CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS + const char *ps1, *ps2; + Py_ssize_t length = PyByteArray_GET_SIZE(s1); + if (length != PyByteArray_GET_SIZE(s2)) goto __pyx_return_false; + ps1 = PyByteArray_AS_STRING(s1); + ps2 = PyByteArray_AS_STRING(s2); + #else + char *ps1, *ps2; + Py_ssize_t length, length2; + ps1 = __Pyx_PyByteArray_AsString(s1); if (unlikely(!ps1)) return -1; + length = __Pyx_PyByteArray_GET_SIZE(s1); if (unlikely(length == -1)) return -1; + ps2 = __Pyx_PyByteArray_AsString(s2); if (unlikely(!ps2)) return -1; + length2 = __Pyx_PyByteArray_GET_SIZE(s2); if (unlikely(length2 == -1)) return -1; + if (length != length2) goto __pyx_return_false; + #endif + if (length == 0) goto __pyx_return_true; + if (ps1[0] != ps2[0]) goto __pyx_return_false; + if (length == 1) goto __pyx_return_true; + { + int cmp; + cmp = memcmp(ps1, ps2, (size_t)length); + if (cmp == 0) goto __pyx_return_true; else goto __pyx_return_false; + } +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolEq +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolEq +static int __Pyx_PyObject_CompareFloatIntBoolEq(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 == ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 == 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_false; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign2 > 0) goto __pyx_return_false; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 == 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 == ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_false; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntFloatBoolEq +#define __Pyx_DEFINED_PyObject_CompareIntFloatBoolEq +static int __Pyx_PyObject_CompareIntFloatBoolEq(PyObject *op1, PyObject *op2) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t iop1 = __Pyx_PyLong_CompactValue(op1); + if (((double)iop1) == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op2))) { + if (0.0 == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign1 = __Pyx_PyLong_Sign(op1); + if (float_op2 >= 0.) { + if (sign1 < 0) goto __pyx_return_false; + if (float_op2 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign1 > 0) goto __pyx_return_false; + if (float_op2 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op2))) { + if (0.0 == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow1; + long iop1 = PyLong_AsLongAndOverflow(op1, &overflow1); + if (likely(!overflow1)) { + if ((long long) iop1 >= (1LL << 53)) { + overflow1 = 1; + } else if ((long long) iop1 <= - (1LL << 53)) { + overflow1 = -1; + } else { + if (((double) iop1) == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow1 < 0) { + if (float_op2 > ((double) (1LL << 53))) goto __pyx_return_false; + } else { + if (float_op2 < - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolEq +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolEq +static int __Pyx_PyObject_CompareIntIntBoolEq(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_true; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + goto __pyx_return_false; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 == iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 == overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_object_object(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (PyFloat_CheckExact(op1)) { + if (PyFloat_CheckExact(op2)) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op2 == -1. && PyErr_Occurred())) return -1; + #endif + if (float_op1 == float_op2) goto __pyx_return_true; else goto __pyx_return_false; + } + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareFloatIntBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + if (PyLong_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (PyLong_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntIntBoolEq(op1, op2); + } + if (PyFloat_CheckExact(op2)) { + return __Pyx_PyObject_CompareIntFloatBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + + if (PyUnicode_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (PyUnicode_CheckExact(op2)) { + return __Pyx_PyObject_CompareStrStrBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + + #if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) + if (PyBytes_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (PyBytes_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyBytesPyBytesBoolEq(op1, op2); + } + if (PyByteArray_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyBytesPyByteArrayBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + #endif + #if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL) + if (PyByteArray_CheckExact(op1)) { + if (op1 == op2) goto __pyx_return_true; + if (PyByteArray_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyByteArrayPyByteArrayBoolEq(op1, op2); + } + if (PyBytes_CheckExact(op2)) { + return __Pyx_PyObject_ComparePyByteArrayPyBytesBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + #endif + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* PyLongCompare */ +static CYTHON_INLINE int __Pyx_PyLong_BoolEqObjC(PyObject *op1, PyObject *op2, long intval, long inplace) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_UNUSED_VAR(inplace); + if (op1 == op2) { + return 1; + } + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + int unequal; + unsigned long uintval; + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + const digit* digits = __Pyx_PyLong_Digits(op1); + if (intval == 0) { + return (__Pyx_PyLong_IsZero(op1) == 1); + } else if (intval < 0) { + if (__Pyx_PyLong_IsNonNeg(op1)) + return 0; + intval = -intval; + } else { + if (__Pyx_PyLong_IsNeg(op1)) + return 0; + } + uintval = (unsigned long) intval; +#if PyLong_SHIFT * 4 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 4)) { + unequal = (size != 5) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[4] != ((uintval >> (4 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 3 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 3)) { + unequal = (size != 4) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 2 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 2)) { + unequal = (size != 3) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 1 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 1)) { + unequal = (size != 2) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif + unequal = (size != 1) || (((unsigned long) digits[0]) != (uintval & (unsigned long) PyLong_MASK)); + return (unequal == 0); + } + #endif + if (PyFloat_CheckExact(op1)) { + const long b = intval; + double a = __Pyx_PyFloat_AS_DOUBLE(op1); + return ((double)a == (double)b); + } + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +} + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolGe +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolGe +static int __Pyx_PyObject_CompareFloatIntBoolGe(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 >= ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 >= 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_true; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign2 > 0) goto __pyx_return_false; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_true; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 >= 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 >= ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_false; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_true; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_GE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolGe +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolGe +static int __Pyx_PyObject_CompareIntIntBoolGe(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_true; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + if (cmp < 0) goto __pyx_return_false; else goto __pyx_return_true; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 >= iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 >= overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_GE); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolGe_object_int(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op2 == Py_None)) { + goto __pyx_richcmp; + } + if (op1 == op2) goto __pyx_return_true; + if (PyFloat_CheckExact(op1)) { + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareFloatIntBoolGe(op1, op2); + } + goto __pyx_richcmp; + } + if (likely(PyLong_CheckExact(op1))) { + if (op1 == op2) goto __pyx_return_true; + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareIntIntBoolGe(op1, op2); + } + goto __pyx_richcmp; + } + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_GE); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* py_set_discard_unhashable (used by py_set_remove) */ +static int __Pyx_PySet_DiscardUnhashable(PyObject *set, PyObject *key) { + PyObject *tmpkey; + int rv; + if (likely(!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))) + return -1; + PyErr_Clear(); + tmpkey = __Pyx_PyFrozenSet_New(key); + if (tmpkey == NULL) + return -1; + rv = PySet_Discard(set, tmpkey); + Py_DECREF(tmpkey); + return rv; +} + +/* py_set_remove */ +static int __Pyx_PySet_RemoveNotFound(PyObject *set, PyObject *key, int found) { + if (unlikely(found < 0)) { + found = __Pyx_PySet_DiscardUnhashable(set, key); + } + if (likely(found == 0)) { + PyObject *tup; + tup = PyTuple_Pack(1, key); + if (!tup) + return -1; + PyErr_SetObject(PyExc_KeyError, tup); + Py_DECREF(tup); + return -1; + } + return found; +} +static CYTHON_INLINE int __Pyx_PySet_Remove(PyObject *set, PyObject *key) { + int found = PySet_Discard(set, key); + if (unlikely(found != 1)) { + return __Pyx_PySet_RemoveNotFound(set, key, found); + } + return 0; +} + +/* ListCompAppendAndDecref */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE +static CYTHON_INLINE int __Pyx_ListComp_AppendAndDecref(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + __Pyx__ListComp_AppendAndDecref(list, len, x); + return 0; + } + int result = PyList_Append(list, x); + Py_DECREF(x); + return result; +} +#else +static CYTHON_INLINE int __Pyx_ListComp_AppendAndDecref(PyObject* list, PyObject* x) { + int result = PyList_Append(list, x); + Py_DECREF(x); + return result; +} +#endif + +/* PyNumberBinop */ +#if !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_GRAAL || CYTHON_COMPILING_IN_LIMITED_API) +#if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#ifndef __Pyx_DEFINED_BinopTypeError +#define __Pyx_DEFINED_BinopTypeError +static void __Pyx_BinopTypeError(PyObject *op1, PyObject *op2, const char* op, int inplace) { + char opname[4] = {op[0], op[1], 0, 0}; + if (inplace) { + opname[op[1] ? 2 : 1] = '='; + } + __Pyx_RaiseErrorWithObjectTypes1( + PyExc_TypeError, + "unsupported operand type(s) for %.3s: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", + opname, op1, op2); +} +#endif +#endif +#ifndef __Pyx_DEFINED_PyNumber_Add_xfloat_object +#define __Pyx_DEFINED_PyNumber_Add_xfloat_object +static PyObject* __Pyx_PyNumber_Add_xfloat_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyLong_CheckExact(op2)) { + double int_op2; + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t compact_op2 = __Pyx_PyLong_CompactValue(op2); + if (compact_op2 == 0) return __Pyx_NewRef(op1); + int_op2 = (double) compact_op2; + } else + #endif + { + int_op2 = PyLong_AsDouble(op2); + if (unlikely((int_op2 == -1.) && PyErr_Occurred())) return NULL; + #if !CYTHON_USE_PYLONG_INTERNALS + if (int_op2 == 0.) return __Pyx_NewRef(op1); + #endif + } + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op1 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(float_op1 + int_op2); + } + if (PyLong_Check(op2)) { + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(&PyFloat_Type, tp_as_number, nb_add, binaryfunc); + if (likely(slot_func)) { + return slot_func(op1, op2); + } + } + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_add, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "+", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2); + #endif +} +#endif +#ifndef __Pyx_DEFINED_PyNumber_Add_xint_object +#define __Pyx_DEFINED_PyNumber_Add_xint_object +static PyObject* __Pyx_PyNumber_Add_xint_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyFloat_CheckExact(op2)) { + double int_op1; + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t compact_op1 = __Pyx_PyLong_CompactValue(op1); + if (compact_op1 == 0) return __Pyx_NewRef(op2); + int_op1 = (double) compact_op1; + } else + #endif + { + int_op1 = PyLong_AsDouble(op1); + if (unlikely((int_op1 == -1.) && PyErr_Occurred())) return NULL; + #if !CYTHON_USE_PYLONG_INTERNALS + if (int_op1 == 0.) return __Pyx_NewRef(op2); + #endif + } + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op2 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(int_op1 + float_op2); + } + #if CYTHON_USE_TYPE_SLOTS || __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + { + PyTypeObject *type_op2 = Py_TYPE(op2); + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(type_op2, tp_as_number, nb_add, binaryfunc); + if (likely(slot_func)) { + PyObject *result = slot_func(op1, op2); + if (likely(result != Py_NotImplemented)) { + return result; + } + Py_DECREF(result); + } + __Pyx_BinopTypeError(op1, op2, "+", inplace); + return NULL; + } + #else + return (inplace) ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2); + #endif +} +#endif +static CYTHON_INLINE PyObject* __Pyx__PyNumber_Add_object_object(PyObject *op1, PyObject *op2, int inplace) { + if (PyFloat_CheckExact(op1)) { + if (PyFloat_CheckExact(op2)) { + double float_op2 = __Pyx_PyFloat_AS_DOUBLE(op2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op2 == -1.) && PyErr_Occurred())) return NULL; + #endif + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((float_op1 == -1.) && PyErr_Occurred())) return NULL; + #endif + return PyFloat_FromDouble(float_op1 + float_op2); + } + return __Pyx_PyNumber_Add_xfloat_object(op1, op2, inplace); + } + if (PyLong_CheckExact(op1)) { + if (PyLong_CheckExact(op2)) { + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op1)) { + Py_ssize_t int_op1 = __Pyx_PyLong_CompactValue(op1); + if (int_op1 == 0) return __Pyx_NewRef(op2); + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t int_op2 = __Pyx_PyLong_CompactValue(op2); + if (int_op2 == 0) return __Pyx_NewRef(op1); + return PyLong_FromSsize_t(int_op1 + int_op2); + } + } + else if (__Pyx_PyLong_IsZero(op2)) return __Pyx_NewRef(op1); + #endif + binaryfunc slot_func = __Pyx_PyType_GetSubSlot(&PyLong_Type, tp_as_number, nb_add, binaryfunc); + if (likely(slot_func)) { + return slot_func(op1, op2); + } + } + return __Pyx_PyNumber_Add_xint_object(op1, op2, inplace); + } + return (inplace) ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2); +} +#endif + +/* PyObjectCompare */ +#ifndef __Pyx_DEFINED_PyObject_CompareFloatIntBoolEq +#define __Pyx_DEFINED_PyObject_CompareFloatIntBoolEq +static int __Pyx_PyObject_CompareFloatIntBoolEq(PyObject *op1, PyObject *op2) { + double float_op1 = __Pyx_PyFloat_AS_DOUBLE(op1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(float_op1 == -1. && PyErr_Occurred())) return -1; + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(op2)) { + Py_ssize_t iop2 = __Pyx_PyLong_CompactValue(op2); + if (float_op1 == ((double)iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + if (unlikely(!isfinite(float_op1))) { + if (float_op1 == 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int sign2 = __Pyx_PyLong_Sign(op2); + if (float_op1 >= 0.) { + if (sign2 < 0) goto __pyx_return_false; + if (float_op1 < (double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } else { + if (sign2 > 0) goto __pyx_return_false; + if (float_op1 > -(double) (1L << PyLong_SHIFT)) goto __pyx_return_false; + } + } + #else + if (unlikely(!isfinite(float_op1))) { + if (float_op1 == 0.0) goto __pyx_return_true; else goto __pyx_return_false; + } else { + int overflow2; + long iop2 = PyLong_AsLongAndOverflow(op2, &overflow2); + if (likely(!overflow2)) { + if ((long long) iop2 >= (1LL << 53)) { + overflow2 = 1; + } else if ((long long) iop2 <= - (1LL << 53)) { + overflow2 = -1; + } else { + if (float_op1 == ((double) iop2)) goto __pyx_return_true; else goto __pyx_return_false; + } + } + if (overflow2 > 0) { + if (float_op1 < ((double) (1LL << 53))) goto __pyx_return_false; + } else { + if (float_op1 > - ((double) (1LL << 53))) goto __pyx_return_false; + } + } + #endif + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +#ifndef __Pyx_DEFINED_PyObject_CompareIntIntBoolEq +#define __Pyx_DEFINED_PyObject_CompareIntIntBoolEq +static int __Pyx_PyObject_CompareIntIntBoolEq(PyObject *op1, PyObject *op2) { +#if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t cmp = __Pyx_PyLong_CompareSignAndSize(op1, op2); + if (cmp == 0) { + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + if (size > 0) { + const digit* digits1 = __Pyx_PyLong_Digits(op1); + const digit* digits2 = __Pyx_PyLong_Digits(op2); + if (size == 1) { + cmp = (Py_ssize_t) digits1[0] - (Py_ssize_t) digits2[0]; + } else if ((size == 2) && (8 * sizeof(Py_ssize_t) >= 2 * PyLong_SHIFT)) { + cmp = (Py_ssize_t) (((((size_t)digits1[1]) << PyLong_SHIFT) | (size_t)digits1[0])) - (Py_ssize_t) (((((size_t)digits2[1]) << PyLong_SHIFT) | (size_t)digits2[0])); + } else { + for (Py_ssize_t i=size-1; i >= 0 && !cmp; --i) { + cmp = (Py_ssize_t) digits1[i] - (Py_ssize_t) digits2[i]; + } + } + } + if (cmp == 0) goto __pyx_return_true; + if (__Pyx_PyLong_IsNeg(op1)) cmp = -cmp; + } + goto __pyx_return_false; +#else + int overflow1, overflow2; + long long iop1 = PyLong_AsLongLongAndOverflow(op1, &overflow1); + long long iop2 = PyLong_AsLongLongAndOverflow(op2, &overflow2); + if (likely(!(overflow1 | overflow2))) { + if (iop1 == iop2) goto __pyx_return_true; else goto __pyx_return_false; + } else if (overflow1 != overflow2) { + if (overflow1 == overflow2) goto __pyx_return_true; else goto __pyx_return_false; + } else { + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); + } +#endif +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} +#endif +static CYTHON_INLINE int __Pyx_PyObject_CompareBoolEq_object_int(PyObject *op1, PyObject *op2, int pyop) { + CYTHON_UNUSED_VAR(pyop); + if (unlikely(op2 == Py_None)) { + if (op1 == Py_None) goto __pyx_return_true; else goto __pyx_richcmp; + } + if (op1 == op2) goto __pyx_return_true; + if (PyFloat_CheckExact(op1)) { + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareFloatIntBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + if (likely(PyLong_CheckExact(op1))) { + if (op1 == op2) goto __pyx_return_true; + if (likely(op2 != Py_None)) { + return __Pyx_PyObject_CompareIntIntBoolEq(op1, op2); + } + goto __pyx_richcmp; + } + if ((0)) goto __pyx_richcmp; + if ((0)) goto __pyx_return_true; + if ((0)) goto __pyx_return_false; +__pyx_richcmp: + return __Pyx_PyObject_RichCompareBool(op1, op2, Py_EQ); +__pyx_return_true: + return 1; +__pyx_return_false: + return 0; +} + +/* AllocateExtensionType */ +static PyObject *__Pyx_AllocateExtensionType(PyTypeObject *t, int is_final) { + if (is_final || likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { + allocfunc alloc_func = __Pyx_PyType_GetSlot(t, tp_alloc, allocfunc); + return alloc_func(t, 0); + } else { + newfunc tp_new = __Pyx_PyType_TryGetSlot(&PyBaseObject_Type, tp_new, newfunc); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (!tp_new) { + PyObject *new_str = PyUnicode_FromString("__new__"); + if (likely(new_str)) { + PyObject *o = PyObject_CallMethodObjArgs((PyObject *)&PyBaseObject_Type, new_str, t, NULL); + Py_DECREF(new_str); + return o; + } else + return NULL; + } else + #endif + return tp_new(t, __pyx_mstate_global->__pyx_empty_tuple, 0); + } +} + +/* CallSlotAsVectorcallUnpackDict (used by CallSlotAsVectorcall) */ +static CYTHON_INLINE int __Pyx_CallSlotAsVectorcallUnpackDict(Py_ssize_t args_size, PyObject *keys_dict, PyObject **args, PyObject *kwnames) { + Py_ssize_t pos = 0, i = 0; + PyObject *key, *value; + while (PyDict_Next(keys_dict, &pos, &key, &value)) { + Py_INCREF(value); + args[args_size+i] = value; + Py_INCREF(key); + if (unlikely(__Pyx_PyTuple_SET_ITEM(kwnames, i, key) == -1)) { + return -1; + } + ++i; + } + return 0; +} + +/* CallSlotAsVectorcall */ +#if CYTHON_VECTORCALL_TPNEW +static PyObject * __Pyx_CallTpnewAsVectorcall(__Pyx_tpnewvectorcallfunc f, PyTypeObject* o, PyObject *a, PyObject *k) { + Py_ssize_t k_size = k ? __Pyx_PyDict_GET_SIZE(k) : 0; +#if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(k_size < 0)) return NULL; +#endif + Py_ssize_t a_size = __Pyx_PyTuple_GET_SIZE(a); +#if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(a_size < 0)) return NULL; +#endif +#if CYTHON_ASSUME_SAFE_MACROS + if (k_size == 0) { + return f(o, &PyTuple_GET_ITEM(a, 0), a_size, NULL); + } +#else + if (k_size == 0 && a_size == 0) { + return f(o, NULL, 0, NULL); + } +#endif + PyObject *stack_args[5]; + PyObject **args = stack_args; + Py_ssize_t maxnargs = PY_SSIZE_T_MAX / sizeof(PyObject*) - 1; + if (a_size > maxnargs - k_size) { + PyErr_NoMemory(); + return NULL; + } + Py_ssize_t total_size = a_size + k_size; + if (total_size > 5) { + args = (PyObject**)PyMem_Malloc(((size_t)total_size)*sizeof(PyObject*)); + if (unlikely(!args)) { + PyErr_NoMemory(); + return NULL; + } + } + PyObject * result = NULL; + PyObject *kwnames = NULL; + int unpack_dict_result; + Py_ssize_t i = 0; + for (; i < a_size; ++i) { + args[i] = __Pyx_PyTuple_GET_ITEM(a, i); +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!args[i])) goto cleanup; +#endif + } +#if !CYTHON_ASSUME_SAFE_MACROS + if (k) // There's a specific shortcut earlier for ASSUME_SAFE_MACROS with no keywords +#endif + { + kwnames = PyTuple_New(k_size); + if (unlikely(!kwnames)) goto cleanup; + __Pyx_BEGIN_CRITICAL_SECTION(k); + unpack_dict_result = __Pyx_CallSlotAsVectorcallUnpackDict(a_size, k, args, kwnames); + __Pyx_END_CRITICAL_SECTION(); + if (unlikely(unpack_dict_result == -1)) goto cleanup; + } + result = f(o, args, a_size, kwnames); + cleanup: + Py_XDECREF(kwnames); + for (i=a_size; i<total_size; ++i) { + Py_XDECREF(args[i]); + } + if (args != stack_args) { + PyMem_Free(args); + } + return result; +} +#endif + +/* CallNewInitFromVectorcall */ +#if CYTHON_VECTORCALL_TPNEW +static PyObject *__Pyx_CallNewInitFromVectorcall(PyTypeObject *t, PyObject *const *args, size_t nargsf, PyObject *kwnames) { + newfunc tp_new = __Pyx_PyType_GetSlot(t, tp_new, newfunc); + if (unlikely(!tp_new)) { + __Pyx_RaiseErrorWithType(PyExc_TypeError, "cannot create " __Pyx_FMT_TYPENAME " instances", t); + return NULL; + } + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(nargsf); + PyObject *result = NULL, *args_tuple = NULL, *kwds_dict = NULL; + Py_ssize_t kw_size = kwnames ? __Pyx_PyTuple_GET_SIZE(kwnames) : 0; +#if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(kw_size == -1)) { + return NULL; + } +#endif + if (kw_size) { + kwds_dict = __Pyx_PyDict_NewPresized(kw_size); + if (unlikely(!kwds_dict)) { + return NULL; + } + for (Py_ssize_t i=0; i<kw_size; ++i) { + PyObject *v = args[nargs + i]; + PyObject *k = __Pyx_PyTuple_GET_ITEM(kwnames, i); +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!k)) { + goto end; + } +#endif + if (unlikely(PyDict_SetItem(kwds_dict, k, v) < 0)) { + goto end; + } + } + } + if (nargs) { + args_tuple = __Pyx_PyTuple_FromArray(args, nargs); + if (unlikely(!args_tuple)) { + goto end; + } + } else { + args_tuple = __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + result = tp_new(t, args_tuple, kwds_dict); + if (unlikely(!result)) { + goto end; + } + if (PyObject_TypeCheck(result, t)) { + initproc tp_init = __Pyx_PyObject_GetSlot(result, tp_init, initproc); + if (tp_init && unlikely(tp_init(result, args_tuple, kwds_dict) < 0)) { + Py_CLEAR(result); + } + } + end: + Py_XDECREF(args_tuple); + Py_XDECREF(kwds_dict); + return result; +} +#endif + +/* CallTypeTraverse */ +#if !CYTHON_USE_TYPE_SPECS +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg) { + if (!always_call) { + PyTypeObject *base = __Pyx_PyObject_GetSlot(o, tp_base, PyTypeObject*); + unsigned long flags = PyType_GetFlags(base); + if (flags & Py_TPFLAGS_HEAPTYPE) { + return 0; + } + } + Py_VISIT((PyObject*)Py_TYPE(o)); + return 0; +} +#endif + +/* PyObjectCallMethod0 (used by PyType_Ready) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || !CYTHON_COMPILING_IN_LIMITED_API) + return PyObject_VectorcallMethod(method_name, &obj, 1 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API + return PyObject_CallMethodObjArgs(obj, method_name, NULL); +#else + return PyObject_CallMethodNoArgs(obj, method_name); +#endif +} + +/* GetTypeDictOffset (used by ValidateBasesTuple) */ +#if !CYTHON_USE_TYPE_SLOTS +CYTHON_UNUSED static Py_ssize_t __Pyx_GetTypeDictOffset(PyObject *tp, int require_cython_valid_result) { + PyObject *tp_dictoffset_o; + Py_ssize_t tp_dictoffset; + tp_dictoffset_o = PyObject_GetAttrString(tp, "__dictoffset__"); + if (unlikely(!tp_dictoffset_o)) return -1; + tp_dictoffset = PyLong_AsSsize_t(tp_dictoffset_o); + Py_DECREF(tp_dictoffset_o); + if (unlikely(require_cython_valid_result && tp_dictoffset == 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' doesn't have a dictoffset"); + return -1; + } else if (unlikely(require_cython_valid_result && tp_dictoffset < 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' has an unexpected negative dictoffset. " + "Please report this as Cython bug"); + return -1; + } + return tp_dictoffset; +} +#endif + +/* RaiseErrorWithObjectType1 (used by ValidateBasesTuple) */ +static void __Pyx_RaiseErrorWithType1(PyObject* exc_type, const char* message, const char *arg, PyTypeObject *type_obj) { + __Pyx_TypeName type_name = __Pyx_PyType_GetFullyQualifiedName(type_obj); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!type_name)) return; + #endif + PyErr_Format(exc_type, message, arg, type_name); + __Pyx_DECREF_TypeName(type_name); +} + +/* ValidateBasesTuple (used by PyType_Ready) */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, int has_dictoffset, PyObject *bases) { + Py_ssize_t i, n; +#if CYTHON_ASSUME_SAFE_SIZE + n = PyTuple_GET_SIZE(bases); +#else + n = PyTuple_Size(bases); + if (unlikely(n < 0)) return -1; +#endif + if (!has_dictoffset) { + PyObject *b; +#if CYTHON_AVOID_BORROWED_REFS + b = PySequence_GetItem(bases, 0); + if (!b) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + b = PyTuple_GET_ITEM(bases, 0); +#else + b = PyTuple_GetItem(bases, 0); + if (!b) return -1; +#endif +#if CYTHON_USE_TYPE_SLOTS + has_dictoffset = ((PyTypeObject*)b)->tp_dictoffset != 0; +#else + Py_ssize_t dictoffset = __Pyx_GetTypeDictOffset(b, 0); + has_dictoffset = dictoffset != 0; +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b); +#endif +#if !CYTHON_USE_TYPE_SLOTS + if (dictoffset == -1 && PyErr_Occurred()) return -1; +#endif + } + for (i = 1; i < n; i++) + { + PyTypeObject *b; +#if CYTHON_AVOID_BORROWED_REFS + PyObject *b0 = PySequence_GetItem(bases, i); + if (!b0) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + PyObject *b0 = PyTuple_GET_ITEM(bases, i); +#else + PyObject *b0 = PyTuple_GetItem(bases, i); + if (!b0) return -1; +#endif + b = (PyTypeObject*) b0; + if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) + { + __Pyx_RaiseErrorWithType( + PyExc_TypeError, "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + if (!has_dictoffset) + { + Py_ssize_t b_dictoffset = 0; +#if CYTHON_USE_TYPE_SLOTS + b_dictoffset = b->tp_dictoffset; +#else + b_dictoffset = __Pyx_GetTypeDictOffset((PyObject*)b, 0); + if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; +#endif + if (b_dictoffset) { + __Pyx_RaiseErrorWithType1( + PyExc_TypeError, + "extension type '%.200s' has no __dict__ slot, " + "but base type '" __Pyx_FMT_TYPENAME "' has: " + "either add 'cdef dict __dict__' to the extension type " + "or add '__slots__ = [...]' to the base type", + type_name, b); +#if !CYTHON_USE_TYPE_SLOTS + dictoffset_return: +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + } +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + } + return 0; +} +#endif + +/* PyType_Ready */ +CYTHON_UNUSED static int __Pyx_PyType_HasMultipleInheritance(PyTypeObject *t) { + while (t) { + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases) { + return 1; + } + t = __Pyx_PyType_GetSlot(t, tp_base, PyTypeObject*); + } + return 0; +} +static int __Pyx_PyType_Ready(PyTypeObject *t) { +#if CYTHON_USE_TYPE_SPECS || !CYTHON_COMPILING_IN_CPYTHON + (void)__Pyx_PyObject_CallMethod0; +#if CYTHON_USE_TYPE_SPECS + (void)__Pyx_validate_bases_tuple; +#endif + return PyType_Ready(t); +#else + int r; + if (!__Pyx_PyType_HasMultipleInheritance(t)) { + return PyType_Ready(t); + } + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset != 0, bases) == -1)) + return -1; + { + int gc_was_enabled; + #if PY_VERSION_HEX >= 0x030A00b1 + gc_was_enabled = PyGC_Disable(); + (void)__Pyx_PyObject_CallMethod0; + #else + PyObject *ret, *py_status; + PyObject *gc = NULL; + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) &&\ + !CYTHON_COMPILING_IN_GRAAL + gc = PyImport_GetModule(__pyx_mstate_global->__pyx_kp_u_gc); + #endif + if (unlikely(!gc)) gc = PyImport_Import(__pyx_mstate_global->__pyx_kp_u_gc); + if (unlikely(!gc)) return -1; + py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_isenabled); + if (unlikely(!py_status)) { + Py_DECREF(gc); + return -1; + } + gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); + Py_DECREF(py_status); + if (gc_was_enabled > 0) { + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_disable); + if (unlikely(!ret)) { + Py_DECREF(gc); + return -1; + } + Py_DECREF(ret); + } else if (unlikely(gc_was_enabled == -1)) { + Py_DECREF(gc); + return -1; + } + #endif + t->tp_flags |= Py_TPFLAGS_HEAPTYPE; +#if PY_VERSION_HEX >= 0x030A0000 + t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; +#endif + r = PyType_Ready(t); + t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; + #if PY_VERSION_HEX >= 0x030A00b1 + if (gc_was_enabled) + PyGC_Enable(); + #else + if (gc_was_enabled) { + PyObject *tp, *v, *tb; + PyErr_Fetch(&tp, &v, &tb); + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_enable); + if (likely(ret || r == -1)) { + Py_XDECREF(ret); + PyErr_Restore(tp, v, tb); + } else { + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + r = -1; + } + } + Py_DECREF(gc); + #endif + } + return r; +#endif +} + +/* HasAttr (used by ImportImpl) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { + PyObject *r; + if (unlikely(!PyUnicode_Check(n))) { + PyErr_SetString(PyExc_TypeError, + "hasattr(): attribute name must be string"); + return -1; + } + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (!r) { + return (unlikely(PyErr_Occurred())) ? -1 : 0; + } else { + Py_DECREF(r); + return 1; + } +} +#endif + +/* ImportImpl (used by Import) */ +static int __Pyx__Import_GetModule(PyObject *qualname, PyObject **module) { + PyObject *imported_module = PyImport_GetModule(qualname); + if (unlikely(!imported_module)) { + *module = NULL; + if (PyErr_Occurred()) { + return -1; + } + return 0; + } + *module = imported_module; + return 1; +} +static int __Pyx__Import_Lookup(PyObject *qualname, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject **module) { + PyObject *imported_module; + PyObject *top_level_package_name; + Py_ssize_t i; + int status, module_found; + Py_ssize_t dot_index; + module_found = __Pyx__Import_GetModule(qualname, &imported_module); + if (unlikely(!module_found || module_found == -1)) { + *module = NULL; + return module_found; + } + if (imported_names) { + for (i = 0; i < len_imported_names; i++) { + PyObject *imported_name = imported_names[i]; +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 + int has_imported_attribute = PyObject_HasAttr(imported_module, imported_name); +#else + int has_imported_attribute = PyObject_HasAttrWithError(imported_module, imported_name); + if (unlikely(has_imported_attribute == -1)) goto error; +#endif + if (!has_imported_attribute) { + goto not_found; + } + } + *module = imported_module; + return 1; + } + dot_index = PyUnicode_FindChar(qualname, '.', 0, PY_SSIZE_T_MAX, 1); + if (dot_index == -1) { + *module = imported_module; + return 1; + } + if (unlikely(dot_index == -2)) goto error; + top_level_package_name = PyUnicode_Substring(qualname, 0, dot_index); + if (unlikely(!top_level_package_name)) goto error; + Py_DECREF(imported_module); + status = __Pyx__Import_GetModule(top_level_package_name, module); + Py_DECREF(top_level_package_name); + return status; +error: + Py_DECREF(imported_module); + *module = NULL; + return -1; +not_found: + Py_DECREF(imported_module); + *module = NULL; + return 0; +} +static PyObject *__Pyx__Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, PyObject *moddict, int level) { + PyObject *module = 0; + PyObject *empty_dict = 0; + PyObject *from_list = 0; + int module_found; + if (!qualname) { + qualname = name; + } + module_found = __Pyx__Import_Lookup(qualname, imported_names, len_imported_names, &module); + if (likely(module_found == 1)) { + return module; + } else if (unlikely(module_found == -1)) { + return NULL; + } + #if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030f00a6 + empty_dict = PyFrozenDict_New(NULL); + #else + empty_dict = PyDict_New(); + #endif + if (unlikely(!empty_dict)) + goto bad; + if (imported_names) { + from_list = __Pyx_PyList_FromArray(imported_names, len_imported_names); + if (unlikely(!from_list)) + goto bad; + } + if (level == -1) { + const char* package_sep = strchr(__Pyx_MODULE_NAME, '.'); + if (package_sep != (0)) { + module = PyImport_ImportModuleLevelObject( + name, moddict, empty_dict, from_list, 1); + if (unlikely(!module)) { + if (unlikely(!PyErr_ExceptionMatches(PyExc_ImportError))) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + if (!module) { + module = PyImport_ImportModuleLevelObject( + name, moddict, empty_dict, from_list, level); + } +bad: + Py_XDECREF(from_list); + Py_XDECREF(empty_dict); + return module; +} + +/* Import */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *const *imported_names, Py_ssize_t len_imported_names, PyObject *qualname, int level) { + return __Pyx__Import(name, imported_names, len_imported_names, qualname, __pyx_mstate_global->__pyx_d, level); +} + +/* ImportFrom */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + const char* module_name_str = 0; + PyObject* module_name = 0; + PyObject* module_dot = 0; + PyObject* full_name = 0; + PyErr_Clear(); + module_name_str = PyModule_GetName(module); + if (unlikely(!module_name_str)) { goto modbad; } + module_name = PyUnicode_FromString(module_name_str); + if (unlikely(!module_name)) { goto modbad; } + module_dot = PyUnicode_Concat(module_name, __pyx_mstate_global->__pyx_kp_u__2); + if (unlikely(!module_dot)) { goto modbad; } + full_name = PyUnicode_Concat(module_dot, name); + if (unlikely(!full_name)) { goto modbad; } + #if (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) ||\ + CYTHON_COMPILING_IN_GRAAL + { + PyObject *modules = PyImport_GetModuleDict(); + if (unlikely(!modules)) + goto modbad; + value = PyObject_GetItem(modules, full_name); + } + #else + value = PyImport_GetModule(full_name); + #endif + modbad: + Py_XDECREF(full_name); + Py_XDECREF(module_dot); + Py_XDECREF(module_name); + } + if (unlikely(!value)) { + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); + } + return value; +} + +/* dict_setdefault (used by FetchCommonType) */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value) { + PyObject* value; +#if __PYX_LIMITED_VERSION_HEX >= 0x030F0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4) + PyDict_SetDefaultRef(d, key, default_value, &value); +#elif CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + PyObject *args[] = {d, key, default_value}; + value = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_n_u_setdefault, args, 3 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API + value = PyObject_CallMethodObjArgs(d, __pyx_mstate_global->__pyx_n_u_setdefault, key, default_value, NULL); +#else + value = PyDict_SetDefault(d, key, default_value); + if (unlikely(!value)) return NULL; + Py_INCREF(value); +#endif + return value; +} + +/* AddModuleRef (used by FetchSharedCythonModule) */ +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && PY_VERSION_HEX < 0x030F00a3 + static PyObject *__Pyx_PyImport_AddModuleObjectRef(PyObject *name) { + PyObject *module_dict = PyImport_GetModuleDict(); + PyObject *m; + if (PyMapping_GetOptionalItem(module_dict, name, &m) < 0) { + return NULL; + } + if (m != NULL && PyModule_Check(m)) { + return m; + } + Py_XDECREF(m); + m = PyModule_NewObject(name); + if (m == NULL) + return NULL; + if (PyDict_CheckExact(module_dict)) { + PyObject *new_m; + (void)PyDict_SetDefaultRef(module_dict, name, m, &new_m); + Py_DECREF(m); + return new_m; + } else { + if (PyObject_SetItem(module_dict, name, m) != 0) { + Py_DECREF(m); + return NULL; + } + return m; + } + } + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + if ((PY_VERSION_HEX >= 0x030E0000) && Py_Version >= 0x030E0100) { + return PyImport_AddModuleRef(name); + } + PyObject *py_name = PyUnicode_FromString(name); + if (!py_name) return NULL; + PyObject *module = __Pyx_PyImport_AddModuleObjectRef(py_name); + Py_DECREF(py_name); + return module; + } +#elif __PYX_LIMITED_VERSION_HEX < 0x030d0000 + static PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *module = PyImport_AddModule(name); + Py_XINCREF(module); + return module; + } +#endif + +/* FetchSharedCythonModule (used by FetchCommonType) */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void) { + return __Pyx_PyImport_AddModuleRef(__PYX_ABI_MODULE_NAME); +} + +/* VerifyCachedType (used by FetchCommonType) */ +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t expected_basicsize) { + Py_ssize_t basicsize; + if (!PyType_Check(cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", name); + return -1; + } + if (expected_basicsize == 0) { + return 0; // size is inherited, nothing useful to check + } +#if CYTHON_COMPILING_IN_LIMITED_API && CYTHON_OPAQUE_OBJECTS + if (expected_basicsize < 0) { + basicsize = PyType_GetTypeDataSize((PyTypeObject*)cached_type); + } else +#endif + { + #if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); + if (unlikely(!py_basicsize)) return -1; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = NULL; + if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) return -1; + #else + basicsize = ((PyTypeObject*) cached_type)->tp_basicsize; + #endif + } + if ((expected_basicsize >= 0) ? + (basicsize != expected_basicsize) : + (basicsize < -expected_basicsize)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + name); + return -1; + } + return 0; +} + +/* FetchCommonType (used by CommonTypesMetaclass) */ +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject* __Pyx_PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *result = __Pyx_PyType_FromModuleAndSpec(module, spec, bases); + if (result && metaclass) { + PyObject *old_tp = (PyObject*)Py_TYPE(result); + Py_INCREF((PyObject*)metaclass); + Py_SET_TYPE(result, metaclass); + Py_DECREF(old_tp); + PyType_Modified((PyTypeObject*)result); + } + return result; +} +#else +#define __Pyx_PyType_FromMetaclass(me, mo, s, b) PyType_FromMetaclass(me, mo, s, b) +#endif +static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *abi_module = NULL, *cached_type = NULL, *abi_module_dict, *new_cached_type, *py_object_name; + int get_item_ref_result; + const char* object_name = strrchr(spec->name, '.'); + object_name = object_name ? object_name+1 : spec->name; + py_object_name = PyUnicode_FromString(object_name); + if (!py_object_name) return NULL; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) goto done; + abi_module_dict = PyModule_GetDict(abi_module); + if (!abi_module_dict) goto done; + get_item_ref_result = __Pyx_PyDict_GetItemRef(abi_module_dict, py_object_name, &cached_type); + if (get_item_ref_result == 1) { + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else if (unlikely(get_item_ref_result == -1)) { + goto bad; + } + cached_type = __Pyx_PyType_FromMetaclass( + metaclass, + CYTHON_USE_MODULE_STATE ? module : abi_module, + spec, bases); + if (unlikely(!cached_type)) goto bad; + new_cached_type = __Pyx_PyDict_SetDefault(abi_module_dict, py_object_name, cached_type); + if (unlikely(new_cached_type != cached_type)) { + if (unlikely(!new_cached_type)) goto bad; + Py_DECREF(cached_type); + cached_type = new_cached_type; + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else { + Py_DECREF(new_cached_type); + } +done: + Py_XDECREF(abi_module); + Py_DECREF(py_object_name); + assert(cached_type == NULL || PyType_Check(cached_type)); + return (PyTypeObject *) cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} + +/* CommonTypesMetaclass (used by CythonFunctionShared) */ +static PyObject* __pyx_CommonTypesMetaclass_get_module(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED void* context) { + return PyUnicode_FromString(__PYX_ABI_MODULE_NAME); +} +#if __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject* __pyx_CommonTypesMetaclass_call(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *args, CYTHON_UNUSED PyObject *kwds) { + PyErr_SetString(PyExc_TypeError, "Cannot instantiate Cython internal types"); + return NULL; +} +static int __pyx_CommonTypesMetaclass_setattr(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED PyObject *attr, CYTHON_UNUSED PyObject *value) { + PyErr_SetString(PyExc_TypeError, "Cython internal types are immutable"); + return -1; +} +#endif +static PyGetSetDef __pyx_CommonTypesMetaclass_getset[] = { + {"__module__", __pyx_CommonTypesMetaclass_get_module, NULL, NULL, NULL}, + {0, 0, 0, 0, 0} +}; +static PyType_Slot __pyx_CommonTypesMetaclass_slots[] = { + {Py_tp_getset, (void *)__pyx_CommonTypesMetaclass_getset}, + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {Py_tp_call, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_new, (void*)__pyx_CommonTypesMetaclass_call}, + {Py_tp_setattro, (void*)__pyx_CommonTypesMetaclass_setattr}, + #endif + {0, 0} +}; +static PyType_Spec __pyx_CommonTypesMetaclass_spec = { + __PYX_TYPE_MODULE_PREFIX "_common_types_metatype", + 0, + 0, + Py_TPFLAGS_IMMUTABLETYPE | + Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT, + __pyx_CommonTypesMetaclass_slots +}; +static int __pyx_CommonTypesMetaclass_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + PyObject *bases = PyTuple_Pack(1, &PyType_Type); + if (unlikely(!bases)) { + return -1; + } + mstate->__pyx_CommonTypesMetaclassType = __Pyx_FetchCommonTypeFromSpec(NULL, module, &__pyx_CommonTypesMetaclass_spec, bases); + Py_DECREF(bases); + if (unlikely(mstate->__pyx_CommonTypesMetaclassType == NULL)) { + return -1; + } + return 0; +} + +/* CythonFunctionPerModule (used by CythonFunctionShared) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunctionNoMethod(PyObject *func, void (*cfunc)(void)) { + if (__Pyx_CyFunction_Check(func)) { + return __Pyx_as_CyFunctionObject(func)->func_methoddef->ml_meth == (PyCFunction) cfunc; + } else if (PyCFunction_Check(func)) { + return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; + } + return 0; +} +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if ((PyObject*)Py_TYPE(func) == __pyx_mstate_global->__Pyx_CachedMethodType) { + int result; + PyObject *newFunc = PyObject_GetAttr(func, __pyx_mstate_global->__pyx_n_u_func); + if (unlikely(!newFunc)) { + PyErr_Clear(); // It's only an optimization, so don't throw an error + return 0; + } + result = __Pyx__IsSameCyOrCFunctionNoMethod(newFunc, cfunc); + Py_DECREF(newFunc); + return result; + } + return __Pyx__IsSameCyOrCFunctionNoMethod(func, cfunc); +} +#else +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if (PyMethod_Check(func)) { + func = PyMethod_GET_FUNCTION(func); + } + return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +} +#endif +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { +#if CYTHON_COMPILING_IN_LIMITED_API + __Pyx_Py_XDECREF_SET( + __Pyx__CyFunction_GetClassObj(f), + ((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#else + __Pyx_Py_XDECREF_SET( + ((PyCMethodObject *) (f))->mm_class, + (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, PyTypeObject *defaults_type) { + __pyx_CyFunctionObject *m = __Pyx_as_CyFunctionObject(func); + m->defaults = PyObject_CallObject((PyObject*)defaults_type, NULL); // _PyObject_New(defaults_type); + if (unlikely(!m->defaults)) + return NULL; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = __Pyx_as_CyFunctionObject(func); + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = __Pyx_as_CyFunctionObject(func); + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = __Pyx_as_CyFunctionObject(func); + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* PyMethodNew (used by CythonFunctionShared) */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + PyObject *result; + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + #if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + { + PyObject *args[] = {func, self}; + result = PyObject_Vectorcall(__pyx_mstate_global->__Pyx_CachedMethodType, args, 2, NULL); + } + #else + result = PyObject_CallFunctionObjArgs(__pyx_mstate_global->__Pyx_CachedMethodType, func, self, NULL); + #endif + return result; +} +#else +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + return PyMethod_New(func, self); +} +#endif + +/* PyVectorcallFastCallDict (used by CythonFunctionShared) */ +#if CYTHON_VECTORCALL +static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + PyObject *res = NULL; + PyObject *kwnames; + PyObject **newargs; + PyObject **kwvalues; + Py_ssize_t i; + #if CYTHON_AVOID_BORROWED_REFS + PyObject *pos; + #else + Py_ssize_t pos; + #endif + size_t j; + PyObject *key, *value; + unsigned long keys_are_strings; + #if !CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t nkw = PyDict_Size(kw); + if (unlikely(nkw == -1)) return NULL; + #else + Py_ssize_t nkw = PyDict_GET_SIZE(kw); + #endif + newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); + if (unlikely(newargs == NULL)) { + PyErr_NoMemory(); + return NULL; + } + for (j = 0; j < nargs; j++) newargs[j] = args[j]; + kwnames = PyTuple_New(nkw); + if (unlikely(kwnames == NULL)) { + PyMem_Free(newargs); + return NULL; + } + kwvalues = newargs + nargs; + pos = 0; + i = 0; + keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; + while (__Pyx_PyDict_NextRef(kw, &pos, &key, &value)) { + keys_are_strings &= + #if CYTHON_COMPILING_IN_LIMITED_API + PyType_GetFlags(Py_TYPE(key)); + #else + Py_TYPE(key)->tp_flags; + #endif + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(PyTuple_SetItem(kwnames, i, key) < 0)) goto cleanup; + #else + PyTuple_SET_ITEM(kwnames, i, key); + #endif + kwvalues[i] = value; + i++; + } + if (unlikely(!keys_are_strings)) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + goto cleanup; + } + res = vc(func, newargs, nargs, kwnames); +cleanup: + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(pos); + #endif + Py_DECREF(kwnames); + for (i = 0; i < nkw; i++) + Py_DECREF(kwvalues[i]); + PyMem_Free(newargs); + return res; +} +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + Py_ssize_t kw_size = + likely(kw == NULL) ? + 0 : +#if !CYTHON_ASSUME_SAFE_SIZE + PyDict_Size(kw); +#else + PyDict_GET_SIZE(kw); +#endif + if (kw_size == 0) { + return vc(func, args, nargs, NULL); + } +#if !CYTHON_ASSUME_SAFE_SIZE + else if (unlikely(kw_size == -1)) { + return NULL; + } +#endif + return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); +} +#endif + +/* CythonFunctionShared (used by CythonFunction) */ +static PyObject * +__Pyx_CyFunction_get_doc_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_doc == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + const char *doc = op->func_methoddef->ml_doc; +#else + const char *doc = ((PyCFunctionObject*)op)->m_ml->ml_doc; +#endif + if (doc) { + op->func_doc = PyUnicode_FromString(doc); + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static PyObject * +__Pyx_CyFunction_get_doc(PyObject *op_in, void *closure) { + PyObject *result; + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + CYTHON_UNUSED_VAR(closure); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + result = __Pyx_CyFunction_get_doc_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_doc(PyObject *op_in, PyObject *value, void *context) +{ + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->func_doc, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_name == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + const char *name = op->func_methoddef->ml_name; +#else + const char *name = ((PyCFunctionObject*)op)->m_ml->ml_name; +#endif + op->func_name = PyUnicode_InternFromString(name); + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static PyObject * +__Pyx_CyFunction_get_name(PyObject *op, void *context) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_name_locked(__Pyx_as_CyFunctionObject(op)); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_name(PyObject *op_in, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->func_name, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(PyObject *op_in, void *context) +{ + CYTHON_UNUSED_VAR(context); + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + PyObject *result; + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + Py_INCREF(op->func_qualname); + result = op->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_qualname(PyObject *op_in, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->func_qualname, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +#endif +static PyObject * +__Pyx_CyFunction_get_globals(PyObject *op_in, void *context) +{ + CYTHON_UNUSED_VAR(context); + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(PyObject *op, void *context) +{ + CYTHON_UNUSED_VAR(op); + CYTHON_UNUSED_VAR(context); + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(PyObject *op_in, void *context) +{ + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + PyObject* result = (op->func_code) ? op->func_code : Py_None; + CYTHON_UNUSED_VAR(context); + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op, PyObject *op_obj) { + int result = 0; + PyObject *res = op->defaults_getter(op_obj); + if (unlikely(!res)) + return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif + Py_DECREF(res); + return result; +} +static int +__Pyx_CyFunction_set_defaults(PyObject *op_in, PyObject* value, void *context) { + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults_locked(PyObject *op_in) { + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + PyObject* result = op->defaults_tuple; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op, op_in) < 0)) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_defaults(PyObject *op, void *context) { + PyObject* result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_defaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(PyObject *op_in, PyObject* value, void *context) { + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults_locked(PyObject *op_in) { + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + PyObject* result = op->defaults_kwdict; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op, op_in) < 0)) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(PyObject *op, void *context) { + PyObject* result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_kwdefaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int __Pyx_CyFunction_set_annotate_in_dict_if_exists(PyObject *op_in, PyObject *value); +static int +__Pyx_CyFunction_set_annotations(PyObject *op_in, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value || value == Py_None) { + value = NULL; + } else if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + Py_XINCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->func_annotations, value); + __Pyx_END_CRITICAL_SECTION(); + if (unlikely(__Pyx_CyFunction_set_annotate_in_dict_if_exists(op_in, Py_None) < 0)) return -1; + return 0; +} +static int +__Pyx_CyFunction_get_dict_if_exists(PyObject *op_in, PyObject **dict) { + /* Return 1 if the function dict exists, 0 otherwise. This cannot fail: + * _PyObject_GetDictPtr() may clear errors internally, but never reports them. */ +#if CYTHON_COMPILING_IN_PYPY + *dict = PyObject_GenericGetDict(op_in, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030C0000 + *dict = __Pyx_as_CyFunctionObject(op_in)->func_dict; +#else + PyObject **dictptr = _PyObject_GetDictPtr(op_in); + *dict = likely(dictptr) ? *dictptr : NULL; +#endif + return *dict ? 1 : 0; +} +static int +__Pyx_CyFunction_get_annotate_from_dict_if_exists(PyObject *op_in, PyObject **annotate) { + PyObject *dict; + int dict_found; + *annotate = NULL; + dict_found = __Pyx_CyFunction_get_dict_if_exists(op_in, &dict); + if (!dict_found) return 0; + return __Pyx_PyDict_GetItemRef(dict, __pyx_mstate_global->__pyx_n_u_annotate, annotate); +} +static int +__Pyx_CyFunction_set_annotate_in_dict_if_exists(PyObject *op_in, PyObject *value) { + PyObject *dict; + int dict_found; + dict_found = __Pyx_CyFunction_get_dict_if_exists(op_in, &dict); + if (!dict_found) return 0; + if (value) { + return PyDict_SetItem(dict, __pyx_mstate_global->__pyx_n_u_annotate, value); + } else { +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 + return PyDict_Pop(dict, __pyx_mstate_global->__pyx_n_u_annotate, NULL); +#else + int result = PyDict_Contains(dict, __pyx_mstate_global->__pyx_n_u_annotate); + if (result == 1) { + result = PyDict_DelItem(dict, __pyx_mstate_global->__pyx_n_u_annotate); + } + return result; +#endif + } +} +static int +__Pyx_CyFunction_set_annotate_in_dict(PyObject *op_in, PyObject *value) { + PyObject *dict; + int result; +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + dict = __Pyx_CyFunction_get_dict(__Pyx_as_CyFunctionObject(op_in), NULL); +#else + dict = PyObject_GenericGetDict(op_in, NULL); +#endif + if (unlikely(!dict)) return -1; + result = PyDict_SetItem(dict, __pyx_mstate_global->__pyx_n_u_annotate, value); + Py_DECREF(dict); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotations_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->func_annotations; + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotations(PyObject *op_in, void *context) { + PyObject *annotate = NULL; + PyObject *result = NULL; + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + result = __Pyx_XNewRef(op->func_annotations); + __Pyx_END_CRITICAL_SECTION(); + if (result) return result; + if (unlikely(__Pyx_CyFunction_get_annotate_from_dict_if_exists(op_in, &annotate) < 0)) return NULL; + if (!annotate || annotate == Py_None) { + Py_XDECREF(annotate); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + result = __Pyx_CyFunction_get_annotations_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; + } + PyObject *format = PyLong_FromLong(1L); // annotationlib.Format.VALUE + if (likely(format)) { + if (!Py_EnterRecursiveCall(" cyfunction __annotations__.__get__")) { + result = __Pyx_PyObject_CallOneArg(annotate, format); + Py_LeaveRecursiveCall(); + Py_DECREF(format); + } + } + Py_DECREF(annotate); + if (unlikely(!result)) return NULL; + if (unlikely(!PyDict_Check(result))) { + PyErr_SetString(PyExc_TypeError, "__annotate__ must return a dict"); + Py_DECREF(result); + return NULL; + } + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + __Pyx_Py_XDECREF_SET(op->func_annotations, __Pyx_NewRef(result)); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyObject *__Pyx_CyFunction_annotate_impl(PyObject *self, PyObject *arg) { + CYTHON_UNUSED_VAR(arg); + if (unlikely(!self)) { + PyErr_SetString(PyExc_SystemError, "cython __annotate__ called without 'self' argument"); + return NULL; + } + PyObject *result; + if (Py_EnterRecursiveCall(" in cyfunction annotate")) { + return NULL; + } + result = __Pyx_CyFunction_get_annotations(self, NULL); + Py_LeaveRecursiveCall(); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotate(PyObject *op_in, void *context); +static int +__Pyx_CyFunction_set_annotate(PyObject *op_in, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, "__annotate__ cannot be deleted"); + return -1; + } + if (unlikely(value != Py_None && !PyCallable_Check(value))) { + PyErr_SetString(PyExc_TypeError, "__annotate__ must be callable or None"); + return -1; + } + if (unlikely(__Pyx_TypeCheck(value, &PyCFunction_Type))) { +#if !CYTHON_ASSUME_SAFE_MACROS && !CYTHON_COMPILING_IN_PYPY + PyCFunction cfunction = PyCFunction_GetFunction(value); + if (unlikely(!cfunction)) return -1; + PyObject *value_self = PyCFunction_GetSelf(value); + if (unlikely(!value_self && PyErr_Occurred())) return -1; +#else + PyCFunction cfunction = PyCFunction_GET_FUNCTION(value); + PyObject *value_self = PyCFunction_GET_SELF(value); +#endif + if (cfunction == __Pyx_CyFunction_annotate_impl && value_self == op_in) { + return __Pyx_CyFunction_set_annotate_in_dict_if_exists(op_in, NULL); + } + } + if (value != Py_None) { + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + Py_CLEAR(op->func_annotations); + __Pyx_END_CRITICAL_SECTION(); + } + return __Pyx_CyFunction_set_annotate_in_dict(op_in, value); +} +#if __PYX_LIMITED_VERSION_HEX < 0x030B0000 +static PyObject * +__Pyx_CyFunction_get_is_coroutine_value(__pyx_CyFunctionObject *op) { + int is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; + if (is_coroutine) { + PyObject *is_coroutine_value, *module, *fromlist, *marker = __pyx_mstate_global->__pyx_n_u_is_coroutine; + fromlist = PyList_New(1); + if (unlikely(!fromlist)) return NULL; + Py_INCREF(marker); +#if CYTHON_ASSUME_SAFE_MACROS + PyList_SET_ITEM(fromlist, 0, marker); +#else + if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { + Py_DECREF(fromlist); + return NULL; + } +#endif + module = PyImport_ImportModuleLevelObject(__pyx_mstate_global->__pyx_n_u_asyncio_coroutines, NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + if (unlikely(!module)) { + goto ignore_or_error; + } + is_coroutine_value = __Pyx_PyObject_GetAttrStr(module, marker); + Py_DECREF(module); + if (likely(is_coroutine_value)) { + return is_coroutine_value; + } +ignore_or_error: + if (!__Pyx_IgnoreException(PyExc_Exception)) { + return NULL; + } + } + return __Pyx_PyBool_FromLong(is_coroutine); +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine(PyObject *op_in, void *context) { + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + PyObject *result; + CYTHON_UNUSED_VAR(context); + if (op->func_is_coroutine) { + return __Pyx_NewRef(op->func_is_coroutine); + } + result = __Pyx_CyFunction_get_is_coroutine_value(op); + if (unlikely(!result)) + return NULL; + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + if (op->func_is_coroutine) { + Py_DECREF(result); + result = __Pyx_NewRef(op->func_is_coroutine); + } else { + op->func_is_coroutine = __Pyx_NewRef(result); + } + __Pyx_END_CRITICAL_SECTION(); + return result; +} +#endif +static void __Pyx_CyFunction_raise_argument_count_error(PyObject *func, const char* message, Py_ssize_t size) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, message, size); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + name, message, size); +#endif +} +static void __Pyx_CyFunction_raise_type_error(PyObject *func, const char* message) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s", + py_name, message); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s", + name, message); +#endif +} +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx_CyFunction_get_module(PyObject *op_in, void *context) { + CYTHON_UNUSED_VAR(context); + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + Py_INCREF(op->func_module); + return op->func_module; +} +static int +__Pyx_CyFunction_set_module(PyObject *op_in, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + PyObject *old = op->func_module; + op->func_module = value; + Py_DECREF(old); + return 0; +} +#endif +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {"func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + {"func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)PyObject_GenericSetDict, 0, 0}, +#else + {"func_dict", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, + {"__dict__", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0}, +#endif + {"func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {"__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {"__annotate__", (getter)__Pyx_CyFunction_get_annotate, (setter)__Pyx_CyFunction_set_annotate, 0, 0}, +#if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + {"_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyMemberDef __pyx_CyFunction_members[] = { +#if !CYTHON_COMPILING_IN_LIMITED_API + {"__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + {"__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), + __PYX_SHARED_RELATIVE_OFFSET | READONLY, 0}, +#endif +#if CYTHON_VECTORCALL +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + {"__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), + __PYX_SHARED_RELATIVE_OFFSET | READONLY, 0}, +#else + {"__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + {"__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), + __PYX_SHARED_RELATIVE_OFFSET | READONLY, 0}, +#else + {"__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, +#endif +#endif + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(PyObject *m_in, PyObject *args) +{ + PyObject *result = NULL; + __pyx_CyFunctionObject *m = __Pyx_as_CyFunctionObject(m_in); + CYTHON_UNUSED_VAR(args); + __Pyx_BEGIN_CRITICAL_SECTION(m_in); + Py_INCREF(m->func_qualname); + result = m->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__annotate_cython__", __Pyx_CyFunction_annotate_impl, METH_O, + "Placeholder __annotate__ function to allow 'functools.wraps' to work " + "on Cython functions."}, + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_get_annotate(PyObject *op_in, void *context) { + PyObject *annotate = NULL; + CYTHON_UNUSED_VAR(context); + if (unlikely(__Pyx_CyFunction_get_annotate_from_dict_if_exists(op_in, &annotate) < 0)) return NULL; + if (annotate) return annotate; + PyObject *method = PyCFunction_New( + &__pyx_CyFunction_methods[0], + op_in); + return method; +} +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) +#endif +static PyObject *__Pyx_CyFunction_Init(PyObject *op_in, + PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + __pyx_CyFunctionObject* op = __Pyx_as_CyFunctionObject(op_in); +#if !CYTHON_COMPILING_IN_LIMITED_API + PyCFunctionObject *cf = (PyCFunctionObject*) op; +#endif + if (unlikely(op == NULL)) + return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_methoddef = ml; + Py_INCREF(module); + op->func_module = module; +#endif + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; +#if !CYTHON_COMPILING_IN_LIMITED_API + cf->m_ml = ml; + cf->m_self = (PyObject *) op; +#endif + Py_XINCREF(closure); + op->func_closure = closure; +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_XINCREF(module); + cf->m_module = module; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + op->func_dict = NULL; +#endif + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_classobj = NULL; +#else + ((PyCMethodObject*)op)->mm_class = NULL; +#endif + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; +#if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + op->func_is_coroutine = NULL; +#endif +#if CYTHON_VECTORCALL + switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { + case METH_NOARGS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; + break; + case METH_O: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; + break; + case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; + break; + case METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; + break; + case METH_VARARGS | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = NULL; + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + Py_DECREF(op_in); + return NULL; + } +#endif + return op_in; +} +static int __Pyx__CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func_module); +#else + Py_CLEAR(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func_dict); +#elif PY_VERSION_HEX < 0x030d0000 + _PyObject_ClearManagedDict((PyObject*)m); +#else + PyObject_ClearManagedDict((PyObject*)m); +#endif + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func_classobj); +#else + { + PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; + ((PyCMethodObject *) (m))->mm_class = NULL; + Py_XDECREF(cls); + } +#endif + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); +#if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + Py_CLEAR(m->func_is_coroutine); +#endif + Py_CLEAR(m->defaults); + return 0; +} +static int +__Pyx_CyFunction_clear(PyObject *m) +{ + return __Pyx__CyFunction_clear(__Pyx_as_CyFunctionObject(m)); +} +static void __Pyx__CyFunction_dealloc(PyObject *m) +{ + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(m); + if (__Pyx_CyFunction_weakreflist(cyfunc) != NULL) + PyObject_ClearWeakRefs(m); + __Pyx__CyFunction_clear(cyfunc); + __Pyx_PyHeapTypeObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(PyObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(PyObject *m_in, visitproc visit, void *arg) +{ + __pyx_CyFunctionObject *m = __Pyx_as_CyFunctionObject(m_in); + { + int e = __Pyx_call_type_traverse(m_in, 1, visit, arg); + if (e) return e; + } + Py_VISIT(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func_module); +#else + Py_VISIT(((PyCFunctionObject*)m)->m_module); +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func_dict); +#else + { + int e = +#if PY_VERSION_HEX < 0x030d0000 + _PyObject_VisitManagedDict +#else + PyObject_VisitManagedDict +#endif + ((PyObject*)m, visit, arg); + if (e != 0) return e; + } +#endif + __Pyx_VISIT_CONST(m->func_name); + __Pyx_VISIT_CONST(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + __Pyx_VISIT_CONST(m->func_code); + Py_VISIT(__Pyx__CyFunction_GetClassObj(m)); + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + Py_VISIT(m->func_annotations); +#if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + Py_VISIT(m->func_is_coroutine); +#endif + Py_VISIT(m->defaults); + return 0; +} +static PyObject* +__Pyx_CyFunction_repr(PyObject *op_in) +{ + __pyx_CyFunctionObject *op = __Pyx_as_CyFunctionObject(op_in); + PyObject *repr; + __Pyx_BEGIN_CRITICAL_SECTION(op_in); + repr = PyUnicode_FromFormat("<cyfunction %U at %p>", + op->func_qualname, (void *)op); + __Pyx_END_CRITICAL_SECTION(); + return repr; +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { +#if CYTHON_COMPILING_IN_LIMITED_API + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(func); + PyCFunction meth = cyfunc->func_methoddef->ml_meth; + int flags = cyfunc->func_methoddef->ml_flags; +#else + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + int flags = f->m_ml->ml_flags; +#endif + Py_ssize_t size; + switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)(void(*)(void))meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 0)) + return (*meth)(self, NULL); + __Pyx_CyFunction_raise_argument_count_error( + func, + "takes no arguments", size); + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } + __Pyx_CyFunction_raise_argument_count_error( + func, + "takes exactly one argument", size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + return NULL; + } + __Pyx_CyFunction_raise_type_error( + func, "takes no keyword arguments"); + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + result = __Pyx_CyFunction_CallMethod(func, func, arg, kw); + return result; +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(func); +#if CYTHON_VECTORCALL + __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); + if (vc) { +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); +#else + (void) &__Pyx_PyVectorcall_FastCallDict; + return PyVectorcall_Call(func, args, kw); +#endif + } +#endif + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; +#if CYTHON_ASSUME_SAFE_SIZE + argc = PyTuple_GET_SIZE(args); +#else + argc = PyTuple_Size(args); + if (unlikely(argc < 0)) return NULL; +#endif + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); + PyErr_Format(PyExc_TypeError, + "unbound method %.200S() needs an argument", + cyfunc->func_qualname); + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +#if CYTHON_VECTORCALL +static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(PyObject *func, __pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) +{ + int ret = 0; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + if (unlikely(nargs < 1)) { + __Pyx_CyFunction_raise_type_error( + func, "needs an argument"); + return -1; + } + ret = 1; + } + if (unlikely(kwnames) && unlikely(__Pyx_PyTuple_GET_SIZE(kwnames))) { + __Pyx_CyFunction_raise_type_error( + func, "takes no keyword arguments"); + return -1; + } + return ret; +} +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(func); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = cyfunc->func_methoddef->ml_meth; + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(func, cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = func; + break; + default: + return NULL; + } + if (unlikely(nargs != 0)) { + __Pyx_CyFunction_raise_argument_count_error( + func, "takes no arguments", nargs); + return NULL; + } + return meth(self, NULL); +} +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(func); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = cyfunc->func_methoddef->ml_meth; + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(func, cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = func; + break; + default: + return NULL; + } + if (unlikely(nargs != 1)) { + __Pyx_CyFunction_raise_argument_count_error( + func, "takes exactly one argument", nargs); + return NULL; + } + return meth(self, args[0]); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(func); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = cyfunc->func_methoddef->ml_meth; + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(func, cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = func; + break; + default: + return NULL; + } + return ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))meth)(self, args, nargs, kwnames); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = __Pyx_as_CyFunctionObject(func); + PyTypeObject *cls = (PyTypeObject *) __Pyx__CyFunction_GetClassObj(cyfunc); + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = cyfunc->func_methoddef->ml_meth; + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(func, cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = func; + break; + default: + return NULL; + } + #if PY_VERSION_HEX < 0x030e00A6 + size_t nargs_value = (size_t) nargs; + #else + Py_ssize_t nargs_value = nargs; + #endif + return ((__Pyx_PyCMethod)(void(*)(void))meth)(self, cls, args, nargs_value, kwnames); +} +#endif +static PyType_Slot __pyx_CyFunctionType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, + {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, + {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, + {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, + {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, + {Py_tp_methods, (void *)__pyx_CyFunction_methods}, + {Py_tp_members, (void *)__pyx_CyFunction_members}, + {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, + {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, + {0, 0}, +}; +static PyType_Spec __pyx_CyFunctionType_spec = { + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + __PYX_SHARED_SIZEOF(__pyx_CyFunctionObject), + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if CYTHON_VECTORCALL +#if defined(Py_TPFLAGS_HAVE_VECTORCALL) + Py_TPFLAGS_HAVE_VECTORCALL | +#elif defined(_Py_TPFLAGS_HAVE_VECTORCALL) + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif +#endif // CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x030C0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_TPFLAGS_MANAGED_DICT | +#endif + Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + __pyx_CyFunctionType_slots +}; +static int __pyx_CyFunction_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + mstate->__pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec( + mstate->__pyx_CommonTypesMetaclassType, module, &__pyx_CyFunctionType_spec, NULL); + if (unlikely(mstate->__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} + +/* CythonFunction */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + (void)&__Pyx_Get_CyFunction_Type; + PyObject *op = __Pyx_CyFunction_Init( + PyObject_GC_New(PyObject, __pyx_mstate_global->__pyx_CyFunctionType), + ml, flags, qualname, closure, module, globals, code + ); + if (likely(op)) { + PyObject_GC_Track(op); + } + return op; +} +static PyTypeObject *__Pyx_Get_CyFunction_Type(void) { + PyTypeObject *tp = __pyx_mstate_global->__pyx_CyFunctionType; + Py_INCREF((PyObject*)tp); + return tp; +} + +/* CLineInTraceback (used by AddTraceback) */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 +#define __Pyx_PyProbablyModule_GetDict(o) __Pyx_XNewRef(PyModule_GetDict(o)) +#elif !CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyProbablyModule_GetDict(o) PyObject_GenericGetDict(o, NULL); +#else +PyObject* __Pyx_PyProbablyModule_GetDict(PyObject *o) { + PyObject **dict_ptr = _PyObject_GetDictPtr(o); + return dict_ptr ? __Pyx_XNewRef(*dict_ptr) : NULL; +} +#endif +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { + PyObject *use_cline = NULL; + PyObject *ptype, *pvalue, *ptraceback; + PyObject *cython_runtime_dict; + CYTHON_MAYBE_UNUSED_VAR(tstate); + if (unlikely(!__pyx_mstate_global->__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + cython_runtime_dict = __Pyx_PyProbablyModule_GetDict(__pyx_mstate_global->__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, cython_runtime_dict, + __Pyx_PyDict_SetDefault(cython_runtime_dict, __pyx_mstate_global->__pyx_n_u_cline_in_traceback, Py_False)) + } + if (use_cline == NULL || use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + Py_XDECREF(use_cline); + Py_XDECREF(cython_runtime_dict); + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache (used by AddTraceback) */ +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static __Pyx_CachedCodeObjectType *__pyx__find_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line) { + __Pyx_CachedCodeObjectType* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!code_cache->entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if (unlikely(pos >= code_cache->count) || unlikely(code_cache->entries[pos].code_line != code_line)) { + return NULL; + } + code_object = code_cache->entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__find_code_object; + return NULL; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just miss. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type old_count = __pyx_atomic_incr_acq_rel(&code_cache->accessor_count); + if (old_count < 0) { + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); + return NULL; + } +#endif + __Pyx_CachedCodeObjectType *result = __pyx__find_code_object(code_cache, code_line); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); +#endif + return result; +#endif +} +static void __pyx__insert_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line, __Pyx_CachedCodeObjectType* code_object) +{ + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = code_cache->entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + code_cache->entries = entries; + code_cache->max_count = 64; + code_cache->count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if ((pos < code_cache->count) && unlikely(code_cache->entries[pos].code_line == code_line)) { + __Pyx_CachedCodeObjectType* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_INCREF(code_object); + Py_DECREF(tmp); + return; + } + if (code_cache->count == code_cache->max_count) { + int new_max = code_cache->max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + code_cache->entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + code_cache->entries = entries; + code_cache->max_count = new_max; + } + for (i=code_cache->count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + code_cache->count++; + Py_INCREF(code_object); +} +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__insert_code_object; + return; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just fail. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type expected = 0; + if (!__pyx_atomic_int_cmp_exchange(&code_cache->accessor_count, &expected, INT_MIN)) { + return; + } +#endif + __pyx__insert_code_object(code_cache, code_line, code_object); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_sub(&code_cache->accessor_count, INT_MIN); +#endif +#endif +} + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API && !defined(PYPY_VERSION) + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, + PyObject *firstlineno, PyObject *name) { + PyObject *replace = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; + replace = PyObject_GetAttrString(code, "replace"); + if (likely(replace)) { + PyObject *result = PyObject_Call(replace, __pyx_mstate_global->__pyx_empty_tuple, scratch_dict); + Py_DECREF(replace); + return result; + } + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; + PyObject *replace = NULL, *getframe = NULL, *frame = NULL; + PyObject *exc_type, *exc_value, *exc_traceback; + int success = 0; + if (c_line) { + c_line = __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); + } + __Pyx_PyErr_FetchException(&exc_type, &exc_value, &exc_traceback); + code_object = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!code_object) { + code_object = Py_CompileString("_getframe()", filename, Py_eval_input); + if (unlikely(!code_object)) goto bad; + py_py_line = PyLong_FromLong(py_line); + if (unlikely(!py_py_line)) goto bad; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + } else { + py_funcname = PyUnicode_FromString(funcname); + } + if (unlikely(!py_funcname)) goto bad; + dict = PyDict_New(); + if (unlikely(!dict)) goto bad; + { + PyObject *old_code_object = code_object; + code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); + Py_DECREF(old_code_object); + } + if (unlikely(!code_object)) goto bad; + __pyx_insert_code_object(c_line ? -c_line : py_line, code_object); + } else { + dict = PyDict_New(); + } + getframe = PySys_GetObject("_getframe"); + if (unlikely(!getframe)) goto bad; + if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; + frame = PyEval_EvalCode(code_object, dict, dict); + if (unlikely(!frame) || frame == Py_None) goto bad; + success = 1; + bad: + __Pyx_PyErr_RestoreException(exc_type, exc_value, exc_traceback); + Py_XDECREF(code_object); + Py_XDECREF(py_py_line); + Py_XDECREF(py_funcname); + Py_XDECREF(dict); + Py_XDECREF(replace); + if (success) { + PyTraceBack_Here( + (struct _frame*)frame); + } + Py_XDECREF(frame); +} +#else +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + } + py_code = PyCode_NewEmpty(filename, funcname, py_line); + Py_XDECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_mstate_global->__pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} +#endif + +/* CIntFromPyVerify */ +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* CIntFromPy */ +static int __Pyx_LargePyLong___Pyx_PyLong_As_int(PyObject *x); +static int __Pyx_raise_neg_overflow___Pyx_PyLong_As_int(void) { + const char* type_name = "int"; + PyErr_Format(PyExc_OverflowError, + "can't convert negative value to %.200s", type_name); + return (int) -1; +} +static int __Pyx_raise_overflow___Pyx_PyLong_As_int(void) { + const char* type_name = "int"; + PyErr_Format(PyExc_OverflowError, + "value too large to convert to %.200s", type_name); + return (int) -1; +} +static CYTHON_INLINE int __Pyx_PyULong___Pyx_PyLong_As_int(PyObject *x) { + const int is_unsigned = 1; +#if CYTHON_USE_PYLONG_INTERNALS + { + const digit* digits = __Pyx_PyLong_Digits(x); + const Py_ssize_t size = __Pyx_PyLong_DigitCount(x); + if (size == 2 && (8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } else + if (size == 3 && (8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } else + if (size == 4 && (8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } else + {} + } +#elif CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + return __Pyx_LargePyLong___Pyx_PyLong_As_int(x); +raise_neg_overflow: + return __Pyx_raise_neg_overflow___Pyx_PyLong_As_int(); +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_int(); +} +static CYTHON_INLINE int __Pyx_PySLong___Pyx_PyLong_As_int(PyObject *x) { + const int is_unsigned = 0; +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsNeg(x)) { + const Py_ssize_t size = __Pyx_PyLong_DigitCount(x); + const digit* digits = __Pyx_PyLong_Digits(x); + if (size == 2 && (8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + long ival = - (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + __PYX_VERIFY_RETURN_INT(int, long, ival) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((int) -1) * (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } else + if (size == 3 && (8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + long ival = - (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + __PYX_VERIFY_RETURN_INT(int, long, ival) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((int) -1) * (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } else + if (size == 4 && (8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 4 * PyLong_SHIFT)) { + long ival = - (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + __PYX_VERIFY_RETURN_INT(int, long, ival) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((int) -1) * (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } else + {} + } else { + const Py_ssize_t size = __Pyx_PyLong_DigitCount(x); + const digit* digits = __Pyx_PyLong_Digits(x); + if (size == 2 && (8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } else + if (size == 3 && (8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } else + if (size == 4 && (8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } else + {} + } +#endif + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + if ((sizeof(int) <= sizeof(int)) && (sizeof(int) < sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, int, PyLong_AsInt(x)) + } else + #endif + if ((sizeof(int) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) + } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + return __Pyx_LargePyLong___Pyx_PyLong_As_int(x); +raise_neg_overflow: + return __Pyx_raise_neg_overflow___Pyx_PyLong_As_int(); +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_int(); +} +static int __Pyx_LargePyLong___Pyx_PyLong_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + int val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); + if ((0)) goto raise_overflow; +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int) -1; + } else { + stepval = v; + } + v = NULL; + val = (int) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; +done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int) -1; + return val; +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_int(); +} +static CYTHON_INLINE int __Pyx_PyLong___Pyx_PyLong_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + #if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else + #endif + { + return __Pyx_PyULong___Pyx_PyLong_As_int(x); + } + } else { + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else + #endif + { + return __Pyx_PySLong___Pyx_PyLong_As_int(x); + } + } +#if CYTHON_USE_PYLONG_INTERNALS +raise_neg_overflow: + return __Pyx_raise_neg_overflow___Pyx_PyLong_As_int(); +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_int(); +#endif +} +static int __Pyx_NonPyLong___Pyx_PyLong_As_int(PyObject *x) { + int val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int) -1; + val = __Pyx_PyLong_As_int(tmp); + Py_DECREF(tmp); + return val; +} +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *x) { + if (likely(PyLong_Check(x))) { + return __Pyx_PyLong___Pyx_PyLong_As_int(x); + } else { + return __Pyx_NonPyLong___Pyx_PyLong_As_int(x); + } +} + +/* PyObjectVectorcallKwds (used by PyObjectVectorcallMethodKwds) */ +#if CYTHON_VECTORCALL +CYTHON_UNUSED static int __Pyx_CheckVectorcallKwarg(PyObject *kwnames, Py_ssize_t i) { + PyObject *key = __Pyx_PyTuple_GET_ITEM(kwnames, i); +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!key)) return -1; +#endif + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return 0; +} +#else +CYTHON_UNUSED static PyObject *__Pyx_MakeKwargDict(PyObject **keys, PyObject **values, Py_ssize_t n) { + PyObject *out = PyDict_New(); + if (unlikely(!out)) return NULL; + for (Py_ssize_t i=0; i<n; ++i) { + if (unlikely(PyDict_SetItem(out, keys[i], values[i]) < 0)) { + Py_DECREF(out); + return NULL; + } + } + return out; +} +CYTHON_UNUSED static int __Pyx_CheckVectorcallKwarg(PyObject **kwnames, Py_ssize_t i) { + PyObject *key = kwnames[i]; + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return 0; +} +#endif + +/* PyObjectVectorcallMethodKwds (used by CIntToPy) */ +#if !CYTHON_VECTORCALL +static PyObject *__Pyx_Object_VectorcallMethodKwds(PyObject *name, PyObject *const *args, size_t nargsf, PyObject *kwnames) { + PyObject *result; + PyObject *obj = PyObject_GetAttr(args[0], name); + if (unlikely(!obj)) + return NULL; + result = __Pyx_Object_VectorcallKwds(obj, args+1, nargsf-1, kwnames); + Py_DECREF(obj); + return result; +} +#endif + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL, *from_bytes_str = NULL;; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int)); + if (!py_bytes) goto limited_bad; + from_bytes_str = PyUnicode_FromStringAndSize("from_bytes", 10); + if (!from_bytes_str) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[] = { (PyObject*)&PyLong_Type, py_bytes, order_str, Py_True }; + if (!is_unsigned) { + PyObject *signed_str = PyUnicode_FromStringAndSize("signed", 6); + if (!signed_str) goto limited_bad; +#if CYTHON_VECTORCALL + kwds = PyTuple_Pack(1, signed_str); +#else + { + PyObject *keys[] = {signed_str}; + PyObject *values[] = {Py_True}; + kwds = __Pyx_MakeKwargDict(keys, values, 1); + } +#endif + Py_DECREF(signed_str); + if (unlikely(!kwds)) goto limited_bad; + } + result = __Pyx_Object_VectorcallMethodKwds(from_bytes_str, args, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes_str); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL, *from_bytes_str = NULL;; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); + if (!py_bytes) goto limited_bad; + from_bytes_str = PyUnicode_FromStringAndSize("from_bytes", 10); + if (!from_bytes_str) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[] = { (PyObject*)&PyLong_Type, py_bytes, order_str, Py_True }; + if (!is_unsigned) { + PyObject *signed_str = PyUnicode_FromStringAndSize("signed", 6); + if (!signed_str) goto limited_bad; +#if CYTHON_VECTORCALL + kwds = PyTuple_Pack(1, signed_str); +#else + { + PyObject *keys[] = {signed_str}; + PyObject *values[] = {Py_True}; + kwds = __Pyx_MakeKwargDict(keys, values, 1); + } +#endif + Py_DECREF(signed_str); + if (unlikely(!kwds)) goto limited_bad; + } + result = __Pyx_Object_VectorcallMethodKwds(from_bytes_str, args, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes_str); + return result; +#endif + } +} + +/* CIntFromPy */ +static long __Pyx_LargePyLong___Pyx_PyLong_As_long(PyObject *x); +static long __Pyx_raise_neg_overflow___Pyx_PyLong_As_long(void) { + const char* type_name = "long"; + PyErr_Format(PyExc_OverflowError, + "can't convert negative value to %.200s", type_name); + return (long) -1; +} +static long __Pyx_raise_overflow___Pyx_PyLong_As_long(void) { + const char* type_name = "long"; + PyErr_Format(PyExc_OverflowError, + "value too large to convert to %.200s", type_name); + return (long) -1; +} +static CYTHON_INLINE long __Pyx_PyULong___Pyx_PyLong_As_long(PyObject *x) { + const int is_unsigned = 1; +#if CYTHON_USE_PYLONG_INTERNALS + { + const digit* digits = __Pyx_PyLong_Digits(x); + const Py_ssize_t size = __Pyx_PyLong_DigitCount(x); + if (size == 2 && (8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } else + if (size == 3 && (8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } else + if (size == 4 && (8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } else + {} + } +#elif CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(long) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) + } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) + } + return __Pyx_LargePyLong___Pyx_PyLong_As_long(x); +raise_neg_overflow: + return __Pyx_raise_neg_overflow___Pyx_PyLong_As_long(); +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_long(); +} +static CYTHON_INLINE long __Pyx_PySLong___Pyx_PyLong_As_long(PyObject *x) { + const int is_unsigned = 0; +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsNeg(x)) { + const Py_ssize_t size = __Pyx_PyLong_DigitCount(x); + const digit* digits = __Pyx_PyLong_Digits(x); + if (size == 2 && (8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + long ival = - (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + __PYX_VERIFY_RETURN_INT(long, long, ival) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((long) -1) * (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } else + if (size == 3 && (8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + long ival = - (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + __PYX_VERIFY_RETURN_INT(long, long, ival) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((long) -1) * (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } else + if (size == 4 && (8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 4 * PyLong_SHIFT)) { + long ival = - (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + __PYX_VERIFY_RETURN_INT(long, long, ival) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((long) -1) * (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } else + {} + } else { + const Py_ssize_t size = __Pyx_PyLong_DigitCount(x); + const digit* digits = __Pyx_PyLong_Digits(x); + if (size == 2 && (8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } else + if (size == 3 && (8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } else + if (size == 4 && (8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } else + {} + } +#endif + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + if ((sizeof(long) <= sizeof(int)) && (sizeof(int) < sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, int, PyLong_AsInt(x)) + } else + #endif + if ((sizeof(long) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) + } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) + } + return __Pyx_LargePyLong___Pyx_PyLong_As_long(x); +raise_neg_overflow: + return __Pyx_raise_neg_overflow___Pyx_PyLong_As_long(); +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_long(); +} +static long __Pyx_LargePyLong___Pyx_PyLong_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + long val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); + if ((0)) goto raise_overflow; +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (long) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (long) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (long) -1; + } else { + stepval = v; + } + v = NULL; + val = (long) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((long) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((long) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; +done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (long) -1; + return val; +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_long(); +} +static CYTHON_INLINE long __Pyx_PyLong___Pyx_PyLong_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + #if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else + #endif + { + return __Pyx_PyULong___Pyx_PyLong_As_long(x); + } + } else { + #if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else + #endif + { + return __Pyx_PySLong___Pyx_PyLong_As_long(x); + } + } +#if CYTHON_USE_PYLONG_INTERNALS +raise_neg_overflow: + return __Pyx_raise_neg_overflow___Pyx_PyLong_As_long(); +raise_overflow: + return __Pyx_raise_overflow___Pyx_PyLong_As_long(); +#endif +} +static long __Pyx_NonPyLong___Pyx_PyLong_As_long(PyObject *x) { + long val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (long) -1; + val = __Pyx_PyLong_As_long(tmp); + Py_DECREF(tmp); + return val; +} +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *x) { + if (likely(PyLong_Check(x))) { + return __Pyx_PyLong___Pyx_PyLong_As_long(x); + } else { + return __Pyx_NonPyLong___Pyx_PyLong_As_long(x); + } +} + +/* GetRuntimeVersion */ +#if __PYX_LIMITED_VERSION_HEX < 0x030b0000 +void __Pyx_init_runtime_version(void) { + if (__Pyx_cached_runtime_version == 0) { + const char* rt_version = Py_GetVersion(); + unsigned long version = 0; + unsigned long factor = 0x01000000UL; + unsigned int digit = 0; + int i = 0; + while (factor) { + while ('0' <= rt_version[i] && rt_version[i] <= '9') { + digit = digit * 10 + (unsigned int) (rt_version[i] - '0'); + ++i; + } + version += factor * digit; + if (rt_version[i] != '.') + break; + digit = 0; + factor >>= 8; + ++i; + } + __Pyx_cached_runtime_version = version; + } +} +#endif +static unsigned long __Pyx_get_runtime_version(void) { +#if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + return Py_Version & ~0xFFUL; +#else + return __Pyx_cached_runtime_version; +#endif +} + +/* GetTopmostException (used by SaveResetException) */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * +__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) +{ + _PyErr_StackItem *exc_info = tstate->exc_info; + while ((exc_info->exc_value == NULL || exc_info->exc_value == Py_None) && + exc_info->previous_item != NULL) + { + exc_info = exc_info->previous_item; + } + return exc_info; +} +#endif + +/* SaveResetException (used by CoroutineBase) */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + PyObject *exc_value = exc_info->exc_value; + if (exc_value == NULL || exc_value == Py_None) { + *value = NULL; + *type = NULL; + *tb = NULL; + } else { + *value = exc_value; + Py_INCREF(*value); + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + *tb = PyException_GetTraceback(exc_value); + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + *type = exc_info->exc_type; + *value = exc_info->exc_value; + *tb = exc_info->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #else + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #endif +} +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + PyObject *tmp_value = exc_info->exc_value; + exc_info->exc_value = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); + #else + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = type; + exc_info->exc_value = value; + exc_info->exc_traceback = tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); + #endif +} +#endif + +/* SwapException (used by CoroutineBase) */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_value = exc_info->exc_value; + exc_info->exc_value = *value; + if (tmp_value == NULL || tmp_value == Py_None) { + Py_XDECREF(tmp_value); + tmp_value = NULL; + tmp_type = NULL; + tmp_tb = NULL; + } else { + tmp_type = (PyObject*) Py_TYPE(tmp_value); + Py_INCREF(tmp_type); + #if CYTHON_COMPILING_IN_CPYTHON + tmp_tb = ((PyBaseExceptionObject*) tmp_value)->traceback; + Py_XINCREF(tmp_tb); + #else + tmp_tb = PyException_GetTraceback(tmp_value); + #endif + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = *type; + exc_info->exc_value = *value; + exc_info->exc_traceback = *tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; + #endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#endif + +/* PyObjectCallMethod1 (used by CoroutineBase) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { +#if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || !CYTHON_COMPILING_IN_LIMITED_API) + PyObject *args[2] = {obj, arg}; + return PyObject_VectorcallMethod(method_name, args, 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#elif CYTHON_COMPILING_IN_LIMITED_API + return PyObject_CallMethodObjArgs(obj, method_name, arg, NULL); +#else + return PyObject_CallMethodOneArg(obj, method_name, arg); +#endif +} + +/* PyObjectCallNoArg (used by CoroutineBase) */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { + PyObject *arg[2] = {NULL, NULL}; + return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* ReturnWithStopIteration (used by CoroutineBase) */ +static void __Pyx__ReturnWithStopIteration(PyObject* value, int async); +static CYTHON_INLINE void __Pyx_ReturnWithStopIteration(PyObject* value, int async, int iternext) { + if (value == Py_None) { + if (async || !iternext) + PyErr_SetNone(async ? PyExc_StopAsyncIteration : PyExc_StopIteration); + return; + } + __Pyx__ReturnWithStopIteration(value, async); +} +static void __Pyx__ReturnWithStopIteration(PyObject* value, int async) { +#if CYTHON_COMPILING_IN_CPYTHON + __Pyx_PyThreadState_declare +#endif + PyObject *exc; + PyObject *exc_type = async ? PyExc_StopAsyncIteration : PyExc_StopIteration; +#if CYTHON_COMPILING_IN_CPYTHON + if ((PY_VERSION_HEX >= (0x030C00A6)) || unlikely(PyTuple_Check(value) || PyExceptionInstance_Check(value))) { + if (PY_VERSION_HEX >= (0x030e00A1)) { + exc = __Pyx_PyObject_CallOneArg(exc_type, value); + } else { + PyObject *args_tuple = PyTuple_New(1); + if (unlikely(!args_tuple)) return; + Py_INCREF(value); + PyTuple_SET_ITEM(args_tuple, 0, value); + exc = PyObject_Call(exc_type, args_tuple, NULL); + Py_DECREF(args_tuple); + } + if (unlikely(!exc)) return; + } else { + Py_INCREF(value); + exc = value; + } + #if CYTHON_FAST_THREAD_STATE + __Pyx_PyThreadState_assign + #if CYTHON_USE_EXC_INFO_STACK + if (!__pyx_tstate->exc_info->exc_value) + #else + if (!__pyx_tstate->exc_type) + #endif + { + Py_INCREF(exc_type); + __Pyx_ErrRestore(exc_type, exc, NULL); + return; + } + #endif +#else + exc = __Pyx_PyObject_CallOneArg(exc_type, value); + if (unlikely(!exc)) return; +#endif + PyErr_SetObject(exc_type, exc); + Py_DECREF(exc); +} + +/* CoroutineBase (used by Generator) */ +#if !CYTHON_COMPILING_IN_LIMITED_API +#include <frameobject.h> +#if PY_VERSION_HEX >= 0x030b00a6 && !defined(PYPY_VERSION) + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#endif // CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE void +__Pyx_Coroutine_Undelegate(__pyx_CoroutineObject *gen) { +#if CYTHON_USE_AM_SEND + gen->yieldfrom_am_send = NULL; +#endif + Py_CLEAR(gen->yieldfrom); +} +static int __Pyx_PyGen__FetchStopIterationValue(PyThreadState *__pyx_tstate, PyObject **pvalue) { + PyObject *et, *ev, *tb; + PyObject *value = NULL; + CYTHON_UNUSED_VAR(__pyx_tstate); + __Pyx_ErrFetch(&et, &ev, &tb); + if (!et) { + Py_XDECREF(tb); + Py_XDECREF(ev); + Py_INCREF(Py_None); + *pvalue = Py_None; + return 0; + } + if (likely(et == PyExc_StopIteration)) { + if (!ev) { + Py_INCREF(Py_None); + value = Py_None; + } + else if (likely(Py_IS_TYPE(ev, (PyTypeObject*)PyExc_StopIteration))) { + #if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL + value = PyObject_GetAttr(ev, __pyx_mstate_global->__pyx_n_u_value); + if (unlikely(!value)) goto limited_api_failure; + #else + value = ((PyStopIterationObject *)ev)->value; + Py_INCREF(value); + #endif + Py_DECREF(ev); + } + else if (unlikely(PyTuple_Check(ev))) { + Py_ssize_t tuple_size = __Pyx_PyTuple_GET_SIZE(ev); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(tuple_size < 0)) { + Py_XDECREF(tb); + Py_DECREF(ev); + Py_DECREF(et); + return -1; + } + #endif + if (tuple_size >= 1) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + value = PyTuple_GET_ITEM(ev, 0); + Py_INCREF(value); +#elif CYTHON_ASSUME_SAFE_MACROS + value = PySequence_ITEM(ev, 0); +#else + value = PySequence_GetItem(ev, 0); + if (!value) goto limited_api_failure; +#endif + } else { + Py_INCREF(Py_None); + value = Py_None; + } + Py_DECREF(ev); + } + else if (!__Pyx_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration)) { + value = ev; + } + if (likely(value)) { + Py_XDECREF(tb); + Py_DECREF(et); + *pvalue = value; + return 0; + } + } else if (!__Pyx_PyErr_GivenExceptionMatches(et, PyExc_StopIteration)) { + __Pyx_ErrRestore(et, ev, tb); + return -1; + } + PyErr_NormalizeException(&et, &ev, &tb); + if (unlikely(!PyObject_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration))) { + __Pyx_ErrRestore(et, ev, tb); + return -1; + } + Py_XDECREF(tb); + Py_DECREF(et); +#if CYTHON_COMPILING_IN_LIMITED_API + value = PyObject_GetAttr(ev, __pyx_mstate_global->__pyx_n_u_value); +#else + value = ((PyStopIterationObject *)ev)->value; + Py_INCREF(value); +#endif + Py_DECREF(ev); +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!value)) return -1; +#endif + *pvalue = value; + return 0; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL || !CYTHON_ASSUME_SAFE_MACROS + limited_api_failure: + Py_XDECREF(et); + Py_XDECREF(tb); + Py_XDECREF(ev); + return -1; +#endif +} +static CYTHON_INLINE +__Pyx_PySendResult __Pyx_Coroutine_status_from_result(PyObject **retval) { + if (*retval) { + return PYGEN_NEXT; + } else if (likely(__Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, retval) == 0)) { + return PYGEN_RETURN; + } else { + return PYGEN_ERROR; + } +} +static CYTHON_INLINE +void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *exc_state) { +#if PY_VERSION_HEX >= 0x030B00a4 + Py_CLEAR(exc_state->exc_value); +#else + PyObject *t, *v, *tb; + t = exc_state->exc_type; + v = exc_state->exc_value; + tb = exc_state->exc_traceback; + exc_state->exc_type = NULL; + exc_state->exc_value = NULL; + exc_state->exc_traceback = NULL; + Py_XDECREF(t); + Py_XDECREF(v); + Py_XDECREF(tb); +#endif +} +#define __Pyx_Coroutine_AlreadyRunningError(gen) (__Pyx__Coroutine_AlreadyRunningError(gen), (PyObject*)NULL) +static void __Pyx__Coroutine_AlreadyRunningError(__pyx_CoroutineObject *gen) { + const char *msg; + CYTHON_MAYBE_UNUSED_VAR(gen); + if ((0)) { + #ifdef __Pyx_Coroutine_USED + } else if (__Pyx_Coroutine_Check((PyObject*)gen)) { + msg = "coroutine already executing"; + #endif + #ifdef __Pyx_AsyncGen_USED + } else if (__Pyx_AsyncGen_CheckExact((PyObject*)gen)) { + msg = "async generator already executing"; + #endif + } else { + msg = "generator already executing"; + } + PyErr_SetString(PyExc_ValueError, msg); +} +static void __Pyx_Coroutine_AlreadyTerminatedError(PyObject *gen, PyObject *value, int closing) { + CYTHON_MAYBE_UNUSED_VAR(gen); + CYTHON_MAYBE_UNUSED_VAR(closing); + #ifdef __Pyx_Coroutine_USED + if (!closing && __Pyx_Coroutine_Check(gen)) { + PyErr_SetString(PyExc_RuntimeError, "cannot reuse already awaited coroutine"); + } else + #endif + if (value) { + #ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(gen)) + PyErr_SetNone(PyExc_StopAsyncIteration); + else + #endif + PyErr_SetNone(PyExc_StopIteration); + } +} +static +__Pyx_PySendResult __Pyx_Coroutine_SendEx(__pyx_CoroutineObject *self, PyObject *value, PyObject **result, int closing) { + __Pyx_PyThreadState_declare + PyThreadState *tstate; + __Pyx_ExcInfoStruct *exc_state; + PyObject *retval; + assert(__Pyx_Coroutine_get_is_running(self)); // Callers should ensure is_running + if (unlikely(self->resume_label == -1)) { + __Pyx_Coroutine_AlreadyTerminatedError((PyObject*)self, value, closing); + return PYGEN_ERROR; + } +#if CYTHON_FAST_THREAD_STATE + __Pyx_PyThreadState_assign + tstate = __pyx_tstate; +#else + tstate = __Pyx_PyThreadState_Current; +#endif + exc_state = &self->gi_exc_state; + if (exc_state->exc_value) { + #if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + #else + PyObject *exc_tb; + #if PY_VERSION_HEX >= 0x030B00a4 && !CYTHON_COMPILING_IN_CPYTHON + exc_tb = PyException_GetTraceback(exc_state->exc_value); + #elif PY_VERSION_HEX >= 0x030B00a4 + exc_tb = ((PyBaseExceptionObject*) exc_state->exc_value)->traceback; + #else + exc_tb = exc_state->exc_traceback; + #endif + if (exc_tb) { + PyTracebackObject *tb = (PyTracebackObject *) exc_tb; + PyFrameObject *f = tb->tb_frame; + assert(f->f_back == NULL); + #if PY_VERSION_HEX >= 0x030B00A1 + f->f_back = PyThreadState_GetFrame(tstate); + #else + Py_XINCREF(tstate->frame); + f->f_back = tstate->frame; + #endif + #if PY_VERSION_HEX >= 0x030B00a4 && !CYTHON_COMPILING_IN_CPYTHON + Py_DECREF(exc_tb); + #endif + } + #endif + } +#if CYTHON_USE_EXC_INFO_STACK + exc_state->previous_item = tstate->exc_info; + tstate->exc_info = exc_state; +#else + if (exc_state->exc_type) { + __Pyx_ExceptionSwap(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); + } else { + __Pyx_Coroutine_ExceptionClear(exc_state); + __Pyx_ExceptionSave(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); + } +#endif + retval = self->body(self, tstate, value); +#if CYTHON_USE_EXC_INFO_STACK + exc_state = &self->gi_exc_state; + tstate->exc_info = exc_state->previous_item; + exc_state->previous_item = NULL; + __Pyx_Coroutine_ResetFrameBackpointer(exc_state); +#endif + *result = retval; + if (self->resume_label == -1) { + return likely(retval) ? PYGEN_RETURN : PYGEN_ERROR; + } + return PYGEN_NEXT; +} +static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API + CYTHON_UNUSED_VAR(exc_state); +#else + PyObject *exc_tb; + #if PY_VERSION_HEX >= 0x030B00a4 + if (!exc_state->exc_value) return; + exc_tb = PyException_GetTraceback(exc_state->exc_value); + #else + exc_tb = exc_state->exc_traceback; + #endif + if (likely(exc_tb)) { + PyTracebackObject *tb = (PyTracebackObject *) exc_tb; + PyFrameObject *f = tb->tb_frame; + Py_CLEAR(f->f_back); + #if PY_VERSION_HEX >= 0x030B00a4 + Py_DECREF(exc_tb); + #endif + } +#endif +} +#define __Pyx_Coroutine_MethodReturnFromResult(gen, result, retval, iternext)\ + ((result) == PYGEN_NEXT ? (retval) : __Pyx__Coroutine_MethodReturnFromResult(gen, result, retval, iternext)) +static PyObject * +__Pyx__Coroutine_MethodReturnFromResult(PyObject* gen, __Pyx_PySendResult result, PyObject *retval, int iternext) { + CYTHON_MAYBE_UNUSED_VAR(gen); + if (likely(result == PYGEN_RETURN)) { + int is_async = 0; + #ifdef __Pyx_AsyncGen_USED + is_async = __Pyx_AsyncGen_CheckExact(gen); + #endif + __Pyx_ReturnWithStopIteration(retval, is_async, iternext); + Py_XDECREF(retval); + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE +PyObject *__Pyx_PyGen_Send(PyGenObject *gen, PyObject *arg) { +#if PY_VERSION_HEX <= 0x030A00A1 + return _PyGen_Send(gen, arg); +#else + PyObject *result; + if (PyIter_Send((PyObject*)gen, arg ? arg : Py_None, &result) == PYGEN_RETURN) { + if (PyAsyncGen_CheckExact(gen)) { + assert(result == Py_None); + PyErr_SetNone(PyExc_StopAsyncIteration); + } + else if (result == Py_None) { + PyErr_SetNone(PyExc_StopIteration); + } + else { +#if PY_VERSION_HEX < 0x030d00A1 + _PyGen_SetStopIterationValue(result); +#else + if (!PyTuple_Check(result) && !PyExceptionInstance_Check(result)) { + PyErr_SetObject(PyExc_StopIteration, result); + } else { + PyObject *exc = __Pyx_PyObject_CallOneArg(PyExc_StopIteration, result); + if (likely(exc != NULL)) { + PyErr_SetObject(PyExc_StopIteration, exc); + Py_DECREF(exc); + } + } +#endif + } + Py_DECREF(result); + result = NULL; + } + return result; +#endif +} +#endif +static CYTHON_INLINE __Pyx_PySendResult +__Pyx_Coroutine_FinishDelegation(__pyx_CoroutineObject *gen, PyObject** retval) { + __Pyx_PySendResult result; + PyObject *val = NULL; + assert(__Pyx_Coroutine_get_is_running(gen)); + __Pyx_Coroutine_Undelegate(gen); + __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, &val); + result = __Pyx_Coroutine_SendEx(gen, val, retval, 0); + Py_XDECREF(val); + return result; +} +#if CYTHON_USE_AM_SEND +static __Pyx_PySendResult +__Pyx_Coroutine_SendToDelegate(__pyx_CoroutineObject *gen, __Pyx_pyiter_sendfunc gen_am_send, PyObject *value, PyObject **retval) { + PyObject *ret = NULL; + __Pyx_PySendResult delegate_result, result; + assert(__Pyx_Coroutine_get_is_running(gen)); + delegate_result = gen_am_send(gen->yieldfrom, value, &ret); + if (delegate_result == PYGEN_NEXT) { + assert (ret != NULL); + *retval = ret; + return PYGEN_NEXT; + } + assert (delegate_result != PYGEN_ERROR || ret == NULL); + __Pyx_Coroutine_Undelegate(gen); + result = __Pyx_Coroutine_SendEx(gen, ret, retval, 0); + Py_XDECREF(ret); + return result; +} +#endif +static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value) { + PyObject *retval = NULL; + __Pyx_PySendResult result = __Pyx_Coroutine_AmSend(self, value, &retval); + return __Pyx_Coroutine_MethodReturnFromResult(self, result, retval, 0); +} +static __Pyx_PySendResult +__Pyx_Coroutine_AmSend(PyObject *self, PyObject *value, PyObject **retval) { + __Pyx_PySendResult result; + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; + if (unlikely(__Pyx_Coroutine_test_and_set_is_running(gen))) { + *retval = __Pyx_Coroutine_AlreadyRunningError(gen); + return PYGEN_ERROR; + } + #if CYTHON_USE_AM_SEND + if (gen->yieldfrom_am_send) { + result = __Pyx_Coroutine_SendToDelegate(gen, gen->yieldfrom_am_send, value, retval); + } else + #endif + if (gen->yieldfrom) { + PyObject *yf = gen->yieldfrom; + PyObject *ret; + #if !CYTHON_USE_AM_SEND + #ifdef __Pyx_Generator_USED + if (__Pyx_Generator_CheckExact(yf)) { + ret = __Pyx_Coroutine_Send(yf, value); + } else + #endif + #ifdef __Pyx_Coroutine_USED + if (__Pyx_Coroutine_Check(yf)) { + ret = __Pyx_Coroutine_Send(yf, value); + } else + #endif + #ifdef __Pyx_AsyncGen_USED + if (__pyx_PyAsyncGenASend_CheckExact(yf)) { + ret = __Pyx_async_gen_asend_send(yf, value); + } else + #endif + #if CYTHON_COMPILING_IN_CPYTHON + if (PyGen_CheckExact(yf)) { + ret = __Pyx_PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); + } else + if (PyCoro_CheckExact(yf)) { + ret = __Pyx_PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); + } else + #endif + #endif + { + if (value == Py_None && PyIter_Check(yf)) + ret = __Pyx_PyIter_Next_Plain(yf); + else + ret = __Pyx_PyObject_CallMethod1(yf, __pyx_mstate_global->__pyx_n_u_send, value); + } + if (likely(ret)) { + __Pyx_Coroutine_unset_is_running(gen); + *retval = ret; + return PYGEN_NEXT; + } + result = __Pyx_Coroutine_FinishDelegation(gen, retval); + } else { + result = __Pyx_Coroutine_SendEx(gen, value, retval, 0); + } + __Pyx_Coroutine_unset_is_running(gen); + return result; +} +static int __Pyx_Coroutine_CloseIter(__pyx_CoroutineObject *gen, PyObject *yf) { + __Pyx_PySendResult result; + PyObject *retval = NULL; + CYTHON_UNUSED_VAR(gen); + assert(__Pyx_Coroutine_get_is_running(gen)); + #ifdef __Pyx_Generator_USED + if (__Pyx_Generator_CheckExact(yf)) { + result = __Pyx_Coroutine_Close(yf, &retval); + } else + #endif + #ifdef __Pyx_Coroutine_USED + if (__Pyx_Coroutine_Check(yf)) { + result = __Pyx_Coroutine_Close(yf, &retval); + } else + if (__Pyx_CoroutineAwait_CheckExact(yf)) { + result = __Pyx_CoroutineAwait_Close((__pyx_CoroutineAwaitObject*)yf); + } else + #endif + #ifdef __Pyx_AsyncGen_USED + if (__pyx_PyAsyncGenASend_CheckExact(yf)) { + retval = __Pyx_async_gen_asend_close(yf, NULL); + result = PYGEN_RETURN; + } else + if (__pyx_PyAsyncGenAThrow_CheckExact(yf)) { + retval = __Pyx_async_gen_athrow_close(yf, NULL); + result = PYGEN_RETURN; + } else + #endif + { + PyObject *meth; + result = PYGEN_RETURN; + meth = __Pyx_PyObject_GetAttrStrNoError(yf, __pyx_mstate_global->__pyx_n_u_close); + if (unlikely(!meth)) { + if (unlikely(PyErr_Occurred())) { + PyErr_WriteUnraisable(yf); + } + } else { + retval = __Pyx_PyObject_CallNoArg(meth); + Py_DECREF(meth); + if (unlikely(!retval)) { + result = PYGEN_ERROR; + } + } + } + Py_XDECREF(retval); + return result == PYGEN_ERROR ? -1 : 0; +} +static PyObject *__Pyx_Generator_Next(PyObject *self) { + __Pyx_PySendResult result; + PyObject *retval = NULL; + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; + if (unlikely(__Pyx_Coroutine_test_and_set_is_running(gen))) { + return __Pyx_Coroutine_AlreadyRunningError(gen); + } + #if CYTHON_USE_AM_SEND + if (gen->yieldfrom_am_send) { + result = __Pyx_Coroutine_SendToDelegate(gen, gen->yieldfrom_am_send, Py_None, &retval); + } else + #endif + if (gen->yieldfrom) { + PyObject *yf = gen->yieldfrom; + PyObject *ret; + #ifdef __Pyx_Generator_USED + if (__Pyx_Generator_CheckExact(yf)) { + ret = __Pyx_Generator_Next(yf); + } else + #endif + #ifdef __Pyx_Coroutine_USED + if (__Pyx_Coroutine_CheckExact(yf)) { + ret = __Pyx_Coroutine_Send(yf, Py_None); + } else + #endif + #if CYTHON_COMPILING_IN_CPYTHON && (PY_VERSION_HEX < 0x030A00A3 || !CYTHON_USE_AM_SEND) + if (PyGen_CheckExact(yf)) { + ret = __Pyx_PyGen_Send((PyGenObject*)yf, NULL); + } else + #endif + ret = __Pyx_PyIter_Next_Plain(yf); + if (likely(ret)) { + __Pyx_Coroutine_unset_is_running(gen); + return ret; + } + result = __Pyx_Coroutine_FinishDelegation(gen, &retval); + } else { + result = __Pyx_Coroutine_SendEx(gen, Py_None, &retval, 0); + } + __Pyx_Coroutine_unset_is_running(gen); + return __Pyx_Coroutine_MethodReturnFromResult(self, result, retval, 1); +} +static PyObject *__Pyx_Coroutine_Close_Method(PyObject *self, PyObject *arg) { + PyObject *retval = NULL; + __Pyx_PySendResult result; + CYTHON_UNUSED_VAR(arg); + result = __Pyx_Coroutine_Close(self, &retval); + if (unlikely(result == PYGEN_ERROR)) + return NULL; + Py_XDECREF(retval); + Py_RETURN_NONE; +} +static __Pyx_PySendResult +__Pyx_Coroutine_Close(PyObject *self, PyObject **retval) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + __Pyx_PySendResult result; + PyObject *yf; + int err = 0; + if (unlikely(__Pyx_Coroutine_test_and_set_is_running(gen))) { + *retval = __Pyx_Coroutine_AlreadyRunningError(gen); + return PYGEN_ERROR; + } + yf = gen->yieldfrom; + if (yf) { + Py_INCREF(yf); + err = __Pyx_Coroutine_CloseIter(gen, yf); + __Pyx_Coroutine_Undelegate(gen); + Py_DECREF(yf); + } + if (err == 0) + PyErr_SetNone(PyExc_GeneratorExit); + result = __Pyx_Coroutine_SendEx(gen, NULL, retval, 1); + if (result == PYGEN_ERROR) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_Coroutine_unset_is_running(gen); + if (!__Pyx_PyErr_Occurred()) { + return PYGEN_RETURN; + } else if (likely(__Pyx_PyErr_ExceptionMatches2(PyExc_GeneratorExit, PyExc_StopIteration))) { + __Pyx_PyErr_Clear(); + return PYGEN_RETURN; + } + return PYGEN_ERROR; + } else if (likely(result == PYGEN_RETURN && *retval == Py_None)) { + __Pyx_Coroutine_unset_is_running(gen); + return PYGEN_RETURN; + } else { + const char *msg; + Py_DECREF(*retval); + *retval = NULL; + if ((0)) { + #ifdef __Pyx_Coroutine_USED + } else if (__Pyx_Coroutine_Check(self)) { + msg = "coroutine ignored GeneratorExit"; + #endif + #ifdef __Pyx_AsyncGen_USED + } else if (__Pyx_AsyncGen_CheckExact(self)) { + msg = "async generator ignored GeneratorExit"; + #endif + } else { + msg = "generator ignored GeneratorExit"; + } + PyErr_SetString(PyExc_RuntimeError, msg); + __Pyx_Coroutine_unset_is_running(gen); + return PYGEN_ERROR; + } +} +static PyObject *__Pyx__Coroutine_Throw(PyObject *self, PyObject *typ, PyObject *val, PyObject *tb, + PyObject *args, int close_on_genexit) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + PyObject *yf; + if (unlikely(__Pyx_Coroutine_test_and_set_is_running(gen))) + return __Pyx_Coroutine_AlreadyRunningError(gen); + yf = gen->yieldfrom; + if (yf) { + __Pyx_PySendResult result; + PyObject *ret; + Py_INCREF(yf); + if (__Pyx_PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) && close_on_genexit) { + int err = __Pyx_Coroutine_CloseIter(gen, yf); + Py_DECREF(yf); + __Pyx_Coroutine_Undelegate(gen); + if (err < 0) + goto propagate_exception; + goto throw_here; + } + if (0 + #ifdef __Pyx_Generator_USED + || __Pyx_Generator_CheckExact(yf) + #endif + #ifdef __Pyx_Coroutine_USED + || __Pyx_Coroutine_Check(yf) + #endif + ) { + ret = __Pyx__Coroutine_Throw(yf, typ, val, tb, args, close_on_genexit); + #ifdef __Pyx_Coroutine_USED + } else if (__Pyx_CoroutineAwait_CheckExact(yf)) { + ret = __Pyx__Coroutine_Throw(((__pyx_CoroutineAwaitObject*)yf)->coroutine, typ, val, tb, args, close_on_genexit); + #endif + } else { + PyObject *meth = __Pyx_PyObject_GetAttrStrNoError(yf, __pyx_mstate_global->__pyx_n_u_throw); + if (unlikely(!meth)) { + Py_DECREF(yf); + if (unlikely(PyErr_Occurred())) { + __Pyx_Coroutine_unset_is_running(gen); + return NULL; + } + __Pyx_Coroutine_Undelegate(gen); + goto throw_here; + } + if (args) { + ret = __Pyx_PyObject_Call(meth, args, NULL); + } else { + PyObject *cargs[4] = {NULL, typ, val, tb}; + size_t nargs = 1U + (val != NULL) + (tb != NULL); + ret = __Pyx_PyObject_FastCall(meth, cargs+1, nargs | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); + } + Py_DECREF(meth); + } + Py_DECREF(yf); + if (ret) { + __Pyx_Coroutine_unset_is_running(gen); + return ret; + } + result = __Pyx_Coroutine_FinishDelegation(gen, &ret); + __Pyx_Coroutine_unset_is_running(gen); + return __Pyx_Coroutine_MethodReturnFromResult(self, result, ret, 0); + } +throw_here: + __Pyx_Raise(typ, val, tb, NULL); +propagate_exception: + { + PyObject *retval = NULL; + __Pyx_PySendResult result = __Pyx_Coroutine_SendEx(gen, NULL, &retval, 0); + __Pyx_Coroutine_unset_is_running(gen); + return __Pyx_Coroutine_MethodReturnFromResult(self, result, retval, 0); + } +} +static PyObject *__Pyx_Coroutine_Throw(PyObject *self, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + PyObject *args +#else + PyObject *const *args, Py_ssize_t nargs +#endif +) { + PyObject *typ; + PyObject *val = NULL; + PyObject *tb = NULL; +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (unlikely(!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))) + return NULL; +#else + switch (nargs) { + case 3: + tb = args[2]; + CYTHON_FALLTHROUGH; + case 2: + val = args[1]; + CYTHON_FALLTHROUGH; + case 1: + typ = args[0]; + break; + default: + PyErr_SetString(PyExc_TypeError, "throw takes between 1 and 3 positional arguments"); + return NULL; + } +#endif + return __Pyx__Coroutine_Throw(self, typ, val, tb, +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + args, +#else + NULL, +#endif + 1); +} +static CYTHON_INLINE int __Pyx_Coroutine_traverse_excstate(__Pyx_ExcInfoStruct *exc_state, visitproc visit, void *arg) { +#if PY_VERSION_HEX >= 0x030B00a4 + Py_VISIT(exc_state->exc_value); +#else + Py_VISIT(exc_state->exc_type); + Py_VISIT(exc_state->exc_value); + Py_VISIT(exc_state->exc_traceback); +#endif + return 0; +} +static int __Pyx_Coroutine_traverse(__pyx_CoroutineObject *gen, visitproc visit, void *arg) { + { + int e = __Pyx_call_type_traverse((PyObject*)gen, 1, visit, arg); + if (e) return e; + } + Py_VISIT(gen->closure); + Py_VISIT(gen->classobj); + Py_VISIT(gen->yieldfrom); + return __Pyx_Coroutine_traverse_excstate(&gen->gi_exc_state, visit, arg); +} +static int __Pyx_Coroutine_clear(PyObject *self) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + Py_CLEAR(gen->closure); + Py_CLEAR(gen->classobj); + __Pyx_Coroutine_Undelegate(gen); + __Pyx_Coroutine_ExceptionClear(&gen->gi_exc_state); +#ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(self)) { + Py_CLEAR(((__pyx_PyAsyncGenObject*)gen)->ag_finalizer); + } +#endif + Py_CLEAR(gen->gi_code); + Py_CLEAR(gen->gi_frame); + Py_CLEAR(gen->gi_name); + Py_CLEAR(gen->gi_qualname); + Py_CLEAR(gen->gi_modulename); + return 0; +} +static void __Pyx_Coroutine_dealloc(PyObject *self) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + PyObject_GC_UnTrack(gen); + #if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + if (gen->gi_weakreflist != NULL) + #endif + PyObject_ClearWeakRefs(self); + if (gen->resume_label >= 0) { +#if CYTHON_USE_TP_FINALIZE + PyObject_GC_Track(self); + if (unlikely(PyObject_CallFinalizerFromDealloc(self))) + { + return; + } + PyObject_GC_UnTrack(self); +#endif + } +#ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(self)) { + /* We have to handle this case for asynchronous generators + right here, because this code has to be between UNTRACK + and GC_Del. */ + Py_CLEAR(((__pyx_PyAsyncGenObject*)self)->ag_finalizer); + } +#endif + __Pyx_Coroutine_clear(self); + __Pyx_PyHeapTypeObject_GC_Del(gen); +} +#if CYTHON_USE_TP_FINALIZE +static void __Pyx_Coroutine_del(PyObject *self) { + PyObject *error_type, *error_value, *error_traceback; + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + __Pyx_PyThreadState_declare + if (gen->resume_label < 0) { + return; + } + __Pyx_PyThreadState_assign + __Pyx_ErrFetch(&error_type, &error_value, &error_traceback); +#ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(self)) { + __pyx_PyAsyncGenObject *agen = (__pyx_PyAsyncGenObject*)self; + PyObject *finalizer = agen->ag_finalizer; + if (finalizer && !agen->ag_closed) { + PyObject *res = __Pyx_PyObject_CallOneArg(finalizer, self); + if (unlikely(!res)) { + PyErr_WriteUnraisable(self); + } else { + Py_DECREF(res); + } + __Pyx_ErrRestore(error_type, error_value, error_traceback); + return; + } + } +#endif + if (unlikely(gen->resume_label == 0 && !error_value)) { +#ifdef __Pyx_Coroutine_USED +#ifdef __Pyx_Generator_USED + if (!__Pyx_Generator_CheckExact(self)) +#endif + { + PyObject_GC_UnTrack(self); + if (unlikely(PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "coroutine '%.50S' was never awaited", gen->gi_qualname) < 0)) + PyErr_WriteUnraisable(self); + PyObject_GC_Track(self); + } +#endif + } else { + PyObject *retval = NULL; + __Pyx_PySendResult result = __Pyx_Coroutine_Close(self, &retval); + if (result == PYGEN_ERROR) { + PyErr_WriteUnraisable(self); + } else { + Py_XDECREF(retval); + } + } + __Pyx_ErrRestore(error_type, error_value, error_traceback); +} +#endif +static PyObject * +__Pyx_Coroutine_get_name(__pyx_CoroutineObject *self, void *context) +{ + PyObject *name = self->gi_name; + CYTHON_UNUSED_VAR(context); + if (unlikely(!name)) name = Py_None; + Py_INCREF(name); + return name; +} +static int +__Pyx_Coroutine_set_name(__pyx_CoroutineObject *self, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(self->gi_name, value); + return 0; +} +static PyObject * +__Pyx_Coroutine_get_qualname(__pyx_CoroutineObject *self, void *context) +{ + PyObject *name = self->gi_qualname; + CYTHON_UNUSED_VAR(context); + if (unlikely(!name)) name = Py_None; + Py_INCREF(name); + return name; +} +static int +__Pyx_Coroutine_set_qualname(__pyx_CoroutineObject *self, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(self->gi_qualname, value); + return 0; +} +#if !CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx__Coroutine_get_frame_locked(__pyx_CoroutineObject *self) { + PyObject *frame; + frame = self->gi_frame; + if (!frame) { + if (unlikely(!self->gi_code)) { + Py_RETURN_NONE; + } + PyObject *globals = PyDict_New(); + if (unlikely(!globals)) return NULL; + frame = (PyObject *) PyFrame_New( + PyThreadState_Get(), /*PyThreadState *tstate,*/ + (PyCodeObject*) self->gi_code, /*PyCodeObject *code,*/ + globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + Py_DECREF(globals); + if (unlikely(!frame)) + return NULL; + if (unlikely(self->gi_frame)) { + Py_DECREF(frame); + frame = self->gi_frame; + } else { + self->gi_frame = frame; + } + } + Py_INCREF(frame); + return frame; +} +#endif +static PyObject * +__Pyx__Coroutine_get_frame(__pyx_CoroutineObject *self) +{ +#if !CYTHON_COMPILING_IN_LIMITED_API + PyObject *frame; + __Pyx_BEGIN_CRITICAL_SECTION((PyObject*)self); + frame = __Pyx__Coroutine_get_frame_locked(self); + __Pyx_END_CRITICAL_SECTION(); + return frame; +#else + CYTHON_UNUSED_VAR(self); + Py_RETURN_NONE; +#endif +} +static PyObject * +__Pyx_Coroutine_get_frame(__pyx_CoroutineObject *self, void *context) { + CYTHON_UNUSED_VAR(context); + PyObject *frame = self->gi_frame; + if (frame) + return __Pyx_NewRef(frame); + return __Pyx__Coroutine_get_frame(self); +} +static __pyx_CoroutineObject *__Pyx__Coroutine_New( + PyTypeObject* type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, + PyObject *name, PyObject *qualname, PyObject *module_name) { + __pyx_CoroutineObject *gen = PyObject_GC_New(__pyx_CoroutineObject, type); + if (unlikely(!gen)) + return NULL; + return __Pyx__Coroutine_NewInit(gen, body, code, closure, name, qualname, module_name); +} +static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( + __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, + PyObject *name, PyObject *qualname, PyObject *module_name) { + gen->body = body; + gen->closure = closure; + Py_XINCREF(closure); + gen->is_running = 0; + gen->resume_label = 0; + gen->classobj = NULL; + gen->yieldfrom = NULL; + gen->yieldfrom_am_send = NULL; + #if PY_VERSION_HEX >= 0x030B00a4 && !CYTHON_COMPILING_IN_LIMITED_API + gen->gi_exc_state.exc_value = NULL; + #else + gen->gi_exc_state.exc_type = NULL; + gen->gi_exc_state.exc_value = NULL; + gen->gi_exc_state.exc_traceback = NULL; + #endif +#if CYTHON_USE_EXC_INFO_STACK + gen->gi_exc_state.previous_item = NULL; +#endif +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + gen->gi_weakreflist = NULL; +#endif + Py_XINCREF(qualname); + gen->gi_qualname = qualname; + Py_XINCREF(name); + gen->gi_name = name; + Py_XINCREF(module_name); + gen->gi_modulename = module_name; + Py_XINCREF(code); + gen->gi_code = code; + gen->gi_frame = NULL; +#if CYTHON_USE_SYS_MONITORING && (CYTHON_PROFILE || CYTHON_TRACE) + memset(gen->__pyx_pymonitoring_state, 0, sizeof(gen->__pyx_pymonitoring_state)); + gen->__pyx_pymonitoring_version = 0; +#endif + PyObject_GC_Track(gen); + return gen; +} +static char __Pyx_Coroutine_test_and_set_is_running(__pyx_CoroutineObject *gen) { + char result; + __Pyx_BEGIN_CRITICAL_SECTION((PyObject*)gen); + result = gen->is_running; + gen->is_running = 1; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static void __Pyx_Coroutine_unset_is_running(__pyx_CoroutineObject *gen) { + __Pyx_BEGIN_CRITICAL_SECTION((PyObject*)gen); + assert(gen->is_running); + gen->is_running = 0; + __Pyx_END_CRITICAL_SECTION(); +} +static char __Pyx_Coroutine_get_is_running(__pyx_CoroutineObject *gen) { + char result; + __Pyx_BEGIN_CRITICAL_SECTION((PyObject*)gen); + result = gen->is_running; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyObject *__Pyx_Coroutine_get_is_running_getter(PyObject *gen, void *closure) { + CYTHON_UNUSED_VAR(closure); + char result = __Pyx_Coroutine_get_is_running((__pyx_CoroutineObject*)gen); + if (result) Py_RETURN_TRUE; + else Py_RETURN_FALSE; +} +#if __PYX_HAS_PY_AM_SEND == 2 +static void __Pyx_SetBackportTypeAmSend(PyTypeObject *type, __Pyx_PyAsyncMethodsStruct *static_amsend_methods, __Pyx_pyiter_sendfunc am_send) { + Py_ssize_t ptr_offset = (char*)(type->tp_as_async) - (char*)type; + if (ptr_offset < 0 || ptr_offset > type->tp_basicsize) { + return; + } + memcpy((void*)static_amsend_methods, (void*)(type->tp_as_async), sizeof(*type->tp_as_async)); + static_amsend_methods->am_send = am_send; + type->tp_as_async = __Pyx_SlotTpAsAsync(static_amsend_methods); +} +#endif +static PyObject *__Pyx_Coroutine_fail_reduce_ex(PyObject *self, PyObject *arg) { + CYTHON_UNUSED_VAR(arg); + __Pyx_RaiseTypeErrorWithObjectType( + "cannot pickle '" __Pyx_FMT_TYPENAME "' object", self); + return NULL; +} + +/* Generator */ +static PyMethodDef __pyx_Generator_methods[] = { + {"send", (PyCFunction) __Pyx_Coroutine_Send, METH_O, + PyDoc_STR("send(arg) -> send 'arg' into generator,\nreturn next yielded value or raise StopIteration.")}, + {"throw", __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_Coroutine_Throw), +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030A0000 + METH_VARARGS, +#else + METH_FASTCALL, +#endif + PyDoc_STR("throw(typ[,val[,tb]]) -> raise exception in generator,\nreturn next yielded value or raise StopIteration.")}, + {"close", (PyCFunction) __Pyx_Coroutine_Close_Method, METH_NOARGS, + PyDoc_STR("close() -> raise GeneratorExit inside generator.")}, + {"__reduce_ex__", (PyCFunction) __Pyx_Coroutine_fail_reduce_ex, METH_O, 0}, + {"__reduce__", (PyCFunction) __Pyx_Coroutine_fail_reduce_ex, METH_NOARGS, 0}, + {0, 0, 0, 0} +}; +static PyMemberDef __pyx_Generator_memberlist[] = { + {"gi_yieldfrom", T_OBJECT, offsetof(__pyx_CoroutineObject, yieldfrom), READONLY, + PyDoc_STR("object being iterated by 'yield from', or None")}, + {"gi_code", T_OBJECT, offsetof(__pyx_CoroutineObject, gi_code), READONLY, NULL}, + {"__module__", T_OBJECT, offsetof(__pyx_CoroutineObject, gi_modulename), 0, 0}, +#if PY_VERSION_HEX < 0x030C0000 || CYTHON_COMPILING_IN_LIMITED_API + {"__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CoroutineObject, gi_weakreflist), READONLY, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyGetSetDef __pyx_Generator_getsets[] = { + {"__name__", (getter)__Pyx_Coroutine_get_name, (setter)__Pyx_Coroutine_set_name, + PyDoc_STR("name of the generator"), 0}, + {"__qualname__", (getter)__Pyx_Coroutine_get_qualname, (setter)__Pyx_Coroutine_set_qualname, + PyDoc_STR("qualified name of the generator"), 0}, + {"gi_frame", (getter)__Pyx_Coroutine_get_frame, NULL, + PyDoc_STR("Frame of the generator"), 0}, + {"gi_running", __Pyx_Coroutine_get_is_running_getter, NULL, NULL, NULL}, + {0, 0, 0, 0, 0} +}; +static PyType_Slot __pyx_GeneratorType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_Coroutine_dealloc}, + {Py_tp_traverse, (void *)__Pyx_Coroutine_traverse}, + {Py_tp_iter, (void *)PyObject_SelfIter}, + {Py_tp_iternext, (void *)__Pyx_Generator_Next}, + {Py_tp_methods, (void *)__pyx_Generator_methods}, + {Py_tp_members, (void *)__pyx_Generator_memberlist}, + {Py_tp_getset, (void *)__pyx_Generator_getsets}, + {Py_tp_getattro, (void *) PyObject_GenericGetAttr}, +#if CYTHON_USE_TP_FINALIZE + {Py_tp_finalize, (void *)__Pyx_Coroutine_del}, +#endif +#if __PYX_HAS_PY_AM_SEND == 1 + {Py_am_send, (void *)__Pyx_Coroutine_AmSend}, +#endif + {0, 0}, +}; +static PyType_Spec __pyx_GeneratorType_spec = { + __PYX_TYPE_MODULE_PREFIX "generator", + sizeof(__pyx_CoroutineObject), + 0, +#if PY_VERSION_HEX >= 0x030C0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_TPFLAGS_MANAGED_WEAKREF | +#endif + Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | __Pyx_TPFLAGS_HAVE_AM_SEND, + __pyx_GeneratorType_slots +}; +#if __PYX_HAS_PY_AM_SEND == 2 +static __Pyx_PyAsyncMethodsStruct __pyx_Generator_as_async; +#endif +static int __pyx_Generator_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + mstate->__pyx_GeneratorType = __Pyx_FetchCommonTypeFromSpec( + mstate->__pyx_CommonTypesMetaclassType, module, &__pyx_GeneratorType_spec, NULL); + if (unlikely(!mstate->__pyx_GeneratorType)) { + return -1; + } +#if __PYX_HAS_PY_AM_SEND == 2 + __Pyx_SetBackportTypeAmSend(mstate->__pyx_GeneratorType, &__pyx_Generator_as_async, &__Pyx_Coroutine_AmSend); +#endif + return 0; +} +static PyObject *__Pyx_Generator_GetInlinedResult(PyObject *self) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; + PyObject *retval = NULL; + if (unlikely(__Pyx_Coroutine_test_and_set_is_running(gen))) { + return __Pyx_Coroutine_AlreadyRunningError(gen); + } + __Pyx_PySendResult result = __Pyx_Coroutine_SendEx(gen, Py_None, &retval, 0); + __Pyx_Coroutine_unset_is_running(gen); + (void) result; + assert (result == PYGEN_RETURN || result == PYGEN_ERROR); + assert ((result == PYGEN_RETURN && retval != NULL) || (result == PYGEN_ERROR && retval == NULL)); + return retval; +} + +/* CheckBinaryVersion */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { + const unsigned long MAJOR_MINOR = 0xFFFF0000UL; + if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) + return 0; + if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) + return 1; + { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compile time Python version %d.%d " + "of module '%.100s' " + "%s " + "runtime version %d.%d", + (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), + __Pyx_MODULE_NAME, + (allow_newer) ? "was newer than" : "does not match", + (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) + ); + return PyErr_WarnEx(NULL, message, 1); + } +} + +/* NewCodeObj */ +#if CYTHON_COMPILING_IN_LIMITED_API + static PyObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *exception_table = NULL; + PyObject *types_module=NULL, *code_type=NULL, *result=NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + PyObject *version_info; + PyObject *py_minor_version = NULL; + #endif + long minor_version = 0; + #if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + minor_version = 11; + #else + if (!(version_info = PySys_GetObject("version_info"))) goto end; + if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; + minor_version = PyLong_AsLong(py_minor_version); + Py_DECREF(py_minor_version); + if (minor_version == -1 && PyErr_Occurred()) goto end; + #endif + if (!(types_module = PyImport_ImportModule("types"))) goto end; + if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; + if (minor_version <= 10) { + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else { + if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); + } + end: + Py_XDECREF(code_type); + Py_XDECREF(exception_table); + Py_XDECREF(types_module); + if (!result) { + PyObject *exc_type, *exc_value, *exc_tb; + PyErr_Fetch(&exc_type, &exc_value, &exc_tb); + if (PyErr_WarnFormat( + PyExc_RuntimeWarning, 1, + "Code object creation failed in Cython module: %S\nTry recompiling with a more recent version of Cython.", + exc_value ? exc_value : exc_type) == 0) { + result = Py_None; + Py_INCREF(result); + } + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + } + return result; + } +#elif PY_VERSION_HEX >= 0x030B0000 + static PyCodeObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyCodeObject *result; + result = + #if PY_VERSION_HEX >= 0x030C0000 + PyUnstable_Code_NewWithPosOnlyArgs + #else + PyCode_NewWithPosOnlyArgs + #endif + (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, __pyx_mstate_global->__pyx_empty_bytes); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030c00A1 + if (likely(result)) + result->_co_firsttraceable = 0; + #endif + return result; + } +#elif !CYTHON_COMPILING_IN_PYPY + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + PyObject *line_table, + PyObject *tuple_dedup_map +) { + PyObject *code_obj = NULL, *varnames_tuple_dedup = NULL, *code_bytes = NULL; + Py_ssize_t var_count = (Py_ssize_t) descr.nlocals; + PyObject *varnames_tuple = PyTuple_New(var_count); + if (unlikely(!varnames_tuple)) return NULL; + for (Py_ssize_t i=0; i < var_count; i++) { + Py_INCREF(varnames[i]); + if (__Pyx_PyTuple_SET_ITEM(varnames_tuple, i, varnames[i]) != (0)) goto done; + } + #if CYTHON_COMPILING_IN_LIMITED_API + varnames_tuple_dedup = PyDict_GetItem(tuple_dedup_map, varnames_tuple); + if (!varnames_tuple_dedup) { + if (unlikely(PyDict_SetItem(tuple_dedup_map, varnames_tuple, varnames_tuple) < 0)) goto done; + varnames_tuple_dedup = varnames_tuple; + } + #else + varnames_tuple_dedup = PyDict_SetDefault(tuple_dedup_map, varnames_tuple, varnames_tuple); + if (unlikely(!varnames_tuple_dedup)) goto done; + #endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(varnames_tuple_dedup); + #endif + if (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table != NULL && !CYTHON_COMPILING_IN_GRAAL) { + Py_ssize_t line_table_length = __Pyx_PyBytes_GET_SIZE(line_table); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(line_table_length == -1)) goto done; + #endif + Py_ssize_t code_len = (line_table_length * 2 + 4) & ~3LL; + code_bytes = PyBytes_FromStringAndSize(NULL, code_len); + if (unlikely(!code_bytes)) goto done; + char* c_code_bytes = PyBytes_AsString(code_bytes); + if (unlikely(!c_code_bytes)) goto done; + memset(c_code_bytes, 0, (size_t) code_len); + } + code_obj = (PyObject*) __Pyx__PyCode_New( + (int) descr.argcount, + (int) descr.num_posonly_args, + (int) descr.num_kwonly_args, + (int) descr.nlocals, + 0, + (int) descr.flags, + code_bytes ? code_bytes : __pyx_mstate_global->__pyx_empty_bytes, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + varnames_tuple_dedup, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + filename, + funcname, + (int) descr.first_line, + (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table) ? line_table : __pyx_mstate_global->__pyx_empty_bytes + ); +done: + Py_XDECREF(code_bytes); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(varnames_tuple_dedup); + #endif + Py_DECREF(varnames_tuple); + return code_obj; +} + +/* DecompressString */ +CYTHON_UNUSED +static CYTHON_SMALL_CODE PyObject *__Pyx_DecompressString(const char *s, Py_ssize_t length, int algo) { +#ifdef __Pyx_DecompressString_UNUSED + CYTHON_UNUSED_VAR(s); + CYTHON_UNUSED_VAR(length); + CYTHON_UNUSED_VAR(algo); + return NULL; +#else + PyObject *module = NULL, *decompress, *compressed_bytes, *decompressed; + const char* module_name = algo == 3 ? "compression.zstd" : algo == 2 ? "bz2" : "zlib"; + PyObject *methodname = PyUnicode_FromString("decompress"); + if (unlikely(!methodname)) return NULL; + #if __PYX_LIMITED_VERSION_HEX >= 0x030e0000 + if (algo == 3) { + PyObject *fromlist = Py_BuildValue("[O]", methodname); + if (unlikely(!fromlist)) goto bad; + module = PyImport_ImportModuleLevel("compression.zstd", NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + } else + #endif + module = PyImport_ImportModule(module_name); + if (unlikely(!module)) goto import_failed; + decompress = PyObject_GetAttr(module, methodname); + if (unlikely(!decompress)) goto import_failed; + { + #ifdef __cplusplus + char *memview_bytes = const_cast<char*>(s); + #else + #if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wcast-qual" + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-qual" + #endif + char *memview_bytes = (char*) s; + #if defined(__clang__) + #pragma clang diagnostic pop + #elif !defined(__INTEL_COMPILER) && defined(__GNUC__) + #pragma GCC diagnostic pop + #endif + #endif + #if CYTHON_COMPILING_IN_LIMITED_API && !defined(PyBUF_READ) + int memview_flags = 0x100; + #else + int memview_flags = PyBUF_READ; + #endif + compressed_bytes = PyMemoryView_FromMemory(memview_bytes, length, memview_flags); + } + if (unlikely(!compressed_bytes)) { + Py_DECREF(decompress); + goto bad; + } + decompressed = PyObject_CallFunctionObjArgs(decompress, compressed_bytes, NULL); + Py_DECREF(compressed_bytes); + Py_DECREF(decompress); + Py_DECREF(module); + Py_DECREF(methodname); + return decompressed; +import_failed: + PyErr_Format(PyExc_ImportError, + "Failed to import '%.20s.decompress' - cannot initialise module strings. " + "String compression was configured with the C macro 'CYTHON_COMPRESS_STRINGS=%d'.", + module_name, algo); +bad: + Py_XDECREF(module); + Py_DECREF(methodname); + return NULL; +#endif +} + +/* DecompressString_LZSS */ +#ifndef __Pyx_DecompressString_LZSS_UNUSED +CYTHON_UNUSED +static CYTHON_SMALL_CODE size_t __pyx_lzss_decompress(const uint8_t* src, uint8_t* dst, size_t dst_len) { + size_t pos = 0, out_pos = 0; + while (1) { + uint32_t flags = src[pos++] | 0xFF00; + while (flags & 0x100) { + if (flags & 1) { + dst[out_pos++] = src[pos++]; + } else { + uint32_t lo = src[pos++], hi = src[pos++]; + uint32_t end_offset_of_last_occurrence, match_length; + if (!(lo & 0x80)) { + end_offset_of_last_occurrence = lo; + match_length = hi; + } else if (!(hi & 0x80)) { + end_offset_of_last_occurrence = 0x80 + (((hi << 2) & 0x180) | (lo & 0x7F)); + match_length = hi & 0x1F; + } else { + end_offset_of_last_occurrence = 0x80 + ((hi & 0x7F) << 7 | (lo & 0x7F)); + match_length = src[pos++]; + } + match_length += 3; + size_t ref_pos = out_pos - end_offset_of_last_occurrence - match_length; + memcpy(dst + out_pos, dst + ref_pos, match_length); + out_pos += match_length; + } + if (out_pos >= dst_len) return pos; + flags >>= 1; + } + } +} +#endif +static CYTHON_SMALL_CODE PyObject *__Pyx_DecompressString_LZSS(const char *s, size_t compressed_length, size_t uncompressed_length) { +#ifdef __Pyx_DecompressString_LZSS_UNUSED + CYTHON_UNUSED_VAR(s); + CYTHON_UNUSED_VAR(compressed_length); + CYTHON_UNUSED_VAR(uncompressed_length); + return NULL; +#else + PyObject *result; + unsigned char *result_data; + size_t src_length; + result = PyBytes_FromStringAndSize(NULL, (Py_ssize_t) uncompressed_length); + if (unlikely(!result)) return NULL; + result_data = __Pyx_PyBytes_AsWritableUString(result); + if (unlikely(!result_data)) goto bad; + src_length = __pyx_lzss_decompress((const uint8_t*) s, result_data, uncompressed_length); + if (unlikely(src_length != compressed_length)) goto decompression_failed; + return result; +decompression_failed: + PyErr_SetString(PyExc_RuntimeError, "LZSS string data decompression failed"); +bad: + Py_DECREF(result); + return NULL; +#endif +} + +#include <string.h> +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { + size_t len = strlen(s); + if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "byte string is too long"); + return -1; + } + return (Py_ssize_t) len; +} +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return __Pyx_PyUnicode_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return PyByteArray_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + { + const char* result; + Py_ssize_t unicode_length; + CYTHON_MAYBE_UNUSED_VAR(unicode_length); // only for __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (unlikely(PyArg_Parse(o, "s#", &result, length) < 0)) return NULL; + #else + result = PyUnicode_AsUTF8AndSize(o, length); + #endif + #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + unicode_length = PyUnicode_GetLength(o); + if (unlikely(unicode_length < 0)) return NULL; + if (unlikely(unicode_length != *length)) { + PyUnicode_AsASCIIString(o); + return NULL; + } + #endif + return result; + } +#else +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif +} +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + if (PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif + if (PyByteArray_Check(o)) { +#if (CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) || (CYTHON_COMPILING_IN_PYPY && (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))) + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); +#else + *length = PyByteArray_Size(o); + if (*length == -1) return NULL; + return PyByteArray_AsString(o); +#endif + } else + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_LongWrongResultType(PyObject* result) { + __Pyx_TypeName result_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(result)); + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 + if (unlikely(!result_type_name)) goto bad; + #endif + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " + "The ability to return an instance of a strict subclass of int is deprecated, " + "and may be removed in a future version of Python.", + result_type_name)) { + __Pyx_DECREF_TypeName(result_type_name); + goto bad; + } + __Pyx_DECREF_TypeName(result_type_name); + return result; + } + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME ")", + result_type_name); + __Pyx_DECREF_TypeName(result_type_name); +bad: + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + PyObject *res = NULL; + if (likely(PyLong_Check(x))) + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + if (likely(m && m->nb_int)) { + res = m->nb_int(x); + } +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Long(x); + } +#endif + if (likely(res)) { + if (unlikely(!PyLong_CheckExact(res))) { + return __Pyx_PyNumber_LongWrongResultType(res); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyLong_AsSsize_t(PyObject* b) { + #if CYTHON_USE_PYLONG_INTERNALS + Py_ssize_t ival; + const Py_ssize_t size = __Pyx_PyLong_DigitCount(b); + const int is_neg = __Pyx_PyLong_IsNeg(b); + const digit* digits = __Pyx_PyLong_Digits(b); + if (size == 0) return 0; + #if SIZEOF_SIZE_T * 8 > 1 * PyLong_SHIFT + if (size == 1) { + ival = (Py_ssize_t) (((size_t)digits[0])); + } else + #endif + #if SIZEOF_SIZE_T * 8 > 2 * PyLong_SHIFT + if (size == 2) { + ival = (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } else + #endif + #if SIZEOF_SIZE_T * 8 > 3 * PyLong_SHIFT + if (size == 3) { + ival = (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } else + #endif + #if SIZEOF_SIZE_T * 8 > 4 * PyLong_SHIFT + if (size == 4) { + ival = (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } else + #endif + return PyLong_AsSsize_t(b); + return is_neg ? -ival : ival; + #else + return PyLong_AsSsize_t(b); + #endif +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + if (likely(PyLong_Check(b))) { + return __Pyx_PyLong_AsSsize_t(b); + } else { + Py_ssize_t ival; + PyObject *x = PyNumber_Index(b); + if (unlikely(!x)) return -1; + ival = __Pyx_PyLong_AsSsize_t(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyLong_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b) { + CYTHON_UNUSED_VAR(b); + return __Pyx_NewRef(Py_None); +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return __Pyx_NewRef(b ? Py_True: Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t ival) { + return PyLong_FromSize_t(ival); +} + + +/* MultiPhaseInitModuleState */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +#ifndef CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX >= 0x030C0000) + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 1 +#else + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 0 +#endif +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE && !CYTHON_ATOMICS +#error "Module state with PEP489 requires atomics. Currently that's one of\ + C11, C++11, gcc atomic intrinsics or MSVC atomic intrinsics" +#endif +#if !CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#define __Pyx_ModuleStateLookup_Lock() +#define __Pyx_ModuleStateLookup_Unlock() +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 +static PyMutex __Pyx_ModuleStateLookup_mutex = {0}; +#define __Pyx_ModuleStateLookup_Lock() PyMutex_Lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() PyMutex_Unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(__cplusplus) && __cplusplus >= 201103L +#include <mutex> +static std::mutex __Pyx_ModuleStateLookup_mutex; +#define __Pyx_ModuleStateLookup_Lock() __Pyx_ModuleStateLookup_mutex.lock() +#define __Pyx_ModuleStateLookup_Unlock() __Pyx_ModuleStateLookup_mutex.unlock() +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201112L) && !defined(__STDC_NO_THREADS__) +#include <threads.h> +static mtx_t __Pyx_ModuleStateLookup_mutex; +static once_flag __Pyx_ModuleStateLookup_mutex_once_flag = ONCE_FLAG_INIT; +static void __Pyx_ModuleStateLookup_initialize_mutex(void) { + mtx_init(&__Pyx_ModuleStateLookup_mutex, mtx_plain); +} +#define __Pyx_ModuleStateLookup_Lock()\ + call_once(&__Pyx_ModuleStateLookup_mutex_once_flag, __Pyx_ModuleStateLookup_initialize_mutex);\ + mtx_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() mtx_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(HAVE_PTHREAD_H) +#include <pthread.h> +static pthread_mutex_t __Pyx_ModuleStateLookup_mutex = PTHREAD_MUTEX_INITIALIZER; +#define __Pyx_ModuleStateLookup_Lock() pthread_mutex_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() pthread_mutex_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(_WIN32) +#include <Windows.h> // synchapi.h on its own doesn't work +static SRWLOCK __Pyx_ModuleStateLookup_mutex = SRWLOCK_INIT; +#define __Pyx_ModuleStateLookup_Lock() AcquireSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() ReleaseSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#else +#error "No suitable lock available for CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE.\ + Requires C standard >= C11, or C++ standard >= C++11,\ + or pthreads, or the Windows 32 API, or Python >= 3.13." +#endif +typedef struct { + int64_t id; + PyObject *module; +} __Pyx_InterpreterIdAndModule; +typedef struct { + char interpreter_id_as_index; + Py_ssize_t count; + Py_ssize_t allocated; + __Pyx_InterpreterIdAndModule table[1]; +} __Pyx_ModuleStateLookupData; +#define __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE 32 +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_int_type __Pyx_ModuleStateLookup_read_counter = 0; +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_ptr_type __Pyx_ModuleStateLookup_data = 0; +#else +static __Pyx_ModuleStateLookupData* __Pyx_ModuleStateLookup_data = NULL; +#endif +static __Pyx_InterpreterIdAndModule* __Pyx_State_FindModuleStateLookupTableLowerBound( + __Pyx_InterpreterIdAndModule* table, + Py_ssize_t count, + int64_t interpreterId) { + __Pyx_InterpreterIdAndModule* begin = table; + __Pyx_InterpreterIdAndModule* end = begin + count; + if (begin->id == interpreterId) { + return begin; + } + while ((end - begin) > __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + __Pyx_InterpreterIdAndModule* halfway = begin + (end - begin)/2; + if (halfway->id == interpreterId) { + return halfway; + } + if (halfway->id < interpreterId) { + begin = halfway; + } else { + end = halfway; + } + } + for (; begin < end; ++begin) { + if (begin->id >= interpreterId) return begin; + } + return begin; +} +static PyObject *__Pyx_State_FindModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(PyInterpreterState_Get()); + if (interpreter_id == -1) return NULL; +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData* data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + { + __pyx_atomic_incr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + if (likely(data)) { + __Pyx_ModuleStateLookupData* new_data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_acquire(&__Pyx_ModuleStateLookup_data); + if (likely(data == new_data)) { + goto read_finished; + } + } + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + __Pyx_ModuleStateLookup_Lock(); + __pyx_atomic_incr_relaxed(&__Pyx_ModuleStateLookup_read_counter); + data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + __Pyx_ModuleStateLookup_Unlock(); + } + read_finished:; +#else + __Pyx_ModuleStateLookupData* data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_InterpreterIdAndModule* found = NULL; + if (unlikely(!data)) goto end; + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + found = data->table+interpreter_id; + } + } else { + found = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + } + end: + { + PyObject *result=NULL; + if (found && found->id == interpreter_id) { + result = found->module; + } +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); +#endif + return result; + } +} +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static void __Pyx_ModuleStateLookup_wait_until_no_readers(void) { + while (__pyx_atomic_load(&__Pyx_ModuleStateLookup_read_counter) != 0); +} +#else +#define __Pyx_ModuleStateLookup_wait_until_no_readers() +#endif +static int __Pyx_State_AddModuleInterpIdAsIndex(__Pyx_ModuleStateLookupData **old_data, PyObject* module, int64_t interpreter_id) { + Py_ssize_t to_allocate = (*old_data)->allocated; + while (to_allocate <= interpreter_id) { + if (to_allocate == 0) to_allocate = 1; + else to_allocate *= 2; + } + __Pyx_ModuleStateLookupData *new_data = *old_data; + if (to_allocate != (*old_data)->allocated) { + new_data = (__Pyx_ModuleStateLookupData *)realloc( + *old_data, + sizeof(__Pyx_ModuleStateLookupData)+(to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + PyErr_NoMemory(); + return -1; + } + for (Py_ssize_t i = new_data->allocated; i < to_allocate; ++i) { + new_data->table[i].id = i; + new_data->table[i].module = NULL; + } + new_data->allocated = to_allocate; + } + new_data->table[interpreter_id].module = module; + if (new_data->count < interpreter_id+1) { + new_data->count = interpreter_id+1; + } + *old_data = new_data; + return 0; +} +static void __Pyx_State_ConvertFromInterpIdAsIndex(__Pyx_ModuleStateLookupData *data) { + __Pyx_InterpreterIdAndModule *read = data->table; + __Pyx_InterpreterIdAndModule *write = data->table; + __Pyx_InterpreterIdAndModule *end = read + data->count; + for (; read<end; ++read) { + if (read->module) { + write->id = read->id; + write->module = read->module; + ++write; + } + } + data->count = write - data->table; + for (; write<end; ++write) { + write->id = 0; + write->module = NULL; + } + data->interpreter_id_as_index = 0; +} +static int __Pyx_State_AddModule(PyObject* module, CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + int result = 0; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *old_data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *old_data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_ModuleStateLookupData *new_data = old_data; + if (!new_data) { + new_data = (__Pyx_ModuleStateLookupData *)calloc(1, sizeof(__Pyx_ModuleStateLookupData)); + if (!new_data) { + result = -1; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = 1; + new_data->interpreter_id_as_index = 1; + } + __Pyx_ModuleStateLookup_wait_until_no_readers(); + if (new_data->interpreter_id_as_index) { + if (interpreter_id < __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + result = __Pyx_State_AddModuleInterpIdAsIndex(&new_data, module, interpreter_id); + goto end; + } + __Pyx_State_ConvertFromInterpIdAsIndex(new_data); + } + { + Py_ssize_t insert_at = 0; + { + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + new_data->table, new_data->count, interpreter_id); + assert(lower_bound); + insert_at = lower_bound - new_data->table; + if (unlikely(insert_at < new_data->count && lower_bound->id == interpreter_id)) { + lower_bound->module = module; + goto end; // already in table, nothing more to do + } + } + if (new_data->count+1 >= new_data->allocated) { + Py_ssize_t to_allocate = (new_data->count+1)*2; + new_data = + (__Pyx_ModuleStateLookupData*)realloc( + new_data, + sizeof(__Pyx_ModuleStateLookupData) + + (to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + result = -1; + new_data = old_data; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = to_allocate; + } + ++new_data->count; + int64_t last_id = interpreter_id; + PyObject *last_module = module; + for (Py_ssize_t i=insert_at; i<new_data->count; ++i) { + int64_t current_id = new_data->table[i].id; + new_data->table[i].id = last_id; + last_id = current_id; + PyObject *current_module = new_data->table[i].module; + new_data->table[i].module = last_module; + last_module = current_module; + } + } + end: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, new_data); +#else + __Pyx_ModuleStateLookup_data = new_data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return result; +} +static int __Pyx_State_RemoveModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *data = __Pyx_ModuleStateLookup_data; +#endif + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + data->table[interpreter_id].module = NULL; + } + goto done; + } + { + __Pyx_ModuleStateLookup_wait_until_no_readers(); + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + if (!lower_bound) goto done; + if (lower_bound->id != interpreter_id) goto done; + __Pyx_InterpreterIdAndModule *end = data->table+data->count; + for (;lower_bound<end-1; ++lower_bound) { + lower_bound->id = (lower_bound+1)->id; + lower_bound->module = (lower_bound+1)->module; + } + } + --data->count; + if (data->count == 0) { + free(data); + data = NULL; + } + done: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, data); +#else + __Pyx_ModuleStateLookup_data = data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return 0; +} +#endif + +/* #### Code section: utility_code_pragmas_end ### */ +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + + +/* #### Code section: end ### */ +#endif /* Py_PYTHON_H */ diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/iup.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/fontTools/varLib/iup.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..88bc6995bfa340e311f90afe50eaa947f4f86aff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/iup.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19902adfebdacda7d86c774aa5c0d8bf7c8aa9e62682eb80981219993416cd6b +size 1944232 diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/iup.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/iup.py new file mode 100644 index 0000000000000000000000000000000000000000..a53de409cd58c60a0fe10520953a011127e0d826 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/iup.py @@ -0,0 +1,489 @@ +try: + import cython +except (AttributeError, ImportError): + # if cython not installed, use mock module with no-op decorators and types + from fontTools.misc import cython +COMPILED = cython.compiled + +from typing import ( + Sequence, + Tuple, + Union, +) +from numbers import Integral, Real + +_Point = Tuple[Real, Real] +_Delta = Tuple[Real, Real] +_PointSegment = Sequence[_Point] +_DeltaSegment = Sequence[_Delta] +_DeltaOrNone = Union[_Delta, None] +_DeltaOrNoneSegment = Sequence[_DeltaOrNone] +_Endpoints = Sequence[Integral] + + +MAX_LOOKBACK = 8 + + +@cython.cfunc +@cython.locals( + j=cython.int, + n=cython.int, + x1=cython.double, + x2=cython.double, + d1=cython.double, + d2=cython.double, + scale=cython.double, + x=cython.double, + d=cython.double, +) +def iup_segment( + coords: _PointSegment, rc1: _Point, rd1: _Delta, rc2: _Point, rd2: _Delta +): # -> _DeltaSegment: + """Given two reference coordinates `rc1` & `rc2` and their respective + delta vectors `rd1` & `rd2`, returns interpolated deltas for the set of + coordinates `coords`.""" + + # rc1 = reference coord 1 + # rd1 = reference delta 1 + out_arrays = [None, None] + for j in 0, 1: + out_arrays[j] = out = [] + x1, x2, d1, d2 = rc1[j], rc2[j], rd1[j], rd2[j] + + if x1 == x2: + n = len(coords) + if d1 == d2: + out.extend([d1] * n) + else: + out.extend([0] * n) + continue + + if x1 > x2: + x1, x2 = x2, x1 + d1, d2 = d2, d1 + + # x1 < x2 + scale = (d2 - d1) / (x2 - x1) + for pair in coords: + x = pair[j] + + if x <= x1: + d = d1 + elif x >= x2: + d = d2 + else: + # Interpolate + # + # NOTE: we assign an explicit intermediate variable here in + # order to disable a fused mul-add optimization. See: + # + # - https://godbolt.org/z/YsP4T3TqK, + # - https://github.com/fonttools/fonttools/issues/3703 + nudge = (x - x1) * scale + d = d1 + nudge + + out.append(d) + + return zip(*out_arrays) + + +def iup_contour(deltas: _DeltaOrNoneSegment, coords: _PointSegment) -> _DeltaSegment: + """For the contour given in `coords`, interpolate any missing + delta values in delta vector `deltas`. + + Returns fully filled-out delta vector.""" + + assert len(deltas) == len(coords) + if None not in deltas: + return deltas + + n = len(deltas) + # indices of points with explicit deltas + indices = [i for i, v in enumerate(deltas) if v is not None] + if not indices: + # All deltas are None. Return 0,0 for all. + return [(0, 0)] * n + + out = [] + it = iter(indices) + start = next(it) + if start != 0: + # Initial segment that wraps around + i1, i2, ri1, ri2 = 0, start, start, indices[-1] + out.extend( + iup_segment( + coords[i1:i2], coords[ri1], deltas[ri1], coords[ri2], deltas[ri2] + ) + ) + out.append(deltas[start]) + for end in it: + if end - start > 1: + i1, i2, ri1, ri2 = start + 1, end, start, end + out.extend( + iup_segment( + coords[i1:i2], coords[ri1], deltas[ri1], coords[ri2], deltas[ri2] + ) + ) + out.append(deltas[end]) + start = end + if start != n - 1: + # Final segment that wraps around + i1, i2, ri1, ri2 = start + 1, n, start, indices[0] + out.extend( + iup_segment( + coords[i1:i2], coords[ri1], deltas[ri1], coords[ri2], deltas[ri2] + ) + ) + + assert len(deltas) == len(out), (len(deltas), len(out)) + return out + + +def iup_delta( + deltas: _DeltaOrNoneSegment, coords: _PointSegment, ends: _Endpoints +) -> _DeltaSegment: + """For the outline given in `coords`, with contour endpoints given + in sorted increasing order in `ends`, interpolate any missing + delta values in delta vector `deltas`. + + Returns fully filled-out delta vector.""" + + assert sorted(ends) == ends and len(coords) == (ends[-1] + 1 if ends else 0) + 4 + n = len(coords) + ends = ends + [n - 4, n - 3, n - 2, n - 1] + out = [] + start = 0 + for end in ends: + end += 1 + contour = iup_contour(deltas[start:end], coords[start:end]) + out.extend(contour) + start = end + + return out + + +# Optimizer + + +@cython.cfunc +@cython.inline +@cython.locals( + i=cython.int, + j=cython.int, + # tolerance=cython.double, # https://github.com/fonttools/fonttools/issues/3282 + x=cython.double, + y=cython.double, + p=cython.double, + q=cython.double, +) +@cython.returns(int) +def can_iup_in_between( + deltas: _DeltaSegment, + coords: _PointSegment, + i: Integral, + j: Integral, + tolerance: Real, +): # -> bool: + """Return true if the deltas for points at `i` and `j` (`i < j`) can be + successfully used to interpolate deltas for points in between them within + provided error tolerance.""" + + assert j - i >= 2 + interp = iup_segment(coords[i + 1 : j], coords[i], deltas[i], coords[j], deltas[j]) + deltas = deltas[i + 1 : j] + + return all( + abs(complex(x - p, y - q)) <= tolerance + for (x, y), (p, q) in zip(deltas, interp) + ) + + +@cython.locals( + cj=cython.double, + dj=cython.double, + lcj=cython.double, + ldj=cython.double, + ncj=cython.double, + ndj=cython.double, + force=cython.int, + forced=set, +) +def _iup_contour_bound_forced_set( + deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0 +) -> set: + """The forced set is a conservative set of points on the contour that must be encoded + explicitly (ie. cannot be interpolated). Calculating this set allows for significantly + speeding up the dynamic-programming, as well as resolve circularity in DP. + + The set is precise; that is, if an index is in the returned set, then there is no way + that IUP can generate delta for that point, given `coords` and `deltas`. + """ + assert len(deltas) == len(coords) + + n = len(deltas) + forced = set() + # Track "last" and "next" points on the contour as we sweep. + for i in range(len(deltas) - 1, -1, -1): + ld, lc = deltas[i - 1], coords[i - 1] + d, c = deltas[i], coords[i] + nd, nc = deltas[i - n + 1], coords[i - n + 1] + + for j in (0, 1): # For X and for Y + cj = c[j] + dj = d[j] + lcj = lc[j] + ldj = ld[j] + ncj = nc[j] + ndj = nd[j] + + if lcj <= ncj: + c1, c2 = lcj, ncj + d1, d2 = ldj, ndj + else: + c1, c2 = ncj, lcj + d1, d2 = ndj, ldj + + force = False + + # If the two coordinates are the same, then the interpolation + # algorithm produces the same delta if both deltas are equal, + # and zero if they differ. + # + # This test has to be before the next one. + if c1 == c2: + if abs(d1 - d2) > tolerance and abs(dj) > tolerance: + force = True + + # If coordinate for current point is between coordinate of adjacent + # points on the two sides, but the delta for current point is NOT + # between delta for those adjacent points (considering tolerance + # allowance), then there is no way that current point can be IUP-ed. + # Mark it forced. + elif c1 <= cj <= c2: # and c1 != c2 + if not (min(d1, d2) - tolerance <= dj <= max(d1, d2) + tolerance): + force = True + + # Otherwise, the delta should either match the closest, or have the + # same sign as the interpolation of the two deltas. + else: # cj < c1 or c2 < cj + if d1 != d2: + if cj < c1: + if ( + abs(dj) > tolerance + and abs(dj - d1) > tolerance + and ((dj - tolerance < d1) != (d1 < d2)) + ): + force = True + else: # c2 < cj + if ( + abs(dj) > tolerance + and abs(dj - d2) > tolerance + and ((d2 < dj + tolerance) != (d1 < d2)) + ): + force = True + + if force: + forced.add(i) + break + + return forced + + +@cython.locals( + i=cython.int, + j=cython.int, + best_cost=cython.double, + best_j=cython.int, + cost=cython.double, + forced=set, + tolerance=cython.double, +) +def _iup_contour_optimize_dp( + deltas: _DeltaSegment, + coords: _PointSegment, + forced=set(), + tolerance: Real = 0, + lookback: Integral = None, +): + """Straightforward Dynamic-Programming. For each index i, find least-costly encoding of + points 0 to i where i is explicitly encoded. We find this by considering all previous + explicit points j and check whether interpolation can fill points between j and i. + + Note that solution always encodes last point explicitly. Higher-level is responsible + for removing that restriction. + + As major speedup, we stop looking further whenever we see a "forced" point.""" + + n = len(deltas) + if lookback is None: + lookback = n + lookback = min(lookback, MAX_LOOKBACK) + costs = {-1: 0} + chain = {-1: None} + for i in range(0, n): + best_cost = costs[i - 1] + 1 + + costs[i] = best_cost + chain[i] = i - 1 + + if i - 1 in forced: + continue + + for j in range(i - 2, max(i - lookback, -2), -1): + cost = costs[j] + 1 + + if cost < best_cost and can_iup_in_between(deltas, coords, j, i, tolerance): + costs[i] = best_cost = cost + chain[i] = j + + if j in forced: + break + + return chain, costs + + +def _rot_list(l: list, k: int): + """Rotate list by k items forward. Ie. item at position 0 will be + at position k in returned list. Negative k is allowed.""" + n = len(l) + k %= n + if not k: + return l + return l[n - k :] + l[: n - k] + + +def _rot_set(s: set, k: int, n: int): + k %= n + if not k: + return s + return {(v + k) % n for v in s} + + +def iup_contour_optimize( + deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0.0 +) -> _DeltaOrNoneSegment: + """For contour with coordinates `coords`, optimize a set of delta + values `deltas` within error `tolerance`. + + Returns delta vector that has most number of None items instead of + the input delta. + """ + + n = len(deltas) + + # Get the easy cases out of the way: + + # If all are within tolerance distance of 0, encode nothing: + if all(abs(complex(*p)) <= tolerance for p in deltas): + return [None] * n + + # If there's exactly one point, return it: + if n == 1: + return deltas + + # If all deltas are exactly the same, return just one (the first one): + d0 = deltas[0] + if all(d0 == d for d in deltas): + return [d0] + [None] * (n - 1) + + # Else, solve the general problem using Dynamic Programming. + + forced = _iup_contour_bound_forced_set(deltas, coords, tolerance) + # The _iup_contour_optimize_dp() routine returns the optimal encoding + # solution given the constraint that the last point is always encoded. + # To remove this constraint, we use two different methods, depending on + # whether forced set is non-empty or not: + + # Debugging: Make the next if always take the second branch and observe + # if the font size changes (reduced); that would mean the forced-set + # has members it should not have. + if forced: + # Forced set is non-empty: rotate the contour start point + # such that the last point in the list is a forced point. + k = (n - 1) - max(forced) + assert k >= 0 + + deltas = _rot_list(deltas, k) + coords = _rot_list(coords, k) + forced = _rot_set(forced, k, n) + + # Debugging: Pass a set() instead of forced variable to the next call + # to exercise forced-set computation for under-counting. + chain, costs = _iup_contour_optimize_dp(deltas, coords, forced, tolerance) + + # Assemble solution. + solution = set() + i = n - 1 + while i is not None: + solution.add(i) + i = chain[i] + solution.remove(-1) + + # if not forced <= solution: + # print("coord", coords) + # print("deltas", deltas) + # print("len", len(deltas)) + assert forced <= solution, (forced, solution) + + deltas = [deltas[i] if i in solution else None for i in range(n)] + + deltas = _rot_list(deltas, -k) + else: + # Repeat the contour an extra time, solve the new case, then look for solutions of the + # circular n-length problem in the solution for new linear case. I cannot prove that + # this always produces the optimal solution... + chain, costs = _iup_contour_optimize_dp( + deltas + deltas, coords + coords, forced, tolerance, n + ) + best_sol, best_cost = None, n + 1 + + for start in range(n - 1, len(costs) - 1): + # Assemble solution. + solution = set() + i = start + while i > start - n: + solution.add(i % n) + i = chain[i] + if i == start - n: + cost = costs[start] - costs[start - n] + if cost <= best_cost: + best_sol, best_cost = solution, cost + + # if not forced <= best_sol: + # print("coord", coords) + # print("deltas", deltas) + # print("len", len(deltas)) + assert forced <= best_sol, (forced, best_sol) + + deltas = [deltas[i] if i in best_sol else None for i in range(n)] + + return deltas + + +def iup_delta_optimize( + deltas: _DeltaSegment, + coords: _PointSegment, + ends: _Endpoints, + tolerance: Real = 0.0, +) -> _DeltaOrNoneSegment: + """For the outline given in `coords`, with contour endpoints given + in sorted increasing order in `ends`, optimize a set of delta + values `deltas` within error `tolerance`. + + Returns delta vector that has most number of None items instead of + the input delta. + """ + assert sorted(ends) == ends and len(coords) == (ends[-1] + 1 if ends else 0) + 4 + n = len(coords) + ends = ends + [n - 4, n - 3, n - 2, n - 1] + out = [] + start = 0 + for end in ends: + contour = iup_contour_optimize( + deltas[start : end + 1], coords[start : end + 1], tolerance + ) + assert len(contour) == end - start + 1 + out.extend(contour) + start = end + 1 + + return out diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/merger.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/merger.py new file mode 100644 index 0000000000000000000000000000000000000000..8075a7fac9770cbc000f3a8b89d3caf53b9b0106 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/merger.py @@ -0,0 +1,1717 @@ +""" +Merge OpenType Layout tables (GDEF / GPOS / GSUB). +""" + +import os +import copy +import enum +from operator import ior +import logging +from fontTools.colorLib.builder import MAX_PAINT_COLR_LAYER_COUNT, LayerReuseCache +from fontTools.misc import classifyTools +from fontTools.misc.roundTools import otRound +from fontTools.misc.treeTools import build_n_ary_tree +from fontTools.ttLib.tables import otTables as ot +from fontTools.ttLib.tables import otBase as otBase +from fontTools.ttLib.tables.otConverters import BaseFixedValue +from fontTools.ttLib.tables.otTraverse import dfs_base_table +from fontTools.ttLib.tables.DefaultTable import DefaultTable +from fontTools.varLib import builder, models, varStore +from fontTools.varLib.models import nonNone, allNone, allEqual, allEqualTo, subList +from fontTools.varLib.varStore import VarStoreInstancer +from functools import reduce +from fontTools.otlLib.builder import buildSinglePos +from fontTools.otlLib.optimize.gpos import ( + _compression_level_from_env, + compact_pair_pos, +) + +log = logging.getLogger("fontTools.varLib.merger") + +from .errors import ( + ShouldBeConstant, + FoundANone, + MismatchedTypes, + NotANone, + LengthsDiffer, + KeysDiffer, + InconsistentGlyphOrder, + InconsistentExtensions, + InconsistentFormats, + UnsupportedFormat, + VarLibMergeError, +) + + +class Merger(object): + def __init__(self, font=None): + self.font = font + # mergeTables populates this from the parent's master ttfs + self.ttfs = None + + @classmethod + def merger(celf, clazzes, attrs=(None,)): + assert celf != Merger, "Subclass Merger instead." + if "mergers" not in celf.__dict__: + celf.mergers = {} + if type(clazzes) in (type, enum.EnumMeta): + clazzes = (clazzes,) + if type(attrs) == str: + attrs = (attrs,) + + def wrapper(method): + assert method.__name__ == "merge" + done = [] + for clazz in clazzes: + if clazz in done: + continue # Support multiple names of a clazz + done.append(clazz) + mergers = celf.mergers.setdefault(clazz, {}) + for attr in attrs: + assert attr not in mergers, ( + "Oops, class '%s' has merge function for '%s' defined already." + % (clazz.__name__, attr) + ) + mergers[attr] = method + return None + + return wrapper + + @classmethod + def mergersFor(celf, thing, _default={}): + typ = type(thing) + + for celf in celf.mro(): + mergers = getattr(celf, "mergers", None) + if mergers is None: + break + + m = celf.mergers.get(typ, None) + if m is not None: + return m + + return _default + + def mergeObjects(self, out, lst, exclude=()): + if hasattr(out, "ensureDecompiled"): + out.ensureDecompiled(recurse=False) + for item in lst: + if hasattr(item, "ensureDecompiled"): + item.ensureDecompiled(recurse=False) + keys = sorted(vars(out).keys()) + if not all(keys == sorted(vars(v).keys()) for v in lst): + raise KeysDiffer( + self, expected=keys, got=[sorted(vars(v).keys()) for v in lst] + ) + mergers = self.mergersFor(out) + defaultMerger = mergers.get("*", self.__class__.mergeThings) + try: + for key in keys: + if key in exclude: + continue + value = getattr(out, key) + values = [getattr(table, key) for table in lst] + mergerFunc = mergers.get(key, defaultMerger) + mergerFunc(self, value, values) + except VarLibMergeError as e: + e.stack.append("." + key) + raise + + def mergeLists(self, out, lst): + if not allEqualTo(out, lst, len): + raise LengthsDiffer(self, expected=len(out), got=[len(x) for x in lst]) + for i, (value, values) in enumerate(zip(out, zip(*lst))): + try: + self.mergeThings(value, values) + except VarLibMergeError as e: + e.stack.append("[%d]" % i) + raise + + def mergeThings(self, out, lst): + if not allEqualTo(out, lst, type): + raise MismatchedTypes( + self, expected=type(out).__name__, got=[type(x).__name__ for x in lst] + ) + mergerFunc = self.mergersFor(out).get(None, None) + if mergerFunc is not None: + mergerFunc(self, out, lst) + elif isinstance(out, enum.Enum): + # need to special-case Enums as have __dict__ but are not regular 'objects', + # otherwise mergeObjects/mergeThings get trapped in a RecursionError + if not allEqualTo(out, lst): + raise ShouldBeConstant(self, expected=out, got=lst) + elif hasattr(out, "__dict__"): + self.mergeObjects(out, lst) + elif isinstance(out, list): + self.mergeLists(out, lst) + else: + if not allEqualTo(out, lst): + raise ShouldBeConstant(self, expected=out, got=lst) + + def mergeTables(self, font, master_ttfs, tableTags): + for tag in tableTags: + if tag not in font: + continue + try: + self.ttfs = master_ttfs + self.mergeThings(font[tag], [m.get(tag) for m in master_ttfs]) + except VarLibMergeError as e: + e.stack.append(tag) + raise + + +# +# Aligning merger +# +class AligningMerger(Merger): + pass + + +@AligningMerger.merger(ot.GDEF, "GlyphClassDef") +def merge(merger, self, lst): + if self is None: + if not allNone(lst): + raise NotANone(merger, expected=None, got=lst) + return + + lst = [l.classDefs for l in lst] + self.classDefs = {} + # We only care about the .classDefs + self = self.classDefs + + allKeys = set() + allKeys.update(*[l.keys() for l in lst]) + for k in allKeys: + allValues = nonNone(l.get(k) for l in lst) + if not allEqual(allValues): + raise ShouldBeConstant( + merger, expected=allValues[0], got=lst, stack=["." + k] + ) + if not allValues: + self[k] = None + else: + self[k] = allValues[0] + + +def _SinglePosUpgradeToFormat2(self): + if self.Format == 2: + return self + + ret = ot.SinglePos() + ret.Format = 2 + ret.Coverage = self.Coverage + ret.ValueFormat = self.ValueFormat + ret.Value = [self.Value for _ in ret.Coverage.glyphs] + ret.ValueCount = len(ret.Value) + + return ret + + +def _merge_GlyphOrders(font, lst, values_lst=None, default=None): + """Takes font and list of glyph lists (must be sorted by glyph id), and returns + two things: + - Combined glyph list, + - If values_lst is None, return input glyph lists, but padded with None when a glyph + was missing in a list. Otherwise, return values_lst list-of-list, padded with None + to match combined glyph lists. + """ + if values_lst is None: + dict_sets = [set(l) for l in lst] + else: + dict_sets = [{g: v for g, v in zip(l, vs)} for l, vs in zip(lst, values_lst)] + combined = set() + combined.update(*dict_sets) + + sortKey = font.getReverseGlyphMap().__getitem__ + order = sorted(combined, key=sortKey) + # Make sure all input glyphsets were in proper order + if not all(sorted(vs, key=sortKey) == vs for vs in lst): + raise InconsistentGlyphOrder() + del combined + + paddedValues = None + if values_lst is None: + padded = [ + [glyph if glyph in dict_set else default for glyph in order] + for dict_set in dict_sets + ] + else: + assert len(lst) == len(values_lst) + padded = [ + [dict_set[glyph] if glyph in dict_set else default for glyph in order] + for dict_set in dict_sets + ] + return order, padded + + +@AligningMerger.merger(otBase.ValueRecord) +def merge(merger, self, lst): + # Code below sometimes calls us with self being + # a new object. Copy it from lst and recurse. + self.__dict__ = lst[0].__dict__.copy() + merger.mergeObjects(self, lst) + + +@AligningMerger.merger(ot.Anchor) +def merge(merger, self, lst): + # Code below sometimes calls us with self being + # a new object. Copy it from lst and recurse. + self.__dict__ = lst[0].__dict__.copy() + merger.mergeObjects(self, lst) + + +def _Lookup_SinglePos_get_effective_value(merger, subtables, glyph): + for self in subtables: + if ( + self is None + or type(self) != ot.SinglePos + or self.Coverage is None + or glyph not in self.Coverage.glyphs + ): + continue + if self.Format == 1: + return self.Value + elif self.Format == 2: + return self.Value[self.Coverage.glyphs.index(glyph)] + else: + raise UnsupportedFormat(merger, subtable="single positioning lookup") + return None + + +def _Lookup_PairPos_get_effective_value_pair( + merger, subtables, firstGlyph, secondGlyph +): + for self in subtables: + if ( + self is None + or type(self) != ot.PairPos + or self.Coverage is None + or firstGlyph not in self.Coverage.glyphs + ): + continue + if self.Format == 1: + ps = self.PairSet[self.Coverage.glyphs.index(firstGlyph)] + pvr = ps.PairValueRecord + for rec in pvr: # TODO Speed up + if rec.SecondGlyph == secondGlyph: + return rec + continue + elif self.Format == 2: + klass1 = self.ClassDef1.classDefs.get(firstGlyph, 0) + klass2 = self.ClassDef2.classDefs.get(secondGlyph, 0) + return self.Class1Record[klass1].Class2Record[klass2] + else: + raise UnsupportedFormat(merger, subtable="pair positioning lookup") + return None + + +@AligningMerger.merger(ot.SinglePos) +def merge(merger, self, lst): + self.ValueFormat = valueFormat = reduce(int.__or__, [l.ValueFormat for l in lst], 0) + if not (len(lst) == 1 or (valueFormat & ~0xF == 0)): + raise UnsupportedFormat(merger, subtable="single positioning lookup") + + # If all have same coverage table and all are format 1, + coverageGlyphs = self.Coverage.glyphs + if all(v.Format == 1 for v in lst) and all( + coverageGlyphs == v.Coverage.glyphs for v in lst + ): + self.Value = otBase.ValueRecord(valueFormat, self.Value) + if valueFormat != 0: + # If v.Value is None, it means a kerning of 0; we want + # it to participate in the model still. + # https://github.com/fonttools/fonttools/issues/3111 + merger.mergeThings( + self.Value, + [v.Value if v.Value is not None else otBase.ValueRecord() for v in lst], + ) + self.ValueFormat = self.Value.getFormat() + return + + # Upgrade everything to Format=2 + self.Format = 2 + lst = [_SinglePosUpgradeToFormat2(v) for v in lst] + + # Align them + glyphs, padded = _merge_GlyphOrders( + merger.font, [v.Coverage.glyphs for v in lst], [v.Value for v in lst] + ) + + self.Coverage.glyphs = glyphs + self.Value = [otBase.ValueRecord(valueFormat) for _ in glyphs] + self.ValueCount = len(self.Value) + + for i, values in enumerate(padded): + for j, glyph in enumerate(glyphs): + if values[j] is not None: + continue + # Fill in value from other subtables + # Note!!! This *might* result in behavior change if ValueFormat2-zeroedness + # is different between used subtable and current subtable! + # TODO(behdad) Check and warn if that happens? + v = _Lookup_SinglePos_get_effective_value( + merger, merger.lookup_subtables[i], glyph + ) + if v is None: + v = otBase.ValueRecord(valueFormat) + values[j] = v + + merger.mergeLists(self.Value, padded) + + # Merge everything else; though, there shouldn't be anything else. :) + merger.mergeObjects( + self, lst, exclude=("Format", "Coverage", "Value", "ValueCount", "ValueFormat") + ) + self.ValueFormat = reduce( + int.__or__, [v.getEffectiveFormat() for v in self.Value], 0 + ) + + +@AligningMerger.merger(ot.PairSet) +def merge(merger, self, lst): + # Align them + glyphs, padded = _merge_GlyphOrders( + merger.font, + [[v.SecondGlyph for v in vs.PairValueRecord] for vs in lst], + [vs.PairValueRecord for vs in lst], + ) + + self.PairValueRecord = pvrs = [] + for glyph in glyphs: + pvr = ot.PairValueRecord() + pvr.SecondGlyph = glyph + pvr.Value1 = ( + otBase.ValueRecord(merger.valueFormat1) if merger.valueFormat1 else None + ) + pvr.Value2 = ( + otBase.ValueRecord(merger.valueFormat2) if merger.valueFormat2 else None + ) + pvrs.append(pvr) + self.PairValueCount = len(self.PairValueRecord) + + for i, values in enumerate(padded): + for j, glyph in enumerate(glyphs): + # Fill in value from other subtables + v = ot.PairValueRecord() + v.SecondGlyph = glyph + if values[j] is not None: + vpair = values[j] + else: + vpair = _Lookup_PairPos_get_effective_value_pair( + merger, merger.lookup_subtables[i], self._firstGlyph, glyph + ) + if vpair is None: + v1, v2 = None, None + else: + v1 = getattr(vpair, "Value1", None) + v2 = getattr(vpair, "Value2", None) + v.Value1 = ( + otBase.ValueRecord(merger.valueFormat1, src=v1) + if merger.valueFormat1 + else None + ) + v.Value2 = ( + otBase.ValueRecord(merger.valueFormat2, src=v2) + if merger.valueFormat2 + else None + ) + values[j] = v + del self._firstGlyph + + merger.mergeLists(self.PairValueRecord, padded) + + +def _PairPosFormat1_merge(self, lst, merger): + assert allEqual( + [l.ValueFormat2 == 0 for l in lst if l.PairSet] + ), "Report bug against fonttools." + + # Merge everything else; makes sure Format is the same. + merger.mergeObjects( + self, + lst, + exclude=("Coverage", "PairSet", "PairSetCount", "ValueFormat1", "ValueFormat2"), + ) + + empty = ot.PairSet() + empty.PairValueRecord = [] + empty.PairValueCount = 0 + + # Align them + glyphs, padded = _merge_GlyphOrders( + merger.font, + [v.Coverage.glyphs for v in lst], + [v.PairSet for v in lst], + default=empty, + ) + + self.Coverage.glyphs = glyphs + self.PairSet = [ot.PairSet() for _ in glyphs] + self.PairSetCount = len(self.PairSet) + for glyph, ps in zip(glyphs, self.PairSet): + ps._firstGlyph = glyph + + merger.mergeLists(self.PairSet, padded) + + +def _ClassDef_invert(self, allGlyphs=None): + if isinstance(self, dict): + classDefs = self + else: + classDefs = self.classDefs if self and self.classDefs else {} + m = max(classDefs.values()) if classDefs else 0 + + ret = [] + for _ in range(m + 1): + ret.append(set()) + + for k, v in classDefs.items(): + ret[v].add(k) + + # Class-0 is special. It's "everything else". + if allGlyphs is None: + ret[0] = None + else: + # Limit all classes to glyphs in allGlyphs. + # Collect anything without a non-zero class into class=zero. + ret[0] = class0 = set(allGlyphs) + for s in ret[1:]: + s.intersection_update(class0) + class0.difference_update(s) + + return ret + + +def _ClassDef_merge_classify(lst, allGlyphses=None): + self = ot.ClassDef() + self.classDefs = classDefs = {} + allGlyphsesWasNone = allGlyphses is None + if allGlyphsesWasNone: + allGlyphses = [None] * len(lst) + + classifier = classifyTools.Classifier() + for classDef, allGlyphs in zip(lst, allGlyphses): + sets = _ClassDef_invert(classDef, allGlyphs) + if allGlyphs is None: + sets = sets[1:] + classifier.update(sets) + classes = classifier.getClasses() + + if allGlyphsesWasNone: + classes.insert(0, set()) + + for i, classSet in enumerate(classes): + if i == 0: + continue + for g in classSet: + classDefs[g] = i + + return self, classes + + +def _PairPosFormat2_align_matrices(self, lst, font, transparent=False): + matrices = [l.Class1Record for l in lst] + + # Align first classes + self.ClassDef1, classes = _ClassDef_merge_classify( + [l.ClassDef1 for l in lst], [l.Coverage.glyphs for l in lst] + ) + self.Class1Count = len(classes) + new_matrices = [] + for l, matrix in zip(lst, matrices): + nullRow = None + coverage = set(l.Coverage.glyphs) + classDef1 = l.ClassDef1.classDefs + class1Records = [] + for classSet in classes: + exemplarGlyph = next(iter(classSet)) + if exemplarGlyph not in coverage: + # Follow-up to e6125b353e1f54a0280ded5434b8e40d042de69f, + # Fixes https://github.com/googlei18n/fontmake/issues/470 + # Again, revert 8d441779e5afc664960d848f62c7acdbfc71d7b9 + # when merger becomes selfless. + nullRow = None + if nullRow is None: + nullRow = ot.Class1Record() + class2records = nullRow.Class2Record = [] + # TODO: When merger becomes selfless, revert e6125b353e1f54a0280ded5434b8e40d042de69f + for _ in range(l.Class2Count): + if transparent: + rec2 = None + else: + rec2 = ot.Class2Record() + rec2.Value1 = ( + otBase.ValueRecord(self.ValueFormat1) + if self.ValueFormat1 + else None + ) + rec2.Value2 = ( + otBase.ValueRecord(self.ValueFormat2) + if self.ValueFormat2 + else None + ) + class2records.append(rec2) + rec1 = nullRow + else: + klass = classDef1.get(exemplarGlyph, 0) + rec1 = matrix[klass] # TODO handle out-of-range? + class1Records.append(rec1) + new_matrices.append(class1Records) + matrices = new_matrices + del new_matrices + + # Align second classes + self.ClassDef2, classes = _ClassDef_merge_classify([l.ClassDef2 for l in lst]) + self.Class2Count = len(classes) + new_matrices = [] + for l, matrix in zip(lst, matrices): + classDef2 = l.ClassDef2.classDefs + class1Records = [] + for rec1old in matrix: + oldClass2Records = rec1old.Class2Record + rec1new = ot.Class1Record() + class2Records = rec1new.Class2Record = [] + for classSet in classes: + if not classSet: # class=0 + rec2 = oldClass2Records[0] + else: + exemplarGlyph = next(iter(classSet)) + klass = classDef2.get(exemplarGlyph, 0) + rec2 = oldClass2Records[klass] + class2Records.append(copy.deepcopy(rec2)) + class1Records.append(rec1new) + new_matrices.append(class1Records) + matrices = new_matrices + del new_matrices + + return matrices + + +def _PairPosFormat2_merge(self, lst, merger): + assert allEqual( + [l.ValueFormat2 == 0 for l in lst if l.Class1Record] + ), "Report bug against fonttools." + + merger.mergeObjects( + self, + lst, + exclude=( + "Coverage", + "ClassDef1", + "Class1Count", + "ClassDef2", + "Class2Count", + "Class1Record", + "ValueFormat1", + "ValueFormat2", + ), + ) + + # Align coverages + glyphs, _ = _merge_GlyphOrders(merger.font, [v.Coverage.glyphs for v in lst]) + self.Coverage.glyphs = glyphs + + # Currently, if the coverage of PairPosFormat2 subtables are different, + # we do NOT bother walking down the subtable list when filling in new + # rows for alignment. As such, this is only correct if current subtable + # is the last subtable in the lookup. Ensure that. + # + # Note that our canonicalization process merges trailing PairPosFormat2's, + # so in reality this is rare. + for l, subtables in zip(lst, merger.lookup_subtables): + if l.Coverage.glyphs != glyphs: + assert l == subtables[-1] + + matrices = _PairPosFormat2_align_matrices(self, lst, merger.font) + + self.Class1Record = list(matrices[0]) # TODO move merger to be selfless + merger.mergeLists(self.Class1Record, matrices) + + +@AligningMerger.merger(ot.PairPos) +def merge(merger, self, lst): + merger.valueFormat1 = self.ValueFormat1 = reduce( + int.__or__, [l.ValueFormat1 for l in lst], 0 + ) + merger.valueFormat2 = self.ValueFormat2 = reduce( + int.__or__, [l.ValueFormat2 for l in lst], 0 + ) + + if self.Format == 1: + _PairPosFormat1_merge(self, lst, merger) + elif self.Format == 2: + _PairPosFormat2_merge(self, lst, merger) + else: + raise UnsupportedFormat(merger, subtable="pair positioning lookup") + + del merger.valueFormat1, merger.valueFormat2 + + # Now examine the list of value records, and update to the union of format values, + # as merge might have created new values. + vf1 = 0 + vf2 = 0 + if self.Format == 1: + for pairSet in self.PairSet: + for pairValueRecord in pairSet.PairValueRecord: + pv1 = getattr(pairValueRecord, "Value1", None) + if pv1 is not None: + vf1 |= pv1.getFormat() + pv2 = getattr(pairValueRecord, "Value2", None) + if pv2 is not None: + vf2 |= pv2.getFormat() + elif self.Format == 2: + for class1Record in self.Class1Record: + for class2Record in class1Record.Class2Record: + pv1 = getattr(class2Record, "Value1", None) + if pv1 is not None: + vf1 |= pv1.getFormat() + pv2 = getattr(class2Record, "Value2", None) + if pv2 is not None: + vf2 |= pv2.getFormat() + self.ValueFormat1 = vf1 + self.ValueFormat2 = vf2 + + +def _MarkBasePosFormat1_merge(self, lst, merger, Mark="Mark", Base="Base"): + self.ClassCount = max(l.ClassCount for l in lst) + + MarkCoverageGlyphs, MarkRecords = _merge_GlyphOrders( + merger.font, + [getattr(l, Mark + "Coverage").glyphs for l in lst], + [getattr(l, Mark + "Array").MarkRecord for l in lst], + ) + getattr(self, Mark + "Coverage").glyphs = MarkCoverageGlyphs + + BaseCoverageGlyphs, BaseRecords = _merge_GlyphOrders( + merger.font, + [getattr(l, Base + "Coverage").glyphs for l in lst], + [getattr(getattr(l, Base + "Array"), Base + "Record") for l in lst], + ) + getattr(self, Base + "Coverage").glyphs = BaseCoverageGlyphs + + # MarkArray + records = [] + for g, glyphRecords in zip(MarkCoverageGlyphs, zip(*MarkRecords)): + allClasses = [r.Class for r in glyphRecords if r is not None] + + # TODO Right now we require that all marks have same class in + # all masters that cover them. This is not required. + # + # We can relax that by just requiring that all marks that have + # the same class in a master, have the same class in every other + # master. Indeed, if, say, a sparse master only covers one mark, + # that mark probably will get class 0, which would possibly be + # different from its class in other masters. + # + # We can even go further and reclassify marks to support any + # input. But, since, it's unlikely that two marks being both, + # say, "top" in one master, and one being "top" and other being + # "top-right" in another master, we shouldn't do that, as any + # failures in that case will probably signify mistakes in the + # input masters. + + if not allEqual(allClasses): + raise ShouldBeConstant(merger, expected=allClasses[0], got=allClasses) + else: + rec = ot.MarkRecord() + rec.Class = allClasses[0] + allAnchors = [None if r is None else r.MarkAnchor for r in glyphRecords] + if allNone(allAnchors): + anchor = None + else: + anchor = ot.Anchor() + anchor.Format = 1 + merger.mergeThings(anchor, allAnchors) + rec.MarkAnchor = anchor + records.append(rec) + array = ot.MarkArray() + array.MarkRecord = records + array.MarkCount = len(records) + setattr(self, Mark + "Array", array) + + # BaseArray + records = [] + for g, glyphRecords in zip(BaseCoverageGlyphs, zip(*BaseRecords)): + if allNone(glyphRecords): + rec = None + else: + rec = getattr(ot, Base + "Record")() + anchors = [] + setattr(rec, Base + "Anchor", anchors) + glyphAnchors = [ + [] if r is None else getattr(r, Base + "Anchor") for r in glyphRecords + ] + for l in glyphAnchors: + l.extend([None] * (self.ClassCount - len(l))) + for allAnchors in zip(*glyphAnchors): + if allNone(allAnchors): + anchor = None + else: + anchor = ot.Anchor() + anchor.Format = 1 + merger.mergeThings(anchor, allAnchors) + anchors.append(anchor) + records.append(rec) + array = getattr(ot, Base + "Array")() + setattr(array, Base + "Record", records) + setattr(array, Base + "Count", len(records)) + setattr(self, Base + "Array", array) + + +@AligningMerger.merger(ot.MarkBasePos) +def merge(merger, self, lst): + if not allEqualTo(self.Format, (l.Format for l in lst)): + raise InconsistentFormats( + merger, + subtable="mark-to-base positioning lookup", + expected=self.Format, + got=[l.Format for l in lst], + ) + if self.Format == 1: + _MarkBasePosFormat1_merge(self, lst, merger) + else: + raise UnsupportedFormat(merger, subtable="mark-to-base positioning lookup") + + +@AligningMerger.merger(ot.MarkMarkPos) +def merge(merger, self, lst): + if not allEqualTo(self.Format, (l.Format for l in lst)): + raise InconsistentFormats( + merger, + subtable="mark-to-mark positioning lookup", + expected=self.Format, + got=[l.Format for l in lst], + ) + if self.Format == 1: + _MarkBasePosFormat1_merge(self, lst, merger, "Mark1", "Mark2") + else: + raise UnsupportedFormat(merger, subtable="mark-to-mark positioning lookup") + + +def _PairSet_flatten(lst, font): + self = ot.PairSet() + self.Coverage = ot.Coverage() + + # Align them + glyphs, padded = _merge_GlyphOrders( + font, + [[v.SecondGlyph for v in vs.PairValueRecord] for vs in lst], + [vs.PairValueRecord for vs in lst], + ) + + self.Coverage.glyphs = glyphs + self.PairValueRecord = pvrs = [] + for values in zip(*padded): + for v in values: + if v is not None: + pvrs.append(v) + break + else: + assert False + self.PairValueCount = len(self.PairValueRecord) + + return self + + +def _Lookup_PairPosFormat1_subtables_flatten(lst, font): + assert allEqual( + [l.ValueFormat2 == 0 for l in lst if l.PairSet] + ), "Report bug against fonttools." + + self = ot.PairPos() + self.Format = 1 + self.Coverage = ot.Coverage() + self.ValueFormat1 = reduce(int.__or__, [l.ValueFormat1 for l in lst], 0) + self.ValueFormat2 = reduce(int.__or__, [l.ValueFormat2 for l in lst], 0) + + # Align them + glyphs, padded = _merge_GlyphOrders( + font, [v.Coverage.glyphs for v in lst], [v.PairSet for v in lst] + ) + + self.Coverage.glyphs = glyphs + self.PairSet = [ + _PairSet_flatten([v for v in values if v is not None], font) + for values in zip(*padded) + ] + self.PairSetCount = len(self.PairSet) + return self + + +def _Lookup_PairPosFormat2_subtables_flatten(lst, font): + assert allEqual( + [l.ValueFormat2 == 0 for l in lst if l.Class1Record] + ), "Report bug against fonttools." + + self = ot.PairPos() + self.Format = 2 + self.Coverage = ot.Coverage() + self.ValueFormat1 = reduce(int.__or__, [l.ValueFormat1 for l in lst], 0) + self.ValueFormat2 = reduce(int.__or__, [l.ValueFormat2 for l in lst], 0) + + # Align them + glyphs, _ = _merge_GlyphOrders(font, [v.Coverage.glyphs for v in lst]) + self.Coverage.glyphs = glyphs + + matrices = _PairPosFormat2_align_matrices(self, lst, font, transparent=True) + + matrix = self.Class1Record = [] + for rows in zip(*matrices): + row = ot.Class1Record() + matrix.append(row) + row.Class2Record = [] + row = row.Class2Record + for cols in zip(*list(r.Class2Record for r in rows)): + col = next(iter(c for c in cols if c is not None)) + row.append(col) + + return self + + +def _Lookup_PairPos_subtables_canonicalize(lst, font): + """Merge multiple Format1 subtables at the beginning of lst, + and merge multiple consecutive Format2 subtables that have the same + Class2 (ie. were split because of offset overflows). Returns new list.""" + lst = list(lst) + + l = len(lst) + i = 0 + while i < l and lst[i].Format == 1: + i += 1 + lst[:i] = [_Lookup_PairPosFormat1_subtables_flatten(lst[:i], font)] + + l = len(lst) + i = l + while i > 0 and lst[i - 1].Format == 2: + i -= 1 + lst[i:] = [_Lookup_PairPosFormat2_subtables_flatten(lst[i:], font)] + + return lst + + +def _Lookup_SinglePos_subtables_flatten(lst, font, min_inclusive_rec_format): + glyphs, _ = _merge_GlyphOrders(font, [v.Coverage.glyphs for v in lst], None) + num_glyphs = len(glyphs) + new = ot.SinglePos() + new.Format = 2 + new.ValueFormat = min_inclusive_rec_format + new.Coverage = ot.Coverage() + new.Coverage.glyphs = glyphs + new.ValueCount = num_glyphs + new.Value = [None] * num_glyphs + for singlePos in lst: + if singlePos.Format == 1: + val_rec = singlePos.Value + for gname in singlePos.Coverage.glyphs: + i = glyphs.index(gname) + new.Value[i] = copy.deepcopy(val_rec) + elif singlePos.Format == 2: + for j, gname in enumerate(singlePos.Coverage.glyphs): + val_rec = singlePos.Value[j] + i = glyphs.index(gname) + new.Value[i] = copy.deepcopy(val_rec) + return [new] + + +@AligningMerger.merger(ot.CursivePos) +def merge(merger, self, lst): + # Align them + glyphs, padded = _merge_GlyphOrders( + merger.font, + [l.Coverage.glyphs for l in lst], + [l.EntryExitRecord for l in lst], + ) + + self.Format = 1 + self.Coverage = ot.Coverage() + self.Coverage.glyphs = glyphs + self.EntryExitRecord = [] + for _ in glyphs: + rec = ot.EntryExitRecord() + rec.EntryAnchor = ot.Anchor() + rec.EntryAnchor.Format = 1 + rec.ExitAnchor = ot.Anchor() + rec.ExitAnchor.Format = 1 + self.EntryExitRecord.append(rec) + merger.mergeLists(self.EntryExitRecord, padded) + self.EntryExitCount = len(self.EntryExitRecord) + + +@AligningMerger.merger(ot.EntryExitRecord) +def merge(merger, self, lst): + if all(master.EntryAnchor is None for master in lst): + self.EntryAnchor = None + if all(master.ExitAnchor is None for master in lst): + self.ExitAnchor = None + merger.mergeObjects(self, lst) + + +@AligningMerger.merger(ot.Lookup) +def merge(merger, self, lst): + subtables = merger.lookup_subtables = [l.SubTable for l in lst] + + # Remove Extension subtables + for l, sts in list(zip(lst, subtables)) + [(self, self.SubTable)]: + if not sts: + continue + if sts[0].__class__.__name__.startswith("Extension"): + if not allEqual([st.__class__ for st in sts]): + raise InconsistentExtensions( + merger, + expected="Extension", + got=[st.__class__.__name__ for st in sts], + ) + if not allEqual([st.ExtensionLookupType for st in sts]): + raise InconsistentExtensions(merger) + l.LookupType = sts[0].ExtensionLookupType + new_sts = [st.ExtSubTable for st in sts] + del sts[:] + sts.extend(new_sts) + + isPairPos = self.SubTable and isinstance(self.SubTable[0], ot.PairPos) + + if isPairPos: + # AFDKO and feaLib sometimes generate two Format1 subtables instead of one. + # Merge those before continuing. + # https://github.com/fonttools/fonttools/issues/719 + self.SubTable = _Lookup_PairPos_subtables_canonicalize( + self.SubTable, merger.font + ) + subtables = merger.lookup_subtables = [ + _Lookup_PairPos_subtables_canonicalize(st, merger.font) for st in subtables + ] + else: + isSinglePos = self.SubTable and isinstance(self.SubTable[0], ot.SinglePos) + if isSinglePos: + numSubtables = [len(st) for st in subtables] + if not all([nums == numSubtables[0] for nums in numSubtables]): + # Flatten list of SinglePos subtables to single Format 2 subtable, + # with all value records set to the rec format type. + # We use buildSinglePos() to optimize the lookup after merging. + valueFormatList = [t.ValueFormat for st in subtables for t in st] + # Find the minimum value record that can accomodate all the singlePos subtables. + mirf = reduce(ior, valueFormatList) + self.SubTable = _Lookup_SinglePos_subtables_flatten( + self.SubTable, merger.font, mirf + ) + subtables = merger.lookup_subtables = [ + _Lookup_SinglePos_subtables_flatten(st, merger.font, mirf) + for st in subtables + ] + flattened = True + else: + flattened = False + + merger.mergeLists(self.SubTable, subtables) + self.SubTableCount = len(self.SubTable) + + if isPairPos: + # If format-1 subtable created during canonicalization is empty, remove it. + assert len(self.SubTable) >= 1 and self.SubTable[0].Format == 1 + if not self.SubTable[0].Coverage.glyphs: + self.SubTable.pop(0) + self.SubTableCount -= 1 + + # If format-2 subtable created during canonicalization is empty, remove it. + assert len(self.SubTable) >= 1 and self.SubTable[-1].Format == 2 + if not self.SubTable[-1].Coverage.glyphs: + self.SubTable.pop(-1) + self.SubTableCount -= 1 + + # Compact the merged subtables + # This is a good moment to do it because the compaction should create + # smaller subtables, which may prevent overflows from happening. + # Keep reading the value from the ENV until ufo2ft switches to the config system + level = merger.font.cfg.get( + "fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL", + default=_compression_level_from_env(), + ) + if level != 0: + log.info("Compacting GPOS...") + self.SubTable = compact_pair_pos(merger.font, level, self.SubTable) + self.SubTableCount = len(self.SubTable) + + elif isSinglePos and flattened: + singlePosTable = self.SubTable[0] + glyphs = singlePosTable.Coverage.glyphs + # We know that singlePosTable is Format 2, as this is set + # in _Lookup_SinglePos_subtables_flatten. + singlePosMapping = { + gname: valRecord for gname, valRecord in zip(glyphs, singlePosTable.Value) + } + self.SubTable = buildSinglePos( + singlePosMapping, merger.font.getReverseGlyphMap() + ) + merger.mergeObjects(self, lst, exclude=["SubTable", "SubTableCount"]) + + del merger.lookup_subtables + + +# +# InstancerMerger +# + + +class InstancerMerger(AligningMerger): + """A merger that takes multiple master fonts, and instantiates + an instance.""" + + def __init__(self, font, model, location): + Merger.__init__(self, font) + self.model = model + self.location = location + self.masterScalars = model.getMasterScalars(location) + + +@InstancerMerger.merger(ot.CaretValue) +def merge(merger, self, lst): + assert self.Format == 1 + Coords = [a.Coordinate for a in lst] + model = merger.model + masterScalars = merger.masterScalars + self.Coordinate = otRound( + model.interpolateFromValuesAndScalars(Coords, masterScalars) + ) + + +@InstancerMerger.merger(ot.Anchor) +def merge(merger, self, lst): + assert self.Format == 1 + XCoords = [a.XCoordinate for a in lst] + YCoords = [a.YCoordinate for a in lst] + model = merger.model + masterScalars = merger.masterScalars + self.XCoordinate = otRound( + model.interpolateFromValuesAndScalars(XCoords, masterScalars) + ) + self.YCoordinate = otRound( + model.interpolateFromValuesAndScalars(YCoords, masterScalars) + ) + + +@InstancerMerger.merger(otBase.ValueRecord) +def merge(merger, self, lst): + model = merger.model + masterScalars = merger.masterScalars + # TODO Handle differing valueformats + for name, tableName in [ + ("XAdvance", "XAdvDevice"), + ("YAdvance", "YAdvDevice"), + ("XPlacement", "XPlaDevice"), + ("YPlacement", "YPlaDevice"), + ]: + assert not hasattr(self, tableName) + + if hasattr(self, name): + values = [getattr(a, name, 0) for a in lst] + value = otRound( + model.interpolateFromValuesAndScalars(values, masterScalars) + ) + setattr(self, name, value) + + +# +# MutatorMerger +# + + +class MutatorMerger(AligningMerger): + """A merger that takes a variable font, and instantiates + an instance. While there's no "merging" to be done per se, + the operation can benefit from many operations that the + aligning merger does.""" + + def __init__(self, font, instancer, deleteVariations=True): + Merger.__init__(self, font) + self.instancer = instancer + self.deleteVariations = deleteVariations + + +@MutatorMerger.merger((ot.CaretValue, ot.BaseCoord)) +def merge(merger, self, lst): + # Hack till we become selfless. + self.__dict__ = lst[0].__dict__.copy() + + if self.Format != 3: + return + + instancer = merger.instancer + dev = self.DeviceTable + if merger.deleteVariations: + del self.DeviceTable + if dev: + assert dev.DeltaFormat == 0x8000 + varidx = (dev.StartSize << 16) + dev.EndSize + delta = otRound(instancer[varidx]) + self.Coordinate += delta + + if merger.deleteVariations: + self.Format = 1 + + +@MutatorMerger.merger(ot.Anchor) +def merge(merger, self, lst): + # Hack till we become selfless. + self.__dict__ = lst[0].__dict__.copy() + + if self.Format != 3: + return + + instancer = merger.instancer + for v in "XY": + tableName = v + "DeviceTable" + if not hasattr(self, tableName): + continue + dev = getattr(self, tableName) + if merger.deleteVariations: + delattr(self, tableName) + if dev is None: + continue + + assert dev.DeltaFormat == 0x8000 + varidx = (dev.StartSize << 16) + dev.EndSize + delta = otRound(instancer[varidx]) + + attr = v + "Coordinate" + setattr(self, attr, getattr(self, attr) + delta) + + if merger.deleteVariations: + self.Format = 1 + + +@MutatorMerger.merger(otBase.ValueRecord) +def merge(merger, self, lst): + # Hack till we become selfless. + self.__dict__ = lst[0].__dict__.copy() + + instancer = merger.instancer + for name, tableName in [ + ("XAdvance", "XAdvDevice"), + ("YAdvance", "YAdvDevice"), + ("XPlacement", "XPlaDevice"), + ("YPlacement", "YPlaDevice"), + ]: + if not hasattr(self, tableName): + continue + dev = getattr(self, tableName) + if merger.deleteVariations: + delattr(self, tableName) + if dev is None: + continue + + assert dev.DeltaFormat == 0x8000 + varidx = (dev.StartSize << 16) + dev.EndSize + delta = otRound(instancer[varidx]) + + setattr(self, name, getattr(self, name, 0) + delta) + + +# +# VariationMerger +# + + +class VariationMerger(AligningMerger): + """A merger that takes multiple master fonts, and builds a + variable font.""" + + def __init__(self, model, axisTags, font): + Merger.__init__(self, font) + self.store_builder = varStore.OnlineVarStoreBuilder(axisTags) + self.setModel(model) + + def setModel(self, model): + self.model = model + self.store_builder.setModel(model) + + def mergeThings(self, out, lst): + masterModel = None + origTTFs = None + if None in lst: + if allNone(lst): + if out is not None: + raise FoundANone(self, got=lst) + return + + # temporarily subset the list of master ttfs to the ones for which + # master values are not None + origTTFs = self.ttfs + if self.ttfs: + self.ttfs = subList([v is not None for v in lst], self.ttfs) + + masterModel = self.model + model, lst = masterModel.getSubModel(lst) + self.setModel(model) + + super(VariationMerger, self).mergeThings(out, lst) + + if masterModel: + self.setModel(masterModel) + if origTTFs: + self.ttfs = origTTFs + + +def buildVarDevTable(store_builder, master_values): + if allEqual(master_values): + return master_values[0], None + base, varIdx = store_builder.storeMasters(master_values) + return base, builder.buildVarDevTable(varIdx) + + +@VariationMerger.merger(ot.BaseCoord) +def merge(merger, self, lst): + if self.Format != 1: + raise UnsupportedFormat(merger, subtable="a baseline coordinate") + self.Coordinate, DeviceTable = buildVarDevTable( + merger.store_builder, [a.Coordinate for a in lst] + ) + if DeviceTable: + self.Format = 3 + self.DeviceTable = DeviceTable + + +@VariationMerger.merger(ot.CaretValue) +def merge(merger, self, lst): + if self.Format != 1: + raise UnsupportedFormat(merger, subtable="a caret") + self.Coordinate, DeviceTable = buildVarDevTable( + merger.store_builder, [a.Coordinate for a in lst] + ) + if DeviceTable: + self.Format = 3 + self.DeviceTable = DeviceTable + + +@VariationMerger.merger(ot.Anchor) +def merge(merger, self, lst): + if self.Format != 1: + raise UnsupportedFormat(merger, subtable="an anchor") + self.XCoordinate, XDeviceTable = buildVarDevTable( + merger.store_builder, [a.XCoordinate for a in lst] + ) + self.YCoordinate, YDeviceTable = buildVarDevTable( + merger.store_builder, [a.YCoordinate for a in lst] + ) + if XDeviceTable or YDeviceTable: + self.Format = 3 + self.XDeviceTable = XDeviceTable + self.YDeviceTable = YDeviceTable + + +@VariationMerger.merger(otBase.ValueRecord) +def merge(merger, self, lst): + for name, tableName in [ + ("XAdvance", "XAdvDevice"), + ("YAdvance", "YAdvDevice"), + ("XPlacement", "XPlaDevice"), + ("YPlacement", "YPlaDevice"), + ]: + if hasattr(self, name): + value, deviceTable = buildVarDevTable( + merger.store_builder, [getattr(a, name, 0) for a in lst] + ) + setattr(self, name, value) + if deviceTable: + setattr(self, tableName, deviceTable) + + +class COLRVariationMerger(VariationMerger): + """A specialized VariationMerger that takes multiple master fonts containing + COLRv1 tables, and builds a variable COLR font. + + COLR tables are special in that variable subtables can be associated with + multiple delta-set indices (via VarIndexBase). + They also contain tables that must change their type (not simply the Format) + as they become variable (e.g. Affine2x3 -> VarAffine2x3) so this merger takes + care of that too. + """ + + def __init__(self, model, axisTags, font, allowLayerReuse=True): + VariationMerger.__init__(self, model, axisTags, font) + # maps {tuple(varIdxes): VarIndexBase} to facilitate reuse of VarIndexBase + # between variable tables with same varIdxes. + self.varIndexCache = {} + # flat list of all the varIdxes generated while merging + self.varIdxes = [] + # set of id()s of the subtables that contain variations after merging + # and need to be upgraded to the associated VarType. + self.varTableIds = set() + # we keep these around for rebuilding a LayerList while merging PaintColrLayers + self.layers = [] + self.layerReuseCache = None + if allowLayerReuse: + self.layerReuseCache = LayerReuseCache() + # flag to ensure BaseGlyphList is fully merged before LayerList gets processed + self._doneBaseGlyphs = False + + def mergeTables(self, font, master_ttfs, tableTags=("COLR",)): + if "COLR" in tableTags and "COLR" in font: + # The merger modifies the destination COLR table in-place. If this contains + # multiple PaintColrLayers referencing the same layers from LayerList, it's + # a problem because we may risk modifying the same paint more than once, or + # worse, fail while attempting to do that. + # We don't know whether the master COLR table was built with layer reuse + # disabled, thus to be safe we rebuild its LayerList so that it contains only + # unique layers referenced from non-overlapping PaintColrLayers throughout + # the base paint graphs. + self.expandPaintColrLayers(font["COLR"].table) + VariationMerger.mergeTables(self, font, master_ttfs, tableTags) + + def checkFormatEnum(self, out, lst, validate=lambda _: True): + fmt = out.Format + formatEnum = out.formatEnum + ok = False + try: + fmt = formatEnum(fmt) + except ValueError: + pass + else: + ok = validate(fmt) + if not ok: + raise UnsupportedFormat(self, subtable=type(out).__name__, value=fmt) + expected = fmt + got = [] + for v in lst: + fmt = getattr(v, "Format", None) + try: + fmt = formatEnum(fmt) + except ValueError: + pass + got.append(fmt) + if not allEqualTo(expected, got): + raise InconsistentFormats( + self, + subtable=type(out).__name__, + expected=expected, + got=got, + ) + return expected + + def mergeSparseDict(self, out, lst): + for k in out.keys(): + try: + self.mergeThings(out[k], [v.get(k) for v in lst]) + except VarLibMergeError as e: + e.stack.append(f"[{k!r}]") + raise + + def mergeAttrs(self, out, lst, attrs): + for attr in attrs: + value = getattr(out, attr) + values = [getattr(item, attr) for item in lst] + try: + self.mergeThings(value, values) + except VarLibMergeError as e: + e.stack.append(f".{attr}") + raise + + def storeMastersForAttr(self, out, lst, attr): + master_values = [getattr(item, attr) for item in lst] + + # VarStore treats deltas for fixed-size floats as integers, so we + # must convert master values to int before storing them in the builder + # then back to float. + is_fixed_size_float = False + conv = out.getConverterByName(attr) + if isinstance(conv, BaseFixedValue): + is_fixed_size_float = True + master_values = [conv.toInt(v) for v in master_values] + + baseValue = master_values[0] + varIdx = ot.NO_VARIATION_INDEX + if not allEqual(master_values): + baseValue, varIdx = self.store_builder.storeMasters(master_values) + + if is_fixed_size_float: + baseValue = conv.fromInt(baseValue) + + return baseValue, varIdx + + def storeVariationIndices(self, varIdxes) -> int: + # try to reuse an existing VarIndexBase for the same varIdxes, or else + # create a new one + key = tuple(varIdxes) + varIndexBase = self.varIndexCache.get(key) + + if varIndexBase is None: + # scan for a full match anywhere in the self.varIdxes + for i in range(len(self.varIdxes) - len(varIdxes) + 1): + if self.varIdxes[i : i + len(varIdxes)] == varIdxes: + self.varIndexCache[key] = varIndexBase = i + break + + if varIndexBase is None: + # try find a partial match at the end of the self.varIdxes + for n in range(len(varIdxes) - 1, 0, -1): + if self.varIdxes[-n:] == varIdxes[:n]: + varIndexBase = len(self.varIdxes) - n + self.varIndexCache[key] = varIndexBase + self.varIdxes.extend(varIdxes[n:]) + break + + if varIndexBase is None: + # no match found, append at the end + self.varIndexCache[key] = varIndexBase = len(self.varIdxes) + self.varIdxes.extend(varIdxes) + + return varIndexBase + + def mergeVariableAttrs(self, out, lst, attrs) -> int: + varIndexBase = ot.NO_VARIATION_INDEX + varIdxes = [] + for attr in attrs: + baseValue, varIdx = self.storeMastersForAttr(out, lst, attr) + setattr(out, attr, baseValue) + varIdxes.append(varIdx) + + if any(v != ot.NO_VARIATION_INDEX for v in varIdxes): + varIndexBase = self.storeVariationIndices(varIdxes) + + return varIndexBase + + @classmethod + def convertSubTablesToVarType(cls, table): + for path in dfs_base_table( + table, + skip_root=True, + predicate=lambda path: ( + getattr(type(path[-1].value), "VarType", None) is not None + ), + ): + st = path[-1] + subTable = st.value + varType = type(subTable).VarType + newSubTable = varType() + newSubTable.__dict__.update(subTable.__dict__) + newSubTable.populateDefaults() + parent = path[-2].value + if st.index is not None: + getattr(parent, st.name)[st.index] = newSubTable + else: + setattr(parent, st.name, newSubTable) + + @staticmethod + def expandPaintColrLayers(colr): + """Rebuild LayerList without PaintColrLayers reuse. + + Each base paint graph is fully DFS-traversed (with exception of PaintColrGlyph + which are irrelevant for this); any layers referenced via PaintColrLayers are + collected into a new LayerList and duplicated when reuse is detected, to ensure + that all paints are distinct objects at the end of the process. + PaintColrLayers's FirstLayerIndex/NumLayers are updated so that no overlap + is left. Also, any consecutively nested PaintColrLayers are flattened. + The COLR table's LayerList is replaced with the new unique layers. + A side effect is also that any layer from the old LayerList which is not + referenced by any PaintColrLayers is dropped. + """ + if not colr.LayerList: + # if no LayerList, there's nothing to expand + return + uniqueLayerIDs = set() + newLayerList = [] + for rec in colr.BaseGlyphList.BaseGlyphPaintRecord: + frontier = [rec.Paint] + while frontier: + paint = frontier.pop() + if paint.Format == ot.PaintFormat.PaintColrGlyph: + # don't traverse these, we treat them as constant for merging + continue + elif paint.Format == ot.PaintFormat.PaintColrLayers: + # de-treeify any nested PaintColrLayers, append unique copies to + # the new layer list and update PaintColrLayers index/count + children = list(_flatten_layers(paint, colr)) + first_layer_index = len(newLayerList) + for layer in children: + if id(layer) in uniqueLayerIDs: + layer = copy.deepcopy(layer) + assert id(layer) not in uniqueLayerIDs + newLayerList.append(layer) + uniqueLayerIDs.add(id(layer)) + paint.FirstLayerIndex = first_layer_index + paint.NumLayers = len(children) + else: + children = paint.getChildren(colr) + frontier.extend(reversed(children)) + # sanity check all the new layers are distinct objects + assert len(newLayerList) == len(uniqueLayerIDs) + colr.LayerList.Paint = newLayerList + colr.LayerList.LayerCount = len(newLayerList) + + +@COLRVariationMerger.merger(ot.BaseGlyphList) +def merge(merger, self, lst): + # ignore BaseGlyphCount, allow sparse glyph sets across masters + out = {rec.BaseGlyph: rec for rec in self.BaseGlyphPaintRecord} + masters = [{rec.BaseGlyph: rec for rec in m.BaseGlyphPaintRecord} for m in lst] + + for i, g in enumerate(out.keys()): + try: + # missing base glyphs don't participate in the merge + merger.mergeThings(out[g], [v.get(g) for v in masters]) + except VarLibMergeError as e: + e.stack.append(f".BaseGlyphPaintRecord[{i}]") + e.cause["location"] = f"base glyph {g!r}" + raise + + merger._doneBaseGlyphs = True + + +@COLRVariationMerger.merger(ot.LayerList) +def merge(merger, self, lst): + # nothing to merge for LayerList, assuming we have already merged all PaintColrLayers + # found while traversing the paint graphs rooted at BaseGlyphPaintRecords. + assert merger._doneBaseGlyphs, "BaseGlyphList must be merged before LayerList" + # Simply flush the final list of layers and go home. + self.LayerCount = len(merger.layers) + self.Paint = merger.layers + + +def _flatten_layers(root, colr): + assert root.Format == ot.PaintFormat.PaintColrLayers + for paint in root.getChildren(colr): + if paint.Format == ot.PaintFormat.PaintColrLayers: + yield from _flatten_layers(paint, colr) + else: + yield paint + + +def _merge_PaintColrLayers(self, out, lst): + # we only enforce that the (flat) number of layers is the same across all masters + # but we allow FirstLayerIndex to differ to acommodate for sparse glyph sets. + + out_layers = list(_flatten_layers(out, self.font["COLR"].table)) + + # sanity check ttfs are subset to current values (see VariationMerger.mergeThings) + # before matching each master PaintColrLayers to its respective COLR by position + assert len(self.ttfs) == len(lst) + master_layerses = [ + list(_flatten_layers(lst[i], self.ttfs[i]["COLR"].table)) + for i in range(len(lst)) + ] + + try: + self.mergeLists(out_layers, master_layerses) + except VarLibMergeError as e: + # NOTE: This attribute doesn't actually exist in PaintColrLayers but it's + # handy to have it in the stack trace for debugging. + e.stack.append(".Layers") + raise + + # following block is very similar to LayerListBuilder._beforeBuildPaintColrLayers + # but I couldn't find a nice way to share the code between the two... + + if self.layerReuseCache is not None: + # successful reuse can make the list smaller + out_layers = self.layerReuseCache.try_reuse(out_layers) + + # if the list is still too big we need to tree-fy it + is_tree = len(out_layers) > MAX_PAINT_COLR_LAYER_COUNT + out_layers = build_n_ary_tree(out_layers, n=MAX_PAINT_COLR_LAYER_COUNT) + + # We now have a tree of sequences with Paint leaves. + # Convert the sequences into PaintColrLayers. + def listToColrLayers(paint): + if isinstance(paint, list): + layers = [listToColrLayers(l) for l in paint] + paint = ot.Paint() + paint.Format = int(ot.PaintFormat.PaintColrLayers) + paint.NumLayers = len(layers) + paint.FirstLayerIndex = len(self.layers) + self.layers.extend(layers) + if self.layerReuseCache is not None: + self.layerReuseCache.add(layers, paint.FirstLayerIndex) + return paint + + out_layers = [listToColrLayers(l) for l in out_layers] + + if len(out_layers) == 1 and out_layers[0].Format == ot.PaintFormat.PaintColrLayers: + # special case when the reuse cache finds a single perfect PaintColrLayers match + # (it can only come from a successful reuse, _flatten_layers has gotten rid of + # all nested PaintColrLayers already); we assign it directly and avoid creating + # an extra table + out.NumLayers = out_layers[0].NumLayers + out.FirstLayerIndex = out_layers[0].FirstLayerIndex + else: + out.NumLayers = len(out_layers) + out.FirstLayerIndex = len(self.layers) + + self.layers.extend(out_layers) + + # Register our parts for reuse provided we aren't a tree + # If we are a tree the leaves registered for reuse and that will suffice + if self.layerReuseCache is not None and not is_tree: + self.layerReuseCache.add(out_layers, out.FirstLayerIndex) + + +@COLRVariationMerger.merger((ot.Paint, ot.ClipBox)) +def merge(merger, self, lst): + fmt = merger.checkFormatEnum(self, lst, lambda fmt: not fmt.is_variable()) + + if fmt is ot.PaintFormat.PaintColrLayers: + _merge_PaintColrLayers(merger, self, lst) + return + + varFormat = fmt.as_variable() + + varAttrs = () + if varFormat is not None: + varAttrs = otBase.getVariableAttrs(type(self), varFormat) + staticAttrs = (c.name for c in self.getConverters() if c.name not in varAttrs) + + merger.mergeAttrs(self, lst, staticAttrs) + + varIndexBase = merger.mergeVariableAttrs(self, lst, varAttrs) + + subTables = [st.value for st in self.iterSubTables()] + + # Convert table to variable if itself has variations or any subtables have + isVariable = varIndexBase != ot.NO_VARIATION_INDEX or any( + id(table) in merger.varTableIds for table in subTables + ) + + if isVariable: + if varAttrs: + # Some PaintVar* don't have any scalar attributes that can vary, + # only indirect offsets to other variable subtables, thus have + # no VarIndexBase of their own (e.g. PaintVarTransform) + self.VarIndexBase = varIndexBase + + if subTables: + # Convert Affine2x3 -> VarAffine2x3, ColorLine -> VarColorLine, etc. + merger.convertSubTablesToVarType(self) + + assert varFormat is not None + self.Format = int(varFormat) + + +@COLRVariationMerger.merger((ot.Affine2x3, ot.ColorStop)) +def merge(merger, self, lst): + varType = type(self).VarType + + varAttrs = otBase.getVariableAttrs(varType) + staticAttrs = (c.name for c in self.getConverters() if c.name not in varAttrs) + + merger.mergeAttrs(self, lst, staticAttrs) + + varIndexBase = merger.mergeVariableAttrs(self, lst, varAttrs) + + if varIndexBase != ot.NO_VARIATION_INDEX: + self.VarIndexBase = varIndexBase + # mark as having variations so the parent table will convert to Var{Type} + merger.varTableIds.add(id(self)) + + +@COLRVariationMerger.merger(ot.ColorLine) +def merge(merger, self, lst): + merger.mergeAttrs(self, lst, (c.name for c in self.getConverters())) + + if any(id(stop) in merger.varTableIds for stop in self.ColorStop): + merger.convertSubTablesToVarType(self) + merger.varTableIds.add(id(self)) + + +@COLRVariationMerger.merger(ot.ClipList, "clips") +def merge(merger, self, lst): + # 'sparse' in that we allow non-default masters to omit ClipBox entries + # for some/all glyphs (i.e. they don't participate) + merger.mergeSparseDict(self, lst) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/models.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/models.py new file mode 100644 index 0000000000000000000000000000000000000000..1d09bb118273b25d61b34cb15ba09a65c2db1c1e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/models.py @@ -0,0 +1,662 @@ +"""Variation fonts interpolation models.""" + +from __future__ import annotations + +__all__ = [ + "normalizeValue", + "normalizeLocation", + "supportScalar", + "piecewiseLinearMap", + "VariationModel", +] + +from collections.abc import Mapping +from typing import TYPE_CHECKING +from fontTools.misc.roundTools import noRound +from .errors import VariationModelError + +if TYPE_CHECKING: + from typing import Mapping, Sequence + + +def nonNone(lst): + return [l for l in lst if l is not None] + + +def allNone(lst): + return all(l is None for l in lst) + + +def allEqualTo(ref, lst, mapper=None): + if mapper is None: + return all(ref == item for item in lst) + + mapped = mapper(ref) + return all(mapped == mapper(item) for item in lst) + + +def allEqual(lst, mapper=None): + if not lst: + return True + it = iter(lst) + try: + first = next(it) + except StopIteration: + return True + return allEqualTo(first, it, mapper=mapper) + + +def subList(truth, lst): + assert len(truth) == len(lst) + return [l for l, t in zip(lst, truth) if t] + + +def normalizeValue( + v: float, triple: Sequence[float], extrapolate: bool = False +) -> float: + """Normalizes value based on a min/default/max triple. + + >>> normalizeValue(400, (100, 400, 900)) + 0.0 + >>> normalizeValue(100, (100, 400, 900)) + -1.0 + >>> normalizeValue(650, (100, 400, 900)) + 0.5 + """ + lower, default, upper = triple + if not (lower <= default <= upper): + raise ValueError( + f"Invalid axis values, must be minimum, default, maximum: " + f"{lower:3.3f}, {default:3.3f}, {upper:3.3f}" + ) + if not extrapolate: + v = max(min(v, upper), lower) + + if v == default or lower == upper: + return 0.0 + + if (v < default and lower != default) or (v > default and upper == default): + return (v - default) / (default - lower) + else: + assert (v > default and upper != default) or ( + v < default and lower == default + ), f"Ooops... v={v}, triple=({lower}, {default}, {upper})" + return (v - default) / (upper - default) + + +def normalizeLocation( + location: Mapping[str, float], + axes: Mapping[str, tuple[float, float, float]], + extrapolate: bool = False, + *, + validate: bool = False, +) -> dict[str, float]: + """Normalizes location based on axis min/default/max values from axes. + + >>> axes = {"wght": (100, 400, 900)} + >>> normalizeLocation({"wght": 400}, axes) + {'wght': 0.0} + >>> normalizeLocation({"wght": 100}, axes) + {'wght': -1.0} + >>> normalizeLocation({"wght": 900}, axes) + {'wght': 1.0} + >>> normalizeLocation({"wght": 650}, axes) + {'wght': 0.5} + >>> normalizeLocation({"wght": 1000}, axes) + {'wght': 1.0} + >>> normalizeLocation({"wght": 0}, axes) + {'wght': -1.0} + >>> axes = {"wght": (0, 0, 1000)} + >>> normalizeLocation({"wght": 0}, axes) + {'wght': 0.0} + >>> normalizeLocation({"wght": -1}, axes) + {'wght': 0.0} + >>> normalizeLocation({"wght": 1000}, axes) + {'wght': 1.0} + >>> normalizeLocation({"wght": 500}, axes) + {'wght': 0.5} + >>> normalizeLocation({"wght": 1001}, axes) + {'wght': 1.0} + >>> axes = {"wght": (0, 1000, 1000)} + >>> normalizeLocation({"wght": 0}, axes) + {'wght': -1.0} + >>> normalizeLocation({"wght": -1}, axes) + {'wght': -1.0} + >>> normalizeLocation({"wght": 500}, axes) + {'wght': -0.5} + >>> normalizeLocation({"wght": 1000}, axes) + {'wght': 0.0} + >>> normalizeLocation({"wght": 1001}, axes) + {'wght': 0.0} + """ + if validate: + assert set(location.keys()) <= set(axes.keys()), set(location.keys()) - set( + axes.keys() + ) + out = {} + for tag, triple in axes.items(): + v = location.get(tag, triple[1]) + out[tag] = normalizeValue(v, triple, extrapolate=extrapolate) + return out + + +def supportScalar(location, support, ot=True, extrapolate=False, axisRanges=None): + """Returns the scalar multiplier at location, for a master + with support. If ot is True, then a peak value of zero + for support of an axis means "axis does not participate". That + is how OpenType Variation Font technology works. + + If extrapolate is True, axisRanges must be a dict that maps axis + names to (axisMin, axisMax) tuples. + + >>> supportScalar({}, {}) + 1.0 + >>> supportScalar({'wght':.2}, {}) + 1.0 + >>> supportScalar({'wght':.2}, {'wght':(0,2,3)}) + 0.1 + >>> supportScalar({'wght':2.5}, {'wght':(0,2,4)}) + 0.75 + >>> supportScalar({'wght':2.5, 'wdth':0}, {'wght':(0,2,4), 'wdth':(-1,0,+1)}) + 0.75 + >>> supportScalar({'wght':2.5, 'wdth':.5}, {'wght':(0,2,4), 'wdth':(-1,0,+1)}, ot=False) + 0.375 + >>> supportScalar({'wght':2.5, 'wdth':0}, {'wght':(0,2,4), 'wdth':(-1,0,+1)}) + 0.75 + >>> supportScalar({'wght':2.5, 'wdth':.5}, {'wght':(0,2,4), 'wdth':(-1,0,+1)}) + 0.75 + >>> supportScalar({'wght':3}, {'wght':(0,1,2)}, extrapolate=True, axisRanges={'wght':(0, 2)}) + -1.0 + >>> supportScalar({'wght':-1}, {'wght':(0,1,2)}, extrapolate=True, axisRanges={'wght':(0, 2)}) + -1.0 + >>> supportScalar({'wght':3}, {'wght':(0,2,2)}, extrapolate=True, axisRanges={'wght':(0, 2)}) + 1.5 + >>> supportScalar({'wght':-1}, {'wght':(0,2,2)}, extrapolate=True, axisRanges={'wght':(0, 2)}) + -0.5 + """ + if extrapolate and axisRanges is None: + raise TypeError("axisRanges must be passed when extrapolate is True") + scalar = 1.0 + for axis, (lower, peak, upper) in support.items(): + if ot: + # OpenType-specific case handling + if peak == 0.0: + continue + if lower > peak or peak > upper: + continue + if lower < 0.0 and upper > 0.0: + continue + v = location.get(axis, 0.0) + else: + assert axis in location + v = location[axis] + if v == peak: + continue + + if extrapolate: + axisMin, axisMax = axisRanges[axis] + if v < axisMin and lower <= axisMin: + if peak <= axisMin and peak < upper: + scalar *= (v - upper) / (peak - upper) + continue + elif axisMin < peak: + scalar *= (v - lower) / (peak - lower) + continue + elif axisMax < v and axisMax <= upper: + if axisMax <= peak and lower < peak: + scalar *= (v - lower) / (peak - lower) + continue + elif peak < axisMax: + scalar *= (v - upper) / (peak - upper) + continue + + if v <= lower or upper <= v: + scalar = 0.0 + break + + if v < peak: + scalar *= (v - lower) / (peak - lower) + else: # v > peak + scalar *= (v - upper) / (peak - upper) + return scalar + + +class VariationModel(object): + """Locations must have the base master at the origin (ie. 0). + + If axis-ranges are not provided, values are assumed to be normalized to + the range [-1, 1]. + + If the extrapolate argument is set to True, then values are extrapolated + outside the axis range. + + >>> from pprint import pprint + >>> axisRanges = {'wght': (-180, +180), 'wdth': (-1, +1)} + >>> locations = [ \ + {'wght':100}, \ + {'wght':-100}, \ + {'wght':-180}, \ + {'wdth':+.3}, \ + {'wght':+120,'wdth':.3}, \ + {'wght':+120,'wdth':.2}, \ + {}, \ + {'wght':+180,'wdth':.3}, \ + {'wght':+180}, \ + ] + >>> model = VariationModel(locations, axisOrder=['wght'], axisRanges=axisRanges) + >>> pprint(model.locations) + [{}, + {'wght': -100}, + {'wght': -180}, + {'wght': 100}, + {'wght': 180}, + {'wdth': 0.3}, + {'wdth': 0.3, 'wght': 180}, + {'wdth': 0.3, 'wght': 120}, + {'wdth': 0.2, 'wght': 120}] + >>> pprint(model.deltaWeights) + [{}, + {0: 1.0}, + {0: 1.0}, + {0: 1.0}, + {0: 1.0}, + {0: 1.0}, + {0: 1.0, 4: 1.0, 5: 1.0}, + {0: 1.0, 3: 0.75, 4: 0.25, 5: 1.0, 6: 0.6666666666666666}, + {0: 1.0, + 3: 0.75, + 4: 0.25, + 5: 0.6666666666666667, + 6: 0.4444444444444445, + 7: 0.6666666666666667}] + """ + + def __init__( + self, locations, axisOrder=None, extrapolate=False, *, axisRanges=None + ): + locations = [{k: v for k, v in loc.items() if v != 0.0} for loc in locations] + + if len(set(tuple(sorted(l.items())) for l in locations)) != len(locations): + raise VariationModelError("Locations must be unique.") + + self.origLocations = locations + self.axisOrder = axisOrder if axisOrder is not None else [] + self.extrapolate = extrapolate + if axisRanges is None: + if extrapolate: + axisRanges = self.computeAxisRanges(locations) + else: + allAxes = {axis for loc in locations for axis in loc.keys()} + axisRanges = {axis: (-1, 1) for axis in allAxes} + self.axisRanges = axisRanges + keyFunc = self.getMasterLocationsSortKeyFunc( + locations, axisOrder=self.axisOrder + ) + self.locations = sorted(locations, key=keyFunc) + + # Mapping from user's master order to our master order + self.mapping = [self.locations.index(l) for l in locations] + self.reverseMapping = [locations.index(l) for l in self.locations] + + self._computeMasterSupports() + self._subModels = {} + + def getSubModel(self, items): + """Return a sub-model and the items that are not None. + + The sub-model is necessary for working with the subset + of items when some are None. + + The sub-model is cached.""" + if None not in items: + return self, items + key = tuple(v is not None for v in items) + subModel = self._subModels.get(key) + if subModel is None: + subModel = VariationModel( + subList(key, self.origLocations), + self.axisOrder, + extrapolate=self.extrapolate, + axisRanges=self.axisRanges, + ) + self._subModels[key] = subModel + return subModel, subList(key, items) + + @staticmethod + def computeAxisRanges(locations): + axisRanges = {} + allAxes = {axis for loc in locations for axis in loc.keys()} + for loc in locations: + for axis in allAxes: + value = loc.get(axis, 0) + axisMin, axisMax = axisRanges.get(axis, (value, value)) + axisRanges[axis] = min(value, axisMin), max(value, axisMax) + return axisRanges + + @staticmethod + def getMasterLocationsSortKeyFunc(locations, axisOrder=[]): + if {} not in locations: + raise VariationModelError("Base master not found.") + axisPoints = {} + for loc in locations: + if len(loc) != 1: + continue + axis = next(iter(loc)) + value = loc[axis] + if axis not in axisPoints: + axisPoints[axis] = {0.0} + assert ( + value not in axisPoints[axis] + ), 'Value "%s" in axisPoints["%s"] --> %s' % (value, axis, axisPoints) + axisPoints[axis].add(value) + + def getKey(axisPoints, axisOrder): + def sign(v): + return -1 if v < 0 else +1 if v > 0 else 0 + + def key(loc): + rank = len(loc) + onPointAxes = [ + axis + for axis, value in loc.items() + if axis in axisPoints and value in axisPoints[axis] + ] + orderedAxes = [axis for axis in axisOrder if axis in loc] + orderedAxes.extend( + [axis for axis in sorted(loc.keys()) if axis not in axisOrder] + ) + return ( + rank, # First, order by increasing rank + -len(onPointAxes), # Next, by decreasing number of onPoint axes + tuple( + axisOrder.index(axis) if axis in axisOrder else 0x10000 + for axis in orderedAxes + ), # Next, by known axes + tuple(orderedAxes), # Next, by all axes + tuple( + sign(loc[axis]) for axis in orderedAxes + ), # Next, by signs of axis values + tuple( + abs(loc[axis]) for axis in orderedAxes + ), # Next, by absolute value of axis values + ) + + return key + + ret = getKey(axisPoints, axisOrder) + return ret + + def reorderMasters(self, master_list, mapping): + # For changing the master data order without + # recomputing supports and deltaWeights. + new_list = [master_list[idx] for idx in mapping] + self.origLocations = [self.origLocations[idx] for idx in mapping] + locations = [ + {k: v for k, v in loc.items() if v != 0.0} for loc in self.origLocations + ] + self.mapping = [self.locations.index(l) for l in locations] + self.reverseMapping = [locations.index(l) for l in self.locations] + self._subModels = {} + return new_list + + def _computeMasterSupports(self): + self.supports = [] + regions = self._locationsToRegions() + for i, region in enumerate(regions): + locAxes = set(region.keys()) + # Walk over previous masters now + for prev_region in regions[:i]: + # Master with different axes do not participate + if set(prev_region.keys()) != locAxes: + continue + # If it's NOT in the current box, it does not participate + relevant = True + for axis, (lower, peak, upper) in region.items(): + if not ( + prev_region[axis][1] == peak + or lower < prev_region[axis][1] < upper + ): + relevant = False + break + if not relevant: + continue + + # Split the box for new master; split in whatever direction + # that has largest range ratio. + # + # For symmetry, we actually cut across multiple axes + # if they have the largest, equal, ratio. + # https://github.com/fonttools/fonttools/commit/7ee81c8821671157968b097f3e55309a1faa511e#commitcomment-31054804 + + bestAxes = {} + bestRatio = -1 + for axis in prev_region.keys(): + val = prev_region[axis][1] + assert axis in region + lower, locV, upper = region[axis] + newLower, newUpper = lower, upper + if val < locV: + newLower = val + ratio = (val - locV) / (lower - locV) + elif locV < val: + newUpper = val + ratio = (val - locV) / (upper - locV) + else: # val == locV + # Can't split box in this direction. + continue + if ratio > bestRatio: + bestAxes = {} + bestRatio = ratio + if ratio == bestRatio: + bestAxes[axis] = (newLower, locV, newUpper) + + for axis, triple in bestAxes.items(): + region[axis] = triple + self.supports.append(region) + self._computeDeltaWeights() + + def _locationsToRegions(self): + locations = self.locations + axisRanges = self.axisRanges + + regions = [] + for loc in locations: + region = {} + for axis, locV in loc.items(): + if locV > 0: + region[axis] = (0, locV, axisRanges[axis][1]) + else: + region[axis] = (axisRanges[axis][0], locV, 0) + regions.append(region) + return regions + + def _computeDeltaWeights(self): + self.deltaWeights = [] + for i, loc in enumerate(self.locations): + deltaWeight = {} + # Walk over previous masters now, populate deltaWeight + for j, support in enumerate(self.supports[:i]): + scalar = supportScalar(loc, support) + if scalar: + deltaWeight[j] = scalar + self.deltaWeights.append(deltaWeight) + + def getDeltas(self, masterValues, *, round=noRound): + assert len(masterValues) == len(self.deltaWeights), ( + len(masterValues), + len(self.deltaWeights), + ) + mapping = self.reverseMapping + out = [] + for i, weights in enumerate(self.deltaWeights): + delta = masterValues[mapping[i]] + for j, weight in weights.items(): + if weight == 1: + delta -= out[j] + else: + delta -= out[j] * weight + out.append(round(delta)) + return out + + def getDeltasAndSupports(self, items, *, round=noRound): + model, items = self.getSubModel(items) + return model.getDeltas(items, round=round), model.supports + + def getScalars(self, loc): + """Return scalars for each delta, for the given location. + If interpolating many master-values at the same location, + this function allows speed up by fetching the scalars once + and using them with interpolateFromMastersAndScalars().""" + return [ + supportScalar( + loc, support, extrapolate=self.extrapolate, axisRanges=self.axisRanges + ) + for support in self.supports + ] + + def getMasterScalars(self, targetLocation): + """Return multipliers for each master, for the given location. + If interpolating many master-values at the same location, + this function allows speed up by fetching the scalars once + and using them with interpolateFromValuesAndScalars(). + + Note that the scalars used in interpolateFromMastersAndScalars(), + are *not* the same as the ones returned here. They are the result + of getScalars().""" + out = self.getScalars(targetLocation) + for i, weights in reversed(list(enumerate(self.deltaWeights))): + for j, weight in weights.items(): + out[j] -= out[i] * weight + + out = [out[self.mapping[i]] for i in range(len(out))] + return out + + @staticmethod + def interpolateFromValuesAndScalars(values, scalars): + """Interpolate from values and scalars coefficients. + + If the values are master-values, then the scalars should be + fetched from getMasterScalars(). + + If the values are deltas, then the scalars should be fetched + from getScalars(); in which case this is the same as + interpolateFromDeltasAndScalars(). + """ + v = None + assert len(values) == len(scalars) + for value, scalar in zip(values, scalars): + if not scalar: + continue + contribution = value * scalar + if v is None: + v = contribution + else: + v += contribution + return v + + @staticmethod + def interpolateFromDeltasAndScalars(deltas, scalars): + """Interpolate from deltas and scalars fetched from getScalars().""" + return VariationModel.interpolateFromValuesAndScalars(deltas, scalars) + + def interpolateFromDeltas(self, loc, deltas): + """Interpolate from deltas, at location loc.""" + scalars = self.getScalars(loc) + return self.interpolateFromDeltasAndScalars(deltas, scalars) + + def interpolateFromMasters(self, loc, masterValues, *, round=noRound): + """Interpolate from master-values, at location loc.""" + scalars = self.getMasterScalars(loc) + return self.interpolateFromValuesAndScalars(masterValues, scalars) + + def interpolateFromMastersAndScalars(self, masterValues, scalars, *, round=noRound): + """Interpolate from master-values, and scalars fetched from + getScalars(), which is useful when you want to interpolate + multiple master-values with the same location.""" + deltas = self.getDeltas(masterValues, round=round) + return self.interpolateFromDeltasAndScalars(deltas, scalars) + + +def piecewiseLinearMap(v: float, mapping: Mapping[float, float]) -> float: + keys = mapping.keys() + if not keys: + return v + if v in keys: + return mapping[v] + k = min(keys) + if v < k: + return v + mapping[k] - k + k = max(keys) + if v > k: + return v + mapping[k] - k + # Interpolate + a = max(k for k in keys if k < v) + b = min(k for k in keys if k > v) + va = mapping[a] + vb = mapping[b] + return va + (vb - va) * (v - a) / (b - a) + + +def main(args=None): + """Normalize locations on a given designspace""" + from fontTools import configLogger + import argparse + + parser = argparse.ArgumentParser( + "fonttools varLib.models", + description=main.__doc__, + ) + parser.add_argument( + "--loglevel", + metavar="LEVEL", + default="INFO", + help="Logging level (defaults to INFO)", + ) + + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("-d", "--designspace", metavar="DESIGNSPACE", type=str) + group.add_argument( + "-l", + "--locations", + metavar="LOCATION", + nargs="+", + help="Master locations as comma-separate coordinates. One must be all zeros.", + ) + + args = parser.parse_args(args) + + configLogger(level=args.loglevel) + from pprint import pprint + + if args.designspace: + from fontTools.designspaceLib import DesignSpaceDocument + + doc = DesignSpaceDocument() + doc.read(args.designspace) + locs = [s.location for s in doc.sources] + print("Original locations:") + pprint(locs) + doc.normalize() + print("Normalized locations:") + locs = [s.location for s in doc.sources] + pprint(locs) + else: + axes = [chr(c) for c in range(ord("A"), ord("Z") + 1)] + locs = [ + dict(zip(axes, (float(v) for v in s.split(",")))) for s in args.locations + ] + + model = VariationModel(locs) + print("Sorted locations:") + pprint(model.locations) + print("Supports:") + pprint(model.supports) + + +if __name__ == "__main__": + import doctest, sys + + if len(sys.argv) > 1: + sys.exit(main()) + + sys.exit(doctest.testmod().failed) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/multiVarStore.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/multiVarStore.py new file mode 100644 index 0000000000000000000000000000000000000000..95318a670a2b108d506b8467054290376bf4ed86 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/multiVarStore.py @@ -0,0 +1,282 @@ +from fontTools.misc.roundTools import noRound, otRound +from fontTools.misc.intTools import bit_count +from fontTools.misc.vector import Vector +from fontTools.ttLib.tables import otTables as ot +from fontTools.varLib.models import supportScalar +import fontTools.varLib.varStore # For monkey-patching +from fontTools.varLib.builder import ( + buildVarRegionList, + buildSparseVarRegionList, + buildSparseVarRegion, + buildMultiVarStore, + buildMultiVarData, +) +from fontTools.misc.iterTools import batched +from functools import partial +from collections import defaultdict +from heapq import heappush, heappop + +NO_VARIATION_INDEX = ot.NO_VARIATION_INDEX +ot.MultiVarStore.NO_VARIATION_INDEX = NO_VARIATION_INDEX + + +def _getLocationKey(loc): + return tuple(sorted(loc.items(), key=lambda kv: kv[0])) + + +class OnlineMultiVarStoreBuilder(object): + def __init__(self, axisTags): + self._axisTags = axisTags + self._regionMap = {} + self._regionList = buildSparseVarRegionList([], axisTags) + self._store = buildMultiVarStore(self._regionList, []) + self._data = None + self._model = None + self._supports = None + self._varDataIndices = {} + self._varDataCaches = {} + self._cache = None + + def setModel(self, model): + self.setSupports(model.supports) + self._model = model + + def setSupports(self, supports): + self._model = None + self._supports = list(supports) + if not self._supports[0]: + del self._supports[0] # Drop base master support + self._cache = None + self._data = None + + def finish(self): + self._regionList.RegionCount = len(self._regionList.Region) + self._store.MultiVarDataCount = len(self._store.MultiVarData) + return self._store + + def _add_MultiVarData(self): + regionMap = self._regionMap + regionList = self._regionList + + regions = self._supports + regionIndices = [] + for region in regions: + key = _getLocationKey(region) + idx = regionMap.get(key) + if idx is None: + varRegion = buildSparseVarRegion(region, self._axisTags) + idx = regionMap[key] = len(regionList.Region) + regionList.Region.append(varRegion) + regionIndices.append(idx) + + # Check if we have one already... + key = tuple(regionIndices) + varDataIdx = self._varDataIndices.get(key) + if varDataIdx is not None: + self._outer = varDataIdx + self._data = self._store.MultiVarData[varDataIdx] + self._cache = self._varDataCaches[key] + if len(self._data.Item) == 0xFFFF: + # This is full. Need new one. + varDataIdx = None + + if varDataIdx is None: + self._data = buildMultiVarData(regionIndices, []) + self._outer = len(self._store.MultiVarData) + self._store.MultiVarData.append(self._data) + self._varDataIndices[key] = self._outer + if key not in self._varDataCaches: + self._varDataCaches[key] = {} + self._cache = self._varDataCaches[key] + + def storeMasters(self, master_values, *, round=round): + deltas = self._model.getDeltas(master_values, round=round) + base = deltas.pop(0) + return base, self.storeDeltas(deltas, round=noRound) + + def storeDeltas(self, deltas, *, round=round): + deltas = tuple(round(d) for d in deltas) + + if not any(deltas): + return NO_VARIATION_INDEX + + deltas_tuple = tuple(tuple(d) for d in deltas) + + if not self._data: + self._add_MultiVarData() + + varIdx = self._cache.get(deltas_tuple) + if varIdx is not None: + return varIdx + + inner = len(self._data.Item) + if inner == 0xFFFF: + # Full array. Start new one. + self._add_MultiVarData() + return self.storeDeltas(deltas, round=noRound) + self._data.addItem(deltas, round=noRound) + + varIdx = (self._outer << 16) + inner + self._cache[deltas_tuple] = varIdx + return varIdx + + +def MultiVarData_addItem(self, deltas, *, round=round): + deltas = tuple(round(d) for d in deltas) + + assert len(deltas) == self.VarRegionCount + + values = [] + for d in deltas: + values.extend(d) + + self.Item.append(values) + self.ItemCount = len(self.Item) + + +ot.MultiVarData.addItem = MultiVarData_addItem + + +def SparseVarRegion_get_support(self, fvar_axes): + return { + fvar_axes[reg.AxisIndex].axisTag: (reg.StartCoord, reg.PeakCoord, reg.EndCoord) + for reg in self.SparseVarRegionAxis + } + + +ot.SparseVarRegion.get_support = SparseVarRegion_get_support + + +def MultiVarStore___bool__(self): + return bool(self.MultiVarData) + + +ot.MultiVarStore.__bool__ = MultiVarStore___bool__ + + +class MultiVarStoreInstancer(object): + def __init__(self, multivarstore, fvar_axes, location={}): + self.fvar_axes = fvar_axes + assert multivarstore is None or multivarstore.Format == 1 + self._varData = multivarstore.MultiVarData if multivarstore else [] + self._regions = ( + multivarstore.SparseVarRegionList.Region if multivarstore else [] + ) + self.setLocation(location) + + def setLocation(self, location): + self.location = dict(location) + self._clearCaches() + + def _clearCaches(self): + self._scalars = {} + + def _getScalar(self, regionIdx): + scalar = self._scalars.get(regionIdx) + if scalar is None: + support = self._regions[regionIdx].get_support(self.fvar_axes) + scalar = supportScalar(self.location, support) + self._scalars[regionIdx] = scalar + return scalar + + @staticmethod + def interpolateFromDeltasAndScalars(deltas, scalars): + if not deltas: + return Vector([]) + assert len(deltas) % len(scalars) == 0, (len(deltas), len(scalars)) + m = len(deltas) // len(scalars) + delta = Vector([0] * m) + for d, s in zip(batched(deltas, m), scalars): + if not s: + continue + delta += Vector(d) * s + return delta + + def __getitem__(self, varidx): + major, minor = varidx >> 16, varidx & 0xFFFF + if varidx == NO_VARIATION_INDEX: + return Vector([]) + varData = self._varData + scalars = [self._getScalar(ri) for ri in varData[major].VarRegionIndex] + deltas = varData[major].Item[minor] + return self.interpolateFromDeltasAndScalars(deltas, scalars) + + def interpolateFromDeltas(self, varDataIndex, deltas): + varData = self._varData + scalars = [self._getScalar(ri) for ri in varData[varDataIndex].VarRegionIndex] + return self.interpolateFromDeltasAndScalars(deltas, scalars) + + +def MultiVarStore_subset_varidxes(self, varIdxes): + return ot.VarStore.subset_varidxes(self, varIdxes, VarData="MultiVarData") + + +def MultiVarStore_prune_regions(self): + return ot.VarStore.prune_regions( + self, VarData="MultiVarData", VarRegionList="SparseVarRegionList" + ) + + +ot.MultiVarStore.prune_regions = MultiVarStore_prune_regions +ot.MultiVarStore.subset_varidxes = MultiVarStore_subset_varidxes + + +def MultiVarStore_get_supports(self, major, fvarAxes): + supports = [] + varData = self.MultiVarData[major] + for regionIdx in varData.VarRegionIndex: + region = self.SparseVarRegionList.Region[regionIdx] + support = region.get_support(fvarAxes) + supports.append(support) + return supports + + +ot.MultiVarStore.get_supports = MultiVarStore_get_supports + + +def ConditionTable_collect_varidxes(self, varidxes): + if self.Format == 2: + varidxes.add(self.VarIdx) + elif self.Format in (3, 4): + for condition in self.ConditionTable: + condition.collect_varidxes(varidxes) + elif self.Format == 5: + self.ConditionTable.collect_varidxes(varidxes) + + +def ConditionTable_remap_varidxes(self, varidxes_map): + if self.Format == 2: + self.VarIdx = varidxes_map[self.VarIdx] + elif self.Format in (3, 4): + for condition in self.ConditionTable: + condition.remap_varidxes(varidxes_map) + elif self.Format == 5: + self.ConditionTable.remap_varidxes(varidxes_map) + + +ot.ConditionTable.collect_varidxes = ConditionTable_collect_varidxes +ot.ConditionTable.remap_varidxes = ConditionTable_remap_varidxes + + +def VARC_collect_varidxes(self, varidxes): + for glyph in self.VarCompositeGlyphs.VarCompositeGlyph: + for component in glyph.components: + varidxes.add(component.axisValuesVarIndex) + varidxes.add(component.transformVarIndex) + if self.ConditionList is not None: + for condition in self.ConditionList.ConditionTable: + condition.collect_varidxes(varidxes) + + +def VARC_remap_varidxes(self, varidxes_map): + for glyph in self.VarCompositeGlyphs.VarCompositeGlyph: + for component in glyph.components: + component.axisValuesVarIndex = varidxes_map[component.axisValuesVarIndex] + component.transformVarIndex = varidxes_map[component.transformVarIndex] + if self.ConditionList is not None: + for condition in self.ConditionList.ConditionTable: + condition.remap_varidxes(varidxes_map) + + +ot.VARC.collect_varidxes = VARC_collect_varidxes +ot.VARC.remap_varidxes = VARC_remap_varidxes diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/mutator.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/mutator.py new file mode 100644 index 0000000000000000000000000000000000000000..082750f56d4644b63e06025cf07085467812af9c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/mutator.py @@ -0,0 +1,528 @@ +""" +Instantiate a variation font. Run, eg: + +.. code-block:: sh + + $ fonttools varLib.mutator ./NotoSansArabic-VF.ttf wght=140 wdth=85 + +.. warning:: + ``fontTools.varLib.mutator`` is deprecated in favor of :mod:`fontTools.varLib.instancer` + which provides equivalent full instancing and also supports partial instancing. + Please migrate CLI usage to ``fonttools varLib.instancer`` and API usage to + :func:`fontTools.varLib.instancer.instantiateVariableFont`. +""" + +from fontTools.misc.fixedTools import floatToFixedToFloat, floatToFixed +from fontTools.misc.loggingTools import deprecateFunction +from fontTools.misc.roundTools import otRound +from fontTools.pens.boundsPen import BoundsPen +from fontTools.ttLib import TTFont, newTable +from fontTools.ttLib.tables import ttProgram +from fontTools.ttLib.tables._g_l_y_f import ( + GlyphCoordinates, + flagOverlapSimple, + OVERLAP_COMPOUND, +) +from fontTools.varLib.models import ( + supportScalar, + normalizeLocation, + piecewiseLinearMap, +) +from fontTools.varLib.merger import MutatorMerger +from fontTools.varLib.varStore import VarStoreInstancer +from fontTools.varLib.mvar import MVAR_ENTRIES +from fontTools.varLib.iup import iup_delta +import fontTools.subset.cff +import os.path +import logging +from io import BytesIO + +log = logging.getLogger("fontTools.varlib.mutator") + +# map 'wdth' axis (1..200) to OS/2.usWidthClass (1..9), rounding to closest +OS2_WIDTH_CLASS_VALUES = {} +percents = [50.0, 62.5, 75.0, 87.5, 100.0, 112.5, 125.0, 150.0, 200.0] +for i, (prev, curr) in enumerate(zip(percents[:-1], percents[1:]), start=1): + half = (prev + curr) / 2 + OS2_WIDTH_CLASS_VALUES[half] = i + + +def interpolate_cff2_PrivateDict(topDict, interpolateFromDeltas): + pd_blend_lists = ( + "BlueValues", + "OtherBlues", + "FamilyBlues", + "FamilyOtherBlues", + "StemSnapH", + "StemSnapV", + ) + pd_blend_values = ("BlueScale", "BlueShift", "BlueFuzz", "StdHW", "StdVW") + for fontDict in topDict.FDArray: + pd = fontDict.Private + vsindex = pd.vsindex if (hasattr(pd, "vsindex")) else 0 + for key, value in pd.rawDict.items(): + if (key in pd_blend_values) and isinstance(value, list): + delta = interpolateFromDeltas(vsindex, value[1:]) + pd.rawDict[key] = otRound(value[0] + delta) + elif (key in pd_blend_lists) and isinstance(value[0], list): + """If any argument in a BlueValues list is a blend list, + then they all are. The first value of each list is an + absolute value. The delta tuples are calculated from + relative master values, hence we need to append all the + deltas to date to each successive absolute value.""" + delta = 0 + for i, val_list in enumerate(value): + delta += otRound(interpolateFromDeltas(vsindex, val_list[1:])) + value[i] = val_list[0] + delta + + +def interpolate_cff2_charstrings(topDict, interpolateFromDeltas, glyphOrder): + charstrings = topDict.CharStrings + for gname in glyphOrder: + # Interpolate charstring + # e.g replace blend op args with regular args, + # and use and discard vsindex op. + charstring = charstrings[gname] + new_program = [] + vsindex = 0 + last_i = 0 + for i, token in enumerate(charstring.program): + if token == "vsindex": + vsindex = charstring.program[i - 1] + if last_i != 0: + new_program.extend(charstring.program[last_i : i - 1]) + last_i = i + 1 + elif token == "blend": + num_regions = charstring.getNumRegions(vsindex) + numMasters = 1 + num_regions + num_args = charstring.program[i - 1] + # The program list starting at program[i] is now: + # ..args for following operations + # num_args values from the default font + # num_args tuples, each with numMasters-1 delta values + # num_blend_args + # 'blend' + argi = i - (num_args * numMasters + 1) + end_args = tuplei = argi + num_args + while argi < end_args: + next_ti = tuplei + num_regions + deltas = charstring.program[tuplei:next_ti] + delta = interpolateFromDeltas(vsindex, deltas) + charstring.program[argi] += otRound(delta) + tuplei = next_ti + argi += 1 + new_program.extend(charstring.program[last_i:end_args]) + last_i = i + 1 + if last_i != 0: + new_program.extend(charstring.program[last_i:]) + charstring.program = new_program + + +def interpolate_cff2_metrics(varfont, topDict, glyphOrder, loc): + """Unlike TrueType glyphs, neither advance width nor bounding box + info is stored in a CFF2 charstring. The width data exists only in + the hmtx and HVAR tables. Since LSB data cannot be interpolated + reliably from the master LSB values in the hmtx table, we traverse + the charstring to determine the actual bound box.""" + + charstrings = topDict.CharStrings + boundsPen = BoundsPen(glyphOrder) + hmtx = varfont["hmtx"] + hvar_table = None + if "HVAR" in varfont: + hvar_table = varfont["HVAR"].table + fvar = varfont["fvar"] + varStoreInstancer = VarStoreInstancer(hvar_table.VarStore, fvar.axes, loc) + + for gid, gname in enumerate(glyphOrder): + entry = list(hmtx[gname]) + # get width delta. + if hvar_table: + if hvar_table.AdvWidthMap: + width_idx = hvar_table.AdvWidthMap.mapping[gname] + else: + width_idx = gid + width_delta = otRound(varStoreInstancer[width_idx]) + else: + width_delta = 0 + + # get LSB. + boundsPen.init() + charstring = charstrings[gname] + charstring.draw(boundsPen) + if boundsPen.bounds is None: + # Happens with non-marking glyphs + lsb_delta = 0 + else: + lsb = otRound(boundsPen.bounds[0]) + lsb_delta = entry[1] - lsb + + if lsb_delta or width_delta: + if width_delta: + entry[0] = max(0, entry[0] + width_delta) + if lsb_delta: + entry[1] = lsb + hmtx[gname] = tuple(entry) + + +@deprecateFunction( + "use fontTools.varLib.instancer.instantiateVariableFont instead " + "for either full or partial instancing", +) +def instantiateVariableFont(varfont, location, inplace=False, overlap=True): + """Generate a static instance from a variable TTFont and a dictionary + defining the desired location along the variable font's axes. + The location values must be specified as user-space coordinates, e.g.: + + .. code-block:: + + {'wght': 400, 'wdth': 100} + + By default, a new TTFont object is returned. If ``inplace`` is True, the + input varfont is modified and reduced to a static font. + + When the overlap parameter is defined as True, + OVERLAP_SIMPLE and OVERLAP_COMPOUND bits are set to 1. See + https://docs.microsoft.com/en-us/typography/opentype/spec/glyf + """ + if not inplace: + # make a copy to leave input varfont unmodified + stream = BytesIO() + varfont.save(stream) + stream.seek(0) + varfont = TTFont(stream) + + fvar = varfont["fvar"] + axes = {a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in fvar.axes} + loc = normalizeLocation(location, axes) + if "avar" in varfont: + maps = varfont["avar"].segments + loc = {k: piecewiseLinearMap(v, maps[k]) for k, v in loc.items()} + # Quantize to F2Dot14, to avoid surprise interpolations. + loc = {k: floatToFixedToFloat(v, 14) for k, v in loc.items()} + # Location is normalized now + log.info("Normalized location: %s", loc) + + if "gvar" in varfont: + log.info("Mutating glyf/gvar tables") + gvar = varfont["gvar"] + glyf = varfont["glyf"] + hMetrics = varfont["hmtx"].metrics + vMetrics = getattr(varfont.get("vmtx"), "metrics", None) + # get list of glyph names in gvar sorted by component depth + glyphnames = sorted( + gvar.variations.keys(), + key=lambda name: ( + ( + glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth + if glyf[name].isComposite() + else 0 + ), + name, + ), + ) + for glyphname in glyphnames: + variations = gvar.variations[glyphname] + coordinates, _ = glyf._getCoordinatesAndControls( + glyphname, hMetrics, vMetrics + ) + origCoords, endPts = None, None + for var in variations: + scalar = supportScalar(loc, var.axes) + if not scalar: + continue + delta = var.coordinates + if None in delta: + if origCoords is None: + origCoords, g = glyf._getCoordinatesAndControls( + glyphname, hMetrics, vMetrics + ) + delta = iup_delta(delta, origCoords, g.endPts) + coordinates += GlyphCoordinates(delta) * scalar + glyf._setCoordinates(glyphname, coordinates, hMetrics, vMetrics) + else: + glyf = None + + if "DSIG" in varfont: + del varfont["DSIG"] + + if "cvar" in varfont: + log.info("Mutating cvt/cvar tables") + cvar = varfont["cvar"] + cvt = varfont["cvt "] + deltas = {} + for var in cvar.variations: + scalar = supportScalar(loc, var.axes) + if not scalar: + continue + for i, c in enumerate(var.coordinates): + if c is not None: + deltas[i] = deltas.get(i, 0) + scalar * c + for i, delta in deltas.items(): + cvt[i] += otRound(delta) + + if "CFF2" in varfont: + log.info("Mutating CFF2 table") + glyphOrder = varfont.getGlyphOrder() + CFF2 = varfont["CFF2"] + topDict = CFF2.cff.topDictIndex[0] + vsInstancer = VarStoreInstancer(topDict.VarStore.otVarStore, fvar.axes, loc) + interpolateFromDeltas = vsInstancer.interpolateFromDeltas + interpolate_cff2_PrivateDict(topDict, interpolateFromDeltas) + CFF2.desubroutinize() + interpolate_cff2_charstrings(topDict, interpolateFromDeltas, glyphOrder) + interpolate_cff2_metrics(varfont, topDict, glyphOrder, loc) + del topDict.rawDict["VarStore"] + del topDict.VarStore + + if "MVAR" in varfont: + log.info("Mutating MVAR table") + mvar = varfont["MVAR"].table + varStoreInstancer = VarStoreInstancer(mvar.VarStore, fvar.axes, loc) + records = mvar.ValueRecord + for rec in records: + mvarTag = rec.ValueTag + if mvarTag not in MVAR_ENTRIES: + continue + tableTag, itemName = MVAR_ENTRIES[mvarTag] + delta = otRound(varStoreInstancer[rec.VarIdx]) + if not delta: + continue + setattr( + varfont[tableTag], + itemName, + getattr(varfont[tableTag], itemName) + delta, + ) + + log.info("Mutating FeatureVariations") + for tableTag in "GSUB", "GPOS": + if not tableTag in varfont: + continue + table = varfont[tableTag].table + if not getattr(table, "FeatureVariations", None): + continue + variations = table.FeatureVariations + for record in variations.FeatureVariationRecord: + applies = True + for condition in record.ConditionSet.ConditionTable: + if condition.Format == 1: + axisIdx = condition.AxisIndex + axisTag = fvar.axes[axisIdx].axisTag + Min = condition.FilterRangeMinValue + Max = condition.FilterRangeMaxValue + v = loc[axisTag] + if not (Min <= v <= Max): + applies = False + else: + applies = False + if not applies: + break + + if applies: + assert record.FeatureTableSubstitution.Version == 0x00010000 + for rec in record.FeatureTableSubstitution.SubstitutionRecord: + table.FeatureList.FeatureRecord[rec.FeatureIndex].Feature = ( + rec.Feature + ) + break + del table.FeatureVariations + + if "GDEF" in varfont and varfont["GDEF"].table.Version >= 0x00010003: + log.info("Mutating GDEF/GPOS/GSUB tables") + gdef = varfont["GDEF"].table + instancer = VarStoreInstancer(gdef.VarStore, fvar.axes, loc) + + merger = MutatorMerger(varfont, instancer) + merger.mergeTables(varfont, [varfont], ["GDEF", "GPOS"]) + + # Downgrade GDEF. + del gdef.VarStore + gdef.Version = 0x00010002 + if gdef.MarkGlyphSetsDef is None: + del gdef.MarkGlyphSetsDef + gdef.Version = 0x00010000 + + if not ( + gdef.LigCaretList + or gdef.MarkAttachClassDef + or gdef.GlyphClassDef + or gdef.AttachList + or (gdef.Version >= 0x00010002 and gdef.MarkGlyphSetsDef) + ): + del varfont["GDEF"] + + addidef = False + if glyf: + for glyph in glyf.glyphs.values(): + if hasattr(glyph, "program"): + instructions = glyph.program.getAssembly() + # If GETVARIATION opcode is used in bytecode of any glyph add IDEF + addidef = any(op.startswith("GETVARIATION") for op in instructions) + if addidef: + break + if overlap: + for glyph_name in glyf.keys(): + glyph = glyf[glyph_name] + # Set OVERLAP_COMPOUND bit for compound glyphs + if glyph.isComposite(): + glyph.components[0].flags |= OVERLAP_COMPOUND + # Set OVERLAP_SIMPLE bit for simple glyphs + elif glyph.numberOfContours > 0: + glyph.flags[0] |= flagOverlapSimple + if addidef: + log.info("Adding IDEF to fpgm table for GETVARIATION opcode") + asm = [] + if "fpgm" in varfont: + fpgm = varfont["fpgm"] + asm = fpgm.program.getAssembly() + else: + fpgm = newTable("fpgm") + fpgm.program = ttProgram.Program() + varfont["fpgm"] = fpgm + asm.append("PUSHB[000] 145") + asm.append("IDEF[ ]") + args = [str(len(loc))] + for a in fvar.axes: + args.append(str(floatToFixed(loc[a.axisTag], 14))) + asm.append("NPUSHW[ ] " + " ".join(args)) + asm.append("ENDF[ ]") + fpgm.program.fromAssembly(asm) + + # Change maxp attributes as IDEF is added + if "maxp" in varfont: + maxp = varfont["maxp"] + setattr( + maxp, "maxInstructionDefs", 1 + getattr(maxp, "maxInstructionDefs", 0) + ) + setattr( + maxp, + "maxStackElements", + max(len(loc), getattr(maxp, "maxStackElements", 0)), + ) + + if "name" in varfont: + log.info("Pruning name table") + exclude = {a.axisNameID for a in fvar.axes} + for i in fvar.instances: + exclude.add(i.subfamilyNameID) + exclude.add(i.postscriptNameID) + if "ltag" in varfont: + # Drop the whole 'ltag' table if all its language tags are referenced by + # name records to be pruned. + # TODO: prune unused ltag tags and re-enumerate langIDs accordingly + excludedUnicodeLangIDs = [ + n.langID + for n in varfont["name"].names + if n.nameID in exclude and n.platformID == 0 and n.langID != 0xFFFF + ] + if set(excludedUnicodeLangIDs) == set(range(len((varfont["ltag"].tags)))): + del varfont["ltag"] + varfont["name"].names[:] = [ + n + for n in varfont["name"].names + if n.nameID < 256 or n.nameID not in exclude + ] + + if "wght" in location and "OS/2" in varfont: + varfont["OS/2"].usWeightClass = otRound(max(1, min(location["wght"], 1000))) + if "wdth" in location: + wdth = location["wdth"] + for percent, widthClass in sorted(OS2_WIDTH_CLASS_VALUES.items()): + if wdth < percent: + varfont["OS/2"].usWidthClass = widthClass + break + else: + varfont["OS/2"].usWidthClass = 9 + if "slnt" in location and "post" in varfont: + varfont["post"].italicAngle = max(-90, min(location["slnt"], 90)) + + log.info("Removing variable tables") + for tag in ("avar", "cvar", "fvar", "gvar", "HVAR", "MVAR", "VVAR", "STAT"): + if tag in varfont: + del varfont[tag] + + return varfont + + +def main(args=None): + """Instantiate a variation font""" + from fontTools import configLogger + import argparse + + parser = argparse.ArgumentParser( + "fonttools varLib.mutator", description="Instantiate a variable font" + ) + parser.add_argument("input", metavar="INPUT.ttf", help="Input variable TTF file.") + parser.add_argument( + "locargs", + metavar="AXIS=LOC", + nargs="*", + help="List of space separated locations. A location consist in " + "the name of a variation axis, followed by '=' and a number. E.g.: " + " wght=700 wdth=80. The default is the location of the base master.", + ) + parser.add_argument( + "-o", + "--output", + metavar="OUTPUT.ttf", + default=None, + help="Output instance TTF file (default: INPUT-instance.ttf).", + ) + parser.add_argument( + "--no-recalc-timestamp", + dest="recalc_timestamp", + action="store_false", + help="Don't set the output font's timestamp to the current time.", + ) + logging_group = parser.add_mutually_exclusive_group(required=False) + logging_group.add_argument( + "-v", "--verbose", action="store_true", help="Run more verbosely." + ) + logging_group.add_argument( + "-q", "--quiet", action="store_true", help="Turn verbosity off." + ) + parser.add_argument( + "--no-overlap", + dest="overlap", + action="store_false", + help="Don't set OVERLAP_SIMPLE/OVERLAP_COMPOUND glyf flags.", + ) + options = parser.parse_args(args) + + varfilename = options.input + outfile = ( + os.path.splitext(varfilename)[0] + "-instance.ttf" + if not options.output + else options.output + ) + configLogger( + level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO") + ) + + loc = {} + for arg in options.locargs: + try: + tag, val = arg.split("=") + assert len(tag) <= 4 + loc[tag.ljust(4)] = float(val) + except (ValueError, AssertionError): + parser.error("invalid location argument format: %r" % arg) + log.info("Location: %s", loc) + + log.info("Loading variable font") + varfont = TTFont(varfilename, recalcTimestamp=options.recalc_timestamp) + + instantiateVariableFont(varfont, loc, inplace=True, overlap=options.overlap) + + log.info("Saving instance font %s", outfile) + varfont.save(outfile) + + +if __name__ == "__main__": + import sys + + if len(sys.argv) > 1: + sys.exit(main()) + import doctest + + sys.exit(doctest.testmod().failed) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/mvar.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/mvar.py new file mode 100644 index 0000000000000000000000000000000000000000..653aeb45e0ff18e06c2dd04ad58085d77a73c1b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/mvar.py @@ -0,0 +1,40 @@ +MVAR_ENTRIES = { + "hasc": ("OS/2", "sTypoAscender"), # horizontal ascender + "hdsc": ("OS/2", "sTypoDescender"), # horizontal descender + "hlgp": ("OS/2", "sTypoLineGap"), # horizontal line gap + "hcla": ("OS/2", "usWinAscent"), # horizontal clipping ascent + "hcld": ("OS/2", "usWinDescent"), # horizontal clipping descent + "vasc": ("vhea", "ascent"), # vertical ascender + "vdsc": ("vhea", "descent"), # vertical descender + "vlgp": ("vhea", "lineGap"), # vertical line gap + "hcrs": ("hhea", "caretSlopeRise"), # horizontal caret rise + "hcrn": ("hhea", "caretSlopeRun"), # horizontal caret run + "hcof": ("hhea", "caretOffset"), # horizontal caret offset + "vcrs": ("vhea", "caretSlopeRise"), # vertical caret rise + "vcrn": ("vhea", "caretSlopeRun"), # vertical caret run + "vcof": ("vhea", "caretOffset"), # vertical caret offset + "xhgt": ("OS/2", "sxHeight"), # x height + "cpht": ("OS/2", "sCapHeight"), # cap height + "sbxs": ("OS/2", "ySubscriptXSize"), # subscript em x size + "sbys": ("OS/2", "ySubscriptYSize"), # subscript em y size + "sbxo": ("OS/2", "ySubscriptXOffset"), # subscript em x offset + "sbyo": ("OS/2", "ySubscriptYOffset"), # subscript em y offset + "spxs": ("OS/2", "ySuperscriptXSize"), # superscript em x size + "spys": ("OS/2", "ySuperscriptYSize"), # superscript em y size + "spxo": ("OS/2", "ySuperscriptXOffset"), # superscript em x offset + "spyo": ("OS/2", "ySuperscriptYOffset"), # superscript em y offset + "strs": ("OS/2", "yStrikeoutSize"), # strikeout size + "stro": ("OS/2", "yStrikeoutPosition"), # strikeout offset + "unds": ("post", "underlineThickness"), # underline size + "undo": ("post", "underlinePosition"), # underline offset + #'gsp0': ('gasp', 'gaspRange[0].rangeMaxPPEM'), # gaspRange[0] + #'gsp1': ('gasp', 'gaspRange[1].rangeMaxPPEM'), # gaspRange[1] + #'gsp2': ('gasp', 'gaspRange[2].rangeMaxPPEM'), # gaspRange[2] + #'gsp3': ('gasp', 'gaspRange[3].rangeMaxPPEM'), # gaspRange[3] + #'gsp4': ('gasp', 'gaspRange[4].rangeMaxPPEM'), # gaspRange[4] + #'gsp5': ('gasp', 'gaspRange[5].rangeMaxPPEM'), # gaspRange[5] + #'gsp6': ('gasp', 'gaspRange[6].rangeMaxPPEM'), # gaspRange[6] + #'gsp7': ('gasp', 'gaspRange[7].rangeMaxPPEM'), # gaspRange[7] + #'gsp8': ('gasp', 'gaspRange[8].rangeMaxPPEM'), # gaspRange[8] + #'gsp9': ('gasp', 'gaspRange[9].rangeMaxPPEM'), # gaspRange[9] +} diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/plot.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/plot.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a7ca50d3f317d7c3219b77ff84f0f8bb310c6d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/plot.py @@ -0,0 +1,238 @@ +"""Visualize DesignSpaceDocument and resulting VariationModel.""" + +from fontTools.varLib.models import VariationModel, supportScalar +from fontTools.designspaceLib import DesignSpaceDocument +from matplotlib import pyplot +from mpl_toolkits.mplot3d import axes3d +from itertools import cycle +import math +import logging +import sys + +log = logging.getLogger(__name__) + + +def stops(support, count=10): + a, b, c = support + + return ( + [a + (b - a) * i / count for i in range(count)] + + [b + (c - b) * i / count for i in range(count)] + + [c] + ) + + +def _plotLocationsDots(locations, axes, subplot, **kwargs): + for loc, color in zip(locations, cycle(pyplot.cm.Set1.colors)): + if len(axes) == 1: + subplot.plot([loc.get(axes[0], 0)], [1.0], "o", color=color, **kwargs) + elif len(axes) == 2: + subplot.plot( + [loc.get(axes[0], 0)], + [loc.get(axes[1], 0)], + [1.0], + "o", + color=color, + **kwargs, + ) + else: + raise AssertionError(len(axes)) + + +def plotLocations(locations, fig, names=None, **kwargs): + n = len(locations) + cols = math.ceil(n**0.5) + rows = math.ceil(n / cols) + + if names is None: + names = [None] * len(locations) + + model = VariationModel(locations) + names = [names[model.reverseMapping[i]] for i in range(len(names))] + + axes = sorted(locations[0].keys()) + if len(axes) == 1: + _plotLocations2D(model, axes[0], fig, cols, rows, names=names, **kwargs) + elif len(axes) == 2: + _plotLocations3D(model, axes, fig, cols, rows, names=names, **kwargs) + else: + raise ValueError("Only 1 or 2 axes are supported") + + +def _plotLocations2D(model, axis, fig, cols, rows, names, **kwargs): + subplot = fig.add_subplot(111) + for i, (support, color, name) in enumerate( + zip(model.supports, cycle(pyplot.cm.Set1.colors), cycle(names)) + ): + if name is not None: + subplot.set_title(name) + subplot.set_xlabel(axis) + pyplot.xlim(-1.0, +1.0) + + Xs = support.get(axis, (-1.0, 0.0, +1.0)) + X, Y = [], [] + for x in stops(Xs): + y = supportScalar({axis: x}, support) + X.append(x) + Y.append(y) + subplot.plot(X, Y, color=color, **kwargs) + + _plotLocationsDots(model.locations, [axis], subplot) + + +def _plotLocations3D(model, axes, fig, rows, cols, names, **kwargs): + ax1, ax2 = axes + + axis3D = fig.add_subplot(111, projection="3d") + for i, (support, color, name) in enumerate( + zip(model.supports, cycle(pyplot.cm.Set1.colors), cycle(names)) + ): + if name is not None: + axis3D.set_title(name) + axis3D.set_xlabel(ax1) + axis3D.set_ylabel(ax2) + pyplot.xlim(-1.0, +1.0) + pyplot.ylim(-1.0, +1.0) + + Xs = support.get(ax1, (-1.0, 0.0, +1.0)) + Ys = support.get(ax2, (-1.0, 0.0, +1.0)) + for x in stops(Xs): + X, Y, Z = [], [], [] + for y in Ys: + z = supportScalar({ax1: x, ax2: y}, support) + X.append(x) + Y.append(y) + Z.append(z) + axis3D.plot(X, Y, Z, color=color, **kwargs) + for y in stops(Ys): + X, Y, Z = [], [], [] + for x in Xs: + z = supportScalar({ax1: x, ax2: y}, support) + X.append(x) + Y.append(y) + Z.append(z) + axis3D.plot(X, Y, Z, color=color, **kwargs) + + _plotLocationsDots(model.locations, [ax1, ax2], axis3D) + + +def plotDocument(doc, fig, **kwargs): + doc.normalize() + locations = [s.location for s in doc.sources] + names = [s.name for s in doc.sources] + plotLocations(locations, fig, names, **kwargs) + + +def _plotModelFromMasters2D(model, masterValues, fig, **kwargs): + assert len(model.axisOrder) == 1 + axis = model.axisOrder[0] + + axis_min = min(loc.get(axis, 0) for loc in model.locations) + axis_max = max(loc.get(axis, 0) for loc in model.locations) + + import numpy as np + + X = np.arange(axis_min, axis_max, (axis_max - axis_min) / 100) + Y = [] + + for x in X: + loc = {axis: x} + v = model.interpolateFromMasters(loc, masterValues) + Y.append(v) + + subplot = fig.add_subplot(111) + subplot.plot(X, Y, "-", **kwargs) + + +def _plotModelFromMasters3D(model, masterValues, fig, **kwargs): + assert len(model.axisOrder) == 2 + axis1, axis2 = model.axisOrder[0], model.axisOrder[1] + + axis1_min = min(loc.get(axis1, 0) for loc in model.locations) + axis1_max = max(loc.get(axis1, 0) for loc in model.locations) + axis2_min = min(loc.get(axis2, 0) for loc in model.locations) + axis2_max = max(loc.get(axis2, 0) for loc in model.locations) + + import numpy as np + + X = np.arange(axis1_min, axis1_max, (axis1_max - axis1_min) / 100) + Y = np.arange(axis2_min, axis2_max, (axis2_max - axis2_min) / 100) + X, Y = np.meshgrid(X, Y) + Z = [] + + for row_x, row_y in zip(X, Y): + z_row = [] + Z.append(z_row) + for x, y in zip(row_x, row_y): + loc = {axis1: x, axis2: y} + v = model.interpolateFromMasters(loc, masterValues) + z_row.append(v) + Z = np.array(Z) + + axis3D = fig.add_subplot(111, projection="3d") + axis3D.plot_surface(X, Y, Z, **kwargs) + + +def plotModelFromMasters(model, masterValues, fig, **kwargs): + """Plot a variation model and set of master values corresponding + to the locations to the model into a pyplot figure. Variation + model must have axisOrder of size 1 or 2.""" + if len(model.axisOrder) == 1: + _plotModelFromMasters2D(model, masterValues, fig, **kwargs) + elif len(model.axisOrder) == 2: + _plotModelFromMasters3D(model, masterValues, fig, **kwargs) + else: + raise ValueError("Only 1 or 2 axes are supported") + + +def main(args=None): + from fontTools import configLogger + + if args is None: + args = sys.argv[1:] + + # configure the library logger (for >= WARNING) + configLogger() + # comment this out to enable debug messages from logger + # log.setLevel(logging.DEBUG) + + if len(args) < 1: + print("usage: fonttools varLib.plot source.designspace", file=sys.stderr) + print(" or") + print("usage: fonttools varLib.plot location1 location2 ...", file=sys.stderr) + print(" or") + print( + "usage: fonttools varLib.plot location1=value1 location2=value2 ...", + file=sys.stderr, + ) + sys.exit(1) + + fig = pyplot.figure() + fig.set_tight_layout(True) + + if len(args) == 1 and args[0].endswith(".designspace"): + doc = DesignSpaceDocument() + doc.read(args[0]) + plotDocument(doc, fig) + else: + axes = [chr(c) for c in range(ord("A"), ord("Z") + 1)] + if "=" not in args[0]: + locs = [dict(zip(axes, (float(v) for v in s.split(",")))) for s in args] + plotLocations(locs, fig) + else: + locations = [] + masterValues = [] + for arg in args: + loc, v = arg.split("=") + locations.append(dict(zip(axes, (float(v) for v in loc.split(","))))) + masterValues.append(float(v)) + model = VariationModel(locations, axes[: len(locations[0])]) + plotModelFromMasters(model, masterValues, fig) + + pyplot.show() + + +if __name__ == "__main__": + import sys + + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/stat.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/stat.py new file mode 100644 index 0000000000000000000000000000000000000000..eacbf580aed454fea16935c2c4ec2a3706752e66 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/stat.py @@ -0,0 +1,149 @@ +"""Extra methods for DesignSpaceDocument to generate its STAT table data.""" + +from __future__ import annotations + +from typing import Dict, List, Union + +import fontTools.otlLib.builder +from fontTools.designspaceLib import ( + AxisLabelDescriptor, + DesignSpaceDocument, + DesignSpaceDocumentError, + LocationLabelDescriptor, +) +from fontTools.designspaceLib.types import Region, getVFUserRegion, locationInRegion +from fontTools.ttLib import TTFont + + +def buildVFStatTable(ttFont: TTFont, doc: DesignSpaceDocument, vfName: str) -> None: + """Build the STAT table for the variable font identified by its name in + the given document. + + Knowing which variable we're building STAT data for is needed to subset + the STAT locations to only include what the variable font actually ships. + + .. versionadded:: 5.0 + + .. seealso:: + - :func:`getStatAxes()` + - :func:`getStatLocations()` + - :func:`fontTools.otlLib.builder.buildStatTable()` + """ + for vf in doc.getVariableFonts(): + if vf.name == vfName: + break + else: + raise DesignSpaceDocumentError( + f"Cannot find the variable font by name {vfName}" + ) + + region = getVFUserRegion(doc, vf) + + # if there are not currently any mac names don't add them here, that's inconsistent + # https://github.com/fonttools/fonttools/issues/683 + macNames = any( + nr.platformID == 1 for nr in getattr(ttFont.get("name"), "names", ()) + ) + + return fontTools.otlLib.builder.buildStatTable( + ttFont, + getStatAxes(doc, region), + getStatLocations(doc, region), + doc.elidedFallbackName if doc.elidedFallbackName is not None else 2, + macNames=macNames, + ) + + +def getStatAxes(doc: DesignSpaceDocument, userRegion: Region) -> List[Dict]: + """Return a list of axis dicts suitable for use as the ``axes`` + argument to :func:`fontTools.otlLib.builder.buildStatTable()`. + + .. versionadded:: 5.0 + """ + # First, get the axis labels with explicit ordering + # then append the others in the order they appear. + maxOrdering = max( + (axis.axisOrdering for axis in doc.axes if axis.axisOrdering is not None), + default=-1, + ) + axisOrderings = [] + for axis in doc.axes: + if axis.axisOrdering is not None: + axisOrderings.append(axis.axisOrdering) + else: + maxOrdering += 1 + axisOrderings.append(maxOrdering) + return [ + dict( + tag=axis.tag, + name={"en": axis.name, **axis.labelNames}, + ordering=ordering, + values=[ + _axisLabelToStatLocation(label) + for label in axis.axisLabels + if locationInRegion({axis.name: label.userValue}, userRegion) + ], + ) + for axis, ordering in zip(doc.axes, axisOrderings) + ] + + +def getStatLocations(doc: DesignSpaceDocument, userRegion: Region) -> List[Dict]: + """Return a list of location dicts suitable for use as the ``locations`` + argument to :func:`fontTools.otlLib.builder.buildStatTable()`. + + .. versionadded:: 5.0 + """ + axesByName = {axis.name: axis for axis in doc.axes} + return [ + dict( + name={"en": label.name, **label.labelNames}, + # Location in the designspace is keyed by axis name + # Location in buildStatTable by axis tag + location={ + axesByName[name].tag: value + for name, value in label.getFullUserLocation(doc).items() + }, + flags=_labelToFlags(label), + ) + for label in doc.locationLabels + if locationInRegion(label.getFullUserLocation(doc), userRegion) + ] + + +def _labelToFlags(label: Union[AxisLabelDescriptor, LocationLabelDescriptor]) -> int: + flags = 0 + if label.olderSibling: + flags |= 1 + if label.elidable: + flags |= 2 + return flags + + +def _axisLabelToStatLocation( + label: AxisLabelDescriptor, +) -> Dict: + label_format = label.getFormat() + name = {"en": label.name, **label.labelNames} + flags = _labelToFlags(label) + if label_format == 1: + return dict(name=name, value=label.userValue, flags=flags) + if label_format == 3: + return dict( + name=name, + value=label.userValue, + linkedValue=label.linkedUserValue, + flags=flags, + ) + if label_format == 2: + res = dict( + name=name, + nominalValue=label.userValue, + flags=flags, + ) + if label.userMinimum is not None: + res["rangeMinValue"] = label.userMinimum + if label.userMaximum is not None: + res["rangeMaxValue"] = label.userMaximum + return res + raise NotImplementedError("Unknown STAT label format") diff --git a/.venv/lib/python3.12/site-packages/fontTools/varLib/varStore.py b/.venv/lib/python3.12/site-packages/fontTools/varLib/varStore.py new file mode 100644 index 0000000000000000000000000000000000000000..7f9aad63d04af86fade4fc8c0704a0a0d3cc88c0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/varLib/varStore.py @@ -0,0 +1,927 @@ +from fontTools.misc.roundTools import noRound, otRound +from fontTools.misc.intTools import bit_count +from fontTools.ttLib.tables import otTables as ot +from fontTools.varLib.models import supportScalar +from fontTools.varLib.builder import ( + buildVarRegionList, + buildVarStore, + buildVarRegion, + buildVarData, +) +from functools import partial +from collections import defaultdict +from heapq import heappush, heappop +import itertools + +NO_VARIATION_INDEX = ot.NO_VARIATION_INDEX +ot.VarStore.NO_VARIATION_INDEX = NO_VARIATION_INDEX + + +def _getLocationKey(loc): + return tuple(sorted(loc.items(), key=lambda kv: kv[0])) + + +class OnlineVarStoreBuilder(object): + def __init__(self, axisTags): + self._axisTags = axisTags + self._regionMap = {} + self._regionList = buildVarRegionList([], axisTags) + self._store = buildVarStore(self._regionList, []) + self._data = None + self._model = None + self._supports = None + self._varDataIndices = {} + self._varDataCaches = {} + self._cache = None + + def setModel(self, model): + self.setSupports(model.supports) + self._model = model + + def setSupports(self, supports): + self._model = None + self._supports = list(supports) + if self._supports and not self._supports[0]: + del self._supports[0] # Drop base master support + self._cache = None + self._data = None + + def finish(self, optimize=True): + self._regionList.RegionCount = len(self._regionList.Region) + self._store.VarDataCount = len(self._store.VarData) + for data in self._store.VarData: + data.ItemCount = len(data.Item) + data.calculateNumShorts(optimize=optimize) + return self._store + + def _add_VarData(self, num_items=1): + regionMap = self._regionMap + regionList = self._regionList + + regions = self._supports + regionIndices = [] + for region in regions: + key = _getLocationKey(region) + idx = regionMap.get(key) + if idx is None: + varRegion = buildVarRegion(region, self._axisTags) + idx = regionMap[key] = len(regionList.Region) + regionList.Region.append(varRegion) + regionIndices.append(idx) + + # Check if we have one already... + key = tuple(regionIndices) + varDataIdx = self._varDataIndices.get(key) + if varDataIdx is not None: + self._outer = varDataIdx + self._data = self._store.VarData[varDataIdx] + self._cache = self._varDataCaches[key] + if len(self._data.Item) + num_items > 0xFFFF: + # This is full. Need new one. + varDataIdx = None + + if varDataIdx is None: + self._data = buildVarData(regionIndices, [], optimize=False) + self._outer = len(self._store.VarData) + self._store.VarData.append(self._data) + self._varDataIndices[key] = self._outer + if key not in self._varDataCaches: + self._varDataCaches[key] = {} + self._cache = self._varDataCaches[key] + + def storeMasters(self, master_values, *, round=round): + deltas = self._model.getDeltas(master_values, round=round) + base = deltas.pop(0) + return base, self.storeDeltas(deltas, round=noRound) + + def storeMastersMany(self, master_values_list, *, round=round): + deltas_list = [ + self._model.getDeltas(master_values, round=round) + for master_values in master_values_list + ] + base_list = [deltas.pop(0) for deltas in deltas_list] + return base_list, self.storeDeltasMany(deltas_list, round=noRound) + + def storeDeltas(self, deltas, *, round=round): + deltas = [round(d) for d in deltas] + if len(deltas) == len(self._supports) + 1: + deltas = tuple(deltas[1:]) + else: + assert len(deltas) == len(self._supports) + deltas = tuple(deltas) + + if not self._data: + self._add_VarData() + + varIdx = self._cache.get(deltas) + if varIdx is not None: + return varIdx + + inner = len(self._data.Item) + if inner == 0xFFFF: + # Full array. Start new one. + self._add_VarData() + return self.storeDeltas(deltas, round=noRound) + self._data.addItem(deltas, round=noRound) + + varIdx = (self._outer << 16) + inner + self._cache[deltas] = varIdx + return varIdx + + def storeDeltasMany(self, deltas_list, *, round=round): + deltas_list = [[round(d) for d in deltas] for deltas in deltas_list] + deltas_list = tuple(tuple(deltas) for deltas in deltas_list) + + if not self._data: + self._add_VarData(len(deltas_list)) + + varIdx = self._cache.get(deltas_list) + if varIdx is not None: + return varIdx + + inner = len(self._data.Item) + if inner + len(deltas_list) > 0xFFFF: + # Full array. Start new one. + self._add_VarData(len(deltas_list)) + return self.storeDeltasMany(deltas_list, round=noRound) + for i, deltas in enumerate(deltas_list): + self._data.addItem(deltas, round=noRound) + + varIdx = (self._outer << 16) + inner + i + self._cache[deltas] = varIdx + + varIdx = (self._outer << 16) + inner + self._cache[deltas_list] = varIdx + + return varIdx + + +def VarData_addItem(self, deltas, *, round=round): + deltas = [round(d) for d in deltas] + + countUs = self.VarRegionCount + countThem = len(deltas) + if countUs + 1 == countThem: + deltas = list(deltas[1:]) + else: + assert countUs == countThem, (countUs, countThem) + deltas = list(deltas) + self.Item.append(deltas) + self.ItemCount = len(self.Item) + + +ot.VarData.addItem = VarData_addItem + + +def VarRegion_get_support(self, fvar_axes): + return { + fvar_axes[i].axisTag: (reg.StartCoord, reg.PeakCoord, reg.EndCoord) + for i, reg in enumerate(self.VarRegionAxis) + if reg.PeakCoord != 0 + } + + +ot.VarRegion.get_support = VarRegion_get_support + + +def VarStore___bool__(self): + return bool(self.VarData) + + +ot.VarStore.__bool__ = VarStore___bool__ + + +class VarStoreInstancer(object): + """Evaluate a VarStore's deltas at a (mutable via setLocation) location. + + Region supports are cached for the lifetime of the instancer: after + mutating the store's regions (or the fvar axes), construct a new + instancer rather than reusing this one via setLocation. + """ + + def __init__(self, varstore, fvar_axes, location={}): + self.fvar_axes = fvar_axes + assert varstore is None or varstore.Format == 1 + self._varData = varstore.VarData if varstore else [] + self._regions = varstore.VarRegionList.Region if varstore else [] + # Region supports are location-independent, so cache them for the + # lifetime of the instancer (they survive setLocation); only the + # per-region scalars, which depend on the location, are recomputed. + # This makes reusing one instancer across many locations cheap. + self._supports = {} + self.setLocation(location) + + def setLocation(self, location): + self.location = dict(location) + self._clearCaches() + + def _clearCaches(self): + self._scalars = {} + + def _getSupport(self, regionIdx): + support = self._supports.get(regionIdx) + if support is None: + support = self._regions[regionIdx].get_support(self.fvar_axes) + self._supports[regionIdx] = support + return support + + def _getScalar(self, regionIdx): + scalar = self._scalars.get(regionIdx) + if scalar is None: + scalar = supportScalar(self.location, self._getSupport(regionIdx)) + self._scalars[regionIdx] = scalar + return scalar + + @staticmethod + def interpolateFromDeltasAndScalars(deltas, scalars): + delta = 0.0 + for d, s in zip(deltas, scalars): + if not s: + continue + delta += d * s + return delta + + def __getitem__(self, varidx): + major, minor = varidx >> 16, varidx & 0xFFFF + if varidx == NO_VARIATION_INDEX: + return 0.0 + varData = self._varData + # Keep full instancing consistent with _effectiveAvar2VarIdx: out-of-range + # delta-set indices contribute zero. HarfBuzz uses the same policy: + # https://github.com/harfbuzz/harfbuzz/blob/d2df3cdcc0836299a163dc0399a6b047d19ac56c/src/hb-ot-layout-common.hh#L2912-L2918 + # https://github.com/harfbuzz/harfbuzz/blob/d2df3cdcc0836299a163dc0399a6b047d19ac56c/src/hb-ot-layout-common.hh#L3354-L3363 + if major >= len(varData) or minor >= len(varData[major].Item): + return 0.0 + scalars = [self._getScalar(ri) for ri in varData[major].VarRegionIndex] + deltas = varData[major].Item[minor] + return self.interpolateFromDeltasAndScalars(deltas, scalars) + + def interpolateFromDeltas(self, varDataIndex, deltas): + varData = self._varData + scalars = [self._getScalar(ri) for ri in varData[varDataIndex].VarRegionIndex] + return self.interpolateFromDeltasAndScalars(deltas, scalars) + + +# +# Optimizations +# +# retainFirstMap - If true, major 0 mappings are retained. Deltas for unused indices are zeroed +# advIdxes - Set of major 0 indices for advance deltas to be listed first. Other major 0 indices follow. + + +def VarStore_subset_varidxes( + self, + varIdxes, + optimize=True, + retainFirstMap=False, + advIdxes=set(), + *, + VarData="VarData", +): + # Sort out used varIdxes by major/minor. + used = defaultdict(set) + for varIdx in varIdxes: + if varIdx == NO_VARIATION_INDEX: + continue + major = varIdx >> 16 + minor = varIdx & 0xFFFF + used[major].add(minor) + del varIdxes + + # + # Subset VarData + # + + varData = getattr(self, VarData) + newVarData = [] + varDataMap = {NO_VARIATION_INDEX: NO_VARIATION_INDEX} + for major, data in enumerate(varData): + usedMinors = used.get(major) + if usedMinors is None: + continue + newMajor = len(newVarData) + newVarData.append(data) + + items = data.Item + newItems = [] + if major == 0 and retainFirstMap: + for minor in range(len(items)): + newItems.append( + items[minor] if minor in usedMinors else [0] * len(items[minor]) + ) + varDataMap[minor] = minor + else: + if major == 0: + minors = sorted(advIdxes) + sorted(usedMinors - advIdxes) + else: + minors = sorted(usedMinors) + for minor in minors: + newMinor = len(newItems) + newItems.append(items[minor]) + varDataMap[(major << 16) + minor] = (newMajor << 16) + newMinor + + data.Item = newItems + data.ItemCount = len(data.Item) + + if VarData == "VarData": + data.calculateNumShorts(optimize=optimize) + + setattr(self, VarData, newVarData) + setattr(self, VarData + "Count", len(newVarData)) + + self.prune_regions() + + return varDataMap + + +ot.VarStore.subset_varidxes = VarStore_subset_varidxes + + +def VarStore_prune_regions(self, *, VarData="VarData", VarRegionList="VarRegionList"): + """Remove unused VarRegions.""" + # + # Subset VarRegionList + # + + # Collect. + usedRegions = set() + for data in getattr(self, VarData): + usedRegions.update(data.VarRegionIndex) + # Subset. + regionList = getattr(self, VarRegionList) + regions = regionList.Region + newRegions = [] + regionMap = {} + for i in sorted(usedRegions): + regionMap[i] = len(newRegions) + newRegions.append(regions[i]) + regionList.Region = newRegions + regionList.RegionCount = len(regionList.Region) + # Map. + for data in getattr(self, VarData): + data.VarRegionIndex = [regionMap[i] for i in data.VarRegionIndex] + + +ot.VarStore.prune_regions = VarStore_prune_regions + + +def _visit(self, func): + """Recurse down from self, if type of an object is ot.Device, + call func() on it. Works on otData-style classes.""" + + if type(self) == ot.Device: + func(self) + + elif isinstance(self, list): + for that in self: + _visit(that, func) + + elif hasattr(self, "getConverters") and not hasattr(self, "postRead"): + for conv in self.getConverters(): + that = getattr(self, conv.name, None) + if that is not None: + _visit(that, func) + + elif isinstance(self, ot.ValueRecord): + for that in self.__dict__.values(): + _visit(that, func) + + +def _Device_recordVarIdx(self, s): + """Add VarIdx in this Device table (if any) to the set s.""" + if self.DeltaFormat == 0x8000: + s.add((self.StartSize << 16) + self.EndSize) + + +def Object_collect_device_varidxes(self, varidxes): + adder = partial(_Device_recordVarIdx, s=varidxes) + _visit(self, adder) + + +ot.GDEF.collect_device_varidxes = Object_collect_device_varidxes +ot.GPOS.collect_device_varidxes = Object_collect_device_varidxes + + +def _Device_mapVarIdx(self, mapping, done): + """Map VarIdx in this Device table (if any) through mapping.""" + if id(self) in done: + return + done.add(id(self)) + if self.DeltaFormat == 0x8000: + varIdx = mapping[(self.StartSize << 16) + self.EndSize] + self.StartSize = varIdx >> 16 + self.EndSize = varIdx & 0xFFFF + + +def Object_remap_device_varidxes(self, varidxes_map): + mapper = partial(_Device_mapVarIdx, mapping=varidxes_map, done=set()) + _visit(self, mapper) + + +ot.GDEF.remap_device_varidxes = Object_remap_device_varidxes +ot.GPOS.remap_device_varidxes = Object_remap_device_varidxes +ot.BASE.remap_device_varidxes = Object_remap_device_varidxes + + +class _Encoding(object): + def __init__(self, chars): + self.chars = chars + self.width = bit_count(chars) + self.columns = self._columns(chars) + self.overhead = self._characteristic_overhead(self.columns) + self.items = set() + + def append(self, row): + self.items.add(row) + + def extend(self, lst): + self.items.update(lst) + + def width_sort_key(self): + return self.width, self.chars + + @staticmethod + def _characteristic_overhead(columns): + """Returns overhead in bytes of encoding this characteristic + as a VarData.""" + c = 4 + 6 # 4 bytes for LOffset, 6 bytes for VarData header + c += bit_count(columns) * 2 + return c + + @staticmethod + def _columns(chars): + cols = 0 + i = 1 + while chars: + if chars & 0b1111: + cols |= i + chars >>= 4 + i <<= 1 + return cols + + def gain_from_merging(self, other_encoding): + combined_chars = other_encoding.chars | self.chars + combined_width = bit_count(combined_chars) + combined_columns = self.columns | other_encoding.columns + combined_overhead = _Encoding._characteristic_overhead(combined_columns) + combined_gain = ( + +self.overhead + + other_encoding.overhead + - combined_overhead + - (combined_width - self.width) * len(self.items) + - (combined_width - other_encoding.width) * len(other_encoding.items) + ) + return combined_gain + + +class _EncodingDict(dict): + def __missing__(self, chars): + r = self[chars] = _Encoding(chars) + return r + + def add_row(self, row): + chars = self._row_characteristics(row) + self[chars].append(row) + + @staticmethod + def _row_characteristics(row): + """Returns encoding characteristics for a row.""" + longWords = False + + chars = 0 + i = 1 + for v in row: + if v: + chars += i + if not (-128 <= v <= 127): + chars += i * 0b0010 + if not (-32768 <= v <= 32767): + longWords = True + break + i <<= 4 + + if longWords: + # Redo; only allow 2byte/4byte encoding + chars = 0 + i = 1 + for v in row: + if v: + chars += i * 0b0011 + if not (-32768 <= v <= 32767): + chars += i * 0b1100 + i <<= 4 + + return chars + + +def VarStore_optimize(self, use_NO_VARIATION_INDEX=True, quantization=1): + """Optimize storage. Returns mapping from old VarIdxes to new ones.""" + + # Overview: + # + # For each VarData row, we first extend it with zeroes to have + # one column per region in VarRegionList. We then group the + # rows into _Encoding objects, by their "characteristic" bitmap. + # The characteristic bitmap is a binary number representing how + # many bytes each column of the data takes up to encode. Each + # column is encoded in four bits. For example, if a column has + # only values in the range -128..127, it would only have a single + # bit set in the characteristic bitmap for that column. If it has + # values in the range -32768..32767, it would have two bits set. + # The number of ones in the characteristic bitmap is the "width" + # of the encoding. + # + # Each encoding as such has a number of "active" (ie. non-zero) + # columns. The overhead of encoding the characteristic bitmap + # is 10 bytes, plus 2 bytes per active column. + # + # When an encoding is merged into another one, if the characteristic + # of the old encoding is a subset of the new one, then the overhead + # of the old encoding is completely eliminated. However, each row + # now would require more bytes to encode, to the tune of one byte + # per characteristic bit that is active in the new encoding but not + # in the old one. + # + # The "gain" of merging two encodings is how many bytes we save by doing so. + # + # High-level algorithm: + # + # - Each encoding has a minimal way to encode it. However, because + # of the overhead of encoding the characteristic bitmap, it may + # be beneficial to merge two encodings together, if there is + # gain in doing so. As such, we need to search for the best + # such successive merges. + # + # Algorithm: + # + # - Put all encodings into a "todo" list. + # + # - Sort todo list (for stability) by width_sort_key(), which is a tuple + # of the following items: + # * The "width" of the encoding. + # * The characteristic bitmap of the encoding, with higher-numbered + # columns compared first. + # + # - Make a priority-queue of the gain from combining each two + # encodings in the todo list. The priority queue is sorted by + # decreasing gain. Only positive gains are included. + # + # - While priority queue is not empty: + # - Pop the first item from the priority queue, + # - Merge the two encodings it represents, + # - Remove the two encodings from the todo list, + # - Insert positive gains from combining the new encoding with + # all existing todo list items into the priority queue, + # - If a todo list item with the same characteristic bitmap as + # the new encoding exists, remove it from the todo list and + # merge it into the new encoding. + # - Insert the new encoding into the todo list, + # + # - Encode all remaining items in the todo list. + # + # The output is then sorted for stability, in the following way: + # - The VarRegionList of the input is kept intact. + # - The VarData is sorted by the same width_sort_key() used at the beginning. + # - Within each VarData, the items are sorted as vectors of numbers. + # + # Finally, each VarData is optimized to remove the empty columns and + # reorder columns as needed. + + # TODO + # Check that no two VarRegions are the same; if they are, fold them. + + n = len(self.VarRegionList.Region) # Number of columns + zeroes = [0] * n + + front_mapping = {} # Map from old VarIdxes to full row tuples + + encodings = _EncodingDict() + + # Collect all items into a set of full rows (with lots of zeroes.) + for major, data in enumerate(self.VarData): + regionIndices = data.VarRegionIndex + + for minor, item in enumerate(data.Item): + row = list(zeroes) + + if quantization == 1: + for regionIdx, v in zip(regionIndices, item): + row[regionIdx] += v + else: + for regionIdx, v in zip(regionIndices, item): + row[regionIdx] += ( + round(v / quantization) * quantization + ) # TODO https://github.com/fonttools/fonttools/pull/3126#discussion_r1205439785 + + row = tuple(row) + + if use_NO_VARIATION_INDEX and not any(row): + front_mapping[(major << 16) + minor] = None + continue + + encodings.add_row(row) + front_mapping[(major << 16) + minor] = row + + # Prepare for the main algorithm. + todo = sorted(encodings.values(), key=_Encoding.width_sort_key) + del encodings + + # Repeatedly pick two best encodings to combine, and combine them. + + heap = [] + for i, encoding in enumerate(todo): + for j in range(i + 1, len(todo)): + other_encoding = todo[j] + combining_gain = encoding.gain_from_merging(other_encoding) + if combining_gain > 0: + heappush(heap, (-combining_gain, i, j)) + + while heap: + _, i, j = heappop(heap) + if todo[i] is None or todo[j] is None: + continue + + encoding, other_encoding = todo[i], todo[j] + todo[i], todo[j] = None, None + + # Combine the two encodings + combined_chars = other_encoding.chars | encoding.chars + combined_encoding = _Encoding(combined_chars) + combined_encoding.extend(encoding.items) + combined_encoding.extend(other_encoding.items) + + for k, enc in enumerate(todo): + if enc is None: + continue + + # In the unlikely event that the same encoding exists already, + # combine it. + if enc.chars == combined_chars: + combined_encoding.extend(enc.items) + todo[k] = None + continue + + combining_gain = combined_encoding.gain_from_merging(enc) + if combining_gain > 0: + heappush(heap, (-combining_gain, k, len(todo))) + + todo.append(combined_encoding) + + encodings = [encoding for encoding in todo if encoding is not None] + + # Assemble final store. + back_mapping = {} # Mapping from full rows to new VarIdxes + encodings.sort(key=_Encoding.width_sort_key) + self.VarData = [] + for encoding in encodings: + items = sorted(encoding.items) + + while items: + major = len(self.VarData) + data = ot.VarData() + self.VarData.append(data) + data.VarRegionIndex = range(n) + data.VarRegionCount = len(data.VarRegionIndex) + + # Each major can only encode up to 0xFFFF entries. + data.Item, items = items[:0xFFFF], items[0xFFFF:] + + for minor, item in enumerate(data.Item): + back_mapping[item] = (major << 16) + minor + + # Compile final mapping. + varidx_map = {NO_VARIATION_INDEX: NO_VARIATION_INDEX} + for k, v in front_mapping.items(): + varidx_map[k] = back_mapping[v] if v is not None else NO_VARIATION_INDEX + + # Recalculate things and go home. + self.VarRegionList.RegionCount = len(self.VarRegionList.Region) + self.VarDataCount = len(self.VarData) + for data in self.VarData: + data.ItemCount = len(data.Item) + data.optimize() + + # Remove unused regions. + self.prune_regions() + + return varidx_map + + +ot.VarStore.optimize = VarStore_optimize + + +def _tentValue(v, start, peak, end): + """Per-axis support-scalar factor at coordinate v (supportScalar semantics).""" + if v == peak: + return 1.0 + if v <= start or end <= v: + return 0.0 + if v < peak: + return (v - start) / (peak - start) + return (end - v) / (end - peak) + + +# Maximum number of grid vertices VarStore_getExtremes enumerates for the +# exact answer before falling back to the (looser but conservative and cheap) +# interval bound. The grid is authoring-controlled, so a cap is needed to keep +# crafted fonts from hanging the instancer. +_GET_EXTREMES_MAX_GRID = 1 << 14 +_F2DOT14_UNIT = 1.0 / (1 << 14) + + +def VarStore_getExtremes(self, varIdx, fvarAxes, axisLimits, identityAxisIndex=None): + """Conservatively bound the value this VarStore produces for varIdx. + + Returns (minV, maxV) in F2Dot14 delta units, guaranteed to cover the + truly reachable range as the input axes vary over their extents: + [-1, +1] per axis, or the [min, max] interval from axisLimits (a dict of + axis tag to a (min, default, max, ...) sequence) for axes listed there. + If identityAxisIndex is not None, that axis's own identity contribution + (its coordinate, in F2Dot14 units) is added to the bound. + + Before the final OpenType rounding, the produced value is piecewise + multilinear in the axis coordinates (each region's scalar is a product + of independent per-axis tents), so over the box its exact extremes are + attained at vertices of the grid formed by each axis's tent + breakpoints. One-sided tents (start == peak or peak == end) are + discontinuous at their peak, so the grid also includes the adjacent + F2Dot14 coordinate on the open side. When that grid is small enough + (real fonts) it is enumerated and the result is exact; otherwise the + result falls back to a per-region interval bound, which ignores + correlations between regions and may be wider than the true range — + never narrower. Callers use this to cull provably-unreachable + variation data, so conservativeness is a soundness requirement, not a + nicety. The fallback costs O(regions × axes); the cap on the exact + path keeps crafted fonts from hanging the instancer. + + Raw extrema are rounded only after summing the identity and delta terms, + matching avar2 processing. + """ + + def axisInterval(axisIdx): + tag = fvarAxes[axisIdx].axisTag + if tag in axisLimits: + limits = axisLimits[tag] + return limits[0], limits[2] + return -1.0, +1.0 + + if varIdx == NO_VARIATION_INDEX: + activeRegions = [] + else: + major = varIdx >> 16 + minor = varIdx & 0xFFFF + varData = self.VarData[major] + regions = self.VarRegionList.Region + deltas = varData.Item[minor] + # Per region: (delta, [(axisIndex, start, peak, end), ...]) with the + # axes supportScalar would ignore already dropped. + activeRegions = [] + for regionIndex, delta in zip(varData.VarRegionIndex, deltas): + if not delta: + continue + region = regions[regionIndex] + tents = [] + for i, regionAxis in enumerate(region.VarRegionAxis): + start = regionAxis.StartCoord + peak = regionAxis.PeakCoord + end = regionAxis.EndCoord + # Mirror supportScalar's OT rules for axes it ignores. + if peak == 0 or start > peak or peak > end: + continue + if start < 0 and end > 0: + continue + tents.append((i, start, peak, end)) + activeRegions.append((delta, tents)) + + # Try the exact path: enumerate the breakpoint grid. + breakpoints = {} # axisIndex -> set of coordinates + if identityAxisIndex is not None: + lo, hi = axisInterval(identityAxisIndex) + breakpoints[identityAxisIndex] = {lo, hi} + for delta, tents in activeRegions: + for i, start, peak, end in tents: + if i not in breakpoints: + lo, hi = axisInterval(i) + breakpoints[i] = {lo, hi} + lo, hi = axisInterval(i) + breakpoints[i].update(min(max(v, lo), hi) for v in (start, peak, end)) + if start == peak: + breakpoints[i].add(min(max(peak - _F2DOT14_UNIT, lo), hi)) + if peak == end: + breakpoints[i].add(min(max(peak + _F2DOT14_UNIT, lo), hi)) + gridSize = 1 + for points in breakpoints.values(): + gridSize *= len(points) + if gridSize > _GET_EXTREMES_MAX_GRID: + break + + if gridSize <= _GET_EXTREMES_MAX_GRID: + # Exact: evaluate at every grid vertex. Within each grid cell every + # region scalar is multilinear, so the extremes lie on vertices. + axisIndices = sorted(breakpoints) + axisPos = {i: n for n, i in enumerate(axisIndices)} + minV = maxV = None + for vertex in itertools.product(*(sorted(breakpoints[i]) for i in axisIndices)): + v = 0.0 + for delta, tents in activeRegions: + scalar = 1.0 + for i, start, peak, end in tents: + scalar *= _tentValue(vertex[axisPos[i]], start, peak, end) + if scalar == 0: + break + if scalar: + v += delta * scalar + if identityAxisIndex is not None: + v += otRound(vertex[axisPos[identityAxisIndex]] * 16384) + if minV is None: + minV = maxV = v + else: + minV = min(minV, v) + maxV = max(maxV, v) + return otRound(minV), otRound(maxV) + + # Fallback: per-region interval arithmetic. Each region's scalar range + # over the box is exact (per-axis tent factors are independent), but + # correlations between regions (and with the identity term) are ignored. + minV = maxV = 0.0 + for delta, tents in activeRegions: + scalarMin = scalarMax = 1.0 + for i, start, peak, end in tents: + lo, hi = axisInterval(i) + # The tent rises to the peak then falls, so over [lo, hi] the + # maximum is at the clamped peak, the minimum at an endpoint. + scalarMax *= _tentValue(min(max(peak, lo), hi), start, peak, end) + scalarMin *= min( + _tentValue(lo, start, peak, end), + _tentValue(hi, start, peak, end), + ) + if scalarMax == 0: + break + if scalarMax == 0: + continue + minV += min(delta * scalarMin, delta * scalarMax) + maxV += max(delta * scalarMin, delta * scalarMax) + + if identityAxisIndex is not None: + lo, hi = axisInterval(identityAxisIndex) + minV += otRound(lo * 16384) + maxV += otRound(hi * 16384) + + return otRound(minV), otRound(maxV) + + +ot.VarStore.getExtremes = VarStore_getExtremes + + +def main(args=None): + """Optimize a font's GDEF variation store""" + from argparse import ArgumentParser + from fontTools import configLogger + from fontTools.ttLib import TTFont + from fontTools.ttLib.tables.otBase import OTTableWriter + + parser = ArgumentParser(prog="varLib.varStore", description=main.__doc__) + parser.add_argument("--quantization", type=int, default=1) + parser.add_argument("fontfile") + parser.add_argument("outfile", nargs="?") + options = parser.parse_args(args) + + # TODO: allow user to configure logging via command-line options + configLogger(level="INFO") + + quantization = options.quantization + fontfile = options.fontfile + outfile = options.outfile + + font = TTFont(fontfile) + gdef = font["GDEF"] + store = gdef.table.VarStore + + writer = OTTableWriter() + store.compile(writer, font) + size = len(writer.getAllData()) + print("Before: %7d bytes" % size) + + varidx_map = store.optimize(quantization=quantization) + + writer = OTTableWriter() + store.compile(writer, font) + size = len(writer.getAllData()) + print("After: %7d bytes" % size) + + if outfile is not None: + gdef.table.remap_device_varidxes(varidx_map) + if "GPOS" in font: + font["GPOS"].table.remap_device_varidxes(varidx_map) + + font.save(outfile) + + +if __name__ == "__main__": + import sys + + if len(sys.argv) > 1: + sys.exit(main()) + import doctest + + sys.exit(doctest.testmod().failed) diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/__init__.py b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..886aa3a7864523656e609dd602683d73f985f467 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__init__.py @@ -0,0 +1,5 @@ +"""fontTools.voltLib -- a package for dealing with Visual OpenType Layout Tool +(VOLT) files.""" + +# See +# http://www.microsoft.com/typography/VOLT.mspx diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/__main__.py b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa2c3b3e610ddc1f9161dd2a956c783bd38f4079 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__main__.py @@ -0,0 +1,206 @@ +import argparse +import logging +import sys +from io import StringIO +from pathlib import Path + +from fontTools import configLogger +from fontTools.feaLib.builder import addOpenTypeFeaturesFromString +from fontTools.feaLib.error import FeatureLibError +from fontTools.feaLib.lexer import Lexer +from fontTools.misc.cliTools import makeOutputFileName +from fontTools.ttLib import TTFont, TTLibError +from fontTools.voltLib.parser import Parser +from fontTools.voltLib.voltToFea import TABLES, VoltToFea + +log = logging.getLogger("fontTools.feaLib") + +SUPPORTED_TABLES = TABLES + ["cmap"] + + +def invalid_fea_glyph_name(name): + """Check if the glyph name is valid according to FEA syntax.""" + if name[0] not in Lexer.CHAR_NAME_START_: + return True + if any(c not in Lexer.CHAR_NAME_CONTINUATION_ for c in name[1:]): + return True + return False + + +def sanitize_glyph_name(name): + """Sanitize the glyph name to ensure it is valid according to FEA syntax.""" + sanitized = "" + for i, c in enumerate(name): + if i == 0 and c not in Lexer.CHAR_NAME_START_: + sanitized += "a" + c + elif c not in Lexer.CHAR_NAME_CONTINUATION_: + sanitized += "_" + else: + sanitized += c + + return sanitized + + +def main(args=None): + """Build tables from a MS VOLT project into an OTF font""" + parser = argparse.ArgumentParser( + description="Use fontTools to compile MS VOLT projects." + ) + parser.add_argument( + "input", + metavar="INPUT", + help="Path to the input font/VTP file to process", + type=Path, + ) + parser.add_argument( + "-f", + "--font", + metavar="INPUT_FONT", + help="Path to the input font (if INPUT is a VTP file)", + type=Path, + ) + parser.add_argument( + "-o", + "--output", + dest="output", + metavar="OUTPUT", + help="Path to the output font.", + type=Path, + ) + parser.add_argument( + "-t", + "--tables", + metavar="TABLE_TAG", + choices=SUPPORTED_TABLES, + nargs="+", + help="Specify the table(s) to be built.", + ) + parser.add_argument( + "-F", + "--debug-feature-file", + help="Write the generated feature file to disk.", + action="store_true", + ) + parser.add_argument( + "--ship", + help="Remove source VOLT tables from output font.", + action="store_true", + ) + parser.add_argument( + "-v", + "--verbose", + help="Increase the logger verbosity. Multiple -v options are allowed.", + action="count", + default=0, + ) + parser.add_argument( + "-T", + "--traceback", + help="show traceback for exceptions.", + action="store_true", + ) + options = parser.parse_args(args) + + levels = ["WARNING", "INFO", "DEBUG"] + configLogger(level=levels[min(len(levels) - 1, options.verbose)]) + + output_font = options.output or Path( + makeOutputFileName(options.font or options.input) + ) + log.info(f"Compiling MS VOLT to '{output_font}'") + + file_or_path = options.input + font = None + + # If the input is a font file, extract the VOLT data from the "TSIV" table + try: + font = TTFont(file_or_path) + if "TSIV" in font: + file_or_path = StringIO(font["TSIV"].data.decode("utf-8")) + else: + log.error('"TSIV" table is missing') + return 1 + except TTLibError: + pass + + # If input is not a font file, the font must be provided + if font is None: + if not options.font: + log.error("Please provide an input font") + return 1 + font = TTFont(options.font) + + # FEA syntax does not allow some glyph names that VOLT accepts, so if we + # found such glyph name we will temporarily rename such glyphs. + glyphOrder = font.getGlyphOrder() + tempGlyphOrder = None + if any(invalid_fea_glyph_name(n) for n in glyphOrder): + tempGlyphOrder = [] + for n in glyphOrder: + if invalid_fea_glyph_name(n): + n = sanitize_glyph_name(n) + existing = set(tempGlyphOrder) | set(glyphOrder) + while n in existing: + n = "a" + n + tempGlyphOrder.append(n) + font.setGlyphOrder(tempGlyphOrder) + + doc = Parser(file_or_path).parse() + + log.info("Converting VTP data to FEA") + converter = VoltToFea(doc, font) + try: + fea = converter.convert(options.tables, ignore_unsupported_settings=True) + except NotImplementedError as e: + if options.traceback: + raise + location = getattr(e.args[0], "location", None) + message = f'"{e}" is not supported' + if location: + path, line, column = location + log.error(f"{path}:{line}:{column}: {message}") + else: + log.error(message) + return 1 + + fea_filename = options.input + if options.debug_feature_file: + fea_filename = output_font.with_suffix(".fea") + log.info(f"Writing FEA to '{fea_filename}'") + with open(fea_filename, "w") as fp: + fp.write(fea) + + log.info("Compiling FEA to OpenType tables") + try: + addOpenTypeFeaturesFromString( + font, + fea, + filename=fea_filename, + tables=options.tables, + ) + except FeatureLibError as e: + if options.traceback: + raise + log.error(e) + return 1 + + if options.ship: + for tag in ["TSIV", "TSIS", "TSIP", "TSID"]: + if tag in font: + del font[tag] + + # Restore original glyph names. + if tempGlyphOrder: + import io + + f = io.BytesIO() + font.save(f) + font = TTFont(f) + font.setGlyphOrder(glyphOrder) + font["post"].extraNames = [] + + font.save(output_font) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..875b279e0b387a91273a231f4a17a341c5de9d37 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d133e3e8b6555fe3dc32e64166785e545eafddc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/__main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/ast.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/ast.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..159a1d6d3e3770374c029bb6bfb6089bd6c4d23a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/ast.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/error.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34fcdaae38a5233de95cac676e570fbc191a9f7d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/error.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/lexer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/lexer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e579b73d588e79157d07bc55c68448d7bd9ff1dd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/lexer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/parser.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e6d0ed60d695b4d062c296951aea46f7adfb4a8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/parser.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/voltToFea.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/voltToFea.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adf98f996073bfa08d8fd550bf72f9aa5c8ba19c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fontTools/voltLib/__pycache__/voltToFea.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/ast.py b/.venv/lib/python3.12/site-packages/fontTools/voltLib/ast.py new file mode 100644 index 0000000000000000000000000000000000000000..dba8f4d45b3e16a3f7a13aa43daf52f0f6bc45e0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/voltLib/ast.py @@ -0,0 +1,452 @@ +from fontTools.voltLib.error import VoltLibError +from typing import NamedTuple + + +class Pos(NamedTuple): + adv: int + dx: int + dy: int + adv_adjust_by: dict + dx_adjust_by: dict + dy_adjust_by: dict + + def __str__(self): + res = " POS" + for attr in ("adv", "dx", "dy"): + value = getattr(self, attr) + if value is not None: + res += f" {attr.upper()} {value}" + adjust_by = getattr(self, f"{attr}_adjust_by", {}) + for size, adjustment in adjust_by.items(): + res += f" ADJUST_BY {adjustment} AT {size}" + res += " END_POS" + return res + + +class Element(object): + def __init__(self, location=None): + self.location = location + + def build(self, builder): + pass + + def __str__(self): + raise NotImplementedError + + +class Statement(Element): + pass + + +class Expression(Element): + pass + + +class VoltFile(Statement): + def __init__(self): + Statement.__init__(self, location=None) + self.statements = [] + + def build(self, builder): + for s in self.statements: + s.build(builder) + + def __str__(self): + return "\n" + "\n".join(str(s) for s in self.statements) + " END\n" + + +class GlyphDefinition(Statement): + def __init__(self, name, gid, gunicode, gtype, components, location=None): + Statement.__init__(self, location) + self.name = name + self.id = gid + self.unicode = gunicode + self.type = gtype + self.components = components + + def __str__(self): + res = f'DEF_GLYPH "{self.name}" ID {self.id}' + if self.unicode is not None: + if len(self.unicode) > 1: + unicodes = ",".join(f"U+{u:04X}" for u in self.unicode) + res += f' UNICODEVALUES "{unicodes}"' + else: + res += f" UNICODE {self.unicode[0]}" + if self.type is not None: + res += f" TYPE {self.type}" + if self.components is not None: + res += f" COMPONENTS {self.components}" + res += " END_GLYPH" + return res + + +class GroupDefinition(Statement): + def __init__(self, name, enum, location=None): + Statement.__init__(self, location) + self.name = name + self.enum = enum + self.glyphs_ = None + + def glyphSet(self, groups=None): + if groups is not None and self.name in groups: + raise VoltLibError( + 'Group "%s" contains itself.' % (self.name), self.location + ) + if self.glyphs_ is None: + if groups is None: + groups = set({self.name}) + else: + groups.add(self.name) + self.glyphs_ = self.enum.glyphSet(groups) + return self.glyphs_ + + def __str__(self): + enum = self.enum and str(self.enum) or "" + return f'DEF_GROUP "{self.name}"\n{enum}\nEND_GROUP' + + +class GlyphName(Expression): + """A single glyph name, such as cedilla.""" + + def __init__(self, glyph, location=None): + Expression.__init__(self, location) + self.glyph = glyph + + def glyphSet(self): + return (self.glyph,) + + def __str__(self): + return f' GLYPH "{self.glyph}"' + + +class Enum(Expression): + """An enum""" + + def __init__(self, enum, location=None): + Expression.__init__(self, location) + self.enum = enum + + def __iter__(self): + for e in self.glyphSet(): + yield e + + def glyphSet(self, groups=None): + glyphs = [] + for element in self.enum: + if isinstance(element, (GroupName, Enum)): + glyphs.extend(element.glyphSet(groups)) + else: + glyphs.extend(element.glyphSet()) + return tuple(glyphs) + + def __str__(self): + enum = "".join(str(e) for e in self.enum) + return f" ENUM{enum} END_ENUM" + + +class GroupName(Expression): + """A glyph group""" + + def __init__(self, group, parser, location=None): + Expression.__init__(self, location) + self.group = group + self.parser_ = parser + + def glyphSet(self, groups=None): + group = self.parser_.resolve_group(self.group) + if group is not None: + self.glyphs_ = group.glyphSet(groups) + return self.glyphs_ + else: + raise VoltLibError( + 'Group "%s" is used but undefined.' % (self.group), self.location + ) + + def __str__(self): + return f' GROUP "{self.group}"' + + +class Range(Expression): + """A glyph range""" + + def __init__(self, start, end, parser, location=None): + Expression.__init__(self, location) + self.start = start + self.end = end + self.parser = parser + + def glyphSet(self): + return tuple(self.parser.glyph_range(self.start, self.end)) + + def __str__(self): + return f' RANGE "{self.start}" TO "{self.end}"' + + +class ScriptDefinition(Statement): + def __init__(self, name, tag, langs, location=None): + Statement.__init__(self, location) + self.name = name + self.tag = tag + self.langs = langs + + def __str__(self): + res = "DEF_SCRIPT" + if self.name is not None: + res += f' NAME "{self.name}"' + res += f' TAG "{self.tag}"\n\n' + for lang in self.langs: + res += f"{lang}" + res += "END_SCRIPT" + return res + + +class LangSysDefinition(Statement): + def __init__(self, name, tag, features, location=None): + Statement.__init__(self, location) + self.name = name + self.tag = tag + self.features = features + + def __str__(self): + res = "DEF_LANGSYS" + if self.name is not None: + res += f' NAME "{self.name}"' + res += f' TAG "{self.tag}"\n\n' + for feature in self.features: + res += f"{feature}" + res += "END_LANGSYS\n" + return res + + +class FeatureDefinition(Statement): + def __init__(self, name, tag, lookups, location=None): + Statement.__init__(self, location) + self.name = name + self.tag = tag + self.lookups = lookups + + def __str__(self): + res = f'DEF_FEATURE NAME "{self.name}" TAG "{self.tag}"\n' + res += " " + " ".join(f'LOOKUP "{l}"' for l in self.lookups) + "\n" + res += "END_FEATURE\n" + return res + + +class LookupDefinition(Statement): + def __init__( + self, + name, + process_base, + process_marks, + mark_glyph_set, + direction, + reversal, + comments, + context, + sub, + pos, + location=None, + ): + Statement.__init__(self, location) + self.name = name + self.process_base = process_base + self.process_marks = process_marks + self.mark_glyph_set = mark_glyph_set + self.direction = direction + self.reversal = reversal + self.comments = comments + self.context = context + self.sub = sub + self.pos = pos + + def __str__(self): + res = f'DEF_LOOKUP "{self.name}"' + res += f' {self.process_base and "PROCESS_BASE" or "SKIP_BASE"}' + if self.process_marks: + res += " PROCESS_MARKS " + if self.mark_glyph_set: + res += f'MARK_GLYPH_SET "{self.mark_glyph_set}"' + elif isinstance(self.process_marks, str): + res += f'"{self.process_marks}"' + else: + res += "ALL" + else: + res += " SKIP_MARKS" + if self.direction is not None: + res += f" DIRECTION {self.direction}" + if self.reversal: + res += " REVERSAL" + if self.comments is not None: + comments = self.comments.replace("\n", r"\n") + res += f'\nCOMMENTS "{comments}"' + if self.context: + res += "\n" + "\n".join(str(c) for c in self.context) + else: + res += "\nIN_CONTEXT\nEND_CONTEXT" + if self.sub: + res += f"\n{self.sub}" + if self.pos: + res += f"\n{self.pos}" + return res + + +class SubstitutionDefinition(Statement): + def __init__(self, mapping, location=None): + Statement.__init__(self, location) + self.mapping = mapping + + def __str__(self): + res = "AS_SUBSTITUTION\n" + for src, dst in self.mapping.items(): + src = "".join(str(s) for s in src) + dst = "".join(str(d) for d in dst) + res += f"SUB{src}\nWITH{dst}\nEND_SUB\n" + res += "END_SUBSTITUTION" + return res + + +class SubstitutionSingleDefinition(SubstitutionDefinition): + pass + + +class SubstitutionMultipleDefinition(SubstitutionDefinition): + pass + + +class SubstitutionLigatureDefinition(SubstitutionDefinition): + pass + + +class SubstitutionAlternateDefinition(SubstitutionDefinition): + pass + + +class SubstitutionReverseChainingSingleDefinition(SubstitutionDefinition): + pass + + +class PositionAttachDefinition(Statement): + def __init__(self, coverage, coverage_to, location=None): + Statement.__init__(self, location) + self.coverage = coverage + self.coverage_to = coverage_to + + def __str__(self): + coverage = "".join(str(c) for c in self.coverage) + res = f"AS_POSITION\nATTACH{coverage}\nTO" + for coverage, anchor in self.coverage_to: + coverage = "".join(str(c) for c in coverage) + res += f'{coverage} AT ANCHOR "{anchor}"' + res += "\nEND_ATTACH\nEND_POSITION" + return res + + +class PositionAttachCursiveDefinition(Statement): + def __init__(self, coverages_exit, coverages_enter, location=None): + Statement.__init__(self, location) + self.coverages_exit = coverages_exit + self.coverages_enter = coverages_enter + + def __str__(self): + res = "AS_POSITION\nATTACH_CURSIVE" + for coverage in self.coverages_exit: + coverage = "".join(str(c) for c in coverage) + res += f"\nEXIT {coverage}" + for coverage in self.coverages_enter: + coverage = "".join(str(c) for c in coverage) + res += f"\nENTER {coverage}" + res += "\nEND_ATTACH\nEND_POSITION" + return res + + +class PositionAdjustPairDefinition(Statement): + def __init__(self, coverages_1, coverages_2, adjust_pair, location=None): + Statement.__init__(self, location) + self.coverages_1 = coverages_1 + self.coverages_2 = coverages_2 + self.adjust_pair = adjust_pair + + def __str__(self): + res = "AS_POSITION\nADJUST_PAIR\n" + for coverage in self.coverages_1: + coverage = " ".join(str(c) for c in coverage) + res += f" FIRST {coverage}" + res += "\n" + for coverage in self.coverages_2: + coverage = " ".join(str(c) for c in coverage) + res += f" SECOND {coverage}" + res += "\n" + for (id_1, id_2), (pos_1, pos_2) in self.adjust_pair.items(): + res += f" {id_1} {id_2} BY{pos_1}{pos_2}\n" + res += "\nEND_ADJUST\nEND_POSITION" + return res + + +class PositionAdjustSingleDefinition(Statement): + def __init__(self, adjust_single, location=None): + Statement.__init__(self, location) + self.adjust_single = adjust_single + + def __str__(self): + res = "AS_POSITION\nADJUST_SINGLE" + for coverage, pos in self.adjust_single: + coverage = "".join(str(c) for c in coverage) + res += f"{coverage} BY{pos}" + res += "\nEND_ADJUST\nEND_POSITION" + return res + + +class ContextDefinition(Statement): + def __init__(self, ex_or_in, left=None, right=None, location=None): + Statement.__init__(self, location) + self.ex_or_in = ex_or_in + self.left = left if left is not None else [] + self.right = right if right is not None else [] + + def __str__(self): + res = self.ex_or_in + "\n" + for coverage in self.left: + coverage = "".join(str(c) for c in coverage) + res += f" LEFT{coverage}\n" + for coverage in self.right: + coverage = "".join(str(c) for c in coverage) + res += f" RIGHT{coverage}\n" + res += "END_CONTEXT" + return res + + +class AnchorDefinition(Statement): + def __init__(self, name, gid, glyph_name, component, locked, pos, location=None): + Statement.__init__(self, location) + self.name = name + self.gid = gid + self.glyph_name = glyph_name + self.component = component + self.locked = locked + self.pos = pos + + def __str__(self): + locked = self.locked and " LOCKED" or "" + return ( + f'DEF_ANCHOR "{self.name}"' + f" ON {self.gid}" + f" GLYPH {self.glyph_name}" + f" COMPONENT {self.component}" + f"{locked}" + f" AT {self.pos} END_ANCHOR" + ) + + +class SettingDefinition(Statement): + def __init__(self, name, value, location=None): + Statement.__init__(self, location) + self.name = name + self.value = value + + def __str__(self): + if self.value is True: + return f"{self.name}" + if isinstance(self.value, (tuple, list)): + value = " ".join(str(v) for v in self.value) + return f"{self.name} {value}" + return f"{self.name} {self.value}" diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/error.py b/.venv/lib/python3.12/site-packages/fontTools/voltLib/error.py new file mode 100644 index 0000000000000000000000000000000000000000..c51d3b8fdc45afdb7bafbeb13a951264e0228985 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/voltLib/error.py @@ -0,0 +1,12 @@ +class VoltLibError(Exception): + def __init__(self, message, location): + Exception.__init__(self, message) + self.location = location + + def __str__(self): + message = Exception.__str__(self) + if self.location: + path, line, column = self.location + return "%s:%d:%d: %s" % (path, line, column, message) + else: + return message diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/lexer.py b/.venv/lib/python3.12/site-packages/fontTools/voltLib/lexer.py new file mode 100644 index 0000000000000000000000000000000000000000..706b21bbb19717a32025e505c3ae4a2e5f2154ec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/voltLib/lexer.py @@ -0,0 +1,99 @@ +from fontTools.voltLib.error import VoltLibError + + +class Lexer(object): + NUMBER = "NUMBER" + STRING = "STRING" + NAME = "NAME" + NEWLINE = "NEWLINE" + + CHAR_WHITESPACE_ = " \t" + CHAR_NEWLINE_ = "\r\n" + CHAR_DIGIT_ = "0123456789" + CHAR_UC_LETTER_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + CHAR_LC_LETTER_ = "abcdefghijklmnopqrstuvwxyz" + CHAR_UNDERSCORE_ = "_" + CHAR_PERIOD_ = "." + CHAR_NAME_START_ = ( + CHAR_UC_LETTER_ + CHAR_LC_LETTER_ + CHAR_PERIOD_ + CHAR_UNDERSCORE_ + ) + CHAR_NAME_CONTINUATION_ = CHAR_NAME_START_ + CHAR_DIGIT_ + + def __init__(self, text, filename): + self.filename_ = filename + self.line_ = 1 + self.pos_ = 0 + self.line_start_ = 0 + self.text_ = text + self.text_length_ = len(text) + + def __iter__(self): + return self + + def next(self): # Python 2 + return self.__next__() + + def __next__(self): # Python 3 + while True: + token_type, token, location = self.next_() + if token_type not in {Lexer.NEWLINE}: + return (token_type, token, location) + + def location_(self): + column = self.pos_ - self.line_start_ + 1 + return (self.filename_ or "<volt>", self.line_, column) + + def next_(self): + self.scan_over_(Lexer.CHAR_WHITESPACE_) + location = self.location_() + start = self.pos_ + text = self.text_ + limit = len(text) + if start >= limit: + raise StopIteration() + cur_char = text[start] + next_char = text[start + 1] if start + 1 < limit else None + + if cur_char == "\n": + self.pos_ += 1 + self.line_ += 1 + self.line_start_ = self.pos_ + return (Lexer.NEWLINE, None, location) + if cur_char == "\r": + self.pos_ += 2 if next_char == "\n" else 1 + self.line_ += 1 + self.line_start_ = self.pos_ + return (Lexer.NEWLINE, None, location) + if cur_char == '"': + self.pos_ += 1 + self.scan_until_('"\r\n') + if self.pos_ < self.text_length_ and self.text_[self.pos_] == '"': + self.pos_ += 1 + return (Lexer.STRING, text[start + 1 : self.pos_ - 1], location) + else: + raise VoltLibError("Expected '\"' to terminate string", location) + if cur_char in Lexer.CHAR_NAME_START_: + self.pos_ += 1 + self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_) + token = text[start : self.pos_] + return (Lexer.NAME, token, location) + if cur_char in Lexer.CHAR_DIGIT_: + self.scan_over_(Lexer.CHAR_DIGIT_) + return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) + if cur_char == "-" and next_char in Lexer.CHAR_DIGIT_: + self.pos_ += 1 + self.scan_over_(Lexer.CHAR_DIGIT_) + return (Lexer.NUMBER, int(text[start : self.pos_], 10), location) + raise VoltLibError("Unexpected character: '%s'" % cur_char, location) + + def scan_over_(self, valid): + p = self.pos_ + while p < self.text_length_ and self.text_[p] in valid: + p += 1 + self.pos_ = p + + def scan_until_(self, stop_at): + p = self.pos_ + while p < self.text_length_ and self.text_[p] not in stop_at: + p += 1 + self.pos_ = p diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/parser.py b/.venv/lib/python3.12/site-packages/fontTools/voltLib/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..31a76e69bff9c2c74e79463e91684f6da605d119 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/voltLib/parser.py @@ -0,0 +1,664 @@ +import fontTools.voltLib.ast as ast +from fontTools.voltLib.lexer import Lexer +from fontTools.voltLib.error import VoltLibError +from io import open + +PARSE_FUNCS = { + "DEF_GLYPH": "parse_def_glyph_", + "DEF_GROUP": "parse_def_group_", + "DEF_SCRIPT": "parse_def_script_", + "DEF_LOOKUP": "parse_def_lookup_", + "DEF_ANCHOR": "parse_def_anchor_", + "GRID_PPEM": "parse_ppem_", + "PRESENTATION_PPEM": "parse_ppem_", + "PPOSITIONING_PPEM": "parse_ppem_", + "COMPILER_USEEXTENSIONLOOKUPS": "parse_noarg_option_", + "COMPILER_USEPAIRPOSFORMAT2": "parse_noarg_option_", + "CMAP_FORMAT": "parse_cmap_format", + "DO_NOT_TOUCH_CMAP": "parse_noarg_option_", +} + + +class Parser(object): + def __init__(self, path): + self.doc_ = ast.VoltFile() + self.glyphs_ = OrderedSymbolTable() + self.groups_ = SymbolTable() + self.anchors_ = {} # dictionary of SymbolTable() keyed by glyph + self.scripts_ = SymbolTable() + self.langs_ = SymbolTable() + self.lookups_ = SymbolTable() + self.next_token_type_, self.next_token_ = (None, None) + self.next_token_location_ = None + self.make_lexer_(path) + self.advance_lexer_() + + def make_lexer_(self, file_or_path): + if hasattr(file_or_path, "read"): + filename = getattr(file_or_path, "name", None) + data = file_or_path.read() + else: + filename = file_or_path + with open(file_or_path, "r") as f: + data = f.read() + self.lexer_ = Lexer(data, filename) + + def parse(self): + statements = self.doc_.statements + while self.next_token_type_ is not None: + self.advance_lexer_() + if self.cur_token_ in PARSE_FUNCS.keys(): + func = getattr(self, PARSE_FUNCS[self.cur_token_]) + statements.append(func()) + elif self.is_cur_keyword_("END"): + break + else: + raise VoltLibError( + "Expected " + ", ".join(sorted(PARSE_FUNCS.keys())), + self.cur_token_location_, + ) + return self.doc_ + + def parse_def_glyph_(self): + assert self.is_cur_keyword_("DEF_GLYPH") + location = self.cur_token_location_ + name = self.expect_string_() + self.expect_keyword_("ID") + gid = self.expect_number_() + if gid < 0: + raise VoltLibError("Invalid glyph ID", self.cur_token_location_) + gunicode = None + if self.next_token_ == "UNICODE": + self.expect_keyword_("UNICODE") + gunicode = [self.expect_number_()] + if gunicode[0] < 0: + raise VoltLibError("Invalid glyph UNICODE", self.cur_token_location_) + elif self.next_token_ == "UNICODEVALUES": + self.expect_keyword_("UNICODEVALUES") + gunicode = self.parse_unicode_values_() + gtype = None + if self.next_token_ == "TYPE": + self.expect_keyword_("TYPE") + gtype = self.expect_name_() + assert gtype in ("BASE", "LIGATURE", "MARK", "COMPONENT") + components = None + if self.next_token_ == "COMPONENTS": + self.expect_keyword_("COMPONENTS") + components = self.expect_number_() + self.expect_keyword_("END_GLYPH") + if self.glyphs_.resolve(name) is not None: + raise VoltLibError( + 'Glyph "%s" (gid %i) already defined' % (name, gid), location + ) + def_glyph = ast.GlyphDefinition( + name, gid, gunicode, gtype, components, location=location + ) + self.glyphs_.define(name, def_glyph) + return def_glyph + + def parse_def_group_(self): + assert self.is_cur_keyword_("DEF_GROUP") + location = self.cur_token_location_ + name = self.expect_string_() + enum = None + if self.next_token_ == "ENUM": + enum = self.parse_enum_() + self.expect_keyword_("END_GROUP") + if self.groups_.resolve(name) is not None: + raise VoltLibError( + 'Glyph group "%s" already defined, ' + "group names are case insensitive" % name, + location, + ) + def_group = ast.GroupDefinition(name, enum, location=location) + self.groups_.define(name, def_group) + return def_group + + def parse_def_script_(self): + assert self.is_cur_keyword_("DEF_SCRIPT") + location = self.cur_token_location_ + name = None + if self.next_token_ == "NAME": + self.expect_keyword_("NAME") + name = self.expect_string_() + self.expect_keyword_("TAG") + tag = self.expect_string_() + if self.scripts_.resolve(tag) is not None: + raise VoltLibError( + 'Script "%s" already defined, ' + "script tags are case insensitive" % tag, + location, + ) + self.langs_.enter_scope() + langs = [] + while self.next_token_ != "END_SCRIPT": + self.advance_lexer_() + lang = self.parse_langsys_() + self.expect_keyword_("END_LANGSYS") + if self.langs_.resolve(lang.tag) is not None: + raise VoltLibError( + 'Language "%s" already defined in script "%s", ' + "language tags are case insensitive" % (lang.tag, tag), + location, + ) + self.langs_.define(lang.tag, lang) + langs.append(lang) + self.expect_keyword_("END_SCRIPT") + self.langs_.exit_scope() + def_script = ast.ScriptDefinition(name, tag, langs, location=location) + self.scripts_.define(tag, def_script) + return def_script + + def parse_langsys_(self): + assert self.is_cur_keyword_("DEF_LANGSYS") + location = self.cur_token_location_ + name = None + if self.next_token_ == "NAME": + self.expect_keyword_("NAME") + name = self.expect_string_() + self.expect_keyword_("TAG") + tag = self.expect_string_() + features = [] + while self.next_token_ != "END_LANGSYS": + self.advance_lexer_() + feature = self.parse_feature_() + self.expect_keyword_("END_FEATURE") + features.append(feature) + def_langsys = ast.LangSysDefinition(name, tag, features, location=location) + return def_langsys + + def parse_feature_(self): + assert self.is_cur_keyword_("DEF_FEATURE") + location = self.cur_token_location_ + self.expect_keyword_("NAME") + name = self.expect_string_() + self.expect_keyword_("TAG") + tag = self.expect_string_() + lookups = [] + while self.next_token_ != "END_FEATURE": + # self.advance_lexer_() + self.expect_keyword_("LOOKUP") + lookup = self.expect_string_() + lookups.append(lookup) + feature = ast.FeatureDefinition(name, tag, lookups, location=location) + return feature + + def parse_def_lookup_(self): + assert self.is_cur_keyword_("DEF_LOOKUP") + location = self.cur_token_location_ + name = self.expect_string_() + if not name[0].isalpha(): + raise VoltLibError( + 'Lookup name "%s" must start with a letter' % name, location + ) + if self.lookups_.resolve(name) is not None: + raise VoltLibError( + 'Lookup "%s" already defined, ' + "lookup names are case insensitive" % name, + location, + ) + process_base = True + if self.next_token_ == "PROCESS_BASE": + self.advance_lexer_() + elif self.next_token_ == "SKIP_BASE": + self.advance_lexer_() + process_base = False + process_marks = True + mark_glyph_set = None + if self.next_token_ == "PROCESS_MARKS": + self.advance_lexer_() + if self.next_token_ == "MARK_GLYPH_SET": + self.advance_lexer_() + mark_glyph_set = self.expect_string_() + elif self.next_token_ == "ALL": + self.advance_lexer_() + elif self.next_token_ == "NONE": + self.advance_lexer_() + process_marks = False + elif self.next_token_type_ == Lexer.STRING: + process_marks = self.expect_string_() + else: + raise VoltLibError( + "Expected ALL, NONE, MARK_GLYPH_SET or an ID. " + "Got %s" % (self.next_token_type_), + location, + ) + elif self.next_token_ == "SKIP_MARKS": + self.advance_lexer_() + process_marks = False + direction = None + if self.next_token_ == "DIRECTION": + self.expect_keyword_("DIRECTION") + direction = self.expect_name_() + assert direction in ("LTR", "RTL") + reversal = None + if self.next_token_ == "REVERSAL": + self.expect_keyword_("REVERSAL") + reversal = True + comments = None + if self.next_token_ == "COMMENTS": + self.expect_keyword_("COMMENTS") + comments = self.expect_string_().replace(r"\n", "\n") + context = [] + while self.next_token_ in ("EXCEPT_CONTEXT", "IN_CONTEXT"): + context = self.parse_context_() + as_pos_or_sub = self.expect_name_() + sub = None + pos = None + if as_pos_or_sub == "AS_SUBSTITUTION": + sub = self.parse_substitution_(reversal) + elif as_pos_or_sub == "AS_POSITION": + pos = self.parse_position_() + else: + raise VoltLibError( + "Expected AS_SUBSTITUTION or AS_POSITION. " "Got %s" % (as_pos_or_sub), + location, + ) + def_lookup = ast.LookupDefinition( + name, + process_base, + process_marks, + mark_glyph_set, + direction, + reversal, + comments, + context, + sub, + pos, + location=location, + ) + self.lookups_.define(name, def_lookup) + return def_lookup + + def parse_context_(self): + location = self.cur_token_location_ + contexts = [] + while self.next_token_ in ("EXCEPT_CONTEXT", "IN_CONTEXT"): + side = None + coverage = None + ex_or_in = self.expect_name_() + # side_contexts = [] # XXX + if self.next_token_ != "END_CONTEXT": + left = [] + right = [] + while self.next_token_ in ("LEFT", "RIGHT"): + side = self.expect_name_() + coverage = self.parse_coverage_() + if side == "LEFT": + left.append(coverage) + else: + right.append(coverage) + self.expect_keyword_("END_CONTEXT") + context = ast.ContextDefinition( + ex_or_in, left, right, location=location + ) + contexts.append(context) + else: + self.expect_keyword_("END_CONTEXT") + return contexts + + def parse_substitution_(self, reversal): + assert self.is_cur_keyword_("AS_SUBSTITUTION") + location = self.cur_token_location_ + src = [] + dest = [] + if self.next_token_ != "SUB": + raise VoltLibError("Expected SUB", location) + while self.next_token_ == "SUB": + self.expect_keyword_("SUB") + src.append(self.parse_coverage_()) + self.expect_keyword_("WITH") + dest.append(self.parse_coverage_()) + self.expect_keyword_("END_SUB") + self.expect_keyword_("END_SUBSTITUTION") + max_src = max([len(cov) for cov in src]) + max_dest = max([len(cov) for cov in dest]) + + # many to many or mixed is invalid + if max_src > 1 and max_dest > 1: + raise VoltLibError("Invalid substitution type", location) + + mapping = dict(zip(tuple(src), tuple(dest))) + if max_src == 1 and max_dest == 1: + # Alternate substitutions are represented by adding multiple + # substitutions for the same glyph, so we detect that here + glyphs = [x.glyphSet() for cov in src for x in cov] # flatten src + if len(set(glyphs)) != len(glyphs): # src has duplicates + sub = ast.SubstitutionAlternateDefinition(mapping, location=location) + else: + if reversal: + # Reversal is valid only for single glyph substitutions + # and VOLT ignores it otherwise. + sub = ast.SubstitutionReverseChainingSingleDefinition( + mapping, location=location + ) + else: + sub = ast.SubstitutionSingleDefinition(mapping, location=location) + elif max_src == 1 and max_dest > 1: + sub = ast.SubstitutionMultipleDefinition(mapping, location=location) + elif max_src > 1 and max_dest == 1: + sub = ast.SubstitutionLigatureDefinition(mapping, location=location) + return sub + + def parse_position_(self): + assert self.is_cur_keyword_("AS_POSITION") + location = self.cur_token_location_ + pos_type = self.expect_name_() + if pos_type not in ("ATTACH", "ATTACH_CURSIVE", "ADJUST_PAIR", "ADJUST_SINGLE"): + raise VoltLibError( + "Expected ATTACH, ATTACH_CURSIVE, ADJUST_PAIR, ADJUST_SINGLE", location + ) + if pos_type == "ATTACH": + position = self.parse_attach_() + elif pos_type == "ATTACH_CURSIVE": + position = self.parse_attach_cursive_() + elif pos_type == "ADJUST_PAIR": + position = self.parse_adjust_pair_() + elif pos_type == "ADJUST_SINGLE": + position = self.parse_adjust_single_() + self.expect_keyword_("END_POSITION") + return position + + def parse_attach_(self): + assert self.is_cur_keyword_("ATTACH") + location = self.cur_token_location_ + coverage = self.parse_coverage_() + coverage_to = [] + self.expect_keyword_("TO") + while self.next_token_ != "END_ATTACH": + cov = self.parse_coverage_() + self.expect_keyword_("AT") + self.expect_keyword_("ANCHOR") + anchor_name = self.expect_string_() + coverage_to.append((cov, anchor_name)) + self.expect_keyword_("END_ATTACH") + position = ast.PositionAttachDefinition( + coverage, coverage_to, location=location + ) + return position + + def parse_attach_cursive_(self): + assert self.is_cur_keyword_("ATTACH_CURSIVE") + location = self.cur_token_location_ + coverages_exit = [] + coverages_enter = [] + while self.next_token_ != "ENTER": + self.expect_keyword_("EXIT") + coverages_exit.append(self.parse_coverage_()) + while self.next_token_ != "END_ATTACH": + self.expect_keyword_("ENTER") + coverages_enter.append(self.parse_coverage_()) + self.expect_keyword_("END_ATTACH") + position = ast.PositionAttachCursiveDefinition( + coverages_exit, coverages_enter, location=location + ) + return position + + def parse_adjust_pair_(self): + assert self.is_cur_keyword_("ADJUST_PAIR") + location = self.cur_token_location_ + coverages_1 = [] + coverages_2 = [] + adjust_pair = {} + while self.next_token_ == "FIRST": + self.advance_lexer_() + coverage_1 = self.parse_coverage_() + coverages_1.append(coverage_1) + while self.next_token_ == "SECOND": + self.advance_lexer_() + coverage_2 = self.parse_coverage_() + coverages_2.append(coverage_2) + while self.next_token_ != "END_ADJUST": + id_1 = self.expect_number_() + id_2 = self.expect_number_() + self.expect_keyword_("BY") + pos_1 = self.parse_pos_() + pos_2 = self.parse_pos_() + adjust_pair[(id_1, id_2)] = (pos_1, pos_2) + self.expect_keyword_("END_ADJUST") + position = ast.PositionAdjustPairDefinition( + coverages_1, coverages_2, adjust_pair, location=location + ) + return position + + def parse_adjust_single_(self): + assert self.is_cur_keyword_("ADJUST_SINGLE") + location = self.cur_token_location_ + adjust_single = [] + while self.next_token_ != "END_ADJUST": + coverages = self.parse_coverage_() + self.expect_keyword_("BY") + pos = self.parse_pos_() + adjust_single.append((coverages, pos)) + self.expect_keyword_("END_ADJUST") + position = ast.PositionAdjustSingleDefinition(adjust_single, location=location) + return position + + def parse_def_anchor_(self): + assert self.is_cur_keyword_("DEF_ANCHOR") + location = self.cur_token_location_ + name = self.expect_string_() + self.expect_keyword_("ON") + gid = self.expect_number_() + self.expect_keyword_("GLYPH") + glyph_name = self.expect_name_() + self.expect_keyword_("COMPONENT") + component = self.expect_number_() + # check for duplicate anchor names on this glyph + if glyph_name in self.anchors_: + anchor = self.anchors_[glyph_name].resolve(name) + if anchor is not None and anchor.component == component: + raise VoltLibError( + 'Anchor "%s" already defined, ' + "anchor names are case insensitive" % name, + location, + ) + if self.next_token_ == "LOCKED": + locked = True + self.advance_lexer_() + else: + locked = False + self.expect_keyword_("AT") + pos = self.parse_pos_() + self.expect_keyword_("END_ANCHOR") + anchor = ast.AnchorDefinition( + name, gid, glyph_name, component, locked, pos, location=location + ) + if glyph_name not in self.anchors_: + self.anchors_[glyph_name] = SymbolTable() + self.anchors_[glyph_name].define(name, anchor) + return anchor + + def parse_adjust_by_(self): + self.advance_lexer_() + assert self.is_cur_keyword_("ADJUST_BY") + adjustment = self.expect_number_() + self.expect_keyword_("AT") + size = self.expect_number_() + return adjustment, size + + def parse_pos_(self): + # VOLT syntax doesn't seem to take device Y advance + self.advance_lexer_() + location = self.cur_token_location_ + assert self.is_cur_keyword_("POS"), location + adv = None + dx = None + dy = None + adv_adjust_by = {} + dx_adjust_by = {} + dy_adjust_by = {} + if self.next_token_ == "ADV": + self.advance_lexer_() + adv = self.expect_number_() + while self.next_token_ == "ADJUST_BY": + adjustment, size = self.parse_adjust_by_() + adv_adjust_by[size] = adjustment + if self.next_token_ == "DX": + self.advance_lexer_() + dx = self.expect_number_() + while self.next_token_ == "ADJUST_BY": + adjustment, size = self.parse_adjust_by_() + dx_adjust_by[size] = adjustment + if self.next_token_ == "DY": + self.advance_lexer_() + dy = self.expect_number_() + while self.next_token_ == "ADJUST_BY": + adjustment, size = self.parse_adjust_by_() + dy_adjust_by[size] = adjustment + self.expect_keyword_("END_POS") + return ast.Pos(adv, dx, dy, adv_adjust_by, dx_adjust_by, dy_adjust_by) + + def parse_unicode_values_(self): + location = self.cur_token_location_ + try: + unicode_values = self.expect_string_().split(",") + unicode_values = [int(uni[2:], 16) for uni in unicode_values if uni != ""] + except ValueError as err: + raise VoltLibError(str(err), location) + return unicode_values if unicode_values != [] else None + + def parse_enum_(self): + self.expect_keyword_("ENUM") + location = self.cur_token_location_ + enum = ast.Enum(self.parse_coverage_(), location=location) + self.expect_keyword_("END_ENUM") + return enum + + def parse_coverage_(self): + coverage = [] + location = self.cur_token_location_ + while self.next_token_ in ("GLYPH", "GROUP", "RANGE", "ENUM"): + if self.next_token_ == "ENUM": + enum = self.parse_enum_() + coverage.append(enum) + elif self.next_token_ == "GLYPH": + self.expect_keyword_("GLYPH") + name = self.expect_string_() + coverage.append(ast.GlyphName(name, location=location)) + elif self.next_token_ == "GROUP": + self.expect_keyword_("GROUP") + name = self.expect_string_() + coverage.append(ast.GroupName(name, self, location=location)) + elif self.next_token_ == "RANGE": + self.expect_keyword_("RANGE") + start = self.expect_string_() + self.expect_keyword_("TO") + end = self.expect_string_() + coverage.append(ast.Range(start, end, self, location=location)) + return tuple(coverage) + + def resolve_group(self, group_name): + return self.groups_.resolve(group_name) + + def glyph_range(self, start, end): + return self.glyphs_.range(start, end) + + def parse_ppem_(self): + location = self.cur_token_location_ + ppem_name = self.cur_token_ + value = self.expect_number_() + setting = ast.SettingDefinition(ppem_name, value, location=location) + return setting + + def parse_noarg_option_(self): + location = self.cur_token_location_ + name = self.cur_token_ + value = True + setting = ast.SettingDefinition(name, value, location=location) + return setting + + def parse_cmap_format(self): + location = self.cur_token_location_ + name = self.cur_token_ + value = (self.expect_number_(), self.expect_number_(), self.expect_number_()) + setting = ast.SettingDefinition(name, value, location=location) + return setting + + def is_cur_keyword_(self, k): + return (self.cur_token_type_ is Lexer.NAME) and (self.cur_token_ == k) + + def expect_string_(self): + self.advance_lexer_() + if self.cur_token_type_ is not Lexer.STRING: + raise VoltLibError("Expected a string", self.cur_token_location_) + return self.cur_token_ + + def expect_keyword_(self, keyword): + self.advance_lexer_() + if self.cur_token_type_ is Lexer.NAME and self.cur_token_ == keyword: + return self.cur_token_ + raise VoltLibError('Expected "%s"' % keyword, self.cur_token_location_) + + def expect_name_(self): + self.advance_lexer_() + if self.cur_token_type_ is Lexer.NAME: + return self.cur_token_ + raise VoltLibError("Expected a name", self.cur_token_location_) + + def expect_number_(self): + self.advance_lexer_() + if self.cur_token_type_ is not Lexer.NUMBER: + raise VoltLibError("Expected a number", self.cur_token_location_) + return self.cur_token_ + + def advance_lexer_(self): + self.cur_token_type_, self.cur_token_, self.cur_token_location_ = ( + self.next_token_type_, + self.next_token_, + self.next_token_location_, + ) + try: + if self.is_cur_keyword_("END"): + raise StopIteration + ( + self.next_token_type_, + self.next_token_, + self.next_token_location_, + ) = self.lexer_.next() + except StopIteration: + self.next_token_type_, self.next_token_ = (None, None) + + +class SymbolTable(object): + def __init__(self): + self.scopes_ = [{}] + + def enter_scope(self): + self.scopes_.append({}) + + def exit_scope(self): + self.scopes_.pop() + + def define(self, name, item): + self.scopes_[-1][name] = item + + def resolve(self, name, case_insensitive=True): + for scope in reversed(self.scopes_): + item = scope.get(name) + if item: + return item + if case_insensitive: + for key in scope: + if key.lower() == name.lower(): + return scope[key] + return None + + +class OrderedSymbolTable(SymbolTable): + def __init__(self): + self.scopes_ = [{}] + + def enter_scope(self): + self.scopes_.append({}) + + def resolve(self, name, case_insensitive=False): + SymbolTable.resolve(self, name, case_insensitive=case_insensitive) + + def range(self, start, end): + for scope in reversed(self.scopes_): + if start in scope and end in scope: + start_idx = list(scope.keys()).index(start) + end_idx = list(scope.keys()).index(end) + return list(scope.keys())[start_idx : end_idx + 1] + return None diff --git a/.venv/lib/python3.12/site-packages/fontTools/voltLib/voltToFea.py b/.venv/lib/python3.12/site-packages/fontTools/voltLib/voltToFea.py new file mode 100644 index 0000000000000000000000000000000000000000..d552f4b52a80855338ef8ea7308a83ee051fc7a5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fontTools/voltLib/voltToFea.py @@ -0,0 +1,911 @@ +"""\ +MS VOLT ``.vtp`` to AFDKO ``.fea`` OpenType Layout converter. + +Usage +----- + +To convert a VTP project file: + + +.. code-block:: sh + + $ fonttools voltLib.voltToFea input.vtp output.fea + +It is also possible convert font files with `TSIV` table (as saved from Volt), +in this case the glyph names used in the Volt project will be mapped to the +actual glyph names in the font files when written to the feature file: + +.. code-block:: sh + + $ fonttools voltLib.voltToFea input.ttf output.fea + +The ``--quiet`` option can be used to suppress warnings. + +The ``--traceback`` can be used to get Python traceback in case of exceptions, +instead of suppressing the traceback. + + +Limitations +----------- + +* Not all VOLT features are supported, the script will error if it it + encounters something it does not understand. Please report an issue if this + happens. +* AFDKO feature file syntax for mark positioning is awkward and does not allow + setting the mark coverage. It also defines mark anchors globally, as a result + some mark positioning lookups might cover many marks than what was in the VOLT + file. This should not be an issue in practice, but if it is then the only way + is to modify the VOLT file or the generated feature file manually to use unique + mark anchors for each lookup. +* VOLT allows subtable breaks in any lookup type, but AFDKO feature file + implementations vary in their support; currently AFDKO’s makeOTF supports + subtable breaks in pair positioning lookups only, while FontTools’ feaLib + support it for most substitution lookups and only some positioning lookups. +""" + +import logging +import re +from io import StringIO +from graphlib import TopologicalSorter + +from fontTools.feaLib import ast +from fontTools.ttLib import TTFont, TTLibError +from fontTools.voltLib import ast as VAst +from fontTools.voltLib.parser import Parser as VoltParser + +log = logging.getLogger("fontTools.voltLib.voltToFea") + +TABLES = ["GDEF", "GSUB", "GPOS"] + + +def _flatten_group(group): + ret = [] + if isinstance(group, (tuple, list)): + for item in group: + ret.extend(_flatten_group(item)) + elif hasattr(group, "enum"): + ret.extend(_flatten_group(group.enum)) + else: + ret.append(group) + return ret + + +# Topologically sort of group definitions to ensure that all groups are defined +# before they are referenced. This is necessary because FEA requires it but +# VOLT does not, see below. +def sort_groups(groups): + group_map = {group.name.lower(): group for group in groups} + graph = { + group.name.lower(): [ + x.group.lower() + for x in _flatten_group(group) + if isinstance(x, VAst.GroupName) + ] + for group in groups + } + sorter = TopologicalSorter(graph) + return [group_map[name] for name in sorter.static_order()] + + +class Lookup(ast.LookupBlock): + def __init__(self, name, use_extension=False, location=None): + super().__init__(name, use_extension, location) + self.chained = [] + + +class VoltToFea: + _NOT_LOOKUP_NAME_RE = re.compile(r"[^A-Za-z_0-9.]") + _NOT_CLASS_NAME_RE = re.compile(r"[^A-Za-z_0-9.\-]") + + def __init__(self, file_or_path, font=None): + if isinstance(file_or_path, VAst.VoltFile): + self._doc, self._file_or_path = file_or_path, None + else: + self._doc, self._file_or_path = None, file_or_path + self._font = font + + self._glyph_map = {} + self._glyph_order = None + + self._gdef = {} + self._glyphclasses = {} + self._features = {} + self._lookups = {} + + self._marks = set() + self._ligatures = {} + + self._markclasses = {} + self._anchors = {} + + self._settings = {} + + self._lookup_names = {} + self._class_names = {} + + def _lookupName(self, name): + if name not in self._lookup_names: + res = self._NOT_LOOKUP_NAME_RE.sub("_", name) + while res in self._lookup_names.values(): + res += "_" + self._lookup_names[name] = res + return self._lookup_names[name] + + def _className(self, name): + if name not in self._class_names: + res = self._NOT_CLASS_NAME_RE.sub("_", name) + while res in self._class_names.values(): + res += "_" + self._class_names[name] = res + return self._class_names[name] + + def _collectStatements(self, doc, tables, ignore_unsupported_settings=False): + # Collect glyph difinitions first, as we need them to map VOLT glyph names to font glyph name. + for statement in doc.statements: + if isinstance(statement, VAst.GlyphDefinition): + self._glyphDefinition(statement) + + # Collect and sort group definitions first, to make sure a group + # definition that references other groups comes after them since VOLT + # does not enforce such ordering, and feature file require it. + groups = [s for s in doc.statements if isinstance(s, VAst.GroupDefinition)] + for group in sort_groups(groups): + self._groupDefinition(group) + + for statement in doc.statements: + if isinstance(statement, VAst.AnchorDefinition): + if "GPOS" in tables: + self._anchorDefinition(statement) + elif isinstance(statement, VAst.SettingDefinition): + self._settingDefinition(statement, ignore_unsupported_settings) + elif isinstance(statement, (VAst.GlyphDefinition, VAst.GroupDefinition)): + pass # Handled above + elif isinstance(statement, VAst.ScriptDefinition): + self._scriptDefinition(statement) + elif not isinstance(statement, VAst.LookupDefinition): + raise NotImplementedError(statement) + + # Lookup definitions need to be handled last as they reference glyph + # and mark classes that might be defined after them. + for statement in doc.statements: + if isinstance(statement, VAst.LookupDefinition): + if statement.pos and "GPOS" not in tables: + continue + if statement.sub and "GSUB" not in tables: + continue + self._lookupDefinition(statement) + + def _buildFeatureFile(self, tables): + doc = ast.FeatureFile() + statements = doc.statements + + if self._glyphclasses: + statements.append(ast.Comment("# Glyph classes")) + statements.extend(self._glyphclasses.values()) + + if self._markclasses: + statements.append(ast.Comment("\n# Mark classes")) + statements.extend(c[1] for c in sorted(self._markclasses.items())) + + if self._lookups: + statements.append(ast.Comment("\n# Lookups")) + for lookup in self._lookups.values(): + statements.extend(lookup.chained) + statements.append(lookup) + + # Prune features + features = self._features.copy() + for feature_tag in features: + scripts = features[feature_tag] + for script_tag in scripts: + langs = scripts[script_tag] + for language_tag in langs: + langs[language_tag] = [ + l for l in langs[language_tag] if l.lower() in self._lookups + ] + scripts[script_tag] = {t: l for t, l in langs.items() if l} + features[feature_tag] = {t: s for t, s in scripts.items() if s} + features = {t: f for t, f in features.items() if f} + + if features: + statements.append(ast.Comment("# Features")) + for feature_tag, scripts in features.items(): + feature = ast.FeatureBlock(feature_tag) + script_tags = sorted(scripts, key=lambda k: 0 if k == "DFLT" else 1) + if feature_tag == "aalt" and len(script_tags) > 1: + log.warning( + "FEA syntax does not allow script statements in 'aalt' feature, " + "so only lookups from the first script will be included." + ) + script_tags = script_tags[:1] + for script_tag in script_tags: + if feature_tag != "aalt": + feature.statements.append(ast.ScriptStatement(script_tag)) + language_tags = sorted( + scripts[script_tag], + key=lambda k: 0 if k == "dflt" else 1, + ) + if feature_tag == "aalt" and len(language_tags) > 1: + log.warning( + "FEA syntax does not allow language statements in 'aalt' feature, " + "so only lookups from the first language will be included." + ) + language_tags = language_tags[:1] + for language_tag in language_tags: + if feature_tag != "aalt": + include_default = True if language_tag == "dflt" else False + feature.statements.append( + ast.LanguageStatement( + language_tag.ljust(4), + include_default=include_default, + ) + ) + for name in scripts[script_tag][language_tag]: + lookup = self._lookups[name.lower()] + lookupref = ast.LookupReferenceStatement(lookup) + feature.statements.append(lookupref) + statements.append(feature) + + if self._gdef and "GDEF" in tables: + classes = [] + for name in ("BASE", "MARK", "LIGATURE", "COMPONENT"): + if name in self._gdef: + classname = "GDEF_" + name.lower() + glyphclass = ast.GlyphClassDefinition(classname, self._gdef[name]) + statements.append(glyphclass) + classes.append(ast.GlyphClassName(glyphclass)) + else: + classes.append(None) + + gdef = ast.TableBlock("GDEF") + gdef.statements.append(ast.GlyphClassDefStatement(*classes)) + statements.append(gdef) + + return doc + + def convert(self, tables=None, ignore_unsupported_settings=False): + if self._doc is None: + self._doc = VoltParser(self._file_or_path).parse() + doc = self._doc + + if tables is None: + tables = TABLES + if self._font is not None: + self._glyph_order = self._font.getGlyphOrder() + + self._collectStatements(doc, tables, ignore_unsupported_settings) + fea = self._buildFeatureFile(tables) + return fea.asFea() + + def _glyphName(self, glyph): + try: + name = glyph.glyph + except AttributeError: + name = glyph + return ast.GlyphName(self._glyph_map.get(name, name)) + + def _groupName(self, group): + try: + name = group.group + except AttributeError: + name = group + return ast.GlyphClassName(self._glyphclasses[name.lower()]) + + def _glyphSet(self, item): + return [ + (self._glyphName(x) if isinstance(x, (str, VAst.GlyphName)) else x) + for x in item.glyphSet() + ] + + def _coverage(self, coverage, flatten=False): + items = [] + for item in coverage: + if isinstance(item, VAst.GlyphName): + items.append(self._glyphName(item)) + elif isinstance(item, VAst.GroupName): + items.append(self._groupName(item)) + elif isinstance(item, VAst.Enum): + item = self._coverage(item.enum, flatten=True) + if flatten: + items.extend(item) + else: + items.append(ast.GlyphClass(item)) + elif isinstance(item, VAst.Range): + item = self._glyphSet(item) + if flatten: + items.extend(item) + else: + items.append(ast.GlyphClass(item)) + else: + raise NotImplementedError(item) + return items + + def _context(self, context): + out = [] + for item in context: + coverage = self._coverage(item, flatten=True) + if len(coverage) > 1: + coverage = ast.GlyphClass(coverage) + else: + coverage = coverage[0] + out.append(coverage) + return out + + def _groupDefinition(self, group): + name = self._className(group.name) + glyphs = self._coverage(group.enum.enum, flatten=True) + glyphclass = ast.GlyphClass(glyphs) + classdef = ast.GlyphClassDefinition(name, glyphclass) + self._glyphclasses[group.name.lower()] = classdef + + def _glyphDefinition(self, glyph): + try: + self._glyph_map[glyph.name] = self._glyph_order[glyph.id] + except TypeError: + pass + + if glyph.type in ("BASE", "MARK", "LIGATURE", "COMPONENT"): + if glyph.type not in self._gdef: + self._gdef[glyph.type] = ast.GlyphClass() + self._gdef[glyph.type].glyphs.append(self._glyphName(glyph.name)) + + if glyph.type == "MARK": + self._marks.add(glyph.name) + elif glyph.type == "LIGATURE": + self._ligatures[glyph.name] = glyph.components + + def _scriptDefinition(self, script): + stag = script.tag + for lang in script.langs: + ltag = lang.tag + for feature in lang.features: + lookups = {l.split("\\")[0]: True for l in feature.lookups} + ftag = feature.tag + if ftag not in self._features: + self._features[ftag] = {} + if stag not in self._features[ftag]: + self._features[ftag][stag] = {} + assert ltag not in self._features[ftag][stag] + self._features[ftag][stag][ltag] = lookups.keys() + + def _settingDefinition(self, setting, ignore_unsupported=False): + if setting.name.startswith("COMPILER_"): + self._settings[setting.name] = setting.value + elif not ignore_unsupported: + log.warning(f"Unsupported setting ignored: {setting.name}") + + def _adjustment(self, adjustment): + adv, dx, dy, adv_adjust_by, dx_adjust_by, dy_adjust_by = adjustment + + adv_device = adv_adjust_by and adv_adjust_by.items() or None + dx_device = dx_adjust_by and dx_adjust_by.items() or None + dy_device = dy_adjust_by and dy_adjust_by.items() or None + + return ast.ValueRecord( + xPlacement=dx, + yPlacement=dy, + xAdvance=adv, + xPlaDevice=dx_device, + yPlaDevice=dy_device, + xAdvDevice=adv_device, + ) + + def _anchor(self, adjustment): + adv, dx, dy, adv_adjust_by, dx_adjust_by, dy_adjust_by = adjustment + + assert not adv_adjust_by + dx_device = dx_adjust_by and dx_adjust_by.items() or None + dy_device = dy_adjust_by and dy_adjust_by.items() or None + + return ast.Anchor( + dx or 0, + dy or 0, + xDeviceTable=dx_device or None, + yDeviceTable=dy_device or None, + ) + + def _anchorDefinition(self, anchordef): + anchorname = anchordef.name + glyphname = anchordef.glyph_name + anchor = self._anchor(anchordef.pos) + + if glyphname not in self._anchors: + self._anchors[glyphname] = {} + if anchorname.startswith("MARK_"): + anchorname = anchorname[:5] + anchorname[5:].lower() + else: + anchorname = anchorname.lower() + if anchorname not in self._anchors[glyphname]: + self._anchors[glyphname][anchorname] = {} + self._anchors[glyphname][anchorname][anchordef.component] = anchor + + def _gposLookup(self, lookup, fealookup): + statements = fealookup.statements + + pos = lookup.pos + if isinstance(pos, VAst.PositionAdjustPairDefinition): + for (idx1, idx2), (pos1, pos2) in pos.adjust_pair.items(): + coverage_1 = pos.coverages_1[idx1 - 1] + coverage_2 = pos.coverages_2[idx2 - 1] + + # If not both are groups, use “enum pos” otherwise makeotf will + # fail. + enumerated = False + for item in coverage_1 + coverage_2: + if not isinstance(item, VAst.GroupName): + enumerated = True + + glyphs1 = self._coverage(coverage_1) + glyphs2 = self._coverage(coverage_2) + record1 = self._adjustment(pos1) + record2 = self._adjustment(pos2) + assert len(glyphs1) == 1 + assert len(glyphs2) == 1 + statements.append( + ast.PairPosStatement( + glyphs1[0], record1, glyphs2[0], record2, enumerated=enumerated + ) + ) + elif isinstance(pos, VAst.PositionAdjustSingleDefinition): + for a, b in pos.adjust_single: + glyphs = self._coverage(a) + record = self._adjustment(b) + assert len(glyphs) == 1 + statements.append( + ast.SinglePosStatement([(glyphs[0], record)], [], [], False) + ) + elif isinstance(pos, VAst.PositionAttachDefinition): + anchors = {} + allmarks = set() + for coverage, anchorname in pos.coverage_to: + # In feature files mark classes are global, but in VOLT they + # are defined per-lookup. If we output mark class definitions + # for all marks that use a given anchor, we might end up with a + # mark used in two different classes in the same lookup, which + # is causes feature file compilation error. + # At the expense of uglier feature code, we make the mark class + # name by appending the current lookup name not the anchor + # name, and output mark class definitions only for marks used + # in this lookup. + classname = self._className(f"{anchorname}.{lookup.name}") + markclass = ast.MarkClass(classname) + + # Anchor names are case-insensitive in VOLT + anchorname = anchorname.lower() + + # We might still end in marks used in two different anchor + # classes, so we filter out already used marks. + marks = set() + for mark in coverage: + marks.update(mark.glyphSet()) + if not marks.isdisjoint(allmarks): + marks.difference_update(allmarks) + if not marks: + continue + allmarks.update(marks) + + for glyphname in marks: + glyph = self._glyphName(glyphname) + anchor = self._anchors[glyphname][f"MARK_{anchorname}"][1] + markdef = ast.MarkClassDefinition(markclass, anchor, glyph) + self._markclasses[(glyphname, classname)] = markdef + + for base in pos.coverage: + for name in base.glyphSet(): + if name not in anchors: + anchors[name] = [] + if (anchorname, classname) not in anchors[name]: + anchors[name].append((anchorname, classname)) + + is_ligature = all(n in self._ligatures for n in anchors) + is_mark = all(n in self._marks for n in anchors) + for name in anchors: + components = 1 + if is_ligature: + components = self._ligatures[name] + + marks = [[] for _ in range(components)] + for mark, classname in anchors[name]: + markclass = ast.MarkClass(classname) + for component in range(1, components + 1): + if component in self._anchors[name][mark]: + anchor = self._anchors[name][mark][component] + marks[component - 1].append((anchor, markclass)) + + base = self._glyphName(name) + if is_mark: + mark = ast.MarkMarkPosStatement(base, marks[0]) + elif is_ligature: + mark = ast.MarkLigPosStatement(base, marks) + else: + mark = ast.MarkBasePosStatement(base, marks[0]) + statements.append(mark) + elif isinstance(pos, VAst.PositionAttachCursiveDefinition): + # Collect enter and exit glyphs + enter_coverage = [] + for coverage in pos.coverages_enter: + for base in coverage: + for name in base.glyphSet(): + enter_coverage.append(name) + exit_coverage = [] + for coverage in pos.coverages_exit: + for base in coverage: + for name in base.glyphSet(): + exit_coverage.append(name) + + # Write enter anchors, also check if the glyph has exit anchor and + # write it, too. + for name in enter_coverage: + glyph = self._glyphName(name) + entry = self._anchors[name]["entry"][1] + exit = None + if name in exit_coverage: + exit = self._anchors[name]["exit"][1] + exit_coverage.pop(exit_coverage.index(name)) + statements.append(ast.CursivePosStatement(glyph, entry, exit)) + + # Write any remaining exit anchors. + for name in exit_coverage: + glyph = self._glyphName(name) + exit = self._anchors[name]["exit"][1] + statements.append(ast.CursivePosStatement(glyph, None, exit)) + else: + raise NotImplementedError(pos) + + def _gposContextLookup(self, lookup, prefix, suffix, ignore, fealookup, chained): + statements = fealookup.statements + + pos = lookup.pos + if isinstance(pos, VAst.PositionAdjustPairDefinition): + for (idx1, idx2), (pos1, pos2) in pos.adjust_pair.items(): + glyphs1 = self._coverage(pos.coverages_1[idx1 - 1]) + glyphs2 = self._coverage(pos.coverages_2[idx2 - 1]) + assert len(glyphs1) == 1 + assert len(glyphs2) == 1 + glyphs = (glyphs1[0], glyphs2[0]) + + if ignore: + statement = ast.IgnorePosStatement([(prefix, glyphs, suffix)]) + else: + statement = ast.ChainContextPosStatement( + prefix, glyphs, suffix, [chained, chained] + ) + statements.append(statement) + elif isinstance(pos, VAst.PositionAdjustSingleDefinition): + glyphs = [ast.GlyphClass()] + for a, _ in pos.adjust_single: + glyphs[0].extend(self._coverage(a, flatten=True)) + + if ignore: + statement = ast.IgnorePosStatement([(prefix, glyphs, suffix)]) + else: + statement = ast.ChainContextPosStatement( + prefix, glyphs, suffix, [chained] + ) + statements.append(statement) + elif isinstance(pos, VAst.PositionAttachDefinition): + glyphs = [ast.GlyphClass()] + for coverage, _ in pos.coverage_to: + glyphs[0].extend(self._coverage(coverage, flatten=True)) + + if ignore: + statement = ast.IgnorePosStatement([(prefix, glyphs, suffix)]) + else: + statement = ast.ChainContextPosStatement( + prefix, glyphs, suffix, [chained] + ) + statements.append(statement) + else: + raise NotImplementedError(pos) + + def _gsubLookup(self, lookup, fealookup): + statements = fealookup.statements + + sub = lookup.sub + + # Alternate substitutions are represented by adding multiple + # substitutions for the same glyph, so we need to collect them into one + # to many mapping. + if isinstance(sub, VAst.SubstitutionAlternateDefinition): + alternates = {} + for key, val in sub.mapping.items(): + if not key or not val: + path, line, column = sub.location + log.warning(f"{path}:{line}:{column}: Ignoring empty substitution") + continue + glyphs = self._coverage(key) + replacements = self._coverage(val) + assert len(glyphs) == 1 + for src_glyph, repl_glyph in zip( + glyphs[0].glyphSet(), replacements[0].glyphSet() + ): + alternates.setdefault(str(self._glyphName(src_glyph)), []).append( + str(self._glyphName(repl_glyph)) + ) + + for glyph, replacements in alternates.items(): + statement = ast.AlternateSubstStatement( + [], glyph, [], ast.GlyphClass(replacements) + ) + statements.append(statement) + return + + for key, val in sub.mapping.items(): + if not key or not val: + path, line, column = sub.location + log.warning(f"{path}:{line}:{column}: Ignoring empty substitution") + continue + glyphs = self._coverage(key) + replacements = self._coverage(val) + if isinstance(sub, VAst.SubstitutionSingleDefinition): + assert len(glyphs) == 1 + assert len(replacements) == 1 + statements.append( + ast.SingleSubstStatement(glyphs, replacements, [], [], False) + ) + elif isinstance(sub, VAst.SubstitutionReverseChainingSingleDefinition): + # This is handled in gsubContextLookup() + pass + elif isinstance(sub, VAst.SubstitutionMultipleDefinition): + assert len(glyphs) == 1 + statements.append( + ast.MultipleSubstStatement([], glyphs[0], [], replacements) + ) + elif isinstance(sub, VAst.SubstitutionLigatureDefinition): + assert len(replacements) == 1 + statement = ast.LigatureSubstStatement( + [], glyphs, [], replacements[0], False + ) + + # If any of the input glyphs is a group, we need to + # explode the substitution into multiple ligature substitutions + # since feature file syntax does not support classes in + # ligature substitutions. + n = max(len(x.glyphSet()) for x in glyphs) + if n > 1: + # All input should either be groups of the same length or single glyphs + assert all(len(x.glyphSet()) in (n, 1) for x in glyphs) + glyphs = [x.glyphSet() for x in glyphs] + glyphs = [([x[0]] * n if len(x) == 1 else x) for x in glyphs] + + # In this case ligature replacements must be a group of the same length + # as the input groups, or a single glyph. VOLT + # allows the replacement glyphs to be longer and truncates them. + # So well allow that and zip() below will do the truncation + # for us. + replacement = replacements[0].glyphSet() + if len(replacement) == 1: + replacement = [replacement[0]] * n + assert len(replacement) >= n + + # Add the unexploded statement commented out for reference. + statements.append(ast.Comment(f"# {statement}")) + + for zipped in zip(*glyphs, replacement): + zipped = [self._glyphName(x) for x in zipped] + statements.append( + ast.LigatureSubstStatement( + [], zipped[:-1], [], zipped[-1], False + ) + ) + else: + statements.append(statement) + else: + raise NotImplementedError(sub) + + def _gsubContextLookup(self, lookup, prefix, suffix, ignore, fealookup, chained): + statements = fealookup.statements + + sub = lookup.sub + + if isinstance(sub, VAst.SubstitutionReverseChainingSingleDefinition): + # Reverse substitutions is a special case, it can’t use chained lookups. + for key, val in sub.mapping.items(): + if not key or not val: + path, line, column = sub.location + log.warning(f"{path}:{line}:{column}: Ignoring empty substitution") + continue + glyphs = self._coverage(key) + replacements = self._coverage(val) + statements.append( + ast.ReverseChainSingleSubstStatement( + prefix, suffix, glyphs, replacements + ) + ) + fealookup.chained = [] + return + + if not isinstance( + sub, + ( + VAst.SubstitutionSingleDefinition, + VAst.SubstitutionMultipleDefinition, + VAst.SubstitutionLigatureDefinition, + VAst.SubstitutionAlternateDefinition, + ), + ): + raise NotImplementedError(type(sub)) + + glyphs = [] + for key, val in sub.mapping.items(): + if not key or not val: + path, line, column = sub.location + log.warning(f"{path}:{line}:{column}: Ignoring empty substitution") + continue + glyphs.extend(self._coverage(key, flatten=True)) + + if len(glyphs) > 1: + glyphs = [ast.GlyphClass(glyphs)] + if ignore: + statements.append(ast.IgnoreSubstStatement([(prefix, glyphs, suffix)])) + else: + statements.append( + ast.ChainContextSubstStatement(prefix, glyphs, suffix, [chained]) + ) + + def _lookupDefinition(self, lookup): + mark_attachement = None + mark_filtering = None + + flags = 0 + if lookup.direction == "RTL": + flags |= 1 + if not lookup.process_base: + flags |= 2 + # FIXME: Does VOLT support this? + # if not lookup.process_ligatures: + # flags |= 4 + if not lookup.process_marks: + flags |= 8 + elif isinstance(lookup.process_marks, str): + mark_attachement = self._groupName(lookup.process_marks) + elif lookup.mark_glyph_set is not None: + mark_filtering = self._groupName(lookup.mark_glyph_set) + + lookupflags = None + if flags or mark_attachement is not None or mark_filtering is not None: + lookupflags = ast.LookupFlagStatement( + flags, mark_attachement, mark_filtering + ) + + use_extension = False + if self._settings.get("COMPILER_USEEXTENSIONLOOKUPS"): + use_extension = True + + if "\\" in lookup.name: + # Merge sub lookups as subtables (lookups named “base\sub”), + # makeotf/feaLib will issue a warning and ignore the subtable + # statement if it is not a pairpos lookup, though. + name = lookup.name.split("\\")[0] + if name.lower() not in self._lookups: + fealookup = Lookup( + self._lookupName(name), + use_extension=use_extension, + ) + if lookupflags is not None: + fealookup.statements.append(lookupflags) + fealookup.statements.append(ast.Comment("# " + lookup.name)) + else: + fealookup = self._lookups[name.lower()] + fealookup.statements.append(ast.SubtableStatement()) + fealookup.statements.append(ast.Comment("# " + lookup.name)) + self._lookups[name.lower()] = fealookup + else: + fealookup = Lookup( + self._lookupName(lookup.name), + use_extension=use_extension, + ) + if lookupflags is not None: + fealookup.statements.append(lookupflags) + self._lookups[lookup.name.lower()] = fealookup + + if lookup.comments is not None: + fealookup.statements.append(ast.Comment("# " + lookup.comments)) + + contexts = [] + for context in lookup.context: + prefix = self._context(context.left) + suffix = self._context(context.right) + ignore = context.ex_or_in == "EXCEPT_CONTEXT" + contexts.append([prefix, suffix, ignore]) + # It seems that VOLT will create contextual substitution using + # only the input if there is no other contexts in this lookup. + if ignore and len(lookup.context) == 1: + contexts.append([[], [], False]) + + if contexts: + chained = ast.LookupBlock( + self._lookupName(lookup.name + " chained"), + use_extension=use_extension, + ) + fealookup.chained.append(chained) + if lookup.sub is not None: + self._gsubLookup(lookup, chained) + elif lookup.pos is not None: + self._gposLookup(lookup, chained) + for prefix, suffix, ignore in contexts: + if lookup.sub is not None: + self._gsubContextLookup( + lookup, prefix, suffix, ignore, fealookup, chained + ) + elif lookup.pos is not None: + self._gposContextLookup( + lookup, prefix, suffix, ignore, fealookup, chained + ) + else: + if lookup.sub is not None: + self._gsubLookup(lookup, fealookup) + elif lookup.pos is not None: + self._gposLookup(lookup, fealookup) + + +def main(args=None): + """Convert MS VOLT to AFDKO feature files.""" + + import argparse + from pathlib import Path + + from fontTools import configLogger + + parser = argparse.ArgumentParser( + "fonttools voltLib.voltToFea", description=main.__doc__ + ) + parser.add_argument( + "input", metavar="INPUT", type=Path, help="input font/VTP file to process" + ) + parser.add_argument( + "featurefile", metavar="OUTPUT", type=Path, help="output feature file" + ) + parser.add_argument( + "-t", + "--table", + action="append", + choices=TABLES, + dest="tables", + help="List of tables to write, by default all tables are written", + ) + parser.add_argument( + "-q", "--quiet", action="store_true", help="Suppress non-error messages" + ) + parser.add_argument( + "--traceback", action="store_true", help="Don’t catch exceptions" + ) + + options = parser.parse_args(args) + + configLogger(level=("ERROR" if options.quiet else "INFO")) + + file_or_path = options.input + font = None + try: + font = TTFont(file_or_path) + if "TSIV" in font: + file_or_path = StringIO(font["TSIV"].data.decode("utf-8")) + else: + log.error('"TSIV" table is missing, font was not saved from VOLT?') + return 1 + except TTLibError: + pass + + converter = VoltToFea(file_or_path, font) + try: + fea = converter.convert(options.tables) + except NotImplementedError as e: + if options.traceback: + raise + location = getattr(e.args[0], "location", None) + message = f'"{e}" is not supported' + if location: + path, line, column = location + log.error(f"{path}:{line}:{column}: {message}") + else: + log.error(message) + return 1 + with open(options.featurefile, "w") as feafile: + feafile.write(fea) + + +if __name__ == "__main__": + import sys + + sys.exit(main()) diff --git a/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..9e0cd1eaa4177c1dff1423bca31037e3cc96a112 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/METADATA @@ -0,0 +1,2444 @@ +Metadata-Version: 2.4 +Name: fonttools +Version: 4.65.0 +Summary: Tools to manipulate font files +Home-page: http://github.com/fonttools/fonttools +Author: Just van Rossum +Author-email: just@letterror.com +Maintainer: Behdad Esfahbod +Maintainer-email: behdad@behdad.org +License: MIT +Platform: Any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Environment :: Other Environment +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: End Users/Desktop +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3 +Classifier: Topic :: Text Processing :: Fonts +Classifier: Topic :: Multimedia :: Graphics +Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: LICENSE.external +Provides-Extra: ufo +Provides-Extra: lxml +Requires-Dist: lxml>=4.0; extra == "lxml" +Provides-Extra: woff +Requires-Dist: brotli>=1.0.1; platform_python_implementation == "CPython" and extra == "woff" +Requires-Dist: brotlicffi>=0.8.0; platform_python_implementation != "CPython" and extra == "woff" +Requires-Dist: zopfli>=0.1.4; extra == "woff" +Provides-Extra: unicode +Requires-Dist: unicodedata2>=17.0.0; python_version <= "3.14" and extra == "unicode" +Provides-Extra: graphite +Requires-Dist: lz4>=1.7.4.2; extra == "graphite" +Provides-Extra: interpolatable +Requires-Dist: scipy; platform_python_implementation != "PyPy" and extra == "interpolatable" +Requires-Dist: munkres; platform_python_implementation == "PyPy" and extra == "interpolatable" +Requires-Dist: pycairo; extra == "interpolatable" +Provides-Extra: plot +Requires-Dist: matplotlib; extra == "plot" +Provides-Extra: symfont +Requires-Dist: sympy; extra == "symfont" +Provides-Extra: type1 +Requires-Dist: xattr; sys_platform == "darwin" and extra == "type1" +Provides-Extra: pathops +Requires-Dist: skia-pathops>=0.5.0; extra == "pathops" +Provides-Extra: repacker +Requires-Dist: uharfbuzz>=0.45.0; extra == "repacker" +Provides-Extra: all +Requires-Dist: lxml>=4.0; extra == "all" +Requires-Dist: brotli>=1.0.1; platform_python_implementation == "CPython" and extra == "all" +Requires-Dist: brotlicffi>=0.8.0; platform_python_implementation != "CPython" and extra == "all" +Requires-Dist: zopfli>=0.1.4; extra == "all" +Requires-Dist: unicodedata2>=17.0.0; python_version <= "3.14" and extra == "all" +Requires-Dist: lz4>=1.7.4.2; extra == "all" +Requires-Dist: scipy; platform_python_implementation != "PyPy" and extra == "all" +Requires-Dist: munkres; platform_python_implementation == "PyPy" and extra == "all" +Requires-Dist: pycairo; extra == "all" +Requires-Dist: matplotlib; extra == "all" +Requires-Dist: sympy; extra == "all" +Requires-Dist: xattr; sys_platform == "darwin" and extra == "all" +Requires-Dist: skia-pathops>=0.5.0; extra == "all" +Requires-Dist: uharfbuzz>=0.45.0; extra == "all" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: maintainer +Dynamic: maintainer-email +Dynamic: platform +Dynamic: provides-extra +Dynamic: requires-python +Dynamic: summary + +|CI Build Status| |Coverage Status| |PyPI| |Gitter Chat| + +What is this? +~~~~~~~~~~~~~ + +| fontTools is a library for manipulating fonts, written in Python. The + project includes the TTX tool, that can convert TrueType and OpenType + fonts to and from an XML text format, which is also called TTX. It + supports TrueType, OpenType, AFM and to an extent Type 1 and some + Mac-specific formats. The project has an `MIT open-source + license <LICENSE>`__. +| Among other things this means you can use it free of charge. + +`User documentation <https://fonttools.readthedocs.io/en/latest/>`_ and +`developer documentation <https://fonttools.readthedocs.io/en/latest/developer.html>`_ +are available at `Read the Docs <https://fonttools.readthedocs.io/>`_. + +Installation +~~~~~~~~~~~~ + +FontTools requires `Python <http://www.python.org/download/>`__ 3.10 +or later. We try to follow the same schedule of minimum Python version support as +NumPy (see `NEP 29 <https://numpy.org/neps/nep-0029-deprecation_policy.html>`__). + +The package is listed in the Python Package Index (PyPI), so you can +install it with `pip <https://pip.pypa.io>`__: + +.. code:: sh + + pip install fonttools + +If you would like to contribute to its development, you can clone the +repository from GitHub, install the package in 'editable' mode and +modify the source code in place. We recommend creating a virtual +environment, using `virtualenv <https://virtualenv.pypa.io>`__ or +Python 3 `venv <https://docs.python.org/3/library/venv.html>`__ module. + +.. code:: sh + + # download the source code to 'fonttools' folder + git clone https://github.com/fonttools/fonttools.git + cd fonttools + + # create new virtual environment called e.g. 'fonttools-venv', or anything you like + python -m virtualenv fonttools-venv + + # source the `activate` shell script to enter the environment (Unix-like); to exit, just type `deactivate` + . fonttools-venv/bin/activate + + # to activate the virtual environment in Windows `cmd.exe`, do + fonttools-venv\Scripts\activate.bat + + # install in 'editable' mode + pip install -e . + +Optional Requirements +--------------------- + +The ``fontTools`` package currently has no (required) external dependencies +besides the modules included in the Python Standard Library. +However, a few extra dependencies are required by some of its modules, which +are needed to unlock optional features. +The ``fonttools`` PyPI distribution also supports so-called "extras", i.e. a +set of keywords that describe a group of additional dependencies, which can be +used when installing via pip, or when specifying a requirement. +For example: + +.. code:: sh + + pip install fonttools[ufo,lxml,woff,unicode] + +This command will install fonttools, as well as the optional dependencies that +are required to unlock the extra features named "ufo", etc. + +- ``Lib/fontTools/misc/etree.py`` + + The module exports a ElementTree-like API for reading/writing XML files, and + allows to use as the backend either the built-in ``xml.etree`` module or + `lxml <https://lxml.de>`__. The latter is preferred whenever present, + as it is generally faster and more secure. + + *Extra:* ``lxml`` + +- ``Lib/fontTools/ttLib/woff2.py`` + + Module to compress/decompress WOFF 2.0 web fonts; it requires: + + * `brotli <https://pypi.python.org/pypi/Brotli>`__: Python bindings of + the Brotli compression library. + + *Extra:* ``woff`` + +- ``Lib/fontTools/ttLib/sfnt.py`` + + To better compress WOFF 1.0 web fonts, the following module can be used + instead of the built-in ``zlib`` library: + + * `zopfli <https://pypi.python.org/pypi/zopfli>`__: Python bindings of + the Zopfli compression library. + + *Extra:* ``woff`` + +- ``Lib/fontTools/unicode.py`` + + To display the Unicode character names when dumping the ``cmap`` table + with ``ttx`` we use the ``unicodedata`` module in the Standard Library. + The version included in there varies between different Python versions. + To use the latest available data, you can install: + + * `unicodedata2 <https://pypi.python.org/pypi/unicodedata2>`__: + ``unicodedata`` backport for Python 3.x updated to the latest Unicode + version 17.0. + + *Extra:* ``unicode`` + +- ``Lib/fontTools/varLib/interpolatable.py`` + + Module for finding wrong contour/component order between different masters. + It requires one of the following packages in order to solve the so-called + "minimum weight perfect matching problem in bipartite graphs", or + the Assignment problem: + + * `scipy <https://pypi.python.org/pypi/scipy>`__: the Scientific Library + for Python, which internally uses `NumPy <https://pypi.python.org/pypi/numpy>`__ + arrays and hence is very fast; + * `munkres <https://pypi.python.org/pypi/munkres>`__: a pure-Python + module that implements the Hungarian or Kuhn-Munkres algorithm. Slower than + SciPy, but useful for minimalistic systems where adding SciPy is undesirable. + + This ensures both performance (via SciPy) and minimal footprint (via Munkres) + are possible. + + To plot the results to a PDF or HTML format, you also need to install: + + * `pycairo <https://pypi.org/project/pycairo/>`__: Python bindings for the + Cairo graphics library. Note that wheels are currently only available for + Windows, for other platforms see pycairo's `installation instructions + <https://pycairo.readthedocs.io/en/latest/getting_started.html>`__. + + *Extra:* ``interpolatable`` + +- ``Lib/fontTools/varLib/plot.py`` + + Module for visualizing DesignSpaceDocument and resulting VariationModel. + + * `matplotlib <https://pypi.org/pypi/matplotlib>`__: 2D plotting library. + + *Extra:* ``plot`` + +- ``Lib/fontTools/misc/symfont.py`` + + Advanced module for symbolic font statistics analysis; it requires: + + * `sympy <https://pypi.python.org/pypi/sympy>`__: the Python library for + symbolic mathematics. + + *Extra:* ``symfont`` + +- ``Lib/fontTools/t1Lib.py`` + + To get the file creator and type of Macintosh PostScript Type 1 fonts + on Python 3 you need to install the following module, as the old ``MacOS`` + module is no longer included in Mac Python: + + * `xattr <https://pypi.python.org/pypi/xattr>`__: Python wrapper for + extended filesystem attributes (macOS platform only). + + *Extra:* ``type1`` + +- ``Lib/fontTools/ttLib/removeOverlaps.py`` + + Simplify TrueType glyphs by merging overlapping contours and components. + + * `skia-pathops <https://pypi.python.org/pypi/skia-pathops>`__: Python + bindings for the Skia library's PathOps module, performing boolean + operations on paths (union, intersection, etc.). + + *Extra:* ``pathops`` + +- ``Lib/fontTools/ufoLib`` + + Package for reading and writing UFO source files; if available, it will use: + + * `fs <https://pypi.org/pypi/fs>`__: (aka ``pyfilesystem2``) filesystem abstraction layer + + for reading and writing UFOs to the local filesystem or zip files (.ufoz), instead of + the built-in ``fontTools.misc.filesystem`` package. + The reader and writer classes can in theory also accept any object compatible the + ``fs.base.FS`` interface, although not all have been tested. + +- ``Lib/fontTools/pens/cocoaPen.py`` and ``Lib/fontTools/pens/quartzPen.py`` + + Pens for drawing glyphs with Cocoa ``NSBezierPath`` or ``CGPath`` require: + + * `PyObjC <https://pypi.python.org/pypi/pyobjc>`__: the bridge between + Python and the Objective-C runtime (macOS platform only). + +- ``Lib/fontTools/pens/qtPen.py`` + + Pen for drawing glyphs with Qt's ``QPainterPath``, requires: + + * `PyQt5 <https://pypi.python.org/pypi/PyQt5>`__: Python bindings for + the Qt cross platform UI and application toolkit. + +- ``Lib/fontTools/pens/reportLabPen.py`` + + Pen to drawing glyphs as PNG images, requires: + + * `reportlab <https://pypi.python.org/pypi/reportlab>`__: Python toolkit + for generating PDFs and graphics. + +- ``Lib/fontTools/pens/freetypePen.py`` + + Pen to drawing glyphs with FreeType as raster images, requires: + + * `freetype-py <https://pypi.python.org/pypi/freetype-py>`__: Python binding + for the FreeType library. + +- ``Lib/fontTools/ttLib/tables/otBase.py`` + + Use the Harfbuzz library to serialize GPOS/GSUB using ``hb_repack`` method, requires: + + * `uharfbuzz <https://pypi.python.org/pypi/uharfbuzz>`__: Streamlined Cython + bindings for the harfbuzz shaping engine + + *Extra:* ``repacker`` + +How to make a new release +~~~~~~~~~~~~~~~~~~~~~~~~~ + +1) Update ``NEWS.rst`` with all the changes since the last release. Write a + changelog entry for each PR, with one or two short sentences summarizing it, + as well as links to the PR and relevant issues addressed by the PR. Do not + put a new title, the next command will do it for you. +2) Use semantic versioning to decide whether the new release will be a 'major', + 'minor' or 'patch' release. It's usually one of the latter two, depending on + whether new backward compatible APIs were added, or simply some bugs were fixed. +3) From inside a venv, first do ``pip install -r dev-requirements.txt``, then run + the ``python setup.py release`` command from the tip of the ``main`` branch. + By default this bumps the third or 'patch' digit only, unless you pass ``--major`` + or ``--minor`` to bump respectively the first or second digit. + This bumps the package version string, extracts the changes since the latest + version from ``NEWS.rst``, and uses that text to create an annotated git tag + (or a signed git tag if you pass the ``--sign`` option and your git and Github + account are configured for `signing commits <https://docs.github.com/en/github/authenticating-to-github/managing-commit-signature-verification/signing-commits>`__ + using a GPG key). + It also commits an additional version bump which opens the main branch for + the subsequent developmental cycle +4) Push both the tag and commit to the upstream repository, by running the command + ``git push --follow-tags``. Note: it may push other local tags as well, be + careful. +5) Let the CI build the wheel and source distribution packages and verify both + get uploaded to the Python Package Index (PyPI). +6) [Optional] Go to fonttools `Github Releases <https://github.com/fonttools/fonttools/releases>`__ + page and create a new release, copy-pasting the content of the git tag + message. This way, the release notes are nicely formatted as markdown, and + users watching the repo will get an email notification. One day we shall + automate that too. + + +Acknowledgments +~~~~~~~~~~~~~~~~ + +In alphabetical order: + +aschmitz, Olivier Berten, Samyak Bhuta, Erik van Blokland, Petr van Blokland, +Jelle Bosma, Sascha Brawer, Tom Byrer, Antonio Cavedoni, Frédéric Coiffier, +Vincent Connare, David Corbett, Simon Cozens, Dave Crossland, Simon Daniels, +Peter Dekkers, Behdad Esfahbod, Behnam Esfahbod, Hannes Famira, Sam Fishman, +Matt Fontaine, Takaaki Fuji, Rob Hagemans, Yannis Haralambous, Greg Hitchcock, +Jeremie Hornus, Khaled Hosny, John Hudson, Denis Moyogo Jacquerye, Jack Jansen, +Tom Kacvinsky, Jens Kutilek, Antoine Leca, Werner Lemberg, Tal Leming, Liang Hai, Peter +Lofting, Cosimo Lupo, Olli Meier, Masaya Nakamura, Dave Opstad, Laurence Penney, +Roozbeh Pournader, Garret Rieger, Read Roberts, Colin Rofls, Guido van Rossum, +Just van Rossum, Andreas Seidel, Georg Seifert, Chris Simpkins, Miguel Sousa, +Adam Twardoch, Adrien Tétar, Vitaly Volkov, Paul Wise. + +Copyrights +~~~~~~~~~~ + +| Copyright (c) 1999-2004 Just van Rossum, LettError + (just@letterror.com) +| See `LICENSE <LICENSE>`__ for the full license. + +Copyright (c) 2000 BeOpen.com. All Rights Reserved. + +Copyright (c) 1995-2001 Corporation for National Research Initiatives. +All Rights Reserved. + +Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All +Rights Reserved. + +Have fun! + +.. |CI Build Status| image:: https://github.com/fonttools/fonttools/workflows/Test/badge.svg + :target: https://github.com/fonttools/fonttools/actions?query=workflow%3ATest +.. |Coverage Status| image:: https://codecov.io/gh/fonttools/fonttools/branch/main/graph/badge.svg + :target: https://codecov.io/gh/fonttools/fonttools +.. |PyPI| image:: https://img.shields.io/pypi/v/fonttools.svg + :target: https://pypi.org/project/FontTools +.. |Gitter Chat| image:: https://badges.gitter.im/fonttools-dev/Lobby.svg + :alt: Join the chat at https://gitter.im/fonttools-dev/Lobby + :target: https://gitter.im/fonttools-dev/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge + +Changelog +~~~~~~~~~ + +4.65.0 (released 2026-09-10) +---------------------------- + +- [glyf] Add ``__iter__``, ``items`` and ``values`` methods to the ``glyf`` table + to make it more dict-like (#4156). +- [feaLib] Escape the anonymous block tag when scanning for its terminator, so tags + containing regex metacharacters are matched literally (#4167). +- [varLib] Strip directory components from ``<variable-font name="..."/>`` when + deriving the output filename in the ``varLib`` command line, so a designspace + cannot write outside the output directory (#4168). +- [feaLib] Fix tracking of the current script and language across redundant + ``script`` statements. Rules following a ``script`` statement that names the + first declared language system no longer end up under the ``DFLT`` script, and + a ``script`` statement naming the already-current script still narrows the + language systems and terminates the current lookup while leaving the + ``lookupflag`` alone, matching makeotf (#1824, #2522, #4169). +- [varLib.interpolatable] Escape glyph names in the HTML report (#4172). +- [otlLib] Fix overflow handling when building contextual lookups: offset overflows + now raise ``OTLOffsetOverflowError`` instead of ``AttributeError`` so another + contextual format can be tried (regression from #3439). When all formats + overflow, split the ruleset in halves until it fits (#4171). + +4.64.0 (released 2026-08-31) +---------------------------- + +- [feaLib] Fix name-table parsing for multibyte Mac encodings (#1196, #4092). +- [ttProgram] Also indent TrueType assembly following ``IDEF[ ]``, like function + definitions (#4093). +- [subset] Keep East Asian spacing ``palt`` by default (#4094). +- [subset] Bug fix for MATH table in which constructions for glyphs that are only + added during MATH closure were kept (#4096). +- [ufoLib] Make glyph-to-group construction accessible outside of lookup function + (#4102). +- [glyf] Use reverse glyph map for O(1) ``__setitem__`` membership (#4103). +- [ttLib] Fix ``fixLookupOverFlows()`` reporting success when it had not promoted + any lookup to Extension, masking unresolvable overflows. +- [ttLib] Add support for TrueType Collection version 2 (#4100). +- [ttLib] Pin a single head.modified timestamp across ``TTCollection.save`` (#4111). +- [ttLib] Give an actionable error when LookupList overflow is unrecoverable (#4109). +- [ttLib] Add support for the AAT bitmap tables ``bhed``, ``bdat``, ``bloc``, + variants of ``head``, ``EBDT``, ``EBLC`` used in legacy Apple bitmap-only fonts + (#4115). +- [ttLib] Check ``OS/2`` fsSelection/macStyle consistency against ``bhed`` as well + as ``head`` (#4118, #4119). +- [misc.roundTools] Add types and documentation (#4123). +- [varLib.instancer] Instance the ``BASE`` table (#4137). +- [varLib.instancer] Fix Private-dict ``vsindex`` handling in ``instantiateCFF2`` + (#4129, #4132). +- [varLib.instancer] Fix crash instancing CFF2 fonts without a VariationStore + (#4130, #4131). +- [sfnt] Raise ``TTLibError`` instead of ``AssertionError`` or ``struct.error`` + when reading a font truncated within the table directory or a table entry + (#4147, #4149). +- [misc.xmlWriter] Escape the ```` terminator inside CDATA sections, so an SVG + document containing it can no longer smuggle markup past a TTX round trip + (#4139). +- [varLib.instancer] Implement avar2 partial-instancing: the avar version 2 + ItemVariationStore is adjusted so that remaining axes behave the same after + limiting the designspace (#4045). +- [feaLib] Add shorthand for the value at the default location in a variable + scalar: ``(100 wght=900:120)`` means ``(wght=400:100 wght=900:120)`` when the + wght default is 400 (#4024). +- [cmap] Raise ``TTLibError`` for a truncated or out-of-bounds cmap subtable + header (#4151). +- [designspaceLib] Reject conflicting duplicate inputs in axis maps instead of + silently keeping the last one (#4153). +- [designspaceLib] Read an empty ```` element as an empty lib instead of + raising ``IndexError`` (#4142, #4144). +- [colorLib] Raise a legible error when a COLRv0 layer, or a COLRv1 PaintGlyph or + PaintColrGlyph, references a glyph missing from the glyphMap, instead of failing + obscurely later (#2629, #4141). +- [cmap] Don't drop subtables in unsupported formats when compiling or dumping a + font read from binary (#4136). +- [ttLib] Implement ``splitSinglePos`` so GPOS lookup type 1 offset overflows can + be recovered by splitting the subtable (#4091, #4108). +- [cmap] Round-trip empty Macintosh format 2 subtables (#3663, #4117). +- [glyf] Raise ``TTLibError`` instead of ``RecursionError`` when ``recalcBounds()`` + hits a composite-component reference cycle (#3899, #4116). +- [svgLib] Fix crash parsing an SVG path with consecutive closepath commands + (``Z Z``) (#4122). +- [ttLib] Fix ``DefaultTable`` type annotations (#4126). +- [ttLib] Add support for the ``EBSC`` (Embedded Bitmap Scaling) table (#4113). +- [svgLib] Suppress spurious close segments caused by floating-point drift in + relative path commands (#3860, #4127). +- [qu2cu] Fix ``TypeError`` in the Cython-compiled build when ``Qu2CuPen`` passes + tuple splines (#4160). +- [mort] Add semantic decompilation, TTX, and compilation support for + rearrangement, contextual-substitution, ligature, and insertion subtables + (#4158, #4159, #4161). +- [svgLib] Start a new subpath at the just-closed subpath's initial point when a + drawto command follows a closepath, per SVG spec (#4154, #4155). +- [misc.filesystem] **SECURITY** Reject paths that resolve outside the filesystem + root: a malicious UFO could read arbitrary files via ``..`` components in + ``contents.plist``, and a crafted ``.ufoz`` could create files outside its + temporary mirror (#4124). +- [ttLib] **SECURITY** Sanitise glyph names used as filenames in EBDT/CBDT + ``ttx -z extfile`` export, preventing arbitrary file writes from untrusted + fonts (#4128). +- [misc.etree] **SECURITY** Don't resolve external XML entities in ``XMLParser`` + when lxml is used, preventing XXE file disclosure on lxml < 5.0 (#4145). +- [subset] Fully prune ``VARC`` auxiliary data: collect and remap variation + indices referenced by condition tables when subsetting the ``MultiVarStore``, + and drop the ``AxisIndicesList``, ``ConditionList``, and ``MultiVarStore`` + when they end up empty (#4162). + +4.63.0 (released 2026-05-14) +---------------------------- + +- [ttLib] Add support for Apple Color Emoji ``bgcl`` table (#4065). +- [ttLib] Add support for ``IFT`` and ``IFTX`` tables (Incremental Font Transfer, + PatchMapFormat2) (#4070, #4072). +- [otData] Introduce ``FieldSpec`` dataclass for OpenType table schema definitions, + replacing raw tuples in ``otData.py`` (#4076). +- [Feat] Show ``name`` table strings as comments next to label IDs in TTX output, + matching the convention used by ``fvar``, ``STAT``, ``trak`` (#4089). +- [cu2qu] Fix Cython complex-division rounding difference in + ``split_cubic_into_three`` that could cause ±1 off-curve coordinate shifts + (#3928, #4083). +- [designspaceLib] Fix ``map_backward`` for many-to-one (flat-segment) axis maps + that silently dropped entries via dict comprehension + (googlefonts/ufo2ft#978, #4085). +- [OS/2] Fix ``setUnicodeRanges`` to accept reserved bits 123-127, restoring + round-trip with ``getUnicodeRanges`` and fixing ``recalcUnicodeRanges`` crash + in the subsetter (#4087, #4088). +- [cython] Declare Cython extensions as free-threading compatible on Python 3.13+, + so that importing them on free-threaded Python no longer re-enables the GIL + (#4073, #4090). + +4.62.1 (released 2026-03-13) +---------------------------- + +- [feaLib] Extend contextual rule merging to all rule types: single subst, GSUB/GPOS + named lookups, ignore rules, and chained alternate subst (#4061). + +4.62.0 (released 2026-03-09) +---------------------------- + +- [diff] Add new ``fonttools diff`` command for comparing font files, imported from the + ``fdiff`` project and heavily reworked (#1190, #4007, #4009, #4011, #4013, #4019). +- [feaLib] Fix ``VariableScalar`` interpolation bug with non-linear avar mappings. Also + decouple ``VariableScalar`` from compiled fonts, allowing it to work with designspace data + before compilation (#3938, #4054). +- [feaLib] Fix ``VariableScalar`` axis ordering and iterative delta rounding to match fontc + behavior (#4053). +- [feaLib] Merge chained multi subst rules with same context into a single subtable instead of + emitting one subtable per glyph (#4016, #4058). +- [feaLib] Pass location to ``ConditionsetStatement`` to fix glyphsLib round-tripping + (fontra/fontra-glyphs#130, #4057). +- [feaLib] Write ``0xFFFF`` instead of ``0`` for missing nameIDs in ``cv`` feature params + (#4010, #4012). +- [cmap] Fix ``CmapSubtable.__lt__()`` ``TypeError`` on Python 3 when subtables share the + same encoding record, and add compile-time validation for unique encoding records (#4035, + #4055). +- [svgLib] Skip non-element XML nodes (comments, processing instructions) when drawing SVG + paths (#4042, #4043). +- [glifLib] Fix regression reading glyph outlines when ``glyphObject=None`` (#4030, #4031). +- [pointPen] Fix ``SegmentToPointPen`` edge case: only remove a duplicate final point on + ``closePath()`` if it is an on-curve point (#4014, #4015). +- [cffLib] **SECURITY** Replace ``eval()`` with ``safeEval()`` in ``parseBlendList()`` to + prevent arbitrary code execution from crafted TTX files (#4039, #4040). +- [ttLib] Remove defunct Adobe SING Glyphlet tables (``META``, ``SING``, ``GMAP``, ``GPKG``) + (#4044). +- [varLib.interpolatable] Various bugfixes: fix swapped nodeTypes assignment, duplicate + kink-detector condition, typos, CFF2 vsindex parsing, glyph existence check, and plot + helpers (#4046). +- [varLib.models] Fix ``getSubModel`` not forwarding ``extrapolate``/``axisRanges``; check + location uniqueness after stripping zeros (#4047). +- [varLib] Fix ``--variable-fonts`` filter in ``build_many``; remove dead code and fix + comments (#4048). +- [avar] Preserve existing name table in build; keep ``unbuild`` return types consistent; + validate ``map`` CLI coordinates (#4051). +- [cu2qu/qu2cu] Add input validation: reject non-positive tolerances, validate curve inputs + and list lengths (#4052). +- [colorLib] Raise a clear ``ColorLibError`` when base glyphs are missing from glyphMap, + instead of a confusing ``KeyError`` (#4041). +- [glyf] Remove unnecessary ``fvar`` table dependency (#4017). +- [fvar/trak] Remove unnecessary ``name`` table dependency (#4018). +- [ufoLib] Relax guideline validation to follow the updated spec (#3537, #3553). +- [ttFont] Fix ``saveXML`` regression with empty table lists, clarify docstring (#4025, #4026, + #4056). +- [setup.py] Link ``libm`` for Cython extensions using math functions (#4028, #4029). +- Add typing annotations for ``DSIG``, ``DefaultTable``, ``ttProgram`` (#4033). + +4.61.1 (released 2025-12-12) +---------------------------- + +- [otlLib] buildCoverage: return empty Coverage instead of None (#4003, #4004). +- [instancer] bug fix in ``avar2`` full instancing (#4002). +- [designspaceLib] Preserve empty conditionsets when serializing to XML (#4001). +- [fontBu ilder] Fix FontBuilder ``setupOS2()`` default params globally polluted (#3996, #3997). +- [ttFont] Add more typing annotations to ttFont, xmlWriter, sfnt, varLib.models and others (#3952, #3826). +- Explicitly test and declare support for Python 3.14, even though we were already shipping pre-built wheels for it (#3990). + +4.60.2 (released 2025-12-09) +---------------------------- + +- **Backport release** Same as 4.61.0 but without "Drop support for EOL Python 3.9" change to allow + downstream projects still on Python 3.9 to avail of the security fix for CVE-2025-66034 (#3994, #3999). + +4.61.0 (released 2025-11-28) +---------------------------- + +- [varLib.main]: **SECURITY** Only use basename(vf.filename) to prevent path traversal attacks when + running ``fonttools varLib`` command, or code which invokes ``fonttools.varLib.main()``. + Fixes CVE-2025-66034, see: + https://github.com/fonttools/fonttools/security/advisories/GHSA-768j-98cg-p3fv. +- [feaLib] Sort BaseLangSysRecords by tag (#3986). +- Drop support for EOL Python 3.9 (#3982). +- [instancer] Support --remove-overlaps for fonts with CFF2 table (#3975). +- [CFF2ToCFF] Add --remove-overlaps option (#3976). +- [feaLib] Raise an error for rsub with NULL target (#3979). +- [bezierTools] Fix logic bug in curveCurveIntersections (#3963). +- [feaLib] Error when condition sets have the same name (#3958). +- [cu2qu.ufo] skip processing empty glyphs to support sparse kerning masters (#3956). +- [unicodedata] Update to Unicode 17. Require ``unicodedata2 >= 17.0.0`` when installed with 'unicode' extra. + +4.60.1 (released 2025-09-29) +---------------------------- + +- [ufoLib] Reverted accidental method name change in ``UFOReader.getKerningGroupConversionRenameMaps`` + that broke compatibility with downstream projects like defcon (#3948, #3947, robotools/defcon#478). +- [ufoLib] Added test coverage for ``getKerningGroupConversionRenameMaps`` method (#3950). +- [subset] Don't try to subset BASE table; pass it through by default instead (#3949). +- [subset] Remove empty BaseRecord entries in MarkBasePos lookups (#3897, #3892). +- [subset] Add pruning for MarkLigPos and MarkMarkPos lookups (#3946). +- [subset] Remove duplicate features when subsetting (#3945). +- [Docs] Added documentation for the visitor module (#3944). + +4.60.0 (released 2025-09-17) +---------------------------- + +- [pointPen] Allow ``reverseFlipped`` parameter of ``DecomposingPointPen`` to take a ``ReverseFlipped`` + enum value to control whether/how to reverse contour direction of flipped components, in addition to + the existing True/False. This allows to set ``ReverseFlipped.ON_CURVE_FIRST`` to ensure that + the decomposed outline starts with an on-curve point before being reversed, for better consistency + with other segment-oriented contour transformations. The change is backward compatible, and the + default behavior hasn't changed (#3934). +- [filterPen] Added ``ContourFilterPointPen``, base pen for buffered contour operations, and + ``OnCurveStartPointPen`` filter to ensure contours start with an on-curve point (#3934). +- [cu2qu] Fixed difference in cython vs pure-python complex division by real number (#3930). +- [varLib.avar] Refactored and added some new sub-modules and scripts (#3926). + * ``varLib.avar.build`` module to build avar (and a missing fvar) binaries into a possibly empty TTFont, + * ``varLib.avar.unbuild`` module to print a .designspace snippet that would generate the same avar binary, + * ``varLib.avar.map`` module to take TTFont and do the mapping, in user/normalized space, + * ``varLib.avar.plan`` module moved from ``varLib.avarPlanner``. + The bare ``fonttools varLib.avar`` script is deprecated, in favour of ``fonttools varLib.avar.build`` (or ``unbuild``). +- [interpolatable] Clarify ``linear_sum_assignment`` backend options and minimal dependency + usage (#3927). +- [post] Speed up ``build_psNameMapping`` (#3923). +- [ufoLib] Added typing annotations to fontTools.ufoLib (#3875). + +4.59.2 (released 2025-08-27) +---------------------------- + +- [varLib] Clear ``USE_MY_METRICS`` component flags when inconsistent across masters (#3912). +- [varLib.instancer] Avoid negative advance width/height values when instatiating HVAR/VVAR, + (unlikely in well-behaved fonts) (#3918). +- [subset] Fix shaping behaviour when pruning empty mark sets (#3915, harfbuzz/harfbuzz#5499). +- [cu2qu] Fixed ``dot()`` product of perpendicular vectors not always returning exactly 0.0 + in all Python implementations (#3911) +- [varLib.instancer] Implemented fully-instantiating ``avar2`` fonts (#3909). +- [feaLib] Allow float values in ``VariableScalar``'s axis locations (#3906, #3907). +- [cu2qu] Handle special case in ``calc_intersect`` for degenerate cubic curves where 3 to 4 + control points are equal (#3904). + +4.59.1 (released 2025-08-14) +---------------------------- + +- [featureVars] Update OS/2.usMaxContext if possible after addFeatureVariationsRaw (#3894). +- [vhmtx] raise TTLibError('not enough data...') when hmtx/vmtx are truncated (#3843, #3901). +- [feaLib] Combine duplicate features that have the same set of lookups regardless of the order in which those lookups are added to the feature (#3895). +- [varLib] Deprecate ``varLib.mutator`` in favor of ``varLib.instancer``. The latter + provides equivalent full (static font) instancing in addition to partial VF instancing. + CLI users should replace ``fonttools varLib.mutator`` with ``fonttools varLib.instancer``. + API users should migrate to ``fontTools.varLib.instancer.instantiateVariableFont`` (#2680). + + +4.59.0 (released 2025-07-16) +---------------------------- + +- Removed hard-dependency on pyfilesystem2 (``fs`` package) from ``fonttools[ufo]`` extra. + This is replaced by the `fontTools.misc.filesystem` package, a stdlib-only, drop-in + replacement for the subset of the pyfilesystem2's API used by ``fontTools.ufoLib``. + The latter should continue to work with the upstream ``fs`` (we even test with/without). + Clients who wish to continue using ``fs`` can do so by depending on it directly instead + of via the ``fonttools[ufo]`` extra (#3885, #3620). +- [xmlWriter] Replace illegal XML characters (e.g. control or non-characters) with "?" + when dumping to ttx (#3868, #71). +- [varLib.hvar] Fixed vertical metrics fields copy/pasta error (#3884). +- Micro optimizations in ttLib and sstruct modules (#3878, #3879). +- [unicodedata] Add Garay script to RTL_SCRIPTS (#3882). +- [roundingPen] Remove unreliable kwarg usage. Argument names aren’t consistent among + point pens’ ``.addComponent()`` implementations, in particular ``baseGlyphName`` + vs ``glyphName`` (#3880). + +4.58.5 (released 2025-07-03) +---------------------------- + +- [feaLib] Don't try to combine ligature & multisub rules (#3874). +- [feaLib/ast] Use weakref proxies to avoid cycles in visitor (#3873). +- [varLib.instancer] Fixed instancing CFF2 fonts where VarData contains more than 64k items (#3858). + +4.58.4 (released 2025-06-13) +---------------------------- + +- [feaLib] Allow for empty MarkFilter & MarkAttach sets (#3856). + +4.58.3 (released 2025-06-13) +---------------------------- + +- [feaLib] Fixed iterable check for Python 3.13.4 and newer (#3854, #3855). + +4.58.2 (released 2025-06-06) +---------------------------- + +- [ttLib.reorderGlyphs] Handle CFF2 when reordering glyphs (#3852) +- [subset] Copy name IDs in use before scrapping or scrambling them for webfonts (#3853) + +4.58.1 (released 2025-05-28) +---------------------------- + +- [varLib] Make sure that fvar named instances only reuse name ID 2 or 17 if they are at the default location across all axes, to match OT spec requirement (#3831). +- [feaLib] Improve single substitution promotion to multiple/ligature substitutions, fixing a few bugs as well (#3849). +- [loggingTools] Make ``Timer._time`` a static method that doesn't take self, makes it easier to override (#3836). +- [featureVars] Use ``None`` for empty ConditionSet, which translates to a null offset in the compiled table (#3850). +- [feaLib] Raise an error on conflicting ligature substitution rules instead of silently taking the last one (#3835). +- Add typing annotations to T2CharStringPen (#3837). +- [feaLib] Add single substitutions that were promoted to multiple or ligature substitutions to ``aalt`` feature (#3847). +- [featureVars] Create a default ``LangSys`` in a ``ScriptRecord`` if missing when adding feature variations to existing GSUB later in the build (#3838). +- [symfont] Added a ``main()``. +- [cffLib.specializer] Fix rmoveto merging when blends used (#3839, #3840). +- [pyftmerge] Add support for cmap format 14 in the merge tool (#3830). +- [varLib.instancer/cff2] Fix vsindex of Private dicts when instantiating (#3828, #3232). +- Update text file read to use UTF-8 with optional BOM so it works with e.g. Windows Notepad.exe (#3824). +- [varLib] Ensure that instances only reuse name ID 2 or 17 if they are at the default location across all axes (#3831). +- [varLib] Create a dflt LangSys in a ScriptRecord when adding variations later, to fix an avoidable crash in an edge case (#3838). + +4.58.0 (released 2025-05-10) +---------------------------- + +- Drop Python 3.8, require 3.9+ (#3819) +- [HVAR, VVAR] Prune unused regions when using a direct mapping (#3797) +- [Docs] Improvements to ufoLib documentation (#3721) +- [Docs] Improvements to varLib documentation (#3727) +- [Docs] Improvements to Pens and pen-module documentation (#3724) +- [Docs] Miscellany updates to docs (misc modules and smaller modules) (#3730) +- [subset] Close codepoints over BiDi mirror variants. (#3801) +- [feaLib] Fix serializing ChainContextPosStatement and + ChainContextSubstStatement in some rare cases (#3788) +- [designspaceLib] Clarify user expectations for getStatNames (#2892) +- [GVAR] Add support for new `GVAR` table (#3728) +- [TSI0, TSI5] Derive number of entries to decompile from data length (#2477) +- [ttLib] Fix `AttributeError` when reporting table overflow (#3808) +- [ttLib] Apply rounding more often in getCoordinates (#3798) +- [ttLib] Ignore component bounds if empty (#3799) +- [ttLib] Change the separator for duplicate glyph names from "#" to "." (#3809) +- [feaLib] Support subtable breaks in CursivePos, MarkBasePos, MarkToLigPos and + MarkToMarkPos lookups (#3800, #3807) +- [feaLib] If the same lookup has single substitutions and ligature + substitutions, upgrade single substitutions to ligature substitutions with + one input glyph (#3805) +- [feaLib] Correctly handle in single pos lookups (#3803) +- [feaLib] Remove duplicates from class pair pos classes instead of raising an + error (#3804) +- [feaLib] Support creating extension lookups using useExtenion lookup flag + instead of silently ignoring it (#3811) +- [STAT] Add typing for the simpler STAT arguments (#3812) +- [otlLib.builder] Add future import for annotations (#3814) +- [cffLib] Fix reading supplement encoding (#3813) +- [voltLib] Add some missing functionality and fixes to voltLib and VoltToFea, + making the conversion to feature files more robust. Add also `fonttools + voltLib` command line tool to compile VOLT sources directly (doing an + intermediate fea conversion internally) (#3818) +- [pens] Add some PointPen annotations (#3820) + +4.57.0 (released 2025-04-03) +---------------------------- + +- [ttLib.__main__] Add `--no-recalc-timestamp` flag (#3771) +- [ttLib.__main__] Add `-b` (recalcBBoxes=False) flag (#3772) +- [cmap] Speed up glyphOrder loading from cmap (#3774) +- [ttLib.__main__] Improvements around the `-t` flag (#3776) +- [Debg] Fix parsing from XML; add roundtrip tests (#3781) +- [fealib] Support \*Base.MinMax tables (#3783, #3786) +- [config] Add OPTIMIZE_FONT_SPEED (#3784) +- [varLib.hvar] New module to add HVAR table to the font (#3780) +- [otlLib.optimize] Fix crash when the provided TTF does not contain a `GPOS` (#3794) + +4.56.0 (released 2025-02-07) +---------------------------- + +- [varStore] Sort the input todo list with the same sorting key used for the opimizer's output (#3767). +- [otData] Fix DeviceTable's ``DeltaValue`` repeat value which caused a crash after importing from XML and then compiling a GPOS containing Device tables (#3758). +- [feaLib] Make ``FeatureLibError`` pickleable, so client can e.g. use feaLib to can compile features in parallel with multiprocessing (#3762). +- [varLib/gvar] Removed workaround for old, long-fixed macOS bug about composite glyphs with all zero deltas (#1381, #1788). +- [Docs] Updated ttLib documentation, beefed up TTFont and TTGlyphSet explanations (#3720). + +4.55.8 (released 2025-01-29) +---------------------------- + +- [MetaTools] Fixed bug in buildUCD.py script whereby the first non-header line of some UCD text file was being skipped. This affected in particular the U+00B7 (MIDDLE DOT) entry of ScriptExtensions.txt (#3756). + +4.55.7 (released 2025-01-28) +---------------------------- + +- Shorten the changelog included in PyPI package description to accommodate maximum length limit imposed by Azure DevOps. No actual code changes since v4.55.6 (#3754). + +4.55.6 (released 2025-01-24) +---------------------------- + +- [glyf] Fixed regression introduced in 4.55.5 when computing bounds of nested composite glyphs with transformed components (#3752). + +4.55.5 (released 2025-01-23) +---------------------------- + +- [glyf] Fixed recalcBounds of transformed components with unrounded coordinates (#3750). +- [feaLib] Allow duplicate script/language statements (#3749). + +4.55.4 (released 2025-01-21) +---------------------------- + +- [bezierTools] Fixed ``splitCubicAtT`` sometimes not returning identical start/end points as result of numerical precision (#3742, #3743). +- [feaLib/ast] Fixed docstring of ``AlternateSubstStatement`` (#3735). +- [transform] Typing fixes (#3734). + +4.55.3 (released 2024-12-10) +---------------------------- + +- [Docs] fill out ttLib table section [#3716] +- [feaLib] More efficient inline format 4 lookups [#3726] + +4.55.2 (released 2024-12-05) +---------------------------- + +- [Docs] update Sphinx config (#3712) +- [designspaceLib] Allow axisOrdering to be set to zero (#3715) +- [feaLib] Don’t modify variable anchors in place (#3717) + +4.55.1 (released 2024-12-02) +---------------------------- + +- [ttGlyphSet] Support VARC CFF2 fonts (#3683) +- [DecomposedTransform] Document and implement always skewY == 0 (#3697) +- [varLib] "Fix" cython iup issue? (#3704) +- Cython minor refactor (#3705) + + +4.55.0 (released 2024-11-14) +---------------------------- + +- [cffLib.specializer] Adjust stack use calculation (#3689) +- [varLib] Lets not add mac names if the rest of name doesn't have them (#3688) +- [ttLib.reorderGlyphs] Update CFF table charstrings and charset (#3682) +- [cffLib.specializer] Add cmdline to specialize a CFF2 font (#3675, #3679) +- [CFF2] Lift uint16 VariationStore.length limitation (#3674) +- [subset] consider variation selectors subsetting cmap14 (#3672) +- [varLib.interpolatable] Support CFF2 fonts (#3670) +- Set isfinal to true in XML parser for proper resource cleanup (#3669) +- [removeOverlaps] Fix CFF CharString width (#3659) +- [glyf] Add optimizeSize option (#3657) +- Python 3.13 support (#3656) +- [TupleVariation] Optimize for loading speed, not size (#3650, #3653) + + +4.54.1 (released 2024-09-24) +---------------------------- + +- [unicodedata] Update to Unicode 16 +- [subset] Escape ``\\`` in doc string + +4.54.0 (released 2024-09-23) +---------------------------- + +- [Docs] Small docs cleanups by @n8willis (#3611) +- [Docs] cleanup code blocks by @n8willis (#3627) +- [Docs] fix Sphinx builds by @n8willis (#3625) +- [merge] Minor fixes to documentation for merge by @drj11 (#3588) +- [subset] Small tweaks to pyftsubset documentation by @RoelN (#3633) +- [Tests] Do not require fonttools command to be available by @behdad (#3612) +- [Tests] subset_test: add failing test to reproduce issue #3616 by @anthrotype (#3622) +- [ttLib] NameRecordVisitor: include whole sequence of character variants' UI labels, not just the first by @anthrotype (#3617) +- [varLib.avar] Reconstruct mappings from binary by @behdad (#3598) +- [varLib.instancer] Fix visual artefacts with partial L2 instancing by @Hoolean (#3635) +- [varLib.interpolatable] Support discrete axes in .designspace by @behdad (#3599) +- [varLib.models] By default, assume OpenType-like normalized space by @behdad (#3601) + +4.53.1 (released 2024-07-05) +---------------------------- + +- [feaLib] Improve the sharing of inline chained lookups (#3559) +- [otlLib] Correct the calculation of OS/2.usMaxContext with reversed chaining contextual single substitutions (#3569) +- [misc.visitor] Visitors search the inheritance chain of objects they are visiting (#3581) + +4.53.0 (released 2024-05-31) +---------------------------- + +- [ttLib.removeOverlaps] Support CFF table to aid in downconverting CFF2 fonts (#3528) +- [avar] Fix crash when accessing not-yet-existing attribute (#3550) +- [docs] Add buildMathTable to otlLib.builder documentation (#3540) +- [feaLib] Allow UTF-8 with BOM when reading features (#3495) +- [SVGPathPen] Revert rounding coordinates to two decimal places by default (#3543) +- [varLib.instancer] Refix output filename decision-making (#3545, #3544, #3548) + +4.52.4 (released 2024-05-27) +---------------------------- + +- [varLib.cff] Restore and deprecate convertCFFtoCFF2 that was removed in 4.52.0 + release as it is used by downstream projects (#3535). + +4.52.3 (released 2024-05-27) +---------------------------- + +- Fixed a small syntax error in the reStructuredText-formatted NEWS.rst file + which caused the upload to PyPI to fail for 4.52.2. No other code changes. + +4.52.2 (released 2024-05-27) +---------------------------- + +- [varLib.interpolatable] Ensure that scipy/numpy output is JSON-serializable + (#3522, #3526). +- [housekeeping] Regenerate table lists, to fix pyinstaller packaging of the new + ``VARC`` table (#3531, #3529). +- [cffLib] Make CFFToCFF2 and CFF2ToCFF more robust (#3521, #3525). + +4.52.1 (released 2024-05-24) +---------------------------- + +- Fixed a small syntax error in the reStructuredText-formatted NEWS.rst file + which caused the upload to PyPI to fail for 4.52.0. No other code changes. + +4.52.0 (released 2024-05-24) +---------------------------- + +- Added support for the new ``VARC`` (Variable Composite) table that is being + proposed to OpenType spec (#3395). For more info: + https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md +- [ttLib.__main__] Fixed decompiling all tables (90fed08). +- [feaLib] Don't reference the same lookup index multiple times within the same + feature record, it is only applied once anyway (#3520). +- [cffLib] Moved methods to desubroutinize, remove hints and unused subroutines + from subset module to cffLib (#3517). +- [varLib.instancer] Added support for partial-instancing CFF2 tables! Also, added + method to down-convert from CFF2 to CFF 1.0, and CLI entry points to convert + CFF<->CFF2 (#3506). +- [subset] Prune unused user name IDs even with --name-IDs='*' (#3410). +- [ttx] use GNU-style getopt to intermix options and positional arguments (#3509). +- [feaLib.variableScalar] Fixed ``value_at_location()`` method (#3491) +- [psCharStrings] Shorten output of ``encodeFloat`` (#3492). +- [bezierTools] Fix infinite-recursion in ``calcCubicArcLength`` (#3502). +- [avar2] Implement ``avar2`` support in ``TTFont.getGlyphSet()`` (#3473). + +4.51.0 (released 2024-04-05) +---------------------------- + +- [ttLib] Optimization on loading aux fields (#3464). +- [ttFont] Add reorderGlyphs (#3468). + +4.50.0 (released 2024-03-15) +---------------------------- + +- [pens] Added decomposing filter pens that draw components as regular contours (#3460). +- [instancer] Drop explicit no-op axes from TupleVariations (#3457). +- [cu2qu/ufo] Return set of modified glyph names from fonts_to_quadratic (#3456). + +4.49.0 (released 2024-02-15) +---------------------------- + +- [otlLib] Add API for building ``MATH`` table (#3446) + +4.48.1 (released 2024-02-06) +---------------------------- + +- Fixed uploading wheels to PyPI, no code changes since v4.48.0. + +4.48.0 (released 2024-02-06) +---------------------------- + +- [varLib] Do not log when there are no OTL tables to be merged. +- [setup.py] Do not restrict lxml<5 any more, tests pass just fine with lxml>=5. +- [feaLib] Remove glyph and class names length restrictions in FEA (#3424). +- [roundingPens] Added ``transformRoundFunc`` parameter to the rounding pens to allow + for custom rounding of the components' transforms (#3426). +- [feaLib] Keep declaration order of ligature components within a ligature set, instead + of sorting by glyph name (#3429). +- [feaLib] Fixed ordering of alternates in ``aalt`` lookups, following the declaration + order of feature references within the ``aalt`` feature block (#3430). +- [varLib.instancer] Fixed a bug in the instancer's IUP optimization (#3432). +- [sbix] Support sbix glyphs with new graphicType "flip" (#3433). +- [svgPathPen] Added ``--glyphs`` option to dump the SVG paths for the named glyphs + in the font (0572f78). +- [designspaceLib] Added "description" attribute to ```` and ```` + elements, and allow multiple ```` elements to group ```` elements + that are logically related (#3435, #3437). +- [otlLib] Correctly choose the most compact GSUB contextual lookup format (#3439). + +4.47.2 (released 2024-01-11) +---------------------------- + +Minor release to fix uploading wheels to PyPI. + +4.47.1 (released 2024-01-11) +---------------------------- + +- [merge] Improve help message and add standard command line options (#3408) +- [otlLib] Pass ``ttFont`` to ``name.addName`` in ``buildStatTable`` (#3406) +- [featureVars] Re-use ``FeatureVariationRecord``'s when possible (#3413) + +4.47.0 (released 2023-12-18) +---------------------------- + +- [varLib.models] New API for VariationModel: ``getMasterScalars`` and + ``interpolateFromValuesAndScalars``. +- [varLib.interpolatable] Various bugfixes and rendering improvements. In particular, + add a Summary page in the front, and an Index and Table-of-Contents in the back. + Change the page size to Letter. +- [Docs/designspaceLib] Defined a new ``public.fontInfo`` lib key, not used anywhere yet (#3358). + +4.46.0 (released 2023-12-02) +---------------------------- + +- [featureVars] Allow to register the same set of substitution rules to multiple features. + The ``addFeatureVariations`` function can now take a list of featureTags; similarly, the + lib key 'com.github.fonttools.varLib.featureVarsFeatureTag' can now take a + comma-separateed string of feature tags (e.g. "salt,ss01") instead of a single tag (#3360). +- [featureVars] Don't overwrite GSUB FeatureVariations, but append new records to it + for features which are not already there. But raise ``VarLibError`` if the feature tag + already has feature variations associated with it (#3363). +- [varLib] Added ``addGSUBFeatureVariations`` function to add GSUB Feature Variations + to an existing variable font from rules defined in a DesignSpace document (#3362). +- [varLib.interpolatable] Various bugfixes and rendering improvements. In particular, + a new test for "underweight" glyphs. The new test reports quite a few false-positives + though. Please send feedback. + +4.45.1 (released 2023-11-23) +---------------------------- + +- [varLib.interpolatable] Various bugfixes and improvements, better reporting, reduced + false positives. +- [ttGlyphSet] Added option to not recalculate glyf bounds (#3348). + +4.45.0 (released 2023-11-20) +---------------------------- + +- [varLib.interpolatable] Vastly improved algorithms. Also available now is ``--pdf`` + and ``--html`` options to generate a PDF or HTML report of the interpolation issues. + The PDF/HTML report showcases the problematic masters, the interpolated broken + glyph, as well as the proposed fixed version. + +4.44.3 (released 2023-11-15) +---------------------------- + +- [subset] Only prune codepage ranges for OS/2.version >= 1, ignore otherwise (#3334). +- [instancer] Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing + MVAR table containing 'hasc', 'hdsc' or 'hlgp' tags (#3297). + +4.44.2 (released 2023-11-14) +---------------------------- + +- [glyf] Have ``Glyph.recalcBounds`` skip empty components (base glyph with no contours) + when computing the bounding box of composite glyphs. This simply restores the existing + behavior before some changes were introduced in fonttools 4.44.0 (#3333). + +4.44.1 (released 2023-11-14) +---------------------------- + +- [feaLib] Ensure variable mark anchors are deep-copied while building since they + get modified in-place and later reused (#3330). +- [OS/2|subset] Added method to ``recalcCodePageRanges`` to OS/2 table class; added + ``--prune-codepage-ranges`` to `fonttools subset` command (#3328, #2607). + +4.44.0 (released 2023-11-03) +---------------------------- + +- [instancer] Recalc OS/2 AvgCharWidth after instancing if default changes (#3317). +- [otlLib] Make ClassDefBuilder class order match varLib.merger's, i.e. large + classes first, then glyph lexicographic order (#3321, #3324). +- [instancer] Allow not specifying any of min:default:max values and let be filled + up with fvar's values (#3322, #3323). +- [instancer] When running --update-name-table ignore axes that have no STAT axis + values (#3318, #3319). +- [Debg] When dumping to ttx, write the embedded JSON as multi-line string with + indentation (92cbfee0d). +- [varStore] Handle > 65535 items per encoding by splitting VarData subtable (#3310). +- [subset] Handle null-offsets in MarkLigPos subtables. +- [subset] Keep East Asian spacing fatures vhal, halt, chws, vchw by default (#3305). +- [instancer.solver] Fixed case where axisDef < lower and upper < axisMax (#3304). +- [glyf] Speed up compilation, mostly around ``recalcBounds`` (#3301). +- [varLib.interpolatable] Speed it up when working on variable fonts, plus various + micro-optimizations (#3300). +- Require unicodedata2 >= 15.1.0 when installed with 'unicode' extra, contains UCD 15.1. + +4.43.1 (released 2023-10-06) +---------------------------- + +- [EBDT] Fixed TypeError exception in `_reverseBytes` method triggered when dumping + some bitmap fonts with `ttx -z bitwise` option (#3162). +- [v/hhea] Fixed UnboundLocalError exception in ``recalc`` method when no vmtx or hmtx + tables are present (#3290). +- [bezierTools] Fixed incorrectly typed cython local variable leading to TypeError when + calling ``calcQuadraticArcLength`` (#3288). +- [feaLib/otlLib] Better error message when building Coverage table with missing glyph (#3286). + +4.43.0 (released 2023-09-29) +---------------------------- + +- [subset] Set up lxml ``XMLParser(resolve_entities=False)`` when parsing OT-SVG documents + to prevent XML External Entity (XXE) attacks (9f61271dc): + https://codeql.github.com/codeql-query-help/python/py-xxe/ +- [varLib.iup] Added workaround for a Cython bug in ``iup_delta_optimize`` that was + leading to IUP tolerance being incorrectly initialised, resulting in sub-optimal deltas + (60126435d, cython/cython#5732). +- [varLib] Added new command-line entry point ``fonttools varLib.avar`` to add an + ``avar`` table to an existing VF from axes mappings in a .designspace file (0a3360e52). +- [instancer] Fixed bug whereby no longer used variation regions were not correctly pruned + after VarData optimization (#3268). +- Added support for Python 3.12 (#3283). + +4.42.1 (released 2023-08-20) +---------------------------- + +- [t1Lib] Fixed several Type 1 issues (#3238, #3240). +- [otBase/packer] Allow sharing tables reached by different offset sizes (#3241, #3236). +- [varLib/merger] Fix Cursive attachment merging error when all anchors are NULL (#3248, #3247). +- [ttLib] Fixed warning when calling ``addMultilingualName`` and ``ttFont`` parameter was not + passed on to ``findMultilingualName`` (#3253). + +4.42.0 (released 2023-08-02) +---------------------------- + +- [varLib] Use sentinel value 0xFFFF to mark a glyph advance in hmtx/vmtx as non + participating, allowing sparse masters to contain glyphs for variation purposes other + than {H,V}VAR (#3235). +- [varLib/cff] Treat empty glyphs in non-default masters as missing, thus not participating + in CFF2 delta computation, similarly to how varLib already treats them for gvar (#3234). +- Added varLib.avarPlanner script to deduce 'correct' avar v1 axis mappings based on + glyph average weights (#3223). + +4.41.1 (released 2023-07-21) +---------------------------- + +- [subset] Fixed perf regression in v4.41.0 by making ``NameRecordVisitor`` only visit + tables that do contain nameID references (#3213, #3214). +- [varLib.instancer] Support instancing fonts containing null ConditionSet offsets in + FeatureVariationRecords (#3211, #3212). +- [statisticsPen] Report font glyph-average weight/width and font-wide slant. +- [fontBuilder] Fixed head.created date incorrectly set to 0 instead of the current + timestamp, regression introduced in v4.40.0 (#3210). +- [varLib.merger] Support sparse ``CursivePos`` masters (#3209). + +4.41.0 (released 2023-07-12) +---------------------------- + +- [fontBuilder] Fixed bug in setupOS2 with default panose attribute incorrectly being + set to a dict instead of a Panose object (#3201). +- [name] Added method to ``removeUnusedNameRecords`` in the user range (#3185). +- [varLib.instancer] Fixed issue with L4 instancing (moving default) (#3179). +- [cffLib] Use latin1 so we can roundtrip non-ASCII in {Full,Font,Family}Name (#3202). +- [designspaceLib] Mark as optional in docs (as it is in the code). +- [glyf-1] Fixed drawPoints() bug whereby last cubic segment becomes quadratic (#3189, #3190). +- [fontBuilder] Propagate the 'hidden' flag to the fvar Axis instance (#3184). +- [fontBuilder] Update setupAvar() to also support avar 2, fixing ``_add_avar()`` call + site (#3183). +- Added new ``voltLib.voltToFea`` submodule (originally Tiro Typeworks' "Volto") for + converting VOLT OpenType Layout sources to FEA format (#3164). + +4.40.0 (released 2023-06-12) +---------------------------- + +- Published native binary wheels to PyPI for all the python minor versions and platform + and architectures currently supported that would benefit from this. They will include + precompiled Cython-accelerated modules (e.g. cu2qu) without requiring to compile them + from source. The pure-python wheel and source distribution will continue to be + published as always (pip will automatically chose them when no binary wheel is + available for the given platform, e.g. pypy). Use ``pip install --no-binary=fonttools fonttools`` + to expliclity request pip to install from the pure-python source. +- [designspaceLib|varLib] Add initial support for specifying axis mappings and build + ``avar2`` table from those (#3123). +- [feaLib] Support variable ligature caret position (#3130). +- [varLib|glyf] Added option to --drop-implied-oncurves; test for impliable oncurve + points either before or after rounding (#3146, #3147, #3155, #3156). +- [TTGlyphPointPen] Don't error with empty contours, simply ignore them (#3145). +- [sfnt] Fixed str vs bytes remnant of py3 transition in code dealing with de/compiling + WOFF metadata (#3129). +- [instancer-solver] Fixed bug when moving default instance with sparse masters (#3139, #3140). +- [feaLib] Simplify variable scalars that don’t vary (#3132). +- [pens] Added filter pen that explicitly emits closing line when lastPt != movePt (#3100). +- [varStore] Improve optimize algorithm and better document the algorithm (#3124, #3127). + Added ``quantization`` option (#3126). +- Added CI workflow config file for building native binary wheels (#3121). +- [fontBuilder] Added glyphDataFormat=0 option; raise error when glyphs contain cubic + outlines but glyphDataFormat was not explicitly set to 1 (#3113, #3119). +- [subset] Prune emptied GDEF.MarkGlyphSetsDef and remap indices; ensure GDEF is + subsetted before GSUB and GPOS (#3114, #3118). +- [xmlReader] Fixed issue whereby DSIG table data was incorrectly parsed (#3115, #2614). +- [varLib/merger] Fixed merging of SinglePos with pos=0 (#3111, #3112). +- [feaLib] Demote "Feature has not been defined" error to a warning when building aalt + and referenced feature is empty (#3110). +- [feaLib] Dedupe multiple substitutions with classes (#3105). + +4.39.4 (released 2023-05-10) +---------------------------- + +- [varLib.interpolatable] Allow for sparse masters (#3075) +- [merge] Handle differing default/nominalWidthX in CFF (#3070) +- [ttLib] Add missing main.py file to ttLib package (#3088) +- [ttx] Fix missing composite instructions in XML (#3092) +- [ttx] Fix split tables option to work on filenames containing '%' (#3096) +- [featureVars] Process lookups for features other than rvrn last (#3099) +- [feaLib] support multiple substitution with classes (#3103) + +4.39.3 (released 2023-03-28) +---------------------------- + +- [sbix] Fixed TypeError when compiling empty glyphs whose imageData is None, regression + was introduced in v4.39 (#3059). +- [ttFont] Fixed AttributeError on python <= 3.10 when opening a TTFont from a tempfile + SpooledTemporaryFile, seekable method only added on python 3.11 (#3052). + +4.39.2 (released 2023-03-16) +---------------------------- + +- [varLib] Fixed regression introduced in 4.39.1 whereby an incomplete 'STAT' table + would be built even though a DesignSpace v5 did contain 'STAT' definitions (#3045, #3046). + +4.39.1 (released 2023-03-16) +---------------------------- + +- [avar2] Added experimental support for reading/writing avar version 2 as specified in + this draft proposal: https://github.com/harfbuzz/boring-expansion-spec/blob/main/avar2.md +- [glifLib] Wrap underlying XML library exceptions with GlifLibError when parsing GLIFs, + and also print the name and path of the glyph that fails to be parsed (#3042). +- [feaLib] Consult avar for normalizing user-space values in ConditionSets and in + VariableScalars (#3042, #3043). +- [ttProgram] Handle string input to Program.fromAssembly() (#3038). +- [otlLib] Added a config option to emit GPOS 7 lookups, currently disabled by default + because of a macOS bug (#3034). +- [COLRv1] Added method to automatically compute ClipBoxes (#3027). +- [ttFont] Fixed getGlyphID to raise KeyError on missing glyphs instead of returning + None. The regression was introduced in v4.27.0 (#3032). +- [sbix] Fixed UnboundLocalError: cannot access local variable 'rawdata' (#3031). +- [varLib] When building VF, do not overwrite a pre-existing ``STAT`` table that was built + with feaLib from FEA feature file. Also, added support for building multiple VFs + defined in Designspace v5 from ``fonttools varLib`` script (#3024). +- [mtiLib] Only add ``Debg`` table with lookup names when ``FONTTOOLS_LOOKUP_DEBUGGING`` + env variable is set (#3023). + +4.39.0 (released 2023-03-06) +---------------------------- + +- [mtiLib] Optionally add `Debg` debug info for MTI feature builds (#3018). +- [ttx] Support reading input file from standard input using special `-` character, + similar to existing `-o -` option to write output to standard output (#3020). +- [cython] Prevent ``cython.compiled`` raise AttributeError if cython not installed + properly (#3017). +- [OS/2] Guard against ZeroDivisionError when calculating xAvgCharWidth in the unlikely + scenario no glyph has non-zero advance (#3015). +- [subset] Recompute xAvgCharWidth independently of --no-prune-unicode-ranges, + previously the two options were involuntarily bundled together (#3012). +- [fontBuilder] Add ``debug`` parameter to addOpenTypeFeatures method to add source + debugging information to the font in the ``Debg`` private table (#3008). +- [name] Make NameRecord `__lt__` comparison not fail on Unicode encoding errors (#3006). +- [featureVars] Fixed bug in ``overlayBox`` (#3003, #3005). +- [glyf] Added experimental support for cubic bezier curves in TrueType glyf table, as + outlined in glyf v1 proposal (#2988): + https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1-cubicOutlines.md +- Added new qu2cu module and related qu2cuPen, the reverse of cu2qu for converting + TrueType quadratic splines to cubic bezier curves (#2993). +- [glyf] Added experimental support for reading and writing Variable Composites/Components + as defined in glyf v1 spec proposal (#2958): + https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1-varComposites.md. +- [pens]: Added `addVarComponent` method to pen protocols' base classes, which pens can implement + to handle varcomponents (by default they get decomposed) (#2958). +- [misc.transform] Added DecomposedTransform class which implements an affine transformation + with separate translate, rotation, scale, skew, and transformation-center components (#2598) +- [sbix] Ensure Glyph.referenceGlyphName is set; fixes error after dumping and + re-compiling sbix table with 'dupe' glyphs (#2984). +- [feaLib] Be cleverer when merging chained single substitutions into same lookup + when they are specified using the inline notation (#2150, #2974). +- [instancer] Clamp user-inputted axis ranges to those of fvar (#2959). +- [otBase/subset] Define ``__getstate__`` for BaseTable so that a copied/pickled 'lazy' + object gets its own OTTableReader to read from; incidentally fixes a bug while + subsetting COLRv1 table containing ClipBoxes on python 3.11 (#2965, #2968). +- [sbix] Handle glyphs with "dupe" graphic type on compile correctly (#2963). +- [glyf] ``endPointsOfContours`` field should be unsigned! Kudos to behdad for + spotting one of the oldest bugs in FT. Probably nobody has ever dared to make + glyphs with more than 32767 points... (#2957). +- [feaLib] Fixed handling of ``ignore`` statements with unmarked glyphs to match + makeotf behavior, which assumes the first glyph is marked (#2950). +- Reformatted code with ``black`` and enforce new code style via CI check (#2925). +- [feaLib] Sort name table entries following OT spec prescribed order in the builder (#2927). +- [cu2quPen] Add Cu2QuMultiPen that converts multiple outlines at a time in + interpolation compatible way; its methods take a list of tuples arguments + that would normally be passed to individual segment pens, and at the end it + dispatches the converted outlines to each pen (#2912). +- [reverseContourPen/ttGlyphPen] Add outputImpliedClosingLine option (#2913, #2914, + #2921, #2922, #2995). +- [gvar] Avoid expanding all glyphs unnecessarily upon compile (#2918). +- [scaleUpem] Fixed bug whereby CFF2 vsindex was scaled; it should not (#2893, #2894). +- [designspaceLib] Add DS.getAxisByTag and refactor getAxis (#2891). +- [unicodedata] map Zmth<->math in ot_tag_{to,from}_script (#1737, #2889). +- [woff2] Support encoding/decoding OVERLAP_SIMPLE glyf flags (#2576, #2884). +- [instancer] Update OS/2 class and post.italicAngle when default moved (L4) +- Dropped support for Python 3.7 which reached EOL, fontTools requires 3.8+. +- [instancer] Fixed instantiateFeatureVariations logic when a rule range becomes + default-applicable (#2737, #2880). +- [ttLib] Add main to ttFont and ttCollection that just decompile and re-compile the + input font (#2869). +- [featureVars] Insert 'rvrn' lookup at the beginning of LookupList, to work around bug + in Apple implementation of 'rvrn' feature which the spec says it should be processed + early whereas on macOS 10.15 it follows lookup order (#2140, #2867). +- [instancer/mutator] Remove 'DSIG' table if present. +- [svgPathPen] Don't close path in endPath(), assume open unless closePath() (#2089, #2865). + +4.38.0 (released 2022-10-21) +---------------------------- + +- [varLib.instancer] Added support for L4 instancing, i.e. moving the default value of + an axis while keeping it variable. Thanks Behdad! (#2728, #2861). + It's now also possible to restrict an axis min/max values beyond the current default + value, e.g. a font wght has min=100, def=400, max=900 and you want a partial VF that + only varies between 500 and 700, you can now do that. + You can either specify two min/max values (wght=500:700), and the new default will be + set to either the minimum or maximum, depending on which one is closer to the current + default (e.g. 500 in this case). Or you can specify three values (e.g. wght=500:600:700) + to specify the new default value explicitly. +- [otlLib/featureVars] Set a few Count values so one doesn't need to compile the font + to update them (#2860). +- [varLib.models] Make extrapolation work for 2-master models as well where one master + is at the default location (#2843, #2846). + Add optional extrapolate=False to normalizeLocation() (#2847, #2849). +- [varLib.cff] Fixed sub-optimal packing of CFF2 deltas by no longer rounding them to + integer (#2838). +- [scaleUpem] Calculate numShorts in VarData after scale; handle CFF hintmasks (#2840). + +4.37.4 (released 2022-09-30) +---------------------------- + +- [subset] Keep nameIDs used by CPAL palette entry labels (#2837). +- [varLib] Avoid negative hmtx values when creating font from variable CFF2 font (#2827). +- [instancer] Don't prune stat.ElidedFallbackNameID (#2828). +- [unicodedata] Update Scripts/Blocks to Unicode 15.0 (#2833). + +4.37.3 (released 2022-09-20) +---------------------------- + +- Fix arguments in calls to (glyf) glyph.draw() and drawPoints(), whereby offset wasn't + correctly passed down; this fix also exposed a second bug, where lsb and tsb were not + set (#2824, #2825, adobe-type-tools/afdko#1560). + +4.37.2 (released 2022-09-15) +---------------------------- + +- [subset] Keep CPAL table and don't attempt to prune unused color indices if OT-SVG + table is present even if COLR table was subsetted away; OT-SVG may be referencing the + CPAL table; for now we assume that's the case (#2814, #2815). +- [varLib.instancer] Downgrade GPOS/GSUB version if there are no more FeatureVariations + after instancing (#2812). +- [subset] Added ``--no-lazy`` to optionally load fonts eagerly (mostly to ease + debugging of table lazy loading, no practical effects) (#2807). +- [varLib] Avoid building empty COLR.DeltaSetIndexMap with only identity mappings (#2803). +- [feaLib] Allow multiple value record types (by promoting to the most general format) + within the same PairPos subtable; e.g. this allows variable and non variable kerning + rules to share the same subtable. This also fixes a bug whereby some kerning pairs + would become unreachable while shapiong because of premature subtable splitting (#2772, #2776). +- [feaLib] Speed up ``VarScalar`` by caching models for recurring master locations (#2798). +- [feaLib] Optionally cythonize ``feaLib.lexer``, speeds up parsing FEA a bit (#2799). +- [designspaceLib] Avoid crash when handling unbounded rule conditions (#2797). +- [post] Don't crash if ``post`` legacy format 1 is malformed/improperly used (#2786) +- [gvar] Don't be "lazy" (load all glyph variations up front) when TTFont.lazy=False (#2771). +- [TTFont] Added ``normalizeLocation`` method to normalize a location dict from the + font's defined axes space (also known as "user space") into the normalized (-1..+1) + space. It applies ``avar`` mapping if the font contains an ``avar`` table (#2789). +- [TTVarGlyphSet] Support drawing glyph instances from CFF2 variable glyph set (#2784). +- [fontBuilder] Do not error when building cmap if there are zero code points (#2785). +- [varLib.plot] Added ability to plot a variation model and set of accompaning master + values corresponding to the model's master locations into a pyplot figure (#2767). +- [Snippets] Added ``statShape.py`` script to draw statistical shape of a glyph as an + ellips (requires pycairo) (baecd88). +- [TTVarGlyphSet] implement drawPoints natively, avoiding going through + SegmentToPointPen (#2778). +- [TTVarGlyphSet] Fixed bug whereby drawing a composite glyph multiple times, its + components would shif; needed an extra copy (#2774). + +4.37.1 (released 2022-08-24) +---------------------------- + +- [subset] Fixed regression introduced with v4.37.0 while subsetting the VarStore of + ``HVAR`` and ``VVAR`` tables, whereby an ``AttributeError: subset_varidxes`` was + thrown because an apparently unused import statement (with the side-effect of + dynamically binding that ``subset_varidxes`` method to the VarStore class) had been + accidentally deleted in an unrelated PR (#2679, #2773). +- [pens] Added ``cairoPen`` (#2678). +- [gvar] Read ``gvar`` more lazily by not parsing all of the ``glyf`` table (#2771). +- [ttGlyphSet] Make ``drawPoints(pointPen)`` method work for CFF fonts as well via + adapter pen (#2770). + +4.37.0 (released 2022-08-23) +---------------------------- + +- [varLib.models] Reverted PR #2717 which added support for "narrow tents" in v4.36.0, + as it introduced a regression (#2764, #2765). It will be restored in upcoming release + once we found a solution to the bug. +- [cff.specializer] Fixed issue in charstring generalizer with the ``blend`` operator + (#2750, #1975). +- [varLib.models] Added support for extrapolation (#2757). +- [ttGlyphSet] Ensure the newly added ``_TTVarGlyphSet`` inherits from ``_TTGlyphSet`` + to keep backward compatibility with existing API (#2762). +- [kern] Allow compiling legacy kern tables with more than 64k entries (d21cfdede). +- [visitor] Added new visitor API to traverse tree of objects and dispatch based + on the attribute type: cf. ``fontTools.misc.visitor`` and ``fontTools.ttLib.ttVisitor``. Added ``fontTools.ttLib.scaleUpem`` module that uses the latter to + change a font's units-per-em and scale all the related fields accordingly (#2718, + #2755). + +4.36.0 (released 2022-08-17) +---------------------------- + +- [varLib.models] Use a simpler model that generates narrower "tents" (regions, master + supports) whenever possible: specifically when any two axes that actively "cooperate" + (have masters at non-zero positions for both axes) have a complete set of intermediates. + The simpler algorithm produces fewer overlapping regions and behaves better with + respect to rounding at the peak positions than the generic solver, always matching + intermediate masters exactly, instead of maximally 0.5 units off. This may be useful + when 100% metrics compatibility is desired (#2218, #2717). +- [feaLib] Remove warning when about ``GDEF`` not being built when explicitly not + requested; don't build one unconditonally even when not requested (#2744, also works + around #2747). +- [ttFont] ``TTFont.getGlyphSet`` method now supports selecting a location that + represents an instance of a variable font (supports both user-scale and normalized + axes coordinates via the ``normalized=False`` parameter). Currently this only works + for TrueType-flavored variable fonts (#2738). + +4.35.0 (released 2022-08-15) +---------------------------- + +- [otData/otConverters] Added support for 'biased' PaintSweepGradient start/end angles + to match latest COLRv1 spec (#2743). +- [varLib.instancer] Fixed bug in ``_instantiateFeatureVariations`` when at the same + time pinning one axis and restricting the range of a subsequent axis; the wrong axis + tag was being used in the latter step (as the records' axisIdx was updated in the + preceding step but looked up using the old axes order in the following step) (#2733, + #2734). +- [mtiLib] Pad script tags with space when less than 4 char long (#1727). +- [merge] Use ``'.'`` instead of ``'#'`` in duplicate glyph names (#2742). +- [gvar] Added support for lazily loading glyph variations (#2741). +- [varLib] In ``build_many``, we forgot to pass on ``colr_layer_reuse`` parameter to + the ``build`` method (#2730). +- [svgPathPen] Add a main that prints SVG for input text (6df779fd). +- [cffLib.width] Fixed off-by-one in optimized values; previous code didn't match the + code block above it (2963fa50). +- [varLib.interpolatable] Support reading .designspace and .glyphs files (via optional + ``glyphsLib``). +- Compile some modules with Cython when available and building/installing fonttools + from source: ``varLib.iup`` (35% faster), ``pens.momentsPen`` (makes + ``varLib.interpolatable`` 3x faster). +- [feaLib] Allow features to be built for VF without also building a GDEF table (e.g. + only build GSUB); warn when GDEF would be needed but isn't requested (#2705, 2694). +- [otBase] Fixed ``AttributeError`` when uharfbuzz < 0.23.0 and 'repack' method is + missing (32aa8eaf). Use new ``uharfbuzz.repack_with_tag`` when available (since + uharfbuzz>=0.30.0), enables table-specific optimizations to be performed during + repacking (#2724). +- [statisticsPen] By default report all glyphs (4139d891). Avoid division-by-zero + (52b28f90). +- [feaLib] Added missing required argument to FeatureLibError exception (#2693) +- [varLib.merge] Fixed error during error reporting (#2689). Fixed undefined + ``NotANone`` variable (#2714). + +4.34.4 (released 2022-07-07) +---------------------------- + +- Fixed typo in varLib/merger.py that causes NameError merging COLR glyphs + containing more than 255 layers (#2685). + +4.34.3 (released 2022-07-07) +---------------------------- + +- [designspaceLib] Don't make up bad PS names when no STAT data (#2684) + +4.34.2 (released 2022-07-06) +---------------------------- + +- [varStore/subset] fixed KeyError exception to do with NO_VARIATION_INDEX while + subsetting varidxes in GPOS/GDEF (a08140d). + +4.34.1 (released 2022-07-06) +---------------------------- + +- [instancer] When optimizing HVAR/VVAR VarStore, use_NO_VARIATION_INDEX=False to avoid + including NO_VARIATION_INDEX in AdvWidthMap, RsbMap, LsbMap mappings, which would + push the VarIdx width to maximum (4bytes), which is not desirable. This also fixes + a hard crash when attempting to subset a varfont after it had been partially instanced + with use_NO_VARIATION_INDEX=True. + +4.34.0 (released 2022-07-06) +---------------------------- + +- [instancer] Set RIBBI bits in head and OS/2 table when cutting instances and the + subfamily nameID=2 contains strings like 'Italic' or 'Bold' (#2673). +- [otTraverse] Addded module containing methods for traversing trees of otData tables + (#2660). +- [otTables] Made DeltaSetIndexMap TTX dump less verbose by omitting no-op entries + (#2660). +- [colorLib.builder] Added option to disable PaintColrLayers's reuse of layers from + LayerList (#2660). +- [varLib] Added support for merging multiple master COLRv1 tables into a variable + COLR table (#2660, #2328). Base color glyphs of same name in different masters must have + identical paint graph structure (incl. number of layers, palette indices, number + of color line stops, corresponding paint formats at each level of the graph), + but can differ in the variable fields (e.g. PaintSolid.Alpha). PaintVar* tables + are produced when this happens and a VarStore/DeltaSetIndexMap is added to the + variable COLR table. It is possible for non-default masters to be 'sparse', i.e. + omit some of the color glyphs present in the default master. +- [feaLib] Let the Parser set nameIDs 1 through 6 that were previously reserved (#2675). +- [varLib.varStore] Support NO_VARIATION_INDEX in optimizer and instancer. +- [feaLib] Show all missing glyphs at once at end of parsing (#2665). +- [varLib.iup] Rewrite force-set conditions and limit DP loopback length (#2651). + For Noto Sans, IUP time drops from 23s down to 9s, with only a slight size increase + in the final font. This basically turns the algorithm from O(n^3) into O(n). +- [featureVars] Report about missing glyphs in substitution rules (#2654). +- [mutator/instancer] Added CLI flag to --no-recalc-timestamp (#2649). +- [SVG] Allow individual SVG documents in SVG OT table to be compressed on uncompressed, + and remember that when roundtripping to/from ttx. The SVG.docList is now a list + of SVGDocument namedtuple-like dataclass containing an extra ``compressed`` field, + and no longer a bare 3-tuple (#2645). +- [designspaceLib] Check for descriptor types with hasattr() to allow custom classes + that don't inherit the default descriptors (#2634). +- [subset] Enable sharing across subtables of extension lookups for harfbuzz packing + (#2626). Updated how table packing falls back to fontTools from harfbuzz (#2668). +- [subset] Updated default feature tags following current Harfbuzz (#2637). +- [svgLib] Fixed regex for real number to support e.g. 1e-4 in addition to 1.0e-4. + Support parsing negative rx, ry on arc commands (#2596, #2611). +- [subset] Fixed subsetting SinglePosFormat2 when ValueFormat=0 (#2603). + +4.33.3 (released 2022-04-26) +---------------------------- + +- [designspaceLib] Fixed typo in ``deepcopyExceptFonts`` method, preventing font + references to be transferred (#2600). Fixed another typo in the name of ``Range`` + dataclass's ``__post_init__`` magic method (#2597). + +4.33.2 (released 2022-04-22) +---------------------------- + +- [otBase] Make logging less verbose when harfbuzz fails to serialize. Do not exit + at the first failure but continue attempting to fix offset overflow error using + the pure-python serializer even when the ``USE_HARFBUZZ_REPACKER`` option was + explicitly set to ``True``. This is normal with fonts with relatively large + tables, at least until hb.repack implements proper table splitting. + +4.33.1 (released 2022-04-22) +---------------------------- + +- [otlLib] Put back the ``FONTTOOLS_GPOS_COMPACT_MODE`` environment variable to fix + regression in ufo2ft (and thus fontmake) introduced with v4.33.0 (#2592, #2593). + This is deprecated and will be removed one ufo2ft gets updated to use the new + config setup. + +4.33.0 (released 2022-04-21) +---------------------------- + +- [OS/2 / merge] Automatically recalculate ``OS/2.xAvgCharWidth`` after merging + fonts with ``fontTools.merge`` (#2591, #2538). +- [misc/config] Added ``fontTools.misc.configTools`` module, a generic configuration + system (#2416, #2439). + Added ``fontTools.config`` module, a fontTools-specific configuration + system using ``configTools`` above. + Attached a ``Config`` object to ``TTFont``. +- [otlLib] Replaced environment variable for GPOS compression level with an + equivalent option using the new config system. +- [designspaceLib] Incremented format version to 5.0 (#2436). + Added discrete axes, variable fonts, STAT information, either design- or + user-space location on instances. + Added ``fontTools.designspaceLib.split`` module to split a designspace + into sub-spaces that interpolate and that represent the variable fonts + listed in the document. + Made instance names optional and allow computing them from STAT data instead. + Added ``fontTools.designspaceLib.statNames`` module. + Allow instances to have the same location as a previously defined STAT label. + Deprecated some attributes: + ``SourceDescriptor``: ``copyLib``, ``copyInfo``, ``copyGroups``, ``copyFeatures``. + ``InstanceDescriptor``: ``kerning``, ``info``; ``glyphs``: use rules or sparse + sources. + For both, ``location``: use the more explicit designLocation. + Note: all are soft deprecations and existing code should keep working. + Updated documentation for Python methods and the XML format. +- [varLib] Added ``build_many`` to build several variable fonts from a single + designspace document (#2436). + Added ``fontTools.varLib.stat`` module to build STAT tables from a designspace + document. +- [otBase] Try to use the Harfbuzz Repacker for packing GSUB/GPOS tables when + ``uharfbuzz`` python bindings are available (#2552). Disable it by setting the + "fontTools.ttLib.tables.otBase:USE_HARFBUZZ_REPACKER" config option to ``False``. + If the option is set explicitly to ``True`` but ``uharfbuzz`` can't be imported + or fails to serialize for any reasons, an error will be raised (ImportError or + uharfbuzz errors). +- [CFF/T2] Ensure that ``pen.closePath()`` gets called for CFF2 charstrings (#2577). + Handle implicit CFF2 closePath within ``T2OutlineExtractor`` (#2580). + +4.32.0 (released 2022-04-08) +---------------------------- + +- [otlLib] Disable GPOS7 optimization to work around bug in Apple CoreText. + Always force Chaining GPOS8 for now (#2540). +- [glifLib] Added ``outputImpliedClosingLine=False`` parameter to ``Glyph.draw()``, + to control behaviour of ``PointToSegmentPen`` (6b4e2e7). +- [varLib.interpolatable] Check for wrong contour starting point (#2571). +- [cffLib] Remove leftover ``GlobalState`` class and fix calls to ``TopDictIndex()`` + (#2569, #2570). +- [instancer] Clear ``AxisValueArray`` if it is empty after instantiating (#2563). + +4.31.2 (released 2022-03-22) +---------------------------- + +- [varLib] fix instantiation of GPOS SinglePos values (#2555). + +4.31.1 (released 2022-03-18) +---------------------------- + +- [subset] fix subsetting OT-SVG when glyph id attribute is on the root ```` + element (#2553). + +4.31.0 (released 2022-03-18) +---------------------------- + +- [ttCollection] Fixed 'ResourceWarning: unclosed file' warning (#2549). +- [varLib.merger] Handle merging SinglePos with valueformat=0 (#2550). +- [ttFont] Update glyf's glyphOrder when calling TTFont.setGlyphOrder() (#2544). +- [ttFont] Added ``ensureDecompiled`` method to load all tables irrespective + of the ``lazy`` attribute (#2551). +- [otBase] Added ``iterSubTable`` method to iterate over BaseTable's children of + type BaseTable; useful for traversing a tree of otTables (#2551). + +4.30.0 (released 2022-03-10) +---------------------------- + +- [varLib] Added debug logger showing the glyph name for which ``gvar`` is built (#2542). +- [varLib.errors] Fixed undefined names in ``FoundANone`` and ``UnsupportedFormat`` + exceptions (ac4d5611). +- [otlLib.builder] Added ``windowsNames`` and ``macNames`` (bool) parameters to the + ``buildStatTabe`` function, so that one can select whether to only add one or both + of the two sets (#2528). +- [t1Lib] Added the ability to recreate PostScript stream (#2504). +- [name] Added ``getFirstDebugName``, ``getBest{Family,SubFamily,Full}Name`` methods (#2526). + +4.29.1 (released 2022-02-01) +---------------------------- + +- [colorLib] Fixed rounding issue with radial gradient's start/end circles inside + one another (#2521). +- [freetypePen] Handle rotate/skew transform when auto-computing width/height of the + buffer; raise PenError wen missing moveTo (#2517) + +4.29.0 (released 2022-01-24) +---------------------------- + +- [ufoLib] Fixed illegal characters and expanded reserved filenames (#2506). +- [COLRv1] Don't emit useless PaintColrLayers of lenght=1 in LayerListBuilder (#2513). +- [ttx] Removed legacy ``waitForKeyPress`` method on Windows (#2509). +- [pens] Added FreeTypePen that uses ``freetype-py`` and the pen protocol for + rasterizating outline paths (#2494). +- [unicodedata] Updated the script direction list to Unicode 14.0 (#2484). + Bumped unicodedata2 dependency to 14.0 (#2499). +- [psLib] Fixed type of ``fontName`` in ``suckfont`` (#2496). + +4.28.5 (released 2021-12-19) +---------------------------- + +- [svgPathPen] Continuation of #2471: make sure all occurrences of ``str()`` are now + replaced with user-defined ``ntos`` callable. +- [merge] Refactored code into submodules, plus several bugfixes and improvements: + fixed duplicate-glyph-resolution GSUB-lookup generation code; use tolerance in glyph + comparison for empty glyph's width; ignore space of default ignorable glyphs; + downgrade duplicates-resolution missing-GSUB from assert to warn; added --drop-tables + option (#2473, #2475, #2476). + +4.28.4 (released 2021-12-15) +---------------------------- + +- [merge] Merge GDEF marksets in Lookups properly (#2474). +- [feaLib] Have ``fontTools feaLib`` script exit with error code when build fails (#2459) +- [svgPathPen] Added ``ntos`` option to customize number formatting (e.g. rounding) (#2471). +- [subset] Speed up subsetting of large CFF fonts (#2467). +- [otTables] Speculatively promote lookups to extension to speed up compilation. If the + offset to lookup N is too big to fit in a ushort, the offset to lookup N+1 is going to + be too big as well, so we promote to extension all lookups from lookup N onwards (#2465). + +4.28.3 (released 2021-12-03) +---------------------------- + +- [subset] Fixed bug while subsetting ``COLR`` table, whereby incomplete layer records + pointing to missing glyphs were being retained leading to ``struct.error`` upon + compiling. Make it so that ``glyf`` glyph closure, which follows the ``COLR`` glyph + closure, does not influence the ``COLR`` table subsetting (#2461, #2462). +- [docs] Fully document the ``cmap`` and ``glyf`` tables (#2454, #2457). +- [colorLib.unbuilder] Fixed CLI by deleting no longer existing parameter (180bb1867). + +4.28.2 (released 2021-11-22) +---------------------------- + +- [otlLib] Remove duplicates when building coverage (#2433). +- [docs] Add interrogate configuration (#2443). +- [docs] Remove comment about missing “start” optional argument to ``calcChecksum`` (#2448). +- [cu2qu/cli] Adapt to the latest ufoLib2. +- [subset] Support subsetting SVG table and remove it from the list of drop by default tables (#534). +- [subset] add ``--pretty-svg`` option to pretty print SVG table contents (#2452). +- [merge] Support merging ``CFF`` tables (CID-keyed ``CFF`` is still not supported) (#2447). +- [merge] Support ``--output-file`` (#2447). +- [docs] Split table docs into individual pages (#2444). +- [feaLib] Forbid empty classes (#2446). +- [docs] Improve documentation for ``fontTools.ttLib.ttFont`` (#2442). + +4.28.1 (released 2021-11-08) +---------------------------- + +- [subset] Fixed AttributeError while traversing a color glyph's Paint graph when there is no + LayerList, which is optional (#2441). + +4.28.0 (released 2021-11-05) +---------------------------- + +- Dropped support for EOL Python 3.6, require Python 3.7 (#2417). +- [ufoLib/glifLib] Make filename-clash checks faster by using a set instead of a list (#2422). +- [subset] Don't crash if optional ClipList and LayerList are ``None`` (empty) (#2424, 2439). +- [OT-SVG] Removed support for old deprecated version 1 and embedded color palettes, + which were never officially part of the OpenType SVG spec. Upon compile, reuse offsets + to SVG documents that are identical (#2430). +- [feaLib] Added support for Variable Feature File syntax. This is experimental and subject + to change until it is finalized in the Adobe FEA spec (#2432). +- [unicodedata] Update Scripts/ScriptExtensions/Blocks to UnicodeData 14.0 (#2437). + +4.27.1 (released 2021-09-23) +---------------------------- + +- [otlLib] Fixed error when chained contextual lookup builder overflows (#2404, #2411). +- [bezierTools] Fixed two floating-point bugs: one when computing `t` for a point + lying on an almost horizontal/vertical line; another when computing the intersection + point between a curve and a line (#2413). + +4.27.0 (released 2021-09-14) +---------------------------- + +- [ttLib/otTables] Cleaned up virtual GID handling: allow virtual GIDs in ``Coverage`` + and ``ClassDef`` readers; removed unused ``allowVID`` argument from ``TTFont`` + constructor, and ``requireReal`` argument in ``TTFont.getGlyphID`` method. + Make ``TTFont.setGlyphOrder`` clear reverse glyphOrder map, and assume ``glyphOrder`` + internal attribute is never modified outside setGlyphOrder; added ``TTFont.getGlyphNameMany`` + and ``getGlyphIDMany`` (#1536, #1654, #2334, #2398). +- [py23] Dropped internal use of ``fontTools.py23`` module to fix deprecation warnings + in client code that imports from fontTools (#2234, #2399, #2400). +- [subset] Fix subsetting COLRv1 clip boxes when font is loaded lazily (#2408). + +4.26.2 (released 2021-08-09) +---------------------------- + +- [otTables] Added missing ``CompositeMode.PLUS`` operator (#2390). + +4.26.1 (released 2021-08-03) +---------------------------- + +- [transform] Added ``transformVector`` and ``transformVectors`` methods to the + ``Transform`` class. Similar to ``transformPoint`` but ignore the translation + part (#2386). + +4.26.0 (released 2021-08-03) +---------------------------- + +- [xmlWriter] Default to ``"\n"`` for ``newlinestr`` instead of platform-specific + ``os.linesep`` (#2384). +- [otData] Define COLRv1 ClipList and ClipBox (#2379). +- [removeOverlaps/instancer] Added --ignore-overlap-errors option to work around + Skia PathOps.Simplify bug (#2382, #2363, google/fonts#3365). +- NOTE: This will be the last version to support Python 3.6. FontTools will require + Python 3.7 or above from the next release (#2350) + +4.25.2 (released 2021-07-26) +---------------------------- + +- [COLRv1] Various changes to sync with the latest CORLv1 draft spec. In particular: + define COLR.VarIndexMap, remove/inline ColorIndex struct, add VarIndexBase to ``PaintVar*`` tables (#2372); + add reduced-precicion specialized transform Paints; + define Angle as fraction of half circle encoded as F2Dot14; + use FWORD (int16) for all Paint center coordinates; + change PaintTransform to have an offset to Affine2x3; +- [ttLib] when importing XML, only set sfntVersion if the font has no reader and is empty (#2376) + +4.25.1 (released 2021-07-16) +---------------------------- + +- [ttGlyphPen] Fixed bug in ``TTGlyphPointPen``, whereby open contours (i.e. starting + with segmentType "move") would throw ``NotImplementedError``. They are now treated + as if they are closed, like with the ``TTGlyphPen`` (#2364, #2366). + +4.25.0 (released 2021-07-05) +---------------------------- + +- [tfmLib] Added new library for parsing TeX Font Metric (TFM) files (#2354). +- [TupleVariation] Make shared tuples order deterministic on python < 3.7 where + Counter (subclass of dict) doesn't remember insertion order (#2351, #2353). +- [otData] Renamed COLRv1 structs to remove 'v1' suffix and match the updated draft + spec: 'LayerV1List' -> 'LayerList', 'BaseGlyphV1List' -> 'BaseGlyphList', + 'BaseGlyphV1Record' -> 'BaseGlyphPaintRecord' (#2346). + Added 8 new ``PaintScale*`` tables: with/without centers, uniform vs non-uniform. + Added ``*AroundCenter`` variants to ``PaintRotate`` and ``PaintSkew``: the default + versions no longer have centerX/Y, but default to origin. + ``PaintRotate``, ``PaintSkew`` and ``PaintComposite`` formats were re-numbered. + NOTE: these are breaking changes; clients using the experimental COLRv1 API will + have to be updated (#2348). +- [pointPens] Allow ``GuessSmoothPointPen`` to accept a tolerance. Fixed call to + ``math.atan2`` with x/y parameters inverted. Sync the code with fontPens (#2344). +- [post] Fixed parsing ``post`` table format 2.0 when it contains extra garbage + at the end of the stringData array (#2314). +- [subset] drop empty features unless 'size' with FeatureParams table (#2324). +- [otlLib] Added ``otlLib.optimize`` module; added GPOS compaction algorithm. + The compaction can be run on existing fonts with ``fonttools otlLib.optimize`` + or using the snippet ``compact_gpos.py``. There's experimental support for + compacting fonts at compilation time using an environment variable, but that + might be removed later (#2326). + +4.24.4 (released 2021-05-25) +---------------------------- + +- [subset/instancer] Fixed ``AttributeError`` when instantiating a VF that + contains GPOS ValueRecords with ``Device`` tables but without the respective + non-Device values (e.g. ``XAdvDevice`` without ``XAdvance``). When not + explicitly set, the latter are assumed to be 0 (#2323). + +4.24.3 (released 2021-05-20) +---------------------------- + +- [otTables] Fixed ``AttributeError`` in methods that split LigatureSubst, + MultipleSubst and AlternateSubst subtables when an offset overflow occurs. + The ``Format`` attribute was removed in v4.22.0 (#2319). + +4.24.2 (released 2021-05-20) +---------------------------- + +- [ttGlyphPen] Fixed typing annotation of TTGlyphPen glyphSet parameter (#2315). +- Fixed two instances of DeprecationWarning: invalid escape sequence (#2311). + +4.24.1 (released 2021-05-20) +---------------------------- + +- [subset] Fixed AttributeError when SinglePos subtable has None Value (ValueFormat 0) + (#2312, #2313). + +4.24.0 (released 2021-05-17) +---------------------------- + +- [pens] Add ``ttGlyphPen.TTGlyphPointPen`` similar to ``TTGlyphPen`` (#2205). + +4.23.1 (released 2021-05-14) +---------------------------- + +- [subset] Fix ``KeyError`` after subsetting ``COLR`` table that initially contains + both v0 and v1 color glyphs when the subset only requested v1 glyphs; we were + not pruning the v0 portion of the table (#2308). +- [colorLib] Set ``LayerV1List`` attribute to ``None`` when empty, it's optional + in CORLv1 (#2308). + +4.23.0 (released 2021-05-13) +---------------------------- + +- [designspaceLib] Allow to use ``\\UNC`` absolute paths on Windows (#2299, #2306). +- [varLib.merger] Fixed bug where ``VarLibMergeError`` was raised with incorrect + parameters (#2300). +- [feaLib] Allow substituting a glyph class with ``NULL`` to delete multiple glyphs + (#2303). +- [glyf] Fixed ``NameError`` exception in ``getPhantomPoints`` (#2295, #2305). +- [removeOverlaps] Retry pathops.simplify after rounding path coordinates to integers + if it fails the first time using floats, to work around a rare and hard to debug + Skia bug (#2288). +- [varLib] Added support for building, reading, writing and optimizing 32-bit + ``ItemVariationStore`` as used in COLRv1 table (#2285). +- [otBase/otConverters] Add array readers/writers for int types (#2285). +- [feaLib] Allow more than one lookahead glyph/class in contextual positioning with + "value at end" (#2293, #2294). +- [COLRv1] Default varIdx should be 0xFFFFFFFF (#2297, #2298). +- [pens] Make RecordingPointPen actually pass on identifiers; replace asserts with + explicit ``PenError`` exception (#2284). +- [mutator] Round lsb for CF2 fonts as well (#2286). + +4.22.1 (released 2021-04-26) +---------------------------- + +- [feaLib] Skip references to named lookups if the lookup block definition + is empty, similarly to makeotf. This also fixes an ``AttributeError`` while + generating ``aalt`` feature (#2276, #2277). +- [subset] Fixed bug with ``--no-hinting`` implementation for Device tables (#2272, + #2275). The previous code was alwyas dropping Device tables if no-hinting was + requested, but some Device tables (DeltaFormat=0x8000) are also used to encode + variation indices and need to be retained. +- [otBase] Fixed bug in getting the ValueRecordSize when decompiling ``MVAR`` + table with ``lazy=True`` (#2273, #2274). +- [varLib/glyf/gvar] Optimized and simplified ``GlyphCoordinates`` and + ``TupleVariation`` classes, use ``bytearray`` where possible, refactored + phantom-points calculations. We measured about 30% speedup in total time + of loading master ttfs, building gvar, and saving (#2261, #2266). +- [subset] Fixed ``AssertionError`` while pruning unused CPAL palettes when + ``0xFFFF`` is present (#2257, #2259). + +4.22.0 (released 2021-04-01) +---------------------------- + +- [ttLib] Remove .Format from Coverage, ClassDef, SingleSubst, LigatureSubst, + AlternateSubst, MultipleSubst (#2238). + ATTENTION: This will change your TTX dumps! +- [misc.arrayTools] move Vector to its own submodule, and rewrite as a tuple + subclass (#2201). +- [docs] Added a terminology section for varLib (#2209). +- [varLib] Move rounding to VariationModel, to avoid error accumulation from + multiple deltas (#2214) +- [varLib] Explain merge errors in more human-friendly terms (#2223, #2226) +- [otlLib] Correct some documentation (#2225) +- [varLib/otlLib] Allow merging into VariationFont without first saving GPOS + PairPos2 (#2229) +- [subset] Improve PairPosFormat2 subsetting (#2221) +- [ttLib] TTFont.save: create file on disk as late as possible (#2253) +- [cffLib] Add missing CFF2 dict operators LanguageGroup and ExpansionFactor + (#2249) + ATTENTION: This will change your TTX dumps! + +4.21.1 (released 2021-02-26) +---------------------------- + +- [pens] Reverted breaking change that turned ``AbstractPen`` and ``AbstractPointPen`` + into abstract base classes (#2164, #2198). + +4.21.0 (released 2021-02-26) +---------------------------- + +- [feaLib] Indent anchor statements in ``asFea()`` to make them more legible and + diff-able (#2193). +- [pens] Turn ``AbstractPen`` and ``AbstractPointPen`` into abstract base classes + (#2164). +- [feaLib] Added support for parsing and building ``STAT`` table from AFDKO feature + files (#2039). +- [instancer] Added option to update name table of generated instance using ``STAT`` + table's axis values (#2189). +- [bezierTools] Added functions to compute bezier point-at-time, as well as line-line, + curve-line and curve-curve intersections (#2192). + +4.20.0 (released 2021-02-15) +---------------------------- + +- [COLRv1] Added ``unbuildColrV1`` to deconstruct COLRv1 otTables to raw json-able + data structure; it does the reverse of ``buildColrV1`` (#2171). +- [feaLib] Allow ``sub X by NULL`` sequence to delete a glyph (#2170). +- [arrayTools] Fixed ``Vector`` division (#2173). +- [COLRv1] Define new ``PaintSweepGradient`` (#2172). +- [otTables] Moved ``Paint.Format`` enum class outside of ``Paint`` class definition, + now named ``PaintFormat``. It was clashing with paint instance ``Format`` attribute + and thus was breaking lazy load of COLR table which relies on magic ``__getattr__`` + (#2175). +- [COLRv1] Replace hand-coded builder functions with otData-driven dynamic + implementation (#2181). +- [COLRv1] Define additional static (non-variable) Paint formats (#2181). +- [subset] Added support for subsetting COLR v1 and CPAL tables (#2174, #2177). +- [fontBuilder] Allow ``setupFvar`` to optionally take ``designspaceLib.AxisDescriptor`` + objects. Added new ``setupAvar`` method. Support localised names for axes and + named instances (#2185). + +4.19.1 (released 2021-01-28) +---------------------------- + +- [woff2] An initial off-curve point with an overlap flag now stays an off-curve + point after compression. + +4.19.0 (released 2021-01-25) +---------------------------- + +- [codecs] Handle ``errors`` parameter different from 'strict' for the custom + extended mac encodings (#2137, #2132). +- [featureVars] Raise better error message when a script is missing the required + default language system (#2154). +- [COLRv1] Avoid abrupt change caused by rounding ``PaintRadialGradient.c0`` when + the start circle almost touches the end circle's perimeter (#2148). +- [COLRv1] Support building unlimited lists of paints as 255-ary trees of + ``PaintColrLayers`` tables (#2153). +- [subset] Prune redundant format-12 cmap subtables when all non-BMP characters + are dropped (#2146). +- [basePen] Raise ``MissingComponentError`` instead of bare ``KeyError`` when a + referenced component is missing (#2145). + +4.18.2 (released 2020-12-16) +---------------------------- + +- [COLRv1] Implemented ``PaintTranslate`` paint format (#2129). +- [varLib.cff] Fixed unbound local variable error (#1787). +- [otlLib] Don't crash when creating OpenType class definitions if some glyphs + occur more than once (#2125). + +4.18.1 (released 2020-12-09) +---------------------------- + +- [colorLib] Speed optimization for ``LayerV1ListBuilder`` (#2119). +- [mutator] Fixed missing tab in ``interpolate_cff2_metrics`` (0957dc7a). + +4.18.0 (released 2020-12-04) +---------------------------- + +- [COLRv1] Update to latest draft: added ``PaintRotate`` and ``PaintSkew`` (#2118). +- [woff2] Support new ``brotlicffi`` bindings for PyPy (#2117). +- [glifLib] Added ``expectContentsFile`` parameter to ``GlyphSet``, for use when + reading existing UFOs, to comply with the specification stating that a + ``contents.plist`` file must exist in a glyph set (#2114). +- [subset] Allow ``LangSys`` tags in ``--layout-scripts`` option (#2112). For example: + ``--layout-scripts=arab.dflt,arab.URD,latn``; this will keep ``DefaultLangSys`` + and ``URD`` language for ``arab`` script, and all languages for ``latn`` script. +- [varLib.interpolatable] Allow UFOs to be checked; report open paths, non existant + glyphs; add a ``--json`` option to produce a machine-readable list of + incompatibilities +- [pens] Added ``QuartzPen`` to create ``CGPath`` from glyph outlines on macOS. + Requires pyobjc (#2107). +- [feaLib] You can export ``FONTTOOLS_LOOKUP_DEBUGGING=1`` to enable feature file + debugging info stored in ``Debg`` table (#2106). +- [otlLib] Build more efficient format 1 and format 2 contextual lookups whenever + possible (#2101). + +4.17.1 (released 2020-11-16) +---------------------------- + +- [colorLib] Fixed regression in 4.17.0 when building COLR v0 table; when color + layers are stored in UFO lib plist, we can't distinguish tuples from lists so + we need to accept either types (e5439eb9, googlefonts/ufo2ft/issues#426). + +4.17.0 (released 2020-11-12) +---------------------------- + +- [colorLib/otData] Updated to latest draft ``COLR`` v1 spec (#2092). +- [svgLib] Fixed parsing error when arc commands' boolean flags are not separated + by space or comma (#2094). +- [varLib] Interpret empty non-default glyphs as 'missing', if the default glyph is + not empty (#2082). +- [feaLib.builder] Only stash lookup location for ``Debg`` if ``Builder.buildLookups_`` + has cooperated (#2065, #2067). +- [varLib] Fixed bug in VarStore optimizer (#2073, #2083). +- [varLib] Add designspace lib key for custom feavar feature tag (#2080). +- Add HashPointPen adapted from psautohint. With this pen, a hash value of a glyph + can be computed, which can later be used to detect glyph changes (#2005). + +4.16.1 (released 2020-10-05) +---------------------------- + +- [varLib.instancer] Fixed ``TypeError`` exception when instantiating a VF with + a GSUB table 1.1 in which ``FeatureVariations`` attribute is present but set to + ``None`` -- indicating that optional ``FeatureVariations`` is missing (#2077). +- [glifLib] Make ``x`` and ``y`` attributes of the ``point`` element required + even when validation is turned off, and raise a meaningful ``GlifLibError`` + message when that happens (#2075). + +4.16.0 (released 2020-09-30) +---------------------------- + +- [removeOverlaps] Added new module and ``removeOverlaps`` function that merges + overlapping contours and components in TrueType glyphs. It requires the + `skia-pathops `__ module. + Note that removing overlaps invalidates the TrueType hinting (#2068). +- [varLib.instancer] Added ``--remove-overlaps`` command-line option. + The ``overlap`` option in ``instantiateVariableFont`` now takes an ``OverlapMode`` + enum: 0: KEEP_AND_DONT_SET_FLAGS, 1: KEEP_AND_SET_FLAGS (default), and 2: REMOVE. + The latter is equivalent to calling ``removeOverlaps`` on the generated static + instance. The option continues to accept ``bool`` value for backward compatibility. + + +4.15.0 (released 2020-09-21) +---------------------------- + +- [plistlib] Added typing annotations to plistlib module. Set up mypy static + typechecker to run automatically on CI (#2061). +- [ttLib] Implement private ``Debg`` table, a reverse-DNS namespaced JSON dict. +- [feaLib] Optionally add an entry into the ``Debg`` table with the original + lookup name (if any), feature name / script / language combination (if any), + and original source filename and line location. Annotate the ttx output for + a lookup with the information from the Debg table (#2052). +- [sfnt] Disabled checksum checking by default in ``SFNTReader`` (#2058). +- [Docs] Document ``mtiLib`` module (#2027). +- [varLib.interpolatable] Added checks for contour node count and operation type + of each node (#2054). +- [ttLib] Added API to register custom table packer/unpacker classes (#2055). + +4.14.0 (released 2020-08-19) +---------------------------- + +- [feaLib] Allow anonymous classes in LookupFlags definitions (#2037). +- [Docs] Better document DesignSpace rules processing order (#2041). +- [ttLib] Fixed 21-year old bug in ``maxp.maxComponentDepth`` calculation (#2044, + #2045). +- [varLib.models] Fixed misspelled argument name in CLI entry point (81d0042a). +- [subset] When subsetting GSUB v1.1, fixed TypeError by checking whether the + optional FeatureVariations table is present (e63ecc5b). +- [Snippets] Added snippet to show how to decompose glyphs in a TTF (#2030). +- [otlLib] Generate GSUB type 5 and GPOS type 7 contextual lookups where appropriate + (#2016). + +4.13.0 (released 2020-07-10) +---------------------------- + +- [feaLib/otlLib] Moved lookup subtable builders from feaLib to otlLib; refactored + some common code (#2004, #2007). +- [docs] Document otlLib module (#2009). +- [glifLib] Fixed bug with some UFO .glif filenames clashing on case-insensitive + filesystems (#2001, #2002). +- [colorLib] Updated COLRv1 implementation following changes in the draft spec: + (#2008, googlefonts/colr-gradients-spec#24). + +4.12.1 (released 2020-06-16) +---------------------------- + +- [_n_a_m_e] Fixed error in ``addMultilingualName`` with one-character names. + Only attempt to recovered malformed UTF-16 data from a ``bytes`` string, + not from unicode ``str`` (#1997, #1998). + +4.12.0 (released 2020-06-09) +---------------------------- + +- [otlLib/varLib] Ensure that the ``AxisNameID`` in the ``STAT`` and ``fvar`` + tables is grater than 255 as per OpenType spec (#1985, #1986). +- [docs] Document more modules in ``fontTools.misc`` package: ``filenames``, + ``fixedTools``, ``intTools``, ``loggingTools``, ``macCreatorType``, ``macRes``, + ``plistlib`` (#1981). +- [OS/2] Don't calculate whole sets of unicode codepoints, use faster and more memory + efficient ranges and bisect lookups (#1984). +- [voltLib] Support writing back abstract syntax tree as VOLT data (#1983). +- [voltLib] Accept DO_NOT_TOUCH_CMAP keyword (#1987). +- [subset/merge] Fixed a namespace clash involving a private helper class (#1955). + +4.11.0 (released 2020-05-28) +---------------------------- + +- [feaLib] Introduced ``includeDir`` parameter on Parser and IncludingLexer to + explicitly specify the directory to search when ``include()`` statements are + encountered (#1973). +- [ufoLib] Silently delete duplicate glyphs within the same kerning group when reading + groups (#1970). +- [ttLib] Set version of COLR table when decompiling COLRv1 (commit 9d8a7e2). + +4.10.2 (released 2020-05-20) +---------------------------- + +- [sfnt] Fixed ``NameError: SimpleNamespace`` while reading TTC header. The regression + was introduced with 4.10.1 after removing ``py23`` star import. + +4.10.1 (released 2020-05-19) +---------------------------- + +- [sfnt] Make ``SFNTReader`` pickleable even when TTFont is loaded with lazy=True + option and thus keeps a reference to an external file (#1962, #1967). +- [feaLib.ast] Restore backward compatibility (broken in 4.10 with #1905) for + ``ChainContextPosStatement`` and ``ChainContextSubstStatement`` classes. + Make them accept either list of lookups or list of lists of lookups (#1961). +- [docs] Document some modules in ``fontTools.misc`` package: ``arrayTools``, + ``bezierTools`` ``cliTools`` and ``eexec`` (#1956). +- [ttLib._n_a_m_e] Fixed ``findMultilingualName()`` when name record's ``string`` is + encoded as bytes sequence (#1963). + +4.10.0 (released 2020-05-15) +---------------------------- + +- [varLib] Allow feature variations to be active across the entire space (#1957). +- [ufoLib] Added support for ``formatVersionMinor`` in UFO's ``fontinfo.plist`` and for + ``formatMinor`` attribute in GLIF file as discussed in unified-font-object/ufo-spec#78. + No changes in reading or writing UFOs until an upcoming (non-0) minor update of the + UFO specification is published (#1786). +- [merge] Fixed merging fonts with different versions of ``OS/2`` table (#1865, #1952). +- [subset] Fixed ``AttributeError`` while subsetting ``ContextSubst`` and ``ContextPos`` + Format 3 subtable (#1879, #1944). +- [ttLib.table._m_e_t_a] if data happens to be ascii, emit comment in TTX (#1938). +- [feaLib] Support multiple lookups per glyph position (#1905). +- [psCharStrings] Use inheritance to avoid repeated code in initializer (#1932). +- [Doc] Improved documentation for the following modules: ``afmLib`` (#1933), ``agl`` + (#1934), ``cffLib`` (#1935), ``cu2qu`` (#1937), ``encodings`` (#1940), ``feaLib`` + (#1941), ``merge`` (#1949). +- [Doc] Split off developer-centric info to new page, making front page of docs more + user-focused. List all utilities and sub-modules with brief descriptions. + Make README more concise and focused (#1914). +- [otlLib] Add function to build STAT table from high-level description (#1926). +- [ttLib._n_a_m_e] Add ``findMultilingualName()`` method (#1921). +- [unicodedata] Update ``RTL_SCRIPTS`` for Unicode 13.0 (#1925). +- [gvar] Sort ``gvar`` XML output by glyph name, not glyph order (#1907, #1908). +- [Doc] Added help options to ``fonttools`` command line tool (#1913, #1920). + Ensure all fonttools CLI tools have help documentation (#1948). +- [ufoLib] Only write fontinfo.plist when there actually is content (#1911). + +4.9.0 (released 2020-04-29) +--------------------------- + +- [subset] Fixed subsetting of FeatureVariations table. The subsetter no longer drops + FeatureVariationRecords that have empty substitutions as that will keep the search + going and thus change the logic. It will only drop empty records that occur at the + end of the FeatureVariationRecords array (#1881). +- [subset] Remove FeatureVariations table and downgrade GSUB/GPOS to version 0x10000 + when FeatureVariations contain no FeatureVariationRecords after subsetting (#1903). +- [agl] Add support for legacy Adobe Glyph List of glyph names in ``fontTools.agl`` + (#1895). +- [feaLib] Ignore superfluous script statements (#1883). +- [feaLib] Hide traceback by default on ``fonttools feaLib`` command line. + Use ``--traceback`` option to show (#1898). +- [feaLib] Check lookup index in chaining sub/pos lookups and print better error + message (#1896, #1897). +- [feaLib] Fix building chained alt substitutions (#1902). +- [Doc] Included all fontTools modules in the sphinx-generated documentation, and + published it to ReadTheDocs for continuous documentation of the fontTools project + (#1333). Check it out at https://fonttools.readthedocs.io/. Thanks to Chris Simpkins! +- [transform] The ``Transform`` class is now subclass of ``typing.NamedTuple``. No + change in functionality (#1904). + + +4.8.1 (released 2020-04-17) +--------------------------- + +- [feaLib] Fixed ``AttributeError: 'NoneType' has no attribute 'getAlternateGlyphs'`` + when ``aalt`` feature references a chain contextual substitution lookup + (googlefonts/fontmake#648, #1878). + +4.8.0 (released 2020-04-16) +--------------------------- + +- [feaLib] If Parser is initialized without a ``glyphNames`` parameter, it cannot + distinguish between a glyph name containing an hyphen, or a range of glyph names; + instead of raising an error, it now interprets them as literal glyph names, while + also outputting a logging warning to alert user about the ambiguity (#1768, #1870). +- [feaLib] When serializing AST to string, emit spaces around hyphens that denote + ranges. Also, fixed an issue with CID ranges when round-tripping AST->string->AST + (#1872). +- [Snippets/otf2ttf] In otf2ttf.py script update LSB in hmtx to match xMin (#1873). +- [colorLib] Added experimental support for building ``COLR`` v1 tables as per + the `colr-gradients-spec `__ + draft proposal. **NOTE**: both the API and the XML dump of ``COLR`` v1 are + susceptible to change while the proposal is being discussed and formalized (#1822). + +4.7.0 (released 2020-04-03) +--------------------------- + +- [cu2qu] Added ``fontTools.cu2qu`` package, imported from the original + `cu2qu `__ project. The ``cu2qu.pens`` module + was moved to ``fontTools.pens.cu2quPen``. The optional cu2qu extension module + can be compiled by installing `Cython `__ before installing + fonttools from source (i.e. git repo or sdist tarball). The wheel package that + is published on PyPI (i.e. the one ``pip`` downloads, unless ``--no-binary`` + option is used), will continue to be pure-Python for now (#1868). + +4.6.0 (released 2020-03-24) +--------------------------- + +- [varLib] Added support for building variable ``BASE`` table version 1.1 (#1858). +- [CPAL] Added ``fromRGBA`` method to ``Color`` class (#1861). + + +4.5.0 (released 2020-03-20) +--------------------------- + +- [designspaceLib] Added ``add{Axis,Source,Instance,Rule}Descriptor`` methods to + ``DesignSpaceDocument`` class, to initialize new descriptor objects using keyword + arguments, and at the same time append them to the current document (#1860). +- [unicodedata] Update to Unicode 13.0 (#1859). + +4.4.3 (released 2020-03-13) +--------------------------- + +- [varLib] Always build ``gvar`` table for TrueType-flavored Variable Fonts, + even if it contains no variation data. The table is required according to + the OpenType spec (#1855, #1857). + +4.4.2 (released 2020-03-12) +--------------------------- + +- [ttx] Annotate ``LookupFlag`` in XML dump with comment explaining what bits + are set and what they mean (#1850). +- [feaLib] Added more descriptive message to ``IncludedFeaNotFound`` error (#1842). + +4.4.1 (released 2020-02-26) +--------------------------- + +- [woff2] Skip normalizing ``glyf`` and ``loca`` tables if these are missing from + a font (e.g. in NotoColorEmoji using ``CBDT/CBLC`` tables). +- [timeTools] Use non-localized date parsing in ``timestampFromString``, to fix + error when non-English ``LC_TIME`` locale is set (#1838, #1839). +- [fontBuilder] Make sure the CFF table generated by fontBuilder can be used by varLib + without having to compile and decompile the table first. This was breaking in + converting the CFF table to CFF2 due to some unset attributes (#1836). + +4.4.0 (released 2020-02-18) +--------------------------- + +- [colorLib] Added ``fontTools.colorLib.builder`` module, initially with ``buildCOLR`` + and ``buildCPAL`` public functions. More color font formats will follow (#1827). +- [fontBuilder] Added ``setupCOLR`` and ``setupCPAL`` methods (#1826). +- [ttGlyphPen] Quantize ``GlyphComponent.transform`` floats to ``F2Dot14`` to fix + round-trip issue when computing bounding boxes of transformed components (#1830). +- [glyf] If a component uses reference points (``firstPt`` and ``secondPt``) for + alignment (instead of X and Y offsets), compute the effective translation offset + *after* having applied any transform (#1831). +- [glyf] When all glyphs have zero contours, compile ``glyf`` table data as a single + null byte in order to pass validation by OTS and Windows (#1829). +- [feaLib] Parsing feature code now ensures that referenced glyph names are part of + the known glyph set, unless a glyph set was not provided. +- [varLib] When filling in the default axis value for a missing location of a source or + instance, correctly map the value forward. +- [varLib] The avar table can now contain mapping output values that are greater than + OR EQUAL to the preceeding value, as the avar specification allows this. +- [varLib] The errors of the module are now ordered hierarchically below VarLibError. + See #1821. + +4.3.0 (released 2020-02-03) +--------------------------- + +- [EBLC/CBLC] Fixed incorrect padding length calculation for Format 3 IndexSubTable + (#1817, #1818). +- [varLib] Fixed error when merging OTL tables and TTFonts were loaded as ``lazy=True`` + (#1808, #1809). +- [varLib] Allow to use master fonts containing ``CFF2`` table when building VF (#1816). +- [ttLib] Make ``recalcBBoxes`` option work also with ``CFF2`` table (#1816). +- [feaLib] Don't reset ``lookupflag`` in lookups defined inside feature blocks. + They will now inherit the current ``lookupflag`` of the feature. This is what + Adobe ``makeotf`` also does in this case (#1815). +- [feaLib] Fixed bug with mixed single/multiple substitutions. If a single substitution + involved a glyph class, we were incorrectly using only the first glyph in the class + (#1814). + +4.2.5 (released 2020-01-29) +--------------------------- + +- [feaLib] Do not fail on duplicate multiple substitutions, only warn (#1811). +- [subset] Optimize SinglePos subtables to Format 1 if all ValueRecords are the same + (#1802). + +4.2.4 (released 2020-01-09) +--------------------------- + +- [unicodedata] Update RTL_SCRIPTS for Unicode 11 and 12. + +4.2.3 (released 2020-01-07) +--------------------------- + +- [otTables] Fixed bug when splitting `MarkBasePos` subtables as offsets overflow. + The mark class values in the split subtable were not being updated, leading to + invalid mark-base attachments (#1797, googlefonts/noto-source#145). +- [feaLib] Only log a warning instead of error when features contain duplicate + substitutions (#1767). +- [glifLib] Strip XML comments when parsing with lxml (#1784, #1785). + +4.2.2 (released 2019-12-12) +--------------------------- + +- [subset] Fixed issue with subsetting FeatureVariations table when the index + of features changes as features get dropped. The feature index need to be + remapped to point to index of the remaining features (#1777, #1782). +- [fontBuilder] Added `addFeatureVariations` method to `FontBuilder` class. This + is a shorthand for calling `featureVars.addFeatureVariations` on the builder's + TTFont object (#1781). +- [glyf] Fixed the flags bug in glyph.drawPoints() like we did for glyph.draw() + (#1771, #1774). + +4.2.1 (released 2019-12-06) +--------------------------- + +- [glyf] Use the ``flagOnCurve`` bit mask in ``glyph.draw()``, so that we ignore + the ``overlap`` flag that may be set when instantiating variable fonts (#1771). + +4.2.0 (released 2019-11-28) +--------------------------- + +- [pens] Added the following pens: + + * ``roundingPen.RoundingPen``: filter pen that rounds coordinates and components' + offsets to integer; + * ``roundingPen.RoundingPointPen``: like the above, but using PointPen protocol. + * ``filterPen.FilterPointPen``: base class for filter point pens; + * ``transformPen.TransformPointPen``: filter point pen to apply affine transform; + * ``recordingPen.RecordingPointPen``: records and replays point-pen commands. + +- [ttGlyphPen] Always round float coordinates and component offsets to integers + (#1763). +- [ufoLib] When converting kerning groups from UFO2 to UFO3, avoid confusing + groups with the same name as one of the glyphs (#1761, #1762, + unified-font-object/ufo-spec#98). + +4.1.0 (released 2019-11-18) +--------------------------- + +- [instancer] Implemented restricting axis ranges (level 3 partial instancing). + You can now pass ``{axis_tag: (min, max)}`` tuples as input to the + ``instantiateVariableFont`` function. Note that changing the default axis + position is not supported yet. The command-line script also accepts axis ranges + in the form of colon-separated float values, e.g. ``wght=400:700`` (#1753, #1537). +- [instancer] Never drop STAT ``DesignAxis`` records, but only prune out-of-range + ``AxisValue`` records. +- [otBase/otTables] Enforce that VarStore.RegionAxisCount == fvar.axisCount, even + when regions list is empty to appease OTS < v8.0 (#1752). +- [designspaceLib] Defined new ``processing`` attribute for ```` element, + with values "first" or "last", plus other editorial changes to DesignSpace + specification. Bumped format version to 4.1 (#1750). +- [varLib] Improved error message when masters' glyph orders do not match (#1758, + #1759). +- [featureVars] Allow to specify custom feature tag in ``addFeatureVariations``; + allow said feature to already exist, in which case we append new lookup indices + to existing features. Implemented ```` attribute ``processing`` according to + DesignSpace specification update in #1750. Depending on this flag, we generate + either an 'rvrn' (always processed first) or a 'rclt' feature (follows lookup order, + therefore last) (#1747, #1625, #1371). +- [ttCollection] Added support for context manager auto-closing via ``with`` statement + like with ``TTFont`` (#1751). +- [unicodedata] Require unicodedata2 >= 12.1.0. +- [py2.py3] Removed yet more PY2 vestiges (#1743). +- [_n_a_m_e] Fixed issue when comparing NameRecords with different string types (#1742). +- [fixedTools] Changed ``fixedToFloat`` to not do any rounding but simply return + ``value / (1 << precisionBits)``. Added ``floatToFixedToStr`` and + ``strToFixedToFloat`` functions to be used when loading from or dumping to XML. + Fixed values (e.g. fvar axes and instance coordinates, avar mappings, etc.) are + are now stored as un-rounded decimal floats upon decompiling (#1740, #737). +- [feaLib] Fixed handling of multiple ``LigatureCaret`` statements for the same glyph. + Only the first rule per glyph is used, additional ones are ignored (#1733). + +4.0.2 (released 2019-09-26) +--------------------------- + +- [voltLib] Added support for ``ALL`` and ``NONE`` in ``PROCESS_MARKS`` (#1732). +- [Silf] Fixed issue in ``Silf`` table compilation and decompilation regarding str vs + bytes in python3 (#1728). +- [merge] Handle duplicate glyph names better: instead of appending font index to + all glyph names, use similar code like we use in ``post`` and ``CFF`` tables (#1729). + +4.0.1 (released 2019-09-11) +--------------------------- + +- [otTables] Support fixing offset overflows in ``MultipleSubst`` lookup subtables + (#1706). +- [subset] Prune empty strikes in ``EBDT`` and ``CBDT`` table data (#1698, #1633). +- [pens] Fixed issue in ``PointToSegmentPen`` when last point of closed contour has + same coordinates as the starting point and was incorrectly dropped (#1720). +- [Graphite] Fixed ``Sill`` table output to pass OTS (#1705). +- [name] Added ``removeNames`` method to ``table__n_a_m_e`` class (#1719). +- [ttLib] Added aliases for renamed entries ``ascender`` and ``descender`` in + ``hhea`` table (#1715). + +4.0.0 (released 2019-08-22) +--------------------------- + +- NOTE: The v4.x version series only supports Python 3.6 or greater. You can keep + using fonttools 3.x if you need support for Python 2. +- [py23] Removed all the python2-only code since it is no longer reachable, thus + unused; only the Python3 symbols were kept, but these are no-op. The module is now + DEPRECATED and will removed in the future. +- [ttLib] Fixed UnboundLocalError for empty loca/glyph tables (#1680). Also, allow + the glyf table to be incomplete when dumping to XML (#1681). +- [varLib.models] Fixed KeyError while sorting masters and there are no on-axis for + a given axis (38a8eb0e). +- [cffLib] Make sure glyph names are unique (#1699). +- [feaLib] Fix feature parser to correctly handle octal numbers (#1700). + +\... see `here `__ for earlier changes diff --git a/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..eb623821e78ebe6f2c49ce289c557bf8d2bae40e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/RECORD @@ -0,0 +1,709 @@ +../../../bin/fonttools,sha256=AsXW42kFxp4z5nBKsfLHtHpDqOWwOx1yvrBjEU98pIQ,249 +../../../bin/pyftmerge,sha256=gwskZdCNVhy5eW9diAdxMJGlJ7ntUa8hjFkL4EKkT5E,246 +../../../bin/pyftsubset,sha256=9ElU95XucYYpbCBIxO9v12AsJtz6oc15qkcuL_-CJa8,247 +../../../bin/ttx,sha256=V8oF0Gr4QNrH9G4gLhz9qPB5s-OxNTn2qk2R_HKXlNs,244 +../../../share/man/man1/ttx.1,sha256=cLbm_pOOj1C76T2QXvDxzwDj9gk-GTd5RztvTMsouFw,5377 +fontTools/__init__.py,sha256=NhalGUDzO1KIFHH4MdKrxFY9at4Wggr6fDiqxIfKqQ0,183 +fontTools/__main__.py,sha256=VjkGh1UD-i1zTDA1dXo1uecSs6PxHdGQ5vlCk_mCCYs,925 +fontTools/__pycache__/__init__.cpython-312.pyc,, +fontTools/__pycache__/__main__.cpython-312.pyc,, +fontTools/__pycache__/afmLib.cpython-312.pyc,, +fontTools/__pycache__/agl.cpython-312.pyc,, +fontTools/__pycache__/annotations.cpython-312.pyc,, +fontTools/__pycache__/fontBuilder.cpython-312.pyc,, +fontTools/__pycache__/help.cpython-312.pyc,, +fontTools/__pycache__/tfmLib.cpython-312.pyc,, +fontTools/__pycache__/ttx.cpython-312.pyc,, +fontTools/__pycache__/unicode.cpython-312.pyc,, +fontTools/afmLib.py,sha256=rmp-cXQMGLJ5x_btmS9gUKU5i6YSMQa1nMJRyUBGI7s,13374 +fontTools/agl.py,sha256=U96o78Zorn5uznaLWqxVSxXKuF2e5KFFRvv1zRLWiqQ,113030 +fontTools/annotations.py,sha256=BdIIriNYDzBfgniwWFg_u71qLZnV0sCcn4-VAkXkYNM,1225 +fontTools/cffLib/CFF2ToCFF.py,sha256=5sgs0A74Q6rtByUiIBdMJBb1Nkt5E96LHy2-np2u3MI,8200 +fontTools/cffLib/CFFToCFF2.py,sha256=Qnk7lYlsTRHnlZQ6NXNdr_f4MJwZQ21kcS08KFbsyY8,10119 +fontTools/cffLib/__init__.py,sha256=RG1jUl82tehcsjI0SbsKJ_-MhVTvKxQ2ThgWOI3SA0k,107890 +fontTools/cffLib/__pycache__/CFF2ToCFF.cpython-312.pyc,, +fontTools/cffLib/__pycache__/CFFToCFF2.cpython-312.pyc,, +fontTools/cffLib/__pycache__/__init__.cpython-312.pyc,, +fontTools/cffLib/__pycache__/specializer.cpython-312.pyc,, +fontTools/cffLib/__pycache__/transforms.cpython-312.pyc,, +fontTools/cffLib/__pycache__/width.cpython-312.pyc,, +fontTools/cffLib/specializer.py,sha256=vsOPkR_jHNe6tESQEjmm0i76y7sWI5MKo3bsTmI3sNM,32609 +fontTools/cffLib/transforms.py,sha256=SEIZc1XxWYiVXVBsoNm6LTvM9SUN7Z76QOaSAlR1ZCo,17455 +fontTools/cffLib/width.py,sha256=9yvMvTpWRaPwypN5c8SQdKZb1kMqUkr9lWmAxlyfb2M,6073 +fontTools/colorLib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fontTools/colorLib/__pycache__/__init__.cpython-312.pyc,, +fontTools/colorLib/__pycache__/builder.cpython-312.pyc,, +fontTools/colorLib/__pycache__/errors.cpython-312.pyc,, +fontTools/colorLib/__pycache__/geometry.cpython-312.pyc,, +fontTools/colorLib/__pycache__/table_builder.cpython-312.pyc,, +fontTools/colorLib/__pycache__/unbuilder.cpython-312.pyc,, +fontTools/colorLib/builder.py,sha256=3lO9vFZSaatEsmdinJgc0cgtpWLkzs53HMsySYz9toU,24961 +fontTools/colorLib/errors.py,sha256=CsaviiRxxrpgVX4blm7KCyK8553ljwL44xkJOeC5U7U,41 +fontTools/colorLib/geometry.py,sha256=3ScySrR2YDJa7d5K5_xM5Yt1-3NCV-ry8ikYA5VwVbI,5518 +fontTools/colorLib/table_builder.py,sha256=ZeltWY6n-YPiJv_hQ1iBXoEFAG70EKxZyScgsMKUFGU,7469 +fontTools/colorLib/unbuilder.py,sha256=iW-E5I39WsV82K3NgCO4Cjzwm1WqzGrtypHt8epwbHM,2142 +fontTools/config/__init__.py,sha256=saGLKWZSJMyjXHBSQT6hLTVaV9eUM0dtIAPLewR7Lyg,3098 +fontTools/config/__pycache__/__init__.cpython-312.pyc,, +fontTools/cu2qu/__init__.py,sha256=Cuc7Uglb0nSgaraTxXY5J8bReznH5wApW0uakN7MycY,618 +fontTools/cu2qu/__main__.py,sha256=gyqV6Yq8eH8MOtfWCS0EVz9Q26uUs63d4rzq_JLMR-Y,91 +fontTools/cu2qu/__pycache__/__init__.cpython-312.pyc,, +fontTools/cu2qu/__pycache__/__main__.cpython-312.pyc,, +fontTools/cu2qu/__pycache__/benchmark.cpython-312.pyc,, +fontTools/cu2qu/__pycache__/cli.cpython-312.pyc,, +fontTools/cu2qu/__pycache__/cu2qu.cpython-312.pyc,, +fontTools/cu2qu/__pycache__/errors.cpython-312.pyc,, +fontTools/cu2qu/__pycache__/ufo.cpython-312.pyc,, +fontTools/cu2qu/benchmark.py,sha256=wasPJmf8q9k9UHjpHChC3WQAGbBAyHN9PvJzXvWC0Fw,1296 +fontTools/cu2qu/cli.py,sha256=cT6419FTnrGVm4pJeH3bOenQq7LHGAj-GGrtvtTzg4Y,6075 +fontTools/cu2qu/cu2qu.c,sha256=Z3s4VcPGdfSRMwhTUvpryHwLNB5D0IA_vYRajWqWpXM,693337 +fontTools/cu2qu/cu2qu.cpython-312-x86_64-linux-gnu.so,sha256=nYI2gVGvBwfaH6gGp713iAo1d3j-H6tvFEb13oeU23Y,1166864 +fontTools/cu2qu/cu2qu.py,sha256=IMZNdD-LtSdSEkL2MPqjubjncMtxKiycQXIKt-BIjj4,18282 +fontTools/cu2qu/errors.py,sha256=PyJNMy8lHDtKpfFkc0nkM8F4jNLZAC4lPQCN1Km4bpg,2441 +fontTools/cu2qu/ufo.py,sha256=pzZ_YEEqeQvGuEJeHJ3pdZ4U3dZA0nUCz8RMytBDwnE,13123 +fontTools/designspaceLib/__init__.py,sha256=GmQlXlAmWFnsEvQnVYmbU5tMFkVmRPFSsA25IqBkB5o,131897 +fontTools/designspaceLib/__main__.py,sha256=PWPy-oTsFA67lMnRFojbsuN2-DNDWVPCVHvUQYkBzFk,102 +fontTools/designspaceLib/__pycache__/__init__.cpython-312.pyc,, +fontTools/designspaceLib/__pycache__/__main__.cpython-312.pyc,, +fontTools/designspaceLib/__pycache__/split.cpython-312.pyc,, +fontTools/designspaceLib/__pycache__/statNames.cpython-312.pyc,, +fontTools/designspaceLib/__pycache__/types.cpython-312.pyc,, +fontTools/designspaceLib/split.py,sha256=FB1NuvhUO453UXveQZi9oyrW_caoCPM3RADp1rYWkDs,19239 +fontTools/designspaceLib/statNames.py,sha256=gXGKWVr1ju2_oL-R_DkyoZ3GlI7mfLORovpk1Ebgmvc,9237 +fontTools/designspaceLib/types.py,sha256=ofK65qXNADqcpl7zI72Pa5s07-cm7G41iEmLVV44-Es,5320 +fontTools/diff/__init__.py,sha256=DgYBwtNerim9gxmYvy3KT8TEx6zHw3zDFuAaAPAQp1c,13626 +fontTools/diff/__main__.py,sha256=sV9DXsv9yuoHcJYuYQekpLxEXhWyLJ9TFx0JSSXdtgo,92 +fontTools/diff/__pycache__/__init__.cpython-312.pyc,, +fontTools/diff/__pycache__/__main__.cpython-312.pyc,, +fontTools/diff/__pycache__/color.cpython-312.pyc,, +fontTools/diff/__pycache__/diff.cpython-312.pyc,, +fontTools/diff/__pycache__/utils.cpython-312.pyc,, +fontTools/diff/color.py,sha256=irtBTlKWAc2FQvY8tI3_hkVCkfKGxTUqu3F7XFNb-Yc,1387 +fontTools/diff/diff.py,sha256=Sw_QdyYkTJilzDaQMo5ijCIVXeI5bDcNzUZrB7e2U0o,8964 +fontTools/diff/utils.py,sha256=OTdXNfK4JO8VvT4eueZ-XtYf01lOop0XGBIp84BtPz8,1020 +fontTools/encodings/MacRoman.py,sha256=4vEooUDm2gLCG8KIIDhRxm5-A64w7XrhP9cjDRr2Eo0,3576 +fontTools/encodings/StandardEncoding.py,sha256=Eo3AGE8FE_p-IVYYuV097KouSsF3UrXoRRN0XyvYbrs,3581 +fontTools/encodings/__init__.py,sha256=DJBWmoX_Haau7qlgmvWyfbhSzrX2qL636Rns7CG01pk,75 +fontTools/encodings/__pycache__/MacRoman.cpython-312.pyc,, +fontTools/encodings/__pycache__/StandardEncoding.cpython-312.pyc,, +fontTools/encodings/__pycache__/__init__.cpython-312.pyc,, +fontTools/encodings/__pycache__/codecs.cpython-312.pyc,, +fontTools/encodings/codecs.py,sha256=ysBqUR-VAa6bDI-zptgr3AX_cNt2EsESoaYD2W7epgc,4722 +fontTools/feaLib/__init__.py,sha256=jlIru2ghxvb1HhC5Je2BCXjFJmFQlYKpruorPoz3BvQ,213 +fontTools/feaLib/__main__.py,sha256=ORfpvQYEiMHB-HDZ1wevOAkE0rNqvMifE4Fs5F3OQRI,2239 +fontTools/feaLib/__pycache__/__init__.cpython-312.pyc,, +fontTools/feaLib/__pycache__/__main__.cpython-312.pyc,, +fontTools/feaLib/__pycache__/ast.cpython-312.pyc,, +fontTools/feaLib/__pycache__/builder.cpython-312.pyc,, +fontTools/feaLib/__pycache__/error.cpython-312.pyc,, +fontTools/feaLib/__pycache__/lexer.cpython-312.pyc,, +fontTools/feaLib/__pycache__/location.cpython-312.pyc,, +fontTools/feaLib/__pycache__/lookupDebugInfo.cpython-312.pyc,, +fontTools/feaLib/__pycache__/parser.cpython-312.pyc,, +fontTools/feaLib/__pycache__/variableScalar.cpython-312.pyc,, +fontTools/feaLib/ast.py,sha256=48Y6vpSD_wYfucWyh_bQtzf2AQFX-pOwBvsxdcpVDz0,74158 +fontTools/feaLib/builder.py,sha256=qlTXTA0Pktbh0gZrzlxK_YqIvs1NSWwweijxqxTIiGQ,76212 +fontTools/feaLib/error.py,sha256=Bz_5tNcNVcY7_nrAmFlQNhQldtqZWd8WUGQ2E3PWhZo,648 +fontTools/feaLib/lexer.c,sha256=zmVeWO3dXRBNx0rY9LZLlWr7D1c8B38N8UcL6WZfMQc,839901 +fontTools/feaLib/lexer.cpython-312-x86_64-linux-gnu.so,sha256=W3h0IvOErgNBb4xuMcq4VyqWrs-_Tz-ayao71yTMUZY,1504880 +fontTools/feaLib/lexer.py,sha256=NXWZt_ZSomP_3jYW-TyymRQTtlF0JoMlcx-icIjDX7o,11132 +fontTools/feaLib/location.py,sha256=JXzHqGV56EHdcq823AwA5oaK05hf_1ySWpScbo3zGC0,234 +fontTools/feaLib/lookupDebugInfo.py,sha256=gVRr5-APWfT_a5-25hRuawSVX8fEvXVsOSLWkH91T2w,304 +fontTools/feaLib/parser.py,sha256=I1wIRmhrEcuQY7nufefvr_5GEYxowPBi9RRlNRZlpzw,100830 +fontTools/feaLib/variableScalar.py,sha256=EET6iZz57tumU4by6WTwAtBMAV8EbQldfeXtOYqpB2M,9785 +fontTools/fontBuilder.py,sha256=lb4V6kbIty36dF63iIz3_pNo-_Al86DKmg9hqW0B5oc,34277 +fontTools/help.py,sha256=bAjatvIhV7TJyXI7WhsxdYO4YVlhScZXu_kRtHANEPo,1125 +fontTools/merge/__init__.py,sha256=iNTHxHr9ylWIvi104qT5D0at6K1SpNoccu1pNv2fqlk,8255 +fontTools/merge/__main__.py,sha256=bst-CXhKmjeAV0-zsJl7_9wbauBsxeeiHscyEQ8RvgE,93 +fontTools/merge/__pycache__/__init__.cpython-312.pyc,, +fontTools/merge/__pycache__/__main__.cpython-312.pyc,, +fontTools/merge/__pycache__/base.cpython-312.pyc,, +fontTools/merge/__pycache__/cmap.cpython-312.pyc,, +fontTools/merge/__pycache__/layout.cpython-312.pyc,, +fontTools/merge/__pycache__/options.cpython-312.pyc,, +fontTools/merge/__pycache__/tables.cpython-312.pyc,, +fontTools/merge/__pycache__/unicode.cpython-312.pyc,, +fontTools/merge/__pycache__/util.cpython-312.pyc,, +fontTools/merge/base.py,sha256=z2hnbt0hIl39lCZ-uSYRr7VFTwmtm9GH5i_Lu1fwI3c,2388 +fontTools/merge/cmap.py,sha256=IyTDLanQ0T1fy-bMhoGz3VcCfApjM_jMhiaKYoKiseA,6727 +fontTools/merge/layout.py,sha256=coqS4YT4IBv8PVMbHOBV_NoPDeOuVBjJM4t2yCq33ME,16074 +fontTools/merge/options.py,sha256=xko_1-WErcNQkirECzIOOYxSJR_bRtdQYQYOtmgccYI,2501 +fontTools/merge/tables.py,sha256=qWDNSMS9why77Rm4acwKK4Zs5LnrBGTH2rvMzbr-O0M,10957 +fontTools/merge/unicode.py,sha256=kb1Jrfuoq1KUcVhhSKnflAED_wMZxXDjVwB-CI9k05Y,4273 +fontTools/merge/util.py,sha256=-v3MefZRpvMbZIw-dNyvRpVn_ff4wJT109X5cBqI7AQ,3377 +fontTools/misc/__init__.py,sha256=DJBWmoX_Haau7qlgmvWyfbhSzrX2qL636Rns7CG01pk,75 +fontTools/misc/__pycache__/__init__.cpython-312.pyc,, +fontTools/misc/__pycache__/arrayTools.cpython-312.pyc,, +fontTools/misc/__pycache__/bezierTools.cpython-312.pyc,, +fontTools/misc/__pycache__/classifyTools.cpython-312.pyc,, +fontTools/misc/__pycache__/cliTools.cpython-312.pyc,, +fontTools/misc/__pycache__/configTools.cpython-312.pyc,, +fontTools/misc/__pycache__/cython.cpython-312.pyc,, +fontTools/misc/__pycache__/dictTools.cpython-312.pyc,, +fontTools/misc/__pycache__/eexec.cpython-312.pyc,, +fontTools/misc/__pycache__/encodingTools.cpython-312.pyc,, +fontTools/misc/__pycache__/enumTools.cpython-312.pyc,, +fontTools/misc/__pycache__/etree.cpython-312.pyc,, +fontTools/misc/__pycache__/filenames.cpython-312.pyc,, +fontTools/misc/__pycache__/fixedTools.cpython-312.pyc,, +fontTools/misc/__pycache__/iftSparseBitSet.cpython-312.pyc,, +fontTools/misc/__pycache__/intTools.cpython-312.pyc,, +fontTools/misc/__pycache__/iterTools.cpython-312.pyc,, +fontTools/misc/__pycache__/lazyTools.cpython-312.pyc,, +fontTools/misc/__pycache__/loggingTools.cpython-312.pyc,, +fontTools/misc/__pycache__/macCreatorType.cpython-312.pyc,, +fontTools/misc/__pycache__/macRes.cpython-312.pyc,, +fontTools/misc/__pycache__/psCharStrings.cpython-312.pyc,, +fontTools/misc/__pycache__/psLib.cpython-312.pyc,, +fontTools/misc/__pycache__/psOperators.cpython-312.pyc,, +fontTools/misc/__pycache__/py23.cpython-312.pyc,, +fontTools/misc/__pycache__/roundTools.cpython-312.pyc,, +fontTools/misc/__pycache__/sstruct.cpython-312.pyc,, +fontTools/misc/__pycache__/symfont.cpython-312.pyc,, +fontTools/misc/__pycache__/testTools.cpython-312.pyc,, +fontTools/misc/__pycache__/textTools.cpython-312.pyc,, +fontTools/misc/__pycache__/timeTools.cpython-312.pyc,, +fontTools/misc/__pycache__/transform.cpython-312.pyc,, +fontTools/misc/__pycache__/treeTools.cpython-312.pyc,, +fontTools/misc/__pycache__/vector.cpython-312.pyc,, +fontTools/misc/__pycache__/visitor.cpython-312.pyc,, +fontTools/misc/__pycache__/xmlReader.cpython-312.pyc,, +fontTools/misc/__pycache__/xmlWriter.cpython-312.pyc,, +fontTools/misc/arrayTools.py,sha256=zc7X-S6bu43vKwm375p4zkraUM97DvtZOKPFv_o2qkg,11457 +fontTools/misc/bezierTools.c,sha256=VAmhwj1p2pCIR3mHJ8tVHYoLU1tvU_fNazuO5Veq2ss,2049184 +fontTools/misc/bezierTools.cpython-312-x86_64-linux-gnu.so,sha256=oNmFRUjydjpC86L0KOe1LpnM5k6Axg32a5zBRVXWBB4,4889112 +fontTools/misc/bezierTools.py,sha256=w-E_HB_ZtmBRqTLjz5EG8o7cNQTsSVFh3eGfzLU-EVs,45239 +fontTools/misc/classifyTools.py,sha256=bhbMtGaLxnle3498vjBtAR2F6yfMawM47Na_jb9lBGY,5611 +fontTools/misc/cliTools.py,sha256=xXVkFXKxynRwFI69nAST_gLhtmb8rZwWK5eO2qyerVw,1861 +fontTools/misc/configTools.py,sha256=T1J3yKRJzhGtXhFeNUc93dRvklKw4Ncbe0TtrJJ24ZY,11228 +fontTools/misc/cython.py,sha256=FvQ7PoYzbi2y7iFpUkE-QqtKWueYfopwUxXTSzeuoik,681 +fontTools/misc/dictTools.py,sha256=VxjarsGJuk_wa3z29FSCtKZNCFfXtMBiNEu0RPAlpDk,2417 +fontTools/misc/eexec.py,sha256=GNn2OCRvO1HbbIeDPxk9i0glO7cux_AQaoVMXhBR8y8,3331 +fontTools/misc/encodingTools.py,sha256=z7-J4IqiNMwCg8HmSwZUWS9Tg8X3L4fzCzrDLbIWj2s,2072 +fontTools/misc/enumTools.py,sha256=FU3TB95Y5G3iYfChwFwoKKEDL4CnBq14xAzGC-vc9zQ,501 +fontTools/misc/etree.py,sha256=hmTv7EMhgR8wsAw24wEkFd3LyYKss7ki-VP9mED0t8w,17155 +fontTools/misc/filenames.py,sha256=MMCO3xjk1pcDc-baobcKd8IdoFPt-bcGqu8t8HUGAkI,8223 +fontTools/misc/filesystem/__init__.py,sha256=iwoOj6DpXKk8q-NRRHqOfRxFF6lcXIhsIA46j-cZswU,2011 +fontTools/misc/filesystem/__pycache__/__init__.cpython-312.pyc,, +fontTools/misc/filesystem/__pycache__/_base.cpython-312.pyc,, +fontTools/misc/filesystem/__pycache__/_copy.cpython-312.pyc,, +fontTools/misc/filesystem/__pycache__/_errors.cpython-312.pyc,, +fontTools/misc/filesystem/__pycache__/_info.cpython-312.pyc,, +fontTools/misc/filesystem/__pycache__/_osfs.cpython-312.pyc,, +fontTools/misc/filesystem/__pycache__/_path.cpython-312.pyc,, +fontTools/misc/filesystem/__pycache__/_subfs.cpython-312.pyc,, +fontTools/misc/filesystem/__pycache__/_tempfs.cpython-312.pyc,, +fontTools/misc/filesystem/__pycache__/_tools.cpython-312.pyc,, +fontTools/misc/filesystem/__pycache__/_walk.cpython-312.pyc,, +fontTools/misc/filesystem/__pycache__/_zipfs.cpython-312.pyc,, +fontTools/misc/filesystem/_base.py,sha256=p74O7xREadfPQgzPJ9mP3ehu0ZHDgsmXlpsL9CnTRso,4010 +fontTools/misc/filesystem/_copy.py,sha256=ifMSs-A_bz1Aa4tIQrlUd9HtdJQ5fp5M3B6mbYuDtXI,1361 +fontTools/misc/filesystem/_errors.py,sha256=5CaKlhPbqOHMTp5NkZsWm6MQ1lDqob1R_fIRtsA4qZ0,955 +fontTools/misc/filesystem/_info.py,sha256=pbV7bDTJ5F8ms6alK34J0FZYWzmRO7FT0NM3yRA3czo,2013 +fontTools/misc/filesystem/_osfs.py,sha256=0CKvmzwAEmK3Q_CV5VFRa8xUbk7G9FeZCSFyzFE_DoM,6323 +fontTools/misc/filesystem/_path.py,sha256=uRt30Yo-8bgb1_Mg1L617a58dkP9vc9-H6cypKpf4Fk,2122 +fontTools/misc/filesystem/_subfs.py,sha256=vRotQwyLVfINbR88xIBQUbq9j4Kmg1_mJvEhnpvK_t4,3028 +fontTools/misc/filesystem/_tempfs.py,sha256=9FUXdCBTwFtZMFx8ghYuZVYoQdDb0tDB-jXNu3D-Qy0,924 +fontTools/misc/filesystem/_tools.py,sha256=r75dpadp7C9EdQ6r7pJQKZlCZDUJzVq2ikb_LXN-wCI,972 +fontTools/misc/filesystem/_walk.py,sha256=KMQ-GavWYr4SsA5V8ohLPmz3boilvY2P0JKrLoxW6NU,1655 +fontTools/misc/filesystem/_zipfs.py,sha256=PSTgmSxPltYl7fIlXMEdj6Q7kMVsNLz_qaguWB6JmCU,7253 +fontTools/misc/fixedTools.py,sha256=QA_pezHYeusOJeLM-5Fq9qI732FvHGAIaNwgW55fKo4,7703 +fontTools/misc/iftSparseBitSet.py,sha256=nhqQIa3o-P5frMdk4XlySzEAmGc7igouYlhBSR8U7ss,10521 +fontTools/misc/intTools.py,sha256=l6pjk4UYlXcyLtfC0DdOC5RL6UJ8ihRR0zRiYow5xA8,586 +fontTools/misc/iterTools.py,sha256=17H6LPZszp32bTKoNorp6uZF1PKj47BAbe5QG8irUjo,390 +fontTools/misc/lazyTools.py,sha256=BC6MmF-OzJ3GrBD8TYDZ-VCSN4UOx0pN0r3oF4GSoiw,1020 +fontTools/misc/loggingTools.py,sha256=_m8osCG2dagP4rxuaGaZuJZcdmMCrIUCoKYjt1se85U,19932 +fontTools/misc/macCreatorType.py,sha256=Je9jtqUr7EPbpH3QxlVl3pizoQ-1AOPMBIctHIMTM3k,1593 +fontTools/misc/macRes.py,sha256=GT_pnfPw2NCvvOF86nHLAnOtZ6SMHqEuLntaplXzvHM,8579 +fontTools/misc/plistlib/__init__.py,sha256=adFabkiQc0_BOuJipxYhyeZxNTDgTZYE-Dm2zcFTthY,21113 +fontTools/misc/plistlib/__pycache__/__init__.cpython-312.pyc,, +fontTools/misc/plistlib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fontTools/misc/psCharStrings.py,sha256=ifXGyp1krROUdpxkUExP1j7Nlq4iJo1L1_w7I6gtKxg,43467 +fontTools/misc/psLib.py,sha256=IosssLC498dejhf8RMYHiPsx6N5yyGmXWSvkLup5gPM,12098 +fontTools/misc/psOperators.py,sha256=9SLl5PPBulLo0Xxg_dqlJMitNIBdiGKdkXhOWsNSYZE,15700 +fontTools/misc/py23.py,sha256=aPVCEUz_deggwLBCeTSsccX6QgJavZqvdVtuhpzrPvA,2238 +fontTools/misc/roundTools.py,sha256=5oQg9RHxlC4-KZRO3paGrDfUlY7Egd4kEkdj22B3h_A,4871 +fontTools/misc/sstruct.py,sha256=HXJyJsPkjkHyZUK6uQ5zCmb5ba5ErobyRfoKO-WhhH8,7114 +fontTools/misc/symfont.py,sha256=wu_fMcBfPM51pSNczJGmvTb6h1Yq-5en0xymuYworvg,6961 +fontTools/misc/testTools.py,sha256=3vj_KllUQVEiVFbS0SzTmeuKv44-L-disI1dZ4XhOfw,7052 +fontTools/misc/textTools.py,sha256=4jIPxCDE5Jv6zjefyLdovYDLWk-SIO9CfeBAsCfeQds,3482 +fontTools/misc/timeTools.py,sha256=7uNX5iz4pBiK4i74aIzNiiLfrNoIQgbiAGTVAcFfevU,2232 +fontTools/misc/transform.py,sha256=4orecCUhsJt8Dni0RphusF-GPbzx92flYsj9u-dFXMI,16003 +fontTools/misc/treeTools.py,sha256=tLWkwyDHeZUPVOGNnJeD4Pn7x2bQeZetwJKaEAW2J2M,1269 +fontTools/misc/vector.py,sha256=svox1_yEeBghKHMnvTa3S1G0Q5AMpf8IK3OYiQVVdqY,4061 +fontTools/misc/visitor.py,sha256=zwBAVfZ3MTsrbhNFj03pSSjNRyT6oGkare-kfWkN5ns,5754 +fontTools/misc/xmlReader.py,sha256=11dhqLNbtTUmhF7yBxZWRTFzujN5kvNuYSmqnegQdTk,6579 +fontTools/misc/xmlWriter.py,sha256=WB0yBd5d29aNHbmJNHt4JbCniYwCtScOcnPZ3VEymOY,7581 +fontTools/mtiLib/__init__.py,sha256=MeYYLmFYPNG40xNZsm7OrS26KuADp3FMFq_BeVvb7Os,46594 +fontTools/mtiLib/__main__.py,sha256=gd8X89jnZOe-752k7uaR1lWoiju-2zIT5Yx35Kl0Xek,94 +fontTools/mtiLib/__pycache__/__init__.cpython-312.pyc,, +fontTools/mtiLib/__pycache__/__main__.cpython-312.pyc,, +fontTools/otlLib/__init__.py,sha256=D2leUW-3gsUTOFcJYGC18edBYjIJ804ut4qitJYWsaQ,45 +fontTools/otlLib/__pycache__/__init__.cpython-312.pyc,, +fontTools/otlLib/__pycache__/builder.cpython-312.pyc,, +fontTools/otlLib/__pycache__/error.cpython-312.pyc,, +fontTools/otlLib/__pycache__/maxContextCalc.cpython-312.pyc,, +fontTools/otlLib/builder.py,sha256=OC50392PlJ3Smlf8GcV2oEEcRZWwEFjhoWQaD1ICVUs,130342 +fontTools/otlLib/error.py,sha256=cthuhBuOwZYpkTLi5gFPupUxkXkCHe-L_YgkE7N1wCI,335 +fontTools/otlLib/maxContextCalc.py,sha256=3es4Kt84TaZ49sA2ev1zrlwPJikJCAECx5KavwhyB-I,3175 +fontTools/otlLib/optimize/__init__.py,sha256=UUQRpNkHU2RczCRt-Gz7sEiYE9AQq9BHLXZEOyvsnX4,1530 +fontTools/otlLib/optimize/__main__.py,sha256=n_fd1tUZnXrI4CT1fTT2_GwcJn3XcmRZsOk9LMrVmPU,103 +fontTools/otlLib/optimize/__pycache__/__init__.cpython-312.pyc,, +fontTools/otlLib/optimize/__pycache__/__main__.cpython-312.pyc,, +fontTools/otlLib/optimize/__pycache__/gpos.cpython-312.pyc,, +fontTools/otlLib/optimize/gpos.py,sha256=htOgSP743DZDUKF3eWAeJ-kdqNYOnpGXdlV-rbEXJ1A,17668 +fontTools/pens/__init__.py,sha256=DJBWmoX_Haau7qlgmvWyfbhSzrX2qL636Rns7CG01pk,75 +fontTools/pens/__pycache__/__init__.cpython-312.pyc,, +fontTools/pens/__pycache__/areaPen.cpython-312.pyc,, +fontTools/pens/__pycache__/basePen.cpython-312.pyc,, +fontTools/pens/__pycache__/boundsPen.cpython-312.pyc,, +fontTools/pens/__pycache__/cairoPen.cpython-312.pyc,, +fontTools/pens/__pycache__/cocoaPen.cpython-312.pyc,, +fontTools/pens/__pycache__/cu2quPen.cpython-312.pyc,, +fontTools/pens/__pycache__/explicitClosingLinePen.cpython-312.pyc,, +fontTools/pens/__pycache__/filterPen.cpython-312.pyc,, +fontTools/pens/__pycache__/freetypePen.cpython-312.pyc,, +fontTools/pens/__pycache__/hashPointPen.cpython-312.pyc,, +fontTools/pens/__pycache__/momentsPen.cpython-312.pyc,, +fontTools/pens/__pycache__/perimeterPen.cpython-312.pyc,, +fontTools/pens/__pycache__/pointInsidePen.cpython-312.pyc,, +fontTools/pens/__pycache__/pointPen.cpython-312.pyc,, +fontTools/pens/__pycache__/qtPen.cpython-312.pyc,, +fontTools/pens/__pycache__/qu2cuPen.cpython-312.pyc,, +fontTools/pens/__pycache__/quartzPen.cpython-312.pyc,, +fontTools/pens/__pycache__/recordingPen.cpython-312.pyc,, +fontTools/pens/__pycache__/reportLabPen.cpython-312.pyc,, +fontTools/pens/__pycache__/reverseContourPen.cpython-312.pyc,, +fontTools/pens/__pycache__/roundingPen.cpython-312.pyc,, +fontTools/pens/__pycache__/statisticsPen.cpython-312.pyc,, +fontTools/pens/__pycache__/svgPathPen.cpython-312.pyc,, +fontTools/pens/__pycache__/t2CharStringPen.cpython-312.pyc,, +fontTools/pens/__pycache__/teePen.cpython-312.pyc,, +fontTools/pens/__pycache__/transformPen.cpython-312.pyc,, +fontTools/pens/__pycache__/ttGlyphPen.cpython-312.pyc,, +fontTools/pens/__pycache__/wxPen.cpython-312.pyc,, +fontTools/pens/areaPen.py,sha256=L0GD9qtTm3Ue1kh32zEZd0g_-V9UzwcxqpoY2w9uMFs,1471 +fontTools/pens/basePen.py,sha256=I2hg1ET9lshlYJfQYT9Cm1on_uVNtzL7vkY6jmCX3sE,17080 +fontTools/pens/boundsPen.py,sha256=ab7-QFpxH-K7S1b7Xv7VKmL2MogN8MUKzfn2a_o2ZoY,3128 +fontTools/pens/cairoPen.py,sha256=pWfbFbkKEPsWxmULPh1qGCVdi8f0e4r-70DUr8LBz0E,591 +fontTools/pens/cocoaPen.py,sha256=TVbI07PyRnbcr-ml6iU1GVkm6-LXPmdTCpHWctFLPAE,611 +fontTools/pens/cu2quPen.py,sha256=gMUwFUsm_-WzBlDjTMQiNnEuI2heomGeOJBX81zYXPo,13007 +fontTools/pens/explicitClosingLinePen.py,sha256=kKKtdZiwaf8Cj4_ytrIDdGB2GMpPPDXm5Nwbw5WDgwU,3219 +fontTools/pens/filterPen.py,sha256=REgspXaaSvF3XUwqe40abe3X_E7-WbBP13IqLUUBLCw,14703 +fontTools/pens/freetypePen.py,sha256=HD-gXJSbgImJdBc8sIBk0HWBdjv3WKFofs6PgCCsGOY,19908 +fontTools/pens/hashPointPen.py,sha256=gElrFyQoOQp3ZbpKHRWPwC61A9OgT2Js8crVUD8BQAY,3573 +fontTools/pens/momentsPen.c,sha256=HikVnBVa8J7J8n_ZhDNGp3y3OC5ag12UlO7Jm3GImuk,623883 +fontTools/pens/momentsPen.cpython-312-x86_64-linux-gnu.so,sha256=8jnu2X785roaf-J0aG-nYQCBI8mypm634maYCMgYO0k,1191872 +fontTools/pens/momentsPen.py,sha256=kjLVXhGe55Abl__Yr1gob0bl0dHe7fPSwyr7TRJnbug,25658 +fontTools/pens/perimeterPen.py,sha256=2L4aZ3zC5i2eWvYHJNfW76HWiym1ITZSz6r27Mw1a9g,2152 +fontTools/pens/pointInsidePen.py,sha256=QnHv2DsnjFeiYRaB1wbuDrAA4mng0nC144MM_Ya6wVI,6354 +fontTools/pens/pointPen.py,sha256=mXO5Tv25kyAdZ9FX29IoTQSjeh00kmtv3SZIMru8ZvI,24604 +fontTools/pens/qtPen.py,sha256=YXMdevYwKEJiaS_ZwCTZGgQeIG1SGqpBEagEpGQ4-bA,633 +fontTools/pens/qu2cuPen.py,sha256=pRST43-rUpzlOP83Z_Rr0IvIQBCx6RWI6nnNaitQcLk,3985 +fontTools/pens/quartzPen.py,sha256=Y1xZQ8GYQ0BGjPhW9bA4LJ9cGFul3vnFToMaH_wEyEc,1286 +fontTools/pens/recordingPen.py,sha256=ahorYM3UH5Gdese1zZKgHjHWkqxMYRIaTcqMpCqSBbE,12488 +fontTools/pens/reportLabPen.py,sha256=SFsXfRQyC3eHE-TKBzcxJYdkv3gSS6MOlzfxucN2F0o,2055 +fontTools/pens/reverseContourPen.py,sha256=ts8qWkOaOB0QZyBXzeu3oKR_IvlJHJUfSv2dr6qU_cM,4021 +fontTools/pens/roundingPen.py,sha256=NmFDVRveaIy2klqigm6z6wQQOgo9U4tCaHKQT0NZT1Y,4619 +fontTools/pens/statisticsPen.py,sha256=piWK6NjjWqk9MLROjeE2-4EsxVYMyNU7UQFGD_trE9g,9808 +fontTools/pens/svgPathPen.py,sha256=T3b6SZS9B9sVWMK9mSFDtjHeviQs_yOJOZKq5Sg5Zdg,8572 +fontTools/pens/t2CharStringPen.py,sha256=GgGklb5XsCer0w37ujgRLRXx-EuzdFsyCYuzCx4n-Qs,2931 +fontTools/pens/teePen.py,sha256=2fgjet8cZ-qSRtBgPmZB2rXaIjcEdUSEa2Ogk-vkHmE,1289 +fontTools/pens/transformPen.py,sha256=1pa6ZbjyfMWh-aY070VkwAf1h8lDK1Xbk4ffbzNIty4,4055 +fontTools/pens/ttGlyphPen.py,sha256=1_71Pr1h_OpdU_uxzGDGdlcGjQ9DIe3pqSBFbTcL2NQ,11869 +fontTools/pens/wxPen.py,sha256=raSZpsGkkhJfSOFoKwOn1hAJUPyzZX9GoMHhgl63p9Y,679 +fontTools/qu2cu/__init__.py,sha256=Jfm1JljXbt91w4gyvZn6jzEmVnhRx50sh2fDongrOsE,618 +fontTools/qu2cu/__main__.py,sha256=j1XxrqL7Zq18ILGTCvqzgamfMaQ7mcpA9ROj7LdIWw4,92 +fontTools/qu2cu/__pycache__/__init__.cpython-312.pyc,, +fontTools/qu2cu/__pycache__/__main__.cpython-312.pyc,, +fontTools/qu2cu/__pycache__/benchmark.cpython-312.pyc,, +fontTools/qu2cu/__pycache__/cli.cpython-312.pyc,, +fontTools/qu2cu/__pycache__/qu2cu.cpython-312.pyc,, +fontTools/qu2cu/benchmark.py,sha256=GMcr_4r7L6K9SmJ13itt-_XKhnKqSVUDPlXUG6IZmmM,1400 +fontTools/qu2cu/cli.py,sha256=G3oFXn-n4uNePjGmRbew6YiGBgIqz15v0VGT-53iJ7o,3839 +fontTools/qu2cu/qu2cu.c,sha256=cV3julhIB0opnTAI2k-wk_pp1TkDdw8OVu7KzlXQOXs,831850 +fontTools/qu2cu/qu2cu.cpython-312-x86_64-linux-gnu.so,sha256=DbLJ9xQOg587sonHyKeWAWzlsssKnDKvsrzUexPt91I,1476144 +fontTools/qu2cu/qu2cu.py,sha256=A3Im8VNpqM3kWREbgyC2V1Nuhkts1dEZfCTrOd7E7Hg,13138 +fontTools/subset/__init__.py,sha256=syax0fIfHgZebUXJYgP8NRnCoXihO4NamR8erLaPgro,143695 +fontTools/subset/__main__.py,sha256=IxD3xjjHp58Mlzn4aFHPiXUY4b0Sw8yTt0Hf6OtK6C4,94 +fontTools/subset/__pycache__/__init__.cpython-312.pyc,, +fontTools/subset/__pycache__/__main__.cpython-312.pyc,, +fontTools/subset/__pycache__/cff.cpython-312.pyc,, +fontTools/subset/__pycache__/svg.cpython-312.pyc,, +fontTools/subset/__pycache__/util.cpython-312.pyc,, +fontTools/subset/cff.py,sha256=rqMRJOlX5FacV1LW8aDlVOglgEM87TkMA9bdsYenask,6145 +fontTools/subset/svg.py,sha256=Tp7XV-SyZCDCGDcELPAMFjQtFA1GjKz4jZqMbSMVt2o,9296 +fontTools/subset/util.py,sha256=9SXFYb5Ef9Z58uXmYPCQil8B2i3Q7aFB_1fFDFSppdU,754 +fontTools/svgLib/__init__.py,sha256=IGCLwSbU8jLhq6HI2vSdPQgNs6zDUi5774TgX5MCXPY,75 +fontTools/svgLib/__pycache__/__init__.cpython-312.pyc,, +fontTools/svgLib/path/__init__.py,sha256=HHsggqSCevbMfxgRJdHUhbRTGFp_aoNngpfKLI0GO_0,2047 +fontTools/svgLib/path/__pycache__/__init__.cpython-312.pyc,, +fontTools/svgLib/path/__pycache__/arc.cpython-312.pyc,, +fontTools/svgLib/path/__pycache__/parser.cpython-312.pyc,, +fontTools/svgLib/path/__pycache__/shapes.cpython-312.pyc,, +fontTools/svgLib/path/arc.py,sha256=M2oY3KH8kUF6ToDB9xYbzWZxdeY-c6yK8q8KUFMXA7U,5811 +fontTools/svgLib/path/parser.py,sha256=_aXZt8RrD-YOPiV0jGJpkFKoVnSvb3JhJd3CZ_GC6Pk,12408 +fontTools/svgLib/path/shapes.py,sha256=5NYE-JSSNsxUt2T20ZK3TIFWrNg3cH3ETvOTwak-6cA,5387 +fontTools/t1Lib/__init__.py,sha256=THe-FAJDCJ7s3E6yfxeh21OHMa5ZaFh4MJLgYJcwXaU,20928 +fontTools/t1Lib/__pycache__/__init__.cpython-312.pyc,, +fontTools/tfmLib.py,sha256=Dig5JjMNc4Nhc6NmR5O_wuBt63RbcMu25CQQZ22bs5Q,14480 +fontTools/ttLib/__init__.py,sha256=aAIW5mgXOcJhWRhsxkFUXT48nNIBKT5-blBJyXqOj7I,660 +fontTools/ttLib/__main__.py,sha256=lHMPWsnzjKPuMFavf6i1gpk9KexiAk4qzgDd50Mbby0,4733 +fontTools/ttLib/__pycache__/__init__.cpython-312.pyc,, +fontTools/ttLib/__pycache__/__main__.cpython-312.pyc,, +fontTools/ttLib/__pycache__/macUtils.cpython-312.pyc,, +fontTools/ttLib/__pycache__/removeOverlaps.cpython-312.pyc,, +fontTools/ttLib/__pycache__/reorderGlyphs.cpython-312.pyc,, +fontTools/ttLib/__pycache__/scaleUpem.cpython-312.pyc,, +fontTools/ttLib/__pycache__/sfnt.cpython-312.pyc,, +fontTools/ttLib/__pycache__/standardGlyphOrder.cpython-312.pyc,, +fontTools/ttLib/__pycache__/ttCollection.cpython-312.pyc,, +fontTools/ttLib/__pycache__/ttFont.cpython-312.pyc,, +fontTools/ttLib/__pycache__/ttGlyphSet.cpython-312.pyc,, +fontTools/ttLib/__pycache__/ttVisitor.cpython-312.pyc,, +fontTools/ttLib/__pycache__/woff2.cpython-312.pyc,, +fontTools/ttLib/macUtils.py,sha256=lj3oeFpyjV7ko_JqnluneITmAtlc119J-vwTTg2s73A,1737 +fontTools/ttLib/removeOverlaps.py,sha256=nqUojoiSsVhOLreTqfJswZ_OVCjB_nV8brbJ1tvjcwM,12743 +fontTools/ttLib/reorderGlyphs.py,sha256=LegV28WQzzMLAfg1dDafmvYBZRRKJ47kq1vlqgziDFY,10370 +fontTools/ttLib/scaleUpem.py,sha256=kW7sRjn_9Wix0hucwWKM2PugZLq-9AMpqqPnBQ1k9Uw,14617 +fontTools/ttLib/sfnt.py,sha256=GpjgqV-njSxSX14SRHVi1rAiLiGeoN9qWCNd3gt9FPA,24751 +fontTools/ttLib/standardGlyphOrder.py,sha256=7AY_fVWdtwZ4iv5uWdyKAUcbEQiSDt1lN4sqx9xXwE0,5785 +fontTools/ttLib/tables/B_A_S_E_.py,sha256=H71A9pJ850mvjbrWHqy8iFI2Dxg7102YRtAkfdCooig,369 +fontTools/ttLib/tables/BitmapGlyphMetrics.py,sha256=d1jXxisotcRVR5iHQacVlXm8z9AeiV6vBO5s4uy6_2A,1768 +fontTools/ttLib/tables/C_B_D_T_.py,sha256=5LNdc8FMir1kC5fvp5iHwWfeuE-RuqdxAArFXaqPjQ0,3646 +fontTools/ttLib/tables/C_B_L_C_.py,sha256=YXlwovoCHYx8THLQD9iBU_VGoaB9LFObEKtL6ddD320,520 +fontTools/ttLib/tables/C_F_F_.py,sha256=yg3mUtYBudgmpG7Bz475j_DNnCelsgrTsM8DH1uR4ek,1978 +fontTools/ttLib/tables/C_F_F__2.py,sha256=YoHfJQdF-ezx4OwRQ2Y2O7rRJEPjOkf3Hx5Y11Xq0AM,807 +fontTools/ttLib/tables/C_O_L_R_.py,sha256=SHwFVNVmoUQR2e87KuTSe-J9LfeegS4f2hEpee29_2o,5993 +fontTools/ttLib/tables/C_P_A_L_.py,sha256=odFjqM4GnjXyQYGEC-e0Gvqms1jQ5zHHG3SDg7y-BI0,11942 +fontTools/ttLib/tables/D_S_I_G_.py,sha256=ahBwKMgJf9hPm3ETuF1IvG4d1_UlSW0UdzO85DibOck,5903 +fontTools/ttLib/tables/D__e_b_g.py,sha256=KDnfkNOUnm3F13wD_j3YNBOvYadZ40Gf_0170hFkJp0,1134 +fontTools/ttLib/tables/DefaultTable.py,sha256=lg5XvObsbNvtFCLiFBSVLtJm1e_ngs9Xh9np5b3nteM,1986 +fontTools/ttLib/tables/E_B_D_T_.py,sha256=HTpvinGivpFtRKmn6fS0aiXLPAi8SDWh4l0b-ELin6A,33713 +fontTools/ttLib/tables/E_B_L_C_.py,sha256=VGYnFRhCzqkBsu5LS1rK1l6bNTYupGSHKUsDnBDTI2Q,30047 +fontTools/ttLib/tables/E_B_S_C_.py,sha256=NTL49pDjYW74XncueM_cAcN5D4ZuSzFXIpQ30X3P97o,5810 +fontTools/ttLib/tables/F_F_T_M_.py,sha256=_450vdbEH7Y-0_rOwb3Q0hg-Qq2W8C_sHljy7rZtqqM,1683 +fontTools/ttLib/tables/F__e_a_t.py,sha256=1uSEIC6xSaFimotJ6TNw256ROMKAccmsO28ABzLlY_c,5935 +fontTools/ttLib/tables/G_D_E_F_.py,sha256=QXiILFCRnPNZcwpub6ojN5S9WP6y56LsXi25pUWLgp4,299 +fontTools/ttLib/tables/G_P_O_S_.py,sha256=UkP3mlnyvQg-jj6ZBOh6j-OieVg_goJQ31nlLvoLGSI,397 +fontTools/ttLib/tables/G_S_U_B_.py,sha256=cwFMKO-pgwsn1H8Q9Jb58Z6ZrBrCoN0sqJB0YunBfSk,294 +fontTools/ttLib/tables/G_V_A_R_.py,sha256=13oO2dD-L4yfkrBuR-KN2rc40wh5lLIlx_khwMz5GH4,94 +fontTools/ttLib/tables/G__l_a_t.py,sha256=a0VRLX98MDFtrkDu9nNu5rv14WAInm9voNLGMtgoIZU,8640 +fontTools/ttLib/tables/G__l_o_c.py,sha256=E_aJgFohOr30U-G8WhzShQJ0hXnQUl4qjcAn4KJ3UZw,2684 +fontTools/ttLib/tables/H_V_A_R_.py,sha256=6kPLDUGT8EussA3y9gKr_mrgY5PNv7YaK1V0keMXD9w,313 +fontTools/ttLib/tables/I_F_T_.py,sha256=d63nXOfLF7WqGrNj99PcLkvLIiCQ3JdZl5Sf9a7ITGk,272 +fontTools/ttLib/tables/I_F_T_X_.py,sha256=5A7KfKBr_7FgtkQV6NT2YS1eGlrWrOnjYrLnG-BGFNY,274 +fontTools/ttLib/tables/J_S_T_F_.py,sha256=Q9TEf3OuyDIxZlmoz9a3c-mDMlJK6YBQ9KcYmiwFRbU,315 +fontTools/ttLib/tables/L_T_S_H_.py,sha256=Iu6syJFuhJj0_7Aan2NPlDuQDIq-AzLwsOQbXVTnlL0,2189 +fontTools/ttLib/tables/M_A_T_H_.py,sha256=-TVu9Nlcs-1shkElbIk-CWtUwXUMdycHFkjvPE8C_fs,342 +fontTools/ttLib/tables/M_V_A_R_.py,sha256=67cEuiTw5y5W1Zk98L_S_SmJINIfy_mzWCkyHcujz94,308 +fontTools/ttLib/tables/O_S_2f_2.py,sha256=50J2qTiIupv-nloNB-QasAlEKdP2gGZi7m4sjtjUkFo,28272 +fontTools/ttLib/tables/S_T_A_T_.py,sha256=y9NiWCtnlZtMjw4K9_SdA84Xa-dJk7G5eb2dSe6ciWc,498 +fontTools/ttLib/tables/S_V_G_.py,sha256=q_FN1PBRWq0Nb-mUd6ZCfQKiXiMOrZboAqJ0fIW477Y,7794 +fontTools/ttLib/tables/S__i_l_f.py,sha256=026WGVz27s7pwDPCs5jKSN7U5zT_hJJAPkGnJd6fM8U,34971 +fontTools/ttLib/tables/S__i_l_l.py,sha256=tzuBa9iUmgPoIsRmpZ_2voEhTI2D5_i3JRowuRaQTBs,3218 +fontTools/ttLib/tables/T_S_I_B_.py,sha256=zp74PDjXZrLsNLf7uqClPe91uQKV5hEldHLfsNrSCkk,340 +fontTools/ttLib/tables/T_S_I_C_.py,sha256=qNBNaEdOqFUPMttRT7Ui69iCRYL393u5CaZgqtu1k40,380 +fontTools/ttLib/tables/T_S_I_D_.py,sha256=6truKJ4gm5rRUgPHt9ju8ToEILdi_GC_TC3RKs57FUM,340 +fontTools/ttLib/tables/T_S_I_J_.py,sha256=LSetu90n9MaLDwARXFbqBHhE-yigjJUpifAsYMHmS4c,340 +fontTools/ttLib/tables/T_S_I_P_.py,sha256=tjgSl86wp48RCg7tjJChFnMGdhesnmjcs3CVUYEB0PA,340 +fontTools/ttLib/tables/T_S_I_S_.py,sha256=6oLVJ4nt1LKUTG1lvrKVHp8mDSEdmKV4AFs6ZKqSo_s,340 +fontTools/ttLib/tables/T_S_I_V_.py,sha256=llz3d-MyMHV0KL3jijLDxZXLNIkJDCmGB977Z3uEArM,854 +fontTools/ttLib/tables/T_S_I__0.py,sha256=O-2oI0eBgt4mP15-UwH0_0r7YWi3EEEhG-4etqDueGI,2505 +fontTools/ttLib/tables/T_S_I__1.py,sha256=Cy6jq1s9KfT-eFF7sv1GB5zwuLWI11bVrPCoOnBFsf8,6970 +fontTools/ttLib/tables/T_S_I__2.py,sha256=D73GQ8x9qsJ1SOEK6g1m2vPV4pzlvSdBHPfd6hHXBIc,495 +fontTools/ttLib/tables/T_S_I__3.py,sha256=wQMM9eyhJmH6rYXS2KTOKbNL16BC8L9LMJ23quRyh5Y,542 +fontTools/ttLib/tables/T_S_I__5.py,sha256=hhvJn6jiXs8kuBtun8krNUTXTljH-eKxaxXM1T-7SXM,1905 +fontTools/ttLib/tables/T_T_F_A_.py,sha256=LuT0w__AMtawnsBMobhEMW9gp2yk0mA5ZRzwF45c0UI,392 +fontTools/ttLib/tables/TupleVariation.py,sha256=WYn4GnnTl3oqW6sau58XtWEOImqy06BeY13WmEzpI5A,32195 +fontTools/ttLib/tables/V_A_R_C_.py,sha256=3jFX50J6X-Cc4dwwiztKKsDTRXVHTXlVdQH328UN1-k,289 +fontTools/ttLib/tables/V_D_M_X_.py,sha256=RbHl7vvO9pcjT_kKvcCmcByQj39n4PmVeq55wD5C14g,10437 +fontTools/ttLib/tables/V_O_R_G_.py,sha256=Cn3OxjVtcO-Uvp61P5c2336V9iEbuGr6vWAXnSIaihk,5965 +fontTools/ttLib/tables/V_V_A_R_.py,sha256=Cstw6tc_U4-EmTriRItBSpvTJODAjMFQjfyTaxLzsbI,319 +fontTools/ttLib/tables/__init__.py,sha256=cQY82WQc19PsqssRsD-XjbHD-5ogG00DdrBWjgfbD-M,2730 +fontTools/ttLib/tables/__pycache__/B_A_S_E_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/BitmapGlyphMetrics.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/C_B_D_T_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/C_B_L_C_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/C_F_F_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/C_F_F__2.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/C_O_L_R_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/C_P_A_L_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/D_S_I_G_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/D__e_b_g.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/DefaultTable.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/E_B_D_T_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/E_B_L_C_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/E_B_S_C_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/F_F_T_M_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/F__e_a_t.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/G_D_E_F_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/G_P_O_S_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/G_S_U_B_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/G_V_A_R_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/G__l_a_t.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/G__l_o_c.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/H_V_A_R_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/I_F_T_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/I_F_T_X_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/J_S_T_F_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/L_T_S_H_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/M_A_T_H_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/M_V_A_R_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/O_S_2f_2.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/S_T_A_T_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/S_V_G_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/S__i_l_f.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/S__i_l_l.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_S_I_B_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_S_I_C_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_S_I_D_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_S_I_J_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_S_I_P_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_S_I_S_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_S_I_V_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_S_I__0.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_S_I__1.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_S_I__2.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_S_I__3.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_S_I__5.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/T_T_F_A_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/TupleVariation.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/V_A_R_C_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/V_D_M_X_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/V_O_R_G_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/V_V_A_R_.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/__init__.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_a_n_k_r.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_a_v_a_r.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_b_d_a_t.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_b_g_c_l.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_b_h_e_d.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_b_l_o_c.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_b_s_l_n.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_c_i_d_g.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_c_m_a_p.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_c_v_a_r.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_c_v_t.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_f_e_a_t.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_f_p_g_m.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_f_v_a_r.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_g_a_s_p.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_g_c_i_d.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_g_l_y_f.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_g_v_a_r.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_h_d_m_x.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_h_e_a_d.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_h_h_e_a.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_h_m_t_x.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_k_e_r_n.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_l_c_a_r.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_l_o_c_a.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_l_t_a_g.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_m_a_x_p.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_m_e_t_a.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_m_o_r_t.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_m_o_r_x.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_n_a_m_e.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_o_p_b_d.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_p_o_s_t.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_p_r_e_p.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_p_r_o_p.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_s_b_i_x.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_t_r_a_k.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_v_h_e_a.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/_v_m_t_x.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/asciiTable.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/grUtils.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/otBase.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/otConverters.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/otData.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/otDataSchema.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/otTables.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/otTraverse.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/sbixGlyph.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/sbixStrike.cpython-312.pyc,, +fontTools/ttLib/tables/__pycache__/ttProgram.cpython-312.pyc,, +fontTools/ttLib/tables/_a_n_k_r.py,sha256=MpAzIifmIi_3gx2oP6PC3R2lu36Ewsr2-W1rXjsz2Ug,483 +fontTools/ttLib/tables/_a_v_a_r.py,sha256=qHDLREWNLcWAa4DPU2tiz0gQJkHUT8u7MjiYfUD3dkU,9018 +fontTools/ttLib/tables/_b_d_a_t.py,sha256=u30aVomJ32qSl2WABu9Vro7QvsZG2-Et0zUY-tD2rUw,124 +fontTools/ttLib/tables/_b_g_c_l.py,sha256=e8-vrpQlyh2CBnIRIYAK9xcMtWXdXr0i1Gmz13eTOsk,5484 +fontTools/ttLib/tables/_b_h_e_d.py,sha256=6TMTmG_Z2IB5tEiBOrsJWrgf-OvXfcpkVQusObgLVPY,108 +fontTools/ttLib/tables/_b_l_o_c.py,sha256=KnFPzSLKyAIG-BPrqqxphe8IEujDJ6XbCszQ5eJsm-g,127 +fontTools/ttLib/tables/_b_s_l_n.py,sha256=_848o7SQqztzBDfHYei-80u9ltxIHVBzXu1dYHLV57M,465 +fontTools/ttLib/tables/_c_i_d_g.py,sha256=yt8rVIadpJSDUCoVH4dZetNiy0Azm5ESAxHjB2BX_eA,913 +fontTools/ttLib/tables/_c_m_a_p.py,sha256=0JBEgo9RHzRASlcwVkWGGlyLfsIvcms53cWpzsVkhVQ,66330 +fontTools/ttLib/tables/_c_v_a_r.py,sha256=2FG9emFPOJgKBQV_TEVGVQt5C5WavTBO8PGMqxQfkZs,3526 +fontTools/ttLib/tables/_c_v_t.py,sha256=1_RhEcTmhWQWQp7Hsj8UsByKmXCIppZyIbIArGywEEM,1618 +fontTools/ttLib/tables/_f_e_a_t.py,sha256=Fi1XnjhkCG0tp43AcvpIaivD-YRFpufo6feGIrenQDo,469 +fontTools/ttLib/tables/_f_p_g_m.py,sha256=uZHZzqL6OdLn_Hxskv-xf3XuE4fyaSv_jbALEjwXYug,1633 +fontTools/ttLib/tables/_f_v_a_r.py,sha256=QfsZS-sVVNE68jf76TDAqCRVufMV8IwaBJYi9FM761U,8807 +fontTools/ttLib/tables/_g_a_s_p.py,sha256=C9yR9465DZqMIowHClQWU136qP0VZLD0_H1HweeXmRg,2202 +fontTools/ttLib/tables/_g_c_i_d.py,sha256=AJ4uV7PTHbnsw4Tfw8c2Ezh0VMox3oAH0qhhq7y8hdM,362 +fontTools/ttLib/tables/_g_l_y_f.py,sha256=gVMfLBdNSZPrqj6yUMylODYdKmUUeGLv6LNgL6hxWKE,86445 +fontTools/ttLib/tables/_g_v_a_r.py,sha256=E9WCKjeITUfd5hcJLQ0rjQFBtZdxw1eswFlWp1U6bD4,12196 +fontTools/ttLib/tables/_h_d_m_x.py,sha256=wMrO4D04QNT8u30p8AV-aG3bndXCq4wlPNvtbd8ip7c,4252 +fontTools/ttLib/tables/_h_e_a_d.py,sha256=WVNlQDJv21qhYnijZFPMxvya0966Sp4W3yzLADQv-KQ,4925 +fontTools/ttLib/tables/_h_h_e_a.py,sha256=6xB0L4sJiz6hg9JSDhNPxF3RuppVgNF0utfsM3K6bGU,4766 +fontTools/ttLib/tables/_h_m_t_x.py,sha256=l5w8-BmFoH1lmJrpTpO2J6hqaS-0xi0QZMtjwXss5O4,6191 +fontTools/ttLib/tables/_k_e_r_n.py,sha256=jMFBba5OwcsaokRg4DVevRtTiUVDiBm_qWhZpyDatSo,10793 +fontTools/ttLib/tables/_l_c_a_r.py,sha256=8W6xFOj-sm003MCXX4bIHxs9ntfVvT0FXYllPxa3z4I,390 +fontTools/ttLib/tables/_l_o_c_a.py,sha256=e4MyDF5sJSB9fNw269vhLXlBgCDZx_C1vboZ5l_l_ME,2179 +fontTools/ttLib/tables/_l_t_a_g.py,sha256=9YpApjI-rZ4e3HeT8Pj-osiHl3uALD9JXg5O7pqk9L0,2552 +fontTools/ttLib/tables/_m_a_x_p.py,sha256=cIDIZWse9czwwsnlxIh3qwgwaXbt7PQAjXKAcmMDspY,5264 +fontTools/ttLib/tables/_m_e_t_a.py,sha256=A0CZPEAVxYrpytjXUGQJCTddwG8KrvUVbtBe3A1MqgI,3913 +fontTools/ttLib/tables/_m_o_r_t.py,sha256=u35tYqn3cjzKxeCF0FUFeLtaf36mjDDSN08uuk0Kme8,487 +fontTools/ttLib/tables/_m_o_r_x.py,sha256=OwamVpIO7REDnFr95HuFPoY_0U6i9zQPb11K1sFTvDY,548 +fontTools/ttLib/tables/_n_a_m_e.py,sha256=PwUZSLTvLHIuHR7sLzpOI0yd7JMBpq0EYchFK9A4bY4,41265 +fontTools/ttLib/tables/_o_p_b_d.py,sha256=TNZv_2YTrj4dGzd6wA9Jb-KGZ99un177s5p3LlfxQ74,448 +fontTools/ttLib/tables/_p_o_s_t.py,sha256=9siVXSisWGdTfj_mC1E9dUDz9Jdm1i3QzI-l3i3VWME,11671 +fontTools/ttLib/tables/_p_r_e_p.py,sha256=CcKr4HrswkupLmbJdrJLTM-z9XgLefQyv8467j9V0zs,427 +fontTools/ttLib/tables/_p_r_o_p.py,sha256=Eg8x5qWyXDzPezMafFu0s0qyPDHj-sPsFxGtE6h29qo,427 +fontTools/ttLib/tables/_s_b_i_x.py,sha256=iqHmmw6KGX_goin_EXem2UgH1LDMPXtGrqNn-nyADQM,4864 +fontTools/ttLib/tables/_t_r_a_k.py,sha256=itWRHfjzTiaqnvfrWFmCS_eWcRLeZVJCTxDJwaf6UOM,11349 +fontTools/ttLib/tables/_v_h_e_a.py,sha256=U-uudUbFQHGfiXVeUNu9urltM7anzMfKULlwdfjfET8,4458 +fontTools/ttLib/tables/_v_m_t_x.py,sha256=AUuxtyQvMWrTBNbOIaL6uKcB_DNpNb0YX28JIuTHw_Y,500 +fontTools/ttLib/tables/asciiTable.py,sha256=4c69jsAirUnDEpylf9CYBoCKTzwbmfbtUAOrtPnpHjY,637 +fontTools/ttLib/tables/grUtils.py,sha256=hcOJ5oJPOd2uJWnWA7qwR7AfL37YZ5zUT7g8o5BBV80,2270 +fontTools/ttLib/tables/otBase.py,sha256=Cje7tkdabZ8fowzz1dXrBcSOtRdpBgvpAq5tQBUKkXA,53237 +fontTools/ttLib/tables/otConverters.py,sha256=UoUxKeiQqKcJPeBpcv_U64pzz-4epyHqymg8Kjd34hA,113137 +fontTools/ttLib/tables/otData.py,sha256=5pBSszZRkn4ZpQA3NwyKSxYUOg5obW_JpmVIz_FhnYA,203941 +fontTools/ttLib/tables/otDataSchema.py,sha256=JWAnyuhMTfT2satixLYsL8ci0jvWArQqOM3D_9Y1gqA,1667 +fontTools/ttLib/tables/otTables.py,sha256=IEkFcn0ri9UKCG91TzMoNYlKgqCDuFQpYFU9MFS6CB4,100458 +fontTools/ttLib/tables/otTraverse.py,sha256=rTRpB_FIpKG-VU5R9vM3YtGCgc3CUcZ5DcGLftq96ds,5517 +fontTools/ttLib/tables/sbixGlyph.py,sha256=gkFQPWpbkOBV0TooGrkkeD1GtA617CmMb-5nlXRyZ80,5795 +fontTools/ttLib/tables/sbixStrike.py,sha256=dL8O9K8R4S6RVQDP-PVjIPBrvbqbE9zwra0uRL0nLq0,6651 +fontTools/ttLib/tables/table_API_readme.txt,sha256=eZlRTLUkLzc_9Ot3pdfhyMb3ahU0_Iipx0vSbzOVGy8,2748 +fontTools/ttLib/tables/ttProgram.py,sha256=a4PIAm8kPkn8v1vfx00bfoQfkp551ilyCEJ4tMLpWGE,36009 +fontTools/ttLib/ttCollection.py,sha256=1IBOj8WOdstkEP9EYHMnQgAW61mf9GiEUvmjXa7-okM,7314 +fontTools/ttLib/ttFont.py,sha256=Ab7VC-VnMHqEzU8MGeElFOdGaJUB9veqzdwE7e61kHk,64058 +fontTools/ttLib/ttGlyphSet.py,sha256=cUBhMGa5hszeVqOm2KpOdeJh-LsiqE7RNdyIUPZ2vO8,17476 +fontTools/ttLib/ttVisitor.py,sha256=_tah4C42Tv6Pm9QeLNQwwVCxqI4VNEAqYCbmThp6cvY,1025 +fontTools/ttLib/woff2.py,sha256=P34AKMkkrTHWEW640lOHDtDeif7CTll7l-nQavB0ONg,60920 +fontTools/ttx.py,sha256=wwhLqjrNWQJRqKxU1ZeXHpjwxjPxxNAJ6TWvjZj0n5c,17276 +fontTools/ufoLib/__init__.py,sha256=chTCZoHcVj85nXt66BIcr4BrxgeFTQHVSq_HOkRQKQs,98982 +fontTools/ufoLib/__pycache__/__init__.cpython-312.pyc,, +fontTools/ufoLib/__pycache__/converters.cpython-312.pyc,, +fontTools/ufoLib/__pycache__/errors.cpython-312.pyc,, +fontTools/ufoLib/__pycache__/etree.cpython-312.pyc,, +fontTools/ufoLib/__pycache__/filenames.cpython-312.pyc,, +fontTools/ufoLib/__pycache__/glifLib.cpython-312.pyc,, +fontTools/ufoLib/__pycache__/kerning.cpython-312.pyc,, +fontTools/ufoLib/__pycache__/plistlib.cpython-312.pyc,, +fontTools/ufoLib/__pycache__/pointPen.cpython-312.pyc,, +fontTools/ufoLib/__pycache__/utils.cpython-312.pyc,, +fontTools/ufoLib/__pycache__/validators.cpython-312.pyc,, +fontTools/ufoLib/converters.py,sha256=YnBKr8kmyjwLcq8LdD46ubGOgyL9Pxt9avlvZn9anKI,13444 +fontTools/ufoLib/errors.py,sha256=aMWgyjiZfWYcNY6RFLgN5eHbXp9xyyVgXrkFSTMCSdI,843 +fontTools/ufoLib/etree.py,sha256=T3sjLTgjMAq6VyYRicWPaMIVBJ2YSuwZxV6Vc5yZtQI,231 +fontTools/ufoLib/filenames.py,sha256=hoyUhzzQMDaeckT7UdreISANq4-gLR2jGyk5yAyYtOA,10654 +fontTools/ufoLib/glifLib.py,sha256=VBbz67ece59g_re8GxtEWDP3zh6Fqsf3lmFXr7zxDoA,77495 +fontTools/ufoLib/kerning.py,sha256=uNYs_-tNUguebF_c7ih160-H1zl1KEtmQmylWbWrpM8,6176 +fontTools/ufoLib/plistlib.py,sha256=jzMGOGvHO6XvS-IO8hS04ur7r8-v2dnVq-vKMoJZvqQ,1510 +fontTools/ufoLib/pointPen.py,sha256=CuREcm3IYteZNBDAd_ZRAV4XqBsy0s07jdWc4en9r-8,244 +fontTools/ufoLib/utils.py,sha256=nZoJJqHXQSL-LXYE58_WHA97XlbTkEbYkdH3GL32SmQ,3192 +fontTools/ufoLib/validators.py,sha256=Il9qYYVj9Po51_IGVGmeVE2SXf77pFccgJpVLkgAFKk,31991 +fontTools/unicode.py,sha256=ZZ7OMmWvIyV1IL1k6ioTzaRAh3tUvm6gvK7QgFbOIHY,1237 +fontTools/unicodedata/Blocks.py,sha256=frShN07WqD1uLt-V0TNlUZPnn0-cKc0Nuhtd2uNDoSw,33139 +fontTools/unicodedata/Mirrored.py,sha256=kdhwCWOWaArmfNkDah0Thv-67M9wWz45R5IMPhqyzFM,9242 +fontTools/unicodedata/OTTags.py,sha256=wOPpbMsNcp_gdvPFeITtgVMnTN8TJSNAsVEdu_nuPXE,1196 +fontTools/unicodedata/ScriptExtensions.py,sha256=udL53Wdd5n-ZFEVHeIC0LpKKBqPHD2WqRiBbzXs2U7U,28647 +fontTools/unicodedata/Scripts.py,sha256=wBD6SElfM3w-u6JcgyNsyofXPvqW1e4YltgeHE4XaOc,131148 +fontTools/unicodedata/__init__.py,sha256=IP6X4GhzO2zO-n3kc_4BIiAmo4wdJyZ9NEINv4yQIx8,9084 +fontTools/unicodedata/__pycache__/Blocks.cpython-312.pyc,, +fontTools/unicodedata/__pycache__/Mirrored.cpython-312.pyc,, +fontTools/unicodedata/__pycache__/OTTags.cpython-312.pyc,, +fontTools/unicodedata/__pycache__/ScriptExtensions.cpython-312.pyc,, +fontTools/unicodedata/__pycache__/Scripts.cpython-312.pyc,, +fontTools/unicodedata/__pycache__/__init__.cpython-312.pyc,, +fontTools/varLib/__init__.py,sha256=Uiss5-SbfkISvMU9W0ck5Gef6OcGpJR-Xtjb6jaAjB0,56768 +fontTools/varLib/__main__.py,sha256=B7JO5wnfG5XQiXqWQmWJhvVIq5a-Cf6OPxyP7Bx0mXk,94 +fontTools/varLib/__pycache__/__init__.cpython-312.pyc,, +fontTools/varLib/__pycache__/__main__.cpython-312.pyc,, +fontTools/varLib/__pycache__/avarPlanner.cpython-312.pyc,, +fontTools/varLib/__pycache__/builder.cpython-312.pyc,, +fontTools/varLib/__pycache__/cff.cpython-312.pyc,, +fontTools/varLib/__pycache__/errors.cpython-312.pyc,, +fontTools/varLib/__pycache__/featureVars.cpython-312.pyc,, +fontTools/varLib/__pycache__/hvar.cpython-312.pyc,, +fontTools/varLib/__pycache__/interpolatable.cpython-312.pyc,, +fontTools/varLib/__pycache__/interpolatableHelpers.cpython-312.pyc,, +fontTools/varLib/__pycache__/interpolatablePlot.cpython-312.pyc,, +fontTools/varLib/__pycache__/interpolatableTestContourOrder.cpython-312.pyc,, +fontTools/varLib/__pycache__/interpolatableTestStartingPoint.cpython-312.pyc,, +fontTools/varLib/__pycache__/interpolate_layout.cpython-312.pyc,, +fontTools/varLib/__pycache__/iup.cpython-312.pyc,, +fontTools/varLib/__pycache__/merger.cpython-312.pyc,, +fontTools/varLib/__pycache__/models.cpython-312.pyc,, +fontTools/varLib/__pycache__/multiVarStore.cpython-312.pyc,, +fontTools/varLib/__pycache__/mutator.cpython-312.pyc,, +fontTools/varLib/__pycache__/mvar.cpython-312.pyc,, +fontTools/varLib/__pycache__/plot.cpython-312.pyc,, +fontTools/varLib/__pycache__/stat.cpython-312.pyc,, +fontTools/varLib/__pycache__/varStore.cpython-312.pyc,, +fontTools/varLib/avar/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fontTools/varLib/avar/__main__.py,sha256=ew1fJpg81GpYbdkrp4I7ntWdbhkDeg5fNn1SrpF254k,1770 +fontTools/varLib/avar/__pycache__/__init__.cpython-312.pyc,, +fontTools/varLib/avar/__pycache__/__main__.cpython-312.pyc,, +fontTools/varLib/avar/__pycache__/build.cpython-312.pyc,, +fontTools/varLib/avar/__pycache__/map.cpython-312.pyc,, +fontTools/varLib/avar/__pycache__/plan.cpython-312.pyc,, +fontTools/varLib/avar/__pycache__/unbuild.cpython-312.pyc,, +fontTools/varLib/avar/build.py,sha256=g0rlRT1HqVFv7pIzY0MN8phqZhEuJ0YO2S-mauW4frA,2089 +fontTools/varLib/avar/map.py,sha256=dtCkJ7dP6Cvav8pyO3GJIaXq9OIPuSdyaRgWCmKeFag,3482 +fontTools/varLib/avar/plan.py,sha256=qDKZjQq6OfeXBr3T3DZnrmauyMm5ek0rm5YVosAO_UA,27354 +fontTools/varLib/avar/unbuild.py,sha256=Es_D9yiqp-ib-5bxfxCsZF9Jq7f60eb2aVfx-Eepv10,10517 +fontTools/varLib/avarPlanner.py,sha256=CabG5xB57FMdwmN1acpVMvyOucVPxCdRdJSK2gu7gb4,109 +fontTools/varLib/builder.py,sha256=mSKOCcnnw-WzmZs15FayoqCDh77Ts7o9Tre9psh8CUc,6609 +fontTools/varLib/cff.py,sha256=A5aEWkeI9D8YJs31l2TVAKr3RwjR18aJP9Pt3XONMBc,22900 +fontTools/varLib/errors.py,sha256=dMo8eGj76I7H4hrBEiNbYrGs2J1K1SwdsUyTHpkVOrQ,6934 +fontTools/varLib/featureVars.py,sha256=kp4gPjKyyGRu7yBWxgd1N4OkKnU9V45QwiWSHs6OWd0,26180 +fontTools/varLib/hvar.py,sha256=1IvL5BneTkg8jJYicH0TSQViB6D0vBEesLdlfqoLBX4,3695 +fontTools/varLib/instancer/__init__.py,sha256=uLh4toV1hJFn9K7DzBU6WeXwwVRx6Xio4bRf3Ic_Am0,116907 +fontTools/varLib/instancer/__main__.py,sha256=zfULwcP01FhplS1IlcMgNQnLxk5RVfmOuinWjqeid-g,104 +fontTools/varLib/instancer/__pycache__/__init__.cpython-312.pyc,, +fontTools/varLib/instancer/__pycache__/__main__.cpython-312.pyc,, +fontTools/varLib/instancer/__pycache__/featureVars.cpython-312.pyc,, +fontTools/varLib/instancer/__pycache__/names.cpython-312.pyc,, +fontTools/varLib/instancer/__pycache__/solver.cpython-312.pyc,, +fontTools/varLib/instancer/featureVars.py,sha256=X262-OXjyPTkeYubzQ17emMH158DJ7EvkAexy8J8Rlk,7109 +fontTools/varLib/instancer/names.py,sha256=IPRqel_M8zVU0jl30WsfgufxUm9PBBQDQCY3VHapeHc,14950 +fontTools/varLib/instancer/solver.py,sha256=uMePwX0BVT5F94kUvDglsI4_F0nEH67F7RFuJ6tQwQ0,11002 +fontTools/varLib/interpolatable.py,sha256=VSYUOIXvHhFnw1WbZSlNrA52vWFgMxagqxwqObctg-8,45380 +fontTools/varLib/interpolatableHelpers.py,sha256=9EZUwcgXLeKAn_mPA2E5mCqWkpXREB71a5efsmzyk9o,10286 +fontTools/varLib/interpolatablePlot.py,sha256=14AMcuUIrgQItBfeWlAP6FFFtmvoh97Hwjicj1Fj5KA,44272 +fontTools/varLib/interpolatableTestContourOrder.py,sha256=xIPmAKLDq_5wtI9hDtYRbprfNT9Bj-uaQmklBth8Xh0,2970 +fontTools/varLib/interpolatableTestStartingPoint.py,sha256=WrV4VzmL6YmaLmThXrMd_U9A1dlzStV-AqkamIRNh24,4364 +fontTools/varLib/interpolate_layout.py,sha256=22VjGZuV2YiAe2MpdTf0xPVz1x2G84bcOL0vOeBpGQM,3689 +fontTools/varLib/iup.c,sha256=UeEWkagpCWfiC32EDbb-1NiiX40xamoFx__yeOEomtk,1013553 +fontTools/varLib/iup.cpython-312-x86_64-linux-gnu.so,sha256=GZAq3-vazafYbHdKpcDYv3yKqeYmguuAmBIZmTQWzWs,1944232 +fontTools/varLib/iup.py,sha256=29Asdn2sUxd7BTe_AveeczmJp1M0XE_lwwrxVmtC_2s,14983 +fontTools/varLib/merger.py,sha256=9jTtEO5Z8pmm8SJ0U57hFJBsXhyt3YAAjviHhWSbMb0,60818 +fontTools/varLib/models.py,sha256=huON6bFmJj4Vm7r9bljs5SRzuFTRp1oPiag_mq9DNDY,22909 +fontTools/varLib/multiVarStore.py,sha256=wo7Gw5Cv2qtbIhMbHqA5FlArPmSRJ0bTkR1zsQKoR8E,9404 +fontTools/varLib/mutator.py,sha256=CTenFX8onpdoYbe2H2Ie5CTZQ2PcrFPb_EXeyJpGNdg,19803 +fontTools/varLib/mvar.py,sha256=LTV77vH_3Ecg_qKBO5xQzjLOlJir_ppEr7mPVZRgad8,2449 +fontTools/varLib/plot.py,sha256=NoSZkJ5ndxNcDvJIvd5pQ9_jX6X1oM1K2G_tR4sdPVs,7494 +fontTools/varLib/stat.py,sha256=XuNKKZxGlBrl4OGFDAwVXhpBwJi23U3BdHmNTKoJnvE,4811 +fontTools/varLib/varStore.py,sha256=cIqIgzJyqWMbjUUlvTdBD_VxtuhnS2jFX7g_KQlPjFA,32419 +fontTools/voltLib/__init__.py,sha256=ZZ1AsTx1VlDn40Kupce-fM3meOWugy3RZraBW9LG-9M,151 +fontTools/voltLib/__main__.py,sha256=uVtABLzMeHtvKL8zetf4rpC4aB8BkYr5QLSegNjZZZI,5928 +fontTools/voltLib/__pycache__/__init__.cpython-312.pyc,, +fontTools/voltLib/__pycache__/__main__.cpython-312.pyc,, +fontTools/voltLib/__pycache__/ast.cpython-312.pyc,, +fontTools/voltLib/__pycache__/error.cpython-312.pyc,, +fontTools/voltLib/__pycache__/lexer.cpython-312.pyc,, +fontTools/voltLib/__pycache__/parser.cpython-312.pyc,, +fontTools/voltLib/__pycache__/voltToFea.cpython-312.pyc,, +fontTools/voltLib/ast.py,sha256=arA9W3Gqo6OqljwNNKnMAojz-C5LStbC5SgjJh7buKk,13300 +fontTools/voltLib/error.py,sha256=phcQOQj-xOspCXu9hBJQRhSOBDzxHRgZd3fWQOFNJzw,395 +fontTools/voltLib/lexer.py,sha256=OvuETOSvlS6v7iCVeJ3IdH2Cg71n3OJoEyiB3-h6vhE,3368 +fontTools/voltLib/parser.py,sha256=rkw2IHBZPsrhGVC7Kw7V501m0u52kh1JSM5HXp-xchM,25396 +fontTools/voltLib/voltToFea.py,sha256=Z2yvnaZLQXzPLT86Uta0zRsXIYgj6NnvZtSWt5xmw2s,36549 +fonttools-4.65.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +fonttools-4.65.0.dist-info/METADATA,sha256=dnx3LfX-xCRjHki6oTz6VUmPTXvptB0QcbNL9SzCj6g,125002 +fonttools-4.65.0.dist-info/RECORD,, +fonttools-4.65.0.dist-info/WHEEL,sha256=H-JolGg8H9-hAjBqklOSOKzErb6-vI48SxW3EjdGE44,151 +fonttools-4.65.0.dist-info/entry_points.txt,sha256=8kVHddxfFWA44FSD4mBpmC-4uCynQnkoz_9aNJb227Y,147 +fonttools-4.65.0.dist-info/licenses/LICENSE,sha256=Z4cgj4P2Wcy8IiOy_elS_6b36KymLxqKK_W8UbsbI4M,1072 +fonttools-4.65.0.dist-info/licenses/LICENSE.external,sha256=lKg6ruBymg8wLTSsxKzsvZ1YNm8mJCkHX-VX5KVLLmk,20022 +fonttools-4.65.0.dist-info/top_level.txt,sha256=rRgRylrXzekqWOsrhygzib12pQ7WILf7UGjqEwkIFDM,10 diff --git a/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..4fc5f783f722f866b6c81c180dc403d06663fe99 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (84.0.0) +Root-Is-Purelib: false +Tag: cp312-cp312-manylinux_2_17_x86_64 +Tag: cp312-cp312-manylinux2014_x86_64 + diff --git a/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..87ae781f169a63f0cf672a9050474035bfa5add4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/entry_points.txt @@ -0,0 +1,5 @@ +[console_scripts] +fonttools = fontTools.__main__:main +pyftmerge = fontTools.merge:main +pyftsubset = fontTools.subset:main +ttx = fontTools.ttx:main diff --git a/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..cc633905d333c4b42c1a0c8b34e9f734adeb6e1e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Just van Rossum + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/licenses/LICENSE.external b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/licenses/LICENSE.external new file mode 100644 index 0000000000000000000000000000000000000000..5c45052f870940119ee6bc2b51ab3a7bc43d01d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/licenses/LICENSE.external @@ -0,0 +1,388 @@ +FontTools includes the following font projects for testing purposes, which are +under SIL Open Font License, Version 1.1: + +Lobster + Copyright (c) 2010, Pablo Impallari (www.impallari.com|impallari@gmail.com), + with Reserved Font Name Lobster. + This Font Software is licensed under the SIL Open Font License, Version 1.1. + +Noto Fonts + This Font Software is licensed under the SIL Open Font License, Version 1.1. + +XITS font project + Copyright (c) 2001-2010 by the STI Pub Companies, consisting of the American + Institute of Physics, the American Chemical Society, the American + Mathematical Society, the American Physical Society, Elsevier, Inc., and The + Institute of Electrical and Electronic Engineers, Inc. (www.stixfonts.org), + with Reserved Font Name STIX Fonts, STIX Fonts (TM) is a trademark of The + Institute of Electrical and Electronics Engineers, Inc. + + Portions copyright (c) 1998-2003 by MicroPress, Inc. + (www.micropress-inc.com), with Reserved Font Name TM Math. To obtain + additional mathematical fonts, please contact MicroPress, Inc., 68-30 Harrow + Street, Forest Hills, NY 11375, USA, Phone: (718) 575-1816. + + Portions copyright (c) 1990 by Elsevier, Inc. + + This Font Software is licensed under the SIL Open Font License, Version 1.1. + +Iosevka + Copyright (c) 2015-2020 Belleve Invis (belleve@typeof.net). + This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +===== + +FontTools includes Adobe AGL & AGLFN, which is under 3-clauses BSD license: + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +Neither the name of Adobe Systems Incorporated nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +===== + +FontTools includes cu2qu, which is Copyright 2016 Google Inc. All Rights Reserved. +Licensed under the Apache License, Version 2.0, a copy of which is reproduced below: + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +===== + +FontTools includes code in `fontTools.misc.filesystem` which is derived from: + +PyFilesystem2 (i.e. the `fs` package) by Will McGugan +Licensed under the MIT License +https://github.com/PyFilesystem/pyfilesystem2 + +Copyright (c) 2017-2021 The PyFilesystem2 contributors +Copyright (c) 2016-2019 Will McGugan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..9af65ba39d292309497df4accdc44bd6f8143d10 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fonttools-4.65.0.dist-info/top_level.txt @@ -0,0 +1 @@ +fontTools diff --git a/.venv/lib/python3.12/site-packages/fsspec/__init__.py b/.venv/lib/python3.12/site-packages/fsspec/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5de87eda16630e55f6a48eae3e145515c167d9cb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fsspec/__init__.py @@ -0,0 +1,75 @@ +from . import caching +from .callbacks import Callback +from .compression import available_compressions +from .core import get_fs_token_paths, open, open_files, open_local, url_to_fs +from .exceptions import FSTimeoutError +from .mapping import FSMap, get_mapper +from .registry import ( + available_protocols, + filesystem, + get_filesystem_class, + register_implementation, + registry, +) +from .spec import AbstractFileSystem + +try: + from ._version import __version__ # noqa: F401 +except ImportError: + __version__ = "unknown" + +__all__ = [ + "AbstractFileSystem", + "FSTimeoutError", + "FSMap", + "filesystem", + "register_implementation", + "get_filesystem_class", + "get_fs_token_paths", + "get_mapper", + "open", + "open_files", + "open_local", + "registry", + "caching", + "Callback", + "available_protocols", + "available_compressions", + "url_to_fs", +] + + +def process_entries(): + try: + from importlib.metadata import entry_points + except ImportError: + return + if entry_points is not None: + try: + eps = entry_points() + except TypeError: + pass # importlib-metadata < 0.8 + else: + if hasattr(eps, "select"): # Python 3.10+ / importlib_metadata >= 3.9.0 + specs = eps.select(group="fsspec.specs") + else: + specs = eps.get("fsspec.specs", []) + registered_names = {} + for spec in specs: + err_msg = f"Unable to load filesystem from {spec}" + name = spec.name + if name in registered_names: + continue + registered_names[name] = True + register_implementation( + name, + spec.value.replace(":", "."), + errtxt=err_msg, + # We take our implementations as the ones to overload with if + # for some reason we encounter some, may be the same, already + # registered + clobber=True, + ) + + +process_entries() diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..133b7c94f83c14068d63b27d231d6138f2dde87a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/_version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/_version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c57b16417d42dbc9c2b23bcdafb8a75ee7fced0a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/_version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/archive.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/archive.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32872b2d72f6a946af0b5ae7e62e1331819613c6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/archive.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/asyn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/asyn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f087cd58ea19073357e1c8152934bd48ca0fbb16 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/asyn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/caching.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/caching.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5a0245e0caaf4a9664b06f153ab4c9b2768958f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/caching.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/callbacks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/callbacks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b77dcbe16883303efb722090f5e9de8618d2e43e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/callbacks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/compression.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/compression.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc43bed99a49ec4c491bb30a3a7df0b5a75ca80c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/compression.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bf8b6b77304950862522d70dda44cd62d05c2c6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/conftest.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/conftest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9a454f59db4d4eb86981957f72c09668cb7ccab Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/conftest.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e328b92930634c37be648b1f22967c00cd6088c3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/dircache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/dircache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f71b0361c90d1ec8793538ba14b3e425e8bd8446 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/dircache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/exceptions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83ff4afc45be5dc2e65a5377078f575b90bacc11 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/exceptions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/fuse.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/fuse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae9b14c7adc6251140cde0ccfed8fd6b217e0314 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/fuse.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/generic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/generic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32e75ed3e9a4820309bc080fbb373135c0d5c38e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/generic.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/gui.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/gui.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..715cd2509bd4e742838089068f1f27a83fd71275 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/gui.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/json.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/json.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41d006658bfe7779608b12d27df11f9a653c4390 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/json.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/mapping.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/mapping.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9bdbe7d26881e84dc1dac05f18506ad50f6bf9b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/mapping.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/parquet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/parquet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b6f16d4641ccdaae8cb715c293933400a38301f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/parquet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/registry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13e82942f549341ca498bef9be07e9393710c229 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/registry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/spec.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/spec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b86b74813516061d38d54434415c8319dfb8048 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/spec.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/transaction.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/transaction.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1aee94c5cc831d7b537879beb390c34fbbecb81f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/transaction.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85b0276e6f78871a84829e5bb2efb227b8fdf51d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/fsspec/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/fsspec/_version.py b/.venv/lib/python3.12/site-packages/fsspec/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..64642af9bccd08c5c0c2193d1702d36418b25349 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fsspec/_version.py @@ -0,0 +1,24 @@ +# file generated by vcs-versioning +# don't change, don't track in version control +from __future__ import annotations + +__all__ = [ + "__version__", + "__version_tuple__", + "version", + "version_tuple", + "__commit_id__", + "commit_id", +] + +version: str +__version__: str +__version_tuple__: tuple[int | str, ...] +version_tuple: tuple[int | str, ...] +commit_id: str | None +__commit_id__: str | None + +__version__ = version = '2026.7.0' +__version_tuple__ = version_tuple = (2026, 7, 0) + +__commit_id__ = commit_id = None diff --git a/.venv/lib/python3.12/site-packages/fsspec/archive.py b/.venv/lib/python3.12/site-packages/fsspec/archive.py new file mode 100644 index 0000000000000000000000000000000000000000..13a4da8df7c9405297cdd7d37476be2f725b2f57 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fsspec/archive.py @@ -0,0 +1,75 @@ +import operator + +from fsspec import AbstractFileSystem +from fsspec.utils import tokenize + + +class AbstractArchiveFileSystem(AbstractFileSystem): + """ + A generic superclass for implementing Archive-based filesystems. + + Currently, it is shared amongst + :class:`~fsspec.implementations.zip.ZipFileSystem`, + :class:`~fsspec.implementations.libarchive.LibArchiveFileSystem` and + :class:`~fsspec.implementations.tar.TarFileSystem`. + """ + + def __str__(self): + return f"" + + __repr__ = __str__ + + def ukey(self, path): + return tokenize(path, self.fo, self.protocol) + + def _all_dirnames(self, paths): + """Returns *all* directory names for each path in paths, including intermediate + ones. + + Parameters + ---------- + paths: Iterable of path strings + """ + if len(paths) == 0: + return set() + + dirnames = {self._parent(path) for path in paths} - {self.root_marker} + return dirnames | self._all_dirnames(dirnames) + + def info(self, path, **kwargs): + self._get_dirs() + path = self._strip_protocol(path) + if path in {"", "/"} and self.dir_cache: + return {"name": "", "type": "directory", "size": 0} + if path in self.dir_cache: + return self.dir_cache[path] + elif path + "/" in self.dir_cache: + return self.dir_cache[path + "/"] + else: + raise FileNotFoundError(path) + + def ls(self, path, detail=True, **kwargs): + self._get_dirs() + paths = {} + for p, f in self.dir_cache.items(): + p = p.rstrip("/") + if "/" in p: + root = p.rsplit("/", 1)[0] + else: + root = "" + if root == path.rstrip("/"): + paths[p] = f + elif all( + (a == b) + for a, b in zip(path.split("/"), [""] + p.strip("/").split("/")) + ): + # root directory entry + ppath = p.rstrip("/").split("/", 1)[0] + if ppath not in paths: + out = {"name": ppath, "size": 0, "type": "directory"} + paths[ppath] = out + if detail: + out = sorted(paths.values(), key=operator.itemgetter("name")) + return out + else: + return sorted(paths) diff --git a/.venv/lib/python3.12/site-packages/fsspec/asyn.py b/.venv/lib/python3.12/site-packages/fsspec/asyn.py new file mode 100644 index 0000000000000000000000000000000000000000..32ad3d35d132355feb5989c3c999599392a56ea5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/fsspec/asyn.py @@ -0,0 +1,1171 @@ +import asyncio +import asyncio.events +import functools +import inspect +import io +import numbers +import os +import re +import threading +from collections.abc import Iterable +from glob import has_magic +from typing import TYPE_CHECKING + +from .callbacks import DEFAULT_CALLBACK +from .exceptions import FSTimeoutError +from .implementations.local import LocalFileSystem, make_path_posix, trailing_sep +from .spec import AbstractBufferedFile, AbstractFileSystem +from .utils import glob_translate, is_exception, other_paths + +private = re.compile("_[^_]") +iothread = [None] # dedicated fsspec IO thread +loop = [None] # global event loop for any non-async instance +_lock = None # global lock placeholder +get_running_loop = asyncio.get_running_loop + + +def get_lock(): + """Allocate or return a threading lock. + + The lock is allocated on first use to allow setting one lock per forked process. + """ + global _lock + if not _lock: + _lock = threading.Lock() + return _lock + + +def reset_lock(): + """Reset the global lock. + + This should be called only on the init of a forked process to reset the lock to + None, enabling the new forked process to get a new lock. + """ + global _lock + + iothread[0] = None + loop[0] = None + _lock = None + + +async def _runner(event, coro, result, timeout=None): + timeout = timeout if timeout else None # convert 0 or 0.0 to None + if timeout is not None: + coro = asyncio.wait_for(coro, timeout=timeout) + try: + result[0] = await coro + except Exception as ex: + result[0] = ex + finally: + event.set() + + +def sync(loop, func, *args, timeout=None, **kwargs): + """ + Make loop run coroutine until it returns. Runs in other thread + + Examples + -------- + >>> fsspec.asyn.sync(fsspec.asyn.get_loop(), func, *args, + timeout=timeout, **kwargs) + """ + timeout = timeout if timeout else None # convert 0 or 0.0 to None + # NB: if the loop is not running *yet*, it is OK to submit work + # and we will wait for it + if loop is None or loop.is_closed(): + raise RuntimeError("Loop is not running") + try: + loop0 = asyncio.events.get_running_loop() + if loop0 is loop: + raise NotImplementedError("Calling sync() from within a running loop") + except NotImplementedError: + raise + except RuntimeError: + pass + coro = func(*args, **kwargs) + result = [None] + event = threading.Event() + asyncio.run_coroutine_threadsafe(_runner(event, coro, result, timeout), loop) + while True: + # this loops allows thread to get interrupted + if event.wait(1): + break + if timeout is not None: + timeout -= 1 + if timeout < 0: + raise FSTimeoutError + + return_result = result[0] + if isinstance(return_result, asyncio.TimeoutError): + # suppress asyncio.TimeoutError, raise FSTimeoutError + raise FSTimeoutError from return_result + elif isinstance(return_result, BaseException): + raise return_result + else: + return return_result + + +def sync_wrapper(func, obj=None): + """Given a function, make so can be called in blocking contexts + + Leave obj=None if defining within a class. Pass the instance if attaching + as an attribute of the instance. + """ + + @functools.wraps(func) + def wrapper(*args, **kwargs): + self = obj or args[0] + return sync(self.loop, func, *args, **kwargs) + + return wrapper + + +def async_gen_wrapper(func, obj=None): + """Given a async generator, make so can be called in blocking contexts""" + + @functools.wraps(func) + def wrapper(*args, **kwargs): + self = obj or args[0] + gen = func(*args, **kwargs) + while True: + try: + yield sync(self.loop, gen.__anext__) + except StopAsyncIteration: + break + + return wrapper + + +def get_loop(): + """Create or return the default fsspec IO loop + + The loop will be running on a separate thread. + """ + if loop[0] is None: + with get_lock(): + # repeat the check just in case the loop got filled between the + # previous two calls from another thread + if loop[0] is None: + loop[0] = asyncio.new_event_loop() + th = threading.Thread(target=loop[0].run_forever, name="fsspecIO") + th.daemon = True + th.start() + iothread[0] = th + return loop[0] + + +def reset_after_fork(): + global lock + loop[0] = None + iothread[0] = None + lock = None + + +if hasattr(os, "register_at_fork"): + # should be posix; this will do nothing for spawn or forkserver subprocesses + os.register_at_fork(after_in_child=reset_after_fork) + + +if TYPE_CHECKING: + import resource + + ResourceError = resource.error +else: + try: + import resource + except ImportError: + resource = None + ResourceError = OSError + else: + ResourceError = getattr(resource, "error", OSError) + +_DEFAULT_BATCH_SIZE = 128 +_NOFILES_DEFAULT_BATCH_SIZE = 1280 + + +def _get_batch_size(nofiles=False): + from fsspec.config import conf + + if nofiles: + if "nofiles_gather_batch_size" in conf: + return conf["nofiles_gather_batch_size"] + else: + if "gather_batch_size" in conf: + return conf["gather_batch_size"] + if nofiles: + return _NOFILES_DEFAULT_BATCH_SIZE + if resource is None: + return _DEFAULT_BATCH_SIZE + + try: + soft_limit, _ = resource.getrlimit(resource.RLIMIT_NOFILE) + except (ImportError, ValueError, ResourceError): + return _DEFAULT_BATCH_SIZE + + if soft_limit == resource.RLIM_INFINITY: + return -1 + else: + return soft_limit // 8 + + +def running_async() -> bool: + """Being executed by an event loop?""" + try: + asyncio.get_running_loop() + return True + except RuntimeError: + return False + + +async def _run_coros_in_chunks( + coros, + batch_size=None, + callback=DEFAULT_CALLBACK, + timeout=None, + return_exceptions=False, + nofiles=False, +): + """Run the given coroutines in chunks. + + Parameters + ---------- + coros: list of coroutines to run + batch_size: int or None + Number of coroutines to submit/wait on simultaneously. + If -1, then it will not be any throttling. If + None, it will be inferred from _get_batch_size() + callback: fsspec.callbacks.Callback instance + Gets a relative_update when each coroutine completes + timeout: number or None + If given, each coroutine times out after this time. Note that, since + there are multiple batches, the total run time of this function will in + general be longer + return_exceptions: bool + Same meaning as in asyncio.gather + nofiles: bool + If inferring the batch_size, does this operation involve local files? + If yes, you normally expect smaller batches. + """ + + if batch_size is None: + batch_size = _get_batch_size(nofiles=nofiles) + + if batch_size == -1: + batch_size = len(coros) + elif batch_size <= 0: + raise ValueError + + async def _run_coro(coro, i): + try: + return await asyncio.wait_for(coro, timeout=timeout), i + except Exception as e: + if not return_exceptions: + raise + return e, i + finally: + callback.relative_update(1) + + i = 0 + n = len(coros) + results = [None] * n + pending = set() + + while pending or i < n: + while len(pending) < batch_size and i < n: + pending.add(asyncio.ensure_future(_run_coro(coros[i], i))) + i += 1 + + if not pending: + break + + done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) + first_exc = None + while done: + task = done.pop() + try: + result, k = await task + results[k] = result + except Exception as exc: + if first_exc is None: + first_exc = exc + + if first_exc is not None: + for task in pending: + task.cancel() + if pending: + await asyncio.gather(*pending, return_exceptions=True) + raise first_exc + + return results + + +# these methods should be implemented as async by any async-able backend +async_methods = [ + "_ls", + "_cat_file", + "_get_file", + "_put_file", + "_rm_file", + "_cp_file", + "_pipe_file", + "_expand_path", + "_info", + "_isfile", + "_isdir", + "_exists", + "_walk", + "_glob", + "_find", + "_du", + "_size", + "_mkdir", + "_makedirs", +] + + +class AsyncFileSystem(AbstractFileSystem): + """Async file operations, default implementations + + Passes bulk operations to asyncio.gather for concurrent operation. + + Implementations that have concurrent batch operations and/or async methods + should inherit from this class instead of AbstractFileSystem. Docstrings are + copied from the un-underscored method in AbstractFileSystem, if not given. + """ + + # note that methods do not have docstring here; they will be copied + # for _* methods and inferred for overridden methods. + + async_impl = True + mirror_sync_methods = True + disable_throttling = False + + def __init__(self, *args, asynchronous=False, loop=None, batch_size=None, **kwargs): + self.asynchronous = asynchronous + self._pid = os.getpid() + if not asynchronous: + self._loop = loop or get_loop() + else: + self._loop = None + self.batch_size = batch_size + super().__init__(*args, **kwargs) + + @property + def loop(self): + if self._pid != os.getpid(): + raise RuntimeError("This class is not fork-safe") + return self._loop + + async def _rm_file(self, path, **kwargs): + if ( + inspect.iscoroutinefunction(self._rm) + and type(self)._rm is not AsyncFileSystem._rm + ): + return await self._rm(path, recursive=False, batch_size=1, **kwargs) + raise NotImplementedError + + async def _rm(self, path, recursive=False, batch_size=None, **kwargs): + # TODO: implement on_error + batch_size = batch_size or self.batch_size + path = await self._expand_path(path, recursive=recursive) + return await _run_coros_in_chunks( + [self._rm_file(p, **kwargs) for p in reversed(path)], + batch_size=batch_size, + nofiles=True, + ) + + async def _cp_file(self, path1, path2, **kwargs): + raise NotImplementedError + + async def _mv_file(self, path1, path2): + await self._cp_file(path1, path2) + await self._rm_file(path1) + + async def _copy( + self, + path1, + path2, + recursive=False, + on_error=None, + maxdepth=None, + batch_size=None, + **kwargs, + ): + if on_error is None and recursive: + on_error = "ignore" + elif on_error is None: + on_error = "raise" + + if isinstance(path1, list) and isinstance(path2, list): + # No need to expand paths when both source and destination + # are provided as lists + paths1 = path1 + paths2 = path2 + else: + source_is_str = isinstance(path1, str) + paths1 = await self._expand_path( + path1, maxdepth=maxdepth, recursive=recursive + ) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + paths1 = [ + p for p in paths1 if not (trailing_sep(p) or await self._isdir(p)) + ] + if not paths1: + return + + source_is_file = len(paths1) == 1 + dest_is_dir = isinstance(path2, str) and ( + trailing_sep(path2) or await self._isdir(path2) + ) + + exists = source_is_str and ( + (has_magic(path1) and source_is_file) + or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1)) + ) + paths2 = other_paths( + paths1, + path2, + exists=exists, + flatten=not source_is_str, + ) + + batch_size = batch_size or self.batch_size + coros = [self._cp_file(p1, p2, **kwargs) for p1, p2 in zip(paths1, paths2)] + result = await _run_coros_in_chunks( + coros, batch_size=batch_size, return_exceptions=True, nofiles=True + ) + + for ex in filter(is_exception, result): + if on_error == "ignore" and isinstance(ex, FileNotFoundError): + continue + raise ex + + async def _pipe_file(self, path, value, mode="overwrite", **kwargs): + raise NotImplementedError + + async def _pipe(self, path, value=None, batch_size=None, **kwargs): + if isinstance(path, str): + path = {path: value} + batch_size = batch_size or self.batch_size + return await _run_coros_in_chunks( + [self._pipe_file(k, v, **kwargs) for k, v in path.items()], + batch_size=batch_size, + nofiles=True, + ) + + async def _process_limits(self, url, start, end): + """Helper for "Range"-based _cat_file""" + size = None + suff = False + if start is not None and start < 0: + # if start is negative and end None, end is the "suffix length" + if end is None: + end = -start + start = "" + suff = True + else: + size = size or (await self._info(url))["size"] + start = size + start + elif start is None: + start = 0 + if not suff: + if end is not None and end < 0: + if start is not None: + size = size or (await self._info(url))["size"] + end = size + end + elif end is None: + end = "" + if isinstance(end, numbers.Integral): + end -= 1 # bytes range is inclusive + return f"bytes={start}-{end}" + + async def _cat_file(self, path, start=None, end=None, **kwargs): + raise NotImplementedError + + async def _cat( + self, path, recursive=False, on_error="raise", batch_size=None, **kwargs + ): + paths = await self._expand_path(path, recursive=recursive) + coros = [self._cat_file(path, **kwargs) for path in paths] + batch_size = batch_size or self.batch_size + out = await _run_coros_in_chunks( + coros, batch_size=batch_size, nofiles=True, return_exceptions=True + ) + if on_error == "raise": + ex = next(filter(is_exception, out), False) + if ex: + raise ex + if ( + len(paths) > 1 + or isinstance(path, list) + or paths[0] != self._strip_protocol(path) + ): + return { + k: v + for k, v in zip(paths, out) + if on_error != "omit" or not is_exception(v) + } + else: + return out[0] + + async def _cat_ranges( + self, + paths, + starts, + ends, + max_gap=None, + batch_size=None, + on_error="return", + **kwargs, + ): + """Get the contents of byte ranges from one or more files + + Parameters + ---------- + paths: list + A list of of filepaths on this filesystems + starts, ends: int or list + Bytes limits of the read. If using a single int, the same value will be + used to read all the specified files. + on_error: "return" or "raise" + If "return" (default), any per-range exception is placed in the output + list at the corresponding position. Otherwise the first such exception + is raised. Matches ``AbstractFileSystem.cat_ranges``. + """ + if max_gap is not None: + # use utils.merge_offset_ranges + raise NotImplementedError + if not isinstance(paths, list): + raise TypeError + if not isinstance(starts, Iterable): + starts = [starts] * len(paths) + if not isinstance(ends, Iterable): + ends = [ends] * len(paths) + if len(starts) != len(paths) or len(ends) != len(paths): + raise ValueError + coros = [ + self._cat_file(p, start=s, end=e, **kwargs) + for p, s, e in zip(paths, starts, ends) + ] + batch_size = batch_size or self.batch_size + out = await _run_coros_in_chunks( + coros, batch_size=batch_size, nofiles=True, return_exceptions=True + ) + if on_error != "return": + ex = next(filter(is_exception, out), None) + if ex is not None: + raise ex + return out + + async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs): + raise NotImplementedError + + async def _put( + self, + lpath, + rpath, + recursive=False, + callback=DEFAULT_CALLBACK, + batch_size=None, + maxdepth=None, + **kwargs, + ): + """Copy file(s) from local. + + Copies a specific file or tree of files (if recursive=True). If rpath + ends with a "/", it will be assumed to be a directory, and target files + will go within. + + The put_file method will be called concurrently on a batch of files. The + batch_size option can configure the amount of futures that can be executed + at the same time. If it is -1, then all the files will be uploaded concurrently. + The default can be set for this instance by passing "batch_size" in the + constructor, or for all instances by setting the "gather_batch_size" key + in ``fsspec.config.conf``, falling back to 1/8th of the system limit . + """ + if isinstance(lpath, list) and isinstance(rpath, list): + # No need to expand paths when both source and destination + # are provided as lists + rpaths = rpath + lpaths = lpath + else: + source_is_str = isinstance(lpath, str) + if source_is_str: + lpath = make_path_posix(lpath) + fs = LocalFileSystem() + lpaths = fs.expand_path(lpath, recursive=recursive, maxdepth=maxdepth) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))] + if not lpaths: + return + + source_is_file = len(lpaths) == 1 + dest_is_dir = isinstance(rpath, str) and ( + trailing_sep(rpath) or await self._isdir(rpath) + ) + + rpath = self._strip_protocol(rpath) + exists = source_is_str and ( + (has_magic(lpath) and source_is_file) + or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath)) + ) + rpaths = other_paths( + lpaths, + rpath, + exists=exists, + flatten=not source_is_str, + ) + + is_dir = {l: os.path.isdir(l) for l in lpaths} + rdirs = [r for l, r in zip(lpaths, rpaths) if is_dir[l]] + file_pairs = [(l, r) for l, r in zip(lpaths, rpaths) if not is_dir[l]] + + await asyncio.gather(*[self._makedirs(d, exist_ok=True) for d in rdirs]) + batch_size = batch_size or self.batch_size + + coros = [] + callback.set_size(len(file_pairs)) + for lfile, rfile in file_pairs: + put_file = callback.branch_coro(self._put_file) + coros.append(put_file(lfile, rfile, **kwargs)) + + return await _run_coros_in_chunks( + coros, batch_size=batch_size, callback=callback + ) + + async def _get_file(self, rpath, lpath, **kwargs): + raise NotImplementedError + + async def _get( + self, + rpath, + lpath, + recursive=False, + callback=DEFAULT_CALLBACK, + maxdepth=None, + **kwargs, + ): + """Copy file(s) to local. + + Copies a specific file or tree of files (if recursive=True). If lpath + ends with a "/", it will be assumed to be a directory, and target files + will go within. Can submit a list of paths, which may be glob-patterns + and will be expanded. + + The get_file method will be called concurrently on a batch of files. The + batch_size option can configure the amount of futures that can be executed + at the same time. If it is -1, then all the files will be uploaded concurrently. + The default can be set for this instance by passing "batch_size" in the + constructor, or for all instances by setting the "gather_batch_size" key + in ``fsspec.config.conf``, falling back to 1/8th of the system limit . + """ + if isinstance(lpath, list) and isinstance(rpath, list): + # No need to expand paths when both source and destination + # are provided as lists + rpaths = rpath + lpaths = lpath + else: + source_is_str = isinstance(rpath, str) + # First check for rpath trailing slash as _strip_protocol removes it. + source_not_trailing_sep = source_is_str and not trailing_sep(rpath) + rpath = self._strip_protocol(rpath) + rpaths = await self._expand_path( + rpath, recursive=recursive, maxdepth=maxdepth + ) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + rpaths = [ + p for p in rpaths if not (trailing_sep(p) or await self._isdir(p)) + ] + if not rpaths: + return + + lpath = make_path_posix(lpath) + source_is_file = len(rpaths) == 1 + dest_is_dir = isinstance(lpath, str) and ( + trailing_sep(lpath) or LocalFileSystem().isdir(lpath) + ) + + exists = source_is_str and ( + (has_magic(rpath) and source_is_file) + or (not has_magic(rpath) and dest_is_dir and source_not_trailing_sep) + ) + lpaths = other_paths( + rpaths, + lpath, + exists=exists, + flatten=not source_is_str, + ) + + [os.makedirs(os.path.dirname(lp), exist_ok=True) for lp in lpaths] + batch_size = kwargs.pop("batch_size", self.batch_size) + + coros = [] + callback.set_size(len(lpaths)) + for lpath, rpath in zip(lpaths, rpaths): + get_file = callback.branch_coro(self._get_file) + coros.append(get_file(rpath, lpath, **kwargs)) + return await _run_coros_in_chunks( + coros, batch_size=batch_size, callback=callback + ) + + async def _isfile(self, path): + try: + return (await self._info(path))["type"] == "file" + except: # noqa: E722 + return False + + async def _isdir(self, path): + try: + return (await self._info(path))["type"] == "directory" + except OSError: + return False + + async def _size(self, path): + return (await self._info(path)).get("size", None) + + async def _sizes(self, paths, batch_size=None): + batch_size = batch_size or self.batch_size + return await _run_coros_in_chunks( + [self._size(p) for p in paths], batch_size=batch_size + ) + + async def _exists(self, path, **kwargs): + try: + await self._info(path, **kwargs) + return True + except FileNotFoundError: + return False + + async def _info(self, path, **kwargs): + raise NotImplementedError + + async def _ls(self, path, detail=True, **kwargs): + raise NotImplementedError + + async def _walk(self, path, maxdepth=None, topdown=True, on_error="omit", **kwargs): + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + path = self._strip_protocol(path) + full_dirs = {} + dirs = {} + files = {} + + detail = kwargs.pop("detail", False) + try: + listing = await self._ls(path, detail=True, **kwargs) + except (FileNotFoundError, OSError) as e: + if on_error == "raise": + raise + elif callable(on_error): + on_error(e) + if detail: + yield path, {}, {} + else: + yield path, [], [] + return + + for info in listing: + # each info name must be at least [path]/part , but here + # we check also for names like [path]/part/ + pathname = info["name"].rstrip("/") + name = pathname.rsplit("/", 1)[-1] + if info["type"] == "directory" and pathname != path: + # do not include "self" path + full_dirs[name] = pathname + dirs[name] = info + elif pathname == path: + # file-like with same name as give path + files[""] = info + else: + files[name] = info + + if not detail: + dirs = list(dirs) + files = list(files) + + if topdown: + # Yield before recursion if walking top down + yield path, dirs, files + + if maxdepth is not None: + maxdepth -= 1 + if maxdepth < 1: + if not topdown: + yield path, dirs, files + return + + for d in dirs: + async for _ in self._walk( + full_dirs[d], + maxdepth=maxdepth, + detail=detail, + topdown=topdown, + **kwargs, + ): + yield _ + + if not topdown: + # Yield after recursion if walking bottom up + yield path, dirs, files + + async def _glob(self, path, maxdepth=None, **kwargs): + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + import re + + seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,) + ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash + path = self._strip_protocol(path) + append_slash_to_dirname = ends_with_sep or path.endswith( + tuple(sep + "**" for sep in seps) + ) + idx_star = path.find("*") if path.find("*") >= 0 else len(path) + idx_qmark = path.find("?") if path.find("?") >= 0 else len(path) + idx_brace = path.find("[") if path.find("[") >= 0 else len(path) + + min_idx = min(idx_star, idx_qmark, idx_brace) + + detail = kwargs.pop("detail", False) + withdirs = kwargs.pop("withdirs", True) + + if not has_magic(path): + if await self._exists(path, **kwargs): + if not detail: + return [path] + else: + return {path: await self._info(path, **kwargs)} + else: + if not detail: + return [] # glob of non-existent returns empty + else: + return {} + elif "/" in path[:min_idx]: + first_wildcard_idx = min_idx + min_idx = path[:min_idx].rindex("/") + root = path[ + : min_idx + 1 + ] # everything up to the last / before the first wildcard + prefix = path[ + min_idx + 1 : first_wildcard_idx + ] # stem between last "/" and first wildcard + depth = path[min_idx + 1 :].count("/") + 1 + else: + root = "" + prefix = path[:min_idx] # stem up to the first wildcard + depth = path[min_idx + 1 :].count("/") + 1 + + if "**" in path: + if maxdepth is not None: + idx_double_stars = path.find("**") + depth_double_stars = path[idx_double_stars:].count("/") + 1 + depth = depth - depth_double_stars + maxdepth + else: + depth = None + + # Pass the filename stem as prefix= so backends that support it such as + # gcsfs, s3fs and adlfs can filter server-side up to the first wildcard. + if prefix: + kwargs["prefix"] = prefix + allpaths = await self._find( + root, maxdepth=depth, withdirs=withdirs, detail=True, **kwargs + ) + + pattern = glob_translate(path + ("/" if ends_with_sep else "")) + pattern = re.compile(pattern) + + out = { + p: info + for p, info in sorted(allpaths.items()) + if pattern.match( + p + "/" + if append_slash_to_dirname and info["type"] == "directory" + else p + ) + } + + if detail: + return out + else: + return list(out) + + async def _du(self, path, total=True, maxdepth=None, **kwargs): + sizes = {} + # async for? + for f in await self._find(path, maxdepth=maxdepth, **kwargs): + info = await self._info(f) + sizes[info["name"]] = info["size"] + if total: + return sum(sizes.values()) + else: + return sizes + + async def _find(self, path, maxdepth=None, withdirs=False, **kwargs): + path = self._strip_protocol(path) + out = {} + detail = kwargs.pop("detail", False) + + # Add the root directory if withdirs is requested + # This is needed for posix glob compliance + if withdirs and path != "" and await self._isdir(path): + out[path] = await self._info(path) + + # async for? + async for _, dirs, files in self._walk(path, maxdepth, detail=True, **kwargs): + if withdirs: + files.update(dirs) + out.update({info["name"]: info for name, info in files.items()}) + if not out and (await self._isfile(path)): + # walk works on directories, but find should also return [path] + # when path happens to be a file + out[path] = {} + names = sorted(out) + if not detail: + return names + else: + return {name: out[name] for name in names} + + async def _expand_path( + self, path, recursive=False, maxdepth=None, assume_literal=False + ): + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + if isinstance(path, str): + out = await self._expand_path([path], recursive, maxdepth) + else: + out = set() + path = [self._strip_protocol(p) for p in path] + for p in path: # can gather here + if not assume_literal and has_magic(p): + bit = set(await self._glob(p, maxdepth=maxdepth)) + out |= bit + if recursive: + # glob call above expanded one depth so if maxdepth is defined + # then decrement it in expand_path call below. If it is zero + # after decrementing then avoid expand_path call. + if maxdepth is not None and maxdepth <= 1: + continue + out |= set( + await self._expand_path( + list(bit), + recursive=recursive, + maxdepth=maxdepth - 1 if maxdepth is not None else None, + assume_literal=True, + ) + ) + continue + elif recursive: + rec = set(await self._find(p, maxdepth=maxdepth, withdirs=True)) + out |= rec + if p not in out and (recursive is False or (await self._exists(p))): + # should only check once, for the root + out.add(p) + if not out: + raise FileNotFoundError(path) + return sorted(out) + + async def _mkdir(self, path, create_parents=True, **kwargs): + pass # not necessary to implement, may not have directories + + async def _makedirs(self, path, exist_ok=False): + pass # not necessary to implement, may not have directories + + async def open_async(self, path, mode="rb", **kwargs): + if "b" not in mode or kwargs.get("compression"): + raise ValueError + raise NotImplementedError + + +def mirror_sync_methods(obj): + """Populate sync and async methods for obj + + For each method will create a sync version if the name refers to an async method + (coroutine) and there is no override in the child class; will create an async + method for the corresponding sync method if there is no implementation. + + Uses the methods specified in + - async_methods: the set that an implementation is expected to provide + - default_async_methods: that can be derived from their sync version in + AbstractFileSystem + - AsyncFileSystem: async-specific default coroutines + """ + from fsspec import AbstractFileSystem + + for method in set(async_methods + dir(AsyncFileSystem)): + if not method.startswith("_"): + continue + smethod = method[1:] + if private.match(method): + isco = inspect.iscoroutinefunction(getattr(obj, method, None)) + unsync = getattr(getattr(obj, smethod, False), "__func__", None) + is_default = unsync is getattr(AbstractFileSystem, smethod, "") + if isco and is_default: + mth = sync_wrapper(getattr(obj, method), obj=obj) + elif inspect.isasyncgenfunction(getattr(obj, method, None)) and is_default: + mth = async_gen_wrapper(getattr(obj, method), obj=obj) + else: + continue + setattr(obj, smethod, mth) + if not mth.__doc__: + mth.__doc__ = getattr( + getattr(AbstractFileSystem, smethod, None), "__doc__", "" + ) + + +class FSSpecCoroutineCancel(Exception): + pass + + +def _dump_running_tasks( + printout=True, cancel=True, exc=FSSpecCoroutineCancel, with_task=False +): + import traceback + + tasks = [t for t in asyncio.tasks.all_tasks(loop[0]) if not t.done()] + if printout: + [task.print_stack() for task in tasks] + out = [ + { + "locals": task._coro.cr_frame.f_locals, + "file": task._coro.cr_frame.f_code.co_filename, + "firstline": task._coro.cr_frame.f_code.co_firstlineno, + "linelo": task._coro.cr_frame.f_lineno, + "stack": traceback.format_stack(task._coro.cr_frame), + "task": task if with_task else None, + } + for task in tasks + ] + if cancel: + for t in tasks: + cbs = t._callbacks + t.cancel() + asyncio.futures.Future.set_exception(t, exc) + asyncio.futures.Future.cancel(t) + [cb[0](t) for cb in cbs] # cancels any dependent concurrent.futures + try: + t._coro.throw(exc) # exits coro, unless explicitly handled + except exc: + pass + return out + + +class AbstractAsyncStreamedFile(AbstractBufferedFile): + # no read buffering, and always auto-commit + # TODO: readahead might still be useful here, but needs async version + + async def read(self, length=-1): + """ + Return data from cache, or fetch pieces as necessary + + Parameters + ---------- + length: int (-1) + Number of bytes to read; if <0, all remaining bytes. + """ + length = -1 if length is None else int(length) + if self.mode != "rb": + raise ValueError("File not in read mode") + if length < 0: + length = self.size - self.loc + if self.closed: + raise ValueError("I/O operation on closed file.") + if length == 0: + # don't even bother calling fetch + return b"" + out = await self._fetch_range(self.loc, self.loc + length) + self.loc += len(out) + return out + + async def write(self, data): + """ + Write data to buffer. + + Buffer only sent on flush() or if buffer is greater than + or equal to blocksize. + + Parameters + ---------- + data: bytes + Set of bytes to be written. + """ + if self.mode not in {"wb", "ab"}: + raise ValueError("File not in write mode") + if self.closed: + raise ValueError("I/O operation on closed file.") + if self.forced: + raise ValueError("This file has been force-flushed, can only close") + out = self.buffer.write(data) + self.loc += out + if self.buffer.tell() >= self.blocksize: + await self.flush() + return out + + async def close(self): + """Close file + + Finalizes writes, discards cache + """ + if getattr(self, "_unclosable", False): + return + if self.closed: + return + if self.mode == "rb": + self.cache = None + else: + if not self.forced: + await self.flush(force=True) + + if self.fs is not None: + self.fs.invalidate_cache(self.path) + self.fs.invalidate_cache(self.fs._parent(self.path)) + + self.closed = True + + async def flush(self, force=False): + if self.closed: + raise ValueError("Flush on closed file") + if force and self.forced: + raise ValueError("Force flush cannot be called more than once") + if force: + self.forced = True + + if self.mode not in {"wb", "ab"}: + # no-op to flush on read-mode + return + + if not force and self.buffer.tell() < self.blocksize: + # Defer write on small block + return + + if self.offset is None: + # Initialize a multipart upload + self.offset = 0 + try: + await self._initiate_upload() + except: + self.closed = True + raise + + if await self._upload_chunk(final=force) is not False: + self.offset += self.buffer.seek(0, 2) + self.buffer = io.BytesIO() + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + await self.close() + + async def _fetch_range(self, start, end): + raise NotImplementedError + + async def _initiate_upload(self): + pass + + async def _upload_chunk(self, final=False): + raise NotImplementedError