def _loadFromGLIF(self, glifData): try: readGlyphFromString(aString=glifData, glyphObject=self.naked(), pointPen=self.getPointPen()) except GlifLibError: raise FontPartsError("Not valid glif data")
def glifToPy(self, glif): glif = stripText(glif) glif = "<?xml version=\"1.0\"?>\n" + glif glyph = Glyph() readGlyphFromString(glif, glyphObject=glyph, pointPen=glyph, validate=True) return glyph.py()
def _loadFromGLIF(self, glifData): try: readGlyphFromString( aString=glifData, glyphObject=self.naked(), pointPen=self.getPointPen() ) except GlifLibError: raise FontPartsError("Not valid glif data")
def dropEvent(self, event): mimeData = event.mimeData() if mimeData.hasUrls(): paths = mimeData.urls() # pick just one image path = paths[0].toLocalFile() fileName = os.path.basename(path) with open(path, "rb") as imgFile: data = imgFile.read() ext = os.path.splitext(path)[1][1:] # TODO: make sure we cleanup properly when replacing an image with # another if ext.lower() == "glif": otherGlyph = self._glyph.__class__() try: readGlyphFromString(data, otherGlyph, otherGlyph.getPointPen()) except Exception as e: errorReports.showCriticalException(e) return self._glyph.beginUndoGroup() otherGlyph.drawPoints(self._glyph.getPointPen()) self._glyph.endUndoGroup() return if ext.lower() == "svg": try: svgPath = SVGPath.fromstring(data) except Exception as e: errorReports.showCriticalException(e) return self._glyph.beginUndoGroup() svgPath.draw(self._glyph.getPen()) self._glyph.endUndoGroup() return if ext.lower() != "png": # convert img = QImage(path) data = QByteArray() buffer = QBuffer(data) buffer.open(QIODevice.WriteOnly) img.save(buffer, "PNG") # format data = bytearray(data) fileName = "%s.png" % os.path.splitext(fileName)[0] imageSet = self._glyph.font.images try: imageSet[fileName] = data except Exception as e: errorReports.showCriticalException(e) return image = self._glyph.instantiateImage() image.fileName = fileName self._glyph.image = image event.setAccepted(True) else: super().dropEvent(event)
def loadFromGLIF(cls, glifPath): with open(glifPath) as f: data = f.read() self = cls() try: readGlyphFromString(data, self, self.getPointPen()) except Exception: logger.error(f"failed to load .glif file: {glifPath}") raise return self
def test_roundtrip(self): glyph = _Glyph() glyph.name = "a" glyph.unicodes = [0x0061] s1 = writeGlyphToString(glyph.name, glyph) glyph2 = _Glyph() readGlyphFromString(s1, glyph2) assert glyph.__dict__ == glyph2.__dict__ s2 = writeGlyphToString(glyph2.name, glyph2) assert s1 == s2
def testRoundTrip(self): glyph = _Glyph() glyph.name = "a" glyph.unicodes = [0x0061] s1 = writeGlyphToString(glyph.name, glyph) glyph2 = _Glyph() readGlyphFromString(s1, glyph2) self.assertEqual(glyph.__dict__, glyph2.__dict__) s2 = writeGlyphToString(glyph2.name, glyph2) self.assertEqual(s1, s2)
def test_parse_xml_remove_comments(self): s = b"""<?xml version='1.0' encoding='UTF-8'?> <!-- a comment --> <glyph name="A" format="2"> <advance width="1290"/> <unicode hex="0041"/> <!-- another comment --> </glyph> """ g = _Glyph() readGlyphFromString(s, g) assert g.name == "A" assert g.width == 1290 assert g.unicodes == [0x0041]
def test_read_ensure_x_y(self): """Ensure that a proper GlifLibError is raised when point coordinates are missing, regardless of validation setting.""" s = """<?xml version='1.0' encoding='utf-8'?> <glyph name="A" format="2"> <outline> <contour> <point x="545" y="0" type="line"/> <point x="638" type="line"/> </contour> </outline> </glyph> """ pen = RecordingPointPen() with pytest.raises(GlifLibError, match="Required y attribute"): readGlyphFromString(s, _Glyph(), pen) with pytest.raises(GlifLibError, match="Required y attribute"): readGlyphFromString(s, _Glyph(), pen, validate=False)
def make_let(self): # _let = "a" f = NewFont() g = f.newGlyph(_let) pen = g.getPointPen() glyph_result = readGlyphFromString(self.g_data, glyphObject=g, pointPen=pen) # f_g = f[_let] # return f_g
def make_glyph(_g_dat, _name): # _let = _name f = NewFont() g = f.newGlyph(_let) pen = g.getPointPen() glyph_result = readGlyphFromString(_g_dat, glyphObject=g, pointPen=pen) # # f_g = f[_let] # # return f_g
def test_read_allow_format_versions(self): s = """<?xml version='1.0' encoding='utf-8'?> <glyph name="A" format="2"> <advance width="500"/> <unicode hex="0041"/> </glyph> """ # these two calls are are equivalent readGlyphFromString(s, _Glyph(), formatVersions=[1, 2]) readGlyphFromString(s, _Glyph(), formatVersions=[(1, 0), (2, 0)]) # if at least one supported formatVersion, unsupported ones are ignored readGlyphFromString(s, _Glyph(), formatVersions=[(2, 0), (123, 456)]) with pytest.raises( ValueError, match="None of the requested GLIF formatVersions are supported" ): readGlyphFromString(s, _Glyph(), formatVersions=[0, 2001]) with pytest.raises(GlifLibError, match="Forbidden GLIF format version"): readGlyphFromString(s, _Glyph(), formatVersions=[1])
def make_glyph(self, _g_dat, _name): # _let = _name f = NewFont() g = f.newGlyph(_let) pen = g.getPointPen() glyph_result = readGlyphFromString(_g_dat, glyphObject=g, pointPen=pen) # f_g = f[_let] # #print(f_g) # #for contour in f_g: # # print(cont) #contour.autoStartSegment() # return f_g
def test_read_unsupported_format_version(self, caplog): s = """<?xml version='1.0' encoding='utf-8'?> <glyph name="A" format="0" formatMinor="0"> <advance width="500"/> <unicode hex="0041"/> </glyph> """ with pytest.raises(UnsupportedGLIFFormat): readGlyphFromString(s, _Glyph()) # validate=True by default with pytest.raises(UnsupportedGLIFFormat): readGlyphFromString(s, _Glyph(), validate=True) caplog.clear() with caplog.at_level(logging.WARNING, logger="fontTools.ufoLib.glifLib"): readGlyphFromString(s, _Glyph(), validate=False) assert len(caplog.records) == 1 assert "Unsupported GLIF format" in caplog.text assert "Assuming the latest supported version" in caplog.text
def paste(self): isGlyphTab = self.isGlyphTab() widget = self.stackWidget.currentWidget() if isGlyphTab: glyphs = (widget.activeGlyph(),) else: selection = self.glyphCellView.selection() glyphs = widget.glyphsForIndexes(selection) clipboard = QApplication.clipboard() mimeData = clipboard.mimeData() if mimeData.hasFormat("application/x-trufont-glyph-data"): data = pickle.loads(mimeData.data("application/x-trufont-glyph-data")) if len(data) == len(glyphs): for pickled, glyph in zip(data, glyphs): if isGlyphTab: pasteGlyph = glyph.__class__() pasteGlyph.deserialize(pickled) # TODO: if we serialize selected state, we don't need # to do this pasteGlyph.selected = True if ( len(pasteGlyph) or len(pasteGlyph.components) or len(pasteGlyph.anchors) ): glyph.beginUndoGroup() glyph.holdNotifications() count = len(glyph) pen = glyph.getPointPen() # contours, components pasteGlyph.drawPoints(pen) for contour in glyph[count:]: contour.selected = True # anchors for anchor in pasteGlyph.anchors: glyph.appendAnchor(dict(anchor)) # guidelines for guideline in pasteGlyph.guidelines: glyph.appendGuideline(dict(guideline)) glyph.releaseHeldNotifications() glyph.endUndoGroup() else: glyph.deserialize(pickled) return if mimeData.hasFormat("image/svg+xml"): if len(glyphs) == 1: glyph = glyphs[0] try: svgPath = SVGPath.fromstring(mimeData.data("image/svg+xml")) except Exception: pass else: glyph.beginUndoGroup() if not isGlyphTab: glyph.clear() svgPath.draw(glyph.getPen()) glyph.endUndoGroup() return if mimeData.hasText(): if len(glyphs) == 1: glyph = glyphs[0] otherGlyph = glyph.__class__() text = mimeData.text() try: readGlyphFromString(text, otherGlyph, otherGlyph.getPointPen()) except Exception: try: svgPath = SVGPath.fromstring(text) svgPath.draw(otherGlyph.getPen()) except Exception: return glyph.beginUndoGroup() if not isGlyphTab: glyph.clear() otherGlyph.drawPoints(glyph.getPointPen()) glyph.endUndoGroup()