code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
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()
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>`.
getCoordinates
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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
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.
getComponentNames
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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
Remove padding and, if requested, hinting, from a glyph. This works on both expanded and compacted glyphs, without expanding it.
trim
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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()
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.
draw
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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()
Draw the glyph using the supplied pointPen. As opposed to Glyph.draw(), this will not change the point indices.
drawPoints
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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()
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
dropImpliedOnCurvePoints
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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
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.
getComponentInfo
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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() )
Return True if it's a 'simple' component. That is, it has no anchor points and no transform other than integer translate.
_hasOnlyIntegerTranslate
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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
Creates a new ``GlyphCoordinates`` object with all coordinates set to (0,0)
zeros
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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
Creates a new ``GlyphCoordinates`` object which is a copy of the current one.
copy
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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
Sets a point's coordinates to a two element tuple (x,y)
__setitem__
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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
>>> g = GlyphCoordinates([(1,2)]) >>> g2 = GlyphCoordinates([(1.0,2)]) >>> g3 = GlyphCoordinates([(1.5,2)]) >>> g == g2 True >>> g == g3 False >>> g2 == g3 False
__eq__
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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
>>> g = GlyphCoordinates([(1,2)]) >>> g2 = GlyphCoordinates([(1.0,2)]) >>> g3 = GlyphCoordinates([(1.5,2)]) >>> g != g2 False >>> g != g3 True >>> g2 != g3 True
__ne__
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_l_y_f.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
MIT
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)
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.
compileOffsets_
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_g_v_a_r.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_v_a_r.py
MIT
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
Add 'tag' to the list of langauge tags if not already there. Returns the integer index of 'tag' in the list of all tags.
addTag
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_l_t_a_g.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_l_t_a_g.py
MIT
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
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.
recalc
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_m_a_x_p.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_m_a_x_p.py
MIT
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))
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.
setName
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_n_a_m_e.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_n_a_m_e.py
MIT
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() ) ]
Remove any name records identified by the given combination of 'nameID', 'platformID', 'platEncID' and 'langID'.
removeNames
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_n_a_m_e.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_n_a_m_e.py
MIT
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
Remove any name records which are not in NameID range 0-255 and not utilized within the font itself.
removeUnusedNames
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_n_a_m_e.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_n_a_m_e.py
MIT
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
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.
_findUnusedNameID
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_n_a_m_e.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_n_a_m_e.py
MIT
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
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.
addName
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_n_a_m_e.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_n_a_m_e.py
MIT
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
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.
_makeWindowsName
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_n_a_m_e.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_n_a_m_e.py
MIT
def toUnicode(self, errors="strict"): """ 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): 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
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.
toUnicode
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_n_a_m_e.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_n_a_m_e.py
MIT
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
This function will get called by a ttLib.TTFont instance. Do not call this function yourself, use TTFont().getGlyphOrder() or its relatives instead!
getGlyphOrder
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/_p_o_s_t.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_p_o_s_t.py
MIT
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 F_F_T_M_ from . import F__e_a_t from . import G_D_E_F_ from . import G_M_A_P_ from . import G_P_K_G_ 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 J_S_T_F_ from . import L_T_S_H_ from . import M_A_T_H_ from . import M_E_T_A_ from . import M_V_A_R_ from . import O_S_2f_2 from . import S_I_N_G_ 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_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
Dummy function to let modulefinder know what tables may be dynamically imported. Generated by MetaTools/buildTableList.py. >>> _moduleFinderHint()
_moduleFinderHint
python
fonttools/fonttools
Lib/fontTools/ttLib/tables/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/__init__.py
MIT
def convertUFO1OrUFO2KerningToUFO3Kerning(kerning, groups, glyphSet=()): """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 = {} 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 = {} 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)
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.
convertUFO1OrUFO2KerningToUFO3Kerning
python
fonttools/fonttools
Lib/fontTools/ufoLib/converters.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/converters.py
MIT
def findKnownKerningGroups(groups): """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
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
findKnownKerningGroups
python
fonttools/fonttools
Lib/fontTools/ufoLib/converters.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/converters.py
MIT
def makeUniqueGroupName(name, groupNames, counter=0): """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
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.
makeUniqueGroupName
python
fonttools/fonttools
Lib/fontTools/ufoLib/converters.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/converters.py
MIT
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 """
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
test
python
fonttools/fonttools
Lib/fontTools/ufoLib/converters.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/converters.py
MIT
def userNameToFileName(userName: str, existing=(), prefix="", suffix=""): """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
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
userNameToFileName
python
fonttools/fonttools
Lib/fontTools/ufoLib/filenames.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/filenames.py
MIT
def handleClash1(userName, existing=[], prefix="", suffix=""): """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
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
handleClash1
python
fonttools/fonttools
Lib/fontTools/ufoLib/filenames.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/filenames.py
MIT
def handleClash2(existing=[], prefix="", suffix=""): """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
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
handleClash2
python
fonttools/fonttools
Lib/fontTools/ufoLib/filenames.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/filenames.py
MIT
def draw(self, pen, outputImpliedClosingLine=False): """ Draw this glyph onto a *FontTools* Pen. """ pointPen = PointToSegmentPen( pen, outputImpliedClosingLine=outputImpliedClosingLine ) self.drawPoints(pointPen)
Draw this glyph onto a *FontTools* Pen.
draw
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def __init__( self, path, glyphNameToFileNameFunc=None, ufoFormatVersion=None, validateRead=True, validateWrite=True, expectContentsFile=False, ): """ '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 = 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.osfs.OSFS(path) except fs.errors.CreateFailed: raise GlifLibError("No glyphs directory '%s'" % path) self._shouldClose = 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 = fs.path.parts(path)[-1] self.fs = filesystem # if glyphSet contains no 'contents.plist', we consider it empty self._havePreviousFile = filesystem.exists(CONTENTS_FILENAME) if expectContentsFile and not self._havePreviousFile: raise GlifLibError(f"{CONTENTS_FILENAME} is missing.") # attribute kept for backward compatibility self.ufoFormatVersion = ufoFormatVersion.major self.ufoFormatVersionTuple = ufoFormatVersion if glyphNameToFileNameFunc is None: glyphNameToFileNameFunc = glyphNameToFileName self.glyphNameToFileName = glyphNameToFileNameFunc self._validateRead = validateRead self._validateWrite = validateWrite self._existingFileNames: set[str] | None = None self._reverseContents = None self.rebuildContents()
'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.
__init__
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def rebuildContents(self, validateRead=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 = contents self._existingFileNames = None self._reverseContents = 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.
rebuildContents
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def getReverseContents(self): """ 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
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.
getReverseContents
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def readLayerInfo(self, info, validateRead=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 )
``validateRead`` will validate the data, by default it is set to the class's ``validateRead`` value, can be overridden.
readLayerInfo
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def writeLayerInfo(self, info, validateWrite=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)
``validateWrite`` will validate the data, by default it is set to the class's ``validateWrite`` value, can be overridden.
writeLayerInfo
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def getGLIF(self, glyphName): """ 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) )
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.
getGLIF
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def readGlyph(self, glyphName, glyphObject=None, pointPen=None, validate=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
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.
readGlyph
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def writeGlyph( self, glyphName, glyphObject=None, drawPointsFunc=None, formatVersion=None, validate=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 = GLIFFormatVersion(formatVersion) 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)
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.
writeGlyph
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def deleteGlyph(self, glyphName): """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]
Permanently delete the glyph from the glyph set on disk. Will raise KeyError if the glyph is not present in the glyph set.
deleteGlyph
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def getUnicodes(self, glyphNames=None): """ 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
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.
getUnicodes
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def getComponentReferences(self, glyphNames=None): """ 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
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.
getComponentReferences
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def getImageReferences(self, glyphNames=None): """ 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
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.
getImageReferences
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def glyphNameToFileName(glyphName, existingFileNames): """ 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")
Wrapper around the userNameToFileName function in filenames.py Note that existingFileNames should be a set for large glyphsets or performance will suffer.
glyphNameToFileName
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def readGlyphFromString( aString, glyphObject=None, pointPen=None, formatVersions=None, validate=True, ): """ 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 = GLIFFormatVersion.supported_versions() else: validFormatVersions, invalidFormatVersions = set(), set() for v in formatVersions: try: formatVersion = GLIFFormatVersion(v) 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, )
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.
readGlyphFromString
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def _writeGlyphToBytes( glyphName, glyphObject=None, drawPointsFunc=None, writer=None, formatVersion=None, validate=True, ): """Return .glif data for a glyph as a UTF-8 encoded bytes string.""" try: formatVersion = GLIFFormatVersion(formatVersion) 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() # 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
Return .glif data for a glyph as a UTF-8 encoded bytes string.
_writeGlyphToBytes
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def writeGlyphToString( glyphName, glyphObject=None, drawPointsFunc=None, formatVersion=None, validate=True, ): """ 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")
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.
writeGlyphToString
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def validateLayerInfoVersion3ValueForAttribute(attr, value): """ 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 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
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.
validateLayerInfoVersion3ValueForAttribute
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def validateLayerInfoVersion3Data(infoData): """ 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
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.
validateLayerInfoVersion3Data
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def _number(s): """ 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 = 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)
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.
_number
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def _fetchUnicodes(glif): """ Get a list of unicodes listed in glif. """ parser = _FetchUnicodesParser() parser.parse(glif) return parser.unicodes
Get a list of unicodes listed in glif.
_fetchUnicodes
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def _fetchImageFileName(glif): """ The image file name (if any) from glif. """ parser = _FetchImageFileNameParser() try: parser.parse(glif) except _DoneParsing: pass return parser.fileName
The image file name (if any) from glif.
_fetchImageFileName
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def _fetchComponentBases(glif): """ Get a list of component base glyphs listed in glif. """ parser = _FetchComponentBasesParser() try: parser.parse(glif) except _DoneParsing: pass return list(parser.bases)
Get a list of component base glyphs listed in glif.
_fetchComponentBases
python
fonttools/fonttools
Lib/fontTools/ufoLib/glifLib.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/glifLib.py
MIT
def lookupKerningValue( pair, kerning, groups, fallback=0, glyphToFirstGroup=None, glyphToSecondGroup=None ): """Retrieve the kerning value (if any) between a pair of elements. The elments can be either individual glyphs (by name) or kerning groups (by name), or any combination of the two. 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 set of kerning groups. 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 """ # quickly check to see if the pair is in the kerning dictionary if pair in kerning: return kerning[pair] # create glyph to group mapping if glyphToFirstGroup is not None: assert glyphToSecondGroup is not None if glyphToSecondGroup is not None: assert glyphToFirstGroup is not None if glyphToFirstGroup is None: 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 # 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 first = None else: firstGroup = glyphToFirstGroup.get(first) if second.startswith("public.kern2."): secondGroup = second second = None else: secondGroup = glyphToSecondGroup.get(second) # make an ordered list of pairs to look up pairs = [ (first, second), (first, secondGroup), (firstGroup, second), (firstGroup, secondGroup), ] # 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
Retrieve the kerning value (if any) between a pair of elements. The elments can be either individual glyphs (by name) or kerning groups (by name), or any combination of the two. 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 set of kerning groups. 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
lookupKerningValue
python
fonttools/fonttools
Lib/fontTools/ufoLib/kerning.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/kerning.py
MIT
def deprecated(msg=""): """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): @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 wrapper return deprecated_decorator
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
deprecated
python
fonttools/fonttools
Lib/fontTools/ufoLib/utils.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/utils.py
MIT
def isDictEnough(value): """ 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
Some objects will likely come in that aren't dicts but are dict-ish enough.
isDictEnough
python
fonttools/fonttools
Lib/fontTools/ufoLib/validators.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/validators.py
MIT
def identifierValidator(value): """ 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: c = ord(c) if c < validCharactersMin or c > validCharactersMax: return False return True
Version 3+. >>> identifierValidator("a") True >>> identifierValidator("") False >>> identifierValidator("a" * 101) False
identifierValidator
python
fonttools/fonttools
Lib/fontTools/ufoLib/validators.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/validators.py
MIT
def colorValidator(value): """ 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 try: part = int(part) converted = True except ValueError: pass if not converted: try: part = float(part) converted = True except ValueError: pass if not converted: return False if part < 0: return False if part > 1: return False return True
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
colorValidator
python
fonttools/fonttools
Lib/fontTools/ufoLib/validators.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/validators.py
MIT
def pngValidator(path=None, data=None, fileObj=None): """ 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
Version 3+. This checks the signature of the image data.
pngValidator
python
fonttools/fonttools
Lib/fontTools/ufoLib/validators.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/validators.py
MIT
def layerContentsValidator(value, ufoPathOrFileSystem): """ 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
Check the validity of layercontents.plist. Version 3+.
layerContentsValidator
python
fonttools/fonttools
Lib/fontTools/ufoLib/validators.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/validators.py
MIT
def groupsValidator(value): """ 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 = {} secondSideMapping = {} 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
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.
groupsValidator
python
fonttools/fonttools
Lib/fontTools/ufoLib/validators.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/validators.py
MIT
def kerningValidator(data): """ 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
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.
kerningValidator
python
fonttools/fonttools
Lib/fontTools/ufoLib/validators.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/validators.py
MIT
def fontLibValidator(value): """ 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
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,...
fontLibValidator
python
fonttools/fonttools
Lib/fontTools/ufoLib/validators.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/validators.py
MIT
def glyphLibValidator(value): """ 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
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.
glyphLibValidator
python
fonttools/fonttools
Lib/fontTools/ufoLib/validators.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/validators.py
MIT
def getFileModificationTime(self, path): """ 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: return dt.timestamp()
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.
getFileModificationTime
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def _getPlist(self, fileName, default=None): """ 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}")
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.
_getPlist
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def _writePlist(self, fileName, obj): """ 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.openbin(fileName, mode="w") 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) )
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.
_writePlist
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def _upConvertKerning(self, validate): """ 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
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.
_upConvertKerning
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def readBytesFromPath(self, path): """ 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
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.
readBytesFromPath
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def getReadFileForPath(self, path, encoding=None): """ 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.openbin(path) else: return self.fs.open(path, mode="r", encoding=encoding) except fs.errors.ResourceNotFound: return None
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.
getReadFileForPath
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def _readMetaInfo(self, validate=None): """ 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
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.
_readMetaInfo
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def readMetaInfo(self, validate=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"]
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.
readMetaInfo
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def readGroups(self, validate=None): """ 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 = self._upConvertedKerningData["groups"] # normal else: groups = self._readGroups() if validate: valid, message = groupsValidator(groups) if not valid: raise UFOLibError(message) return groups
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.
readGroups
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def getKerningGroupConversionRenameMaps(self, validate=None): """ 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 self._upConvertedKerningData["groupRenameMaps"]
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.
getKerningGroupConversionRenameMaps
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def readInfo(self, info, validate=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 )
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.
readInfo
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def readKerning(self, validate=None): """ 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 = 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
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.
readKerning
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def readLib(self, validate=None): """ 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
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.
readLib
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def readFeatures(self): """ 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 ""
Read features.fea. Return a string. The returned string is empty if the file is missing.
readFeatures
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def _readLayerContents(self, validate): """ 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
Rebuild the layer contents list by checking what glyphsets are available on disk. ``validate`` will validate the layer contents.
_readLayerContents
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def getLayerNames(self, validate=None): """ 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
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.
getLayerNames
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def getDefaultLayerName(self, validate=None): """ 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.")
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.
getDefaultLayerName
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def getGlyphSet(self, layerName=None, validateRead=None, validateWrite=None): """ 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, )
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.
getGlyphSet
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def getCharacterMapping(self, layerName=None, validate=None): """ 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 = {} for glyphName, unicodes in allUnicodes.items(): for code in unicodes: if code in cmap: cmap[code].append(glyphName) else: cmap[code] = [glyphName] return cmap
Return a dictionary that maps unicode values (ints) to lists of glyph names.
getCharacterMapping
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def getDataDirectoryListing(self): """ 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 []
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.
getDataDirectoryListing
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def getImageDirectoryListing(self, validate=None): """ 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.openbin(path.name) as fp: valid, error = pngValidator(fileObj=fp) if valid: result.append(path.name) else: result.append(path.name) return result
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.
getImageDirectoryListing
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def readData(self, fileName): """ 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
Return bytes for the file named 'fileName' inside the 'data/' directory.
readData
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def readImage(self, fileName, validate=None): """ 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
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.
readImage
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def copyFromReader(self, reader, sourcePath, destPath): """ 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)
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.
copyFromReader
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def writeBytesToPath(self, path, data): """ 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)
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.
writeBytesToPath
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def getFileObjectForPath(self, path, mode="w", encoding=None): """ 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: return UFOLibError(f"unable to open '{path}' on {self.fs}: {e}")
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.
getFileObjectForPath
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def removePath(self, path, force=False, removeEmptyParents=True): """ 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)
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.
removePath
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def setModificationTime(self): """ 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)
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.
setModificationTime
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def setKerningGroupConversionRenameMaps(self, maps): """ 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)
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.
setKerningGroupConversionRenameMaps
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def writeGroups(self, groups, validate=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)
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.
writeGroups
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def writeInfo(self, info, validate=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)
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.
writeInfo
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def writeKerning(self, kerning, validate=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 = {} 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)
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.
writeKerning
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def writeLib(self, libDict, validate=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)
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.
writeLib
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def writeFeatures(self, features, validate=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)
Write features.fea. This method requires a features string as an argument.
writeFeatures
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT