Esempio n. 1
0
        value: function(el, isShape, selection, isComponent) {
            var elementName, controller;

            elementName = el.nodeName.toLowerCase();

            this.type = el.nodeName;
            this.selection = selection ? selection : elementName;

            if(isComponent) {
                controller = "component";
                this.pi = this.elementNameToPi(selection.replace(/\s+/g, ''));
                this.isComponent = true;
            } else {
                controller = this.elementNameToController(elementName);
                this.pi = this.elementNameToPi(elementName);
            }

            this.props3D = Montage.create(Properties3D);

            if(isShape) {
                this.controller = ControllerFactory.getController("shape");
                this.shapeModel = Montage.create(ShapeModel);
                this.isShape = true;
            } else {
                this.controller = ControllerFactory.getController(controller);
            }

            return this;

        }
Esempio n. 2
0
var getInfoForElement = function(el) {
    var elementName, controller, pi, shapeModel = null, isShape = false, isComponent = false;

    elementName = el.nodeName.toLowerCase();
    controller = elementNameToController(elementName);
    pi = elementNameToPi(elementName);

    // Element is a shape
    if(el.getAttribute("data-RDGE-id")) {
        controller = "shape";
        shapeModel = Montage.create(ShapeModel);
        isShape = true;
    }

    if(el.nodeName.toLowerCase() === "ninja-content") {
        elementName = "div";
        controller = elementNameToController("body");
        pi = elementNameToPi("body");
    }

    // TODO: Add this in case there is no controller for the component
    /*
    if(el.getAttribute("data-montage-id")) {
        elementName = null;
        this.isComponent = true;
    }
    */

    // Element is a component
    if(el.controller) {
        var componentInfo = Montage.getInfoForObject(el.controller);
        var componentName = componentInfo.objectName;//.toLowerCase();

        controller = "component";
        elementName = componentName;
        pi = elementNameToPi(componentName.replace(/\s+/g, ''));
        isComponent = true;
    }

    return {
        type: el.nodeName,
        selection: elementName,
        controller: ControllerFactory.getController(controller),
        pi: pi,
        props3d: Montage.create(Properties3D),
        shapeModel: shapeModel,
        isShape: isShape,
        isComponent: isComponent
    }
};
Esempio n. 3
0
        get: function () {
            this.fooCount++;

            var component = new Foo();

            // enable logger to work
            Montage.getInfoForObject(this).property = 'Foo';

            component.identifier = 'Foo' + this.fooCount;
            component.title = component.title + this.fooCount;

            //component.buildInCssClass = null;
            //component.buildInTransitionCssClass = null;
            //component.buildOutCssClass = null;

            //component.buildInCssClass = "zoomInDown";
            //component.buildInTransitionCssClass = null;
            //component.buildOutCssClass = "zoomOutDown";

            //component.classList.add("absolute");

            //Object.observe(component, function (changes) {
            //    changes.forEach(function (change) {
            //        if (change.name === '_inDocument') {
            //            console.log("Property " + '_inDocument' + " changed");
            //            console.log(change);
            //        }
            //    });
            //})
            return component;
        }
Esempio n. 4
0
        value: function (event) {
            var canvas, w, h;
            this.drawData = this.getDrawingData();

            if(this.drawData) {
                w = Math.floor(this.drawData.width);
                h = Math.floor(this.drawData.height);

                if( (w > 0) && (h > 0) ) {
                    if(!this._useExistingCanvas()) {
                        canvas = document.application.njUtils.make("canvas", {"data-RDGE-id": NJUtils.generateRandom()}, this.application.ninja.currentDocument);

                        var styles = document.application.njUtils.stylesFromDraw(canvas, w, h, this.drawData);
                        this.application.ninja.elementMediator.addElements(canvas, styles);
                    } else {
                        canvas = this._targetedElement;
                        if (!canvas.getAttribute( "data-RDGE-id" ))
                            canvas.setAttribute( "data-RDGE-id", NJUtils.generateRandom() );
                        canvas.elementModel.controller = ShapesController;
                        if(!canvas.elementModel.shapeModel) {
                            canvas.elementModel.shapeModel = Montage.create(ShapeModel);
                        }
                        this.RenderShape(w, h, this.drawData.planeMat, this.drawData.midPt, canvas);
                    }
                }
            }

            this.endDraw(event);

            this._isDrawing = false;
            this._hasDraw=false;

            this.DrawHandles();
        }
Esempio n. 5
0
 value: function(file, context, callback, view){
     //
     var codeDocumentView = CodeDocumentView.create(), container = null; //TODO: Why is this initilzied to null?
     //Creating instance of Text Document Model
     this.model = Montage.create(TextDocumentModel,{
         file: {value: file},
         parentContainer: {value: document.getElementById("codeViewContainer")}, //TODO: Remove reference to this element, should be dynamic
         views: {value: {'code': codeDocumentView, 'design': null}} //TODO: Add check if file might have design view, if so, then create it
     });
     //TODO: Add design view logic
     //Initilizing view(s)
     codeDocumentView.initialize(this.model.parentContainer);
     //Checking for view specified
     if (view === 'code') {
         //TODO: Remove reference and use as part of model
         this.currentView = 'code';
         //Setting current view object to design
         this.model.currentView = this.model.views.code;
         //Rendering view
         codeDocumentView.textArea.value = file.content;
         codeDocumentView.initializeTextView(file, this);
     } else {
         //Other view(s) logic goes here
     }
     //Checking if callback is needed
     if (callback) callback.call(context, this);
 }
Esempio n. 6
0
        value:function (els, value, isFill, eventType, source, currentValue, borderSide) {

            if (eventType === "Changing") {
                this._setColor(els, value, isFill, eventType, source, borderSide);
            } else {
                // Calculate currentValue if not found for each element
                if (!currentValue) {
                    var that = this;
                    currentValue = els.map(function (item) {
                        return that.getColor(item, isFill);
                    });
                }

                var command = Montage.create(Command, {
                    _els:{ value:els },
                    _value:{ value:value },
                    _isFill:{ value:isFill },
                    _previous:{ value:currentValue },
                    _eventType:{ value:eventType},
                    _source:{ value:"undo-redo"},
                    description:{ value:"Set Color"},
                    receiver:{ value:this},
                    _borderSide:{ value:borderSide},

                    execute:{
                        value:function (senderObject) {
                            if (senderObject) this._source = senderObject;
                            this.receiver._setColor(this._els, this._value, this._isFill, this._eventType, this._source, this._borderSide);
                            this._source = "undo-redo";
                            return "";
                        }
                    },

                    unexecute:{
                        value:function () {
                            this.receiver._setColor(this._els, this._previous, this._isFill, this._eventType, this._source);
                            return "";
                        }
                    }
                });

                NJevent("sendToUndo", command);
                command.execute(source);
            }

        }
Esempio n. 7
0
        get: function () {
            this.barCount++;

            var component = new Bar();

            // enable logger to work
            Montage.getInfoForObject(this).property = 'Bar';

            //component.identifier = 'Bar' + this.barCount;
            component.title = component.title + this.barCount;

            //component.buildInCssClass = null;
            //component.buildInTransitionCssClass = null;
            //component.buildOutCssClass = null;

            return component;
        }
Esempio n. 8
0
            this.rulesToDraw.forEach(function(ruleObj) {
                var el = document.createElement(this.ruleNodeName);

                var componentBase = this.supportedRules[ruleObj.rule.type],
                    instance;

                ///// Draw the rule if we have a template for the rule type
                if(!componentBase) { return false; }

                instance = Montage.create(componentBase);
                instance.element = document.createElement(this.ruleNodeName);
                instance.rule = ruleObj.rule;
                instance.applied = ruleObj.applies;

                if(this.focusDelegate) {
                    instance.focusDelegate = this.focusDelegate;
                }

                ruleObj.instance = instance;

            }, this);
Esempio n. 9
0
        value: function FreeNASService() {
            this.backendBridge = BackEndBridgeModule.defaultBackendBridge;

            var info = Montage.getInfoForObject(this);
            this._authorizationServices = [info.moduleId];

            if (this.providesAuthorization) {
                DataService.authorizationManager.registerAuthorizationService(this);
            }

            if (this.authorizationPolicy === DataService.AuthorizationPolicyType.UpfrontAuthorizationPolicy) {
                DataService.authorizationManager.authorizeService(this).then(function (authorization) {
                    console.log("I'm Authorized!! ", authorization);
                });
            }


            //Fixme: temporary cache
            this.modelsCache = new Map();

            return this;
        }
Esempio n. 10
0
        value: function() {
            var rootBranch;

            ///// Get user-defined branch/leaf components or use defaults
            this.branchComponent = this.branchComponent || this.defaultBranchComponent;

            ///// Tell branch component what the label key is (defined in tree controller)
            this.branchComponent.labelKey = this.contentController.labelKey;

            ///// Tell branch component what the branch key is (so it can recursively generate branches)
            this.branchComponent.branchKey = this.contentController.branchKey;

            rootBranch = Montage.create(this.branchComponent);
            rootBranch.hideLabel = !this.showRoot;
            rootBranch.treeView = this;

            this.slot.content = rootBranch;
            rootBranch.sourceObject = this.contentController.root;
            rootBranch.needsDraw = true;
            this.rootBranch = rootBranch;

            this.needsDraw = true;

        }
