client/js/paper-renderer.js
author veltr
Tue, 21 Aug 2012 18:49:41 +0200
changeset 25 b5ada3bb8e53
parent 23 70c8af9b44ec
child 26 2fad193bae98
permissions -rw-r--r--
Bugfixes

Rkns.Renderer = {}

Rkns.Renderer.Utils = {
    _EDITOR_ARROW_LENGTH : 20,
    _EDITOR_ARROW_WIDTH : 40,
    _EDITOR_MARGIN : 15,
    _EDITOR_PADDING : 10,
    _EDITOR_GRADIENT : new paper.Gradient(['#f0f0f0', '#d0d0d0']),
    drawEditBox : function(_coords, _path, _width, _height) {
        var _isLeft = (_coords.x < paper.view.center.x ? 1 : -1),
            _left = _coords.x + _isLeft * ( this._EDITOR_MARGIN + this._EDITOR_ARROW_LENGTH ),
            _right = _coords.x + _isLeft * ( this._EDITOR_MARGIN + this._EDITOR_ARROW_LENGTH + _width ),
            _top = _coords.y - _height / 2;
        if (_top < this._EDITOR_MARGIN) {
            _top = Math.min( this._EDITOR_MARGIN, _coords.y - this._EDITOR_ARROW_WIDTH / 2 );
        }
        var _bottom = _top + _height;
        if (_bottom > (paper.view.size.height - this._EDITOR_MARGIN)) {
            _bottom = Math.max( paper.view.size.height - this._EDITOR_MARGIN, _coords.y + this._EDITOR_ARROW_WIDTH / 2 );
            _top = _bottom - _height;
        }
        _path.segments[0].point
            = _path.segments[7].point
            = _coords.add([_isLeft * this._EDITOR_MARGIN, 0]);
        _path.segments[1].point.x
            = _path.segments[2].point.x
            = _path.segments[5].point.x
            = _path.segments[6].point.x
            = _left;
        _path.segments[3].point.x
            = _path.segments[4].point.x
            = _right;
        _path.segments[2].point.y
            = _path.segments[3].point.y
            = _top;
        _path.segments[4].point.y
            = _path.segments[5].point.y
            = _bottom;
        _path.segments[1].point.y = _coords.y - this._EDITOR_ARROW_WIDTH / 2;
        _path.segments[6].point.y = _coords.y + this._EDITOR_ARROW_WIDTH / 2;
        _path.fillColor = new paper.GradientColor(this._EDITOR_GRADIENT, [0,_top], [0, _bottom])
        return {
            left: (this._EDITOR_PADDING + Math.min(_left, _right)),
            top: (this._EDITOR_PADDING + _top)
        }
    },
    sector : function(_repr, _inR, _outR, _startAngle, _endAngle, _padding, _imgsrc) {
        var _startRads = _startAngle * Math.PI / 180,
            _endRads = _endAngle * Math.PI / 180,
            _img = new Image(),
            _span = _endRads - _startRads,
            _k = .0879 * _span,
            _kin = _k * _inR,
            _kout = _k * _outR,
            _startdx = - Math.sin(_startRads),
            _startdy = Math.cos(_startRads),
            _startXIn = Math.cos(_startRads) * _inR + _padding * _startdx,
            _startYIn = Math.sin(_startRads) * _inR + _padding * _startdy,
            _startXOut = Math.cos(_startRads) * _outR + _padding * _startdx,
            _startYOut = Math.sin(_startRads) * _outR + _padding * _startdy,
            _enddx = - Math.sin(_endRads),
            _enddy = Math.cos(_endRads),
            _endXIn = Math.cos(_endRads) * _inR - _padding * _enddx,
            _endYIn = Math.sin(_endRads) * _inR - _padding * _enddy,
            _endXOut = Math.cos(_endRads) * _outR - _padding * _enddx,
            _endYOut = Math.sin(_endRads) * _outR - _padding * _enddy,
            _centerR = (_inR + _outR)/2,
            _centerRads = (_startRads + _endRads) / 2,
            _centerX = Math.cos(_centerRads) * _centerR,
            _centerY = Math.sin(_centerRads) * _centerR,
            _segments = [];
        _segments.push([[_startXIn, _startYIn], [0, 0], [ _kin * _startdx, _kin * _startdy ]]);
        for (var i = 1; i < 4; i++) {
            var _rads = i * _span / 4 + _startRads,
                _dx = - Math.sin(_rads),
                _dy = Math.cos(_rads),
                _x = Math.cos(_rads) * _inR,
                _y = Math.sin(_rads) * _inR;
            _segments.push([[_x, _y], [ - _kin * _dx, - _kin * _dy], [ _kin * _dx, _kin * _dy ]]);
        }
        _segments.push([[_endXIn, _endYIn], [ - _kin * _enddx, - _kin * _enddy ], [0,0]]);
        _segments.push([[_endXOut, _endYOut], [ 0,0 ], [ - _kout * _enddx, - _kout * _enddy ]]);
        for (var i = 3; i > 0; i--) {
            var _rads = i * _span / 4 + _startRads,
                _dx = - Math.sin(_rads),
                _dy = Math.cos(_rads),
                _x = Math.cos(_rads) * _outR,
                _y = Math.sin(_rads) * _outR;
            _segments.push([[_x, _y], [ _kout * _dx, _kout * _dy], [ - _kout * _dx, - _kout * _dy ]]);
        }
        _segments.push([[_startXOut, _startYOut], [ _kout * _startdx, _kout * _startdy ], [0, 0]]);
        var _path = new paper.Path();
        _path.add.apply(_path, _segments);
        _path.fillColor = "#333333";
        _path.opacity = .5;
        _path.closed = true;
        _path.__representation = _repr;
        var _visible = false,
            _restPos = new paper.Point(-200, -200),
            _grp = new paper.Group([_path]),
            _delta = _grp.position,
            _imgdelta = new paper.Point([_centerX, _centerY]),
            _currentPos = new paper.Point(0,0);
        _grp.visible = false;
        _grp.position = _restPos;
        var _res = {
            show: function() {
                _visible = true;
                _grp.position = _currentPos.add(_delta);
                _grp.visible = true;
            },
            moveTo: function(_point) {
                _currentPos = _point;
                if (_visible) {
                    _grp.position = _point.add(_delta);
                }
            },
            hide: function() {
                _visible = false;
                _grp.visible = false;
                _grp.position = _restPos;
            },
            select: function() {
                _path.opacity = .8;
            },
            unselect: function() {
                _path.opacity = .5;
            },
            destroy: function() {
                _grp.remove();
            }
        }
        _img.onload = function() {
            var _w = _img.width,
                _h = _img.height;
            var _raster = new paper.Raster(_img);
            _raster.position = _imgdelta.add(_grp.position).subtract(_delta);
            _grp.addChild(_raster);
        }
        _img.src = _imgsrc;
        return _res
    }
}

