Wait for user input in Maya


In my last article you may have noticed the Context commands were not actually waiting for the user input. All the commands following them would be executed even though the user didn’t complete the Context tool. The trick (without using the API) is to use a scriptJob that got executed only once, and that is immediately destroyed after its execution.

You call your context tool and create the scriptJob, then that scriptJob will execute the command when the condition you want is met.

try:
    cmds.dynWireCtx("paintMesh")
except RuntimeError:
    pass
cmds.setToolTo("paintMesh")
cmds.scriptJob(runOnce = True, event = ("SelectionChanged", "executed_after_action()"))

def executed_after_action():
    print "Done!"

If you are drawing a curve for example, the selection will change as soon as the user release its mouse button, you can then process whatever you want to process.

You still have to do some verifications in case the user didn’t cancel the tool. You can do so by checking if the new selection is what you were expecting, or/and if new nodes were created. Keep in mind that neither of those checks are full proof in this situation. The final code:

try:
    cmds.dynWireCtx("paintMesh")
except RuntimeError:
    pass
cmds.setToolTo("paintMesh")
cmds.scriptJob(runOnce=True, event=("SelectionChanged", "executed_after_action()"))


def executed_after_action():
    cmds.setToolTo( 'moveSuperContext' )
    shape = cmds.listRelatives( cmds.ls(sl=True), fullPath=True, shapes=True)
    if cmds.objectType(shape) == 'stroke':
        print "Done!"

You can even do that for each curve the user draw without exiting the current Context Tool. Do not set the scriptJob with runOnce, and destroy it once the conditions are not checked in the executed_after_action(). That’s it!