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

1677 lines
72KB

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