Rkns.Renderer._BaseRepresentation = function(_renderer, _model) {
    if (typeof _renderer !== "undefined") {
        this.renderer = _renderer;
        this.project = _renderer.renkan.project;
        this.model = _model;
    }
}

Rkns.Renderer._BaseRepresentation.prototype.select = function() {}

Rkns.Renderer._BaseRepresentation.prototype.unselect = function() {}

Rkns.Renderer._BaseRepresentation.prototype.mouseup = function() {}

Rkns.Renderer._BaseRepresentation.prototype.destroy = function() {}

Rkns.Renderer.Node = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.Node.prototype._init = function() {
    this.renderer.node_layer.activate();
    this.type = "Node";
    this.circle = new paper.Path.Circle([0, 0], Rkns._NODE_RADIUS);
    this.circle.fillColor = '#ffffff';
    this.circle.__representation = this;
    this.title = new paper.PointText([0,0]);
    this.title.characterStyle = {
        fontSize: Rkns._NODE_FONT_SIZE,
        fillColor: 'black'
    };
    this.edit_button = new Rkns.Renderer.NodeEditButton(this.renderer, {});
    this.edit_button.node_representation = this;
    this.remove_button = new Rkns.Renderer.NodeRemoveButton(this.renderer, {});
    this.remove_button.node_representation = this;
    this.link_button = new Rkns.Renderer.NodeLinkButton(this.renderer, {});
    this.link_button.node_representation = this;
    this.title.paragraphStyle.justification = 'center';
    this.title.__representation = this;
}

Rkns.Renderer.Node.prototype.redraw = function() {
    var _model_coords = new paper.Point(this.model.get("position"));
    this.paper_coords = this.renderer.toPaperCoords(_model_coords);
    this.circle.position = this.paper_coords;
    this.title.content = this.model.get("title");
    this.title.position = this.paper_coords.add([0, 2 * Rkns._NODE_RADIUS]);
    this.circle.strokeColor = this.model.get("created_by").get("color");
    this.edit_button.moveTo(this.paper_coords);
    this.remove_button.moveTo(this.paper_coords);
    this.link_button.moveTo(this.paper_coords);
}

Rkns.Renderer.Node.prototype.paperShift = function(_delta) {
    var _coords = this.renderer.toModelCoords(this.paper_coords.add(_delta)),
        _data = {
            position: {
                x: _coords.x,
                y: _coords.y
            }
        };
    this.model.set(_data);
    this.renderer.redraw();
}

Rkns.Renderer.Node.prototype.openEditor = function() {
    this.renderer.removeRepresentationsOfType("editor");
    var _editor = this.renderer.addRepresentation("NodeEditor",null);
    _editor.node_representation = this;
    _editor.redraw();
}

Rkns.Renderer.Node.prototype.select = function() {
    this.circle.strokeWidth = 3;
    this.edit_button.show();
    this.remove_button.show();
    this.link_button.show();
}

Rkns.Renderer.Node.prototype.unselect = function(_newTarget) {
    if (!_newTarget || (_newTarget !== this.edit_button && _newTarget !== this.remove_button && _newTarget !== this.link_button)) {
        this.edit_button.hide();
        this.remove_button.hide();
        this.link_button.hide();
    }
    this.circle.strokeWidth = 1;
}

