Mouse Click Event

Mouse Click Event

Anonymous
Not applicable
3,216 Views
17 Replies
Message 1 of 18

Mouse Click Event

Anonymous
Not applicable

Hi.

 

I made a command which have button1 and textBox1.

I want to add a following mouse click event.

 

1. Click button1.(get-point mode is activated.)

2. Click any point of coordinates.

3. Get the point vector and write it to textBox1.

 

Could you help me with this problem? or give me a example of mouse click event?

 

Thank you.

 

0 Likes
3,217 Views
17 Replies
Replies (17)
Message 2 of 18

ekinsb
Alumni
Alumni

I just finished writing a little sample for this and have discovered a problem with the mouse click event where it's not being fired correctly.  Until it's fixed you can possibly make do with the mouse up event instead.  However, you need to be aware of what the event is actually giving you to see if any of these can meet your needs.  The mouse related events return the current position of the mouse in window coordinates.  These are 2D coordinates where (0,0) is the upper-left corner of the main Fusion window.  There isn't an equivalent 3D point available.  However, if there was, it's position is somewhat arbitrary because two positions are defined by the mouse but the depth in 3D space is undefined.


Brian Ekins
Inventor and Fusion 360 API Expert
Mod the Machine blog
0 Likes
Message 3 of 18

Anonymous
Not applicable

When I click the button something like 'Box', (1) I can select a plane, and (2) choice a point on the plane.

 

Is there a API to do like that?

0 Likes
Message 4 of 18

ekinsb
Alumni
Alumni

You can do the selection of something using a SelectionCommandInput.  This returns a Selection object which provides access to the entity that was selected and also the point where it was selected.  We're missing the ability to just have a mouse point specified and is something we need to look at adding to the API.


Brian Ekins
Inventor and Fusion 360 API Expert
Mod the Machine blog
0 Likes
Message 5 of 18

MichaelT_123
Advisor
Advisor

G'day Mr. Ekins,

 

I have difficult problem, which needs simple solution. 😉

I want to differentiate, which mouse button is used when clicking on button box.

 

You have mentioned that there is an implementation issue with MouseEventHandler family.

Has the issue been resolved?

 

Regards

MichaelT

 

 

 

 

MichaelT
0 Likes
Message 6 of 18

ekinsb
Alumni
Alumni

When a button, or any command input, is interacted with on a command dialog the API only reports which command input was interacted with and not how it was interacted with.  I've never heard this requirement before and am curious why you want to do something like that. 


Brian Ekins
Inventor and Fusion 360 API Expert
Mod the Machine blog
0 Likes
Message 7 of 18

MichaelT_123
Advisor
Advisor

G'Night Mr. Ekins

 

... I just want(ed) create quick "snap/unsnap" trigger mechanisms using right and left button on the mouse. Possibly other ideas could be realised ... who knows.

I have to say, it is not a critical problem ... I can live without it's resolution, ... but I am curious ..  :).

I have used as a template the sample code from API doc. The one adding button on ToolBar_QAT

I have modified it slightly and it has been working just fine. Unfortunately, bad on me, one night I had an Idea ..."Why not devote the right mouse button for a specific function?" 

And as usual  ... curiosity struck back !

Here is a snipet of code dealing of adding handler function to command definition together with the str(Handlers) themselves and resulting error log.

----------------------------------------------------------------------------------------------------

try:

    onMouseClick = MyMouseClickHandler()       #Vanila/minimal definition

    onMouseClickStr = str(onMouseClick)

    cmdDefinition_SSnap.mouseClick.add(onMouseClick)

    handlers.append(onMouseClick)

    ui.messageBox(_('MyMouseClickHandler() command created successfully'))

except:

   errorStr = _('QAT command created failed: {}').format(traceback.format_exc())

   ui.messageBox(_('QAT command created failed: {}').format(traceback.format_exc()))

   exit()

---------------------------------------------------------------

<__main__C%3A%2FFusion360%2FAPI%2FAddIns%2FSSnap%2FSSnap_py.CommandCreatedEventHandlerQAT; proxy of <Swig Object of type 'adsk::core::CommandCreatedEventHandler *' at 0x000000A717FCA780> >
<__main__C%3A%2FFusion360%2FAPI%2FAddIns%2FSSnap%2FSSnap_py.MyMouseClickHandler; proxy of <Swig Object of type 'adsk::core::MouseEventHandler *' at 0x000000A717FCA7B0> >

