geometry_utils.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. /* This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
  2. * Copyright 2011 by the AToMPM team and licensed under the LGPL
  3. * See COPYING.lesser and README.md in the root of this project for full details
  4. */
  5. GeometryUtils = function(){
  6. var geometryControlsOverlay = undefined;
  7. var transformationPreviewOverlay = undefined;
  8. /**
  9. * Determines whether or not geometric transformations are allowed. This only
  10. * applies if:
  11. * 1. Geometry controls are hidden
  12. * 2. If an edge is selected, its start and end icons are also selected
  13. */
  14. this.areTransformationsAllowed = function(){
  15. var seen = {};
  16. return (geometryControlsOverlay == undefined ||
  17. geometryControlsOverlay.css("display") == 'none') &&
  18. __selection['items'].every(
  19. function(it)
  20. {
  21. if( it in __edges )
  22. {
  23. var start = __edges[it]['start'],
  24. end = __edges[it]['end'];
  25. if( ! (start in seen) &&
  26. ! utils.contains(__selection['items'],start) )
  27. return false;
  28. if( ! (end in seen) &&
  29. ! utils.contains(__selection['items'],end) )
  30. return false;
  31. seen[start] = seen[end] = 1;
  32. }
  33. return true;
  34. });
  35. };
  36. /**
  37. * Hides the geometry controls overlay
  38. */
  39. this.hideGeometryControlsOverlay = function() {
  40. if( geometryControlsOverlay != undefined )
  41. geometryControlsOverlay.css("display", "none");
  42. __setCanvasScrolling(true);
  43. };
  44. /**
  45. * Hides the transformation preview overlay
  46. */
  47. this.hideTransformationPreviewOverlay = function() {
  48. if( transformationPreviewOverlay != undefined )
  49. {
  50. transformationPreviewOverlay.remove();
  51. transformationPreviewOverlay = undefined;
  52. }
  53. };
  54. /*
  55. NOTE:: _x and _y are used to remember the last 'confirmed' position which we
  56. to compute the relative parameters of calls to translate(..)
  57. NOTE:: the call to toBack() causes whatever is beneath the transformation
  58. preview overlay to become above it, thus becoming detectable by
  59. document.elementFromPoint()... this is used to distinguish between
  60. dropping selections on the canvas and on icons, with the latter
  61. possibly causing insertion */
  62. /**
  63. * Initializes a Raphael rectangle matching the selection bounding box.
  64. */
  65. this.initSelectionTransformationPreviewOverlay = function(x,y)
  66. {
  67. if( transformationPreviewOverlay != undefined )
  68. return;
  69. var bbox = __selection['bbox'];
  70. transformationPreviewOverlay = __bbox2rect(bbox,'transformation_preview');
  71. transformationPreviewOverlay.node.setAttribute('_x0',x);
  72. transformationPreviewOverlay.node.setAttribute('_y0',y);
  73. transformationPreviewOverlay.node.setAttribute('_x',x);
  74. transformationPreviewOverlay.node.setAttribute('_y',y);
  75. transformationPreviewOverlay.node.onmouseup =
  76. function(event)
  77. {
  78. if( event.button == 0 )
  79. transformationPreviewOverlay.toBack();
  80. var beneathTPO = document.elementFromPoint(event.clientX,event.clientY),
  81. _event;
  82. if ( transformationPreviewOverlay.node != beneathTPO &&
  83. beneathTPO != __selection['rect'].node )
  84. {
  85. _event = document.createEvent('MouseEvents');
  86. _event.initMouseEvent(
  87. event.type, event.canBubble, event.cancelable, event.view,
  88. event.detail, event.screenX, event.screenY, event.clientX,
  89. event.clientY, event.ctrlKey, event.altKey, event.shiftKey,
  90. event.metaKey, event.button, event.relatedTarget );
  91. beneathTPO.parentNode.dispatchEvent(_event);
  92. } else {
  93. BehaviorManager.handleUserEvent(__EVENT_LEFT_RELEASE_CANVAS,event);
  94. }
  95. };
  96. };
  97. /**
  98. * Applies the effects of the specified transformation to the preview overlay
  99. */
  100. this.previewSelectionTransformation = function(op,dir) {
  101. if (transformationPreviewOverlay == undefined)
  102. return;
  103. var bbox = __selection['bbox'],
  104. scale = (dir > 0 ? 1.05 : 0.95),
  105. angle = (dir > 0 ? 3 : -3);
  106. if( op == 'resize' )
  107. transformationPreviewOverlay.scale(scale,scale,bbox.x,bbox.y);
  108. else if( op == 'resizeH' )
  109. transformationPreviewOverlay.scale(1,scale,bbox.x,bbox.y);
  110. else if( op == 'resizeW' )
  111. transformationPreviewOverlay.scale(scale,1,bbox.x,bbox.y);
  112. else if( op == 'rotate' )
  113. transformationPreviewOverlay.rotate(angle,bbox.x,bbox.y);
  114. };
  115. /**
  116. * Moves the transformation preview overlay to the specified coordinates
  117. */
  118. this.previewSelectionTranslation = function(x,y) {
  119. if (transformationPreviewOverlay == undefined)
  120. return;
  121. var _x = parseInt(transformationPreviewOverlay.node.getAttribute('_x')),
  122. _y = parseInt(transformationPreviewOverlay.node.getAttribute('_y'));
  123. transformationPreviewOverlay.translate(x-_x,y-_y);
  124. transformationPreviewOverlay.node.setAttribute('_x',x);
  125. transformationPreviewOverlay.node.setAttribute('_y',y);
  126. };
  127. /*
  128. 0. exit on empty icon list
  129. 1. foreach non-link icon,
  130. a. loop back to step 1 if it has no container
  131. b. determine if it's bbox is fully inside, fully outside or intersects
  132. with its container's
  133. i. when fully inside, loop to step 1
  134. ii. when fully outside AND was actually contained (as opposed to
  135. to-be-inserted) AND dragouts are enabled, produce deletion
  136. request for containment link
  137. iii. otherwise, store needed changes to container position and size
  138. to fit icon... we do this (as opposed to producing a request)
  139. to lump together all changes to a given container (each which
  140. may originiate from different icons)
  141. 2. exit on empty request and container changes lists
  142. 3. convert container changes to CS update requests and append to existing
  143. deletion requests, if any
  144. 4. recurse with 'icons' set to any modified containers and 'context' set
  145. to their pending changes (computed in step 1biii) and append returned
  146. requests... the purpose of this step is for container resizing to have
  147. a cascading effect (i.e., a resized container triggers its parent's
  148. resizing if need be)
  149. 5. send batchEdit or return requests
  150. NOTE:: the 'context' parameter contains a list of pending changes computed by
  151. GeometryUtils.transformSelection() but not yet persisted onto the canvas, as well
  152. as a map of pending insertions, if any... this seemingly odd passing
  153. around of pending information is necessary to enable atomicity of icon
  154. transformations, insertions and container resizings */
  155. /**
  156. * Resizes the containers of icons (specified as uri array) that have moved within
  157. * them as required and uninsert dragged-out icons.
  158. */
  159. this.resizeContainers = function(icons,context,dryRun,disabledDragouts,reqs) {
  160. if( icons.length == 0 )
  161. return (dryRun ? [] : undefined);
  162. if( reqs == undefined )
  163. reqs = [];
  164. var requests = [],
  165. containers2changes = {},
  166. resizeContainer =
  167. function(c,clink,it)
  168. {
  169. var cbbox = __getBBox(
  170. c,utils.mergeDicts([context,containers2changes]) ),
  171. itbbox = __getBBox(it,context);
  172. if( __isBBoxInside(itbbox, cbbox) )
  173. return;
  174. else if( __isBBoxDisjoint(itbbox, cbbox) &&
  175. clink &&
  176. ! disabledDragouts )
  177. requests.push(
  178. {'method':'DELETE',
  179. 'uri':HttpUtils.url(clink,__NO_USERNAME+__NO_WID)});
  180. else
  181. {
  182. containers2changes[c] =
  183. containers2changes[c] ||
  184. utils.mergeDicts(
  185. [{'position':
  186. [parseFloat(__getIcon(c).getAttr('__x')),
  187. parseFloat(__getIcon(c).getAttr('__y'))],
  188. 'scale':
  189. [parseFloat(__getIcon(c).getAttr('__sx')),
  190. parseFloat(__getIcon(c).getAttr('__sy'))]},
  191. context[c]]);
  192. var padding = 20,
  193. overflow =
  194. {'right': (itbbox.x + itbbox.width) -
  195. (cbbox.x + cbbox.width) + padding,
  196. 'left': cbbox.x - itbbox.x + padding,
  197. 'top': cbbox.y - itbbox.y + padding,
  198. 'bottom': (itbbox.y + itbbox.height) -
  199. (cbbox.y + cbbox.height) + padding};
  200. if( overflow.left > 0 )
  201. {
  202. containers2changes[c]['position'][0] -= overflow.left;
  203. containers2changes[c]['scale'][0] *=
  204. (cbbox.width+overflow.left)/cbbox.width;
  205. cbbox.width *= containers2changes[c]['scale'][0];
  206. }
  207. if( overflow.right > 0 )
  208. containers2changes[c]['scale'][0] *=
  209. (cbbox.width+overflow.right)/cbbox.width;
  210. if( overflow.top > 0 )
  211. {
  212. containers2changes[c]['position'][1] -= overflow.top;
  213. containers2changes[c]['scale'][1] *=
  214. (cbbox.height+overflow.top)/cbbox.height;
  215. cbbox.height *= containers2changes[c]['scale'][1];
  216. }
  217. if( overflow.bottom > 0 )
  218. containers2changes[c]['scale'][1] *=
  219. (cbbox.height+overflow.bottom)/cbbox.height;
  220. }
  221. };
  222. icons.forEach(
  223. function(it)
  224. {
  225. if( !(it in __icons) || __isConnectionType(it) )
  226. return;
  227. __icons[it]['edgesIn'].forEach(
  228. function(edgeId)
  229. {
  230. var linkIn = __edgeId2ends(edgeId)[0];
  231. if( __isContainmentConnectionType(linkIn) ) {
  232. if ( reqs.map(function(_node) {return _node['uri'];}).indexOf(__edgeId2ends(__icons[linkIn]['edgesIn'][0])[0] + '.cs') < 0 ) {
  233. resizeContainer(
  234. __edgeId2ends(__icons[linkIn]['edgesIn'][0])[0],
  235. linkIn,
  236. it);
  237. }
  238. }
  239. });
  240. if( context.toBeInserted && it in context.toBeInserted )
  241. resizeContainer(context.toBeInserted[it],undefined,it);
  242. });
  243. if( utils.keys(containers2changes).length == 0 && requests.length == 0 )
  244. return (dryRun ? [] : undefined);
  245. for( var uri in containers2changes )
  246. requests.push(
  247. {'method':'PUT',
  248. 'uri':HttpUtils.url(uri+'.cs',__NO_USERNAME+__NO_WID),
  249. 'reqData':{'changes':containers2changes[uri]}});
  250. for (var req_id in requests) {
  251. var to_concat = utils.flatten(GeometryUtils.resizeContainers(
  252. utils.keys(containers2changes),
  253. containers2changes,
  254. true,
  255. false,
  256. requests)
  257. );
  258. requests = requests.concat(to_concat);
  259. }
  260. if( dryRun )
  261. return requests;
  262. else
  263. HttpUtils.httpReq(
  264. 'POST',
  265. HttpUtils.url('/batchEdit',__NO_USERNAME),
  266. requests);
  267. };
  268. /**
  269. * Shows the geometry controls overlay (positioning is based on the bounding box
  270. * of the current selection) and initializes the transformation preview overlay
  271. */
  272. this.showGeometryControlsOverlay = function() {
  273. var bbox = __selection['bbox'];
  274. if( geometryControlsOverlay == undefined )
  275. {
  276. geometryControlsOverlay = $('#div_geom_ctrls');
  277. ['resize','resizeH','resizeW','rotate'].forEach(
  278. function(x)
  279. {
  280. var img = $('<img>');
  281. img.attr('class', 'geometry_ctrl');
  282. img.attr('src', 'client/media/'+x+'.png');
  283. img.attr('id', x + "_btn");
  284. let wheelFunc = function(event)
  285. {
  286. let dir = null;
  287. if (event.wheelDelta){
  288. dir = event.wheelDelta;
  289. }else if (event.deltaY){
  290. dir = event.deltaY;
  291. }
  292. GeometryUtils.previewSelectionTransformation(x,dir);
  293. return false;
  294. };
  295. //detect mouse wheel on all browsers
  296. img.get(0).onmousewheel = wheelFunc;
  297. img.get(0).onwheel = wheelFunc;
  298. geometryControlsOverlay.append(img);
  299. });
  300. var img = $('<img>');
  301. img.attr('class', 'geometry_ctrl');
  302. img.attr('src', 'client/media/ok.png');
  303. img.attr('id', "ok_btn");
  304. img.click(function(event) {GeometryUtils.transformSelection(__GEOM_TRANSF);});
  305. geometryControlsOverlay.append(img);
  306. }
  307. geometryControlsOverlay.css("top",
  308. bbox.y + bbox.height - $("#div_container").scrollTop() + "px"),
  309. geometryControlsOverlay.css("left",
  310. bbox.x + bbox.width/2 - __GEOM_CTRLS_WIDTH/2.0 - $("#div_container").scrollLeft() + "px");
  311. geometryControlsOverlay.css("display", "inline");
  312. GeometryUtils.initSelectionTransformationPreviewOverlay();
  313. __setCanvasScrolling(false);
  314. };
  315. /**
  316. * Snaps the top-left corner of the selection bounding box to the nearest
  317. * grid point
  318. */
  319. this.snapSelectionToGrid = function() {
  320. var bbox = __selection['bbox'],
  321. dx = bbox.x % __GRID_CELL_SIZE,
  322. dy = bbox.y % __GRID_CELL_SIZE;
  323. if( dx == 0 && dy == 0 )
  324. return;
  325. GeometryUtils.initSelectionTransformationPreviewOverlay(bbox.x,bbox.y);
  326. GeometryUtils.previewSelectionTranslation(
  327. bbox.x + (dx < __GRID_CELL_SIZE/2 ? -dx : __GRID_CELL_SIZE-dx),
  328. bbox.y + (dy < __GRID_CELL_SIZE/2 ? -dy : __GRID_CELL_SIZE-dy));
  329. GeometryUtils.transformSelection(__GEOM_TRANSF);
  330. };
  331. /* applies the transformation currently applied to the preview overlay to the
  332. selected icon(s)/edge(s) and removes the geometry controls and transformation
  333. preview overlays... if 'insertInfo' is specified, also inserts selection into
  334. it (see NOTE about why this is done from here)... this function doesn't
  335. actually transform the icons, it merely requests the update of the icon(s)'s
  336. 'transformation' and/or the link(s)'s $segments attributes on the csworker
  337. (i.e., a changelog triggers the actual transformation)
  338. 1. extract transformation and build up changes in 'uri2changes'
  339. 2. add $segments changes to 'uris2changes'
  340. 3. retrieve and compute all necessary requests
  341. a. retrieve insertion requests (+ provide DataUtils.insert() with data needed
  342. to compute bboxes of to-be-transformed icons, i.e., 'uris2changes')
  343. b. convert 'uri2changes' to icon transformation requests
  344. c. retrieve container resizing requests (+ provide GeometryUtils.resizeContainers()
  345. with 'uris2changes', a list of pending insertions from step 3a, and
  346. possibly a dragout prohibition)
  347. 4. send batchEdit with requests from step 3... note that requests from
  348. step 3a. are inserted last s.t. the event-flow is 1-something moved
  349. followed by 2-something inserted... this ordering is needed to ensure
  350. mappers and parsers are evaluated in a sensible order
  351. the following describes the algorithm for getting edge ends to follow their
  352. icons when these are transformed:
  353. 1. for each outgoing edge,
  354. z) do nothing if the edge's Link is in __selection
  355. a) fetch the edge's source xy
  356. b) apply transformation T on it to produce xy'
  357. c) 'move' the edge source and possibly its first control point (when
  358. they are colocated) to xy'... in reality, save the desired motion in
  359. connectedEdgesChanges
  360. 2. for each outgoing edge, apply similar logic but to edge's end and last
  361. control point
  362. NOTE:: to avoid race conditions between updates to different edges within a
  363. single Link's $segments, relevant changes are accumulated in
  364. connectedEdgesChanges s.t. those pertaining to the same Link end up
  365. bundled in a single update request
  366. NOTE:: to avoid race conditions between updates to $segments resulting from
  367. edge ends following connected icon and updates resulting from edges
  368. themselves being transformed (i.e., when they are within __selection),
  369. the former are ignored when we know the latter will be carried out
  370. NOTE:: because SVG transformations are always relative to the global (0,0),
  371. non-translate transformations still technically translate things...
  372. Raphael allows specifiying different origins for transformations...
  373. default SVG scale x2 :
  374. Rect(10,10,200,100) > Rect(20,20,400,200)
  375. Raphael scale with scale origin set to (10,10)
  376. Rect(10,10,200,100) > Rect(10,10,200,100)
  377. in the above example, Raphael's transformation matrix will report the
  378. translation from (20,20) back to (10,10) even though from my
  379. perspective, the figure hasn't moved and has only been scaled... to
  380. account for this, when decomposing the said matrix, we ignore tx,ty
  381. when r|sx|sy aren't 0|1|1 and vice-versa... this doesn't cause any
  382. problems because the client interface doesn't support scaling/rotating
  383. *and* translating without an intermediate call to this function...
  384. NOTE:: essentially, the above-explained ignored rotation/scaling translation
  385. components apply to the top-left corner of the selection bbox (i.e.,
  386. it's Raphael ensuring that the said corner does not move as a result
  387. of rotations/scalings 'centered' on it)... however, similar rotation/
  388. scaling translation components apply to contents of the selection...
  389. this is because the said contents are changing wrt. the top-left
  390. corner of the selection, not wrt. their own (x,y)... ignoring these
  391. 'internal' translation components would cause altering a selection to
  392. act like altering each selected item individually... long story short,
  393. we can not and do not ignore them... below is the algorithm we use to
  394. compute the internal translation components:
  395. 1. foreach selected icon
  396. [do nothing if no rotation or and no scaling]
  397. a) compute offset between icon's x,y and selection's top-left corner
  398. b) apply extracted (from transformation matrix) rotation and scale
  399. to a point whose coordinates are the x and y offsets from step a)
  400. c) determine translation from point from step a) to transformed
  401. point from step b)
  402. d) the icon's transformation is now the extracted rotation and
  403. scaling *and* the translation from step c)
  404. NOTE:: since the selection transformation should be an atomic operation,
  405. changes are accumulated in 'uris2changes' and are only actually sent
  406. to the csworker at the very end of this function... also, since
  407. insertions and container resizings and the selection transformations
  408. that triggered them should be atomic too, requests pertaining to the 2
  409. former tasks are computed and bundled with those that effect the
  410. latter... the results of this form the emitted batchEdit */
  411. this.transformSelection = function(callingContext,insertInfo) {
  412. if (transformationPreviewOverlay == undefined)
  413. return;
  414. var T = transformationPreviewOverlay.node.getAttribute('transform');
  415. if( T == null || T == 'matrix(1,0,0,1,0,0)' )
  416. {
  417. GeometryUtils.hideGeometryControlsOverlay();
  418. GeometryUtils.hideTransformationPreviewOverlay();
  419. return;
  420. }
  421. /** 1 **/
  422. var _T = __decomposeTransformationMatrix(T),
  423. connectedEdgesChanges = {},
  424. uris2changes = {};
  425. __selection['items'].forEach(
  426. function(it)
  427. {
  428. if( it in __icons )
  429. {
  430. var icon = __icons[it]['icon'],
  431. changes = {};
  432. if( _T.r == 0 &&
  433. Math.abs(1-_T.sx) <= 0.001 &&
  434. Math.abs(1-_T.sy) <= 0.001 )
  435. {
  436. /* translation only */
  437. if( _T.tx != 0 || _T.ty != 0 )
  438. changes['position'] =
  439. [_T.tx + parseFloat(icon.getAttr('__x')),
  440. _T.ty + parseFloat(icon.getAttr('__y'))];
  441. }
  442. else
  443. {
  444. /* rotation/scale only */
  445. var offset = [icon.getAttr('__x') - __selection['bbox'].x,
  446. icon.getAttr('__y') - __selection['bbox'].y],
  447. rsOffset = GeometryUtils.transformPoint(
  448. offset[0],
  449. offset[1],
  450. 'rotate('+_T.r+') scale('+_T.sx+','+_T.sy+')'),
  451. offsetTx = rsOffset[0] - offset[0],
  452. offsetTy = rsOffset[1] - offset[1];
  453. if( _T.r != 0 )
  454. changes['orientation'] =
  455. (parseFloat(icon.getAttr('__r')) + _T.r) % 360;
  456. if( Math.abs(1-_T.sx) > 0.001 || Math.abs(1-_T.sy) > 0.001 )
  457. changes['scale'] =
  458. [_T.sx * parseFloat(icon.getAttr('__sx')),
  459. _T.sy * parseFloat(icon.getAttr('__sy'))];
  460. if( offsetTx != 0 || offsetTy != 0 )
  461. changes['position'] =
  462. [offsetTx + parseFloat(icon.getAttr('__x')),
  463. offsetTy + parseFloat(icon.getAttr('__y'))];
  464. }
  465. uris2changes[it] = changes;
  466. if (!__isConnectionType(it)) {
  467. let inLinkUris = __icons[it]['edgesIn'].map(__edgeId2linkuri);
  468. let outLinkUris = __icons[it]['edgesOut'].map(__edgeId2linkuri);
  469. /* have edge ends out follow */
  470. __icons[it]['edgesOut'].forEach(
  471. function (edgeId) {
  472. let linkuri = __edgeId2linkuri(edgeId);
  473. if (__isSelected(linkuri))
  474. return;
  475. let isLooping = inLinkUris.includes(linkuri);
  476. let changes = moveEdges(edgeId, T, true, isLooping);
  477. let newEdgeChanges = changes[0];
  478. let centrePoint = changes[1];
  479. connectedEdgesChanges[linkuri] =
  480. (connectedEdgesChanges[linkuri] || {});
  481. connectedEdgesChanges[linkuri] = utils.mergeDicts([connectedEdgesChanges[linkuri], newEdgeChanges]);
  482. //move the assoc text if the central point changed
  483. if (centrePoint != null) {
  484. if (uris2changes[__edgeId2linkuri(edgeId)] == null) {
  485. uris2changes[__edgeId2linkuri(edgeId)] = {};
  486. }
  487. uris2changes[__edgeId2linkuri(edgeId)]['position'] = centrePoint;
  488. }
  489. });
  490. /* have edge ends in follow */
  491. __icons[it]['edgesIn'].forEach(
  492. function (edgeId) {
  493. let linkuri = __edgeId2linkuri(edgeId);
  494. if (__isSelected(linkuri))
  495. return;
  496. let isLooping = outLinkUris.includes(linkuri);
  497. let changes = moveEdges(edgeId, T, false, isLooping);
  498. let newEdgeChanges = changes[0];
  499. let centrePoint = changes[1];
  500. connectedEdgesChanges[linkuri] =
  501. (connectedEdgesChanges[linkuri] || {});
  502. connectedEdgesChanges[linkuri] = utils.mergeDicts([connectedEdgesChanges[linkuri], newEdgeChanges]);
  503. //move the assoc text if the central point changed
  504. if (centrePoint != null) {
  505. if (uris2changes[__edgeId2linkuri(edgeId)] == null) {
  506. uris2changes[__edgeId2linkuri(edgeId)] = {};
  507. }
  508. uris2changes[__edgeId2linkuri(edgeId)]['position'] = centrePoint;
  509. }
  510. });
  511. }
  512. else
  513. {
  514. /* transform entire edges */
  515. var __segments = __linkuri2segments(it),
  516. changes = {};
  517. for( var edgeId in __segments )
  518. {
  519. var segments = __segments[edgeId],
  520. points = segments.match(/([\d\.]*,[\d\.]*)/g),
  521. newPoints = points.map(
  522. function(p)
  523. {
  524. p = p.split(',');
  525. return GeometryUtils.transformPoint(p[0],p[1],T);
  526. });
  527. changes[edgeId] = 'M'+newPoints.join('L');
  528. }
  529. uris2changes[it]['$segments'] = changes;
  530. }
  531. }
  532. });
  533. /** 2 **/
  534. if( utils.keys(connectedEdgesChanges).length > 0 )
  535. for( var linkuri in connectedEdgesChanges )
  536. {
  537. if( !(linkuri in uris2changes) )
  538. uris2changes[linkuri] = {};
  539. if( !('$segments' in uris2changes[linkuri]) )
  540. uris2changes[linkuri]['$segments'] = __linkuri2segments(linkuri);
  541. uris2changes[linkuri]['$segments'] =
  542. utils.mergeDicts([
  543. uris2changes[linkuri]['$segments'],
  544. connectedEdgesChanges[linkuri]]);
  545. }
  546. /** 3-4 **/
  547. if( utils.keys(uris2changes).length > 0 )
  548. {
  549. var csRequests = [],
  550. insertRequests = [];
  551. if( insertInfo )
  552. {
  553. insertRequests = DataUtils.insert(
  554. insertInfo['dropTarget'].getAttribute('__csuri'),
  555. __selection['items'],
  556. insertInfo['connectionType'],
  557. uris2changes,
  558. true);
  559. var toBeInserted = {};
  560. insertRequests.forEach(
  561. function(r)
  562. {
  563. if ('reqData' in r)
  564. toBeInserted[r['reqData']['dest']] = r['reqData']['src'];
  565. });
  566. }
  567. for( var uri in uris2changes )
  568. if( utils.keys(uris2changes[uri]).length > 0 )
  569. csRequests.push(
  570. {'method':'PUT',
  571. 'uri':HttpUtils.url(uri+'.cs',__NO_USERNAME+__NO_WID),
  572. 'reqData':{'changes':uris2changes[uri]}});
  573. HttpUtils.httpReq(
  574. 'POST',
  575. HttpUtils.url('/batchEdit',__NO_USERNAME),
  576. csRequests.concat(
  577. GeometryUtils.resizeContainers(
  578. __selection['items'],
  579. utils.mergeDicts(
  580. [uris2changes, {'toBeInserted':toBeInserted}]),
  581. true,
  582. (callingContext == __GEOM_TRANSF)),
  583. insertRequests));
  584. }
  585. };
  586. /**
  587. * Moves the points for this edge using the transformation T
  588. * If the edge is only comprised of three points
  589. * (the point on the icon, the central point, and the connected node's point)
  590. * then move the central point
  591. * Returns the changes to be made to the edges, and the central point if calculated
  592. */
  593. this.moveEdges = function (edgeId, T, isOutDir, isLooping) {
  594. let segments = __edges[edgeId]['segments'];
  595. let points = segments.match(/([\d\.]*,[\d\.]*)/g);
  596. let xy = null;
  597. let newXY = null;
  598. //update the point connected to the icon
  599. if (isOutDir) {
  600. xy = utils.head(points).split(',');
  601. newXY = GeometryUtils.transformPoint(xy[0], xy[1], T);
  602. points.splice(0, 1, newXY.join(','));
  603. } else {
  604. xy = utils.tail(points).split(',');
  605. newXY = GeometryUtils.transformPoint(xy[0], xy[1], T);
  606. points.splice(points.length - 1, 1, newXY.join(','));
  607. }
  608. //dict to hold edge updates
  609. let edgeDict = {};
  610. // the centre point if the association text should be moved
  611. let centrePoint = null;
  612. // if there are exactly two points in this edge,
  613. // move the middle control point as well
  614. // by updating the other edge in the association
  615. //
  616. //don't do this if it's a looping edge
  617. //as it will overwrite the changes
  618. if (points.length == 2 && !isLooping) {
  619. let connectionPartici = __getConnectionParticipants(edgeId);
  620. let otherEdge = isOutDir ? connectionPartici[2] : connectionPartici[1];
  621. let otherSegments = __edges[otherEdge]['segments'];
  622. let otherPoints = otherSegments.match(/([\d\.]*,[\d\.]*)/g);
  623. //get the other edge's point which is not the center point
  624. let otherxy = isOutDir ? otherPoints[1] : otherPoints[otherPoints.length - 2];
  625. otherxy = otherxy.split(",");
  626. let xCentrePoint = (parseFloat(newXY[0]) + parseFloat(otherxy[0])) / 2;
  627. let yCentrePoint = (parseFloat(newXY[1]) + parseFloat(otherxy[1])) / 2;
  628. let centrePointStr = xCentrePoint + "," + yCentrePoint;
  629. if (isOutDir) {
  630. points.splice(points.length - 1, 1, centrePointStr);
  631. otherPoints.splice(0, 1, centrePointStr);
  632. } else {
  633. points.splice(0, 1, centrePointStr);
  634. otherPoints.splice(otherPoints.length - 1, 1, centrePointStr);
  635. }
  636. let newOtherEdge = 'M' + otherPoints.join('L');
  637. edgeDict[otherEdge] = newOtherEdge;
  638. centrePoint = [xCentrePoint, yCentrePoint];
  639. }
  640. let newEdge = 'M' + points.join('L');
  641. edgeDict[edgeId] = newEdge;
  642. return [edgeDict, centrePoint];
  643. };
  644. /**
  645. * Apply the specified transformation to the given point and return
  646. * the resulting point
  647. */
  648. this.transformPoint = function(x,y,T) {
  649. var pt = __canvas.group();
  650. pt.push( __canvas.point(x,y) );
  651. pt.node.setAttribute('transform',T);
  652. var bbox = pt.getBBox();
  653. pt.remove();
  654. return [bbox.x+bbox.width/2,bbox.y+bbox.height/2];
  655. };
  656. return this;
  657. }();