Rkns.Renderer.Node.prototype.mouseup = function(_event) {
    if (!this.renderer.is_dragging) {
        this.openEditor();
    }
}

Rkns.Renderer.Node.prototype.destroy = function(_event) {
    this.edit_button.destroy();
    this.remove_button.destroy();
    this.circle.remove();
    this.title.remove();
}

/* */

Rkns.Renderer.Edge = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.Edge.prototype._init = function() {
    this.renderer.edge_layer.activate();
    this.type = "Edge";
    this.from_representation = this.renderer.getRepresentationByModel(this.model.get("from"));
    this.to_representation = this.renderer.getRepresentationByModel(this.model.get("to"));
    this.line = new paper.Path();
    this.line.add([0,0],[0,0]);
    this.line.__representation = this;
    this.arrow = new paper.Path();
    this.arrow.add([0,0],[Rkns._ARROW_LENGTH,Rkns._ARROW_WIDTH / 2],[0,Rkns._ARROW_WIDTH]);
    this.arrow.__representation = this;
    this.text = new paper.PointText();
    this.text.characterStyle = {
        fontSize: Rkns._EDGE_FONT_SIZE,
        fillColor: 'black'
    };
    this.text.paragraphStyle.justification = 'center';
    this.text.__representation = this;
    this.text_angle = 0;
    this.arrow_angle = 0;
    this.edit_button = new Rkns.Renderer.EdgeEditButton(this.renderer, {});
    this.edit_button.edge_representation = this;
    this.remove_button = new Rkns.Renderer.EdgeRemoveButton(this.renderer, {});
    this.remove_button.edge_representation = this;
}

Rkns.Renderer.Edge.prototype.redraw = function() {
    var _p0o = this.from_representation.paper_coords,
        _p1o = this.to_representation.paper_coords,
        _v = _p1o.subtract(_p0o),
        _r = _v.length,
        _u = _v.divide(_r),
        _delta = new paper.Point([- _u.y, _u.x]).multiply( 4 ),
        _p0 = _p0o.add(_delta), /* Adding a 4 px difference */
        _p1 = _p1o.add(_delta), /* to differentiate inbound and outbound links */
        _a = _v.angle,
        _color = this.model.get("created_by").get("color");
    this.paper_coords = _p0.add(_p1).divide(2);
    this.line.strokeColor = _color;
    this.line.segments[0].point = _p0;
    this.line.segments[1].point = _p1;
    this.arrow.rotate(_a - this.arrow_angle);
    this.arrow.fillColor = _color;
    this.arrow.position = this.paper_coords.subtract(_u.multiply(4));
    this.arrow_angle = _a;
    if (_a > 90) {
        _a -= 180;
    }
    if (_a < -90) {
        _a += 180;
    }
    this.text.rotate(_a - this.text_angle);
    this.text.content = this.model.get("title");
    this.text.position = this.paper_coords;
    this.text_angle = _a;
    this.edit_button.moveTo(this.paper_coords);
    this.remove_button.moveTo(this.paper_coords);
}

Rkns.Renderer.Edge.prototype.openEditor = function() {
    this.renderer.removeRepresentationsOfType("editor");
    var _editor = this.renderer.addRepresentation("EdgeEditor",null);
    _editor.edge_representation = this;
    _editor.redraw();
}

Rkns.Renderer.Edge.prototype.select = function() {
    this.line.strokeWidth = 3;
    this.edit_button.show();
    this.remove_button.show();
}

Rkns.Renderer.Edge.prototype.unselect = function(_newTarget) {
    if (!_newTarget || (_newTarget !== this.edit_button && _newTarget !== this.remove_button)) {
        this.edit_button.hide();
        this.remove_button.hide();
    }
    this.line.strokeWidth = 1;
}

Rkns.Renderer.Edge.prototype.mouseup = function(_event) {
    if (!this.renderer.is_dragging) {
        this.openEditor();
    }
}

Rkns.Renderer.Edge.prototype.paperShift = function(_delta) {
    this.from_representation.paperShift(_delta);
    this.to_representation.paperShift(_delta);
    this.renderer.redraw();
}

Rkns.Renderer.Edge.prototype.destroy = function() {
    this.line.remove();
    this.arrow.remove();
    this.text.remove();
    this.edit_button.destroy();
    this.remove_button.destroy();
}

/* */

Rkns.Renderer.TempEdge = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.TempEdge.prototype._init = function() {
    this.renderer.edge_layer.activate();
    this.type = "temp-edge";
    
    var _color = this.project.get("users").get(this.renderer.renkan.current_user).get("color");
    this.line = new paper.Path();
    this.line.strokeColor = _color;
    this.line.add([0,0],[0,0]);
    this.line.__representation = this;
    this.arrow = new paper.Path();
    this.arrow.fillColor = _color;
    this.arrow.add([0,0],[Rkns._ARROW_LENGTH,Rkns._ARROW_WIDTH / 2],[0,Rkns._ARROW_WIDTH]);
    this.arrow.__representation = this;
    this.arrow_angle = 0;
}