QAT command created failed: Traceback (most recent call last):
File ".\Ssnap.py", line 260, in run
cmdDefinition_SSnap.mouseClick.add(onMouseClick)
File "…\adsk\core.py", line 3757, in <lambda>
__getattr__ = lambda self, name: _swig_getattr(self, CommandDefinition, name)
File "…\adsk\core.py", line 57, in _swig_getattr
raise AttributeError(name)
AttributeError: mouseClick

-------------------------------------------------------------------------------------

 

With Regards

MichaelT

 

PS. As I mentioned, please don't bother too much ... it is not a serious problem ... there is also possibility that I did something stupid ... so if you will point it out ... I will be delighted!

 

 

 

 

 

 

 

 

MichaelT
0 Likes
Message 8 of 18

brad.bylls
Collaborator
Collaborator

You mention with SelectionCommandInput you can get a face and the point where selected.

This exactly what I am looking for. 

I want the user to select a planar face and that face will be the sketch plane and the selection point the center of a circle. 

Is there some sample code somewhere that shows how to do this? 

Thank you. 

Brad Bylls
0 Likes
Message 9 of 18

kandennti
Mentor
Mentor

Hi @brad.bylls .

 

I made a sample.

import adsk.core, adsk.fusion, traceback

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

        design = app.activeProduct
        rootComp = design.rootComponent
        sketches :adsk.fusion.Sketches = rootComp.sketches

        # select PlanarFaces
        try:
            returnValue :adsk.core.Selections = ui.selectEntity(
                'Select Face', 'PlanarFaces')
        except:
            return

        # Selected surface
        surf :adsk.fusion.BRepFace = returnValue.entity
        
        # Create Sketch
        skt :adsk.fusion.Sketch = sketches.add(surf)

        # Click Point
        pnt :adsk.core.Point3D = returnValue.point

        # Get the difference between the RootComponent and the origin of the sketch.
        mat :adsk.core.Matrix3D = skt.transform

        # Inverts this matrix.
        mat.invert()

        # Convert the difference
        pnt.transformBy(mat)

        # Draw Sketch
        radius = 2.0
        circles :adsk.fusion.SketchCircles = skt.sketchCurves.sketchCircles
        circles.addByCenterRadius(pnt, radius)
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
0 Likes
Message 10 of 18

brad.bylls
Collaborator
Collaborator

This is my code using your sample.

It goes through the ui.selectentity code, but doesn't stop to get the face and returns out of the code.

 

