Skip to content

fontlab.flShapeData

flShapeData

The Shared Drawing Record.

What Is flShapeData?

Every flShape has an flShapeData sitting behind it. While flShape is the editing shell you interact with in the layer — it carries the transform, selection state, and lock flags — flShapeData is where the actual drawing lives: the contours, the include list for composites, and the parametric builder reference.

Most of the time you work with flShape directly and never think about flShapeData. But it becomes important in two situations:

Components. When a glyph reuses artwork from another glyph (for example, a shared accent in an accented character), multiple flShape objects across different glyphs can point to the same flShapeData. The referenceCount property tells you how many shapes are currently sharing that data. If referenceCount > 1, you are looking at a shared component — editing the contours inside the flShapeData directly would affect every shape that references it, which is usually not what you want. In that case, work through the flShape and let FontLab manage the copy-on-write logic.

Low-level contour assembly. Sometimes you want to build up contours and structure directly at the data level — for example, when reading from an external source and constructing a shape programmatically. flShapeData lets you manage contours, includes, and ordering without going through the full shape layer machinery.

Why Does referenceCount Matter?

Imagine you have a font with 200 accented characters, all sharing the same acute accent element. That one acute lives in one flShapeData object, referenced by 200 different flShape objects (one per glyph-layer). The referenceCount would be 200. If you need to modify only one glyph's acute, you must first make a private copy of the data. FontLab normally handles this automatically when you edit through the UI, but in scripts that manipulate flShapeData directly, you are responsible for avoiding accidental shared edits.

Tutorial

This tutorial shows how to read shape data from an existing glyph, build new shape data from scratch, and work with composite and component shapes.

import fontlab as fl
from fontlab import flShapeData, flContour, flNode

font  = fl.CurrentFont()

# ----------------------------------------------------------------
# Part 1: Reading shape data from a glyph
# ----------------------------------------------------------------
# Access the shape data via any shape in the glyph's layer.
glyph = font['O']
layer = glyph.layers[0]
shape = layer.shapes[0]

sd = shape.shapeData

# Print the type so we know what kind of shape we're dealing with.
print("ShapeType:", sd.shapeType)       # Contour | Composite | Image | Component
print("Is composite:", sd.isComposite)
print("Is component:", sd.isComponent)

# The reference count tells us how many shapes share this data.
# If it's greater than 1, this is shared component data.
print("Reference count:", sd.referenceCount)
if sd.referenceCount > 1:
    print("  WARNING: Shared data — edits here affect all references!")

# ----------------------------------------------------------------
# Part 2: Inspecting contours through shape data
# ----------------------------------------------------------------
# You can access contours either through flShape.contours or flShapeData.contours.
# The shape data path is useful when you need to work below the shape level.
for contour in sd.contours:
    nodes = contour.nodes()
    print(f"  Contour: {len(nodes)} nodes, closed={contour.closed}")

# The segments property gives you a flat list of all Bézier segments
# across all contours — handy for geometric analysis.
for seg in sd.segments:
    print(f"  Segment: p0={seg.p0}  p3={seg.p3}")

# ----------------------------------------------------------------
# Part 3: Building shape data from scratch
# ----------------------------------------------------------------
# Create a fresh shape data object and add contours to it manually.
new_sd = flShapeData()

# Build a simple square contour and add it.
c = flContour()
c.closed = True
for x, y in [(0, 0), (100, 0), (100, 100), (0, 100)]:
    c.append(flNode(x, y, nodeType='on'))
new_sd.addContour(c)

# After adding contours, arrange them so outer contours precede inner ones.
# This is required for correct rendering in font engines.
reordered = new_sd.arrangeContours()
print("Contours reordered:", reordered)

# Attach a note for traceability — useful in batch-generation scripts.
new_sd.note = "Generated by script — square reference mark"
print("Note:", new_sd.note)

# ----------------------------------------------------------------
# Part 4: Composite shapes — inspecting and reordering children
# ----------------------------------------------------------------
# Find a composite shape in the font (if any) and inspect its children.
for gname in font.glyphsNames:
    g = font[gname]
    for lyr in g.layers:
        for sh in lyr.shapes:
            if sh.isComposite:
                sd2 = sh.shapeData
                children = sd2.includesList()
                print(f"\n{gname}: composite with {len(children)} children")
                for child in children:
                    print(f"  child shapeType={child.shapeType}")

                # Move the first child to the front of the rendering stack.
                if len(children) >= 2:
                    moved = sd2.sendToFront(children[0])
                    print("  Sent first child to front:", moved)
                break  # just show one composite for the tutorial