Rkns.Renderer.TempEdge.prototype.redraw = function() {
    var _p0 = this.from_representation.paper_coords,
        _p1 = this.end_pos,
        _a = _p1.subtract(_p0).angle,
        _c = _p0.add(_p1).divide(2);
    this.line.segments[0].point = _p0;
    this.line.segments[1].point = _p1;
    this.arrow.rotate(_a - this.arrow_angle);
    this.arrow.position = _c;
    this.arrow_angle = _a;
}

Rkns.Renderer.TempEdge.prototype.paperShift = function(_delta) {
    this.end_pos = this.end_pos.add(_delta);
    var _hitResult = paper.project.hitTest(this.end_pos);
    this.renderer.findTarget(_hitResult);
    this.redraw();
}

Rkns.Renderer.TempEdge.prototype.mouseup = function(_event) {
    var _hitResult = paper.project.hitTest(_event.point);
    if (_hitResult && typeof _hitResult.item.__representation !== "undefined") {
        var _target = _hitResult.item.__representation;
        if (_target.type === "Node" && this.from_representation.model !== _target.model) {
            var _data = {
                id: Rkns.Utils.getUID('edge'),
                created_by: this.renderer.renkan.current_user,
                from: this.from_representation.model.get("id"),
                to: _target.model.get("id")
            };
            this.project.addEdge(_data);
        }
    }
    this.renderer.removeRepresentation(this);
}

Rkns.Renderer.TempEdge.prototype.destroy = function() {
    this.arrow.remove();
    this.line.remove();
}

/* */

Rkns.Renderer.NodeEditor = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.NodeEditor.prototype._init = function() {
    this.renderer.overlay_layer.activate();
    this.type = "editor";
    this.editor_block = new paper.Path();
    var _pts = Rkns._(Rkns._.range(8)).map(function() {return [0,0]});
    this.editor_block.add.apply(this.editor_block, _pts);
    this.editor_block.strokeWidth = 2;
    this.editor_block.strokeColor = "#999999";
    this.editor_block.fillColor = "#e0e0e0";
    this.editor_block.opacity = .8;
    this.editor_$ = Rkns.$('<div>')
        .appendTo(this.renderer.editor_$)
        .css({
            position: "absolute",
            opacity: .8
        })
        .hide();
}

Rkns.Renderer.NodeEditor.prototype.template = Rkns._.template(
    '<h2><span class="Rk-CloseX">&times;</span><%=l10n.edit_node%></span></h2>'
    + '<p><label><%=l10n.edit_title%></label><input class="Rk-Edit-Title" type="text" value="<%=node.title%>"/></p>'
    + '<p><label><%=l10n.edit_uri%></label><input class="Rk-Edit-URI" type="text" value="<%=node.uri%>"/></p>'
    + '<p><label><%=l10n.edit_description%></label><textarea class="Rk-Edit-Description"><%=node.description%></textarea></p>'
    + '<p><label><%=l10n.created_by%></label> <span class="Rk-UserColor" style="background:<%=node.created_by_color%>;"></span><%=node.created_by_title%></p>'
);

Rkns.Renderer.NodeEditor.prototype.redraw = function() {
    var _coords = this.node_representation.paper_coords,
        _model = this.node_representation.model,
        _css = Rkns.Renderer.Utils.drawEditBox(_coords, this.editor_block, 250, 300);
    this.editor_$
        .html(this.template({
            node: {
                title: _model.get("title"),
                uri: _model.get("uri"),
                description: _model.get("description"),
                created_by_color: _model.get("created_by").get("color"),
                created_by_title: _model.get("created_by").get("title")
            },
            l10n: this.renderer.renkan.l10n
        }))
        .show()
        .css(_css);
    var _this = this;
    this.editor_$.find(".Rk-CloseX").click(function() {
        _this.renderer.removeRepresentation(_this);
        paper.view.draw();
    });
    this.editor_$.find("input, textarea").bind("keyup change", function() {
        var _data = {
            title: _this.editor_$.find(".Rk-Edit-Title").val(),
            description: _this.editor_$.find(".Rk-Edit-Description").val(),
            uri: _this.editor_$.find(".Rk-Edit-URI").val()
        }
        _model.set(_data);
        paper.view.draw();
    });
    this.editor_$.find(".Rk-Edit-Title")[0].focus();
    paper.view.draw();
}

Rkns.Renderer.NodeEditor.prototype.destroy = function() {
    this.editor_block.remove();
    this.editor_$.detach();
}

/* */

Rkns.Renderer.EdgeEditor = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.EdgeEditor.prototype._init = function() {
    this.renderer.overlay_layer.activate();
    this.type = "editor";
    this.editor_block = new paper.Path();
    var _pts = Rkns._(Rkns._.range(8)).map(function() {return [0,0]});
    this.editor_block.add.apply(this.editor_block, _pts);
    this.editor_block.strokeWidth = 2;
    this.editor_block.strokeColor = "#999999";
    this.editor_block.fillColor = "#e0e0e0";
    this.editor_block.opacity = .8;
    this.editor_$ = Rkns.$('<div>')
        .appendTo(this.renderer.editor_$)
        .css({
            position: "absolute",
            opacity: .8
        })
        .hide();
}

