Get a Glyph’s path?



  • Does anyone have an easy way to get the path to the .glif file, given a Glyph object?

    For a font, you can obviously do this:

    >>> font.path
    
    path/to/my.ufo
    

    but FontParts does not have a glyph.path.

    In the past I have kludged it together using this, but I don't like this:

    import os
    from fontTools.misc.filenames import userNameToFileName
    
    g = CurrentGlyph()
    
    fontPath = g.font.path
    layerName = "glyphs." + userNameToFileName(g.layer.name) if g.layer.name != g.font.defaultLayerName else "glyphs"
    glifName = userNameToFileName(g.name, suffix=".glif")
    
    combined = os.path.join(fontPath, layerName, glifName)
    if os.path.exists(combined):
        print(combined)
    
    path/to/my.ufo/glyphs.background/A_.glif
    

    This makes a ton of assumptions that the UFO follows the convention used by the current fontTools.ufoLib (which will potentially not work if the UFO was made by a different package, or even an older version of ufoLib)

    Anyone have any better ideas to get .glif file for a RGlyph object without having to make so many assumptions?


  • admin

    hello @colinmford,

    I gave it a try using the GlyphSet object, this seems to work:

    import os
    
    def getGlifPath(glyph):
        # get glyphset for currrent layer
        glyphSet = glyph.naked().layer._glyphSet
        # get filename for glyph name
        glifName = glyphSet.glyphNameToFileName(glyph.name, None)
        # glif path = ufo path + layer folder + glif file
        glifPath = os.path.join(glyph.font.path, glyphSet.dirName, glifName)
        return glifPath
    
    g = CurrentGlyph()
    print(getGlifPath(g))
    

    let us know if this works with your data too…

    cheers!



  • @gferreira Much better! And quicker to boot, I think!

    Thanks so much!


  • admin

    a cleaner version without using internal objects

    import os
    from fontTools.ufoLib import UFOReader
    
    def getGlifPath(glyph):
        reader = UFOReader(glyph.font.path)
        # get glyphset for currrent layer
        glyphSet = reader.getGlyphSet(glyph.layer.name)
        # get filename for glyph name
        glifName = glyphSet.glyphNameToFileName(glyph.name, None)
        # glif path = ufo path + layer folder + glif file
        glifPath = os.path.join(glyph.font.path, glyphSet.dirName, glifName)
        return glifPath
    
    g = CurrentGlyph()
    print(getGlifPath(g))
    


  • Thanks, @frederik!