Refactor canvas.convertToPath() internals to svgutils in preparation for getBBox performance improvements.

Two new functions in svgutils: convertToPath() and getBBoxOfElementAsPath().
Updated test/svgutils_test.html.
master
Flint O'Brien 2016-04-22 12:24:52 -04:00
parent a3dbb7c5af
commit 01ad9d7fdd
3 changed files with 480 additions and 161 deletions

View File

@ -6576,17 +6576,15 @@ this.setSegType = function(new_type) {
this.convertToPath = function(elem, getBBox) {
if (elem == null) {
var elems = selectedElements;
$.each(selectedElements, function(i, elem) {
$.each(elems, function(i, elem) {
if (elem) {canvas.convertToPath(elem);}
});
return;
}
if (!getBBox) {
var batchCmd = new svgedit.history.BatchCommand('Convert element to Path');
}
var attrs = getBBox?{}:{
if( getBBox) {
return svgedit.utilities.getBBoxOfElementAsPath( elem, addSvgElementFromJson, pathActions)
} else {
var attrs = {
'fill': cur_shape.fill,
'fill-opacity': cur_shape.fill_opacity,
'stroke': cur_shape.stroke,
@ -6598,157 +6596,7 @@ this.convertToPath = function(elem, getBBox) {
'opacity': cur_shape.opacity,
'visibility':'hidden'
};
// any attribute on the element not covered by the above
// TODO: make this list global so that we can properly maintain it
// TODO: what about @transform, @clip-rule, @fill-rule, etc?
$.each(['marker-start', 'marker-end', 'marker-mid', 'filter', 'clip-path'], function() {
if (elem.getAttribute(this)) {
attrs[this] = elem.getAttribute(this);
}
});
var path = addSvgElementFromJson({
'element': 'path',
'attr': attrs
});
var eltrans = elem.getAttribute('transform');
if (eltrans) {
path.setAttribute('transform', eltrans);
}
var id = elem.id;
var parent = elem.parentNode;
if (elem.nextSibling) {
parent.insertBefore(path, elem);
} else {
parent.appendChild(path);
}
var d = '';
var joinSegs = function(segs) {
$.each(segs, function(j, seg) {
var i;
var l = seg[0], pts = seg[1];
d += l;
for (i = 0; i < pts.length; i+=2) {
d += (pts[i] +','+pts[i+1]) + ' ';
}
});
};
// Possibly the cubed root of 6, but 1.81 works best
var num = 1.81;
var a, rx;
switch (elem.tagName) {
case 'ellipse':
case 'circle':
a = $(elem).attr(['rx', 'ry', 'cx', 'cy']);
var cx = a.cx, cy = a.cy;
rx = a.rx;
ry = a.ry;
if (elem.tagName == 'circle') {
rx = ry = $(elem).attr('r');
}
joinSegs([
['M',[(cx-rx),(cy)]],
['C',[(cx-rx),(cy-ry/num), (cx-rx/num),(cy-ry), (cx),(cy-ry)]],
['C',[(cx+rx/num),(cy-ry), (cx+rx),(cy-ry/num), (cx+rx),(cy)]],
['C',[(cx+rx),(cy+ry/num), (cx+rx/num),(cy+ry), (cx),(cy+ry)]],
['C',[(cx-rx/num),(cy+ry), (cx-rx),(cy+ry/num), (cx-rx),(cy)]],
['Z',[]]
]);
break;
case 'path':
d = elem.getAttribute('d');
break;
case 'line':
a = $(elem).attr(['x1', 'y1', 'x2', 'y2']);
d = 'M'+a.x1+','+a.y1+'L'+a.x2+','+a.y2;
break;
case 'polyline':
case 'polygon':
d = 'M' + elem.getAttribute('points');
break;
case 'rect':
var r = $(elem).attr(['rx', 'ry']);
rx = r.rx;
ry = r.ry;
var b = elem.getBBox();
var x = b.x, y = b.y, w = b.width, h = b.height;
num = 4 - num; // Why? Because!
if (!rx && !ry) {
// Regular rect
joinSegs([
['M',[x, y]],
['L',[x+w, y]],
['L',[x+w, y+h]],
['L',[x, y+h]],
['L',[x, y]],
['Z',[]]
]);
} else {
joinSegs([
['M',[x, y+ry]],
['C',[x, y+ry/num, x+rx/num, y, x+rx, y]],
['L',[x+w-rx, y]],
['C',[x+w-rx/num, y, x+w, y+ry/num, x+w, y+ry]],
['L',[x+w, y+h-ry]],
['C',[x+w, y+h-ry/num, x+w-rx/num, y+h, x+w-rx, y+h]],
['L',[x+rx, y+h]],
['C',[x+rx/num, y+h, x, y+h-ry/num, x, y+h-ry]],
['L',[x, y+ry]],
['Z',[]]
]);
}
break;
default:
path.parentNode.removeChild(path);
break;
}
if (d) {
path.setAttribute('d', d);
}
if (!getBBox) {
// Replace the current element with the converted one
// Reorient if it has a matrix
if (eltrans) {
var tlist = svgedit.transformlist.getTransformList(path);
if (svgedit.math.hasMatrixTransform(tlist)) {
pathActions.resetOrientation(path);
}
}
var nextSibling = elem.nextSibling;
batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(elem, nextSibling, parent));
batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(path));
clearSelection();
elem.parentNode.removeChild(elem);
path.setAttribute('id', id);
path.removeAttribute('visibility');
addToSelection([path], true);
addCommandToHistory(batchCmd);
} else {
// Get the correct BBox of the new path, then discard it
pathActions.resetOrientation(path);
var bb = false;
try {
bb = path.getBBox();
} catch(e) {
// Firefox fails
}
path.parentNode.removeChild(path);
return bb;
return svgedit.utilities.convertToPath( elem, attrs, addSvgElementFromJson, pathActions, clearSelection, addToSelection, svgedit.history, addCommandToHistory)
}
};

View File

@ -529,6 +529,245 @@ svgedit.utilities.getBBox = function(elem) {
return ret;
};
svgedit.utilities.getPathDFromSegments = function( pathSegments) {
var d = '';
$.each(pathSegments, function(j, seg) {
var i;
var l = seg[0], pts = seg[1];
d += l;
for (i = 0; i < pts.length; i+=2) {
d += (pts[i] +','+pts[i+1]) + ' ';
}
});
return d
}
svgedit.utilities.getPathDFromElement = function( elem) {
// Possibly the cubed root of 6, but 1.81 works best
var num = 1.81;
var d, a, rx, ry;
switch (elem.tagName) {
case 'ellipse':
case 'circle':
a = $(elem).attr(['rx', 'ry', 'cx', 'cy']);
var cx = a.cx, cy = a.cy;
rx = a.rx;
ry = a.ry;
if (elem.tagName == 'circle') {
rx = ry = $(elem).attr('r');
}
d = svgedit.utilities.getPathDFromSegments([
['M',[(cx-rx),(cy)]],
['C',[(cx-rx),(cy-ry/num), (cx-rx/num),(cy-ry), (cx),(cy-ry)]],
['C',[(cx+rx/num),(cy-ry), (cx+rx),(cy-ry/num), (cx+rx),(cy)]],
['C',[(cx+rx),(cy+ry/num), (cx+rx/num),(cy+ry), (cx),(cy+ry)]],
['C',[(cx-rx/num),(cy+ry), (cx-rx),(cy+ry/num), (cx-rx),(cy)]],
['Z',[]]
]);
break;
case 'path':
d = elem.getAttribute('d');
break;
case 'line':
a = $(elem).attr(['x1', 'y1', 'x2', 'y2']);
d = 'M'+a.x1+','+a.y1+'L'+a.x2+','+a.y2;
break;
case 'polyline':
d = 'M' + elem.getAttribute('points');
break;
case 'polygon':
d = 'M' + elem.getAttribute('points') + ' Z';
break;
case 'rect':
var r = $(elem).attr(['rx', 'ry']);
rx = r.rx;
ry = r.ry;
var b = elem.getBBox();
var x = b.x, y = b.y, w = b.width, h = b.height;
num = 4 - num; // Why? Because!
if (!rx && !ry) {
// Regular rect
d = svgedit.utilities.getPathDFromSegments([
['M',[x, y]],
['L',[x+w, y]],
['L',[x+w, y+h]],
['L',[x, y+h]],
['L',[x, y]],
['Z',[]]
]);
} else {
d = svgedit.utilities.getPathDFromSegments([
['M',[x, y+ry]],
['C',[x, y+ry/num, x+rx/num, y, x+rx, y]],
['L',[x+w-rx, y]],
['C',[x+w-rx/num, y, x+w, y+ry/num, x+w, y+ry]],
['L',[x+w, y+h-ry]],
['C',[x+w, y+h-ry/num, x+w-rx/num, y+h, x+w-rx, y+h]],
['L',[x+rx, y+h]],
['C',[x+rx/num, y+h, x, y+h-ry/num, x, y+h-ry]],
['L',[x, y+ry]],
['Z',[]]
]);
}
break;
default:
break;
}
return d;
};
svgedit.utilities.addAttributesForConvertToPath = function( elem, attrs) {
// TODO: make this list global so that we can properly maintain it
// TODO: what about @transform, @clip-rule, @fill-rule, etc?
$.each(['marker-start', 'marker-end', 'marker-mid', 'filter', 'clip-path'], function() {
if (elem.getAttribute(this)) {
attrs[this] = elem.getAttribute(this);
}
});
};
// Function: getBBoxOfElementAsPath
// Get the BBox of an element-as-path
//
// Parameters:
// elem - The DOM element to be probed
// addSvgElementFromJson - Function to add the path element to the current layer. See canvas.addSvgElementFromJso
// pathActions - If a transform exists, pathActions.resetOrientation() is used. See: canvas.pathActions.
//
// Returns:
// The resulting path's bounding box object.
svgedit.utilities.getBBoxOfElementAsPath = function(elem, addSvgElementFromJson, pathActions) {
var attrs = {}
// any attribute on the element not covered by the above
svgedit.utilities.addAttributesForConvertToPath( elem, attrs)
var path = addSvgElementFromJson({
'element': 'path',
'attr': attrs
});
var eltrans = elem.getAttribute('transform');
if (eltrans) {
path.setAttribute('transform', eltrans);
}
var id = elem.id;
var parent = elem.parentNode;
if (elem.nextSibling) {
parent.insertBefore(path, elem);
} else {
parent.appendChild(path);
}
var d = svgedit.utilities.getPathDFromElement( elem);
if( d)
path.setAttribute('d', d);
else
path.parentNode.removeChild(path);
// Get the correct BBox of the new path, then discard it
pathActions.resetOrientation(path);
var bb = false;
try {
bb = path.getBBox();
} catch(e) {
// Firefox fails
}
path.parentNode.removeChild(path);
return bb;
}
// Function: getBBoxOfElementAsPath
// Convert selected element to a path.
//
// Parameters:
// elem - The DOM element to be converted
// attrs - Apply attributes to new path. see canvas.convertToPath
// addSvgElementFromJson - Function to add the path element to the current layer. See canvas.addSvgElementFromJso
// pathActions - If a transform exists, pathActions.resetOrientation() is used. See: canvas.pathActions.
// clearSelection - see canvas.clearSelection
// addToSelection - see canvas.addToSelection
// history - see svgedit.history
// addCommandToHistory - see canvas.addCommandToHistory
//
// Returns:
// The resulting path's bounding box object.
svgedit.utilities.convertToPath = function(elem, attrs, addSvgElementFromJson, pathActions, clearSelection, addToSelection, history, addCommandToHistory) {
var batchCmd = new history.BatchCommand('Convert element to Path');
// any attribute on the element not covered by the above
// TODO: make this list global so that we can properly maintain it
// TODO: what about @transform, @clip-rule, @fill-rule, etc?
$.each(['marker-start', 'marker-end', 'marker-mid', 'filter', 'clip-path'], function() {
if (elem.getAttribute(this)) {
attrs[this] = elem.getAttribute(this);
}
});
var path = addSvgElementFromJson({
'element': 'path',
'attr': attrs
});
var eltrans = elem.getAttribute('transform');
if (eltrans) {
path.setAttribute('transform', eltrans);
}
var id = elem.id;
var parent = elem.parentNode;
if (elem.nextSibling) {
parent.insertBefore(path, elem);
} else {
parent.appendChild(path);
}
var d = svgedit.utilities.getPathDFromElement( elem);
if( d) {
path.setAttribute('d', d);
// Replace the current element with the converted one
// Reorient if it has a matrix
if (eltrans) {
var tlist = svgedit.transformlist.getTransformList(path);
if (svgedit.math.hasMatrixTransform(tlist)) {
pathActions.resetOrientation(path);
}
}
var nextSibling = elem.nextSibling;
batchCmd.addSubCommand(new history.RemoveElementCommand(elem, nextSibling, parent));
batchCmd.addSubCommand(new history.InsertElementCommand(path));
clearSelection();
elem.parentNode.removeChild(elem);
path.setAttribute('id', id);
path.removeAttribute('visibility');
addToSelection([path], true);
addCommandToHistory(batchCmd);
return path;
} else {
// the elem.tagName was not recognized, so no "d" attribute. Remove it, so we've haven't changed anything.
path.parentNode.removeChild(path);
return null;
}
};
// Function: svgedit.utilities.getRotationAngle
// Get the rotation angle of the given/selected DOM element
//

View File

@ -10,6 +10,7 @@
<script src='../editor/pathseg.js'></script>
<script src='../editor/browser.js'></script>
<script src='../editor/svgtransformlist.js'></script>
<script src='../editor/jquery-svg.js'></script> <!-- has $.attr() that takes an array . Used by svgedit.utilities.getPathDFromElement -->
<script src='../editor/svgutils.js'></script>
<script src='qunit/qunit.js'></script>
<script>
@ -21,9 +22,64 @@
}
};
var svg = document.createElementNS(svgedit.NS.SVG, 'svg');
function mockCreateSVGElement(jsonMap) {
var elem = document.createElementNS(svgedit.NS.SVG, jsonMap['element']);
for (var attr in jsonMap['attr']) {
elem.setAttribute(attr, jsonMap['attr'][attr]);
}
return elem;
}
function mockAddSvgElementFromJson( json) {
var elem = mockCreateSVGElement( json)
svgroot.appendChild( elem)
return elem
}
var mockPathActions = { resetOrientation: function () {}}
var mockHistorySubCommands = []
var mockHistory = {
BatchCommand: function() {
return {
addSubCommand: function( cmd) { mockHistorySubCommands.push(cmd)}
}
},
RemoveElementCommand: function(elem, nextSibling, parent) {
this.elem = elem;
this.nextSibling = nextSibling;
this.parent = parent
},
InsertElementCommand: function(path){
this.path = path
}
}
var mockCount = {
clearSelection: 0,
addToSelection: 0,
addCommandToHistory: 0
}
function mockClearSelection() { mockCount.clearSelection ++}
function mockAddToSelection() { mockCount.addToSelection ++}
function mockAddCommandToHistory() {mockCount.addCommandToHistory ++}
var svg = document.createElementNS(svgedit.NS.SVG, 'svg');
var sandbox = document.getElementById('sandbox');
var svgroot = mockCreateSVGElement({
'element': 'svg',
'attr': {'id': 'svgroot'}
});
sandbox.appendChild(svgroot);
module('svgedit.utilities', {
setup: function() {
mockHistorySubCommands = [];
mockCount.clearSelection = 0;
mockCount.addToSelection = 0;
mockCount.addCommandToHistory = 0;
},
teardown: function() {
}
});
module('svgedit.utilities');
test('Test svgedit.utilities package', function() {
expect(3);
@ -82,7 +138,7 @@
var convert = svgedit.utilities.convertToXMLReferences;
equals(convert('ABC'), 'ABC');
// equals(convert('ÀBC'), '&#192;BC');
// equals(convert('<EFBFBD>BC'), '&#192;BC');
});
test('Test svgedit.utilities.bboxToObj() function', function() {
@ -123,6 +179,181 @@
ok(bb.y && !isNaN(bb.y));
});
test("Test getPathDFromSegments", function() {
var d;
var getPathDFromSegments = svgedit.utilities.getPathDFromSegments;
var doc = svgedit.utilities.text2xml('<svg></svg>');
var path = doc.createElementNS(svgedit.NS.SVG, 'path');
path.setAttributeNS(null, 'd', 'm0,0l5,0l0,5l-5,0l0,-5z');
d = getPathDFromSegments( [
['M', [1, 2]],
['Z', []],
]);
equal( d, 'M1,2 Z');
d = getPathDFromSegments( [
['M', [1, 2]],
['M', [3, 4]],
['Z', []],
]);
equal( d, 'M1,2 M3,4 Z');
d = getPathDFromSegments( [
['M', [1, 2]],
['C', [3, 4, 5, 6]],
['Z', []],
]);
equal( d, 'M1,2 C3,4 5,6 Z');
});
test("Test getPathDFromElement", function() {
var getPathDFromElement = svgedit.utilities.getPathDFromElement;
var elem = mockCreateSVGElement({
'element': 'path',
'attr': { 'id': 'path', 'd': 'M0,1 Z'}
});
svgroot.appendChild( elem)
equal( getPathDFromElement( elem), 'M0,1 Z');
svgroot.removeChild( elem)
elem = mockCreateSVGElement({
'element': 'rect',
'attr': { 'id': 'rect', 'x': '0', 'y': '1', 'width': '5', 'height': '10'}
});
svgroot.appendChild( elem)
equal( getPathDFromElement( elem), 'M0,1 L5,1 L5,11 L0,11 L0,1 Z');
svgroot.removeChild( elem)
elem = mockCreateSVGElement({
'element': 'rect',
'attr': { 'id': 'roundrect', 'x': '0', 'y': '1', 'rx': '2', 'ry': '3', 'width': '10', 'height': '11'}
});
svgroot.appendChild( elem)
var closeEnough = new RegExp( 'M0,4 C0,2.3[0-9]* 0.9[0-9]*,1 2,1 L8,1 C9.0[0-9]*,1 10,2.3[0-9]* 10,4 L10,9 C10,10.6[0-9]* 9.08675799086758,12 8,12 L2,12 C0.9[0-9]*,12 0,10.6[0-9]* 0,9 L0,4 Z')
equal(closeEnough.test(getPathDFromElement( elem)), true);
svgroot.removeChild( elem)
elem = mockCreateSVGElement({
'element': 'line',
'attr': { 'id': 'line', 'x1': '0', 'y1': '1', 'x2': '5', 'y2': '6'}
});
svgroot.appendChild( elem)
equal( getPathDFromElement( elem), 'M0,1L5,6');
svgroot.removeChild( elem)
elem = mockCreateSVGElement({
'element': 'circle',
'attr': { 'id': 'circle', 'cx': '10', 'cy': '11', 'rx': '5', 'ry': '10'}
});
svgroot.appendChild( elem)
equal( getPathDFromElement( elem), 'M10,11 C10,11 10,11 10,11 C10,11 10,11 10,11 C10,11 10,11 10,11 C10,11 10,11 10,11 Z');
svgroot.removeChild( elem)
elem = mockCreateSVGElement({
'element': 'polyline',
'attr': { 'id': 'polyline', 'points': '0,1 5,1 5,11 0,11'}
});
svgroot.appendChild( elem)
equal( getPathDFromElement( elem), 'M0,1 5,1 5,11 0,11');
svgroot.removeChild( elem)
equal( getPathDFromElement( {tagName: 'something unknown'}), undefined);
});
test("Test getBBoxOfElementAsPath", function() {
function getBBoxOfElementAsPath( elem, addSvgElementFromJson, pathActions) {
var bbox = svgedit.utilities.getBBoxOfElementAsPath(elem, addSvgElementFromJson, pathActions);
return svgedit.utilities.bboxToObj( bbox) // need this for QUnit equal() to work.
}
var bbox;
var elem = mockCreateSVGElement({
'element': 'path',
'attr': { 'id': 'path', 'd': 'M0,1 Z'}
});
svgroot.appendChild( elem)
bbox = getBBoxOfElementAsPath(elem, mockAddSvgElementFromJson, mockPathActions)
deepEqual(bbox, {"x": 0, "y": 1, "width": 0, "height": 0 });
svgroot.removeChild( elem);
elem = mockCreateSVGElement({
'element': 'rect',
'attr': { 'id': 'rect', 'x': '0', 'y': '1', 'width': '5', 'height': '10'}
});
svgroot.appendChild( elem);
bbox = getBBoxOfElementAsPath( elem, mockAddSvgElementFromJson, mockPathActions)
deepEqual( bbox, { "x": 0, "y": 1, "width": 5, "height": 10});
svgroot.removeChild( elem);
elem = mockCreateSVGElement({
'element': 'line',
'attr': { 'id': 'line', 'x1': '0', 'y1': '1', 'x2': '5', 'y2': '6'}
});
svgroot.appendChild( elem);
bbox = getBBoxOfElementAsPath( elem, mockAddSvgElementFromJson, mockPathActions)
deepEqual( bbox, { "x": 0, "y": 1, "width": 5, "height": 5});
svgroot.removeChild( elem);
// TODO: test element with transform. Need resetOrientation above to be working or mock it.
});
test("Test convertToPath rect", function() {
var convertToPath = svgedit.utilities.convertToPath;
var attrs = {
'fill': 'red',
'stroke': 'white',
'stroke-width': '1',
'visibility':'hidden'
};
var elem = mockCreateSVGElement({
'element': 'rect',
'attr': { 'id': 'rect', 'x': '0', 'y': '1', 'width': '5', 'height': '10'}
});
svgroot.appendChild( elem)
var path = convertToPath( elem, attrs, mockAddSvgElementFromJson, mockPathActions, mockClearSelection, mockAddToSelection, mockHistory, mockAddCommandToHistory);
equal( path.getAttribute('d'), 'M0,1 L5,1 L5,11 L0,11 L0,1 Z');
equal( path.getAttribute('visibilituy'), null);
equal( path.id, 'rect');
equal( path.parentNode, svgroot);
equal( elem.parentNode, null);
equal( mockHistorySubCommands.length, 2);
equal( mockCount.clearSelection, 1);
equal( mockCount.addToSelection, 1);
equal( mockCount.addCommandToHistory, 1);
svgroot.removeChild( path);
});
test("Test convertToPath unknown element", function() {
var convertToPath = svgedit.utilities.convertToPath;
var attrs = {
'fill': 'red',
'stroke': 'white',
'stroke-width': '1',
'visibility':'hidden'
};
var elem = {
tagName: 'something unknown',
id: 'something-unknown',
getAttribute: function( attr) { return '';},
parentNode: svgroot
};
var path = convertToPath( elem, attrs, mockAddSvgElementFromJson, mockPathActions, mockClearSelection, mockAddToSelection, mockHistory, mockAddCommandToHistory);
equal( path, null);
equal( elem.parentNode, svgroot);
equal( mockHistorySubCommands.length, 0);
equal( mockCount.clearSelection, 0);
equal( mockCount.addToSelection, 0);
equal( mockCount.addCommandToHistory, 0);
});
});
</script>
</head>
@ -131,5 +362,6 @@
<h2 id='qunit-banner'></h2>
<h2 id='qunit-userAgent'></h2>
<ol id='qunit-tests'></ol>
<div id='sandbox'></div>
</body>
</html>