Esempio n. 11
0
var modelGenerator = exports.modelGenerator = function() {
    var info = getInfoForElement(this);

    Object.defineProperty(this, "_model", {
        configurable: true,
        enumerable: false,
        writable: true,
        value: Montage.create(elmo, {
            type:           { value: info.type},
            selection:      { value: info.selection},
            controller:     { value: info.controller},
            pi:             { value: info.pi},
            props3D:        { value: info.props3d},
            shapeModel:     { value: info.shapeModel},
            isShape:        { value: info.isShape}
        })
    });

    if(this._model.selection !== "body" && this.nodeName.toLowerCase() !== "ninja-content") {
        this._model.props3D.init(this, false);
    }

    return this._model;
};
Esempio n. 12
0
exports.BrushTool = Montage.create(ShapeTool, {
    hasReel: { value: false },
    _toolID: { value: "brushTool" },
    _imageID: { value: "brushToolImg" },
    _toolImageClass: { value: "brushToolUp" },
    _selectedToolImageClass: { value: "brushToolDown" },
    _toolTipText: { value: "Brush Tool" },
    _brushView: { value: null, writable: true },

    _selectedToolClass: { value: "brushToolSpecificProperties" },
    _penToolProperties: { enumerable: false, value: null, writable: true },
    _parentNode: { enumerable: false, value: null, writable: true },
    _toolsPropertiesContainer: { enumerable: false, value: null, writable: true },

    //config options
    _useWebGL: {value: false, writable: false},

    //view options
    _brushStrokeCanvas: {value: null, writable: true},
    _brushStrokePlaneMat: {value: null, writable: true},
    dragPlane: {value: null, writable: true},

    //the current brush stroke
    _selectedBrushStroke: {value: null, writable: true},

    ShowToolProperties: {
        value: function () {
            this._brushView = PenView.create();
            this._brushView.element = document.getElementById('topPanelContainer').children[0];
            this._brushView.needsDraw = true;
            this._brushView.addEventListener(ToolEvents.TOOL_OPTION_CHANGE, this, false);
        }
    },


    /*
    _getUnsnappedPosition: {
        value: function(x,y){
            var elemSnap = snapManager.elementSnapEnabled();
            var gridSnap = snapManager.gridSnapEnabled();
            var alignSnap = snapManager.snapAlignEnabled();

            snapManager.enableElementSnap(false);
            snapManager.enableGridSnap(false);
            snapManager.enableSnapAlign(false);

            var point = webkitConvertPointFromPageToNode(this.application.ninja.stage.canvas, new WebKitPoint(x,y));
            var unsnappedpos = DrawingToolBase.getHitRecPos(snapManager.snap(point.x, point.y, false));
            this.dragPlane = snapManager.getDragPlane();

            snapManager.enableElementSnap(elemSnap);
            snapManager.enableGridSnap(gridSnap);
            snapManager.enableSnapAlign(alignSnap);

            return unsnappedpos;
        }
    },
    */

    //use the snap manager to build a hit record corresponding to the screen X, Y position
    // will use the plane of the selected path as the working plane if available, else use stage
    getHitRecord:{
        value: function(x,y, doSnap){
            var elemSnap = snapManager.elementSnapEnabled();
            var gridSnap = snapManager.gridSnapEnabled();
            var alignSnap = snapManager.snapAlignEnabled();

            if (!doSnap){
                snapManager.enableElementSnap(false);
                snapManager.enableGridSnap(false);
                snapManager.enableSnapAlign(false);
            }

            if (this._selectedSubpathCanvas){
                var drawingCanvas = this._selectedSubpathCanvas;
                var contentPlane = ViewUtils.getUnprojectedElementPlane(drawingCanvas);
                snapManager.pushWorkingPlane(contentPlane);

            }
            var tmpPoint = webkitConvertPointFromPageToNode(this.application.ninja.stage.canvas, new WebKitPoint(x,y));
            var hitRec = snapManager.snap(tmpPoint.x, tmpPoint.y, false);
            this.dragPlane = snapManager.getDragPlane();
            if (this._selectedSubpathCanvas){
                snapManager.popWorkingPlane();
            }

            if (!doSnap){
                snapManager.enableElementSnap(elemSnap);
                snapManager.enableGridSnap(gridSnap);
                snapManager.enableSnapAlign(alignSnap);
            }
            return hitRec;
        }
    },

    HandleLeftButtonDown: {
         value: function (event) {
             //ignore any right or middle clicks
             if (event.button !== 0) {
                //NOTE: this will work on Webkit only...IE has different codes (left: 1, middle: 4, right: 2)
                return;
             }
             if (this._canDraw) {
                this._isDrawing = true;
             }

             var hitRec = this.getHitRecord(event.pageX, event.pageY, false);
             this._brushStrokePlaneMat = hitRec.getPlaneMatrix();

             //start a new brush stroke
             if (this._selectedBrushStroke === null){
                 this._selectedBrushStroke = new BrushStroke();
                 var colorObj;
                 var fill = this.options.fill;
                 var color = fill.color;
                 if(fill.colorMode === "gradient") {
                     colorObj = {gradientMode:fill.color.gradientMode, color:fill.color.stops};
                 } else if (color) {
                     colorObj = [color.r/255, color.g/255, color.b/255, color.a];
                 } else {
                     colorObj = [1,1,1,0];
                 }
                 this._selectedBrushStroke.setFillColor(colorObj);

                 //add this point to the brush stroke in case the user does a mouse up before doing a mouse move
                 var currMousePos = hitRec.calculateStageWorldPoint();
                 currMousePos[0]+= snapManager.getStageWidth()*0.5;
                 currMousePos[1]+= snapManager.getStageHeight()*0.5;
                 this._selectedBrushStroke.addPoint(currMousePos);

                 var strokeSize = 1;
                 if (this.options.strokeSize) {
                     strokeSize = ShapesController.GetValueInPixels(this.options.strokeSize.value, this.options.strokeSize.units);
                 }
                 this._selectedBrushStroke.setStrokeWidth(strokeSize);

                 var strokeHardness = 100;
                 if (this.options.strokeHardness){
                     strokeHardness = this.options.strokeHardness.value;
                 }
                 this._selectedBrushStroke.setStrokeHardness(strokeHardness);

                 var doSmoothing = false;
                 if (this.options.doSmoothing){
                     doSmoothing = this.options.doSmoothing;
                 }
                 this._selectedBrushStroke.setDoSmoothing(doSmoothing);
                 if (doSmoothing){
                     this._selectedBrushStroke.setSmoothingAmount(this.options.smoothingAmount.value);
                 }

                 var useCalligraphic = false;
                 if (this.options.useCalligraphic){
                     useCalligraphic = this.options.useCalligraphic;
                 }
                 if (useCalligraphic) {
                     this._selectedBrushStroke.setStrokeUseCalligraphic(true);
                     var strokeAngle = 0;
                     if (this.options.strokeAngle){
                         strokeAngle= this.options.strokeAngle.value;
                     }
                     this._selectedBrushStroke.setStrokeAngle(Math.PI * strokeAngle/180);
                 } else {
                     this._selectedBrushStroke.setStrokeUseCalligraphic(false);
                 }

             }
             if (!g_DoBrushToolMouseMove)
                 NJevent("enableStageMove");//stageManagerModule.stageManager.enableMouseMove();
         } //value: function (event) {
     }, //HandleLeftButtonDown

    HandleMouseMove:
    {
        value: function (event) {
            //ignore any right or middle clicks
            if (event.button !== 0) {
               //NOTE: this will work on Webkit only...IE has different codes (left: 1, middle: 4, right: 2)
               return;
            }

            var hitRec = this.getHitRecord(event.pageX, event.pageY, false);
            var currMousePos = hitRec.calculateStageWorldPoint();
            currMousePos[0]+= snapManager.getStageWidth()*0.5;
            currMousePos[1]+= snapManager.getStageHeight()*0.5;
            if (this._isDrawing) {
                if (this._selectedBrushStroke && this._selectedBrushStroke.getNumPoints()<1000){
                   this._selectedBrushStroke.addPoint(currMousePos);
                }
                this.ShowCurrentBrushStrokeOnStage();
            } else {
                this.ShowCurrentBrushIconOnStage(hitRec.getScreenPoint());
            }

            //this.drawLastSnap();        //TODO.. is this line necessary if we're not snapping? // Required cleanup for both Draw/Feedbacks

       }//value: function(event)
    },



    HandleLeftButtonUp: {
        value: function (event) {
            this.endDraw(event);

            this._isDrawing = false;
            this._hasDraw = false;

            //finish giving enough info. to the brush stroke
            if (this._selectedBrushStroke){
                this._selectedBrushStroke.setPlaneMatrix(this._brushStrokePlaneMat);
                this._selectedBrushStroke.setPlaneMatrixInverse(glmat4.inverse(this._brushStrokePlaneMat,[]));
                this._selectedBrushStroke.setDragPlane(this.dragPlane);
            }

            //display the previously drawn stroke in a separate canvas
            this.RenderCurrentBrushStroke();

            this._selectedBrushStroke = null;
            this._brushStrokeCanvas = null;
            if (!g_DoBrushToolMouseMove)
                NJevent("disableStageMove");
        }
    },

    ShowCurrentBrushIconOnStage:{
        value: function(currMousePos) {
            //clear the canvas before we draw anything else
            this.application.ninja.stage.clearDrawingCanvas();
            //display the brush icon of proper size (query the options bar)
            var strokeSize = 1;
            if (this.options.strokeSize) {
                strokeSize = ShapesController.GetValueInPixels(this.options.strokeSize.value, this.options.strokeSize.units);
            }
            var useCalligraphic = false;
            if (this.options.useCalligraphic){
                useCalligraphic = this.options.useCalligraphic;
            }

            var ctx = this.application.ninja.stage.drawingContext;//stageManagerModule.stageManager.drawingContext;
            if (ctx === null)
                throw ("null drawing context in Brushtool::ShowCurrentBrushStrokeOnStage");
            ctx.save();

            var horizontalOffset = 0;//this.application.ninja.stage.userContentLeft;
            var verticalOffset = 0;//this.application.ninja.stage.userContentTop;
            var halfStrokeWidth = 0.5*strokeSize;
            ctx.beginPath();
            if (!useCalligraphic) {
                //for round brushes, draw a circle at the current mouse position
                ctx.arc(currMousePos[0] + horizontalOffset, currMousePos[1]+ verticalOffset, halfStrokeWidth, 0, 2 * Math.PI, false);
            } else {
                //draw an angled stroke to represent the brush tip
                var strokeAngle = 0;
                if (this.options.strokeAngle){
                    strokeAngle= this.options.strokeAngle.value;
                }
                strokeAngle = Math.PI * strokeAngle/180;
                var deltaDisplacement = [Math.cos(strokeAngle),Math.sin(strokeAngle)];
                deltaDisplacement = VecUtils.vecNormalize(2, deltaDisplacement, 1);
                var startPos = VecUtils.vecSubtract(2, currMousePos, [-horizontalOffset+halfStrokeWidth*deltaDisplacement[0],-verticalOffset+halfStrokeWidth*deltaDisplacement[1]]);
                ctx.moveTo(startPos[0], startPos[1]);
                var endPos = VecUtils.vecAdd(2, startPos, [strokeSize*deltaDisplacement[0], strokeSize*deltaDisplacement[1]]);
                ctx.lineTo(endPos[0], endPos[1]);
                ctx.lineWidth = 2;
            }
            ctx.strokeStyle = "black";
            ctx.stroke();
            ctx.restore();
        }
    },

    ShowCurrentBrushStrokeOnStage:{
        value: function() {
            //clear the canvas before we draw anything else
            this.application.ninja.stage.clearDrawingCanvas();
            if (this._selectedBrushStroke && this._selectedBrushStroke.getNumPoints()>0){
                var ctx = this.application.ninja.stage.drawingContext;//stageManagerModule.stageManager.drawingContext;
                if (ctx === null)
                    throw ("null drawing context in Brushtool::ShowCurrentBrushStrokeOnStage");
                ctx.save();

                /*var horizontalOffset = this.application.ninja.stage.userContentLeft;
                var verticalOffset = this.application.ninja.stage.userContentTop;
                var origX = -horizontalOffset;
                var origY = -verticalOffset;*/
                var deltaX = -snapManager.getStageWidth()*0.5;
                var deltaY = -snapManager.getStageHeight()*0.5;
                var swToGlobalMat = ViewUtils.getStageWorldToGlobalMatrix();
                this._selectedBrushStroke.drawToContext(ctx, true, deltaX, deltaY, swToGlobalMat);

                /*
                origX=0;origY=0;

                ctx.lineWidth = 2;
                var numPoints = this._selectedBrushStroke.getNumPoints();
                ctx.beginPath();
                var tempP = this._selectedBrushStroke.getPoint(0);
                tempP[0]-=snapManager.getStageWidth()*0.5;
                tempP[1]-=snapManager.getStageHeight()*0.5;
                var p = MathUtils.transformAndDivideHomogeneousPoint(tempP, swToGlobalMat);
                ctx.moveTo(p[0]-origX, p[1]-origY);
                if (numPoints===1){
                    //display a tiny segment as a single point
                   ctx.lineTo(p[0]-origX, p[1]-origY+0.01);
                }
                for (var i=1;i<numPoints;i++){
                    tempP = this._selectedBrushStroke.getPoint(i);
                    tempP[0]-=snapManager.getStageWidth()*0.5;
                    tempP[1]-=snapManager.getStageHeight()*0.5;
                    p = MathUtils.transformAndDivideHomogeneousPoint(tempP, swToGlobalMat);
                    ctx.lineTo(p[0]-origX, p[1]-origY);
                }
                ctx.stroke();
                */

                ctx.restore();
            }
        }
    },

    RenderCurrentBrushStroke:{
        value: function() {
            if (this._selectedBrushStroke){
                //DEBUGGING
                /*var localData = this._selectedBrushStroke.buildLocalDataFromStageWorldCoord();
                var bboxWidth = localData[1];
                var bboxHeight = localData[2];
                var bboxMid = localData[0];*/
                this._selectedBrushStroke.init();
                var bboxWidth = this._selectedBrushStroke.getWidth();
                var bboxHeight = this._selectedBrushStroke.getHeight();
                var bboxMid = this._selectedBrushStroke.getStageWorldCenter();
                //end DEBUGGING
                //call render shape with the bbox width and height
                this.RenderShape(bboxWidth, bboxHeight, this._brushStrokePlaneMat, bboxMid, this._brushStrokeCanvas);

                /*this._selectedBrushStroke.computeMetaGeometry();
                var bboxMin = this._selectedBrushStroke.getBBoxMin();
                var bboxMax = this._selectedBrushStroke.getBBoxMax();
                var bboxWidth = bboxMax[0] - bboxMin[0];
                var bboxHeight = bboxMax[1] - bboxMin[1];
                var bboxMid = [0.5 * (bboxMax[0] + bboxMin[0]), 0.5 * (bboxMax[1] + bboxMin[1]), 0.5 * (bboxMax[2] + bboxMin[2])];

                this._selectedBrushStroke.setCanvasX(bboxMid[0]);
                this._selectedBrushStroke.setCanvasY(bboxMid[1]);
                //call render shape with the bbox width and height
                this.RenderShape(bboxWidth, bboxHeight, this._brushStrokePlaneMat, bboxMid, this._brushStrokeCanvas);
                */
            }
        }
    },


    RenderShape: {
        value: function (w, h, planeMat, midPt, canvas) {
            if ((Math.floor(w) === 0) || (Math.floor(h) === 0)) {
                return;
            }

            if (!canvas) {
                var newCanvas = document.application.njUtils.make("canvas", {"data-RDGE-id": NJUtils.generateRandom()}, this.application.ninja.currentDocument);
                var styles = document.application.njUtils.stylesFromDraw(newCanvas, w, h, {midPt: midPt, planeMat: planeMat});
                this.application.ninja.elementMediator.addElements(newCanvas, styles, false);

                // create all the GL stuff
                var world = this.getGLWorld(newCanvas, this._useWebGL);
                //store a reference to this newly created canvas
                this._brushStrokeCanvas = newCanvas;

                var brushStroke = this._selectedBrushStroke;
                if (brushStroke){
                    brushStroke.setWorld(world);
                    brushStroke.setCanvas(newCanvas);

                    brushStroke.setPlaneMatrix(planeMat);
                    var planeMatInv = glmat4.inverse( planeMat, [] );
                    brushStroke.setPlaneMatrixInverse(planeMatInv);
                    brushStroke.setPlaneCenter(midPt);

                    world.addObject(brushStroke);
                    world.render();
                    //TODO this will not work if there are multiple shapes in the same canvas
                    newCanvas.elementModel.shapeModel.GLGeomObj = brushStroke;

                    newCanvas.elementModel.shapeModel.shapeCount++;
                    if(newCanvas.elementModel.shapeModel.shapeCount === 1)
                    {
                        newCanvas.elementModel.selection = "BrushStroke";
                        newCanvas.elementModel.pi = "BrushStrokePi";
                        newCanvas.elementModel.shapeModel.strokeSize = this.options.strokeSize.value + " " + this.options.strokeSize.units;

                        newCanvas.elementModel.shapeModel.GLGeomObj = brushStroke;
                        newCanvas.elementModel.shapeModel.useWebGl = this.options.use3D;
                    }
                    else
                    {
                        // TODO - update the shape's info only.  shapeModel will likely need an array of shapes.
                    }

                    //now send the event that will add this canvas to the timeline
                    NJevent("elementAdded", newCanvas);

                    //if(newCanvas.elementModel.isShape)
                    if (true)
                    {
                        this.application.ninja.selectionController.selectElement(newCanvas);
                    }
                }
            } //if (!canvas) {
            else {

                /*
                var world = null;
                if (canvas.elementModel.shapeModel && canvas.elementModel.shapeModel.GLWorld) {
                    world = canvas.elementModel.shapeModel.GLWorld;
                } else {
                    world = this.getGLWorld(canvas, this._useWebGL);
                }


                if (this._entryEditMode !== this.ENTRY_SELECT_CANVAS){
                    //update the left and top of the canvas element
                    var canvasArray=[canvas];
                    ElementMediator.setProperty(canvasArray, "left", [parseInt(left)+"px"],"Changing", "brushTool");
                    ElementMediator.setProperty(canvasArray, "top", [parseInt(top) + "px"],"Changing", "brushTool");
                    canvas.width = w;
                    canvas.height = h;
                    //update the viewport and projection to reflect the new canvas width and height
                    world.setViewportFromCanvas(canvas);
                    if (this._useWebGL){
                        var cam = world.renderer.cameraManager().getActiveCamera();
                        cam.setPerspective(world.getFOV(), world.getAspect(), world.getZNear(), world.getZFar());
                    }
                }

                var brushStroke = this._selectedBrushStroke;

                if (brushStroke){
                    brushStroke.setDrawingTool(this);

                    brushStroke.setPlaneMatrix(planeMat);
                    var planeMatInv = glmat4.inverse( planeMat, [] );
                    brushStroke.setPlaneMatrixInverse(planeMatInv);
                    brushStroke.setPlaneCenter(midPt);

                    brushStroke.setWorld(world);
                    world.addIfNewObject(brushStroke);
                    //world.addObject(subpath);
                    world.render();
                    //TODO this will not work if there are multiple shapes in the same canvas
                    canvas.elementModel.shapeModel.GLGeomObj = brushStroke;
                }
                */
                alert("BrushStroke cannot edit existing canvas");
            } //else of if (!canvas) {
        } //value: function (w, h, planeMat, midPt, canvas) {
    }, //RenderShape: {

    Configure: {
        value: function (wasSelected) {
            if (wasSelected) {
                if (g_DoBrushToolMouseMove){
                    NJevent("enableStageMove");
                }
            }
            else {
                if (g_DoBrushToolMouseMove){
                    NJevent("disbleStageMove");
                }
            }
        }
    }

});
Esempio n. 13
0
exports.Object3DProperties = Montage.create(ToolProperties, {
    rotateLocally: {
        value: null,
        serializable: true
    },

    rotateGlobally: {
        value: null,
        serializable: true
    },

    _subPrepare: {
        value: function () {
            this.rotateLocally.addEventListener("click", this, false);
            this.rotateGlobally.addEventListener("click", this, false);
        }
    },

    handleClick: {
        value: function (event) {
            if (event._event.target === this.rotateLocally) {
                this.selectedMode = "rotateLocally";
            } else {
                this.selectedMode = "rotateGlobally";
            }

            NJevent("toolOptionsChange", { source: "Object3DProperties", mode: (this.selectedMode === "rotateLocally") });
        }
    },

    _selectedMode: {
        value: "rotateLocally", enumerable: false
    },

    selectedMode: {
        get: function () { return this._selectedMode; },
        set: function (value) { this._selectedMode = value; }
    }


});
Esempio n. 14
0
exports.SliderExample = Montage.create(Component, {

        image: {value: null},

        _colorAdjust : {value: null},
        _red: {value: null},
        red: {
            set: function(v) {
                this._red = v;
                this._colorAdjust = true;
                this.needsDraw = true;
            },
            get: function() {return this._red;}
        },
        _green: {value: null},
        green: {
            set: function(v) {
                this._green = v;
                this._colorAdjust = true;
                this.needsDraw = true;},
            get: function() {return this._green;}
        },
        _blue: {value: null},
        blue: {
            set: function(v) {
                this._blue = v;
                this._colorAdjust = true;
                this.needsDraw = true;
            },
            get: function() {return this._blue;}
        },

        // Glow
        _glowAmount: {value: null},
        glowAmount: {
            set: function(v) {this._glowAmount = v; this.needsDraw = true;},
            get: function() {return this._glowAmount;}
        },
        _glowRadius: {value: null},
        glowRadius: {
            set: function(v) {this._glowRadius = v; this.needsDraw = true;},
            get: function() {return this._glowRadius;}
        },

        // Sharpen
        _sharpnessChanged: {value: null},
        _sharpnessAmount: {value: null},
        sharpnessAmount: {
            set: function(v) {
                this._sharpnessAmount = v;
                this._sharpnessChanged = true;
                this.needsDraw = true;
            },
            get: function() {return this._sharpnessAmount;}
        },

        _applyEffect: {
            value: function() {

                // unfortunately, this is required to be done (Pixastic)
                var img = document.getElementById("image");

                var self = this, resultImg = img;

                if(this._colorAdjust === true) {
                    Pixastic.process(img, "coloradjust", {
                        red: this.red,
                        green: this.green,
                        blue: this.blue
                    });
                    this._colorAdjust = false;
                }


                if(this._sharpnessChanged) {
                    Pixastic.process(img, "sharpen", {
                        amount: this.sharpnessAmount
                    });
                    this._sharpnessChanged = false;
                }

            }
        },

        prepareForDraw: {
            value: function() {
                // Invoke Google pretty printer on source code samples
                prettyPrint();
                this.handleResetAction();
            }
        },

        draw: {
            value: function() {
                if(Pixastic && this.image.complete) {
                    this._applyEffect();
                }
            }
        },

        handleResetAction: {
            value: function() {
                Pixastic.revert(document.getElementById("image"));
                this.red = 0;
                this.green = 0;
                this.blue = 0;
                this.sharpnessAmount = 0;
            }
        },

        didDraw: {
            value: function() {
                //

            }
        },

        logger: {
            value: null
        }
    });
