"Error: Access violation" when trying to save or close document from AddIn Command

"Error: Access violation" when trying to save or close document from AddIn Command

paulgeeser
Explorer Explorer
554 Views
3 Replies
Message 1 of 4

"Error: Access violation" when trying to save or close document from AddIn Command

paulgeeser
Explorer
Explorer

Hello,
I am pretty new to creating scripts/addins for Fusion360 and run into a problem I can't find a way to solve.
When creating a new document and trying to save or close it (triggered by the command.execute event) I always get an Access violation error. I also tried changing the active document, which also results in this error. I am using the API with Python.  Is there any way to fix this? Thanks for any help!

0 Likes
555 Views
3 Replies
Replies (3)
Message 2 of 4

kandennti
Mentor
Mentor

Hi @paulgeeser -San.

Unfortunately, without seeing what you have created, we cannot determine the cause.
If it is something that can be made public, if you can use this page to show it to us, we can help you and others.

1.png


What little advice I can give you is to use the saveAs and close methods of the FusionDocument Object to save and close the new document.

https://help.autodesk.com/view/fusion360/ENU/?guid=GUID-b8e53dec-cd50-41da-8ba9-bc61556687d1 

0 Likes
Message 3 of 4

paulgeeser
Explorer
Explorer

Thank you, I didn't see that I can post code in here. I made a quick example to show the problem. I used the AddIn template included in Fusion360:

import adsk.core, adsk.fusion
import os, time
from ...lib import fusion360utils as futil
from ... import config
app = adsk.core.Application.get()
ui = app.userInterface


CMD_ID = f'{config.COMPANY_NAME}_{config.ADDIN_NAME}_test'
CMD_NAME = 'Test'
CMD_Description = 'Test'

IS_PROMOTED = True

WORKSPACE_ID = 'FusionSolidEnvironment'
PANEL_ID = 'SolidScriptsAddinsPanel'
COMMAND_BESIDE_ID = 'ScriptsManagerCommand'

ICON_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'resources', '')

local_handlers = []


def start():
    cmd_def = ui.commandDefinitions.addButtonDefinition(CMD_ID, CMD_NAME, CMD_Description, ICON_FOLDER)

    futil.add_handler(cmd_def.commandCreated, command_created)

    workspace = ui.workspaces.itemById(WORKSPACE_ID)

    panel = workspace.toolbarPanels.itemById(PANEL_ID)

    control = panel.controls.addCommand(cmd_def, COMMAND_BESIDE_ID, False)

    control.isPromoted = IS_PROMOTED

def stop():
    workspace = ui.workspaces.itemById(WORKSPACE_ID)
    panel = workspace.toolbarPanels.itemById(PANEL_ID)
    command_control = panel.controls.itemById(CMD_ID)
    command_definition = ui.commandDefinitions.itemById(CMD_ID)

    if command_control:
        command_control.deleteMe()

    if command_definition:
        command_definition.deleteMe()

def command_created(args: adsk.core.CommandCreatedEventArgs):
    futil.log(f'{CMD_NAME} Command Created Event')

    inputs = args.command.commandInputs
    inputs.addTextBoxCommandInput('text_box', 'Some Text', 'Enter some text.', 1, False)

    defaultLengthUnits = app.activeProduct.unitsManager.defaultLengthUnits
    default_value = adsk.core.ValueInput.createByString('1')
    inputs.addValueInput('value_input', 'Some Value', defaultLengthUnits, default_value)

    futil.add_handler(args.command.execute, command_execute, local_handlers=local_handlers)

def command_execute(args: adsk.core.CommandEventArgs):
    futil.log(f'{CMD_NAME} Command Execute Event')

    expDoc: adsk.fusion.FusionDocument = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)
    expDesign = expDoc.design
    expDesign.designType = adsk.fusion.DesignTypes.DirectDesignType

    time.sleep(1) # do something

    expDoc.close(False)

 

The creation of a new document works without any problems but as soon as I call the `.close()` or `.saveAs()` method, Fusion360 freezes and gives me the mentioned error.

Message 4 of 4

kandennti
Mentor
Mentor

@paulgeeser -San.

Thank you for publishing this.


There does not seem to be a problem with the process, but I can reproduce the crash when I run it.

I have tried other events and text commands and it still crashes.

 

The only thing that didn't crash, although it doesn't help, is the following condition

1.png


With two unsaved documents, the second one is active.
The command_execute function is set as follows

def command_execute(args: adsk.core.CommandEventArgs):
    futil.log(f'{CMD_NAME} Command Execute Event')

    expDoc: adsk.fusion.FusionDocument = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)
    expDesign = expDoc.design
    expDesign.designType = adsk.fusion.DesignTypes.DirectDesignType

    # time.sleep(1) # do something

    tempDoc = futil.app.documents[0]
    tempDoc.activate()

    expDoc.close(False)

Before closing the new document, we activate the one other than the document that was active when the command was executed and then close it.
Only in this case it did not crash.

 


Also, I have created a sample that does not use the add-in template. (attached).

import traceback
import adsk
import adsk.core as core
import adsk.fusion as fusion

_handlers = []

CMD_INFO = {
    'id': 'kantoku_test',
    'name': 'test',
    'tooltip': 'test'
}


class MyCommandCreatedHandler(core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args: core.CommandCreatedEventArgs):
        try:
            global _handlers
            cmd: core.Command = core.Command.cast(args.command)

            onDestroy = MyCommandDestroyHandler()
            cmd.destroy.add(onDestroy)
            _handlers.append(onDestroy)

            onExecute = MyExecuteHandler()
            cmd.execute.add(onExecute)
            _handlers.append(onExecute)

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


class MyExecuteHandler(core.CommandEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args: core.CommandEventArgs):
        app: core.Application = core.Application.get()
        doc: fusion.FusionDocument = app.documents.add(
            core.DocumentTypes.FusionDesignDocumentType
        )
        app.log(f"documents.count:{app.documents.count}")
        app.log(f"doc.name:{doc.name}")
        doc.close(False)
        app.log(f"documents.count:{app.documents.count}")


class MyCommandDestroyHandler(core.CommandEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args: core.CommandEventArgs):
        adsk.terminate()


def run(context):
    try:
        global _app, _ui
        _app = core.Application.get()
        _ui = _app.userInterface

        cmdDef: core.CommandDefinition = _ui.commandDefinitions.itemById(
            CMD_INFO['id']
        )

        if not cmdDef:
            cmdDef = _ui.commandDefinitions.addButtonDefinition(
                CMD_INFO['id'],
                CMD_INFO['name'],
                CMD_INFO['tooltip']
            )

        global _handlers
        onCommandCreated = MyCommandCreatedHandler()
        cmdDef.commandCreated.add(onCommandCreated)
        _handlers.append(onCommandCreated)

        cmdDef.execute()

        adsk.autoTerminate(False)

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

The execute event simply creates a new document and closes it.
In this case, it does not crash.
I think there is a cause of the crash somewhere in the add-in template, but I could not identify the cause.

0 Likes