Question: I created a script by JavaScript as below. It delegates the event workspaceActivated. It works well. When switching the workspace, the event will be fired.
//define event handler var MyWorkspaceActivatedHandler = function(args) { var ws = args.workspace; var app = adsk.core.Application.get(); var ui = app.userInterface; ui.messageBox(“active workspace is: (JavaScript).’ +ws.name ); };
function run(context) { var app = adsk.core.Application.get(); var ui = app.userInterface; //delegate the event with the handler ui.workspaceActivated.add(MyWorkspaceActivatedHandler); } }
But the similar code of Python does not work. It looks it successfully delegates the event, but the event is not fired when switching workspace.
When the JavaScript code above runs, it connects the event and then continues to run in the background, allowing its handler to be called and respond to the event. But for a Python script (not an add-in) , it will automatically terminate when it runs. To allow the script to continue to run so it can react the event, adsk.autoTerminate(false) will need to call at the end of run fuction. The argument False indicates Fusion that the script should continue to run in the background.
import adsk.core, adsk.fusion, traceback
#global event handlers handlers = []
#define event class class MyWorkspaceActivatedHandler(adsk.core.WorkspaceEventHandler): def __init__(self): super().__init__() def notify(self, args): #fire for the event ws = args.workspace app = adsk.core.Application.get() ui = app.userInterface
ui.messageBox(‘ active workspace is: (Python).’ + ws.name )
#delegate the event with the handlers onWorkspaceActivated = MyWorkspaceActivatedHandler() ui.workspaceActivated.add(onWorkspaceActivated) handlers.append(onWorkspaceActivated)
#if it is a script, call adsk.autoTerminate to indicate #Fusion to continue run the script. #if it is an add-in, this line is not required. adsk.autoTerminate(False) except: if ui: ui.messageBox(‘Failed:\n{}’.format(traceback.format_exc()))
Leave a Reply