Copy glyph from default layer to another

  • I'm trying to copy a glyph from its default layer to a background layer. I'm doing it in script, so I can eventually do it for all glyphs in a UFO.

    I think this copying is relatively simple with a pointPen, but I must be missing a critical part.

    Here's my code for doing it to the current glyph, which already has a "bg" layer (unless I'm misunderstanding the UFO structure, which is a possibility). It doesn't yet work.

    glyph = CurrentGlyph()
    glyphDefaultLayerName = glyph.layers[0]
    glyphDefaultLayer = glyph.getLayer(glyphLayerName)
    pen = glyphDefaultLayer.getPointPen()
    # just to make sure layer is there and cleared
    glyphLayer = glyph.newLayer("bg")
    ## doesn't work ... not sure why
    ## also doesn't work
    # f.getLayer("bg")[].drawPoints(pen)

    Any insight is very appreciated!

  • Was told the solution by a helpful person. Turns out, copyToLayer works great!

    Also, I didn't need to get the name of the layer and use that to get the layer... obviously. 😄

    Here's the code:

    glyph = CurrentGlyph()
    glyph.layers[0].copyToLayer("bg", clear=True)
    # apparently, better than matching `width`
    glyph.getLayer("bg").leftMargin = glyph.layers[0].leftMargin
    glyph.getLayer("bg").rightMargin = glyph.layers[0].rightMargin

  • Basic question, how might one rewrite this for selected glyphs only?

  • admin

    font = CurrentFont()
    # use font.templateSelectedGlyphNames is you need the template glyphs
    for glyphName in font.selectedGlyphNames:
        glyph = font[glyphName]
        # the above script

    good luck!!

  • As a later follow-up, I've found that copyLayerToLayer is actually more what I was looking for, as it just copies over everything without issue: contours, anchors, width, guidelines. copyToLayer is nice in that it gives more control, if you want it.

    from mojo.UI import AskString
    f = CurrentFont()
    newLayer = AskString('Layer to copy all existing glyphs to, e.g. "overlap"')
    for glyph in f:
        glyph.layers[0].copyLayerToLayer("foreground", newLayer)