Tools

This module provides functions to create interactive javascript tools. These tools allow the developer to handle mouse interaction with the objective to create or modify any drawing or node in the scene.

Methods

(static) createDrawing()

Creates a drawing for the current selected element.
Example

Create an empty drawing if none exists.

 var settings = Tools.getToolSettings();
    if (settings.currentDrawing) {
      return;
    }
    scene.beginUndoRedoAccum("Create Drawing example");
    settings = Tools.createDrawing();
    scene.endUndoRedoAccum();

(static) getToolSettings()

This function is used to retrieve tool settings informations.
Example
var settings = Tools.getToolSettings();
 // settings will contain:  
 settings = {
   "activeArt":2,  // The active art. 0 = underlay, 1 = color, 2 = line, 3 = overlay
   "currentTool":{"id":21,"name":"Select"}, // description of the current tool
   "animationMode":{"id":1,"name":"Dynamic Mode"}, // The scene planning animation mode
   "currentDrawing": // The current drawing descriptor or false if there is no current drawing
     {"drawingId":"12","elementId":1,"projectId":"08ec7c99ee66ac1b","isValid":true}
 };

(static) registerTool(toolDefinition) → {number}

This function is used to create a layer in a specified drawing. The function takes a tool definition object in parameter. This definition object must contain methods that will be called during the tool lifecycle.
Example

