Пример #1
0
def split_slnt(ttfont, out_dir):
    """Use varlib instance to split a variable font if it contains a
    slnt or ital axis."""
    sanityCheckVariableTables(ttfont)

    axes = {a.axisTag: a for a in ttfont['fvar'].axes}
    ital_angle = axes['ital'].maxValue
    roman = instantiateVariableFont(ttfont, {"ital": 0})
    italic = instantiateVariableFont(ttfont, {"ital": ital_angle})

    _update_bits(italic)
    _update_nametable(italic)

    _update_fvar(roman)
    _update_fvar(italic)

    _update_roman_stat(roman)
    _update_italic_stat(italic)

    roman_filename = os.path.join(
        out_dir,
        vf_filename(roman)
    )
    roman.save(roman_filename)
    italic_filename = os.path.join(
        out_dir,
        vf_filename(italic)
    )
    italic.save(italic_filename)
Пример #2
0
def _instance_size(font_file, axis_limits):
    font = _ttFont(font_file)
    if axis_limits:
        try:
            instancer.instantiateVariableFont(font, axis_limits, inplace=True)
        except Exception:
            print('FAILED TO INSTANCE %s at %s' % (font_file, axis_limits))
            print(traceback.print_exc())
            return (-1, -1)
    ttf_sz = len(_save_to_bytes(font).getbuffer())
    font.flavor = 'woff2'
    woff2_sz = len(_save_to_bytes(font).getbuffer())
    return (ttf_sz, woff2_sz)
Пример #3
0
    def makeVarFont(self):
        (minimum, maximum), tag2name = self.findRegularBoldDefaultLocation()
        # check if defautl exist
        otherTags = [
            a.tag for a in self.designSpaceDocument.axes if a.tag != "wght"
        ]
        print("\tLoad {}.designspace".format(self.familyName))
        self.designSpaceDocument.loadSourceFonts(defcon.Font)
        vfont, _, _ = varLib.build(compileInterpolatableTTFsFromDS(
            self.designSpaceDocument,
            featureWriters=[
                KernFeatureWriter(mode="append"),
                MarkFeatureWriter()
            ]),
                                   optimize=False)

        fullfontsFolder = os.path.join(self.dirpath, "fonts/VAR")
        if not os.path.exists(fullfontsFolder):
            os.makedirs(fullfontsFolder)
        path = os.path.join(fullfontsFolder, self.familyName + "-VF.ttf")
        vfont.save(path)
        vfont = TTFont(path)

        tags = {"wght": (minimum, maximum)}
        if len(otherTags) == 0:
            slimft = instancer.instantiateVariableFont(vfont, tags)
        else:
            for t in otherTags:
                tags[t] = None
            slimft = instancer.instantiateVariableFont(vfont, tags)

        for namerecord in slimft['name'].names:
            namerecord.string = namerecord.toUnicode()
            if namerecord.nameID == 3:
                unicID = namerecord.string.split(";")
                newID = "4.444" + ";" + unicID[1] + ";" + unicID[2]
                print("\tTagging the font as a 'slim' one:", newID)
                namerecord.string = newID
            if namerecord.nameID == 5:
                namerecord.string = "Version 4.444"
        print("\tSaving " + self.familyName + "Slim-VF.ttf\n")
        slimFontFolder = os.path.join(fullfontsFolder + "/SlimVF")
        if not os.path.exists(slimFontFolder):
            os.makedirs(slimFontFolder)
        slimft.save(
            os.path.join(slimFontFolder, "%sSlim-VF.ttf" % self.familyName))
Пример #4
0
def test_gen_stat_family_with_uneven_axes(var_fonts3):
    from fontTools.varLib.instancer import instantiateVariableFont
    roman, italic = var_fonts3
    # Drop the width axis from the roman font
    roman = instantiateVariableFont(roman, {"wdth": None})
    # We cannot add STAT tables to these families since the Google Fonts API
    # doesn't support them
    with pytest.raises(ValueError,
                       match="fvar axes are not consistent across the family"):
        gen_stat_tables([roman, italic], axis_order=["wdth", "wght", "ital"])