def drawBolt(designnumBushingIDnumBushingODnumBushingLengthnumClearLengthnumHeadDiamnumHeadHeight😞
    ui = None
    try:
        # Create a new component by creating an occurrence.
        occs = design.rootComponent.occurrences
        mat = adsk.core.Matrix3D.create()
        newOcc = occs.addNewComponent(mat)
        newComp = adsk.fusion.Component.cast(newOcc.component)
        ui = adsk.core.UserInterface

        # Everthing here expects all distances to be in centimeters,
        # so convert for the bolt creation.
        sizeUnits = 2.54
        numClearDiam = (numBushingID + .125) * sizeUnits
        numBushingID = numBushingID * sizeUnits
        numPressDiam = (numBushingOD - .0005) * sizeUnits
        numBushingOD = numBushingOD * sizeUnits
        numBushingLength = numBushingLength * sizeUnits
        numCboreDiam = (numHeadDiam + .01) * sizeUnits
        numHeadDiam = numHeadDiam * sizeUnits
        numHeadHeight = numHeadHeight * sizeUnits
        numClearLength = numClearLength * sizeUnits
 
        try:
            returnValue :adsk.core.Selections = ui.selectEntity(
                'Select Face''PlanarFaces')
        except:
            return  <<<<< executes to here and exits
 
        xyPlane :adsk.fusion.BRepFace = returnValue.entity
        xyPlane :adsk.fusion.Sketch = sketches.add(xyPlane)
        pnt :adsk.core.Point3D = returnValue.point
        mat :adsk.core.Matrix3D = xyPlane.transform
        mat.invert()
        pnt.transformBy(mat)
            
        # create the head
        headSketch = sketches.add(xyPlane)
        headCircle = headSketch.sketchCurves.sketchCircles.addByCenterRadius(center, numHeadDiam / 2)
        headSketch.sketchDimensions.addDiameterDimension(headCircle, adsk.core.Point3D.create(110))
        headSketch.name = 'Head Diameter Sketch'
        extrudes = newComp.features.extrudeFeatures
        headProf = headSketch.profiles[0]
        headExtInput = extrudes.createInput(headProf, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
        distance1 = adsk.core.ValueInput.createByReal(numHeadHeight)
        headExtInput.setDistanceExtent(False, distance1)
        headExt = extrudes.add(headExtInput)
        headExt.name = 'Head Height'

        # Create the OD body
        bushingOdSketch = sketches.add(xyPlane)
        bushingOdCircle = bushingOdSketch.sketchCurves.sketchCircles.addByCenterRadius(center, numBushingOD / 2)
        bushingOdSketch.sketchDimensions.addDiameterDimension(bushingOdCircle, adsk.core.Point3D.create(100))
        bushingOdSketch.name = 'O.D. Sketch'
        bushingOdProf = bushingOdSketch.profiles[0]
        bushingOdExtInput = extrudes.createInput(bushingOdProf, adsk.fusion.FeatureOperations.JoinFeatureOperation)
        distance2 = adsk.core.ValueInput.createByReal(numBushingLength)
        bushingOdExtInput.setDistanceExtent(False, distance2)
        bushingOdExt = extrudes.add(bushingOdExtInput)
        bushingOdExt.name = 'Bushing Length'

        # Create the ID cut
        bushingIdSketch = sketches.add(xyPlane)
        bushingIdCircle = bushingIdSketch.sketchCurves.sketchCircles.addByCenterRadius(center, numBushingID / 2)
        bushingIdSketch.sketchDimensions.addDiameterDimension(bushingIdCircle, adsk.core.Point3D.create(110))
        bushingIdSketch.name = 'I.D. Sketch'
        bushingIdProf = bushingIdSketch.profiles[0]
        bushingIdExtInput = extrudes.createInput(bushingIdProf, adsk.fusion.FeatureOperations.CutFeatureOperation)
        distance3 = adsk.core.ValueInput.createByReal(numBushingLength)
        bushingIdExtInput.setDistanceExtent(False, distance3)
        bushingIdExtInput.participantBodies = [bushingOdExt.bodies.item(0)]
        bushingIdExt = extrudes.add(bushingIdExtInput)
        bushingIdExt.name = 'Bushing Length'

        # Create the bushing fillet
        bushingEnds = bushingOdExt.endFaces.item(0)
        filletEdge = bushingEnds.edges.item(0)
        edgeCol = adsk.core.ObjectCollection.create()
        edgeCol.add(filletEdge)
        filletFeats = newComp.features.filletFeatures
        filletInput = filletFeats.createInput()
        filletSize = adsk.core.ValueInput.createByReal(.254)
        filletInput.addConstantRadiusEdgeSet(edgeCol, filletSize, True)
        newFilletFeats = filletFeats.add(filletInput)
        newFilletFeats.name = 'Fillet'

        # Name the body
        fc = bushingOdExt.faces[0]
        bd = fc.body
        bd.name = _inputCatalogNumber.text + ' Bushing'
        fusionMaterials = _app.materialLibraries.itemByName('Fusion 360 Appearance Library')
        appear = fusionMaterials.appearances.itemByName('Powder Coat (Blue)')
        bd.appearance = appear

        # Group everything used to create the bushing body in the timeline.
        bushingTimelineGroups = design.timeline.timelineGroups
        bushingOccIndex = newOcc.timelineObject.index
        filletFeatsIndex = newFilletFeats.timelineObject.index
        bushingTimelineGroup = bushingTimelineGroups.add(bushingOccIndex, filletFeatsIndex)
        bushingTimelineGroup.name = _inputCatalogNumber.text + ' Bushing'

        # Create a clearance length extrude. Used in parameter expressions
        clearanceLengthSketch = sketches.add(xyPlane)
        clearanceLengthCircle = clearanceLengthSketch.sketchCurves.sketchCircles.addByCenterRadius(center, .01)
        clearanceLengthSketch.name = 'Clearance Length Sketch'
        clearanceLengthProf = clearanceLengthSketch.profiles[0]
        clearanceLengthExtInput = extrudes.createInput(clearanceLengthProf, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
        distance3 = adsk.core.ValueInput.createByReal(numClearLength * -1)
        clearanceLengthExtInput.setDistanceExtent(False, distance3)
        clearanceLengthExt = extrudes.add(clearanceLengthExtInput)
        clearanceLengthExt.name = 'Clearance Length'
        clearanceLengthExt.isSuppressed = True

        # Create the bushing press fit
        cutBushingSketch = sketches.add(xyPlane)
        cutBushingCircle = cutBushingSketch.sketchCurves.sketchCircles.addByCenterRadius(center, numPressDiam / 2)
        cutBushingSketch.sketchDimensions.addDiameterDimension(cutBushingCircle, adsk.core.Point3D.create(010))
        cutBushingSketch.name = 'Bushing Press Fit Sketch'
        cutBushingProf = cutBushingSketch.profiles[0]
        cutBushingExtInput = extrudes.createInput(cutBushingProf, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
        distance4 = adsk.core.ValueInput.createByReal(numBushingLength)
        cutBushingExtInput.setDistanceExtent(False, distance4)
        cutBushingExt = extrudes.add(cutBushingExtInput)
        cutBushingExt.name = 'Bushing Press Fit'

        # Create the head clearance
        cutHeadSketch = sketches.add(xyPlane)
        cutHeadCircle = cutHeadSketch.sketchCurves.sketchCircles.addByCenterRadius(center, numCboreDiam / 2)
        cutHeadSketch.sketchDimensions.addDiameterDimension(cutHeadCircle, adsk.core.Point3D.create(-110))
        cutHeadSketch.name = 'Head Clearance Sketch'
        cutHeadProf = cutHeadSketch.profiles[0]
        cutHeadExtInput = extrudes.createInput(cutHeadProf, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
        distance5 = adsk.core.ValueInput.createByReal(numHeadHeight)
        cutHeadExtInput.setDistanceExtent(False, distance5)
        cutHeadExt = extrudes.add(cutHeadExtInput)
        cutHeadExt.name = 'Head Clearance Length'

        # Create the bushing clearance hole
        cutBushingClearSketch = sketches.add(xyPlane)
        cutBushingClearCircle = cutBushingClearSketch.sketchCurves.sketchCircles.addByCenterRadius(center, numClearDiam / 2)
        cutBushingClearSketch.sketchDimensions.addDiameterDimension(cutBushingClearCircle, adsk.core.Point3D.create(-100))
        cutBushingClearSketch.name = 'Bushing Clearance Sketch'
        cutBushingClearProf = cutBushingClearSketch.profiles[0]
        cutBushingClearExtInput = extrudes.createInput(cutBushingClearProf, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
        distance6 = adsk.core.ValueInput.createByReal(numClearLength * -1)
        cutBushingClearExtInput.setDistanceExtent(False, distance6)
        cutBushingClearExt = extrudes.add(cutBushingClearExtInput)
        cutBushingClearExt.name = 'Bushing Clearance Length'

        # Create cut body with combine
        cutBody = cutBushingExt.bodies[0]
        bodyCollection = adsk.core.ObjectCollection.create()
        bodyCollection.add(cutHeadExt.bodies[0])
        bodyCollection.add(cutBushingClearExt.bodies[0])
        model = design.activeComponent
        features = model.features
        combineFeat = features.combineFeatures
        combineInput = combineFeat.createInput(cutBody, bodyCollection)
        combineFeatur = combineFeat.add(combineInput)

        # Name the cut body
        fc = combineFeatur.faces[0]
        bd = fc.body
        bd.name = 'Bushing Cut Body'
        fusionMaterials = _app.materialLibraries.itemByName('Fusion 360 Appearance Library')
        appear = fusionMaterials.appearances.itemByName('Powder Coat (Green)')
        bd.appearance = appear

        # Group everything used to create the bushing cut body in the timeline.
        cutTimelineGroups = design.timeline.timelineGroups
        cutOccIndex = clearanceLengthSketch.timelineObject.index
        combineFeatIndex = combineFeatur.timelineObject.index
        cutTimelineGroup = cutTimelineGroups.add(cutOccIndex, combineFeatIndex)
        cutTimelineGroup.name = _inputCatalogNumber.text + ' Cut Body'

        # Add an attribute to the component with all of the input values.  This might
        # be used in the future to be able to edit the bushing.
        bushingValues = {}
        bushingValues['bushingID'] = str(numBushingID)
        bushingValues['bushingOD'] = str(numBushingOD)
        bushingValues['bushingLength'] = str(numBushingLength)
        bushingValues['headDiameter'] = str(numHeadDiam)
        bushingValues['headHeight'] = str(numHeadHeight)
        bushingValues['catalogNumber'] = _inputCatalogNumber
        attrib = newComp.attributes.add('CreateShbu''Values'str(bushingValues))

        newComp.name = _inputCatalogNumber.text + ' Guide Bushing'
        return newComp
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
Brad Bylls
0 Likes
Message 11 of 18

kandennti
Mentor
Mentor

I have not tried, but perhaps this is the cause.

・・・
        newOcc = occs.addNewComponent(mat)
        newComp = adsk.fusion.Component.cast(newOcc.component)
        ui :adsk.core.UserInterface = adsk.core.Application.get().userInterface #<-here

        # Everthing here expects all distances to be in centimeters,
        # so convert for the bolt creation.
・・・
0 Likes
Message 12 of 18

brad.bylls
Collaborator
Collaborator

Sorry, when it gets to this line:

returnValue :adsk.core.Selections = ui.selectEntity(
                'Select Face''PlanarFaces')
It locks up F360
I have to go into the task manager and kill it.
Brad Bylls
0 Likes
Message 13 of 18

brad.bylls
Collaborator
Collaborator

From what I am seeing in other posts, there is a problem with selectEntity in a addin but not in a plain script.

Do you know how to do this with selectCommandInput?

Brad Bylls
0 Likes
Message 14 of 18

kandennti
Mentor
Mentor

I think it would work if we stopped selecting in the drawBolt function and received the face and point as parameters of the function.

 

# https://help.autodesk.com/view/fusion360/ENU/?guid=GUID-4fbdc9ad-1dd4-4dca-bdf1-0000cbfe10d9
class MyExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        eventArgs = adsk.core.CommandEventArgs.cast(args)

        # https://help.autodesk.com/view/fusion360/ENU/?guid=GUID-e02e3629-e849-4881-92dc-f6f92bcffced
        selection_var = selectionCommandInput_var.selection(0)

        # https://help.autodesk.com/view/fusion360/ENU/?guid=GUID-5b91bbc5-c644-4405-b462-08930de210f9
        selectPlanarFace = selection_var.entity

        # https://help.autodesk.com/view/fusion360/ENU/?guid=GUID-c6307268-d1b4-4cbe-92e7-ed43c24562f2
        clickPoint = selection_var.point

        # call function
        def drawBolt(design_var, ・・・・, selectPlanarFace, clickPoint)


def drawBolt(
    design, 
    numBushingID, 
    numBushingOD, 
    numBushingLength, 
    numClearLength, 
    numHeadDiam, 
    numHeadHeight,
    xyPlane :adsk.fusion.BRepFace,
    pnt :adsk.core.Point3D):

・・・
0 Likes
Message 15 of 18

brad.bylls
Collaborator
Collaborator

No go.

Still locks up on the selectEntity line in the addin.

 

        _ui.messageBox('Select A Face to Place Bushing')
        selectionCommandInput_var = _ui.selectEntity('Select a Face''PlanarFaces')
        selection_var = selectionCommandInput_var.selection(0)
        selectPlanarFace = selection_var.entity
        clickPoint = selection_var.point

        # Create the bolt.
        boltComp = drawBolt(des, numBushingID, numBushingOD, numBushingLength, numClearLength, \
                    numHeadDiam, numHeadHeight, selectPlanarFace, clickPoint)
Brad Bylls
0 Likes
Message 16 of 18

brad.bylls
Collaborator
Collaborator

Got it.

Disregard my last reply.

Thank you so much.

Brad Bylls
0 Likes
Message 17 of 18

brad.bylls
Collaborator
Collaborator

Hello,

I thought I had it working but the 3DPoint values comes back in cm's I think.

How can I change the x,y,z values of the 3DPoint to inches?

Brad Bylls
0 Likes
Message 18 of 18

BrianEkins
Mentor
Mentor

The internal units for length inside Fusion is centimeters and the API uses these same units.  You can read more about this in the API user manual (http://help.autodesk.com/view/fusion360/ENU/?guid=GUID-A81B295F-984A-4039-B1CF-B449BEE893D7).

---------------------------------------------------------------
Brian Ekins
Inventor and Fusion 360 API Expert
Website/Blog: https://EkinsSolutions.com
0 Likes