Rkns.Renderer.EdgeEditor.prototype.template = Rkns._.template(
    '<h2><span class="Rk-CloseX">&times;</span><%=l10n.edit_edge%></span></h2>'
    + '<p><label><%=l10n.edit_title%></label><input class="Rk-Edit-Title" type="text" value="<%=edge.title%>"/></p>'
    + '<p><label><%=l10n.edit_uri%></label><input class="Rk-Edit-URI" type="text" value="<%=edge.uri%>"/></p>'
    + '<p><label><%=l10n.edit_from%></label><span class="Rk-UserColor" style="background:<%=edge.from_created_by_color%>;"></span><%=edge.from_title%></p>'
    + '<p><label><%=l10n.edit_to%></label><span class="Rk-UserColor" style="background:<%=edge.to_created_by_color%>;"></span><%=edge.to_title%></p>'
    + '<p><label><%=l10n.created_by%> </label><span class="Rk-UserColor" style="background:<%=edge.created_by_color%>;"></span><%=edge.created_by_title%></p>'
);

Rkns.Renderer.EdgeEditor.prototype.redraw = function() {
    var _coords = this.edge_representation.paper_coords,
        _model = this.edge_representation.model,
        _css = Rkns.Renderer.Utils.drawEditBox(_coords, this.editor_block, 250, 200);
    this.editor_$
        .html(this.template({
            edge: {
                title: _model.get("title"),
                uri: _model.get("uri"),
                description: _model.get("description"),
                from_title: _model.get("from").get("title"),
                to_title: _model.get("to").get("title"),
                from_created_by_color: _model.get("from").get("created_by").get("color"),
                to_created_by_color: _model.get("to").get("created_by").get("color"),
                created_by_color: _model.get("created_by").get("color"),
                created_by_title: _model.get("created_by").get("title")
            },
            l10n: this.renderer.renkan.l10n
        }))
        .show()
        .css(_css);
    var _this = this;
    this.editor_$.find(".Rk-CloseX").click(function() {
        _this.renderer.removeRepresentation(_this);
        paper.view.draw();
    });
    this.editor_$.find("input, textarea").bind("keyup change", function() {
        var _data = {
            title: _this.editor_$.find(".Rk-Edit-Title").val(),
            uri: _this.editor_$.find(".Rk-Edit-URI").val()
        }
        _model.set(_data);
        paper.view.draw();
    });
    paper.view.draw();
}

Rkns.Renderer.EdgeEditor.prototype.destroy = function() {
    this.editor_block.remove();
    this.editor_$.detach();
}

/* */

Rkns.Renderer.NodeEditButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.NodeEditButton.prototype._init = function() {
    this.renderer.node_layer.activate();
    this.type = "Node-edit-button";
    this.sector = Rkns.Renderer.Utils.sector(this, 1 + Rkns._NODE_RADIUS, 3 * Rkns._NODE_RADIUS, - 90, 30, 2, 'img/edit.png');
}

Rkns.Renderer.NodeEditButton.prototype.moveTo = function(_pos) {
    this.sector.moveTo(_pos);
}

Rkns.Renderer.NodeEditButton.prototype.show = function() {
    this.sector.show();
}

Rkns.Renderer.NodeEditButton.prototype.hide = function() {
    this.sector.hide();
}

Rkns.Renderer.NodeEditButton.prototype.select = function() {
    this.sector.select();
}

Rkns.Renderer.NodeEditButton.prototype.unselect = function() {
    this.sector.unselect();
    this.hide();
    this.node_representation.remove_button.hide();
    this.node_representation.link_button.hide();
}

Rkns.Renderer.NodeEditButton.prototype.mouseup = function() {
    if (!this.renderer.is_dragging) {
        this.node_representation.openEditor();
    }
}

Rkns.Renderer.NodeEditButton.prototype.destroy = function() {
    this.sector.destroy();
}

/* */

Rkns.Renderer.NodeRemoveButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.NodeRemoveButton.prototype._init = function() {
    this.renderer.node_layer.activate();
    this.type = "Node-remove-button";
    this.sector = Rkns.Renderer.Utils.sector(this, 1 + Rkns._NODE_RADIUS, 3 * Rkns._NODE_RADIUS, -210, -90, 2, 'img/remove.png');
}

Rkns.Renderer.NodeRemoveButton.prototype.moveTo = function(_pos) {
    this.sector.moveTo(_pos);
}

Rkns.Renderer.NodeRemoveButton.prototype.show = function() {
    this.sector.show();
}

Rkns.Renderer.NodeRemoveButton.prototype.hide = function() {
    this.sector.hide();
}

Rkns.Renderer.NodeRemoveButton.prototype.select = function() {
    this.sector.select();
}

Rkns.Renderer.NodeRemoveButton.prototype.unselect = function() {
    this.sector.unselect();
    this.hide();
    this.node_representation.edit_button.hide();
    this.node_representation.link_button.hide();
}

