scour-0.26/ 0000700 0001750 0001750 00000000000 11564201127 012441 5 ustar alessio alessio scour-0.26/svg_transform.py 0000644 0001750 0001750 00000016311 11562136375 015733 0 ustar alessio alessio #!/usr/bin/env python
# -*- coding: utf-8 -*-
# SVG transformation list parser
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
""" Small recursive descent parser for SVG transform="" data.
In [1]: from svg_transform import svg_transform_parser
In [3]: svg_transform_parser.parse('translate(50, 50)')
Out[3]: [('translate', [50.0, 50.0])]
In [4]: svg_transform_parser.parse('translate(50)')
Out[4]: [('translate', [50.0])]
In [5]: svg_transform_parser.parse('rotate(36 50,50)')
Out[5]: [('rotate', [36.0, 50.0, 50.0])]
In [6]: svg_transform_parser.parse('rotate(36)')
Out[6]: [('rotate', [36.0])]
In [7]: svg_transform_parser.parse('skewX(20)')
Out[7]: [('skewX', [20.0])]
In [8]: svg_transform_parser.parse('skewY(40)')
Out[8]: [('skewX', [20.0])]
In [9]: svg_transform_parser.parse('scale(2 .5)')
Out[9]: [('scale', [2.0, 0.5])]
In [10]: svg_transform_parser.parse('scale(.5)')
Out[10]: [('scale', [0.5])]
In [11]: svg_transform_parser.parse('matrix(1 0 50 0 1 80)')
Out[11]: [('matrix', [1.0, 0.0, 50.0, 0.0, 1.0, 80.0])]
Multiple transformations are supported:
In [12]: svg_transform_parser.parse('translate(30 -30) rotate(36)')
Out[12]: [('translate', [30.0, -30.0]), ('rotate', [36.0])]
"""
import re
from decimal import *
# Sentinel.
class _EOF(object):
def __repr__(self):
return 'EOF'
EOF = _EOF()
lexicon = [
('float', r'[-+]?(?:(?:[0-9]*\.[0-9]+)|(?:[0-9]+\.?))(?:[Ee][-+]?[0-9]+)?'),
('int', r'[-+]?[0-9]+'),
('command', r'(?:matrix|translate|scale|rotate|skew[XY])'),
('coordstart', r'\('),
('coordend', r'\)'),
]
class Lexer(object):
""" Break SVG path data into tokens.
The SVG spec requires that tokens are greedy. This lexer relies on Python's
regexes defaulting to greediness.
This style of implementation was inspired by this article:
http://www.gooli.org/blog/a-simple-lexer-in-python/
"""
def __init__(self, lexicon):
self.lexicon = lexicon
parts = []
for name, regex in lexicon:
parts.append('(?P<%s>%s)' % (name, regex))
self.regex_string = '|'.join(parts)
self.regex = re.compile(self.regex_string)
def lex(self, text):
""" Yield (token_type, str_data) tokens.
The last token will be (EOF, None) where EOF is the singleton object
defined in this module.
"""
for match in self.regex.finditer(text):
for name, _ in self.lexicon:
m = match.group(name)
if m is not None:
yield (name, m)
break
yield (EOF, None)
svg_lexer = Lexer(lexicon)
class SVGTransformationParser(object):
""" Parse SVG transform="" data into a list of commands.
Each distinct command will take the form of a tuple (type, data). The
`type` is the character string that defines the type of transformation in the
transform data, so either of "translate", "rotate", "scale", "matrix",
"skewX" and "skewY". Data is always a list of numbers contained within the
transformation's parentheses.
See the SVG documentation for the interpretation of the individual elements
for each transformation.
The main method is `parse(text)`. It can only consume actual strings, not
filelike objects or iterators.
"""
def __init__(self, lexer=svg_lexer):
self.lexer = lexer
self.command_dispatch = {
'translate': self.rule_1or2numbers,
'scale': self.rule_1or2numbers,
'skewX': self.rule_1number,
'skewY': self.rule_1number,
'rotate': self.rule_1or3numbers,
'matrix': self.rule_6numbers,
}
# self.number_tokens = set(['int', 'float'])
self.number_tokens = list(['int', 'float'])
def parse(self, text):
""" Parse a string of SVG transform="" data.
"""
next = self.lexer.lex(text).next
commands = []
token = next()
while token[0] is not EOF:
command, token = self.rule_svg_transform(next, token)
commands.append(command)
return commands
def rule_svg_transform(self, next, token):
if token[0] != 'command':
raise SyntaxError("expecting a transformation type; got %r" % (token,))
command = token[1]
rule = self.command_dispatch[command]
token = next()
if token[0] != 'coordstart':
raise SyntaxError("expecting '('; got %r" % (token,))
numbers, token = rule(next, token)
if token[0] != 'coordend':
raise SyntaxError("expecting ')'; got %r" % (token,))
token = next()
return (command, numbers), token
def rule_1or2numbers(self, next, token):
numbers = []
# 1st number is mandatory
token = next()
number, token = self.rule_number(next, token)
numbers.append(number)
# 2nd number is optional
number, token = self.rule_optional_number(next, token)
if number is not None:
numbers.append(number)
return numbers, token
def rule_1number(self, next, token):
# this number is mandatory
token = next()
number, token = self.rule_number(next, token)
numbers = [number]
return numbers, token
def rule_1or3numbers(self, next, token):
numbers = []
# 1st number is mandatory
token = next()
number, token = self.rule_number(next, token)
numbers.append(number)
# 2nd number is optional
number, token = self.rule_optional_number(next, token)
if number is not None:
# but, if the 2nd number is provided, the 3rd is mandatory.
# we can't have just 2.
numbers.append(number)
number, token = self.rule_number(next, token)
numbers.append(number)
return numbers, token
def rule_6numbers(self, next, token):
numbers = []
token = next()
# all numbers are mandatory
for i in xrange(6):
number, token = self.rule_number(next, token)
numbers.append(number)
return numbers, token
def rule_number(self, next, token):
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
x = Decimal(token[1]) * 1
token = next()
return x, token
def rule_optional_number(self, next, token):
if token[0] not in self.number_tokens:
return None, token
else:
x = Decimal(token[1]) * 1
token = next()
return x, token
svg_transform_parser = SVGTransformationParser()
scour-0.26/release-notes.html 0000644 0001750 0001750 00000032270 11562136375 016125 0 ustar alessio alessio
Fix Bug 603994, fix parsing of <style> element contents when a CDATA is present
Fix Bug 583758, added a bit to the Inkscape help text saying that groups aren't collapsed if IDs are also not stripped.
Fix Bug 583458, another typo in the Inkscape help tab.
Fix Bug 594930, In a <switch>, require one level of <g> if there was a <g> in the file already. Otherwise, only the first subelement of the <g> is chosen and rendered.
Fix Bug 576958, "Viewbox option doesn't work when units are set", when renderer workarounds are disabled.
Added many options: --remove-metadata, --quiet, --enable-comment-stripping, --shorten-ids, --renderer-workaround.
Remove all unused namespace declarations on the document element
Removes any empty <defs>, <metadata>, or <g> elements
Style fix-ups:
Fixes any style properties like this: style="fill: url(#linearGradient1000) rgb(0, 0, 0);"
Removes any style property of: opacity: 1;
Removes any stroke properties when stroke=none or stroke-opacity=0 or stroke-width=0
Removes any fill properties when fill=none or fill-opacity=0
Removes all fill/stroke properties when opacity=0
Removes any stop-opacity: 1
Removes any fill-opacity: 1
Removes any stroke-opacity: 1
Convert style properties into SVG attributes
scour-0.26/svg_regex.py 0000644 0001750 0001750 00000024603 11562136375 015035 0 ustar alessio alessio # This software is OSI Certified Open Source Software.
# OSI Certified is a certification mark of the Open Source Initiative.
#
# Copyright (c) 2006, Enthought, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Enthought, Inc. nor the names of its contributors may
# be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" Small hand-written recursive descent parser for SVG data.
In [1]: from svg_regex import svg_parser
In [3]: svg_parser.parse('M 10,20 30,40V50 60 70')
Out[3]: [('M', [(10.0, 20.0), (30.0, 40.0)]), ('V', [50.0, 60.0, 70.0])]
In [4]: svg_parser.parse('M 0.6051.5') # An edge case
Out[4]: [('M', [(0.60509999999999997, 0.5)])]
In [5]: svg_parser.parse('M 100-200') # Another edge case
Out[5]: [('M', [(100.0, -200.0)])]
"""
import re
from decimal import *
# Sentinel.
class _EOF(object):
def __repr__(self):
return 'EOF'
EOF = _EOF()
lexicon = [
('float', r'[-+]?(?:(?:[0-9]*\.[0-9]+)|(?:[0-9]+\.?))(?:[Ee][-+]?[0-9]+)?'),
('int', r'[-+]?[0-9]+'),
('command', r'[AaCcHhLlMmQqSsTtVvZz]'),
]
class Lexer(object):
""" Break SVG path data into tokens.
The SVG spec requires that tokens are greedy. This lexer relies on Python's
regexes defaulting to greediness.
This style of implementation was inspired by this article:
http://www.gooli.org/blog/a-simple-lexer-in-python/
"""
def __init__(self, lexicon):
self.lexicon = lexicon
parts = []
for name, regex in lexicon:
parts.append('(?P<%s>%s)' % (name, regex))
self.regex_string = '|'.join(parts)
self.regex = re.compile(self.regex_string)
def lex(self, text):
""" Yield (token_type, str_data) tokens.
The last token will be (EOF, None) where EOF is the singleton object
defined in this module.
"""
for match in self.regex.finditer(text):
for name, _ in self.lexicon:
m = match.group(name)
if m is not None:
yield (name, m)
break
yield (EOF, None)
svg_lexer = Lexer(lexicon)
class SVGPathParser(object):
""" Parse SVG data into a list of commands.
Each distinct command will take the form of a tuple (command, data). The
`command` is just the character string that starts the command group in the
data, so 'M' for absolute moveto, 'm' for relative moveto, 'Z' for
closepath, etc. The kind of data it carries with it depends on the command.
For 'Z' (closepath), it's just None. The others are lists of individual
argument groups. Multiple elements in these lists usually mean to repeat the
command. The notable exception is 'M' (moveto) where only the first element
is truly a moveto. The remainder are implicit linetos.
See the SVG documentation for the interpretation of the individual elements
for each command.
The main method is `parse(text)`. It can only consume actual strings, not
filelike objects or iterators.
"""
def __init__(self, lexer=svg_lexer):
self.lexer = lexer
self.command_dispatch = {
'Z': self.rule_closepath,
'z': self.rule_closepath,
'M': self.rule_moveto_or_lineto,
'm': self.rule_moveto_or_lineto,
'L': self.rule_moveto_or_lineto,
'l': self.rule_moveto_or_lineto,
'H': self.rule_orthogonal_lineto,
'h': self.rule_orthogonal_lineto,
'V': self.rule_orthogonal_lineto,
'v': self.rule_orthogonal_lineto,
'C': self.rule_curveto3,
'c': self.rule_curveto3,
'S': self.rule_curveto2,
's': self.rule_curveto2,
'Q': self.rule_curveto2,
'q': self.rule_curveto2,
'T': self.rule_curveto1,
't': self.rule_curveto1,
'A': self.rule_elliptical_arc,
'a': self.rule_elliptical_arc,
}
# self.number_tokens = set(['int', 'float'])
self.number_tokens = list(['int', 'float'])
def parse(self, text):
""" Parse a string of SVG data.
"""
next = self.lexer.lex(text).next
token = next()
return self.rule_svg_path(next, token)
def rule_svg_path(self, next, token):
commands = []
while token[0] is not EOF:
if token[0] != 'command':
raise SyntaxError("expecting a command; got %r" % (token,))
rule = self.command_dispatch[token[1]]
command_group, token = rule(next, token)
commands.append(command_group)
return commands
def rule_closepath(self, next, token):
command = token[1]
token = next()
return (command, []), token
def rule_moveto_or_lineto(self, next, token):
command = token[1]
token = next()
coordinates = []
while token[0] in self.number_tokens:
pair, token = self.rule_coordinate_pair(next, token)
coordinates.extend(pair)
return (command, coordinates), token
def rule_orthogonal_lineto(self, next, token):
command = token[1]
token = next()
coordinates = []
while token[0] in self.number_tokens:
coord, token = self.rule_coordinate(next, token)
coordinates.append(coord)
return (command, coordinates), token
def rule_curveto3(self, next, token):
command = token[1]
token = next()
coordinates = []
while token[0] in self.number_tokens:
pair1, token = self.rule_coordinate_pair(next, token)
pair2, token = self.rule_coordinate_pair(next, token)
pair3, token = self.rule_coordinate_pair(next, token)
coordinates.extend(pair1)
coordinates.extend(pair2)
coordinates.extend(pair3)
return (command, coordinates), token
def rule_curveto2(self, next, token):
command = token[1]
token = next()
coordinates = []
while token[0] in self.number_tokens:
pair1, token = self.rule_coordinate_pair(next, token)
pair2, token = self.rule_coordinate_pair(next, token)
coordinates.extend(pair1)
coordinates.extend(pair2)
return (command, coordinates), token
def rule_curveto1(self, next, token):
command = token[1]
token = next()
coordinates = []
while token[0] in self.number_tokens:
pair1, token = self.rule_coordinate_pair(next, token)
coordinates.extend(pair1)
return (command, coordinates), token
def rule_elliptical_arc(self, next, token):
command = token[1]
token = next()
arguments = []
while token[0] in self.number_tokens:
rx = Decimal(token[1]) * 1
if rx < Decimal("0.0"):
raise SyntaxError("expecting a nonnegative number; got %r" % (token,))
token = next()
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
ry = Decimal(token[1]) * 1
if ry < Decimal("0.0"):
raise SyntaxError("expecting a nonnegative number; got %r" % (token,))
token = next()
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
axis_rotation = Decimal(token[1]) * 1
token = next()
if token[1] not in ('0', '1'):
raise SyntaxError("expecting a boolean flag; got %r" % (token,))
large_arc_flag = Decimal(token[1]) * 1
token = next()
if token[1] not in ('0', '1'):
raise SyntaxError("expecting a boolean flag; got %r" % (token,))
sweep_flag = Decimal(token[1]) * 1
token = next()
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
x = Decimal(token[1]) * 1
token = next()
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
y = Decimal(token[1]) * 1
token = next()
arguments.extend([rx, ry, axis_rotation, large_arc_flag, sweep_flag, x, y])
return (command, arguments), token
def rule_coordinate(self, next, token):
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
x = getcontext().create_decimal(token[1])
token = next()
return x, token
def rule_coordinate_pair(self, next, token):
# Inline these since this rule is so common.
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
x = getcontext().create_decimal(token[1])
token = next()
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
y = getcontext().create_decimal(token[1])
token = next()
return [x, y], token
svg_parser = SVGPathParser()
scour-0.26/yocto_css.py 0000644 0001750 0001750 00000005470 11562136375 015052 0 ustar alessio alessio #!/usr/bin/env python
# -*- coding: utf-8 -*-
# yocto-css, an extremely bare minimum CSS parser
#
# Copyright 2009 Jeff Schiller
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
# In order to resolve Bug 368716 (https://bugs.launchpad.net/scour/+bug/368716)
# scour needed a bare-minimum CSS parser in order to determine if some elements
# were still referenced by CSS properties.
# I looked at css-py (a CSS parser built in Python), but that library
# is about 35k of Python and requires ply to be installed. I just need
# something very basic to suit scour's needs.
# yocto-css takes a string of CSS and tries to spit out a list of rules
# A rule is an associative array (dictionary) with the following keys:
# - selector: contains the string of the selector (see CSS grammar)
# - properties: contains an associative array of CSS properties for this rule
# TODO: need to build up some unit tests for yocto_css
# stylesheet : [ CDO | CDC | S | statement ]*;
# statement : ruleset | at-rule;
# at-rule : ATKEYWORD S* any* [ block | ';' S* ];
# block : '{' S* [ any | block | ATKEYWORD S* | ';' S* ]* '}' S*;
# ruleset : selector? '{' S* declaration? [ ';' S* declaration? ]* '}' S*;
# selector : any+;
# declaration : property S* ':' S* value;
# property : IDENT;
# value : [ any | block | ATKEYWORD S* ]+;
# any : [ IDENT | NUMBER | PERCENTAGE | DIMENSION | STRING
# | DELIM | URI | HASH | UNICODE-RANGE | INCLUDES
# | DASHMATCH | FUNCTION S* any* ')'
# | '(' S* any* ')' | '[' S* any* ']' ] S*;
def parseCssString(str):
rules = []
# first, split on } to get the rule chunks
chunks = str.split('}')
for chunk in chunks:
# second, split on { to get the selector and the list of properties
bits = chunk.split('{')
if len(bits) != 2: continue
rule = {}
rule['selector'] = bits[0].strip()
# third, split on ; to get the property declarations
bites = bits[1].strip().split(';')
if len(bites) < 1: continue
props = {}
for bite in bites:
# fourth, split on : to get the property name and value
nibbles = bite.strip().split(':')
if len(nibbles) != 2: continue
props[nibbles[0].strip()] = nibbles[1].strip()
rule['properties'] = props
rules.append(rule)
return rules
scour-0.26/LICENSE 0000644 0001750 0001750 00000026135 11562136375 013501 0 ustar alessio alessio Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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
http://www.apache.org/licenses/LICENSE-2.0
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.
scour-0.26/scour.py 0000755 0001750 0001750 00000325713 11562142207 014177 0 ustar alessio alessio #!/usr/bin/env python
# -*- 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 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 has only one element in it, collapse the (ensure transform, etc are carried down)
# necessary to get true division
from __future__ import division
import os
import sys
import xml.dom.minidom
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:
print >>sys.stderr, "Scour requires Python 2.4."
# Import Psyco if available
try:
import psyco
psyco.full()
except ImportError:
pass
APP = 'scour'
VER = '0.26'
COPYRIGHT = 'Copyright Jeff Schiller, Louis Simard, 2010'
NS = { 'SVG': 'http://www.w3.org/2000/svg',
'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/'
}
unwanted_ns = [ NS['SODIPODI'], NS['INKSCAPE'], NS['ADOBE_ILLUSTRATOR'],
NS['ADOBE_GRAPHS'], NS['ADOBE_SVG_VIEWER'], NS['ADOBE_VARIABLES'],
NS['ADOBE_SFW'], NS['ADOBE_EXTENSIBILITY'], NS['ADOBE_FLOWS'],
NS['ADOBE_IMAGE_REPLACEMENT'], NS['ADOBE_CUSTOM'], NS['ADOBE_XPATH'] ]
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',
}
def isSameSign(a,b): return (a <= 0 and b <= 0) or (a >= 0 and b >= 0)
scinumber = re.compile(r"[-+]?(\d*\.?)?\d+[eE][-+]?\d+")
number = re.compile(r"[-+]?(\d*\.?)?\d+")
sciExponent = re.compile(r"[eE]([-+]?\d+)")
unit = re.compile("(em|ex|px|pt|pc|cm|mm|in|%){1,1}$")
class Unit(object):
# 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
def get(unitstr):
if unitstr is None: return Unit.NONE
try:
return Unit.s2u[unitstr]
except KeyError:
return Unit.INVALID
# @staticmethod
def str(unitint):
try:
return Unit.u2s[unitint]
except KeyError:
return 'INVALID'
get = staticmethod(get)
str = staticmethod(str)
class SVGLength(object):
def __init__(self, str):
try: # simple unitless and no scientific notation
self.value = float(str)
if int(self.value) == self.value:
self.value = int(self.value)
self.units = Unit.NONE
except ValueError:
# we know that the length string has an exponent, a unit, both or is invalid
# parse out number, exponent and unit
self.value = 0
unitBegin = 0
scinum = scinumber.match(str)
if scinum != None:
# this will always match, no need to check it
numMatch = number.match(str)
expMatch = sciExponent.search(str, numMatch.start(0))
self.value = (float(numMatch.group(0)) *
10 ** float(expMatch.group(1)))
unitBegin = expMatch.end(1)
else:
# unit or invalid
numMatch = number.match(str)
if numMatch != None:
self.value = float(numMatch.group(0))
unitBegin = numMatch.end(0)
if int(self.value) == self.value:
self.value = int(self.value)
if unitBegin != 0 :
unitMatch = unit.search(str, unitBegin)
if unitMatch != None :
self.units = Unit.get(unitMatch.group(0))
# invalid
else:
# TODO: this needs to set the default for the given attribute (how?)
self.value = 0
self.units = Unit.INVALID
def findElementsWithId(node, elems=None):
"""
Returns all elements with id attributes
"""
if elems is None:
elems = {}
id = node.getAttribute('id')
if id != '' :
elems[id] = node
if node.hasChildNodes() :
for child in node.childNodes:
# from http://www.w3.org/TR/DOM-Level-2-Core/idl-definitions.html
# we are only really interested in nodes of type Element (1)
if child.nodeType == 1 :
findElementsWithId(child, elems)
return elems
referencingProps = ['fill', 'stroke', 'filter', 'clip-path', 'mask', 'marker-start',
'marker-end', 'marker-mid']
def findReferencedElements(node, ids=None):
"""
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
if node.nodeName == 'style' and node.namespaceURI == NS['SVG']:
# 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)
stylesheet = "".join([child.nodeValue for child in node.childNodes])
if stylesheet != '':
cssRules = parseCssString(stylesheet)
for rule in cssRules:
for propname in rule['properties']:
propval = rule['properties'][propname]
findReferencingProperty(node, propname, propval, ids)
return ids
# else if xlink:href is set, then grab the id
href = node.getAttributeNS(NS['XLINK'],'href')
if href != '' and len(href) > 1 and href[0] == '#':
# we remove the hash mark from the beginning of the id
id = href[1:]
if id in ids:
ids[id][0] += 1
ids[id][1].append(node)
else:
ids[id] = [1,[node]]
# now get all style properties and the fill, stroke, filter attributes
styles = node.getAttribute('style').split(';')
for attr in referencingProps:
styles.append(':'.join([attr, node.getAttribute(attr)]))
for style in styles:
propval = style.split(':')
if len(propval) == 2 :
prop = propval[0].strip()
val = propval[1].strip()
findReferencingProperty(node, prop, val, ids)
if node.hasChildNodes() :
for child in node.childNodes:
if child.nodeType == 1 :
findReferencedElements(child, ids)
return ids
def findReferencingProperty(node, prop, val, ids):
global referencingProps
if prop in referencingProps and val != '' :
if len(val) >= 7 and val[0:5] == 'url(#' :
id = val[5:val.find(')')]
if ids.has_key(id) :
ids[id][0] += 1
ids[id][1].append(node)
else:
ids[id] = [1,[node]]
# if the url has a quote in it, we need to compensate
elif len(val) >= 8 :
id = None
# double-quote
if val[0:6] == 'url("#' :
id = val[6:val.find('")')]
# single-quote
elif val[0:6] == "url('#" :
id = val[6:val.find("')")]
if id != None:
if ids.has_key(id) :
ids[id][0] += 1
ids[id][1].append(node)
else:
ids[id] = [1,[node]]
numIDsRemoved = 0
numElemsRemoved = 0
numAttrsRemoved = 0
numRastersEmbedded = 0
numPathSegmentsReduced = 0
numCurvesStraightened = 0
numBytesSavedInPathData = 0
numBytesSavedInColors = 0
numBytesSavedInIDs = 0
numBytesSavedInLengths = 0
numBytesSavedInTransforms = 0
numPointsRemovedFromPolygon = 0
numCommentBytes = 0
def removeUnusedDefs(doc, defElem, elemsToRemove=None):
if elemsToRemove is None:
elemsToRemove = []
identifiedElements = findElementsWithId(doc.documentElement)
referencedIDs = findReferencedElements(doc.documentElement)
keepTags = ['font', 'style', 'metadata', 'script', 'title', 'desc']
for elem in defElem.childNodes:
# only look at it if an element and not referenced anywhere else
if elem.nodeType == 1 and (elem.getAttribute('id') == '' or \
(not elem.getAttribute('id') in referencedIDs)):
# we only inspect the children of a group in a defs if the group
# is not referenced anywhere else
if elem.nodeName == 'g' and elem.namespaceURI == NS['SVG']:
elemsToRemove = removeUnusedDefs(doc, elem, elemsToRemove)
# we only remove if it is not one of our tags we always keep (see above)
elif not elem.nodeName in keepTags:
elemsToRemove.append(elem)
return elemsToRemove
def removeUnreferencedElements(doc):
"""
Removes all unreferenced elements except for