Skip to content

fontlab.flShape

flShape

The Element.

What Is an flShape?

In FontLab's interface, what you see as an element in the Glyph window is an flShape in Python. Every time you draw a contour, paste artwork, or use a parametric element (like a stroke or an inline), FontLab wraps that drawing in an flShape and places it on a layer.

Think of flShape as the editing shell around your drawing. It carries: - The geometric transform that positions the element within the glyph - Selection and lock state - Colour/opacity for colour font work - A reference to the actual drawing data (flShapeData)

The Three Kinds of Shape

Understanding which type of shape you're working with will save you a lot of confusion in scripts:

Simple shape — This is the most common kind. It directly holds a list of flContour objects. When you draw an "A", the stem, the crossbar, and the counter are each contours inside one or more simple shapes. isComposite is False. The current simpleShape() implementation always returns False, so use shape type and component/composite checks when selecting editable contours.

Composite shape — A composite is a shape that contains other shapes as children (its "include list"). In the UI you make a composite by grouping elements together. The sub-shapes live inside and can be rearranged, ejected back out, or merged down. isComposite is True.

Component shape — A component references the shape data of another glyph. When you place an accented character like "Á" and the acute accent is reused from another glyph, it arrives as a component shape. isComponent is True and shapeData.componentGlyph tells you the source glyph name. You cannot edit the contours of a component directly — you must decompose it first.

Inherits from flObject.

Tutorial

This tutorial walks through the most common shape scripting tasks: reading shapes from a glyph, building new shapes, and working with composites.

import fontlab as fl
from fontlab import flShape, flContour, flNode
from PythonQt.QtCore import QPointF
from PythonQt.QtGui import QTransform

font  = fl.CurrentFont()
glyph = font['A']
layer = glyph.layers[0]

# --- Reading shapes from a layer ---
# Each item in layer.shapes is an flShape. Let's see what we're working with.
for sh in layer.shapes:
    kind = "composite" if sh.isComposite else ("component" if sh.isComponent else "simple")
    print(f"Shape: {kind}, contours={sh.contoursCount}, bounds={sh.boundingBox}")

# --- Inspecting contours of a simple shape ---
# Make sure it's a simple shape before trying to iterate contours.
shape = layer.shapes[0]
if shape.simpleShape():
    for contour in shape.getContours():
        nodes = contour.nodes()
        print(f"  Contour: {len(nodes)} nodes, closed={contour.closed}")

# --- Building a new rectangular shape and adding it to the layer ---
# First create the shape object, then build contour geometry, then add to layer.
new_shape = flShape()
rect = flContour()
rect.closed = True

# Add four corner nodes for a 200×300 rectangle
for x, y in [(0, 0), (200, 0), (200, 300), (0, 300)]:
    rect.add(flNode(x, y, nodeType='on'))
new_shape.addContour(rect)

# Add the new shape to the layer so it appears in the glyph
layer.addShape(new_shape)
print("Added rectangular shape. Bounds:", new_shape.boundingBox)

# --- Moving a shape by changing its transform ---
# Prepare the transform cache before any geometric operation.
new_shape.prepareTransformationData()
tx = QTransform().translate(50, 0)   # move 50 units to the right
new_shape.applyTransform(tx)
new_shape.resetTransformationData()
print("After move, bounds:", new_shape.boundingBox)

# --- Checking and clearing selection ---
# Useful at the start of a script that will set a specific selection.
new_shape.unselectAllNodes()

# --- Working with a composite shape ---
# Check if any shapes on this layer are composites and inspect their children.
for sh in layer.shapes:
    if sh.isComposite:
        print(f"Composite with {len(sh.includesList)} children")
        for child in sh.includesList:
            print(f"  child type: {child.shapeType}")

        # To break a composite apart, use ejectTo.
        # apply_tx=True keeps each child in its current visual position.
        children = sh.ejectTo(clone=True, apply_tx=True)
        print(f"Ejected {len(children)} shapes from composite")

# --- Checking for components (references to other glyphs) ---
# Components cannot be edited until you decompose them.
for sh in layer.shapes:
    if sh.isComponent:
        src = sh.shapeData.componentGlyph
        print(f"Component references glyph: {src}")
        # Decompose to get real editable contours:
        sh.decomposite()
        print("  Decomposed to plain contours")

# --- Working with anchors on a shape ---
# Anchors are used for diacritic attachment. Most shapes won't have them.
for sh in layer.shapes:
    anchors = sh.getAnchors()
    if anchors:
        for anchor in anchors:
            print(f"Anchor at: {anchor.anchorPoint}")