Rkns.Renderer.NodeRemoveButton.prototype.mouseup = function() {
    if (confirm('Do you really wish to remove node "' + this.node_representation.model.get("title") + '"?')) {
        this.project.removeNode(this.node_representation.model);
    }
}

Rkns.Renderer.NodeRemoveButton.prototype.destroy = function() {
    this.sector.destroy();
}

/* */

Rkns.Renderer.NodeLinkButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.NodeLinkButton.prototype._init = function() {
    this.renderer.node_layer.activate();
    this.type = "Node-link-button";
    this.sector = Rkns.Renderer.Utils.sector(this, 1 + Rkns._NODE_RADIUS , 3 * Rkns._NODE_RADIUS, 30, 150, 2, 'img/link.png');
}

Rkns.Renderer.NodeLinkButton.prototype.moveTo = function(_pos) {
    this.sector.moveTo(_pos);
}

Rkns.Renderer.NodeLinkButton.prototype.show = function() {
    this.sector.show();
}

Rkns.Renderer.NodeLinkButton.prototype.hide = function() {
    this.sector.hide();
}

Rkns.Renderer.NodeLinkButton.prototype.select = function() {
    this.sector.select();
}

Rkns.Renderer.NodeLinkButton.prototype.unselect = function() {
    this.sector.unselect();
    this.hide();
    this.node_representation.edit_button.hide();
    this.node_representation.remove_button.hide();
}

Rkns.Renderer.NodeLinkButton.prototype.destroy = function() {
    this.sector.destroy();
}

/* */

Rkns.Renderer.EdgeEditButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.EdgeEditButton.prototype._init = function() {
    this.renderer.edge_layer.activate();
    this.type = "Edge-edit-button";
    this.sector = Rkns.Renderer.Utils.sector(this, 5 , 2 * Rkns._NODE_RADIUS, - 60, 60, 2, 'img/edit.png');
}

Rkns.Renderer.EdgeEditButton.prototype.moveTo = function(_pos) {
    this.sector.moveTo(_pos);
}

Rkns.Renderer.EdgeEditButton.prototype.show = function() {
    this.sector.show();
}

Rkns.Renderer.EdgeEditButton.prototype.hide = function() {
    this.sector.hide();
}

Rkns.Renderer.EdgeEditButton.prototype.select = function() {
    this.sector.select();
}

Rkns.Renderer.EdgeEditButton.prototype.unselect = function() {
    this.sector.unselect();
    this.hide();
    this.edge_representation.remove_button.hide();
}

Rkns.Renderer.EdgeEditButton.prototype.mouseup = function() {
    if (!this.renderer.is_dragging) {
        this.edge_representation.openEditor();
    }
}

Rkns.Renderer.EdgeEditButton.prototype.destroy = function() {
    this.sector.destroy();
}

/* */

Rkns.Renderer.EdgeRemoveButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.EdgeRemoveButton.prototype._init = function() {
    this.renderer.edge_layer.activate();
    this.type = "Edge-remove-button";
    this.sector = Rkns.Renderer.Utils.sector(this, 5, 2 * Rkns._NODE_RADIUS, - 240, -120, 2, 'img/remove.png');
}
Rkns.Renderer.EdgeRemoveButton.prototype.moveTo = function(_pos) {
    this.sector.moveTo(_pos);
}

Rkns.Renderer.EdgeRemoveButton.prototype.show = function() {
    this.sector.show();
}

Rkns.Renderer.EdgeRemoveButton.prototype.hide = function() {
    this.sector.hide();
}

Rkns.Renderer.EdgeRemoveButton.prototype.select = function() {
    this.sector.select();
}

Rkns.Renderer.EdgeRemoveButton.prototype.unselect = function() {
    this.sector.unselect();
    this.hide();
    this.edge_representation.edit_button.hide();
}

Rkns.Renderer.EdgeRemoveButton.prototype.mouseup = function() {
    if (confirm('Do you really wish to remove edge "' + this.edge_representation.model.get("title") + '"?')) {
        this.project.removeEdge(this.edge_representation.model);
    }
}

Rkns.Renderer.EdgeRemoveButton.prototype.destroy = function() {
    this.sector.destroy();
}

/* */