Пример #5
0
def getInstance2(vf, location=None, dstPath=None, name=None,
        opticalSize=None, styleName=None, cached=True, lazy=True):
    """Answers the VF-TTFont instance at location (created by
    fontTools.varLib.mutator.instantiateVariableFont) packed as Font instance.

    >>> vf = findFont('Amstelvar-Roman-VF')
    >>> instance = getInstance2(vf, opticalSize=8)
    >>> instance
    <Font Amstelvar-Roman-VF-opsz8>
    >>> instance.location
    {'opsz': 8}
    >>> instance['H'].width
    1740
    """
    """
    >>> instance = getInstance2(vf, location=dict(wght=300), cached=False, opticalSize=150)
    >>> instance.location
    {'wght': 300, 'opsz': 150}
    >>> instance['H'].width
    1740
    >>> instance = getInstance2(vf, path='/tmp/TestVariableFontInstance.ttf', opticalSize=8)
    >>> instance
    <Font TestVariableFontInstance>
    """

    if location is None:
        location = {}
    if opticalSize is not None:
        location['opsz'] = opticalSize

    #if path is None and cached:

    # Make a custom file name from the location e.g. VariableFont-wghtXXX-wdthXXX.ttf
    # Only add axis values to the name that are not default.
    instanceName = ""
    for tag, value in sorted(location.items()):
        if value != vf.axes[tag][1]:
            instanceName += "-%s%s" % (tag, asFormatted(value))
    instanceFileName = '.'.join(vf.path.split('/')[-1].split('.')[:-1]) + instanceName + '.ttf'

    targetDirectory = getInstancePath()
    if not os.path.exists(targetDirectory):
        os.makedirs(targetDirectory)
    path = targetDirectory + instanceFileName

    if cached and os.path.exists(path):
        instance = Font(path=path, name=name, location=location, opticalSize=opticalSize)
    else:
        ttFont = instantiateVariableFont(vf.ttFont, location) # Get instance from fontTools
        instance = Font(path=path, ttFont=ttFont, name=name, location=location, opticalSize=opticalSize,
            styleName=styleName, lazy=lazy)
        if instance.path.endswith('.ttf'):
            instance.save()

    return instance
Пример #6
0
def _create_font_for_symbol_wght_name(ttfont: ttLib.TTFont,
                                      symbol_wght_name: str) -> ttLib.TTFont:
    wght_pos = next(v for n, v in _SYMBOL_NAME_FONT_WEIGHTS
                    if n == symbol_wght_name)
    if "fvar" not in ttfont:
        assert ttfont["OS/2"].usWeightClass == wght_pos
        return ttfont

    # None: drop axis, leaving font at default position
    axis_positions = {a.axisTag: None for a in ttfont["fvar"].axes}
    axis_positions["wght"] = wght_pos

    logging.debug("Generating instances at %s", axis_positions)

    return instancer.instantiateVariableFont(ttfont, axis_positions)
Пример #7
0
def gen_static_font(
    var_font, axes, family_name=None, style_name=None, keep_overlaps=False, dst=None
):
    """Generate a GF spec compliant static font from a variable font.

    Args:
        var_font: a variable TTFont instance
        family_name: font family name
        style_name: font style name
        axes: dictionary containing axis positions e.g {"wdth": 100, "wght": 400}
        keep_overlaps: If true, keep glyph overlaps
        dst: Optional. Path to output font

    Returns:
        A TTFont instance or a filepath if an out path has been provided
    """
    if "fvar" not in var_font:
        raise ValueError("Font is not a variable font!")
    if not keep_overlaps:
        keep_overlaps = OverlapMode.REMOVE

    # if the axes dict doesn't include all fvar axes, add default fvar vals to it
    fvar_dflts = {a.axisTag: a.defaultValue for a in var_font["fvar"].axes}
    for k, v in fvar_dflts.items():
        if k not in axes:
            axes[k] = v

    update_style_name = True if not style_name else False
    static_font = instantiateVariableFont(
        var_font, axes, overlap=keep_overlaps, updateFontNames=update_style_name
    )

    if not family_name:
        family_name = font_familyname(static_font)
    if not style_name:
        style_name = font_stylename(static_font)
    # We need to reupdate the name table using our own update function
    # since GF requires axis particles which are not wght or ital to
    # be appended to the family name. See func for more details.
    update_nametable(static_font, family_name, style_name)
    fix_fs_selection(static_font)
    fix_mac_style(static_font)
    static_font["OS/2"].usWidthClass = 5
    if dst:
        static_font.save(dst)
    return static_font
