<commit_before>export class Shape {
  /**
   * Creates base shape instance
   * It needed for creating your own shapes
   * @constructor
   * @param {Object} options
   */
  constructor(options = {}) {
    this.setWidth(options.width);
    this.setHeight(options.height);
    this.setPosition(options.x, options.y);
    this.setBackground(options.background);
    this.setForeground(options.foreground);
  }

  /**
   * Get shape width
   * @returns {Number}
   */
  getWidth() {
    return this._width;
  }

  /**
   * Set new shape width
   * @param {Number} width
   * @returns {Shape}
   */
  setWidth(width = 10) {
    this._width = width;
    return this;
  }

  /**
   * Get shape height
   * @returns {Number}
   */
  getHeight() {
    return this._height;
  }

  /**
   * Set new shape height
   * @param {Number} height
   * @returns {Shape}
   */
  setHeight(height = 10) {
    this._height = height;
    return this;
  }

  /**
   * Get current position of shape
   * @returns {{x: Number, y: Number}}
   */
  getPosition() {
    return {x: this._x, y: this._y};
  }

  /**
   * Set new shape position
   * @param {Number} x
   * @param {Number} y
   * @returns {Shape}
   */
  setPosition(x = this._x || 10, y = this._y || 10) {
    this._x = x;
    this._y = y;
    return this;
  }

  /**
   * Get background color
   * @returns {String}
   */
  getBackground() {
    return this._background;
  }

  /**
   * Set new background color
   * @param {String} background
   * @returns {Shape}
   */
  setBackground(background) {
    this._background = background;
    return this;
  }

  /**
   * Get foreground color
   * @returns {String}
   */
  getForeground() {
    return this._foreground;
  }

  /**
   * Set new foreground color
   * @param {String} foreground
   * @returns {Shape}
   */
  setForeground(foreground) {
    this._foreground = foreground;
    return this;
  }

  /**
   * Base render method that must be implemented in childes
   */
  render() {
    // TODO: Make sure that it's correct
    throw new Error('render() method must be implemented');
  }
}
<commit_msg>feat(shape): Adds to base shape text property<commit_after>export class Shape {
  /**
   * Creates new base shape instance
   * It needed for creating other shapes as base class
   * @constructor
   * @param {String} text
   * @param {Number} width
   * @param {Number} height
   * @param {Number} x
   * @param {Number} y
   * @param {String} background
   * @param {String} foreground
   */
  constructor({text, width, height, x, y, background, foreground}) {
    this.setText(text);
    this.setWidth(width);
    this.setHeight(height);
    this.setPosition(x, y);
    this.setBackground(background);
    this.setForeground(foreground);
  }

  /**
   * Get text content from this shape
   * @returns {String}
   */
  getText() {
    return this._text;
  }

  /**
   * Set new text content to this shape
   * @param {String} text
   * @returns {Shape}
   */
  setText(text) {
    this._text = text;
    return this;
  }

  /**
   * Get shape width
   * @returns {Number}
   */
  getWidth() {
    return this._width;
  }

  /**
   * Set new shape width
   * @param {Number} width
   * @returns {Shape}
   */
  setWidth(width = 10) {
    this._width = width;
    return this;
  }

  /**
   * Get shape height
   * @returns {Number}
   */
  getHeight() {
    return this._height;
  }

  /**
   * Set new shape height
   * @param {Number} height
   * @returns {Shape}
   */
  setHeight(height = 10) {
    this._height = height;
    return this;
  }

  /**
   * Get current position of shape
   * @returns {{x: Number, y: Number}}
   */
  getPosition() {
    return {x: this._x, y: this._y};
  }

  /**
   * Set new shape position
   * @param {Number} x
   * @param {Number} y
   * @returns {Shape}
   */
  setPosition(x = this._x || 10, y = this._y || 10) {
    this._x = x;
    this._y = y;
    return this;
  }

  /**
   * Get background color
   * @returns {String}
   */
  getBackground() {
    return this._background;
  }

  /**
   * Set new background color
   * @param {String} background
   * @returns {Shape}
   */
  setBackground(background) {
    this._background = background;
    return this;
  }

  /**
   * Get foreground color
   * @returns {String}
   */
  getForeground() {
    return this._foreground;
  }

  /**
   * Set new foreground color
   * @param {String} foreground
   * @returns {Shape}
   */
  setForeground(foreground) {
    this._foreground = foreground;
    return this;
  }

  /**
   * Base render method that must be implemented in childes
   */
  render() {
    // TODO: Make sure that it's correct
    throw new Error('render() method must be implemented');
  }
}
<|endoftext|>


<commit_before>Canvas2D.Sheet = Class.extend( {
    init: function init(props) {
	props = props || {};

	this.name  = props.name  || "default";   // name of the sheet
	this.style = props.style || "static";    // selected style

	this.clear();
	this.dirty = false;

	if(props.canvas) { this.setCanvas(props.canvas); }

	Canvas2D.Keyboard.on( "keyup", this.handleKeyDown.scope(this) );
    },

    setCanvas: function setCanvas(canvas) {
	this.canvas = canvas;
	this.wireCanvasDelegation();
	this.setupProperties();
    },

    wireCanvasDelegation: function wireCanvasDelegation() {
	if( !this.canvas ) { return; }

	Canvas2D.Sheet.Operations.iterate(function(operation) {
	    this[operation] = function() {
		this.transferProperties();
		return this.canvas[operation].apply(this.canvas, arguments);
	    }.scope(this);
	}.scope(this) );
    },

    setupProperties: function setupProperties() {
	Canvas2D.Sheet.Properties.iterate( function(prop) {
	    this[prop] = Canvas2D.Sheet.Defaults[prop] || this.canvas[prop];
	}.scope(this) );
    },

    transferProperties : function() {
	Canvas2D.Sheet.Properties.iterate(function(prop) {
	    this.canvas[prop] = this[prop];
	}.scope(this) );
    },

    makeDirty: function() {
	this.dirty = true;
	this.fireEvent( "change" );
    },

    isDirty: function() {
	return this.dirty;
    },

    clear: function() {
	this.positions      = []; // list of shapes on the sheet
    	this.shapesMap      = {}; // name to shape mapping
    	this.positionsMap   = {}; // shape to position mapping
	this.selectedShapes = []; // list of selected shapes

	this.fireEvent( "change" );
    },

    makeDynamic: function() { this.style = "dynamic";         },
    makeStatic : function() { this.style = "static";          },
    isDynamic  : function() { return this.style == "dynamic"; },
    isStatic   : function() { return !this.isDynamic();       },

    freeze: function() { this.fireEvent( "freeze" ); },
    thaw:   function() { this.fireEvent( "thaw" );   },

    at: function(left, top) {
	this.newTop  = top;
	this.newLeft = left;
	return this;
    },

    put: function(shape) {
	return this.add(shape);
    },

    add: function(shape) {
	var position = new Canvas2D.Position( shape, this.newLeft, this.newTop);
	shape   .on( "change", this.makeDirty.scope(this) );
	position.on( "change", this.makeDirty.scope(this) );

	this.newLeft = null;
	this.newTop = null;

	this.positions.push(position);
	this.shapesMap[shape.getName()] = shape;
	this.positionsMap[shape.getName()] = position;

	this.fireEvent( "newShape", "added new shape" +
			( position.getLeft() != null ?
			  "@" + position.getLeft() + ","
			  + position.getTop() : "" ) );
	return shape;
    },

    getPosition: function getPosition(shape) {
	return this.positionsMap[shape.getName()];
    },

    hit: function(x,y) {
	for( var s = this.positions.length-1; s>=0; s-- ) {
	    var position = this.positions[s];
	    if( position.hit(x,y) ) {
		if( Canvas2D.Keyboard.keyDown(91) ||    // cmd
		    Canvas2D.Keyboard.keyDown(17) )     // ctrl
		{
		    // adding and removing
		    if( this.selectedShapes.contains(position) ) {
			this.selectedShapes.remove(position);
		    } else {
			this.selectedShapes.push(position);
		    }
		} else {
		    if( !this.selectedShapes.contains(position) ) {
			this.selectedShapes = [ position ];
		    } else {
			// just clicked on already selected shape
			return;
		    }
		}
		this.fireEvent( "shapeSelected", position );
		return;
	    }
	}
	// no position was hit, so clearing the selection list
	this.selectedShapes = [];
    },

    hitArea: function( left, top, right, bottom ) {
	var newSelection =
	    ( Canvas2D.Keyboard.keyDown(91) || // cmd
	      Canvas2D.Keyboard.keyDown(17) ) // ctrl
	    ? this.selectedShapes : [];
	for( var s = this.positions.length-1; s>=0; s-- ) {
	    if( this.positions[s].hitArea(left, top, right, bottom) ) {
		newSelection.push( this.positions[s] );
		this.fireEvent( "shapeSelected", this.positions[s] );
	    }
	}
	this.selectedShapes = newSelection.unique();
    },

    handleMouseDown: function(pos) {
	if( !this.isDynamic() ) { return; }
	this.hit( pos.x, pos.y );
	this.currentPos = pos;
	this.makeDirty();
    },

    handleMouseUp: function(pos) {
	if( !this.isDynamic() ) { return; }
	this.selectedShapes.iterate(function(position) {
	    this.fireEvent( "shapesMoved",
			    "Shape moved to " +
			    position.left + ", " + position.top );
	}.scope(this) );
	this.showSelection   = false;
	this.makeDirty();
    },

    handleMouseDrag: function(pos) {
	if( !this.isDynamic() ) { return; }
	if( !this.showSelection && this.selectedShapes.length > 0 ) {
	    this.moveCurrentSelection(pos.dx, pos.dy);
	} else {
	    this.showSelection = true;
	    this.hitArea( this.currentPos.x, this.currentPos.y,
			  pos.x,             pos.y );
	    this.selectionPos  = pos;
	}
	this.makeDirty();
    },

    selectAllShapes: function() {
	// FIXME: only selectable shapes (so no connectors)
	this.selectedShapes = [];
	this.positions.iterate( function(position) {
	    this.selectedShapes.push(position)
	}.scope(this) );
	this.makeDirty();
    },

    moveCurrentSelection: function(dx, dy) {
	this.selectedShapes.iterate(function(position) {
	    position.move(dx, dy);
	}.scope(this) );
    },

    handleKeyDown: function(key) {
	if( Canvas2D.Keyboard.keyDown(16) ) { // shift +
	    switch(key) {
	    case 37: this.moveCurrentSelection( -5,  0 ); break; // left
	    case 38: this.moveCurrentSelection(  0, -5 ); break; // up
	    case 39: this.moveCurrentSelection(  5,  0 ); break; // right
	    case 40: this.moveCurrentSelection(  0,  5 ); break; // down
	    }
	}
	if( ( Canvas2D.Keyboard.keyDown(91) ||    // cmd
	      Canvas2D.Keyboard.keyDown(17) ) &&  // ctrl +
	    key == 65 &&                          // a
	    this.canvas.mouseOver )
	{
	    this.selectAllShapes();
	}
    },

    addSelectionOverlay: function() {
	if( this.showSelection ) {
	    var pos = this.selectionPos;
	    var dx = pos.x - this.currentPos.x;
	    var dy = pos.y - this.currentPos.y;

	    this.canvas.fillStyle = "rgba( 0, 0, 255, 0.1 )";
	    this.canvas.fillRect( pos.x <= this.currentPos.x ?
				  pos.x : this.currentPos.x,
				  pos.y <= this.currentPos.y ?
				  pos.y : this.currentPos.y,
				  Math.abs(dx), Math.abs(dy) );
	}
    },

    addSelectionMarkers: function() {
	this.selectedShapes.iterate( function(shape) {
	    var box = shape.getBox();
	    this.canvas.fillStyle = "rgba( 200, 200, 255, 1 )";
	    [[ box.left, box.top    ], [ box.right, box.top    ],
	     [ box.left, box.bottom ], [ box.right, box.bottom ]].iterate(
		 function(corner) {
		     this.canvas.beginPath();
		     this.canvas.arc( corner[0],  corner[1], 5, 0,
				      Math.PI*2, true );
		     this.canvas.fill();
		 }.scope(this) );
	}.scope(this) );
    },

    render: function() {
	var delayed = [];
	this.positions.iterate( function(shape) {
	    if( shape.delayRender() ) {
		delayed.push(shape);
	    } else {
		shape.render(this);
	    }
	}.scope(this) );

	delayed.iterate( function(shape) {
	    shape.render(this);
	}.scope(this) );

	this.addSelectionOverlay();
	this.addSelectionMarkers();
    },

    toADL: function() {
	var s = "";
	s += "Sheet "  + this.name;
	s += " +" + this.style + " {\n";
	this.positions.iterate(function(shape) {
	    var t = shape.toADL("  ");
	    if( t ) { s += t + "\n"; }
	} );
	s += "}";
	return s;
    }
} );