# --- Checking interpolation compatibility for variable fonts ---
# Before writing interpolation scripts, verify shape compatibility.
if len(layer.shapes) >= 2:
    s1, s2 = layer.shapes[0], layer.shapes[1]
    compat = s1.isCompatible(s2, strong=True)
    print("Shapes are compatible for interpolation:", compat)

# Always call Update() after making changes so FontLab redraws the glyph.
fl.Update()

Common Scripting Patterns

Iterating over all shapes and their contours

for shape in layer.shapes:
    if not shape.simpleShape():
        continue   # skip composites and components
    for contour in shape.getContours():
        for node in contour.nodes():
            print(node.x, node.y)

Finding the shape with the largest bounding box

biggest = max(layer.shapes, key=lambda sh: sh.boundingBox.width() * sh.boundingBox.height())
print("Largest shape bounds:", biggest.boundingBox)

Locking all shapes except the active one

for shape in layer.shapes:
    if not shape.active:
        shape.contentLocked = True

Moving every shape by a fixed offset without touching the node coordinates

offset = QTransform().translate(20, -10)
for shape in layer.shapes:
    shape.prepareTransformationData()
    shape.applyTransform(offset)
    shape.resetTransformationData()
fl.Update()

Excluding all empty shapes from export

for shape in layer.shapes:
    if shape.isEmpty:
        shape.excluded = True
print("Empty shapes flagged for exclusion from export")

Decomposing all components in a glyph to editable contours

glyph = font['agrave']
for layer in glyph.layers:
    for shape in layer.shapes:
        if shape.isComponent:
            shape.decomposite()
fl.Update()

Checking if a glyph has any composite or component shapes

def has_non_simple_shapes(glyph):
    for layer in glyph.layers:
        for shape in layer.shapes:
            if shape.isComposite or shape.isComponent:
                return True
    return False

Stroke scripting

penParameters is a readable/writable dictionary using the stroke keys stored in VFJ/VFC:

  • thickness (or the input alias width), join (miter, bevel, round), and miter_limit agree with the element's QPen.
  • proportion and contrast use percentages; rotation uses degrees.
  • proportion is the share of thickness on the left of the path direction: 0 is entirely on the right, 50 is centered, and 100 is entirely on the left. Reversing the path with the same proportion swaps the geometric side.
  • cap0 and cap1 select the start/end cap. cap_offset0/1, cap_shaping0/1, and cap_curvature0/1 use percentages; cap_rotation0/1 uses degrees.
  • remove_overlap is a boolean. tolerance specifies stroke approximation tolerance.

Assigning a dictionary replaces the extended parameters; omitted extended values return to their defaults. Omitted width, join, miter, and cap type are initialized from the current QPen. The getter includes those values explicitly, so its result can be copied to another element. Positive thickness enables a stroke; zero disables it. The setter preserves the pen's brush/color. Non-dictionaries raise TypeError; invalid or non-finite numeric values and negative thickness raise ValueError before changing the element.

Assigning shape.pen = qpen enables a live stroke when the pen style is not NoPen. Width, join, and miter limit come from QPen. Enabling a stroke or changing QPen's cap style initializes both native end caps from that style. Changes to color, width, or join that keep the same cap style preserve explicit cap0/cap1 and their shaping parameters. Use penParameters for different start/end caps or custom cap geometry.

A fresh QPen uses miter limit 2; native PenParameters and the Add Stroke dialog default to 3. Specify miter_limit explicitly for reproducible imports. Native miter joins clip the tip when it exceeds the limit times the local side width (half the thickness for a centered circular stroke). This is not an SVG/Figma miter-to-bevel conversion rule.

shape.penParameters = {
    "thickness": 40,
    "cap0": "round", "cap1": "round",
    "join": "round", "contrast": 75, "rotation": 30,
}
style = shape.penParameters
other.penParameters = style
expanded = shape.expandStroke()  # equivalent to expandStroke(False)

expandStroke([outer_only]) -> bool replaces one element's stroke with filled outlines using the native stroke engine, without requiring a canvas selection. The fill uses the former pen brush; the stroke is removed. Opacity, transform, locking, and non-spacing state are preserved. It returns False without replacing the element when there is no usable stroke or no outline can be generated. outer_only=True requests the native outer-only expansion mode. This is a geometry operation, not a guarantee of interpolation-compatible results between masters.

The return value is a success flag; read shape.contours after expansion for the resulting contours. shape.inkBox() measures a live stroke without expanding it, using the native preview approximation. boundingBox remains a padded estimate.

Both operations modify the model. Scripts editing document elements must manage history and send the usual change notifications themselves.

Smart corners and ink traps