Rkns.Renderer.Scene = function(_renkan) {
    this.renkan = _renkan;
    this._MARGIN_X = 80;
    this._MARGIN_Y = 50;
    this.$ = Rkns.$(".Rk-Render");
    this.representations = [];
    this.$.html(this.template({
        l10n: _renkan.l10n
    }))
    this.canvas_$ = this.$.find(".Rk-Canvas");
    this.editor_$ = this.$.find(".Rk-Editor");
    paper.setup(this.canvas_$[0]);
    this.scale = 1;
    this.offset = paper.view.center;
    this.totalScroll = 0;
    this.click_target = null;
    this.selected_target = null;
    this.edge_layer = new paper.Layer();
    this.node_layer = new paper.Layer();
    this.overlay_layer = new paper.Layer();
    var _tool = new paper.Tool(),
        _this = this;
    _tool.minDistance = Rkns._MIN_DRAG_DISTANCE;
    _tool.onMouseMove = function(_event) {
        _this.onMouseMove(_event);
    }
    _tool.onMouseDown = function(_event) {
        _this.onMouseDown(_event);
    }
    _tool.onMouseDrag = function(_event) {
        _this.onMouseDrag(_event);
    }
    this.canvas_$.mouseup(function(_event) {
        _this.onMouseUp(_event);
    });
    this.canvas_$.mousewheel(function(_event, _delta) {
        _this.onScroll(_event, _delta);
    });
    this.canvas_$.dblclick(function(_event) {
        _this.onDoubleClick(_event);
    });
    this.canvas_$.mouseenter(function(_event) {
        _this.onMouseEnter(_event);
    });
    this.editor_$.find(".Rk-ZoomOut").click(function() {
        _this.offset = new paper.Point([
            _this.canvas_$.width(),
            _this.canvas_$.height()
        ]).multiply( .5 * ( 1 - Math.SQRT1_2 ) ).add(_this.offset.multiply( Math.SQRT1_2 ));
        _this.scale *= Math.SQRT1_2;
        _this.redraw();
    });
    this.editor_$.find(".Rk-ZoomIn").click(function() {
        _this.offset = new paper.Point([
            _this.canvas_$.width(),
            _this.canvas_$.height()
        ]).multiply( .5 * ( 1 - Math.SQRT2 ) ).add(_this.offset.multiply( Math.SQRT2 ));
        _this.scale *= Math.SQRT2;
        _this.redraw();
    });
    paper.view.onResize = function(_event) {
        _this.offset = _this.offset.add(_event.delta.divide(2));
        _this.redraw();
    }
    
    var _thRedraw = Rkns._.throttle(function() {
        _this.redraw();
    },50);
    
    this.addRepresentations("Node", this.renkan.project.get("nodes"));
    this.addRepresentations("Edge", this.renkan.project.get("edges"));
    
    this.renkan.project.on("add:nodes", function(_node) {
        _this.addRepresentation("Node", _node);
        _thRedraw();
    });
    this.renkan.project.on("add:edges", function(_edge) {
        _this.addRepresentation("Edge", _edge);
        _thRedraw();
    });
    
    this.redraw();
}

Rkns.Renderer.Scene.prototype.template = Rkns._.template(
    '<canvas class="Rk-Canvas" resize></canvas><div class="Rk-Editor">'
    + '<div class="Rk-ZoomButtons"><div class="Rk-ZoomIn" title="<%=l10n.zoom_in%>"></div><div class="Rk-ZoomOut" title="<%=l10n.zoom_out%>"></div></div>'
    + '</div>'
);

Rkns.Renderer.Scene.prototype.autoScale = function() {
    var _xx = this.renkan.project.get("nodes").map(function(_node) { return _node.get("position").x }),
        _yy = this.renkan.project.get("nodes").map(function(_node) { return _node.get("position").y }),
        _minx = Math.min.apply(Math, _xx),
        _miny = Math.min.apply(Math, _yy),
        _maxx = Math.max.apply(Math, _xx),
        _maxy = Math.max.apply(Math, _yy);
    this.scale = Math.min((paper.view.size.width - 2 * this._MARGIN_X) / (_maxx - _minx), (paper.view.size.height - 2 * this._MARGIN_Y) / (_maxy - _miny));
    this.offset = paper.view.center.subtract(new paper.Point([(_maxx + _minx) / 2, (_maxy + _miny) / 2]).multiply(this.scale));
    this.redraw();
}

Rkns.Renderer.Scene.prototype.toPaperCoords = function(_point) {
    return _point.multiply(this.scale).add(this.offset);
}


Rkns.Renderer.Scene.prototype.toModelCoords = function(_point) {
    return _point.subtract(this.offset).divide(this.scale);
}

Rkns.Renderer.Scene.prototype.addRepresentation = function(_type, _model) {
    var _repr = new Rkns.Renderer[_type](this, _model);
    this.representations.push(_repr);
    if (_model) {
        var _this = this;
        _model.on("change", function() {
            _repr.redraw();
        });
        _model.on("remove", function() {
            _this.removeRepresentation(_repr);
            _this.redraw();
        });
    }
    return _repr;
}

Rkns.Renderer.Scene.prototype.addRepresentations = function(_type, _collection) {
    var _this = this;
    _collection.forEach(function(_model) {
        _this.addRepresentation(_type, _model);
    });
}

Rkns.Renderer.Scene.prototype.removeRepresentation = function(_representation) {
    _representation.destroy();
    this.representations = Rkns._(this.representations).reject(
        function(_repr) {
            return _repr == _representation
        }
    );
}

Rkns.Renderer.Scene.prototype.getRepresentationByModel = function(_model) {
    return Rkns._(this.representations).find(function(_repr) {
        return _repr.model === _model;
    });
}

Rkns.Renderer.Scene.prototype.removeRepresentationsOfType = function(_type) {
    var _representations = Rkns._(this.representations).filter(function(_repr) {
            return _repr.type == _type;
        }),
        _this = this;
    Rkns._(_representations).each(function(_repr) {
        _this.removeRepresentation(_repr);
    });
}

