From c446a7185f6080ed8edced328f5c4fdc1dfb815a Mon Sep 17 00:00:00 2001 From: Bruno Heridet Date: Fri, 15 Feb 2013 15:51:58 +0000 Subject: [PATCH] added missing semicolons, radix and cleaned some style inconsistencies git-svn-id: http://svg-edit.googlecode.com/svn/trunk@2395 eee81c28-f429-11dd-99c0-75d572ba1ddd --- editor/svgcanvas.js | 1407 +++++++++++++++++++++---------------------- 1 file changed, 689 insertions(+), 718 deletions(-) diff --git a/editor/svgcanvas.js b/editor/svgcanvas.js index 1ad6e6ab..d64560b0 100644 --- a/editor/svgcanvas.js +++ b/editor/svgcanvas.js @@ -22,13 +22,13 @@ // 10) draw.js // 11) path.js -if(!window.console) { +if (!window.console) { window.console = {}; window.console.log = function(str) {}; window.console.dir = function(str) {}; } -if(window.opera) { +if (window.opera) { window.console.log = function(str) { opera.postError(str); }; window.console.dir = function(str) {}; } @@ -48,41 +48,40 @@ if(window.opera) { var proxied = jQuery.fn.attr, svgns = "http://www.w3.org/2000/svg"; jQuery.fn.attr = function(key, value) { var len = this.length; - if(!len) return proxied.apply(this, arguments); - for(var i=0; i= 0) { + if (elemNames.indexOf(elem.tagName) >= 0) { bb = good_bb = canvas.convertToPath(elem, true); - } else if(elem.tagName == 'rect') { + } else if (elem.tagName == 'rect') { // Look for radius var rx = elem.getAttribute('rx'); var ry = elem.getAttribute('ry'); - if(rx || ry) { + if (rx || ry) { bb = good_bb = canvas.convertToPath(elem, true); } } - if(!good_bb) { + if (!good_bb) { // Must use clone else FF freaks out var clone = elem.cloneNode(true); var g = document.createElementNS(svgns, "g"); @@ -699,7 +697,6 @@ getStrokedBBox = this.getStrokedBBox = function(elems) { parent.removeChild(g); } - // Old method: Works by giving the rotated BBox, // this is (unfortunately) what Opera and Safari do // natively when getting the BBox of the parent group @@ -742,16 +739,16 @@ getStrokedBBox = this.getStrokedBBox = function(elems) { var full_bb; $.each(elems, function() { - if(full_bb) return; - if(!this.parentNode) return; + if (full_bb) return; + if (!this.parentNode) return; full_bb = getCheckedBBox(this); }); // This shouldn't ever happen... - if(full_bb == null) return null; + if (full_bb == null) return null; // full_bb doesn't include the stoke, so this does no good! -// if(elems.length == 1) return full_bb; +// if (elems.length == 1) return full_bb; var max_x = full_bb.x + full_bb.width; var max_y = full_bb.y + full_bb.height; @@ -766,11 +763,11 @@ getStrokedBBox = this.getStrokedBBox = function(elems) { offset += sw/2; } return offset; - } + }; var bboxes = []; $.each(elems, function(i, elem) { var cur_bb = getCheckedBBox(elem); - if(cur_bb) { + if (cur_bb) { var offset = getOffset(elem); min_x = Math.min(min_x, cur_bb.x - offset); min_y = Math.min(min_y, cur_bb.y - offset); @@ -794,7 +791,7 @@ getStrokedBBox = this.getStrokedBBox = function(elems) { full_bb.width = max_x - min_x; full_bb.height = max_y - min_y; return full_bb; -} +}; // Function: getVisibleElements // Get all elements that have a BBox (excludes , , etc). @@ -807,7 +804,7 @@ getStrokedBBox = this.getStrokedBBox = function(elems) { // Returns: // An array with all "visible" elements. var getVisibleElements = this.getVisibleElements = function(parent) { - if(!parent) parent = $(svgcontent).children(); // Prevent layers from being included + if (!parent) parent = $(svgcontent).children(); // Prevent layers from being included var contentElems = []; $(parent).children().each(function(i, elem) { @@ -833,7 +830,7 @@ var getVisibleElements = this.getVisibleElements = function(parent) { // * elem - The element // * bbox - The element's BBox as retrieved from getStrokedBBox var getVisibleElementsAndBBoxes = this.getVisibleElementsAndBBoxes = function(parent) { - if(!parent) parent = $(svgcontent).children(); // Prevent layers from being included + if (!parent) parent = $(svgcontent).children(); // Prevent layers from being included var contentElems = []; $(parent).children().each(function(i, elem) { @@ -855,7 +852,7 @@ var groupSvgElem = this.groupSvgElem = function(elem) { var g = document.createElementNS(svgns, "g"); elem.parentNode.replaceChild(g, elem); $(g).append(elem).data('gsvg', elem)[0].id = getNextId(); -} +}; // Function: copyElem // Create a clone of an element, updating its ID and its children's IDs when needed @@ -878,7 +875,7 @@ var copyElem = function(el) { // Opera's "d" value needs to be reset for Opera/Win/non-EN // Also needed for webkit (else does not keep curved segments on clone) - if(svgedit.browser.isWebkit() && el.nodeName == 'path') { + if (svgedit.browser.isWebkit() && el.nodeName == 'path') { var fixed_d = pathActions.convertPath(el); new_el.setAttribute('d', fixed_d); } @@ -897,14 +894,12 @@ var copyElem = function(el) { } }); - if($(el).data('gsvg')) { + if ($(el).data('gsvg')) { $(new_el).data('gsvg', new_el.firstChild); - } else if($(el).data('symbol')) { + } else if ($(el).data('symbol')) { var ref = $(el).data('symbol'); $(new_el).data('ref', ref).data('symbol', ref); - } - - else if(new_el.tagName == 'image') { + } else if (new_el.tagName == 'image') { preventClickDefault(new_el); } return new_el; @@ -943,7 +938,7 @@ var getId, getNextId, call; // Return: // The previous event c.bind = function(event, f) { - var old = events[event]; + var old = events[event]; events[event] = f; return old; }; @@ -977,15 +972,15 @@ this.prepareSvg = function(newDoc) { // Parameters: // elem - The (text) DOM element to clone var ffClone = function(elem) { - if(!svgedit.browser.isGecko()) return elem; - var clone = elem.cloneNode(true) + if (!svgedit.browser.isGecko()) return elem; + var clone = elem.cloneNode(true); elem.parentNode.insertBefore(clone, elem); elem.parentNode.removeChild(elem); selectorManager.releaseSelector(elem); selectedElements[0] = clone; selectorManager.requestSelector(clone).showGrips(true); return clone; -} +}; // this.each is deprecated, if any extension used this it can be recreated by doing this: @@ -1024,13 +1019,12 @@ this.setRotationAngle = function(val, preventUndo) { var center = svgedit.math.transformPoint(cx,cy,svgedit.math.transformListToTransform(tlist).matrix); var R_nc = svgroot.createSVGTransform(); R_nc.setRotate(val, center.x, center.y); - if(tlist.numberOfItems) { + if (tlist.numberOfItems) { tlist.insertItemBefore(R_nc, 0); } else { tlist.appendItem(R_nc); } - } - else if (tlist.numberOfItems == 0) { + } else if (tlist.numberOfItems == 0) { elem.removeAttribute("transform"); } @@ -1043,7 +1037,7 @@ this.setRotationAngle = function(val, preventUndo) { call("changed", selectedElements); } var pointGripContainer = svgedit.utilities.getElem("pathpointgrip_container"); -// if(elem.nodeName == "path" && pointGripContainer) { +// if (elem.nodeName == "path" && pointGripContainer) { // pathActions.setPointContainerTransform(elem.getAttribute("transform")); // } var selector = selectorManager.requestSelector(selectedElements[0]); @@ -1059,9 +1053,9 @@ var recalculateAllSelectedDimensions = this.recalculateAllSelectedDimensions = f var batchCmd = new BatchCommand(text); var i = selectedElements.length; - while(i--) { + while (i--) { var elem = selectedElements[i]; -// if(svgedit.utilities.getRotationAngle(elem) && !svgedit.math.hasMatrixTransform(getTransformList(elem))) continue; +// if (svgedit.utilities.getRotationAngle(elem) && !svgedit.math.hasMatrixTransform(getTransformList(elem))) continue; var cmd = recalculateDimensions(elem); if (cmd) { batchCmd.addSubCommand(cmd); @@ -1097,20 +1091,20 @@ var remapElement = this.remapElement = function(selected,changes,m) { scaleh = function(h) { return m.d*h; }, doSnapping = curConfig.gridSnapping && selected.parentNode.parentNode.localName === "svg", finishUp = function() { - if(doSnapping) for(var o in changes) changes[o] = snapToGrid(changes[o]); + if (doSnapping) for (var o in changes) changes[o] = snapToGrid(changes[o]); assignAttributes(selected, changes, 1000, true); } box = svgedit.utilities.getBBox(selected); - for(var i = 0; i < 2; i++) { + for (var i = 0; i < 2; i++) { var type = i === 0 ? 'fill' : 'stroke'; var attrVal = selected.getAttribute(type); - if(attrVal && attrVal.indexOf('url(') === 0) { - if(m.a < 0 || m.d < 0) { + if (attrVal && attrVal.indexOf('url(') === 0) { + if (m.a < 0 || m.d < 0) { var grad = svgedit.utilities.getRefElem(attrVal); var newgrad = grad.cloneNode(true); - if(m.a < 0) { + if (m.a < 0) { //flip x var x1 = newgrad.getAttribute('x1'); var x2 = newgrad.getAttribute('x2'); @@ -1118,7 +1112,7 @@ var remapElement = this.remapElement = function(selected,changes,m) { newgrad.setAttribute('x2', -(x2 - 1)); } - if(m.d < 0) { + if (m.d < 0) { //flip y var y1 = newgrad.getAttribute('y1'); var y2 = newgrad.getAttribute('y2'); @@ -1131,7 +1125,7 @@ var remapElement = this.remapElement = function(selected,changes,m) { } // Not really working :( -// if(selected.tagName === 'path') { +// if (selected.tagName === 'path') { // reorientGrads(selected, m); // } } @@ -1139,7 +1133,7 @@ var remapElement = this.remapElement = function(selected,changes,m) { var elName = selected.tagName; - if(elName === "g" || elName === "text" || elName == "tspan" || elName === "use") { + if (elName === "g" || elName === "text" || elName == "tspan" || elName === "use") { // if it was a translate, then just update x,y if (m.a == 1 && m.b == 0 && m.c == 0 && m.d == 1 && (m.e != 0 || m.f != 0) ) @@ -1164,8 +1158,7 @@ var remapElement = this.remapElement = function(selected,changes,m) { // <tspan x="100" y="100">...</tspan> // </text> - } - else { + } else { // we just absorb all matrices into the element and don't do any remapping var chlist = svgedit.transformlist.getTransformList(selected); var mt = svgroot.createSVGTransform(); @@ -1184,7 +1177,7 @@ var remapElement = this.remapElement = function(selected,changes,m) { case "image": // Allow images to be inverted (give them matrix when flipped) - if(elName === 'image' && (m.a < 0 || m.d < 0)) { + if (elName === 'image' && (m.a < 0 || m.d < 0)) { // Convert to matrix var chlist = svgedit.transformlist.getTransformList(selected); var mt = svgroot.createSVGTransform(); @@ -1224,7 +1217,7 @@ var remapElement = this.remapElement = function(selected,changes,m) { var w = tbox.tr.x - tbox.tl.x, h = tbox.bl.y - tbox.tl.y; changes.r = Math.min(w/2, h/2); - if(changes.r) changes.r = Math.abs(changes.r); + if (changes.r) changes.r = Math.abs(changes.r); finishUp(); break; case "line": @@ -1241,7 +1234,7 @@ var remapElement = this.remapElement = function(selected,changes,m) { break; case "g": var gsvg = $(selected).data('gsvg'); - if(gsvg) { + if (gsvg) { assignAttributes(gsvg, changes, 1000, true); } break; @@ -1310,8 +1303,7 @@ var remapElement = this.remapElement = function(selected,changes,m) { seg.y2 = pt2.y; seg.r1 = scalew(seg.r1), seg.r2 = scaleh(seg.r2); - } - else { // relative + } else { // relative seg.x = scalew(seg.x); seg.y = scaleh(seg.y); seg.x1 = scalew(seg.x1); @@ -1428,7 +1420,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { } } // End here if all it has is a rotation - if(tlist.numberOfItems === 1 && + if (tlist.numberOfItems === 1 && svgedit.utilities.getRotationAngle(selected)) return null; } @@ -1446,11 +1438,11 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { var xform = tlist.getItem(k); if (xform.type === 1) { mxs.push([xform.matrix, k]); - } else if(mxs.length) { + } else if (mxs.length) { mxs = []; } } - if(mxs.length === 2) { + if (mxs.length === 2) { var m_new = svgroot.createSVGTransformFromMatrix(svgedit.math.matrixMultiply(mxs[1][0], mxs[0][0])); tlist.removeItem(mxs[0][1]); tlist.removeItem(mxs[1][1]); @@ -1459,7 +1451,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { // combine matrix + translate k = tlist.numberOfItems; - if(k >= 2 && tlist.getItem(k-2).type === 1 && tlist.getItem(k-1).type === 2) { + if (k >= 2 && tlist.getItem(k-2).type === 1 && tlist.getItem(k-1).type === 2) { var mt = svgroot.createSVGTransform(); var m = svgedit.math.matrixMultiply( @@ -1482,7 +1474,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { case 'path': break; default: - if( + if ( (tlist.numberOfItems === 1 && tlist.getItem(0).type === 1) || (tlist.numberOfItems === 2 && tlist.getItem(0).type === 1 && tlist.getItem(0).type === 4) ) { @@ -1537,12 +1529,12 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { break; } // switch on element type to get initial values - if(attrs.length) { + if (attrs.length) { changes = $(selected).attr(attrs); $.each(changes, function(attr, val) { changes[attr] = svgedit.units.convertToNum(attr, val); }); - } else if(gsvg) { + } else if (gsvg) { // GSVG exception changes = { x: $(gsvg).attr('x') || 0, @@ -1559,7 +1551,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { }); } // save the start transform value too - initial["transform"] = start_transform ? start_transform : ""; + initial.transform = start_transform ? start_transform : ""; // if it's a regular group, we have special processing to flatten transforms if ((selected.tagName == "g" && !gsvg) || selected.tagName == "a") { @@ -1569,8 +1561,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { box.y+box.height/2, svgedit.math.transformListToTransform(tlist).matrix), m = svgroot.createSVGMatrix(); - - + // temporarily strip off the rotate and save the old center var gangle = svgedit.utilities.getRotationAngle(selected); if (gangle) { @@ -1597,7 +1588,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { operation = 0, N = tlist.numberOfItems; - if(N) { + if (N) { var first_m = tlist.getItem(0).matrix; } @@ -1628,8 +1619,8 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { var m = svgedit.math.transformListToTransform(childTlist).matrix; // Convert a matrix to a scale if applicable -// if(svgedit.math.hasMatrixTransform(childTlist) && childTlist.numberOfItems == 1) { -// if(m.b==0 && m.c==0 && m.e==0 && m.f==0) { +// if (svgedit.math.hasMatrixTransform(childTlist) && childTlist.numberOfItems == 1) { +// if (m.b==0 && m.c==0 && m.e==0 && m.f==0) { // childTlist.removeItem(0); // var translateOrigin = svgroot.createSVGTransform(), // scale = svgroot.createSVGTransform(), @@ -1647,7 +1638,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { var old_start_transform = start_transform; var childxforms = []; start_transform = child.getAttribute("transform"); - if(angle || svgedit.math.hasMatrixTransform(childTlist)) { + if (angle || svgedit.math.hasMatrixTransform(childTlist)) { var e2t = svgroot.createSVGTransform(); e2t.setMatrix(svgedit.math.matrixMultiply(tm, sm, tmn, m)); childTlist.clear(); @@ -1698,7 +1689,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { // var u = uses.length; // while (u--) { // var useElem = uses.item(u); -// if(href == svgedit.utilities.getHref(useElem)) { +// if (href == svgedit.utilities.getHref(useElem)) { // var usexlate = svgroot.createSVGTransform(); // usexlate.setTranslate(-tx,-ty); // svgedit.transformlist.getTransformList(useElem).insertItemBefore(usexlate,0); @@ -1712,9 +1703,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { tlist.removeItem(N-1); tlist.removeItem(N-2); tlist.removeItem(N-3); - } - else if (N >= 3 && tlist.getItem(N-1).type == 1) - { + } else if (N >= 3 && tlist.getItem(N-1).type == 1) { operation = 3; // scale m = svgedit.math.transformListToTransform(tlist).matrix; var e2t = svgroot.createSVGTransform(); @@ -1749,10 +1738,10 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { if (child.nodeType == 1) { // Check if child has clip-path - if(child.getAttribute('clip-path')) { + if (child.getAttribute('clip-path')) { // tx, ty var attr = child.getAttribute('clip-path'); - if(clipPaths_done.indexOf(attr) === -1) { + if (clipPaths_done.indexOf(attr) === -1) { updateClipPath(attr, tx, ty); clipPaths_done.push(attr); } @@ -1766,7 +1755,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { if (childTlist) { var newxlate = svgroot.createSVGTransform(); newxlate.setTranslate(tx,ty); - if(childTlist.numberOfItems) { + if (childTlist.numberOfItems) { childTlist.insertItemBefore(newxlate, 0); } else { childTlist.appendItem(newxlate); @@ -1780,7 +1769,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { var u = uses.length; while (u--) { var useElem = uses.item(u); - if(href == svgedit.utilities.getHref(useElem)) { + if (href == svgedit.utilities.getHref(useElem)) { var usexlate = svgroot.createSVGTransform(); usexlate.setTranslate(-tx,-ty); svgedit.transformlist.getTransformList(useElem).insertItemBefore(usexlate,0); @@ -1839,7 +1828,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { if (gangle) { var newRot = svgroot.createSVGTransform(); newRot.setRotate(gangle,newcenter.x,newcenter.y); - if(tlist.numberOfItems) { + if (tlist.numberOfItems) { tlist.insertItemBefore(newRot, 0); } else { tlist.appendItem(newRot); @@ -1861,7 +1850,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { var newRot = svgroot.createSVGTransform(); newRot.setRotate(gangle,newcenter.x,newcenter.y); - if(tlist.numberOfItems) { + if (tlist.numberOfItems) { tlist.insertItemBefore(newRot, 0); } else { tlist.appendItem(newRot); @@ -1896,7 +1885,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { var childTlist = svgedit.transformlist.getTransformList(child); var newxlate = svgroot.createSVGTransform(); newxlate.setTranslate(tx,ty); - if(childTlist.numberOfItems) { + if (childTlist.numberOfItems) { childTlist.insertItemBefore(newxlate, 0); } else { childTlist.appendItem(newxlate); @@ -1909,7 +1898,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { } if (gangle) { - if(tlist.numberOfItems) { + if (tlist.numberOfItems) { tlist.insertItemBefore(rnew, 0); } else { tlist.appendItem(rnew); @@ -1928,7 +1917,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { // TODO: Figure out how to get BBox from these elements in case they // have a rotation transform - if(!box && selected.tagName != 'path') return null; + if (!box && selected.tagName != 'path') return null; var m = svgroot.createSVGMatrix(), @@ -1966,14 +1955,14 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { // Check if it has a gradient with userSpaceOnUse, in which case // adjust it by recalculating the matrix transform. // TODO: Make this work in Webkit using svgedit.transformlist.SVGTransformList - if(!svgedit.browser.isWebkit()) { + if (!svgedit.browser.isWebkit()) { var fill = selected.getAttribute('fill'); - if(fill && fill.indexOf('url(') === 0) { + if (fill && fill.indexOf('url(') === 0) { var paint = getRefElem(fill); var type = 'pattern'; - if(paint.tagName !== type) type = 'gradient'; + if (paint.tagName !== type) type = 'gradient'; var attrVal = paint.getAttribute(type + 'Units'); - if(attrVal === 'userSpaceOnUse') { + if (attrVal === 'userSpaceOnUse') { //Update the userSpaceOnUse element m = svgedit.math.transformListToTransform(tlist).matrix; var gtlist = svgedit.transformlist.getTransformList(paint); @@ -2003,7 +1992,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { tlist.removeItem(N-3); } // if we had [T][S][-T][M], then this was a skewed element being resized // Thus, we simply combine it all into one matrix - else if(N == 4 && tlist.getItem(N-1).type == 1) { + else if (N == 4 && tlist.getItem(N-1).type == 1) { operation = 3; // scale m = svgedit.math.transformListToTransform(tlist).matrix; var e2t = svgroot.createSVGTransform(); @@ -2037,7 +2026,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { case 'polyline': case 'polygon': changes.points = selected.getAttribute("points"); - if(changes.points) { + if (changes.points) { var list = selected.points; var len = list.numberOfItems; changes.points = new Array(len); @@ -2063,7 +2052,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { var newRot = svgroot.createSVGTransform(); newRot.setRotate(angle,newcenter.x,newcenter.y); - if(tlist.numberOfItems) { + if (tlist.numberOfItems) { tlist.insertItemBefore(newRot, 0); } else { tlist.appendItem(newRot); @@ -2083,7 +2072,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { // if it was a translate, put back the rotate at the new center if (operation == 2) { if (angle) { - if(!svgedit.math.hasMatrixTransform(tlist)) { + if (!svgedit.math.hasMatrixTransform(tlist)) { newcenter = { x: oldcenter.x + m.e, y: oldcenter.y + m.f @@ -2091,7 +2080,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { } var newRot = svgroot.createSVGTransform(); newRot.setRotate(angle, newcenter.x, newcenter.y); - if(tlist.numberOfItems) { + if (tlist.numberOfItems) { tlist.insertItemBefore(newRot, 0); } else { tlist.appendItem(newRot); @@ -2115,7 +2104,7 @@ var recalculateDimensions = this.recalculateDimensions = function(selected) { remapElement(selected,changes,extrat); if (angle) { - if(tlist.numberOfItems) { + if (tlist.numberOfItems) { tlist.insertItemBefore(rnew, 0); } else { tlist.appendItem(rnew); @@ -2154,7 +2143,7 @@ var clearSelection = this.clearSelection = function(noCall) { } // selectedBBoxes[0] = null; } - if(!noCall) call("selected", selectedElements); + if (!noCall) call("selected", selectedElements); }; // TODO: do we need to worry about selectedBBoxes here? @@ -2184,7 +2173,7 @@ var addToSelection = this.addToSelection = function(elemsToAdd, showGrips) { var elem = elemsToAdd[i]; if (!elem || !svgedit.utilities.getBBox(elem)) continue; - if(elem.tagName === 'a' && elem.childNodes.length === 1) { + if (elem.tagName === 'a' && elem.childNodes.length === 1) { // Make "a" element's child be the selected element elem = elem.firstChild; } @@ -2217,15 +2206,16 @@ var addToSelection = this.addToSelection = function(elemsToAdd, showGrips) { // See: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-compareDocumentPosition selectedElements.sort(function(a,b) { - if(a && b && a.compareDocumentPosition) { + if (a && b && a.compareDocumentPosition) { return 3 - (b.compareDocumentPosition(a) & 6); - } else if(a == null) { + } + if (a == null) { return 1; } }); // Make sure first elements are not null - while(selectedElements[0] == null) selectedElements.shift(0); + while (selectedElements[0] == null) selectedElements.shift(0); }; // Function: selectOnly() @@ -2236,7 +2226,7 @@ var addToSelection = this.addToSelection = function(elemsToAdd, showGrips) { var selectOnly = this.selectOnly = function(elems, showGrips) { clearSelection(true); addToSelection(elems, showGrips); -} +}; // TODO: could use slice here to make this faster? // TODO: should the 'selected' handler @@ -2305,21 +2295,21 @@ var getMouseTarget = this.getMouseTarget = function(evt) { { while (mouse_target.nodeName != "foreignObject") { mouse_target = mouse_target.parentNode; - if(!mouse_target) return svgroot; + if (!mouse_target) return svgroot; } } // Get the desired mouse_target with jQuery selector-fu // If it's root-like, select the root var current_layer = getCurrentDrawing().getCurrentLayer(); - if([svgroot, container, svgcontent, current_layer].indexOf(mouse_target) >= 0) { + if ([svgroot, container, svgcontent, current_layer].indexOf(mouse_target) >= 0) { return svgroot; } var $target = $(mouse_target); // If it's a selection grip, return the grip parent - if($target.closest('#selectorParentGroup').length) { + if ($target.closest('#selectorParentGroup').length) { // While we could instead have just returned mouse_target, // this makes it easier to indentify as being a selector grip return selectorManager.selectorParentGroup; @@ -2357,27 +2347,27 @@ var getMouseTarget = this.getMouseTarget = function(evt) { maxx: null, maxy: null }, - sumDistance= 0, + sumDistance = 0, controllPoint2 = {x:0, y:0}, controllPoint1 = {x:0, y:0}, - start= {x:0, y:0}, - end= {x:0, y:0}, + start = {x:0, y:0}, + end = {x:0, y:0}, parameter, nextParameter, - bSpline= {x:0, y:0}, - nextPos= {x:0, y:0}, - THRESHOLD_DIST=0.8, - STEP_COUNT=10; + bSpline = {x:0, y:0}, + nextPos = {x:0, y:0}, + THRESHOLD_DIST = 0.8, + STEP_COUNT = 10; var getBsplinePoint = function(t) { var spline = {x:0, y:0}, - p0 = controllPoint2, - p1 = controllPoint1, - p2 = start, - p3 = end, - S = 1.0 / 6.0, - t2 = t * t, - t3 = t2 * t; + p0 = controllPoint2, + p1 = controllPoint1, + p2 = start, + p3 = end, + S = 1.0 / 6.0, + t2 = t * t, + t3 = t2 * t; var m = Array ( @@ -2402,33 +2392,32 @@ var getMouseTarget = this.getMouseTarget = function(evt) { x:spline.x, y:spline.y }; - } + }; // - when we are in a create mode, the element is added to the canvas // but the action is not recorded until mousing up // - when we are in select mode, select the element, remember the position // and do nothing else var mouseDown = function(evt) { - if(canvas.spaceKey || evt.button === 1) return; + if (canvas.spaceKey || evt.button === 1) return; var right_click = evt.button === 2; - if(evt.altKey) { // duplicate when dragging + if (evt.altKey) { // duplicate when dragging svgCanvas.cloneSelectedElements(0,0); } root_sctm = svgcontent.getScreenCTM().inverse(); - - // Firefox issue 1046 - if(current_zoom != 1 && root_sctm.a == 1) - { - matrix_e = root_sctm.e / current_zoom - root_sctm.e; - matrix_f = root_sctm.f / current_zoom - root_sctm.f; - matrix_scale = 1/current_zoom; - root_sctm = svgcontent.getScreenCTM().inverse() - .translate(matrix_e, matrix_f) - .scale(matrix_scale); - } + + // Firefox issue 1046 + if (current_zoom != 1 && root_sctm.a == 1) { + matrix_e = root_sctm.e / current_zoom - root_sctm.e; + matrix_f = root_sctm.f / current_zoom - root_sctm.f; + matrix_scale = 1/current_zoom; + root_sctm = svgcontent.getScreenCTM().inverse() + .translate(matrix_e, matrix_f) + .scale(matrix_scale); + } var pt = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm ), mouse_x = pt.x * current_zoom, @@ -2436,13 +2425,13 @@ var getMouseTarget = this.getMouseTarget = function(evt) { evt.preventDefault(); - if(right_click) { + if (right_click) { current_mode = "select"; lastClickPoint = pt; } // This would seem to be unnecessary... -// if(['select', 'resize'].indexOf(current_mode) == -1) { +// if (['select', 'resize'].indexOf(current_mode) == -1) { // setGradient(); // } @@ -2450,7 +2439,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { y = mouse_y / current_zoom, mouse_target = getMouseTarget(evt); - if(mouse_target.tagName === 'a' && mouse_target.childNodes.length === 1) { + if (mouse_target.tagName === 'a' && mouse_target.childNodes.length === 1) { mouse_target = mouse_target.firstChild; } @@ -2458,7 +2447,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var real_x = r_start_x = start_x = x; var real_y = r_start_y = start_y = y; - if(curConfig.gridSnapping){ + if (curConfig.gridSnapping){ x = snapToGrid(x); y = snapToGrid(y); start_x = snapToGrid(start_x); @@ -2476,7 +2465,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { current_mode = "rotate"; } // resizing - else if(griptype == "resize") { + else if (griptype == "resize") { current_mode = "resize"; current_resize_mode = elData(grip, "dir"); } @@ -2489,7 +2478,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { case "select": started = true; current_resize_mode = "none"; - if(right_click) started = false; + if (right_click) started = false; if (mouse_target != svgroot) { // if this element is not yet selected, clear selection and select it @@ -2506,21 +2495,20 @@ var getMouseTarget = this.getMouseTarget = function(evt) { } // else if it's a path, go into pathedit mode in mouseup - if(!right_click) { + if (!right_click) { // insert a dummy transform so if the element(s) are moved it will have // a transform to use for its translate for (var i = 0; i < selectedElements.length; ++i) { - if(selectedElements[i] == null) continue; + if (selectedElements[i] == null) continue; var slist = svgedit.transformlist.getTransformList(selectedElements[i]); - if(slist.numberOfItems) { + if (slist.numberOfItems) { slist.insertItemBefore(svgroot.createSVGTransform(), 0); } else { slist.appendItem(svgroot.createSVGTransform()); } } } - } - else if(!right_click){ + } else if (!right_click){ clearSelection(); current_mode = "multiselect"; if (rubberBox == null) { @@ -2573,7 +2561,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // we can translate,scale,translate in mousemove var pos = svgedit.utilities.getRotationAngle(mouse_target)?1:0; - if(svgedit.math.hasMatrixTransform(tlist)) { + if (svgedit.math.hasMatrixTransform(tlist)) { tlist.insertItemBefore(svgroot.createSVGTransform(), pos); tlist.insertItemBefore(svgroot.createSVGTransform(), pos); tlist.insertItemBefore(svgroot.createSVGTransform(), pos); @@ -2582,29 +2570,29 @@ var getMouseTarget = this.getMouseTarget = function(evt) { tlist.appendItem(svgroot.createSVGTransform()); tlist.appendItem(svgroot.createSVGTransform()); - if(svgedit.browser.supportsNonScalingStroke()) { + if (svgedit.browser.supportsNonScalingStroke()) { // Handle crash for newer Chrome and Safari 6 (Mobile and Desktop): // https://code.google.com/p/svg-edit/issues/detail?id=904 // Chromium issue: https://code.google.com/p/chromium/issues/detail?id=114625 // TODO: Remove this workaround once vendor fixes the issue var isWebkit = svgedit.browser.isWebkit(); - if(isWebkit) { + if (isWebkit) { var delayedStroke = function(ele) { var _stroke = ele.getAttributeNS(null, 'stroke'); ele.removeAttributeNS(null, 'stroke'); //Re-apply stroke after delay. Anything higher than 1 seems to cause flicker - setTimeout(function() { ele.setAttributeNS(null, 'stroke', _stroke) }, 0); - } + setTimeout(function() { ele.setAttributeNS(null, 'stroke', _stroke); }, 0); + }; } mouse_target.style.vectorEffect = 'non-scaling-stroke'; - if(isWebkit) delayedStroke(mouse_target); + if (isWebkit) delayedStroke(mouse_target); var all = mouse_target.getElementsByTagName('*'), len = all.length; - for(var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) { all[i].style.vectorEffect = 'non-scaling-stroke'; - if(isWebkit) delayedStroke(all[i]); + if (isWebkit) delayedStroke(all[i]); } } } @@ -2672,7 +2660,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { break; case "line": started = true; - var stroke_w = cur_shape.stroke_width == 0?1:cur_shape.stroke_width; + var stroke_w = cur_shape.stroke_width == 0 ? 1 : cur_shape.stroke_width; addSvgElementFromJson({ "element": "line", "curStyles": true, @@ -2775,7 +2763,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { }, true); $.each(ext_result, function(i, r) { - if(r && r.started) { + if (r && r.started) { started = true; } }); @@ -2786,7 +2774,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var mouseMove = function(evt) { if (!started) return; - if(evt.button === 1 || canvas.spaceKey) return; + if (evt.button === 1 || canvas.spaceKey) return; var selected = selectedElements[0], pt = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm ), @@ -2797,7 +2785,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var real_x = x = mouse_x / current_zoom; var real_y = y = mouse_y / current_zoom; - if(curConfig.gridSnapping){ + if (curConfig.gridSnapping){ x = snapToGrid(x); y = snapToGrid(y); } @@ -2814,12 +2802,12 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var dx = x - start_x; var dy = y - start_y; - if(curConfig.gridSnapping){ + if (curConfig.gridSnapping){ dx = snapToGrid(dx); dy = snapToGrid(dy); } - if(evt.shiftKey) { var xya = svgedit.math.snapToAngle(start_x,start_y,x,y); x=xya.x; y=xya.y; } + if (evt.shiftKey) { var xya = svgedit.math.snapToAngle(start_x,start_y,x,y); x=xya.x; y=xya.y; } if (dx != 0 || dy != 0) { var len = selectedElements.length; @@ -2841,7 +2829,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // This results in unexpected behaviour xform.setTranslate(dx,dy); - if(tlist.numberOfItems) { + if (tlist.numberOfItems) { tlist.replaceItem(xform, 0); } else { tlist.appendItem(xform); @@ -2877,8 +2865,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var ind = newList.indexOf(selectedElements[i]); if (ind == -1) { elemsToRemove.push(selectedElements[i]); - } - else { + } else { newList[ind] = null; } } @@ -2903,7 +2890,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { left=box.x, top=box.y, width=box.width, height=box.height, dx=(x-start_x), dy=(y-start_y); - if(curConfig.gridSnapping){ + if (curConfig.gridSnapping){ dx = snapToGrid(dx); dy = snapToGrid(dy); height = snapToGrid(height); @@ -2921,10 +2908,10 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // if not stretching in y direction, set dy to 0 // if not stretching in x direction, set dx to 0 - if(current_resize_mode.indexOf("n")==-1 && current_resize_mode.indexOf("s")==-1) { + if (current_resize_mode.indexOf("n")==-1 && current_resize_mode.indexOf("s")==-1) { dy = 0; } - if(current_resize_mode.indexOf("e")==-1 && current_resize_mode.indexOf("w")==-1) { + if (current_resize_mode.indexOf("e")==-1 && current_resize_mode.indexOf("w")==-1) { dx = 0; } @@ -2933,13 +2920,13 @@ var getMouseTarget = this.getMouseTarget = function(evt) { sy = height ? (height+dy)/height : 1, sx = width ? (width+dx)/width : 1; // if we are dragging on the north side, then adjust the scale factor and ty - if(current_resize_mode.indexOf("n") >= 0) { + if (current_resize_mode.indexOf("n") >= 0) { sy = height ? (height-dy)/height : 1; ty = height; } // if we dragging on the east side, then adjust the scale factor and tx - if(current_resize_mode.indexOf("w") >= 0) { + if (current_resize_mode.indexOf("w") >= 0) { sx = width ? (width-dx)/width : 1; tx = width; } @@ -2949,7 +2936,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { scale = svgroot.createSVGTransform(), translateBack = svgroot.createSVGTransform(); - if(curConfig.gridSnapping){ + if (curConfig.gridSnapping){ left = snapToGrid(left); tx = snapToGrid(tx); top = snapToGrid(top); @@ -2957,14 +2944,14 @@ var getMouseTarget = this.getMouseTarget = function(evt) { } translateOrigin.setTranslate(-(left+tx),-(top+ty)); - if(evt.shiftKey) { - if(sx == 1) sx = sy + if (evt.shiftKey) { + if (sx == 1) sx = sy; else sy = sx; } scale.setScale(sx,sy); translateBack.setTranslate(left+tx,top+ty); - if(hasMatrix) { + if (hasMatrix) { var diff = angle?1:0; tlist.replaceItem(translateOrigin, 2+diff); tlist.replaceItem(scale, 1+diff); @@ -3002,7 +2989,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var handle = null; if (!window.opera) svgroot.suspendRedraw(1000); - if(curConfig.gridSnapping){ + if (curConfig.gridSnapping){ x = snapToGrid(x); y = snapToGrid(y); } @@ -3010,7 +2997,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var x2 = x; var y2 = y; - if(evt.shiftKey) { var xya = svgedit.math.snapToAngle(start_x,start_y,x2,y2); x2=xya.x; y2=xya.y; } + if (evt.shiftKey) { var xya = svgedit.math.snapToAngle(start_x,start_y,x2,y2); x2=xya.x; y2=xya.y; } shape.setAttributeNS(null, "x2", x2); shape.setAttributeNS(null, "y2", y2); @@ -3027,7 +3014,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { w = Math.abs(x - start_x), h = Math.abs(y - start_y), new_x, new_y; - if(square) { + if (square) { w = h = Math.max(w, h); new_x = start_x < x ? start_x : start_x - w; new_y = start_y < y ? start_y : start_y - h; @@ -3036,7 +3023,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { new_y = Math.min(start_y,y); } - if(curConfig.gridSnapping){ + if (curConfig.gridSnapping){ w = snapToGrid(w); h = snapToGrid(h); new_x = snapToGrid(new_x); @@ -3055,7 +3042,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var c = $(shape).attr(["cx", "cy"]); var cx = c.cx, cy = c.cy, rad = Math.sqrt( (x-cx)*(x-cx) + (y-cy)*(y-cy) ); - if(curConfig.gridSnapping){ + if (curConfig.gridSnapping){ rad = snapToGrid(rad); } shape.setAttributeNS(null, "r", rad); @@ -3066,7 +3053,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // Opera has a problem with suspendRedraw() apparently handle = null; if (!window.opera) svgroot.suspendRedraw(1000); - if(curConfig.gridSnapping){ + if (curConfig.gridSnapping){ x = snapToGrid(x); cx = snapToGrid(cx); y = snapToGrid(y); @@ -3088,7 +3075,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // d_attr += + real_x + "," + real_y + " "; // shape.setAttributeNS(null, "points", d_attr); end.x = real_x; end.y = real_y; - if(controllPoint2.x && controllPoint2.y){ + if (controllPoint2.x && controllPoint2.y){ for (var i = 0; i < STEP_COUNT - 1; i++) { parameter = i / STEP_COUNT; nextParameter = (i + 1) / STEP_COUNT; @@ -3114,15 +3101,15 @@ var getMouseTarget = this.getMouseTarget = function(evt) { x *= current_zoom; y *= current_zoom; - if(curConfig.gridSnapping){ + if (curConfig.gridSnapping){ x = snapToGrid(x); y = snapToGrid(y); start_x = snapToGrid(start_x); start_y = snapToGrid(start_y); } - if(evt.shiftKey) { + if (evt.shiftKey) { var path = svgedit.path.path; - if(path) { + if (path) { var x1 = path.dragging?path.dragging[0]:start_x; var y1 = path.dragging?path.dragging[1]:start_y; } else { @@ -3133,7 +3120,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { x=xya.x; y=xya.y; } - if(rubberBox && rubberBox.getAttribute('display') !== 'none') { + if (rubberBox && rubberBox.getAttribute('display') !== 'none') { real_x *= current_zoom; real_y *= current_zoom; assignAttributes(rubberBox, { @@ -3149,7 +3136,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { case "textedit": x *= current_zoom; y *= current_zoom; -// if(rubberBox && rubberBox.getAttribute('display') != 'none') { +// if (rubberBox && rubberBox.getAttribute('display') != 'none') { // assignAttributes(rubberBox, { // 'x': Math.min(start_x,x), // 'y': Math.min(start_y,y), @@ -3170,10 +3157,10 @@ var getMouseTarget = this.getMouseTarget = function(evt) { cx = center.x; cy = center.y; var angle = ((Math.atan2(cy-y,cx-x) * (180/Math.PI))-90) % 360; - if(curConfig.gridSnapping){ + if (curConfig.gridSnapping){ angle = snapToGrid(angle); } - if(evt.shiftKey) { // restrict rotations to nice angles (WRS) + if (evt.shiftKey) { // restrict rotations to nice angles (WRS) var snap = 45; angle= Math.round(angle/snap)*snap; } @@ -3199,9 +3186,8 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // - in move/resize mode, the element's attributes which were affected by the move/resize are // identified, a ChangeElementCommand is created and stored on the stack for those attrs // this is done in when we recalculate the selected dimensions() - var mouseUp = function(evt) - { - if(evt.button === 2) return; + var mouseUp = function(evt) { + if (evt.button === 2) return; var tempJustSelected = justSelected; justSelected = null; if (!started) return; @@ -3268,7 +3254,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var len = selectedElements.length; for (var i = 0; i < len; ++i) { if (selectedElements[i] == null) break; - if(!selectedElements[i].firstChild) { + if (!selectedElements[i].firstChild) { // Not needed for groups (incorrectly resizes elems), possibly not needed at all? selectorManager.requestSelector(selectedElements[i]).resize(); } @@ -3282,14 +3268,14 @@ var getMouseTarget = this.getMouseTarget = function(evt) { } // if it was a path // else, if it was selected and this is a shift-click, remove it from selection else if (evt.shiftKey) { - if(tempJustSelected != t) { + if (tempJustSelected != t) { canvas.removeFromSelection([t]); } } } // no change in mouse position // Remove non-scaling stroke - if(svgedit.browser.supportsNonScalingStroke()) { + if (svgedit.browser.supportsNonScalingStroke()) { var elem = selectedElements[0]; if (elem) { elem.removeAttribute('style'); @@ -3320,11 +3306,11 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // causes problems. // Webkit ignores how we set the points attribute with commas and uses space // to separate all coordinates, see https://bugs.webkit.org/show_bug.cgi?id=29870 - sumDistance= 0; + sumDistance = 0; controllPoint2 = {x:0, y:0}; controllPoint1 = {x:0, y:0}; - start= {x:0, y:0}; - end= {x:0, y:0}; + start = {x:0, y:0}; + end = {x:0, y:0}; var coords = element.getAttribute('points'); var commaIndex = coords.indexOf(','); if (commaIndex >= 0) { @@ -3403,7 +3389,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { started = true; var res = pathActions.mouseUp(evt, element, mouse_x, mouse_y); - element = res.element + element = res.element; keep = res.keep; break; case "pathedit": @@ -3440,7 +3426,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { }, true); $.each(ext_result, function(i, r) { - if(r) { + if (r) { keep = r.keep || keep; element = r.element; started = r.started || started; @@ -3475,10 +3461,10 @@ var getMouseTarget = this.getMouseTarget = function(evt) { } else if (element != null) { canvas.addedNew = true; - if(useUnit) svgedit.units.convertAttrs(element); + if (useUnit) svgedit.units.convertAttrs(element); var ani_dur = .2, c_ani; - if(opac_ani.beginElement && element.getAttribute('opacity') != cur_shape.opacity) { + if (opac_ani.beginElement && element.getAttribute('opacity') != cur_shape.opacity) { c_ani = $(opac_ani).clone().attr({ to: cur_shape.opacity, dur: ani_dur @@ -3494,16 +3480,14 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // Ideally this would be done on the endEvent of the animation, // but that doesn't seem to be supported in Webkit setTimeout(function() { - if(c_ani) c_ani.remove(); + if (c_ani) c_ani.remove(); element.setAttribute("opacity", cur_shape.opacity); element.setAttribute("style", "pointer-events:inherit"); cleanupElement(element); - if(current_mode === "path") { + if (current_mode === "path") { pathActions.toEditMode(element); - } else { - if(curConfig.selectNew) { - selectOnly([element], true); - } + } else if (curConfig.selectNew) { + selectOnly([element], true); } // we create the insert command that is stored on the stack // undo means to call cmd.unapply(), redo means to call cmd.apply() @@ -3521,17 +3505,17 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var parent = evt_target.parentNode; // Do nothing if already in current group - if(parent === current_group) return; + if (parent === current_group) return; var mouse_target = getMouseTarget(evt); var tagName = mouse_target.tagName; - if(tagName === 'text' && current_mode !== 'textedit') { + if (tagName === 'text' && current_mode !== 'textedit') { var pt = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm ); textActions.select(mouse_target, pt.x, pt.y); } - if((tagName === "g" || tagName === "a") && svgedit.utilities.getRotationAngle(mouse_target)) { + if ((tagName === "g" || tagName === "a") && svgedit.utilities.getRotationAngle(mouse_target)) { // TODO: Allow method of in-group editing without having to do // this (similar to editing rotated paths) @@ -3541,11 +3525,11 @@ var getMouseTarget = this.getMouseTarget = function(evt) { clearSelection(true); } // Reset context - if(current_group) { + if (current_group) { leaveContext(); } - if((parent.tagName !== 'g' && parent.tagName !== 'a') || + if ((parent.tagName !== 'g' && parent.tagName !== 'a') || parent === getCurrentDrawing().getCurrentLayer() || mouse_target === selectorManager.selectorParentGroup) { @@ -3553,7 +3537,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { return; } setContext(mouse_target); - } + }; // prevent links from being followed in the canvas var handleLinkInCanvas = function(e) { @@ -3568,7 +3552,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { //TODO(rafaelcastrocouto): User preference for shift key and zoom factor $(container).bind("mousewheel DOMMouseScroll", function(e){ - //if(!e.shiftKey) return; + //if (!e.shiftKey) return; e.preventDefault(); var evt = e.originalEvent; @@ -3583,7 +3567,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { }; var delta = (evt.wheelDelta) ? evt.wheelDelta : (evt.detail) ? -evt.detail : 0; - if(!delta) return; + if (!delta) return; bbox.factor = Math.max(3/4, Math.min(4/3, (delta))); @@ -3598,8 +3582,8 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // Parameters: // img - The DOM element to prevent the cilck on var preventClickDefault = function(img) { - $(img).click(function(e){e.preventDefault()}); -} + $(img).click(function(e){e.preventDefault();}); +}; // Group: Text edit functions // Functions relating to editing text elements @@ -3619,18 +3603,18 @@ var textActions = canvas.textActions = function() { var empty = (textinput.value === ""); $(textinput).focus(); - if(!arguments.length) { - if(empty) { + if (!arguments.length) { + if (empty) { index = 0; } else { - if(textinput.selectionEnd !== textinput.selectionStart) return; + if (textinput.selectionEnd !== textinput.selectionStart) return; index = textinput.selectionEnd; } } var charbb; charbb = chardata[index]; - if(!empty) { + if (!empty) { textinput.setSelectionRange(index, index); } cursor = svgedit.utilities.getElem("text_cursor"); @@ -3644,15 +3628,13 @@ var textActions = canvas.textActions = function() { cursor = svgedit.utilities.getElem("selectorParentGroup").appendChild(cursor); } - if(!blinker) { + if (!blinker) { blinker = setInterval(function() { var show = (cursor.getAttribute('display') === 'none'); cursor.setAttribute('display', show?'inline':'none'); }, 600); - } - var start_pt = ptToScreen(charbb.x, textbb.y); var end_pt = ptToScreen(charbb.x, (textbb.y + textbb.height)); @@ -3665,16 +3647,16 @@ var textActions = canvas.textActions = function() { display: 'inline' }); - if(selblock) selblock.setAttribute('d', ''); + if (selblock) selblock.setAttribute('d', ''); } function setSelection(start, end, skipInput) { - if(start === end) { + if (start === end) { setCursor(end); return; } - if(!skipInput) { + if (!skipInput) { textinput.setSelectionRange(start, end); } @@ -3685,15 +3667,13 @@ var textActions = canvas.textActions = function() { assignAttributes(selblock, { 'id': "text_selectblock", 'fill': "green", - 'opacity': .5, + 'opacity': 0.5, 'style': "pointer-events:none" }); svgedit.utilities.getElem("selectorParentGroup").appendChild(selblock); } - - var startbb = chardata[start]; - + var startbb = chardata[start]; var endbb = chardata[end]; cursor.setAttribute('visibility', 'hidden'); @@ -3703,7 +3683,6 @@ var textActions = canvas.textActions = function() { bl = ptToScreen(startbb.x, textbb.y + textbb.height), br = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y + textbb.height); - var dstr = "M" + tl.x + "," + tl.y + " L" + tr.x + "," + tr.y + " " + br.x + "," + br.y @@ -3722,21 +3701,21 @@ var textActions = canvas.textActions = function() { pt.y = mouse_y; // No content, so return 0 - if(chardata.length == 1) return 0; + if (chardata.length == 1) return 0; // Determine if cursor should be on left or right of character var charpos = curtext.getCharNumAtPosition(pt); - if(charpos < 0) { + if (charpos < 0) { // Out of text range, look at mouse coords charpos = chardata.length - 2; - if(mouse_x <= chardata[0].x) { + if (mouse_x <= chardata[0].x) { charpos = 0; } - } else if(charpos >= chardata.length - 2) { + } else if (charpos >= chardata.length - 2) { charpos = chardata.length - 2; } var charbb = chardata[charpos]; var mid = charbb.x + (charbb.width/2); - if(mouse_x > mid) { + if (mouse_x > mid) { charpos++; } return charpos; @@ -3759,12 +3738,12 @@ var textActions = canvas.textActions = function() { var out = { x: x_in, y: y_in - } + }; out.x /= current_zoom; out.y /= current_zoom; - if(matrix) { + if (matrix) { var pt = svgedit.math.transformPoint(out.x, out.y, matrix.inverse()); out.x = pt.x; out.y = pt.y; @@ -3777,9 +3756,9 @@ var textActions = canvas.textActions = function() { var out = { x: x_in, y: y_in - } + }; - if(matrix) { + if (matrix) { var pt = svgedit.math.transformPoint(out.x, out.y, matrix); out.x = pt.x; out.y = pt.y; @@ -3792,7 +3771,7 @@ var textActions = canvas.textActions = function() { } function hideCursor() { - if(cursor) { + if (cursor) { cursor.setAttribute('visibility', 'hidden'); } } @@ -3803,7 +3782,7 @@ var textActions = canvas.textActions = function() { } function selectWord(evt) { - if(!allow_dbl || !curtext) return; + if (!allow_dbl || !curtext) return; var ept = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm ), mouse_x = ept.x * current_zoom, @@ -3854,12 +3833,12 @@ var textActions = canvas.textActions = function() { setEndSelectionFromPoint(pt.x, pt.y, true); // TODO: Find a way to make this work: Use transformed BBox instead of evt.target -// if(last_x === mouse_x && last_y === mouse_y +// if (last_x === mouse_x && last_y === mouse_y // && !svgedit.math.rectsIntersect(transbb, {x: pt.x, y: pt.y, width:0, height:0})) { // textActions.toSelectMode(true); // } - if( + if ( evt.target !== curtext && mouse_x < last_x + 2 && mouse_x > last_x - 2 @@ -3882,12 +3861,12 @@ var textActions = canvas.textActions = function() { $(curtext).css('cursor', 'text'); -// if(svgedit.browser.supportsEditableText()) { +// if (svgedit.browser.supportsEditableText()) { // curtext.setAttribute('editable', 'simple'); // return; // } - if(!arguments.length) { + if (!arguments.length) { setCursor(); } else { var pt = screenToPt(x, y); @@ -3902,18 +3881,18 @@ var textActions = canvas.textActions = function() { current_mode = "select"; clearInterval(blinker); blinker = null; - if(selblock) $(selblock).attr('display','none'); - if(cursor) $(cursor).attr('visibility','hidden'); + if (selblock) $(selblock).attr('display','none'); + if (cursor) $(cursor).attr('visibility','hidden'); $(curtext).css('cursor', 'move'); - if(selectElem) { + if (selectElem) { clearSelection(); $(curtext).css('cursor', 'move'); call("selected", [curtext]); addToSelection([curtext], true); } - if(curtext && !curtext.textContent.length) { + if (curtext && !curtext.textContent.length) { // No content, so delete canvas.deleteSelectedElements(); } @@ -3922,7 +3901,7 @@ var textActions = canvas.textActions = function() { curtext = false; -// if(svgedit.browser.supportsEditableText()) { +// if (svgedit.browser.supportsEditableText()) { // curtext.removeAttribute('editable'); // } }, @@ -3931,19 +3910,19 @@ var textActions = canvas.textActions = function() { // $(textinput).blur(hideCursor); }, clear: function() { - if(current_mode == "textedit") { + if (current_mode == "textedit") { textActions.toSelectMode(); } }, init: function(inputElem) { - if(!curtext) return; + if (!curtext) return; -// if(svgedit.browser.supportsEditableText()) { +// if (svgedit.browser.supportsEditableText()) { // curtext.select(); // return; // } - if(!curtext.parentNode) { + if (!curtext.parentNode) { // Result of the ffClone, need to get correct element curtext = selectedElements[0]; selectorManager.requestSelector(curtext).showGrips(false); @@ -3963,15 +3942,15 @@ var textActions = canvas.textActions = function() { $(curtext).unbind('dblclick', selectWord).dblclick(selectWord); - if(!len) { + if (!len) { var end = {x: textbb.x + (textbb.width/2), width: 0}; } - for(var i=0; i<len; i++) { + for (var i=0; i<len; i++) { var start = curtext.getStartPositionOfChar(i); var end = curtext.getEndPositionOfChar(i); - if(!svgedit.browser.supportsGoodTextCharPos()) { + if (!svgedit.browser.supportsGoodTextCharPos()) { var offset = canvas.contentW * current_zoom; start.x -= offset; end.x -= offset; @@ -3999,7 +3978,7 @@ var textActions = canvas.textActions = function() { }); setSelection(textinput.selectionStart, textinput.selectionEnd, true); } - } + }; }(); // TODO: Migrate all of this code into path.js @@ -4016,41 +3995,41 @@ var pathActions = canvas.pathActions = function() { } // TODO: Move into path.js - svgedit.path.Path.prototype.endChanges = function(text) { - if(svgedit.browser.isWebkit()) resetD(this.elem); - var cmd = new ChangeElementCommand(this.elem, {d: this.last_d}, text); - addCommandToHistory(cmd); - call("changed", [this.elem]); - } + svgedit.path.Path.prototype.endChanges = function(text) { + if (svgedit.browser.isWebkit()) resetD(this.elem); + var cmd = new ChangeElementCommand(this.elem, {d: this.last_d}, text); + addCommandToHistory(cmd); + call("changed", [this.elem]); + }; - svgedit.path.Path.prototype.addPtsToSelection = function(indexes) { - if(!$.isArray(indexes)) indexes = [indexes]; - for(var i=0; i< indexes.length; i++) { - var index = indexes[i]; - var seg = this.segs[index]; - if(seg.ptgrip) { - if(this.selected_pts.indexOf(index) == -1 && index >= 0) { - this.selected_pts.push(index); - } + svgedit.path.Path.prototype.addPtsToSelection = function(indexes) { + if (!$.isArray(indexes)) indexes = [indexes]; + for (var i=0; i< indexes.length; i++) { + var index = indexes[i]; + var seg = this.segs[index]; + if (seg.ptgrip) { + if (this.selected_pts.indexOf(index) == -1 && index >= 0) { + this.selected_pts.push(index); } - }; - this.selected_pts.sort(); - var i = this.selected_pts.length, - grips = new Array(i); - // Loop through points to be selected and highlight each - while(i--) { - var pt = this.selected_pts[i]; - var seg = this.segs[pt]; - seg.select(true); - grips[i] = seg.ptgrip; } - // TODO: Correct this: - pathActions.canDeleteNodes = true; - - pathActions.closed_subpath = this.subpathIsClosed(this.selected_pts[0]); - - call("selected", grips); } + this.selected_pts.sort(); + var i = this.selected_pts.length, + grips = new Array(i); + // Loop through points to be selected and highlight each + while (i--) { + var pt = this.selected_pts[i]; + var seg = this.segs[pt]; + seg.select(true); + grips[i] = seg.ptgrip; + } + // TODO: Correct this: + pathActions.canDeleteNodes = true; + + pathActions.closed_subpath = this.subpathIsClosed(this.selected_pts[0]); + + call("selected", grips); + }; var current_path = null, drawn_path = null, @@ -4104,7 +4083,7 @@ var pathActions = canvas.pathActions = function() { } // handle remaining line segments d.push("L"); - for(;i < N;++i) { + for (;i < N;++i) { var pt = points.getItem(i); d.push([pt.x,pt.y].join(",")); } @@ -4127,7 +4106,7 @@ var pathActions = canvas.pathActions = function() { return { mouseDown: function(evt, mouse_target, start_x, start_y) { - if(current_mode === "path") { + if (current_mode === "path") { mouse_x = start_x; mouse_y = start_y; @@ -4136,7 +4115,7 @@ var pathActions = canvas.pathActions = function() { stretchy = svgedit.utilities.getElem("path_stretch_line"); newPoint = [x, y]; - if(curConfig.gridSnapping){ + if (curConfig.gridSnapping){ x = snapToGrid(x); y = snapToGrid(y); mouse_x = snapToGrid(mouse_x); @@ -4173,14 +4152,13 @@ var pathActions = canvas.pathActions = function() { stretchy.setAttribute('d', ['M', mouse_x, mouse_y, mouse_x, mouse_y].join(' ')); var index = subpath ? svgedit.path.path.segs.length : 0; svgedit.path.addPointGrip(index, mouse_x, mouse_y); - } - else { + } else { // determine if we clicked on an existing point var seglist = drawn_path.pathSegList; var i = seglist.numberOfItems; var FUZZ = 6/current_zoom; var clickOnPoint = false; - while(i) { + while (i) { i --; var item = seglist.getItem(i); var px = item.x, py = item.y; @@ -4214,7 +4192,7 @@ var pathActions = canvas.pathActions = function() { var s_seg = stretchy.pathSegList.getItem(1); - if(s_seg.pathSegType === 4) { + if (s_seg.pathSegType === 4) { var newseg = drawn_path.createSVGPathSegLinetoAbs(abs_x, abs_y); } else { var newseg = drawn_path.createSVGPathSegCurvetoCubicAbs( @@ -4230,7 +4208,7 @@ var pathActions = canvas.pathActions = function() { var endseg = drawn_path.createSVGPathSegClosePath(); seglist.appendItem(newseg); seglist.appendItem(endseg); - } else if(len < 3) { + } else if (len < 3) { keep = false; return keep; } @@ -4241,8 +4219,8 @@ var pathActions = canvas.pathActions = function() { drawn_path = null; started = false; - if(subpath) { - if(svgedit.path.path.matrix) { + if (subpath) { + if (svgedit.path.path.matrix) { remapElement(newpath, {}, svgedit.path.path.matrix.inverse()); } @@ -4250,7 +4228,7 @@ var pathActions = canvas.pathActions = function() { var orig_d = $(svgedit.path.path.elem).attr("d"); $(svgedit.path.path.elem).attr("d", orig_d + new_d); $(newpath).remove(); - if(svgedit.path.path.matrix) { + if (svgedit.path.path.matrix) { svgedit.path.recalcRotatedPath(); } svgedit.path.path.init(); @@ -4262,7 +4240,7 @@ var pathActions = canvas.pathActions = function() { // else, create a new point, update path element else { // Checks if current target or parents are #svgcontent - if(!$.contains(container, getMouseTarget(evt))) { + if (!$.contains(container, getMouseTarget(evt))) { // Clicked outside canvas, so don't make point console.log("Clicked outside canvas"); return false; @@ -4272,11 +4250,11 @@ var pathActions = canvas.pathActions = function() { var last = drawn_path.pathSegList.getItem(num -1); var lastx = last.x, lasty = last.y; - if(evt.shiftKey) { var xya = svgedit.math.snapToAngle(lastx,lasty,x,y); x=xya.x; y=xya.y; } + if (evt.shiftKey) { var xya = svgedit.math.snapToAngle(lastx,lasty,x,y); x=xya.x; y=xya.y; } // Use the segment defined by stretchy var s_seg = stretchy.pathSegList.getItem(1); - if(s_seg.pathSegType === 4) { + if (s_seg.pathSegType === 4) { var newseg = drawn_path.createSVGPathSegLinetoAbs(round(x), round(y)); } else { var newseg = drawn_path.createSVGPathSegCurvetoCubicAbs( @@ -4297,7 +4275,7 @@ var pathActions = canvas.pathActions = function() { // set stretchy line to latest point stretchy.setAttribute('d', ['M', x, y, x, y].join(' ')); var index = num; - if(subpath) index += svgedit.path.path.segs.length; + if (subpath) index += svgedit.path.path.segs.length; svgedit.path.addPointGrip(index, x, y); } // keep = true; @@ -4307,7 +4285,7 @@ var pathActions = canvas.pathActions = function() { } // TODO: Make sure current_path isn't null at this point - if(!svgedit.path.path) return; + if (!svgedit.path.path) return; svgedit.path.path.storeD(); @@ -4321,16 +4299,16 @@ var pathActions = canvas.pathActions = function() { // only clear selection if shift is not pressed (otherwise, add // node to selection) if (!evt.shiftKey) { - if(svgedit.path.path.selected_pts.length <= 1 || !seg.selected) { + if (svgedit.path.path.selected_pts.length <= 1 || !seg.selected) { svgedit.path.path.clearSelection(); } svgedit.path.path.addPtsToSelection(cur_pt); - } else if(seg.selected) { + } else if (seg.selected) { svgedit.path.path.removePtFromSelection(cur_pt); } else { svgedit.path.path.addPtsToSelection(cur_pt); } - } else if(id.indexOf("ctrlpointgrip_") == 0) { + } else if (id.indexOf("ctrlpointgrip_") == 0) { svgedit.path.path.dragging = [start_x, start_y]; var parts = id.split('_')[1].split('c'); @@ -4340,7 +4318,7 @@ var pathActions = canvas.pathActions = function() { } // Start selection box - if(!svgedit.path.path.dragging) { + if (!svgedit.path.path.dragging) { if (rubberBox == null) { rubberBox = selectorManager.getRubberBandBox(); } @@ -4355,14 +4333,14 @@ var pathActions = canvas.pathActions = function() { }, mouseMove: function(mouse_x, mouse_y) { hasMoved = true; - if(current_mode === "path") { - if(!drawn_path) return; + if (current_mode === "path") { + if (!drawn_path) return; var seglist = drawn_path.pathSegList; var index = seglist.numberOfItems - 1; - if(newPoint) { + if (newPoint) { // First point -// if(!index) return; +// if (!index) return; // Set control points var pointGrip1 = svgedit.path.addCtrlGrip('1c1'); @@ -4396,19 +4374,19 @@ var pathActions = canvas.pathActions = function() { display: 'inline' }); - if(index === 0) { + if (index === 0) { firstCtrl = [mouse_x, mouse_y]; } else { var last_x, last_y; var last = seglist.getItem(index - 1); var last_x = last.x; - var last_y = last.y + var last_y = last.y; - if(last.pathSegType === 6) { + if (last.pathSegType === 6) { last_x += (last_x - last.x2); last_y += (last_y - last.y2); - } else if(firstCtrl) { + } else if (firstCtrl) { last_x = firstCtrl[0]/current_zoom; last_y = firstCtrl[1]/current_zoom; } @@ -4418,11 +4396,11 @@ var pathActions = canvas.pathActions = function() { var stretchy = svgedit.utilities.getElem("path_stretch_line"); if (stretchy) { var prev = seglist.getItem(index); - if(prev.pathSegType === 6) { + if (prev.pathSegType === 6) { var prev_x = prev.x + (prev.x - prev.x2); var prev_y = prev.y + (prev.y - prev.y2); svgedit.path.replacePathSeg(6, 1, [mouse_x, mouse_y, prev_x * current_zoom, prev_y * current_zoom, mouse_x, mouse_y], stretchy); - } else if(firstCtrl) { + } else if (firstCtrl) { svgedit.path.replacePathSeg(6, 1, [mouse_x, mouse_y, firstCtrl[0], firstCtrl[1], mouse_x, mouse_y], stretchy); } else { svgedit.path.replacePathSeg(4, 1, [mouse_x, mouse_y], stretchy); @@ -4445,7 +4423,7 @@ var pathActions = canvas.pathActions = function() { var diff_y = mpt.y - pt.y; svgedit.path.path.dragging = [mouse_x, mouse_y]; - if(svgedit.path.path.dragctrl) { + if (svgedit.path.path.dragctrl) { svgedit.path.path.moveCtrl(diff_x, diff_y); } else { svgedit.path.path.movePts(diff_x, diff_y); @@ -4454,7 +4432,7 @@ var pathActions = canvas.pathActions = function() { svgedit.path.path.selected_pts = []; svgedit.path.path.eachSeg(function(i) { var seg = this; - if(!seg.next && !seg.prev) return; + if (!seg.next && !seg.prev) return; var item = seg.item; var rbb = rubberBox.getBBox(); @@ -4471,7 +4449,7 @@ var pathActions = canvas.pathActions = function() { this.select(sel); //Note that addPtsToSelection is not being run - if(sel) svgedit.path.path.selected_pts.push(seg.index); + if (sel) svgedit.path.path.selected_pts.push(seg.index); }); } @@ -4479,9 +4457,9 @@ var pathActions = canvas.pathActions = function() { mouseUp: function(evt, element, mouse_x, mouse_y) { // Create mode - if(current_mode === "path") { + if (current_mode === "path") { newPoint = null; - if(!drawn_path) { + if (!drawn_path) { element = svgedit.utilities.getElem(getId()); started = false; firstCtrl = null; @@ -4490,7 +4468,7 @@ var pathActions = canvas.pathActions = function() { return { keep: true, element: element - } + }; } // Edit mode @@ -4502,20 +4480,18 @@ var pathActions = canvas.pathActions = function() { svgedit.path.path.dragctrl = false; svgedit.path.path.update(); - - if(hasMoved) { + if (hasMoved) { svgedit.path.path.endChanges("Move path point(s)"); } - if(!evt.shiftKey && !hasMoved) { + if (!evt.shiftKey && !hasMoved) { svgedit.path.path.selectPt(last_pt); } - } - else if(rubberBox && rubberBox.getAttribute('display') != 'none') { + } else if (rubberBox && rubberBox.getAttribute('display') != 'none') { // Done with multi-node-select rubberBox.setAttribute("display", "none"); - if(rubberBox.getAttribute('width') <= 2 && rubberBox.getAttribute('height') <= 2) { + if (rubberBox.getAttribute('width') <= 2 && rubberBox.getAttribute('height') <= 2) { pathActions.toSelectMode(evt.target); } @@ -4540,18 +4516,18 @@ var pathActions = canvas.pathActions = function() { current_path = false; clearSelection(); - if(svgedit.path.path.matrix) { + if (svgedit.path.path.matrix) { // Rotated, so may need to re-calculate the center svgedit.path.recalcRotatedPath(); } - if(selPath) { + if (selPath) { call("selected", [elem]); addToSelection([elem], true); } }, addSubPath: function(on) { - if(on) { + if (on) { // Internally we go into "path" mode, but in the UI it will // still appear as if in "pathedit" mode. current_mode = "path"; @@ -4572,9 +4548,9 @@ var pathActions = canvas.pathActions = function() { }, reorient: function() { var elem = selectedElements[0]; - if(!elem) return; + if (!elem) return; var angle = svgedit.utilities.getRotationAngle(elem); - if(angle == 0) return; + if (angle == 0) return; var batchCmd = new BatchCommand("Reorient path"); var changes = { @@ -4608,10 +4584,10 @@ var pathActions = canvas.pathActions = function() { } else if (current_mode == "pathedit") { this.toSelectMode(); } - if(svgedit.path.path) svgedit.path.path.init().show(false); + if (svgedit.path.path) svgedit.path.path.init().show(false); }, resetOrientation: function(path) { - if(path == null || path.nodeName != 'path') return false; + if (path == null || path.nodeName != 'path') return false; var tlist = svgedit.transformlist.getTransformList(path); var m = svgedit.math.transformListToTransform(tlist).matrix; tlist.clear(); @@ -4632,15 +4608,14 @@ var pathActions = canvas.pathActions = function() { // } var last_x, last_y; - for (var i = 0; i < len; ++i) { var seg = segList.getItem(i); var type = seg.pathSegType; - if(type == 1) continue; + if (type == 1) continue; var pts = []; $.each(['',1,2], function(j, n) { var x = seg['x'+n], y = seg['y'+n]; - if(x !== undefined && y !== undefined) { + if (x !== undefined && y !== undefined) { var pt = svgedit.math.transformPoint(x, y, m); pts.splice(pts.length, 0, pt.x, pt.y); } @@ -4649,11 +4624,9 @@ var pathActions = canvas.pathActions = function() { } reorientGrads(path, m); - - }, zoomChange: function() { - if(current_mode == "pathedit") { + if (current_mode == "pathedit") { svgedit.path.path.update(); } }, @@ -4679,7 +4652,7 @@ var pathActions = canvas.pathActions = function() { var i = sel_pts.length; var nums = []; - while(i--) { + while (i--) { var pt = sel_pts[i]; svgedit.path.path.addSeg(pt); @@ -4693,7 +4666,7 @@ var pathActions = canvas.pathActions = function() { opencloseSubPath: function() { var sel_pts = svgedit.path.path.selected_pts; // Only allow one selected node for now - if(sel_pts.length !== 1) return; + if (sel_pts.length !== 1) return; var elem = svgedit.path.path.elem; var list = elem.pathSegList; @@ -4707,34 +4680,34 @@ var pathActions = canvas.pathActions = function() { // Check if subpath is already open svgedit.path.path.eachSeg(function(i) { - if(this.type === 2 && i <= index) { + if (this.type === 2 && i <= index) { start_item = this.item; } - if(i <= index) return true; - if(this.type === 2) { + if (i <= index) return true; + if (this.type === 2) { // Found M first, so open open_pt = i; return false; - } else if(this.type === 1) { + } else if (this.type === 1) { // Found Z first, so closed open_pt = false; return false; } }); - if(open_pt == null) { + if (open_pt == null) { // Single path, so close last seg open_pt = svgedit.path.path.segs.length - 1; } - if(open_pt !== false) { + if (open_pt !== false) { // Close this path // Create a line going to the previous "M" var newseg = elem.createSVGPathSegLinetoAbs(start_item.x, start_item.y); var closer = elem.createSVGPathSegClosePath(); - if(open_pt == svgedit.path.path.segs.length - 1) { + if (open_pt == svgedit.path.path.segs.length - 1) { list.appendItem(newseg); list.appendItem(closer); } else { @@ -4746,8 +4719,6 @@ var pathActions = canvas.pathActions = function() { return; } - - // M 1,1 L 2,2 L 3,3 L 1,1 z // open at 2,2 // M 2,2 L 3,3 L 1,1 @@ -4756,7 +4727,7 @@ var pathActions = canvas.pathActions = function() { var seg = svgedit.path.path.segs[index]; - if(seg.mate) { + if (seg.mate) { list.removeItem(index); // Removes last "L" list.removeItem(index); // Removes the "Z" svgedit.path.path.init().selectPt(index - 1); @@ -4766,17 +4737,17 @@ var pathActions = canvas.pathActions = function() { var last_m, z_seg; // Find this sub-path's closing point and remove - for(var i=0; i<list.numberOfItems; i++) { + for (var i=0; i<list.numberOfItems; i++) { var item = list.getItem(i); - if(item.pathSegType === 2) { + if (item.pathSegType === 2) { // Find the preceding M last_m = i; - } else if(i === index) { + } else if (i === index) { // Remove it list.removeItem(last_m); // index--; - } else if(item.pathSegType === 1 && index < i) { + } else if (item.pathSegType === 1 && index < i) { // Remove the closing seg of this subpath z_seg = i-1; list.removeItem(i); @@ -4786,7 +4757,7 @@ var pathActions = canvas.pathActions = function() { var num = (index - last_m) - 1; - while(num--) { + while (num--) { svgedit.path.insertItemBefore(elem, list.getItem(last_m), z_seg); } @@ -4795,18 +4766,18 @@ var pathActions = canvas.pathActions = function() { // Make this point the new "M" svgedit.path.replacePathSeg(2, last_m, [pt.x, pt.y]); - var i = index + var i = index; svgedit.path.path.init().selectPt(0); }, deletePathNode: function() { - if(!pathActions.canDeleteNodes) return; + if (!pathActions.canDeleteNodes) return; svgedit.path.path.storeD(); var sel_pts = svgedit.path.path.selected_pts; var i = sel_pts.length; - while(i--) { + while (i--) { var pt = sel_pts[i]; svgedit.path.path.deleteSeg(pt); } @@ -4817,38 +4788,38 @@ var pathActions = canvas.pathActions = function() { var len = segList.numberOfItems; var remItems = function(pos, count) { - while(count--) { + while (count--) { segList.removeItem(pos); } - } + }; - if(len <= 1) return true; + if (len <= 1) return true; - while(len--) { + while (len--) { var item = segList.getItem(len); - if(item.pathSegType === 1) { + if (item.pathSegType === 1) { var prev = segList.getItem(len-1); var nprev = segList.getItem(len-2); - if(prev.pathSegType === 2) { + if (prev.pathSegType === 2) { remItems(len-1, 2); cleanup(); break; - } else if(nprev.pathSegType === 2) { + } else if (nprev.pathSegType === 2) { remItems(len-2, 3); cleanup(); break; } - } else if(item.pathSegType === 2) { - if(len > 0) { + } else if (item.pathSegType === 2) { + if (len > 0) { var prev_type = segList.getItem(len-1).pathSegType; // Path has M M - if(prev_type === 2) { + if (prev_type === 2) { remItems(len-1, 1); cleanup(); break; // Entire path ends with Z M - } else if(prev_type === 1 && segList.numberOfItems-1 === len) { + } else if (prev_type === 1 && segList.numberOfItems-1 === len) { remItems(len, 1); cleanup(); break; @@ -4857,24 +4828,23 @@ var pathActions = canvas.pathActions = function() { } } return false; - } + }; cleanup(); // Completely delete a path with 1 or 0 segments - if(svgedit.path.path.elem.pathSegList.numberOfItems <= 1) { + if (svgedit.path.path.elem.pathSegList.numberOfItems <= 1) { pathActions.toSelectMode(svgedit.path.path.elem); canvas.deleteSelectedElements(); return; } svgedit.path.path.init(); - svgedit.path.path.clearSelection(); // TODO: Find right way to select point now // path.selectPt(sel_pt); - if(window.opera) { // Opera repaints incorrectly + if (window.opera) { // Opera repaints incorrectly var cp = $(svgedit.path.path.elem); cp.attr('d',cp.attr('d')); } svgedit.path.path.endChanges("Delete path node(s)"); @@ -4885,7 +4855,7 @@ var pathActions = canvas.pathActions = function() { }, moveNode: function(attr, newValue) { var sel_pts = svgedit.path.path.selected_pts; - if(!sel_pts.length) return; + if (!sel_pts.length) return; svgedit.path.path.storeD(); @@ -4906,13 +4876,13 @@ var pathActions = canvas.pathActions = function() { var last_m; for (var i = 0; i < len; ++i) { var item = segList.getItem(i); - if(item.pathSegType === 2) { + if (item.pathSegType === 2) { last_m = item; } - if(item.pathSegType === 1) { + if (item.pathSegType === 1) { var prev = segList.getItem(i-1); - if(prev.x != last_m.x || prev.y != last_m.y) { + if (prev.x != last_m.x || prev.y != last_m.y) { // Add an L segment here var newseg = elem.createSVGPathSegLinetoAbs(last_m.x, last_m.y); svgedit.path.insertItemBefore(elem, newseg, i); @@ -4923,7 +4893,7 @@ var pathActions = canvas.pathActions = function() { } } - if(svgedit.browser.isWebkit()) resetD(elem); + if (svgedit.browser.isWebkit()) resetD(elem); }, // Convert a path to one with only absolute or relative values convertPath: function(path, toRel) { @@ -4954,7 +4924,7 @@ var pathActions = canvas.pathActions = function() { pnts[i] = svgedit.units.shortFloat(pnt); }); d += letter + pnts.join(' ') + more + last; - } + }; switch (type) { case 1: // z,Z closepath (Z/z) @@ -4963,7 +4933,7 @@ var pathActions = canvas.pathActions = function() { case 12: // absolute horizontal line (H) x -= curx; case 13: // relative horizontal line (h) - if(toRel) { + if (toRel) { curx += x; letter = 'l'; } else { @@ -4977,7 +4947,7 @@ var pathActions = canvas.pathActions = function() { case 14: // absolute vertical line (V) y -= cury; case 15: // relative vertical line (v) - if(toRel) { + if (toRel) { cury += y; letter = 'l'; } else { @@ -4996,13 +4966,13 @@ var pathActions = canvas.pathActions = function() { case 5: // relative line (l) case 3: // relative move (m) // If the last segment was a "z", this must be relative to - if(last_m && segList.getItem(i-1).pathSegType === 1 && !toRel) { + if (last_m && segList.getItem(i-1).pathSegType === 1 && !toRel) { curx = last_m[0]; cury = last_m[1]; } case 19: // relative smooth quad (t) - if(toRel) { + if (toRel) { curx += x; cury += y; } else { @@ -5011,7 +4981,7 @@ var pathActions = canvas.pathActions = function() { curx = x; cury = y; } - if(type === 3) last_m = [curx, cury]; + if (type === 3) last_m = [curx, cury]; addToD([[x,y]]); break; @@ -5019,7 +4989,7 @@ var pathActions = canvas.pathActions = function() { x -= curx; x1 -= curx; x2 -= curx; y -= cury; y1 -= cury; y2 -= cury; case 7: // relative cubic (c) - if(toRel) { + if (toRel) { curx += x; cury += y; } else { @@ -5034,7 +5004,7 @@ var pathActions = canvas.pathActions = function() { x -= curx; x1 -= curx; y -= cury; y1 -= cury; case 9: // relative quad (q) - if(toRel) { + if (toRel) { curx += x; cury += y; } else { @@ -5049,7 +5019,7 @@ var pathActions = canvas.pathActions = function() { x -= curx; y -= cury; case 11: // relative elliptical arc (a) - if(toRel) { + if (toRel) { curx += x; cury += y; } else { @@ -5069,7 +5039,7 @@ var pathActions = canvas.pathActions = function() { x -= curx; x2 -= curx; y -= cury; y2 -= cury; case 17: // relative smooth cubic (s) - if(toRel) { + if (toRel) { curx += x; cury += y; } else { @@ -5084,7 +5054,7 @@ var pathActions = canvas.pathActions = function() { } // for each segment return d; } - } + }; }(); // end pathActions @@ -5098,9 +5068,9 @@ var pathActions = canvas.pathActions = function() { // The amount of elements that were removed var removeUnusedDefElems = this.removeUnusedDefElems = function() { var defs = svgcontent.getElementsByTagNameNS(svgns, "defs"); - if(!defs || !defs.length) return 0; + if (!defs || !defs.length) return 0; -// if(!defs.firstChild) return; +// if (!defs.firstChild) return; var defelem_uses = [], numRemoved = 0; @@ -5110,11 +5080,11 @@ var removeUnusedDefElems = this.removeUnusedDefElems = function() { var all_els = svgcontent.getElementsByTagNameNS(svgns, '*'); var all_len = all_els.length; - for(var i=0; i<all_len; i++) { + for (var i=0; i<all_len; i++) { var el = all_els[i]; - for(var j = 0; j < alen; j++) { + for (var j = 0; j < alen; j++) { var ref = svgedit.utilities.getUrlFromAttr(el.getAttribute(attrs[j])); - if(ref) { + if (ref) { defelem_uses.push(ref.substr(1)); } } @@ -5124,7 +5094,7 @@ var removeUnusedDefElems = this.removeUnusedDefElems = function() { if (href && href.indexOf('#') === 0) { defelem_uses.push(href.substr(1)); } - }; + } var defelems = $(defs).find("linearGradient, radialGradient, filter, marker, svg, symbol"); defelem_ids = [], @@ -5132,7 +5102,7 @@ var removeUnusedDefElems = this.removeUnusedDefElems = function() { while (i--) { var defelem = defelems[i]; var id = defelem.id; - if(defelem_uses.indexOf(id) < 0) { + if (defelem_uses.indexOf(id) < 0) { // Not found, so remove (but remember) removedElements[id] = defelem; defelem.parentNode.removeChild(defelem); @@ -5141,7 +5111,7 @@ var removeUnusedDefElems = this.removeUnusedDefElems = function() { } return numRemoved; -} +}; // Function: svgCanvasToString // Main function to set up the SVG content for output @@ -5150,19 +5120,19 @@ var removeUnusedDefElems = this.removeUnusedDefElems = function() { // String containing the SVG image for output this.svgCanvasToString = function() { // keep calling it until there are none to remove - while (removeUnusedDefElems() > 0) {}; + while (removeUnusedDefElems() > 0) {} pathActions.clear(true); // Keep SVG-Edit comment on top $.each(svgcontent.childNodes, function(i, node) { - if(i && node.nodeType === 8 && node.data.indexOf('Created with') >= 0) { + if (i && node.nodeType === 8 && node.data.indexOf('Created with') >= 0) { svgcontent.insertBefore(node, svgcontent.firstChild); } }); // Move out of in-group editing mode - if(current_group) { + if (current_group) { leaveContext(); selectOnly([current_group]); } @@ -5173,13 +5143,13 @@ this.svgCanvasToString = function() { $(svgcontent).find('g:data(gsvg)').each(function() { var attrs = this.attributes; var len = attrs.length; - for(var i=0; i<len; i++) { - if(attrs[i].nodeName == 'id' || attrs[i].nodeName == 'style') { + for (var i=0; i<len; i++) { + if (attrs[i].nodeName == 'id' || attrs[i].nodeName == 'style') { len--; } } // No significant attributes, so ungroup - if(len <= 0) { + if (len <= 0) { var svg = this.firstChild; naked_svgs.push(svg); $(this).replaceWith(svg); @@ -5188,7 +5158,7 @@ this.svgCanvasToString = function() { var output = this.svgToString(svgcontent, 0); // Rewrap gsvg - if(naked_svgs.length) { + if (naked_svgs.length) { $(naked_svgs).each(function() { groupSvgElem(this); }); @@ -5207,7 +5177,8 @@ this.svgCanvasToString = function() { // Returns: // String with the given element as an SVG tag this.svgToString = function(elem, indent) { - var out = new Array(), toXml = svgedit.utilities.toXml; + var out = [], + toXml = svgedit.utilities.toXml; var unit = curConfig.baseUnit; var unit_re = new RegExp('^-?[\\d\\.]+' + unit + '$'); @@ -5220,14 +5191,14 @@ this.svgToString = function(elem, indent) { for (var i=0; i<indent; i++) out.push(" "); out.push("<"); out.push(elem.nodeName); - if(elem.id === 'svgcontent') { + if (elem.id === 'svgcontent') { // Process root element separately var res = getResolution(); var vb = ""; // TODO: Allow this by dividing all values by current baseVal // Note that this also means we should properly deal with this on import -// if(curConfig.baseUnit !== "px") { +// if (curConfig.baseUnit !== "px") { // var unit = curConfig.baseUnit; // var unit_m = svgedit.units.getTypeMap()[unit]; // res.w = svgedit.units.shortFloat(res.w / unit_m) @@ -5237,7 +5208,7 @@ this.svgToString = function(elem, indent) { // res.h += unit; // } - if(unit !== "px") { + if (unit !== "px") { res.w = svgedit.units.convertUnit(res.w, unit) + unit; res.h = svgedit.units.convertUnit(res.h, unit) + unit; } @@ -5251,7 +5222,7 @@ this.svgToString = function(elem, indent) { var el = this; $.each(this.attributes, function(i, attr) { var uri = attr.namespaceURI; - if(uri && !nsuris[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml' ) { + if (uri && !nsuris[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml' ) { nsuris[uri] = true; out.push(" xmlns:" + nsMap[uri] + '="' + uri +'"'); } @@ -5265,13 +5236,12 @@ this.svgToString = function(elem, indent) { var attrVal = toXml(attr.nodeValue); // Namespaces have already been dealt with, so skip - if(attr.nodeName.indexOf('xmlns:') === 0) continue; + if (attr.nodeName.indexOf('xmlns:') === 0) continue; // only serialize attributes we don't use internally - if (attrVal != "" && attr_names.indexOf(attr.localName) == -1) - { + if (attrVal != "" && attr_names.indexOf(attr.localName) == -1) { - if(!attr.namespaceURI || nsMap[attr.namespaceURI]) { + if (!attr.namespaceURI || nsMap[attr.namespaceURI]) { out.push(' '); out.push(attr.nodeName); out.push("=\""); out.push(attrVal); out.push("\""); @@ -5280,7 +5250,7 @@ this.svgToString = function(elem, indent) { } } else { // Skip empty defs - if(elem.nodeName === 'defs' && !elem.firstChild) return; + if (elem.nodeName === 'defs' && !elem.firstChild) return; var moz_attrs = ['-moz-math-font-style', '_moz-math-font-style']; for (var i=attrs.length-1; i>=0; i--) { @@ -5289,30 +5259,30 @@ this.svgToString = function(elem, indent) { //remove bogus attributes added by Gecko if (moz_attrs.indexOf(attr.localName) >= 0) continue; if (attrVal != "") { - if(attrVal.indexOf('pointer-events') === 0) continue; - if(attr.localName === "class" && attrVal.indexOf('se_') === 0) continue; + if (attrVal.indexOf('pointer-events') === 0) continue; + if (attr.localName === "class" && attrVal.indexOf('se_') === 0) continue; out.push(" "); - if(attr.localName === 'd') attrVal = pathActions.convertPath(elem, true); - if(!isNaN(attrVal)) { + if (attr.localName === 'd') attrVal = pathActions.convertPath(elem, true); + if (!isNaN(attrVal)) { attrVal = svgedit.units.shortFloat(attrVal); - } else if(unit_re.test(attrVal)) { + } else if (unit_re.test(attrVal)) { attrVal = svgedit.units.shortFloat(attrVal) + unit; } // Embed images when saving - if(save_options.apply + if (save_options.apply && elem.nodeName === 'image' && attr.localName === 'href' && save_options.images && save_options.images === 'embed') { var img = encodableImages[attrVal]; - if(img) attrVal = img; + if (img) attrVal = img; } // map various namespaces to our fixed namespace prefixes // (the default xmlns attribute itself does not get a prefix) - if(!attr.namespaceURI || attr.namespaceURI == svgns || nsMap[attr.namespaceURI]) { + if (!attr.namespaceURI || attr.namespaceURI == svgns || nsMap[attr.namespaceURI]) { out.push(attr.nodeName); out.push("=\""); out.push(attrVal); out.push("\""); } @@ -5395,15 +5365,15 @@ this.embedImage = function(val, callback) { encodableImages[val] = false; } last_good_img_url = val; - if(callback) callback(encodableImages[val]); + if (callback) callback(encodableImages[val]); }).attr('src',val); -} +}; // Function: setGoodImage // Sets a given URL to be a "last good image" URL this.setGoodImage = function(val) { last_good_img_url = val; -} +}; this.open = function() { // Nothing by default, handled by optional widget/extension @@ -5420,7 +5390,7 @@ this.save = function(opts) { // remove the selected outline before serializing clearSelection(); // Update save options if provided - if(opts) $.extend(save_options, opts); + if (opts) $.extend(save_options, opts); save_options.apply = true; // no need for doctype, see http://jwatt.org/svg/authoring/#doctype-declaration @@ -5447,12 +5417,12 @@ this.rasterExport = function() { var content = $(svgcontent); // Add font/text check if Canvas Text API is not implemented - if(!("font" in $('<canvas>')[0].getContext('2d'))) { + if (!("font" in $('<canvas>')[0].getContext('2d'))) { issue_list['text'] = uiStrings.exportNoText; } $.each(issue_list, function(sel, descr) { - if(content.find(sel).length) { + if (content.find(sel).length) { issues.push(descr); } }); @@ -5541,8 +5511,7 @@ var uniquifyElems = this.uniquifyElems = function(g) { // check xlink:href now var href = svgedit.utilities.getHref(n); // TODO: what if an <image> or <a> element refers to an element internally? - if(href && ref_elems.indexOf(n.nodeName) >= 0) - { + if (href && ref_elems.indexOf(n.nodeName) >= 0) { var refid = href.substr(1); if (refid) { if (!(refid in ids)) { @@ -5582,33 +5551,33 @@ var uniquifyElems = this.uniquifyElems = function(g) { } } } -} +}; // Function setUseData // Assigns reference data for each use element var setUseData = this.setUseData = function(parent) { var elems = $(parent); - if(parent.tagName !== 'use') { + if (parent.tagName !== 'use') { elems = elems.find('use'); } elems.each(function() { var id = getHref(this).substr(1); var ref_elem = svgedit.utilities.getElem(id); - if(!ref_elem) return; + if (!ref_elem) return; $(this).data('ref', ref_elem); - if(ref_elem.tagName == 'symbol' || ref_elem.tagName == 'svg') { + if (ref_elem.tagName == 'symbol' || ref_elem.tagName == 'svg') { $(this).data('symbol', ref_elem).data('ref', ref_elem); } }); -} +}; // Function convertGradients // Converts gradients from userSpaceOnUse to objectBoundingBox var convertGradients = this.convertGradients = function(elem) { var elems = $(elem).find('linearGradient, radialGradient'); - if(!elems.length && svgedit.browser.isWebkit()) { + if (!elems.length && svgedit.browser.isWebkit()) { // Bug in webkit prevents regular *Gradient selector search elems = $(elem).find('*').filter(function() { return (this.tagName.indexOf('Gradient') >= 0); @@ -5617,24 +5586,24 @@ var convertGradients = this.convertGradients = function(elem) { elems.each(function() { var grad = this; - if($(grad).attr('gradientUnits') === 'userSpaceOnUse') { + if ($(grad).attr('gradientUnits') === 'userSpaceOnUse') { // TODO: Support more than one element with this ref by duplicating parent grad var elems = $(svgcontent).find('[fill="url(#' + grad.id + ')"],[stroke="url(#' + grad.id + ')"]'); - if(!elems.length) return; + if (!elems.length) return; // get object's bounding box var bb = svgedit.utilities.getBBox(elems[0]); // This will occur if the element is inside a <defs> or a <symbol>, // in which we shouldn't need to convert anyway. - if(!bb) return; + if (!bb) return; - if(grad.tagName === 'linearGradient') { + if (grad.tagName === 'linearGradient') { var g_coords = $(grad).attr(['x1', 'y1', 'x2', 'y2']); // If has transform, convert var tlist = grad.gradientTransform.baseVal; - if(tlist && tlist.numberOfItems > 0) { + if (tlist && tlist.numberOfItems > 0) { var m = svgedit.math.transformListToTransform(tlist).matrix; var pt1 = svgedit.math.transformPoint(g_coords.x1, g_coords.y1, m); var pt2 = svgedit.math.transformPoint(g_coords.x2, g_coords.y2, m); @@ -5673,25 +5642,21 @@ var convertGradients = this.convertGradients = function(elem) { // // grad.removeAttribute('gradientUnits'); } - - } }); -} +}; // Function: convertToGroup // Converts selected/given <use> or child SVG element to a group var convertToGroup = this.convertToGroup = function(elem) { - if(!elem) { + if (!elem) { elem = selectedElements[0]; } var $elem = $(elem); - var batchCmd = new BatchCommand(); - var ts; - if($elem.data('gsvg')) { + if ($elem.data('gsvg')) { // Use the gsvg as the new group var svg = elem.firstChild; var pt = $(svg).attr(['x', 'y']); @@ -5705,7 +5670,7 @@ var convertToGroup = this.convertToGroup = function(elem) { tlist.appendItem(xform); recalculateDimensions(elem); call("selected", [elem]); - } else if($elem.data('symbol')) { + } else if ($elem.data('symbol')) { elem = $elem.data('symbol'); ts = $elem.attr('transform'); @@ -5713,7 +5678,7 @@ var convertToGroup = this.convertToGroup = function(elem) { var vb = elem.getAttribute('viewBox'); - if(vb) { + if (vb) { var nums = vb.split(' '); pos.x -= +nums[0]; pos.y -= +nums[1]; @@ -5734,12 +5699,12 @@ var convertToGroup = this.convertToGroup = function(elem) { var g = svgdoc.createElementNS(svgns, "g"); var childs = elem.childNodes; - for(var i = 0; i < childs.length; i++) { + for (var i = 0; i < childs.length; i++) { g.appendChild(childs[i].cloneNode(true)); } // Duplicate the gradients for Gecko, since they weren't included in the <symbol> - if(svgedit.browser.isGecko()) { + if (svgedit.browser.isGecko()) { var dupeGrads = $(svgedit.utilities.findDefs()).children('linearGradient,radialGradient,pattern').clone(); $(g).append(dupeGrads); } @@ -5753,7 +5718,7 @@ var convertToGroup = this.convertToGroup = function(elem) { uniquifyElems(g); // Put the dupe gradients back into <defs> (after uniquifying them) - if(svgedit.browser.isGecko()) { + if (svgedit.browser.isGecko()) { $(findDefs()).append( $(g).find('linearGradient,radialGradient,pattern') ); } @@ -5762,8 +5727,8 @@ var convertToGroup = this.convertToGroup = function(elem) { prev.after(g); - if(parent) { - if(!has_more) { + if (parent) { + if (!has_more) { // remove symbol/svg element var nextSibling = elem.nextSibling; parent.removeChild(elem); @@ -5774,7 +5739,7 @@ var convertToGroup = this.convertToGroup = function(elem) { setUseData(g); - if(svgedit.browser.isGecko()) { + if (svgedit.browser.isGecko()) { convertGradients(svgedit.utilities.findDefs()); } else { convertGradients(g); @@ -5782,17 +5747,23 @@ var convertToGroup = this.convertToGroup = function(elem) { // recalculate dimensions on the top-level children so that unnecessary transforms // are removed - svgedit.utilities.walkTreePost(g, function(n){try{recalculateDimensions(n)}catch(e){console.log(e)}}); + svgedit.utilities.walkTreePost(g, function(n){ + try { + recalculateDimensions(n); + } catch(e) { + console.log(e); + } + }); // Give ID for any visible element missing one $(g).find(visElems).each(function() { - if(!this.id) this.id = getNextId(); + if (!this.id) this.id = getNextId(); }); selectOnly([g]); var cm = pushGroupProperties(g, true); - if(cm) { + if (cm) { batchCmd.addSubCommand(cm); } @@ -5801,7 +5772,7 @@ var convertToGroup = this.convertToGroup = function(elem) { } else { console.log('Unexpected element to ungroup:', elem); } -} +}; // // Function: setSvgString @@ -5828,7 +5799,7 @@ this.setSvgString = function(xmlString) { // set new svg document // If DOM3 adoptNode() available, use it. Otherwise fall back to DOM2 importNode() - if(svgdoc.adoptNode) { + if (svgdoc.adoptNode) { svgcontent = svgdoc.adoptNode(newDoc.documentElement); } else { @@ -5853,10 +5824,10 @@ this.setSvgString = function(xmlString) { var image = this; preventClickDefault(image); var val = getHref(this); - if(val.indexOf('data:') === 0) { + if (val.indexOf('data:') === 0) { // Check if an SVG-edit data URI var m = val.match(/svgedit_url=(.*?);/); - if(m) { + if (m) { var url = decodeURIComponent(m[1]); $(new Image()).load(function() { image.setAttributeNS(xlinkns,'xlink:href',url); @@ -5870,13 +5841,13 @@ this.setSvgString = function(xmlString) { // Wrap child SVGs in group elements content.find('svg').each(function() { // Skip if it's in a <defs> - if($(this).closest('defs').length) return; + if ($(this).closest('defs').length) return; uniquifyElems(this); // Check if it already has a gsvg group var pa = this.parentNode; - if(pa.childNodes.length === 1 && pa.nodeName === 'g') { + if (pa.childNodes.length === 1 && pa.nodeName === 'g') { $(pa).data('gsvg', this); pa.id = pa.id || getNextId(); } else { @@ -5885,11 +5856,10 @@ this.setSvgString = function(xmlString) { }); // For Firefox: Put all paint elems in defs - if(svgedit.browser.isGecko()) { + if (svgedit.browser.isGecko()) { content.find('linearGradient, radialGradient, pattern').appendTo(svgedit.utilities.findDefs()); } - // Set ref element for <use> elements // TODO: This should also be done if the object is re-added through "redo" @@ -5899,7 +5869,13 @@ this.setSvgString = function(xmlString) { // recalculate dimensions on the top-level children so that unnecessary transforms // are removed - svgedit.utilities.walkTreePost(svgcontent, function(n){try{recalculateDimensions(n)}catch(e){console.log(e)}}); + svgedit.utilities.walkTreePost(svgcontent, function(n) { + try { + recalculateDimensions(n); + } catch(e) { + console.log(e); + } + }); var attrs = { id: 'svgcontent', @@ -5920,9 +5896,9 @@ this.setSvgString = function(xmlString) { // Set to 100 if not given var val = content.attr(dim); - if(!val) val = '100%'; + if (!val) val = '100%'; - if((val+'').substr(-1) === "%") { + if ((val+'').substr(-1) === "%") { // Use user units if percentage given percs = true; } else { @@ -5936,11 +5912,11 @@ this.setSvgString = function(xmlString) { // Give ID for any visible layer children missing one content.children().find(visElems).each(function() { - if(!this.id) this.id = getNextId(); + if (!this.id) this.id = getNextId(); }); // Percentage width/height, so let's base it on visible elements - if(percs) { + if (percs) { var bb = getStrokedBBox(); attrs.width = bb.width + bb.x; attrs.height = bb.height + bb.y; @@ -5948,8 +5924,8 @@ this.setSvgString = function(xmlString) { // Just in case negative numbers are given or // result from the percs calculation - if(attrs.width <= 0) attrs.width = 100; - if(attrs.height <= 0) attrs.height = 100; + if (attrs.width <= 0) attrs.width = 100; + if (attrs.height <= 0) attrs.height = 100; content.attr(attrs); this.contentW = attrs['width']; @@ -6004,15 +5980,15 @@ this.importSvgString = function(xmlString) { var useExisting = false; // Look for symbol and make sure symbol exists in image - if(import_ids[uid]) { - if( $(import_ids[uid].symbol).parents('#svgroot').length ) { + if (import_ids[uid]) { + if ( $(import_ids[uid].symbol).parents('#svgroot').length ) { useExisting = true; } } var batchCmd = new BatchCommand("Import SVG"); - if(useExisting) { + if (useExisting) { var symbol = import_ids[uid].symbol; var ts = import_ids[uid].xform; } else { @@ -6024,10 +6000,9 @@ this.importSvgString = function(xmlString) { // import new svg document into our document var svg; // If DOM3 adoptNode() available, use it. Otherwise fall back to DOM2 importNode() - if(svgdoc.adoptNode) { + if (svgdoc.adoptNode) { svg = svgdoc.adoptNode(newDoc.documentElement); - } - else { + } else { svg = svgdoc.importNode(newDoc.documentElement, true); } @@ -6048,8 +6023,7 @@ this.importSvgString = function(xmlString) { if (innerh > innerw) { var ts = "scale(" + (canvash/3)/vb[3] + ")"; - } - else { + } else { var ts = "scale(" + (canvash/3)/vb[2] + ")"; } @@ -6059,7 +6033,7 @@ this.importSvgString = function(xmlString) { var symbol = svgdoc.createElementNS(svgns, "symbol"); var defs = svgedit.utilities.findDefs(); - if(svgedit.browser.isGecko()) { + if (svgedit.browser.isGecko()) { // Move all gradients into root for Firefox, workaround for this bug: // https://bugzilla.mozilla.org/show_bug.cgi?id=353575 // TODO: Make this properly undo-able. @@ -6071,7 +6045,7 @@ this.importSvgString = function(xmlString) { symbol.appendChild(first); } var attrs = svg.attributes; - for(var i=0; i < attrs.length; i++) { + for (var i=0; i < attrs.length; i++) { var attr = attrs[i]; symbol.setAttribute(attr.nodeName, attr.nodeValue); } @@ -6081,13 +6055,12 @@ this.importSvgString = function(xmlString) { import_ids[uid] = { symbol: symbol, xform: ts - } + }; svgedit.utilities.findDefs().appendChild(symbol); batchCmd.addSubCommand(new InsertElementCommand(symbol)); } - var use_el = svgdoc.createElementNS(svgns, "use"); use_el.id = getNextId(); setHref(use_el, "#" + symbol.id); @@ -6159,9 +6132,9 @@ this.cloneLayer = function(name) { var current_layer = getCurrentDrawing().getCurrentLayer(); $(current_layer).after(new_layer); var childs = current_layer.childNodes; - for(var i = 0; i < childs.length; i++) { + for (var i = 0; i < childs.length; i++) { var ch = childs[i]; - if(ch.localName == 'title') continue; + if (ch.localName == 'title') continue; new_layer.appendChild(copyElem(ch)); } @@ -6378,15 +6351,15 @@ this.mergeLayer = function(skipHistory) { var batchCmd = new BatchCommand("Merge Layer"); var drawing = getCurrentDrawing(); var prev = $(drawing.current_layer).prev()[0]; - if(!prev) return; + if (!prev) return; var childs = drawing.current_layer.childNodes; var len = childs.length; var layerNextSibling = drawing.current_layer.nextSibling; batchCmd.addSubCommand(new RemoveElementCommand(drawing.current_layer, layerNextSibling, svgcontent)); - while(drawing.current_layer.firstChild) { + while (drawing.current_layer.firstChild) { var ch = drawing.current_layer.firstChild; - if(ch.localName == 'title') { + if (ch.localName == 'title') { var chNextSibling = ch.nextSibling; batchCmd.addSubCommand(new RemoveElementCommand(ch, chNextSibling, drawing.current_layer)); drawing.current_layer.removeChild(ch); @@ -6400,7 +6373,7 @@ this.mergeLayer = function(skipHistory) { // Remove current layer svgcontent.removeChild(drawing.current_layer); - if(!skipHistory) { + if (!skipHistory) { clearSelection(); identifyLayers(); @@ -6411,13 +6384,13 @@ this.mergeLayer = function(skipHistory) { drawing.current_layer = prev; return batchCmd; -} +}; this.mergeAllLayers = function() { var batchCmd = new BatchCommand("Merge all Layers"); var drawing = getCurrentDrawing(); drawing.current_layer = drawing.all_layers[drawing.getNumLayers()-1][1]; - while($(svgcontent).children('g').length > 1) { + while ($(svgcontent).children('g').length > 1) { batchCmd.addSubCommand(canvas.mergeLayer(true)); } @@ -6425,19 +6398,18 @@ this.mergeAllLayers = function() { identifyLayers(); call("changed", [svgcontent]); addCommandToHistory(batchCmd); -} +}; // Function: leaveContext // Return from a group context to the regular kind, make any previously // disabled elements enabled again var leaveContext = this.leaveContext = function() { var len = disabled_elems.length; - if(len) { - for(var i = 0; i < len; i++) { + if (len) { + for (var i = 0; i < len; i++) { var elem = disabled_elems[i]; - var orig = elData(elem, 'orig_opac'); - if(orig !== 1) { + if (orig !== 1) { elem.setAttribute('opacity', orig); } else { elem.removeAttribute('opacity'); @@ -6449,13 +6421,13 @@ var leaveContext = this.leaveContext = function() { call("contextset", null); } current_group = null; -} +}; // Function: setContext // Set the current context (for in-group editing) var setContext = this.setContext = function(elem) { leaveContext(); - if(typeof elem === 'string') { + if (typeof elem === 'string') { elem = svgedit.utilities.getElem(elem); } @@ -6474,7 +6446,7 @@ var setContext = this.setContext = function(elem) { clearSelection(); call("contextset", current_group); -} +}; // Group: Document functions @@ -6555,7 +6527,7 @@ this.getVersion = function() { // strs - Object with strings (see uiStrings for examples) this.setUiStrings = function(strs) { $.extend(uiStrings, strs.notification); -} +}; // Function: setConfig // Update configuration options with given values @@ -6564,22 +6536,22 @@ this.setUiStrings = function(strs) { // opts - Object with options (see curConfig for examples) this.setConfig = function(opts) { $.extend(curConfig, opts); -} +}; // Function: getTitle // Returns the current group/SVG's title contents this.getTitle = function(elem) { elem = elem || selectedElements[0]; - if(!elem) return; + if (!elem) return; elem = $(elem).data('gsvg') || $(elem).data('symbol') || elem; var childs = elem.childNodes; for (var i=0; i<childs.length; i++) { - if(childs[i].nodeName == 'title') { + if (childs[i].nodeName == 'title') { return childs[i].textContent; } } return ''; -} +}; // Function: setGroupTitle // Sets the group/SVG's title content @@ -6592,12 +6564,12 @@ this.setGroupTitle = function(val) { var batchCmd = new BatchCommand("Set Label"); - if(!val.length) { + if (!val.length) { // Remove title element var tsNextSibling = ts.nextSibling; batchCmd.addSubCommand(new RemoveElementCommand(ts[0], tsNextSibling, elem)); ts.remove(); - } else if(ts.length) { + } else if (ts.length) { // Change title contents var title = ts[0]; batchCmd.addSubCommand(new ChangeElementCommand(title, {'#text': title.textContent})); @@ -6611,13 +6583,13 @@ this.setGroupTitle = function(val) { } addCommandToHistory(batchCmd); -} +}; // Function: getDocumentTitle // Returns the current document title or an empty string if not found this.getDocumentTitle = function() { return canvas.getTitle(svgcontent); -} +}; // Function: setDocumentTitle // Adds/updates a title element for the document with the given name. @@ -6631,18 +6603,18 @@ this.setDocumentTitle = function(newtitle) { var batchCmd = new BatchCommand("Change Image Title"); for (var i=0; i<childs.length; i++) { - if(childs[i].nodeName == 'title') { + if (childs[i].nodeName == 'title') { doc_title = childs[i]; old_title = doc_title.textContent; break; } } - if(!doc_title) { + if (!doc_title) { doc_title = svgdoc.createElementNS(svgns, "title"); svgcontent.insertBefore(doc_title, svgcontent.firstChild); } - if(newtitle.length) { + if (newtitle.length) { doc_title.textContent = newtitle; } else { // No title given, so element is not necessary @@ -6650,7 +6622,7 @@ this.setDocumentTitle = function(newtitle) { } batchCmd.addSubCommand(new ChangeElementCommand(doc_title, {'#text': old_title})); addCommandToHistory(batchCmd); -} +}; // Function: getEditorNS // Returns the editor's namespace URL, optionally adds it to root element @@ -6658,11 +6630,11 @@ this.setDocumentTitle = function(newtitle) { // Parameters: // add - Boolean to indicate whether or not to add the namespace value this.getEditorNS = function(add) { - if(add) { + if (add) { svgcontent.setAttribute('xmlns:se', se_ns); } return se_ns; -} +}; // Function: setResolution // Changes the document's dimensions to the given size @@ -6680,11 +6652,11 @@ this.setResolution = function(x, y) { var w = res.w, h = res.h; var batchCmd; - if(x == 'fit') { + if (x == 'fit') { // Get bounding box var bbox = getStrokedBBox(); - if(bbox) { + if (bbox) { batchCmd = new BatchCommand("Fit Canvas to Content"); var visEls = getVisibleElements(); addToSelection(visEls); @@ -6706,7 +6678,7 @@ this.setResolution = function(x, y) { } if (x != w || y != h) { var handle = svgroot.suspendRedraw(1000); - if(!batchCmd) { + if (!batchCmd) { batchCmd = new BatchCommand("Change Image Dimensions"); } @@ -6735,7 +6707,7 @@ this.setResolution = function(x, y) { // position in the editor's canvas. this.getOffset = function() { return $(svgcontent).attr(['x', 'y']); -} +}; // Function: setBBoxZoom // Sets the zoom level on the canvas-side based on the given value @@ -6748,17 +6720,17 @@ this.setBBoxZoom = function(val, editor_w, editor_h) { var spacer = .85; var bb; var calcZoom = function(bb) { - if(!bb) return false; + if (!bb) return false; var w_zoom = Math.round((editor_w / bb.width)*100 * spacer)/100; var h_zoom = Math.round((editor_h / bb.height)*100 * spacer)/100; var zoomlevel = Math.min(w_zoom,h_zoom); canvas.setZoom(zoomlevel); return {'zoom': zoomlevel, 'bbox': bb}; - } + }; - if(typeof val == 'object') { + if (typeof val == 'object') { bb = val; - if(bb.width == 0 || bb.height == 0) { + if (bb.width == 0 || bb.height == 0) { var newzoom = bb.zoom?bb.zoom:current_zoom * bb.factor; canvas.setZoom(newzoom); return {'zoom': current_zoom, 'bbox': bb}; @@ -6768,8 +6740,8 @@ this.setBBoxZoom = function(val, editor_w, editor_h) { switch (val) { case 'selection': - if(!selectedElements[0]) return; - var sel_elems = $.map(selectedElements, function(n){ if(n) return n; }); + if (!selectedElements[0]) return; + var sel_elems = $.map(selectedElements, function(n){ if (n) return n; }); bb = getStrokedBBox(sel_elems); break; case 'canvas': @@ -6787,7 +6759,7 @@ this.setBBoxZoom = function(val, editor_w, editor_h) { return; } return calcZoom(bb); -} +}; // Function: setZoom // Sets the zoom to the given level @@ -6799,12 +6771,12 @@ this.setZoom = function(zoomlevel) { svgcontent.setAttribute("viewBox", "0 0 " + res.w/zoomlevel + " " + res.h/zoomlevel); current_zoom = zoomlevel; $.each(selectedElements, function(i, elem) { - if(!elem) return; + if (!elem) return; selectorManager.requestSelector(elem).resize(); }); pathActions.zoomChange(); runExtensions("zoomChanged", zoomlevel); -} +}; // Function: getMode // Returns the current editor mode string @@ -6847,11 +6819,15 @@ this.setColor = function(type, val, preventUndo) { while (i--) { var elem = selectedElements[i]; if (elem) { - if (elem.tagName == "g") - svgedit.utilities.walkTree(elem, function(e){if(e.nodeName!="g") elems.push(e);}); - else { - if(type == 'fill') { - if(elem.tagName != "polyline" && elem.tagName != "line") { + if (elem.tagName == "g") { + svgedit.utilities.walkTree(elem, function(e){ + if (e.nodeName != "g") { + elems.push(e); + } + }); + } else { + if (type == 'fill') { + if (elem.tagName != "polyline" && elem.tagName != "line") { elems.push(elem); } } else { @@ -6864,10 +6840,11 @@ this.setColor = function(type, val, preventUndo) { if (!preventUndo) { changeSelectedAttribute(type, val, elems); call("changed", elems); - } else + } else { changeSelectedAttributeNoUndo(type, val, elems); + } } -} +}; // Function: setGradient // Apply the current gradient to selected element's fill or stroke @@ -6875,7 +6852,7 @@ this.setColor = function(type, val, preventUndo) { // Parameters // type - String indicating "fill" or "stroke" to apply to an element var setGradient = this.setGradient = function(type) { - if(!cur_properties[type + '_paint'] || cur_properties[type + '_paint'].type == "solidColor") return; + if (!cur_properties[type + '_paint'] || cur_properties[type + '_paint'].type == "solidColor") return; var grad = canvas[type + 'Grad']; // find out if there is a duplicate gradient already in the defs var duplicate_grad = findDuplicateGradient(grad); @@ -6886,12 +6863,11 @@ var setGradient = this.setGradient = function(type) { grad = defs.appendChild( svgdoc.importNode(grad, true) ); // get next id and set it on the grad grad.id = getNextId(); - } - else { // use existing gradient + } else { // use existing gradient grad = duplicate_grad; } canvas.setColor(type, "url(#" + grad.id + ")"); -} +}; // Function: findDuplicateGradient // Check if exact gradient already exists @@ -6908,7 +6884,7 @@ var findDuplicateGradient = function(grad) { var rad_attrs = ['r','cx','cy','fx','fy']; while (i--) { var og = existing_grads[i]; - if(grad.tagName == "linearGradient") { + if (grad.tagName == "linearGradient") { if (grad.getAttribute('x1') != og.getAttribute('x1') || grad.getAttribute('y1') != og.getAttribute('y1') || grad.getAttribute('x2') != og.getAttribute('x2') || @@ -6922,10 +6898,10 @@ var findDuplicateGradient = function(grad) { var diff = false; $.each(rad_attrs, function(i, attr) { - if(grad_attrs[attr] != og_attrs[attr]) diff = true; + if (grad_attrs[attr] != og_attrs[attr]) diff = true; }); - if(diff) continue; + if (diff) continue; } // else could be a duplicate, iterate through stops @@ -6937,7 +6913,7 @@ var findDuplicateGradient = function(grad) { } var j = stops.length; - while(j--) { + while (j--) { var stop = stops[j]; var ostop = ostops[j]; @@ -6959,12 +6935,12 @@ var findDuplicateGradient = function(grad) { function reorientGrads(elem, m) { var bb = svgedit.utilities.getBBox(elem); - for(var i = 0; i < 2; i++) { + for (var i = 0; i < 2; i++) { var type = i === 0 ? 'fill' : 'stroke'; var attrVal = elem.getAttribute(type); - if(attrVal && attrVal.indexOf('url(') === 0) { + if (attrVal && attrVal.indexOf('url(') === 0) { var grad = svgedit.utilities.getRefElem(attrVal); - if(grad.tagName === 'linearGradient') { + if (grad.tagName === 'linearGradient') { var x1 = grad.getAttribute('x1') || 0; var y1 = grad.getAttribute('y1') || 0; var x2 = grad.getAttribute('x2') || 1; @@ -7014,7 +6990,7 @@ this.setPaint = function(type, paint) { cur_properties[type + '_paint'] = p; switch ( p.type ) { case "solidColor": - this.setColor(type, p.solidColor != "none" ? "#"+p.solidColor : "none");; + this.setColor(type, p.solidColor != "none" ? "#"+p.solidColor : "none"); break; case "linearGradient": case "radialGradient": @@ -7057,13 +7033,13 @@ this.setPaint = function(type, paint) { // if (p.type == "solidColor") { // this.setColor('fill', p.solidColor != "none" ? "#"+p.solidColor : "none"); // } -// else if(p.type == "linearGradient") { +// else if (p.type == "linearGradient") { // canvas.fillGrad = p.linearGradient; -// if(addGrad) setGradient(); +// if (addGrad) setGradient(); // } -// else if(p.type == "radialGradient") { +// else if (p.type == "radialGradient") { // canvas.fillGrad = p.radialGradient; -// if(addGrad) setGradient(); +// if (addGrad) setGradient(); // } // else { // // console.log("none!"); @@ -7083,7 +7059,7 @@ this.getStrokeWidth = function() { // Parameters: // val - A Float indicating the new stroke width value this.setStrokeWidth = function(val) { - if(val == 0 && ['line', 'path'].indexOf(current_mode) >= 0) { + if (val == 0 && ['line', 'path'].indexOf(current_mode) >= 0) { canvas.setStrokeWidth(1); return; } @@ -7095,7 +7071,7 @@ this.setStrokeWidth = function(val) { var elem = selectedElements[i]; if (elem) { if (elem.tagName == "g") - svgedit.utilities.walkTree(elem, function(e){if(e.nodeName!="g") elems.push(e);}); + svgedit.utilities.walkTree(elem, function(e){if (e.nodeName!="g") elems.push(e);}); else elems.push(elem); } @@ -7120,7 +7096,7 @@ this.setStrokeAttr = function(attr, val) { var elem = selectedElements[i]; if (elem) { if (elem.tagName == "g") - svgedit.utilities.walkTree(elem, function(e){if(e.nodeName!="g") elems.push(e);}); + svgedit.utilities.walkTree(elem, function(e){if (e.nodeName!="g") elems.push(e);}); else elems.push(elem); } @@ -7135,7 +7111,7 @@ this.setStrokeAttr = function(attr, val) { // Returns current style options this.getStyle = function() { return cur_shape; -} +}; // Function: getOpacity // Returns the current opacity @@ -7186,11 +7162,11 @@ this.getBlur = function(elem) { var val = 0; // var elem = selectedElements[0]; - if(elem) { + if (elem) { var filter_url = elem.getAttribute('filter'); - if(filter_url) { + if (filter_url) { var blur = svgedit.utilities.getElem(elem.id + '_blur'); - if(blur) { + if (blur) { val = blur.firstChild.getAttribute('stdDeviation'); } } @@ -7209,21 +7185,21 @@ this.getBlur = function(elem) { // Parameters: // val - The new stdDeviation value canvas.setBlurNoUndo = function(val) { - if(!filter) { + if (!filter) { canvas.setBlur(val); return; } - if(val === 0) { + if (val === 0) { // Don't change the StdDev, as that will hide the element. // Instead, just remove the value for "filter" changeSelectedAttributeNoUndo("filter", ""); filterHidden = true; } else { var elem = selectedElements[0]; - if(filterHidden) { + if (filterHidden) { changeSelectedAttributeNoUndo("filter", 'url(#' + elem.id + '_blur)'); } - if(svgedit.browser.isWebkit()) { + if (svgedit.browser.isWebkit()) { console.log('e', elem); elem.removeAttribute('filter'); elem.setAttribute('filter', 'url(#' + elem.id + '_blur)'); @@ -7231,7 +7207,7 @@ this.getBlur = function(elem) { changeSelectedAttributeNoUndo("stdDeviation", val, [filter.firstChild]); canvas.setBlurOffsets(filter, val); } - } + }; function finishChange() { var bCmd = canvas.undoMgr.finishUndoableChange(); @@ -7249,7 +7225,7 @@ this.getBlur = function(elem) { // filter - The filter DOM element to update // stdDev - The standard deviation value on which to base the offset size canvas.setBlurOffsets = function(filter, stdDev) { - if(stdDev > 3) { + if (stdDev > 3) { // TODO: Create algorithm here where size is based on expected blur assignAttributes(filter, { x: '-50%', @@ -7259,14 +7235,14 @@ this.getBlur = function(elem) { }, 100); } else { // Removing these attributes hides text in Chrome (see Issue 579) - if(!svgedit.browser.isWebkit()) { + if (!svgedit.browser.isWebkit()) { filter.removeAttribute('x'); filter.removeAttribute('y'); filter.removeAttribute('width'); filter.removeAttribute('height'); } } - } + }; // Function: setBlur // Adds/updates the blur filter to the selected element @@ -7275,7 +7251,7 @@ this.getBlur = function(elem) { // val - Float with the new stdDeviation blur value // complete - Boolean indicating whether or not the action should be completed (to add to the undo manager) canvas.setBlur = function(val, complete) { - if(cur_command) { + if (cur_command) { finishChange(); return; } @@ -7290,8 +7266,8 @@ this.getBlur = function(elem) { var batchCmd = new BatchCommand(); // Blur found! - if(filter) { - if(val === 0) { + if (filter) { + if (val === 0) { filter = null; } } else { @@ -7317,21 +7293,19 @@ this.getBlur = function(elem) { var changes = {filter: elem.getAttribute('filter')}; - if(val === 0) { + if (val === 0) { elem.removeAttribute("filter"); batchCmd.addSubCommand(new ChangeElementCommand(elem, changes)); return; - } else { - changeSelectedAttribute("filter", 'url(#' + elem_id + '_blur)'); - - batchCmd.addSubCommand(new ChangeElementCommand(elem, changes)); - - canvas.setBlurOffsets(filter, val); } + + changeSelectedAttribute("filter", 'url(#' + elem_id + '_blur)'); + batchCmd.addSubCommand(new ChangeElementCommand(elem, changes)); + canvas.setBlurOffsets(filter, val); cur_command = batchCmd; canvas.undoMgr.beginUndoableChange("stdDeviation", [filter?filter.firstChild:null]); - if(complete) { + if (complete) { canvas.setBlurNoUndo(val); finishChange(); } @@ -7366,7 +7340,7 @@ this.setBold = function(b) { { changeSelectedAttribute("font-weight", b ? "bold" : "normal"); } - if(!selectedElements[0].textContent) { + if (!selectedElements[0].textContent) { textActions.setCursor(); } }; @@ -7398,7 +7372,7 @@ this.setItalic = function(i) { { changeSelectedAttribute("font-style", i ? "italic" : "normal"); } - if(!selectedElements[0].textContent) { + if (!selectedElements[0].textContent) { textActions.setCursor(); } }; @@ -7417,7 +7391,7 @@ this.getFontFamily = function() { this.setFontFamily = function(val) { cur_text.font_family = val; changeSelectedAttribute("font-family", val); - if(selectedElements[0] && !selectedElements[0].textContent) { + if (selectedElements[0] && !selectedElements[0].textContent) { textActions.setCursor(); } }; @@ -7453,7 +7427,7 @@ this.getFontSize = function() { this.setFontSize = function(val) { cur_text.font_size = val; changeSelectedAttribute("font-size", val); - if(!selectedElements[0].textContent) { + if (!selectedElements[0].textContent) { textActions.setCursor(); } }; @@ -7485,7 +7459,7 @@ this.setTextContent = function(val) { // val - String with the image URL/path this.setImageURL = function(val) { var elem = selectedElements[0]; - if(!elem) return; + if (!elem) return; var attrs = $(elem).attr(['width', 'height']); var setsize = (!attrs.width || !attrs.height); @@ -7493,9 +7467,9 @@ this.setImageURL = function(val) { var cur_href = getHref(elem); // Do nothing if no URL change or size change - if(cur_href !== val) { + if (cur_href !== val) { setsize = true; - } else if(!setsize) return; + } else if (!setsize) return; var batchCmd = new BatchCommand("Change Image URL"); @@ -7504,7 +7478,7 @@ this.setImageURL = function(val) { "#href": cur_href })); - if(setsize) { + if (setsize) { $(new Image()).load(function() { var changes = $(elem).attr(['width', 'height']); @@ -7531,11 +7505,11 @@ this.setImageURL = function(val) { // val - String with the link URL/path this.setLinkURL = function(val) { var elem = selectedElements[0]; - if(!elem) return; - if(elem.tagName !== 'a') { + if (!elem) return; + if (elem.tagName !== 'a') { // See if parent is an anchor var parents_a = $(elem).parents('a'); - if(parents_a.length) { + if (parents_a.length) { elem = parents_a[0]; } else { return; @@ -7544,7 +7518,7 @@ this.setLinkURL = function(val) { var cur_href = getHref(elem); - if(cur_href === val) return; + if (cur_href === val) return; var batchCmd = new BatchCommand("Change Link URL"); @@ -7581,14 +7555,14 @@ this.makeHyperlink = function(url) { canvas.groupSelectedElements('a', url); // TODO: If element is a single "g", convert to "a" - // if(selectedElements.length > 1 && selectedElements[1]) { + // if (selectedElements.length > 1 && selectedElements[1]) { -} +}; // Function: removeHyperlink this.removeHyperlink = function() { canvas.ungroupSelectedElement(); -} +}; // Group: Element manipulation @@ -7614,15 +7588,15 @@ this.setSegType = function(new_type) { // If the getBBox flag is true, the resulting path's bounding box object. // Otherwise the resulting path element is returned. this.convertToPath = function(elem, getBBox) { - if(elem == null) { + if (elem == null) { var elems = selectedElements; $.each(selectedElements, function(i, elem) { - if(elem) canvas.convertToPath(elem); + if (elem) canvas.convertToPath(elem); }); return; } - if(!getBBox) { + if (!getBBox) { var batchCmd = new BatchCommand("Convert element to Path"); } @@ -7654,13 +7628,13 @@ this.convertToPath = function(elem, getBBox) { }); var eltrans = elem.getAttribute("transform"); - if(eltrans) { - path.setAttribute("transform",eltrans); + if (eltrans) { + path.setAttribute("transform", eltrans); } var id = elem.id; var parent = elem.parentNode; - if(elem.nextSibling) { + if (elem.nextSibling) { parent.insertBefore(path, elem); } else { parent.appendChild(path); @@ -7672,11 +7646,11 @@ this.convertToPath = function(elem, getBBox) { $.each(segs, function(j, seg) { var l = seg[0], pts = seg[1]; d += l; - for(var i=0; i < pts.length; i+=2) { + for (var 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; @@ -7686,7 +7660,7 @@ this.convertToPath = function(elem, getBBox) { case 'circle': var a = $(elem).attr(['rx', 'ry', 'cx', 'cy']); var cx = a.cx, cy = a.cy, rx = a.rx, ry = a.ry; - if(elem.tagName == 'circle') { + if (elem.tagName == 'circle') { rx = ry = $(elem).attr('r'); } @@ -7717,7 +7691,7 @@ this.convertToPath = function(elem, getBBox) { var x = b.x, y = b.y, w = b.width, h = b.height; var num = 4-num; // Why? Because! - if(!rx && !ry) { + if (!rx && !ry) { // Regular rect joinSegs([ ['M',[x, y]], @@ -7747,17 +7721,17 @@ this.convertToPath = function(elem, getBBox) { break; } - if(d) { + if (d) { path.setAttribute('d',d); } - if(!getBBox) { + if (!getBBox) { // Replace the current element with the converted one // Reorient if it has a matrix - if(eltrans) { + if (eltrans) { var tlist = svgedit.transformlist.getTransformList(path); - if(svgedit.math.hasMatrixTransform(tlist)) { + if (svgedit.math.hasMatrixTransform(tlist)) { pathActions.resetOrientation(path); } } @@ -7767,7 +7741,7 @@ this.convertToPath = function(elem, getBBox) { batchCmd.addSubCommand(new InsertElementCommand(path)); clearSelection(); - elem.parentNode.removeChild(elem) + elem.parentNode.removeChild(elem); path.setAttribute('id', id); path.removeAttribute("visibility"); addToSelection([path], true); @@ -7799,7 +7773,7 @@ this.convertToPath = function(elem, getBBox) { // elems - The DOM elements to apply the change to var changeSelectedAttributeNoUndo = function(attr, newValue, elems) { var handle = svgroot.suspendRedraw(1000); - if(current_mode == 'pathedit') { + if (current_mode == 'pathedit') { // Editing node pathActions.moveNode(attr, newValue); } @@ -7813,12 +7787,12 @@ var changeSelectedAttributeNoUndo = function(attr, newValue, elems) { if (elem == null) continue; // Go into "select" mode for text changes - if(current_mode === "textedit" && attr !== "#text" && elem.textContent.length) { + if (current_mode === "textedit" && attr !== "#text" && elem.textContent.length) { textActions.toSelectMode(elem); } // Set x,y vals on elements that don't have them - if((attr === 'x' || attr === 'y') && no_xy_elems.indexOf(elem.tagName) >= 0) { + if ((attr === 'x' || attr === 'y') && no_xy_elems.indexOf(elem.tagName) >= 0) { var bbox = getStrokedBBox([elem]); var diff_x = attr === 'x' ? newValue - bbox.x : 0; var diff_y = attr === 'y' ? newValue - bbox.y : 0; @@ -7837,7 +7811,7 @@ var changeSelectedAttributeNoUndo = function(attr, newValue, elems) { elem.textContent = newValue; // FF bug occurs on on rotated elements - if(/rotate/.test(elem.getAttribute('transform'))) { + if (/rotate/.test(elem.getAttribute('transform'))) { elem = ffClone(elem); } @@ -7865,8 +7839,8 @@ var changeSelectedAttributeNoUndo = function(attr, newValue, elems) { // selectedBBoxes[0] = svgedit.utilities.getBBox(elem); // Use the Firefox ffClone hack for text elements with gradients or // where other text attributes are changed. - if(svgedit.browser.isGecko() && elem.nodeName === 'text' && /rotate/.test(elem.getAttribute('transform'))) { - if((newValue+'').indexOf('url') === 0 || ['font-size','font-family','x','y'].indexOf(attr) >= 0 && elem.textContent) { + if (svgedit.browser.isGecko() && elem.nodeName === 'text' && /rotate/.test(elem.getAttribute('transform'))) { + if ((newValue+'').indexOf('url') === 0 || ['font-size','font-family','x','y'].indexOf(attr) >= 0 && elem.textContent) { elem = ffClone(elem); } } @@ -7878,9 +7852,9 @@ var changeSelectedAttributeNoUndo = function(attr, newValue, elems) { setTimeout(function() { // Due to element replacement, this element may no longer // be part of the DOM - if(!elem.parentNode) return; + if (!elem.parentNode) return; selectorManager.requestSelector(elem).resize(); - },0); + }, 0); } // if this element was rotated, and we changed the position of this element // we need to update the rotational transform attribute @@ -7954,7 +7928,7 @@ this.deleteSelectedElements = function() { svgedit.path.removePath_(t.id); // Get the parent if it's a single-child anchor - if(parent.tagName === 'a' && parent.childNodes.length === 1) { + if (parent.tagName === 'a' && parent.childNodes.length === 1) { t = parent; parent = parent.parentNode; } @@ -8014,7 +7988,7 @@ this.copySelectedElements = function() { this.pasteElements = function(type, x, y) { var cb = canvas.clipBoard; var len = cb.length; - if(!len) return; + if (!len) return; var pasted = []; var batchCmd = new BatchCommand('Paste elements'); @@ -8023,11 +7997,11 @@ this.pasteElements = function(type, x, y) { while (len--) { var elem = cb[len]; - if(!elem) continue; + if (!elem) continue; var copy = copyElem(elem); // See if elem with elem ID is in the DOM already - if(!svgedit.utilities.getElem(elem.id)) copy.id = elem.id; + if (!svgedit.utilities.getElem(elem.id)) copy.id = elem.id; pasted.push(copy); (current_group || getCurrentDrawing().getCurrentLayer()).appendChild(copy); @@ -8036,14 +8010,14 @@ this.pasteElements = function(type, x, y) { selectOnly(pasted); - if(type !== 'in_place') { + if (type !== 'in_place') { var ctr_x, ctr_y; - if(!type) { + if (!type) { ctr_x = lastClickPoint.x; ctr_y = lastClickPoint.y; - } else if(type === 'point') { + } else if (type === 'point') { ctr_x = x; ctr_y = y; } @@ -8062,12 +8036,10 @@ this.pasteElements = function(type, x, y) { var cmd = canvas.moveSelectedElements(dx, dy, false); batchCmd.addSubCommand(cmd); } - - addCommandToHistory(batchCmd); call("changed", pasted); -} +}; // Function: groupSelectedElements // Wraps all the selected elements in a group (g) element @@ -8075,14 +8047,14 @@ this.pasteElements = function(type, x, y) { // Parameters: // type - type of element to group into, defaults to <g> this.groupSelectedElements = function(type) { - if(!type) type = 'g'; + if (!type) type = 'g'; var cmd_str = ''; - switch ( type ) { + switch (type) { case "a": cmd_str = "Make hyperlink"; var url = ''; - if(arguments.length > 1) { + if (arguments.length > 1) { url = arguments[1]; } break; @@ -8101,7 +8073,7 @@ this.groupSelectedElements = function(type) { "id": getNextId() } }); - if(type === 'a') { + if (type === 'a') { setHref(g, url); } batchCmd.addSubCommand(new InsertElementCommand(g)); @@ -8155,32 +8127,32 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { var gattrs = $(g).attr(['filter', 'opacity']); var gfilter, gblur; - for(var i = 0; i < len; i++) { + for (var i = 0; i < len; i++) { var elem = children[i]; - if(elem.nodeType !== 1) continue; + if (elem.nodeType !== 1) continue; - if(gattrs.opacity !== null && gattrs.opacity !== 1) { + if (gattrs.opacity !== null && gattrs.opacity !== 1) { var c_opac = elem.getAttribute('opacity') || 1; var new_opac = Math.round((elem.getAttribute('opacity') || 1) * gattrs.opacity * 100)/100; changeSelectedAttribute('opacity', new_opac, [elem]); } - if(gattrs.filter) { + if (gattrs.filter) { var cblur = this.getBlur(elem); var orig_cblur = cblur; - if(!gblur) gblur = this.getBlur(g); - if(cblur) { + if (!gblur) gblur = this.getBlur(g); + if (cblur) { // Is this formula correct? cblur = (gblur-0) + (cblur-0); - } else if(cblur === 0) { + } else if (cblur === 0) { cblur = gblur; } // If child has no current filter, get group's filter or clone it. - if(!orig_cblur) { + if (!orig_cblur) { // Set group's filter to use first child's ID - if(!gfilter) { + if (!gfilter) { gfilter = svgedit.utilities.getRefElem(gattrs.filter); } else { // Clone the group's filter @@ -8197,7 +8169,7 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { changeSelectedAttribute('filter', 'url(#' + gfilter.id + ')', [elem]); // Update blur value - if(cblur) { + if (cblur) { changeSelectedAttribute('stdDeviation', cblur, [gfilter.firstChild]); canvas.setBlurOffsets(gfilter, cblur); } @@ -8206,13 +8178,13 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { var chtlist = svgedit.transformlist.getTransformList(elem); // Don't process gradient transforms - if(~elem.tagName.indexOf('Gradient')) chtlist = null; + if (~elem.tagName.indexOf('Gradient')) chtlist = null; // Hopefully not a problem to add this. Necessary for elements like <desc/> - if(!chtlist) continue; + if (!chtlist) continue; // Apparently <defs> can get get a transformlist, but we don't want it to have one! - if(elem.tagName === 'defs') continue; + if (elem.tagName === 'defs') continue; if (glist.numberOfItems) { // TODO: if the group's transform is just a rotate, we can always transfer the @@ -8259,7 +8231,7 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { } if (sangle) { - if(chtlist.numberOfItems) { + if (chtlist.numberOfItems) { chtlist.insertItemBefore(r2, 0); } else { chtlist.appendItem(r2); @@ -8269,14 +8241,13 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { if (trm.e || trm.f) { var tr = svgroot.createSVGTransform(); tr.setTranslate(trm.e, trm.f); - if(chtlist.numberOfItems) { + if (chtlist.numberOfItems) { chtlist.insertItemBefore(tr, 0); } else { chtlist.appendItem(tr); } } - } - else { // more complicated than just a rotate + } else { // more complicated than just a rotate // transfer the group's transform down to each child and then // call recalculateDimensions() @@ -8295,7 +8266,7 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { chtlist.appendItem(newxform); } var cmd = recalculateDimensions(elem); - if(cmd) batchCmd.addSubCommand(cmd); + if (cmd) batchCmd.addSubCommand(cmd); } } @@ -8312,7 +8283,7 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { if (undoable && !batchCmd.isEmpty()) { return batchCmd; } -} +}; // Function: ungroupSelectedElement @@ -8320,12 +8291,12 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { // significant recalculations to apply group's transforms, etc to its children this.ungroupSelectedElement = function() { var g = selectedElements[0]; - if($(g).data('gsvg') || $(g).data('symbol')) { + if ($(g).data('gsvg') || $(g).data('symbol')) { // Is svg, so actually convert to group - convertToGroup(g); return; - } else if(g.tagName === 'use') { + } + if (g.tagName === 'use') { // Somehow doesn't have data set, so retrieve var symbol = svgedit.utilities.getElem(getHref(g).substr(1)); $(g).data('symbol', symbol).data('ref', symbol); @@ -8333,7 +8304,7 @@ this.ungroupSelectedElement = function() { return; } var parents_a = $(g).parents('a'); - if(parents_a.length) { + if (parents_a.length) { g = parents_a[0]; } @@ -8342,7 +8313,7 @@ this.ungroupSelectedElement = function() { var batchCmd = new BatchCommand("Ungroup Elements"); var cmd = pushGroupProperties(g, true); - if(cmd) batchCmd.addSubCommand(cmd); + if (cmd) batchCmd.addSubCommand(cmd); var parent = g.parentNode; var anchor = g.nextSibling; @@ -8356,7 +8327,7 @@ this.ungroupSelectedElement = function() { var oldParent = elem.parentNode; // Remove child title elements - if(elem.tagName === 'title') { + if (elem.tagName === 'title') { var nextSibling = elem.nextSibling; batchCmd.addSubCommand(new RemoveElementCommand(elem, nextSibling, oldParent)); oldParent.removeChild(elem); @@ -8443,11 +8414,11 @@ this.moveUpDownSelected = function(dir) { var closest, found_cur; // jQuery sorts this list var list = $(getIntersectionList(getStrokedBBox([selected]))).toArray(); - if(dir == 'Down') list.reverse(); + if (dir == 'Down') list.reverse(); $.each(list, function() { - if(!found_cur) { - if(this == selected) { + if (!found_cur) { + if (this == selected) { found_cur = true; } return; @@ -8455,7 +8426,7 @@ this.moveUpDownSelected = function(dir) { closest = this; return false; }); - if(!closest) return; + if (!closest) return; var t = selected; var oldParent = t.parentNode; @@ -8486,7 +8457,7 @@ this.moveSelectedElements = function(dx, dy, undoable) { dx /= current_zoom; dy /= current_zoom; } - var undoable = undoable || true; + undoable = undoable || true; var batchCmd = new BatchCommand("position"); var i = selectedElements.length; while (i--) { @@ -8496,7 +8467,7 @@ this.moveSelectedElements = function(dx, dy, undoable) { // selectedBBoxes[0] = svgedit.utilities.getBBox(selected); // var b = {}; -// for(var j in selectedBBoxes[i]) b[j] = selectedBBoxes[i][j]; +// for (var j in selectedBBoxes[i]) b[j] = selectedBBoxes[i][j]; // selectedBBoxes[i] = b; var xform = svgroot.createSVGTransform(); @@ -8517,7 +8488,7 @@ this.moveSelectedElements = function(dx, dy, undoable) { xform.setTranslate(dx,dy); } - if(tlist.numberOfItems) { + if (tlist.numberOfItems) { tlist.insertItemBefore(xform, 0); } else { tlist.appendItem(xform); @@ -8715,7 +8686,7 @@ this.updateCanvas = function(w, h) { selectorManager.selectorParentGroup.setAttribute("transform","translate(" + x + "," + y + ")"); return {x:x, y:y, old_x:old_x, old_y:old_y, d_x:x - old_x, d_y:y - old_y}; -} +}; // Function: setBackground // Set the background of the editor (NOT the actual document) @@ -8728,8 +8699,8 @@ this.setBackground = function(color, url) { var border = $(bg).find('rect')[0]; var bg_img = svgedit.utilities.getElem('background_image'); border.setAttribute('fill',color); - if(url) { - if(!bg_img) { + if (url) { + if (!bg_img) { bg_img = svgdoc.createElementNS(svgns, "image"); assignAttributes(bg_img, { 'id': 'background_image', @@ -8741,10 +8712,10 @@ this.setBackground = function(color, url) { } setHref(bg_img, url); bg.appendChild(bg_img); - } else if(bg_img) { + } else if (bg_img) { bg_img.parentNode.removeChild(bg_img); } -} +}; // Function: cycleElement // Select the next/previous element within the current layer @@ -8755,18 +8726,18 @@ this.cycleElement = function(next) { var cur_elem = selectedElements[0]; var elem = false; var all_elems = getVisibleElements(current_group || getCurrentDrawing().getCurrentLayer()); - if(!all_elems.length) return; + if (!all_elems.length) return; if (cur_elem == null) { var num = next?all_elems.length-1:0; elem = all_elems[num]; } else { var i = all_elems.length; - while(i--) { - if(all_elems[i] == cur_elem) { + while (i--) { + if (all_elems[i] == cur_elem) { var num = next?i-1:i+1; - if(num >= all_elems.length) { + if (num >= all_elems.length) { num = 0; - } else if(num < 0) { + } else if (num < 0) { num = all_elems.length-1; } elem = all_elems[num]; @@ -8776,7 +8747,7 @@ this.cycleElement = function(next) { } selectOnly([elem], true); call("selected", selectedElements); -} +}; this.clear(); @@ -8829,8 +8800,8 @@ this.getPrivateMethods = function() { transformListToTransform: transformListToTransform, transformPoint: transformPoint, walkTree: svgedit.utilities.walkTree - } + }; return obj; }; -} +};