shape.addSmartCorner(node, radius=20, smooth=False) adds or updates a live smart corner and returns True when applicable. Use a negative radius for an ink trap. smooth=True enables G2 smoothing of rounded corners. The node must belong to the shape's editable source and have two nonzero, non-collinear tangents. Smooth points, handles, open endpoints, foreign nodes and locked shapes return False. Invalid radii (zero, nonfinite or outside ±10000000) raise ValueError in Python.

shape.addSmartCorners(radius=20, smooth=False) adds corners to every applicable node that does not already have one, and returns the number added. Repeated calls preserve existing smart corners. Components, groups and incompatible filters are skipped.

Both methods create the native Smart Corners filter automatically, preserving the element's transform and paint. Existing Smart Corners filters are reused. New filters use the owning font's corner tension and ink-trap length, or defaults for detached elements. The editable contours are cloned when the filter is first installed: reacquire nodes through shape.smartCornerSource().contours afterwards. This method returns the shape itself for plain outlines and a null shape for unsupported or locked content.

# Bulk addition, with automatic filter management:
added = shape.addSmartCorners(20)
# Update one source node into an ink trap:
source = shape.smartCornerSource()
shape.addSmartCorner(source.contours[0].nodes()[0], -15)

Notify changes once at glyph level after a script's edits. A complete current-glyph sample is in examples/python/add_smart_corners.py.

MCP: inspect with get_glyph_nodes, then send edit_glyph_nodes an operation such as {"op":"smart_corner","shape_index":0,"contour_index":0,"node_index":2,"radius":20,"smooth":false}. smart_corner_applicable identifies eligible nodes; smart_radius is null for ordinary nodes. The tool creates/reuses the filter and supports atomic batches, dry_run and Undo. Reads and subsequent edits use the filter's source indices.

Constructors: flShape() flShape(flObject) flShape(flShapeData) flShape(flSticker) flShape(QImage) flShape(fgShape) flShape(flShapeBuilder)

Native bases: object

Captured native MRO: flShape, 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: An editing shape with a contours collection of flContour objects. getContours() also returns its contours, and contoursCount reports their count. boundingBox is a QRectF attribute. Read the captured boolean attributes isComponent and isComposite to inspect the shape kind.

Source: FontLab Proteus API documentation

