Understanding the FreeCAD ActiveDocument Object

The ActiveDocument object in FreeCAD serves as the primary programmatic gateway to whichever 3D project document is currently selected and focused by the user. In FreeCAD's Python scripting environment, it represents the active workspace, allowing developers and scriptwriters to create, modify, inspect, and delete geometric features, sketches, and properties without needing to hardcode the document's specific name.

In FreeCAD, multiple documents can be open simultaneously in the workspace. The application-level module, accessed via FreeCAD or App, uses the ActiveDocument attribute (FreeCAD.ActiveDocument or App.ActiveDocument) to track the project tab currently in focus.

Primary Functions of ActiveDocument

  • Object Creation and Management: It acts as the factory for adding new elements to the model. Using methods like ActiveDocument.addObject(), scripts can instantiate primitives, sketches, PartDesign features, and meshes directly into the active design space.
  • Accessing Existing Features: Objects inside the model tree can be accessed directly as attributes of the ActiveDocument (for example, App.ActiveDocument.Box) or through its Objects list, making traversal and batch modifications straightforward.
  • Triggering Recomputations: When changes are made to parametric features via code, the document does not automatically recalculate geometry by default. Calling App.ActiveDocument.recompute() forces FreeCAD to update the dependency graph and redraw the updated shapes.
  • Managing Document State: It provides control over global file parameters, such as document metadata, units, save states, and transaction management for undo and redo operations (openTransaction() and commitTransaction()).

Importance in Scripting and Macros

When creating macros or interactive tools in the Python console, relying on ActiveDocument ensures portability. If a script hardcoded a reference like FreeCAD.getDocument("Unnamed1"), it would fail as soon as the file was saved under a new name or run on another project. Referencing App.ActiveDocument ensures that commands automatically target the model the user is actively viewing.

Handling Headless and Multi-Document Scenarios

While essential for interactive work, ActiveDocument evaluates to None if no document is open in the application. In automated batch processing, headless environments, or background tasks where multiple files are manipulated sequentially, relying strictly on ActiveDocument can introduce errors if focus shifts unexpectedly. In those advanced contexts, assigning documents directly to explicit variables (via FreeCAD.newDocument() or FreeCAD.openDocument()) is preferred, while ActiveDocument remains the standard for interactive modeling and GUI-driven macros.