// add-in some common functionality
ProtoJS.mix( Canvas2D.Factory.extensions.all.EventHandling,
	     Canvas2D.Sheet.prototype );

Canvas2D.Sheet.Properties =
    [ "globalAlpha", "globalCompositeOperation",
      "strokeStyle", "fillStyle", "lineWidth",
      "lineCap", "lineJoin", "miterLimit",
      "shadowOffsetX", "shadowOffsetY", "shadowBlur", "shadowColor",
      "font", "textAlign", "textBaseline",

      "lineStyle", "useCrispLines", "textDecoration" ];

Canvas2D.Sheet.Operations =
    [ "save", "restore",
      "scale", "rotate", "translate", "transform", "setTransform",
      "createRadialGradient", "createPattern",
      "clearRect", "fillRect", "strokeRect",
      "beginPath", "closePath", "moveTo", "lineTo",
      "quadraticCurveTo", "bezierCurveTo",
      "arcTo", "rect", "arc",
      "fill", "stroke",
      "clip","isPointInPath",
      "fillText","fillText","strokeText","strokeText","measureText",
      "drawImage","createImageData","getImageData","putImageData",

      "getFontSize", "fillStrokeRect" ];

Canvas2D.Sheet.from = function(construct, book) {
    var style = "static";
    var styleModifier = construct.modifiers.get( "style" );
    if( styleModifier ) {
	style = styleModifier.value.value.toLowerCase();
    }

    construct.modifiers.iterate(function(key, value) {
	if( key.toLowerCase() == "static"
	    || key.toLowerCase() == "dynamic" ) {
	    style = key.toLowerCase();
	}
    });

    return new Canvas2D.Sheet({ name: construct.name, style: style } );
};

Canvas2D.Sheet.MANIFEST = {
    name      : "sheet",
    properties : [],
    libraries : [ "Canvas2D" ]
};

Canvas2D.registerShape( Canvas2D.Sheet );
<commit_msg>implemented basic support for generics based on string notation in name of shapes<commit_after>Canvas2D.Sheet = Class.extend( {
    init: function init(props) {
	props = props || {};

	this.name  = props.name  || "default";   // name of the sheet
	this.style = props.style || "static";    // selected style

	this.clear();
	this.dirty = false;

	if(props.canvas) { this.setCanvas(props.canvas); }

	Canvas2D.Keyboard.on( "keyup", this.handleKeyDown.scope(this) );
    },

    setCanvas: function setCanvas(canvas) {
	this.canvas = canvas;
	this.wireCanvasDelegation();
	this.setupProperties();
    },

    wireCanvasDelegation: function wireCanvasDelegation() {
	if( !this.canvas ) { return; }

	Canvas2D.Sheet.Operations.iterate(function(operation) {
	    this[operation] = function() {
		this.transferProperties();
		return this.canvas[operation].apply(this.canvas, arguments);
	    }.scope(this);
	}.scope(this) );
    },

    setupProperties: function setupProperties() {
	Canvas2D.Sheet.Properties.iterate( function(prop) {
	    this[prop] = Canvas2D.Sheet.Defaults[prop] || this.canvas[prop];
	}.scope(this) );
    },

    transferProperties : function() {
	Canvas2D.Sheet.Properties.iterate(function(prop) {
	    this.canvas[prop] = this[prop];
	}.scope(this) );
    },

    makeDirty: function() {
	this.dirty = true;
	this.fireEvent( "change" );
    },

    isDirty: function() {
	return this.dirty;
    },

    clear: function() {
	this.positions      = []; // list of shapes on the sheet
    	this.shapesMap      = {}; // name to shape mapping
    	this.positionsMap   = {}; // shape to position mapping
	this.selectedShapes = []; // list of selected shapes

	this.fireEvent( "change" );
    },

    makeDynamic: function() { this.style = "dynamic";         },
    makeStatic : function() { this.style = "static";          },
    isDynamic  : function() { return this.style == "dynamic"; },
    isStatic   : function() { return !this.isDynamic();       },

    freeze: function() { this.fireEvent( "freeze" ); },
    thaw:   function() { this.fireEvent( "thaw" );   },

    at: function(left, top) {
	this.newTop  = top;
	this.newLeft = left;
	return this;
    },

    put: function(shape) {
	return this.add(shape);
    },

    add: function(shape) {
	var position = new Canvas2D.Position( shape, this.newLeft, this.newTop);
	shape   .on( "change", this.makeDirty.scope(this) );
	position.on( "change", this.makeDirty.scope(this) );

	this.newLeft = null;
	this.newTop = null;

	this.positions.push(position);
	this.shapesMap[shape.getName().replace(/<.*$/,'')] = shape;
	this.positionsMap[shape.getName()] = position;

	this.fireEvent( "newShape", "added new shape" +
			( position.getLeft() != null ?
			  "@" + position.getLeft() + ","
			  + position.getTop() : "" ) );
	return shape;
    },

    getPosition: function getPosition(shape) {
	return this.positionsMap[shape.getName()];
    },

    hit: function(x,y) {
	for( var s = this.positions.length-1; s>=0; s-- ) {
	    var position = this.positions[s];
	    if( position.hit(x,y) ) {
		if( Canvas2D.Keyboard.keyDown(91) ||    // cmd
		    Canvas2D.Keyboard.keyDown(17) )     // ctrl
		{
		    // adding and removing
		    if( this.selectedShapes.contains(position) ) {
			this.selectedShapes.remove(position);
		    } else {
			this.selectedShapes.push(position);
		    }
		} else {
		    if( !this.selectedShapes.contains(position) ) {
			this.selectedShapes = [ position ];
		    } else {
			// just clicked on already selected shape
			return;
		    }
		}
		this.fireEvent( "shapeSelected", position );
		return;
	    }
	}
	// no position was hit, so clearing the selection list
	this.selectedShapes = [];
    },

    hitArea: function( left, top, right, bottom ) {
	var newSelection =
	    ( Canvas2D.Keyboard.keyDown(91) || // cmd
	      Canvas2D.Keyboard.keyDown(17) ) // ctrl
	    ? this.selectedShapes : [];
	for( var s = this.positions.length-1; s>=0; s-- ) {
	    if( this.positions[s].hitArea(left, top, right, bottom) ) {
		newSelection.push( this.positions[s] );
		this.fireEvent( "shapeSelected", this.positions[s] );
	    }
	}
	this.selectedShapes = newSelection.unique();
    },

    handleMouseDown: function(pos) {
	if( !this.isDynamic() ) { return; }
	this.hit( pos.x, pos.y );
	this.currentPos = pos;
	this.makeDirty();
    },

    handleMouseUp: function(pos) {
	if( !this.isDynamic() ) { return; }
	this.selectedShapes.iterate(function(position) {
	    this.fireEvent( "shapesMoved",
			    "Shape moved to " +
			    position.left + ", " + position.top );
	}.scope(this) );
	this.showSelection   = false;
	this.makeDirty();
    },

    handleMouseDrag: function(pos) {
	if( !this.isDynamic() ) { return; }
	if( !this.showSelection && this.selectedShapes.length > 0 ) {
	    this.moveCurrentSelection(pos.dx, pos.dy);
	} else {
	    this.showSelection = true;
	    this.hitArea( this.currentPos.x, this.currentPos.y,
			  pos.x,             pos.y );
	    this.selectionPos  = pos;
	}
	this.makeDirty();
    },

    selectAllShapes: function() {
	// FIXME: only selectable shapes (so no connectors)
	this.selectedShapes = [];
	this.positions.iterate( function(position) {
	    this.selectedShapes.push(position)
	}.scope(this) );
	this.makeDirty();
    },

    moveCurrentSelection: function(dx, dy) {
	this.selectedShapes.iterate(function(position) {
	    position.move(dx, dy);
	}.scope(this) );
    },

    handleKeyDown: function(key) {
	if( Canvas2D.Keyboard.keyDown(16) ) { // shift +
	    switch(key) {
	    case 37: this.moveCurrentSelection( -5,  0 ); break; // left
	    case 38: this.moveCurrentSelection(  0, -5 ); break; // up
	    case 39: this.moveCurrentSelection(  5,  0 ); break; // right
	    case 40: this.moveCurrentSelection(  0,  5 ); break; // down
	    }
	}
	if( ( Canvas2D.Keyboard.keyDown(91) ||    // cmd
	      Canvas2D.Keyboard.keyDown(17) ) &&  // ctrl +
	    key == 65 &&                          // a
	    this.canvas.mouseOver )
	{
	    this.selectAllShapes();
	}
    },

    addSelectionOverlay: function() {
	if( this.showSelection ) {
	    var pos = this.selectionPos;
	    var dx = pos.x - this.currentPos.x;
	    var dy = pos.y - this.currentPos.y;

	    this.canvas.fillStyle = "rgba( 0, 0, 255, 0.1 )";
	    this.canvas.fillRect( pos.x <= this.currentPos.x ?
				  pos.x : this.currentPos.x,
				  pos.y <= this.currentPos.y ?
				  pos.y : this.currentPos.y,
				  Math.abs(dx), Math.abs(dy) );
	}
    },

    addSelectionMarkers: function() {
	this.selectedShapes.iterate( function(shape) {
	    var box = shape.getBox();
	    this.canvas.fillStyle = "rgba( 200, 200, 255, 1 )";
	    [[ box.left, box.top    ], [ box.right, box.top    ],
	     [ box.left, box.bottom ], [ box.right, box.bottom ]].iterate(
		 function(corner) {
		     this.canvas.beginPath();
		     this.canvas.arc( corner[0],  corner[1], 5, 0,
				      Math.PI*2, true );
		     this.canvas.fill();
		 }.scope(this) );
	}.scope(this) );
    },

    render: function() {
	var delayed = [];
	this.positions.iterate( function(shape) {
	    if( shape.delayRender() ) {
		delayed.push(shape);
	    } else {
		shape.render(this);
	    }
	}.scope(this) );

	delayed.iterate( function(shape) {
	    shape.render(this);
	}.scope(this) );

	this.addSelectionOverlay();
	this.addSelectionMarkers();
    },

    toADL: function() {
	var s = "";
	s += "Sheet "  + this.name;
	s += " +" + this.style + " {\n";
	this.positions.iterate(function(shape) {
	    var t = shape.toADL("  ");
	    if( t ) { s += t + "\n"; }
	} );
	s += "}";
	return s;
    }
} );

