# Copyright 2009 Autodesk, Inc.  All rights reserved.
# Use of this software is subject to the terms of the Autodesk license agreement 
# provided at the time of installation or download, or which otherwise accompanies
# this software in either electronic or hard copy form.
#
# Script description:
# Shows how to create a tool that will be only instantiated once even if dragged multiple
# times in the Viewer. 
#
# Topic: FBTool
#

from pyfbsdk import *
import pyfbsdk_additions

# Button creation
def BtnCallback(control, event):
    print control.Caption, " has been clicked!"

def PopulateLayout(mainLyt):
    pass

toolname = "Bullet Proof"

def CreateTool():
    """
    Tool creation function. Everything about the tool is created here.
    So if this script is executed multiple times and we only call this function once
    there won't be multiple instantiation of this tool.
    """
    t = pyfbsdk_additions.CreateUniqueTool(toolname)
    t.StartSizeX = 400
    t.StartSizeY = 200
    PopulateLayout(t)
    return t

# Tool Developement
# Ideally, when a tool has been created users should put it in PythonStartup folder and add this tool 
# to a custom layout. This way a tool would be integrated seemlessly in MotionBuilder.
#
# some users might prefer to "drag and drop" a script in the viewer to create a tool. What is wrong
# with this approach is that if the script gets executed multiple times, the tool gets destroy and recreated. 
# This has the following problems:
# 1- This means, the tool state gets wiped out.
# 2- If some particular code must be called once in a MotionBuilder run and at tool initialization it won't work
# 3- If you register some callbacks and they are not removed you might end up with callbacks to your deleted tool
#    which will bring a "UnboundWrapper Exception".
#  
# If a user prefer to to use a Drag and Drop mecanism to pop a tool here is my suggestion:
# 1- Ensure the tool is created once at the first script execution.
# 2- When the script is executed again, "Show" the already existing tool

# The following code implement that behavior:
if toolname in pyfbsdk_additions.ToolList:
    # Each time you rexecute this script (by dragging in viewer or execute from python console)
    # You will "show" the tool instead of recreating this tool.
    print "show me"
    ShowToolByName(toolname)
else:
    # The first time this script is executed, it gets created.
    print "create me"
    t = CreateTool()

    # Comment this line if you want to put this script in PythonStartup folder.
    ShowTool(t)