You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1682 lines
54KB

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