Source: generated/fontlab.py: flShape 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)
activateBuilder function (self) -> Any Enters the shape-builder editing mode for this shape, as if you had double-clicked to enter the parametric element.
active attribute Any Whether this is the currently active (selected for editing) shape in its layer.
addContour function (self, arg0: flContour, check_duplicate: Any=False, validate: Any=True) -> Any Appends a single contour to this shape.
addContours function (self, *args: Any, **kwargs: Any) -> Any Adds multiple contours in one call.
addSmartCorner function (self, node: flNode, radius: float=20, smooth: bool=False) -> bool Bool addSmartCorner(flNode node, float radius=20, bool smooth=False) - add/update a live smart corner; negative radius creates an ink trap; manages the filter; reacquire source nodes afterwards
addSmartCorners function (self, radius: float=20, smooth: bool=False) -> int Int addSmartCorners(float radius=20, bool smooth=False) - add live smart corners at applicable nodes, skip existing corners, return count; manages/reuses the filter
allSelectedData attribute Any True if every node and every sub-shape in this shape is selected.
appendAnchor function (self, node: flNode, guideline: flObject) -> Any Adds an anchor to this shape.
applyTransform function (self, *args: Any, **kwargs: Any) -> Any Bakes the current transform (or a given transform) into the actual node coordinates, then resets the shape's transform to identity.
assign function (self, arg0: fgShape) -> Any Replaces all of this shape's content with the data from a low-level fontgate shape object.
assignStyle function (self, arg0: flShape) -> Any Copies the visual style properties (pen, brush, opacity) from another shape onto this one.
bindDependencies function (self) -> Any Rebuilds all internal dependency links between this shape and its parametric processors.
boundingBox attribute Any Fast bounds in element-local coordinates, padded symmetrically for stroke thickness, proportion, and miter settings.
brush attribute Any The fill brush used when rendering this shape in colour font mode.
canUngroup function (self) -> bool Returns True if the shape is a composite or grouped structure that can be split apart into its constituent sub-shapes.
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 Deletes every contour from this shape, leaving it empty.
clearFlag function (self, f: int) -> Any (shared captured text)
clearFlags function (self) -> Any (shared captured text)
clone function (self, *args: Any, **kwargs: Any) -> Any Clone the object (shared captured text)
cloneObject function (*args: Any, **kwargs: Any) -> Any (shared captured text)
cloneTopLevel function (self) -> flShape Creates a copy of this shape's top-level composite structure (without deep-copying all sub-shapes).
closedPath attribute Any A Qt painter path containing only the closed contours.
contains function (self, arg0: QPointF) -> bool Tests whether a given point in glyph-space coordinates falls inside the filled area of this shape.
containsInInclude function (self, id: Any) -> bool Returns True if a given shape (or a shape with the given ID) is in this composite's include list.
contentLocked attribute Any When True, the shape's contours cannot be edited in the UI.
contours attribute Any Direct access to the contour list.
contoursCount attribute Any The number of contours in this shape.
convertToFgShape function (self, arg0: fgShape) -> Any Writes this shape's data into an existing fontgate shape object.
copyToFgShape function (self, arg0: fgShape) -> Any Like convertToFgShape but performs a full deep copy into the fontgate shape.
createInstance function () -> flShape Allocates and returns a fresh, empty shape.
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)
cutContour function (self, *args: Any, **kwargs: Any) -> Any Cuts this shape using a contour as a knife, returning two lists: contours inside the knife shape and contours outside.
decomposite function (self) -> Any Flattens all composite children into real contours in place, destroying the composite hierarchy.
eject function (self, arg0: flShape) -> Any Removes a specific child shape from this composite and releases it as an independent shape.
ejectTo function (self, clone: Any=...) -> Any Breaks the entire composite apart, returning all child shapes as a Python list.
ensurePaths function (self) -> Any Forces FontLab to regenerate all path data for this shape from the current node coordinates.
excluded attribute Any When True, this shape is excluded from export.
expandStroke function (self, *args: Any, **kwargs: Any) -> Any Bool expandStroke([bool outer_only]) - replace the stroke with its filled outline
findNode function (self, arg0: str) -> flNode Searches all contours within this shape for a node with the given name.
flObjectFlags attribute dict (shared captured text)
fl_transform attribute Any The shape's spatial transform expressed as an flTransform object, which includes scale, rotation, and translation with designer-friendly decomposition.
flag function (self, f: int) -> Any (shared captured text)
getActiveComposite function (self) -> Any FlShape/Nothing getActiveComposite()
getActiveIncludeShape function (self) -> Any FlShape/Nothing getActiveIncludeShape()
getAnchorForObject function (self, arg0: flObject) -> Any FlAnchor/Nothing getAnchorForObject(flObject)
getAnchors function (self) -> Any Returns all anchors attached to this shape.
getCompositesBounding function (self) -> QRectF Computes the combined bounding box across all sub-shapes in a composite.
getContours function (self) -> Any Returns every flContour that belongs to this shape as a Python list.
getNodeAt function (self, index: int, nodetype: Any) -> Any FlNode/Nothing getNodeAt(int index, flNode::NodeType nodetype)
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)
getSelected function (self, SelectionMode: Any) -> Any Returns the contours (or nodes, depending on SelectionMode) that are currently selected in the UI.
getSquare function (self) -> float Returns the signed total area of all contours combined.
getTransformationPermissions function (self, *args: Any, **kwargs: Any) -> Any Returns a tuple of three booleans indicating whether horizontal movement, vertical movement, and rotation are permitted on this shape.
hasBody attribute Any True if the shape contains at least one contour with drawing content.
hasChanges attribute Any (shared captured text)
hasComponents attribute Any True if this shape references one or more component shapes (shapes from other glyphs).
hasContours attribute Any True if the shape has any contour data at all.
hasGlobalAnchoring attribute Any True if this shape uses global anchoring — a system where the shape's position is determined by an anchor rather than a free transform.
hasHistoryState function (self, history_ix: int) -> Any (shared captured text)
hasHistoryStates attribute Any (shared captured text)
hasImage function (self, bitmap_only: bool) -> bool Returns True if this shape contains image data.
hasPath attribute Any True if the shape has a valid Qt painter path cached.
hasSelected function (self, SelectionMode: Any) -> bool Returns True if there is anything selected in this shape matching the given selection mode.
hasSmartAngle attribute Any True if any nodes in this shape are smart-angle nodes (nodes that carry automatic corner angle data).
haveActiveShape attribute Any True if a sub-shape within this composite is currently active.
haveClosed attribute Any True if at least one closed contour exists in this shape.
haveData attribute Any True if the shape has any data at all — contours, composites, or images.
haveObject function (*args: Any, **kwargs: Any) -> Any (shared captured text)
haveUnclosed attribute Any True if any open contours exist.
historyStates function (self, accepted_state: bool) -> Any (shared captured text)
horzReflection function (self) -> bool Returns True if this shape has a horizontal reflection flag set, meaning it is mirrored left-to-right.
id attribute Any Object id (shared captured text)
image attribute Any The bitmap image data for image-type shapes.
imagePtr attribute Any QImage *
include function (self, *args: Any, **kwargs: Any) -> Any Adds one or more shapes as children of this composite shape.
includeTo function (self, ix: int, arg1: flShape) -> Any Inserts a shape into the include list at a specific position rather than appending at the end.
includesList attribute Any The list of child shapes contained within this composite shape.
independedAll function (self) -> Any (shared captured text)
initialHistoryState function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
inkBox function (self, tx: Any=...) -> QRectF Returns the bounding rectangle of the shape's actual ink (visible filled area), optionally transformed by tx.
instanceType function (*args: Any, **kwargs: Any) -> Any (shared captured text)
isChanged attribute Any (shared captured text)
isCompatible function (self, arg0: flShape, strong: bool) -> bool Checks whether this shape and another are interpolation-compatible — meaning they have the same number of nodes in the same order.
isComponent attribute Any True if this shape is a component reference — its drawing data comes from another glyph's shape, not from locally stored contours.
isComposite attribute Any True if this shape is a composite — it contains other shapes as children in an include list.
isEmpty attribute Any True if the shape has no contours, no composites, and no image.
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)
isShape function (arg0: flObject) -> bool Tests whether a generic flObject reference is actually an flShape.
isUnbindedDependencies attribute Any True if this shape has unresolved dependency links — for example, a parametric element whose source data is missing.
isUniform attribute Any True if all contours in this shape wind in the same direction.
isValid attribute Any (shared captured text)
mergeTopComposite function (self) -> Any Collapses the topmost composite level, merging its children's contours directly into this shape.
name attribute Any Object name (shared captured text)
opacity attribute Any Display opacity of the shape, from 0.0 (fully transparent) to 1.0 (fully opaque).
openedPath attribute Any A Qt painter path containing only the open contours.
pen attribute Any The live-stroke pen: controls brush/color, width, join, miter limit, and basic caps.
penParameters attribute Any Dict: stroke parameters (thickness, proportion, contrast, rotation, join, miter_limit, remove_overlap, cap0/cap1, cap_*0/1)
prepareTransformationData function (self) -> Any Caches the current geometry so that interactive transformations (rotate, scale) work smoothly.
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)
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 a specific anchor from this shape.
removeAnchorsForObject function (self, arg0: flObject) -> Any Removes all anchors on this shape that are linked to the specified object.
removeBackContour function (self) -> Any Removes the contour that is at the back of the stacking order (the last one added, or the lowest in the list).
removeChild function (self, arg0: flObject) -> Any (shared captured text)
removeContour function (self, arg0: flContour) -> Any Detaches and removes a specific contour from the shape.
removeContours function (self, *args: Any, **kwargs: Any) -> Any Removes several contours at once.
replaceInclude function (self, old_shape: flShape, new_shape: flShape) -> Any Swaps one child shape for another within the composite list.
resetInkBox function (self) -> Any Invalidates the cached bounding box, forcing it to be recalculated on next access.
resetTransformationData function (self) -> Any Clears the transform cache created by prepareTransformationData().
restoreHistoryState function (self, history_ix: int) -> Any (shared captured text)
selectAllData function (self) -> Any Selects every node and every sub-shape in this shape.
selected attribute Any Whether this shape is selected in the layer.
setFlag function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
setIncludes function (self, *args: Any, **kwargs: Any) -> Any Replaces the entire include list in one operation.
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)
setReflected function (self, *args: Any, **kwargs: Any) -> Any Sets the horizontal and/or vertical reflection state.
shapeBuilder attribute Any The parametric builder attached to this shape, if any.
shapeData attribute Any The underlying shared data record for this shape.
shapeType attribute Any An enum value describing what kind of shape this is: Simple, Composite, AccentInfo, Image, etc.
simpleShape function (self) -> bool Currently returns False unconditionally in the native implementation.
smartCornerSource function (self) -> flShape FlShape smartCornerSource() - editable source of a Smart Corners filter, self for plain outlines, null for unsupported/locked shapes
sticker attribute Any The sticker (visual annotation bubble) attached to this shape, if any.
tag function (self, *args: Any, **kwargs: Any) -> Any (shared captured text)
transform attribute Any The raw Qt transformation matrix for this shape.
type attribute Any Object type (shared captured text)
unselectAllNodes function (self) -> Any Clears the node selection on every contour in this shape.
update function (self) -> Any (shared captured text)
vertReflection function (self) -> bool Returns True if this shape has a vertical reflection flag set, meaning it is mirrored top-to-bottom.