// add-in some common functionality
ProtoJS.mix( Canvas2D.Factory.extensions.all.EventHandling,
	     Canvas2D.Sheet.prototype );

Canvas2D.Sheet.Properties =
    [ "globalAlpha", "globalCompositeOperation",
      "strokeStyle", "fillStyle", "lineWidth",
      "lineCap", "lineJoin", "miterLimit",
      "shadowOffsetX", "shadowOffsetY", "shadowBlur", "shadowColor",
      "font", "textAlign", "textBaseline",

      "lineStyle", "useCrispLines", "textDecoration" ];

Canvas2D.Sheet.Operations =
    [ "save", "restore",
      "scale", "rotate", "translate", "transform", "setTransform",
      "createRadialGradient", "createPattern",
      "clearRect", "fillRect", "strokeRect",
      "beginPath", "closePath", "moveTo", "lineTo",
      "quadraticCurveTo", "bezierCurveTo",
      "arcTo", "rect", "arc",
      "fill", "stroke",
      "clip","isPointInPath",
      "fillText","fillText","strokeText","strokeText","measureText",
      "drawImage","createImageData","getImageData","putImageData",

      "getFontSize", "fillStrokeRect" ];

Canvas2D.Sheet.from = function(construct, book) {
    var style = "static";
    var styleModifier = construct.modifiers.get( "style" );
    if( styleModifier ) {
	style = styleModifier.value.value.toLowerCase();
    }

    construct.modifiers.iterate(function(key, value) {
	if( key.toLowerCase() == "static"
	    || key.toLowerCase() == "dynamic" ) {
	    style = key.toLowerCase();
	}
    });

    return new Canvas2D.Sheet({ name: construct.name, style: style } );
};

Canvas2D.Sheet.MANIFEST = {
    name      : "sheet",
    properties : [],
    libraries : [ "Canvas2D" ]
};

Canvas2D.registerShape( Canvas2D.Sheet );
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file ProjectModel.js
 * @author Arkadiy Paronyan arkadiy@ethdev.com
 * @date 2015
 * Ethereum IDE client.
 */

var basicContractTemplate = "contract FirstContract {}"
var htmlTemplate = "<!doctype>\n" +
		"\n" +
		"\n" +
		"\n" +
		"\n" +
		"\n" +
		"\t
Sample Ratings
\n" +
		"
\n" +
		"Store:\n" +
		"\t<input type='number' id='key'>\n" +
		"\t<button onclick='set()'>Save</button>\n" +
		"
\n" +
		"
\n" +
		"Query:\n" +
		"\t<input value='get' type='button' id='query' onclick='get()' />\n" +
		"\t

\n" +
		"
\n" +
		"\n" +
		"\n";

var contractTemplate = "//Sample contract\n" +
		"contract Sample\n" +
		"{\n" +
		"\tuint value;\n" +
		"\tfunction Sample(uint v) {\n" +
		"\t\tvalue = v;\n" +
		"\t}\n" +
		"\tfunction set(uint v) {\n" +
		"\t\tvalue = v;\n" +
		"\t}\n" +
		"\tfunction get() constant returns (uint) {\n" +
		"\t\treturn value;\n" +
		"\t}\n" +
		"}\n";

function saveDocument(doc)
{
	documentSaving(doc);
	if (doc.isContract)
		contractSaved(doc);
	else
		documentSaved(doc);
}

function saveCurrentDocument()
{
	saveDocument(currentDocument)
}

function saveDocuments(onlyContracts)
{
	for (var i = 0; i < unsavedFiles.length; i++)
	{
		var d = unsavedFiles[k]
		if (!onlyContracts)
			saveDocument(d)
		else if (d.isContract)
			saveDocument(d)
	}
}

function saveAll()
{
	saveDocuments(false)
	saveProject();
}

function createProject() {
	newProjectDialog.open();
}

function closeProject(callBack) {
	if (!isEmpty && unsavedFiles.length > 0)
	{
		saveMessageDialog.callBack = callBack;
		saveMessageDialog.open();
	}
	else
	{
		projectIsClosing = true;
		doCloseProject();
		if (callBack)
			callBack();
	}
}

function saveProject() {
	if (!isEmpty) {
		projectSaving();
		var projectData = saveProjectFile();
		if (projectData !== null)
		{
			projectSaved();
		}
	}
}

function saveProjectProperty(key, value)
{
	var projectFile = projectPath + projectFileName;
	var json = fileIo.readFile(projectFile);
	if (!json)
		return;
	var projectData = JSON.parse(json);
	projectData[key] = value
	json = JSON.stringify(projectData, null, "\t");
	fileIo.writeFile(projectFile, json);
}

function saveProjectFile()
{
	if (!isEmpty) {
		var projectData = {
			files: [],
			title: projectTitle,
			deploymentAddresses: deploymentAddresses,
			applicationUrlEth: projectModel.applicationUrlEth,
			applicationUrlHttp: projectModel.applicationUrlHttp,
			packageHash: deploymentDialog.packageStep.packageHash,
			packageBase64: deploymentDialog.packageStep.packageBase64,
			deploymentDir: deploymentDialog.packageStep.packageDir,
			lastPackageDate:  deploymentDialog.packageStep.lastDeployDate,
			deployBlockNumber: projectModel.deployBlockNumber,
			localPackageUrl: deploymentDialog.packageStep.localPackageUrl,
			deploymentTrHashes: JSON.stringify(projectModel.deploymentTrHashes),
			registerContentHashTrHash: projectModel.registerContentHashTrHash,
			registerUrlTrHash: projectModel.registerUrlTrHash,
			registerContentHashBlockNumber: projectModel.registerContentHashBlockNumber,
			registerUrlBlockNumber: projectModel.registerUrlBlockNumber,
			startUrl: mainContent.webView.relativePath()
		};
		for (var i = 0; i < projectListModel.count; i++)
			projectData.files.push({
									   title: projectListModel.get(i).name,
									   fileName: projectListModel.get(i).fileName,
								   });

		projectFileSaving(projectData);
		var json = JSON.stringify(projectData, null, "\t");
		var projectFile = projectPath + projectFileName;
		fileIo.writeFile(projectFile, json);
		projectFileSaved(projectData);
		return projectData;
	}
	return null;
}

function loadProject(path) {
	closeProject(function() {
		console.log("Loading project at " + path);
		var projectFile = path + projectFileName;
		var json = fileIo.readFile(projectFile);
		if (!json)
			return;
		var projectData = JSON.parse(json);
		if (projectData.deploymentDir)
			projectModel.deploymentDir = projectData.deploymentDir
		if (projectData.packageHash)
			deploymentDialog.packageStep.packageHash =  projectData.packageHash
		if (projectData.packageBase64)
			deploymentDialog.packageStep.packageBase64 =  projectData.packageBase64
		if (projectData.applicationUrlEth)
			projectModel.applicationUrlEth = projectData.applicationUrlEth
		if (projectData.applicationUrlHttp)
			projectModel.applicationUrlHttp = projectData.applicationUrlHttp
		if (projectData.lastPackageDate)
			deploymentDialog.packageStep.lastDeployDate = projectData.lastPackageDate
		if (projectData.deployBlockNumber)
			projectModel.deployBlockNumber = projectData.deployBlockNumber
		if (projectData.localPackageUrl)
			deploymentDialog.packageStep.localPackageUrl =  projectData.localPackageUrl
		if (projectData.deploymentTrHashes)
			projectModel.deploymentTrHashes = JSON.parse(projectData.deploymentTrHashes)
		if (projectData.registerUrlTrHash)
			projectModel.registerUrlTrHash = projectData.registerUrlTrHash
		if (projectData.registerContentHashTrHash)
			projectModel.registerContentHashTrHash = projectData.registerContentHashTrHash
		if (projectData.registerContentHashBlockNumber)
			projectModel.registerContentHashBlockNumber = projectData.registerContentHashBlockNumber
		if (projectData.registerUrlBlockNumber)
			projectModel.registerUrlBlockNumber = projectData.registerUrlBlockNumber
		if (projectData.startUrl)
			projectModel.startUrl = projectData.startUrl
		if (!projectData.title) {
			var parts = path.split("/");
			projectData.title = parts[parts.length - 2];
		}
		deploymentAddresses = projectData.deploymentAddresses ? projectData.deploymentAddresses : {};
		projectTitle = projectData.title;
		if (path.lastIndexOf("/") === path.length - 1)
			path = path.substring(0, path.length - 1)
		projectPath = path;

		// all files/folders from the root path are included in Mix.
		if (!projectData.files)
			projectData.files = [];

		if (mainApplication.trackLastProject)
			projectSettings.lastProjectPath = path;

		projectLoading(projectData);
		//TODO: move this to codemodel
		var contractSources = {};
		for (var d = 0; d < listModel.count; d++) {
			var doc = listModel.get(d);
			if (doc.isContract)
				projectModel.openDocument(doc.documentId)
		}
		projectLoaded()
	});
}

function file(docData)
{
	var fileName = docData.fileName
	var extension = fileName.substring(fileName.lastIndexOf("."), fileName.length);
	var path = docData.path
	var isContract = extension === ".sol";
	var isHtml = extension === ".html";
	var isCss = extension === ".css";
	var isJs = extension === ".js";
	var isImg = extension === ".png"  || extension === ".gif" || extension === ".jpg" || extension === ".svg";
	var syntaxMode = isContract ? "solidity" : isJs ? "javascript" : isHtml ? "htmlmixed" : isCss ? "css" : "";
	var groupName = isContract ? qsTr("Contracts") : isJs ? qsTr("Javascript") : isHtml ? qsTr("Web Pages") : isCss ? qsTr("Styles") : isImg ? qsTr("Images") : qsTr("Misc");
	var docData = {
		contract: false,
		path: path,
		fileName: fileName,
		name: fileName,
		documentId: path,
		syntaxMode: syntaxMode,
		isText: isContract || isHtml || isCss || isJs,
		isContract: isContract,
		isHtml: isHtml,
		groupName: groupName
	};
	return docData
}

function doCloseProject() {
	console.log("Closing project");
	projectListModel.clear();
	projectPath = "";
	currentDocument = null
	projectClosed();
}

