scour.py revision 2843dd8f06ff576409c19fe85c8fcacd7181baeb
# -*- coding: utf-8 -*-
# Scour
#
# Copyright 2010 Jeff Schiller
# Copyright 2010 Louis Simard
#
# This file is part of Scour, http://www.codedread.com/scour/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Notes:
# rubys' path-crunching ideas here: http://intertwingly.net/code/svgtidy/spec.rb
# (and implemented here: http://intertwingly.net/code/svgtidy/svgtidy.rb )
# Yet more ideas here: http://wiki.inkscape.org/wiki/index.php/Save_Cleaned_SVG
#
# * Process Transformations
# * Collapse all group based transformations
# Even more ideas here: http://esw.w3.org/topic/SvgTidy
# * analysis of path elements to see if rect can be used instead? (must also need to look
# at rounded corners)
# Next Up:
# - why are marker-start, -end not removed from the style attribute?
# - why are only overflow style properties considered and not attributes?
# - only remove unreferenced elements if they are not children of a referenced element
# - add an option to remove ids if they match the Inkscape-style of IDs
# - investigate point-reducing algorithms
# - parse transform attribute
# - if a <g> has only one element in it, collapse the <g> (ensure transform, etc are carried down)
# necessary to get true division
from __future__ import division
import os
import sys
import re
import math
from svg_regex import svg_parser
from svg_transform import svg_transform_parser
import optparse
from yocto_css import parseCssString
# Python 2.3- did not have Decimal
try:
from decimal import *
except ImportError:
# Import Psyco if available
try:
import psyco
except ImportError:
pass
APP = 'scour'
VER = '0.25'
COPYRIGHT = 'Copyright Jeff Schiller, Louis Simard, 2010'
'XLINK': 'http://www.w3.org/1999/xlink',
'SODIPODI': 'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd',
'INKSCAPE': 'http://www.inkscape.org/namespaces/inkscape',
'ADOBE_ILLUSTRATOR': 'http://ns.adobe.com/AdobeIllustrator/10.0/',
'ADOBE_GRAPHS': 'http://ns.adobe.com/Graphs/1.0/',
'ADOBE_SVG_VIEWER': 'http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/',
'ADOBE_VARIABLES': 'http://ns.adobe.com/Variables/1.0/',
'ADOBE_SFW': 'http://ns.adobe.com/SaveForWeb/1.0/',
'ADOBE_EXTENSIBILITY': 'http://ns.adobe.com/Extensibility/1.0/',
'ADOBE_FLOWS': 'http://ns.adobe.com/Flows/1.0/',
'ADOBE_IMAGE_REPLACEMENT': 'http://ns.adobe.com/ImageReplacement/1.0/',
'ADOBE_CUSTOM': 'http://ns.adobe.com/GenericCustomNamespace/1.0/',
'ADOBE_XPATH': 'http://ns.adobe.com/XPath/1.0/'
}
svgAttributes = [
'clip-rule',
'display',
'fill',
'fill-opacity',
'fill-rule',
'filter',
'font-family',
'font-size',
'font-stretch',
'font-style',
'font-variant',
'font-weight',
'line-height',
'marker',
'marker-end',
'marker-mid',
'marker-start',
'opacity',
'overflow',
'stop-color',
'stop-opacity',
'stroke',
'stroke-dasharray',
'stroke-dashoffset',
'stroke-linecap',
'stroke-linejoin',
'stroke-miterlimit',
'stroke-opacity',
'stroke-width',
'visibility'
]
colors = {
'aliceblue': 'rgb(240, 248, 255)',
'antiquewhite': 'rgb(250, 235, 215)',
'aqua': 'rgb( 0, 255, 255)',
'aquamarine': 'rgb(127, 255, 212)',
'azure': 'rgb(240, 255, 255)',
'beige': 'rgb(245, 245, 220)',
'bisque': 'rgb(255, 228, 196)',
'black': 'rgb( 0, 0, 0)',
'blanchedalmond': 'rgb(255, 235, 205)',
'blue': 'rgb( 0, 0, 255)',
'blueviolet': 'rgb(138, 43, 226)',
'brown': 'rgb(165, 42, 42)',
'burlywood': 'rgb(222, 184, 135)',
'cadetblue': 'rgb( 95, 158, 160)',
'chartreuse': 'rgb(127, 255, 0)',
'chocolate': 'rgb(210, 105, 30)',
'coral': 'rgb(255, 127, 80)',
'cornflowerblue': 'rgb(100, 149, 237)',
'cornsilk': 'rgb(255, 248, 220)',
'crimson': 'rgb(220, 20, 60)',
'cyan': 'rgb( 0, 255, 255)',
'darkblue': 'rgb( 0, 0, 139)',
'darkcyan': 'rgb( 0, 139, 139)',
'darkgoldenrod': 'rgb(184, 134, 11)',
'darkgray': 'rgb(169, 169, 169)',
'darkgreen': 'rgb( 0, 100, 0)',
'darkgrey': 'rgb(169, 169, 169)',
'darkkhaki': 'rgb(189, 183, 107)',
'darkmagenta': 'rgb(139, 0, 139)',
'darkolivegreen': 'rgb( 85, 107, 47)',
'darkorange': 'rgb(255, 140, 0)',
'darkorchid': 'rgb(153, 50, 204)',
'darkred': 'rgb(139, 0, 0)',
'darksalmon': 'rgb(233, 150, 122)',
'darkseagreen': 'rgb(143, 188, 143)',
'darkslateblue': 'rgb( 72, 61, 139)',
'darkslategray': 'rgb( 47, 79, 79)',
'darkslategrey': 'rgb( 47, 79, 79)',
'darkturquoise': 'rgb( 0, 206, 209)',
'darkviolet': 'rgb(148, 0, 211)',
'deeppink': 'rgb(255, 20, 147)',
'deepskyblue': 'rgb( 0, 191, 255)',
'dimgray': 'rgb(105, 105, 105)',
'dimgrey': 'rgb(105, 105, 105)',
'dodgerblue': 'rgb( 30, 144, 255)',
'firebrick': 'rgb(178, 34, 34)',
'floralwhite': 'rgb(255, 250, 240)',
'forestgreen': 'rgb( 34, 139, 34)',
'fuchsia': 'rgb(255, 0, 255)',
'gainsboro': 'rgb(220, 220, 220)',
'ghostwhite': 'rgb(248, 248, 255)',
'gold': 'rgb(255, 215, 0)',
'goldenrod': 'rgb(218, 165, 32)',
'gray': 'rgb(128, 128, 128)',
'grey': 'rgb(128, 128, 128)',
'green': 'rgb( 0, 128, 0)',
'greenyellow': 'rgb(173, 255, 47)',
'honeydew': 'rgb(240, 255, 240)',
'hotpink': 'rgb(255, 105, 180)',
'indianred': 'rgb(205, 92, 92)',
'indigo': 'rgb( 75, 0, 130)',
'ivory': 'rgb(255, 255, 240)',
'khaki': 'rgb(240, 230, 140)',
'lavender': 'rgb(230, 230, 250)',
'lavenderblush': 'rgb(255, 240, 245)',
'lawngreen': 'rgb(124, 252, 0)',
'lemonchiffon': 'rgb(255, 250, 205)',
'lightblue': 'rgb(173, 216, 230)',
'lightcoral': 'rgb(240, 128, 128)',
'lightcyan': 'rgb(224, 255, 255)',
'lightgoldenrodyellow': 'rgb(250, 250, 210)',
'lightgray': 'rgb(211, 211, 211)',
'lightgreen': 'rgb(144, 238, 144)',
'lightgrey': 'rgb(211, 211, 211)',
'lightpink': 'rgb(255, 182, 193)',
'lightsalmon': 'rgb(255, 160, 122)',
'lightseagreen': 'rgb( 32, 178, 170)',
'lightskyblue': 'rgb(135, 206, 250)',
'lightslategray': 'rgb(119, 136, 153)',
'lightslategrey': 'rgb(119, 136, 153)',
'lightsteelblue': 'rgb(176, 196, 222)',
'lightyellow': 'rgb(255, 255, 224)',
'lime': 'rgb( 0, 255, 0)',
'limegreen': 'rgb( 50, 205, 50)',
'linen': 'rgb(250, 240, 230)',
'magenta': 'rgb(255, 0, 255)',
'maroon': 'rgb(128, 0, 0)',
'mediumaquamarine': 'rgb(102, 205, 170)',
'mediumblue': 'rgb( 0, 0, 205)',
'mediumorchid': 'rgb(186, 85, 211)',
'mediumpurple': 'rgb(147, 112, 219)',
'mediumseagreen': 'rgb( 60, 179, 113)',
'mediumslateblue': 'rgb(123, 104, 238)',
'mediumspringgreen': 'rgb( 0, 250, 154)',
'mediumturquoise': 'rgb( 72, 209, 204)',
'mediumvioletred': 'rgb(199, 21, 133)',
'midnightblue': 'rgb( 25, 25, 112)',
'mintcream': 'rgb(245, 255, 250)',
'mistyrose': 'rgb(255, 228, 225)',
'moccasin': 'rgb(255, 228, 181)',
'navajowhite': 'rgb(255, 222, 173)',
'navy': 'rgb( 0, 0, 128)',
'oldlace': 'rgb(253, 245, 230)',
'olive': 'rgb(128, 128, 0)',
'olivedrab': 'rgb(107, 142, 35)',
'orange': 'rgb(255, 165, 0)',
'orangered': 'rgb(255, 69, 0)',
'orchid': 'rgb(218, 112, 214)',
'palegoldenrod': 'rgb(238, 232, 170)',
'palegreen': 'rgb(152, 251, 152)',
'paleturquoise': 'rgb(175, 238, 238)',
'palevioletred': 'rgb(219, 112, 147)',
'papayawhip': 'rgb(255, 239, 213)',
'peachpuff': 'rgb(255, 218, 185)',
'peru': 'rgb(205, 133, 63)',
'pink': 'rgb(255, 192, 203)',
'plum': 'rgb(221, 160, 221)',
'powderblue': 'rgb(176, 224, 230)',
'purple': 'rgb(128, 0, 128)',
'red': 'rgb(255, 0, 0)',
'rosybrown': 'rgb(188, 143, 143)',
'royalblue': 'rgb( 65, 105, 225)',
'saddlebrown': 'rgb(139, 69, 19)',
'salmon': 'rgb(250, 128, 114)',
'sandybrown': 'rgb(244, 164, 96)',
'seagreen': 'rgb( 46, 139, 87)',
'seashell': 'rgb(255, 245, 238)',
'sienna': 'rgb(160, 82, 45)',
'silver': 'rgb(192, 192, 192)',
'skyblue': 'rgb(135, 206, 235)',
'slateblue': 'rgb(106, 90, 205)',
'slategray': 'rgb(112, 128, 144)',
'slategrey': 'rgb(112, 128, 144)',
'snow': 'rgb(255, 250, 250)',
'springgreen': 'rgb( 0, 255, 127)',
'steelblue': 'rgb( 70, 130, 180)',
'tan': 'rgb(210, 180, 140)',
'teal': 'rgb( 0, 128, 128)',
'thistle': 'rgb(216, 191, 216)',
'tomato': 'rgb(255, 99, 71)',
'turquoise': 'rgb( 64, 224, 208)',
'violet': 'rgb(238, 130, 238)',
'wheat': 'rgb(245, 222, 179)',
'white': 'rgb(255, 255, 255)',
'whitesmoke': 'rgb(245, 245, 245)',
'yellow': 'rgb(255, 255, 0)',
'yellowgreen': 'rgb(154, 205, 50)',
}
default_attributes = { # excluded all attributes with 'auto' as default
# SVG 1.1 presentation attributes
'baseline-shift': 'baseline',
'clip-path': 'none',
'clip-rule': 'nonzero',
'color': '#000',
'color-interpolation-filters': 'linearRGB',
'color-interpolation': 'sRGB',
'direction': 'ltr',
'display': 'inline',
'enable-background': 'accumulate',
'fill': '#000',
'fill-opacity': '1',
'fill-rule': 'nonzero',
'filter': 'none',
'flood-color': '#000',
'flood-opacity': '1',
'font-size-adjust': 'none',
'font-size': 'medium',
'font-stretch': 'normal',
'font-style': 'normal',
'font-variant': 'normal',
'font-weight': 'normal',
'glyph-orientation-horizontal': '0deg',
'letter-spacing': 'normal',
'lighting-color': '#fff',
'marker': 'none',
'marker-start': 'none',
'marker-mid': 'none',
'marker-end': 'none',
'mask': 'none',
'opacity': '1',
'pointer-events': 'visiblePainted',
'stop-color': '#000',
'stop-opacity': '1',
'stroke': 'none',
'stroke-dasharray': 'none',
'stroke-dashoffset': '0',
'stroke-linecap': 'butt',
'stroke-linejoin': 'miter',
'stroke-miterlimit': '4',
'stroke-opacity': '1',
'stroke-width': '1',
'text-anchor': 'start',
'text-decoration': 'none',
'unicode-bidi': 'normal',
'visibility': 'visible',
'word-spacing': 'normal',
'writing-mode': 'lr-tb',
# SVG 1.2 tiny properties
'audio-level': '1',
'solid-color': '#000',
'solid-opacity': '1',
'text-align': 'start',
'vector-effect': 'none',
'viewport-fill': 'none',
'viewport-fill-opacity': '1',
}
# Integer constants for units.
INVALID = -1
NONE = 0
PCT = 1
PX = 2
PT = 3
PC = 4
EM = 5
EX = 6
CM = 7
MM = 8
IN = 9
# String to Unit. Basically, converts unit strings to their integer constants.
s2u = {
'': NONE,
'%': PCT,
'px': PX,
'pt': PT,
'pc': PC,
'em': EM,
'ex': EX,
'cm': CM,
'mm': MM,
'in': IN,
}
# Unit to String. Basically, converts unit integer constants to their corresponding strings.
u2s = {
NONE: '',
PCT: '%',
PX: 'px',
PT: 'pt',
PC: 'pc',
EM: 'em',
EX: 'ex',
CM: 'cm',
MM: 'mm',
IN: 'in',
}
# @staticmethod
try:
except KeyError:
# @staticmethod
try:
except KeyError:
return 'INVALID'
try: # simple unitless and no scientific notation
except ValueError:
# we know that the length string has an exponent, a unit, both or is invalid
# parse out number, exponent and unit
unitBegin = 0
if scinum != None:
# this will always match, no need to check it
else:
# unit or invalid
if numMatch != None:
if unitBegin != 0 :
if unitMatch != None :
# invalid
else:
# TODO: this needs to set the default for the given attribute (how?)
"""
Returns all elements with id attributes
"""
if elems is None:
elems = {}
if id != '' :
if node.hasChildNodes() :
# we are only really interested in nodes of type Element (1)
return elems
'marker-end', 'marker-mid']
"""
Returns the number of times an ID is referenced as well as all elements
that reference it. node is the node at which to start the search. The
return value is a map which has the id as key and each value is an array
where the first value is a count and the second value is a list of nodes
that referenced it.
Currently looks at fill, stroke, clip-path, mask, marker, and
xlink:href attributes.
"""
global referencingProps
if ids is None:
ids = {}
# TODO: input argument ids is clunky here (see below how it is called)
# GZ: alternative to passing dict, use **kwargs
# if this node is a style element, parse its text into CSS
# one stretch of text, please! (we could use node.normalize(), but
# this actually modifies the node, and we don't want to keep
# whitespace around if there's any)
if stylesheet != '':
return ids
# else if xlink:href is set, then grab the id
# we remove the hash mark from the beginning of the id
else:
# now get all style properties and the fill, stroke, filter attributes
for attr in referencingProps:
if node.hasChildNodes() :
return ids
global referencingProps
else:
# if the url has a quote in it, we need to compensate
id = None
# double-quote
# single-quote
if id != None:
else:
numIDsRemoved = 0
numElemsRemoved = 0
numAttrsRemoved = 0
numCommentBytes = 0
if elemsToRemove is None:
elemsToRemove = []
# only look at it if an element and not referenced anywhere else
# we only inspect the children of a group in a defs if the group
# is not referenced anywhere else
# we only remove if it is not one of our tags we always keep (see above)
return elemsToRemove
"""
Removes all unreferenced elements except for <svg>, <font>, <metadata>, <title>, and <desc>.
Also vacuums the defs of any non-referenced renderable elements.
Returns the number of unreferenced elements removed from the document.
"""
global numElemsRemoved
num = 0
# Remove certain unreferenced elements outside of defs
for id in identifiedElements:
if not id in referencedIDs:
num += 1
numElemsRemoved += 1
# Remove most unreferenced elements inside defs
for elem in elemsToRemove:
numElemsRemoved += 1
num += 1
return num
"""
Shortens ID names used in the document. ID names referenced the most often are assigned the
shortest ID names.
If the list unprotectedElements is provided, only IDs from this list will be shortened.
Returns the number of bytes saved by shortening ID names in the document.
"""
num = 0
if unprotectedElements is None:
# Make idList (list of idnames) sorted by reference count
# descending, so the highest reference count is first.
# First check that there's actually a defining element for the current ID name.
# (Cyn: I've seen documents with #id references but no element with that ID!)
if rid in unprotectedElements]
curIdNum = 1
# First make sure that *this* element isn't already using
# the ID name we want to give it.
# Then, skip ahead if the new ID is already in identifiedElement.
while curId in identifiedElements:
curIdNum += 1
# Then go rename it.
curIdNum += 1
return num
"""
Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z,
then from aa to az, ba to bz, etc., until zz.
"""
rid = ''
while idnum > 0:
idnum -= 1
return rid
"""
Changes the ID name from idFrom to idTo, on the declaring element
as well as all references in the document doc.
Updates identifiedElements and referencedIDs.
Does not handle the case where idTo is already the ID name
of another element in doc.
Returns the number of bytes saved by this replacement.
"""
num = 0
del identifiedElements[idFrom]
# Look for the idFrom ID name in each of the referencing elements,
# exactly like findReferencedElements would.
# Cyn: Duplicated processing!
# if this node is a style element, parse its text into CSS
# node.firstChild will be either a CDATA or a Text node now
if node.firstChild != None:
# concatenate the value of all children, in case
# there's a CDATASection node surrounded by whitespace
# nodes
# (node.normalize() will NOT work here, it only acts on Text nodes)
# not going to reparse the whole thing
# and now replace all the children with this new stylesheet.
# again, this is in case the stylesheet was a CDATASection
# if xlink:href is set to #idFrom, then change the id
# if the style has url(#idFrom), then change the id
if styles != '':
# now try the fill, stroke, filter attributes
for attr in referencingProps:
if oldValue != '':
del referencedIDs[idFrom]
return num
u"""Returns a list of unprotected IDs within the document doc."""
if not (options.protect_ids_noninkscape or
return identifiedElements
for prefix in protect_ids_prefixes:
if protected:
del identifiedElements[id]
return identifiedElements
"""
Removes the unreferenced ID attributes.
Returns the number of ID attributes removed
"""
global numIDsRemoved
keepTags = ['font']
num = 0;
numIDsRemoved += 1
num += 1
return num
global numAttrsRemoved
num = 0
# remove all namespace'd attributes from this element
attrsToRemove = []
for attrName in attrsToRemove :
num += 1
numAttrsRemoved += 1
# now recurse for children
return num
global numElemsRemoved
num = 0
# remove all namespace'd child nodes from this element
childrenToRemove = []
for child in childrenToRemove :
num += 1
numElemsRemoved += 1
# now recurse for children
return num
def removeMetadataElements(doc):
global numElemsRemoved
num = 0
# clone the list, as the tag list is live from the DOM
for element in elementsToRemove:
num += 1
numElemsRemoved += 1
return num
def removeNestedGroups(node):
"""
This walks further and further down the tree, removing groups
promoting their children up one level
"""
global numElemsRemoved
num = 0
groupsToRemove = []
# Only consider <g> elements for promotion if this element isn't a <switch>.
# (partial fix for bug 594930, required by the SVG spec however)
# only collapse group if it does not have a title or desc as a direct descendant,
break
else:
for g in groupsToRemove:
g.parentNode.removeChild(g)
numElemsRemoved += 1
num += 1
# now recurse for children
return num
"""
This recursively calls this function on all children of the passed in element
and then iterates over all child elements and removes common inheritable attributes
from the children and places them in the parent group. But only if the parent contains
nothing but element children and whitespace. The attributes are only removed from the
children if the children are not referenced by other elements in the document.
"""
num = 0
childElements = []
# recurse first into the children (depth-first)
# only add and recurse if the child is not referenced elsewhere
# else if the parent has non-whitespace text children, do not
# try to move common attributes
return num
# only process the children if there are more than one element
commonAttrs = {}
# add all inheritable properties of the first child element
# its fill attribute is not what we want to look at, we should look for the first
# non-animate/set element
# this is most of the inheritable properties from http://www.w3.org/TR/SVG11/propidx.html
'display-align',
'fill', 'fill-opacity', 'fill-rule',
'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch',
'font-style', 'font-variant', 'font-weight',
'letter-spacing',
'pointer-events', 'shape-rendering',
'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin',
'stroke-miterlimit', 'stroke-opacity', 'stroke-width',
'text-anchor', 'text-decoration', 'text-rendering', 'visibility',
'word-spacing', 'writing-mode']:
# we just add all the attributes from the first child
# for each subsequent child element
# skip first child
if childNum == 0:
continue
# if we are on an animateXXX/set element, ignore it (due to the 'fill' attribute)
continue
distinctAttrs = []
# loop through all current 'common' attributes
# if this child doesn't match that attribute, schedule it for removal
# remove those attributes which are not common
for name in distinctAttrs:
del commonAttrs[name]
# commonAttrs now has all the inheritable attributes which are common among all child elements
for child in childElements:
# update our statistic (we remove N*M attributes and add back in M attributes)
return num
"""
Creates <g> elements to contain runs of 3 or more
consecutive child elements having at least one common attribute.
Common attributes are not promoted to the <g> by this function.
This is handled by moveCommonAttributesToParentGroup.
If all children have a common attribute, an extra <g> is not created.
This function acts recursively on the given element.
"""
num = 0
global numElemsRemoved
# TODO perhaps all of the Presentation attributes in http://www.w3.org/TR/SVG/struct.html#GElement
# could be added here
# Cyn: These attributes are the same as in moveAttributesToParentGroup, and must always be
for curAttr in ['clip-rule',
'display-align',
'fill', 'fill-opacity', 'fill-rule',
'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch',
'font-style', 'font-variant', 'font-weight',
'letter-spacing',
'pointer-events', 'shape-rendering',
'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin',
'stroke-miterlimit', 'stroke-opacity', 'stroke-width',
'text-anchor', 'text-decoration', 'text-rendering', 'visibility',
'word-spacing', 'writing-mode']:
# Iterate through the children in reverse order, so item(i) for
# items we have yet to visit still returns the correct nodes.
while curChild >= 0:
# We're in a possible run! Track the value and run length.
# Run elements includes only element tags, no whitespace/comments/etc.
# Later, we calculate a run length which includes these.
runElements = 1
# Backtrack to get all the nodes having the same
# attribute value, preserving any nodes in-between.
while runStart > 0:
else:
runElements += 1
runStart -= 1
else: runStart -= 1
if runElements >= 3:
# Include whitespace/comment/etc. nodes in the run.
else: runEnd += 1
# If the current parent is a <g> already,
# do not act altogether on this attribute; all the
# children have it in common.
# Let moveCommonAttributesToParentGroup do it.
curChild = -1
continue
# otherwise, it might be an <svg> element, and
# even if all children have the same attribute value,
# it's going to be worth making the <g> since
# <svg> doesn't support attributes like 'stroke'.
# Fall through.
# Create a <g> element from scratch.
# We need the Document for this.
# Move the run of elements to the group.
# a) ADD the nodes to the new group.
# b) REMOVE the nodes from the element.
# Include the group in elem's children.
num += 1
numElemsRemoved -= 1
else:
curChild -= 1
else:
curChild -= 1
# each child gets the same treatment, recursively
return num
"""
This recursively calls this function on all children of the element passed in,
then removes any unused attributes on this elem if none of the children inherit it
"""
num = 0
childElements = []
# recurse first into the children (depth-first)
# only process the children if there are more than one element
# get all attribute values on this parent
unusedAttrs = {}
'display-align',
'fill', 'fill-opacity', 'fill-rule',
'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch',
'font-style', 'font-variant', 'font-weight',
'letter-spacing',
'pointer-events', 'shape-rendering',
'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin',
'stroke-miterlimit', 'stroke-opacity', 'stroke-width',
'text-anchor', 'text-decoration', 'text-rendering', 'visibility',
'word-spacing', 'writing-mode']:
# for each child, if at least one child inherits the parent's attribute, then remove
inheritedAttrs = []
for a in inheritedAttrs:
del unusedAttrs[a]
# unusedAttrs now has all the parent attributes that are unused
num += 1
return num
global numElemsRemoved
num = 0
stops = {}
stopsToRemove = []
# convert percentages into a floating point number
else:
offset = 0
# set the stop offset value to the integer or floating point equivalent
for stop in stopsToRemove:
num += 1
numElemsRemoved += 1
# linear gradients
return num
global numElemsRemoved
num = 0
# make sure to reset the ref'ed ids for when we are running this in testscour
# Make sure that there's actually a defining element for the current ID name.
# (Cyn: I've seen documents with #id references but no element with that ID!)
# found a gradient that is referenced by only 1 other element
# elem is a gradient referenced by only one other gradient (refElem)
# add the stops to the referencing gradient (this removes them from elem)
for stop in stopsToAdd:
# adopt the gradientUnits, spreadMethod, gradientTransform attributes if
# they are unspecified on refElem
# if both are radialGradients, adopt elem's fx,fy,cx,cy,r attributes if
# they are unspecified on refElem
# if both are linearGradients, adopt elem's x1,y1,x2,y2 attributes if
# they are unspecified on refElem
# now remove the xlink:href from refElem
# now delete elem
numElemsRemoved += 1
num += 1
return num
def removeDuplicateGradients(doc):
global numElemsRemoved
num = 0
gradientsToRemove = {}
duplicateToMaster = {}
# TODO: should slice grads from 'grad' here to optimize
# do not compare gradient to itself
# compare grad to ograd (all properties, then all stops)
# if attributes do not match, go to next gradient
for attr in ['gradientUnits','spreadMethod','gradientTransform','x1','y1','x2','y2','cx','cy','fx','fy','r']:
break;
if someGradAttrsDoNotMatch: continue
# compare xlink:href values too
continue
# all gradient properties match, now time to compare stops
# now compare stops
if stopsNotEqual: break
break
if stopsNotEqual: continue
# ograd is a duplicate of grad, we schedule it to be removed UNLESS
# ograd is ALREADY considered a 'master' element
gradientsToRemove[grad] = []
# get a collection of all elements that are referenced and their referencing elements
# print 'master='+master_id
# if the duplicate gradient no longer has a parent that means it was
# already re-mapped to another master gradient
if not dupGrad.parentNode: continue
# print 'dup='+dup_id
# print referencedIDs[dup_id]
# for each element that referenced the gradient we are going to remove
# find out which attribute referenced the duplicate gradient
# now that all referencing elements have been re-mapped to the master
# it is safe to remove this gradient from the document
numElemsRemoved += 1
num += 1
return num
u"""Returns the style attribute of a node as a dictionary."""
styleMap = { }
return styleMap
else:
return {}
u"""Sets the style attribute of a node to the dictionary ``styleMap``."""
if fixedStyle != '' :
return node
num = 0
if styleMap:
# I've seen this enough to know that I need to correct it:
# fill: url(#linearGradient4918) rgb(0, 0, 0);
if len(chunk) == 2 and (chunk[0][:5] == 'url(#' or chunk[0][:6] == 'url("#' or chunk[0][:6] == "url('#") and chunk[1] == 'rgb(0, 0, 0)' :
num += 1
# Here is where we can weed out unnecessary styles like:
# opacity:1
# if opacity='0' then all fill and stroke properties are useless, remove them
if opacity == 0.0 :
'stroke-opacity', 'stroke-miterlimit', 'stroke-linecap', 'stroke-dasharray',
'stroke-dashoffset', 'stroke-opacity'] :
del styleMap[uselessStyle]
num += 1
# if stroke:none, then remove all stroke-related properties (stroke-width, etc)
# TODO: should also detect if the computed value of this element is stroke="none"
'stroke-linecap', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-opacity'] :
del styleMap[strokestyle]
num += 1
# TODO: This is actually a problem if a parent element has a specified stroke
# we need to properly calculate computed values
del styleMap['stroke']
# if fill:none, then remove all fill-related properties (fill-rule, etc)
num += 1
# fill-opacity: 0
if fillOpacity == 0.0 :
del styleMap[uselessFillStyle]
num += 1
# stroke-opacity: 0
if strokeOpacity == 0.0 :
'stroke-dasharray', 'stroke-dashoffset' ] :
num += 1
# stroke-width: 0
'stroke-dasharray', 'stroke-dashoffset', 'stroke-opacity' ] :
num += 1
# remove font properties for non-text elements
# I've actually observed this in real SVG content
if not mayContainTextNodes(node):
'font-style', 'font-variant', 'font-weight',
'letter-spacing', 'line-height', 'kerning',
'text-align', 'text-anchor', 'text-decoration',
'text-rendering', 'unicode-bidi',
'word-spacing', 'writing-mode'] :
num += 1
# remove inkscape-specific styles
# TODO: need to get a full list of these
for inkscapeStyle in ['-inkscape-font-specification']:
del styleMap[inkscapeStyle]
num += 1
# overflow specified on element other than svg, marker, pattern
del styleMap['overflow']
num += 1
# it is a marker, pattern or svg
# as long as this node is not the document <svg>, then only
# remove overflow='hidden'. See
# http://www.w3.org/TR/2010/WD-SVG11-20100622/masking.html#OverflowProperty
del styleMap['overflow']
num += 1
# else if outer svg has a overflow="visible", we can remove it
del styleMap['overflow']
num += 1
# now if any of the properties match known SVG attributes we prefer attributes
# over style so emit them and remove them from the style map
if options.style_to_xml:
if propName in svgAttributes :
# recurse for our child elements
return num
def mayContainTextNodes(node):
"""
Returns True if the passed-in node is probably a text element, or at least
one of its descendants is probably a text element.
If False is returned, it is guaranteed that the passed-in node has no
business having text-based attributes.
If True is returned, the passed-in node should not have its text-based
attributes removed.
"""
# Cached result of a prior call?
try:
return node.mayContainTextNodes
except AttributeError:
pass
# Comment, text and CDATA nodes don't have attributes and aren't containers
# Non-SVG elements? Unknown elements!
# Blacklisted elements. Those are guaranteed not to be text elements.
'polyline', 'path', 'image', 'stop']:
# Group elements. If we're missing any here, the default of True is used.
'linearGradient', 'radialGradient', 'symbol']:
if mayContainTextNodes(child):
# Everything else should be considered a future SVG-version text element
# at best, or an unknown element at worst. result will stay True.
# Cache this result before returning it.
return result
u"""Adds an attribute to a set of attributes.
Related attributes are also included."""
if taintedAttribute == 'marker':
return taintedSet
u"""'tainted' keeps a set of attributes defined in parent nodes.
For such attributes, we don't delete attributes with default values."""
num = 0
# gradientUnits: objectBoundingBox
num += 1
# spreadMethod: pad
num += 1
# x1: 0%
num += 1
# y1: 0%
num += 1
# x2: 100%
num += 1
# y2: 0%
num += 1
# fx: equal to rx
num += 1
# fy: equal to ry
num += 1
# cx: 50%
num += 1
# cy: 50%
num += 1
# r: 50%
num += 1
# Summarily get rid of some more attributes
for attribute in attributes:
num += 1
else:
# These attributes might also occur as styles
num += 1
else:
# recurse for our child elements
return num
def convertColor(value):
"""
Converts the input color string and returns a #RRGGBB (or #RGB if possible) string
"""
s = value
s = colors[s]
if rgbpMatch != None :
s = '#%02x%02x%02x' % (r, g, b)
else:
if rgbMatch != None :
s = '#%02x%02x%02x' % (r, g, b)
if s[0] == '#':
s = s.lower()
s = '#'+s[1]+s[3]+s[5]
return s
def convertColors(element) :
"""
Recursively converts all color properties into #RRGGBB format if shorter
"""
numBytes = 0
# set up list of color attributes for each element type
attrsToConvert = []
'line', 'polyline', 'path', 'g', 'a']:
attrsToConvert = ['stop-color']
attrsToConvert = ['solid-color']
# now convert all the color formats
for attr in attrsToConvert:
if oldColorValue != '':
# colors might also hide in styles
# now recurse for our child elements
return numBytes
# TODO: go over what this method does and see if there is a way to optimize it
# reusing data structures, etc
"""
Cleans the path string (d attribute) of the element
"""
global numBytesSavedInPathData
global numPathSegmentsReduced
global numCurvesStraightened
# this gets the parser object from svg_regex.py
# This determines whether the stroke has round linecaps. If it does,
# we do not want to collapse empty segments, as they are actually rendered.
# The first command must be a moveto, and whether it's relative (m)
# or absolute (M), the first set of coordinates *is* absolute. So
# the first iteration of the loop below will get x,y and startx,starty.
# convert absolute coordinates into relative ones.
# Reuse the data structure 'path', since we're not adding or removing subcommands.
# Also reuse the coordinate lists since we're not adding or removing any.
i = 0
# adjust abs to rel
# only the A command has some values that we don't want to adjust (radii, rotation, flags)
if cmd == 'A':
data[i+5] -= x
data[i+6] -= y
x += data[i+5]
y += data[i+6]
elif cmd == 'a':
elif cmd == 'H':
data[i] -= x
x += data[i]
elif cmd == 'h':
elif cmd == 'V':
data[i] -= y
y += data[i]
elif cmd == 'v':
elif cmd == 'M':
# If this is a path starter, don't convert its first
# coordinate to relative; that would just make it (0, 0)
if pathIndex != 0:
data[0] -= x
data[1] -= y
i = 2
data[i] -= x
data[i+1] -= y
x += data[i]
y += data[i+1]
data[i] -= x
data[i+1] -= y
x += data[i]
y += data[i+1]
elif cmd in ['m']:
if pathIndex == 0:
# START OF PATH - this is an absolute moveto
# followed by relative linetos
i = 2
else:
x += data[i]
y += data[i+1]
data[i] -= x
data[i+1] -= y
data[i+2] -= x
data[i+3] -= y
x += data[i+2]
y += data[i+3]
elif cmd == 'C':
data[i] -= x
data[i+1] -= y
data[i+2] -= x
data[i+3] -= y
data[i+4] -= x
data[i+5] -= y
x += data[i+4]
y += data[i+5]
elif cmd == 'c':
# remove empty segments
# Reuse the data structure 'path' and the coordinate lists, even if we're
# deleting items, because these deletions are relatively cheap.
if not withRoundLineCaps:
i = 0
if cmd == 'm':
# remove m0,0 segments
# 'm0,0 x,y' can be replaces with 'lx,y',
# except the first m which is a required absolute moveto
else: # else skip move coordinate
i = 2
del data[i:i+2]
else:
i += 2
elif cmd == 'c':
del data[i:i+6]
else:
i += 6
elif cmd == 'a':
del data[i:i+7]
else:
i += 7
elif cmd == 'q':
del data[i:i+4]
else:
i += 4
# fixup: Delete subcommands having no coordinates.
# convert straight curves into lines
i = 0
if cmd == 'c':
newData = []
# since all commands are now relative, we can think of previous point as (0,0)
# and new point (dx,dy) is (data[i+4],data[i+5])
if dx == 0:
else:
# flush any existing curve coords first
if newData:
newData = []
# now create a straight line segment
else:
i += 6
# collapse all consecutive commands of the same type into one command
prevCmd = ''
prevData = []
newPath = []
# flush the previous command if it is not the same type as the current command
if prevCmd != '':
prevCmd = ''
prevData = []
# if the previous and current commands are the same type,
# or the previous command is moveto and the current is lineto, collapse,
# but only if they are not move commands (since move can contain implicit lineto commands)
# save last command and data
else:
# flush last command and data
if prevCmd != '':
# convert to shorthand path segments where possible
newPath = []
# convert line segments into h,v where possible
if cmd == 'l':
i = 0
lineTuples = []
if data[i] == 0:
# vertical
if lineTuples:
# flush the existing line command
lineTuples = []
# append the v and then the remaining line coords
if lineTuples:
# flush the line command, then append the h and then the remaining line coords
lineTuples = []
else:
i += 2
if lineTuples:
# also handle implied relative linetos
elif cmd == 'm':
i = 2
if data[i] == 0:
# vertical
if lineTuples:
# flush the existing m/l command
lineTuples = []
# append the v and then the remaining line coords
if lineTuples:
# flush the m/l command, then append the h and then the remaining line coords
lineTuples = []
else:
i += 2
if lineTuples:
# convert Bézier curve segments into s where possible
elif cmd == 'c':
i = 0
curveTuples = []
# rotate by 180deg means negate both coordinates
# if the previous control point is equal then we can substitute a
# shorthand bezier command
if curveTuples:
curveTuples = []
# append the s command
else:
j = 0
while j <= 5:
j += 1
# set up control point for next curve segment
i += 6
if curveTuples:
# convert quadratic curve segments into t where possible
elif cmd == 'q':
i = 0
curveTuples = []
if curveTuples:
curveTuples = []
# append the t command
else:
j = 0;
while j <= 3:
j += 1
i += 4
if curveTuples:
else:
# for each h or v, collapse unnecessary coordinates that run in the same direction
# i.e. "h-100-100" becomes "h-200" but "h300-100" does not change
# Reuse the data structure 'path', since we're not adding or removing subcommands.
# Also reuse the coordinate lists, even if we're deleting items, because these
# deletions are relatively cheap.
coordIndex = 1
del data[coordIndex]
else:
coordIndex += 1
# it is possible that we have consecutive h, v, c, t commands now
# so again collapse all consecutive commands of the same type into one command
prevCmd = ''
prevData = []
# flush the previous command if it is not the same type as the current command
if prevCmd != '':
prevCmd = ''
prevData = []
# if the previous and current commands are the same type, collapse
# save last command and data
else:
# flush last command and data
if prevCmd != '':
def parseListOfPoints(s):
"""
Parse string into a list of points.
Returns a list of containing an even number of coordinate strings
"""
i = 0
# (wsp)? comma-or-wsp-separated coordinate pairs (wsp)?
# coordinate-pair = coordinate comma-or-wsp coordinate
# coordinate = sign? integer
# comma-wsp: (wsp+ comma? wsp*) | (comma wsp*)
nums = []
# also, if 100-100 is found, split it into two also
# <polygon points="100,-100,100-100,100-100-100,-100-100" />
# this string didn't have any negative coordinates
# we got negative coords
else:
# first number could be positive
if j == 0:
# otherwise all other strings will be negative
else:
# unless we accidentally split a number that was in scientific notation
# and had a negative exponent (500.00e-1)
else:
# if we have an odd number of points, return empty
# now resolve into Decimal values
i = 0
try:
return []
i += 2
return nums
"""
Remove unnecessary closing point of polygon points attribute
"""
global numPointsRemovedFromPolygon
if N >= 2:
del pts[-2:]
"""
Scour the polyline points attribute
"""
"""
Reserializes the path data with some cleanups.
"""
# this fixes an issue outlined in Fix https://bugs.launchpad.net/scour/+bug/412754
"""
Reserializes the transform data with some cleanups.
"""
return ' '.join(
) + ')'
)
"""
Serializes coordinate data with some cleanups:
- removes all trailing zeros after the decimal
- integerize coordinates if possible
- removes extraneous whitespace
- adds spaces between values in a subcommand if required (or if forceCommaWsp is True)
"""
if data != None:
newData = []
c = 0
previousCoord = ''
# only need the comma if the current number starts with a digit
# (numbers can start with - without needing a comma before)
# or if forceCommaWsp is True
# or if this number starts with a dot and the previous number
# had *no* dot or exponent (so we can go like -5.5.5 for -5.5,0.5
# and 4e4.5 for 40000,0.5)
if c > 0 and (forceCommaWsp
):
# add the scoured coordinate to the path string
c += 1
# What we need to do to work around GNOME bugs 548494, 563933 and
# 620565, which are being fixed and unfixed in Ubuntu, is
# to make sure that a dot doesn't immediately follow a command
# (so 'h50' and 'h0.5' are allowed, but not 'h.5').
# Then, we need to add a space character after any coordinates
# having an 'e' (scientific notation), so as to have the exponent
# separate from the next number.
else:
return ''
def scourLength(length):
"""
Scours a length. Accepts units.
"""
"""
Scours the numeric part of a length only. Does not accept units.
This is faster than scourLength on elements guaranteed not to
contain units.
"""
# reduce to the proper number of digits
# if the value is an integer, it may still have .0[...] attached to it for some reason
# remove those
# gather the non-scientific notation version of the coordinate.
# this may actually be in scientific notation if the value is
# sufficiently large or small, so this is a misnomer.
if not needsRendererWorkaround:
# and then the scientific notation version, with E+NUMBER replaced with
# just eNUMBER, since SVG accepts this.
else: return nonsci
else: return nonsci
def reducePrecision(element) :
"""
Because opacities, letter spacings, stroke widths and all that don't need
to be preserved in SVG files with 9 digits of precision.
Takes all of these attributes, in the given element node and its children,
and reduces their precision to the current Decimal context's precision.
Also checks for the attributes actually being lengths, not 'inherit', 'none'
or anything that isn't an SVGLength.
Returns the number of bytes saved after performing these reductions.
"""
num = 0
'stroke-opacity', 'stop-opacity', 'stroke-miterlimit',
'stroke-dashoffset', 'letter-spacing', 'word-spacing',
'kerning', 'font-size-adjust', 'font-size',
'stroke-width']:
if val != '':
# repeat for attributes hidden in styles
return num
def optimizeAngle(angle):
"""
Because any rotation can be expressed within 360 degrees
of any given number, and since negative angles sometimes
are one character longer than corresponding positive angle,
we shorten the number to one in the range to [-90, 270[.
"""
# First, we put the new angle in the range ]-360, 360[.
# The modulo operator yields results with the sign of the
# divisor, so for negative dividends, we preserve the sign
# of the angle.
else: angle %= 360
# 720 degrees is unneccessary, as 360 covers all angles.
# As "-x" is shorter than "35x" and "-xxx" one character
# longer than positive angles <= 260, we constrain angle
# range to [-90, 270[ (or, equally valid: ]-100, 260]).
return angle
def optimizeTransform(transform):
"""
Optimises a series of transformations parsed from a single
transform="" attribute.
The transformation list is modified in-place.
"""
# FIXME: reordering these would optimize even more cases:
# first: Fold consecutive runs of the same transformation
# extra: Attempt to cast between types to create sameness:
# "matrix(0 1 -1 0 0 0) rotate(180) scale(-1)" all
# are rotations (90, 180, 180) -- thus "rotate(90)"
# second: Simplify transforms where numbers are optional.
# third: Attempt to simplify any single remaining matrix()
#
# if there's only one transformation and it's a matrix,
# try to make it a shorter non-matrix transformation
# NOTE: as matrix(a b c d e f) in SVG means the matrix:
# |¯ a c e ¯| make constants |¯ A1 A2 A3 ¯|
# | b d f | translating them | B1 B2 B3 |
# |_ 0 0 1 _| to more readable |_ 0 0 1 _|
# |¯ 1 0 0 ¯|
# | 0 1 0 | Identity matrix (no transformation)
# |_ 0 0 1 _|
del transform[0]
# |¯ 1 0 X ¯|
# | 0 1 Y | Translation by (X, Y).
# |_ 0 0 1 _|
# |¯ X 0 0 ¯|
# | 0 Y 0 | Scaling by (X, Y).
# |_ 0 0 1 _|
# |¯ cos(A) -sin(A) 0 ¯| Rotation by angle A,
# | sin(A) cos(A) 0 | clockwise, about the origin.
# |_ 0 0 1 _| A is in degrees, [-180...180].
# as cos² A + sin² A == 1 and as decimal trig is approximate:
# FIXME: the "epsilon" term here should really be some function
# of the precision of the (sin|cos)_A terms, not 1e-15:
# while asin(A) and acos(A) both only have an 180° range
# the sign of sin(A) and cos(A) varies across quadrants,
# letting us hone in on the angle the matrix represents:
# -- => < -90 | -+ => -90..0 | ++ => 0..90 | +- => >= 90
#
# shows asin has the correct angle the middle quadrants:
if sin_A < 0:
A = -180 - A
else:
A = 180 - A
# Simplify transformations where numbers are optional.
if type == 'translate':
# Only the X coordinate is required for translations.
# If the Y coordinate is unspecified, it's 0.
del args[1]
elif type == 'rotate':
# Only the angle is required for rotations.
# If the coordinates are unspecified, it's the origin (0, 0).
del args[1:]
elif type == 'scale':
# Only the X scaling factor is required.
# If the Y factor is unspecified, it's the same as X.
del args[1]
# Attempt to coalesce runs of the same transformation.
# Translations followed immediately by other translations,
# rotations followed immediately by other rotations,
# scaling followed immediately by other scaling,
# are safe to add.
# |¯ 1 0 0 ¯|
# | tan(A) 1 0 | skews X coordinates by angle A
# |_ 0 0 1 _|
#
# |¯ 1 tan(A) 0 ¯|
# | 0 1 0 | skews Y coordinates by angle A
# |_ 0 0 1 _|
#
# FIXME: A matrix followed immediately by another matrix
# would be safe to multiply together, too.
i = 1
# for y, only add if the second translation has an explicit y
del transform[i]
# Identity translation!
i -= 1
del transform[i]
# Only coalesce if both rotations are from the origin.
del transform[i]
# handle an implicit y
# y1 * y2
# create y2 = uniformscalefactor1 * y2
# y1 * uniformscalefactor2
del transform[i]
# Identity scale!
i -= 1
del transform[i]
else:
i += 1
# Some fixups are needed for single-element transformation lists, since
# the loop above was to coalesce elements with their predecessors in the
# list, and thus it required 2 elements.
i = 0
# Identity skew!
del transform[i]
elif ((currType == 'rotate')
# Identity rotation!
del transform[i]
else:
i += 1
"""
Attempts to optimise transform specifications on the given node and its children.
Returns the number of bytes saved after performing these reductions.
"""
num = 0
if val != '':
else:
return num
def removeComments(element) :
"""
Removes comments from the element and its children.
"""
global numCommentBytes
# must process the document object separately, because its
# documentElement's nodes have None as their parentNode
else:
else:
import base64
import urllib
"""
Converts raster references to inline images.
NOTE: there are size limits to base64-encoding handling in browsers
"""
global numRastersEmbedded
# if xlink:href is set, then grab the id
# find if href value has filename ext
# look for 'png', 'jpg', and 'gif' extensions
# file:// URLs denote files on the local system too
# does the file exist?
# if this is not an absolute path, set path relative
# to script file based on input arg
infilename = '.'
rasterdata = ''
# test if file exists locally
# open raster file as raw binary
# ... should we remove all images which don't resolve?
if rasterdata != '' :
# base64-encode raster
# set href attribute to base64-encoded equivalent
if b64eRaster != '':
# PNG and GIF both have MIME Type 'image/[ext]', but
if ext == 'jpg':
ext = 'jpeg'
numRastersEmbedded += 1
del b64eRaster
# get doc width and height
# well, it may be OK for Web browsers and vector editors, but not for librsvg.
return
# else we have a statically sized image and we should try to remedy that
# parse viewBox attribute
# if we have a valid viewBox we need to check it
try:
# if x or y are specified and non-zero then it is not ok to overwrite it
return
return
# if the viewBox did not parse properly it is invalid and ok to overwrite it
except ValueError:
pass
# create a replacement node
newNode = None
if newprefix != '':
else:
# add all the attributes
# clone and add all the child nodes
# replace old node with new node
# set the node to the new node in the remapped namespace prefix
# now do all child nodes
def makeWellFormed(str):
# starr = []
# for c in str:
# if c in xml_ents:
# starr.append(xml_ents[c])
# else:
# starr.append(c)
# this list comprehension is short-form for the above for-loop:
# hand-rolled serialization function that has the following benefits:
# - pretty printing
# - somewhat judicious use of whitespace
# - ensure id attributes are first
outParts = []
I=''
# always serialize the id or xml:id attributes first
quot = '"'
quot = "'"
quot = '"'
quot = "'"
# now serialize the other attributes
# if the attribute value contains a double-quote, use single-quotes
quot = '"'
quot = "'"
# preserve xmlns: if it is a namespace prefix declaration
elif attr.namespaceURI != None:
if attrValue == 'preserve':
elif attrValue == 'default':
# if no children, self-close
# element node
else:
# text node
# trim it only in the case of not being a child of an element
# where whitespace might be important
else:
# CDATA node
# Comment node
# TODO: entities, processing instructions, what else?
else: # ignore the rest
pass
else:
# this is the main method
# input is a string representation of the input XML
# returns a string representation of the output XML
if options is None:
global numAttrsRemoved
global numStylePropsFixed
global numElemsRemoved
global numBytesSavedInColors
global numCommentsRemoved
global numBytesSavedInIDs
global numBytesSavedInLengths
global numBytesSavedInTransforms
# for whatever reason this does not always remove all inkscape/sodipodi attributes/elements
# on the first pass, so we do it multiple times
# does it have to do with removal of children affecting the childlist?
pass
pass
# remove the xmlns: declarations now
xmlnsDeclsToRemove = []
for attr in xmlnsDeclsToRemove :
numAttrsRemoved += 1
# ensure namespace for SVG is declared
# TODO: what if the default namespace is something else (i.e. some valid namespace)?
# TODO: throw error or warning?
# check for redundant SVG namespace declaration
xmlnsDeclsToRemove = []
redundantPrefixes = []
for attrName in xmlnsDeclsToRemove:
for prefix in redundantPrefixes:
# repair style (remove unnecessary style properties and change them into XML attributes)
# convert colors to #RRGGBB format
if options.simple_colors:
# remove <metadata> if the user wants to
# and most unreferenced elements inside of defs
pass
# remove empty defs, metadata, g
# NOTE: these elements will be removed if they just have whitespace-only text nodes
if removeElem == False :
break
break
else:
if removeElem :
numElemsRemoved += 1
while bContinueLooping:
pass
# remove gradients that are only referenced by one other gradient
pass
# remove duplicate gradients
pass
# create <g> elements if there are runs of elements with the same attributes.
# this MUST be before moveCommonAttributesToParentGroup.
if options.group_create:
# move common attributes to parent group
# NOTE: the if the <svg> element's immediate children
# all have the same value for an attribute, it must not
# get moved to the <svg> element. The <svg> element
# doesn't accept fill=, stroke= etc.!
# remove unused attributes from parent
# Collapse groups LAST, because we've created groups. If done before
# moveAttributesToParentGroup, empty <g>'s may remain.
pass
# remove unnecessary closing point of polygons and scour points
# scour points of polyline
# clean path data
else:
# shorten ID names as much as possible
if options.shorten_ids:
# scour lengths (including coordinates)
for type in ['svg', 'image', 'rect', 'circle', 'ellipse', 'line', 'linearGradient', 'radialGradient', 'stop', 'filter']:
'x1', 'y1', 'x2', 'y2', 'fx', 'fy', 'offset']:
# more length scouring in this function
# remove default values of attributes
# reduce the length of transformation attributes
# convert rasters references to base64-encoded strings
if options.embed_rasters:
# output the document as a pretty string with a single space for indent
# NOTE: removed pretty printing because of this problem:
# rolled our own serialize function here to save on space, put id first, customize indentation, etc
# out_string = doc.documentElement.toprettyxml(' ')
# now strip out empty lines
lines = []
# Get rid of empty lines
# return the string with its XML prolog and surrounding comments
total_output = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n'
else:
total_output = ""
else: # doctypes, entities, comments
return total_output
# used mostly by unit tests
# input is a filename
# returns the minidom doc representation of the SVG
# GZ: Seems most other commandline tools don't do this, is it really wanted?
"""
Show application name, version number, and copyright statement
above usage information.
"""
# GZ: would prefer this to be in a function or class scope, but tests etc need
# access to the defaults anyway
usage="%prog [-i input.svg] [-o output.svg] [OPTIONS]",
description=("If the input/output files are specified with a svgz"
" extension, then compressed SVG is assumed. If the input file is not"
" specified, stdin is used. If the output file is not specified, "
" stdout is used."),
help="won't convert all colors to #RRGGBB format")
help="won't convert styles into XML attributes")
help="won't collapse <g> elements")
help="create <g> elements for runs of elements with identical attributes")
help="remove all un-referenced ID attributes")
help="remove all <!-- --> comments")
help="shorten all ID attributes to the least number of letters possible")
help="won't embed rasters as base64-encoded data")
help="won't remove Inkscape, Sodipodi or Adobe Illustrator elements and attributes")
help="remove <metadata> elements (which may contain license metadata etc.)")
help="work around various renderer bugs (currently only librsvg) (default)")
help="do not work around various renderer bugs (currently only librsvg)")
help="won't output the <?xml ?> prolog")
# GZ: this is confusing, most people will be thinking in terms of
# decimal places, which is not what decimal precision is doing
help="set number of significant digits (default: %default)")
help="suppress non-error output")
help="indentation of the output: none, space, tab (default: %default)")
help="Don't change IDs not ending with a digit")
help="Don't change IDs given in a comma-separated list")
help="Don't change IDs starting with the given prefix")
import gzip
def parse_args(args=None):
if rargs:
if options.infilename:
# GZ: could catch a raised IOError here and report
else:
# GZ: could sniff for gzip compression here
if options.outfilename:
else:
def getReport():
if __name__ == '__main__':
else:
# GZ: is this different from time.time() in any way?
def get_tick():
# do the work
# Close input and output files
# GZ: not using globals would be good too