Пример #8
0
def splitFont(
        outputDirectory=f"RecMono{fontOptions['Family Name']}".replace(" ",""),
        newName="Rec Mono",
):

    # access font as TTFont object
    varfont = ttLib.TTFont(fontPath)

    fontFileName = os.path.basename(fontPath)


    outputSubDir = f"fonts/{outputDirectory}"

    for instance in fontOptions["Fonts"]:

        print("\n--------------------------------------------------------------------------------------\n" + instance)

        instanceFont = instancer.instantiateVariableFont(
            varfont,
            {
                "wght": fontOptions["Fonts"][instance]["wght"],
                "CASL": fontOptions["Fonts"][instance]["CASL"],
                "MONO": fontOptions["Fonts"][instance]["MONO"],
                "slnt": fontOptions["Fonts"][instance]["slnt"],
                "CRSV": fontOptions["Fonts"][instance]["CRSV"],
            },
        )

        # UPDATE NAME ID 6, postscript name
        currentPsName = getFontNameID(instanceFont, 6)
        newPsName = (currentPsName\
            .replace("Sans", "")\
            .replace(oldName,newName.replace(" ", "") + fontOptions['Family Name'].replace(" ",""))\
            .replace("LinearLight", instance.replace(" ", "")))
        setFontNameID(instanceFont, 6, newPsName)

        # UPDATE NAME ID 4, full font name
        currentFullName = getFontNameID(instanceFont, 4)
        newFullName = (currentFullName\
            .replace("Sans", "")\
            .replace(oldName, newName + " " + fontOptions['Family Name'])\
            .replace(" Linear Light", instance))\
            .replace(" Regular", "")
        setFontNameID(instanceFont, 4, newFullName)

        # UPDATE NAME ID 3, unique font ID
        currentUniqueName = getFontNameID(instanceFont, 3)
        newUniqueName = (currentUniqueName.replace(currentPsName, newPsName))
        setFontNameID(instanceFont, 3, newUniqueName)

        # ADD name 2, style linking name
        newStyleLinkingName = instance
        setFontNameID(instanceFont, 2, newStyleLinkingName)
        setFontNameID(instanceFont, 17, newStyleLinkingName)

        # UPDATE NAME ID 1, Font Family name
        currentFamName = getFontNameID(instanceFont, 1)
        newFamName = (newFullName.replace(f" {instance}", ""))
        setFontNameID(instanceFont, 1, newFamName)
        setFontNameID(instanceFont, 16, newFamName)

        newFileName = fontFileName\
            .replace(oldName, (newName + fontOptions['Family Name']).replace(" ", ""))\
            .replace("_VF_", "-" + instance.replace(" ", "") + "-")

        # make dir for new fonts
        pathlib.Path(outputSubDir).mkdir(parents=True, exist_ok=True)

        # -------------------------------------------------------
        # OpenType Table fixes

        # drop STAT table to allow RIBBI style naming & linking on Windows
        del instanceFont["STAT"]

        # In the post table, isFixedPitched flag must be set in the code fonts
        instanceFont['post'].isFixedPitch = 1

        # In the OS/2 table Panose bProportion must be set to 9
        instanceFont["OS/2"].panose.bProportion = 9

        # Also in the OS/2 table, xAvgCharWidth should be set to 600 rather than 612 (612 is an average of glyphs in the "Mono" files which include wide ligatures).
        instanceFont["OS/2"].xAvgCharWidth = 600

        if instance == "Italic":
            instanceFont['OS/2'].fsSelection = 0b1
            instanceFont["head"].macStyle = 0b10
            # In the OS/2 table Panose bProportion must be set to 11 for "oblique boxed" (this is partially a guess)
            instanceFont["OS/2"].panose.bLetterForm = 11

        if instance == "Bold":
            instanceFont['OS/2'].fsSelection = 0b100000
            instanceFont["head"].macStyle = 0b1

        if instance == "Bold Italic":
            instanceFont['OS/2'].fsSelection = 0b100001
            instanceFont["head"].macStyle = 0b11

        # -------------------------------------------------------
        # save instance font

        outputPath = f"{outputSubDir}/{newFileName}"

        # save font
        instanceFont.save(outputPath)

        # -------------------------------------------------------
        # Code font special stuff in post processing

        # freeze in rvrn features with pyftfeatfreeze: serifless 'f', unambiguous 'l', '6', '9'
        pyftfeatfreeze.main([f"--features=rvrn,{','.join(fontOptions['Features'])}", outputPath, outputPath])

        if fontOptions['Code Ligatures']:
            # swap dlig2calt to make code ligatures work in old code editor apps
            dlig2calt(outputPath, inplace=True)

        # if casual, merge with casual PL; if linear merge w/ Linear PL
        if fontOptions["Fonts"][instance]["CASL"] > 0.5:
            mergePowerlineFont(outputPath, "./font-data/NerdfontsPL-Regular Casual.ttf")
        else:
            mergePowerlineFont(outputPath, "./font-data/NerdfontsPL-Regular Linear.ttf")



        # TODO, maybe: make VF for powerline font, then instantiate specific CASL instance before merging

        print(f"\n→ Font saved to '{outputPath}'\n")
