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.

1701 line
55KB

  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. RED.storage.update();
  485. }
  486. }
  487. if (mouse_mode == RED.state.MOVING || mouse_mode == RED.state.MOVING_ACTIVE) {
  488. for (var i=0;i<moving_set.length;i++) {
  489. delete moving_set[i].ox;
  490. delete moving_set[i].oy;
  491. }
  492. }
  493. if (mouse_mode == RED.state.IMPORT_DRAGGING) {
  494. RED.keyboard.remove(/* ESCAPE */ 27);
  495. setDirty(true);
  496. }
  497. redraw();
  498. // clear mouse event vars
  499. resetMouseVars();
  500. }
  501. $('#btn-zoom-out').click(function() {zoomOut();});
  502. $('#btn-zoom-zero').click(function() {zoomZero();});
  503. $('#btn-zoom-in').click(function() {zoomIn();});
  504. $("#chart").on('DOMMouseScroll mousewheel', function (evt) {
  505. if ( evt.altKey ) {
  506. evt.preventDefault();
  507. evt.stopPropagation();
  508. var move = -(evt.originalEvent.detail) || evt.originalEvent.wheelDelta;
  509. if (move <= 0) { zoomOut(); }
  510. else { zoomIn(); }
  511. }
  512. });
  513. $("#chart").droppable({
  514. accept:".palette_node",
  515. drop: function( event, ui ) {
  516. d3.event = event;
  517. var selected_tool = ui.draggable[0].type;
  518. var mousePos = d3.touches(this)[0]||d3.mouse(this);
  519. mousePos[1] += this.scrollTop;
  520. mousePos[0] += this.scrollLeft;
  521. mousePos[1] /= scaleFactor;
  522. mousePos[0] /= scaleFactor;
  523. var nn = {x: mousePos[0],y:mousePos[1],w:node_width,z:activeWorkspace};
  524. nn.type = selected_tool;
  525. nn._def = RED.nodes.getType(nn.type);
  526. nn.id = RED.nodes.cppName(nn);
  527. nn.outputs = nn._def.outputs;
  528. nn.changed = true;
  529. for (var d in nn._def.defaults) {
  530. if (nn._def.defaults.hasOwnProperty(d)) {
  531. nn[d] = nn._def.defaults[d].value;
  532. }
  533. }
  534. if (nn._def.onadd) {
  535. nn._def.onadd.call(nn);
  536. }
  537. nn.h = Math.max(node_height,(nn.outputs||0) * 15);
  538. RED.history.push({t:'add',nodes:[nn.id],dirty:dirty});
  539. RED.nodes.add(nn);
  540. RED.editor.validateNode(nn);
  541. setDirty(true);
  542. // auto select dropped node - so info shows (if visible)
  543. clearSelection();
  544. nn.selected = true;
  545. moving_set.push({n:nn});
  546. updateSelection();
  547. redraw();
  548. if (nn._def.autoedit) {
  549. RED.editor.edit(nn);
  550. }
  551. }
  552. });
  553. function zoomIn() {
  554. if (scaleFactor < 2) {
  555. scaleFactor += 0.1;
  556. redraw();
  557. }
  558. }
  559. function zoomOut() {
  560. if (scaleFactor > 0.3) {
  561. scaleFactor -= 0.1;
  562. redraw();
  563. }
  564. }
  565. function zoomZero() {
  566. scaleFactor = 1;
  567. redraw();
  568. }
  569. function selectAll() {
  570. RED.nodes.eachNode(function(n) {
  571. if (n.z == activeWorkspace) {
  572. if (!n.selected) {
  573. n.selected = true;
  574. n.dirty = true;
  575. moving_set.push({n:n});
  576. }
  577. }
  578. });
  579. selected_link = null;
  580. updateSelection();
  581. redraw();
  582. }
  583. function clearSelection() {
  584. for (var i=0;i<moving_set.length;i++) {
  585. var n = moving_set[i];
  586. n.n.dirty = true;
  587. n.n.selected = false;
  588. }
  589. moving_set = [];
  590. selected_link = null;
  591. }
  592. function updateSelection() {
  593. if (moving_set.length === 0) {
  594. $("#li-menu-export").addClass("disabled");
  595. $("#li-menu-export-clipboard").addClass("disabled");
  596. $("#li-menu-export-library").addClass("disabled");
  597. } else {
  598. $("#li-menu-export").removeClass("disabled");
  599. $("#li-menu-export-clipboard").removeClass("disabled");
  600. $("#li-menu-export-library").removeClass("disabled");
  601. }
  602. if (moving_set.length === 0 && selected_link == null) {
  603. RED.keyboard.remove(/* backspace */ 8);
  604. RED.keyboard.remove(/* delete */ 46);
  605. RED.keyboard.remove(/* c */ 67);
  606. RED.keyboard.remove(/* x */ 88);
  607. } else {
  608. RED.keyboard.add(/* backspace */ 8,function(){deleteSelection();d3.event.preventDefault();});
  609. RED.keyboard.add(/* delete */ 46,function(){deleteSelection();d3.event.preventDefault();});
  610. RED.keyboard.add(/* c */ 67,{ctrl:true},function(){copySelection();d3.event.preventDefault();});
  611. RED.keyboard.add(/* x */ 88,{ctrl:true},function(){copySelection();deleteSelection();d3.event.preventDefault();});
  612. }
  613. if (moving_set.length === 0) {
  614. RED.keyboard.remove(/* up */ 38);
  615. RED.keyboard.remove(/* down */ 40);
  616. RED.keyboard.remove(/* left */ 37);
  617. RED.keyboard.remove(/* right*/ 39);
  618. } else {
  619. RED.keyboard.add(/* up */ 38, function() { if(d3.event.shiftKey){moveSelection( 0,-20)}else{moveSelection( 0,-1);}d3.event.preventDefault();},endKeyboardMove);
  620. RED.keyboard.add(/* down */ 40, function() { if(d3.event.shiftKey){moveSelection( 0, 20)}else{moveSelection( 0, 1);}d3.event.preventDefault();},endKeyboardMove);
  621. RED.keyboard.add(/* left */ 37, function() { if(d3.event.shiftKey){moveSelection(-20, 0)}else{moveSelection(-1, 0);}d3.event.preventDefault();},endKeyboardMove);
  622. RED.keyboard.add(/* right*/ 39, function() { if(d3.event.shiftKey){moveSelection( 20, 0)}else{moveSelection( 1, 0);}d3.event.preventDefault();},endKeyboardMove);
  623. }
  624. if (moving_set.length == 1) {
  625. RED.sidebar.info.refresh(moving_set[0].n);
  626. } else {
  627. RED.sidebar.info.clear();
  628. }
  629. }
  630. function endKeyboardMove() {
  631. var ns = [];
  632. for (var i=0;i<moving_set.length;i++) {
  633. ns.push({n:moving_set[i].n,ox:moving_set[i].ox,oy:moving_set[i].oy});
  634. delete moving_set[i].ox;
  635. delete moving_set[i].oy;
  636. }
  637. RED.history.push({t:'move',nodes:ns,dirty:dirty});
  638. }
  639. function moveSelection(dx,dy) {
  640. var minX = 0;
  641. var minY = 0;
  642. var node;
  643. for (var i=0;i<moving_set.length;i++) {
  644. node = moving_set[i];
  645. if (node.ox == null && node.oy == null) {
  646. node.ox = node.n.x;
  647. node.oy = node.n.y;
  648. }
  649. node.n.x += dx;
  650. node.n.y += dy;
  651. node.n.dirty = true;
  652. minX = Math.min(node.n.x-node.n.w/2-5,minX);
  653. minY = Math.min(node.n.y-node.n.h/2-5,minY);
  654. }
  655. if (minX !== 0 || minY !== 0) {
  656. for (var n = 0; n<moving_set.length; n++) {
  657. node = moving_set[n];
  658. node.n.x -= minX;
  659. node.n.y -= minY;
  660. }
  661. }
  662. redraw();
  663. }
  664. function deleteSelection() {
  665. var removedNodes = [];
  666. var removedLinks = [];
  667. var startDirty = dirty;
  668. if (moving_set.length > 0) {
  669. for (var i=0;i<moving_set.length;i++) {
  670. var node = moving_set[i].n;
  671. node.selected = false;
  672. if (node.x < 0) {
  673. node.x = 25
  674. }
  675. var rmlinks = RED.nodes.remove(node.id);
  676. removedNodes.push(node);
  677. removedLinks = removedLinks.concat(rmlinks);
  678. }
  679. moving_set = [];
  680. setDirty(true);
  681. }
  682. if (selected_link) {
  683. // reenable input port
  684. var n = selected_link.targetPort;
  685. var rect = selected_link.target.inputlist[n];
  686. rect.on("mousedown", (function(d,n){return function(d){portMouseDown(d,1,n);}})(rect, n))
  687. .on("touchstart", (function(d,n){return function(d){portMouseDown(d,1,n);}})(rect, n))
  688. .on("mouseup", (function(d,n){return function(d){portMouseUp(d,1,n);}})(rect, n))
  689. .on("touchend", (function(d,n){return function(d){portMouseUp(d,1,n);}})(rect, n))
  690. .on("mouseover",function(d) { var port = d3.select(this); port.classed("port_hovered",(mouse_mode!=RED.state.JOINING || mousedown_port_type != 1 ));})
  691. .on("mouseout",function(d) { var port = d3.select(this); port.classed("port_hovered",false);})
  692. RED.nodes.removeLink(selected_link);
  693. removedLinks.push(selected_link);
  694. setDirty(true);
  695. }
  696. RED.history.push({t:'delete',nodes:removedNodes,links:removedLinks,dirty:startDirty});
  697. selected_link = null;
  698. updateSelection();
  699. redraw();
  700. }
  701. function copySelection() {
  702. if (moving_set.length > 0) {
  703. var nns = [];
  704. for (var n=0;n<moving_set.length;n++) {
  705. var node = moving_set[n].n;
  706. nns.push(RED.nodes.convertNode(node));
  707. }
  708. clipboard = JSON.stringify(nns);
  709. RED.notify(moving_set.length+" node"+(moving_set.length>1?"s":"")+" copied");
  710. }
  711. }
  712. function calculateTextWidth(str) {
  713. var sp = document.createElement("span");
  714. sp.className = "node_label";
  715. sp.style.position = "absolute";
  716. sp.style.top = "-1000px";
  717. sp.innerHTML = (str||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
  718. document.body.appendChild(sp);
  719. var w = sp.offsetWidth;
  720. document.body.removeChild(sp);
  721. return 50+w;
  722. }
  723. function resetMouseVars() {
  724. mousedown_node = null;
  725. mouseup_node = null;
  726. mousedown_link = null;
  727. mouse_mode = 0;
  728. mousedown_port_type = 0;
  729. }
  730. function portMouseDown(d,portType,portIndex) {
  731. // disable zoom
  732. //vis.call(d3.behavior.zoom().on("zoom"), null);
  733. mousedown_node = d;
  734. selected_link = null;
  735. mouse_mode = RED.state.JOINING;
  736. mousedown_port_type = portType;
  737. mousedown_port_index = portIndex || 0;
  738. document.body.style.cursor = "crosshair";
  739. d3.event.preventDefault();
  740. }
  741. function portMouseUp(d,portType,portIndex) {
  742. document.body.style.cursor = "";
  743. if (mouse_mode == RED.state.JOINING && mousedown_node) {
  744. if (typeof TouchEvent != "undefined" && d3.event instanceof TouchEvent) {
  745. RED.nodes.eachNode(function(n) {
  746. if (n.z == activeWorkspace) {
  747. var hw = n.w/2;
  748. var hh = n.h/2;
  749. if (n.x-hw<mouse_position[0] && n.x+hw> mouse_position[0] &&
  750. n.y-hh<mouse_position[1] && n.y+hh>mouse_position[1]) {
  751. mouseup_node = n;
  752. portType = mouseup_node._def.inputs>0?1:0;
  753. portIndex = 0;
  754. }
  755. }
  756. });
  757. } else {
  758. mouseup_node = d;
  759. }
  760. if (portType == mousedown_port_type || mouseup_node === mousedown_node) {
  761. drag_line.attr("class", "drag_line_hidden");
  762. resetMouseVars();
  763. return;
  764. }
  765. var src,dst,src_port,dst_port;
  766. if (mousedown_port_type === 0) {
  767. src = mousedown_node;
  768. src_port = mousedown_port_index;
  769. dst = mouseup_node;
  770. dst_port = portIndex;
  771. } else if (mousedown_port_type == 1) {
  772. src = mouseup_node;
  773. src_port = portIndex;
  774. dst = mousedown_node;
  775. dst_port = mousedown_port_index;
  776. }
  777. var existingLink = false;
  778. RED.nodes.eachLink(function(d) {
  779. existingLink = existingLink || (d.source === src && d.target === dst && d.sourcePort == src_port && d.targetPort == dst_port);
  780. });
  781. if (!existingLink) {
  782. var link = {source: src, sourcePort:src_port, target: dst, targetPort: dst_port};
  783. RED.nodes.addLink(link);
  784. RED.history.push({t:'add',links:[link],dirty:dirty});
  785. setDirty(true);
  786. // disallow new links to this destination - each input can have only a single link
  787. dst.inputlist[dst_port]
  788. .classed("port_hovered",false)
  789. .on("mousedown",null)
  790. .on("touchstart", null)
  791. .on("mouseup", null)
  792. .on("touchend", null)
  793. .on("mouseover", null)
  794. .on("mouseout", null);
  795. }
  796. selected_link = null;
  797. redraw();
  798. }
  799. }
  800. function nodeMouseUp(d) {
  801. if (dblClickPrimed && mousedown_node == d && clickElapsed > 0 && clickElapsed < 750) {
  802. RED.editor.edit(d);
  803. clickElapsed = 0;
  804. d3.event.stopPropagation();
  805. return;
  806. }
  807. portMouseUp(d, d._def.inputs > 0 ? 1 : 0, 0);
  808. }
  809. function nodeMouseDown(d) {
  810. //var touch0 = d3.event;
  811. //var pos = [touch0.pageX,touch0.pageY];
  812. //RED.touch.radialMenu.show(d3.select(this),pos);
  813. if (mouse_mode == RED.state.IMPORT_DRAGGING) {
  814. RED.keyboard.remove(/* ESCAPE */ 27);
  815. updateSelection();
  816. setDirty(true);
  817. redraw();
  818. resetMouseVars();
  819. d3.event.stopPropagation();
  820. return;
  821. }
  822. mousedown_node = d;
  823. var now = Date.now();
  824. clickElapsed = now-clickTime;
  825. clickTime = now;
  826. dblClickPrimed = (lastClickNode == mousedown_node);
  827. lastClickNode = mousedown_node;
  828. var i;
  829. if (d.selected && d3.event.ctrlKey) {
  830. d.selected = false;
  831. for (i=0;i<moving_set.length;i+=1) {
  832. if (moving_set[i].n === d) {
  833. moving_set.splice(i,1);
  834. break;
  835. }
  836. }
  837. } else {
  838. if (d3.event.shiftKey) {
  839. clearSelection();
  840. var cnodes = RED.nodes.getAllFlowNodes(mousedown_node);
  841. for (var n=0;n<cnodes.length;n++) {
  842. cnodes[n].selected = true;
  843. cnodes[n].dirty = true;
  844. moving_set.push({n:cnodes[n]});
  845. }
  846. } else if (!d.selected) {
  847. if (!d3.event.ctrlKey) {
  848. clearSelection();
  849. }
  850. mousedown_node.selected = true;
  851. moving_set.push({n:mousedown_node});
  852. }
  853. selected_link = null;
  854. if (d3.event.button != 2) {
  855. mouse_mode = RED.state.MOVING;
  856. var mouse = d3.touches(this)[0]||d3.mouse(this);
  857. mouse[0] += d.x-d.w/2;
  858. mouse[1] += d.y-d.h/2;
  859. for (i=0;i<moving_set.length;i++) {
  860. moving_set[i].ox = moving_set[i].n.x;
  861. moving_set[i].oy = moving_set[i].n.y;
  862. moving_set[i].dx = moving_set[i].n.x-mouse[0];
  863. moving_set[i].dy = moving_set[i].n.y-mouse[1];
  864. }
  865. mouse_offset = d3.mouse(document.body);
  866. if (isNaN(mouse_offset[0])) {
  867. mouse_offset = d3.touches(document.body)[0];
  868. }
  869. }
  870. }
  871. d.dirty = true;
  872. updateSelection();
  873. redraw();
  874. d3.event.stopPropagation();
  875. }
  876. function nodeButtonClicked(d) {
  877. if (d._def.button.toggle) {
  878. d[d._def.button.toggle] = !d[d._def.button.toggle];
  879. d.dirty = true;
  880. }
  881. if (d._def.button.onclick) {
  882. d._def.button.onclick.call(d);
  883. }
  884. if (d.dirty) {
  885. redraw();
  886. }
  887. d3.event.preventDefault();
  888. }
  889. function showTouchMenu(obj,pos) {
  890. var mdn = mousedown_node;
  891. var options = [];
  892. options.push({name:"delete",disabled:(moving_set.length===0),onselect:function() {deleteSelection();}});
  893. options.push({name:"cut",disabled:(moving_set.length===0),onselect:function() {copySelection();deleteSelection();}});
  894. options.push({name:"copy",disabled:(moving_set.length===0),onselect:function() {copySelection();}});
  895. options.push({name:"paste",disabled:(clipboard.length===0),onselect:function() {importNodes(clipboard,true);}});
  896. options.push({name:"edit",disabled:(moving_set.length != 1),onselect:function() { RED.editor.edit(mdn);}});
  897. options.push({name:"select",onselect:function() {selectAll();}});
  898. options.push({name:"undo",disabled:(RED.history.depth() === 0),onselect:function() {RED.history.pop();}});
  899. RED.touch.radialMenu.show(obj,pos,options);
  900. resetMouseVars();
  901. }
  902. function redraw() {
  903. vis.attr("transform","scale("+scaleFactor+")");
  904. outer.attr("width", space_width*scaleFactor).attr("height", space_height*scaleFactor);
  905. if (mouse_mode != RED.state.JOINING) {
  906. // Don't bother redrawing nodes if we're drawing links
  907. var node = vis.selectAll(".nodegroup").data(RED.nodes.nodes.filter(function(d) { return d.z == activeWorkspace }),function(d){return d.id});
  908. node.exit().remove();
  909. var nodeEnter = node.enter().insert("svg:g").attr("class", "node nodegroup");
  910. nodeEnter.each(function(d,i) {
  911. var node = d3.select(this);
  912. node.attr("id",d.id);
  913. //var l = d._def.label;
  914. //l = (typeof l === "function" ? l.call(d) : l)||"";
  915. var l = d.id;
  916. d.w = Math.max(node_width,calculateTextWidth(l)+(d._def.inputs>0?7:0) );
  917. d.h = Math.max(node_height,(Math.max(d.outputs,d._def.inputs)||0) * 15);
  918. if (d._def.badge) {
  919. var badge = node.append("svg:g").attr("class","node_badge_group");
  920. var badgeRect = badge.append("rect").attr("class","node_badge").attr("rx",5).attr("ry",5).attr("width",40).attr("height",15);
  921. badge.append("svg:text").attr("class","node_badge_label").attr("x",35).attr("y",11).attr('text-anchor','end').text(d._def.badge());
  922. if (d._def.onbadgeclick) {
  923. badgeRect.attr("cursor","pointer")
  924. .on("click",function(d) { d._def.onbadgeclick.call(d);d3.event.preventDefault();});
  925. }
  926. }
  927. if (d._def.button) {
  928. var nodeButtonGroup = node.append('svg:g')
  929. .attr("transform",function(d) { return "translate("+((d._def.align == "right") ? 94 : -25)+",2)"; })
  930. .attr("class",function(d) { return "node_button "+((d._def.align == "right") ? "node_right_button" : "node_left_button"); });
  931. nodeButtonGroup.append('rect')
  932. .attr("rx",8)
  933. .attr("ry",8)
  934. .attr("width",32)
  935. .attr("height",node_height-4)
  936. .attr("fill","#eee");//function(d) { return d._def.color;})
  937. nodeButtonGroup.append('rect')
  938. .attr("x",function(d) { return d._def.align == "right"? 10:5})
  939. .attr("y",4)
  940. .attr("rx",5)
  941. .attr("ry",5)
  942. .attr("width",16)
  943. .attr("height",node_height-12)
  944. .attr("fill",function(d) { return d._def.color;})
  945. .attr("cursor","pointer")
  946. .on("mousedown",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",0.2);d3.event.preventDefault(); d3.event.stopPropagation();}})
  947. .on("mouseup",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",0.4);d3.event.preventDefault();d3.event.stopPropagation();}})
  948. .on("mouseover",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",0.4);}})
  949. .on("mouseout",function(d) {if (!lasso) {
  950. var op = 1;
  951. if (d._def.button.toggle) {
  952. op = d[d._def.button.toggle]?1:0.2;
  953. }
  954. d3.select(this).attr("fill-opacity",op);
  955. }})
  956. .on("click",nodeButtonClicked)
  957. .on("touchstart",nodeButtonClicked)
  958. }
  959. var mainRect = node.append("rect")
  960. .attr("class", "node")
  961. .classed("node_unknown",function(d) { return d.type == "unknown"; })
  962. .attr("rx", 6)
  963. .attr("ry", 6)
  964. .attr("fill",function(d) { return d._def.color;})
  965. .on("mouseup",nodeMouseUp)
  966. .on("mousedown",nodeMouseDown)
  967. .on("touchstart",function(d) {
  968. var obj = d3.select(this);
  969. var touch0 = d3.event.touches.item(0);
  970. var pos = [touch0.pageX,touch0.pageY];
  971. startTouchCenter = [touch0.pageX,touch0.pageY];
  972. startTouchDistance = 0;
  973. touchStartTime = setTimeout(function() {
  974. showTouchMenu(obj,pos);
  975. },touchLongPressTimeout);
  976. nodeMouseDown.call(this,d)
  977. })
  978. .on("touchend", function(d) {
  979. clearTimeout(touchStartTime);
  980. touchStartTime = null;
  981. if (RED.touch.radialMenu.active()) {
  982. d3.event.stopPropagation();
  983. return;
  984. }
  985. nodeMouseUp.call(this,d);
  986. })
  987. .on("mouseover",function(d) {
  988. if (mouse_mode === 0) {
  989. var node = d3.select(this);
  990. node.classed("node_hovered",true);
  991. }
  992. })
  993. .on("mouseout",function(d) {
  994. var node = d3.select(this);
  995. node.classed("node_hovered",false);
  996. });
  997. //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");
  998. //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");
  999. if (d._def.icon) {
  1000. var icon_group = node.append("g")
  1001. .attr("class","node_icon_group")
  1002. .attr("x",0).attr("y",0);
  1003. var icon_shade = icon_group.append("rect")
  1004. .attr("x",0).attr("y",0)
  1005. .attr("class","node_icon_shade")
  1006. .attr("width","30")
  1007. .attr("stroke","none")
  1008. .attr("fill","#000")
  1009. .attr("fill-opacity","0.05")
  1010. .attr("height",function(d){return Math.min(50,d.h-4);});
  1011. var icon = icon_group.append("image")
  1012. .attr("xlink:href","icons/"+d._def.icon)
  1013. .attr("class","node_icon")
  1014. .attr("x",0)
  1015. .attr("width","30")
  1016. .attr("height","30");
  1017. var icon_shade_border = icon_group.append("path")
  1018. .attr("d",function(d) { return "M 30 1 l 0 "+(d.h-2)})
  1019. .attr("class","node_icon_shade_border")
  1020. .attr("stroke-opacity","0.1")
  1021. .attr("stroke","#000")
  1022. .attr("stroke-width","2");
  1023. if ("right" == d._def.align) {
  1024. icon_group.attr('class','node_icon_group node_icon_group_'+d._def.align);
  1025. icon_shade_border.attr("d",function(d) { return "M 0 1 l 0 "+(d.h-2)})
  1026. //icon.attr('class','node_icon node_icon_'+d._def.align);
  1027. //icon.attr('class','node_icon_shade node_icon_shade_'+d._def.align);
  1028. //icon.attr('class','node_icon_shade_border node_icon_shade_border_'+d._def.align);
  1029. }
  1030. //if (d._def.inputs > 0 && d._def.align == null) {
  1031. // icon_shade.attr("width",35);
  1032. // icon.attr("transform","translate(5,0)");
  1033. // icon_shade_border.attr("transform","translate(5,0)");
  1034. //}
  1035. //if (d._def.outputs > 0 && "right" == d._def.align) {
  1036. // icon_shade.attr("width",35); //icon.attr("x",5);
  1037. //}
  1038. var img = new Image();
  1039. img.src = "icons/"+d._def.icon;
  1040. img.onload = function() {
  1041. icon.attr("width",Math.min(img.width,30));
  1042. icon.attr("height",Math.min(img.height,30));
  1043. icon.attr("x",15-Math.min(img.width,30)/2);
  1044. //if ("right" == d._def.align) {
  1045. // icon.attr("x",function(d){return d.w-img.width-1-(d.outputs>0?5:0);});
  1046. // icon_shade.attr("x",function(d){return d.w-30});
  1047. // icon_shade_border.attr("d",function(d){return "M "+(d.w-30)+" 1 l 0 "+(d.h-2);});
  1048. //}
  1049. }
  1050. //icon.style("pointer-events","none");
  1051. icon_group.style("pointer-events","none");
  1052. }
  1053. var text = node.append('svg:text').attr('class','node_label').attr('x', 38).attr('dy', '.35em').attr('text-anchor','start');
  1054. if (d._def.align) {
  1055. text.attr('class','node_label node_label_'+d._def.align);
  1056. text.attr('text-anchor','end');
  1057. }
  1058. var status = node.append("svg:g").attr("class","node_status_group").style("display","none");
  1059. var statusRect = status.append("rect").attr("class","node_status")
  1060. .attr("x",6).attr("y",1).attr("width",9).attr("height",9)
  1061. .attr("rx",2).attr("ry",2).attr("stroke-width","3");
  1062. var statusLabel = status.append("svg:text")
  1063. .attr("class","node_status_label")
  1064. .attr('x',20).attr('y',9)
  1065. .style({
  1066. 'stroke-width': 0,
  1067. 'fill': '#888',
  1068. 'font-size':'9pt',
  1069. 'stroke':'#000',
  1070. 'text-anchor':'start'
  1071. });
  1072. //node.append("circle").attr({"class":"centerDot","cx":0,"cy":0,"r":5});
  1073. var numInputs = d._def.inputs;
  1074. var inputlist = [];
  1075. for (var n=0; n < numInputs; n++) {
  1076. var link = RED.nodes.links.filter(function(l){return (l.target == d && l.targetPort == n);});
  1077. var y = (d.h/2)-((numInputs-1)/2)*13;
  1078. y = (y+13*n)-5;
  1079. text.attr("x",38);
  1080. var rect = node.append("rect");
  1081. inputlist[n] = rect;
  1082. rect.attr("class","port port_input").attr("rx",3).attr("ry",3)
  1083. .attr("y",y).attr("x",-5).attr("width",10).attr("height",10).attr("index",n);
  1084. if (link && link.length > 0) {
  1085. // this input already has a link connected, so disallow new links
  1086. rect.on("mousedown",null)
  1087. .on("touchstart", null)
  1088. .on("mouseup", null)
  1089. .on("touchend", null)
  1090. .on("mouseover", null)
  1091. .on("mouseout", null)
  1092. .classed("port_hovered",false);
  1093. } else {
  1094. // allow new link on inputs without any link connected
  1095. rect.on("mousedown", (function(nn){return function(d){portMouseDown(d,1,nn);}})(n))
  1096. .on("touchstart", (function(nn){return function(d){portMouseDown(d,1,nn);}})(n))
  1097. .on("mouseup", (function(nn){return function(d){portMouseUp(d,1,nn);}})(n))
  1098. .on("touchend", (function(nn){return function(d){portMouseUp(d,1,nn);}})(n))
  1099. .on("mouseover",function(d) { var port = d3.select(this); port.classed("port_hovered",(mouse_mode!=RED.state.JOINING || mousedown_port_type != 1 ));})
  1100. .on("mouseout",function(d) { var port = d3.select(this); port.classed("port_hovered",false);})
  1101. }
  1102. }
  1103. d.inputlist = inputlist;
  1104. // never show these little status icons
  1105. // people try clicking on them, thinking they're buttons
  1106. // or some sort of user interface widget
  1107. //node.append("path").attr("class","node_error").attr("d","M 3,-3 l 10,0 l -5,-8 z");
  1108. //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);
  1109. //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);
  1110. });
  1111. node.each(function(d,i) {
  1112. if (d.dirty) {
  1113. //if (d.x < -50) deleteSelection(); // Delete nodes if dragged back to palette
  1114. if (d.resize) {
  1115. //var l = d._def.label;
  1116. //l = (typeof l === "function" ? l.call(d) : l)||"";
  1117. var l = d.id;
  1118. d.w = Math.max(node_width,calculateTextWidth(l)+(d._def.inputs>0?7:0) );
  1119. d.h = Math.max(node_height,(Math.max(d.outputs,d._def.inputs)||0) * 15);
  1120. }
  1121. var thisNode = d3.select(this);
  1122. //thisNode.selectAll(".centerDot").attr({"cx":function(d) { return d.w/2;},"cy":function(d){return d.h/2}});
  1123. thisNode.attr("transform", function(d) { return "translate(" + (d.x-d.w/2) + "," + (d.y-d.h/2) + ")"; });
  1124. thisNode.selectAll(".node")
  1125. .attr("width",function(d){return d.w})
  1126. .attr("height",function(d){return d.h})
  1127. .classed("node_selected",function(d) { return d.selected; })
  1128. .classed("node_highlighted",function(d) { return d.highlighted; })
  1129. ;
  1130. //thisNode.selectAll(".node-gradient-top").attr("width",function(d){return d.w});
  1131. //thisNode.selectAll(".node-gradient-bottom").attr("width",function(d){return d.w}).attr("y",function(d){return d.h-30});
  1132. thisNode.selectAll(".node_icon_group_right").attr('transform', function(d){return "translate("+(d.w-30)+",0)"});
  1133. thisNode.selectAll(".node_label_right").attr('x', function(d){return d.w-38});
  1134. //thisNode.selectAll(".node_icon_right").attr("x",function(d){return d.w-d3.select(this).attr("width")-1-(d.outputs>0?5:0);});
  1135. //thisNode.selectAll(".node_icon_shade_right").attr("x",function(d){return d.w-30;});
  1136. //thisNode.selectAll(".node_icon_shade_border_right").attr("d",function(d){return "M "+(d.w-30)+" 1 l 0 "+(d.h-2)});
  1137. var numOutputs = d.outputs;
  1138. var y = (d.h/2)-((numOutputs-1)/2)*13;
  1139. d.ports = d.ports || d3.range(numOutputs);
  1140. d._ports = thisNode.selectAll(".port_output").data(d.ports);
  1141. d._ports.enter().append("rect").attr("class","port port_output").attr("rx",3).attr("ry",3).attr("width",10).attr("height",10)
  1142. .on("mousedown",(function(){var node = d; return function(d,i){portMouseDown(node,0,i);}})() )
  1143. .on("touchstart",(function(){var node = d; return function(d,i){portMouseDown(node,0,i);}})() )
  1144. .on("mouseup",(function(){var node = d; return function(d,i){portMouseUp(node,0,i);}})() )
  1145. .on("touchend",(function(){var node = d; return function(d,i){portMouseUp(node,0,i);}})() )
  1146. .on("mouseover",function(d,i) { var port = d3.select(this); port.classed("port_hovered",(mouse_mode!=RED.state.JOINING || mousedown_port_type !== 0 ));})
  1147. .on("mouseout",function(d,i) { var port = d3.select(this); port.classed("port_hovered",false);});
  1148. d._ports.exit().remove();
  1149. if (d._ports) {
  1150. numOutputs = d.outputs || 1;
  1151. y = (d.h/2)-((numOutputs-1)/2)*13;
  1152. var x = d.w - 5;
  1153. d._ports.each(function(d,i) {
  1154. var port = d3.select(this);
  1155. port.attr("y",(y+13*i)-5).attr("x",x);
  1156. });
  1157. }
  1158. thisNode.selectAll('text.node_label').text(function(d,i){
  1159. /* if (d._def.label) {
  1160. if (typeof d._def.label == "function") {
  1161. return d._def.label.call(d);
  1162. } else {
  1163. return d._def.label;
  1164. }
  1165. }
  1166. return ""; */
  1167. return d.id;
  1168. })
  1169. .attr('y', function(d){return (d.h/2)-1;})
  1170. .attr('class',function(d){
  1171. return 'node_label'+
  1172. (d._def.align?' node_label_'+d._def.align:'')+
  1173. (d._def.label?' '+(typeof d._def.labelStyle == "function" ? d._def.labelStyle.call(d):d._def.labelStyle):'') ;
  1174. });
  1175. thisNode.selectAll(".node_tools").attr("x",function(d){return d.w-35;}).attr("y",function(d){return d.h-20;});
  1176. thisNode.selectAll(".node_changed")
  1177. .attr("x",function(d){return d.w-10})
  1178. .classed("hidden",function(d) { return !d.changed; });
  1179. thisNode.selectAll(".node_error")
  1180. .attr("x",function(d){return d.w-10-(d.changed?13:0)})
  1181. .classed("hidden",function(d) { return d.valid; });
  1182. thisNode.selectAll(".port_input").each(function(d,i) {
  1183. var port = d3.select(this);
  1184. var numInputs = d._def.inputs;
  1185. var y = (d.h/2)-((numInputs-1)/2)*13;
  1186. y = (y+13*i)-5;
  1187. port.attr("y",y)
  1188. });
  1189. thisNode.selectAll(".node_icon").attr("y",function(d){return (d.h-d3.select(this).attr("height"))/2;});
  1190. thisNode.selectAll(".node_icon_shade").attr("height",function(d){return d.h;});
  1191. thisNode.selectAll(".node_icon_shade_border").attr("d",function(d){ return "M "+(("right" == d._def.align) ?0:30)+" 1 l 0 "+(d.h-2)});
  1192. thisNode.selectAll('.node_right_button').attr("transform",function(d){
  1193. var x = d.w-6;
  1194. if (d._def.button.toggle && !d[d._def.button.toggle]) {
  1195. x = x - 8;
  1196. }
  1197. return "translate("+x+",2)";
  1198. });
  1199. thisNode.selectAll('.node_right_button rect').attr("fill-opacity",function(d){
  1200. if (d._def.button.toggle) {
  1201. return d[d._def.button.toggle]?1:0.2;
  1202. }
  1203. return 1;
  1204. });
  1205. //thisNode.selectAll('.node_right_button').attr("transform",function(d){return "translate("+(d.w - d._def.button.width.call(d))+","+0+")";}).attr("fill",function(d) {
  1206. // 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)
  1207. //});
  1208. thisNode.selectAll('.node_badge_group').attr("transform",function(d){return "translate("+(d.w-40)+","+(d.h+3)+")";});
  1209. thisNode.selectAll('text.node_badge_label').text(function(d,i) {
  1210. /* if (d._def.badge) {
  1211. if (typeof d._def.badge == "function") {
  1212. return d._def.badge.call(d);
  1213. } else {
  1214. return d._def.badge;
  1215. }
  1216. }
  1217. return ""; */
  1218. return d.id;
  1219. });
  1220. if (!showStatus || !d.status) {
  1221. thisNode.selectAll('.node_status_group').style("display","none");
  1222. } else {
  1223. thisNode.selectAll('.node_status_group').style("display","inline").attr("transform","translate(3,"+(d.h+3)+")");
  1224. var fill = status_colours[d.status.fill]; // Only allow our colours for now
  1225. if (d.status.shape == null && fill == null) {
  1226. thisNode.selectAll('.node_status').style("display","none");
  1227. } else {
  1228. var style;
  1229. if (d.status.shape == null || d.status.shape == "dot") {
  1230. style = {
  1231. display: "inline",
  1232. fill: fill,
  1233. stroke: fill
  1234. };
  1235. } else if (d.status.shape == "ring" ){
  1236. style = {
  1237. display: "inline",
  1238. fill: '#fff',
  1239. stroke: fill
  1240. }
  1241. }
  1242. thisNode.selectAll('.node_status').style(style);
  1243. }
  1244. if (d.status.text) {
  1245. thisNode.selectAll('.node_status_label').text(d.status.text);
  1246. } else {
  1247. thisNode.selectAll('.node_status_label').text("");
  1248. }
  1249. }
  1250. d.dirty = false;
  1251. }
  1252. });
  1253. }
  1254. 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;});
  1255. var linkEnter = link.enter().insert("g",".node").attr("class","link");
  1256. linkEnter.each(function(d,i) {
  1257. var l = d3.select(this);
  1258. l.append("svg:path").attr("class","link_background link_path")
  1259. .on("mousedown",function(d) {
  1260. mousedown_link = d;
  1261. clearSelection();
  1262. selected_link = mousedown_link;
  1263. updateSelection();
  1264. redraw();
  1265. d3.event.stopPropagation();
  1266. })
  1267. .on("touchstart",function(d) {
  1268. mousedown_link = d;
  1269. clearSelection();
  1270. selected_link = mousedown_link;
  1271. updateSelection();
  1272. redraw();
  1273. d3.event.stopPropagation();
  1274. });
  1275. l.append("svg:path").attr("class","link_outline link_path");
  1276. l.append("svg:path").attr("class","link_line link_path");
  1277. });
  1278. link.exit().remove();
  1279. var links = vis.selectAll(".link_path")
  1280. links.attr("d",function(d){
  1281. var numOutputs = d.source.outputs || 1;
  1282. var sourcePort = d.sourcePort || 0;
  1283. var ysource = -((numOutputs-1)/2)*13 +13*sourcePort;
  1284. var numInputs = d.target._def.inputs || 1;
  1285. var targetPort = d.targetPort || 0;
  1286. var ytarget = -((numInputs-1)/2)*13 +13*targetPort;
  1287. var dy = (d.target.y+ytarget)-(d.source.y+ysource);
  1288. var dx = (d.target.x-d.target.w/2)-(d.source.x+d.source.w/2);
  1289. var delta = Math.sqrt(dy*dy+dx*dx);
  1290. var scale = lineCurveScale;
  1291. var scaleY = 0;
  1292. if (delta < node_width) {
  1293. scale = 0.75-0.75*((node_width-delta)/node_width);
  1294. }
  1295. if (dx < 0) {
  1296. scale += 2*(Math.min(5*node_width,Math.abs(dx))/(5*node_width));
  1297. if (Math.abs(dy) < 3*node_height) {
  1298. 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)) ;
  1299. }
  1300. }
  1301. d.x1 = d.source.x+d.source.w/2;
  1302. d.y1 = d.source.y+ysource;
  1303. d.x2 = d.target.x-d.target.w/2;
  1304. d.y2 = d.target.y+ytarget;
  1305. return "M "+(d.x1)+" "+(d.y1)+
  1306. " C "+(d.x1+scale*node_width)+" "+(d.y1+scaleY*node_height)+" "+
  1307. (d.x2-scale*node_width)+" "+(d.y2-scaleY*node_height)+" "+
  1308. (d.x2)+" "+d.y2;
  1309. })
  1310. link.classed("link_selected", function(d) { return d === selected_link || d.selected; });
  1311. link.classed("link_unknown",function(d) { return d.target.type == "unknown" || d.source.type == "unknown"});
  1312. if (d3.event) {
  1313. d3.event.preventDefault();
  1314. }
  1315. }
  1316. RED.keyboard.add(/* z */ 90,{ctrl:true},function(){RED.history.pop();});
  1317. RED.keyboard.add(/* a */ 65,{ctrl:true},function(){selectAll();d3.event.preventDefault();});
  1318. RED.keyboard.add(/* = */ 187,{ctrl:true},function(){zoomIn();d3.event.preventDefault();});
  1319. RED.keyboard.add(/* - */ 189,{ctrl:true},function(){zoomOut();d3.event.preventDefault();});
  1320. RED.keyboard.add(/* 0 */ 48,{ctrl:true},function(){zoomZero();d3.event.preventDefault();});
  1321. RED.keyboard.add(/* v */ 86,{ctrl:true},function(){importNodes(clipboard);d3.event.preventDefault();});
  1322. RED.keyboard.add(/* e */ 69,{ctrl:true},function(){showExportNodesDialog();d3.event.preventDefault();});
  1323. RED.keyboard.add(/* i */ 73,{ctrl:true},function(){showImportNodesDialog();d3.event.preventDefault();});
  1324. // TODO: 'dirty' should be a property of RED.nodes - with an event callback for ui hooks
  1325. function setDirty(d) {
  1326. dirty = d;
  1327. if (dirty) {
  1328. $("#btn-deploy").removeClass("disabled").addClass("btn-danger");
  1329. RED.storage.update();
  1330. } else {
  1331. $("#btn-deploy").addClass("disabled").removeClass("btn-danger");
  1332. }
  1333. }
  1334. /**
  1335. * Imports a new collection of nodes from a JSON String.
  1336. * - all get new IDs assigned
  1337. * - all 'selected'
  1338. * - attached to mouse for placing - 'IMPORT_DRAGGING'
  1339. */
  1340. function importNodes(newNodesStr,touchImport) {
  1341. try {
  1342. var result = RED.nodes.import(newNodesStr,true);
  1343. if (result) {
  1344. var new_nodes = result[0];
  1345. var new_links = result[1];
  1346. var new_ms = new_nodes.map(function(n) { n.z = activeWorkspace; return {n:n};});
  1347. var new_node_ids = new_nodes.map(function(n){ return n.id; });
  1348. // TODO: pick a more sensible root node
  1349. var root_node = new_ms[0].n;
  1350. var dx = root_node.x;
  1351. var dy = root_node.y;
  1352. if (mouse_position == null) {
  1353. mouse_position = [0,0];
  1354. }
  1355. var minX = 0;
  1356. var minY = 0;
  1357. var i;
  1358. var node;
  1359. for (i=0;i<new_ms.length;i++) {
  1360. node = new_ms[i];
  1361. node.n.selected = true;
  1362. node.n.changed = true;
  1363. node.n.x -= dx - mouse_position[0];
  1364. node.n.y -= dy - mouse_position[1];
  1365. node.dx = node.n.x - mouse_position[0];
  1366. node.dy = node.n.y - mouse_position[1];
  1367. minX = Math.min(node.n.x-node_width/2-5,minX);
  1368. minY = Math.min(node.n.y-node_height/2-5,minY);
  1369. }
  1370. for (i=0;i<new_ms.length;i++) {
  1371. node = new_ms[i];
  1372. node.n.x -= minX;
  1373. node.n.y -= minY;
  1374. node.dx -= minX;
  1375. node.dy -= minY;
  1376. }
  1377. if (!touchImport) {
  1378. mouse_mode = RED.state.IMPORT_DRAGGING;
  1379. }
  1380. RED.keyboard.add(/* ESCAPE */ 27,function(){
  1381. RED.keyboard.remove(/* ESCAPE */ 27);
  1382. clearSelection();
  1383. RED.history.pop();
  1384. mouse_mode = 0;
  1385. });
  1386. RED.history.push({t:'add',nodes:new_node_ids,links:new_links,dirty:RED.view.dirty()});
  1387. clearSelection();
  1388. moving_set = new_ms;
  1389. redraw();
  1390. }
  1391. } catch(error) {
  1392. console.log(error);
  1393. RED.notify("<strong>Error</strong>: "+error,"error");
  1394. }
  1395. }
  1396. $('#btn-import').click(function() {showImportNodesDialog();});
  1397. $('#btn-export-clipboard').click(function() {showExportNodesDialog();});
  1398. $('#btn-export-library').click(function() {showExportNodesLibraryDialog();});
  1399. function showExportNodesDialog() {
  1400. mouse_mode = RED.state.EXPORT;
  1401. var nns = RED.nodes.createExportableNodeSet(moving_set);
  1402. $("#dialog-form").html($("script[data-template-name='export-clipboard-dialog']").html());
  1403. $("#node-input-export").val(JSON.stringify(nns));
  1404. $("#node-input-export").focus(function() {
  1405. var textarea = $(this);
  1406. textarea.select();
  1407. textarea.mouseup(function() {
  1408. textarea.unbind("mouseup");
  1409. return false;
  1410. });
  1411. });
  1412. $( "#dialog" ).dialog("option","title","Export nodes to clipboard").dialog( "open" );
  1413. $("#node-input-export").focus();
  1414. }
  1415. function showExportNodesLibraryDialog() {
  1416. mouse_mode = RED.state.EXPORT;
  1417. var nns = RED.nodes.createExportableNodeSet(moving_set);
  1418. $("#dialog-form").html($("script[data-template-name='export-library-dialog']").html());
  1419. $("#node-input-filename").attr('nodes',JSON.stringify(nns));
  1420. $( "#dialog" ).dialog("option","title","Export nodes to library").dialog( "open" );
  1421. }
  1422. function showImportNodesDialog() {
  1423. mouse_mode = RED.state.IMPORT;
  1424. $("#dialog-form").html($("script[data-template-name='import-dialog']").html());
  1425. $("#node-input-import").val("");
  1426. $( "#dialog" ).dialog("option","title","Import nodes").dialog( "open" );
  1427. }
  1428. function showRenameWorkspaceDialog(id) {
  1429. var ws = RED.nodes.workspace(id);
  1430. $( "#node-dialog-rename-workspace" ).dialog("option","workspace",ws);
  1431. if (workspace_tabs.count() == 1) {
  1432. $( "#node-dialog-rename-workspace").next().find(".leftButton")
  1433. .prop('disabled',true)
  1434. .addClass("ui-state-disabled");
  1435. } else {
  1436. $( "#node-dialog-rename-workspace").next().find(".leftButton")
  1437. .prop('disabled',false)
  1438. .removeClass("ui-state-disabled");
  1439. }
  1440. $( "#node-input-workspace-name" ).val(ws.label);
  1441. $( "#node-dialog-rename-workspace" ).dialog("open");
  1442. }
  1443. $("#node-dialog-rename-workspace form" ).submit(function(e) { e.preventDefault();});
  1444. $( "#node-dialog-rename-workspace" ).dialog({
  1445. modal: true,
  1446. autoOpen: false,
  1447. width: 500,
  1448. title: "Rename sheet",
  1449. buttons: [
  1450. {
  1451. class: 'leftButton',
  1452. text: "Delete",
  1453. click: function() {
  1454. var workspace = $(this).dialog('option','workspace');
  1455. $( this ).dialog( "close" );
  1456. deleteWorkspace(workspace.id);
  1457. }
  1458. },
  1459. {
  1460. text: "Ok",
  1461. click: function() {
  1462. var workspace = $(this).dialog('option','workspace');
  1463. var label = $( "#node-input-workspace-name" ).val();
  1464. if (workspace.label != label) {
  1465. workspace.label = label;
  1466. var link = $("#workspace-tabs a[href='#"+workspace.id+"']");
  1467. link.attr("title",label);
  1468. link.text(label);
  1469. RED.view.dirty(true);
  1470. }
  1471. $( this ).dialog( "close" );
  1472. }
  1473. },
  1474. {
  1475. text: "Cancel",
  1476. click: function() {
  1477. $( this ).dialog( "close" );
  1478. }
  1479. }
  1480. ],
  1481. open: function(e) {
  1482. RED.keyboard.disable();
  1483. },
  1484. close: function(e) {
  1485. RED.keyboard.enable();
  1486. }
  1487. });
  1488. $( "#node-dialog-delete-workspace" ).dialog({
  1489. modal: true,
  1490. autoOpen: false,
  1491. width: 500,
  1492. title: "Confirm delete",
  1493. buttons: [
  1494. {
  1495. text: "Ok",
  1496. click: function() {
  1497. var workspace = $(this).dialog('option','workspace');
  1498. RED.view.removeWorkspace(workspace);
  1499. var historyEvent = RED.nodes.removeWorkspace(workspace.id);
  1500. historyEvent.t = 'delete';
  1501. historyEvent.dirty = dirty;
  1502. historyEvent.workspaces = [workspace];
  1503. RED.history.push(historyEvent);
  1504. RED.view.dirty(true);
  1505. $( this ).dialog( "close" );
  1506. }
  1507. },
  1508. {
  1509. text: "Cancel",
  1510. click: function() {
  1511. $( this ).dialog( "close" );
  1512. }
  1513. }
  1514. ],
  1515. open: function(e) {
  1516. RED.keyboard.disable();
  1517. },
  1518. close: function(e) {
  1519. RED.keyboard.enable();
  1520. }
  1521. });
  1522. return {
  1523. state:function(state) {
  1524. if (state == null) {
  1525. return mouse_mode
  1526. } else {
  1527. mouse_mode = state;
  1528. }
  1529. },
  1530. addWorkspace: function(ws) {
  1531. workspace_tabs.addTab(ws);
  1532. workspace_tabs.resize();
  1533. },
  1534. removeWorkspace: function(ws) {
  1535. workspace_tabs.removeTab(ws.id);
  1536. },
  1537. getWorkspace: function() {
  1538. return activeWorkspace;
  1539. },
  1540. showWorkspace: function(id) {
  1541. workspace_tabs.activateTab(id);
  1542. },
  1543. redraw:redraw,
  1544. dirty: function(d) {
  1545. if (d == null) {
  1546. return dirty;
  1547. } else {
  1548. setDirty(d);
  1549. }
  1550. },
  1551. importNodes: importNodes,
  1552. resize: function() {
  1553. workspace_tabs.resize();
  1554. },
  1555. status: function(s) {
  1556. showStatus = s;
  1557. RED.nodes.eachNode(function(n) { n.dirty = true;});
  1558. //TODO: subscribe/unsubscribe here
  1559. redraw();
  1560. }
  1561. };
  1562. })();