diff --git a/Lib/fontTools/misc/roundTools.py b/Lib/fontTools/misc/roundTools.py index af3e317d2..c1d546f1f 100644 --- a/Lib/fontTools/misc/roundTools.py +++ b/Lib/fontTools/misc/roundTools.py @@ -3,14 +3,21 @@ Various round-to-integer helpers. """ import math +import functools import logging log = logging.getLogger(__name__) __all__ = [ + "noRound", "otRound", + "maybeRound", + "roundFunc", ] +def noRound(value): + return value + def otRound(value): """Round float value to nearest integer towards ``+Infinity``. @@ -34,3 +41,18 @@ def otRound(value): # https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166 return int(math.floor(value + 0.5)) +def maybeRound(v, tolerance, round=otRound): + rounded = round(v) + return rounded if abs(rounded - v) <= tolerance else v + +def roundFunc(tolerance, round=otRound): + if tolerance < 0: + raise ValueError("Rounding tolerance must be positive") + + if tolerance == 0: + return noRound + + if tolerance >= .5: + return round + + return functools.partial(maybeRound, tolerance=tolerance, round=round) diff --git a/Lib/fontTools/pens/t2CharStringPen.py b/Lib/fontTools/pens/t2CharStringPen.py index 8b718ccbc..0fddec1ae 100644 --- a/Lib/fontTools/pens/t2CharStringPen.py +++ b/Lib/fontTools/pens/t2CharStringPen.py @@ -1,29 +1,12 @@ # Copyright (c) 2009 Type Supply LLC # Author: Tal Leming -from fontTools.misc.roundTools import otRound +from fontTools.misc.roundTools import otRound, roundFunc from fontTools.misc.psCharStrings import T2CharString from fontTools.pens.basePen import BasePen from fontTools.cffLib.specializer import specializeCommands, commandsToProgram -def roundFunc(tolerance, round=otRound): - if tolerance < 0: - raise ValueError("Rounding tolerance must be positive") - - if tolerance == 0: - return lambda x: x - - if tolerance >= .5: - return round - - def maybe_round(v): - rounded = round(v) - return rounded if abs(rounded - v) <= tolerance else v - - return maybe_round - - class T2CharStringPen(BasePen): """Pen to draw Type 2 CharStrings. diff --git a/Lib/fontTools/varLib/cff.py b/Lib/fontTools/varLib/cff.py index 6f704bbee..ae14986e5 100644 --- a/Lib/fontTools/varLib/cff.py +++ b/Lib/fontTools/varLib/cff.py @@ -17,8 +17,9 @@ from fontTools.cffLib.specializer import ( from fontTools.ttLib import newTable from fontTools import varLib from fontTools.varLib.models import allEqual +from fontTools.misc.roundTools import roundFunc from fontTools.misc.psCharStrings import T2CharString, T2OutlineExtractor -from fontTools.pens.t2CharStringPen import T2CharStringPen, roundFunc +from fontTools.pens.t2CharStringPen import T2CharStringPen from .errors import VarLibCFFDictMergeError, VarLibCFFPointTypeMergeError, VarLibMergeError