function doCreateProject(title, path) {
	closeProject(function() {
		console.log("Creating project " + title + " at " + path);
		var dirPath = path + "/" + title
		fileIo.makeDir(dirPath);
		var projectFile = dirPath + projectFileName;

		var indexFile = "index.html";
		var contractsFile = "contract.sol";
		var projectData = {
			title: title,
			files: [ contractsFile, indexFile ]
		};
		//TODO: copy from template
		if (!fileIo.fileExists(dirPath + "/" + indexFile))
			fileIo.writeFile(dirPath + "/" + indexFile, htmlTemplate);
		if (!fileIo.fileExists(dirPath + "/" + contractsFile))
			fileIo.writeFile(dirPath + "/" + contractsFile, contractTemplate);

		newProject(projectData);
		var json = JSON.stringify(projectData, null, "\t");
		fileIo.writeFile(projectFile, json);
		loadProject(dirPath);
	});
}

function newHtmlFile() {
	createAndAddFile("page", "html", htmlTemplate);
}

function newCssFile() {
	createAndAddFile("style", "css", "body {\n}\n");
}

function newJsFile() {
	createAndAddFile("script", "js", "function foo() {\n}\n");
}

function newContract() {
	var ctrName = "contract" + Object.keys(codeModel.contracts).length
	var ctr = basicContractTemplate.replace("FirstContract", ctrName)
	createAndAddFile("contract", "sol", ctr, ctrName + ".sol");
}

function createAndAddFile(name, extension, content, fileName) {
	fileName = generateFileName(name, extension);
	var filePath = currentFolder + "/" + fileName;
	if (!fileIo.fileExists(filePath))
		fileIo.writeFile(filePath, content);
	saveProjectFile();
	documentAdded(filePath);
}

function generateFileName(name, extension) {
	var i = 1;
	do {
		var fileName = name + i + "." + extension;
		var filePath = currentFolder + "/" + fileName;
		i++;
	} while (fileIo.fileExists(filePath));
	return fileName
}

<commit_msg> -  bug Fix (while loading/creating project).<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file ProjectModel.js
 * @author Arkadiy Paronyan arkadiy@ethdev.com
 * @date 2015
 * Ethereum IDE client.
 */

var basicContractTemplate = "contract FirstContract {}"
var htmlTemplate = "<!doctype>\n" +
		"\n" +
		"\n" +
		"\n" +
		"\n" +
		"\n" +
		"\t
Sample Ratings
\n" +
		"
\n" +
		"Store:\n" +
		"\t<input type='number' id='key'>\n" +
		"\t<button onclick='set()'>Save</button>\n" +
		"
\n" +
		"
\n" +
		"Query:\n" +
		"\t<input value='get' type='button' id='query' onclick='get()' />\n" +
		"\t

\n" +
		"
\n" +
		"\n" +
		"\n";

var contractTemplate = "//Sample contract\n" +
		"contract Sample\n" +
		"{\n" +
		"\tuint value;\n" +
		"\tfunction Sample(uint v) {\n" +
		"\t\tvalue = v;\n" +
		"\t}\n" +
		"\tfunction set(uint v) {\n" +
		"\t\tvalue = v;\n" +
		"\t}\n" +
		"\tfunction get() constant returns (uint) {\n" +
		"\t\treturn value;\n" +
		"\t}\n" +
		"}\n";

function saveDocument(doc)
{
	documentSaving(doc);
	if (doc.isContract)
		contractSaved(doc);
	else
		documentSaved(doc);
}

function saveCurrentDocument()
{
	saveDocument(currentDocument)
}

function saveDocuments(onlyContracts)
{
	for (var i = 0; i < unsavedFiles.length; i++)
	{
		var d = unsavedFiles[k]
		if (!onlyContracts)
			saveDocument(d)
		else if (d.isContract)
			saveDocument(d)
	}
}

function saveAll()
{
	saveDocuments(false)
	saveProject();
}

function createProject() {
	newProjectDialog.open();
}

function closeProject(callBack) {
	if (!isEmpty && unsavedFiles.length > 0)
	{
		saveMessageDialog.callBack = callBack;
		saveMessageDialog.open();
	}
	else
	{
		projectIsClosing = true;
		doCloseProject();
		if (callBack)
			callBack();
	}
}

function saveProject() {
	if (!isEmpty) {
		projectSaving();
		var projectData = saveProjectFile();
		if (projectData !== null)
		{
			projectSaved();
		}
	}
}

function saveProjectProperty(key, value)
{
	var projectFile = projectPath + projectFileName;
	var json = fileIo.readFile(projectFile);
	if (!json)
		return;
	var projectData = JSON.parse(json);
	projectData[key] = value
	json = JSON.stringify(projectData, null, "\t");
	fileIo.writeFile(projectFile, json);
}

function saveProjectFile()
{
	if (!isEmpty) {
		var projectData = {
			files: [],
			title: projectTitle,
			deploymentAddresses: deploymentAddresses,
			applicationUrlEth: projectModel.applicationUrlEth,
			applicationUrlHttp: projectModel.applicationUrlHttp,
			packageHash: deploymentDialog.packageStep.packageHash,
			packageBase64: deploymentDialog.packageStep.packageBase64,
			deploymentDir: deploymentDialog.packageStep.packageDir,
			lastPackageDate:  deploymentDialog.packageStep.lastDeployDate,
			deployBlockNumber: projectModel.deployBlockNumber,
			localPackageUrl: deploymentDialog.packageStep.localPackageUrl,
			deploymentTrHashes: JSON.stringify(projectModel.deploymentTrHashes),
			registerContentHashTrHash: projectModel.registerContentHashTrHash,
			registerUrlTrHash: projectModel.registerUrlTrHash,
			registerContentHashBlockNumber: projectModel.registerContentHashBlockNumber,
			registerUrlBlockNumber: projectModel.registerUrlBlockNumber,
			startUrl: mainContent.webView.relativePath()
		};
		for (var i = 0; i < projectListModel.count; i++)
			projectData.files.push({
									   title: projectListModel.get(i).name,
									   fileName: projectListModel.get(i).fileName,
								   });

		projectFileSaving(projectData);
		var json = JSON.stringify(projectData, null, "\t");
		var projectFile = projectPath + "/" + projectFileName;
		fileIo.writeFile(projectFile, json);
		projectFileSaved(projectData);
		return projectData;
	}
	return null;
}

function loadProject(path) {
	closeProject(function() {
		console.log("Loading project at " + path);
		var projectFile = path + "/" + projectFileName;
		var json = fileIo.readFile(projectFile);
		if (!json)
			return;
		var projectData = JSON.parse(json);
		if (projectData.deploymentDir)
			projectModel.deploymentDir = projectData.deploymentDir
		if (projectData.packageHash)
			deploymentDialog.packageStep.packageHash =  projectData.packageHash
		if (projectData.packageBase64)
			deploymentDialog.packageStep.packageBase64 =  projectData.packageBase64
		if (projectData.applicationUrlEth)
			projectModel.applicationUrlEth = projectData.applicationUrlEth
		if (projectData.applicationUrlHttp)
			projectModel.applicationUrlHttp = projectData.applicationUrlHttp
		if (projectData.lastPackageDate)
			deploymentDialog.packageStep.lastDeployDate = projectData.lastPackageDate
		if (projectData.deployBlockNumber)
			projectModel.deployBlockNumber = projectData.deployBlockNumber
		if (projectData.localPackageUrl)
			deploymentDialog.packageStep.localPackageUrl =  projectData.localPackageUrl
		if (projectData.deploymentTrHashes)
			projectModel.deploymentTrHashes = JSON.parse(projectData.deploymentTrHashes)
		if (projectData.registerUrlTrHash)
			projectModel.registerUrlTrHash = projectData.registerUrlTrHash
		if (projectData.registerContentHashTrHash)
			projectModel.registerContentHashTrHash = projectData.registerContentHashTrHash
		if (projectData.registerContentHashBlockNumber)
			projectModel.registerContentHashBlockNumber = projectData.registerContentHashBlockNumber
		if (projectData.registerUrlBlockNumber)
			projectModel.registerUrlBlockNumber = projectData.registerUrlBlockNumber
		if (projectData.startUrl)
			projectModel.startUrl = projectData.startUrl
		if (!projectData.title) {
			var parts = path.split("/");
			projectData.title = parts[parts.length - 2];
		}
		deploymentAddresses = projectData.deploymentAddresses ? projectData.deploymentAddresses : {};
		projectTitle = projectData.title;
		if (path.lastIndexOf("/") === path.length - 1)
			path = path.substring(0, path.length - 1)
		projectPath = path;

		// all files/folders from the root path are included in Mix.
		if (!projectData.files)
			projectData.files = [];

		if (mainApplication.trackLastProject)
			projectSettings.lastProjectPath = path;

		projectLoading(projectData);
		//TODO: move this to codemodel
		var contractSources = {};
		for (var d = 0; d < listModel.count; d++) {
			var doc = listModel.get(d);
			if (doc.isContract)
				projectModel.openDocument(doc.documentId)
		}
		projectLoaded()
	});
}

function file(docData)
{
	var fileName = docData.fileName
	var extension = fileName.substring(fileName.lastIndexOf("."), fileName.length);
	var path = docData.path
	var isContract = extension === ".sol";
	var isHtml = extension === ".html";
	var isCss = extension === ".css";
	var isJs = extension === ".js";
	var isImg = extension === ".png"  || extension === ".gif" || extension === ".jpg" || extension === ".svg";
	var syntaxMode = isContract ? "solidity" : isJs ? "javascript" : isHtml ? "htmlmixed" : isCss ? "css" : "";
	var groupName = isContract ? qsTr("Contracts") : isJs ? qsTr("Javascript") : isHtml ? qsTr("Web Pages") : isCss ? qsTr("Styles") : isImg ? qsTr("Images") : qsTr("Misc");
	var docData = {
		contract: false,
		path: path,
		fileName: fileName,
		name: fileName,
		documentId: path,
		syntaxMode: syntaxMode,
		isText: isContract || isHtml || isCss || isJs,
		isContract: isContract,
		isHtml: isHtml,
		groupName: groupName
	};
	return docData
}

function doCloseProject() {
	console.log("Closing project");
	projectListModel.clear();
	projectPath = "";
	currentDocument = null
	projectClosed();
}

function doCreateProject(title, path) {
	closeProject(function() {
		console.log("Creating project " + title + " at " + path);
		var dirPath = path + "/" + title
		fileIo.makeDir(dirPath);
		var projectFile = dirPath + projectFileName;

		var indexFile = "index.html";
		var contractsFile = "contract.sol";
		var projectData = {
			title: title,
			files: [ contractsFile, indexFile ]
		};
		//TODO: copy from template
		if (!fileIo.fileExists(dirPath + "/" + indexFile))
			fileIo.writeFile(dirPath + "/" + indexFile, htmlTemplate);
		if (!fileIo.fileExists(dirPath + "/" + contractsFile))
			fileIo.writeFile(dirPath + "/" + contractsFile, contractTemplate);

		newProject(projectData);
		var json = JSON.stringify(projectData, null, "\t");
		fileIo.writeFile(projectFile, json);
		loadProject(dirPath);
	});
}

function newHtmlFile() {
	createAndAddFile("page", "html", htmlTemplate);
}

function newCssFile() {
	createAndAddFile("style", "css", "body {\n}\n");
}

function newJsFile() {
	createAndAddFile("script", "js", "function foo() {\n}\n");
}

function newContract() {
	var ctrName = "contract" + Object.keys(codeModel.contracts).length
	var ctr = basicContractTemplate.replace("FirstContract", ctrName)
	createAndAddFile("contract", "sol", ctr, ctrName + ".sol");
}

