Save and Insert File API Sample

Description

Demonstrates creating save a new file and then inserting it into a design. To use this sample, have a design open that has been saved and run the script. It will create a new design that contains a cylinder, save it to the same folder the active design was saved to, and then insert it into the active design.

Code Samples

/**
 * Save and Insert File API Sample
 * Demonstrates creating save a new file and then inserting it into a design. To use this sample, have a design open that has been saved and run the script. It will create a new design that contains a cylinder, save it t...
 */

import { adsk } from '@adsk/fusion';

function CreateCylinderDesign(app: adsk.core.Application, filename: string) {

  //Create a new document and have it be invisible.
  const cylinderDoc = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType, true) as adsk.fusion.FusionDocument

  // Get the Design and root component from the document.
  const des = cylinderDoc.products.itemByProductType('DesignProductType') as adsk.fusion.Design
  const root = des.rootComponent

  // Create a sketch with a single circle.
  const sk: adsk.fusion.Sketch = root.sketches.add(root.yZConstructionPlane) as adsk.fusion.Sketch
  const point = adsk.core.Point3D.create(3, 2, 0) as adsk.core.Point3D
  sk.sketchCurves.sketchCircles.addByCenterRadius(point, 4)
  const prof = sk.profiles.item(0) as adsk.fusion.Profile
  const value = adsk.core.ValueInput.createByReal(12) as adsk.core.ValueInput
  // Create an extrusion, using the circle.
  root.features.extrudeFeatures.addSimple(prof, value, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)

  // Save the document.
  cylinderDoc.saveAs(filename, defaultFolder(app, "Fusion Automation API"), 'Sample demonstrating watching for the save to complete.', '')
  while (app.hasActiveJobs) {
    wait(2000);
  }

  // Close the document.
  docId = cylinderDoc.creationId
  cylinderDoc.close(false)
}

function wait(ms: number) {
  const start = new Date().getTime();
  while (new Date().getTime() - start < ms) adsk.doEvents();
}

function defaultFolder(app: adsk.core.Application, defaultProjectName: string) {
  const projects = app.data.activeHub.dataProjects;
  if (!projects) throw Error("Unable to get active hub's projects.");
  for (let i = 0; i < projects.count; ++i) {
    const project = projects.item(i)!;
    if (project.name === defaultProjectName) {
      return project.rootFolder;
    }
  }
  adsk.log(`Creating new project: ${defaultProjectName}`);
  const project = projects.add(defaultProjectName);
  if (!project) throw Error("Unable to create new project.");
  return project.rootFolder;
}

let docId = ''
const newFilename = 'SampleSaveTypeScript'

function run() {

  // Get the Fusion API's application object
  const app = adsk.core.Application.get();
  if (!app) throw Error("No adsk.core.Application.");

  // Get a active document
  const doc = app.activeDocument

  if (!doc.isSaved) {
    adsk.log('The active document must be saved before running this script.')
    return
  }

  const onDataFileComplete = {
    notify: (args: adsk.core.DataEventArgs) => {

      // Check to see if the document we care about is the one that saved.
      adsk.log('event fired')

      if (args.file.name == newFilename) {
        const cylinderDoc = args.file

        const topDoc = app.activeDocument

        // Insert the saved document into the activate document.
        const des = topDoc.products.itemByProductType('DesignProductType') as adsk.fusion.Design
        const root = des.rootComponent
        adsk.log('Inserting document into active document')
        const cylOcc = root.occurrences.addByInsert(cylinderDoc, adsk.core.Matrix3D.create(), true)
        adsk.log('Document inserted into active document')
      }
    },
  };

  app.dataFileComplete.add(onDataFileComplete)
  const handlers: any[] = []
  handlers.push(onDataFileComplete)

  // Create a new design with a cylinder.
  const newDoc = CreateCylinderDesign(app, newFilename)
}

run();
#Author-
#Description-

import adsk.core, adsk.fusion, adsk.cam, traceback

# Global variable used to maintain a reference to all event handlers.
handlers = []

_app = adsk.core.Application.get()
_ui  = _app.userInterface

newFilename = 'SampleSave'
_docId = ''

def run(context):
    try:
        # Check that the active document has been saved.
        doc = _app.activeDocument
        if not doc.isSaved:
            _ui.messageBox('The active document must be saved before running this script.')
            return

        parentFolder = doc.dataFile.parentFolder

        # Connect to the dataFileComplete event, to watch for when the file has been fully saved on Fusion Team.
        onDataFileComplete = MyDataFileCompleteHandler()
        _app.dataFileComplete.add(onDataFileComplete)
        handlers.append(onDataFileComplete)

        # Create a new design with a cylinder.
        newDoc = CreateCylinderDesign(parentFolder, newFilename)

        adsk.autoTerminate(False)
    except:
        _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


# Event handler for the dataFileComplete event.
class MyDataFileCompleteHandler(adsk.core.DataEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args: adsk.core.DataEventArgs):
        try:
            # Check to see if the document we care about is the one that saved.
            if args.file.name == newFilename:
                cylinderDoc = args.file
                
                topDoc = _app.activeDocument

                # Insert the saved document into the activate document.
                des: adsk.fusion.Design = topDoc.products.itemByProductType('DesignProductType')
                root = des.rootComponent

                cylOcc = root.occurrences.addByInsert(args.file, adsk.core.Matrix3D.create(), True)

                adsk.terminate()
        except:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
        

def CreateCylinderDesign(folder, filename):
    try:
        # Create a new document and have it be invisible.
        cylinderDoc: adsk.fusion.FusionDocument = _app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType, True)

        # Get the Design and root component from the document.
        des: adsk.fusion.Design = cylinderDoc.products.itemByProductType('DesignProductType')
        root = des.rootComponent

        # Create a sketch with a single circle.
        sk: adsk.fusion.Sketch = root.sketches.add(root.yZConstructionPlane)
        sk.sketchCurves.sketchCircles.addByCenterRadius(adsk.core.Point3D.create(3,2,0), 4)
        prof = sk.profiles[0]

        # Create an extrusion, using the circle.
        root.features.extrudeFeatures.addSimple(prof, adsk.core.ValueInput.createByReal(12), adsk.fusion.FeatureOperations.NewBodyFeatureOperation)

        # Save the document.
        cylinderDoc.saveAs(filename, folder, 'Sample demonstrating watching for the save to complete.', '')

        global _docId
        _docId = cylinderDoc.creationId
        cylinderDoc.close(False)
    except:
        _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))