Пример #9
0
def splitFont(
    outputDirectory=f"RecMono{fontOptions['Family Name']}".replace(" ", ""),
    newName="Rec Mono",
):

    # access font as TTFont object
    varfont = ttLib.TTFont(fontPath)

    fontFileName = os.path.basename(fontPath)

    outputSubDir = f"fonts/{outputDirectory}"

    for instance in fontOptions["Fonts"]:

        print(
            "\n--------------------------------------------------------------------------------------\n"
            + instance)

        instanceFont = instancer.instantiateVariableFont(
            varfont,
            {
                "wght": fontOptions["Fonts"][instance]["wght"],
                "CASL": fontOptions["Fonts"][instance]["CASL"],
                "MONO": fontOptions["Fonts"][instance]["MONO"],
                "slnt": fontOptions["Fonts"][instance]["slnt"],
                "CRSV": fontOptions["Fonts"][instance]["CRSV"],
            },
        )

        # UPDATE NAME ID 6, postscript name
        currentPsName = getFontNameID(instanceFont, 6)
        newPsName = (currentPsName\
            .replace("Sans", "")\
            .replace(oldName,newName.replace(" ", "") + fontOptions['Family Name'].replace(" ",""))\
            .replace("LinearLight", instance.replace(" ", "")))
        setFontNameID(instanceFont, 6, newPsName)

        # UPDATE NAME ID 4, full font name
        currentFullName = getFontNameID(instanceFont, 4)
        newFullName = (currentFullName\
            .replace("Sans", "")\
            .replace(oldName, newName + " " + fontOptions['Family Name'])\
            .replace(" Linear Light", instance))\
            .replace(" Regular", "")
        setFontNameID(instanceFont, 4, newFullName)

        # UPDATE NAME ID 3, unique font ID
        currentUniqueName = getFontNameID(instanceFont, 3)
        newUniqueName = (currentUniqueName.replace(currentPsName, newPsName))
        setFontNameID(instanceFont, 3, newUniqueName)

        # ADD name 2, style linking name
        newStyleLinkingName = instance
        setFontNameID(instanceFont, 2, newStyleLinkingName)
        setFontNameID(instanceFont, 17, newStyleLinkingName)

        # UPDATE NAME ID 1, Font Family name
        currentFamName = getFontNameID(instanceFont, 1)
        newFamName = (newFullName.replace(f" {instance}", ""))
        setFontNameID(instanceFont, 1, newFamName)
        setFontNameID(instanceFont, 16, newFamName)

        newFileName = fontFileName\
            .replace(oldName, (newName + fontOptions['Family Name']).replace(" ", ""))\
            .replace("_VF_", "-" + instance.replace(" ", "") + "-")

        # make dir for new fonts
        pathlib.Path(outputSubDir).mkdir(parents=True, exist_ok=True)

        # -------------------------------------------------------
        # save instance font

        outputPath = f"{outputSubDir}/{newFileName}"

        # save font
        instanceFont.save(outputPath)

        # -------------------------------------------------------
        # Code font special stuff in post processing

        # freeze in rvrn & stylistic set features with pyftfeatfreeze
        pyftfeatfreeze.main([
            f"--features=rvrn,{','.join(fontOptions['Features'])}", outputPath,
            outputPath
        ])

        if fontOptions['Code Ligatures']:
            # swap dlig2calt to make code ligatures work in old code editor apps
            dlig2calt(outputPath, inplace=True)

        # if casual, merge with casual PL; if linear merge w/ Linear PL
        if fontOptions["Fonts"][instance]["CASL"] > 0.5:
            mergePowerlineFont(outputPath,
                               "./font-data/NerdfontsPL-Regular Casual.ttf")
        else:
            mergePowerlineFont(outputPath,
                               "./font-data/NerdfontsPL-Regular Linear.ttf")

        # TODO, maybe: make VF for powerline font, then instantiate specific CASL instance before merging

        # -------------------------------------------------------
        # OpenType Table fixes

        monoFont = ttLib.TTFont(outputPath)

        # drop STAT table to allow RIBBI style naming & linking on Windows
        try:
            del monoFont["STAT"]
        except KeyError:
            print("Font has no STAT table.")

        # In the post table, isFixedPitched flag must be set in the code fonts
        monoFont['post'].isFixedPitch = 1

        # In the OS/2 table Panose bProportion must be set to 9
        monoFont["OS/2"].panose.bProportion = 9

        # Also in the OS/2 table, xAvgCharWidth should be set to 600 rather than 612 (612 is an average of glyphs in the "Mono" files which include wide ligatures).
        monoFont["OS/2"].xAvgCharWidth = 600

        # Code to fix fsSelection adapted from:
        # https://github.com/googlefonts/gftools/blob/a0b516d71f9e7988dfa45af2d0822ec3b6972be4/Lib/gftools/fix.py#L764

        old_selection = fs_selection = monoFont["OS/2"].fsSelection

        # turn off all bits except for bit 7 (USE_TYPO_METRICS)
        fs_selection &= 1 << 7

        if instance == "Italic":

            monoFont["head"].macStyle = 0b10
            # In the OS/2 table Panose bProportion must be set to 11 for "oblique boxed" (this is partially a guess)
            monoFont["OS/2"].panose.bLetterForm = 11

            # set Italic bit
            fs_selection |= 1 << 0

        if instance == "Bold":
            monoFont['OS/2'].fsSelection = 0b100000
            monoFont["head"].macStyle = 0b1

            # set Bold bit
            fs_selection |= 1 << 5

        if instance == "Bold Italic":
            monoFont['OS/2'].fsSelection = 0b100001
            monoFont["head"].macStyle = 0b11

            # set Italic & Bold bits
            fs_selection |= 1 << 0
            fs_selection |= 1 << 5

        monoFont["OS/2"].fsSelection = fs_selection

        monoFont.save(outputPath)

        print(f"\n→ Font saved to '{outputPath}'\n")

        print('Features are ', fontOptions['Features'])