Esempio n. 15
0
exports.RectTool = Montage.create(ShapeTool, {

    _toolID: { value: "rectTool" },
    _imageID: { value: "rectToolImg" },
    _toolImageClass: { value: "rectToolUp" },
    _selectedToolImageClass: { value: "rectToolDown" },
    _toolTipText : { value : "Rectangle Tool (R)" },
    _selectedSubTool :{value :"rect"},
    _ovalTool:{value:null,writable:true},
    _rectTool:{value:null,writable:true},
    _rectView:{value:null,writable:true},
    _ovalView:{value:null,writable:true},

    _selectedToolClass:{value:"rectToolSpecificProperties"},
    _rectToolProperties:{enumerable:false , value:null,writable:true},
    _parentNode:{enumerable:false , value:null,writable:true},
    _toolsPropertiesContainer:{enumerable:false , value:null,writable:true},

    _lockRadiusButton : { value: null, writable: true, enumerable: true, configurable: true },
    _tlRadiusHotText : { value: null, writable: true, enumerable: true, configurable: true },
    _trRadiusHotText : { value: null, writable: true, enumerable: true, configurable: true },
    _blRadiusHotText : { value: null, writable: true, enumerable: true, configurable: true },
    _brRadiusHotText : { value: null, writable: true, enumerable: true, configurable: true },

    _lockRadius : { value: false, writable: true, enumerable: true, configurable: true },
    _buttons: {enumerable: false,value: { hexinput: [] , lockbutton: []}},

    RenderShape: {
        value: function (w, h, planeMat, midPt, canvas)
        {
            if( (Math.floor(w) === 0) || (Math.floor(h) === 0) )
            {
                return;
            }

            var left = Math.round(midPt[0] - 0.5*w);
            var top = Math.round(midPt[1] - 0.5*h);

            var strokeStyleIndex = this.options.strokeStyleIndex;
            var strokeStyle = this.options.strokeStyle;

            var strokeSize = ShapesController.GetValueInPixels(this.options.strokeSize.value, this.options.strokeSize.units, h);

            var tlRadius = ShapesController.GetValueInPixels(this.options.TLRadiusControl.value, this.options.TLRadiusControl.units, h);
            var trRadius = ShapesController.GetValueInPixels(this.options.TRRadiusControl.value, this.options.TRRadiusControl.units, h);
            var blRadius = ShapesController.GetValueInPixels(this.options.BLRadiusControl.value, this.options.BLRadiusControl.units, h);
            var brRadius = ShapesController.GetValueInPixels(this.options.BRRadiusControl.value, this.options.BRRadiusControl.units, h);

            var strokeColor = this.options.stroke.webGlColor || [0,0,0,1];
            var fillColor = this.options.fill.webGlColor || [1,1,1,1];
            // for default stroke and fill/no materials
            var strokeMaterial = null;
            var fillMaterial = null;
            var fillM = null;
            var strokeM = null;

            if(this.options.use3D)
            {
                strokeM = this.options.strokeMaterial;
                if(strokeM)
                {
                    strokeMaterial = Object.create(MaterialsModel.getMaterial(strokeM));
                }
                if (strokeMaterial && this.options.stroke.color && (strokeMaterial.gradientType === this.options.stroke.color.gradientMode)) {
                    strokeColor = {gradientMode:strokeMaterial.gradientType, color:this.options.stroke.color.stops};
                } else {
                    strokeColor = ShapesController.getMaterialColor(strokeM) || strokeColor;
                }

                fillM = this.options.fillMaterial;
                if(fillM)
                {
                    fillMaterial = Object.create(MaterialsModel.getMaterial(fillM));
                }
                if (fillMaterial && this.options.fill.color && (fillMaterial.gradientType === this.options.fill.color.gradientMode)) {
                    fillColor = {gradientMode:fillMaterial.gradientType, color:this.options.fill.color.stops};
                } else {
                    fillColor = ShapesController.getMaterialColor(fillM) || fillColor;
                }
            }

            var world = this.getGLWorld(canvas, this.options.use3D);

            var xOffset = ((left - canvas.offsetLeft + w/2) - canvas.width/2);
            var yOffset = (canvas.height/2 - (top - canvas.offsetTop + h/2));

            var rect = Object.create(Rectangle, {});
            rect.init(world, xOffset, yOffset, w, h, strokeSize, strokeColor, fillColor,
                                        tlRadius, trRadius, blRadius, brRadius, strokeMaterial, fillMaterial, strokeStyle);

            world.addObject(rect);
            world.render();

            canvas.elementModel.shapeModel.shapeCount++;
            if(canvas.elementModel.shapeModel.shapeCount === 1)
            {
                canvas.elementModel.selection = "Rectangle";
                canvas.elementModel.pi = "RectanglePi";
                canvas.elementModel.shapeModel.strokeSize = this.options.strokeSize.value + " " + this.options.strokeSize.units;

                canvas.elementModel.shapeModel.tlRadius = this.options.TLRadiusControl.value + " " + this.options.TLRadiusControl.units;
                canvas.elementModel.shapeModel.trRadius = this.options.TRRadiusControl.value + " " + this.options.TRRadiusControl.units;
                canvas.elementModel.shapeModel.blRadius = this.options.BLRadiusControl.value + " " + this.options.BLRadiusControl.units;
                canvas.elementModel.shapeModel.brRadius = this.options.BRRadiusControl.value + " " + this.options.BRRadiusControl.units;

                canvas.elementModel.shapeModel.strokeStyleIndex = strokeStyleIndex;
                canvas.elementModel.shapeModel.strokeStyle = strokeStyle;

                canvas.elementModel.shapeModel.GLGeomObj = rect;
                canvas.elementModel.shapeModel.useWebGl = this.options.use3D;
            }
            else
            {
                // TODO - update the shape's info only.  shapeModel will likely need an array of shapes.
            }

            // TODO - This needs to be moved into geom obj's init routine instead of here
            if(!fillM) {
                this.setColor(canvas, this.options.fill, true, "rectTool");
            }
            if(!strokeM) {
                this.setColor(canvas, this.options.stroke, false, "rectTool");
            }
            if(canvas.elementModel.isShape)
            {
                this.application.ninja.selectionController.selectElement(canvas);
            }
        }
    }
});
Esempio n. 16
0
var Montage = require("montage/core/core").Montage,
    Component = require("montage/ui/component").Component;

