Community
Fusion API and Scripts
Got a new add-in to share? Need something specialized to be scripted? Ask questions or share what you’ve discovered with the community.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

how to use the SelectionEventHandler

2 REPLIES 2
SOLVED
Reply
Message 1 of 3
mjobson32CFL
920 Views, 2 Replies

how to use the SelectionEventHandler

Hi,

 

I am back butchering code again.

 

I'm trying to select an occurrence and then whilst in the command to display the name of that occurrence.

 

Here is a screen shot of what I'd like it to look like and the resulting name should come up with "Cartridge Upper Front:1" if referring to the image.

 

select occurance.jpg

 

I'm totally stumped. I need the command to remain open, as I will perform a bunch of calculations in the command, but don't need to execute anything from the command. From what I have read, something needs to happen in the SelectionEventHandler, but I don't know what or how.

 

The offending code is below.

 

Any help would be greatly appreciated.

 

 

#Author-
#Description-

import adsk.core, adsk.fusion, traceback

app = None
ui  = None
commandId = 'occur'
commandName = 'Select occurence - state occurence name'
commandDescription = 'Select an occurence, then state name of occurence '

# Global set of event handlers to keep them referenced for the duration of the command
handlers = []

class SelectionDestroy(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            # when the command is done, terminate the script
            # this will release all globals which will remove all event handlers
            adsk.terminate()
        except:
            if ui:
                ui.messageBox('Selection Destroy Class Failed:\n{}'.format(traceback.format_exc()))


class MySelectionEventHandler(adsk.core.SelectionEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        eventArgs = adsk.core.SelectionEventArgs.cast(args)

        # Check which selection input the event is firing for.
        activeSelectionInput = eventArgs.firingEvent.activeInput
        if activeSelectionInput.id == '_partSelection':
          bodySelection = adsk.fusion.BRepBody.cast(activeSelectionInput.entity)
          resultName = bodySelection.name


        else:
          eventArgs.isSelectable = True



class MainProgramHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            cmd = args.command
            cmd.isRepeatable = False
            onDestroy = SelectionDestroy()
            cmd.destroy.add(onDestroy)

            # keep the handler referenced beyond this function
            handlers.append(onDestroy)


            # Define the inputs.
            inputs = cmd.commandInputs

            global commandId

            selectionInput = inputs.addSelectionInput(commandId + '_partSelection', 'Select', 'Select an occurance')
            selectionInput.addSelectionFilter('Occurrences')


            # Create readonly textbox input
            inputs.addTextBoxCommandInput(commandId + '_partName', 'Occurence Name', 'resultName', 1, True)


        except:
            if ui:
                ui.messageBox('Main Program Handler Class Failed:\n{}'.format(traceback.format_exc()))


def run(context):
    ui = None
    try:
        global app
        app = adsk.core.Application.get()
        global ui
        ui = app.userInterface

        global commandId
        global commandName
        global commandDescription

        design = app.activeProduct
        if not design:
          ui.messageBox('No active Fusion design', 'No Design')
          return


        # Create command defintion
        cmdDef = ui.commandDefinitions.itemById(commandId)
        if not cmdDef:
            cmdDef = ui.commandDefinitions.addButtonDefinition(commandId, commandName, commandDescription)

        # Add command created event
        onCommandCreated = MainProgramHandler()
        cmdDef.commandCreated.add(onCommandCreated)
        # Keep the handler referenced beyond this function
        handlers.append(onCommandCreated)

        # Execute command
        cmdDef.execute()

        # Prevent this module from being terminate when the script returns, because we are waiting for event handlers to fire
        adsk.autoTerminate(False)

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

 

 

2 REPLIES 2
Message 2 of 3
ekinsb
in reply to: mjobson32CFL

Here's a variation of your original script.  The primary change is that instead of using selection events I'm using the input changed event.  This is fired when the information associated with any of the command inputs on the dialog is changed.  This includes if any of the selections change.  That's typically where you would watch for changes and update values in other inputs.

 

import adsk.core, adsk.fusion, traceback

app = None
ui  = None
commandId = 'occur'
commandName = 'Select occurence - state occurence name'
commandDescription = 'Select an occurence, then state name of occurence '

# Global set of event handlers to keep them referenced for the duration of the command
handlers = []

class SelectionDestroy(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            # when the command is done, terminate the script
            # this will release all globals which will remove all event handlers
            adsk.terminate()
        except:
            if ui:
                ui.messageBox('Selection Destroy Class Failed:\n{}'.format(traceback.format_exc()))


class MyInputChangedHandler(adsk.core.InputChangedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            eventArgs = adsk.core.InputChangedEventArgs.cast(args)
    
            # Check to see if it was the selection input changed. 
            if eventArgs.input.id == 'partSelection':
                selectionInput = adsk.core.SelectionCommandInput.cast(eventArgs.input)
                if selectionInput.selectionCount == 1:
                    occ = adsk.fusion.Occurrence.cast(selectionInput.selection(0).entity)
                    
                    strInput = adsk.core.StringValueCommandInput.cast(eventArgs.inputs.itemById('partName'))
                    strInput.value = occ.name
        except:
            if ui:
                ui.messageBox('Input Changed Class Failed:\n{}'.format(traceback.format_exc()))


class MainProgramHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            cmd = args.command
            cmd.isRepeatable = False
            
            # Connect to the Destroy event.
            onDestroy = SelectionDestroy()
            cmd.destroy.add(onDestroy)
            handlers.append(onDestroy)
            
            # Connect to the InputChanged event.
            onInputChanged = MyInputChangedHandler()
            cmd.inputChanged.add(onInputChanged)
            handlers.append(onInputChanged)

            # Define the inputs.
            inputs = adsk.core.CommandInputs.cast(cmd.commandInputs)

            selectionInput = inputs.addSelectionInput('partSelection', 'Select', 'Select an occurance')
            selectionInput.addSelectionFilter('Occurrences')
            selectionInput.setSelectionLimits(1,1)
    
            # Create readonly string input
            strInput = inputs.addStringValueInput('partName', 'Occurrence Name', '')
            strInput.isReadOnly = True
        except:
            if ui:
                ui.messageBox('Main Program Handler Class Failed:\n{}'.format(traceback.format_exc()))


def run(context):
    ui = None
    try:
        global app
        app = adsk.core.Application.get()
        global ui
        ui = app.userInterface

        global commandId
        global commandName
        global commandDescription

        design = app.activeProduct
        if not design:
          ui.messageBox('No active Fusion design', 'No Design')
          return


        # Create command defintion
        cmdDef = ui.commandDefinitions.itemById(commandId)
        if not cmdDef:
            cmdDef = ui.commandDefinitions.addButtonDefinition(commandId, commandName, commandDescription)

        # Add command created event
        onCommandCreated = MainProgramHandler()
        cmdDef.commandCreated.add(onCommandCreated)
        
        # Keep the handler referenced beyond this function
        handlers.append(onCommandCreated)

        # Execute command
        cmdDef.execute()

        # Prevent this module from being terminate when the script returns, because we are waiting for event handlers to fire
        adsk.autoTerminate(False)

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

Brian Ekins
Inventor and Fusion 360 API Expert
Mod the Machine blog
Message 3 of 3
mjobson32CFL
in reply to: ekinsb

Thanks again Brian, I tried multiple ways to get this to work last night including the input changed event. But i'm always just stabbing in the dark.

 

This helps me tremendously.

 

There should be a Tip Jar in this forum linked to Fiverr or something for people who help out. 

 

I know it's your job to help people on the forum, but it's not your job to sit there and solve code right?

 

Anyway, I really appreciate your help and patience. Thanks.

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report