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.

4 anni fa
4 anni fa
4 anni fa
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913
  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. /*
  179. var grid = vis.append('g');
  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. */
  209. var drag_line = vis.append("svg:path").attr("class", "drag_line");
  210. var workspace_tabs = RED.tabs.create({
  211. id: "workspace-tabs",
  212. onchange: function(tab) {
  213. if (tab.type == "subflow") {
  214. $("#workspace-toolbar").show();
  215. } else {
  216. $("#workspace-toolbar").hide();
  217. }
  218. var chart = $("#chart");
  219. if (activeWorkspace !== 0) {
  220. workspaceScrollPositions[activeWorkspace] = {
  221. left:chart.scrollLeft(),
  222. top:chart.scrollTop()
  223. };
  224. }
  225. var scrollStartLeft = chart.scrollLeft();
  226. var scrollStartTop = chart.scrollTop();
  227. activeWorkspace = tab.id;
  228. if (workspaceScrollPositions[activeWorkspace]) {
  229. chart.scrollLeft(workspaceScrollPositions[activeWorkspace].left);
  230. chart.scrollTop(workspaceScrollPositions[activeWorkspace].top);
  231. } else {
  232. chart.scrollLeft(0);
  233. chart.scrollTop(0);
  234. }
  235. var scrollDeltaLeft = chart.scrollLeft() - scrollStartLeft;
  236. var scrollDeltaTop = chart.scrollTop() - scrollStartTop;
  237. if (mouse_position != null) {
  238. mouse_position[0] += scrollDeltaLeft;
  239. mouse_position[1] += scrollDeltaTop;
  240. }
  241. clearSelection();
  242. RED.nodes.eachNode(function(n) {
  243. n.dirty = true;
  244. });
  245. redraw();
  246. },
  247. ondblclick: function(tab) {
  248. showRenameWorkspaceDialog(tab.id);
  249. },
  250. onadd: function(tab) {
  251. var menuli = $("<li/>");
  252. var menuA = $("<a/>",{tabindex:"-1",href:"#"+tab.id}).appendTo(menuli);
  253. menuA.html(tab.label);
  254. menuA.on("click",function() {
  255. workspace_tabs.activateTab(tab.id);
  256. });
  257. $('#workspace-menu-list').append(menuli);
  258. if (workspace_tabs.count() == 1) {
  259. $('#btn-workspace-delete').parent().addClass("disabled");
  260. } else {
  261. $('#btn-workspace-delete').parent().removeClass("disabled");
  262. }
  263. },
  264. onremove: function(tab) {
  265. if (workspace_tabs.count() == 1) {
  266. $('#btn-workspace-delete').parent().addClass("disabled");
  267. } else {
  268. $('#btn-workspace-delete').parent().removeClass("disabled");
  269. }
  270. $('#workspace-menu-list a[href="#'+tab.id+'"]').parent().remove();
  271. }
  272. });
  273. var workspaceIndex = 0;
  274. function addWorkspace() {
  275. var tabId = RED.nodes.id();
  276. do {
  277. workspaceIndex += 1;
  278. } while($("#workspace-tabs a[title='Sheet "+workspaceIndex+"']").size() !== 0);
  279. var ws = {type:"tab",id:tabId,label:"Sheet "+workspaceIndex};
  280. RED.nodes.addWorkspace(ws);
  281. workspace_tabs.addTab(ws);
  282. workspace_tabs.activateTab(tabId);
  283. RED.history.push({t:'add',workspaces:[ws],dirty:dirty});
  284. RED.view.dirty(true);
  285. }
  286. $('#btn-workspace-add-tab').on("click",addWorkspace);
  287. $('#btn-workspace-add').on("click",addWorkspace);
  288. $('#btn-workspace-edit').on("click",function() {
  289. showRenameWorkspaceDialog(activeWorkspace);
  290. });
  291. $('#btn-workspace-delete').on("click",function() {
  292. deleteWorkspace(activeWorkspace);
  293. });
  294. function deleteWorkspace(id) {
  295. if (workspace_tabs.count() == 1) {
  296. return;
  297. }
  298. var ws = RED.nodes.workspace(id);
  299. $( "#node-dialog-delete-workspace" ).dialog('option','workspace',ws);
  300. $( "#node-dialog-delete-workspace-name" ).text(ws.label);
  301. $( "#node-dialog-delete-workspace" ).dialog('open');
  302. }
  303. function canvasMouseDown() {
  304. if (!mousedown_node && !mousedown_link) {
  305. selected_link = null;
  306. updateSelection();
  307. }
  308. if (mouse_mode === 0) {
  309. if (lasso) {
  310. lasso.remove();
  311. lasso = null;
  312. }
  313. if (!touchStartTime) {
  314. var point = d3.mouse(this);
  315. lasso = vis.append('rect')
  316. .attr("ox",point[0])
  317. .attr("oy",point[1])
  318. .attr("rx",2)
  319. .attr("ry",2)
  320. .attr("x",point[0])
  321. .attr("y",point[1])
  322. .attr("width",0)
  323. .attr("height",0)
  324. .attr("class","lasso");
  325. d3.event.preventDefault();
  326. }
  327. }
  328. }
  329. function canvasMouseMove() {
  330. mouse_position = d3.touches(this)[0]||d3.mouse(this);
  331. // Prevent touch scrolling...
  332. //if (d3.touches(this)[0]) {
  333. // d3.event.preventDefault();
  334. //}
  335. // TODO: auto scroll the container
  336. //var point = d3.mouse(this);
  337. //if (point[0]-container.scrollLeft < 30 && container.scrollLeft > 0) { container.scrollLeft -= 15; }
  338. //console.log(d3.mouse(this),container.offsetWidth,container.offsetHeight,container.scrollLeft,container.scrollTop);
  339. if (lasso) {
  340. var ox = parseInt(lasso.attr("ox"));
  341. var oy = parseInt(lasso.attr("oy"));
  342. var x = parseInt(lasso.attr("x"));
  343. var y = parseInt(lasso.attr("y"));
  344. var w;
  345. var h;
  346. if (mouse_position[0] < ox) {
  347. x = mouse_position[0];
  348. w = ox-x;
  349. } else {
  350. w = mouse_position[0]-x;
  351. }
  352. if (mouse_position[1] < oy) {
  353. y = mouse_position[1];
  354. h = oy-y;
  355. } else {
  356. h = mouse_position[1]-y;
  357. }
  358. lasso
  359. .attr("x",x)
  360. .attr("y",y)
  361. .attr("width",w)
  362. .attr("height",h)
  363. ;
  364. return;
  365. }
  366. if (mouse_mode != RED.state.IMPORT_DRAGGING && !mousedown_node && selected_link == null) {
  367. return;
  368. }
  369. var mousePos;
  370. if (mouse_mode == RED.state.JOINING) {
  371. // update drag line
  372. drag_line.attr("class", "drag_line");
  373. mousePos = mouse_position;
  374. var numOutputs = (mousedown_port_type === 0)?(mousedown_node.outputs || 1):(mousedown_node._def.inputs || 1);
  375. var sourcePort = mousedown_port_index;
  376. var portY = -((numOutputs-1)/2)*13 +13*sourcePort;
  377. var sc = (mousedown_port_type === 0)?1:-1;
  378. var dy = mousePos[1]-(mousedown_node.y+portY);
  379. var dx = mousePos[0]-(mousedown_node.x+sc*mousedown_node.w/2);
  380. var delta = Math.sqrt(dy*dy+dx*dx);
  381. var scale = lineCurveScale;
  382. var scaleY = 0;
  383. if (delta < node_width) {
  384. scale = 0.75-0.75*((node_width-delta)/node_width);
  385. }
  386. if (dx*sc < 0) {
  387. scale += 2*(Math.min(5*node_width,Math.abs(dx))/(5*node_width));
  388. if (Math.abs(dy) < 3*node_height) {
  389. 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)) ;
  390. }
  391. }
  392. drag_line.attr("d",
  393. "M "+(mousedown_node.x+sc*mousedown_node.w/2)+" "+(mousedown_node.y+portY)+
  394. " C "+(mousedown_node.x+sc*(mousedown_node.w/2+node_width*scale))+" "+(mousedown_node.y+portY+scaleY*node_height)+" "+
  395. (mousePos[0]-sc*(scale)*node_width)+" "+(mousePos[1]-scaleY*node_height)+" "+
  396. mousePos[0]+" "+mousePos[1]
  397. );
  398. d3.event.preventDefault();
  399. } else if (mouse_mode == RED.state.MOVING) {
  400. mousePos = mouse_position;
  401. var d = (mouse_offset[0]-mousePos[0])*(mouse_offset[0]-mousePos[0]) + (mouse_offset[1]-mousePos[1])*(mouse_offset[1]-mousePos[1]);
  402. if (d > 2) {
  403. mouse_mode = RED.state.MOVING_ACTIVE;
  404. clickElapsed = 0;
  405. }
  406. } else if (mouse_mode == RED.state.MOVING_ACTIVE || mouse_mode == RED.state.IMPORT_DRAGGING) {
  407. mousePos = mouse_position;
  408. var node;
  409. var i;
  410. var minX = 0;
  411. var minY = 0;
  412. for (var n = 0; n<moving_set.length; n++) {
  413. node = moving_set[n];
  414. if (d3.event.shiftKey) {
  415. node.n.ox = node.n.x;
  416. node.n.oy = node.n.y;
  417. }
  418. node.n.x = mousePos[0]+node.dx;
  419. node.n.y = mousePos[1]+node.dy;
  420. node.n.dirty = true;
  421. minX = Math.min(node.n.x-node.n.w/2-5,minX);
  422. minY = Math.min(node.n.y-node.n.h/2-5,minY);
  423. }
  424. if (minX !== 0 || minY !== 0) {
  425. for (i = 0; i<moving_set.length; i++) {
  426. node = moving_set[i];
  427. node.n.x -= minX;
  428. node.n.y -= minY;
  429. }
  430. }
  431. if (d3.event.shiftKey && moving_set.length > 0) {
  432. var gridOffset = [0,0];
  433. node = moving_set[0];
  434. gridOffset[0] = node.n.x-(20*Math.floor((node.n.x-node.n.w/2)/20)+node.n.w/2);
  435. gridOffset[1] = node.n.y-(20*Math.floor(node.n.y/20));
  436. if (gridOffset[0] !== 0 || gridOffset[1] !== 0) {
  437. for (i = 0; i<moving_set.length; i++) {
  438. node = moving_set[i];
  439. node.n.x -= gridOffset[0];
  440. node.n.y -= gridOffset[1];
  441. if (node.n.x == node.n.ox && node.n.y == node.n.oy) {
  442. node.dirty = false;
  443. }
  444. }
  445. }
  446. }
  447. }
  448. redraw();
  449. }
  450. function canvasMouseUp() {
  451. if (mousedown_node && mouse_mode == RED.state.JOINING) {
  452. drag_line.attr("class", "drag_line_hidden");
  453. }
  454. if (lasso) {
  455. var x = parseInt(lasso.attr("x"));
  456. var y = parseInt(lasso.attr("y"));
  457. var x2 = x+parseInt(lasso.attr("width"));
  458. var y2 = y+parseInt(lasso.attr("height"));
  459. if (!d3.event.ctrlKey) {
  460. clearSelection();
  461. }
  462. RED.nodes.eachNode(function(n) {
  463. if (n.z == activeWorkspace && !n.selected) {
  464. n.selected = (n.x > x && n.x < x2 && n.y > y && n.y < y2);
  465. if (n.selected) {
  466. n.dirty = true;
  467. moving_set.push({n:n});
  468. }
  469. }
  470. });
  471. updateSelection();
  472. lasso.remove();
  473. lasso = null;
  474. } else if (mouse_mode == RED.state.DEFAULT && mousedown_link == null) {
  475. clearSelection();
  476. updateSelection();
  477. }
  478. if (mouse_mode == RED.state.MOVING_ACTIVE) {
  479. if (moving_set.length > 0) {
  480. var ns = [];
  481. for (var j=0;j<moving_set.length;j++) {
  482. ns.push({n:moving_set[j].n,ox:moving_set[j].ox,oy:moving_set[j].oy});
  483. }
  484. RED.history.push({t:'move',nodes:ns,dirty:dirty});
  485. RED.storage.update();
  486. }
  487. }
  488. if (mouse_mode == RED.state.MOVING || mouse_mode == RED.state.MOVING_ACTIVE) {
  489. for (var i=0;i<moving_set.length;i++) {
  490. delete moving_set[i].ox;
  491. delete moving_set[i].oy;
  492. }
  493. }
  494. if (mouse_mode == RED.state.IMPORT_DRAGGING) {
  495. RED.keyboard.remove(/* ESCAPE */ 27);
  496. setDirty(true);
  497. }
  498. redraw();
  499. // clear mouse event vars
  500. resetMouseVars();
  501. }
  502. $('#btn-zoom-out').click(function() {zoomOut();});
  503. $('#btn-zoom-zero').click(function() {zoomZero();});
  504. $('#btn-zoom-in').click(function() {zoomIn();});
  505. $("#chart").on('DOMMouseScroll mousewheel', function (evt) {
  506. if ( evt.altKey ) {
  507. evt.preventDefault();
  508. evt.stopPropagation();
  509. var move = -(evt.originalEvent.detail) || evt.originalEvent.wheelDelta;
  510. if (move <= 0) { zoomOut(); }
  511. else { zoomIn(); }
  512. }
  513. });
  514. $("#chart").droppable({
  515. accept:".palette_node",
  516. drop: function( event, ui ) {
  517. d3.event = event;
  518. var selected_tool = ui.draggable[0].type;
  519. var mousePos = d3.touches(this)[0]||d3.mouse(this);
  520. mousePos[1] += this.scrollTop;
  521. mousePos[0] += this.scrollLeft;
  522. mousePos[1] /= scaleFactor;
  523. mousePos[0] /= scaleFactor;
  524. var nn = {x: mousePos[0],y:mousePos[1],w:node_width,z:activeWorkspace};
  525. nn.type = selected_tool;
  526. nn._def = RED.nodes.getType(nn.type);
  527. nn.id = RED.nodes.cppName(nn);
  528. nn._def.defaults = nn._def.defaults ? nn._def.defaults : {};
  529. nn._def.defaults.name = { value: nn.id };
  530. nn.outputs = nn._def.outputs;
  531. nn.changed = true;
  532. for (var d in nn._def.defaults) {
  533. if (nn._def.defaults.hasOwnProperty(d)) {
  534. nn[d] = nn._def.defaults[d].value;
  535. }
  536. }
  537. if (nn._def.onadd) {
  538. nn._def.onadd.call(nn);
  539. }
  540. nn.h = Math.max(node_height,(nn.outputs||0) * 15);
  541. RED.history.push({t:'add',nodes:[nn.id],dirty:dirty});
  542. RED.nodes.add(nn);
  543. RED.editor.validateNode(nn);
  544. setDirty(true);
  545. // auto select dropped node - so info shows (if visible)
  546. clearSelection();
  547. nn.selected = true;
  548. moving_set.push({n:nn});
  549. updateSelection();
  550. redraw();
  551. redraw(); //there is no other way to mark _all_ errors on conflicts :(
  552. if (nn._def.autoedit) {
  553. RED.editor.edit(nn);
  554. }
  555. }
  556. });
  557. function zoomIn() {
  558. if (scaleFactor < 2) {
  559. scaleFactor += 0.1;
  560. redraw();
  561. }
  562. }
  563. function zoomOut() {
  564. if (scaleFactor > 0.3) {
  565. scaleFactor -= 0.1;
  566. redraw();
  567. }
  568. }
  569. function zoomZero() {
  570. scaleFactor = 1;
  571. redraw();
  572. }
  573. function selectAll() {
  574. RED.nodes.eachNode(function(n) {
  575. if (n.z == activeWorkspace) {
  576. if (!n.selected) {
  577. n.selected = true;
  578. n.dirty = true;
  579. moving_set.push({n:n});
  580. }
  581. }
  582. });
  583. selected_link = null;
  584. updateSelection();
  585. redraw();
  586. }
  587. function clearSelection() {
  588. for (var i=0;i<moving_set.length;i++) {
  589. var n = moving_set[i];
  590. n.n.dirty = true;
  591. n.n.selected = false;
  592. }
  593. moving_set = [];
  594. selected_link = null;
  595. }
  596. function updateSelection() {
  597. if (moving_set.length === 0) {
  598. $("#li-menu-export").addClass("disabled");
  599. $("#li-menu-export-clipboard").addClass("disabled");
  600. $("#li-menu-export-library").addClass("disabled");
  601. } else {
  602. $("#li-menu-export").removeClass("disabled");
  603. $("#li-menu-export-clipboard").removeClass("disabled");
  604. $("#li-menu-export-library").removeClass("disabled");
  605. }
  606. if (moving_set.length === 0 && selected_link == null) {
  607. RED.keyboard.remove(/* backspace */ 8);
  608. RED.keyboard.remove(/* delete */ 46);
  609. RED.keyboard.remove(/* c */ 67);
  610. RED.keyboard.remove(/* x */ 88);
  611. } else {
  612. RED.keyboard.add(/* backspace */ 8,function(){deleteSelection();d3.event.preventDefault();});
  613. RED.keyboard.add(/* delete */ 46,function(){deleteSelection();d3.event.preventDefault();});
  614. RED.keyboard.add(/* c */ 67,{ctrl:true},function(){copySelection();d3.event.preventDefault();});
  615. RED.keyboard.add(/* x */ 88,{ctrl:true},function(){copySelection();deleteSelection();d3.event.preventDefault();});
  616. }
  617. if (moving_set.length === 0) {
  618. RED.keyboard.remove(/* up */ 38);
  619. RED.keyboard.remove(/* down */ 40);
  620. RED.keyboard.remove(/* left */ 37);
  621. RED.keyboard.remove(/* right*/ 39);
  622. } else {
  623. RED.keyboard.add(/* up */ 38, function() { if(d3.event.shiftKey){moveSelection( 0,-20)}else{moveSelection( 0,-1);}d3.event.preventDefault();},endKeyboardMove);
  624. RED.keyboard.add(/* down */ 40, function() { if(d3.event.shiftKey){moveSelection( 0, 20)}else{moveSelection( 0, 1);}d3.event.preventDefault();},endKeyboardMove);
  625. RED.keyboard.add(/* left */ 37, function() { if(d3.event.shiftKey){moveSelection(-20, 0)}else{moveSelection(-1, 0);}d3.event.preventDefault();},endKeyboardMove);
  626. RED.keyboard.add(/* right*/ 39, function() { if(d3.event.shiftKey){moveSelection( 20, 0)}else{moveSelection( 1, 0);}d3.event.preventDefault();},endKeyboardMove);
  627. }
  628. if (moving_set.length == 1) {
  629. RED.sidebar.info.refresh(moving_set[0].n);
  630. RED.nodes.selectNode(moving_set[0].n.type);
  631. } else {
  632. RED.sidebar.info.clear();
  633. }
  634. }
  635. function endKeyboardMove() {
  636. var ns = [];
  637. for (var i=0;i<moving_set.length;i++) {
  638. ns.push({n:moving_set[i].n,ox:moving_set[i].ox,oy:moving_set[i].oy});
  639. delete moving_set[i].ox;
  640. delete moving_set[i].oy;
  641. }
  642. RED.history.push({t:'move',nodes:ns,dirty:dirty});
  643. }
  644. function moveSelection(dx,dy) {
  645. var minX = 0;
  646. var minY = 0;
  647. var node;
  648. for (var i=0;i<moving_set.length;i++) {
  649. node = moving_set[i];
  650. if (node.ox == null && node.oy == null) {
  651. node.ox = node.n.x;
  652. node.oy = node.n.y;
  653. }
  654. node.n.x += dx;
  655. node.n.y += dy;
  656. node.n.dirty = true;
  657. minX = Math.min(node.n.x-node.n.w/2-5,minX);
  658. minY = Math.min(node.n.y-node.n.h/2-5,minY);
  659. }
  660. if (minX !== 0 || minY !== 0) {
  661. for (var n = 0; n<moving_set.length; n++) {
  662. node = moving_set[n];
  663. node.n.x -= minX;
  664. node.n.y -= minY;
  665. }
  666. }
  667. redraw();
  668. }
  669. function deleteSelection() {
  670. var removedNodes = [];
  671. var removedLinks = [];
  672. var startDirty = dirty;
  673. if (moving_set.length > 0) {
  674. for (var i=0;i<moving_set.length;i++) {
  675. var node = moving_set[i].n;
  676. node.selected = false;
  677. if (node.x < 0) {
  678. node.x = 25
  679. }
  680. var rmlinks = RED.nodes.remove(node.id);
  681. for (var j=0; j < rmlinks.length; j++) {
  682. var link = rmlinks[j];
  683. //console.log("delete link: " + link.source.id + ":" + link.sourcePort
  684. // + " -> " + link.target.id + ":" + link.targetPort);
  685. if (link.source == node) {
  686. // reenable input port
  687. var n = link.targetPort;
  688. var rect = link.target.inputlist[n];
  689. rect.on("mousedown", (function(d,n){return function(d){portMouseDown(d,1,n);}})(rect, n))
  690. .on("touchstart", (function(d,n){return function(d){portMouseDown(d,1,n);}})(rect, n))
  691. .on("mouseup", (function(d,n){return function(d){portMouseUp(d,1,n);}})(rect, n))
  692. .on("touchend", (function(d,n){return function(d){portMouseUp(d,1,n);}})(rect, n))
  693. .on("mouseover",function(d) { var port = d3.select(this); port.classed("port_hovered",(mouse_mode!=RED.state.JOINING || mousedown_port_type != 1 ));})
  694. .on("mouseout",function(d) { var port = d3.select(this); port.classed("port_hovered",false);})
  695. }
  696. }
  697. removedNodes.push(node);
  698. removedLinks = removedLinks.concat(rmlinks);
  699. }
  700. moving_set = [];
  701. setDirty(true);
  702. }
  703. if (selected_link) {
  704. // reenable input port
  705. var n = selected_link.targetPort;
  706. var rect = selected_link.target.inputlist[n];
  707. rect.on("mousedown", (function(d,n){return function(d){portMouseDown(d,1,n);}})(rect, n))
  708. .on("touchstart", (function(d,n){return function(d){portMouseDown(d,1,n);}})(rect, n))
  709. .on("mouseup", (function(d,n){return function(d){portMouseUp(d,1,n);}})(rect, n))
  710. .on("touchend", (function(d,n){return function(d){portMouseUp(d,1,n);}})(rect, n))
  711. .on("mouseover",function(d) { var port = d3.select(this); port.classed("port_hovered",(mouse_mode!=RED.state.JOINING || mousedown_port_type != 1 ));})
  712. .on("mouseout",function(d) { var port = d3.select(this); port.classed("port_hovered",false);});
  713. RED.nodes.removeLink(selected_link);
  714. removedLinks.push(selected_link);
  715. setDirty(true);
  716. }
  717. RED.history.push({t:'delete',nodes:removedNodes,links:removedLinks,dirty:startDirty});
  718. selected_link = null;
  719. updateSelection();
  720. redraw();
  721. }
  722. function copySelection() {
  723. if (moving_set.length > 0) {
  724. var nns = [];
  725. for (var n=0;n<moving_set.length;n++) {
  726. var node = moving_set[n].n;
  727. nns.push(RED.nodes.convertNode(node));
  728. }
  729. clipboard = JSON.stringify(nns);
  730. RED.notify(moving_set.length+" node"+(moving_set.length>1?"s":"")+" copied");
  731. }
  732. }
  733. function calculateTextWidth(str) {
  734. var sp = document.createElement("span");
  735. sp.className = "node_label";
  736. sp.style.position = "absolute";
  737. sp.style.top = "-1000px";
  738. sp.innerHTML = (str||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
  739. document.body.appendChild(sp);
  740. var w = sp.offsetWidth;
  741. document.body.removeChild(sp);
  742. return 50+w;
  743. }
  744. function resetMouseVars() {
  745. mousedown_node = null;
  746. mouseup_node = null;
  747. mousedown_link = null;
  748. mouse_mode = 0;
  749. mousedown_port_type = 0;
  750. }
  751. function portMouseDown(d,portType,portIndex) {
  752. // disable zoom
  753. //vis.call(d3.behavior.zoom().on("zoom"), null);
  754. mousedown_node = d;
  755. selected_link = null;
  756. mouse_mode = RED.state.JOINING;
  757. mousedown_port_type = portType;
  758. mousedown_port_index = portIndex || 0;
  759. document.body.style.cursor = "crosshair";
  760. d3.event.preventDefault();
  761. }
  762. function portMouseUp(d,portType,portIndex) {
  763. document.body.style.cursor = "";
  764. if (mouse_mode == RED.state.JOINING && mousedown_node) {
  765. if (typeof TouchEvent != "undefined" && d3.event instanceof TouchEvent) {
  766. RED.nodes.eachNode(function(n) {
  767. if (n.z == activeWorkspace) {
  768. var hw = n.w/2;
  769. var hh = n.h/2;
  770. if (n.x-hw<mouse_position[0] && n.x+hw> mouse_position[0] &&
  771. n.y-hh<mouse_position[1] && n.y+hh>mouse_position[1]) {
  772. mouseup_node = n;
  773. portType = mouseup_node._def.inputs>0?1:0;
  774. portIndex = 0;
  775. }
  776. }
  777. });
  778. } else {
  779. mouseup_node = d;
  780. }
  781. if (portType == mousedown_port_type || mouseup_node === mousedown_node) {
  782. drag_line.attr("class", "drag_line_hidden");
  783. resetMouseVars();
  784. return;
  785. }
  786. var src,dst,src_port,dst_port;
  787. if (mousedown_port_type === 0) {
  788. src = mousedown_node;
  789. src_port = mousedown_port_index;
  790. dst = mouseup_node;
  791. dst_port = portIndex;
  792. } else if (mousedown_port_type == 1) {
  793. src = mouseup_node;
  794. src_port = portIndex;
  795. dst = mousedown_node;
  796. dst_port = mousedown_port_index;
  797. }
  798. var existingLink = false;
  799. RED.nodes.eachLink(function(d) {
  800. existingLink = existingLink || (d.source === src && d.target === dst && d.sourcePort == src_port && d.targetPort == dst_port);
  801. });
  802. if (!existingLink) {
  803. var link = {source: src, sourcePort:src_port, target: dst, targetPort: dst_port};
  804. RED.nodes.addLink(link);
  805. RED.history.push({t:'add',links:[link],dirty:dirty});
  806. setDirty(true);
  807. // disallow new links to this destination - each input can have only a single link
  808. dst.inputlist[dst_port]
  809. .classed("port_hovered",false)
  810. .on("mousedown",null)
  811. .on("touchstart", null)
  812. .on("mouseup", null)
  813. .on("touchend", null)
  814. .on("mouseover", null)
  815. .on("mouseout", null);
  816. }
  817. selected_link = null;
  818. redraw();
  819. }
  820. }
  821. function nodeMouseUp(d) {
  822. if (dblClickPrimed && mousedown_node == d && clickElapsed > 0 && clickElapsed < 750) {
  823. RED.editor.edit(d);
  824. clickElapsed = 0;
  825. d3.event.stopPropagation();
  826. return;
  827. }
  828. portMouseUp(d, d._def.inputs > 0 ? 1 : 0, 0);
  829. }
  830. function nodeMouseDown(d) {
  831. //var touch0 = d3.event;
  832. //var pos = [touch0.pageX,touch0.pageY];
  833. //RED.touch.radialMenu.show(d3.select(this),pos);
  834. if (mouse_mode == RED.state.IMPORT_DRAGGING) {
  835. RED.keyboard.remove(/* ESCAPE */ 27);
  836. updateSelection();
  837. setDirty(true);
  838. redraw();
  839. resetMouseVars();
  840. d3.event.stopPropagation();
  841. return;
  842. }
  843. mousedown_node = d;
  844. var now = Date.now();
  845. clickElapsed = now-clickTime;
  846. clickTime = now;
  847. dblClickPrimed = (lastClickNode == mousedown_node);
  848. lastClickNode = mousedown_node;
  849. var i;
  850. if (d.selected && d3.event.ctrlKey) {
  851. d.selected = false;
  852. for (i=0;i<moving_set.length;i+=1) {
  853. if (moving_set[i].n === d) {
  854. moving_set.splice(i,1);
  855. break;
  856. }
  857. }
  858. } else {
  859. if (d3.event.shiftKey) {
  860. clearSelection();
  861. var cnodes = RED.nodes.getAllFlowNodes(mousedown_node);
  862. for (var n=0;n<cnodes.length;n++) {
  863. cnodes[n].selected = true;
  864. cnodes[n].dirty = true;
  865. moving_set.push({n:cnodes[n]});
  866. }
  867. } else if (!d.selected) {
  868. if (!d3.event.ctrlKey) {
  869. clearSelection();
  870. }
  871. mousedown_node.selected = true;
  872. moving_set.push({n:mousedown_node});
  873. }
  874. selected_link = null;
  875. if (d3.event.button != 2) {
  876. mouse_mode = RED.state.MOVING;
  877. var mouse = d3.touches(this)[0]||d3.mouse(this);
  878. mouse[0] += d.x-d.w/2;
  879. mouse[1] += d.y-d.h/2;
  880. for (i=0;i<moving_set.length;i++) {
  881. moving_set[i].ox = moving_set[i].n.x;
  882. moving_set[i].oy = moving_set[i].n.y;
  883. moving_set[i].dx = moving_set[i].n.x-mouse[0];
  884. moving_set[i].dy = moving_set[i].n.y-mouse[1];
  885. }
  886. mouse_offset = d3.mouse(document.body);
  887. if (isNaN(mouse_offset[0])) {
  888. mouse_offset = d3.touches(document.body)[0];
  889. }
  890. }
  891. }
  892. d.dirty = true;
  893. updateSelection();
  894. redraw();
  895. d3.event.stopPropagation();
  896. }
  897. function nodeButtonClicked(d) {
  898. if (d._def.button.toggle) {
  899. d[d._def.button.toggle] = !d[d._def.button.toggle];
  900. d.dirty = true;
  901. }
  902. if (d._def.button.onclick) {
  903. d._def.button.onclick.call(d);
  904. }
  905. if (d.dirty) {
  906. redraw();
  907. }
  908. d3.event.preventDefault();
  909. }
  910. function showTouchMenu(obj,pos) {
  911. var mdn = mousedown_node;
  912. var options = [];
  913. options.push({name:"delete",disabled:(moving_set.length===0),onselect:function() {deleteSelection();}});
  914. options.push({name:"cut",disabled:(moving_set.length===0),onselect:function() {copySelection();deleteSelection();}});
  915. options.push({name:"copy",disabled:(moving_set.length===0),onselect:function() {copySelection();}});
  916. options.push({name:"paste",disabled:(clipboard.length===0),onselect:function() {importNodes(clipboard,true);}});
  917. options.push({name:"edit",disabled:(moving_set.length != 1),onselect:function() { RED.editor.edit(mdn);}});
  918. options.push({name:"select",onselect:function() {selectAll();}});
  919. options.push({name:"undo",disabled:(RED.history.depth() === 0),onselect:function() {RED.history.pop();}});
  920. RED.touch.radialMenu.show(obj,pos,options);
  921. resetMouseVars();
  922. }
  923. function redraw() {
  924. vis.attr("transform","scale("+scaleFactor+")");
  925. outer.attr("width", space_width*scaleFactor).attr("height", space_height*scaleFactor);
  926. if (mouse_mode != RED.state.JOINING) {
  927. // Don't bother redrawing nodes if we're drawing links
  928. var node = vis.selectAll(".nodegroup").data(RED.nodes.nodes.filter(function(d) { return d.z == activeWorkspace }),function(d){return d.id});
  929. node.exit().remove();
  930. var nodeEnter = node.enter().insert("svg:g").attr("class", "node nodegroup");
  931. nodeEnter.each(function(d,i) {
  932. var node = d3.select(this);
  933. node.attr("id",d.id);
  934. //var l = d._def.label;
  935. //l = (typeof l === "function" ? l.call(d) : l)||"";
  936. var l = d.name ? d.name : d.id;
  937. d.w = Math.max(node_width,calculateTextWidth(l)+(d._def.inputs>0?7:0) );
  938. d.h = Math.max(node_height,(Math.max(d.outputs,d._def.inputs)||0) * 15);
  939. node.append("dfn").attr("class", "tooltip").append("span").attr("role","tooltip");
  940. if (d._def.badge) {
  941. var badge = node.append("svg:g").attr("class","node_badge_group");
  942. var badgeRect = badge.append("rect").attr("class","node_badge").attr("rx",5).attr("ry",5).attr("width",40).attr("height",15);
  943. badge.append("svg:text").attr("class","node_badge_label").attr("x",35).attr("y",11).attr('text-anchor','end').text(d._def.badge());
  944. if (d._def.onbadgeclick) {
  945. badgeRect.attr("cursor","pointer")
  946. .on("click",function(d) { d._def.onbadgeclick.call(d);d3.event.preventDefault();});
  947. }
  948. }
  949. if (d._def.button) {
  950. var nodeButtonGroup = node.append('svg:g')
  951. .attr("transform",function(d) { return "translate("+((d._def.align == "right") ? 94 : -25)+",2)"; })
  952. .attr("class",function(d) { return "node_button "+((d._def.align == "right") ? "node_right_button" : "node_left_button"); });
  953. nodeButtonGroup.append('rect')
  954. .attr("rx",8)
  955. .attr("ry",8)
  956. .attr("width",32)
  957. .attr("height",node_height-4)
  958. .attr("fill","#eee");//function(d) { return d._def.color;})
  959. nodeButtonGroup.append('rect')
  960. .attr("x",function(d) { return d._def.align == "right"? 10:5})
  961. .attr("y",4)
  962. .attr("rx",5)
  963. .attr("ry",5)
  964. .attr("width",16)
  965. .attr("height",node_height-12)
  966. .attr("fill",function(d) { return d._def.color;})
  967. .attr("cursor","pointer")
  968. .on("mousedown",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",0.2);d3.event.preventDefault(); d3.event.stopPropagation();}})
  969. .on("mouseup",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",0.4);d3.event.preventDefault();d3.event.stopPropagation();}})
  970. .on("mouseover",function(d) {if (!lasso) { d3.select(this).attr("fill-opacity",0.4);}})
  971. .on("mouseout",function(d) {if (!lasso) {
  972. var op = 1;
  973. if (d._def.button.toggle) {
  974. op = d[d._def.button.toggle]?1:0.2;
  975. }
  976. d3.select(this).attr("fill-opacity",op);
  977. }})
  978. .on("click",nodeButtonClicked)
  979. .on("touchstart",nodeButtonClicked)
  980. }
  981. var mainRect = node.append("rect")
  982. .attr("class", "node")
  983. .classed("node_unknown",function(d) { return d.type == "unknown"; })
  984. .attr("rx", 6)
  985. .attr("ry", 6)
  986. .attr("fill",function(d) { return d._def.color;})
  987. .on("mouseup",nodeMouseUp)
  988. .on("mousedown",nodeMouseDown)
  989. .on("touchstart",function(d) {
  990. var obj = d3.select(this);
  991. var touch0 = d3.event.touches.item(0);
  992. var pos = [touch0.pageX,touch0.pageY];
  993. startTouchCenter = [touch0.pageX,touch0.pageY];
  994. startTouchDistance = 0;
  995. touchStartTime = setTimeout(function() {
  996. showTouchMenu(obj,pos);
  997. },touchLongPressTimeout);
  998. nodeMouseDown.call(this,d)
  999. })
  1000. .on("touchend", function(d) {
  1001. clearTimeout(touchStartTime);
  1002. touchStartTime = null;
  1003. if (RED.touch.radialMenu.active()) {
  1004. d3.event.stopPropagation();
  1005. return;
  1006. }
  1007. nodeMouseUp.call(this,d);
  1008. })
  1009. .on("mouseover",function(d) {
  1010. if (mouse_mode === 0) {
  1011. var node = d3.select(this);
  1012. node.classed("node_hovered",true);
  1013. }
  1014. })
  1015. .on("mouseout",function(d) {
  1016. var node = d3.select(this);
  1017. node.classed("node_hovered",false);
  1018. });
  1019. //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");
  1020. //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");
  1021. if (d._def.icon) {
  1022. var icon_group = node.append("g")
  1023. .attr("class","node_icon_group")
  1024. .attr("x",0).attr("y",0);
  1025. var icon_shade = icon_group.append("rect")
  1026. .attr("x",0).attr("y",0)
  1027. .attr("class","node_icon_shade")
  1028. .attr("width","30")
  1029. .attr("stroke","none")
  1030. .attr("fill","#000")
  1031. .attr("fill-opacity","0.05")
  1032. .attr("height",function(d){return Math.min(50,d.h-4);});
  1033. var icon = icon_group.append("image")
  1034. .attr("xlink:href","icons/"+d._def.icon)
  1035. .attr("class","node_icon")
  1036. .attr("x",0)
  1037. .attr("width","30")
  1038. .attr("height","30");
  1039. var icon_shade_border = icon_group.append("path")
  1040. .attr("d",function(d) { return "M 30 1 l 0 "+(d.h-2)})
  1041. .attr("class","node_icon_shade_border")
  1042. .attr("stroke-opacity","0.1")
  1043. .attr("stroke","#000")
  1044. .attr("stroke-width","2");
  1045. if ("right" == d._def.align) {
  1046. icon_group.attr('class','node_icon_group node_icon_group_'+d._def.align);
  1047. icon_shade_border.attr("d",function(d) { return "M 0 1 l 0 "+(d.h-2)});
  1048. //icon.attr('class','node_icon node_icon_'+d._def.align);
  1049. //icon.attr('class','node_icon_shade node_icon_shade_'+d._def.align);
  1050. //icon.attr('class','node_icon_shade_border node_icon_shade_border_'+d._def.align);
  1051. }
  1052. //if (d._def.inputs > 0 && d._def.align == null) {
  1053. // icon_shade.attr("width",35);
  1054. // icon.attr("transform","translate(5,0)");
  1055. // icon_shade_border.attr("transform","translate(5,0)");
  1056. //}
  1057. //if (d._def.outputs > 0 && "right" == d._def.align) {
  1058. // icon_shade.attr("width",35); //icon.attr("x",5);
  1059. //}
  1060. var img = new Image();
  1061. img.src = "icons/"+d._def.icon;
  1062. img.onload = function() {
  1063. icon.attr("width",Math.min(img.width,30));
  1064. icon.attr("height",Math.min(img.height,30));
  1065. icon.attr("x",15-Math.min(img.width,30)/2);
  1066. //if ("right" == d._def.align) {
  1067. // icon.attr("x",function(d){return d.w-img.width-1-(d.outputs>0?5:0);});
  1068. // icon_shade.attr("x",function(d){return d.w-30});
  1069. // icon_shade_border.attr("d",function(d){return "M "+(d.w-30)+" 1 l 0 "+(d.h-2);});
  1070. //}
  1071. };
  1072. //icon.style("pointer-events","none");
  1073. icon_group.style("pointer-events","none");
  1074. }
  1075. var text = node.append('svg:text').attr('class','node_label').attr('x', 38).attr('dy', '.35em').attr('text-anchor','start');
  1076. if (d._def.align) {
  1077. text.attr('class','node_label node_label_'+d._def.align);
  1078. text.attr('text-anchor','end');
  1079. }
  1080. var status = node.append("svg:g").attr("class","node_status_group").style("display","none");
  1081. var statusRect = status.append("rect").attr("class","node_status")
  1082. .attr("x",6).attr("y",1).attr("width",9).attr("height",9)
  1083. .attr("rx",2).attr("ry",2).attr("stroke-width","3");
  1084. var statusLabel = status.append("svg:text")
  1085. .attr("class","node_status_label")
  1086. .attr('x',20).attr('y',9)
  1087. .style({
  1088. 'stroke-width': 0,
  1089. 'fill': '#888',
  1090. 'font-size':'9pt',
  1091. 'stroke':'#000',
  1092. 'text-anchor':'start'
  1093. });
  1094. //node.append("circle").attr({"class":"centerDot","cx":0,"cy":0,"r":5});
  1095. var numInputs = d._def.inputs;
  1096. var inputlist = [];
  1097. for (var n=0; n < numInputs; n++) {
  1098. var link = RED.nodes.links.filter(function(l){return (l.target == d && l.targetPort == n);});
  1099. var y = (d.h/2)-((numInputs-1)/2)*13;
  1100. y = (y+13*n)-5;
  1101. text.attr("x",38);
  1102. var rect = node.append("rect");
  1103. inputlist[n] = rect;
  1104. rect.attr("class","port port_input").attr("rx",3).attr("ry",3)
  1105. .attr("y",y).attr("x",-5).attr("width",10).attr("height",10).attr("index",n);
  1106. if (link && link.length > 0) {
  1107. // this input already has a link connected, so disallow new links
  1108. rect.on("mousedown",null)
  1109. .on("touchstart", null)
  1110. .on("mouseup", null)
  1111. .on("touchend", null)
  1112. .on("mouseover", null)
  1113. .on("mouseout", null)
  1114. .classed("port_hovered",false);
  1115. } else {
  1116. // allow new link on inputs without any link connected
  1117. rect.on("mousedown", (function(nn){return function(d){portMouseDown(d,1,nn);}})(n))
  1118. .on("touchstart", (function(nn){return function(d){portMouseDown(d,1,nn);}})(n))
  1119. .on("mouseup", (function(nn){return function(d){portMouseUp(d,1,nn);}})(n))
  1120. .on("touchend", (function(nn){return function(d){portMouseUp(d,1,nn);}})(n))
  1121. .on("mouseover",function(d) { var port = d3.select(this); port.classed("port_hovered",(mouse_mode!=RED.state.JOINING || mousedown_port_type != 1 ));})
  1122. .on("mouseout",function(d) { var port = d3.select(this); port.classed("port_hovered",false);})
  1123. }
  1124. }
  1125. d.inputlist = inputlist;
  1126. // never show these little status icons
  1127. // people try clicking on them, thinking they're buttons
  1128. // or some sort of user interface widget
  1129. //node.append("path").attr("class","node_error").attr("d","M 3,-3 l 10,0 l -5,-8 z");
  1130. //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);
  1131. //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);
  1132. node.append("image").attr("class","node_reqerror hidden").attr("xlink:href","icons/error.png").attr("x",0).attr("y",-12).attr("width",20).attr("height",20);
  1133. });
  1134. node.each(function(d,i) {
  1135. /**********************************************************************/
  1136. //Add requirements
  1137. d.requirementError = false;
  1138. d.conflicts = new Array();
  1139. d.requirements = new Array();
  1140. requirements.forEach(function(r) {
  1141. if (r.type == d.type) d.requirements.push(r);
  1142. });
  1143. //check for conflicts with other nodes:
  1144. d.requirements.forEach(function(r) {
  1145. RED.nodes.eachNode(function (n2) {
  1146. if (n2 != d && n2.requirements != null ) {
  1147. n2.requirements.forEach(function(r2) {
  1148. if (r["resource"] == r2["resource"]) {
  1149. if (r["shareable"] == false ) {
  1150. var msg = "Conflict: shareable '"+r["resource"]+"' "+d.name+" and "+n2.name;
  1151. console.log(msg);
  1152. msg = n2.name + " uses " + r["resource"] + ", too";
  1153. d.conflicts.push(msg);
  1154. d.requirementError = true;
  1155. }
  1156. //else
  1157. if (r["setting"] != r2["setting"]) {
  1158. var msg = "Conflict: "+ d.name + " setting['"+r["setting"]+"'] and "+n2.name+" setting['"+r2["setting"]+"']";
  1159. console.log(msg);
  1160. msg = n2.name + " has different settings: " + r["setting"] + " ./. " + r2["setting"];
  1161. d.conflicts.push(msg);
  1162. d.requirementError = true;
  1163. }
  1164. }
  1165. });
  1166. }
  1167. });
  1168. });
  1169. /**********************************************************************/
  1170. if (d.dirty || d.requirementError != undefined) {
  1171. //if (d.x < -50) deleteSelection(); // Delete nodes if dragged back to palette
  1172. if (d.resize) {
  1173. //var l = d._def.label;
  1174. //l = (typeof l === "function" ? l.call(d) : l)||"";
  1175. var l = d.name ? d.name : d.id;
  1176. d.w = Math.max(node_width,calculateTextWidth(l)+(d._def.inputs>0?7:0) );
  1177. d.h = Math.max(node_height,(Math.max(d.outputs,d._def.inputs)||0) * 15);
  1178. }
  1179. var thisNode = d3.select(this);
  1180. //thisNode.selectAll(".centerDot").attr({"cx":function(d) { return d.w/2;},"cy":function(d){return d.h/2}});
  1181. thisNode.attr("transform", function(d) { return "translate(" + (d.x-d.w/2) + "," + (d.y-d.h/2) + ")"; });
  1182. thisNode.selectAll(".node")
  1183. .attr("width",function(d){return d.w})
  1184. .attr("height",function(d){return d.h})
  1185. .classed("node_selected",function(d) { return d.selected; })
  1186. .classed("node_highlighted",function(d) { return d.highlighted; })
  1187. ;
  1188. //thisNode.selectAll(".node-gradient-top").attr("width",function(d){return d.w});
  1189. //thisNode.selectAll(".node-gradient-bottom").attr("width",function(d){return d.w}).attr("y",function(d){return d.h-30});
  1190. thisNode.selectAll(".node_icon_group_right").attr('transform', function(d){return "translate("+(d.w-30)+",0)"});
  1191. thisNode.selectAll(".node_label_right").attr('x', function(d){return d.w-38});
  1192. //thisNode.selectAll(".node_icon_right").attr("x",function(d){return d.w-d3.select(this).attr("width")-1-(d.outputs>0?5:0);});
  1193. //thisNode.selectAll(".node_icon_shade_right").attr("x",function(d){return d.w-30;});
  1194. //thisNode.selectAll(".node_icon_shade_border_right").attr("d",function(d){return "M "+(d.w-30)+" 1 l 0 "+(d.h-2)});
  1195. var numOutputs = d.outputs;
  1196. var y = (d.h/2)-((numOutputs-1)/2)*13;
  1197. d.ports = d.ports || d3.range(numOutputs);
  1198. d._ports = thisNode.selectAll(".port_output").data(d.ports);
  1199. d._ports.enter().append("rect").attr("class","port port_output").attr("rx",3).attr("ry",3).attr("width",10).attr("height",10)
  1200. .on("mousedown",(function(){var node = d; return function(d,i){portMouseDown(node,0,i);}})() )
  1201. .on("touchstart",(function(){var node = d; return function(d,i){portMouseDown(node,0,i);}})() )
  1202. .on("mouseup",(function(){var node = d; return function(d,i){portMouseUp(node,0,i);}})() )
  1203. .on("touchend",(function(){var node = d; return function(d,i){portMouseUp(node,0,i);}})() )
  1204. .on("mouseover",function(d,i) { var port = d3.select(this); port.classed("port_hovered",(mouse_mode!=RED.state.JOINING || mousedown_port_type !== 0 ));})
  1205. .on("mouseout",function(d,i) { var port = d3.select(this); port.classed("port_hovered",false);});
  1206. d._ports.exit().remove();
  1207. if (d._ports) {
  1208. numOutputs = d.outputs || 1;
  1209. y = (d.h/2)-((numOutputs-1)/2)*13;
  1210. var x = d.w - 5;
  1211. d._ports.each(function(d,i) {
  1212. var port = d3.select(this);
  1213. port.attr("y",(y+13*i)-5).attr("x",x);
  1214. });
  1215. }
  1216. thisNode.selectAll('text.node_label').text(function(d,i){
  1217. /* if (d._def.label) {
  1218. if (typeof d._def.label == "function") {
  1219. return d._def.label.call(d);
  1220. } else {
  1221. return d._def.label;
  1222. }
  1223. }
  1224. return "n.a.";
  1225. */
  1226. return d.name ? d.name : d.id;
  1227. })
  1228. .attr('y', function(d){return (d.h/2)-1;})
  1229. .attr('class',function(d){
  1230. return 'node_label'+
  1231. (d._def.align?' node_label_'+d._def.align:'')+
  1232. (d._def.label?' '+(typeof d._def.labelStyle == "function" ? d._def.labelStyle.call(d):d._def.labelStyle):'') ;
  1233. });
  1234. thisNode.selectAll(".node_tools").attr("x",function(d){return d.w-35;}).attr("y",function(d){return d.h-20;});
  1235. thisNode.selectAll(".node_changed")
  1236. .attr("x",function(d){return d.w-10})
  1237. .classed("hidden",function(d) { return !d.changed; });
  1238. thisNode.selectAll(".node_error")
  1239. .attr("x",function(d){return d.w-10-(d.changed?13:0)})
  1240. .classed("hidden",function(d) { return d.valid; });
  1241. thisNode.selectAll(".port_input").each(function(d,i) {
  1242. var port = d3.select(this);
  1243. var numInputs = d._def.inputs;
  1244. var y = (d.h/2)-((numInputs-1)/2)*13;
  1245. y = (y+13*i)-5;
  1246. port.attr("y",y)
  1247. });
  1248. thisNode.selectAll(".node_reqerror")
  1249. .attr("x",function(d){return d.w-25-(d.changed?13:0)})
  1250. .classed("hidden",function(d){ return !d.requirementError; })
  1251. .on("click", function(){RED.notify(
  1252. 'Conflicts:<ul><li>'+d.conflicts.join('</li><li>')+'</li></ul>'
  1253. )});
  1254. thisNode.selectAll(".node_icon").attr("y",function(d){return (d.h-d3.select(this).attr("height"))/2;});
  1255. thisNode.selectAll(".node_icon_shade").attr("height",function(d){return d.h;});
  1256. thisNode.selectAll(".node_icon_shade_border").attr("d",function(d){ return "M "+(("right" == d._def.align) ?0:30)+" 1 l 0 "+(d.h-2)});
  1257. thisNode.selectAll('.node_right_button').attr("transform",function(d){
  1258. var x = d.w-6;
  1259. if (d._def.button.toggle && !d[d._def.button.toggle]) {
  1260. x = x - 8;
  1261. }
  1262. return "translate("+x+",2)";
  1263. });
  1264. thisNode.selectAll('.node_right_button rect').attr("fill-opacity",function(d){
  1265. if (d._def.button.toggle) {
  1266. return d[d._def.button.toggle]?1:0.2;
  1267. }
  1268. return 1;
  1269. });
  1270. //thisNode.selectAll('.node_right_button').attr("transform",function(d){return "translate("+(d.w - d._def.button.width.call(d))+","+0+")";}).attr("fill",function(d) {
  1271. // 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)
  1272. //});
  1273. thisNode.selectAll('.node_badge_group').attr("transform",function(d){return "translate("+(d.w-40)+","+(d.h+3)+")";});
  1274. thisNode.selectAll('text.node_badge_label').text(function(d,i) {
  1275. /* if (d._def.badge) {
  1276. if (typeof d._def.badge == "function") {
  1277. return d._def.badge.call(d);
  1278. } else {
  1279. return d._def.badge;
  1280. }
  1281. }
  1282. return ""; */
  1283. return d.name ? d.name : d.id;
  1284. });
  1285. if (!showStatus || !d.status) {
  1286. thisNode.selectAll('.node_status_group').style("display","none");
  1287. } else {
  1288. thisNode.selectAll('.node_status_group').style("display","inline").attr("transform","translate(3,"+(d.h+3)+")");
  1289. var fill = status_colours[d.status.fill]; // Only allow our colours for now
  1290. if (d.status.shape == null && fill == null) {
  1291. thisNode.selectAll('.node_status').style("display","none");
  1292. } else {
  1293. var style;
  1294. if (d.status.shape == null || d.status.shape == "dot") {
  1295. style = {
  1296. display: "inline",
  1297. fill: fill,
  1298. stroke: fill
  1299. };
  1300. } else if (d.status.shape == "ring" ){
  1301. style = {
  1302. display: "inline",
  1303. fill: '#fff',
  1304. stroke: fill
  1305. }
  1306. }
  1307. thisNode.selectAll('.node_status').style(style);
  1308. }
  1309. if (d.status.text) {
  1310. thisNode.selectAll('.node_status_label').text(d.status.text);
  1311. } else {
  1312. thisNode.selectAll('.node_status_label').text("");
  1313. }
  1314. }
  1315. d.dirty = false;
  1316. }
  1317. });
  1318. }
  1319. 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;});
  1320. var linkEnter = link.enter().insert("g",".node").attr("class","link");
  1321. linkEnter.each(function(d,i) {
  1322. var l = d3.select(this);
  1323. l.append("svg:path").attr("class","link_background link_path")
  1324. .on("mousedown",function(d) {
  1325. mousedown_link = d;
  1326. clearSelection();
  1327. selected_link = mousedown_link;
  1328. updateSelection();
  1329. redraw();
  1330. d3.event.stopPropagation();
  1331. })
  1332. .on("touchstart",function(d) {
  1333. mousedown_link = d;
  1334. clearSelection();
  1335. selected_link = mousedown_link;
  1336. updateSelection();
  1337. redraw();
  1338. d3.event.stopPropagation();
  1339. });
  1340. l.append("svg:path").attr("class","link_outline link_path");
  1341. l.append("svg:path").attr("class","link_line link_path");
  1342. });
  1343. link.exit().remove();
  1344. var links = vis.selectAll(".link_path");
  1345. links.attr("d",function(d){
  1346. var numOutputs = d.source.outputs || 1;
  1347. var sourcePort = d.sourcePort || 0;
  1348. var ysource = -((numOutputs-1)/2)*13 +13*sourcePort;
  1349. var numInputs = d.target._def.inputs || 1;
  1350. var targetPort = d.targetPort || 0;
  1351. var ytarget = -((numInputs-1)/2)*13 +13*targetPort;
  1352. var dy = (d.target.y+ytarget)-(d.source.y+ysource);
  1353. var dx = (d.target.x-d.target.w/2)-(d.source.x+d.source.w/2);
  1354. var delta = Math.sqrt(dy*dy+dx*dx);
  1355. var scale = lineCurveScale;
  1356. var scaleY = 0;
  1357. if (delta < node_width) {
  1358. scale = 0.75-0.75*((node_width-delta)/node_width);
  1359. }
  1360. if (dx < 0) {
  1361. scale += 2*(Math.min(5*node_width,Math.abs(dx))/(5*node_width));
  1362. if (Math.abs(dy) < 3*node_height) {
  1363. 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)) ;
  1364. }
  1365. }
  1366. d.x1 = d.source.x+d.source.w/2;
  1367. d.y1 = d.source.y+ysource;
  1368. d.x2 = d.target.x-d.target.w/2;
  1369. d.y2 = d.target.y+ytarget;
  1370. return "M "+(d.x1)+" "+(d.y1)+
  1371. " C "+(d.x1+scale*node_width)+" "+(d.y1+scaleY*node_height)+" "+
  1372. (d.x2-scale*node_width)+" "+(d.y2-scaleY*node_height)+" "+
  1373. (d.x2)+" "+d.y2;
  1374. });
  1375. link.classed("link_selected", function(d) { return d === selected_link || d.selected; });
  1376. link.classed("link_unknown",function(d) { return d.target.type == "unknown" || d.source.type == "unknown"});
  1377. if (d3.event) {
  1378. d3.event.preventDefault();
  1379. }
  1380. }
  1381. function conflict(a) { alert(a); }
  1382. function doSort (arr) {
  1383. arr.sort(function (a, b) {
  1384. var nameA = a.name ? a.name : a.id;
  1385. var nameB = b.name ? b.name : b.id;
  1386. return nameA.localeCompare(nameB, 'en', {numeric: 'true'});
  1387. });
  1388. }
  1389. function setNewCoords (lastX, lastY, arr) {
  1390. var x = lastX;
  1391. var y = lastY;
  1392. for (var i = 0; i < arr.length; i++) {
  1393. var node = arr[i];
  1394. var name = node.name ? node.name : node.id;
  1395. var def = node._def;
  1396. var dH = Math.max(RED.view.defaults.height, (Math.max(def.outputs, def.inputs) || 0) * 15);
  1397. x = lastX + Math.max(RED.view.defaults.width, RED.view.calculateTextWidth(name) + (def.inputs > 0 ? 7 : 0));
  1398. node.x = x;
  1399. node.y = y + dH/2;
  1400. y = y + dH + 15;
  1401. node.dirty = true;
  1402. }
  1403. return { x: x, y: y };
  1404. }
  1405. function arrangeAll() {
  1406. var ioNoIn = [];
  1407. var ioInOut = [];
  1408. var ioMultiple = [];
  1409. var ioNoOut = [];
  1410. var ioCtrl = [];
  1411. RED.nodes.eachNode(function (node) {
  1412. if (node._def.inputs == 0 && node._def.outputs == 0) {
  1413. ioCtrl.push(node);
  1414. } else if (node._def.inputs == 0) {
  1415. ioNoIn.push(node);
  1416. } else if (node._def.outputs == 0) {
  1417. ioNoOut.push(node);
  1418. } else if (node._def.inputs == 1 && node._def.outputs == 1) {
  1419. ioInOut.push(node);
  1420. } else if (node._def.inputs > 1) {
  1421. ioMultiple.push(node);
  1422. }
  1423. });
  1424. var cols = new Array(ioNoIn, ioInOut, ioMultiple, ioNoOut, ioCtrl);
  1425. var lowestY = 0;
  1426. for (var i = 0; i < cols.length; i++) {
  1427. var dX = ((i < cols.length - 1) ? i : 0) * (RED.view.defaults.width * 2) + (RED.view.defaults.width / 2) + 15;
  1428. var dY = ((i < cols.length - 1) ? (RED.view.defaults.height / 4) : lowestY) + 15;
  1429. var startX = 0;
  1430. var startY = 0;
  1431. doSort(cols[i]);
  1432. var last = setNewCoords(startX + dX, startY + dY, cols[i]);
  1433. lowestY = Math.max(lowestY, last.y);
  1434. startX = ((i < cols.length - 1) ? last.x : 0) + (RED.view.defaults.width) * 4;
  1435. startY = lowestY + (RED.view.defaults.height * 1.5);
  1436. }
  1437. RED.storage.update();
  1438. redraw();
  1439. }
  1440. RED.keyboard.add(/* z */ 90,{ctrl:true},function(){RED.history.pop();});
  1441. RED.keyboard.add(/* o */ 79,{ctrl:true},function(){arrangeAll();d3.event.preventDefault();});
  1442. RED.keyboard.add(/* a */ 65,{ctrl:true},function(){selectAll();d3.event.preventDefault();});
  1443. RED.keyboard.add(/* = */ 187,{ctrl:true},function(){zoomIn();d3.event.preventDefault();});
  1444. RED.keyboard.add(/* - */ 189,{ctrl:true},function(){zoomOut();d3.event.preventDefault();});
  1445. RED.keyboard.add(/* 0 */ 48,{ctrl:true},function(){zoomZero();d3.event.preventDefault();});
  1446. RED.keyboard.add(/* v */ 86,{ctrl:true},function(){importNodes(clipboard);d3.event.preventDefault();});
  1447. RED.keyboard.add(/* e */ 69,{ctrl:true},function(){showExportNodesDialog();d3.event.preventDefault();});
  1448. RED.keyboard.add(/* i */ 73,{ctrl:true},function(){showImportNodesDialog();d3.event.preventDefault();});
  1449. // TODO: 'dirty' should be a property of RED.nodes - with an event callback for ui hooks
  1450. function setDirty(d) {
  1451. dirty = d;
  1452. if (dirty) {
  1453. $("#btn-deploy").removeClass("disabled").addClass("btn-danger");
  1454. RED.storage.update();
  1455. } else {
  1456. $("#btn-deploy").addClass("disabled").removeClass("btn-danger");
  1457. }
  1458. }
  1459. /**
  1460. * Imports a new collection of nodes from a JSON String.
  1461. * - all get new IDs assigned
  1462. * - all 'selected'
  1463. * - attached to mouse for placing - 'IMPORT_DRAGGING'
  1464. */
  1465. function importNodes(newNodesStr,touchImport) {
  1466. var createNewIds = true;
  1467. var useStorage = false;
  1468. if ($("#node-input-arduino").prop('checked') === true) {
  1469. var nodesJSON = RED.nodes.cppToJSON(newNodesStr);
  1470. if (nodesJSON.count <= 0) {
  1471. var note = "No nodes imported!";
  1472. RED.notify("<strong>Note</strong>: " + note, "warning");
  1473. }
  1474. newNodesStr = nodesJSON.data;
  1475. createNewIds = false;
  1476. if (useStorage) {
  1477. RED.storage.clear();
  1478. localStorage.setItem("audio_library_guitool", newNodesStr);
  1479. RED.storage.load();
  1480. redraw();
  1481. return;
  1482. }
  1483. }
  1484. try {
  1485. var result = RED.nodes.import(newNodesStr,createNewIds);
  1486. if (result) {
  1487. var new_nodes = result[0];
  1488. var new_links = result[1];
  1489. var new_ms = new_nodes.map(function(n) { n.z = activeWorkspace; return {n:n};});
  1490. var new_node_ids = new_nodes.map(function(n){ return n.id; });
  1491. // TODO: pick a more sensible root node
  1492. var root_node = new_ms[0].n;
  1493. var dx = root_node.x;
  1494. var dy = root_node.y;
  1495. if (mouse_position == null) {
  1496. mouse_position = [0,0];
  1497. }
  1498. var minX = 0;
  1499. var minY = 0;
  1500. var i;
  1501. var node;
  1502. for (i=0;i<new_ms.length;i++) {
  1503. node = new_ms[i];
  1504. node.n.selected = true;
  1505. node.n.changed = true;
  1506. node.n.x -= dx - mouse_position[0];
  1507. node.n.y -= dy - mouse_position[1];
  1508. node.dx = node.n.x - mouse_position[0];
  1509. node.dy = node.n.y - mouse_position[1];
  1510. minX = Math.min(node.n.x-node_width/2-5,minX);
  1511. minY = Math.min(node.n.y-node_height/2-5,minY);
  1512. }
  1513. for (i=0;i<new_ms.length;i++) {
  1514. node = new_ms[i];
  1515. node.n.x -= minX;
  1516. node.n.y -= minY;
  1517. node.dx -= minX;
  1518. node.dy -= minY;
  1519. }
  1520. if (!touchImport) {
  1521. mouse_mode = RED.state.IMPORT_DRAGGING;
  1522. }
  1523. RED.keyboard.add(/* ESCAPE */ 27,function(){
  1524. RED.keyboard.remove(/* ESCAPE */ 27);
  1525. clearSelection();
  1526. RED.history.pop();
  1527. mouse_mode = 0;
  1528. });
  1529. RED.history.push({t:'add',nodes:new_node_ids,links:new_links,dirty:RED.view.dirty()});
  1530. clearSelection();
  1531. moving_set = new_ms;
  1532. redraw();
  1533. }
  1534. } catch(error) {
  1535. console.log(error);
  1536. RED.notify("<strong>Error</strong>: "+error,"error");
  1537. }
  1538. }
  1539. $('#btn-import').click(function() {showImportNodesDialog();});
  1540. $('#btn-export-clipboard').click(function() {showExportNodesDialog();});
  1541. $('#btn-export-library').click(function() {showExportNodesLibraryDialog();});
  1542. function showExportNodesDialog() {
  1543. mouse_mode = RED.state.EXPORT;
  1544. var nns = RED.nodes.createExportableNodeSet(moving_set);
  1545. //$("#dialog-form").html(getForm("dialog-form", "export-clipboard-dialog"));
  1546. var frm = getForm("dialog-form", "export-clipboard-dialog", function (d, f) {
  1547. $("#node-input-export").val(JSON.stringify(nns)).focus(function() {
  1548. var textarea = $(this);
  1549. textarea.select();
  1550. textarea.mouseup(function() {
  1551. textarea.unbind("mouseup");
  1552. return false;
  1553. });
  1554. }).focus();
  1555. $( "#dialog" ).dialog("option","title","Export nodes to clipboard").dialog( "open" );
  1556. });
  1557. }
  1558. function showExportNodesLibraryDialog() {
  1559. mouse_mode = RED.state.EXPORT;
  1560. var nns = RED.nodes.createExportableNodeSet(moving_set);
  1561. //$("#dialog-form").html(this.getForm('export-library-dialog'));
  1562. getForm("dialog-form", "export-library-dialog", function(d, f) {
  1563. $("#node-input-filename").attr('nodes',JSON.stringify(nns));
  1564. $( "#dialog" ).dialog("option","title","Export nodes to library").dialog( "open" );
  1565. });
  1566. }
  1567. function showImportNodesDialog() {
  1568. mouse_mode = RED.state.IMPORT;
  1569. //$("#dialog-form").html(this.getForm('import-dialog'));
  1570. getForm("dialog-form", "import-dialog", function(d, f) {
  1571. $("#node-input-import").val("");
  1572. $( "#dialog" ).dialog("option","title","Import nodes").dialog( "open" );
  1573. });
  1574. }
  1575. function showRenameWorkspaceDialog(id) {
  1576. var ws = RED.nodes.workspace(id);
  1577. $( "#node-dialog-rename-workspace" ).dialog("option","workspace",ws);
  1578. if (workspace_tabs.count() == 1) {
  1579. $( "#node-dialog-rename-workspace").next().find(".leftButton")
  1580. .prop('disabled',true)
  1581. .addClass("ui-state-disabled");
  1582. } else {
  1583. $( "#node-dialog-rename-workspace").next().find(".leftButton")
  1584. .prop('disabled',false)
  1585. .removeClass("ui-state-disabled");
  1586. }
  1587. $( "#node-input-workspace-name" ).val(ws.label);
  1588. $( "#node-dialog-rename-workspace" ).dialog("open");
  1589. }
  1590. function getForm(formId, key, callback) {
  1591. // server test switched off - test purposes only
  1592. var patt = new RegExp(/^[http|https]/);
  1593. var server = false && patt.test(location.protocol);
  1594. var form = $("<h2>No form found.</h2>");
  1595. if (!server) {
  1596. data = $("script[data-template-name|='" + key + "']").html();
  1597. form = $("#" + formId);
  1598. $(form).empty();
  1599. $(form).append(data);
  1600. if(typeof callback == 'function') {
  1601. callback.call(this, form);
  1602. }
  1603. } else {
  1604. var frmPlugin = "resources/form/" + key + ".html";
  1605. $.get(frmPlugin, function(data) {
  1606. form = $("#" + formId);
  1607. $(form).empty();
  1608. $(form).append(data);
  1609. if(typeof callback == 'function') {
  1610. callback.call(this, form);
  1611. }
  1612. });
  1613. }
  1614. return form;
  1615. }
  1616. $("#node-dialog-rename-workspace form" ).submit(function(e) { e.preventDefault();});
  1617. $( "#node-dialog-rename-workspace" ).dialog({
  1618. modal: true,
  1619. autoOpen: false,
  1620. width: 500,
  1621. title: "Rename sheet",
  1622. buttons: [
  1623. {
  1624. class: 'leftButton',
  1625. text: "Delete",
  1626. click: function() {
  1627. var workspace = $(this).dialog('option','workspace');
  1628. $( this ).dialog( "close" );
  1629. deleteWorkspace(workspace.id);
  1630. }
  1631. },
  1632. {
  1633. text: "Ok",
  1634. click: function() {
  1635. var workspace = $(this).dialog('option','workspace');
  1636. var label = $( "#node-input-workspace-name" ).val();
  1637. if (workspace.label != label) {
  1638. workspace.label = label;
  1639. var link = $("#workspace-tabs a[href='#"+workspace.id+"']");
  1640. link.attr("title",label);
  1641. link.text(label);
  1642. RED.view.dirty(true);
  1643. }
  1644. $( this ).dialog( "close" );
  1645. }
  1646. },
  1647. {
  1648. text: "Cancel",
  1649. click: function() {
  1650. $( this ).dialog( "close" );
  1651. }
  1652. }
  1653. ],
  1654. open: function(e) {
  1655. RED.keyboard.disable();
  1656. },
  1657. close: function(e) {
  1658. RED.keyboard.enable();
  1659. }
  1660. });
  1661. $( "#node-dialog-delete-workspace" ).dialog({
  1662. modal: true,
  1663. autoOpen: false,
  1664. width: 500,
  1665. title: "Confirm delete",
  1666. buttons: [
  1667. {
  1668. text: "Ok",
  1669. click: function() {
  1670. var workspace = $(this).dialog('option','workspace');
  1671. RED.view.removeWorkspace(workspace);
  1672. var historyEvent = RED.nodes.removeWorkspace(workspace.id);
  1673. historyEvent.t = 'delete';
  1674. historyEvent.dirty = dirty;
  1675. historyEvent.workspaces = [workspace];
  1676. RED.history.push(historyEvent);
  1677. RED.view.dirty(true);
  1678. $( this ).dialog( "close" );
  1679. }
  1680. },
  1681. {
  1682. text: "Cancel",
  1683. click: function() {
  1684. $( this ).dialog( "close" );
  1685. }
  1686. }
  1687. ],
  1688. open: function(e) {
  1689. RED.keyboard.disable();
  1690. },
  1691. close: function(e) {
  1692. RED.keyboard.enable();
  1693. }
  1694. });
  1695. return {
  1696. state:function(state) {
  1697. if (state == null) {
  1698. return mouse_mode
  1699. } else {
  1700. mouse_mode = state;
  1701. }
  1702. },
  1703. addWorkspace: function(ws) {
  1704. workspace_tabs.addTab(ws);
  1705. workspace_tabs.resize();
  1706. },
  1707. removeWorkspace: function(ws) {
  1708. workspace_tabs.removeTab(ws.id);
  1709. },
  1710. getWorkspace: function() {
  1711. return activeWorkspace;
  1712. },
  1713. showWorkspace: function(id) {
  1714. workspace_tabs.activateTab(id);
  1715. },
  1716. redraw:redraw,
  1717. dirty: function(d) {
  1718. if (d == null) {
  1719. return dirty;
  1720. } else {
  1721. setDirty(d);
  1722. }
  1723. },
  1724. importNodes: importNodes,
  1725. resize: function() {
  1726. workspace_tabs.resize();
  1727. },
  1728. status: function(s) {
  1729. showStatus = s;
  1730. RED.nodes.eachNode(function(n) { n.dirty = true;});
  1731. //TODO: subscribe/unsubscribe here
  1732. redraw();
  1733. },
  1734. getForm: getForm,
  1735. calculateTextWidth: calculateTextWidth,
  1736. defaults: {
  1737. width: node_width,
  1738. height: node_height
  1739. }
  1740. };
  1741. })();