exports.Master = Montage.create(Component, {});
Esempio n. 17
0
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
</copyright> */
var Montage = require("montage/core/core").Montage;
var Component = require("montage/ui/component").Component;

exports.PreferenceSelectItem = Montage.create(Component, {
    preferenceObject: {
        value: null
    },

    optionsController: {
        value: null
    },

    selectInput: {
        value: null
    },

    templateDidLoad: {
        value: function() {
            this.optionsController.selectedObjects = [this.preferenceObject.value];
        }
    }
});
Esempio n. 18
0
var Montage=require("montage/core/core").Montage,Component=require("montage/ui/component").Component,Snapshot=exports.Snapshot=Montage.create(Component,{src:{value:null},image:{value:null},_rotation:{value:0},rotation:{get:function(){return this._rotation},set:function(e){this._rotation=e,this.needsDraw=!0}},prepareForDraw:{value:function(){var e=30;this.rotation=Math.random()*e*2-e}},draw:{value:function(){}}})
Esempio n. 19
0
exports.ModifierToolBase = Montage.create(DrawingTool, {

    //-------------------------------------------------------------------------
    // Drawing Mode Info
    drawingFeedback: { value: { mode: "Draw3D", type: "rectangle" } },

    //-------------------------------------------------------------------------
    // Snapping-specific properties
    _canSnap: { value: true },
    _snapParam: { value: null },
    _snapIndex: { value: -1 },
    _useQuadPt: { value: false },
    _shouldUseQuadPt: { value: false },

    // we set snapping capabilities depending on the tool.
    // The following variables are set in a tool's initializeSnapping method called on mouse down.
    _snapToElements: { value: true },
    _snapToGrid: { value: true },

    _clickedObject : {value : null },
    clickedObject:
    {
        get: function () {
            return this._clickedObject;
        },
        set: function (value) {
            if(value === this.application.ninja.currentDocument.model.documentRoot)
            {
                this._clickedObject = this._target;
            }
            else
            {
                this._clickedObject = value;
            }

            if(value)
            {
                this._startMat = viewUtils.getMatrixFromElement(this._clickedObject);
            }
            else
            {
                this._startMat = null;
            }
        }
    },

    _getObjectBeingTracked :
    {
        value: function(hitRec)
        {
            var elt = hitRec.getElt();
            if(elt === this.application.ninja.currentDocument.model.documentRoot)
            {
                elt = this._target;
            }

            return elt;
        }
    },

    drawWithoutSnapping:
    {
        value: function(event)
        {
            // override in subclasses
        }
    },

    initializeSnapping:
    {
        value: function(event)
        {
            this._mouseDownHitRec = null;
            this._mouseUpHitRec   = null;

            snapManager.clearAvoidList();
            snapManager.clearDragPlane();

            // the translate tool does snap align to the bounds of the object only.
            // turn off snap align to the cursor.  This needs to be re-enabled in the mouse up method
            snapManager.enableSnapAlign( false );

            // snap to element and snap to grid are conditionally enabled based
            // on the snap results of the mouse down.  enable everything for the first snap
            this._snapToElements = snapManager.elementSnapEnabledAppLevel();
            this._snapToGrid = snapManager.gridSnapEnabledAppLevel();

            this._dragPlane = null;
            var do3DSnap = true;

//            if(this._handleMode === null)
//            {
//                if(!this._activateOriginHandle)
//                {
//                    this.doSelection(event);

                    snapManager.enableElementSnap   ( true  );
//                    snapManager.enableGridSnap        ( true  );
//                }
//            }
//            else
//            {
//                this._matL = this._handles[this._handleMode]._matL.slice(0);
//                this._planeEq = this._handles[this._handleMode]._planeEq.slice(0);
//                this._dirVecL = this._handles[this._handleMode]._dirVecL.slice(0);
//                this.m_startPoint = MathUtils.getLocalPoint(event.layerX, event.layerY, this._planeEq, this._matL);
//                if(!this.m_startPoint)
//                {
//                    this.m_startPoint = [this.m_xStart, this.m_yStart];
//                }
//            }

            if(this.application.ninja.selectedElements.length)
            {
                var point = webkitConvertPointFromPageToNode(this.application.ninja.stage.canvas,
                                                                new WebKitPoint(event.pageX, event.pageY));
                // do the snap before setting up the avoid list to allow
                // a snap on the mouse down
                var hitRec = snapManager.snap(point.x, point.y, do3DSnap);

                // TODO - Check that hitRec's element matches element that browser says we clicked on
                var elt = this.application.ninja.stage.getElement(event, true);
                if(elt !== hitRec.getElement())
                {
                    hitRec = snapManager.findHitRecordForElement(elt);
                }

                // we don't want to snap to selected objects during the drag
                this.application.ninja.selectedElements.forEach(function(element) {
                    snapManager.addToAvoidList(element);
                });

                if (hitRec)
                {
                    // disable snap attributes
                    if (hitRec.getType() == hitRec.SNAP_TYPE_ELEMENT)
                    {
                        this._snapToElements = false;
                        this._snapToGrid = false;
                    }
                    else if (hitRec.getType() == hitRec.SNAP_TYPE_ELEMENT_CENTER)
                    {
                        snapManager.enableSnapAlign( snapManager.snapAlignEnabledAppLevel() );
                    }

                    // parameterize the snap point on the target
                    this._snapParam = this.parameterizeSnap( hitRec );

                    if(!this._dragPlane)
                    {
                        if((this._handleMode !== null) && (this.application.ninja.toolsData.selectedTool.action === "SelectionTool"))
                        {
                            this._dragPlane = viewUtils.getUnprojectedElementPlane(this.application.ninja.selectedElements[0]);
                            snapManager.setupDragPlaneFromPlane(this._dragPlane);
                        }
                        else
                        {
                            this._dragPlane = snapManager.setupDragPlanes( hitRec, true );
                        }
                    }

                    // only do quadrant snapping if the 4 corners of the element are in the drag plane
                    var sign = MathUtils.fpSign( vecUtils.vecDot(3,this._dragPlane,[0,0,1]) + this._dragPlane[3] - 1.0);
                    this._shouldUseQuadPt = (sign == 0)

                    var wpHitRec = hitRec.convertToWorkingPlane( this._dragPlane );
                    this._mouseDownHitRec = wpHitRec;
                    this._mouseUpHitRec = null;

                    var pt = hitRec.getScreenPoint();
                    this.downPoint.x = pt[0];
                    this.downPoint.y = pt[1];

                    snapManager.drawLastHit();

                    snapManager.enableSnapAlign( snapManager.snapAlignEnabledAppLevel() );
                    snapManager.enableElementSnap( snapManager.elementSnapEnabledAppLevel() );
                    snapManager.enableGridSnap( snapManager.gridSnapEnabledAppLevel() );
                }
            }
            else
            {
                this.target = null;
            }
        }
    },

    /*
     *  The parameterization is based on the position of the
     *  snap point in pre-transformed element screen space
     */
    parameterizeSnap:
    {
        value: function( hitRec )
        {
            var paramPt = [0,0,0];
            var elt = this._getObjectBeingTracked(hitRec);
            if (elt)
            {
                this.clickedObject = elt;

                var worldPt = hitRec.calculateStageWorldPoint();
                MathUtils.makeDimension4( worldPt );
                var mat = viewUtils.getObjToStageWorldMatrix( elt, true );
                if(mat)
                {
                    var invMat = glmat4.inverse(mat, []);
                    var scrPt = MathUtils.transformHomogeneousPoint( worldPt, invMat );
                    scrPt = MathUtils.applyHomogeneousCoordinate( scrPt );

                    var bounds = viewUtils.getElementViewBounds3D( elt );
                    var x0 = bounds[0][0],  x1 = bounds[3][0],
                        y0 = bounds[0][1],  y1 = bounds[1][1];
                    var dx = x1 - x0,   dy = y1 - y0;
                    var u = 0, v = 0;
                    if (MathUtils.fpSign(dx) != 0)
                        u = (scrPt[0] - x0) / dx;
                    if (MathUtils.fpSign(dy) != 0)
                        v = (scrPt[1] - y0) / dy;

                    paramPt[0] = u;
                    paramPt[1] = v;
                    paramPt[2] = scrPt[2];
                }
            }

            //console.log( "ParameterizeSnap: " + paramPt );
            return paramPt;
        }
    },


    GetObjectHitPoint :
    {
        value: function()
        {
            var scrPt;
            var elt = this._clickedObject;
            if (elt)
            {
                var bounds = viewUtils.getElementViewBounds3D( elt );
                var x0 = bounds[0][0],  x1 = bounds[3][0],
                    y0 = bounds[0][1],  y1 = bounds[1][1];
                var dx = x1 - x0,   dy = y1 - y0;

                var x = x0 + this._snapParam[0]*dx,
                    y = x0 + this._snapParam[1]*dy,
                    z = this._snapParam[2];
                scrPt = [x,y,z];
            }

            return scrPt;
        }
    },

    GetQuadrantSnapPoint:
    {
        value: function(xEvent, yEvent)
        {
            var globalPt;
            var elt = this._clickedObject;
            if (elt && this._snapParam)
            {
                var tx = this._snapParam[0] <= 0.5 ? 0.0 : 1.0,
                    ty = this._snapParam[1] <= 0.5 ? 0.0 : 1.0;

                var bounds = viewUtils.getElementViewBounds3D( elt );
                var x0 = bounds[0][0],  x1 = bounds[3][0],
                    y0 = bounds[0][1],  y1 = bounds[1][1];
                var dx = x1 - x0,   dy = y1 - y0;

                var x = x0 + tx*dx,
                    y = x0 + ty*dy,
                    z = 0.0;
                var localPt = [x,y,z];

                globalPt = viewUtils.localToGlobal( localPt,  elt );

                // add in the delta
                var hitPt = this.GetObjectHitPoint();
                var scrPt = viewUtils.localToGlobal( hitPt, this._clickedObject );
                var delta = [xEvent-scrPt[0], yEvent-scrPt[1], 0-scrPt[2]];
                globalPt[0] += delta[0];
                globalPt[1] += delta[1];
                globalPt[2] += delta[2];
            }

            return globalPt;
        }
    },

    GetQuadrantPoint:
    {
        value: function(useViewPoint)
        {
            var elt = this._clickedObject;
            var tx = this._snapParam[0] <= 0.5 ? 0.0 : 1.0,
                ty = this._snapParam[1] <= 0.5 ? 0.0 : 1.0;

            var bounds = viewUtils.getElementViewBounds3D( elt );
            var x0 = bounds[0][0],  x1 = bounds[3][0],
                y0 = bounds[0][1],  y1 = bounds[1][1];
            var dx = x1 - x0,   dy = y1 - y0;

            var x = x0 + tx*dx,
                y = x0 + ty*dy,
                z = 0.0;
            var scrPt = [x,y,z];

            viewUtils.pushViewportObj( elt );
            var viewPt = viewUtils.screenToView( scrPt[0], scrPt[1], scrPt[2] );
            viewUtils.popViewportObj();

            if(useViewPoint)
            {
                return viewPt;
            }
            else
            {
                return MathUtils.transformPoint( viewPt, this._startMat );
            }
        }
    },

    GetSourcePointFromBoundary :
    {
        value: function( index, useViewPoint )
        {
            var elt = this._clickedObject;
            var bounds = viewUtils.getElementViewBounds3D( elt );

            var x = bounds[index][0],
                y = bounds[index][1],
                z = 0;
            var scrPt = [x,y,z];

            viewUtils.pushViewportObj( elt );
            var viewPt = viewUtils.screenToView( scrPt[0], scrPt[1], scrPt[2] );
            viewUtils.popViewportObj();

            if(useViewPoint)
            {
                return viewPt;
            }
            else
            {
                return MathUtils.transformPoint( viewPt, this._startMat );
            }
        }
    },

    GetSourcePointFromParameterizedTarget :
    {
        value: function(useViewPoint)
        {
            var elt = this._clickedObject;
            var bounds = viewUtils.getElementViewBounds3D( elt );
            var x0 = bounds[0][0],  x1 = bounds[3][0],
                y0 = bounds[0][1],  y1 = bounds[1][1];
            var dx = x1 - x0,   dy = y1 - y0;

            var x = x0 + this._snapParam[0]*dx,
                y = x0 + this._snapParam[1]*dy,
                z = this._snapParam[2];
            var scrPt = [x,y,z];

            viewUtils.pushViewportObj( elt );
            var viewPt = viewUtils.screenToView( scrPt[0], scrPt[1], scrPt[2] );
            viewUtils.popViewportObj();

            if(useViewPoint)
            {
                return viewPt;
            }
            else
            {
                return MathUtils.transformPoint( viewPt, this._startMat );
            }
        }
    },

    getMousePoints: {
        value: function()
        {
            var elt = this._clickedObject;
            if (elt)
            {
                var index = this._snapIndex;
                var pt0;
                var useViewPoint = this.rotateStage || (this._inLocalMode && (this.application.ninja.selectedElements.length === 1));
                if (this._useQuadPt)
                {
                    pt0 = this.GetQuadrantPoint(useViewPoint);
                }
                else
                {
                    pt0 = (index < 0) ? this.GetSourcePointFromParameterizedTarget(useViewPoint) : this.GetSourcePointFromBoundary( index, useViewPoint );
                }
                var pt1 = this._mouseUpHitRec.calculateStageWorldPoint();
                MathUtils.makeDimension4( pt1 );
                var obj2World = viewUtils.getObjToStageWorldMatrix( elt, true );
                var world2Obj = glmat4.inverse(obj2World, []);
                pt1 = MathUtils.transformHomogeneousPoint( pt1, world2Obj );
                pt1 = MathUtils.applyHomogeneousCoordinate( pt1 );
                viewUtils.pushViewportObj( elt );
                pt1 = viewUtils.screenToView( pt1[0], pt1[1], pt1[2] );
                viewUtils.popViewportObj();
                if(!useViewPoint)
                {
                    pt1 = MathUtils.transformPoint( pt1, this._startMat );
                }

                //console.log( "getMousePoints, useViewPoint: " + useViewPoint + ",  " + pt0 + " => " + pt1 );
                return {pt0:pt0, pt1:pt1};
            }
            else
            {
                return null;
            }
        }
    },

    updateUsingSnappingData: {
        value: function(event) {
            this.getUpdatedSnapPoint(event);
            if (this._mouseDownHitRec && this._mouseUpHitRec)
            {
                var data = this.getMousePoints();
                if(data)
                {
                    this.modifyElements(data, event);
                }
            }
        }
    },

    startDraw: {
        value: function(event) {
            this.drawData = null;

            if(this._target)
            {
                this.isDrawing = true;
                this._updateTargets();

                if(this._canSnap)
                {
                    this.initializeSnapping(event);
                }
                else
                {
                    this.drawWithoutSnapping(event);
                }
            }
        }
    },

    /*
     * Non-snapping mouse move calculation for points
     */
    updateWithoutSnappingData: {
        value: function(event) {
            var point = webkitConvertPointFromPageToNode(this.application.ninja.stage.canvas,
                                                        new WebKitPoint(event.pageX, event.pageY));

            var data = {pt0:this.downPoint, pt1:point};

            this.modifyElements(data, event);
        }
    },

    doSnap: {
        value: function (event) {
            this.application.ninja.stage.clearDrawingCanvas();
            this.getUpdatedSnapPoint(event);
        }
    },

    /**
     * Used on the Mouse Move to calculate new snap point.
     */
    getUpdatedSnapPoint: {
        value: function(event) {
            var point = webkitConvertPointFromPageToNode(this.application.ninja.stage.canvas,
                                                            new WebKitPoint(event.pageX, event.pageY));
            var x = point.x, y = point.y;
            this._useQuadPt = false;

            ///////////////////////////////////////////////////////////
            // do a 3D snap if the mouse button is not down
            this._snapIndex = -1;
            this._useQuadPt = false;
            var mouseIsDown = (this._mouseDownHitRec !== null);
            var do3DSnap = (!mouseIsDown || event.shiftKey);

            // set the snapping capabilities
            if (mouseIsDown)
            {
                snapManager.enableElementSnap   ( this._snapToElements  );
                snapManager.enableGridSnap      ( this._snapToGrid      );
            }
//          else
//          {
//              this._showFeedbackOnMouseMove(event);
//          }

            snapManager.enableElementSnap   ( snapManager.elementSnapEnabledAppLevel()  );
            snapManager.enableGridSnap      ( snapManager.gridSnapEnabledAppLevel()     );
            //snapManager.enableSnapAlign       ( snapManager.snapAlignEnabledAppLevel()    );
            snapManager.enableSnapAlign     ( false );  // only snap to element bounds (below)

            // do the snap
            var quadPt;
            if (mouseIsDown && !do3DSnap && this._shouldUseQuadPt && (this._handleMode === null) && (this._mode === 0))
                quadPt = this.GetQuadrantSnapPoint(x,y);
            var hitRec = snapManager.snap(x, y, do3DSnap, quadPt );

            snapManager.enableSnapAlign( snapManager.snapAlignEnabledAppLevel() );
            if ( snapManager.snapAlignEnabled() && this._clickedObject &&
                (this._clickedObject !== this.application.ninja.currentDocument.model.documentRoot) )
            {
                var alignBounds = !hitRec || (hitRec.getType() == hitRec.SNAP_TYPE_STAGE) || hitRec.isSomeGridTypeSnap();
                if (alignBounds)
                {
                    // calculate the delta to offset the points of the element by
                    var scrPt = this.GetObjectHitPoint();
                    scrPt = viewUtils.localToGlobal( scrPt, this._clickedObject );
                    var delta = [x-scrPt[0], y-scrPt[1]];

                    var alignArray = new Array();
                    snapManager.snapAlignToElementBounds( this._clickedObject, delta, alignArray );
                    if (alignArray.length > 0)
                        hitRec = alignArray[0];
                }
            }

            if (hitRec)
            {
                if (mouseIsDown && this._clickedObject)
                {
                    // make the hit record working plane relative
                    this._snapIndex = hitRec.getSnapBoundaryIndex();
                    this._useQuadPt = hitRec.getUseQuadPoint();
                    var wp = this._dragPlane ? this._dragPlane : workingPlane;
                    hitRec = hitRec.convertToWorkingPlane( wp );

                    // update the target
                    this._mouseUpHitRec = hitRec;
                    var pt = hitRec.getScreenPoint();
                    this.upPoint.x = pt[0];
                    this.upPoint.y = pt[1];
                    this.upPoint.z = pt[2];
                }
            }
        }
    },

    doDraw: {
        value: function(event)
        {
            this.application.ninja.stage.clearDrawingCanvas();

            if(this._canSnap)
            {
                this.updateUsingSnappingData(event);
            }
            else
            {
                this.updateWithoutSnappingData(event);
            }
        }
    },

    endDraw: {
        value: function (event) {
            this.application.ninja.stage.clearDrawingCanvas();

            this.downPoint.x = null;
            this.downPoint.y = null;
            this.upPoint.x = null;
            this.upPoint.y = null;
//            this.isDrawing = false;

            if(this._canSnap)
            {
                this.cleanupSnap();
            }
            this._mode = 0;
        }
    },

    cleanupSnap: {
        value: function() {
            this.mouseDownHitRec = null;
            this.mouseUpHitRec = null;

            this._dragPlane = null;
            this._useQuadPt = false;

            snapManager.clearAvoidList();
            snapManager.clearDragPlane();

            // restore the snap settings
            snapManager.enableSnapAlign( snapManager.snapAlignEnabledAppLevel() );
            snapManager.enableElementSnap( snapManager.elementSnapEnabledAppLevel() );
            snapManager.enableGridSnap( snapManager.gridSnapEnabledAppLevel() );
        }
    },
    //-------------------------------------------------------------------------

    //-------------------------------------------------------------------------
    // Info for tool's handles
    _activateOriginHandle: { value: false },
    _startOriginArray : {value : null },
    _origin: { value: null },
    _delta: { value: null },
    _startPoint: { value: [0, 0] },
    _matL : { value: Matrix.I(4) },
    _planeEq: { value: null },
    _dirVecL: { value: null },

    // override in subclasses
    _initializeToolHandles: {
        value: function() {
            if(!this._handles)
            {
            }
            else
            {
            }
        }
    },
    //-------------------------------------------------------------------------

    //-------------------------------------------------------------------------
    // Info about objects being modified by the tool
    // mode === 0 => x/y translation, mode === 1 => z translation
    _mode : {value : 0 },
    _mouseSpeed: { value: 1 },

    _target: { value: null },
    target:
    {
        get: function () {
            return this._target;
        },
        set: function (value) {
            this._target = value;
            if (value === null)
            {
                return;
            }

            if (this._target.elementModel && this._target.elementModel.props3D)
            {
                // do nothing
            }
            else
            {
                console.warn("no props3D model");
//                if(!this._target.elementModel)
//                {
//
//                }
//                var p3d = Montage.create(Properties3D).init(el);
//
//                this._target.elementModel = Montage.create(ElementModel, {
//                                    type:       { value: tag},
//                                    selection:  { value: selection},
//                                    controller: { value: ControllerFactory.getController(controller)},
//                                    props3D:    { value: p3d}
//                            });
//              this._target.props3D = Object.create(Properties3D, {});
//              this._target.props3D.Init(this._target);
            }
        }
    },

    _startMat: { value: Matrix.I(4) },

    _undoArray: { value: [] },

    _initProps3D:
    {
        value: function(elt)
        {
            if (elt.elementModel && elt.elementModel.props3D)
            {
                // do nothing
            }
            else
            {
                console.warn("no props3D model");
//                elt.props3D = Object.create(Properties3D, {});
//                elt.props3D.Init(elt);
            }
        }
    },

    _updateTargets: {
        value: function(addToUndoStack) {
            // override in subclasses
        }
    },
    //-------------------------------------------------------------------------

    //-------------------------------------------------------------------------
    // Routines to run when tool is selected/deselected
    Configure: {
        value: function(wasSelected) {
            if(wasSelected) {
                this.eventManager.addEventListener("selectionChange", this, true);
                this.application.ninja.stage._iframeContainer.addEventListener("scroll", this, false);
                this._initializeToolHandles();
                this.captureSelectionDrawn(null);
                this.eventManager.addEventListener( "toolOptionsChange", this, false);
                this.eventManager.addEventListener( "toolDoubleClick", this, false);
                NJevent("enableStageMove");
            } else {
                this.eventManager.removeEventListener("selectionChange", this, true);
                this.application.ninja.stage._iframeContainer.removeEventListener("scroll", this, false);

                // Clean up
                NJevent("disableStageMove");

                // clear the drag plane
                snapManager.clearDragPlane();

                // restore the snap settings
                snapManager.enableSnapAlign( snapManager.snapAlignEnabledAppLevel() );
                snapManager.enableElementSnap( snapManager.elementSnapEnabledAppLevel() );
                snapManager.enableGridSnap( snapManager.gridSnapEnabledAppLevel() );
                this.eventManager.removeEventListener( "toolOptionsChange", this, false);
                this.eventManager.removeEventListener( "toolDoubleClick", this, false);

                if (this._targetedElement) {
                    this._targetedElement.classList.remove("active-element-outline");
                    this._targetedElement = null;
                }
            }
        }
    },

    captureSelectionChange: {
        value: function(event){
            this.eventManager.addEventListener("selectionDrawn", this, true);
        }
    },

    captureSelectionDrawn: {
        value: function(event){
            this._origin = null;
            this._delta = null;

            var len = this.application.ninja.selectedElements.length;
            if(len)
            {
                if(len === 1)
                {
                    this.target = this.application.ninja.selectedElements[0];
                }
                else
                {
                    this.target = this.application.ninja.currentDocument.model.documentRoot;
                }
//              this._updateTargets();
            }
            else
            {
                this.target = null;
            }
            this.DrawHandles();

            if(event)
            {
                this.eventManager.removeEventListener("selectionDrawn", this, true);
            }
        }
    },
    //-------------------------------------------------------------------------

    //-------------------------------------------------------------------------
    // User interaction routines
    HandleLeftButtonDown: {
        value: function(event) {

//            console.log( "modifier-tool-base.HandleLeftButtonDown" );

            var point = webkitConvertPointFromPageToNode(this.application.ninja.stage.canvas, new WebKitPoint(event.pageX, event.pageY));
            this.downPoint.x = point.x;
            this.downPoint.y = point.y;

            if(this._handleMode === null)
            {
                // TODO - Special casing the double-click workflow for reseting tool handle's center for now.
                if(!this._activateOriginHandle)
                {
                    this.application.ninja.stage.drawNow = true;
                    var canSnap = this._canSnap;
                    this._canSnap = true;
                    this.doSelection(event);
                    this._canSnap = canSnap;
                }
            }

            this.startDraw(event);
        }
    },

    HandleMouseMove: {
        value: function(event) {
            if(this._escape) {
                this._escape = false;
                this.isDrawing = true;
            }

            if(this.isDrawing) {
                this._hasDraw = true;   // Flag for position of element
                this.doDraw(event);
            } else {
                this._showFeedbackOnMouseMove(event);
                if(this._canSnap)
                {
                    this.doSnap(event);
                }
            }

            if (!this._isDrawing || (this.application.ninja.selectedElements.length == 1))
            this.DrawHandles(this._delta);

            if(this._canSnap)
            {
                snapManager.drawLastHit();
            }
        }
    },

    HandleLeftButtonUp: {
        value: function(event) {
            var point = webkitConvertPointFromPageToNode(this.application.ninja.stage.canvas,
                                                                    new WebKitPoint(event.pageX, event.pageY));

            this.isDrawing = false;
            if(this._escape) {
                this._escape = false;
                return;
            }

            if(this._hasDraw)
            {
                if(this._activateOriginHandle)
                {
                    this._setTransformOrigin(true);
                }
                else if ( ((this.downPoint.x - point.x) !== 0) ||
                            ((this.downPoint.y - point.y) !== 0) )
                {
                    this._updateTargets(true);
                }

                this._hasDraw = false;
            }
            if(this._handleMode !== null)
            {
                this._handleMode = null;
                this._delta = null;
            }
            this.endDraw(event);

            this.application.ninja.stage.draw();
            if (this.application.ninja.selectedElements.length > 1)
            {
                //this._origin = null;
                this._updateHandlesOrigin();
            }
            this.DrawHandles();
        }
    },

    _updateHandlesOrigin: {
        value: function () { }
    },

    handleToolDoubleClick: {
        value: function(event) {
            if(!this._target)
            {
                return;
            }

            this.Reset();
        }
    },

    Reset : {
        value: function () {
            // override in sub-classes
        }
    },

    handleToolOptionsChange: {
        value: function(event) {
            this._handleToolOptionsChange(event);
        }
    },

    _handleToolOptionsChange : {
        value: function (event) {
            // override in sub-classes
        }
    },

    /**
     * This function is for specifying custom feedback routine
     * upon mouse over.
     * For example, the drawing tools will add a glow when mousing
     * over existing canvas elements to signal to the user that
     * the drawing operation will act on the targeted canvas.
     */
    _showFeedbackOnMouseMove : {
        value: function (event) {
            if(this._target && this._handles)
            {
                var len = this._handles.length;
                var i = 0,
                    toolHandle,
                    c,
                    point = webkitConvertPointFromPageToNode(this.application.ninja.stage.canvas,
                                                            new WebKitPoint(event.pageX, event.pageY));
                for (i=0; i<len; i++)
                {
                    toolHandle = this._handles[i];
                    c = toolHandle.collidesWithPoint(point.x, point.y);
                    if(c === 1)
                    {
                        this.application.ninja.stage.drawingCanvas.style.cursor = "move";
                        this._handleMode = i;
                        return;
                    }
                    else if(c === 2)
                    {
                        this.application.ninja.stage.drawingCanvas.style.cursor = toolHandle._cursor;
                        this._handleMode = i;
                        return;
                    }
                }
            }

            this._handleMode = null;
   //            this.application.ninja.stage.drawingCanvas.style.cursor = this._cursor;
            this.application.ninja.stage.drawingCanvas.style.cursor = "auto";
        }
    },
    //-------------------------------------------------------------------------

    HandleKeyPress: {
        value : function (event) {
            var point = webkitConvertPointFromPageToNode(this.application.ninja.stage.canvas,
                                                        new WebKitPoint(event.pageX, event.pageY));
            if(event.ctrlKey || event.metaKey)
            {
                // set 'z-translation' mode
                this._mode = 1;

                if(this._mouseDownHitRec && this._target)
                {
                    if ( ((this.downPoint.x - point.x) !== 0) ||
                          ((this.downPoint.y - point.y) !== 0) )
                    {
                        this._updateTargets();

                        this.downPoint.x = point.x;
                        this.downPoint.y = point.y;
                    }
                }
            }
        }
    },

    HandleKeyUp: {
        value: function(event) {
            var point = webkitConvertPointFromPageToNode(this.application.ninja.stage.canvas,
                                                        new WebKitPoint(event.pageX, event.pageY));
            if(event.keyCode === 93 || event.keyCode === 91 || event.keyCode === 17)
            {
                // set 'x/y-translation' mode
                this._mode = 0;

                if(this._mouseDownHitRec && this._target)
                {
                    if ( ((this.downPoint.x - point.x) !== 0) ||
                          ((this.downPoint.y - point.y) !== 0) )
                    {
                        this._updateTargets();

                        this.downPoint.x = point.x;
                        this.downPoint.y = point.y;
                    }
                }
            }
        }
    },

    modifyElements: {
        value: function(data, event) {
            // override in subclasses.
        }
    }
    //-------------------------------------------------------------------------
});
Esempio n. 20
0
var Montage = require("montage/core/core").Montage,
    Component = require("montage/ui/component").Component;

