How to use the defcon.Font function in defcon

To help you get started, we’ve selected a few defcon examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github adobe-type-tools / python-scripts / generateAllKernFiles.py View on Github external
totalFonts = len(fonts)
    print("%d fonts found\n" % totalFonts)

    for i, font in enumerate(fonts, 1):
        folderPath, fontFileName = os.path.split(font)
        styleName = os.path.basename(folderPath)
        folderPath = os.path.abspath(folderPath)

        os.chdir(folderPath)

        exportMessage = 'Exporting kern files for %s...(%d/%d)' % (
            styleName, i, totalFonts)
        print('*' * len(exportMessage))
        print(exportMessage)

        ufoFont = Font(fontFileName)
        kernFeatureWriter.run(ufoFont, folderPath, writeSubtables=True)

        os.chdir(startpath)
github typemytype / batchRoboFontExtension / Batch.roboFontExt / lib / variableFontGenerator / __init__.py View on Github external
outputPath = os.path.join(dirname, "temp_%02d_%s-%s-%s.ttf" % (masterCount, master.font.info.familyName, master.font.info.styleName, master.name))
            masterBinaryPaths[sourceDescriptor.path] = outputPath
            self._generatedFiles.add(outputPath)
            masterCount += 1
            # set the output path
            options.outputPath = outputPath
            options.layerName = master.name
            try:
                # generate the font
                result = generateFont(master.font, options=options)
                if getDefault("Batch.Debug", False):
                    tempSavePath = os.path.join(dirname, "temp_%s-%s-%s.ufo" % (master.font.info.familyName, master.font.info.styleName, master.name))
                    font = master.font
                    font.save(tempSavePath)
                    if font.layers.defaultLayer.name != master.name:
                        tempFont = defcon.Font(tempSavePath)
                        tempFont.layers.defaultLayer = tempFont.layers[master.name]
                        tempFont.save()
            except Exception:
                import traceback
                result = traceback.format_exc()
                print(result)
            self.generateReport.newLine()
            self.generateReport.write("Generate %s %s (%s)" % (master.font.info.familyName, master.font.info.styleName, master.name))
            self.generateReport.indent()
            self.generateReport.write(result)
            self.generateReport.dedent()
        self.generateReport.dedent()
        # optimize the design space for varlib
        designSpacePath = os.path.join(os.path.dirname(self.path), "temp_%s" % os.path.basename(self.path))
        self.write(designSpacePath)
        self._generatedFiles.add(designSpacePath)
github adobe-type-tools / kern-dump / ufoTool.py View on Github external
def stripClasses(ufo):
	f = Font(ufo)
	for name, group in f.groups.items()[::-1]:
		if len(group) == 0:
			del f.groups[name]
	f.save()
github adobe-type-tools / afdko / FDK / Tools / SharedData / FDKScripts / buildMasterOTFs.py View on Github external
def _determine_which_masters_to_generate(ds_path):
	"""'ds_path' is the path to a designspace file.
	   Returns a list of integers representing the indexes
	   of the temp masters to generate.
	"""
	master_list = ET.parse(ds_path).getroot().find('sources').findall('source')

	# Make a set of the glyphsets of all the masters while collecting each
	# glyphset. Glyph order is ignored.
	all_gsets = set()
	each_gset = []
	for master in master_list:
		master_path = master.attrib['filename']
		ufo_path = os.path.join(os.path.dirname(ds_path), master_path)
		gset = set(defcon.Font(ufo_path).keys())
		all_gsets.update(gset)
		each_gset.append(gset)

	master_indexes = []
	for i, gset in enumerate(each_gset):
		if gset != all_gsets:
			master_indexes.append(i)

	return master_indexes
github adobe-type-tools / afdko / FDK / Tools / SharedData / FDKScripts / buildMasterOTFs.py View on Github external
# for generating the temp master(s)
	master_paths = []
	for i, master in enumerate(masterList):
		masterPath = master.attrib['filename']
		if i not in temp_masters_to_generate:
			master_paths.append(masterPath)
			continue
		instance = XMLElement('instance')
		instance.append(master.find('location'))
		instance.append(XMLElement('kerning'))
		instance.append(XMLElement('info'))
		tempMasterPath = os.path.splitext(masterPath)[0] + kTempUFOExt
		master_paths.append(tempMasterPath)
		instance.attrib['filename'] = tempMasterPath
		ufo_path = os.path.join(os.path.dirname(dsPath), masterPath)
		ufo_info = defcon.Font(ufo_path).info
		instance.attrib['familyname'] = ufo_info.familyName
		instance.attrib['stylename'] = ufo_info.styleName
		instance.attrib['postscriptfontname'] = ufo_info.postscriptFontName
		instances.append(instance)
	tempDSPath = os.path.splitext(dsPath)[0] + kTempDSExt
	fp = open(tempDSPath, "wt")
	fp.write(xmlToString(ds))
	fp.close()
	return tempDSPath, master_paths