def splitFont(
    fontPath,
    outputDirectory="fonts/rec_mono-for-code",
    newName="Rec Mono",
    ttc=False,
    zip=False,
):

    # access font as TTFont object
    varfont = ttLib.TTFont(fontPath)

    fontFileName = os.path.basename(fontPath)

    for package in instanceValues:
        outputSubDir = f"{outputDirectory}/{package}"

        for instance in instanceValues[package]:

            print(instance)

            instanceFont = instancer.instantiateVariableFont(
                varfont,
                {
                    "wght": instanceValues[package][instance]["wght"],
                    "CASL": instanceValues[package][instance]["CASL"],
                    "MONO": instanceValues[package][instance]["MONO"],
                    "slnt": instanceValues[package][instance]["slnt"],
                    "CRSV": instanceValues[package][instance]["CRSV"],
                },
            )

            # UPDATE NAME ID 6, postscript name
            currentPsName = getFontNameID(instanceFont, 6)
            newPsName = (currentPsName.replace("Sans", "").replace(
                oldName,
                newName.replace(" ", "")).replace("LinearLight",
                                                  instance.replace(" ", "")))
            setFontNameID(instanceFont, 6, newPsName)

            # UPDATE NAME ID 4, full font name
            currentFullName = getFontNameID(instanceFont, 4)
            newFullName = (currentFullName.replace("Sans", "").replace(
                oldName, newName).replace(" Linear Light", instance))
            setFontNameID(instanceFont, 4, newFullName)

            # UPDATE NAME ID 3, unique font ID
            currentUniqueName = getFontNameID(instanceFont, 3)
            newUniqueName = (currentUniqueName.replace("Sans", "").replace(
                oldName,
                newName.replace(" ", "")).replace("LinearLight",
                                                  instance.replace(" ", "")))
            setFontNameID(instanceFont, 3, newUniqueName)

            # ADD name 2, style linking name
            newStyleLinkingName = instanceValues[package][instance]["style"]
            setFontNameID(instanceFont, 2, newStyleLinkingName)
            setFontNameID(instanceFont, 17, newStyleLinkingName)

            # UPDATE NAME ID 1, unique font ID
            currentFamName = getFontNameID(instanceFont, 1)
            newFamName = (currentFamName.replace(" Sans", "").replace(
                oldName, newName).replace(
                    "Linear Light",
                    instance.replace(
                        " " + instanceValues[package][instance]["style"], ""),
                ))
            setFontNameID(instanceFont, 1, newFamName)
            setFontNameID(instanceFont, 16, newFamName)

            newFileName = fontFileName.replace(oldName, newName.replace(
                " ", "")).replace("_VF_",
                                  "-" + instance.replace(" ", "") + "-")

            # make dir for new fonts
            pathlib.Path(outputSubDir).mkdir(parents=True, exist_ok=True)

            # drop STAT table to allow RIBBI style naming & linking on Windows
            del instanceFont["STAT"]

            outputPath = f"{outputSubDir}/{newFileName}"

            # save font
            instanceFont.save(outputPath)

            # freeze in rvrn features with pyftfeatfreeze
            pyftfeatfreeze.main(["--features=rvrn", outputPath, outputPath])

            # swap dlig2calt to make code ligatures work in old code editor apps
            dlig2calt(outputPath, inplace=True)

        # -----------------------------------------------------------
        # make TTC (truetype collection) of fonts – doesn't current work on Mac very well :(

        if ttc:
            # make list of fonts in subdir
            fontPaths = [
                os.path.abspath(outputSubDir + "/" + x)
                for x in os.listdir(outputSubDir)
            ]

            # form command
            command = f"otf2otc {' '.join(fontPaths)} -o {outputDirectory}/RecMono-{package}.ttc"
            print("▶", command, "\n")

            # run command in shell
            subprocess.run(command.split(), check=True, text=True)

            # remove dir with individual fontpaths
            shutil.rmtree(os.path.abspath(outputSubDir))

    # Make zip of output, then put inside output directory
    if zip:
        shutil.make_archive(f"{outputDirectory}", "zip", outputDirectory)
        shutil.move(
            f"{outputDirectory}.zip",
            f"{outputDirectory}/{outputDirectory.split('/')[-1]}.zip",
        )