Rkns.Renderer.Scene.prototype.redraw = function() {
    Rkns._(this.representations).each(function(_representation) {
        _representation.redraw();
    });
    paper.view.draw();
}

Rkns.Renderer.Scene.prototype.addTempEdge = function(_from, _point) {
    var _tmpEdge = this.addRepresentation("TempEdge",null);
    _tmpEdge.end_pos = _point;
    _tmpEdge.from_representation = _from;
    _tmpEdge.redraw();
    this.click_target = _tmpEdge;
}

Rkns.Renderer.Scene.prototype.findTarget = function(_hitResult) {
    if (_hitResult && typeof _hitResult.item.__representation !== "undefined") {
        var _newTarget = _hitResult.item.__representation;
        if (this.selected_target !== _hitResult.item.__representation) {
            if (this.selected_target) {
                this.selected_target.unselect(_newTarget);
            }
            _newTarget.select(this.selected_target);
            this.selected_target = _newTarget;
        }
    } else {
        if (this.selected_target) {
            this.selected_target.unselect(null);
        }
        this.selected_target = null;
    }
}

Rkns.Renderer.Scene.prototype.onMouseMove = function(_event) {
    var _hitResult = paper.project.hitTest(_event.point);
    if (this.is_dragging) {
        if (this.click_target && typeof this.click_target.paperShift === "function") {
            this.click_target.paperShift(_event.delta);
        } else {
            this.offset = this.offset.add(_event.delta);
            this.redraw();
        }
    } else {
        this.findTarget(_hitResult);
    }
}

Rkns.Renderer.Scene.prototype.onMouseDown = function(_event) {
    this.is_dragging = false;
    var _hitResult = paper.project.hitTest(_event.point);
    if (_hitResult && typeof _hitResult.item.__representation !== "undefined") {
        this.click_target = _hitResult.item.__representation;
        if (this.click_target.type === "Node" && _hitResult.type === "stroke") {
            this.addTempEdge(this.click_target, _event.point);
        }
        if (this.click_target.type === "Node-link-button") {
            this.addTempEdge(this.click_target.node_representation, _event.point);
        }
    } else {
        this.click_target = null;
    }
}

Rkns.Renderer.Scene.prototype.onMouseDrag = function(_event) {
    this.is_dragging = true;
    this.onMouseMove(_event);
}

Rkns.Renderer.Scene.prototype.onMouseUp = function(_event) {
    if (this.click_target) {
        var _off = this.canvas_$.offset();
        this.click_target.mouseup(
            {
                point: new paper.Point([
                    _event.pageX - _off.left,
                    _event.pageY - _off.top
                ])
            }
        );
    }
    this.is_dragging = false;
    this.click_target = null;
}

Rkns.Renderer.Scene.prototype.onScroll = function(_event, _scrolldelta) {
    this.totalScroll += _scrolldelta;
    if (Math.abs(this.totalScroll) >= 1) {
        var _off = this.canvas_$.offset(),
            _delta = new paper.Point([
                _event.pageX - _off.left,
                _event.pageY - _off.top
            ]).subtract(this.offset).multiply( Math.SQRT2 - 1 );
        if (this.totalScroll > 0) {
            this.offset = this.offset.subtract(_delta);
            this.scale *= Math.SQRT2;
        } else {
            this.offset = this.offset.add(_delta.divide( Math.SQRT2 ));
            this.scale *= Math.SQRT1_2;
        }
        this.totalScroll = 0;
        this.redraw();
    }
}

Rkns.Renderer.Scene.prototype.onDoubleClick = function(_event) {
    var _off = this.canvas_$.offset(),
        _point = new paper.Point([
            _event.pageX - _off.left,
            _event.pageY - _off.top
        ]);
    var _hitResult = paper.project.hitTest(_point);
    if (!_hitResult || typeof _hitResult.item.__representation === "undefined") {
        var _coords = this.toModelCoords(_point),
            _data = {
                id: Rkns.Utils.getUID('node'),
                created_by: this.renkan.current_user,
                position: {
                    x: _coords.x,
                    y: _coords.y
                }
            };
            _node = this.renkan.project.addNode(_data);
            this.getRepresentationByModel(_node).openEditor();
    }
    paper.view.draw();
}

Rkns.Renderer.Scene.prototype.onMouseEnter = function(_event) {
    var _newEl = this.renkan.selected_bin_item;
    if (_newEl) {
        var _off = this.canvas_$.offset(),
            _point = new paper.Point([
                _event.pageX - _off.left,
                _event.pageY - _off.top
            ]),
            _coords = this.toModelCoords(_point),
            _data = {
                id: Rkns.Utils.getUID('node'),
                created_by: this.renkan.current_user,
                uri: _newEl.uri,
                title: _newEl.title,
                description: _newEl.description,
                position: {
                    x: _coords.x,
                    y: _coords.y
                }
            };
        var _node = this.renkan.project.addNode(_data);
        this.renkan.selected_bin_item = null;
        this.is_dragging = true;
        this.click_target = this.getRepresentationByModel(_node);
    }
}