github unified-font-object / ufo4Research / fontSizeReporter / UFOStats.py View on Github external
def _profileFont_defcon(path, profile):
	"""
	defcon specific profiler.
	"""
	profile["outputEnvironment"] = "defcon"
	if isinstance(path, defcon.Font):
		font = path
	else:
		font = defcon.Font(path)
	try:
		for layer in font.layers:
			profileGlyphSet(layer.keys(), layer, profile)
	except AttributeError:
		profileGlyphSet(font.keys(), font, profile)
	profileKerning(font.kerning, profile)
	profileGroups(font.groups, profile)
	profileFeatures(font.features.text, profile)
	profileFontInfo(font.info, profile)
github adobe-type-tools / kern-dump / kerning2UFO.py View on Github external
def replaceKerning(ufo, classes, pairs):
	f = Font(ufo)

	f.groups.clear()
	for i in classes:
		i.name = makeMMK(i.name, i.side)

		for g in i.glyphs:
			if not g in f.keys():
				i.glyphs.remove(g)
		if len(i.glyphs) == 0:
			continue
		else:
	  		f.groups[i.name] = i.glyphs

	f.save()
	f.kerning.clear()
github googlefonts / glyphsLib / Lib / glyphs2ufo / builder.py View on Github external
version_major = data.pop('versionMajor')
    version_minor = data.pop('versionMinor')
    user_data = data.pop('userData', {})
    copyright = data.pop('copyright', None)
    designer = data.pop('designer', None)
    designer_url = data.pop('designerURL', None)
    manufacturer = data.pop('manufacturer', None)
    manufacturer_url = data.pop('manufacturerURL', None)

    misc = ['DisplayStrings', 'disablesAutomaticAlignment', 'disablesNiceNames']
    custom_params = parse_custom_params(data, misc)

    ufos = {}
    master_id_order = []
    for master in data['fontMaster']:
        ufo = Font()

        ufo.info.familyName = family_name
        ufo.info.styleName = build_style_name(master, ('width', 'weight'), italic)

        ufo.info.openTypeHeadCreated = date_created
        ufo.info.unitsPerEm = units_per_em
        ufo.info.versionMajor = version_major
        ufo.info.versionMinor = version_minor

        if copyright:
            ufo.info.copyright = unicode(copyright.decode("utf-8"))
        if designer:
            ufo.info.openTypeNameDesigner = designer
        if designer_url:
            ufo.info.openTypeNameDesignerURL = designer_url
        if manufacturer:
github typemytype / batchRoboFontExtension / Batch.roboFontExt / lib / toolBox.py View on Github external
def get(self, supportedExtensions=None, flattenDesignSpace=True):
        items = self.paths.get()
        paths = []
        for item in items:
            path = item.path()
            ext = os.path.splitext(path)[1].lower()
            if ext == ".ufo":
                f = DefconFont(path)
                if f.info.familyName and f.info.styleName:
                    paths.append(path)
                else:
                    message = "%s has no family name or style name" % path
                    print("*" * len(message))
                    print(message)
                    print("*" * len(message))
            elif os.path.isdir(path):
                for ext in self.supportedFontFileFormats:
                    paths.extend(walkDirectoryForFile(path, ext=ext))
            elif flattenDesignSpace and ext == ".designspace":
                if not hasattr(item, "designSpaceDocument"):
                    item.designSpaceDocument = BatchDesignSpaceProcessor(path, ufoVersion)
                item.designSpaceDocument.generateUFO()
                paths.extend([path for path in item.designSpaceDocument.masterUFOPaths()])
                paths.extend([path for path in item.designSpaceDocument.instancesUFOPaths()])
github fadox / fontamental / Lib / fontamental / minify.py View on Github external
def __init__(self, source, template=None, config=None):
        self.GDB = GlyphsLib(False, config)  # buildFea set to false
        self.srcUFO = self.sourceFont(source)
        self.UFO = Font()
        self.layers = {}

        if template is None:
            template = os.path.join(os.path.dirname(__file__), 'database/template.ufo')
        self.templateUFO = Font(template)