src/js/libs/renkan.js
changeset 997 1615c7e4ef9d
parent 955 5055aa35340f
child 998 9521347ede1d
equal deleted inserted replaced
996:c472984db275 997:1615c7e4ef9d
       
     1 /* 
       
     2  *  Copyright 2012-2013 Institut de recherche et d'innovation 
       
     3  *  contributor(s) : Yves-Marie Haussonne, Raphael Velt, Samuel Huron
       
     4  *   
       
     5  *  contact@iri.centrepompidou.fr
       
     6  *  http://www.iri.centrepompidou.fr 
       
     7  *   
       
     8  *  This software is a computer program whose purpose is to show and add annotations on a video .
       
     9  *  This software is governed by the CeCILL-C license under French law and
       
    10  *  abiding by the rules of distribution of free software. You can  use, 
       
    11  *  modify and/ or redistribute the software under the terms of the CeCILL-C
       
    12  *  license as circulated by CEA, CNRS and INRIA at the following URL
       
    13  *  "http://www.cecill.info". 
       
    14  *  
       
    15  *  The fact that you are presently reading this means that you have had
       
    16  *  knowledge of the CeCILL-C license and that you accept its terms.
       
    17 */
       
    18 
       
    19 /* Declaring the Renkan Namespace Rkns and Default values */
       
    20 
       
    21 if (typeof Rkns !== "object") {
       
    22     Rkns = {}
       
    23 }
       
    24 
       
    25 Rkns.$ = jQuery;
       
    26 
       
    27 Rkns._ = _;
       
    28 
       
    29 Rkns.VERSION = '0.2';
       
    30 
       
    31 Rkns.pickerColors = ["#8f1919", "#a80000", "#d82626", "#ff0000", "#e87c7c", "#ff6565", "#f7d3d3", "#fecccc",
       
    32     "#8f5419", "#a85400", "#d87f26", "#ff7f00", "#e8b27c", "#ffb265", "#f7e5d3", "#fee5cc",
       
    33     "#8f8f19", "#a8a800", "#d8d826", "#feff00", "#e8e87c", "#feff65", "#f7f7d3", "#fefecc",
       
    34     "#198f19", "#00a800", "#26d826", "#00ff00", "#7ce87c", "#65ff65", "#d3f7d3", "#ccfecc",
       
    35     "#198f8f", "#00a8a8", "#26d8d8", "#00feff", "#7ce8e8", "#65feff", "#d3f7f7", "#ccfefe",
       
    36     "#19198f", "#0000a8", "#2626d8", "#0000ff", "#7c7ce8", "#6565ff", "#d3d3f7", "#ccccfe",
       
    37     "#8f198f", "#a800a8", "#d826d8", "#ff00fe", "#e87ce8", "#ff65fe", "#f7d3f7", "#feccfe",
       
    38     "#000000", "#242424", "#484848", "#6d6d6d", "#919191", "#b6b6b6", "#dadada", "#ffffff"];
       
    39 
       
    40 Rkns._BaseBin = function(_renkan, _opts) {
       
    41     if (typeof _renkan !== "undefined") {
       
    42         this.renkan = _renkan;
       
    43         this.renkan.$.find(".Rk-Bin-Main").hide();
       
    44         this.$ = Rkns.$('<li>')
       
    45             .addClass("Rk-Bin")
       
    46             .appendTo(_renkan.$.find(".Rk-Bin-List"));
       
    47         this.title_icon_$ = Rkns.$('<span>')
       
    48             .addClass("Rk-Bin-Title-Icon")
       
    49             .appendTo(this.$);
       
    50             
       
    51         var _this = this;
       
    52         
       
    53         Rkns.$('<a>')
       
    54             .attr({
       
    55                 href: "#",
       
    56                 title: _renkan.translate("Close bin")
       
    57             })
       
    58             .addClass("Rk-Bin-Close")
       
    59             .html('&times;')
       
    60             .appendTo(this.$)
       
    61             .click(function() {
       
    62                 _this.destroy();
       
    63                 if (!_renkan.$.find(".Rk-Bin-Main:visible").length) {
       
    64                     _renkan.$.find(".Rk-Bin-Main:last").slideDown();
       
    65                 }
       
    66                 _renkan.resizeBins();
       
    67                 return false;
       
    68             });
       
    69         Rkns.$('<a>')
       
    70             .attr({
       
    71                 href: "#",
       
    72                 title: _renkan.translate("Refresh bin")
       
    73             })
       
    74             .addClass("Rk-Bin-Refresh")
       
    75             .appendTo(this.$)
       
    76             .click(function() {
       
    77                 _this.refresh();
       
    78                 return false;
       
    79             });
       
    80         this.count_$ = Rkns.$('<div>')
       
    81             .addClass("Rk-Bin-Count")
       
    82             .appendTo(this.$);
       
    83         this.title_$ = Rkns.$('<h2>')
       
    84             .addClass("Rk-Bin-Title")
       
    85             .appendTo(this.$);
       
    86         this.main_$ = Rkns.$('<div>')
       
    87             .addClass("Rk-Bin-Main")
       
    88             .appendTo(this.$)
       
    89             .html('<h4 class="Rk-Bin-Loading">' + _renkan.translate("Loading, please wait") + '</h4>');
       
    90         this.title_$.html(_opts.title || '(new bin)');
       
    91         this.renkan.resizeBins();
       
    92         
       
    93         if (_opts.auto_refresh) {
       
    94             window.setInterval(function() {
       
    95                 _this.refresh();
       
    96             },_opts.auto_refresh)
       
    97         }
       
    98     }
       
    99 };
       
   100 
       
   101 Rkns._BaseBin.prototype.destroy = function() {
       
   102     this.$.detach();
       
   103     this.renkan.resizeBins();
       
   104 };
       
   105 
       
   106 /* Point of entry */
       
   107 
       
   108 Rkns.Renkan = function(_opts) {
       
   109     var _this = this;
       
   110     
       
   111     this.options = _.defaults(_opts, Rkns.defaults);
       
   112         
       
   113     Rkns._(this.options.property_files).each(function(f) {
       
   114         Rkns.$.getJSON(f, function(data) {
       
   115             _this.options.properties = _this.options.properties.concat(data);
       
   116         });
       
   117     });
       
   118     
       
   119     this.read_only = this.options.read_only || !this.options.editor_mode;
       
   120 
       
   121     this.project = new Rkns.Models.Project();
       
   122     
       
   123     if (typeof this.options.user_id !== "undefined") {
       
   124         this.current_user = this.options.user_id;
       
   125     }
       
   126     this.$ = Rkns.$("#" + this.options.container);
       
   127     this.$
       
   128         .addClass("Rk-Main")
       
   129         .html(this.template(this));
       
   130     this.renderer = new Rkns.Renderer.Scene(this);
       
   131     this.tabs = [];
       
   132     this.search_engines = [];
       
   133 
       
   134     this.current_user_list = new Rkns.Models.UsersList();
       
   135     
       
   136     if (!this.options.search.length) {
       
   137         this.$.find(".Rk-Web-Search-Form").detach();
       
   138     } else {
       
   139         var _tmpl = Rkns._.template('<li class="<%= className %>" data-key="<%= key %>"><%= title %></li>'),
       
   140             _select = this.$.find(".Rk-Search-List"),
       
   141             _input = this.$.find(".Rk-Web-Search-Input")
       
   142             _form = this.$.find(".Rk-Web-Search-Form");
       
   143         Rkns._(this.options.search).each(function(_search, _key) {
       
   144             if (Rkns[_search.type] && Rkns[_search.type].Search) {
       
   145                 _this.search_engines.push(new Rkns[_search.type].Search(_this, _search));
       
   146             }
       
   147         });
       
   148         _select.html(
       
   149             Rkns._(this.search_engines).map(function(_search, _key) {
       
   150                 return _tmpl({
       
   151                     key: _key,
       
   152                     title: _search.getSearchTitle(),
       
   153                     className: _search.getBgClass()
       
   154                 });
       
   155             }).join("")
       
   156         );
       
   157         _select.find("li").click(function() {
       
   158             var _el = Rkns.$(this);
       
   159             _this.setSearchEngine(_el.attr("data-key"));
       
   160             _form.submit();
       
   161         });
       
   162         _form.submit(function() {
       
   163             if (_input.val()) {
       
   164                 var _search = _this.search_engine;
       
   165                 _search.search(_input.val());
       
   166             }
       
   167             return false;
       
   168         });
       
   169         this.$.find(".Rk-Search-Current").mouseenter(
       
   170             function() { _select.slideDown(); }
       
   171         );
       
   172         this.$.find(".Rk-Search-Select").mouseleave(
       
   173             function() { _select.hide(); }
       
   174         );
       
   175         this.setSearchEngine(0);
       
   176     }
       
   177     Rkns._(this.options.bins).each(function(_bin) {
       
   178         if (Rkns[_bin.type] && Rkns[_bin.type].Bin) {
       
   179             _this.tabs.push(new Rkns[_bin.type].Bin(_this, _bin));
       
   180         }
       
   181     });
       
   182     
       
   183     var elementDropped = false;
       
   184     
       
   185     this.$.find(".Rk-Bins")
       
   186         .on("click",".Rk-Bin-Title,.Rk-Bin-Title-Icon", function() {
       
   187             var _mainDiv = Rkns.$(this).siblings(".Rk-Bin-Main");
       
   188             if (_mainDiv.is(":hidden")) {
       
   189                 _this.$.find(".Rk-Bin-Main").slideUp();
       
   190                 _mainDiv.slideDown();
       
   191             }
       
   192         }).on("mouseover", ".Rk-Bin-Item", function(_e) {
       
   193             var _t = Rkns.$(this);
       
   194             if (_t && $(_t).attr("data-uri")) {
       
   195                 var _models = _this.project.get("nodes").where({
       
   196                     uri: $(_t).attr("data-uri")
       
   197                 });
       
   198                 Rkns._(_models).each(function(_model) {
       
   199                     _this.renderer.highlightModel(_model);
       
   200                 });
       
   201             }
       
   202         }).mouseout(function() {
       
   203             _this.renderer.unhighlightAll();
       
   204         }).on("mousemove", ".Rk-Bin-Item", function(e) {
       
   205             try {
       
   206                 this.dragDrop();
       
   207             }
       
   208             catch(err) {}
       
   209         }).on("touchstart", ".Rk-Bin-Item", function(e) {
       
   210             elementDropped = false;
       
   211         }).on("touchmove", ".Rk-Bin-Item", function(e) {
       
   212             e.preventDefault();
       
   213             var touch = e.originalEvent.changedTouches[0],
       
   214                 off = _this.renderer.canvas_$.offset(),
       
   215                 w = _this.renderer.canvas_$.width(),
       
   216                 h = _this.renderer.canvas_$.height();
       
   217             if (touch.pageX >= off.left && touch.pageX < (off.left + w) && touch.pageY >= off.top && touch.pageY < (off.top + h)) {
       
   218                 if (elementDropped) {
       
   219                     _this.renderer.onMouseMove(touch, true);
       
   220                 } else {
       
   221                     elementDropped = true;
       
   222                     var div = document.createElement('div');
       
   223                     div.appendChild(this.cloneNode(true));
       
   224                     _this.renderer.dropData({"text/html": div.innerHTML}, touch);
       
   225                     _this.renderer.onMouseDown(touch, true);
       
   226                 }
       
   227             }
       
   228         }).on("touchend", ".Rk-Bin-Item", function(e) {
       
   229             if (elementDropped) {
       
   230                 _this.renderer.onMouseUp(e.originalEvent.changedTouches[0], true);
       
   231             }
       
   232             elementDropped = false;
       
   233         }).on("dragstart", ".Rk-Bin-Item", function(e) {
       
   234             var div = document.createElement('div');
       
   235             div.appendChild(this.cloneNode(true));
       
   236             try {
       
   237                 e.originalEvent.dataTransfer.setData("text/html",div.innerHTML);
       
   238             }
       
   239             catch(err) {
       
   240                 e.originalEvent.dataTransfer.setData("text",div.innerHTML);
       
   241             }
       
   242         });
       
   243     Rkns.$(window).resize(function() {
       
   244         _this.resizeBins();
       
   245     });
       
   246     
       
   247     this.$.find(".Rk-Bins-Search-Input").on("change keyup paste input", function() {
       
   248        var val = Rkns.$(this).val();
       
   249        Rkns._(_this.tabs).each(function(tab) {
       
   250            tab.render(val);
       
   251        });
       
   252     });
       
   253     this.$.find(".Rk-Bins-Search-Form").submit(function() {
       
   254         return false
       
   255     });
       
   256 };
       
   257 
       
   258 Rkns.Renkan.prototype.template = Rkns._.template(
       
   259     '<% if (options.show_bins) { %><div class="Rk-Bins"><div class="Rk-Bins-Head"><h2 class="Rk-Bins-Title"><%- translate("Select contents:")%></h2>'
       
   260     + '<form class="Rk-Web-Search-Form Rk-Search-Form"><input class="Rk-Web-Search-Input Rk-Search-Input" type="search" placeholder="<%- translate("Search the Web") %>" />'
       
   261     + '<div class="Rk-Search-Select"><div class="Rk-Search-Current"></div><ul class="Rk-Search-List"></ul></div>'
       
   262     + '<input type="submit" value="" class="Rk-Web-Search-Submit Rk-Search-Submit" title="<%- translate("Search the Web") %>" /></form>'
       
   263     + '<form class="Rk-Bins-Search-Form Rk-Search-Form"><input class="Rk-Bins-Search-Input Rk-Search-Input" type="search" placeholder="<%- translate("Search in Bins") %>" />'
       
   264     + '<input type="submit" value="" class="Rk-Bins-Search-Submit Rk-Search-Submit" title="<%- translate("Search in Bins") %>" /></form></div>'
       
   265     + '<ul class="Rk-Bin-List"></ul></div><% } %><div class="Rk-Render Rk-Render-<% if (options.show_bins) { %>Panel<% } else { %>Full<% } %>"></div>'
       
   266 );
       
   267 
       
   268 Rkns.Renkan.prototype.translate = function(_text) {
       
   269     if (Rkns.i18n[this.options.language] && Rkns.i18n[this.options.language][_text]) {
       
   270         return Rkns.i18n[this.options.language][_text];
       
   271     }
       
   272     if (this.options.language.length > 2 && Rkns.i18n[this.options.language.substr(0,2)] && Rkns.i18n[this.options.language.substr(0,2)][_text]) {
       
   273         return Rkns.i18n[this.options.language.substr(0,2)][_text];
       
   274     }
       
   275     return _text;
       
   276 };
       
   277 
       
   278 Rkns.Renkan.prototype.onStatusChange = function() {
       
   279     this.renderer.onStatusChange();
       
   280 };
       
   281 
       
   282 Rkns.Renkan.prototype.setSearchEngine = function(_key) {
       
   283     this.search_engine = this.search_engines[_key];
       
   284     this.$.find(".Rk-Search-Current").attr("class","Rk-Search-Current " + this.search_engine.getBgClass());
       
   285 };
       
   286 
       
   287 Rkns.Renkan.prototype.resizeBins = function() {
       
   288     var _d = + this.$.find(".Rk-Bins-Head").outerHeight();
       
   289     this.$.find(".Rk-Bin-Title:visible").each(function() {
       
   290         _d += Rkns.$(this).outerHeight();
       
   291     });
       
   292     this.$.find(".Rk-Bin-Main").css({
       
   293         height: this.$.find(".Rk-Bins").height() - _d
       
   294     });
       
   295 };
       
   296 
       
   297 /* Utility functions */
       
   298 
       
   299 Rkns.Utils = {
       
   300     _ID_AUTO_INCREMENT : 0,
       
   301     _ID_BASE : (function(_d) {
       
   302         
       
   303         function pad(n){return n<10 ? '0'+n : n}
       
   304         function fillrand(n) {
       
   305             var _res = ''
       
   306             for (var i=0; i<n; i++) {
       
   307                 _res += Math.floor(16*Math.random()).toString(16);
       
   308             }
       
   309             return _res;
       
   310         }
       
   311         return _d.getUTCFullYear() + '-'  
       
   312             + pad(_d.getUTCMonth()+1) + '-'  
       
   313             + pad(_d.getUTCDate()) + '-'
       
   314             + fillrand(16);
       
   315         
       
   316     })(new Date()),
       
   317     getUID : function(_base) {
       
   318         
       
   319         var _n = (++this._ID_AUTO_INCREMENT).toString(16),
       
   320             _base = (typeof _base === "undefined" ? "" : _base + "-" );
       
   321         while (_n.length < 4) {
       
   322             _n = '0' + _n
       
   323         }
       
   324         return _base + this._ID_BASE + '-' + _n;
       
   325         
       
   326     },
       
   327     getFullURL : function(url) {
       
   328         
       
   329         if(typeof(url) == 'undefined' || url == null ) {
       
   330             return "";
       
   331         }
       
   332         if(/https?:\/\//.test(url)) {
       
   333             return url;
       
   334         }
       
   335         var img = new Image();
       
   336         img.src = url;
       
   337         var res = img.src;
       
   338         img.src = null;
       
   339         return res;
       
   340         
       
   341     },
       
   342     inherit : function(_baseClass, _callbefore) {
       
   343         
       
   344         var _class = function(_arg) {
       
   345             if (typeof _callbefore === "function") {
       
   346                 _callbefore.apply(this, Array.prototype.slice.call(arguments, 0));
       
   347             }
       
   348             _baseClass.apply(this, Array.prototype.slice.call(arguments, 0));
       
   349             if (typeof this._init == "function" && !this._initialized) {
       
   350                 this._init.apply(this, Array.prototype.slice.call(arguments, 0));
       
   351                 this._initialized = true;
       
   352             }
       
   353         }
       
   354         Rkns._(_class.prototype).extend(_baseClass.prototype);
       
   355         return _class;
       
   356         
       
   357     }
       
   358 };
       
   359 
       
   360 Rkns.defaults = {
       
   361     
       
   362     language: (navigator.language || navigator.userLanguage || "en"),
       
   363         /* GUI Language */
       
   364     container: "renkan",
       
   365         /* GUI Container DOM element ID */
       
   366     search: [],
       
   367         /* List of Search Engines */
       
   368     bins: [],
       
   369            /* List of Bins */
       
   370     static_url: "",
       
   371         /* URL for static resources */
       
   372     show_bins: true,
       
   373         /* Show bins in left column */
       
   374     properties: [],
       
   375         /* Semantic properties for edges */
       
   376     read_only: false,
       
   377         /* Allows editing of renkan without changing the rest of the GUI. Can be switched on/off on the fly to block/enable editing */
       
   378     editor_mode: true,
       
   379         /* Switch for Publish/Edit GUI. If editor_mode is false, read_only will be true.  */
       
   380     snapshot_mode: false,
       
   381         /* In snapshot mode, clicking on the floppy will save a snapshot. Otherwise, it will show the connection status */
       
   382     show_top_bar: true,
       
   383         /* Show the top bar, (title, buttons, users) */
       
   384     default_user_color: "#303030",
       
   385     size_bug_fix: true,
       
   386         /* Resize the canvas after load (fixes a bug on iPad and FF Mac) */
       
   387     force_resize: false,
       
   388     allow_double_click: true,
       
   389         /* Allows Double Click to create a node on an empty background */
       
   390     element_delete_delay: 5000,
       
   391     
       
   392     /* MINI-MAP OPTIONS */
       
   393     
       
   394     show_minimap: true,
       
   395         /* Show a small map at the bottom right */
       
   396     minimap_width: 160,
       
   397     minimap_height: 120,
       
   398     minimap_background_color: "#ffffff",
       
   399     minimap_border_color: "#cccccc",
       
   400     minimap_highlight_color: "#ffff00",
       
   401     minimap_highlight_weight: 5,
       
   402     
       
   403     /* EDGE/NODE COMMON OPTIONS */
       
   404        
       
   405     buttons_background: "#202020",
       
   406     buttons_label_color: "#c000c0",
       
   407     buttons_label_font_size: 9,
       
   408     
       
   409     /* NODE DISPLAY OPTIONS */
       
   410     
       
   411     show_node_circles: true,
       
   412         /* Show circles for nodes */
       
   413     clip_node_images: true,
       
   414         /* Constraint node images to circles */
       
   415     node_size_base: 25,
       
   416     node_stroke_width: 2,
       
   417     selected_node_stroke_width: 4,
       
   418     node_fill_color: "#ffffff",
       
   419     highlighted_node_fill_color: "#ffff00",
       
   420     node_label_distance: 5,
       
   421         /* Vertical distance between node and label */
       
   422     node_label_max_length: 60,
       
   423         /* Maximum displayed text length */
       
   424     label_untitled_nodes: "(untitled)",
       
   425         /* Label to display on untitled nodes */
       
   426     
       
   427     /* EDGE DISPLAY OPTIONS */
       
   428     
       
   429     edge_stroke_width: 2,
       
   430     selected_edge_stroke_width: 4,
       
   431     edge_label_distance: 0,
       
   432     edge_label_max_length: 20,
       
   433     edge_arrow_length: 18,
       
   434     edge_arrow_width: 12,
       
   435     edge_gap_in_bundles: 12,
       
   436     label_untitled_edges: "",
       
   437     
       
   438     /* CONTEXTUAL DISPLAY (TOOLTIP OR EDITOR) OPTIONS */
       
   439    
       
   440     tooltip_width: 275,
       
   441     tooltip_padding: 10,
       
   442     tooltip_margin: 15,
       
   443     tooltip_arrow_length : 20,
       
   444     tooltip_arrow_width : 40,
       
   445     tooltip_top_color: "#f0f0f0",
       
   446     tooltip_bottom_color: "#d0d0d0",
       
   447     tooltip_border_color: "#808080",
       
   448     tooltip_border_width: 1
       
   449     
       
   450 };
       
   451 
       
   452 (function() {
       
   453     
       
   454     var root = this;
       
   455         
       
   456     var Backbone = root.Backbone;
       
   457     
       
   458     var Models = root.Rkns.Models = {};
       
   459     
       
   460     
       
   461     Models.getUID = function(obj) {
       
   462         var guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
       
   463             var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
       
   464             return v.toString(16);
       
   465         });
       
   466         return obj.type + "-" + guid; 
       
   467     };
       
   468     
       
   469     
       
   470     var RenkanModel = Backbone.RelationalModel.extend({
       
   471         idAttribute : "_id",
       
   472         constructor: function(options) {
       
   473             
       
   474             if (typeof options !== "undefined") {
       
   475                 options._id = options._id || options.id || Models.getUID(this);
       
   476                 options.title = options.title || "";
       
   477                 options.description = options.description || "";
       
   478                 options.uri = options.uri || "";
       
   479                 
       
   480                 if(typeof this.prepare === "function") {
       
   481                     options = this.prepare(options);
       
   482                 }
       
   483             }
       
   484             Backbone.RelationalModel.prototype.constructor.call(this, options);
       
   485         },
       
   486         validate: function() {
       
   487             if(!this.type) {
       
   488                 return "object has no type";
       
   489             }
       
   490         },
       
   491         addReference : function(_options, _propName, _list, _id, _default) {
       
   492             var _element = _list.get(_id);
       
   493             if (typeof _element === "undefined" && typeof _default !== "undefined") {
       
   494                 _options[_propName ] = _default;
       
   495             }
       
   496             else {
       
   497                 _options[_propName ] = _element;
       
   498             }
       
   499         }
       
   500     });
       
   501         
       
   502     // USER
       
   503     var User = Models.User = RenkanModel.extend({
       
   504         type: "user",
       
   505         prepare: function(options) {
       
   506             options.color = options.color || "#666666";
       
   507             return options;
       
   508         },
       
   509         toJSON: function() {
       
   510             return {
       
   511                 _id: this.get("_id"),
       
   512                 title: this.get("title"),
       
   513                 uri: this.get("uri"),
       
   514                 description: this.get("description"),
       
   515                 color: this.get("color"),
       
   516             };
       
   517         },
       
   518     });
       
   519     
       
   520     // NODE
       
   521     var Node = Models.Node = RenkanModel.extend({
       
   522         type: "node",
       
   523         relations: [{
       
   524             type: Backbone.HasOne,
       
   525             key: "created_by",
       
   526             relatedModel: User
       
   527         }],
       
   528         prepare: function(options) {
       
   529             project = options.project;
       
   530             this.addReference(options, "created_by", project.get("users"), options.created_by, project.current_user);
       
   531             options.description = options.description || "";
       
   532             return options;
       
   533         },
       
   534         toJSON: function() {
       
   535             return {
       
   536                 _id: this.get("_id"),
       
   537                 title: this.get("title"),
       
   538                 uri: this.get("uri"),
       
   539                 description: this.get("description"),
       
   540                 position: this.get("position"),
       
   541                 image: this.get("image"),
       
   542                 color: this.get("color"),
       
   543                 created_by: this.get("created_by") ? this.get("created_by").get("_id") : null,
       
   544                 size: this.get("size")
       
   545             };
       
   546         },
       
   547     });
       
   548     
       
   549     // EDGE
       
   550     var Edge = Models.Edge = RenkanModel.extend({
       
   551         type: "edge",
       
   552         relations: [
       
   553           {
       
   554             type: Backbone.HasOne,
       
   555             key: "created_by",
       
   556             relatedModel: User
       
   557           },
       
   558           {
       
   559             type: Backbone.HasOne,
       
   560             key: "from",
       
   561             relatedModel: Node
       
   562           },
       
   563           {
       
   564             type: Backbone.HasOne,
       
   565             key: "to",
       
   566             relatedModel: Node
       
   567           },
       
   568         ],
       
   569         prepare: function(options) {
       
   570             project = options.project;
       
   571             this.addReference(options, "created_by", project.get("users"), options.created_by, project.current_user);
       
   572             this.addReference(options, "from", project.get("nodes"), options.from);
       
   573             this.addReference(options, "to", project.get("nodes"), options.to);
       
   574             return options;
       
   575         },
       
   576         toJSON: function() {
       
   577             return {
       
   578                 _id: this.get("_id"),
       
   579                 title: this.get("title"),
       
   580                 uri: this.get("uri"),
       
   581                 description: this.get("description"),
       
   582                 from: this.get("from") ? this.get("from").get("_id") : null,
       
   583                 to: this.get("to") ? this.get("to").get("_id") : null,
       
   584                 color: this.get("color"),
       
   585                 created_by: this.get("created_by") ? this.get("created_by").get("_id") : null
       
   586             };
       
   587         },
       
   588     });
       
   589         
       
   590     // PROJECT
       
   591     var Project = Models.Project = RenkanModel.extend({
       
   592         type: "project",
       
   593         relations: [
       
   594           {
       
   595             type: Backbone.HasMany,
       
   596             key: "users",
       
   597             relatedModel: User,
       
   598             reverseRelation: {
       
   599                 key: 'project',
       
   600                 includeInJSON: '_id'
       
   601             },
       
   602           },
       
   603           {
       
   604             type: Backbone.HasMany,
       
   605             key: "nodes",
       
   606             relatedModel: Node,
       
   607             reverseRelation: {
       
   608                 key: 'project',
       
   609                 includeInJSON: '_id'
       
   610             },
       
   611           },
       
   612           {
       
   613             type: Backbone.HasMany,
       
   614             key: "edges",
       
   615             relatedModel: Edge,
       
   616             reverseRelation: {
       
   617                 key: 'project',
       
   618                 includeInJSON: '_id'
       
   619             },
       
   620           }
       
   621         ],
       
   622         addUser: function(_props, _options) {
       
   623             _props.project = this;
       
   624             var _user = User.findOrCreate(_props);
       
   625             this.get("users").push(_user, _options);
       
   626             return _user;
       
   627         },
       
   628         addNode: function(_props, _options) {
       
   629             _props.project = this;            
       
   630             var _node = Node.findOrCreate(_props);
       
   631             this.get("nodes").push(_node, _options);
       
   632             return _node;
       
   633         },
       
   634         addEdge: function(_props, _options) {
       
   635             _props.project = this;
       
   636             var _edge = Edge.findOrCreate(_props);
       
   637             this.get("edges").push(_edge, _options);
       
   638             return _edge;
       
   639         },
       
   640         removeNode: function(_model) {
       
   641             this.get("nodes").remove(_model);
       
   642         },
       
   643         removeEdge: function(_model) {
       
   644             this.get("edges").remove(_model);
       
   645         },
       
   646         validate: function(options) {
       
   647             var _project = this;
       
   648             _(options.users).each(function(_item) {
       
   649                 _item.project = _project;
       
   650             });
       
   651             _(options.nodes).each(function(_item) {
       
   652                 _item.project = _project;
       
   653             });
       
   654             _(options.edges).each(function(_item) {
       
   655                 _item.project = _project;
       
   656             });
       
   657         },
       
   658         // Add event handler to remove edges when a node is removed
       
   659         initialize: function() {
       
   660             var _this = this;
       
   661             this.on("remove:nodes", function(_node) {
       
   662                 _this.get("edges").remove(
       
   663                     _this.get("edges").filter(function(_edge) {
       
   664                         return _edge.get("from") == _node || _edge.get("to") == _node;
       
   665                     })
       
   666                 );
       
   667             });
       
   668         }
       
   669     });
       
   670     
       
   671     var RosterUser = Models.RosterUser = Backbone.Model.extend({
       
   672         type: "roster_user",               
       
   673         idAttribute : "_id",
       
   674         
       
   675         constructor: function(options) {
       
   676             
       
   677             if (typeof options !== "undefined") {
       
   678                 options._id = options._id || options.id || Models.getUID(this);
       
   679                 options.title = options.title || "(untitled " + this.type + ")";
       
   680                 options.description = options.description || "";
       
   681                 options.uri = options.uri || "";
       
   682                 options.project = options.project || null;
       
   683                 options.site_id = options.site_id || 0;
       
   684                 
       
   685                 if(typeof this.prepare === "function") {
       
   686                     options = this.prepare(options);
       
   687                 }
       
   688             }
       
   689             Backbone.Model.prototype.constructor.call(this, options);
       
   690         },
       
   691         
       
   692         validate: function() {
       
   693             if(!this.type) {
       
   694                 return "object has no type";
       
   695             }
       
   696         },
       
   697         
       
   698         prepare: function(options) {
       
   699             options.color = options.color || "#666666";
       
   700             return options;
       
   701         },
       
   702         
       
   703         toJSON: function() {
       
   704             return {
       
   705                 _id: this.get("_id"),
       
   706                 title: this.get("title"),
       
   707                 uri: this.get("uri"),
       
   708                 description: this.get("description"),
       
   709                 color: this.get("color"),
       
   710                 project: (this.get("project") != null)?this.get("project").get("id"):null,
       
   711                 site_id: this.get("site_id")
       
   712             };
       
   713         },
       
   714     });
       
   715     
       
   716     var UsersList = Models.UsersList = Backbone.Collection.extend({
       
   717         model: RosterUser
       
   718     });
       
   719     
       
   720 
       
   721 }).call(window);
       
   722 
       
   723 Rkns.i18n = {
       
   724     fr: {
       
   725         "Edit Node": "Édition d’un nœud",
       
   726         "Edit Edge": "Édition d’un lien",
       
   727         "Title:": "Titre :",
       
   728         "URI:": "URI :",
       
   729         "Description:": "Description :",
       
   730         "From:": "De :",
       
   731         "To:": "Vers :",
       
   732         "Image": "Image",
       
   733         "Image URL:": "URL d'Image",
       
   734         "Choose Image File:": "Choisir un fichier image",
       
   735         "Full Screen": "Mode plein écran",
       
   736         "Add Node": "Ajouter un nœud",
       
   737         "Add Edge": "Ajouter un lien",
       
   738         "Archive Project": "Archiver le projet",
       
   739         "Auto-save enabled": "Enregistrement automatique activé",
       
   740         "Connection lost": "Connexion perdue",
       
   741         "Created by:": "Créé par :",
       
   742         "Zoom In": "Agrandir l’échelle",
       
   743         "Zoom Out": "Rapetisser l’échelle",
       
   744         "Edit": "Éditer",
       
   745         "Remove": "Supprimer",
       
   746         "Cancel deletion": "Annuler la suppression",
       
   747         "Link to another node": "Créer un lien",
       
   748         "Enlarge": "Agrandir",
       
   749         "Shrink": "Rétrécir",
       
   750         "Click on the background canvas to add a node": "Cliquer sur le fond du graphe pour rajouter un nœud",
       
   751         "Click on a first node to start the edge": "Cliquer sur un premier nœud pour commencer le lien",
       
   752         "Click on a second node to complete the edge": "Cliquer sur un second nœud pour terminer le lien",
       
   753         "Twitter": "Twitter",
       
   754         "Wikipedia": "Wikipédia",
       
   755         "Wikipedia in ": "Wikipédia en ",
       
   756         "French": "Français",
       
   757         "English": "Anglais",
       
   758         "Japanese": "Japonais",
       
   759         "Untitled project": "Projet sans titre",
       
   760         "Lignes de Temps": "Lignes de Temps",
       
   761         "Loading, please wait": "Chargement en cours, merci de patienter",
       
   762         "Edge color:": "Couleur :",
       
   763         "Node color:": "Couleur :",
       
   764         "Choose color": "Choisir une couleur",
       
   765         "Change edge direction": "Changer le sens du lien",
       
   766         "Do you really wish to remove node ": "Voulez-vous réellement supprimer le nœud ",
       
   767         "Do you really wish to remove edge ": "Voulez-vous réellement supprimer le lien ",
       
   768         "This file is not an image": "Ce fichier n'est pas une image",
       
   769         "Image size must be under ": "L'image doit peser moins de ",
       
   770         "Size:": "Taille :",
       
   771         "KB": "ko",
       
   772         "Choose from vocabulary:": "Choisir dans un vocabulaire :",
       
   773         "SKOS Documentation properties": "SKOS: Propriétés documentaires",
       
   774         "has note": "a pour note",
       
   775         "has example": "a pour exemple",
       
   776         "has definition": "a pour définition",
       
   777         "SKOS Semantic relations": "SKOS: Relations sémantiques",
       
   778         "has broader": "a pour concept plus large",
       
   779         "has narrower": "a pour concept plus étroit",
       
   780         "has related": "a pour concept apparenté",
       
   781         "Dublin Core Metadata": "Métadonnées Dublin Core",
       
   782         "has contributor": "a pour contributeur",
       
   783         "covers": "couvre",
       
   784         "created by": "créé par",
       
   785         "has date": "a pour date",
       
   786         "published by": "édité par",
       
   787         "has source": "a pour source",
       
   788         "has subject": "a pour sujet",
       
   789         "Dragged resource": "Ressource glisée-déposée",
       
   790         "Search the Web": "Rechercher en ligne",
       
   791         "Search in Bins": "Rechercher dans les chutiers",
       
   792         "Close bin": "Fermer le chutier",
       
   793         "Refresh bin": "Rafraîchir le chutier",
       
   794         "(untitled)": "(sans titre)",
       
   795         "Select contents:": "Sélectionner des contenus :",
       
   796         "Drag items from this website, drop them in Renkan": "Glissez des éléments de ce site web vers Renkan",
       
   797         "Drag this button to your bookmark bar. When on a third-party website, click it to enable drag-and-drop from the website to Renkan.": "Glissez ce bouton vers votre barre de favoris. Ensuite, depuis un site tiers, cliquez dessus pour activer 'Drag-to-Add' puis glissez des éléments de ce site vers Renkan"
       
   798     }
       
   799 }
       
   800 
       
   801 /* Loads a JSON File */
       
   802 
       
   803 Rkns.jsonIO = function(_renkan, _opts) {
       
   804     var _proj = _renkan.project;
       
   805     if (typeof _opts.http_method == "undefined") {
       
   806         _opts.http_method = 'PUT';
       
   807     }
       
   808     var _load = function() {
       
   809         Rkns.$.getJSON(_opts.url, function(_data) {
       
   810             _proj.set(_data, {validate: true});
       
   811             _renkan.renderer.autoScale();
       
   812         });
       
   813     }
       
   814         
       
   815     _load();
       
   816 }
       
   817 
       
   818 Rkns.Renderer = {
       
   819     _MINIMAP_MARGIN: 20,
       
   820     _MIN_DRAG_DISTANCE: 2,
       
   821     _NODE_BUTTON_WIDTH: 40,
       
   822     _EDGE_BUTTON_INNER: 2,
       
   823     _EDGE_BUTTON_OUTER: 40,
       
   824     _CLICKMODE_ADDNODE : 1,
       
   825     _CLICKMODE_STARTEDGE : 2,
       
   826     _CLICKMODE_ENDEDGE : 3,
       
   827     _IMAGE_MAX_KB : 500,
       
   828     _NODE_SIZE_STEP: Math.LN2/4,
       
   829     _MIN_SCALE: 1/20,
       
   830     _MAX_SCALE: 20,
       
   831     _AUTOSCALE_MARGIN: 50,
       
   832     _MOUSEMOVE_RATE: 80,
       
   833     _DOUBLETAP_DELAY: 800,
       
   834     _DOUBLETAP_DISTANCE: 20*20,
       
   835     _USER_PLACEHOLDER : function(_renkan) {
       
   836         return {
       
   837             color: _renkan.options.default_user_color,
       
   838             title: _renkan.translate("(unknown user)"),
       
   839             get: function(attr) {
       
   840                 return this[attr] || false;
       
   841             }
       
   842         }
       
   843     },
       
   844     _BOOKMARKLET_CODE: function(_renkan) {
       
   845         return "(function(a,b,c,d,e,f,h,i,j,k,l,m,n,o,p,q,r){a=document;b=a.body;c=a.location.href;j='draggable';m='text/x-iri-';d=a.createElement('div');d.innerHTML='<p_style=\"position:fixed;top:0;right:0;font:bold_18px_sans-serif;color:#fff;background:#909;padding:10px;z-index:100000;\">"
       
   846         + _renkan.translate("Drag items from this website, drop them in Renkan").replace(/ /g,"_")
       
   847         + "</p>'.replace(/_/g,String.fromCharCode(32));b.appendChild(d);e=[{r:/https?:\\/\\/[^\\/]*twitter\\.com\\//,s:'.tweet',n:'twitter'},{r:/https?:\\/\\/[^\\/]*google\\.[^\\/]+\\//,s:'.g',n:'google'},{r:/https?:\\/\\/[^\\/]*lemonde\\.fr\\//,s:'[data-vr-contentbox]',n:'lemonde'}];f=false;e.forEach(function(g){if(g.r.test(c)){f=g;}});if(f){h=function(){Array.prototype.forEach.call(a.querySelectorAll(f.s),function(i){i[j]=true;k=i.style;k.borderWidth='2px';k.borderColor='#909';k.borderStyle='solid';k.backgroundColor='rgba(200,0,180,.1)';})};window.setInterval(h,500);h();};a.addEventListener('dragstart',function(k){l=k.dataTransfer;l.setData(m+'source-uri',c);l.setData(m+'source-title',a.title);n=k.target;if(f){o=n;while(!o.attributes[j]){o=o.parentNode;if(o==b){break;}}}if(f&&o.attributes[j]){p=o.cloneNode(true);l.setData(m+'specific-site',f.n)}else{q=a.getSelection();if(q.type==='Range'||!q.type){p=q.getRangeAt(0).cloneContents();}else{p=n.cloneNode();}}r=a.createElement('div');r.appendChild(p);l.setData('text/x-iri-selected-text',r.textContent.trim());l.setData('text/x-iri-selected-html',r.innerHTML);},false);})();"
       
   848     },
       
   849     shortenText : function(_text, _maxlength) {
       
   850         return (_text.length > _maxlength ? (_text.substr(0,_maxlength) + '…') : _text);
       
   851     },
       
   852     drawEditBox : function(_options, _coords, _path, _xmargin, _selector) {
       
   853         _selector.css({
       
   854             width: ( _options.tooltip_width - 2* _options.tooltip_padding ),
       
   855         })
       
   856         var _height = _selector.outerHeight() + 2* _options.tooltip_padding,
       
   857             _isLeft = (_coords.x < paper.view.center.x ? 1 : -1),
       
   858             _left = _coords.x + _isLeft * ( _xmargin + _options.tooltip_arrow_length ),
       
   859             _right = _coords.x + _isLeft * ( _xmargin + _options.tooltip_arrow_length + _options.tooltip_width ),
       
   860             _top = _coords.y - _height / 2;
       
   861         if (_top + _height > (paper.view.size.height - _options.tooltip_margin)) {
       
   862             _top = Math.max( paper.view.size.height - _options.tooltip_margin, _coords.y + _options.tooltip_arrow_width / 2 ) - _height;
       
   863         }
       
   864         if (_top < _options.tooltip_margin) {
       
   865             _top = Math.min( _options.tooltip_margin, _coords.y - _options.tooltip_arrow_width / 2 );
       
   866         }
       
   867         var _bottom = _top + _height;
       
   868         _path.segments[0].point
       
   869             = _path.segments[7].point
       
   870             = _coords.add([_isLeft * _xmargin, 0]);
       
   871         _path.segments[1].point.x
       
   872             = _path.segments[2].point.x
       
   873             = _path.segments[5].point.x
       
   874             = _path.segments[6].point.x
       
   875             = _left;
       
   876         _path.segments[3].point.x
       
   877             = _path.segments[4].point.x
       
   878             = _right;
       
   879         _path.segments[2].point.y
       
   880             = _path.segments[3].point.y
       
   881             = _top;
       
   882         _path.segments[4].point.y
       
   883             = _path.segments[5].point.y
       
   884             = _bottom;
       
   885         _path.segments[1].point.y = _coords.y - _options.tooltip_arrow_width / 2;
       
   886         _path.segments[6].point.y = _coords.y + _options.tooltip_arrow_width / 2;
       
   887         _path.closed = true;
       
   888         _path.fillColor = new paper.GradientColor(new paper.Gradient([_options.tooltip_top_color, _options.tooltip_bottom_color]), [0,_top], [0, _bottom]);
       
   889         _selector.css({
       
   890             left: (_options.tooltip_padding + Math.min(_left, _right)),
       
   891             top: (_options.tooltip_padding + _top)
       
   892         });
       
   893         return _path;
       
   894     }
       
   895 }
       
   896 
       
   897 Rkns.Renderer._BaseRepresentation = function(_renderer, _model) {
       
   898     if (typeof _renderer !== "undefined") {
       
   899         this.renderer = _renderer;
       
   900         this.renkan = _renderer.renkan;
       
   901         this.project = _renderer.renkan.project;
       
   902         this.options = _renderer.renkan.options;
       
   903         this.model = _model;
       
   904         if (this.model) {
       
   905             var _this = this;
       
   906             this._changeBinding = function() {
       
   907                 _this.redraw();
       
   908             }
       
   909             this._removeBinding = function() {
       
   910                 _renderer.removeRepresentation(_this);
       
   911                 _(function() {
       
   912                     _renderer.redraw()
       
   913                 }).defer();
       
   914             }
       
   915             this._selectBinding = function() {
       
   916                 _this.select();
       
   917             }
       
   918             this._unselectBinding = function() {
       
   919                 _this.unselect();
       
   920             }
       
   921             this.model.on("change", this._changeBinding );
       
   922             this.model.on("remove", this._removeBinding );
       
   923             this.model.on("select", this._selectBinding );
       
   924             this.model.on("unselect", this._unselectBinding );
       
   925         }
       
   926     }
       
   927 }
       
   928 
       
   929 Rkns.Renderer._BaseRepresentation.prototype.super = function(_func) {
       
   930     Rkns.Renderer._BaseRepresentation.prototype[_func].apply(this, Array.prototype.slice.call(arguments, 1));
       
   931 }
       
   932 
       
   933 Rkns.Renderer._BaseRepresentation.prototype.redraw = function() {}
       
   934 
       
   935 Rkns.Renderer._BaseRepresentation.prototype.moveTo = function() {}
       
   936 
       
   937 Rkns.Renderer._BaseRepresentation.prototype.show = function() {}
       
   938 
       
   939 Rkns.Renderer._BaseRepresentation.prototype.hide = function() {}
       
   940 
       
   941 Rkns.Renderer._BaseRepresentation.prototype.select = function() {
       
   942     if (this.model) {
       
   943         this.model.trigger("selected");
       
   944     }
       
   945 }
       
   946 
       
   947 Rkns.Renderer._BaseRepresentation.prototype.unselect = function() {
       
   948     if (this.model) {
       
   949         this.model.trigger("unselected");
       
   950     }
       
   951 }
       
   952 
       
   953 Rkns.Renderer._BaseRepresentation.prototype.highlight = function() {}
       
   954 
       
   955 Rkns.Renderer._BaseRepresentation.prototype.unhighlight = function() {}
       
   956 
       
   957 Rkns.Renderer._BaseRepresentation.prototype.mousedown = function() {}
       
   958 
       
   959 Rkns.Renderer._BaseRepresentation.prototype.mouseup = function() {
       
   960     if (this.model) {
       
   961         this.model.trigger("clicked");
       
   962     }
       
   963 }
       
   964 
       
   965 Rkns.Renderer._BaseRepresentation.prototype.destroy = function() {
       
   966     if (this.model) {
       
   967         this.model.off("change", this._changeBinding );
       
   968         this.model.off("remove", this._removeBinding );
       
   969         this.model.off("select", this._selectBinding );
       
   970         this.model.off("unselect", this._unselectBinding );
       
   971     }
       
   972 }
       
   973 
       
   974 /* */
       
   975 
       
   976 Rkns.Renderer._BaseButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);
       
   977 
       
   978 Rkns.Renderer._BaseButton.prototype.moveTo = function(_pos) {
       
   979     this.sector.moveTo(_pos);
       
   980 }
       
   981 
       
   982 Rkns.Renderer._BaseButton.prototype.show = function() {
       
   983     this.sector.show();
       
   984 }
       
   985 
       
   986 Rkns.Renderer._BaseButton.prototype.hide = function() {
       
   987     this.sector.hide();
       
   988 }
       
   989 
       
   990 Rkns.Renderer._BaseButton.prototype.select = function() {
       
   991     this.sector.select();
       
   992 }
       
   993 
       
   994 Rkns.Renderer._BaseButton.prototype.unselect = function(_newTarget) {
       
   995     this.sector.unselect();
       
   996     if (!_newTarget || (_newTarget !== this.source_representation && _newTarget.source_representation !== this.source_representation)) {
       
   997         this.source_representation.unselect();
       
   998     }
       
   999 }
       
  1000 
       
  1001 Rkns.Renderer._BaseButton.prototype.destroy = function() {
       
  1002     this.sector.destroy();
       
  1003 }
       
  1004 
       
  1005 /* */
       
  1006 
       
  1007 Rkns.Renderer.Node = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);
       
  1008 
       
  1009 Rkns.Renderer.Node.prototype._init = function() {
       
  1010     this.renderer.node_layer.activate();
       
  1011     this.type = "Node";
       
  1012     this.circle = new paper.Path.Circle([0, 0], 1);
       
  1013     this.circle.__representation = this;
       
  1014     if (this.options.show_node_circles) {
       
  1015         this.circle.strokeWidth = this.options.node_stroke_width;
       
  1016         this.h_ratio = 1;
       
  1017     } else {
       
  1018         this.h_ratio = 0;
       
  1019     }
       
  1020     this.title = Rkns.$('<div class="Rk-Label">').appendTo(this.renderer.labels_$);
       
  1021     if (this.options.editor_mode) {
       
  1022         this.normal_buttons = [
       
  1023             new Rkns.Renderer.NodeEditButton(this.renderer, null),
       
  1024             new Rkns.Renderer.NodeRemoveButton(this.renderer, null),
       
  1025             new Rkns.Renderer.NodeLinkButton(this.renderer, null),
       
  1026             new Rkns.Renderer.NodeEnlargeButton(this.renderer, null),
       
  1027             new Rkns.Renderer.NodeShrinkButton(this.renderer, null)
       
  1028         ];
       
  1029         this.pending_delete_buttons = [
       
  1030             new Rkns.Renderer.NodeRevertButton(this.renderer, null)
       
  1031         ];
       
  1032         this.all_buttons = this.normal_buttons.concat(this.pending_delete_buttons)
       
  1033         for (var i = 0; i < this.all_buttons.length; i++) {
       
  1034             this.all_buttons[i].source_representation = this;
       
  1035         }
       
  1036         this.active_buttons = [];
       
  1037     } else {
       
  1038         this.active_buttons = this.all_buttons = [];
       
  1039     }
       
  1040     this.last_circle_radius = 1;
       
  1041     
       
  1042     if (this.renderer.minimap) {
       
  1043         this.renderer.minimap.node_layer.activate();
       
  1044         this.minimap_circle = new paper.Path.Circle([0, 0], 1);
       
  1045         this.minimap_circle.__representation = this.renderer.minimap.miniframe.__representation;
       
  1046         this.renderer.minimap.node_group.addChild(this.minimap_circle);
       
  1047     }
       
  1048 }
       
  1049 
       
  1050 Rkns.Renderer.Node.prototype.redraw = function(_dontRedrawEdges) {
       
  1051     var _model_coords = new paper.Point(this.model.get("position")),
       
  1052         _baseRadius = this.options.node_size_base * Math.exp((this.model.get("size") || 0) * Rkns.Renderer._NODE_SIZE_STEP);
       
  1053     if (!this.is_dragging || !this.paper_coords) {
       
  1054         this.paper_coords = this.renderer.toPaperCoords(_model_coords);
       
  1055     }
       
  1056     this.circle_radius = _baseRadius * this.renderer.scale;
       
  1057     if (this.last_circle_radius !== this.circle_radius) {
       
  1058         this.all_buttons.forEach(function(b) {
       
  1059             b.setSectorSize();
       
  1060         });
       
  1061         var square = new paper.Size(this.circle_radius, this.circle_radius),
       
  1062             topleft = this.paper_coords.subtract(square),
       
  1063             bounds = new paper.Rectangle(topleft, square.multiply(2));
       
  1064         this.circle.fitBounds(bounds);
       
  1065         if (this.node_image) {
       
  1066             this.node_image.fitBounds(bounds);
       
  1067         }
       
  1068     } else {
       
  1069         this.circle.position = this.paper_coords;
       
  1070         if (this.node_image) {
       
  1071             this.node_image.position = this.paper_coords;
       
  1072         }
       
  1073     }
       
  1074     this.last_circle_radius = this.circle_radius;
       
  1075     
       
  1076     var old_act_btn = this.active_buttons;
       
  1077     
       
  1078     if (this.model.get("delete_scheduled")) {
       
  1079         var opacity = .5;
       
  1080         this.active_buttons = this.pending_delete_buttons;
       
  1081         this.circle.dashArray = [2,2];
       
  1082     } else {
       
  1083         var opacity = 1;
       
  1084         this.active_buttons = this.normal_buttons;
       
  1085         this.circle.dashArray = null;
       
  1086     }
       
  1087     
       
  1088     if (this.selected && this.renderer.isEditable()) {
       
  1089         if (old_act_btn !== this.active_buttons) {
       
  1090             old_act_btn.forEach(function(b) {
       
  1091                 b.hide();
       
  1092             });
       
  1093         }
       
  1094         this.active_buttons.forEach(function(b) {
       
  1095             b.show();
       
  1096         });
       
  1097     }
       
  1098     
       
  1099     if (this.node_image) {
       
  1100         this.node_image.opacity = this.highlighted ? opacity * .5 : (opacity - .01);
       
  1101     }
       
  1102     
       
  1103     this.circle.fillColor = this.highlighted ? this.options.highlighted_node_fill_color : this.options.node_fill_color;
       
  1104     
       
  1105     this.circle.opacity = this.options.show_node_circles ? opacity : .01;
       
  1106     
       
  1107     var _text = this.model.get("title") || this.renkan.translate(this.options.label_untitled_nodes) || "";
       
  1108     _text = Rkns.Renderer.shortenText(_text, this.options.node_label_max_length);
       
  1109     this.title.text(_text);
       
  1110     this.title.css({
       
  1111         left: this.paper_coords.x,
       
  1112         top: this.paper_coords.y + this.circle_radius * this.h_ratio + this.options.node_label_distance,
       
  1113         opacity: opacity
       
  1114     })
       
  1115     var _color = this.model.get("color") || (this.model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan)).get("color");
       
  1116     this.circle.strokeColor = _color;
       
  1117     var _pc = this.paper_coords;
       
  1118     this.all_buttons.forEach(function(b) {
       
  1119         b.moveTo(_pc);
       
  1120     });
       
  1121     var _img = this.model.get("image");
       
  1122     if (_img && _img !== this.img) {
       
  1123         var _image = new Image(),
       
  1124             _this = this;
       
  1125         _image.onload = function() {
       
  1126             if (_this.node_image) {
       
  1127                 _this.node_image.remove();
       
  1128             }
       
  1129             _this.renderer.node_layer.activate();
       
  1130             var _ratio = Math.min(2 / _image.width, 2 / _image.height );
       
  1131             if (!_this.options.show_node_circles) {
       
  1132                 _this.h_ratio = Math.min(1, _image.height / _image.width);
       
  1133             }
       
  1134             var _raster = new paper.Raster(_image);
       
  1135             if (_this.options.clip_node_images) {
       
  1136                 var _clip = new paper.Path.Circle([0, 0], 1);
       
  1137                 _raster.scale(_ratio);
       
  1138                 _this.node_image = new paper.Group(_clip, _raster);
       
  1139                 _this.node_image.opacity = .99;
       
  1140                 /* This is a workaround to allow clipping at group level
       
  1141                  * If opacity was set to 1, paper.js would merge all clipping groups in one (known bug).
       
  1142                 */
       
  1143                 _this.node_image.clipped = true;
       
  1144                 _clip.__representation = _this;
       
  1145             } else {
       
  1146                 _this.node_image = _raster;
       
  1147             }
       
  1148             _this.node_image.__representation = _this;
       
  1149             var square = new paper.Size(_this.circle_radius, _this.circle_radius),
       
  1150                 topleft = _this.paper_coords.subtract(square),
       
  1151                 bounds = new paper.Rectangle(topleft, square.multiply(2));
       
  1152             _this.node_image.fitBounds(bounds);
       
  1153             _this.redraw();
       
  1154             paper.view.draw();
       
  1155         }
       
  1156         _image.src = _img;
       
  1157     }
       
  1158     this.img = _img;
       
  1159     if (this.node_image && !this.img) {
       
  1160         this.node_image.remove();
       
  1161         delete this.node_image;
       
  1162     }
       
  1163     
       
  1164     if (this.renderer.minimap) {
       
  1165         this.minimap_circle.fillColor = _color;
       
  1166         var minipos = this.renderer.toMinimapCoords(_model_coords),
       
  1167             miniradius = this.renderer.minimap.scale * _baseRadius,
       
  1168             minisize = new paper.Size([miniradius, miniradius]);
       
  1169         this.minimap_circle.fitBounds(minipos.subtract(minisize), minisize.multiply(2));
       
  1170     }
       
  1171     
       
  1172     if (!_dontRedrawEdges) {
       
  1173         Rkns._.each(this.project.get("edges").filter(function (ed) { return ((ed.to === this.model) || (ed.from === this.model));}), function(edge, index, list){
       
  1174             var repr = this.renderer.getRepresentationByModel(edge);
       
  1175             if(repr != null && typeof repr.from_representation.paper_coords !== "undefined" && typeof repr.to_representation.paper_coords !== "undefined") {
       
  1176                 repr.redraw();
       
  1177             }
       
  1178         }, this);
       
  1179     }
       
  1180 
       
  1181 }
       
  1182 
       
  1183 Rkns.Renderer.Node.prototype.paperShift = function(_delta) {
       
  1184     if (this.options.editor_mode) {
       
  1185         if (!this.renkan.read_only) {
       
  1186             this.is_dragging = true;
       
  1187             this.paper_coords = this.paper_coords.add(_delta);
       
  1188             this.redraw();
       
  1189         }
       
  1190     } else {
       
  1191         this.renderer.paperShift(_delta);
       
  1192     }
       
  1193 }
       
  1194 
       
  1195 Rkns.Renderer.Node.prototype.openEditor = function() {
       
  1196     this.renderer.removeRepresentationsOfType("editor");
       
  1197     var _editor = this.renderer.addRepresentation("NodeEditor",null);
       
  1198     _editor.source_representation = this;
       
  1199     _editor.draw();
       
  1200 }
       
  1201 
       
  1202 Rkns.Renderer.Node.prototype.select = function() {
       
  1203     this.selected = true;
       
  1204     this.circle.strokeWidth = this.options.selected_node_stroke_width;
       
  1205     if (this.renderer.isEditable()) {
       
  1206         this.active_buttons.forEach(function(b) {
       
  1207             b.show();
       
  1208         });
       
  1209     }
       
  1210     var _uri = this.model.get("uri");
       
  1211     if (_uri) {
       
  1212         Rkns.$('.Rk-Bin-Item').each(function() {
       
  1213             var _el = Rkns.$(this);
       
  1214             if (_el.attr("data-uri") == _uri) {
       
  1215                 _el.addClass("selected");
       
  1216             }
       
  1217         });
       
  1218     }
       
  1219     if (!this.options.editor_mode) {
       
  1220         this.openEditor();
       
  1221     }
       
  1222     
       
  1223     if (this.renderer.minimap) {
       
  1224         this.minimap_circle.strokeWidth = this.options.minimap_highlight_weight;
       
  1225         this.minimap_circle.strokeColor = this.options.minimap_highlight_color;
       
  1226     }
       
  1227     this.super("select");
       
  1228 }
       
  1229 
       
  1230 Rkns.Renderer.Node.prototype.unselect = function(_newTarget) {
       
  1231     if (!_newTarget || _newTarget.source_representation !== this) {
       
  1232         this.selected = false;
       
  1233         this.all_buttons.forEach(function(b) {
       
  1234             b.hide();
       
  1235         });
       
  1236         this.circle.strokeWidth = this.options.node_stroke_width;
       
  1237         Rkns.$('.Rk-Bin-Item').removeClass("selected");
       
  1238         if (this.renderer.minimap) {
       
  1239             this.minimap_circle.strokeColor = undefined;
       
  1240         }
       
  1241         this.super("unselect");
       
  1242     }
       
  1243 }
       
  1244     
       
  1245 Rkns.Renderer.Node.prototype.highlight = function() {
       
  1246     if (this.highlighted) {
       
  1247         return;
       
  1248     }
       
  1249     this.highlighted = true;
       
  1250     this.redraw();
       
  1251     this.renderer.throttledPaperDraw();
       
  1252 }
       
  1253 
       
  1254 Rkns.Renderer.Node.prototype.unhighlight = function() {
       
  1255     if (!this.highlighted) {
       
  1256         return;
       
  1257     }
       
  1258     this.highlighted = false;
       
  1259     this.redraw();
       
  1260     this.renderer.throttledPaperDraw();
       
  1261 }
       
  1262 
       
  1263 Rkns.Renderer.Node.prototype.saveCoords = function() {
       
  1264     var _coords = this.renderer.toModelCoords(this.paper_coords),
       
  1265         _data = {
       
  1266             position: {
       
  1267                 x: _coords.x,
       
  1268                 y: _coords.y
       
  1269             }
       
  1270         };
       
  1271     if (this.renderer.isEditable()) {
       
  1272         this.model.set(_data);
       
  1273     }
       
  1274 }
       
  1275 
       
  1276 Rkns.Renderer.Node.prototype.mousedown = function(_event, _isTouch) {
       
  1277     if (_isTouch) {
       
  1278         this.renderer.unselectAll();
       
  1279         this.select();
       
  1280     }
       
  1281 }
       
  1282 
       
  1283 Rkns.Renderer.Node.prototype.mouseup = function(_event, _isTouch) {
       
  1284     if (this.renderer.is_dragging && this.renderer.isEditable()) {
       
  1285         this.saveCoords();
       
  1286     } else {
       
  1287         if (!_isTouch && !this.model.get("delete_scheduled")) {
       
  1288             this.openEditor();
       
  1289         }
       
  1290         this.model.trigger("clicked");
       
  1291     }
       
  1292     this.renderer.click_target = null;
       
  1293     this.renderer.is_dragging = false;
       
  1294     this.is_dragging = false;
       
  1295 }
       
  1296 
       
  1297 Rkns.Renderer.Node.prototype.destroy = function(_event) {
       
  1298     this.super("destroy");
       
  1299     this.all_buttons.forEach(function(b) {
       
  1300         b.destroy();
       
  1301     });
       
  1302     this.circle.remove();
       
  1303     this.title.remove();
       
  1304     if (this.renderer.minimap) {
       
  1305         this.minimap_circle.remove();
       
  1306     }
       
  1307     if (this.node_image) {
       
  1308         this.node_image.remove();
       
  1309     }
       
  1310 }
       
  1311 
       
  1312 /* */
       
  1313 
       
  1314 Rkns.Renderer.Edge = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);
       
  1315 
       
  1316 Rkns.Renderer.Edge.prototype._init = function() {
       
  1317     this.renderer.edge_layer.activate();
       
  1318     this.type = "Edge";
       
  1319     this.from_representation = this.renderer.getRepresentationByModel(this.model.get("from"));
       
  1320     this.to_representation = this.renderer.getRepresentationByModel(this.model.get("to"));
       
  1321     this.bundle = this.renderer.addToBundles(this);
       
  1322     this.line = new paper.Path();
       
  1323     this.line.add([0,0],[0,0],[0,0]);
       
  1324     this.line.__representation = this;
       
  1325     this.line.strokeWidth = this.options.edge_stroke_width;
       
  1326     this.arrow = new paper.Path();
       
  1327     this.arrow.add(
       
  1328         [ 0, 0 ],
       
  1329         [ this.options.edge_arrow_length, this.options.edge_arrow_width / 2 ],
       
  1330         [ 0, this.options.edge_arrow_width ]
       
  1331     );
       
  1332     this.arrow.__representation = this;
       
  1333     this.text = Rkns.$('<div class="Rk-Label Rk-Edge-Label">').appendTo(this.renderer.labels_$);
       
  1334     this.arrow_angle = 0;
       
  1335     if (this.options.editor_mode) {
       
  1336         this.normal_buttons = [
       
  1337             new Rkns.Renderer.EdgeEditButton(this.renderer, null),
       
  1338             new Rkns.Renderer.EdgeRemoveButton(this.renderer, null),
       
  1339         ];
       
  1340         this.pending_delete_buttons = [
       
  1341             new Rkns.Renderer.EdgeRevertButton(this.renderer, null)
       
  1342         ];
       
  1343         this.all_buttons = this.normal_buttons.concat(this.pending_delete_buttons)
       
  1344         for (var i = 0; i < this.all_buttons.length; i++) {
       
  1345             this.all_buttons[i].source_representation = this;
       
  1346         }
       
  1347         this.active_buttons = [];
       
  1348     } else {
       
  1349         this.active_buttons = this.all_buttons = [];
       
  1350     }
       
  1351     
       
  1352     if (this.renderer.minimap) {
       
  1353         this.renderer.minimap.edge_layer.activate();
       
  1354         this.minimap_line = new paper.Path();
       
  1355         this.minimap_line.add([0,0],[0,0]);
       
  1356         this.minimap_line.__representation = this.renderer.minimap.miniframe.__representation;
       
  1357         this.minimap_line.strokeWidth = 1;
       
  1358     }
       
  1359 }
       
  1360 
       
  1361 Rkns.Renderer.Edge.prototype.redraw = function() {
       
  1362     this.from_representation = this.renderer.getRepresentationByModel(this.model.get("from"));
       
  1363     this.to_representation = this.renderer.getRepresentationByModel(this.model.get("to"));
       
  1364     if (!this.from_representation || !this.to_representation) {
       
  1365         return;
       
  1366     }
       
  1367     var _p0a = this.from_representation.paper_coords,
       
  1368         _p1a = this.to_representation.paper_coords,
       
  1369         _v = _p1a.subtract(_p0a),
       
  1370         _r = _v.length,
       
  1371         _u = _v.divide(_r),
       
  1372         _ortho = new paper.Point([- _u.y, _u.x]),
       
  1373         _group_pos = this.bundle.getPosition(this),
       
  1374         _delta = _ortho.multiply( this.options.edge_gap_in_bundles * _group_pos ),
       
  1375         _p0b = _p0a.add(_delta), /* Adding a 4 px difference */
       
  1376         _p1b = _p1a.add(_delta), /* to differentiate bundled links */
       
  1377         _a = _v.angle,
       
  1378         _textdelta = _ortho.multiply(this.options.edge_label_distance),
       
  1379         _handle = _v.divide(3),
       
  1380         _color = this.model.get("color") || this.model.get("color") || (this.model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan)).get("color");
       
  1381     
       
  1382     if (this.model.get("delete_scheduled") || this.from_representation.model.get("delete_scheduled") || this.to_representation.model.get("delete_scheduled")) {
       
  1383         var opacity = .5;
       
  1384         this.line.dashArray = [2, 2];
       
  1385     } else {
       
  1386         var opacity = 1;
       
  1387         this.line.dashArray = null;
       
  1388     }
       
  1389     
       
  1390     var old_act_btn = this.active_buttons;
       
  1391     
       
  1392     this.active_buttons = this.model.get("delete_scheduled") ? this.pending_delete_buttons : this.normal_buttons;
       
  1393     
       
  1394     if (this.selected && this.renderer.isEditable() && old_act_btn !== this.active_buttons) {
       
  1395         old_act_btn.forEach(function(b) {
       
  1396             b.hide();
       
  1397         });
       
  1398         this.active_buttons.forEach(function(b) {
       
  1399             b.show();
       
  1400         });
       
  1401     }
       
  1402     
       
  1403     this.paper_coords = _p0b.add(_p1b).divide(2);
       
  1404     this.line.strokeColor = _color;
       
  1405     this.line.opacity = opacity;
       
  1406     this.line.segments[0].point = _p0a;
       
  1407     this.line.segments[1].point = this.paper_coords;
       
  1408     this.line.segments[1].handleIn = _handle.multiply(-1);
       
  1409     this.line.segments[1].handleOut = _handle;
       
  1410     this.line.segments[2].point = _p1a;
       
  1411     this.arrow.rotate(_a - this.arrow_angle);
       
  1412     this.arrow.fillColor = _color;
       
  1413     this.arrow.opacity = opacity;
       
  1414     this.arrow.position = this.paper_coords;
       
  1415     this.arrow_angle = _a;
       
  1416     if (_a > 90) {
       
  1417         _a -= 180;
       
  1418         _textdelta = _textdelta.multiply(-1);
       
  1419     }
       
  1420     if (_a < -90) {
       
  1421         _a += 180;
       
  1422         _textdelta = _textdelta.multiply(-1);
       
  1423     }
       
  1424     var _text = this.model.get("title") || this.renkan.translate(this.options.label_untitled_edges) || "";
       
  1425     _text = Rkns.Renderer.shortenText(_text, this.options.node_label_max_length);
       
  1426     this.text.text(_text);
       
  1427     var _textpos = this.paper_coords.add(_textdelta);
       
  1428     this.text.css({
       
  1429         left: _textpos.x,
       
  1430         top: _textpos.y,
       
  1431         transform: "rotate(" + _a + "deg)",
       
  1432         "-moz-transform": "rotate(" + _a + "deg)",
       
  1433         "-webkit-transform": "rotate(" + _a + "deg)",
       
  1434         opacity: opacity
       
  1435     });
       
  1436     this.text_angle = _a;
       
  1437     
       
  1438     var _pc = this.paper_coords;
       
  1439     this.all_buttons.forEach(function(b) {
       
  1440         b.moveTo(_pc);
       
  1441     });
       
  1442     
       
  1443     if (this.renderer.minimap) {
       
  1444         this.minimap_line.strokeColor = _color;
       
  1445         this.minimap_line.segments[0].point = this.renderer.toMinimapCoords(new paper.Point(this.from_representation.model.get("position")));
       
  1446          this.minimap_line.segments[1].point = this.renderer.toMinimapCoords(new paper.Point(this.to_representation.model.get("position")));
       
  1447     }
       
  1448 }
       
  1449 
       
  1450 Rkns.Renderer.Edge.prototype.openEditor = function() {
       
  1451     this.renderer.removeRepresentationsOfType("editor");
       
  1452     var _editor = this.renderer.addRepresentation("EdgeEditor",null);
       
  1453     _editor.source_representation = this;
       
  1454     _editor.draw();
       
  1455 }
       
  1456 
       
  1457 Rkns.Renderer.Edge.prototype.select = function() {
       
  1458     this.selected = true;
       
  1459     this.line.strokeWidth = this.options.selected_edge_stroke_width;
       
  1460     if (this.renderer.isEditable()) {
       
  1461         this.active_buttons.forEach(function(b) {
       
  1462             b.show();
       
  1463         });
       
  1464     }
       
  1465     if (!this.options.editor_mode) {
       
  1466         this.openEditor();
       
  1467     }
       
  1468     this.super("select");
       
  1469 }
       
  1470 
       
  1471 Rkns.Renderer.Edge.prototype.unselect = function(_newTarget) {
       
  1472     if (!_newTarget || _newTarget.source_representation !== this) {
       
  1473         this.selected = false;
       
  1474         if (this.options.editor_mode) {
       
  1475             this.all_buttons.forEach(function(b) {
       
  1476                 b.hide();
       
  1477             });
       
  1478         }
       
  1479         this.line.strokeWidth = this.options.edge_stroke_width;
       
  1480         this.super("unselect");
       
  1481     }
       
  1482 }
       
  1483 
       
  1484 Rkns.Renderer.Edge.prototype.mousedown = function(_event, _isTouch) {
       
  1485     if (_isTouch) {
       
  1486         this.renderer.unselectAll();
       
  1487         this.select();
       
  1488     }
       
  1489 }
       
  1490 
       
  1491 Rkns.Renderer.Edge.prototype.mouseup = function(_event, _isTouch) {
       
  1492     if (!this.renkan.read_only && this.renderer.is_dragging) {
       
  1493         this.from_representation.saveCoords();
       
  1494         this.to_representation.saveCoords();
       
  1495         this.from_representation.is_dragging = false;
       
  1496         this.to_representation.is_dragging = false;
       
  1497     } else {
       
  1498         if (!_isTouch) {
       
  1499             this.openEditor();
       
  1500         }
       
  1501         this.model.trigger("clicked");
       
  1502     }
       
  1503     this.renderer.click_target = null;
       
  1504     this.renderer.is_dragging = false;
       
  1505 }
       
  1506 
       
  1507 Rkns.Renderer.Edge.prototype.paperShift = function(_delta) {
       
  1508     if (this.options.editor_mode) {
       
  1509         if (!this.options.read_only) {
       
  1510             this.from_representation.paperShift(_delta);
       
  1511             this.to_representation.paperShift(_delta);
       
  1512         }
       
  1513     } else {
       
  1514         this.renderer.paperShift(_delta);
       
  1515     }
       
  1516 }
       
  1517 
       
  1518 Rkns.Renderer.Edge.prototype.destroy = function() {
       
  1519     this.super("destroy");
       
  1520     this.line.remove();
       
  1521     this.arrow.remove();
       
  1522     this.text.remove();
       
  1523     if (this.renderer.minimap) {
       
  1524         this.minimap_line.remove();
       
  1525     }
       
  1526     this.all_buttons.forEach(function(b) {
       
  1527         b.destroy();
       
  1528     });
       
  1529     var _this = this;
       
  1530     this.bundle.edges = Rkns._(this.bundle.edges).reject(function(_edge) {
       
  1531         return _edge === _this;
       
  1532     });
       
  1533 }
       
  1534 
       
  1535 /* */
       
  1536 
       
  1537 Rkns.Renderer.TempEdge = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);
       
  1538 
       
  1539 Rkns.Renderer.TempEdge.prototype._init = function() {
       
  1540     this.renderer.edge_layer.activate();
       
  1541     this.type = "Temp-edge";
       
  1542     
       
  1543     var _color = (this.project.get("users").get(this.renkan.current_user) || Rkns.Renderer._USER_PLACEHOLDER(this.renkan)).get("color");
       
  1544     this.line = new paper.Path();
       
  1545     this.line.strokeColor = _color;
       
  1546     this.line.dashArray = [4, 2];
       
  1547     this.line.strokeWidth = this.options.selected_edge_stroke_width;
       
  1548     this.line.add([0,0],[0,0]);
       
  1549     this.line.__representation = this;
       
  1550     this.arrow = new paper.Path();
       
  1551     this.arrow.fillColor = _color;
       
  1552     this.arrow.add(
       
  1553         [ 0, 0 ],
       
  1554         [ this.options.edge_arrow_length, this.options.edge_arrow_width / 2 ],
       
  1555         [ 0, this.options.edge_arrow_width ]
       
  1556     );
       
  1557     this.arrow.__representation = this;
       
  1558     this.arrow_angle = 0;
       
  1559 }
       
  1560 
       
  1561 Rkns.Renderer.TempEdge.prototype.redraw = function() {
       
  1562     var _p0 = this.from_representation.paper_coords,
       
  1563         _p1 = this.end_pos,
       
  1564         _a = _p1.subtract(_p0).angle,
       
  1565         _c = _p0.add(_p1).divide(2);
       
  1566     this.line.segments[0].point = _p0;
       
  1567     this.line.segments[1].point = _p1;
       
  1568     this.arrow.rotate(_a - this.arrow_angle);
       
  1569     this.arrow.position = _c;
       
  1570     this.arrow_angle = _a;
       
  1571 }
       
  1572 
       
  1573 Rkns.Renderer.TempEdge.prototype.paperShift = function(_delta) {
       
  1574     if (!this.renderer.isEditable()) {
       
  1575         this.renderer.removeRepresentation(_this);
       
  1576         paper.view.draw();
       
  1577         return;
       
  1578     }
       
  1579     this.end_pos = this.end_pos.add(_delta);
       
  1580     var _hitResult = paper.project.hitTest(this.end_pos);
       
  1581     this.renderer.findTarget(_hitResult);
       
  1582     this.redraw();
       
  1583 }
       
  1584 
       
  1585 Rkns.Renderer.TempEdge.prototype.mouseup = function(_event, _isTouch) {
       
  1586     var _hitResult = paper.project.hitTest(_event.point),
       
  1587         _model = this.from_representation.model,
       
  1588         _endDrag = true;
       
  1589     if (_hitResult && typeof _hitResult.item.__representation !== "undefined") {
       
  1590         var _target = _hitResult.item.__representation;
       
  1591         if (_target.type.substr(0,4) === "Node") {
       
  1592             var _destmodel = _target.model || _target.source_representation.model;
       
  1593             if (_model !== _destmodel) {
       
  1594                 var _data = {
       
  1595                     id: Rkns.Utils.getUID('edge'),
       
  1596                     created_by: this.renkan.current_user,
       
  1597                     from: _model,
       
  1598                     to: _destmodel
       
  1599                 };
       
  1600                 if (this.renderer.isEditable()) {
       
  1601                     this.project.addEdge(_data);
       
  1602                 }
       
  1603             }
       
  1604         }
       
  1605         
       
  1606         if (_model === _target.model || (_target.source_representation && _target.source_representation.model === _model)) {
       
  1607             _endDrag = false;
       
  1608             this.renderer.is_dragging = true;
       
  1609         }
       
  1610     }
       
  1611     if (_endDrag) {
       
  1612         this.renderer.click_target = null;
       
  1613         this.renderer.is_dragging = false;
       
  1614         this.renderer.removeRepresentation(this);
       
  1615         paper.view.draw();
       
  1616     }
       
  1617 }
       
  1618 
       
  1619 Rkns.Renderer.TempEdge.prototype.destroy = function() {
       
  1620     this.arrow.remove();
       
  1621     this.line.remove();
       
  1622 }
       
  1623 
       
  1624 /* */
       
  1625 
       
  1626 Rkns.Renderer._BaseEditor = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);
       
  1627 
       
  1628 Rkns.Renderer._BaseEditor.prototype._init = function() {
       
  1629     this.renderer.buttons_layer.activate();
       
  1630     this.type = "editor";
       
  1631     this.editor_block = new paper.Path();
       
  1632     var _pts = Rkns._(Rkns._.range(8)).map(function() {return [0,0]});
       
  1633     this.editor_block.add.apply(this.editor_block, _pts);
       
  1634     this.editor_block.strokeWidth = this.options.tooltip_border_width;
       
  1635     this.editor_block.strokeColor = this.options.tooltip_border_color;
       
  1636     this.editor_block.opacity = .8;
       
  1637     this.editor_$ = Rkns.$('<div>')
       
  1638         .appendTo(this.renderer.editor_$)
       
  1639         .css({
       
  1640             position: "absolute",
       
  1641             opacity: .8
       
  1642         })
       
  1643         .hide();
       
  1644 }
       
  1645 
       
  1646 Rkns.Renderer._BaseEditor.prototype.destroy = function() {
       
  1647     this.editor_block.remove();
       
  1648     this.editor_$.remove();
       
  1649 }
       
  1650 
       
  1651 /* */
       
  1652 
       
  1653 Rkns.Renderer.NodeEditor = Rkns.Utils.inherit(Rkns.Renderer._BaseEditor);
       
  1654 
       
  1655 Rkns.Renderer.NodeEditor.prototype.template = Rkns._.template(
       
  1656     '<h2><span class="Rk-CloseX">&times;</span><%-renkan.translate("Edit Node")%></span></h2>'
       
  1657     + '<p><label><%-renkan.translate("Title:")%></label><input class="Rk-Edit-Title" type="text" value="<%-node.title%>"/></p>'
       
  1658     + '<p><label><%-renkan.translate("URI:")%></label><input class="Rk-Edit-URI" type="text" value="<%-node.uri%>"/><a class="Rk-Edit-Goto" href="<%-node.uri%>" target="_blank"></a></p>'
       
  1659     + '<p><label><%-renkan.translate("Description:")%></label><textarea class="Rk-Edit-Description"><%-node.description%></textarea></p>'
       
  1660     + '<p><span class="Rk-Editor-Label"><%-renkan.translate("Size:")%></span><a href="#" class="Rk-Edit-Size-Down">-</a><span class="Rk-Edit-Size-Value"><%-node.size%></span><a href="#" class="Rk-Edit-Size-Up">+</a></p>'
       
  1661     + '<div class="Rk-Editor-p"><span class="Rk-Editor-Label"><%-renkan.translate("Node color:")%></span><div class="Rk-Edit-ColorPicker-Wrapper"><span class="Rk-Edit-Color" style="background:<%-node.color%>;"><span class="Rk-Edit-ColorTip"></span></span><ul class="Rk-Edit-ColorPicker">'
       
  1662     + '<% _(Rkns.pickerColors).each(function(c) { %><li data-color="<%=c%>" style="background: <%=c%>"></li><% }); %></ul><span class="Rk-Edit-ColorPicker-Text"><%- renkan.translate("Choose color") %></span></div></div>'
       
  1663     + '<img class="Rk-Edit-ImgPreview" src="<%-node.image || node.image_placeholder%>" />'
       
  1664     + '<p><label><%-renkan.translate("Image URL:")%></label><input class="Rk-Edit-Image" type="text" value="<%-node.image%>"/></p>'
       
  1665     + '<p><label><%-renkan.translate("Choose Image File:")%></label><input class="Rk-Edit-Image-File" type="file" accept="image/*"/></p>'    
       
  1666     + '<% if (node.has_creator) { %><p><span class="Rk-Editor-Label"><%-renkan.translate("Created by:")%></span> <span class="Rk-UserColor" style="background:<%-node.created_by_color%>;"></span><%- Rkns.Renderer.shortenText(node.created_by_title, 25) %></p><% } %>'
       
  1667 );
       
  1668 
       
  1669 Rkns.Renderer.NodeEditor.prototype.readOnlyTemplate = Rkns._.template(
       
  1670     '<h2><span class="Rk-CloseX">&times;</span><span class="Rk-UserColor" style="background:<%-node.color%>;"></span>'
       
  1671     + '<span class="Rk-Display-Title"><% if (node.uri) { %><a href="<%-node.uri%>" target="_blank"><% } %><%-node.title%><% if (node.uri) { %></a><% } %></span></h2>'
       
  1672     + '<% if (node.uri) { %><p class="Rk-Display-URI"><a href="<%-node.uri%>" target="_blank"><%-node.short_uri%></a></p><% } %>'
       
  1673     + '<p><%-node.description%></p>'
       
  1674     + '<% if (node.image) { %><img class="Rk-Display-ImgPreview" src="<%-node.image%>" /><% } %>'
       
  1675     + '<% if (node.has_creator) { %><p><span class="Rk-Editor-Label"><%-renkan.translate("Created by:")%></span><span class="Rk-UserColor" style="background:<%-node.created_by_color%>;"></span><%- Rkns.Renderer.shortenText(node.created_by_title, 25) %></p><% } %>'
       
  1676 );
       
  1677 
       
  1678 Rkns.Renderer.NodeEditor.prototype.draw = function() {
       
  1679     var _model = this.source_representation.model,
       
  1680         _created_by = _model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan),
       
  1681         _template = (this.renderer.isEditable() ? this.template : this.readOnlyTemplate ),
       
  1682         _image_placeholder = this.options.static_url + "img/image-placeholder.png",
       
  1683         _size = (_model.get("size") || 0);
       
  1684     this.editor_$
       
  1685         .html(_template({
       
  1686             node: {
       
  1687                 has_creator: !!_model.get("created_by"),
       
  1688                 title: _model.get("title"),
       
  1689                 uri: _model.get("uri"),
       
  1690                 short_uri:  Rkns.Renderer.shortenText((_model.get("uri") || "").replace(/^(https?:\/\/)?(www\.)?/,'').replace(/\/$/,''),40),
       
  1691                 description: _model.get("description"),
       
  1692                 image: _model.get("image") || "",
       
  1693                 image_placeholder: _image_placeholder,
       
  1694                 color: _model.get("color") || _created_by.get("color"),
       
  1695                 created_by_color: _created_by.get("color"),
       
  1696                 created_by_title: _created_by.get("title"),
       
  1697                 size: (_size > 0 ? "+" : "") + _size
       
  1698             },
       
  1699             renkan: this.renkan
       
  1700         }));
       
  1701     this.redraw();
       
  1702     var _this = this,
       
  1703         closeEditor = function() {
       
  1704             _this.renderer.removeRepresentation(_this);
       
  1705             paper.view.draw();
       
  1706         }
       
  1707         
       
  1708     this.editor_$.find(".Rk-CloseX").click(closeEditor);
       
  1709     
       
  1710     if (this.renderer.isEditable()) {
       
  1711         
       
  1712         var onFieldChange = Rkns._(function() {
       
  1713             Rkns._(function() {
       
  1714                 if (_this.renderer.isEditable()) {
       
  1715                     var _uri = _this.editor_$.find(".Rk-Edit-URI").val(),
       
  1716                         _image = _this.editor_$.find(".Rk-Edit-Image").val();
       
  1717                     _this.editor_$.find(".Rk-Edit-ImgPreview").attr("src", _image || _image_placeholder);
       
  1718                     _this.editor_$.find(".Rk-Edit-Goto").attr("href",_uri);
       
  1719                     var _data = {
       
  1720                         title: _this.editor_$.find(".Rk-Edit-Title").val(),
       
  1721                         description: _this.editor_$.find(".Rk-Edit-Description").val(),
       
  1722                         uri: _uri,
       
  1723                         image: _image
       
  1724                     }
       
  1725                     _model.set(_data);
       
  1726                     _this.redraw();
       
  1727                 } else {
       
  1728                     closeEditor();
       
  1729                 }
       
  1730                 
       
  1731             }).defer();
       
  1732         }).throttle(500);
       
  1733         
       
  1734         this.editor_$.on("keyup", function(_e) {
       
  1735             if (_e.keyCode === 27) {
       
  1736                 closeEditor();
       
  1737             }
       
  1738         });
       
  1739         
       
  1740         this.editor_$.find("input, textarea").on("change keyup paste", onFieldChange);
       
  1741         
       
  1742         this.editor_$.find(".Rk-Edit-Image-File").change(function() {
       
  1743             if (this.files.length) {
       
  1744                 var f = this.files[0],
       
  1745                     fr = new FileReader();
       
  1746                 if (f.type.substr(0,5) !== "image") {
       
  1747                     alert(_this.renkan.translate("This file is not an image"));
       
  1748                     return;
       
  1749                 }
       
  1750                 if (f.size > (Rkns.Renderer._IMAGE_MAX_KB * 1024)) {
       
  1751                     alert(_this.renkan.translate("Image size must be under ")+Rkns.Renderer._IMAGE_MAX_KB+_this.renkan.translate("KB"));
       
  1752                     return;
       
  1753                 }
       
  1754                 fr.onload = function(e) {
       
  1755                     _this.editor_$.find(".Rk-Edit-Image").val(e.target.result);
       
  1756                     onFieldChange();
       
  1757                 }
       
  1758                 fr.readAsDataURL(f);
       
  1759             }
       
  1760         });
       
  1761         this.editor_$.find(".Rk-Edit-Title")[0].focus();
       
  1762         
       
  1763         var _picker = _this.editor_$.find(".Rk-Edit-ColorPicker");
       
  1764         
       
  1765         this.editor_$.find(".Rk-Edit-ColorPicker-Wrapper").hover(
       
  1766             function(_e) {
       
  1767                 _e.preventDefault();
       
  1768                 _picker.show();
       
  1769             },
       
  1770             function(_e) {
       
  1771                 _e.preventDefault();
       
  1772                 _picker.hide();
       
  1773             }
       
  1774         );
       
  1775         
       
  1776         _picker.find("li").hover(
       
  1777             function(_e) {
       
  1778                 _e.preventDefault();
       
  1779                 _this.editor_$.find(".Rk-Edit-Color").css("background", $(this).attr("data-color"));
       
  1780             },
       
  1781             function(_e) {
       
  1782                 _e.preventDefault();
       
  1783                 _this.editor_$.find(".Rk-Edit-Color").css("background", _model.get("color") || (_model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(_this.renkan)).get("color"))
       
  1784             }
       
  1785         ).click(function(_e) {
       
  1786             _e.preventDefault();
       
  1787             if (_this.renderer.isEditable()) {
       
  1788                 _model.set("color", $(this).attr("data-color"));
       
  1789                 _picker.hide();
       
  1790                 paper.view.draw();
       
  1791             } else {
       
  1792                 closeEditor();
       
  1793             }
       
  1794         });
       
  1795         
       
  1796         function shiftSize(n) {
       
  1797             if (_this.renderer.isEditable()) {
       
  1798                 var _newsize = n+(_model.get("size") || 0);
       
  1799                 _this.editor_$.find(".Rk-Edit-Size-Value").text((_newsize > 0 ? "+" : "") + _newsize);
       
  1800                 _model.set("size", _newsize);
       
  1801                 paper.view.draw();
       
  1802             } else {
       
  1803                 closeEditor();
       
  1804             }
       
  1805         }
       
  1806         
       
  1807         this.editor_$.find(".Rk-Edit-Size-Down").click(function() {
       
  1808             shiftSize(-1);
       
  1809             return false;
       
  1810         });
       
  1811         this.editor_$.find(".Rk-Edit-Size-Up").click(function() {
       
  1812             shiftSize(1);
       
  1813             return false;
       
  1814         });
       
  1815     }
       
  1816     this.editor_$.find("img").load(function() {
       
  1817         _this.redraw();
       
  1818     });
       
  1819 }
       
  1820 
       
  1821 Rkns.Renderer.NodeEditor.prototype.redraw = function() {
       
  1822     var _coords = this.source_representation.paper_coords;
       
  1823     Rkns.Renderer.drawEditBox(this.options, _coords, this.editor_block, this.source_representation.circle_radius * .75, this.editor_$);
       
  1824     this.editor_$.show();
       
  1825     paper.view.draw();
       
  1826 }
       
  1827 
       
  1828 /* */
       
  1829 
       
  1830 Rkns.Renderer.EdgeEditor = Rkns.Utils.inherit(Rkns.Renderer._BaseEditor);
       
  1831 
       
  1832 Rkns.Renderer.EdgeEditor.prototype.template = Rkns._.template(
       
  1833     '<h2><span class="Rk-CloseX">&times;</span><%-renkan.translate("Edit Edge")%></span></h2>'
       
  1834     + '<p><label><%-renkan.translate("Title:")%></label><input class="Rk-Edit-Title" type="text" value="<%-edge.title%>"/></p>'
       
  1835     + '<p><label><%-renkan.translate("URI:")%></label><input class="Rk-Edit-URI" type="text" value="<%-edge.uri%>"/><a class="Rk-Edit-Goto" href="<%-edge.uri%>" target="_blank"></a></p>'
       
  1836     + '<% if (properties.length) { %><p><label><%-renkan.translate("Choose from vocabulary:")%></label><select class="Rk-Edit-Vocabulary">'
       
  1837     + '<% _(properties).each(function(ontology) { %><option class="Rk-Edit-Vocabulary-Class" value=""><%- renkan.translate(ontology.label) %></option>'
       
  1838     + '<% _(ontology.properties).each(function(property) { var uri = ontology["base-uri"] + property.uri; %><option class="Rk-Edit-Vocabulary-Property" value="<%- uri %>'
       
  1839     + '"<% if (uri === edge.uri) { %> selected<% } %>><%- renkan.translate(property.label) %></option>'
       
  1840     + '<% }) %><% }) %></select></p><% } %>'
       
  1841     + '<div class="Rk-Editor-p"><span class="Rk-Editor-Label"><%-renkan.translate("Edge color:")%></span><div class="Rk-Edit-ColorPicker-Wrapper"><span class="Rk-Edit-Color" style="background:<%-edge.color%>;"><span class="Rk-Edit-ColorTip"></span></span><ul class="Rk-Edit-ColorPicker">'
       
  1842     + '<% _(Rkns.pickerColors).each(function(c) { %><li data-color="<%=c%>" style="background: <%=c%>"></li><% }); %></ul><span class="Rk-Edit-ColorPicker-Text"><%- renkan.translate("Choose color") %></span></div></div>'
       
  1843     + '<p><span class="Rk-Edit-Direction"><%- renkan.translate("Change edge direction") %></span></p>'
       
  1844     + '<p><span class="Rk-Editor-Label"><%-renkan.translate("From:")%></span><span class="Rk-UserColor" style="background:<%-edge.from_color%>;"></span><%- Rkns.Renderer.shortenText(edge.from_title, 25) %></p>'
       
  1845     + '<p><span class="Rk-Editor-Label"><%-renkan.translate("To:")%></span><span class="Rk-UserColor" style="background:<%-edge.to_color%>;"></span><%- Rkns.Renderer.shortenText(edge.to_title, 25) %></p>'
       
  1846     + '<% if (edge.has_creator) { %><p><span class="Rk-Editor-Label"><%-renkan.translate("Created by:")%></span><span class="Rk-UserColor" style="background:<%-edge.created_by_color%>;"></span><%- Rkns.Renderer.shortenText(edge.created_by_title, 25) %></p><% } %>'
       
  1847 );
       
  1848 
       
  1849 Rkns.Renderer.EdgeEditor.prototype.readOnlyTemplate = Rkns._.template(
       
  1850     '<h2><span class="Rk-CloseX">&times;</span><span class="Rk-UserColor" style="background:<%-edge.color%>;"></span>'
       
  1851     + '<span class="Rk-Display-Title"><% if (edge.uri) { %><a href="<%-edge.uri%>" target="_blank"><% } %><%-edge.title%><% if (edge.uri) { %></a><% } %></span></h2>'
       
  1852     + '<% if (edge.uri) { %><p class="Rk-Display-URI"><a href="<%-edge.uri%>" target="_blank"><%-edge.short_uri%></a></p><% } %>'
       
  1853     + '<p><%-edge.description%></p>'
       
  1854     + '<p><span class="Rk-Editor-Label"><%-renkan.translate("From:")%></span><span class="Rk-UserColor" style="background:<%-edge.from_color%>;"></span><%- Rkns.Renderer.shortenText(edge.from_title, 25) %></p>'
       
  1855     + '<p><span class="Rk-Editor-Label"><%-renkan.translate("To:")%></span><span class="Rk-UserColor" style="background:<%-edge.to_color%>;"></span><%- Rkns.Renderer.shortenText(edge.to_title, 25) %></p>'
       
  1856     + '<% if (edge.has_creator) { %><p><span class="Rk-Editor-Label"><%-renkan.translate("Created by:")%></span><span class="Rk-UserColor" style="background:<%-edge.created_by_color%>;"></span><%- Rkns.Renderer.shortenText(edge.created_by_title, 25) %></p><% } %>'
       
  1857 );
       
  1858 
       
  1859 Rkns.Renderer.EdgeEditor.prototype.draw = function() {
       
  1860     var _model = this.source_representation.model,
       
  1861         _from_model = _model.get("from"),
       
  1862         _to_model = _model.get("to"),
       
  1863         _created_by = _model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan),
       
  1864         _template = (this.renderer.isEditable() ? this.template : this.readOnlyTemplate);
       
  1865     this.editor_$
       
  1866         .html(_template({
       
  1867             edge: {
       
  1868                 has_creator: !!_model.get("created_by"),
       
  1869                 title: _model.get("title"),
       
  1870                 uri: _model.get("uri"),
       
  1871                 short_uri:  Rkns.Renderer.shortenText((_model.get("uri") || "").replace(/^(https?:\/\/)?(www\.)?/,'').replace(/\/$/,''),40),
       
  1872                 description: _model.get("description"),
       
  1873                 color: _model.get("color") || _created_by.get("color"),
       
  1874                 from_title: _from_model.get("title"),
       
  1875                 to_title: _to_model.get("title"),
       
  1876                 from_color: _from_model.get("color") || (_from_model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan)).get("color"),
       
  1877                 to_color: _to_model.get("color") || (_to_model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan)).get("color"),
       
  1878                 created_by_color: _created_by.get("color"),
       
  1879                 created_by_title: _created_by.get("title")
       
  1880             },
       
  1881             renkan: this.renkan,
       
  1882             properties: this.options.properties
       
  1883         }));
       
  1884     this.redraw();
       
  1885     var _this = this,
       
  1886         closeEditor = function() {
       
  1887             _this.renderer.removeRepresentation(_this);
       
  1888             paper.view.draw();
       
  1889         }
       
  1890     this.editor_$.find(".Rk-CloseX").click(closeEditor);
       
  1891     
       
  1892     if (this.renderer.isEditable()) {
       
  1893         
       
  1894         var onFieldChange = Rkns._(function() {
       
  1895             Rkns._(function() {
       
  1896                 if (_this.renderer.isEditable()) {
       
  1897                     _this.editor_$.find(".Rk-Edit-Goto").attr("href",_this.editor_$.find(".Rk-Edit-URI").val());
       
  1898                     var _data = {
       
  1899                         title: _this.editor_$.find(".Rk-Edit-Title").val(),
       
  1900                         uri: _this.editor_$.find(".Rk-Edit-URI").val()
       
  1901                     }
       
  1902                     _model.set(_data);
       
  1903                     paper.view.draw();
       
  1904                 } else {
       
  1905                     closeEditor();
       
  1906                 }
       
  1907             }).defer();
       
  1908         }).throttle(500);
       
  1909         
       
  1910         this.editor_$.on("keyup", function(_e) {
       
  1911             if (_e.keyCode === 27) {
       
  1912                 closeEditor();
       
  1913             }
       
  1914         });
       
  1915         
       
  1916         this.editor_$.find("input").on("keyup change paste", onFieldChange);
       
  1917         
       
  1918         this.editor_$.find(".Rk-Edit-Vocabulary").change(function() {
       
  1919             var e = $(this),
       
  1920                 v = e.val();
       
  1921             if (v) {
       
  1922                 _this.editor_$.find(".Rk-Edit-Title").val(e.find(":selected").text());
       
  1923                 _this.editor_$.find(".Rk-Edit-URI").val(v);
       
  1924                 onFieldChange();
       
  1925             }
       
  1926         });
       
  1927         this.editor_$.find(".Rk-Edit-Direction").click(function() {
       
  1928             if (_this.renderer.isEditable()) {
       
  1929                 _model.set({
       
  1930                     from: _model.get("to"),
       
  1931                     to: _model.get("from")
       
  1932                 });
       
  1933                 _this.draw();
       
  1934             } else {
       
  1935                 closeEditor();
       
  1936             }
       
  1937         });
       
  1938         
       
  1939         var _picker = _this.editor_$.find(".Rk-Edit-ColorPicker");
       
  1940         
       
  1941         this.editor_$.find(".Rk-Edit-ColorPicker-Wrapper").hover(
       
  1942             function(_e) {
       
  1943                 _e.preventDefault();
       
  1944                 _picker.show();
       
  1945             },
       
  1946             function(_e) {
       
  1947                 _e.preventDefault();
       
  1948                 _picker.hide();
       
  1949             }
       
  1950         );
       
  1951         
       
  1952         _picker.find("li").hover(
       
  1953             function(_e) {
       
  1954                 _e.preventDefault();
       
  1955                 _this.editor_$.find(".Rk-Edit-Color").css("background", $(this).attr("data-color"));
       
  1956             },
       
  1957             function(_e) {
       
  1958                 _e.preventDefault();
       
  1959                 _this.editor_$.find(".Rk-Edit-Color").css("background", _model.get("color") || (_model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(_this.renkan)).get("color"))
       
  1960             }
       
  1961         ).click(function(_e) {
       
  1962             _e.preventDefault();
       
  1963             if (_this.renderer.isEditable()) {
       
  1964                 _model.set("color", $(this).attr("data-color"));
       
  1965                 _picker.hide();
       
  1966                 paper.view.draw();
       
  1967             } else {
       
  1968                 closeEditor();
       
  1969             }
       
  1970         });
       
  1971     }
       
  1972 }
       
  1973 
       
  1974 Rkns.Renderer.EdgeEditor.prototype.redraw = function() {
       
  1975     var _coords = this.source_representation.paper_coords;
       
  1976     Rkns.Renderer.drawEditBox(this.options, _coords, this.editor_block, 5, this.editor_$);
       
  1977     this.editor_$.show();
       
  1978     paper.view.draw();
       
  1979 }
       
  1980 
       
  1981 /* */
       
  1982 
       
  1983 Rkns.Renderer._NodeButton = Rkns.Utils.inherit(Rkns.Renderer._BaseButton);
       
  1984 
       
  1985 Rkns.Renderer._NodeButton.prototype.setSectorSize = function() {
       
  1986     var sectorInner = this.source_representation.circle_radius;
       
  1987     if (sectorInner !== this.lastSectorInner) {
       
  1988         if (this.sector) {
       
  1989             this.sector.destroy();
       
  1990         }
       
  1991         this.sector = this.renderer.drawSector(
       
  1992             this, 1 + sectorInner,
       
  1993             Rkns.Renderer._NODE_BUTTON_WIDTH + sectorInner,
       
  1994             this.startAngle,
       
  1995             this.endAngle,
       
  1996             1,
       
  1997             this.imageName,
       
  1998             this.renkan.translate(this.text)
       
  1999         );
       
  2000         this.lastSectorInner = sectorInner;
       
  2001     }
       
  2002 }
       
  2003 
       
  2004 /* */
       
  2005 
       
  2006 Rkns.Renderer.NodeEditButton = Rkns.Utils.inherit(Rkns.Renderer._NodeButton);
       
  2007 
       
  2008 Rkns.Renderer.NodeEditButton.prototype._init = function() {
       
  2009     this.type = "Node-edit-button";
       
  2010     this.lastSectorInner = 0;
       
  2011     this.startAngle = -135;
       
  2012     this.endAngle = -45;
       
  2013     this.imageName = "edit";
       
  2014     this.text = "Edit";
       
  2015 }
       
  2016 
       
  2017 Rkns.Renderer.NodeEditButton.prototype.mouseup = function() {
       
  2018     if (!this.renderer.is_dragging) {
       
  2019         this.source_representation.openEditor();
       
  2020     }
       
  2021 }
       
  2022 
       
  2023 /* */
       
  2024 
       
  2025 Rkns.Renderer.NodeRemoveButton = Rkns.Utils.inherit(Rkns.Renderer._NodeButton);
       
  2026 
       
  2027 Rkns.Renderer.NodeRemoveButton.prototype._init = function() {
       
  2028     this.type = "Node-remove-button";
       
  2029     this.lastSectorInner = 0;
       
  2030     this.startAngle = 0;
       
  2031     this.endAngle = 90;
       
  2032     this.imageName = "remove";
       
  2033     this.text = "Remove";
       
  2034 }
       
  2035 
       
  2036 Rkns.Renderer.NodeRemoveButton.prototype.mouseup = function() {
       
  2037     this.renderer.click_target = null;
       
  2038     this.renderer.is_dragging = false;
       
  2039     this.renderer.removeRepresentationsOfType("editor");
       
  2040     if (this.renderer.isEditable()) {
       
  2041         var delid = Rkns.Utils.getUID("delete");
       
  2042         this.renderer.delete_list.push({
       
  2043             id: delid,
       
  2044             time: new Date().valueOf() + this.options.element_delete_delay
       
  2045         });
       
  2046         this.source_representation.model.set("delete_scheduled", delid);
       
  2047     }
       
  2048 }
       
  2049 
       
  2050 /* */
       
  2051 
       
  2052 Rkns.Renderer.NodeRevertButton = Rkns.Utils.inherit(Rkns.Renderer._NodeButton);
       
  2053 
       
  2054 Rkns.Renderer.NodeRevertButton.prototype._init = function() {
       
  2055     this.type = "Node-revert-button";
       
  2056     this.lastSectorInner = 0;
       
  2057     this.startAngle = -135;
       
  2058     this.endAngle = 135;
       
  2059     this.imageName = "revert";
       
  2060     this.text = "Cancel deletion";
       
  2061 }
       
  2062 
       
  2063 Rkns.Renderer.NodeRevertButton.prototype.mouseup = function() {
       
  2064     this.renderer.click_target = null;
       
  2065     this.renderer.is_dragging = false;
       
  2066     if (this.renderer.isEditable()) {
       
  2067         this.source_representation.model.unset("delete_scheduled");
       
  2068     }
       
  2069 }
       
  2070 
       
  2071 /* */
       
  2072 
       
  2073 Rkns.Renderer.NodeLinkButton = Rkns.Utils.inherit(Rkns.Renderer._NodeButton);
       
  2074 
       
  2075 Rkns.Renderer.NodeLinkButton.prototype._init = function() {
       
  2076     this.type = "Node-link-button";
       
  2077     this.lastSectorInner = 0;
       
  2078     this.startAngle = 90;
       
  2079     this.endAngle = 180;
       
  2080     this.imageName = "link";
       
  2081     this.text = "Link to another node";
       
  2082 }
       
  2083 
       
  2084 Rkns.Renderer.NodeLinkButton.prototype.mousedown = function(_event, _isTouch) {
       
  2085     if (this.renderer.isEditable()) {
       
  2086         var _off = this.renderer.canvas_$.offset(),
       
  2087             _point = new paper.Point([
       
  2088                 _event.pageX - _off.left,
       
  2089                 _event.pageY - _off.top
       
  2090             ]);
       
  2091         this.renderer.click_target = null;
       
  2092         this.renderer.removeRepresentationsOfType("editor");
       
  2093         this.renderer.addTempEdge(this.source_representation, _point);
       
  2094     }
       
  2095 }
       
  2096 
       
  2097 /* */
       
  2098 
       
  2099 Rkns.Renderer.NodeEnlargeButton = Rkns.Utils.inherit(Rkns.Renderer._NodeButton);
       
  2100 
       
  2101 Rkns.Renderer.NodeEnlargeButton.prototype._init = function() {
       
  2102     this.type = "Node-enlarge-button";
       
  2103     this.lastSectorInner = 0;
       
  2104     this.startAngle = -45;
       
  2105     this.endAngle = 0;
       
  2106     this.imageName = "enlarge";
       
  2107     this.text = "Enlarge";
       
  2108 }
       
  2109 
       
  2110 Rkns.Renderer.NodeEnlargeButton.prototype.mouseup = function() {
       
  2111     var _newsize = 1 + (this.source_representation.model.get("size") || 0);
       
  2112     this.source_representation.model.set("size", _newsize);
       
  2113     this.source_representation.select();
       
  2114     this.select();
       
  2115     paper.view.draw();
       
  2116 }
       
  2117 
       
  2118 /* */
       
  2119 
       
  2120 Rkns.Renderer.NodeShrinkButton = Rkns.Utils.inherit(Rkns.Renderer._NodeButton);
       
  2121 
       
  2122 Rkns.Renderer.NodeShrinkButton.prototype._init = function() {
       
  2123     this.type = "Node-shrink-button";
       
  2124     this.lastSectorInner = 0;
       
  2125     this.startAngle = -180;
       
  2126     this.endAngle = -135;
       
  2127     this.imageName = "shrink";
       
  2128     this.text = "Shrink";
       
  2129 }
       
  2130 
       
  2131 Rkns.Renderer.NodeShrinkButton.prototype.mouseup = function() {
       
  2132     var _newsize = -1 + (this.source_representation.model.get("size") || 0);
       
  2133     this.source_representation.model.set("size", _newsize);
       
  2134     this.source_representation.select();
       
  2135     this.select();
       
  2136     paper.view.draw();
       
  2137 }
       
  2138 
       
  2139 /* */
       
  2140 
       
  2141 Rkns.Renderer.EdgeEditButton = Rkns.Utils.inherit(Rkns.Renderer._BaseButton);
       
  2142 
       
  2143 Rkns.Renderer.EdgeEditButton.prototype._init = function() {
       
  2144     this.type = "Edge-edit-button";
       
  2145     this.sector = this.renderer.drawSector(this, Rkns.Renderer._EDGE_BUTTON_INNER, Rkns.Renderer._EDGE_BUTTON_OUTER, -270, -90, 1, "edit", this.renkan.translate("Edit"));
       
  2146 }
       
  2147 
       
  2148 Rkns.Renderer.EdgeEditButton.prototype.mouseup = function() {
       
  2149     if (!this.renderer.is_dragging) {
       
  2150         this.source_representation.openEditor();
       
  2151     }
       
  2152 }
       
  2153 
       
  2154 /* */
       
  2155 
       
  2156 Rkns.Renderer.EdgeRemoveButton = Rkns.Utils.inherit(Rkns.Renderer._BaseButton);
       
  2157 
       
  2158 Rkns.Renderer.EdgeRemoveButton.prototype._init = function() {
       
  2159     this.type = "Edge-remove-button";
       
  2160     this.sector = this.renderer.drawSector(this, Rkns.Renderer._EDGE_BUTTON_INNER, Rkns.Renderer._EDGE_BUTTON_OUTER, -90, 90, 1, "remove", this.renkan.translate("Remove"));
       
  2161 }
       
  2162 
       
  2163 Rkns.Renderer.EdgeRemoveButton.prototype.mouseup = function() {
       
  2164     this.renderer.click_target = null;
       
  2165     this.renderer.is_dragging = false;
       
  2166     this.renderer.removeRepresentationsOfType("editor");
       
  2167     if (this.renderer.isEditable()) {
       
  2168         var delid = Rkns.Utils.getUID("delete");
       
  2169         this.renderer.delete_list.push({
       
  2170             id: delid,
       
  2171             time: new Date().valueOf() + this.options.element_delete_delay
       
  2172         });
       
  2173         this.source_representation.model.set("delete_scheduled", delid);
       
  2174     }
       
  2175 }
       
  2176 
       
  2177 /* */
       
  2178 
       
  2179 Rkns.Renderer.EdgeRevertButton = Rkns.Utils.inherit(Rkns.Renderer._BaseButton);
       
  2180 
       
  2181 Rkns.Renderer.EdgeRevertButton.prototype._init = function() {
       
  2182     this.type = "Edge-revert-button";
       
  2183     this.sector = this.renderer.drawSector(this, Rkns.Renderer._EDGE_BUTTON_INNER, Rkns.Renderer._EDGE_BUTTON_OUTER, -135, 135, 1, "revert", this.renkan.translate("Cancel deletion"));
       
  2184 }
       
  2185 
       
  2186 Rkns.Renderer.EdgeRevertButton.prototype.mouseup = function() {
       
  2187     this.renderer.click_target = null;
       
  2188     this.renderer.is_dragging = false;
       
  2189     if (this.renderer.isEditable()) {
       
  2190         this.source_representation.model.unset("delete_scheduled");
       
  2191     }
       
  2192 }
       
  2193 
       
  2194 /* */
       
  2195 
       
  2196 Rkns.Renderer.MiniFrame = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);
       
  2197 
       
  2198 Rkns.Renderer.MiniFrame.prototype.paperShift = function(_delta) {
       
  2199     this.renderer.offset = this.renderer.offset.subtract(_delta.divide(this.renderer.minimap.scale).multiply(this.renderer.scale));
       
  2200     this.renderer.redraw();
       
  2201 }
       
  2202 
       
  2203 Rkns.Renderer.MiniFrame.prototype.mouseup = function(_delta) {
       
  2204     this.renderer.click_target = null;
       
  2205     this.renderer.is_dragging = false;
       
  2206 }
       
  2207 
       
  2208 /* */
       
  2209 
       
  2210 Rkns.Renderer.Scene = function(_renkan) {
       
  2211     this.renkan = _renkan;
       
  2212     this.$ = Rkns.$(".Rk-Render");
       
  2213     this.representations = [];
       
  2214     this.$.html(this.template(_renkan));
       
  2215     this.onStatusChange();
       
  2216     this.canvas_$ = this.$.find(".Rk-Canvas");
       
  2217     this.labels_$ = this.$.find(".Rk-Labels");
       
  2218     this.editor_$ = this.$.find(".Rk-Editor");
       
  2219     this.notif_$ = this.$.find(".Rk-Notifications");
       
  2220     paper.setup(this.canvas_$[0]);
       
  2221     this.scale = 1;
       
  2222     this.offset = paper.view.center;
       
  2223     this.totalScroll = 0;
       
  2224     this.mouse_down = false;
       
  2225     this.click_target = null;
       
  2226     this.selected_target = null;
       
  2227     this.edge_layer = new paper.Layer();
       
  2228     this.node_layer = new paper.Layer();
       
  2229     this.buttons_layer = new paper.Layer();
       
  2230     this.delete_list = [];
       
  2231     
       
  2232     if (_renkan.options.show_minimap) {
       
  2233         this.minimap = {
       
  2234             background_layer: new paper.Layer(),
       
  2235             edge_layer: new paper.Layer(),
       
  2236             node_layer: new paper.Layer(),
       
  2237             node_group: new paper.Group(),
       
  2238             size: new paper.Size( _renkan.options.minimap_width, _renkan.options.minimap_height )
       
  2239         }
       
  2240         
       
  2241         this.minimap.background_layer.activate();
       
  2242         this.minimap.topleft = paper.view.bounds.bottomRight.subtract(this.minimap.size);
       
  2243         this.minimap.rectangle = new paper.Path.Rectangle(this.minimap.topleft.subtract([2,2]), this.minimap.size.add([4,4]));
       
  2244         this.minimap.rectangle.fillColor = _renkan.options.minimap_background_color;
       
  2245         this.minimap.rectangle.strokeColor = _renkan.options.minimap_border_color;
       
  2246         this.minimap.rectangle.strokeWidth = 4;
       
  2247         this.minimap.offset = new paper.Point(this.minimap.size.divide(2));
       
  2248         this.minimap.scale = .1;
       
  2249         
       
  2250         this.minimap.node_layer.activate();
       
  2251         this.minimap.cliprectangle = new paper.Path.Rectangle(this.minimap.topleft, this.minimap.size);
       
  2252         this.minimap.node_group.addChild(this.minimap.cliprectangle);
       
  2253         this.minimap.node_group.clipped = true;
       
  2254         this.minimap.miniframe = new paper.Path.Rectangle(this.minimap.topleft, this.minimap.size);
       
  2255         this.minimap.node_group.addChild(this.minimap.miniframe);
       
  2256         this.minimap.miniframe.fillColor = '#c0c0ff';
       
  2257         this.minimap.miniframe.opacity = .3;
       
  2258         this.minimap.miniframe.strokeColor = '#000080';
       
  2259         this.minimap.miniframe.strokeWidth = 3;
       
  2260         this.minimap.miniframe.__representation = new Rkns.Renderer.MiniFrame(this, null);
       
  2261     }
       
  2262     
       
  2263     this.throttledPaperDraw = Rkns._(function() {
       
  2264         paper.view.draw();
       
  2265     }).throttle(100);
       
  2266     
       
  2267     this.bundles = [];
       
  2268     this.click_mode = false;
       
  2269     
       
  2270     var _this = this,
       
  2271         _allowScroll = true,
       
  2272         _originalScale,
       
  2273         _zooming = false,
       
  2274         _lastTapDate,
       
  2275         _lastTapX,
       
  2276         _lastTapY;
       
  2277     
       
  2278     this.imageCache = {};
       
  2279     
       
  2280     ['edit', 'remove', 'link', 'enlarge', 'shrink', 'revert' ].forEach(function(imgname) {
       
  2281         var img = new Image();
       
  2282         img.src = _renkan.options.static_url + 'img/' + imgname + '.png';
       
  2283         _this.imageCache[imgname] = img;
       
  2284     });
       
  2285     
       
  2286     var throttledMouseMove = _.throttle(function(_event, _isTouch) {
       
  2287         _this.onMouseMove(_event, _isTouch);
       
  2288     }, Rkns.Renderer._MOUSEMOVE_RATE);
       
  2289     
       
  2290     this.canvas_$.on({
       
  2291         mousedown: function(_event) {
       
  2292             _event.preventDefault();
       
  2293             _this.onMouseDown(_event, false);
       
  2294         },
       
  2295         mousemove: function(_event) {
       
  2296             _event.preventDefault();
       
  2297             throttledMouseMove(_event, false);
       
  2298         },
       
  2299         mouseup: function(_event) {
       
  2300             _event.preventDefault();
       
  2301             _this.onMouseUp(_event, false);
       
  2302         },
       
  2303         mousewheel: function(_event, _delta) {
       
  2304             _event.preventDefault();
       
  2305             if (_allowScroll) {
       
  2306                 _this.onScroll(_event, _delta);
       
  2307             }
       
  2308         },
       
  2309         touchstart: function(_event) {
       
  2310             _event.preventDefault();
       
  2311             var _touches = _event.originalEvent.touches[0];
       
  2312             if (
       
  2313                 _renkan.options.allow_double_click
       
  2314                 && new Date() - _lastTap < Rkns.Renderer._DOUBLETAP_DELAY
       
  2315                 && ( Math.pow(_lastTapX - _touches.pageX, 2) + Math.pow(_lastTapY - _touches.pageY, 2) < Rkns.Renderer._DOUBLETAP_DISTANCE )
       
  2316             ) {
       
  2317                 _lastTap = 0;
       
  2318                 _this.onDoubleClick(_touches);
       
  2319             } else {
       
  2320                 _lastTap = new Date();
       
  2321                 _lastTapX = _touches.pageX;
       
  2322                 _lastTapY = _touches.pageY;
       
  2323                 _originalScale = _this.scale;
       
  2324                 _zooming = false;
       
  2325                 _this.onMouseDown(_touches, true);
       
  2326             }
       
  2327         },
       
  2328         touchmove: function(_event) {
       
  2329             _event.preventDefault();
       
  2330             _lastTap = 0;
       
  2331             if (_event.originalEvent.touches.length == 1) {
       
  2332                 _this.onMouseMove(_event.originalEvent.touches[0], true);
       
  2333             } else {
       
  2334                 if (!_zooming) {
       
  2335                     _this.onMouseUp(_event.originalEvent.touches[0], true);
       
  2336                     _this.click_target = null;
       
  2337                     _this.is_dragging = false;
       
  2338                     _zooming = true;
       
  2339                 }
       
  2340                 if (_event.originalEvent.scale === "undefined") {
       
  2341                     return;
       
  2342                 }
       
  2343                 var _newScale = _event.originalEvent.scale * _originalScale,
       
  2344                     _scaleRatio = _newScale / _this.scale,
       
  2345                     _newOffset = new paper.Point([
       
  2346                         _this.canvas_$.width(),
       
  2347                         _this.canvas_$.height()
       
  2348                     ]).multiply( .5 * ( 1 - _scaleRatio ) ).add(_this.offset.multiply( _scaleRatio ));
       
  2349                 _this.setScale(_newScale, _this.offset);
       
  2350             }
       
  2351         },
       
  2352         touchend: function(_event) {
       
  2353             _event.preventDefault();
       
  2354             _this.onMouseUp(_event.originalEvent.changedTouches[0], true);
       
  2355         },
       
  2356         dblclick: function(_event) {
       
  2357             _event.preventDefault();
       
  2358             if (_renkan.options.allow_double_click) {
       
  2359                 _this.onDoubleClick(_event);
       
  2360             }
       
  2361         },
       
  2362         mouseleave: function(_event) {
       
  2363             _event.preventDefault();
       
  2364             _this.onMouseUp(_event, false);
       
  2365             _this.click_target = null;
       
  2366             _this.is_dragging = false;
       
  2367         },
       
  2368         dragover: function(_event) {
       
  2369             _event.preventDefault();
       
  2370         },
       
  2371         dragenter: function(_event) {
       
  2372             _event.preventDefault();
       
  2373             _allowScroll = false;
       
  2374         },
       
  2375         dragleave: function(_event) {
       
  2376             _event.preventDefault();
       
  2377             _allowScroll = true;
       
  2378         },
       
  2379         drop: function(_event) {
       
  2380             _event.preventDefault();
       
  2381             _allowScroll = true;
       
  2382             var res = {};
       
  2383             Rkns._(_event.originalEvent.dataTransfer.types).each(function(t) {
       
  2384                 try {
       
  2385                     res[t] = _event.originalEvent.dataTransfer.getData(t);
       
  2386                 } catch(e) {}
       
  2387             });
       
  2388             var text = _event.originalEvent.dataTransfer.getData("Text");
       
  2389             if (typeof text === "string") {
       
  2390                 switch(text[0]) {
       
  2391                     case "{":
       
  2392                     case "[":
       
  2393                         try {
       
  2394                             var data = JSON.parse(text);
       
  2395                             _(res).extend(data);
       
  2396                         }
       
  2397                         catch(e) {
       
  2398                             if (!res["text/plain"]) {
       
  2399                                 res["text/plain"] = text;
       
  2400                             }
       
  2401                         }
       
  2402                     break;
       
  2403                     case "<":
       
  2404                         if (!res["text/html"]) {
       
  2405                             res["text/html"] = text;
       
  2406                         }
       
  2407                     break;
       
  2408                     default:
       
  2409                         if (!res["text/plain"]) {
       
  2410                             res["text/plain"] = text;
       
  2411                         }
       
  2412                 }
       
  2413             }
       
  2414             var url = _event.originalEvent.dataTransfer.getData("URL");
       
  2415             if (url && !res["text/uri-list"]) {
       
  2416                 res["text/uri-list"] = url;
       
  2417             }
       
  2418             _this.dropData(res, _event.originalEvent);
       
  2419         }
       
  2420     });
       
  2421     this.editor_$.find(".Rk-ZoomOut").click(function() {
       
  2422         var _newScale = _this.scale * Math.SQRT1_2,
       
  2423             _offset = new paper.Point([
       
  2424                 _this.canvas_$.width(),
       
  2425                 _this.canvas_$.height()
       
  2426             ]).multiply( .5 * ( 1 - Math.SQRT1_2 ) ).add(_this.offset.multiply( Math.SQRT1_2 ));
       
  2427         _this.setScale( _newScale, _offset );
       
  2428     });
       
  2429     this.editor_$.find(".Rk-ZoomIn").click(function() {
       
  2430         var _newScale = _this.scale * Math.SQRT2,
       
  2431             _offset = new paper.Point([
       
  2432                 _this.canvas_$.width(),
       
  2433                 _this.canvas_$.height()
       
  2434             ]).multiply( .5 * ( 1 - Math.SQRT2 ) ).add(_this.offset.multiply( Math.SQRT2 ));
       
  2435         _this.setScale( _newScale, _offset );
       
  2436     });
       
  2437     this.$.find(".Rk-CurrentUser").mouseenter(
       
  2438         function() { _this.$.find(".Rk-UserList").slideDown() }
       
  2439     );
       
  2440     this.$.find(".Rk-Users").mouseleave(
       
  2441         function() { _this.$.find(".Rk-UserList").slideUp(); }
       
  2442     );
       
  2443     this.$.find(".Rk-FullScreen-Button").click(function() {
       
  2444         var _isFull = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen,
       
  2445             _el = _this.renkan.$[0],
       
  2446             _requestMethods = ["requestFullScreen","mozRequestFullScreen","webkitRequestFullScreen"],
       
  2447             _cancelMethods = ["cancelFullScreen","mozCancelFullScreen","webkitCancelFullScreen"];
       
  2448         if (_isFull) {
       
  2449             for (var i = 0; i < _cancelMethods.length; i++) {
       
  2450                 if (typeof document[_cancelMethods[i]] === "function") {
       
  2451                     document[_cancelMethods[i]]();
       
  2452                     break;
       
  2453                 }
       
  2454             }
       
  2455         } else {
       
  2456             for (var i = 0; i < _requestMethods.length; i++) {
       
  2457                 if (typeof _el[_requestMethods[i]] === "function") {
       
  2458                     _el[_requestMethods[i]]();
       
  2459                     break;
       
  2460                 }
       
  2461             }
       
  2462         }
       
  2463     });
       
  2464     this.$.find(".Rk-AddNode-Button").click(function() {
       
  2465         if (_this.click_mode === Rkns.Renderer._CLICKMODE_ADDNODE) {
       
  2466             _this.click_mode = false;
       
  2467             _this.notif_$.hide();
       
  2468         } else {
       
  2469             _this.click_mode = Rkns.Renderer._CLICKMODE_ADDNODE;
       
  2470             _this.notif_$.text(_renkan.translate("Click on the background canvas to add a node")).fadeIn();
       
  2471         }
       
  2472     });
       
  2473     this.$.find(".Rk-AddEdge-Button").click(function() {
       
  2474         if (_this.click_mode === Rkns.Renderer._CLICKMODE_STARTEDGE || _this.click_mode === Rkns.Renderer._CLICKMODE_ENDEDGE) {
       
  2475             _this.click_mode = false;
       
  2476             _this.notif_$.hide();
       
  2477         } else {
       
  2478             _this.click_mode = Rkns.Renderer._CLICKMODE_STARTEDGE;
       
  2479             _this.notif_$.text(_renkan.translate("Click on a first node to start the edge")).fadeIn();
       
  2480         }
       
  2481     });
       
  2482     this.$.find(".Rk-Bookmarklet-Button")
       
  2483         .attr("href","javascript:" + Rkns.Renderer._BOOKMARKLET_CODE(_renkan))
       
  2484         .click(function(){
       
  2485             _this.notif_$
       
  2486                 .text(_renkan.translate("Drag this button to your bookmark bar. When on a third-party website, click it to enable drag-and-drop from the website to Renkan."))
       
  2487                 .fadeIn()
       
  2488                 .delay(5000)
       
  2489                 .fadeOut();
       
  2490             return false;
       
  2491         });
       
  2492     this.$.find(".Rk-TopBar-Button").mouseover(function() {
       
  2493         Rkns.$(this).find(".Rk-TopBar-Tooltip").show();
       
  2494     }).mouseout(function() {
       
  2495         Rkns.$(this).find(".Rk-TopBar-Tooltip").hide();
       
  2496     });
       
  2497     this.$.find(".Rk-Fold-Bins").click(function() {
       
  2498         var bins = _renkan.$.find(".Rk-Bins");
       
  2499         if (bins.offset().left < 0) {
       
  2500             bins.animate({left: 0},250);
       
  2501             _this.$.animate({left: 300},250,function() {
       
  2502                 var w = _this.$.width();
       
  2503                 paper.view.viewSize = new paper.Size([w, _this.canvas_$.height()]);
       
  2504             });
       
  2505             $(this).html("&laquo;");
       
  2506         } else {
       
  2507             bins.animate({left: -300},250);
       
  2508             _this.$.animate({left: 0},250,function() {
       
  2509                 var w = _this.$.width();
       
  2510                 paper.view.viewSize = new paper.Size([w, _this.canvas_$.height()]);
       
  2511             });
       
  2512             $(this).html("&raquo;");
       
  2513         }
       
  2514     });
       
  2515     
       
  2516     paper.view.onResize = function(_event) {
       
  2517         _this.offset = _this.offset.add(_event.delta.divide(2));
       
  2518         if (_this.minimap) {
       
  2519             _this.minimap.topleft = paper.view.bounds.bottomRight.subtract(_this.minimap.size)
       
  2520             _this.minimap.rectangle.fitBounds(_this.minimap.topleft.subtract([2,2]), _this.minimap.size.add([4,4]));
       
  2521             _this.minimap.cliprectangle.fitBounds(_this.minimap.topleft, _this.minimap.size);
       
  2522         }
       
  2523         _this.redraw();
       
  2524     }
       
  2525     
       
  2526     var _thRedraw = Rkns._.throttle(function() {
       
  2527         _this.redraw();
       
  2528     },50);
       
  2529     
       
  2530     this.addRepresentations("Node", this.renkan.project.get("nodes"));
       
  2531     this.addRepresentations("Edge", this.renkan.project.get("edges"));
       
  2532     this.renkan.project.on("change:title", function() {
       
  2533         _this.$.find(".Rk-PadTitle").val(_renkan.project.get("title"));
       
  2534     });
       
  2535     
       
  2536     this.$.find(".Rk-PadTitle").on("keyup input paste", function() {
       
  2537         _renkan.project.set({"title": $(this).val()});
       
  2538     })
       
  2539     
       
  2540     this.renkan.project.get("users").each(function(_user) {
       
  2541         _this.addUser(_user);
       
  2542     });
       
  2543     
       
  2544     this.renkan.project.on("add:users", function(_user) {
       
  2545         _this.addUser(_user);
       
  2546     });
       
  2547     this.renkan.project.on("add:nodes", function(_node) {
       
  2548         _this.addRepresentation("Node", _node);
       
  2549         _thRedraw();
       
  2550     });
       
  2551     this.renkan.project.on("add:edges", function(_edge) {
       
  2552         _this.addRepresentation("Edge", _edge);
       
  2553         _thRedraw();
       
  2554     });
       
  2555     this.renkan.project.on("change:title", function(_model, _title) {
       
  2556         var el = _this.$.find(".Rk-PadTitle");
       
  2557         if (el.is("input")) {
       
  2558             if (el.val() !== _title) {
       
  2559                 el.val(_title);
       
  2560             }
       
  2561         } else {
       
  2562             el.text(_title);
       
  2563         }
       
  2564     });
       
  2565     
       
  2566     if (_renkan.options.size_bug_fix) {
       
  2567         var _delay = (
       
  2568             typeof _renkan.options.size_bug_fix === "number"
       
  2569             ? _renkan.options.size_bug_fix
       
  2570             : 500
       
  2571         );
       
  2572         window.setTimeout(
       
  2573             function() {
       
  2574                 _this.fixSize(true);
       
  2575             },
       
  2576             _delay
       
  2577         );
       
  2578     }
       
  2579     
       
  2580     if (_renkan.options.force_resize) {
       
  2581         $(window).resize(function() {
       
  2582             _this.fixSize(false);
       
  2583         });
       
  2584     }
       
  2585     
       
  2586     this.redraw();
       
  2587     
       
  2588     window.setInterval(function() {
       
  2589         var _now = new Date().valueOf();
       
  2590         _this.delete_list.forEach(function(d) {
       
  2591             if (_now >= d.time) {
       
  2592                 var el = _renkan.project.get("nodes").findWhere({"delete_scheduled":d.id});
       
  2593                 if (el) {
       
  2594                     project.removeNode(el);
       
  2595                 }
       
  2596                 el = _renkan.project.get("edges").findWhere({"delete_scheduled":d.id});
       
  2597                 if (el) {
       
  2598                     project.removeEdge(el);
       
  2599                 }
       
  2600             }
       
  2601         });
       
  2602         _this.delete_list = _this.delete_list.filter(function(d) {
       
  2603             return _renkan.project.get("nodes").findWhere({"delete_scheduled":d.id}) || _renkan.project.get("edges").findWhere({"delete_scheduled":d.id})
       
  2604         });
       
  2605     }, 500);
       
  2606     
       
  2607     if (this.minimap) {
       
  2608         window.setInterval(function() {
       
  2609             _this.rescaleMinimap()
       
  2610         }, 2000);
       
  2611     }
       
  2612 
       
  2613 }
       
  2614 
       
  2615 Rkns.Renderer.Scene.prototype.template = Rkns._.template(
       
  2616     '<% if (options.show_top_bar) { %><div class="Rk-TopBar"><% if (!options.editor_mode) { %><h2 class="Rk-PadTitle"><%- project.get("title") || translate("Untitled project")%></h2>'
       
  2617     + '<% } else { %><input type="text" class="Rk-PadTitle" value="<%- project.get("title") || "" %>" placeholder="<%-translate("Untitled project")%>" /><% } %>'
       
  2618     + '<div class="Rk-Users"><div class="Rk-CurrentUser"><span class="Rk-CurrentUser-Color"></span><span class="Rk-CurrentUser-Name">&lt;unknown user&gt;</span></div><ul class="Rk-UserList"></ul></div>'
       
  2619     + '<div class="Rk-TopBar-Separator"></div><div class="Rk-TopBar-Button Rk-FullScreen-Button"><div class="Rk-TopBar-Tooltip"><div class="Rk-TopBar-Tooltip-Tip"></div><div class="Rk-TopBar-Tooltip-Contents"><%-translate("Full Screen")%></div></div></div>'
       
  2620     + '<% if (options.editor_mode) { %>'
       
  2621     + '<div class="Rk-TopBar-Separator"></div><div class="Rk-TopBar-Button Rk-AddNode-Button"><div class="Rk-TopBar-Tooltip"><div class="Rk-TopBar-Tooltip-Tip"></div><div class="Rk-TopBar-Tooltip-Contents"><%-translate("Add Node")%></div></div></div>'
       
  2622     + '<div class="Rk-TopBar-Separator"></div><div class="Rk-TopBar-Button Rk-AddEdge-Button"><div class="Rk-TopBar-Tooltip"><div class="Rk-TopBar-Tooltip-Tip"></div><div class="Rk-TopBar-Tooltip-Contents"><%-translate("Add Edge")%></div></div></div>'
       
  2623     + '<div class="Rk-TopBar-Separator"></div><div class="Rk-TopBar-Button Rk-Save-Button"><div class="Rk-TopBar-Tooltip"><div class="Rk-TopBar-Tooltip-Tip"></div><div class="Rk-TopBar-Tooltip-Contents"> </div></div></div>'
       
  2624     + '<div class="Rk-TopBar-Separator"></div><a class="Rk-TopBar-Button Rk-Bookmarklet-Button" href="#"><div class="Rk-TopBar-Tooltip"><div class="Rk-TopBar-Tooltip-Tip"></div><div class="Rk-TopBar-Tooltip-Contents">'
       
  2625     + '<%-translate("Renkan \'Drag-to-Add\' bookmarklet")%></div></div></a>'
       
  2626     + '<div class="Rk-TopBar-Separator"></div>'
       
  2627     + '<% } %></div><% } %>'
       
  2628     + '<div class="Rk-Editing-Space<% if (!options.show_top_bar) { %> Rk-Editing-Space-Full<% } %>">'
       
  2629     + '<div class="Rk-Labels"></div><canvas class="Rk-Canvas" resize></canvas><div class="Rk-Editor"><div class="Rk-Notifications"></div>'
       
  2630     + '<% if (options.show_bins) { %><div class="Rk-Fold-Bins">&laquo;</div><% } %>'
       
  2631     + '<div class="Rk-ZoomButtons"><div class="Rk-ZoomIn" title="<%-translate("Zoom In")%>"></div><div class="Rk-ZoomOut" title="<%-translate("Zoom Out")%>"></div></div>'
       
  2632     + '</div></div>'
       
  2633 );
       
  2634 
       
  2635 Rkns.Renderer.Scene.prototype.fixSize = function(_autoscale) {
       
  2636     var w = this.$.width(),
       
  2637         h = this.$.height();
       
  2638     if (this.renkan.options.show_top_bar) {
       
  2639         h -= this.$.find(".Rk-TopBar").height();
       
  2640     }
       
  2641     this.canvas_$.attr({
       
  2642         width: w,
       
  2643         height: h
       
  2644     });
       
  2645     
       
  2646     paper.view.viewSize = new paper.Size([w, h]);
       
  2647     
       
  2648     if (_autoscale) {
       
  2649         this.autoScale();
       
  2650     }
       
  2651 }
       
  2652 
       
  2653 Rkns.Renderer.Scene.prototype.drawSector = function(_repr, _inR, _outR, _startAngle, _endAngle, _padding, _imgname, _caption) {
       
  2654     var _options = this.renkan.options,
       
  2655         _startRads = _startAngle * Math.PI / 180,
       
  2656         _endRads = _endAngle * Math.PI / 180,
       
  2657         _img = this.imageCache[_imgname],
       
  2658         _span = _endRads - _startRads,
       
  2659         _startdx = - Math.sin(_startRads),
       
  2660         _startdy = Math.cos(_startRads),
       
  2661         _startXIn = Math.cos(_startRads) * _inR + _padding * _startdx,
       
  2662         _startYIn = Math.sin(_startRads) * _inR + _padding * _startdy,
       
  2663         _startXOut = Math.cos(_startRads) * _outR + _padding * _startdx,
       
  2664         _startYOut = Math.sin(_startRads) * _outR + _padding * _startdy,
       
  2665         _enddx = - Math.sin(_endRads),
       
  2666         _enddy = Math.cos(_endRads),
       
  2667         _endXIn = Math.cos(_endRads) * _inR - _padding * _enddx,
       
  2668         _endYIn = Math.sin(_endRads) * _inR - _padding * _enddy,
       
  2669         _endXOut = Math.cos(_endRads) * _outR - _padding * _enddx,
       
  2670         _endYOut = Math.sin(_endRads) * _outR - _padding * _enddy,
       
  2671         _centerR = (_inR + _outR)/2,
       
  2672         _centerRads = (_startRads + _endRads) / 2,
       
  2673         _centerX = Math.cos(_centerRads) * _centerR,
       
  2674         _centerY = Math.sin(_centerRads) * _centerR,
       
  2675         _centerXIn = Math.cos(_centerRads) * _inR,
       
  2676         _centerXOut = Math.cos(_centerRads) * _outR,
       
  2677         _centerYIn = Math.sin(_centerRads) * _inR,
       
  2678         _centerYOut = Math.sin(_centerRads) * _outR,
       
  2679         _textX = Math.cos(_centerRads) * (_outR + 3),
       
  2680         _textY = Math.sin(_centerRads) * (_outR + _options.buttons_label_font_size) + _options.buttons_label_font_size / 2,
       
  2681         _segments = [];
       
  2682     this.buttons_layer.activate();
       
  2683     var _path = new paper.Path();
       
  2684     _path.add([_startXIn, _startYIn]);
       
  2685     _path.arcTo([_centerXIn, _centerYIn], [_endXIn, _endYIn]);
       
  2686     _path.lineTo([_endXOut,  _endYOut]);
       
  2687     _path.arcTo([_centerXOut, _centerYOut], [_startXOut, _startYOut]);
       
  2688     _path.fillColor = _options.buttons_background;
       
  2689     _path.opacity = .5;
       
  2690     _path.closed = true;
       
  2691     _path.__representation = _repr;
       
  2692     var _text = new paper.PointText(_textX,_textY);
       
  2693     _text.characterStyle = {
       
  2694         fontSize: _options.buttons_label_font_size,
       
  2695         fillColor: _options.buttons_label_color
       
  2696     };
       
  2697     if (_textX > 2) {
       
  2698         _text.paragraphStyle.justification = 'left';
       
  2699     } else if (_textX < -2) {
       
  2700         _text.paragraphStyle.justification = 'right';
       
  2701     } else {
       
  2702         _text.paragraphStyle.justification = 'center';
       
  2703     }
       
  2704     _text.visible = false;
       
  2705     var _visible = false,
       
  2706         _restPos = new paper.Point(-200, -200),
       
  2707         _grp = new paper.Group([_path, _text]),
       
  2708         _delta = _grp.position,
       
  2709         _imgdelta = new paper.Point([_centerX, _centerY]),
       
  2710         _currentPos = new paper.Point(0,0);
       
  2711     _text.content = _caption;
       
  2712     _grp.visible = false;
       
  2713     _grp.position = _restPos;
       
  2714     var _res = {
       
  2715         show: function() {
       
  2716             _visible = true;
       
  2717             _grp.position = _currentPos.add(_delta);
       
  2718             _grp.visible = true;
       
  2719         },
       
  2720         moveTo: function(_point) {
       
  2721             _currentPos = _point;
       
  2722             if (_visible) {
       
  2723                 _grp.position = _point.add(_delta);
       
  2724             }
       
  2725         },
       
  2726         hide: function() {
       
  2727             _visible = false;
       
  2728             _grp.visible = false;
       
  2729             _grp.position = _restPos;
       
  2730         },
       
  2731         select: function() {
       
  2732             _path.opacity = .8;
       
  2733             _text.visible = true;
       
  2734         },
       
  2735         unselect: function() {
       
  2736             _path.opacity = .5;
       
  2737             _text.visible = false;
       
  2738         },
       
  2739         destroy: function() {
       
  2740             _grp.remove();
       
  2741         }
       
  2742     }
       
  2743     function showImage() {
       
  2744         var _raster = new paper.Raster(_img);
       
  2745         _raster.position = _imgdelta.add(_grp.position).subtract(_delta);
       
  2746         _grp.addChild(_raster);
       
  2747     }
       
  2748     if (_img.width) {
       
  2749         showImage();
       
  2750     } else {
       
  2751         Rkns.$(_img).on("load",showImage);
       
  2752     }
       
  2753     
       
  2754     return _res
       
  2755 }
       
  2756 
       
  2757 Rkns.Renderer.Scene.prototype.addToBundles = function(_edgeRepr) {
       
  2758     var _bundle = Rkns._(this.bundles).find(function(_bundle) {
       
  2759         return ( 
       
  2760             ( _bundle.from === _edgeRepr.from_representation && _bundle.to === _edgeRepr.to_representation )
       
  2761             || ( _bundle.from === _edgeRepr.to_representation && _bundle.to === _edgeRepr.from_representation )
       
  2762         );
       
  2763     });
       
  2764     if (typeof _bundle !== "undefined") {
       
  2765         _bundle.edges.push(_edgeRepr)
       
  2766     } else {
       
  2767         _bundle = {
       
  2768             from: _edgeRepr.from_representation,
       
  2769             to: _edgeRepr.to_representation,
       
  2770             edges: [ _edgeRepr ],
       
  2771             getPosition: function(_er) {
       
  2772                 var _dir = (_er.from_representation === this.from) ? 1 : -1;
       
  2773                 return _dir * ( Rkns._(this.edges).indexOf(_er) - (this.edges.length - 1) / 2 );
       
  2774             }
       
  2775         }
       
  2776         this.bundles.push(_bundle);
       
  2777     }
       
  2778     return _bundle;
       
  2779 }
       
  2780 
       
  2781 Rkns.Renderer.Scene.prototype.isEditable = function() {
       
  2782     return (this.renkan.options.editor_mode && !this.renkan.read_only)
       
  2783 }
       
  2784 
       
  2785 Rkns.Renderer.Scene.prototype.onStatusChange = function() {
       
  2786     var savebtn = this.$.find(".Rk-Save-Button"),
       
  2787         tip = savebtn.find(".Rk-TopBar-Tooltip-Contents");
       
  2788     if (this.renkan.read_only) {
       
  2789         savebtn.removeClass("disabled Rk-Save-Online").addClass("Rk-Save-ReadOnly");
       
  2790         tip.text(this.renkan.translate("Connection lost"));
       
  2791     } else {
       
  2792         if (this.renkan.options.snapshot_mode) {
       
  2793             savebtn.removeClass("Rk-Save-ReadOnly Rk-Save-Online");
       
  2794             tip.text(this.renkan.translate("Archive Project"));
       
  2795         } else {
       
  2796             savebtn.removeClass("disabled Rk-Save-ReadOnly").addClass("Rk-Save-Online");
       
  2797             tip.text(this.renkan.translate("Auto-save enabled"));
       
  2798         }
       
  2799     }
       
  2800 }
       
  2801 
       
  2802 Rkns.Renderer.Scene.prototype.setScale = function(_newScale, _offset) {
       
  2803     if (_newScale > Rkns.Renderer._MIN_SCALE && _newScale < Rkns.Renderer._MAX_SCALE) {
       
  2804         this.scale = _newScale;
       
  2805         if (_offset) {
       
  2806             this.offset = _offset
       
  2807         }
       
  2808         this.redraw();
       
  2809     }
       
  2810 }
       
  2811 
       
  2812 Rkns.Renderer.Scene.prototype.autoScale = function() {
       
  2813     var nodes = this.renkan.project.get("nodes")
       
  2814     if (nodes.length > 1) {
       
  2815         var _xx = nodes.map(function(_node) { return _node.get("position").x }),
       
  2816             _yy = nodes.map(function(_node) { return _node.get("position").y }),
       
  2817             _minx = Math.min.apply(Math, _xx),
       
  2818             _miny = Math.min.apply(Math, _yy),
       
  2819             _maxx = Math.max.apply(Math, _xx),
       
  2820             _maxy = Math.max.apply(Math, _yy);
       
  2821         var _scale = Math.max(Rkns.Renderer._MIN_SCALE, Math.min(Rkns.Renderer._MAX_SCALE, (paper.view.size.width - 2 * Rkns.Renderer._AUTOSCALE_MARGIN) / (_maxx - _minx), (paper.view.size.height - 2 * Rkns.Renderer._AUTOSCALE_MARGIN) / (_maxy - _miny)));
       
  2822         this.setScale(_scale, paper.view.center.subtract(new paper.Point([(_maxx + _minx) / 2, (_maxy + _miny) / 2]).multiply(_scale)));
       
  2823     }
       
  2824     if (nodes.length === 1) {
       
  2825         this.setScale(1, paper.view.center.subtract(new paper.Point([nodes.at(0).get("position").x, nodes.at(0).get("position").y])));
       
  2826     }
       
  2827 }
       
  2828 
       
  2829 Rkns.Renderer.Scene.prototype.redrawMiniframe = function() {
       
  2830     var topleft = this.toMinimapCoords(this.toModelCoords(new paper.Point([0,0]))),
       
  2831         bottomright = this.toMinimapCoords(this.toModelCoords(paper.view.bounds.bottomRight));
       
  2832     this.minimap.miniframe.fitBounds(topleft, bottomright);
       
  2833 }
       
  2834 
       
  2835 Rkns.Renderer.Scene.prototype.rescaleMinimap = function() {
       
  2836     var nodes = this.renkan.project.get("nodes")
       
  2837     if (nodes.length > 1) {
       
  2838         var _xx = nodes.map(function(_node) { return _node.get("position").x }),
       
  2839             _yy = nodes.map(function(_node) { return _node.get("position").y }),
       
  2840             _minx = Math.min.apply(Math, _xx),
       
  2841             _miny = Math.min.apply(Math, _yy),
       
  2842             _maxx = Math.max.apply(Math, _xx),
       
  2843             _maxy = Math.max.apply(Math, _yy);
       
  2844         var _scale = Math.min(
       
  2845             this.scale * .8 * this.renkan.options.minimap_width / paper.view.bounds.width,
       
  2846             this.scale * .8 * this.renkan.options.minimap_height / paper.view.bounds.height,
       
  2847             ( this.renkan.options.minimap_width - 2 * Rkns.Renderer._MINIMAP_MARGIN ) / (_maxx - _minx),
       
  2848             ( this.renkan.options.minimap_height - 2 * Rkns.Renderer._MINIMAP_MARGIN ) / (_maxy - _miny)
       
  2849         );
       
  2850         this.minimap.offset = this.minimap.size.divide(2).subtract(new paper.Point([(_maxx + _minx) / 2, (_maxy + _miny) / 2]).multiply(_scale));
       
  2851         this.minimap.scale = _scale;
       
  2852     }
       
  2853     if (nodes.length === 1) {
       
  2854         this.minimap.scale = .1;
       
  2855         this.minimap.offset = this.minimap.size.divide(2).subtract(new paper.Point([nodes.at(0).get("position").x, nodes.at(0).get("position").y]).multiply(this.minimap.scale));
       
  2856     }
       
  2857     this.redraw();
       
  2858 }
       
  2859 
       
  2860 Rkns.Renderer.Scene.prototype.toPaperCoords = function(_point) {
       
  2861     return _point.multiply(this.scale).add(this.offset);
       
  2862 }
       
  2863 
       
  2864 Rkns.Renderer.Scene.prototype.toMinimapCoords = function(_point) {
       
  2865     return _point.multiply(this.minimap.scale).add(this.minimap.offset).add(this.minimap.topleft);
       
  2866 }
       
  2867 
       
  2868 Rkns.Renderer.Scene.prototype.toModelCoords = function(_point) {
       
  2869     return _point.subtract(this.offset).divide(this.scale);
       
  2870 }
       
  2871 
       
  2872 Rkns.Renderer.Scene.prototype.addRepresentation = function(_type, _model) {
       
  2873     var _repr = new Rkns.Renderer[_type](this, _model);
       
  2874     this.representations.push(_repr);
       
  2875     return _repr;
       
  2876 }
       
  2877 
       
  2878 Rkns.Renderer.Scene.prototype.addRepresentations = function(_type, _collection) {
       
  2879     var _this = this;
       
  2880     _collection.forEach(function(_model) {
       
  2881         _this.addRepresentation(_type, _model);
       
  2882     });
       
  2883 }
       
  2884 
       
  2885 Rkns.Renderer.Scene.prototype.userTemplate = Rkns._.template(
       
  2886     '<li class="Rk-User"><span class="Rk-UserColor" style="background:<%=background%>;"></span><%=name%></li>'
       
  2887 );
       
  2888 
       
  2889 Rkns.Renderer.Scene.prototype.addUser = function(_user) {
       
  2890     if (_user.get("_id") === this.renkan.current_user) {
       
  2891         this.$.find(".Rk-CurrentUser-Name").text(_user.get("title"));
       
  2892         this.$.find(".Rk-CurrentUser-Color").css("background", _user.get("color"));
       
  2893     } else {
       
  2894         this.$.find(".Rk-UserList").append(
       
  2895             Rkns.$(
       
  2896                 this.userTemplate({
       
  2897                     name: _user.get("title"),
       
  2898                     background: _user.get("color")
       
  2899                 })
       
  2900             )
       
  2901         );
       
  2902     }
       
  2903 }
       
  2904 
       
  2905 Rkns.Renderer.Scene.prototype.removeRepresentation = function(_representation) {
       
  2906     _representation.destroy();
       
  2907     this.representations = Rkns._(this.representations).reject(
       
  2908         function(_repr) {
       
  2909             return _repr == _representation
       
  2910         }
       
  2911     );
       
  2912 }
       
  2913 
       
  2914 Rkns.Renderer.Scene.prototype.getRepresentationByModel = function(_model) {
       
  2915     return Rkns._(this.representations).find(function(_repr) {
       
  2916         return _repr.model === _model;
       
  2917     });
       
  2918 }
       
  2919 
       
  2920 Rkns.Renderer.Scene.prototype.removeRepresentationsOfType = function(_type) {
       
  2921     var _representations = Rkns._(this.representations).filter(function(_repr) {
       
  2922             return _repr.type == _type;
       
  2923         }),
       
  2924         _this = this;
       
  2925     Rkns._(_representations).each(function(_repr) {
       
  2926         _this.removeRepresentation(_repr);
       
  2927     });
       
  2928 }
       
  2929 
       
  2930 Rkns.Renderer.Scene.prototype.highlightModel = function(_model) {
       
  2931     var _repr = this.getRepresentationByModel(_model);
       
  2932     if (_repr) {
       
  2933         _repr.highlight();
       
  2934     }
       
  2935 }
       
  2936 
       
  2937 Rkns.Renderer.Scene.prototype.unhighlightAll = function(_model) {
       
  2938     Rkns._(this.representations).each(function(_repr) {
       
  2939         _repr.unhighlight();
       
  2940     });
       
  2941 }
       
  2942 
       
  2943 Rkns.Renderer.Scene.prototype.unselectAll = function(_model) {
       
  2944     Rkns._(this.representations).each(function(_repr) {
       
  2945         _repr.unselect();
       
  2946     });
       
  2947 }
       
  2948 
       
  2949 Rkns.Renderer.Scene.prototype.redraw = function() {
       
  2950     Rkns._(this.representations).each(function(_representation) {
       
  2951         _representation.redraw(true);
       
  2952     });
       
  2953     if (this.minimap) {
       
  2954         this.redrawMiniframe();
       
  2955     }
       
  2956     paper.view.draw();
       
  2957 }
       
  2958 
       
  2959 Rkns.Renderer.Scene.prototype.addTempEdge = function(_from, _point) {
       
  2960     var _tmpEdge = this.addRepresentation("TempEdge",null);
       
  2961     _tmpEdge.end_pos = _point;
       
  2962     _tmpEdge.from_representation = _from;
       
  2963     _tmpEdge.redraw();
       
  2964     this.click_target = _tmpEdge;
       
  2965 }
       
  2966 
       
  2967 Rkns.Renderer.Scene.prototype.findTarget = function(_hitResult) {
       
  2968     if (_hitResult && typeof _hitResult.item.__representation !== "undefined") {
       
  2969         var _newTarget = _hitResult.item.__representation;
       
  2970         if (this.selected_target !== _hitResult.item.__representation) {
       
  2971             if (this.selected_target) {
       
  2972                 this.selected_target.unselect(_newTarget);
       
  2973             }
       
  2974             _newTarget.select(this.selected_target);
       
  2975             this.selected_target = _newTarget;
       
  2976         }
       
  2977     } else {
       
  2978         if (this.selected_target) {
       
  2979             this.selected_target.unselect();
       
  2980         }
       
  2981         this.selected_target = null;
       
  2982     }
       
  2983 }
       
  2984 
       
  2985 Rkns.Renderer.Scene.prototype.paperShift = function(_delta) {
       
  2986     this.offset = this.offset.add(_delta);
       
  2987     this.redraw();
       
  2988 }
       
  2989 
       
  2990 Rkns.Renderer.Scene.prototype.onMouseMove = function(_event) {
       
  2991     var _off = this.canvas_$.offset(),
       
  2992         _point = new paper.Point([
       
  2993             _event.pageX - _off.left,
       
  2994             _event.pageY - _off.top
       
  2995         ]),
       
  2996         _delta = _point.subtract(this.last_point);
       
  2997     this.last_point = _point;
       
  2998     if (!this.is_dragging && this.mouse_down && _delta.length > Rkns.Renderer._MIN_DRAG_DISTANCE) {
       
  2999         this.is_dragging = true;
       
  3000     }
       
  3001     var _hitResult = paper.project.hitTest(_point);
       
  3002     if (this.is_dragging) {
       
  3003         if (this.click_target && typeof this.click_target.paperShift === "function") {
       
  3004             this.click_target.paperShift(_delta);
       
  3005         } else {
       
  3006             this.paperShift(_delta);
       
  3007         }
       
  3008     } else {
       
  3009         this.findTarget(_hitResult);
       
  3010     }
       
  3011     paper.view.draw();
       
  3012 }
       
  3013 
       
  3014 Rkns.Renderer.Scene.prototype.onMouseDown = function(_event, _isTouch) {
       
  3015     var _off = this.canvas_$.offset(),
       
  3016         _point = new paper.Point([
       
  3017             _event.pageX - _off.left,
       
  3018             _event.pageY - _off.top
       
  3019         ]);
       
  3020     this.last_point = _point;
       
  3021     this.mouse_down = true;
       
  3022     if (!this.click_target || this.click_target.type !== "Temp-edge") {
       
  3023         this.removeRepresentationsOfType("editor");
       
  3024         this.is_dragging = false;
       
  3025         var _hitResult = paper.project.hitTest(_point);
       
  3026         if (_hitResult && typeof _hitResult.item.__representation !== "undefined") {
       
  3027             this.click_target = _hitResult.item.__representation;
       
  3028             this.click_target.mousedown(_event, _isTouch);
       
  3029         } else {
       
  3030             this.click_target = null;
       
  3031             if (this.isEditable() && this.click_mode === Rkns.Renderer._CLICKMODE_ADDNODE) {
       
  3032                 var _coords = this.toModelCoords(_point),
       
  3033                     _data = {
       
  3034                         id: Rkns.Utils.getUID('node'),
       
  3035                         created_by: this.renkan.current_user,
       
  3036                         position: {
       
  3037                             x: _coords.x,
       
  3038                             y: _coords.y
       
  3039                         }
       
  3040                     };
       
  3041                     _node = this.renkan.project.addNode(_data);
       
  3042                 this.getRepresentationByModel(_node).openEditor();
       
  3043             }
       
  3044         }
       
  3045     }
       
  3046     if (this.click_mode) {
       
  3047         if (this.isEditable() && this.click_mode === Rkns.Renderer._CLICKMODE_STARTEDGE && this.click_target && this.click_target.type === "Node") {
       
  3048             this.removeRepresentationsOfType("editor");
       
  3049             this.addTempEdge(this.click_target, _point);
       
  3050             this.click_mode = Rkns.Renderer._CLICKMODE_ENDEDGE;
       
  3051             this.notif_$.fadeOut(function() {
       
  3052                 Rkns.$(this).html(_renkan.translate("Click on a second node to complete the edge")).fadeIn();
       
  3053             });
       
  3054         } else {
       
  3055             this.notif_$.hide();
       
  3056             this.click_mode = false;
       
  3057         }
       
  3058     }
       
  3059     paper.view.draw();
       
  3060 }
       
  3061 
       
  3062 Rkns.Renderer.Scene.prototype.onMouseUp = function(_event, _isTouch) {
       
  3063     this.mouse_down = false;
       
  3064     if (this.click_target) {
       
  3065         var _off = this.canvas_$.offset();
       
  3066         this.click_target.mouseup(
       
  3067             {
       
  3068                 point: new paper.Point([
       
  3069                     _event.pageX - _off.left,
       
  3070                     _event.pageY - _off.top
       
  3071                 ])
       
  3072             },
       
  3073             _isTouch
       
  3074         );
       
  3075     } else {
       
  3076         this.click_target = null;
       
  3077         this.is_dragging = false;
       
  3078         if (_isTouch) {
       
  3079             this.unselectAll();
       
  3080         }
       
  3081     }
       
  3082     paper.view.draw();
       
  3083 }
       
  3084 
       
  3085 Rkns.Renderer.Scene.prototype.onScroll = function(_event, _scrolldelta) {
       
  3086     this.totalScroll += _scrolldelta;
       
  3087     if (Math.abs(this.totalScroll) >= 1) {
       
  3088         var _off = this.canvas_$.offset(),
       
  3089             _delta = new paper.Point([
       
  3090                 _event.pageX - _off.left,
       
  3091                 _event.pageY - _off.top
       
  3092             ]).subtract(this.offset).multiply( Math.SQRT2 - 1 );
       
  3093         if (this.totalScroll > 0) {
       
  3094             this.setScale( this.scale * Math.SQRT2, this.offset.subtract(_delta) );
       
  3095         } else {
       
  3096             this.setScale( this.scale * Math.SQRT1_2, this.offset.add(_delta.divide(Math.SQRT2)));
       
  3097         }
       
  3098         this.totalScroll = 0;
       
  3099     }
       
  3100 }
       
  3101 
       
  3102 Rkns.Renderer.Scene.prototype.onDoubleClick = function(_event) {
       
  3103     if (!this.isEditable()) {
       
  3104         return;
       
  3105     }
       
  3106     var _off = this.canvas_$.offset(),
       
  3107         _point = new paper.Point([
       
  3108             _event.pageX - _off.left,
       
  3109             _event.pageY - _off.top
       
  3110         ]);
       
  3111     var _hitResult = paper.project.hitTest(_point);
       
  3112     if (this.isEditable() && (!_hitResult || typeof _hitResult.item.__representation === "undefined")) {
       
  3113         var _coords = this.toModelCoords(_point),
       
  3114             _data = {
       
  3115                 id: Rkns.Utils.getUID('node'),
       
  3116                 created_by: this.renkan.current_user,
       
  3117                 position: {
       
  3118                     x: _coords.x,
       
  3119                     y: _coords.y
       
  3120                 }
       
  3121             };
       
  3122             _node = this.renkan.project.addNode(_data);
       
  3123             this.getRepresentationByModel(_node).openEditor();
       
  3124     }
       
  3125     paper.view.draw();
       
  3126 }
       
  3127 
       
  3128 Rkns.Renderer.Scene.prototype.dropData = function(_data, _event) {
       
  3129     if (!this.isEditable()) {
       
  3130         return;
       
  3131     }
       
  3132     if (_data["text/json"] || _data["application/json"]) {
       
  3133         try {
       
  3134             var jsondata = JSON.parse(_data["text/json"] || _data["application/json"]);
       
  3135             _(_data).extend(jsondata);
       
  3136         }
       
  3137         catch(e) {}
       
  3138     }
       
  3139     var newNode = {};
       
  3140     switch(_data["text/x-iri-specific-site"]) {
       
  3141         case "twitter":
       
  3142             var snippet = Rkns.$('<div>').html(_data["text/x-iri-selected-html"]),
       
  3143                 tweetdiv = snippet.find(".tweet")
       
  3144             newNode.title = _renkan.translate("Tweet by ") + tweetdiv.attr("data-name");
       
  3145             newNode.uri = "http://twitter.com/" + tweetdiv.attr("data-screen-name") + "/status/" + tweetdiv.attr("data-tweet-id");
       
  3146             newNode.image = tweetdiv.find(".avatar").attr("src");
       
  3147             newNode.description = tweetdiv.find(".js-tweet-text:first").text();
       
  3148         break;
       
  3149         case "google":
       
  3150             var snippet = Rkns.$('<div>').html(_data["text/x-iri-selected-html"]);
       
  3151             newNode.title = snippet.find("h3:first").text().trim();
       
  3152             newNode.uri = snippet.find("h3 a").attr("href");
       
  3153             newNode.description = snippet.find(".st:first").text().trim();
       
  3154         break;
       
  3155         case undefined:
       
  3156         default:
       
  3157             if (_data["text/x-iri-source-uri"]) {
       
  3158                 newNode.uri = _data["text/x-iri-source-uri"];
       
  3159             }
       
  3160             if (_data["text/plain"] || _data["text/x-iri-selected-text"]) {
       
  3161                 newNode.description = (_data["text/plain"] || _data["text/x-iri-selected-text"]).replace(/[\s\n]+/gm,' ').trim();
       
  3162             }
       
  3163             if (_data["text/html"] || _data["text/x-iri-selected-html"]) {
       
  3164                 var snippet = Rkns.$('<div>').html(_data["text/html"] || _data["text/x-iri-selected-html"]);
       
  3165                 var _imgs = snippet.find("img");
       
  3166                 if (_imgs.length) {
       
  3167                     newNode.image = _imgs[0].src;
       
  3168                 }
       
  3169                 var _as = snippet.find("a");
       
  3170                 if (_as.length) {
       
  3171                     newNode.uri = _as[0].href;
       
  3172                 }
       
  3173                 newNode.title = snippet.find("[title]").attr("title") || newNode.title;
       
  3174                 newNode.description = snippet.text().replace(/[\s\n]+/gm,' ').trim();
       
  3175             }
       
  3176             if (_data["text/uri-list"]) {
       
  3177                 newNode.uri = _data["text/uri-list"];
       
  3178             }
       
  3179             if (_data["text/x-moz-url"] && !newNode.title) {
       
  3180                 newNode.title = (_data["text/x-moz-url"].split("\n")[1] || "").trim();
       
  3181                 if (newNode.title === newNode.uri) {
       
  3182                     newNode.title = false;
       
  3183                 }
       
  3184             }
       
  3185             if (_data["text/x-iri-source-title"] && !newNode.title) {
       
  3186                 newNode.title = _data["text/x-iri-source-title"];
       
  3187             }
       
  3188             if (_data["text/html"] || _data["text/x-iri-selected-html"]) {
       
  3189                 newNode.image = snippet.find("[data-image]").attr("data-image") || newNode.image;
       
  3190                 newNode.uri = snippet.find("[data-uri]").attr("data-uri") || newNode.uri;
       
  3191                 newNode.title = snippet.find("[data-title]").attr("data-title") || newNode.title;
       
  3192                 newNode.description = snippet.find("[data-description]").attr("data-description") || newNode.description;
       
  3193             }
       
  3194     }
       
  3195     if (!newNode.title) {
       
  3196         newNode.title = this.renkan.translate("Dragged resource");
       
  3197     }
       
  3198     var fields = ["title", "description", "uri", "image"];
       
  3199     for (var i = 0; i < fields.length; i++) {
       
  3200         var f = fields[i];
       
  3201         if (_data["text/x-iri-" + f] || _data[f]) {
       
  3202             newNode[f] = _data["text/x-iri-" + f] || _data[f];
       
  3203         }
       
  3204         if (newNode[f] === "none" || newNode[f] === "null") {
       
  3205             newNode[f] = undefined;
       
  3206         }
       
  3207     }
       
  3208     var _off = this.canvas_$.offset(),
       
  3209         _point = new paper.Point([
       
  3210             _event.pageX - _off.left,
       
  3211             _event.pageY - _off.top
       
  3212         ]),
       
  3213         _coords = this.toModelCoords(_point),
       
  3214         _nodedata = {
       
  3215             id: Rkns.Utils.getUID('node'),
       
  3216             created_by: this.renkan.current_user,
       
  3217             uri: newNode.uri || "",
       
  3218             title: newNode.title || "",
       
  3219             description: newNode.description || "",
       
  3220             image: newNode.image || "",
       
  3221             color: newNode.color || undefined,
       
  3222             position: {
       
  3223                 x: _coords.x,
       
  3224                 y: _coords.y
       
  3225             }
       
  3226         };
       
  3227     var _node = this.renkan.project.addNode(_nodedata),
       
  3228         _repr = this.getRepresentationByModel(_node);
       
  3229     if (_event.type === "drop") {
       
  3230         _repr.openEditor();
       
  3231     }
       
  3232 }