Пример #11
0
def _drop_axes(font, axes):
    if not axes:
        return font
    return instancer.instantiateVariableFont(font, {tag: None
                                                    for tag in axes},
                                             inplace=True)
Пример #12
0
def splitFont(splits=10,
              fontPath="fonts_1.031/Variable_TTF/Recursive_VF_1.031.ttf",
              outputDirectoryyyy="recursive-split",
              run=False):
    """
		Use to split Recursive VF into an arbitrary number of instances, so that each style is slightly different from the previous one.

		USAGE: On the command line, install dependencies with a virtual environment and pip, then run a command like:
		
		python src/proofs/final-specimen/create-instance-per-page.py -f fonts_1.031/Variable_TTF/Recursive_VF_1.031.ttf -s 57 -r

		Outputs to "recursive-split" directory by default.
	"""

    report = ""

    if run:
        if os.path.exists(outputDirectoryyyy):
            shutil.rmtree(outputDirectoryyyy)
        if not os.path.exists(outputDirectoryyyy):
            os.makedirs(outputDirectoryyyy)

    varfont = ttLib.TTFont(fontPath)

    for split in range(0, splits):
        t = split / (splits - 1)
        mono = round(interpolate(axes['mono'][0], axes['mono'][1], t), 2)
        casl = round(interpolate(axes['casl'][0], axes['casl'][1], t), 2)
        wght = round(interpolate(axes['wght'][0], axes['wght'][1], t), 2)
        slnt = round(interpolate(axes['slnt'][0], axes['slnt'][1], t), 2)
        ital = 0.5

        pageNum = str(split + 1).rjust(2, '0')
        monoVal = "{:.2f}".format(mono).rjust(7, ' ')
        caslVal = "{:.2f}".format(casl).rjust(7, ' ')
        wghtVal = "{:.2f}".format(wght).rjust(7, ' ')
        slntVal = "{:.2f}".format(slnt).rjust(7, ' ')
        italVal = "{:.2f}".format(ital).rjust(7, ' ')

        output = f"page {pageNum} | MONO: {monoVal}, CASL: {caslVal}, wght: {wghtVal}, slnt: {slntVal}, ital: {italVal}"
        print("\n", output)
        report += output + "\n"

        # actually create the instance
        if run:

            instance = instancer.instantiateVariableFont(
                varfont, {
                    "wght": wght,
                    "CASL": casl,
                    "MONO": mono,
                    "slnt": slnt
                })

            # give instance page-based style name
            setFontNameID(instance, 1, f"Recursive {splits}p")
            setFontNameID(instance, 3,
                          f"1.031;ARRW;RecVarSplit-split{pageNum}")
            setFontNameID(instance, 4, f"Recursive {splits}p")
            setFontNameID(instance, 6, f"RecVarSplit-split{pageNum}")
            setFontNameID(instance, 16, f"Recursive {splits}p")
            setFontNameID(instance, 17, f"Split_{pageNum}")

            # save custom instance
            instance.save(
                f"{outputDirectoryyyy}/recursive-split--page_{pageNum}--MONO{mono}_CASL{casl}_wght{wght}_slnt{slnt}.ttf"
            )

    if run:
        with open(f"{outputDirectoryyyy}/font-split-report.txt", "w") as file:
            file.write(report)

    if not run:
        print(
            "\n\tINFO: This was a dry run to preview output. To generate fonts, please add argument --run or -r\n\n"
        )
Пример #13
0
def update_attribs(font, **kwargs):
    for table in font.keys():
        for k in kwargs:
            if hasattr(font[table], k):
                print(f"Setting {k} to {kwargs[k]}")
                setattr(font[table], k, kwargs[k])


def update_names(font, **kwargs):
    nametable = font["name"]
    for k in kwargs:
        print(f"Setting {k} to {kwargs[k]}")
        nametable.setName(kwargs[k], *tuple(map(int, k.split(","))))

    for name_id in range(256, 308):
        font['name'].removeNames(name_id)


vf = TTFont(sys.argv[1])
out_dir = mkdir(sys.argv[2])

for inst in instances:
    print(f"Making {inst['filename']}")
    instance = instantiateVariableFont(vf, inst["axes"])
    update_attribs(instance, **inst["attribs"])
    update_names(instance, **inst["names"])
    del instance['STAT']
    out_path = os.path.join(sys.argv[2], inst["filename"])
    instance.save(out_path)