Python fontTools.ttLib.newTable() Examples

The following are 30 code examples of fontTools.ttLib.newTable(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module fontTools.ttLib , or try the search function .
Example #1
Source File: builder.py    From Emoji-Tools with GNU General Public License v3.0 6 votes vote down vote up
def buildGDEF(self):
        gdef = otTables.GDEF()
        gdef.GlyphClassDef = self.buildGDEFGlyphClassDef_()
        gdef.AttachList = \
            otl.buildAttachList(self.attachPoints_, self.glyphMap)
        gdef.LigCaretList = \
            otl.buildLigCaretList(self.ligCaretCoords_, self.ligCaretPoints_,
                                  self.glyphMap)
        gdef.MarkAttachClassDef = self.buildGDEFMarkAttachClassDef_()
        gdef.MarkGlyphSetsDef = self.buildGDEFMarkGlyphSetsDef_()
        gdef.Version = 0x00010002 if gdef.MarkGlyphSetsDef else 1.0
        if any((gdef.GlyphClassDef, gdef.AttachList, gdef.LigCaretList,
                gdef.MarkAttachClassDef, gdef.MarkGlyphSetsDef)):
            result = newTable("GDEF")
            result.table = gdef
            return result
        else:
            return None 
Example #2
Source File: builder.py    From Emoji-Tools with GNU General Public License v3.0 6 votes vote down vote up
def build_name(self):
        if not self.names_:
            return
        table = self.font.get("name")
        if not table:  # this only happens for unit tests
            table = self.font["name"] = newTable("name")
            table.names = []
        for name in self.names_:
            nameID, platformID, platEncID, langID, string = name
            if not isinstance(nameID, int):
                # A featureNames name and nameID is actually the tag
                tag = nameID
                if tag not in self.featureNames_ids_:
                    self.featureNames_ids_[tag] = self.get_user_name_id(table)
                    assert self.featureNames_ids_[tag] is not None
                nameID = self.featureNames_ids_[tag]
            table.setName(string, nameID, platformID, platEncID, langID) 
Example #3
Source File: builder.py    From Emoji-Tools with GNU General Public License v3.0 6 votes vote down vote up
def build_hhea(self):
        if not self.hhea_:
            return
        table = self.font.get("hhea")
        if not table:  # this only happens for unit tests
            table = self.font["hhea"] = newTable("hhea")
            table.decompile(b"\0" * 36, self.font)
            table.tableVersion = 1.0
        if "caretoffset" in self.hhea_:
            table.caretOffset = self.hhea_["caretoffset"]
        if "ascender" in self.hhea_:
            table.ascent = self.hhea_["ascender"]
        if "descender" in self.hhea_:
            table.descent = self.hhea_["descender"]
        if "linegap" in self.hhea_:
            table.lineGap = self.hhea_["linegap"] 
Example #4
Source File: O_S_2f_2_test.py    From Emoji-Tools with GNU General Public License v3.0 6 votes vote down vote up
def test_recalcUnicodeRanges(self):
		font = TTFont()
		font['OS/2'] = os2 = newTable('OS/2')
		font['cmap'] = cmap = newTable('cmap')
		st = getTableModule('cmap').CmapSubtable.newSubtable(4)
		st.platformID, st.platEncID, st.language = 3, 1, 0
		st.cmap = {0x0041:'A', 0x03B1: 'alpha', 0x0410: 'Acyr'}
		cmap.tables = []
		cmap.tables.append(st)
		os2.setUnicodeRanges({0, 1, 9})
		# 'pruneOnly' will clear any bits for which there's no intersection:
		# bit 1 ('Latin 1 Supplement'), in this case. However, it won't set
		# bit 7 ('Greek and Coptic') despite the "alpha" character is present.
		self.assertEqual(os2.recalcUnicodeRanges(font, pruneOnly=True), {0, 9})
		# try again with pruneOnly=False: bit 7 is now set.
		self.assertEqual(os2.recalcUnicodeRanges(font), {0, 7, 9})
		# add a non-BMP char from 'Mahjong Tiles' block (bit 122)
		st.cmap[0x1F000] = 'eastwindtile'
		# the bit 122 and the special bit 57 ('Non Plane 0') are also enabled
		self.assertEqual(os2.recalcUnicodeRanges(font), {0, 7, 9, 57, 122}) 
Example #5
Source File: C_P_A_L_test.py    From Emoji-Tools with GNU General Public License v3.0 6 votes vote down vote up
def test_fromXML_v0(self):
        cpal = newTable('CPAL')
        for name, attrs, content in parseXML(
                '<version value="0"/>'
                '<numPaletteEntries value="2"/>'
                '<palette index="0">'
                '  <color index="0" value="#12345678"/>'
                '  <color index="1" value="#FEDCBA98"/>'
                '</palette>'):
            cpal.fromXML(name, attrs, content, ttFont=None)
        self.assertEqual(cpal.version, 0)
        self.assertEqual(cpal.numPaletteEntries, 2)
        self.assertEqual(repr(cpal.palettes), '[[#12345678, #FEDCBA98]]')
        self.assertEqual(cpal.paletteLabels, [0])
        self.assertEqual(cpal.paletteTypes, [0])
        self.assertEqual(cpal.paletteEntryLabels, [0, 0]) 
Example #6
Source File: outlineCompiler.py    From ufo2ft with MIT License 6 votes vote down vote up
def setupTable_hmtx(self):
        """
        Make the hmtx table.

        **This should not be called externally.** Subclasses
        may override or supplement this method to handle the
        table creation in a different way if desired.
        """
        if "hmtx" not in self.tables:
            return

        self.otf["hmtx"] = hmtx = newTable("hmtx")
        hmtx.metrics = {}
        for glyphName, glyph in self.allGlyphs.items():
            width = otRound(glyph.width)
            if width < 0:
                raise ValueError("The width should not be negative: '%s'" % (glyphName))
            bounds = self.glyphBoundingBoxes[glyphName]
            left = bounds.xMin if bounds else 0
            hmtx[glyphName] = (width, left) 
Example #7
Source File: outlineCompiler.py    From ufo2ft with MIT License 6 votes vote down vote up
def setupTable_vmtx(self):
        """
        Make the vmtx table.

        **This should not be called externally.** Subclasses
        may override or supplement this method to handle the
        table creation in a different way if desired.
        """
        if "vmtx" not in self.tables:
            return

        self.otf["vmtx"] = vmtx = newTable("vmtx")
        vmtx.metrics = {}
        for glyphName, glyph in self.allGlyphs.items():
            height = otRound(glyph.height)
            if height < 0:
                raise ValueError(
                    "The height should not be negative: '%s'" % (glyphName)
                )
            verticalOrigin = _getVerticalOrigin(self.otf, glyph)
            bounds = self.glyphBoundingBoxes[glyphName]
            top = bounds.yMax if bounds else 0
            vmtx[glyphName] = (height, verticalOrigin - top) 
Example #8
Source File: outlineCompiler.py    From ufo2ft with MIT License 6 votes vote down vote up
def setupTable_VORG(self):
        """
        Make the VORG table.

        **This should not be called externally.** Subclasses
        may override or supplement this method to handle the
        table creation in a different way if desired.
        """
        if "VORG" not in self.tables:
            return

        self.otf["VORG"] = vorg = newTable("VORG")
        vorg.majorVersion = 1
        vorg.minorVersion = 0
        vorg.VOriginRecords = {}
        # Find the most frequent verticalOrigin
        vorg_count = Counter(
            _getVerticalOrigin(self.otf, glyph) for glyph in self.allGlyphs.values()
        )
        vorg.defaultVertOriginY = vorg_count.most_common(1)[0][0]
        if len(vorg_count) > 1:
            for glyphName, glyph in self.allGlyphs.items():
                vorg.VOriginRecords[glyphName] = _getVerticalOrigin(self.otf, glyph)
        vorg.numVertOriginYMetrics = len(vorg.VOriginRecords) 
Example #9
Source File: C_P_A_L_test.py    From Emoji-Tools with GNU General Public License v3.0 6 votes vote down vote up
def test_toXML_v1(self):
        name = FakeNameTable({258: "Spring theme", 259: "Winter theme"})
        cpal = newTable('CPAL')
        ttFont = {"name": name, "CPAL": cpal}
        cpal.decompile(CPAL_DATA_V1, ttFont)
        self.assertEqual(getXML(cpal.toXML, ttFont),
                         '<version value="1"/>'
                         '<numPaletteEntries value="3"/>'
                         '<palette index="0" label="258" type="1">'
                         '  <!-- Spring theme -->'
                         '  <color index="0" value="#CAFECAFE"/>'
                         '  <color index="1" value="#22110033"/>'
                         '  <color index="2" value="#66554477"/>'
                         '</palette>'
                         '<palette index="1" label="259" type="2">'
                         '  <!-- Winter theme -->'
                         '  <color index="0" value="#59413127"/>'
                         '  <color index="1" value="#42424242"/>'
                         '  <color index="2" value="#13330037"/>'
                         '</palette>'
                         '<paletteEntryLabels>'
                         '  <label index="0" value="513"/>'
                         '  <label index="1" value="514"/>'
                         '  <label index="2" value="515"/>'
                         '</paletteEntryLabels>') 
Example #10
Source File: outlineCompiler.py    From ufo2ft with MIT License 6 votes vote down vote up
def setupTable_maxp(self):
        """Make the maxp table."""
        if "maxp" not in self.tables:
            return

        self.otf["maxp"] = maxp = newTable("maxp")
        maxp.tableVersion = 0x00010000
        maxp.numGlyphs = len(self.glyphOrder)
        maxp.maxZones = 1
        maxp.maxTwilightPoints = 0
        maxp.maxStorage = 0
        maxp.maxFunctionDefs = 0
        maxp.maxInstructionDefs = 0
        maxp.maxStackElements = 0
        maxp.maxSizeOfInstructions = 0
        maxp.maxComponentElements = max(
            len(g.components) for g in self.allGlyphs.values()
        ) 
Example #11
Source File: outlineCompiler.py    From ufo2ft with MIT License 6 votes vote down vote up
def setupTable_glyf(self):
        """Make the glyf table."""
        if not {"glyf", "loca"}.issubset(self.tables):
            return

        self.otf["loca"] = newTable("loca")
        self.otf["glyf"] = glyf = newTable("glyf")
        glyf.glyphs = {}
        glyf.glyphOrder = self.glyphOrder

        hmtx = self.otf.get("hmtx")
        ttGlyphs = self.getCompiledGlyphs()
        for name in self.glyphOrder:
            ttGlyph = ttGlyphs[name]
            if ttGlyph.isComposite() and hmtx is not None and self.autoUseMyMetrics:
                self.autoUseMyMetrics(ttGlyph, name, hmtx)
            glyf[name] = ttGlyph 
Example #12
Source File: C_P_A_L_test.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def test_decompile_v1_noLabelsNoTypes(self):
        cpal = newTable('CPAL')
        cpal.decompile(CPAL_DATA_V1_NOLABELS_NOTYPES, ttFont=None)
        self.assertEqual(cpal.version, 1)
        self.assertEqual(cpal.numPaletteEntries, 3)
        self.assertEqual([repr(p) for p in cpal.palettes], [
            '[#CAFECAFE, #22110033, #66554477]',  # RGBA
            '[#59413127, #42424242, #13330037]'])
        self.assertEqual(cpal.paletteLabels, [0, 0])
        self.assertEqual(cpal.paletteTypes, [0, 0])
        self.assertEqual(cpal.paletteEntryLabels, [0, 0, 0]) 
Example #13
Source File: woff2_test.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def test_getVersion(self):
		# no version
		self.assertEqual((0, 0), self.writer._getVersion())
		# version from head.fontRevision
		fontRevision = self.font['head'].fontRevision
		versionTuple = tuple(int(i) for i in str(fontRevision).split("."))
		entry = self.writer.tables['head'] = ttLib.newTable('head')
		entry.data = self.font.getTableData('head')
		self.assertEqual(versionTuple, self.writer._getVersion())
		# version from writer.flavorData
		flavorData = self.writer.flavorData = WOFF2FlavorData()
		flavorData.majorVersion, flavorData.minorVersion = (10, 11)
		self.assertEqual((10, 11), self.writer._getVersion()) 
Example #14
Source File: C_P_A_L_test.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def test_decompile_v1(self):
        cpal = newTable('CPAL')
        cpal.decompile(CPAL_DATA_V1, ttFont=None)
        self.assertEqual(cpal.version, 1)
        self.assertEqual(cpal.numPaletteEntries, 3)
        self.assertEqual([repr(p) for p in cpal.palettes], [
            '[#CAFECAFE, #22110033, #66554477]',  # RGBA
            '[#59413127, #42424242, #13330037]'])
        self.assertEqual(cpal.paletteTypes, [1, 2])
        self.assertEqual(cpal.paletteLabels, [258, 259])
        self.assertEqual(cpal.paletteEntryLabels, [513, 514, 515]) 
Example #15
Source File: C_P_A_L_test.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def test_compile_v0(self):
        cpal = newTable('CPAL')
        cpal.decompile(CPAL_DATA_V0, ttFont=None)
        self.assertEqual(cpal.compile(ttFont=None), CPAL_DATA_V0) 
Example #16
Source File: C_P_A_L_test.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def test_compile_v1(self):
        cpal = newTable('CPAL')
        cpal.decompile(CPAL_DATA_V1, ttFont=None)
        self.assertEqual(cpal.compile(ttFont=None), CPAL_DATA_V1) 
Example #17
Source File: C_P_A_L_test.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def test_compile_v1_noLabelsNoTypes(self):
        cpal = newTable('CPAL')
        cpal.decompile(CPAL_DATA_V1_NOLABELS_NOTYPES, ttFont=None)
        self.assertEqual(cpal.compile(ttFont=None),
                         CPAL_DATA_V1_NOLABELS_NOTYPES) 
Example #18
Source File: C_P_A_L_test.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def test_toXML_v0(self):
        cpal = newTable('CPAL')
        cpal.decompile(CPAL_DATA_V0, ttFont=None)
        self.assertEqual(getXML(cpal.toXML),
                         '<version value="0"/>'
                         '<numPaletteEntries value="2"/>'
                         '<palette index="0">'
                         '  <color index="0" value="#000000FF"/>'
                         '  <color index="1" value="#66CCFFFF"/>'
                         '</palette>'
                         '<palette index="1">'
                         '  <color index="0" value="#000000FF"/>'
                         '  <color index="1" value="#800000FF"/>'
                         '</palette>') 
Example #19
Source File: builder.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def build(self):
        self.parseTree = Parser(self.file).parse()
        self.parseTree.build(self)
        self.build_feature_aalt_()
        self.build_head()
        self.build_hhea()
        self.build_name()
        self.build_OS_2()
        for tag in ('GPOS', 'GSUB'):
            table = self.makeTable(tag)
            if (table.ScriptList.ScriptCount > 0 or
                    table.FeatureList.FeatureCount > 0 or
                    table.LookupList.LookupCount > 0):
                fontTable = self.font[tag] = newTable(tag)
                fontTable.table = table
            elif tag in self.font:
                del self.font[tag]
        gdef = self.buildGDEF()
        if gdef:
            self.font["GDEF"] = gdef
        elif "GDEF" in self.font:
            del self.font["GDEF"]
        base = self.buildBASE()
        if base:
            self.font["BASE"] = base
        elif "BASE" in self.font:
            del self.font["BASE"] 
Example #20
Source File: builder.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def build_head(self):
        if not self.fontRevision_:
            return
        table = self.font.get("head")
        if not table:  # this only happens for unit tests
            table = self.font["head"] = newTable("head")
            table.decompile(b"\0" * 54, self.font)
            table.tableVersion = 1.0
            table.created = table.modified = 3406620153  # 2011-12-13 11:22:33
        table.fontRevision = self.fontRevision_ 
Example #21
Source File: fix-vf-meta.py    From inter with SIL Open Font License 1.1 5 votes vote down vote up
def create_stat_table(ttfont):
  """Atm, Fontmake is only able to produce a basic stat table. Because of
  this, we'll create a STAT using the font's fvar table."""
  stat = newTable('STAT')
  stat.table = otTables.STAT()
  stat.table.Version = 0x00010001

  # # Build DesignAxisRecords from fvar
  stat.table.DesignAxisRecord = otTables.AxisRecordArray()
  stat.table.DesignAxisRecord.Axis = []

  stat_axises = stat.table.DesignAxisRecord.Axis

  # TODO (M Foley) add support for fonts which have multiple
  # axises e.g Barlow
  if len(ttfont['fvar'].axes) > 1:
    raise Exception('VFs with more than one axis are currently '
            'not supported.')

  for idx, axis in enumerate(ttfont['fvar'].axes):
    append_stat_axis(stat, axis.axisTag, axis.axisNameID)

  # Build AxisValueArrays for each namedInstance from fvar namedInstances
  stat.table.AxisValueArray = otTables.AxisValueArray()
  stat.table.AxisValueArray.AxisValue = []

  for idx, instance in enumerate(ttfont['fvar'].instances):
    append_stat_record(stat, 0, list(instance.coordinates.values())[0], instance.subfamilyNameID)

  # Set ElidedFallbackNameID
  stat.table.ElidedFallbackNameID = 2
  ttfont['STAT'] = stat 
Example #22
Source File: C_P_A_L_test.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def test_decompile_v0_sharingColors(self):
        cpal = newTable('CPAL')
        cpal.decompile(CPAL_DATA_V0_SHARING_COLORS, ttFont=None)
        self.assertEqual(cpal.version, 0)
        self.assertEqual(cpal.numPaletteEntries, 3)
        self.assertEqual([repr(p) for p in cpal.palettes], [
            '[#223344FF, #99887711, #55555555]',
            '[#223344FF, #99887711, #55555555]',
            '[#223344FF, #99887711, #FFFFFFFF]',
            '[#223344FF, #99887711, #55555555]'])
        self.assertEqual(cpal.paletteLabels, [0, 0, 0, 0])
        self.assertEqual(cpal.paletteTypes, [0, 0, 0, 0])
        self.assertEqual(cpal.paletteEntryLabels, [0, 0, 0]) 
Example #23
Source File: C_P_A_L_test.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def test_decompile_v0(self):
        cpal = newTable('CPAL')
        cpal.decompile(CPAL_DATA_V0, ttFont=None)
        self.assertEqual(cpal.version, 0)
        self.assertEqual(cpal.numPaletteEntries, 2)
        self.assertEqual(repr(cpal.palettes),
                         '[[#000000FF, #66CCFFFF], [#000000FF, #800000FF]]')
        self.assertEqual(cpal.paletteLabels, [0, 0])
        self.assertEqual(cpal.paletteTypes, [0, 0])
        self.assertEqual(cpal.paletteEntryLabels, [0, 0]) 
Example #24
Source File: woff2_test.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
		self.font = font = ttLib.TTFont(recalcBBoxes=False, recalcTimestamp=False)
		font['head'] = ttLib.newTable('head')
		font['loca'] = WOFF2LocaTable()
		font['glyf'] = WOFF2GlyfTable() 
Example #25
Source File: gftools-fix-dsig.py    From gftools with Apache License 2.0 5 votes vote down vote up
def set_empty_dsig(ttFont):
  newDSIG = ttLib.newTable("DSIG")
  newDSIG.ulVersion = 1
  newDSIG.usFlag = 0
  newDSIG.usNumSigs = 0
  newDSIG.signatureRecords = []
  ttFont.tables["DSIG"] = newDSIG 
Example #26
Source File: woff2_test.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def normalise_table(font, tag, padding=4):
	""" Return normalised table data. Keep 'font' instance unmodified. """
	assert tag in ('glyf', 'loca', 'head')
	assert tag in font
	if tag == 'head':
		origHeadFlags = font['head'].flags
		font['head'].flags |= (1 << 11)
		tableData = font['head'].compile(font)
	if font.sfntVersion in ("\x00\x01\x00\x00", "true"):
		assert {'glyf', 'loca', 'head'}.issubset(font.keys())
		origIndexFormat = font['head'].indexToLocFormat
		if hasattr(font['loca'], 'locations'):
			origLocations = font['loca'].locations[:]
		else:
			origLocations = []
		glyfTable = ttLib.newTable('glyf')
		glyfTable.decompile(font.getTableData('glyf'), font)
		glyfTable.padding = padding
		if tag == 'glyf':
			tableData = glyfTable.compile(font)
		elif tag == 'loca':
			glyfTable.compile(font)
			tableData = font['loca'].compile(font)
		if tag == 'head':
			glyfTable.compile(font)
			font['loca'].compile(font)
			tableData = font['head'].compile(font)
		font['head'].indexToLocFormat = origIndexFormat
		font['loca'].set(origLocations)
	if tag == 'head':
		font['head'].flags = origHeadFlags
	return tableData 
Example #27
Source File: merge_test.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
		self.merger = Merger()
		self.table1 = ttLib.newTable('cmap')
		self.table2 = ttLib.newTable('cmap')
		self.mergedTable = ttLib.newTable('cmap')
		pass 
Example #28
Source File: addSbixImages.py    From Emoji-Tools with GNU General Public License v3.0 5 votes vote down vote up
def main():
    # open the source font
    f = ttLib.TTFont(sys.argv[1]) #Arg 1 = Original Font Location

    resolutions = sys.argv[3]
    resolutionsList = resolutions.split(",")

    sets = {}
    for resolution in resolutionsList:
        sets[int(resolution)] = sys.argv[2]+"/set_"+resolution

    sbix = ttLib.newTable("sbix")
    go = f.getGlyphOrder()

    for s, d in sets.iteritems():
        # make an empty bitmap set for current image size
        mySet = BitmapSet(size=s)
        for root, dirs, files in walk(d, topdown=False):
            for myFile in files:
                if myFile[-4:] == ".png":
                    # use file name without suffix as glyph name
                    # FIXME: filename clashes with case-sensitive glyph names
                    glyphname = myFile[:-4]
                    if glyphname in go:  # only use files that have a matching glyph in the source font
                        print glyphname
                        img = open(join(root, myFile), "rb")
                        imgData = img.read()
                        img.close()
                        # make a bitmap record for the current image
                        myBitmap = Bitmap(glyphName=glyphname, imageFormatTag="png ", imageData=imgData)
                        # add bitmap to current bitmap set
                        mySet.bitmaps[glyphname] = myBitmap
        sbix.bitmapSets[s] = mySet
    # add sbix table to the source font
    f["sbix"] = sbix
    # save font under new name
    f.save(sys.argv[2]+"/AppleColorEmoji@2x.ttf") #Arg 2 = Output Directory Location 
Example #29
Source File: outlineCompiler.py    From ufo2ft with MIT License 5 votes vote down vote up
def setupTable_maxp(self):
        """Make the maxp table."""
        if "maxp" not in self.tables:
            return

        self.otf["maxp"] = maxp = newTable("maxp")
        maxp.tableVersion = 0x00005000
        maxp.numGlyphs = len(self.glyphOrder) 
Example #30
Source File: outlineCompiler.py    From ufo2ft with MIT License 5 votes vote down vote up
def setupTable_gasp(self):
        if "gasp" not in self.tables:
            return

        self.otf["gasp"] = gasp = newTable("gasp")
        gasp_ranges = dict()
        for record in self.ufo.info.openTypeGaspRangeRecords:
            rangeMaxPPEM = record["rangeMaxPPEM"]
            behavior_bits = record["rangeGaspBehavior"]
            rangeGaspBehavior = intListToNum(behavior_bits, 0, 4)
            gasp_ranges[rangeMaxPPEM] = rangeGaspBehavior
        gasp.gaspRange = gasp_ranges