recalculate.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. /*globals $*/
  2. /*jslint vars: true, eqeq: true, continue: true*/
  3. /**
  4. * Recalculate.
  5. *
  6. * Licensed under the MIT License
  7. *
  8. */
  9. // Dependencies:
  10. // 1) jquery
  11. // 2) jquery-svg.js
  12. // 3) svgedit.js
  13. // 4) browser.js
  14. // 5) math.js
  15. // 6) history.js
  16. // 7) units.js
  17. // 8) svgtransformlist.js
  18. // 9) svgutils.js
  19. // 10) coords.js
  20. var svgedit = svgedit || {};
  21. (function() {
  22. if (!svgedit.recalculate) {
  23. svgedit.recalculate = {};
  24. }
  25. var NS = svgedit.NS;
  26. var context_;
  27. // Function: svgedit.recalculate.init
  28. svgedit.recalculate.init = function(editorContext) {
  29. context_ = editorContext;
  30. };
  31. // Function: svgedit.recalculate.updateClipPath
  32. // Updates a <clipPath>s values based on the given translation of an element
  33. //
  34. // Parameters:
  35. // attr - The clip-path attribute value with the clipPath's ID
  36. // tx - The translation's x value
  37. // ty - The translation's y value
  38. svgedit.recalculate.updateClipPath = function(attr, tx, ty) {
  39. var path = getRefElem(attr).firstChild;
  40. var cp_xform = svgedit.transformlist.getTransformList(path);
  41. var newxlate = context_.getSVGRoot().createSVGTransform();
  42. newxlate.setTranslate(tx, ty);
  43. cp_xform.appendItem(newxlate);
  44. // Update clipPath's dimensions
  45. svgedit.recalculate.recalculateDimensions(path);
  46. };
  47. // Function: svgedit.recalculate.recalculateDimensions
  48. // Decides the course of action based on the element's transform list
  49. //
  50. // Parameters:
  51. // selected - The DOM element to recalculate
  52. //
  53. // Returns:
  54. // Undo command object with the resulting change
  55. svgedit.recalculate.recalculateDimensions = function(selected) {
  56. if (selected == null) {return null;}
  57. // Firefox Issue - 1081
  58. if (selected.nodeName == "svg" && navigator.userAgent.indexOf("Firefox/20") >= 0) {
  59. return null;
  60. }
  61. var svgroot = context_.getSVGRoot();
  62. var tlist = svgedit.transformlist.getTransformList(selected);
  63. var k;
  64. // remove any unnecessary transforms
  65. if (tlist && tlist.numberOfItems > 0) {
  66. k = tlist.numberOfItems;
  67. while (k--) {
  68. var xform = tlist.getItem(k);
  69. if (xform.type === 0) {
  70. tlist.removeItem(k);
  71. }
  72. // remove identity matrices
  73. else if (xform.type === 1) {
  74. if (svgedit.math.isIdentity(xform.matrix)) {
  75. tlist.removeItem(k);
  76. }
  77. }
  78. // remove zero-degree rotations
  79. else if (xform.type === 4) {
  80. if (xform.angle === 0) {
  81. tlist.removeItem(k);
  82. }
  83. }
  84. }
  85. // End here if all it has is a rotation
  86. if (tlist.numberOfItems === 1 &&
  87. svgedit.utilities.getRotationAngle(selected)) {return null;}
  88. }
  89. // if this element had no transforms, we are done
  90. if (!tlist || tlist.numberOfItems == 0) {
  91. // Chrome has a bug that requires clearing the attribute first.
  92. selected.setAttribute('transform', '');
  93. selected.removeAttribute('transform');
  94. return null;
  95. }
  96. // TODO: Make this work for more than 2
  97. if (tlist) {
  98. k = tlist.numberOfItems;
  99. var mxs = [];
  100. while (k--) {
  101. var xform = tlist.getItem(k);
  102. if (xform.type === 1) {
  103. mxs.push([xform.matrix, k]);
  104. } else if (mxs.length) {
  105. mxs = [];
  106. }
  107. }
  108. if (mxs.length === 2) {
  109. var m_new = svgroot.createSVGTransformFromMatrix(svgedit.math.matrixMultiply(mxs[1][0], mxs[0][0]));
  110. tlist.removeItem(mxs[0][1]);
  111. tlist.removeItem(mxs[1][1]);
  112. tlist.insertItemBefore(m_new, mxs[1][1]);
  113. }
  114. // combine matrix + translate
  115. k = tlist.numberOfItems;
  116. if (k >= 2 && tlist.getItem(k-2).type === 1 && tlist.getItem(k-1).type === 2) {
  117. var mt = svgroot.createSVGTransform();
  118. var m = svgedit.math.matrixMultiply(
  119. tlist.getItem(k-2).matrix,
  120. tlist.getItem(k-1).matrix);
  121. mt.setMatrix(m);
  122. tlist.removeItem(k-2);
  123. tlist.removeItem(k-2);
  124. tlist.appendItem(mt);
  125. }
  126. }
  127. // If it still has a single [M] or [R][M], return null too (prevents BatchCommand from being returned).
  128. switch ( selected.tagName ) {
  129. // Ignore these elements, as they can absorb the [M]
  130. case 'line':
  131. case 'polyline':
  132. case 'polygon':
  133. case 'path':
  134. break;
  135. default:
  136. if ((tlist.numberOfItems === 1 && tlist.getItem(0).type === 1) ||
  137. (tlist.numberOfItems === 2 && tlist.getItem(0).type === 1 && tlist.getItem(0).type === 4)) {
  138. return null;
  139. }
  140. }
  141. // Grouped SVG element
  142. var gsvg = $(selected).data('gsvg');
  143. // we know we have some transforms, so set up return variable
  144. var batchCmd = new svgedit.history.BatchCommand('Transform');
  145. // store initial values that will be affected by reducing the transform list
  146. var changes = {}, initial = null, attrs = [];
  147. switch (selected.tagName) {
  148. case 'line':
  149. attrs = ['x1', 'y1', 'x2', 'y2'];
  150. break;
  151. case 'circle':
  152. attrs = ['cx', 'cy', 'r'];
  153. break;
  154. case 'ellipse':
  155. attrs = ['cx', 'cy', 'rx', 'ry'];
  156. break;
  157. case 'foreignObject':
  158. case 'rect':
  159. case 'image':
  160. attrs = ['width', 'height', 'x', 'y'];
  161. break;
  162. case 'use':
  163. case 'text':
  164. case 'tspan':
  165. attrs = ['x', 'y'];
  166. break;
  167. case 'polygon':
  168. case 'polyline':
  169. initial = {};
  170. initial.points = selected.getAttribute('points');
  171. var list = selected.points;
  172. var len = list.numberOfItems;
  173. changes.points = new Array(len);
  174. var i;
  175. for (i = 0; i < len; ++i) {
  176. var pt = list.getItem(i);
  177. changes.points[i] = {x:pt.x, y:pt.y};
  178. }
  179. break;
  180. case 'path':
  181. initial = {};
  182. initial.d = selected.getAttribute('d');
  183. changes.d = selected.getAttribute('d');
  184. break;
  185. } // switch on element type to get initial values
  186. if (attrs.length) {
  187. changes = $(selected).attr(attrs);
  188. $.each(changes, function(attr, val) {
  189. changes[attr] = svgedit.units.convertToNum(attr, val);
  190. });
  191. } else if (gsvg) {
  192. // GSVG exception
  193. changes = {
  194. x: $(gsvg).attr('x') || 0,
  195. y: $(gsvg).attr('y') || 0
  196. };
  197. }
  198. // if we haven't created an initial array in polygon/polyline/path, then
  199. // make a copy of initial values and include the transform
  200. if (initial == null) {
  201. initial = $.extend(true, {}, changes);
  202. $.each(initial, function(attr, val) {
  203. initial[attr] = svgedit.units.convertToNum(attr, val);
  204. });
  205. }
  206. // save the start transform value too
  207. initial.transform = context_.getStartTransform() || '';
  208. // if it's a regular group, we have special processing to flatten transforms
  209. if ((selected.tagName == 'g' && !gsvg) || selected.tagName == 'a') {
  210. var box = svgedit.utilities.getBBox(selected),
  211. oldcenter = {x: box.x+box.width/2, y: box.y+box.height/2},
  212. newcenter = svgedit.math.transformPoint(box.x+box.width/2,
  213. box.y+box.height/2,
  214. svgedit.math.transformListToTransform(tlist).matrix),
  215. m = svgroot.createSVGMatrix();
  216. // temporarily strip off the rotate and save the old center
  217. var gangle = svgedit.utilities.getRotationAngle(selected);
  218. if (gangle) {
  219. var a = gangle * Math.PI / 180;
  220. if ( Math.abs(a) > (1.0e-10) ) {
  221. var s = Math.sin(a)/(1 - Math.cos(a));
  222. } else {
  223. // FIXME: This blows up if the angle is exactly 0!
  224. var s = 2/a;
  225. }
  226. var i;
  227. for (i = 0; i < tlist.numberOfItems; ++i) {
  228. var xform = tlist.getItem(i);
  229. if (xform.type == 4) {
  230. // extract old center through mystical arts
  231. var rm = xform.matrix;
  232. oldcenter.y = (s*rm.e + rm.f)/2;
  233. oldcenter.x = (rm.e - s*rm.f)/2;
  234. tlist.removeItem(i);
  235. break;
  236. }
  237. }
  238. }
  239. var tx = 0, ty = 0,
  240. operation = 0,
  241. N = tlist.numberOfItems;
  242. if (N) {
  243. var first_m = tlist.getItem(0).matrix;
  244. }
  245. // first, if it was a scale then the second-last transform will be it
  246. if (N >= 3 && tlist.getItem(N-2).type == 3 &&
  247. tlist.getItem(N-3).type == 2 && tlist.getItem(N-1).type == 2)
  248. {
  249. operation = 3; // scale
  250. // if the children are unrotated, pass the scale down directly
  251. // otherwise pass the equivalent matrix() down directly
  252. var tm = tlist.getItem(N-3).matrix,
  253. sm = tlist.getItem(N-2).matrix,
  254. tmn = tlist.getItem(N-1).matrix;
  255. var children = selected.childNodes;
  256. var c = children.length;
  257. while (c--) {
  258. var child = children.item(c);
  259. tx = 0;
  260. ty = 0;
  261. if (child.nodeType == 1) {
  262. var childTlist = svgedit.transformlist.getTransformList(child);
  263. // some children might not have a transform (<metadata>, <defs>, etc)
  264. if (!childTlist) {continue;}
  265. var m = svgedit.math.transformListToTransform(childTlist).matrix;
  266. // Convert a matrix to a scale if applicable
  267. // if (svgedit.math.hasMatrixTransform(childTlist) && childTlist.numberOfItems == 1) {
  268. // if (m.b==0 && m.c==0 && m.e==0 && m.f==0) {
  269. // childTlist.removeItem(0);
  270. // var translateOrigin = svgroot.createSVGTransform(),
  271. // scale = svgroot.createSVGTransform(),
  272. // translateBack = svgroot.createSVGTransform();
  273. // translateOrigin.setTranslate(0, 0);
  274. // scale.setScale(m.a, m.d);
  275. // translateBack.setTranslate(0, 0);
  276. // childTlist.appendItem(translateBack);
  277. // childTlist.appendItem(scale);
  278. // childTlist.appendItem(translateOrigin);
  279. // }
  280. // }
  281. var angle = svgedit.utilities.getRotationAngle(child);
  282. var oldStartTransform = context_.getStartTransform();
  283. var childxforms = [];
  284. context_.setStartTransform(child.getAttribute('transform'));
  285. if (angle || svgedit.math.hasMatrixTransform(childTlist)) {
  286. var e2t = svgroot.createSVGTransform();
  287. e2t.setMatrix(svgedit.math.matrixMultiply(tm, sm, tmn, m));
  288. childTlist.clear();
  289. childTlist.appendItem(e2t);
  290. childxforms.push(e2t);
  291. }
  292. // if not rotated or skewed, push the [T][S][-T] down to the child
  293. else {
  294. // update the transform list with translate,scale,translate
  295. // slide the [T][S][-T] from the front to the back
  296. // [T][S][-T][M] = [M][T2][S2][-T2]
  297. // (only bringing [-T] to the right of [M])
  298. // [T][S][-T][M] = [T][S][M][-T2]
  299. // [-T2] = [M_inv][-T][M]
  300. var t2n = svgedit.math.matrixMultiply(m.inverse(), tmn, m);
  301. // [T2] is always negative translation of [-T2]
  302. var t2 = svgroot.createSVGMatrix();
  303. t2.e = -t2n.e;
  304. t2.f = -t2n.f;
  305. // [T][S][-T][M] = [M][T2][S2][-T2]
  306. // [S2] = [T2_inv][M_inv][T][S][-T][M][-T2_inv]
  307. var s2 = svgedit.math.matrixMultiply(t2.inverse(), m.inverse(), tm, sm, tmn, m, t2n.inverse());
  308. var translateOrigin = svgroot.createSVGTransform(),
  309. scale = svgroot.createSVGTransform(),
  310. translateBack = svgroot.createSVGTransform();
  311. translateOrigin.setTranslate(t2n.e, t2n.f);
  312. scale.setScale(s2.a, s2.d);
  313. translateBack.setTranslate(t2.e, t2.f);
  314. childTlist.appendItem(translateBack);
  315. childTlist.appendItem(scale);
  316. childTlist.appendItem(translateOrigin);
  317. childxforms.push(translateBack);
  318. childxforms.push(scale);
  319. childxforms.push(translateOrigin);
  320. // logMatrix(translateBack.matrix);
  321. // logMatrix(scale.matrix);
  322. } // not rotated
  323. batchCmd.addSubCommand( svgedit.recalculate.recalculateDimensions(child) );
  324. // TODO: If any <use> have this group as a parent and are
  325. // referencing this child, then we need to impose a reverse
  326. // scale on it so that when it won't get double-translated
  327. // var uses = selected.getElementsByTagNameNS(NS.SVG, 'use');
  328. // var href = '#' + child.id;
  329. // var u = uses.length;
  330. // while (u--) {
  331. // var useElem = uses.item(u);
  332. // if (href == svgedit.utilities.getHref(useElem)) {
  333. // var usexlate = svgroot.createSVGTransform();
  334. // usexlate.setTranslate(-tx,-ty);
  335. // svgedit.transformlist.getTransformList(useElem).insertItemBefore(usexlate,0);
  336. // batchCmd.addSubCommand( svgedit.recalculate.recalculateDimensions(useElem) );
  337. // }
  338. // }
  339. context_.setStartTransform(oldStartTransform);
  340. } // element
  341. } // for each child
  342. // Remove these transforms from group
  343. tlist.removeItem(N-1);
  344. tlist.removeItem(N-2);
  345. tlist.removeItem(N-3);
  346. } else if (N >= 3 && tlist.getItem(N-1).type == 1) {
  347. operation = 3; // scale
  348. m = svgedit.math.transformListToTransform(tlist).matrix;
  349. var e2t = svgroot.createSVGTransform();
  350. e2t.setMatrix(m);
  351. tlist.clear();
  352. tlist.appendItem(e2t);
  353. }
  354. // next, check if the first transform was a translate
  355. // if we had [ T1 ] [ M ] we want to transform this into [ M ] [ T2 ]
  356. // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ]
  357. else if ( (N == 1 || (N > 1 && tlist.getItem(1).type != 3)) &&
  358. tlist.getItem(0).type == 2)
  359. {
  360. operation = 2; // translate
  361. var T_M = svgedit.math.transformListToTransform(tlist).matrix;
  362. tlist.removeItem(0);
  363. var M_inv = svgedit.math.transformListToTransform(tlist).matrix.inverse();
  364. var M2 = svgedit.math.matrixMultiply( M_inv, T_M );
  365. tx = M2.e;
  366. ty = M2.f;
  367. if (tx != 0 || ty != 0) {
  368. // we pass the translates down to the individual children
  369. var children = selected.childNodes;
  370. var c = children.length;
  371. var clipPaths_done = [];
  372. while (c--) {
  373. var child = children.item(c);
  374. if (child.nodeType == 1) {
  375. // Check if child has clip-path
  376. if (child.getAttribute('clip-path')) {
  377. // tx, ty
  378. var attr = child.getAttribute('clip-path');
  379. if (clipPaths_done.indexOf(attr) === -1) {
  380. svgedit.recalculate.updateClipPath(attr, tx, ty);
  381. clipPaths_done.push(attr);
  382. }
  383. }
  384. var oldStartTransform = context_.getStartTransform();
  385. context_.setStartTransform(child.getAttribute('transform'));
  386. var childTlist = svgedit.transformlist.getTransformList(child);
  387. // some children might not have a transform (<metadata>, <defs>, etc)
  388. if (childTlist) {
  389. var newxlate = svgroot.createSVGTransform();
  390. newxlate.setTranslate(tx, ty);
  391. if (childTlist.numberOfItems) {
  392. childTlist.insertItemBefore(newxlate, 0);
  393. } else {
  394. childTlist.appendItem(newxlate);
  395. }
  396. batchCmd.addSubCommand(svgedit.recalculate.recalculateDimensions(child));
  397. // If any <use> have this group as a parent and are
  398. // referencing this child, then impose a reverse translate on it
  399. // so that when it won't get double-translated
  400. var uses = selected.getElementsByTagNameNS(NS.SVG, 'use');
  401. var href = '#' + child.id;
  402. var u = uses.length;
  403. while (u--) {
  404. var useElem = uses.item(u);
  405. if (href == svgedit.utilities.getHref(useElem)) {
  406. var usexlate = svgroot.createSVGTransform();
  407. usexlate.setTranslate(-tx,-ty);
  408. svgedit.transformlist.getTransformList(useElem).insertItemBefore(usexlate, 0);
  409. batchCmd.addSubCommand( svgedit.recalculate.recalculateDimensions(useElem) );
  410. }
  411. }
  412. context_.setStartTransform(oldStartTransform);
  413. }
  414. }
  415. }
  416. clipPaths_done = [];
  417. context_.setStartTransform(oldStartTransform);
  418. }
  419. }
  420. // else, a matrix imposition from a parent group
  421. // keep pushing it down to the children
  422. else if (N == 1 && tlist.getItem(0).type == 1 && !gangle) {
  423. operation = 1;
  424. var m = tlist.getItem(0).matrix,
  425. children = selected.childNodes,
  426. c = children.length;
  427. while (c--) {
  428. var child = children.item(c);
  429. if (child.nodeType == 1) {
  430. var oldStartTransform = context_.getStartTransform();
  431. context_.setStartTransform(child.getAttribute('transform'));
  432. var childTlist = svgedit.transformlist.getTransformList(child);
  433. if (!childTlist) {continue;}
  434. var em = svgedit.math.matrixMultiply(m, svgedit.math.transformListToTransform(childTlist).matrix);
  435. var e2m = svgroot.createSVGTransform();
  436. e2m.setMatrix(em);
  437. childTlist.clear();
  438. childTlist.appendItem(e2m, 0);
  439. batchCmd.addSubCommand( svgedit.recalculate.recalculateDimensions(child) );
  440. context_.setStartTransform(oldStartTransform);
  441. // Convert stroke
  442. // TODO: Find out if this should actually happen somewhere else
  443. var sw = child.getAttribute('stroke-width');
  444. if (child.getAttribute('stroke') !== 'none' && !isNaN(sw)) {
  445. var avg = (Math.abs(em.a) + Math.abs(em.d)) / 2;
  446. child.setAttribute('stroke-width', sw * avg);
  447. }
  448. }
  449. }
  450. tlist.clear();
  451. }
  452. // else it was just a rotate
  453. else {
  454. if (gangle) {
  455. var newRot = svgroot.createSVGTransform();
  456. newRot.setRotate(gangle, newcenter.x, newcenter.y);
  457. if (tlist.numberOfItems) {
  458. tlist.insertItemBefore(newRot, 0);
  459. } else {
  460. tlist.appendItem(newRot);
  461. }
  462. }
  463. if (tlist.numberOfItems == 0) {
  464. selected.removeAttribute('transform');
  465. }
  466. return null;
  467. }
  468. // if it was a translate, put back the rotate at the new center
  469. if (operation == 2) {
  470. if (gangle) {
  471. newcenter = {
  472. x: oldcenter.x + first_m.e,
  473. y: oldcenter.y + first_m.f
  474. };
  475. var newRot = svgroot.createSVGTransform();
  476. newRot.setRotate(gangle, newcenter.x, newcenter.y);
  477. if (tlist.numberOfItems) {
  478. tlist.insertItemBefore(newRot, 0);
  479. } else {
  480. tlist.appendItem(newRot);
  481. }
  482. }
  483. }
  484. // if it was a resize
  485. else if (operation == 3) {
  486. var m = svgedit.math.transformListToTransform(tlist).matrix;
  487. var roldt = svgroot.createSVGTransform();
  488. roldt.setRotate(gangle, oldcenter.x, oldcenter.y);
  489. var rold = roldt.matrix;
  490. var rnew = svgroot.createSVGTransform();
  491. rnew.setRotate(gangle, newcenter.x, newcenter.y);
  492. var rnew_inv = rnew.matrix.inverse(),
  493. m_inv = m.inverse(),
  494. extrat = svgedit.math.matrixMultiply(m_inv, rnew_inv, rold, m);
  495. tx = extrat.e;
  496. ty = extrat.f;
  497. if (tx != 0 || ty != 0) {
  498. // now push this transform down to the children
  499. // we pass the translates down to the individual children
  500. var children = selected.childNodes;
  501. var c = children.length;
  502. while (c--) {
  503. var child = children.item(c);
  504. if (child.nodeType == 1) {
  505. var oldStartTransform = context_.getStartTransform();
  506. context_.setStartTransform(child.getAttribute('transform'));
  507. var childTlist = svgedit.transformlist.getTransformList(child);
  508. var newxlate = svgroot.createSVGTransform();
  509. newxlate.setTranslate(tx, ty);
  510. if (childTlist.numberOfItems) {
  511. childTlist.insertItemBefore(newxlate, 0);
  512. } else {
  513. childTlist.appendItem(newxlate);
  514. }
  515. batchCmd.addSubCommand( svgedit.recalculate.recalculateDimensions(child) );
  516. context_.setStartTransform(oldStartTransform);
  517. }
  518. }
  519. }
  520. if (gangle) {
  521. if (tlist.numberOfItems) {
  522. tlist.insertItemBefore(rnew, 0);
  523. } else {
  524. tlist.appendItem(rnew);
  525. }
  526. }
  527. }
  528. }
  529. // else, it's a non-group
  530. else {
  531. // FIXME: box might be null for some elements (<metadata> etc), need to handle this
  532. var box = svgedit.utilities.getBBox(selected);
  533. // Paths (and possbly other shapes) will have no BBox while still in <defs>,
  534. // but we still may need to recalculate them (see issue 595).
  535. // TODO: Figure out how to get BBox from these elements in case they
  536. // have a rotation transform
  537. if (!box && selected.tagName != 'path') return null;
  538. var m = svgroot.createSVGMatrix(),
  539. // temporarily strip off the rotate and save the old center
  540. angle = svgedit.utilities.getRotationAngle(selected);
  541. if (angle) {
  542. var oldcenter = {x: box.x+box.width/2, y: box.y+box.height/2},
  543. newcenter = svgedit.math.transformPoint(box.x+box.width/2, box.y+box.height/2,
  544. svgedit.math.transformListToTransform(tlist).matrix);
  545. var a = angle * Math.PI / 180;
  546. if ( Math.abs(a) > (1.0e-10) ) {
  547. var s = Math.sin(a)/(1 - Math.cos(a));
  548. } else {
  549. // FIXME: This blows up if the angle is exactly 0!
  550. var s = 2/a;
  551. }
  552. for (var i = 0; i < tlist.numberOfItems; ++i) {
  553. var xform = tlist.getItem(i);
  554. if (xform.type == 4) {
  555. // extract old center through mystical arts
  556. var rm = xform.matrix;
  557. oldcenter.y = (s*rm.e + rm.f)/2;
  558. oldcenter.x = (rm.e - s*rm.f)/2;
  559. tlist.removeItem(i);
  560. break;
  561. }
  562. }
  563. }
  564. // 2 = translate, 3 = scale, 4 = rotate, 1 = matrix imposition
  565. var operation = 0;
  566. var N = tlist.numberOfItems;
  567. // Check if it has a gradient with userSpaceOnUse, in which case
  568. // adjust it by recalculating the matrix transform.
  569. // TODO: Make this work in Webkit using svgedit.transformlist.SVGTransformList
  570. if (!svgedit.browser.isWebkit()) {
  571. var fill = selected.getAttribute('fill');
  572. if (fill && fill.indexOf('url(') === 0) {
  573. var paint = getRefElem(fill);
  574. var type = 'pattern';
  575. if (paint.tagName !== type) type = 'gradient';
  576. var attrVal = paint.getAttribute(type + 'Units');
  577. if (attrVal === 'userSpaceOnUse') {
  578. //Update the userSpaceOnUse element
  579. m = svgedit.math.transformListToTransform(tlist).matrix;
  580. var gtlist = svgedit.transformlist.getTransformList(paint);
  581. var gmatrix = svgedit.math.transformListToTransform(gtlist).matrix;
  582. m = svgedit.math.matrixMultiply(m, gmatrix);
  583. var m_str = 'matrix(' + [m.a, m.b, m.c, m.d, m.e, m.f].join(',') + ')';
  584. paint.setAttribute(type + 'Transform', m_str);
  585. }
  586. }
  587. }
  588. // first, if it was a scale of a non-skewed element, then the second-last
  589. // transform will be the [S]
  590. // if we had [M][T][S][T] we want to extract the matrix equivalent of
  591. // [T][S][T] and push it down to the element
  592. if (N >= 3 && tlist.getItem(N-2).type == 3 &&
  593. tlist.getItem(N-3).type == 2 && tlist.getItem(N-1).type == 2)
  594. // Removed this so a <use> with a given [T][S][T] would convert to a matrix.
  595. // Is that bad?
  596. // && selected.nodeName != 'use'
  597. {
  598. operation = 3; // scale
  599. m = svgedit.math.transformListToTransform(tlist, N-3, N-1).matrix;
  600. tlist.removeItem(N-1);
  601. tlist.removeItem(N-2);
  602. tlist.removeItem(N-3);
  603. } // if we had [T][S][-T][M], then this was a skewed element being resized
  604. // Thus, we simply combine it all into one matrix
  605. else if (N == 4 && tlist.getItem(N-1).type == 1) {
  606. operation = 3; // scale
  607. m = svgedit.math.transformListToTransform(tlist).matrix;
  608. var e2t = svgroot.createSVGTransform();
  609. e2t.setMatrix(m);
  610. tlist.clear();
  611. tlist.appendItem(e2t);
  612. // reset the matrix so that the element is not re-mapped
  613. m = svgroot.createSVGMatrix();
  614. } // if we had [R][T][S][-T][M], then this was a rotated matrix-element
  615. // if we had [T1][M] we want to transform this into [M][T2]
  616. // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ] and we can push [T2]
  617. // down to the element
  618. else if ( (N == 1 || (N > 1 && tlist.getItem(1).type != 3)) &&
  619. tlist.getItem(0).type == 2)
  620. {
  621. operation = 2; // translate
  622. var oldxlate = tlist.getItem(0).matrix,
  623. meq = svgedit.math.transformListToTransform(tlist,1).matrix,
  624. meq_inv = meq.inverse();
  625. m = svgedit.math.matrixMultiply( meq_inv, oldxlate, meq );
  626. tlist.removeItem(0);
  627. }
  628. // else if this child now has a matrix imposition (from a parent group)
  629. // we might be able to simplify
  630. else if (N == 1 && tlist.getItem(0).type == 1 && !angle) {
  631. // Remap all point-based elements
  632. m = svgedit.math.transformListToTransform(tlist).matrix;
  633. switch (selected.tagName) {
  634. case 'line':
  635. changes = $(selected).attr(['x1', 'y1', 'x2', 'y2']);
  636. case 'polyline':
  637. case 'polygon':
  638. changes.points = selected.getAttribute('points');
  639. if (changes.points) {
  640. var list = selected.points;
  641. var len = list.numberOfItems;
  642. changes.points = new Array(len);
  643. for (var i = 0; i < len; ++i) {
  644. var pt = list.getItem(i);
  645. changes.points[i] = {x:pt.x, y:pt.y};
  646. }
  647. }
  648. case 'path':
  649. changes.d = selected.getAttribute('d');
  650. operation = 1;
  651. tlist.clear();
  652. break;
  653. default:
  654. break;
  655. }
  656. }
  657. // if it was a rotation, put the rotate back and return without a command
  658. // (this function has zero work to do for a rotate())
  659. else {
  660. operation = 4; // rotation
  661. if (angle) {
  662. var newRot = svgroot.createSVGTransform();
  663. newRot.setRotate(angle, newcenter.x, newcenter.y);
  664. if (tlist.numberOfItems) {
  665. tlist.insertItemBefore(newRot, 0);
  666. } else {
  667. tlist.appendItem(newRot);
  668. }
  669. }
  670. if (tlist.numberOfItems == 0) {
  671. selected.removeAttribute('transform');
  672. }
  673. return null;
  674. }
  675. // if it was a translate or resize, we need to remap the element and absorb the xform
  676. if (operation == 1 || operation == 2 || operation == 3) {
  677. svgedit.coords.remapElement(selected, changes, m);
  678. } // if we are remapping
  679. // if it was a translate, put back the rotate at the new center
  680. if (operation == 2) {
  681. if (angle) {
  682. if (!svgedit.math.hasMatrixTransform(tlist)) {
  683. newcenter = {
  684. x: oldcenter.x + m.e,
  685. y: oldcenter.y + m.f
  686. };
  687. }
  688. var newRot = svgroot.createSVGTransform();
  689. newRot.setRotate(angle, newcenter.x, newcenter.y);
  690. if (tlist.numberOfItems) {
  691. tlist.insertItemBefore(newRot, 0);
  692. } else {
  693. tlist.appendItem(newRot);
  694. }
  695. }
  696. // We have special processing for tspans: Tspans are not transformable
  697. // but they can have x,y coordinates (sigh). Thus, if this was a translate,
  698. // on a text element, also translate any tspan children.
  699. if (selected.tagName == 'text') {
  700. var children = selected.childNodes;
  701. var c = children.length;
  702. while (c--) {
  703. var child = children.item(c);
  704. if (child.tagName == 'tspan') {
  705. var tspanChanges = {
  706. x: $(child).attr('x') || 0,
  707. y: $(child).attr('y') || 0
  708. };
  709. svgedit.coords.remapElement(child, tspanChanges, m);
  710. }
  711. }
  712. }
  713. }
  714. // [Rold][M][T][S][-T] became [Rold][M]
  715. // we want it to be [Rnew][M][Tr] where Tr is the
  716. // translation required to re-center it
  717. // Therefore, [Tr] = [M_inv][Rnew_inv][Rold][M]
  718. else if (operation == 3 && angle) {
  719. var m = svgedit.math.transformListToTransform(tlist).matrix;
  720. var roldt = svgroot.createSVGTransform();
  721. roldt.setRotate(angle, oldcenter.x, oldcenter.y);
  722. var rold = roldt.matrix;
  723. var rnew = svgroot.createSVGTransform();
  724. rnew.setRotate(angle, newcenter.x, newcenter.y);
  725. var rnew_inv = rnew.matrix.inverse();
  726. var m_inv = m.inverse();
  727. var extrat = svgedit.math.matrixMultiply(m_inv, rnew_inv, rold, m);
  728. svgedit.coords.remapElement(selected, changes, extrat);
  729. if (angle) {
  730. if (tlist.numberOfItems) {
  731. tlist.insertItemBefore(rnew, 0);
  732. } else {
  733. tlist.appendItem(rnew);
  734. }
  735. }
  736. }
  737. } // a non-group
  738. // if the transform list has been emptied, remove it
  739. if (tlist.numberOfItems == 0) {
  740. selected.removeAttribute('transform');
  741. }
  742. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(selected, initial));
  743. return batchCmd;
  744. };
  745. })();