Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

1655 lines
70KB

  1. /**
  2. * Copyright 2013, 2014 IBM Corp.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. **/
  16. RED.view = (function() {
  17. var space_width = 5000,
  18. space_height = 5000,
  19. lineCurveScale = 0.75,
  20. scaleFactor = 1,
  21. node_width = 100,
  22. node_height = 30;
  23. var touchLongPressTimeout = 1000,
  24. startTouchDistance = 0,
  25. startTouchCenter = [],
  26. moveTouchCenter = [],
  27. touchStartTime = 0;
  28. var activeWorkspace = 0;
  29. var workspaceScrollPositions = {};
  30. var selected_link = null,
  31. mousedown_link = null,
  32. mousedown_node = null,
  33. mousedown_port_type = null,
  34. mousedown_port_index = 0,
  35. mouseup_node = null,
  36. mouse_offset = [0,0],
  37. mouse_position = null,
  38. mouse_mode = 0,
  39. moving_set = [],
  40. dirty = false,
  41. lasso = null,
  42. showStatus = false,
  43. lastClickNode = null,
  44. dblClickPrimed = null,
  45. clickTime = 0,
  46. clickElapsed = 0;
  47. var clipboard = "";
  48. var status_colours = {
  49. "red": "#c00",
  50. "green": "#5a8",
  51. "yellow": "#F9DF31",
  52. "blue": "#53A3F3",
  53. "grey": "#d3d3d3"
  54. }
  55. var outer = d3.select("#chart")
  56. .append("svg:svg")
  57. .attr("width", space_width)
  58. .attr("height", space_height)
  59. .attr("pointer-events", "all")
  60. .style("cursor","crosshair");
  61. var vis = outer
  62. .append('svg:g')
  63. .on("dblclick.zoom", null)
  64. .append('svg:g')
  65. .on("mousemove", canvasMouseMove)
  66. .on("mousedown", canvasMouseDown)
  67. .on("mouseup", canvasMouseUp)
  68. .on("touchend", function() {
  69. clearTimeout(touchStartTime);
  70. touchStartTime = null;
  71. if (RED.touch.radialMenu.active()) {
  72. return;
  73. }
  74. if (lasso) {
  75. outer_background.attr("fill","#fff");
  76. }
  77. canvasMouseUp.call(this);
  78. })
  79. .on("touchcancel", canvasMouseUp)
  80. .on("touchstart", function() {
  81. var touch0;
  82. if (d3.event.touches.length>1) {
  83. clearTimeout(touchStartTime);
  84. touchStartTime = null;
  85. d3.event.preventDefault();
  86. touch0 = d3.event.touches.item(0);
  87. var touch1 = d3.event.touches.item(1);
  88. var a = touch0['pageY']-touch1['pageY'];
  89. var b = touch0['pageX']-touch1['pageX'];
  90. var offset = $("#chart").offset();
  91. var scrollPos = [$("#chart").scrollLeft(),$("#chart").scrollTop()];
  92. startTouchCenter = [
  93. (touch1['pageX']+(b/2)-offset.left+scrollPos[0])/scaleFactor,
  94. (touch1['pageY']+(a/2)-offset.top+scrollPos[1])/scaleFactor
  95. ];
  96. moveTouchCenter = [
  97. touch1['pageX']+(b/2),
  98. touch1['pageY']+(a/2)
  99. ]
  100. startTouchDistance = Math.sqrt((a*a)+(b*b));
  101. } else {
  102. var obj = d3.select(document.body);
  103. touch0 = d3.event.touches.item(0);
  104. var pos = [touch0.pageX,touch0.pageY];
  105. startTouchCenter = [touch0.pageX,touch0.pageY];
  106. startTouchDistance = 0;
  107. var point = d3.touches(this)[0];
  108. touchStartTime = setTimeout(function() {
  109. touchStartTime = null;
  110. showTouchMenu(obj,pos);
  111. //lasso = vis.append('rect')
  112. // .attr("ox",point[0])
  113. // .attr("oy",point[1])
  114. // .attr("rx",2)
  115. // .attr("ry",2)
  116. // .attr("x",point[0])
  117. // .attr("y",point[1])
  118. // .attr("width",0)
  119. // .attr("height",0)
  120. // .attr("class","lasso");
  121. //outer_background.attr("fill","#e3e3f3");
  122. },touchLongPressTimeout);
  123. }
  124. })
  125. .on("touchmove", function(){
  126. if (RED.touch.radialMenu.active()) {
  127. d3.event.preventDefault();
  128. return;
  129. }
  130. var touch0;
  131. if (d3.event.touches.length<2) {
  132. if (touchStartTime) {
  133. touch0 = d3.event.touches.item(0);
  134. var dx = (touch0.pageX-startTouchCenter[0]);
  135. var dy = (touch0.pageY-startTouchCenter[1]);
  136. var d = Math.abs(dx*dx+dy*dy);
  137. if (d > 64) {
  138. clearTimeout(touchStartTime);
  139. touchStartTime = null;
  140. }
  141. } else if (lasso) {
  142. d3.event.preventDefault();
  143. }
  144. canvasMouseMove.call(this);
  145. } else {
  146. touch0 = d3.event.touches.item(0);
  147. var touch1 = d3.event.touches.item(1);
  148. var a = touch0['pageY']-touch1['pageY'];
  149. var b = touch0['pageX']-touch1['pageX'];
  150. var offset = $("#chart").offset();
  151. var scrollPos = [$("#chart").scrollLeft(),$("#chart").scrollTop()];
  152. var moveTouchDistance = Math.sqrt((a*a)+(b*b));
  153. var touchCenter = [
  154. touch1['pageX']+(b/2),
  155. touch1['pageY']+(a/2)
  156. ];
  157. if (!isNaN(moveTouchDistance)) {
  158. oldScaleFactor = scaleFactor;
  159. scaleFactor = Math.min(2,Math.max(0.3, scaleFactor + (Math.floor(((moveTouchDistance*100)-(startTouchDistance*100)))/10000)));
  160. var deltaTouchCenter = [ // Try to pan whilst zooming - not 100%
  161. startTouchCenter[0]*(scaleFactor-oldScaleFactor),//-(touchCenter[0]-moveTouchCenter[0]),
  162. startTouchCenter[1]*(scaleFactor-oldScaleFactor) //-(touchCenter[1]-moveTouchCenter[1])
  163. ];
  164. startTouchDistance = moveTouchDistance;
  165. moveTouchCenter = touchCenter;
  166. $("#chart").scrollLeft(scrollPos[0]+deltaTouchCenter[0]);
  167. $("#chart").scrollTop(scrollPos[1]+deltaTouchCenter[1]);
  168. redraw();
  169. }
  170. }
  171. });
  172. var outer_background = vis.append('svg:rect')
  173. .attr('width', space_width)
  174. .attr('height', space_height)
  175. .attr('fill','#fff');
  176. //var gridScale = d3.scale.linear().range([0,2000]).domain([0,2000]);
  177. //var grid = vis.append('g');
  178. //
  179. //grid.selectAll("line.horizontal").data(gridScale.ticks(100)).enter()
  180. // .append("line")
  181. // .attr(
  182. // {
  183. // "class":"horizontal",
  184. // "x1" : 0,
  185. // "x2" : 2000,
  186. // "y1" : function(d){ return gridScale(d);},
  187. // "y2" : function(d){ return gridScale(d);},
  188. // "fill" : "none",
  189. // "shape-rendering" : "crispEdges",
  190. // "stroke" : "#eee",
  191. // "stroke-width" : "1px"
  192. // });
  193. //grid.selectAll("line.vertical").data(gridScale.ticks(100)).enter()
  194. // .append("line")
  195. // .attr(
  196. // {
  197. // "class":"vertical",
  198. // "y1" : 0,
  199. // "y2" : 2000,
  200. // "x1" : function(d){ return gridScale(d);},
  201. // "x2" : function(d){ return gridScale(d);},
  202. // "fill" : "none",
  203. // "shape-rendering" : "crispEdges",
  204. // "stroke" : "#eee",
  205. // "stroke-width" : "1px"
  206. // });
  207. var drag_line = vis.append("svg:path").attr("class", "drag_line");
  208. var workspace_tabs = RED.tabs.create({
  209. id: "workspace-tabs",
  210. onchange: function(tab) {
  211. if (tab.type == "subflow") {
  212. $("#workspace-toolbar").show();
  213. } else {
  214. $("#workspace-toolbar").hide();
  215. }
  216. var chart = $("#chart");
  217. if (activeWorkspace !== 0) {
  218. workspaceScrollPositions[activeWorkspace] = {
  219. left:chart.scrollLeft(),
  220. top:chart.scrollTop()
  221. };
  222. }
  223. var scrollStartLeft = chart.scrollLeft();
  224. var scrollStartTop = chart.scrollTop();
  225. activeWorkspace = tab.id;
  226. if (workspaceScrollPositions[activeWorkspace]) {
  227. chart.scrollLeft(workspaceScrollPositions[activeWorkspace].left);
  228. chart.scrollTop(workspaceScrollPositions[activeWorkspace].top);
  229. } else {
  230. chart.scrollLeft(0);
  231. chart.scrollTop(0);
  232. }
  233. var scrollDeltaLeft = chart.scrollLeft() - scrollStartLeft;
  234. var scrollDeltaTop = chart.scrollTop() - scrollStartTop;
  235. if (mouse_position != null) {
  236. mouse_position[0] += scrollDeltaLeft;
  237. mouse_position[1] += scrollDeltaTop;
  238. }
  239. clearSelection();
  240. RED.nodes.eachNode(function(n) {
  241. n.dirty = true;
  242. });
  243. redraw();
  244. },
  245. ondblclick: function(tab) {
  246. showRenameWorkspaceDialog(tab.id);
  247. },
  248. onadd: function(tab) {
  249. var menuli = $("<li/>");
  250. var menuA = $("<a/>",{tabindex:"-1",href:"#"+tab.id}).appendTo(menuli);
  251. menuA.html(tab.label);
  252. menuA.on("click",function() {
  253. workspace_tabs.activateTab(tab.id);
  254. });
  255. $('#workspace-menu-list').append(menuli);
  256. if (workspace_tabs.count() == 1) {
  257. $('#btn-workspace-delete').parent().addClass("disabled");
  258. } else {
  259. $('#btn-workspace-delete').parent().removeClass("disabled");
  260. }
  261. },
  262. onremove: function(tab) {
  263. if (workspace_tabs.count() == 1) {
  264. $('#btn-workspace-delete').parent().addClass("disabled");
  265. } else {
  266. $('#btn-workspace-delete').parent().removeClass("disabled");
  267. }
  268. $('#workspace-menu-list a[href="#'+tab.id+'"]').parent().remove();
  269. }
  270. });
  271. var workspaceIndex = 0;
  272. function addWorkspace() {
  273. var tabId = RED.nodes.id();
  274. do {
  275. workspaceIndex += 1;
  276. } while($("#workspace-tabs a[title='Sheet "+workspaceIndex+"']").size() !== 0);
  277. var ws = {type:"tab",id:tabId,label:"Sheet "+workspaceIndex};
  278. RED.nodes.addWorkspace(ws);
  279. workspace_tabs.addTab(ws);
  280. workspace_tabs.activateTab(tabId);
  281. RED.history.push({t:'add',workspaces:[ws],dirty:dirty});
  282. RED.view.dirty(true);
  283. }
  284. $('#btn-workspace-add-tab').on("click",addWorkspace);
  285. $('#btn-workspace-add').on("click",addWorkspace);
  286. $('#btn-workspace-edit').on("click",function() {
  287. showRenameWorkspaceDialog(activeWorkspace);
  288. });
  289. $('#btn-workspace-delete').on("click",function() {
  290. deleteWorkspace(activeWorkspace);
  291. });
  292. function deleteWorkspace(id) {
  293. if (workspace_tabs.count() == 1) {
  294. return;
  295. }
  296. var ws = RED.nodes.workspace(id);
  297. $( "#node-dialog-delete-workspace" ).dialog('option','workspace',ws);
  298. $( "#node-dialog-delete-workspace-name" ).text(ws.label);
  299. $( "#node-dialog-delete-workspace" ).dialog('open');
  300. }
  301. function canvasMouseDown() {
  302. if (!mousedown_node && !mousedown_link) {
  303. selected_link = null;
  304. updateSelection();
  305. }
  306. if (mouse_mode === 0) {
  307. if (lasso) {
  308. lasso.remove();
  309. lasso = null;
  310. }
  311. if (!touchStartTime) {
  312. var point = d3.mouse(this);
  313. lasso = vis.append('rect')
  314. .attr("ox",point[0])
  315. .attr("oy",point[1])
  316. .attr("rx",2)
  317. .attr("ry",2)
  318. .attr("x",point[0])
  319. .attr("y",point[1])
  320. .attr("width",0)
  321. .attr("height",0)
  322. .attr("class","lasso");
  323. d3.event.preventDefault();
  324. }
  325. }
  326. }
  327. function canvasMouseMove() {
  328. mouse_position = d3.touches(this)[0]||d3.mouse(this);
  329. // Prevent touch scrolling...
  330. //if (d3.touches(this)[0]) {
  331. // d3.event.preventDefault();
  332. //}
  333. // TODO: auto scroll the container
  334. //var point = d3.mouse(this);
  335. //if (point[0]-container.scrollLeft < 30 && container.scrollLeft > 0) { container.scrollLeft -= 15; }
  336. //console.log(d3.mouse(this),container.offsetWidth,container.offsetHeight,container.scrollLeft,container.scrollTop);
  337. if (lasso) {
  338. var ox = parseInt(lasso.attr("ox"));
  339. var oy = parseInt(lasso.attr("oy"));
  340. var x = parseInt(lasso.attr("x"));
  341. var y = parseInt(lasso.attr("y"));
  342. var w;
  343. var h;
  344. if (mouse_position[0] < ox) {
  345. x = mouse_position[0];
  346. w = ox-x;
  347. } else {
  348. w = mouse_position[0]-x;
  349. }
  350. if (mouse_position[1] < oy) {
  351. y = mouse_position[1];
  352. h = oy-y;
  353. } else {
  354. h = mouse_position[1]-y;
  355. }
  356. lasso
  357. .attr("x",x)
  358. .attr("y",y)
  359. .attr("width",w)
  360. .attr("height",h)
  361. ;
  362. return;
  363. }
  364. if (mouse_mode != RED.state.IMPORT_DRAGGING && !mousedown_node && selected_link == null) {
  365. return;
  366. }
  367. var mousePos;
  368. if (mouse_mode == RED.state.JOINING) {
  369. // update drag line
  370. drag_line.attr("class", "drag_line");
  371. mousePos = mouse_position;
  372. var numOutputs = (mousedown_port_type === 0)?(mousedown_node.outputs || 1):(mousedown_node._def.inputs || 1);
  373. var sourcePort = mousedown_port_index;
  374. var portY = -((numOutputs-1)/2)*13 +13*sourcePort;
  375. var sc = (mousedown_port_type === 0)?1:-1;
  376. var dy = mousePos[1]-(mousedown_node.y+portY);
  377. var dx = mousePos[0]-(mousedown_node.x+sc*mousedown_node.w/2);
  378. var delta = Math.sqrt(dy*dy+dx*dx);
  379. var scale = lineCurveScale;
  380. var scaleY = 0;
  381. if (delta < node_width) {
  382. scale = 0.75-0.75*((node_width-delta)/node_width);
  383. }
  384. if (dx*sc < 0) {
  385. scale += 2*(Math.min(5*node_width,Math.abs(dx))/(5*node_width));
  386. if (Math.abs(dy) < 3*node_height) {
  387. scaleY = ((dy>0)?0.5:-0.5)*(((3*node_height)-Math.abs(dy))/(3*node_height))*(Math.min(node_width,Math.abs(dx))/(node_width)) ;
  388. }
  389. }
  390. drag_line.attr("d",
  391. "M "+(mousedown_node.x+sc*mousedown_node.w/2)+" "+(mousedown_node.y+portY)+
  392. " C "+(mousedown_node.x+sc*(mousedown_node.w/2+node_width*scale))+" "+(mousedown_node.y+portY+scaleY*node_height)+" "+
  393. (mousePos[0]-sc*(scale)*node_width)+" "+(mousePos[1]-scaleY*node_height)+" "+
  394. mousePos[0]+" "+mousePos[1]
  395. );
  396. d3.event.preventDefault();
  397. } else if (mouse_mode == RED.state.MOVING) {
  398. mousePos = mouse_position;
  399. var d = (mouse_offset[0]-mousePos[0])*(mouse_offset[0]-mousePos[0]) + (mouse_offset[1]-mousePos[1])*(mouse_offset[1]-mousePos[1]);
  400. if (d > 2) {
  401. mouse_mode = RED.state.MOVING_ACTIVE;
  402. clickElapsed = 0;
  403. }
  404. } else if (mouse_mode == RED.state.MOVING_ACTIVE || mouse_mode == RED.state.IMPORT_DRAGGING) {
  405. mousePos = mouse_position;
  406. var node;
  407. var i;
  408. var minX = 0;
  409. var minY = 0;
  410. for (var n = 0; n<moving_set.length; n++) {
  411. node = moving_set[n];
  412. if (d3.event.shiftKey) {
  413. node.n.ox = node.n.x;
  414. node.n.oy = node.n.y;
  415. }
  416. node.n.x = mousePos[0]+node.dx;
  417. node.n.y = mousePos[1]+node.dy;
  418. node.n.dirty = true;
  419. minX = Math.min(node.n.x-node.n.w/2-5,minX);
  420. minY = Math.min(node.n.y-node.n.h/2-5,minY);
  421. }
  422. if (minX !== 0 || minY !== 0) {
  423. for (i = 0; i<moving_set.length; i++) {
  424. node = moving_set[i];
  425. node.n.x -= minX;
  426. node.n.y -= minY;
  427. }
  428. }
  429. if (d3.event.shiftKey && moving_set.length > 0) {
  430. var gridOffset = [0,0];
  431. node = moving_set[0];
  432. gridOffset[0] = node.n.x-(20*Math.floor((node.n.x-node.n.w/2)/20)+node.n.w/2);
  433. gridOffset[1] = node.n.y-(20*Math.floor(node.n.y/20));
  434. if (gridOffset[0] !== 0 || gridOffset[1] !== 0) {
  435. for (i = 0; i<moving_set.length; i++) {
  436. node = moving_set[i];
  437. node.n.x -= gridOffset[0];
  438. node.n.y -= gridOffset[1];
  439. if (node.n.x == node.n.ox && node.n.y == node.n.oy) {
  440. node.dirty = false;
  441. }
  442. }
  443. }
  444. }
  445. }
  446. redraw();
  447. }
  448. function canvasMouseUp() {
  449. if (mousedown_node && mouse_mode == RED.state.JOINING) {
  450. drag_line.attr("class", "drag_line_hidden");
  451. }
  452. if (lasso) {
  453. var x = parseInt(lasso.attr("x"));
  454. var y = parseInt(lasso.attr("y"));
  455. var x2 = x+parseInt(lasso.attr("width"));
  456. var y2 = y+parseInt(lasso.attr("height"));
  457. if (!d3.event.ctrlKey) {
  458. clearSelection();
  459. }
  460. RED.nodes.eachNode(function(n) {
  461. if (n.z == activeWorkspace && !n.selected) {
  462. n.selected = (n.x > x && n.x < x2 && n.y > y && n.y < y2);
  463. if (n.selected) {
  464. n.dirty = true;
  465. moving_set.push({n:n});
  466. }
  467. }
  468. });
  469. updateSelection();
  470. lasso.remove();
  471. lasso = null;
  472. } else if (mouse_mode == RED.state.DEFAULT && mousedown_link == null) {
  473. clearSelection();
  474. updateSelection();
  475. }
  476. if (mouse_mode == RED.state.MOVING_ACTIVE) {
  477. if (moving_set.length > 0) {
  478. var ns = [];
  479. for (var j=0;j<moving_set.length;j++) {
  480. ns.push({n:moving_set[j].n,ox:moving_set[j].ox,oy:moving_set[j].oy});
  481. }
  482. RED.history.push({t:'move',nodes:ns,dirty:dirty});
  483. }
  484. }
  485. if (mouse_mode == RED.state.MOVING || mouse_mode == RED.state.MOVING_ACTIVE) {
  486. for (var i=0;i<moving_set.length;i++) {
  487. delete moving_set[i].ox;
  488. delete moving_set[i].oy;
  489. }
  490. }
  491. if (mouse_mode == RED.state.IMPORT_DRAGGING) {
  492. RED.keyboard.remove(/* ESCAPE */ 27);
  493. setDirty(true);
  494. }
  495. redraw();
  496. // clear mouse event vars
  497. resetMouseVars();
  498. }
  499. $('#btn-zoom-out').click(function() {zoomOut();});
  500. $('#btn-zoom-zero').click(function() {zoomZero();});
  501. $('#btn-zoom-in').click(function() {zoomIn();});
  502. $("#chart").on('DOMMouseScroll mousewheel', function (evt) {
  503. if ( evt.altKey ) {
  504. evt.preventDefault();
  505. evt.stopPropagation();
  506. var move = -(evt.originalEvent.detail) || evt.originalEvent.wheelDelta;
  507. if (move <= 0) { zoomOut(); }
  508. else { zoomIn(); }
  509. }
  510. });
  511. $("#chart").droppable({
  512. accept:".palette_node",
  513. drop: function( event, ui ) {
  514. d3.event = event;
  515. var selected_tool = ui.draggable[0].type;
  516. var mousePos = d3.touches(this)[0]||d3.mouse(this);
  517. mousePos[1] += this.scrollTop;
  518. mousePos[0] += this.scrollLeft;
  519. mousePos[1] /= scaleFactor;
  520. mousePos[0] /= scaleFactor;
  521. var nn = { id:(1+Math.random()*4294967295).toString(16),x: mousePos[0],y:mousePos[1],w:node_width,z:activeWorkspace};
  522. nn.type = selected_tool;
  523. nn._def = RED.nodes.getType(nn.type);
  524. nn.outputs = nn._def.outputs;
  525. nn.changed = true;
  526. for (var d in nn._def.defaults) {
  527. if (nn._def.defaults.hasOwnProperty(d)) {
  528. nn[d] = nn._def.defaults[d].value;
  529. }
  530. }
  531. if (nn._def.onadd) {
  532. nn._def.onadd.call(nn);
  533. }
  534. nn.h = Math.max(node_height,(nn.outputs||0) * 15);
  535. RED.history.push({t:'add',nodes:[nn.id],dirty:dirty});
  536. RED.nodes.add(nn);
  537. RED.editor.validateNode(nn);
  538. setDirty(true);
  539. // auto select dropped node - so info shows (if visible)
  540. clearSelection();
  541. nn.selected = true;
  542. moving_set.push({n:nn});
  543. updateSelection();
  544. redraw();
  545. if (nn._def.autoedit) {
  546. RED.editor.edit(nn);
  547. }
  548. }
  549. });
  550. function zoomIn() {
  551. if (scaleFactor < 2) {
  552. scaleFactor += 0.1;
  553. redraw();
  554. }
  555. }
  556. function zoomOut() {
  557. if (scaleFactor > 0.3) {
  558. scaleFactor -= 0.1;
  559. redraw();
  560. }
  561. }
  562. function zoomZero() {
  563. scaleFactor = 1;
  564. redraw();
  565. }
  566. function selectAll() {
  567. RED.nodes.eachNode(function(n) {
  568. if (n.z == activeWorkspace) {
  569. if (!n.selected) {
  570. n.selected = true;
  571. n.dirty = true;
  572. moving_set.push({n:n});
  573. }
  574. }
  575. });
  576. selected_link = null;
  577. updateSelection();
  578. redraw();
  579. }
  580. function clearSelection() {
  581. for (var i=0;i<moving_set.length;i++) {
  582. var n = moving_set[i];
  583. n.n.dirty = true;
  584. n.n.selected = false;
  585. }
  586. moving_set = [];
  587. selected_link = null;
  588. }
  589. function updateSelection() {
  590. if (moving_set.length === 0) {
  591. $("#li-menu-export").addClass("disabled");
  592. $("#li-menu-export-clipboard").addClass("disabled");
  593. $("#li-menu-export-library").addClass("disabled");
  594. } else {
  595. $("#li-menu-export").removeClass("disabled");
  596. $("#li-menu-export-clipboard").removeClass("disabled");
  597. $("#li-menu-export-library").removeClass("disabled");
  598. }
  599. if (moving_set.length === 0 && selected_link == null) {
  600. RED.keyboard.remove(/* backspace */ 8);
  601. RED.keyboard.remove(/* delete */ 46);
  602. RED.keyboard.remove(/* c */ 67);
  603. RED.keyboard.remove(/* x */ 88);
  604. } else {
  605. RED.keyboard.add(/* backspace */ 8,function(){deleteSelection();d3.event.preventDefault();});
  606. RED.keyboard.add(/* delete */ 46,function(){deleteSelection();d3.event.preventDefault();});
  607. RED.keyboard.add(/* c */ 67,{ctrl:true},function(){copySelection();d3.event.preventDefault();});
  608. RED.keyboard.add(/* x */ 88,{ctrl:true},function(){copySelection();deleteSelection();d3.event.preventDefault();});
  609. }
  610. if (moving_set.length === 0) {
  611. RED.keyboard.remove(/* up */ 38);
  612. RED.keyboard.remove(/* down */ 40);
  613. RED.keyboard.remove(/* left */ 37);
  614. RED.keyboard.remove(/* right*/ 39);
  615. } else {
  616. RED.keyboard.add(/* up */ 38, function() { if(d3.event.shiftKey){moveSelection( 0,-20)}else{moveSelection( 0,-1);}d3.event.preventDefault();},endKeyboardMove);
  617. RED.keyboard.add(/* down */ 40, function() { if(d3.event.shiftKey){moveSelection( 0, 20)}else{moveSelection( 0, 1);}d3.event.preventDefault();},endKeyboardMove);
  618. RED.keyboard.add(/* left */ 37, function() { if(d3.event.shiftKey){moveSelection(-20, 0)}else{moveSelection(-1, 0);}d3.event.preventDefault();},endKeyboardMove);
  619. RED.keyboard.add(/* right*/ 39, function() { if(d3.event.shiftKey){moveSelection( 20, 0)}else{moveSelection( 1, 0);}d3.event.preventDefault();},endKeyboardMove);
  620. }
  621. if (moving_set.length == 1) {
  622. RED.sidebar.info.refresh(moving_set[0].n);
  623. } else {
  624. RED.sidebar.info.clear();
  625. }
  626. }
  627. function endKeyboardMove() {
  628. var ns = [];
  629. for (var i=0;i<moving_set.length;i++) {
  630. ns.push({n:moving_set[i].n,ox:moving_set[i].ox,oy:moving_set[i].oy});
  631. delete moving_set[i].ox;
  632. delete moving_set[i].oy;
  633. }
  634. RED.history.push({t:'move',nodes:ns,dirty:dirty});
  635. }
  636. function moveSelection(dx,dy) {
  637. var minX = 0;
  638. var minY = 0;
  639. var node;
  640. for (var i=0;i<moving_set.length;i++) {
  641. node = moving_set[i];
  642. if (node.ox == null && node.oy == null) {
  643. node.ox = node.n.x;
  644. node.oy = node.n.y;
  645. }
  646. node.n.x += dx;
  647. node.n.y += dy;
  648. node.n.dirty = true;
  649. minX = Math.min(node.n.x-node.n.w/2-5,minX);
  650. minY = Math.min(node.n.y-node.n.h/2-5,minY);
  651. }
  652. if (minX !== 0 || minY !== 0) {
  653. for (var n = 0; n<moving_set.length; n++) {
  654. node = moving_set[n];
  655. node.n.x -= minX;
  656. node.n.y -= minY;
  657. }
  658. }
  659. redraw();
  660. }
  661. function deleteSelection() {
  662. var removedNodes = [];
  663. var removedLinks = [];
  664. var startDirty = dirty;
  665. if (moving_set.length > 0) {
  666. for (var i=0;i<moving_set.length;i++) {
  667. var node = moving_set[i].n;
  668. node.selected = false;
  669. if (node.x < 0) {
  670. node.x = 25
  671. }
  672. var rmlinks = RED.nodes.remove(node.id);
  673. removedNodes.push(node);
  674. removedLinks = removedLinks.concat(rmlinks);
  675. }
  676. moving_set = [];
  677. setDirty(true);
  678. }
  679. if (selected_link) {
  680. RED.nodes.removeLink(selected_link);
  681. removedLinks.push(selected_link);
  682. setDirty(true);
  683. }
  684. RED.history.push({t:'delete',nodes:removedNodes,links:removedLinks,dirty:startDirty});
  685. selected_link = null;
  686. updateSelection();
  687. redraw();
  688. }
  689. function copySelection() {
  690. if (moving_set.length > 0) {
  691. var nns = [];
  692. for (var n=0;n<moving_set.length;n++) {
  693. var node = moving_set[n].n;
  694. nns.push(RED.nodes.convertNode(node));
  695. }
  696. clipboard = JSON.stringify(nns);
  697. RED.notify(moving_set.length+" node"+(moving_set.length>1?"s":"")+" copied");
  698. }
  699. }
  700. function calculateTextWidth(str) {
  701. var sp = document.createElement("span");
  702. sp.className = "node_label";
  703. sp.style.position = "absolute";
  704. sp.style.top = "-1000px";
  705. sp.innerHTML = (str||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
  706. document.body.appendChild(sp);
  707. var w = sp.offsetWidth;
  708. document.body.removeChild(sp);
  709. return 50+w;
  710. }
  711. function resetMouseVars() {
  712. mousedown_node = null;
  713. mouseup_node = null;
  714. mousedown_link = null;
  715. mouse_mode = 0;
  716. mousedown_port_type = 0;
  717. }
  718. function portMouseDown(d,portType,portIndex) {
  719. // disable zoom
  720. //vis.call(d3.behavior.zoom().on("zoom"), null);
  721. mousedown_node = d;
  722. selected_link = null;
  723. mouse_mode = RED.state.JOINING;
  724. mousedown_port_type = portType;
  725. mousedown_port_index = portIndex || 0;
  726. document.body.style.cursor = "crosshair";
  727. d3.event.preventDefault();
  728. }
  729. function portMouseUp(d,portType,portIndex) {
  730. document.body.style.cursor = "";
  731. if (mouse_mode == RED.state.JOINING && mousedown_node) {
  732. if (typeof TouchEvent != "undefined" && d3.event instanceof TouchEvent) {
  733. RED.nodes.eachNode(function(n) {
  734. if (n.z == activeWorkspace) {
  735. var hw = n.w/2;
  736. var hh = n.h/2;
  737. if (n.x-hw<mouse_position[0] && n.x+hw> mouse_position[0] &&
  738. n.y-hh<mouse_position[1] && n.y+hh>mouse_position[1]) {
  739. mouseup_node = n;
  740. portType = mouseup_node._def.inputs>0?1:0;
  741. portIndex = 0;
  742. }
  743. }
  744. });
  745. } else {
  746. mouseup_node = d;
  747. }
  748. if (portType == mousedown_port_type || mouseup_node === mousedown_node) {
  749. drag_line.attr("class", "drag_line_hidden");
  750. resetMouseVars();
  751. return;
  752. }
  753. var src,dst,src_port,dst_port;
  754. if (mousedown_port_type === 0) {
  755. src = mousedown_node;
  756. src_port = mousedown_port_index;
  757. dst = mouseup_node;
  758. dst_port = portIndex;
  759. } else if (mousedown_port_type == 1) {
  760. src = mouseup_node;
  761. src_port = portIndex;
  762. dst = mousedown_node;
  763. dst_port = mousedown_port_index;
  764. }
  765. var existingLink = false;
  766. RED.nodes.eachLink(function(d) {
  767. existingLink = existingLink || (d.source === src && d.target === dst && d.sourcePort == src_port && d.targetPort == dst_port);
  768. });
  769. if (!existingLink) {
  770. var link = {source: src, sourcePort:src_port, target: dst, targetPort: dst_port};
  771. RED.nodes.addLink(link);
  772. RED.history.push({t:'add',links:[link],dirty:dirty});
  773. setDirty(true);
  774. }
  775. selected_link = null;
  776. redraw();
  777. }
  778. }
  779. function nodeMouseUp(d) {
  780. if (dblClickPrimed && mousedown_node == d && clickElapsed > 0 && clickElapsed < 750) {
  781. RED.editor.edit(d);
  782. clickElapsed = 0;
  783. d3.event.stopPropagation();
  784. return;
  785. }
  786. portMouseUp(d, d._def.inputs > 0 ? 1 : 0, 0);
  787. }
  788. function nodeMouseDown(d) {
  789. //var touch0 = d3.event;
  790. //var pos = [touch0.pageX,touch0.pageY];
  791. //RED.touch.radialMenu.show(d3.select(this),pos);
  792. if (mouse_mode == RED.state.IMPORT_DRAGGING) {
  793. RED.keyboard.remove(/* ESCAPE */ 27);
  794. updateSelection();
  795. setDirty(true);
  796. redraw();
  797. resetMouseVars();
  798. d3.event.stopPropagation();
  799. return;
  800. }
  801. mousedown_node = d;
  802. var now = Date.now();
  803. clickElapsed = now-clickTime;
  804. clickTime = now;
  805. dblClickPrimed = (lastClickNode == mousedown_node);
  806. lastClickNode = mousedown_node;
  807. var i;
  808. if (d.selected && d3.event.ctrlKey) {
  809. d.selected = false;
  810. for (i=0;i<moving_set.length;i+=1) {
  811. if (moving_set[i].n === d) {
  812. moving_set.splice(i,1);
  813. break;
  814. }
  815. }
  816. } else {
  817. if (d3.event.shiftKey) {
  818. clearSelection();
  819. var cnodes = RED.nodes.getAllFlowNodes(mousedown_node);
  820. for (var n=0;n<cnodes.length;n++) {
  821. cnodes[n].selected = true;
  822. cnodes[n].dirty = true;
  823. moving_set.push({n:cnodes[n]});
  824. }
  825. } else if (!d.selected) {
  826. if (!d3.event.ctrlKey) {
  827. clearSelection();
  828. }
  829. mousedown_node.selected = true;
  830. moving_set.push({n:mousedown_node});
  831. }
  832. selected_link = null;
  833. if (d3.event.button != 2) {
  834. mouse_mode = RED.state.MOVING;
  835. var mouse = d3.touches(this)[0]||d3.mouse(this);
  836. mouse[0] += d.x-d.w/2;
  837. mouse[1] += d.y-d.h/2;
  838. for (i=0;i<moving_set.length;i++) {
  839. moving_set[i].ox = moving_set[i].n.x;
  840. moving_set[i].oy = moving_set[i].n.y;
  841. moving_set[i].dx = moving_set[i].n.x-mouse[0];
  842. moving_set[i].dy = moving_set[i].n.y-mouse[1];
  843. }
  844. mouse_offset = d3.mouse(document.body);
  845. if (isNaN(mouse_offset[0])) {
  846. mouse_offset = d3.touches(document.body)[0];
  847. }
  848. }
  849. }
  850. d.dirty = true;
  851. updateSelection();
  852. redraw();
  853. d3.event.stopPropagation();
  854. }
  855. function nodeButtonClicked(d) {
  856. if (d._def.button.toggle) {
  857. d[d._def.button.toggle] = !d[d._def.button.toggle];
  858. d.dirty = true;
  859. }
  860. if (d._def.button.onclick) {
  861. d._def.button.onclick.call(d);
  862. }
  863. if (d.dirty) {
  864. redraw();
  865. }
  866. d3.event.preventDefault();
  867. }
  868. function showTouchMenu(obj,pos) {
  869. var mdn = mousedown_node;
  870. var options = [];
  871. options.push({name:"delete",disabled:(moving_set.length===0),onselect:function() {deleteSelection();}});
  872. options.push({name:"cut",disabled:(moving_set.length===0),onselect:function() {copySelection();deleteSelection();}});
  873. options.push({name:"copy",disabled:(moving_set.length===0),onselect:function() {copySelection();}});
  874. options.push({name:"paste",disabled:(clipboard.length===0),onselect:function() {importNodes(clipboard,true);}});
  875. options.push({name:"edit",disabled:(moving_set.length != 1),onselect:function() { RED.editor.edit(mdn);}});
  876. options.push({name:"select",onselect:function() {selectAll();}});
  877. options.push({name:"undo",disabled:(RED.history.depth() === 0),onselect:function() {RED.history.pop();}});
  878. RED.touch.radialMenu.show(obj,pos,options);
  879. resetMouseVars();
  880. }
  881. function redraw() {
  882. vis.attr("transform","scale("+scaleFactor+")");
  883. outer.attr("width", space_width*scaleFactor).attr("height", space_height*scaleFactor);
  884. if (mouse_mode != RED.state.JOINING) {
  885. // Don't bother redrawing nodes if we're drawing links
  886. var node = vis.selectAll(".nodegroup").data(RED.nodes.nodes.filter(function(d) { return d.z == activeWorkspace }),function(d){return d.id});
  887. node.exit().remove();
  888. var nodeEnter = node.enter().insert("svg:g").attr("class", "node nodegroup");
  889. nodeEnter.each(function(d,i) {
  890. var node = d3.select(this);
  891. node.attr("id",d.id);
  892. var l = d._def.label;
  893. l = (typeof l === "function" ? l.call(d) : l)||"";
  894. d.w = Math.max(node_width,calculateTextWidth(l)+(d._def.inputs>0?7:0) );
  895. d.h = Math.max(node_height,(Math.max(d.outputs,d._def.inputs)||0) * 15);
  896. if (d._def.badge) {
  897. var badge = node.append("svg:g").attr("class","node_badge_group");
  898. var badgeRect = badge.append("rect").attr("class","node_badge").attr("rx",5).attr("ry",5).attr("width",40).attr("height",15);
  899. badge.append("svg:text").attr("class","node_badge_label").attr("x",35).attr("y",11).attr('text-anchor','end').text(d._def.badge());
  900. if (d._def.onbadgeclick) {
  901. badgeRect.attr("cursor","pointer")
  902. .on("click",function(d) { d._def.onbadgeclick.call(d);d3.event.preventDefault();});
  903. }
  904. }
  905. if (d._def.button) {
  906. var nodeButtonGroup = node.append('svg:g')
  907. .attr("transform",function(d) { return "translate("+((d._def.align == "right") ? 94 : -25)+",2)"; })
  908. .attr("class",function(d) { return "node_button "+((d._def.align == "right") ? "node_right_button" : "node_left_button"); });
  909. nodeButtonGroup.append('rect')
  910. .attr("rx",8)
  911. .attr("ry",8)
  912. .attr("width",32)
  913. .attr("height",node_height-4)
  914. .attr("fill","#eee");//function(d) { return d._def.color;})
  915. nodeButtonGroup.append('rect')
  916. .attr("x",function(d) { return d._def.align == "right"? 10:5})
  917. .attr("y",4)
  918. .attr("rx",5)
  919. .attr("ry",5)
  920. .attr("width",16)
  921. .attr("height",node_height-12)
  922. .attr("fill",function(d) { return d._def.color;})
  923. .attr("cursor","pointer")
  924. .on("mousedown",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",0.2);d3.event.preventDefault(); d3.event.stopPropagation();}})
  925. .on("mouseup",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",0.4);d3.event.preventDefault();d3.event.stopPropagation();}})
  926. .on("mouseover",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",0.4);}})
  927. .on("mouseout",function(d) {if (!lasso) {
  928. var op = 1;
  929. if (d._def.button.toggle) {
  930. op = d[d._def.button.toggle]?1:0.2;
  931. }
  932. d3.select(this).attr("fill-opacity",op);
  933. }})
  934. .on("click",nodeButtonClicked)
  935. .on("touchstart",nodeButtonClicked)
  936. }
  937. var mainRect = node.append("rect")
  938. .attr("class", "node")
  939. .classed("node_unknown",function(d) { return d.type == "unknown"; })
  940. .attr("rx", 6)
  941. .attr("ry", 6)
  942. .attr("fill",function(d) { return d._def.color;})
  943. .on("mouseup",nodeMouseUp)
  944. .on("mousedown",nodeMouseDown)
  945. .on("touchstart",function(d) {
  946. var obj = d3.select(this);
  947. var touch0 = d3.event.touches.item(0);
  948. var pos = [touch0.pageX,touch0.pageY];
  949. startTouchCenter = [touch0.pageX,touch0.pageY];
  950. startTouchDistance = 0;
  951. touchStartTime = setTimeout(function() {
  952. showTouchMenu(obj,pos);
  953. },touchLongPressTimeout);
  954. nodeMouseDown.call(this,d)
  955. })
  956. .on("touchend", function(d) {
  957. clearTimeout(touchStartTime);
  958. touchStartTime = null;
  959. if (RED.touch.radialMenu.active()) {
  960. d3.event.stopPropagation();
  961. return;
  962. }
  963. nodeMouseUp.call(this,d);
  964. })
  965. .on("mouseover",function(d) {
  966. if (mouse_mode === 0) {
  967. var node = d3.select(this);
  968. node.classed("node_hovered",true);
  969. }
  970. })
  971. .on("mouseout",function(d) {
  972. var node = d3.select(this);
  973. node.classed("node_hovered",false);
  974. });
  975. //node.append("rect").attr("class", "node-gradient-top").attr("rx", 6).attr("ry", 6).attr("height",30).attr("stroke","none").attr("fill","url(#gradient-top)").style("pointer-events","none");
  976. //node.append("rect").attr("class", "node-gradient-bottom").attr("rx", 6).attr("ry", 6).attr("height",30).attr("stroke","none").attr("fill","url(#gradient-bottom)").style("pointer-events","none");
  977. if (d._def.icon) {
  978. var icon_group = node.append("g")
  979. .attr("class","node_icon_group")
  980. .attr("x",0).attr("y",0);
  981. var icon_shade = icon_group.append("rect")
  982. .attr("x",0).attr("y",0)
  983. .attr("class","node_icon_shade")
  984. .attr("width","30")
  985. .attr("stroke","none")
  986. .attr("fill","#000")
  987. .attr("fill-opacity","0.05")
  988. .attr("height",function(d){return Math.min(50,d.h-4);});
  989. var icon = icon_group.append("image")
  990. .attr("xlink:href","icons/"+d._def.icon)
  991. .attr("class","node_icon")
  992. .attr("x",0)
  993. .attr("width","30")
  994. .attr("height","30");
  995. var icon_shade_border = icon_group.append("path")
  996. .attr("d",function(d) { return "M 30 1 l 0 "+(d.h-2)})
  997. .attr("class","node_icon_shade_border")
  998. .attr("stroke-opacity","0.1")
  999. .attr("stroke","#000")
  1000. .attr("stroke-width","2");
  1001. if ("right" == d._def.align) {
  1002. icon_group.attr('class','node_icon_group node_icon_group_'+d._def.align);
  1003. icon_shade_border.attr("d",function(d) { return "M 0 1 l 0 "+(d.h-2)})
  1004. //icon.attr('class','node_icon node_icon_'+d._def.align);
  1005. //icon.attr('class','node_icon_shade node_icon_shade_'+d._def.align);
  1006. //icon.attr('class','node_icon_shade_border node_icon_shade_border_'+d._def.align);
  1007. }
  1008. //if (d._def.inputs > 0 && d._def.align == null) {
  1009. // icon_shade.attr("width",35);
  1010. // icon.attr("transform","translate(5,0)");
  1011. // icon_shade_border.attr("transform","translate(5,0)");
  1012. //}
  1013. //if (d._def.outputs > 0 && "right" == d._def.align) {
  1014. // icon_shade.attr("width",35); //icon.attr("x",5);
  1015. //}
  1016. var img = new Image();
  1017. img.src = "icons/"+d._def.icon;
  1018. img.onload = function() {
  1019. icon.attr("width",Math.min(img.width,30));
  1020. icon.attr("height",Math.min(img.height,30));
  1021. icon.attr("x",15-Math.min(img.width,30)/2);
  1022. //if ("right" == d._def.align) {
  1023. // icon.attr("x",function(d){return d.w-img.width-1-(d.outputs>0?5:0);});
  1024. // icon_shade.attr("x",function(d){return d.w-30});
  1025. // icon_shade_border.attr("d",function(d){return "M "+(d.w-30)+" 1 l 0 "+(d.h-2);});
  1026. //}
  1027. }
  1028. //icon.style("pointer-events","none");
  1029. icon_group.style("pointer-events","none");
  1030. }
  1031. var text = node.append('svg:text').attr('class','node_label').attr('x', 38).attr('dy', '.35em').attr('text-anchor','start');
  1032. if (d._def.align) {
  1033. text.attr('class','node_label node_label_'+d._def.align);
  1034. text.attr('text-anchor','end');
  1035. }
  1036. var status = node.append("svg:g").attr("class","node_status_group").style("display","none");
  1037. var statusRect = status.append("rect").attr("class","node_status")
  1038. .attr("x",6).attr("y",1).attr("width",9).attr("height",9)
  1039. .attr("rx",2).attr("ry",2).attr("stroke-width","3");
  1040. var statusLabel = status.append("svg:text")
  1041. .attr("class","node_status_label")
  1042. .attr('x',20).attr('y',9)
  1043. .style({
  1044. 'stroke-width': 0,
  1045. 'fill': '#888',
  1046. 'font-size':'9pt',
  1047. 'stroke':'#000',
  1048. 'text-anchor':'start'
  1049. });
  1050. //node.append("circle").attr({"class":"centerDot","cx":0,"cy":0,"r":5});
  1051. var numInputs = d._def.inputs;
  1052. for (var n=0; n < numInputs; n++) {
  1053. var y = (d.h/2)-((numInputs-1)/2)*13;
  1054. y = (y+13*n)-5;
  1055. text.attr("x",38);
  1056. node.append("rect").attr("class","port port_input").attr("rx",3).attr("ry",3).attr("y",y).attr("x",-5).attr("width",10).attr("height",10)
  1057. .on("mousedown", (function(nn){return function(d){portMouseDown(d,1,nn);}})(n))
  1058. .on("touchstart", (function(nn){return function(d){portMouseDown(d,1,nn);}})(n))
  1059. .on("mouseup", (function(nn){return function(d){portMouseUp(d,1,nn);}})(n))
  1060. .on("touchend", (function(nn){return function(d){portMouseUp(d,1,nn);}})(n))
  1061. .on("mouseover",function(d) { var port = d3.select(this); port.classed("port_hovered",(mouse_mode!=RED.state.JOINING || mousedown_port_type != 1 ));})
  1062. .on("mouseout",function(d) { var port = d3.select(this); port.classed("port_hovered",false);})
  1063. }
  1064. //node.append("path").attr("class","node_error").attr("d","M 3,-3 l 10,0 l -5,-8 z");
  1065. node.append("image").attr("class","node_error hidden").attr("xlink:href","icons/node-error.png").attr("x",0).attr("y",-6).attr("width",10).attr("height",9);
  1066. node.append("image").attr("class","node_changed hidden").attr("xlink:href","icons/node-changed.png").attr("x",12).attr("y",-6).attr("width",10).attr("height",10);
  1067. });
  1068. node.each(function(d,i) {
  1069. if (d.dirty) {
  1070. //if (d.x < -50) deleteSelection(); // Delete nodes if dragged back to palette
  1071. if (d.resize) {
  1072. var l = d._def.label;
  1073. l = (typeof l === "function" ? l.call(d) : l)||"";
  1074. d.w = Math.max(node_width,calculateTextWidth(l)+(d._def.inputs>0?7:0) );
  1075. d.h = Math.max(node_height,(Math.max(d.outputs,d._def.inputs)||0) * 15);
  1076. }
  1077. var thisNode = d3.select(this);
  1078. //thisNode.selectAll(".centerDot").attr({"cx":function(d) { return d.w/2;},"cy":function(d){return d.h/2}});
  1079. thisNode.attr("transform", function(d) { return "translate(" + (d.x-d.w/2) + "," + (d.y-d.h/2) + ")"; });
  1080. thisNode.selectAll(".node")
  1081. .attr("width",function(d){return d.w})
  1082. .attr("height",function(d){return d.h})
  1083. .classed("node_selected",function(d) { return d.selected; })
  1084. .classed("node_highlighted",function(d) { return d.highlighted; })
  1085. ;
  1086. //thisNode.selectAll(".node-gradient-top").attr("width",function(d){return d.w});
  1087. //thisNode.selectAll(".node-gradient-bottom").attr("width",function(d){return d.w}).attr("y",function(d){return d.h-30});
  1088. thisNode.selectAll(".node_icon_group_right").attr('transform', function(d){return "translate("+(d.w-30)+",0)"});
  1089. thisNode.selectAll(".node_label_right").attr('x', function(d){return d.w-38});
  1090. //thisNode.selectAll(".node_icon_right").attr("x",function(d){return d.w-d3.select(this).attr("width")-1-(d.outputs>0?5:0);});
  1091. //thisNode.selectAll(".node_icon_shade_right").attr("x",function(d){return d.w-30;});
  1092. //thisNode.selectAll(".node_icon_shade_border_right").attr("d",function(d){return "M "+(d.w-30)+" 1 l 0 "+(d.h-2)});
  1093. var numOutputs = d.outputs;
  1094. var y = (d.h/2)-((numOutputs-1)/2)*13;
  1095. d.ports = d.ports || d3.range(numOutputs);
  1096. d._ports = thisNode.selectAll(".port_output").data(d.ports);
  1097. d._ports.enter().append("rect").attr("class","port port_output").attr("rx",3).attr("ry",3).attr("width",10).attr("height",10)
  1098. .on("mousedown",(function(){var node = d; return function(d,i){portMouseDown(node,0,i);}})() )
  1099. .on("touchstart",(function(){var node = d; return function(d,i){portMouseDown(node,0,i);}})() )
  1100. .on("mouseup",(function(){var node = d; return function(d,i){portMouseUp(node,0,i);}})() )
  1101. .on("touchend",(function(){var node = d; return function(d,i){portMouseUp(node,0,i);}})() )
  1102. .on("mouseover",function(d,i) { var port = d3.select(this); port.classed("port_hovered",(mouse_mode!=RED.state.JOINING || mousedown_port_type !== 0 ));})
  1103. .on("mouseout",function(d,i) { var port = d3.select(this); port.classed("port_hovered",false);});
  1104. d._ports.exit().remove();
  1105. if (d._ports) {
  1106. numOutputs = d.outputs || 1;
  1107. y = (d.h/2)-((numOutputs-1)/2)*13;
  1108. var x = d.w - 5;
  1109. d._ports.each(function(d,i) {
  1110. var port = d3.select(this);
  1111. port.attr("y",(y+13*i)-5).attr("x",x);
  1112. });
  1113. }
  1114. thisNode.selectAll('text.node_label').text(function(d,i){
  1115. if (d._def.label) {
  1116. if (typeof d._def.label == "function") {
  1117. return d._def.label.call(d);
  1118. } else {
  1119. return d._def.label;
  1120. }
  1121. }
  1122. return "";
  1123. })
  1124. .attr('y', function(d){return (d.h/2)-1;})
  1125. .attr('class',function(d){
  1126. return 'node_label'+
  1127. (d._def.align?' node_label_'+d._def.align:'')+
  1128. (d._def.label?' '+(typeof d._def.labelStyle == "function" ? d._def.labelStyle.call(d):d._def.labelStyle):'') ;
  1129. });
  1130. thisNode.selectAll(".node_tools").attr("x",function(d){return d.w-35;}).attr("y",function(d){return d.h-20;});
  1131. thisNode.selectAll(".node_changed")
  1132. .attr("x",function(d){return d.w-10})
  1133. .classed("hidden",function(d) { return !d.changed; });
  1134. thisNode.selectAll(".node_error")
  1135. .attr("x",function(d){return d.w-10-(d.changed?13:0)})
  1136. .classed("hidden",function(d) { return d.valid; });
  1137. thisNode.selectAll(".port_input").each(function(d,i) {
  1138. var port = d3.select(this);
  1139. var numInputs = d._def.inputs;
  1140. var y = (d.h/2)-((numInputs-1)/2)*13;
  1141. y = (y+13*i)-5;
  1142. port.attr("y",y)
  1143. });
  1144. thisNode.selectAll(".node_icon").attr("y",function(d){return (d.h-d3.select(this).attr("height"))/2;});
  1145. thisNode.selectAll(".node_icon_shade").attr("height",function(d){return d.h;});
  1146. thisNode.selectAll(".node_icon_shade_border").attr("d",function(d){ return "M "+(("right" == d._def.align) ?0:30)+" 1 l 0 "+(d.h-2)});
  1147. thisNode.selectAll('.node_right_button').attr("transform",function(d){
  1148. var x = d.w-6;
  1149. if (d._def.button.toggle && !d[d._def.button.toggle]) {
  1150. x = x - 8;
  1151. }
  1152. return "translate("+x+",2)";
  1153. });
  1154. thisNode.selectAll('.node_right_button rect').attr("fill-opacity",function(d){
  1155. if (d._def.button.toggle) {
  1156. return d[d._def.button.toggle]?1:0.2;
  1157. }
  1158. return 1;
  1159. });
  1160. //thisNode.selectAll('.node_right_button').attr("transform",function(d){return "translate("+(d.w - d._def.button.width.call(d))+","+0+")";}).attr("fill",function(d) {
  1161. // return typeof d._def.button.color === "function" ? d._def.button.color.call(d):(d._def.button.color != null ? d._def.button.color : d._def.color)
  1162. //});
  1163. thisNode.selectAll('.node_badge_group').attr("transform",function(d){return "translate("+(d.w-40)+","+(d.h+3)+")";});
  1164. thisNode.selectAll('text.node_badge_label').text(function(d,i) {
  1165. if (d._def.badge) {
  1166. if (typeof d._def.badge == "function") {
  1167. return d._def.badge.call(d);
  1168. } else {
  1169. return d._def.badge;
  1170. }
  1171. }
  1172. return "";
  1173. });
  1174. if (!showStatus || !d.status) {
  1175. thisNode.selectAll('.node_status_group').style("display","none");
  1176. } else {
  1177. thisNode.selectAll('.node_status_group').style("display","inline").attr("transform","translate(3,"+(d.h+3)+")");
  1178. var fill = status_colours[d.status.fill]; // Only allow our colours for now
  1179. if (d.status.shape == null && fill == null) {
  1180. thisNode.selectAll('.node_status').style("display","none");
  1181. } else {
  1182. var style;
  1183. if (d.status.shape == null || d.status.shape == "dot") {
  1184. style = {
  1185. display: "inline",
  1186. fill: fill,
  1187. stroke: fill
  1188. };
  1189. } else if (d.status.shape == "ring" ){
  1190. style = {
  1191. display: "inline",
  1192. fill: '#fff',
  1193. stroke: fill
  1194. }
  1195. }
  1196. thisNode.selectAll('.node_status').style(style);
  1197. }
  1198. if (d.status.text) {
  1199. thisNode.selectAll('.node_status_label').text(d.status.text);
  1200. } else {
  1201. thisNode.selectAll('.node_status_label').text("");
  1202. }
  1203. }
  1204. d.dirty = false;
  1205. }
  1206. });
  1207. }
  1208. var link = vis.selectAll(".link").data(RED.nodes.links.filter(function(d) { return d.source.z == activeWorkspace && d.target.z == activeWorkspace }),function(d) { return d.source.id+":"+d.sourcePort+":"+d.target.id+":"+d.targetPort;});
  1209. var linkEnter = link.enter().insert("g",".node").attr("class","link");
  1210. linkEnter.each(function(d,i) {
  1211. var l = d3.select(this);
  1212. l.append("svg:path").attr("class","link_background link_path")
  1213. .on("mousedown",function(d) {
  1214. mousedown_link = d;
  1215. clearSelection();
  1216. selected_link = mousedown_link;
  1217. updateSelection();
  1218. redraw();
  1219. d3.event.stopPropagation();
  1220. })
  1221. .on("touchstart",function(d) {
  1222. mousedown_link = d;
  1223. clearSelection();
  1224. selected_link = mousedown_link;
  1225. updateSelection();
  1226. redraw();
  1227. d3.event.stopPropagation();
  1228. });
  1229. l.append("svg:path").attr("class","link_outline link_path");
  1230. l.append("svg:path").attr("class","link_line link_path");
  1231. });
  1232. link.exit().remove();
  1233. var links = vis.selectAll(".link_path")
  1234. links.attr("d",function(d){
  1235. var numOutputs = d.source.outputs || 1;
  1236. var sourcePort = d.sourcePort || 0;
  1237. var ysource = -((numOutputs-1)/2)*13 +13*sourcePort;
  1238. var numInputs = d.target._def.inputs || 1;
  1239. var targetPort = d.targetPort || 0;
  1240. var ytarget = -((numInputs-1)/2)*13 +13*targetPort;
  1241. var dy = (d.target.y+ytarget)-(d.source.y+ysource);
  1242. var dx = (d.target.x-d.target.w/2)-(d.source.x+d.source.w/2);
  1243. var delta = Math.sqrt(dy*dy+dx*dx);
  1244. var scale = lineCurveScale;
  1245. var scaleY = 0;
  1246. if (delta < node_width) {
  1247. scale = 0.75-0.75*((node_width-delta)/node_width);
  1248. }
  1249. if (dx < 0) {
  1250. scale += 2*(Math.min(5*node_width,Math.abs(dx))/(5*node_width));
  1251. if (Math.abs(dy) < 3*node_height) {
  1252. scaleY = ((dy>0)?0.5:-0.5)*(((3*node_height)-Math.abs(dy))/(3*node_height))*(Math.min(node_width,Math.abs(dx))/(node_width)) ;
  1253. }
  1254. }
  1255. d.x1 = d.source.x+d.source.w/2;
  1256. d.y1 = d.source.y+ysource;
  1257. d.x2 = d.target.x-d.target.w/2;
  1258. d.y2 = d.target.y+ytarget;
  1259. return "M "+(d.x1)+" "+(d.y1)+
  1260. " C "+(d.x1+scale*node_width)+" "+(d.y1+scaleY*node_height)+" "+
  1261. (d.x2-scale*node_width)+" "+(d.y2-scaleY*node_height)+" "+
  1262. (d.x2)+" "+d.y2;
  1263. })
  1264. link.classed("link_selected", function(d) { return d === selected_link || d.selected; });
  1265. link.classed("link_unknown",function(d) { return d.target.type == "unknown" || d.source.type == "unknown"});
  1266. if (d3.event) {
  1267. d3.event.preventDefault();
  1268. }
  1269. }
  1270. RED.keyboard.add(/* z */ 90,{ctrl:true},function(){RED.history.pop();});
  1271. RED.keyboard.add(/* a */ 65,{ctrl:true},function(){selectAll();d3.event.preventDefault();});
  1272. RED.keyboard.add(/* = */ 187,{ctrl:true},function(){zoomIn();d3.event.preventDefault();});
  1273. RED.keyboard.add(/* - */ 189,{ctrl:true},function(){zoomOut();d3.event.preventDefault();});
  1274. RED.keyboard.add(/* 0 */ 48,{ctrl:true},function(){zoomZero();d3.event.preventDefault();});
  1275. RED.keyboard.add(/* v */ 86,{ctrl:true},function(){importNodes(clipboard);d3.event.preventDefault();});
  1276. RED.keyboard.add(/* e */ 69,{ctrl:true},function(){showExportNodesDialog();d3.event.preventDefault();});
  1277. RED.keyboard.add(/* i */ 73,{ctrl:true},function(){showImportNodesDialog();d3.event.preventDefault();});
  1278. // TODO: 'dirty' should be a property of RED.nodes - with an event callback for ui hooks
  1279. function setDirty(d) {
  1280. dirty = d;
  1281. if (dirty) {
  1282. $("#btn-deploy").removeClass("disabled").addClass("btn-danger");
  1283. } else {
  1284. $("#btn-deploy").addClass("disabled").removeClass("btn-danger");
  1285. }
  1286. }
  1287. /**
  1288. * Imports a new collection of nodes from a JSON String.
  1289. * - all get new IDs assigned
  1290. * - all 'selected'
  1291. * - attached to mouse for placing - 'IMPORT_DRAGGING'
  1292. */
  1293. function importNodes(newNodesStr,touchImport) {
  1294. try {
  1295. var result = RED.nodes.import(newNodesStr,true);
  1296. if (result) {
  1297. var new_nodes = result[0];
  1298. var new_links = result[1];
  1299. var new_ms = new_nodes.map(function(n) { n.z = activeWorkspace; return {n:n};});
  1300. var new_node_ids = new_nodes.map(function(n){ return n.id; });
  1301. // TODO: pick a more sensible root node
  1302. var root_node = new_ms[0].n;
  1303. var dx = root_node.x;
  1304. var dy = root_node.y;
  1305. if (mouse_position == null) {
  1306. mouse_position = [0,0];
  1307. }
  1308. var minX = 0;
  1309. var minY = 0;
  1310. var i;
  1311. var node;
  1312. for (i=0;i<new_ms.length;i++) {
  1313. node = new_ms[i];
  1314. node.n.selected = true;
  1315. node.n.changed = true;
  1316. node.n.x -= dx - mouse_position[0];
  1317. node.n.y -= dy - mouse_position[1];
  1318. node.dx = node.n.x - mouse_position[0];
  1319. node.dy = node.n.y - mouse_position[1];
  1320. minX = Math.min(node.n.x-node_width/2-5,minX);
  1321. minY = Math.min(node.n.y-node_height/2-5,minY);
  1322. }
  1323. for (i=0;i<new_ms.length;i++) {
  1324. node = new_ms[i];
  1325. node.n.x -= minX;
  1326. node.n.y -= minY;
  1327. node.dx -= minX;
  1328. node.dy -= minY;
  1329. }
  1330. if (!touchImport) {
  1331. mouse_mode = RED.state.IMPORT_DRAGGING;
  1332. }
  1333. RED.keyboard.add(/* ESCAPE */ 27,function(){
  1334. RED.keyboard.remove(/* ESCAPE */ 27);
  1335. clearSelection();
  1336. RED.history.pop();
  1337. mouse_mode = 0;
  1338. });
  1339. RED.history.push({t:'add',nodes:new_node_ids,links:new_links,dirty:RED.view.dirty()});
  1340. clearSelection();
  1341. moving_set = new_ms;
  1342. redraw();
  1343. }
  1344. } catch(error) {
  1345. console.log(error);
  1346. RED.notify("<strong>Error</strong>: "+error,"error");
  1347. }
  1348. }
  1349. $('#btn-import').click(function() {showImportNodesDialog();});
  1350. $('#btn-export-clipboard').click(function() {showExportNodesDialog();});
  1351. $('#btn-export-library').click(function() {showExportNodesLibraryDialog();});
  1352. function showExportNodesDialog() {
  1353. mouse_mode = RED.state.EXPORT;
  1354. var nns = RED.nodes.createExportableNodeSet(moving_set);
  1355. $("#dialog-form").html($("script[data-template-name='export-clipboard-dialog']").html());
  1356. $("#node-input-export").val(JSON.stringify(nns));
  1357. $("#node-input-export").focus(function() {
  1358. var textarea = $(this);
  1359. textarea.select();
  1360. textarea.mouseup(function() {
  1361. textarea.unbind("mouseup");
  1362. return false;
  1363. });
  1364. });
  1365. $( "#dialog" ).dialog("option","title","Export nodes to clipboard").dialog( "open" );
  1366. $("#node-input-export").focus();
  1367. }
  1368. function showExportNodesLibraryDialog() {
  1369. mouse_mode = RED.state.EXPORT;
  1370. var nns = RED.nodes.createExportableNodeSet(moving_set);
  1371. $("#dialog-form").html($("script[data-template-name='export-library-dialog']").html());
  1372. $("#node-input-filename").attr('nodes',JSON.stringify(nns));
  1373. $( "#dialog" ).dialog("option","title","Export nodes to library").dialog( "open" );
  1374. }
  1375. function showImportNodesDialog() {
  1376. mouse_mode = RED.state.IMPORT;
  1377. $("#dialog-form").html($("script[data-template-name='import-dialog']").html());
  1378. $("#node-input-import").val("");
  1379. $( "#dialog" ).dialog("option","title","Import nodes").dialog( "open" );
  1380. }
  1381. function showRenameWorkspaceDialog(id) {
  1382. var ws = RED.nodes.workspace(id);
  1383. $( "#node-dialog-rename-workspace" ).dialog("option","workspace",ws);
  1384. if (workspace_tabs.count() == 1) {
  1385. $( "#node-dialog-rename-workspace").next().find(".leftButton")
  1386. .prop('disabled',true)
  1387. .addClass("ui-state-disabled");
  1388. } else {
  1389. $( "#node-dialog-rename-workspace").next().find(".leftButton")
  1390. .prop('disabled',false)
  1391. .removeClass("ui-state-disabled");
  1392. }
  1393. $( "#node-input-workspace-name" ).val(ws.label);
  1394. $( "#node-dialog-rename-workspace" ).dialog("open");
  1395. }
  1396. $("#node-dialog-rename-workspace form" ).submit(function(e) { e.preventDefault();});
  1397. $( "#node-dialog-rename-workspace" ).dialog({
  1398. modal: true,
  1399. autoOpen: false,
  1400. width: 500,
  1401. title: "Rename sheet",
  1402. buttons: [
  1403. {
  1404. class: 'leftButton',
  1405. text: "Delete",
  1406. click: function() {
  1407. var workspace = $(this).dialog('option','workspace');
  1408. $( this ).dialog( "close" );
  1409. deleteWorkspace(workspace.id);
  1410. }
  1411. },
  1412. {
  1413. text: "Ok",
  1414. click: function() {
  1415. var workspace = $(this).dialog('option','workspace');
  1416. var label = $( "#node-input-workspace-name" ).val();
  1417. if (workspace.label != label) {
  1418. workspace.label = label;
  1419. var link = $("#workspace-tabs a[href='#"+workspace.id+"']");
  1420. link.attr("title",label);
  1421. link.text(label);
  1422. RED.view.dirty(true);
  1423. }
  1424. $( this ).dialog( "close" );
  1425. }
  1426. },
  1427. {
  1428. text: "Cancel",
  1429. click: function() {
  1430. $( this ).dialog( "close" );
  1431. }
  1432. }
  1433. ],
  1434. open: function(e) {
  1435. RED.keyboard.disable();
  1436. },
  1437. close: function(e) {
  1438. RED.keyboard.enable();
  1439. }
  1440. });
  1441. $( "#node-dialog-delete-workspace" ).dialog({
  1442. modal: true,
  1443. autoOpen: false,
  1444. width: 500,
  1445. title: "Confirm delete",
  1446. buttons: [
  1447. {
  1448. text: "Ok",
  1449. click: function() {
  1450. var workspace = $(this).dialog('option','workspace');
  1451. RED.view.removeWorkspace(workspace);
  1452. var historyEvent = RED.nodes.removeWorkspace(workspace.id);
  1453. historyEvent.t = 'delete';
  1454. historyEvent.dirty = dirty;
  1455. historyEvent.workspaces = [workspace];
  1456. RED.history.push(historyEvent);
  1457. RED.view.dirty(true);
  1458. $( this ).dialog( "close" );
  1459. }
  1460. },
  1461. {
  1462. text: "Cancel",
  1463. click: function() {
  1464. $( this ).dialog( "close" );
  1465. }
  1466. }
  1467. ],
  1468. open: function(e) {
  1469. RED.keyboard.disable();
  1470. },
  1471. close: function(e) {
  1472. RED.keyboard.enable();
  1473. }
  1474. });
  1475. return {
  1476. state:function(state) {
  1477. if (state == null) {
  1478. return mouse_mode
  1479. } else {
  1480. mouse_mode = state;
  1481. }
  1482. },
  1483. addWorkspace: function(ws) {
  1484. workspace_tabs.addTab(ws);
  1485. workspace_tabs.resize();
  1486. },
  1487. removeWorkspace: function(ws) {
  1488. workspace_tabs.removeTab(ws.id);
  1489. },
  1490. getWorkspace: function() {
  1491. return activeWorkspace;
  1492. },
  1493. showWorkspace: function(id) {
  1494. workspace_tabs.activateTab(id);
  1495. },
  1496. redraw:redraw,
  1497. dirty: function(d) {
  1498. if (d == null) {
  1499. return dirty;
  1500. } else {
  1501. setDirty(d);
  1502. }
  1503. },
  1504. importNodes: importNodes,
  1505. resize: function() {
  1506. workspace_tabs.resize();
  1507. },
  1508. status: function(s) {
  1509. showStatus = s;
  1510. RED.nodes.eachNode(function(n) { n.dirty = true;});
  1511. //TODO: subscribe/unsubscribe here
  1512. redraw();
  1513. }
  1514. };
  1515. })();