exports.InputNumber = Montage.create(Component, {});
Esempio n. 21
0
exports.Tree = Montage.create(Component, {

    treeViewDataObject:{
        writable:true,
        enumerable:true,
        value:null
    },

    showIcons :{
        writable:true,
        enumerable:true,
        value:true
    },

    expandTreeAfterDraw:{
        writable:true,
        enumerable:true,
        value:false
    },

    highlightedUri:{
        writable:true,
        enumerable:true,
        value:null
    },

    willDraw: {
        enumerable: false,
        value: function() {

        }
    },
    draw: {
        enumerable: false,
        value: function() {

        }
    },
    didDraw: {
        enumerable: false,
        value: function() {

        }
    }

});
Esempio n. 22
0
var Tween = exports.Tween = Montage.create(Component, {

    // ==== Begin Models
    keyframe: {
        value: null,
        serializable: true
    },

    tweenspan: {
        value: null,
        serializable: true
    },

    _tweenData:{
        value:{}
    },

    tweenData:{
        get:function(){
            return this._tweenData;
        },
        set:function(val){
            this._tweenData = val;
            if(this._tweenData){
                this.setData();
            }
        }
    },

    _spanWidth: {
        value: 0
    },

    spanWidth: {
        serializable:true,
        get: function(){
            return this._spanWidth;
        },
        set: function(value){
            this._spanWidth = value;
            this.tweenData.spanWidth = value;
            this.needsDraw=true;
        }
    },

    _spanPosition:{
        value: 0
    },

    spanPosition:{
        serializable:true,
        get:function () {
            return this._spanPosition;
        },
        set:function (value) {
            this._spanPosition = value;
            this.tweenData.spanPosition = value;
            this.needsDraw=true;
        }
    },

    _keyFramePosition:{
        value:0
    },

    keyFramePosition:{
        serializable:true,
        get:function () {
            return this._keyFramePosition;
        },
        set:function (value) {
            this._keyFramePosition = value;
            this.tweenData.keyFramePosition = value;
            this.needsDraw=true;
        }
    },

    _keyFrameMillisec:{
        value:0
    },

    keyFrameMillisec:{
        serializable:true,
        get:function () {
            return this._keyFrameMillisec;
        },
        set:function (value) {
            this._keyFrameMillisec = value;
        }
    },

    _tweenID:{
        value:0
    },

    tweenID:{
        serializable:true,
        get:function () {
            return this._tweenID;
        },
        set:function (value) {
            this._tweenID = value;
            this.tweenData.tweenID = value;
        }
    },

    _tweenedProperties:{
        value:[]
    },

    tweenedProperties:{
        serializable:true,
        get:function(){
            return this._tweenedProperties;
        },
        set:function(val){
            this._tweenedProperties = val;
        }
    },

    _isTweenAnimated:{
        value:false
    },

    isTweenAnimated:{
        serializable:true,
        get:function () {
            return this._isTweenAnimated;
        },
        set:function (value) {
            this._isTweenAnimated = value;
        }
    },

    _isDragging: {
        value: false
    },
    isDragging: {
        serializable: true,
        get:function () {
            return this._isDragging;
        },
        set:function (newVal) {
            this._isDragging = newVal;
        }

    },

    _easing: {
        value: "none"
    },
    easing: {
        serializable: true,
        get:function () {
            return this._easing;
        },
        set:function (newVal) {
            this._easing = newVal;
        }

    },

    _initSelect:{
        value: null
    },
    initSelect:{
        serializable:true,
        get:function () {
            return this._initSelect;
        },
        set:function (newVal) {
            this._initSelect = newVal;
            this.tweenData.initSelect = newVal;
        }
    },

    setData:{
        value:function(){
            this.spanWidth = this.tweenData.spanWidth;
            this.keyFramePosition = this.tweenData.keyFramePosition;
            this.spanPosition = this.tweenData.spanPosition;
            this.keyFrameMillisec = this.tweenData.keyFrameMillisec;
            this.tweenID = this.tweenData.tweenID;
            this.tweenedProperties = this.tweenData.tweenedProperties;
            this.isTweenAnimated = this.tweenData.isTweenAnimated;
            this.easing = this.tweenData.easing;
            this.initSelect = this.tweenData.initSelect;
            this.needsDraw = true;
        }
    },
    // ==== End Models

    // ==== Begin Draw cycle methods
    prepareForDraw:{
        value:function(){
            if(this.initSelect){
                // Select our new keyframe only if our parent is a main track.
                // TODO: When we decouple all property tracks, this will go away.
                if (typeof(this.parentComponent.parentComponent.trackType) === "undefined") {
                    if (this.tweenID > 0) {
                        this.keyframe.selectKeyframe();
                    }
                }
                this.initSelect = false;
            }
        }
    },

    draw:{
        value:function () {
        	this.tweenspan.element.style.width = this.spanWidth + "px";
            this.keyframe.element.style.left = (this.spanWidth -5) + "px";
            this.tweenspan.spanWidth = this.spanWidth;
            this.element.style.left = this.spanPosition + "px";
            this.keyframe.position = this.spanWidth;
            this.tweenspan.easing = this.easing;
            if(this.isTweenAnimated){
                this.tweenspan.highlightSpan();
            }
        }
    },
    // ==== End Draw cycle methods

    // ==== Begin Event handlers
    handleElementChange:{
        value:function (event) {
            if(event.detail.type === "cssChange"){
                event.detail.source="cssPanelChange"
            }
            if (event.detail.source && event.detail.source !== "tween") {

                if(this.parentComponent.parentComponent.isSubproperty){
                    this.setStyleTweenProperty(event.detail);
                } else {
                    if (this.application.ninja.selectedElements[0] != this.parentComponent.parentComponent.animatedElement) {
                        console.log("Wrong element selected for this keyframe track");
                    } else {
                        this.setTweenProperties(event.detail);
                    }
                }
            }
        }
    },
    // ==== End Event handlers

    // ==== Begin Controllers
    setTweenProperties:{
        value:function (eventDetail) {
        	if (eventDetail.source === "SelectionTool" || eventDetail.source === "timeline" || eventDetail.source === "pi" || eventDetail.source === "cssPanelChange") {
	            if(this.parentComponent.parentComponent.animatedElement.offsetTop != this.tweenedProperties["top"]){
	                this.tweenedProperties["top"] = this.parentComponent.parentComponent.animatedElement.offsetTop + "px";
	            }
	            if(this.parentComponent.parentComponent.animatedElement.offsetLeft != this.tweenedProperties["left"]){
	                this.tweenedProperties["left"] = this.parentComponent.parentComponent.animatedElement.offsetLeft + "px";
	            }
	            if (this.parentComponent.parentComponent.animatedElement.offsetWidth != this.tweenedProperties["width"]){
	                this.tweenedProperties["width"] = this.parentComponent.parentComponent.animatedElement.offsetWidth + "px";
	            }
	            if (this.parentComponent.parentComponent.animatedElement.offsetHeight != this.tweenedProperties["height"]){
	                this.tweenedProperties["height"] = this.parentComponent.parentComponent.animatedElement.offsetHeight + "px";
	            }

	            this.parentComponent.parentComponent.updateKeyframeRule();
	            this.isTweenAnimated = true;
        	}
			
			if (eventDetail.source === "translateTool" || eventDetail.source === "rotateTool") {
        		var arrMat = eventDetail.data.value[0].properties.mat,
        			strTweenProperty = "perspective(1400) matrix3d(" + arrMat.join() + ")";
        		
        		this.tweenedProperties["-webkit-transform"] = strTweenProperty;
        		this.parentComponent.parentComponent.updateKeyframeRule();
        		this.isTweenAnimated = true;
        	}
        }
    },

    setStyleTweenProperty:{
        value:function (eventDetail) {
            if(eventDetail.type == "setProperties"){
                this.tweenedProperties[this.parentComponent.parentComponent.trackEditorProperty] = eventDetail.data.value[0];
                this.parentComponent.parentComponent.updatePropKeyframeRule();
            } else if(eventDetail.type == "setColor"){
                var prop = this.parentComponent.parentComponent.trackEditorProperty;
                this.tweenedProperties[prop] = eventDetail.data.value.color.css;
                this.parentComponent.parentComponent.updatePropKeyframeRule();
            } else if(eventDetail.type == "setProperty"){
                this.tweenedProperties[this.parentComponent.parentComponent.trackEditorProperty] = eventDetail.data.value[0];
                this.parentComponent.parentComponent.updatePropKeyframeRule();
            } else {
                console.log("TWEEN Unhandled type - setStyleTweenProperty : " + eventDetail.type);
            }
        }
    },

    setKeyframeEase:{
        value:function(easeType){
            this.tweenedProperties["-webkit-animation-timing-function"] = easeType;
            if(this.parentComponent.parentComponent.isSubproperty){
                if(this.parentComponent.parentComponent.trackType == "position"){
                    return;
                }
                this.parentComponent.parentComponent.updatePropKeyframeRule();
            } else {
                this.parentComponent.parentComponent.updateKeyframeRule();
            }
        }
    },

    selectTween:{
        value: function(){
            this.eventManager.addEventListener("elementChange", this, false);
            var selectIndex = this.application.ninja.timeline.getLayerIndexByID(this.parentComponent.parentComponent.trackID);
            // this.application.ninja.timeline.selectLayer(selectIndex, true); // deprecated
            this.application.ninja.timeline.selectLayers([selectIndex]);
            this.application.ninja.timeline.updateStageSelection();
            this.application.ninja.timeline.deselectTweens();
            this.application.ninja.timeline.selectedTweens.push(this);
            this.application.ninja.timeline.playhead.style.left = (this.keyFramePosition - 2) + "px";
            this.application.ninja.timeline.playheadmarker.style.left = this.keyFramePosition + "px";
            var currentMillisecPerPixel = Math.floor(this.application.ninja.timeline.millisecondsOffset / 80);
            var currentMillisec = currentMillisecPerPixel * this.keyFramePosition;
            this.application.ninja.timeline.updateTimeText(currentMillisec);

            if(this.parentComponent.parentComponent.isSubproperty){
                var currentValue = this.tweenedProperties[this.parentComponent.parentComponent.trackEditorProperty];
                var el = this.parentComponent.parentComponent.animatedElement;
                var prop = this.parentComponent.parentComponent.trackEditorProperty;
                this.application.ninja.elementMediator.setProperty([el], prop, [currentValue], "Change", "tween");
            } else {
                var currentTop = this.tweenedProperties["top"];
                var currentLeft = this.tweenedProperties["left"];
                var currentWidth = this.tweenedProperties["width"];
                var currentHeight = this.tweenedProperties["height"];

                this.application.ninja.elementMediator.setProperty([this.parentComponent.parentComponent.animatedElement], "top", [currentTop], "Change", "tween");
                this.application.ninja.elementMediator.setProperty([this.parentComponent.parentComponent.animatedElement], "left", [currentLeft], "Change", "tween");
                this.application.ninja.elementMediator.setProperty([this.parentComponent.parentComponent.animatedElement], "width", [currentWidth], "Change", "tween");
                this.application.ninja.elementMediator.setProperty([this.parentComponent.parentComponent.animatedElement], "height", [currentHeight], "Change", "tween");
            }
        }
    },

    deselectTween:{
        value:function(){
            this.eventManager.removeEventListener("elementChange", this, false);
            this.keyframe.deselectKeyframe();
        }
    }
    // ==== End Controllers
});
exports.WordpressConnector = Montage.specialize({

    constructor: {
        value: function WordpressConnector () {
            this.addPathChangeListener("host", this, "_makeRequest");
            this.addPathChangeListener("path", this, "_makeRequest");
            this.addPathChangeListener("categoryFilter", this, "_makeRequest");
        }
    },

    host: {
        value: null
    },

    path: {
        value: null
    },
    
    categoryFilter: {
        value: null
    },

    articles: {
        value: null
    },
    
    _latestRequest: {
        value: null
    },
    
    _makeRequest: {
        value: function() {

            if (!(this.host && this.path)) {
                return;
            }

            var url = "http://" + this.host + "/wp-json/" + this.path + "?_jsonp=cb",
                self = this,
                request,
                query;
            
            if (this.categoryFilter) {
                query = {"filter[category_name]": this.categoryFilter};
                url += "&" + Reqwest.toQueryString(query);
            }

            request = this._latestRequest = Reqwest({
                url: url,
                type: "jsonp",
                method: "get",
                jsonpCallback: "_jsonp",
                jsonpCallbackName: "cb"
            })
                .then(function (value) {
                    if (request === self._latestRequest) {
                        self.articles = value;
                    }
                });
        }
    },

})
Esempio n. 24
0
exports.TokenFieldExample = Montage.create(Component, {

    json: {value: null},
    states: {value: null},
    members: {value: null},
    tags: {value: null},
    info: {value: null},

    logger: {
        value: null
    },

    _cachedStates: {value: null},

    prepareForDraw: {
        value: function() {
            this.states = [states[0], states[3], states[5]];
            prettyPrint();
        }
    },

    stateShouldGetSuggestions: {
        value: function(tokenField, searchTerm) {
            var results = [];
            if(searchTerm) {
                var term = searchTerm.toLowerCase();
                if(this._cachedStates && this._cachedStates[term]) {
                    results = this._cachedStates[term];
                } else {
                    results = states.filter(function(item) {
                        // @todo - memoize
                        return (item.name.toLowerCase().indexOf(term) >= 0 || item.code.indexOf(term) >= 0);
                    });
                    if(this._cachedStates == null) {
                        this._cachedStates = {};
                    }
                    this._cachedStates[term] = results;
                }
            }
            tokenField.suggestions = results;
        }
    },

    // Return the represented object for the specified stringValue
    stateGetRepresentedObject: {
        value: function(stringValue) {
            if(stringValue) {
                stringValue = stringValue.trim().toLowerCase();
                var i, len = states.length;
                for(i=0; i<len; i++) {
                    if(states[i].name.toLowerCase() === stringValue) {
                        return states[i];
                    }
                }
            }
            return null;
        }
    },

    membersShouldGetSuggestions: {
        value: function(tokenField, searchTerm) {
            var results = [];
            // The data set is based on https://www.google.com/fusiontables/DataSource?docid=1QJT7Wi2oj5zBgjxb2yvZWA42iNPUvnvE8ZOwhA
            // Google fusion tables # 383121. However Google's API returns a CSV. So need to use this app to convert to json
            var query = "SELECT FirstName,LastName from 383121 where FirstName like '%" + searchTerm + "%'"; //" OR LastName like '%" + searchTerm + "%'";
            var uri = 'http://ft2json.appspot.com/q?sql=' + encodeURIComponent(query);

            //console.log('searching ...', uri);
            var xhr = request(uri, 'get');
            xhr.onload = function(e) {
               try {
                   var data;
                   data = JSON.parse(this.response).data;
                   var result = [];
                   if(data && data.length > 0) {
                       result = data;
                   }
                   tokenField.suggestions = result;

               } catch(e) {
                   tokenField.suggestions = [];
               }

            };
            xhr.ontimeout = function() {
                if (logger.isDebug) {
                    logger.debug('xhr timed out');
                }

               tokenField.suggestions = [];
            };
            xhr.onerror = function(e) {
                if (logger.isDebug) {
                    logger.debug('xhr errored out', e);
                }
                tokenField.suggestions = [];
            };

        }
    },

    tagsShouldGetSuggestions: {
        value: function(tokenField, searchTerm) {
            var results = [];
            if(searchTerm) {
                var term = searchTerm.toLowerCase();
                results = tags.filter(function(item) {
                    return (item.toLowerCase().indexOf(term) >= 0);
                });
            }
            tokenField.suggestions = results;
        }
    },

    handleUpdateAction: {
        value: function(event) {
            if (logger.isDebug) {
                logger.debug('data: ', this);
            }
            this.json = JSON.stringify({
                state: this.states,
                members: this.members,
                tags: this.tags
            });
        }
    }
});
Esempio n. 25
0
exports.MenuItem = Montage.create(Component, {

    itemBackground: {
        value: null
    },

    itemText: {
        value: null
    },

    subMenu: {
        value: null
    },

    data: {
        value: null
    },

    _enabled: {
        value: false
    },

    enabled: {
        get: function() {
            return this._enabled;
        },
        set: function(value) {
            if(value !== this._enabled) {
                this._enabled = value;
                this.needsDraw = true;
            }
        }
    },

    _checked: {
        value: null
    },

    checked: {
        get: function() {
            return this._checked;
        },
        set: function(value) {
            /*
            if( Object.prototype.toString.call( value ) === '[object Array]' ) {
                value =  value.indexOf(this.data.displayText + "Panel") >= 0;
            }
            */

            if(this._checked !== value) {
                this._checked = value;
                this.needsDraw = true;
            }
        }
    },

    submenu: {
        value: false
    },

    subentries: {
        value: []
    },

    prepareForDraw: {
        value: function() {

            if(!this.data) return;

            if(this.data.separator) {
                this.element.classList.add("itemSeparator");
                this.itemBackground.classList.remove("menubg");
                this.itemBackground.classList.add("separator");

                return;

            }

            // Binding the checked to the assigned bound property
            if(this.data.checked) {
                Object.defineBinding(this, "checked", {
                  boundObject: this.application.ninja.appModel,
                  boundObjectPropertyPath: this.data.checked.boundProperty
                });

            }

            if(this.data.submenu) {
                this.submenu = true;
                this.subentries = this.data.entries;
                this.subMenu.classList.add("subMenu");
            }

            this.element.addEventListener("mouseover", this, false);
            this.element.addEventListener("mouseout", this, false);

            this.itemText.innerHTML = this.data.displayText;
            this.element.addEventListener("mouseup", this, true);
        }
    },

    draw: {
        value: function() {

            if(this.enabled) {
                this.element.classList.remove("disabled");
            } else {
                this.element.classList.add("disabled");
            }

            if(this.checked) {
                this.itemBackground.classList.add("checked");
            } else {
                this.itemBackground.classList.remove("checked");
            }

            if(this.submenu) {
                this.itemBackground.classList.add("submenu");
            }
        }
    },

    captureMouseup: {
        value: function(event) {

            if(this.data.radio && this.checked){
                this.parentComponent.ownerComponent.toggleOnMenuItemAction();
                return;
            }

            if( ( this.enabled === true || this.enabled > 0 ) && (this.submenu === false) ) {
                if(this.data.action) {
                    NJevent ( this.data.action );
                } else  if(this.checked !== null) {
                    this.checked = !this.checked;
                }
                this.parentComponent.ownerComponent.toggleOnMenuItemAction();
            }

        }
    },

    handleMouseover: {
        value: function() {
            if(this.enabled){
                this.element.style.backgroundColor = "#7f7f7f";
                this.element.style.cursor = "pointer";
                if(this.data.submenu) {
                    this.subMenu.style.display = "block";
                }
            }
        }
    },

    handleMouseout: {
        value: function() {
            this.element.style.backgroundColor = "#474747";
            if(this.data.submenu) {
                this.subMenu.style.display = "none";
            }
        }
    }

});
Esempio n. 26
0
var BrushProperties = exports.BrushProperties = Montage.create(ToolProperties, {
    addedColorChips: { value: false },

    _fillColorCtrl: {
        value: null,
        serializable: true
    },

    _strokeSize: {
        value: null,
        serializable: true
    },

    _strokeHardness: {
        value: null,
        serializable: true
    },

    _doSmoothing: {
        value: null,
        serializable: true
    },

    _smoothingAmount: {
        value: null,
        serializable: true
    },

    _useCalligraphic: {
        value: null,
        serializable: true
    },

    _strokeAngle: {
        value: null,
        serializable: true
    },

    _angleLabel: {
        value: null,
        serializable: true
    },

    _fill: {
        enumerable: false,
        value: { colorMode: 'rgb', color: { r: 0, g: 0, b: 0, a: 1, css: 'rgb(0,0,0)', mode: 'rgb', wasSetByCode: true, type: 'change' }, webGlColor: [0, 0, 0, 1] }
    },

    fill: {
        enumerable: true,
        get: function () {
            return this._fill;
        },
        set: function (value) {
            if (value !== this._fill) {
                this._fill = value;
            }
        }
    },

    draw: {
        enumerable: false,
        value: function () {
            Object.getPrototypeOf(BrushProperties).draw.call(this);

            if (this.addedColorChips === false && this.application.ninja.colorController.colorPanelDrawn) {
                this._fillColorCtrl.props = {side: 'top', align: 'left', wheel: true, palette: true, gradient: true, image: false, nocolor: true, offset: 8};
                this.application.ninja.colorController.addButton("chip", this._fillColorCtrl);

                this._fillColorCtrl.addEventListener("change", this.handleFillColorChange.bind(this), false);

                this.addedColorChips = true;
            }

            if (this.addedColorChips) {
                this._fillColorCtrl.color(this._fill.colorMode, this._fill.color);
            }
        }
    },

    _subPrepare: {
        value: function() {
            this.handleChange(null);
            this._useCalligraphic.addEventListener("change", this, false);
            this._doSmoothing.addEventListener("change", this, false);
        }
    },
    handleChange: {
        value: function(event) {
            if(this._useCalligraphic.checked) {
                this._strokeAngle.element.style["display"] = "";
                this._strokeAngle.visible = true;
                this._angleLabel.style["display"] = "";
            } else {
                this._strokeAngle.element.style["display"] = "none";
                this._strokeAngle.visible = false;
                this._angleLabel.style["display"] = "none";
            }
            if(this._doSmoothing.checked) {
                this._smoothingAmount.element.style["display"] = "";
                this._smoothingAmount.visible = true;
            } else {
                this._smoothingAmount.element.style["display"] = "none";
                this._smoothingAmount.visible = false;
            }
        }
    },

    handleFillColorChange: {
        value: function (e) {
            this.fill = e._event;
            this.fill.webGlColor = this.application.ninja.colorController.colorModel.colorToWebGl(e._event.color);
        }
    },

    strokeSize: {
        get: function() { return this._strokeSize; }
    },
    strokeHardness: {
        get: function() { return this._strokeHardness; }
    },
    doSmoothing:{
        get: function() {return this._doSmoothing.checked; }
    },
    smoothingAmount:{
        get: function() {return this._smoothingAmount;}
    },
    useCalligraphic: {
        get: function() {return this._useCalligraphic.checked;}
    },
    strokeAngle: {
        get: function() {return this._strokeAngle;}
    }
});
Esempio n. 27
0
var Montage = require("montage/core/core").Montage,
    Component = require("montage/ui/component").Component;