This example is a simple implementation of regular polygon tool. You can find the whole package for that tool here: RegularPolygonTool.zip.

 var tid = Tools.registerTool({
     name : "com.toonboom.regularPolygonTool",
     displayName : "Regular Polygon Tool",
     icon : "MyTool.png",
     toolType : "drawing",
     canBeOverridenBySelectOrTransformTool : false,
     options : {
      numSides: 6,
      createStar : false,
      ratio : 0.5
     },
     resourceFolder : "resources",  
     preferenceName : function() {
      return this.name + ".settings";
     },
     defaultOptions : {
        numSides: 6,
        createStar : false,
        ratio : 0.5
     },
     loadFromPreferences : function() {
      try {
        var v = preferences.getString(this.preferenceName(), JSON.stringify(this.defaultOptions));
        this.options = JSON.parse(v);
      }
      catch (e)
      {
        this.options = this.defaultOptions;
      }
     },
     storeToPreferences : function() {
      preferences.setString(this.preferenceName(), JSON.stringify(this.options));
     },
     onRegister : function()
     {
       // This is called once when registering the tool
       // Here the developer can, for example, initialize the tool options
       // from the preferences 
       System.println("Registered tool : " + this.resourceFolder);
       this.loadFromPreferences();
     },
     onCreate : function(ctx) {
       // This is called once for each instance in a view
       // The context could be populated with instance data
     },
     onMouseDown : function(ctx) {
        MessageLog.trace("On mouse down");
        var settings = Tools.getToolSettings();
        if (!settings.currentDrawing)
          return false;

        ctx.origin = ctx.currentPoint;
        System.println("ctx: " + JSON.stringify(ctx));
        return true;
     },
     onMouseMove : function(ctx) {
        // Here, we build the current overlay based on the current mouse move
        // This overlay will be drawn by the system
        this.buildPolygon(ctx, ctx.currentPoint);
        return true;
     },
     onMouseUp : function(ctx) {
      MessageLog.trace("On mouse up");
      var settings = Tools.getToolSettings();
      var cid = PaletteManager.getCurrentColorId();
      
      // Here, we get a chance to capture the current overlay
      // data and build a new drawing layer painted using the
      // current selected color.
      DrawingTools.createLayers( {
        label : "Regular polygon tool", 
        drawing : settings.currentDrawing,
            art: 2,
            layers : [
               {
                  contours : [ 
                  {
                   stroke : true,
                   colorId : cid,
                   polygon: true,
                   path: ctx.overlay.paths[0].path
                  }
               ] }
            ]
      });
      ctx.overlay = {};
      return true;
   },
   onResetTool : function(ctx)
   {
    // Make sure there are no left over
    // from the last tool usage 
    ctx.overlay = {};
   },
   loadPanel : function(dialog, responder) {
      // This method loads the ui file or creates it.
      // It must load the ui in the dialog passed in parameter. 
      var uiFile = this.resourceFolder + "/regularPolygonTool.ui";
      System.println("UIfilename:" + uiFile);
      try
      {
        var ui = UiLoader.load( { uiFile : uiFile, parent : dialog, folder : this.resourceFolder } );

        this.ui = ui;

        ui.options.numSides.setValue(this.options.numSides);
        ui.options.numSides['valueChanged(int)'].connect(this, function(v) {
          this.options.numSides = v;
          this.storeToPreferences();
        });
        ui.options.createStar.setChecked(this.options.createStar);
        ui.options.createStar.toggled.connect(this, function(checked) {
          this.options.createStar = checked;
          ui.options.ratio.setEnabled(this.options.createStar);
          this.storeToPreferences();
        });
        ui.options.ratio.setEnabled(this.options.createStar);
        ui.options.ratio.setValue(Math.round(this.options.ratio * 1000));
        ui.options.ratio['valueChanged(int)'].connect(this, function(v) {
          this.options.ratio = v / 1000.0;
          this.storeToPreferences();
        });
      }
      catch (e)
      {
        System.println("Exception: " + e);
      }
     },
     refreshPanel : function(dialog, responder)
     {
       // In here, the panel could react to changes in the selection or other external sources
       System.println("Refresh panel");
     },
     buildPolygon : function(ctx, pt)
     {
       var dx = pt.x - ctx.origin.x;
       var dy = pt.y - ctx.origin.y;
       var l = Math.sqrt(dx*dx+dy*dy);
       var angle = Math.atan2(dy, dx);
       var poly = [];
       var numSides = this.options.numSides;
       var createStar = this.options.createStar;
       var r1 = 1;
       if (createStar)
       {
         r1 = this.options.ratio;
        numSides *= 2;
       }
       var d =  Math.PI*2/numSides;
       for(var i=0 ; i< numSides; i++)
       {           
         var r = 1;
         if (i%2)
           r = r1;
         poly.push({ x : ctx.origin.x + r * l * Math.cos(angle + i*d), y : ctx.origin.y + r * l * Math.sin(angle + i*d)} );
       }
       poly.push(poly[0]);
       ctx.overlay = { paths : [ { path: poly, color: { r: 0, g: 0, b: 255, a: 255} } ]}
     }
});
}
Parameters:
Name Type Description
toolDefinition Object The definition of the tool.
Properties
Name Type Attributes Default Description
name String The internal name of the tool. We recommand using a reverse DNS notation (e.g. com.toonboom.myTool) to avoid creating conflicts with other organizations. The function will return false if this value is empty or not provided.
displayName String The name that will be shown to the user in menus or tooltips. The function will return false if this value is empty or not provided.
icon String The icon file name for the tool if that tool should need to be associated with an icon.
toolType String <optional>
"drawing" The tool type. It can be either "drawing" or "scenePlanning".
resourceFolder String <optional>
"." The resource folder for this tool. A relative folder can be passed. If it is the case, during registration, the full path value will be computed by the system and be replaced.
canBeOverridenBySelectOrTransformTool boolean <optional>
true If false, your tool will not be overriden by the select/transform tool when pressing the CTRL key.
onRegister function A method that is called once during the registration of the tool.
onCreate function A method that is called once for each instance of the tool. There are one instance per view.
onMouseDown function This method is called when the user clicks on the camera or drawing view. If the tool can operate and process the mouse move and up events, it must return true.
onMouseMove function Called at each mouse move if the tool returned true in the onMouseDown method.
onMouseUp function Called when the mouse is released if the tool returned true in the onMouseDown method. This is typically in this method that the operation should be done.
onResetTool function Called when tool must be reset for external reason like selection change, frame change etc. This is the oportunity for the tool to clear its overlay or reset its manipulator.
loadPanel function This class method is called shortly after registration for the tool to create its property panel. The panel will be shared among all the instance of the tool.
Returns:
The new tool identifier. This identifier can be used to set the current tool id in the Tools.setToolSettings() method.
Type
number

(static) setCurrentTool(tool) → {boolean}

Example

This example will set the tool from the registerTool example as the current tool.

  Tools.setCurrentTool("com.toonboom.regularPolygonTool");
Parameters:
Name Type Description
tool string | number The tool's internal name or its unique id.
Returns:
Returns: true if the tool was found and valid and false otherwise.
Type
boolean

(static) setToolSettings(arg) → {Object}

This function is used to change tool settings informations. Note : you cannot change the currentDrawing with this function.
Example
var settings = Tools.setToolSettings({ currentTool: { id: 3} });
 // settings will contain:  
 // { "activeArt":2,
 //   "currentTool": {"id":3,"name":"Contour Editor"},
 //   "animationMode":{"id":1,"name":"Dynamic Mode"},
 //   "currentDrawing":{"drawingId":"15","elementId":1,"projectId":"08cc9bf65a53f1e1","isValid":true}
 // }
Parameters:
Name Type Description
arg Object A dictionary of options
Properties
Name Type Description
activeArt Object The index of the art to activate. Must be in [0-3] range.
currentTool Object The current tool descriptor
Properties
Name Type Description
id int The current tool id to set
animationMode Object The animation mode descriptor
Properties
Name Type Description
id int The animation mode id to set
Returns:
The new tool settings.
Type
Object