# ----------------------------------------------------------------
# Part 5: Component shapes — reading the source glyph
# ----------------------------------------------------------------
# Components reference artwork from another glyph.
# Find all components in the font and print where they come from.
glyph = font.get('agrave')
if glyph:
    for lyr in glyph.layers:
        for sh in lyr.shapes:
            if sh.isComponent:
                sd3 = sh.shapeData
                print(f"Component: from '{sd3.componentGlyph}' layer '{sd3.componentLayer}'")

# ----------------------------------------------------------------
# Part 6: Sorting and normalising contours
# ----------------------------------------------------------------
# Sorting is useful before comparing shapes for interpolation compatibility.
shape = layer.shapes[0]
sd = shape.shapeData
sd.sortContours(True)   # True = apply the sort for real
print("Contours sorted.")

fl.Update()

Common Scripting Patterns

Checking if it's safe to edit shape data directly

sd = shape.shapeData
if sd.referenceCount > 1:
    print("Shared data — do not edit directly, work through flShape instead")
else:
    print("Private data — safe to edit directly")

Adding a note to every shape in a glyph (for batch audit)

glyph = font['A']
for layer in glyph.layers:
    for i, shape in enumerate(layer.shapes):
        shape.shapeData.note = f"shape_{i}_layer_{layer.name}"

Getting all Bézier segments for geometric analysis

all_segments = []
for shape in layer.shapes:
    if shape.simpleShape():
        all_segments.extend(shape.shapeData.segments)
print(f"Total segments in layer: {len(all_segments)}")

Listing all component sources in a font

for gname in font.glyphsNames:
    g = font[gname]
    for layer in g.layers:
        for shape in layer.shapes:
            if shape.isComponent:
                src = shape.shapeData.componentGlyph
                print(f"{gname} → component of '{src}'")

Fixing contour winding order on all glyphs

for gname in font.glyphsNames:
    g = font[gname]
    for layer in g.layers:
        for shape in layer.shapes:
            if shape.simpleShape():
                changed = shape.shapeData.arrangeContours()
                if changed:
                    print(f"  Fixed winding in {gname}/{layer.name}")
fl.Update()

Reordering composite children (bring the widest one to front)

for shape in layer.shapes:
    if shape.isComposite:
        sd = shape.shapeData
        children = sd.includesList()
        widest = max(children, key=lambda s: s.boundingBox.width())
        sd.sendToFront(widest)
fl.Update()
# assignContours returns a mapping from old IDs to new contours,
# which lets you remap any anchors or other references.
new_contours = [build_contour()]    # your contour-building function
id_map = shape.shapeData.assignContours(new_contours)
print("ID remapping:", id_map)

Constructors: flShapeData() flShapeData(flObject)

Native bases: object

Captured native MRO: flShapeData, object

Native new allocation evidence (not an init overload): (args, *kwargs) Create and return a new object. See help(type) for accurate signature.

Supplemental documentation: Shape data. The captured declaration exposes addContour, addContours, arrangeContours, assignContours, clearContours, clearIncludesList, goDown, goUp, includesList, removeAnchor, removeContour, sendToBack, sendToFront, sortContours, takeIncludesList, builder, componentGlyph, componentLayer, contours, includes, isComponent, isComposite, referenceCount, segments and shapeType. It is created with no captured constructor overloads. It also carries the shared object members changed, clone, cloneObject, getProperty, setProperty, release, remove and update and the shared attributes id, name, type, isValid and isNull.

Source: FontLab Proteus API documentation

Source: generated/fontlab.py: flShapeData captured declaration

Complete member index

Every captured member retains its own identity. Identical captured declaration text is linked once; this does not establish native inheritance or interchangeable objects.