function createAndAddFile(name, extension, content, fileName) {
	fileName = generateFileName(name, extension);
	var filePath = currentFolder + "/" + fileName;
	if (!fileIo.fileExists(filePath))
		fileIo.writeFile(filePath, content);
	saveProjectFile();
	documentAdded(filePath);
}

function generateFileName(name, extension) {
	var i = 1;
	do {
		var fileName = name + i + "." + extension;
		var filePath = currentFolder + "/" + fileName;
		i++;
	} while (fileIo.fileExists(filePath));
	return fileName
}

<|endoftext|>


<commit_before>/*!
* ..Strip.js, uly may2012..
*
* organized like jQuery v1.7.2
*
* most of the Strip methods are intended to work with the "cascading-jsp-style".
*
*/
(function( window, undefined ){

var debug = function( msg ) {
  try {
    console.log( "DEBUG::"+msg );
  }
  catch ( e ) {
    //..
  }
};

var Strip = (function() {
  debug("Strip..");

// "Local" copy of Strip.
var Strip = function() {
    debug("Strip local init..");
    return new Strip.fn.init();
  },
  Sequence = function() {},
  Shot =     function() {},
  Scene =    function() {},
  Text =     function() {},
  Dialogue = function() {};

/*
*   public methods
*/
Strip.fn = Strip.prototype = {

    constructor: Strip,

    init: function() {
      return this;
    },

    // (Strip.Sequence) the particular sequence we are representing now.
    sequence: null,

    //
    //  load a sequence/chapter onto our stage.
    //
    loadSequence: function( sequence ) {
      debug( "strip.loadSequence, sequence:"+sequence );
      this.sequence = sequence;
      return this;
    },

    // the html5 canvas we will draw on.
    canvas: null,

    ctx: null,

    // public setter for our Strip's canvas.
    setCanvas: function( canvas ) {
      debug("canvas:"+canvas);
      this.canvas = canvas;
      this.ctx = canvas.getContext('2d');
      debug("strip.setCanvas, ctx:"+this.ctx);
      return this;
    },

    // synonymous with "start".
    action: function() {
      debug("strip.action");
      if ( !this.sequence ) {
        debug( "sequence is null!" );
      }
      this.sequence.setContext(this.ctx).action();
      return this;
    },

    // synonimous with "stop".
    cut: function() {
      this.sequence.cut();
      return this;
    },

    // go to the next scene.
    next: function() {
      var scene = sequence.scenes[ sequence.selected_scene_index + 1 ];
      scene = scene || sequence.scenes[0];
      scene && this.sequence.loadScene( scene ).setContext( this.ctx ).action();
      return this;
    },

    // go to the previous scene.
    previous: function() {
      var scene = sequence.scenes[ sequence.selected_scene_index - 1 ];
      scene = scene || sequence.scenes[0];
      scene && this.sequence.loadScene( scene ).setContext( this.ctx ).action();
      return this;
    },

    newSequence: function() {
      debug("Strip.newSequence");
      return new Sequence.fn.init();
    },

    newShot: function() {
      debug("Strip.newShot");
      return new Shot.fn.init();
    },

    newScene: function() {
      debug("Strip.newScene()");
      return new Scene.fn.init();
    },

    newDialogue: function() {
      debug("Strip.newDialogue()");
      return new Dialogue.fn.init();
    },

    newText: function(msg) {
      debug("strip.newText");
      return ( new Text.fn.init() ).setMessage(msg);
    }

  };

//---------------------------------------------------------------------------
/*
*   the Sequence "class".
*   represents an ordered collection of scenes to be drawn by the strip.
*/
Sequence.fn = Sequence.prototype = {

  constructor: Sequence,

  init: function() {
    return this;
  },

  selected_scene_index: 0,

  canvas: null,

  // the drawing context.
  ctx: null,

  current_scene_index: -1,

  scenes: [],

  action: function() {
    debug("sequence, action");
    if ( this.current_scene_index < 0 ) {
      this.current_scene_index = 0;
    }
    this.load_current_scene();
    return this;
  },

  //
  //  load the currently selected scene by index.
  //
  load_current_scene: function() {
    debug("load_current_scene");
    var scene,
      idx = this.current_scene_index,
      ctx = this.ctx;

    debug( "idx:"+idx );
    scene = this.scenes[ idx ];

    debug( "scene:"+scene );
    debug( "ctx:"+ctx );

    scene.setup( ctx );

    return this;
  },

  // load/setup a scene.
  loadScene: function( scene ) {
    var i = 0,
      len = this.scenes.length,
      scenes = this.scenes,
      selected_scene_index = -1;

    for ( ;i < len; i++ ) {
      if ( scene === scenes[i] ) {  // TODO does this work?
        selected_scene_index = i;
      }
    }

    scene.setup( ctx );

    return this;
  },

  // add a scene to the sequence stack.
  pushScene: function( scene ) {
    this.scenes = this.scenes || [];
    this.scenes.push( scene );
    return this;
  },

  clearScenes: function() {
    this.scenes = [];
    return this;
  },

  setContext: function( ctx ) {
    debug( "sequence.setContext, ctx:"+ctx );
    this.ctx = ctx;
    return this;
  }
};
//---------------------------------------------------------------------------
/*
* A Scene represents a visual, and possibly some text;
* parent to Shot, and Dialogue.
* 1+ Scenes make up a Sequence.
*/
Scene.fn = Scene.prototype = {
  constructor: Scene,
  init: function() {
    return this;
  },

  setShot: function( shot ) {
    this.shot = shot;
    return this;
  },

// TODO, this would be a nice wrapper...
//addWords: function( s ) {
//  dialogue = dialogue || Strip.newDialogue();
//  dialogue.addText( Text..newText( s ) ); //TODO:this will fail
//  return this;
//},

  setup: function( ctx ) {
    debug( "scene.setup" );
    debug( "scene.setup, ctx:"+ctx );
    this.shot.draw( ctx );
    this.dialogue.draw( ctx );
    return this;
  },

  /* the shot used in this scene. */
  shot: null,
  dialogue: null,

  setDialogue: function( dialogue ) {
    this.dialogue = dialogue;
    return this;
  }
};
//---------------------------------------------------------------------------
Shot.fn = Shot.prototype = {
  constructor: Shot,
  init: function() {
    return this;
  },
  draw: function( context ) {
    if ( !this.image ) {
      debug( "image is missing!!!" ); // TODO:blank out?
    }
    window.image2 = image;
    window.context2 = context;
    context.drawImage( this.image, 0, 0 );  // TODO
//  context.strokeStyle = "#000000";
//  context.fillStyle = "#FFFF00";
//  context.beginPath();
//  context.arc(100,100,50,0,Math.PI*2,true);
//  context.closePath();
//  context.stroke();
//  context.fill();

    return this;
  },
  setImage: function( image ) {
    this.image = image;
    return this;
  }
};
//---------------------------------------------------------------------------
/*
* Dialogue represents an ordered grouping of Texts.
* ie. 2 people talking can be represented by alternating blue vs red Text.
*/
Dialogue.fn = Dialogue.prototype = {
  constructor: Dialogue,
  init: function() {
    return this;
  },

  texts: [],

  /* the currently selected text index. */
  selected_index: 0,

  /* draw the dialogue's words/text onto the stage. */
  //
  //  TODO:how do we know where to put the text relative to the image?
  //
  draw: function( context, width, height ) {
    debug("dialogue.draw");
    var text = this.texts[this.selected_index],
      words,
      prev_x = ~~(width*0.5),
      prev_y = 16,
      i = 0,
      get_fill_style,
      get_x,
      get_y;

    words = text.words;

    // TODO:allow different word-bubble strategies...
    get_x = function() {
      return prev_x += 16;  // TODO:alternative left and right.
    }

    get_y = function() {
      return prev_y += 32;  // TODO:needs to be lower on the canvas!
    }

    get_fill_style = function() {
      switch ( i ) {
        case 0:
          colour = 'aqua';
          break;
        case 1:
          colour = 'red';
          break;
        case 2:
          colour = 'green';
          break;
        case 3:
          colour = 'blue';
          break;
        default:
          colour = 'fuchsia';
          break;
      }

      i++;
      if ( i > 3 ) {
        i = 0;
      }
      return colour;
    }

    // TODO:text color alternation...
    // TODO:probably need to loop through and
    // re-draw all the words from previous texts.
    context.fillStyle = get_fill_style(); // TODO:set larger font size
    context.fillText( words, get_x(), get_y() );
    return this;
  },

  /*
  * add a text object to our list of texts.
  * @param text (Text).
  */
  pushText: function( text ) {
    debug("pushText, text:"+text);
    var texts = this.texts || [];
    texts.push( text );
    this.texts = texts;
    return this;
  }
};
//---------------------------------------------------------------------------
/*
* Text represents a message we want to show/deliver to the audience.
*/
Text.fn = Text.prototype = {
  constructor: Text,
  init: function() {
    return this;
  },
  setMessage: function(s) {
    this.message = s;
    return this;
  }

};
//---------------------------------------------------------------------------

  //
  //  setup our namespaced-classes
  //  note:order matters here...
  //
  Shot    .fn.init.prototype = Shot.fn;
  Sequence.fn.init.prototype = Sequence.fn;
  Scene   .fn.init.prototype = Scene.fn;
  Dialogue.fn.init.prototype = Dialogue.fn;
  Strip   .fn.init.prototype = Strip.fn;
  Text    .fn.init.prototype = Text.fn;

  return Strip;
})();
//---------------------------------------------------------------------------
window.Strip = Strip;
})(window);
<commit_msg>fixed a typo, the text now shows up instead of "undefined".<commit_after>/*!
* ..Strip.js, uly may2012..
*
* organized like jQuery v1.7.2
*
* most of the Strip methods are intended to work with the "cascading-jsp-style".
*
*/
(function( window, undefined ){

var debug = function( msg ) {
  try {
    console.log( "DEBUG::"+msg );
  }
  catch ( e ) {
    //..
  }
};

var Strip = (function() {
  debug("Strip..");

// "Local" copy of Strip.
var Strip = function() {
    debug("Strip local init..");
    return new Strip.fn.init();
  },
  Sequence = function() {},
  Shot =     function() {},
  Scene =    function() {},
  Text =     function() {},
  Dialogue = function() {};

/*
*   public methods
*/
Strip.fn = Strip.prototype = {

    constructor: Strip,

    init: function() {
      return this;
    },

    // (Strip.Sequence) the particular sequence we are representing now.
    sequence: null,

    //
    //  load a sequence/chapter onto our stage.
    //
    loadSequence: function( sequence ) {
      debug( "strip.loadSequence, sequence:"+sequence );
      this.sequence = sequence;
      return this;
    },

    // the html5 canvas we will draw on.
    canvas: null,

    ctx: null,

    // public setter for our Strip's canvas.
    setCanvas: function( canvas ) {
      debug("canvas:"+canvas);
      this.canvas = canvas;
      this.ctx = canvas.getContext('2d');
      debug("strip.setCanvas, ctx:"+this.ctx);
      return this;
    },

    // synonymous with "start".
    action: function() {
      debug("strip.action");
      if ( !this.sequence ) {
        debug( "sequence is null!" );
      }
      this.sequence.setContext(this.ctx).action();
      return this;
    },

    // synonimous with "stop".
    cut: function() {
      this.sequence.cut();
      return this;
    },

    // go to the next scene.
    next: function() {
      var scene = sequence.scenes[ sequence.selected_scene_index + 1 ];
      scene = scene || sequence.scenes[0];
      scene && this.sequence.loadScene( scene ).setContext( this.ctx ).action();
      return this;
    },

    // go to the previous scene.
    previous: function() {
      var scene = sequence.scenes[ sequence.selected_scene_index - 1 ];
      scene = scene || sequence.scenes[0];
      scene && this.sequence.loadScene( scene ).setContext( this.ctx ).action();
      return this;
    },

    newSequence: function() {
      debug("Strip.newSequence");
      return new Sequence.fn.init();
    },

    newShot: function() {
      debug("Strip.newShot");
      return new Shot.fn.init();
    },

    newScene: function() {
      debug("Strip.newScene()");
      return new Scene.fn.init();
    },

    newDialogue: function() {
      debug("Strip.newDialogue()");
      return new Dialogue.fn.init();
    },

    newText: function(msg) {
      debug("strip.newText");
      return ( new Text.fn.init() ).setMessage(msg);
    }

  };

//---------------------------------------------------------------------------
/*
*   the Sequence "class".
*   represents an ordered collection of scenes to be drawn by the strip.
*/
Sequence.fn = Sequence.prototype = {

  constructor: Sequence,

  init: function() {
    return this;
  },

  selected_scene_index: 0,

  canvas: null,

  // the drawing context.
  ctx: null,

  current_scene_index: -1,

  scenes: [],

  action: function() {
    debug("sequence, action");
    if ( this.current_scene_index < 0 ) {
      this.current_scene_index = 0;
    }
    this.load_current_scene();
    return this;
  },

  //
  //  load the currently selected scene by index.
  //
  load_current_scene: function() {
    debug("load_current_scene");
    var scene,
      idx = this.current_scene_index,
      ctx = this.ctx;

    debug( "idx:"+idx );
    scene = this.scenes[ idx ];

    debug( "scene:"+scene );
    debug( "ctx:"+ctx );

    scene.setup( ctx );

    return this;
  },

  // load/setup a scene.
  loadScene: function( scene ) {
    var i = 0,
      len = this.scenes.length,
      scenes = this.scenes,
      selected_scene_index = -1;

    for ( ;i < len; i++ ) {
      if ( scene === scenes[i] ) {  // TODO does this work?
        selected_scene_index = i;
      }
    }

    scene.setup( ctx );

    return this;
  },

  // add a scene to the sequence stack.
  pushScene: function( scene ) {
    this.scenes = this.scenes || [];
    this.scenes.push( scene );
    return this;
  },

  clearScenes: function() {
    this.scenes = [];
    return this;
  },

  setContext: function( ctx ) {
    debug( "sequence.setContext, ctx:"+ctx );
    this.ctx = ctx;
    return this;
  }
};
//---------------------------------------------------------------------------
/*
* A Scene represents a visual, and possibly some text;
* parent to Shot, and Dialogue.
* 1+ Scenes make up a Sequence.
*/
Scene.fn = Scene.prototype = {
  constructor: Scene,
  init: function() {
    return this;
  },

  setShot: function( shot ) {
    this.shot = shot;
    return this;
  },

// TODO, this would be a nice wrapper...
//addWords: function( s ) {
//  dialogue = dialogue || Strip.newDialogue();
//  dialogue.addText( Text..newText( s ) ); //TODO:this will fail
//  return this;
//},

  setup: function( ctx ) {
    debug( "scene.setup" );
    debug( "scene.setup, ctx:"+ctx );
    this.shot.draw( ctx );
    this.dialogue.draw( ctx );
    return this;
  },

  /* the shot used in this scene. */
  shot: null,
  dialogue: null,

  setDialogue: function( dialogue ) {
    this.dialogue = dialogue;
    return this;
  }
};
//---------------------------------------------------------------------------
Shot.fn = Shot.prototype = {
  constructor: Shot,
  init: function() {
    return this;
  },
  draw: function( context ) {
    if ( !this.image ) {
      debug( "image is missing!!!" ); // TODO:blank out?
    }
    window.image2 = image;
    window.context2 = context;
    context.drawImage( this.image, 0, 0 );  // TODO
//  context.strokeStyle = "#000000";
//  context.fillStyle = "#FFFF00";
//  context.beginPath();
//  context.arc(100,100,50,0,Math.PI*2,true);
//  context.closePath();
//  context.stroke();
//  context.fill();

    return this;
  },
  setImage: function( image ) {
    this.image = image;
    return this;
  }
};
//---------------------------------------------------------------------------
/*
* Dialogue represents an ordered grouping of Texts.
* ie. 2 people talking can be represented by alternating blue vs red Text.
*/
Dialogue.fn = Dialogue.prototype = {
  constructor: Dialogue,
  init: function() {
    return this;
  },

  texts: [],

  /* the currently selected text index. */
  selected_index: 0,

  /* draw the dialogue's words/text onto the stage. */
  //
  //  TODO:how do we know where to put the text relative to the image?
  //
  draw: function( context, width, height ) {
    debug("dialogue.draw");
    var text = this.texts[this.selected_index],
      words,
      prev_x = ~~(width*0.5),
      prev_y = 16,
      i = 0,
      get_fill_style,
      get_x,
      get_y;

    words = text.message;

    // TODO:allow different word-bubble strategies...
    get_x = function() {
      return prev_x += 16;  // TODO:alternative left and right.
    }

    get_y = function() {
      return prev_y += 32;  // TODO:needs to be lower on the canvas!
    }

    get_fill_style = function() {
      switch ( i ) {
        case 0:
          colour = 'aqua';
          break;
        case 1:
          colour = 'red';
          break;
        case 2:
          colour = 'green';
          break;
        case 3:
          colour = 'blue';
          break;
        default:
          colour = 'fuchsia';
          break;
      }

      i++;
      if ( i > 3 ) {
        i = 0;
      }
      return colour;
    }

    // TODO:text color alternation...
    // TODO:probably need to loop through and
    // re-draw all the words from previous texts.
    context.fillStyle = get_fill_style(); // TODO:set larger font size
    context.fillText( words, get_x(), get_y() );
    return this;
  },

  /*
  * add a text object to our list of texts.
  * @param text (Text).
  */
  pushText: function( text ) {
    debug("pushText, text:"+text);
    var texts = this.texts || [];
    texts.push( text );
    this.texts = texts;
    return this;
  }
};
//---------------------------------------------------------------------------
/*
* Text represents a message we want to show/deliver to the audience.
*/
Text.fn = Text.prototype = {
  constructor: Text,
  init: function() {
    return this;
  },
  setMessage: function(s) {
    this.message = s;
    return this;
  }

};
//---------------------------------------------------------------------------

  //
  //  setup our namespaced-classes
  //  note:order matters here...
  //
  Shot    .fn.init.prototype = Shot.fn;
  Sequence.fn.init.prototype = Sequence.fn;
  Scene   .fn.init.prototype = Scene.fn;
  Dialogue.fn.init.prototype = Dialogue.fn;
  Strip   .fn.init.prototype = Strip.fn;
  Text    .fn.init.prototype = Text.fn;

  return Strip;
})();
//---------------------------------------------------------------------------
window.Strip = Strip;
})(window);
<|endoftext|>