exports.RepetitionExample = Montage.create(Component, {

    jsonSelectedItems: {
        value: null
    },

    _selectedItems: {value: null},
    selectedItems: {
        get: function(){ return this._selectedItems; },
        set: function(v) {

            this._selectedItems = v;
            this.jsonSelectedItems = JSON.stringify(this._selectedItems||[]);
            console.log('selected items = ', v);
        }
    },

    selectedAnswer: {value: null},

     prepareForDraw: {
        value: function() {
            // Invoke Google pretty printer on source code samples
            prettyPrint();
        }
    }

});
Esempio n. 28
0
exports.JsonpTransport = Montage.specialize(/** @lends JsonpTransport# */ {
    constructor: {
        value: function JsonpTransport() {
            this.super();
        }
    },

    makeRequest: {
        value: function (url, servicePrefix, callbackParameter) {
            var deferredResponse = Promise.defer(),
                self = this,
                parsedUrl = Url.parse(url),
                params = Params.decode(parsedUrl.query),
                callbackNamePrefix = servicePrefix ? servicePrefix + "ServiceCallback" : "serviceCallback",
                callbackMethodName = callbackNamePrefix + Uuid.generate().replace(/-/g, "_"),
                scriptElement = document.createElement("script"),
                requestUrl;

            window[callbackMethodName] = function(data) {
                self._handleResponse(data, deferredResponse);
                document.head.removeChild(scriptElement);
                delete window[callbackMethodName];
            };

            params[callbackParameter? callbackParameter : "callback"] = callbackMethodName;

            requestUrl = url.replace(parsedUrl.query, "") + Params.encode(params);
            scriptElement.src = requestUrl;

            document.head.appendChild(scriptElement);

            return deferredResponse.promise;
        }
    },

    _handleResponse: {
        value: function (data, deferred) {
            console.log("response", data);
            if (!data) {
                deferred.reject(new Error("Unknown API Error"));
            } else if (data.error) {
                deferred.reject(new Error(data.error));
            } else {
                deferred.resolve(data);
            }
        }
    }

});
Esempio n. 29
0
exports.DocumentController = Montage.create(Component, {
    ////////////////////////////////////////////////////////////////////
    //
    hasTemplate: {
        enumerable: false,
        value: false
    },
    ////////////////////////////////////////////////////////////////////
    //
    save: {
        value: function () {
            //
        }
    },
    ////////////////////////////////////////////////////////////////////
    //
    saveAs: {
        value: function () {
            //
        }
    },
    ////////////////////////////////////////////////////////////////////
    //
    close: {
        value: function () {
            //
        }
    }
    ////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////
});
Esempio n. 30
0
exports.ObjectsTray = Montage.create(Component, {
    hideClass : { value: 'hide-objects-tray'},
    _empty : { value: null },
    _workspaceMode : { value: null },

    iconsRepetition : {
        value: null
    },
    offStageObjectsController : {
        value: null
    },

    _showAllObjects : { value: null },
    showAllObjects : {
        get : function() { return this._showAllObjects; },
        set : function(value) {
            if(value === this._showAllObjects) { return; }

            this._showAllObjects = value;

            this.needsDraw = true;
        }
    },

    workspaceMode : {
        get : function() { return this._workspaceMode; },
        set : function(value) {
            if(value === this._workspaceMode) { return; }

            var toHide = (value !== 'binding');

            setTimeout(function() {
                this.hide = toHide;
            }.bind(this), 200);

            this._workspaceMode = value;

            this.needsDraw = true;
        }
    },

    _objects: { value: null },
    objects: {
        get: function() {
            return this._objects;
        },
        set: function(value) {
            this._objects = value;
            this.needsDraw = true;
        }
    },

    offStageObjectFilter : {
        value: function(obj) {
            if(this.showAllObjects) {
                return true;
            }

            return this.application.ninja.objectsController.isOffStageObject(obj);
        }
    },

    _hide : { value: null },
    hide : {
        get : function() { return this._hide; },
        set : function(value) {
            if(value === this._hide) { return; }

            this._hide = value;

            this.needsDraw = true;
        }
    },

    displayHUDForObject : {
        value: function(object) {
            this.parentComponent.boundComponents.push(object);
        }
    },

    /* ---------------------
     Draw Cycle
     --------------------- */

    templateDidLoad: {
        value: function() {
            this.offStageObjectsController.filterFunction = this.offStageObjectFilter.bind(this);
        }
    },

    prepareForDraw : {
        value: function() {

            Object.defineBinding(this, 'workspaceMode', {
                "boundObject": this.application.ninja,
                "boundObjectPropertyPath": "workspaceMode",
                "oneway": true
            });

            Object.defineBinding(this, 'objects', {
                "boundObject": this.application.ninja.objectsController,
                "boundObjectPropertyPath": "objects",
                "oneway": true
            });

        }
    },
    willDraw : {
        value: function() {
            if(this.objects) {
                this._empty = !this.offStageObjectsController.organizedObjects.length;
            } else {
                this._empty = true;
            }
        }
    },
    draw : {
        value: function() {
            if(this.hide || this._empty) {
                this.element.classList.add(this.hideClass);
            } else {
                this.element.classList.remove(this.hideClass);
            }
        }
    }

});