Member Kind Signature Summary
__init__ function (self, /, *args: Any, **kwargs: Any) -> None Initialize self. (shared captured text)
addContour function (self, arg0: flContour) -> Any Appends a single contour to the end of this shape data's contour list.
addContours function (self, *args: Any, **kwargs: Any) -> Any Appends multiple contours in a single call.
arrangeContours function (self) -> bool Reorders the contours so that outer (clockwise) contours come before inner (counter-clockwise) contours.
assignContours function (self, *args: Any, **kwargs: Any) -> Any Replaces all existing contours with the supplied list.
bindDependencies function (self) -> Any Reconnects all internal dependency links — builder dependencies, property processors, and component references.
builder attribute Any The active flShapeBuilder attached to this shape data, or Nothing if this is a plain drawn shape.
changed function (self) -> Any (shared captured text)
checkInitHistoryState function (self, history_ix: int) -> Any (shared captured text)
clearAboveHistory function (self, history_ix: int) -> Any (shared captured text)
clearContours function (self) -> Any Removes every contour from this shape data, leaving it empty.
clearFlag function (self, f: int) -> Any (shared captured text)
clearFlags function (self) -> Any (shared captured text)
clearIncludesList function (self) -> Any Empties the list of included (composited) child shapes.
clone function (self, *args: Any, **kwargs: Any) -> Any Clone the object (shared captured text)
cloneObject function (*args: Any, **kwargs: Any) -> Any (shared captured text)
componentGlyph attribute Any For component shapes: the name of the glyph whose artwork this shape data references.
componentLayer attribute Any For component shapes: which layer within componentGlyph to reference.
contours attribute Any All contours belonging to this shape data.
createObject function (*args: Any, **kwargs: Any) -> Any FlObject/Nothing createObject(int); (shared captured text)
currentHistoryState function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
flObjectFlags attribute dict (shared captured text)
flag function (self, f: int) -> Any (shared captured text)
getProperties function (self, *args: Any, **kwargs: Any) -> Any Get object's properties list (shared captured text)
getProperty function (self, *args: Any, **kwargs: Any) -> Any Get object property by 'key' or number (shared captured text)
getPropertyFloat function (self, *args: Any, **kwargs: Any) -> Any Get float object property by 'key' (shared captured text)
getPropertyInt function (self, *args: Any, **kwargs: Any) -> Any Get int object property by 'key' (shared captured text)
goDown function (self, arg0: flShape) -> bool Moves the specified child shape one step toward the back of the rendering order (rendered later, closer to the front of the visual stack).
goUp function (self, arg0: flShape) -> bool Moves the specified child shape one step toward the front of the rendering order.
hasChanges attribute Any (shared captured text)
hasHistoryState function (self, history_ix: int) -> Any (shared captured text)
hasHistoryStates attribute Any (shared captured text)
haveObject function (*args: Any, **kwargs: Any) -> Any (shared captured text)
historyStates function (self, accepted_state: bool) -> Any (shared captured text)
id attribute Any Object id (shared captured text)
includes attribute Any The raw include list as an flObjectsList.
includesList function (self) -> Any
independedAll function (self) -> Any (shared captured text)
initialHistoryState function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
instanceType function (*args: Any, **kwargs: Any) -> Any (shared captured text)
isChanged attribute Any (shared captured text)
isComponent attribute Any True if this shape data is a component reference (its contours come from another glyph).
isComposite attribute Any True if this shape data contains an include list of child shapes (composite structure).
isEqual function (self, arg0: flObject) -> Any (shared captured text)
isNull attribute Any (shared captured text)
isPresent attribute Any (shared captured text)
isReleased attribute Any (shared captured text)
isValid attribute Any (shared captured text)
name attribute Any Object name (shared captured text)
note attribute Any A free-text annotation you can attach to any shape data.
prepareTransformationData function (self) -> Any Pre-computes and caches the geometric state needed for interactive transformations (rotate, scale, shear).
propertyNames function (self, *args: Any, **kwargs: Any) -> Any PropertyNames(): sorted snapshot of dynamic property keys (shared captured text)
refCnt attribute Any Object references count (shared captured text)
referenceCount attribute Any How many flShape objects currently point to this shape data.
release function (self) -> Any (shared captured text)
remove function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
removeAnchor function (self, arg0: flAnchor) -> Any Removes the specified anchor from this shape data.
removeChild function (self, arg0: flObject) -> Any (shared captured text)
removeContour function (self, arg0: flContour) -> Any Removes a specific contour from this shape data.
resetTransformationData function (self) -> Any Discards the transformation cache created by prepareTransformationData().
restoreHistoryState function (self, history_ix: int) -> Any (shared captured text)
segments attribute Any All Bézier curve segments from all contours in this shape data, expressed as CurveEx objects.
sendToBack function (self, arg0: flShape) -> bool Moves the specified child shape all the way to the back of the compositing order in one call.
sendToFront function (self, arg0: flShape) -> bool Moves the specified child shape all the way to the front of the compositing order.
setFlag function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
setProperty function (self, *args: Any, **kwargs: Any) -> Any Set object property by 'key' or number (shared captured text)
setPropertyFloat function (self, *args: Any, **kwargs: Any) -> Any Set float object property by 'key' (shared captured text)
setPropertyInt function (self, *args: Any, **kwargs: Any) -> Any Set int object property by 'key' (shared captured text)
shapeType attribute Any An enum value describing the kind of shape data: flContour (plain drawn shape), Composite (contains included children), Image (holds a bitmap), or AccentInfo (references another glyph).
sortContours function (self, action: bool) -> Any Sorts the contour list into a canonical order.
tag function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
takeIncludesList function (self) -> Any
type attribute Any Object type (shared captured text)
update function (self) -> Any (shared captured text)