<commit_before>(function() {
    'use strict';
    angular.module('ownblock', [
        'ngResource',
        'ngSanitize',
        'ngCookies',
        'ui.router',
        'ui.calendar',
        'ui.bootstrap',
        'ownblock.controllers',
        'ownblock.services',
        'ownblock.directives'
    ]).
    constant({
        urls: {
            static: '/static/',
            partials: '/static/partials/',
            components: '/static/bower_components/'
        }
    }).
    config(['$httpProvider',
        '$resourceProvider',
        '$stateProvider',
        '$urlRouterProvider',
        'urls',
        function(
            $httpProvider,
            $resourceProvider,
            $stateProvider,
            $urlRouterProvider,
            urls) {

            $resourceProvider.defaults.stripTrailingSlashes = true;

            $httpProvider.defaults.xsrfCookieName = 'csrftoken';
            $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';

            $httpProvider.interceptors.push(function($q, $location, notifier) {
                return {
                    'responseError': function(response) {
                        console.log(response);
                        var warning = "Sorry, an error has occurred",
                            result = $q.reject(response);
                        switch (response.status) {
                            case 401:
                            case 403:
                                // we're out of sync with server, logout
                                $location.path("accessdenied");
                                return result;
                            case 404:
                                $location.path("notfound");
                                return result;
                            case 400:
                                warning = "Sorry, your form appears to have some errors";
                                break;
                            case 413:
                                warning = "Sorry, your upload was too large";
                                break;
                        }
                        if (warning) {
                            notifier.warning(warning);
                        }
                        return $q.reject(response);
                    }
                };
            });

            // handle file uploads
            $httpProvider.defaults.transformRequest = function(data, headersGetter) {

                if (data === undefined) {
                    return data;
                }

                var fd = new FormData(),
                    isFileUpload = false,
                    headers = headersGetter();

                angular.forEach(data, function(value, key) {
                    if (value instanceof FileList) {
                        isFileUpload = true;
                        if (value.length === 1) {
                            fd.append(key, value[0]);
                        } else {
                            angular.forEach(value, function(file, index) {
                                fd.append(key + "_" + index, file);
                            });
                        }
                    } else {
                        fd.append(key, value);
                    }
                });
                if (isFileUpload) {
                    headers["Content-Type"] = undefined;
                    return fd;
                }

                return JSON.stringify(data);
            };

            $stateProvider.
            state('site', {
                'abstract': true,
                templateUrl: urls.partials + 'base.html',
                resolve: {
                    auth: ['auth',
                        function(auth) {
                            return auth;
                        }
                    ]
                }
            }).
            state('accessdenied', {
                url: '/accessdenied',
                templateUrl: urls.partials + 'accessDenied.html',
            }).
            state('notfound', {
                url: '/notfound',
                templateUrl: urls.partials + 'notfound.html',
            }).
            state('account', {
                templateUrl: urls.partials + 'account/base.html',
                parent: 'site'
            }).
            state('account.edit', {
                url: '/account',
                templateUrl: urls.partials + 'account/edit.html',
                controller: 'account.EditCtrl'
            }).
            state('account.password', {
                url: '/account/pass',
                templateUrl: urls.partials + 'account/passwordForm.html',
                controller: 'account.ChangePasswordCtrl'
            }).
            state('residents', {
                templateUrl: urls.partials + 'residents/base.html',
                parent: 'site'
            }).
            state('residents.list', {
                url: '/residents',
                templateUrl: urls.partials + 'residents/list.html',
                controller: 'residents.ListCtrl'
            }).
            state('residents.new', {
                url: '/residents/new',
                templateUrl: urls.partials + 'residents/form.html',
                controller: 'residents.NewCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('residents.edit', {
                url: '/residents/:id/edit',
                templateUrl: urls.partials + 'residents/form.html',
                controller: 'residents.EditCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('residents.detail', {
                url: '/residents/:id',
                templateUrl: urls.partials + 'residents/detail.html',
                controller: 'residents.DetailCtrl'
            }).
            state('messages', {
                templateUrl: urls.partials + 'messages/base.html',
                parent: 'site'
            }).
            state('messages.list', {
                url: '/messages',
                templateUrl: urls.partials + 'messages/list.html',
                controller: 'messages.ListCtrl',
            }).
            state('messages.detail', {
                url: '/messages/:id',
                templateUrl: urls.partials + 'messages/detail.html',
                controller: 'messages.DetailCtrl',
            }).
            state('messages.send', {
                url: '/messages/send/:recipient',
                templateUrl: urls.partials + 'messages/form.html',
                controller: 'messages.SendCtrl'
            }).
            state('messages.reply', {
                url: '/messages/reply/:parent',
                templateUrl: urls.partials + 'messages/form.html',
                controller: 'messages.ReplyCtrl'
            }).
            state('notices', {
                templateUrl: urls.partials + 'notices/base.html',
                parent: 'site'
            }).
            state('notices.list', {
                url: '/notices',
                templateUrl: urls.partials + 'notices/list.html',
                controller: 'notices.ListCtrl'
            }).
            state('notices.new', {
                url: '/notices/new',
                templateUrl: urls.partials + 'notices/form.html',
                controller: 'notices.NewCtrl'
            }).
            state('notices.detail', {
                url: '/notices/:id',
                templateUrl: urls.partials + 'notices/detail.html',
                controller: 'notices.DetailCtrl'
            }).
            state('notices.edit', {
                url: '/notices/:id/edit',
                templateUrl: urls.partials + 'notices/form.html',
                controller: 'notices.EditCtrl'
            }).
            state('amenities', {
                templateUrl: urls.partials + 'amenities/base.html',
                parent: 'site'
            }).
            state('amenities.list', {
                url: '/amenities',
                templateUrl: urls.partials + 'amenities/list.html',
                controller: 'amenities.ListCtrl'
            }).
            state('amenities.newAmenity', {
                url: '/amenities/new',
                templateUrl: urls.partials + 'amenities/amenityForm.html',
                controller: 'amenities.NewAmenityCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('amenities.edit', {
                url: '/amenities/:id/edit',
                templateUrl: urls.partials + 'amenities/amenityForm.html',
                controller: 'amenities.EditAmenityCtrl'
            }).
            state('amenities.detail', {
                url: '/amenities/:id',
                templateUrl: urls.partials + 'amenities/detail.html',
                controller: 'amenities.DetailCtrl'
            }).
            state('amenities.bookingDetail', {
                url: '/amenities/bookings/:id',
                templateUrl: urls.partials + 'amenities/bookingDetail.html',
                controller: 'amenities.BookingDetailCtrl'
            }).
            state('amenities.editBooking', {
                url: '/amenities/bookings/:id/edit',
                templateUrl: urls.partials + 'amenities/bookingForm.html',
                controller: 'amenities.EditBookingCtrl'
            }).
            state('amenities.newBooking', {
                url: '/amenities/:id/bookings/new',
                templateUrl: urls.partials + 'amenities/bookingForm.html',
                controller: 'amenities.NewBookingCtrl',
                data: {
                    access: 'resident'
                }
            }).
            state('complaints', {
                templateUrl: urls.partials + 'complaints/base.html',
                parent: 'site'
            }).
            state('complaints.list', {
                url: '/complaints',
                templateUrl: urls.partials + 'complaints/list.html',
                controller: 'complaints.ListCtrl'
            }).
            state('complaints.new', {
                url: '/complaints/new',
                templateUrl: urls.partials + 'complaints/form.html',
                controller: 'complaints.NewCtrl',
                data: {
                    access: 'resident'
                }
            }).
            state('complaints.detail', {
                url: '/complaints/:id',
                templateUrl: urls.partials + 'complaints/detail.html',
                controller: 'complaints.DetailCtrl'
            }).
            state('tickets', {
                templateUrl: urls.partials + 'tickets/base.html',
                parent: 'site'
            }).
            state('tickets.list', {
                url: '/tickets',
                templateUrl: urls.partials + 'tickets/list.html',
                controller: 'tickets.ListCtrl'
            }).
            state('tickets.new', {
                url: '/tickets/new',
                templateUrl: urls.partials + 'tickets/form.html',
                controller: 'tickets.NewCtrl'
            }).
            state('tickets.detail', {
                url: '/tickets/:id',
                templateUrl: urls.partials + 'tickets/detail.html',
                controller: 'tickets.DetailCtrl'
            }).
            state('tickets.edit', {
                url: '/tickets/:id/edit',
                templateUrl: urls.partials + 'tickets/form.html',
                controller: 'tickets.EditCtrl'
            }).
            state('storage', {
                templateUrl: urls.partials + 'storage/base.html',
                parent: 'site'
            }).
            state('storage.list', {
                url: '/storage',
                templateUrl: urls.partials + 'storage/list.html',
                controller: 'storage.ListCtrl'
            }).
            state('storage.newItem', {
                url: '/storage/items/new',
                templateUrl: urls.partials + 'storage/itemForm.html',
                controller: 'storage.NewItemCtrl',
                data: {
                    access: 'resident'
                }
            }).
            state('storage.newPlace', {
                url: '/storage/places/new',
                templateUrl: urls.partials + 'storage/placeForm.html',
                controller: 'storage.NewPlaceCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('storage.itemDetail', {
                url: '/storage/:id',
                templateUrl: urls.partials + 'storage/itemDetail.html',
                controller: 'storage.ItemDetailCtrl'
            }).
            state('storage.placeDetail', {
                url: '/storage/places/:id',
                templateUrl: urls.partials + 'storage/placeDetail.html',
                controller: 'storage.PlaceDetailCtrl'
            }).
            state('storage.editItem', {
                url: '/storage/:id/edit',
                templateUrl: urls.partials + 'storage/itemForm.html',
                controller: 'storage.EditItemCtrl'
            }).
            state('storage.editPlace', {
                url: '/storage/places/:id/edit',
                templateUrl: urls.partials + 'storage/placeForm.html',
                controller: 'storage.EditPlaceCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('documents', {
                templateUrl: urls.partials + 'documents/base.html',
                parent: 'site'
            }).
            state('documents.list', {
                url: '/docs',
                templateUrl: urls.partials + 'documents/list.html',
                controller: 'documents.ListCtrl'
            }).
            state('documents.upload', {
                url: '/docs/upload',
                templateUrl: urls.partials + 'documents/form.html',
                controller: 'documents.UploadCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('documents.detail', {
                url: '/docs/:id',
                templateUrl: urls.partials + 'documents/detail.html',
                controller: 'documents.DetailCtrl'
            }).
            state('parking', {
                templateUrl: urls.partials + 'parking/base.html',
                parent: 'site'
            }).
            state('parking.list', {
                url: '/parking',
                templateUrl: urls.partials + 'parking/list.html',
                controller: 'parking.ListCtrl'
            }).
            state('parking.new', {
                url: '/parking/new',
                templateUrl: urls.partials + 'parking/vehicleForm.html',
                controller: 'parking.NewCtrl'
            }).
            state('parking.detail', {
                url: '/parking/:id',
                templateUrl: urls.partials + 'parking/detail.html',
                controller: 'parking.DetailCtrl'
            }).
            state('parking.edit', {
                url: '/parking/:id/edit',
                templateUrl: urls.partials + 'parking/vehicleForm.html',
                controller: 'parking.EditCtrl'
            }).
            state('contacts', {
                templateUrl: urls.partials + 'contacts/base.html',
                parent: 'site'
            }).
            state('contacts.list', {
                url: '/contacts',
                templateUrl: urls.partials + 'contacts/list.html',
                controller: 'contacts.ListCtrl'
            }).
            state('contacts.new', {
                url: '/contacts/new',
                templateUrl: urls.partials + 'contacts/form.html',
                controller: 'contacts.NewCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('contacts.detail', {
                url: '/contacts/:id',
                templateUrl: urls.partials + 'contacts/detail.html',
                controller: 'contacts.DetailCtrl'
            }).
            state('contacts.edit', {
                url: '/contacts/:id/edit',
                templateUrl: urls.partials + 'contacts/form.html',
                controller: 'contacts.EditCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('buildings', {
                templateUrl: urls.partials + 'buildings/base.html',
                parent: 'site'
            }).
            state('buildings.list', {
                templateUrl: urls.partials + 'buildings/list.html',
                controller: 'buildings.ListCtrl',
                data: {
                    acess: 'manager'
                }
            }).
            state('buildings.apartment', {
                url: '/building/:id',
                templateUrl: urls.partials + 'buildings/detail.html',
                controller: 'buildings.DetailCtrl'
            }).
            state('buildings.detail', {
                url: '/building',
                templateUrl: urls.partials + 'buildings/detail.html',
                controller: 'buildings.DetailCtrl'
            });

            $urlRouterProvider.otherwise('/building');

        }
    ]).run(function($rootScope, $state, auth) {

        // fetch the current user from the session. If the user is not logged in,
        // redirect to the external login page; otherwise sync user details with the
        // application.
        $rootScope.$on('$stateChangeStart', function(event, toState) {
            if (!auth.authorize(toState)) {
                event.preventDefault();
                $state.transitionTo('accessdenied');
            }

        });

    });
}());
<commit_msg>Add url for buildings<commit_after>(function() {
    'use strict';
    angular.module('ownblock', [
        'ngResource',
        'ngSanitize',
        'ngCookies',
        'ui.router',
        'ui.calendar',
        'ui.bootstrap',
        'ownblock.controllers',
        'ownblock.services',
        'ownblock.directives'
    ]).
    constant({
        urls: {
            static: '/static/',
            partials: '/static/partials/',
            components: '/static/bower_components/'
        }
    }).
    config(['$httpProvider',
        '$resourceProvider',
        '$stateProvider',
        '$urlRouterProvider',
        'urls',
        function(
            $httpProvider,
            $resourceProvider,
            $stateProvider,
            $urlRouterProvider,
            urls) {

            $resourceProvider.defaults.stripTrailingSlashes = true;

            $httpProvider.defaults.xsrfCookieName = 'csrftoken';
            $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';

            $httpProvider.interceptors.push(function($q, $location, notifier) {
                return {
                    'responseError': function(response) {
                        console.log(response);
                        var warning = "Sorry, an error has occurred",
                            result = $q.reject(response);
                        switch (response.status) {
                            case 401:
                            case 403:
                                // we're out of sync with server, logout
                                $location.path("accessdenied");
                                return result;
                            case 404:
                                $location.path("notfound");
                                return result;
                            case 400:
                                warning = "Sorry, your form appears to have some errors";
                                break;
                            case 413:
                                warning = "Sorry, your upload was too large";
                                break;
                        }
                        if (warning) {
                            notifier.warning(warning);
                        }
                        return $q.reject(response);
                    }
                };
            });

            // handle file uploads
            $httpProvider.defaults.transformRequest = function(data, headersGetter) {

                if (data === undefined) {
                    return data;
                }

                var fd = new FormData(),
                    isFileUpload = false,
                    headers = headersGetter();

                angular.forEach(data, function(value, key) {
                    if (value instanceof FileList) {
                        isFileUpload = true;
                        if (value.length === 1) {
                            fd.append(key, value[0]);
                        } else {
                            angular.forEach(value, function(file, index) {
                                fd.append(key + "_" + index, file);
                            });
                        }
                    } else {
                        fd.append(key, value);
                    }
                });
                if (isFileUpload) {
                    headers["Content-Type"] = undefined;
                    return fd;
                }

                return JSON.stringify(data);
            };

            $stateProvider.
            state('site', {
                'abstract': true,
                templateUrl: urls.partials + 'base.html',
                resolve: {
                    auth: ['auth',
                        function(auth) {
                            return auth;
                        }
                    ]
                }
            }).
            state('accessdenied', {
                url: '/accessdenied',
                templateUrl: urls.partials + 'accessDenied.html',
            }).
            state('notfound', {
                url: '/notfound',
                templateUrl: urls.partials + 'notfound.html',
            }).
            state('account', {
                templateUrl: urls.partials + 'account/base.html',
                parent: 'site'
            }).
            state('account.edit', {
                url: '/account',
                templateUrl: urls.partials + 'account/edit.html',
                controller: 'account.EditCtrl'
            }).
            state('account.password', {
                url: '/account/pass',
                templateUrl: urls.partials + 'account/passwordForm.html',
                controller: 'account.ChangePasswordCtrl'
            }).
            state('residents', {
                templateUrl: urls.partials + 'residents/base.html',
                parent: 'site'
            }).
            state('residents.list', {
                url: '/residents',
                templateUrl: urls.partials + 'residents/list.html',
                controller: 'residents.ListCtrl'
            }).
            state('residents.new', {
                url: '/residents/new',
                templateUrl: urls.partials + 'residents/form.html',
                controller: 'residents.NewCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('residents.edit', {
                url: '/residents/:id/edit',
                templateUrl: urls.partials + 'residents/form.html',
                controller: 'residents.EditCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('residents.detail', {
                url: '/residents/:id',
                templateUrl: urls.partials + 'residents/detail.html',
                controller: 'residents.DetailCtrl'
            }).
            state('messages', {
                templateUrl: urls.partials + 'messages/base.html',
                parent: 'site'
            }).
            state('messages.list', {
                url: '/messages',
                templateUrl: urls.partials + 'messages/list.html',
                controller: 'messages.ListCtrl',
            }).
            state('messages.detail', {
                url: '/messages/:id',
                templateUrl: urls.partials + 'messages/detail.html',
                controller: 'messages.DetailCtrl',
            }).
            state('messages.send', {
                url: '/messages/send/:recipient',
                templateUrl: urls.partials + 'messages/form.html',
                controller: 'messages.SendCtrl'
            }).
            state('messages.reply', {
                url: '/messages/reply/:parent',
                templateUrl: urls.partials + 'messages/form.html',
                controller: 'messages.ReplyCtrl'
            }).
            state('notices', {
                templateUrl: urls.partials + 'notices/base.html',
                parent: 'site'
            }).
            state('notices.list', {
                url: '/notices',
                templateUrl: urls.partials + 'notices/list.html',
                controller: 'notices.ListCtrl'
            }).
            state('notices.new', {
                url: '/notices/new',
                templateUrl: urls.partials + 'notices/form.html',
                controller: 'notices.NewCtrl'
            }).
            state('notices.detail', {
                url: '/notices/:id',
                templateUrl: urls.partials + 'notices/detail.html',
                controller: 'notices.DetailCtrl'
            }).
            state('notices.edit', {
                url: '/notices/:id/edit',
                templateUrl: urls.partials + 'notices/form.html',
                controller: 'notices.EditCtrl'
            }).
            state('amenities', {
                templateUrl: urls.partials + 'amenities/base.html',
                parent: 'site'
            }).
            state('amenities.list', {
                url: '/amenities',
                templateUrl: urls.partials + 'amenities/list.html',
                controller: 'amenities.ListCtrl'
            }).
            state('amenities.newAmenity', {
                url: '/amenities/new',
                templateUrl: urls.partials + 'amenities/amenityForm.html',
                controller: 'amenities.NewAmenityCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('amenities.edit', {
                url: '/amenities/:id/edit',
                templateUrl: urls.partials + 'amenities/amenityForm.html',
                controller: 'amenities.EditAmenityCtrl'
            }).
            state('amenities.detail', {
                url: '/amenities/:id',
                templateUrl: urls.partials + 'amenities/detail.html',
                controller: 'amenities.DetailCtrl'
            }).
            state('amenities.bookingDetail', {
                url: '/amenities/bookings/:id',
                templateUrl: urls.partials + 'amenities/bookingDetail.html',
                controller: 'amenities.BookingDetailCtrl'
            }).
            state('amenities.editBooking', {
                url: '/amenities/bookings/:id/edit',
                templateUrl: urls.partials + 'amenities/bookingForm.html',
                controller: 'amenities.EditBookingCtrl'
            }).
            state('amenities.newBooking', {
                url: '/amenities/:id/bookings/new',
                templateUrl: urls.partials + 'amenities/bookingForm.html',
                controller: 'amenities.NewBookingCtrl',
                data: {
                    access: 'resident'
                }
            }).
            state('complaints', {
                templateUrl: urls.partials + 'complaints/base.html',
                parent: 'site'
            }).
            state('complaints.list', {
                url: '/complaints',
                templateUrl: urls.partials + 'complaints/list.html',
                controller: 'complaints.ListCtrl'
            }).
            state('complaints.new', {
                url: '/complaints/new',
                templateUrl: urls.partials + 'complaints/form.html',
                controller: 'complaints.NewCtrl',
                data: {
                    access: 'resident'
                }
            }).
            state('complaints.detail', {
                url: '/complaints/:id',
                templateUrl: urls.partials + 'complaints/detail.html',
                controller: 'complaints.DetailCtrl'
            }).
            state('tickets', {
                templateUrl: urls.partials + 'tickets/base.html',
                parent: 'site'
            }).
            state('tickets.list', {
                url: '/tickets',
                templateUrl: urls.partials + 'tickets/list.html',
                controller: 'tickets.ListCtrl'
            }).
            state('tickets.new', {
                url: '/tickets/new',
                templateUrl: urls.partials + 'tickets/form.html',
                controller: 'tickets.NewCtrl'
            }).
            state('tickets.detail', {
                url: '/tickets/:id',
                templateUrl: urls.partials + 'tickets/detail.html',
                controller: 'tickets.DetailCtrl'
            }).
            state('tickets.edit', {
                url: '/tickets/:id/edit',
                templateUrl: urls.partials + 'tickets/form.html',
                controller: 'tickets.EditCtrl'
            }).
            state('storage', {
                templateUrl: urls.partials + 'storage/base.html',
                parent: 'site'
            }).
            state('storage.list', {
                url: '/storage',
                templateUrl: urls.partials + 'storage/list.html',
                controller: 'storage.ListCtrl'
            }).
            state('storage.newItem', {
                url: '/storage/items/new',
                templateUrl: urls.partials + 'storage/itemForm.html',
                controller: 'storage.NewItemCtrl',
                data: {
                    access: 'resident'
                }
            }).
            state('storage.newPlace', {
                url: '/storage/places/new',
                templateUrl: urls.partials + 'storage/placeForm.html',
                controller: 'storage.NewPlaceCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('storage.itemDetail', {
                url: '/storage/:id',
                templateUrl: urls.partials + 'storage/itemDetail.html',
                controller: 'storage.ItemDetailCtrl'
            }).
            state('storage.placeDetail', {
                url: '/storage/places/:id',
                templateUrl: urls.partials + 'storage/placeDetail.html',
                controller: 'storage.PlaceDetailCtrl'
            }).
            state('storage.editItem', {
                url: '/storage/:id/edit',
                templateUrl: urls.partials + 'storage/itemForm.html',
                controller: 'storage.EditItemCtrl'
            }).
            state('storage.editPlace', {
                url: '/storage/places/:id/edit',
                templateUrl: urls.partials + 'storage/placeForm.html',
                controller: 'storage.EditPlaceCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('documents', {
                templateUrl: urls.partials + 'documents/base.html',
                parent: 'site'
            }).
            state('documents.list', {
                url: '/docs',
                templateUrl: urls.partials + 'documents/list.html',
                controller: 'documents.ListCtrl'
            }).
            state('documents.upload', {
                url: '/docs/upload',
                templateUrl: urls.partials + 'documents/form.html',
                controller: 'documents.UploadCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('documents.detail', {
                url: '/docs/:id',
                templateUrl: urls.partials + 'documents/detail.html',
                controller: 'documents.DetailCtrl'
            }).
            state('parking', {
                templateUrl: urls.partials + 'parking/base.html',
                parent: 'site'
            }).
            state('parking.list', {
                url: '/parking',
                templateUrl: urls.partials + 'parking/list.html',
                controller: 'parking.ListCtrl'
            }).
            state('parking.new', {
                url: '/parking/new',
                templateUrl: urls.partials + 'parking/vehicleForm.html',
                controller: 'parking.NewCtrl'
            }).
            state('parking.detail', {
                url: '/parking/:id',
                templateUrl: urls.partials + 'parking/detail.html',
                controller: 'parking.DetailCtrl'
            }).
            state('parking.edit', {
                url: '/parking/:id/edit',
                templateUrl: urls.partials + 'parking/vehicleForm.html',
                controller: 'parking.EditCtrl'
            }).
            state('contacts', {
                templateUrl: urls.partials + 'contacts/base.html',
                parent: 'site'
            }).
            state('contacts.list', {
                url: '/contacts',
                templateUrl: urls.partials + 'contacts/list.html',
                controller: 'contacts.ListCtrl'
            }).
            state('contacts.new', {
                url: '/contacts/new',
                templateUrl: urls.partials + 'contacts/form.html',
                controller: 'contacts.NewCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('contacts.detail', {
                url: '/contacts/:id',
                templateUrl: urls.partials + 'contacts/detail.html',
                controller: 'contacts.DetailCtrl'
            }).
            state('contacts.edit', {
                url: '/contacts/:id/edit',
                templateUrl: urls.partials + 'contacts/form.html',
                controller: 'contacts.EditCtrl',
                data: {
                    access: 'manager'
                }
            }).
            state('buildings', {
                templateUrl: urls.partials + 'buildings/base.html',
                parent: 'site'
            }).
            state('buildings.list', {
                url: '/building/list',
                templateUrl: urls.partials + 'buildings/list.html',
                controller: 'buildings.ListCtrl',
                data: {
                    acess: 'manager'
                }
            }).
            state('buildings.apartment', {
                url: '/building/:id',
                templateUrl: urls.partials + 'buildings/detail.html',
                controller: 'buildings.DetailCtrl'
            }).
            state('buildings.detail', {
                url: '/building',
                templateUrl: urls.partials + 'buildings/detail.html',
                controller: 'buildings.DetailCtrl'
            });

            $urlRouterProvider.otherwise('/building');

        }
    ]).run(function($rootScope, $state, auth) {

        // fetch the current user from the session. If the user is not logged in,
        // redirect to the external login page; otherwise sync user details with the
        // application.
        $rootScope.$on('$stateChangeStart', function(event, toState) {
            if (!auth.authorize(toState)) {
                event.preventDefault();
                $state.transitionTo('accessdenied');
            }

        });

    });
}());
<|endoftext|>