Merge lp:~ede123/inkscape/scour2 into lp:~inkscape.dev/inkscape/trunk
- scour2
- Merge into trunk
Status: | Merged | ||||||||
---|---|---|---|---|---|---|---|---|---|
Merged at revision: | 14577 | ||||||||
Proposed branch: | lp:~ede123/inkscape/scour2 | ||||||||
Merge into: | lp:~inkscape.dev/inkscape/trunk | ||||||||
Diff against target: |
4198 lines (+140/-3962) 10 files modified
configure.ac (+0/-1) share/extensions/CMakeLists.txt (+0/-3) share/extensions/Makefile.am (+0/-1) share/extensions/scour.inkscape.py (+53/-65) share/extensions/scour.inx (+87/-50) share/extensions/scour/Makefile.am (+0/-13) share/extensions/scour/scour.py (+0/-3235) share/extensions/scour/svg_regex.py (+0/-285) share/extensions/scour/svg_transform.py (+0/-235) share/extensions/scour/yocto_css.py (+0/-74) |
||||||||
To merge this branch: | bzr merge lp:~ede123/inkscape/scour2 | ||||||||
Related bugs: |
|
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Mc | build | Approve | |
su_v (community) | build | Approve | |
Review via email: mp+282391@code.launchpad.net |
Commit message
Update for the Scour extension
Description of the change
Update for the Scour extension (also see discussion in mailing list [1])
* Update the Scour extension (scour.inkscape.py) to work with recent versions of the scour module (0.30 and later)
* Strip the Scour module from Inkscape source code and use an external copy of instead (i.e. make it a requirement). This avoids any potential license issues with the Scour module's Apache license 2.0
* Update Scour extension dialog (scour.inx)
- add new settings added in Scour versions 0.29-0.31
- attempt to arrange/group settings intuitively
- convert "help" tabs to individual tooltips for each setting
[1] https:/
Patrick Storz (ede123) wrote : | # |
su_v (suv-lp) wrote : | # |
Clean new branch fails to fully configure and thus to build & install with autotools (tested on OS X 10.7.5 with a regular linux-style build):
1) error when running autogen.sh:
> configure.ac:1139: error: required file 'share/
Proposed fix:
remove the obsolete entry in configure.ac
2) next error when re-running autogen.sh:
> share/extension
Proposed fix:
remove obsolete entry in share/extension
su_v (suv-lp) wrote : | # |
Proposed diff to fix autotools-based build
1 | === modified file 'configure.ac' |
2 | --- configure.ac 2016-01-11 14:40:38 +0000 |
3 | +++ configure.ac 2016-01-13 14:12:39 +0000 |
4 | @@ -1108,7 +1108,6 @@ |
5 | share/extensions/alphabet_soup/Makefile |
6 | share/extensions/Barcode/Makefile |
7 | share/extensions/Poly3DObjects/Makefile |
8 | -share/extensions/scour/Makefile |
9 | share/extensions/test/Makefile |
10 | share/extensions/xaml2svg/Makefile |
11 | share/extensions/ink2canvas/Makefile |
12 | |
13 | === modified file 'share/extensions/Makefile.am' |
14 | --- share/extensions/Makefile.am 2015-07-06 08:49:46 +0000 |
15 | +++ share/extensions/Makefile.am 2016-01-13 14:14:58 +0000 |
16 | @@ -4,7 +4,6 @@ |
17 | Barcode \ |
18 | ink2canvas \ |
19 | Poly3DObjects \ |
20 | - scour \ |
21 | test \ |
22 | xaml2svg |
23 |
- 14577. By Patrick Storz
-
Remove scour folder from makefiles
Patrick Storz (ede123) wrote : | # |
Oh shoot! I knew I'd overlook something...
Fixed in revision 14577.
su_v (suv-lp) wrote : | # |
Running autogen.sh, configure, make, make check and make install tested successfully with r14577 on OS X 10.7.5, using a regular (linux-style) autotools-based build.
Runtime feature also tested successfully:
A - Scour python module installed for Python 2.7: used as expected when saving a copy as 'Optimized SVG'
B - Scour python module not installed: attempting to save a copy as 'Optimized SVG' notifies the user about the missing python module.
Tests with osx packaging will be done later this week (the expected changes are minor, and no reason to delay or block a merge of this branch into trunk).
Mc (mc...) wrote : | # |
Cmake build tested and works as expected for me
Mc (mc...) wrote : | # |
> Cmake build tested and works as expected for me
( Linux * 4.3.0-1-amd64 #1 SMP Debian 4.3.3-5 (2016-01-04) x86_64 GNU/Linux )
(debian testing up to date)
Preview Diff
1 | === modified file 'configure.ac' |
2 | --- configure.ac 2016-01-11 14:40:38 +0000 |
3 | +++ configure.ac 2016-01-13 18:39:42 +0000 |
4 | @@ -1108,7 +1108,6 @@ |
5 | share/extensions/alphabet_soup/Makefile |
6 | share/extensions/Barcode/Makefile |
7 | share/extensions/Poly3DObjects/Makefile |
8 | -share/extensions/scour/Makefile |
9 | share/extensions/test/Makefile |
10 | share/extensions/xaml2svg/Makefile |
11 | share/extensions/ink2canvas/Makefile |
12 | |
13 | === modified file 'share/extensions/CMakeLists.txt' |
14 | --- share/extensions/CMakeLists.txt 2015-07-06 08:49:46 +0000 |
15 | +++ share/extensions/CMakeLists.txt 2016-01-13 18:39:42 +0000 |
16 | @@ -42,8 +42,5 @@ |
17 | file(GLOB _FILES "ink2canvas/*.py") |
18 | install(FILES ${_FILES} DESTINATION ${SHARE_INSTALL}/inkscape/extensions/ink2canvas) |
19 | |
20 | -file(GLOB _FILES "scour/*.py") |
21 | -install(FILES ${_FILES} DESTINATION ${SHARE_INSTALL}/inkscape/extensions/scour) |
22 | - |
23 | file(GLOB _FILES "xaml2svg/*.xsl") |
24 | install(FILES ${_FILES} DESTINATION ${SHARE_INSTALL}/inkscape/extensions/xaml2svg) |
25 | |
26 | === modified file 'share/extensions/Makefile.am' |
27 | --- share/extensions/Makefile.am 2015-07-06 08:49:46 +0000 |
28 | +++ share/extensions/Makefile.am 2016-01-13 18:39:42 +0000 |
29 | @@ -4,7 +4,6 @@ |
30 | Barcode \ |
31 | ink2canvas \ |
32 | Poly3DObjects \ |
33 | - scour \ |
34 | test \ |
35 | xaml2svg |
36 | |
37 | |
38 | === removed directory 'share/extensions/scour' |
39 | === renamed file 'share/extensions/scour/scour.inkscape.py' => 'share/extensions/scour.inkscape.py' |
40 | --- share/extensions/scour/scour.inkscape.py 2015-09-13 17:09:56 +0000 |
41 | +++ share/extensions/scour.inkscape.py 2016-01-13 18:39:42 +0000 |
42 | @@ -1,77 +1,65 @@ |
43 | #!/usr/bin/env python |
44 | # -*- coding: utf-8 -*- |
45 | -import sys, inkex |
46 | -from scour import scourString |
47 | +import sys, platform, inkex |
48 | + |
49 | +try: |
50 | + import scour |
51 | + from scour.scour import scourString |
52 | +except Exception as e: |
53 | + inkex.errormsg("Failed to import Python module 'scour'.\nPlease make sure it is installed (e.g. using 'pip install scour' or 'sudo apt-get install python-scour') and try again.") |
54 | + inkex.errormsg("\nDetails:\n" + str(e)) |
55 | + sys.exit() |
56 | + |
57 | +try: |
58 | + import six |
59 | +except Exception as e: |
60 | + inkex.errormsg("Failed to import Python module 'six'.\nPlease make sure it is installed (e.g. using 'pip install six' or 'sudo apt-get install python-six') and try again.") |
61 | + inkex.errormsg("\nDetails:\n" + str(e)) |
62 | + sys.exit() |
63 | |
64 | class ScourInkscape (inkex.Effect): |
65 | |
66 | def __init__(self): |
67 | inkex.Effect.__init__(self) |
68 | - self.OptionParser.add_option("--tab", |
69 | - action="store", type="string", |
70 | - dest="tab") |
71 | - self.OptionParser.add_option("--simplify-colors", type="inkbool", |
72 | - action="store", dest="simple_colors", default=True, |
73 | - help="won't convert all colors to #RRGGBB format") |
74 | - self.OptionParser.add_option("--style-to-xml", type="inkbool", |
75 | - action="store", dest="style_to_xml", default=True, |
76 | - help="won't convert styles into XML attributes") |
77 | - self.OptionParser.add_option("--group-collapsing", type="inkbool", |
78 | - action="store", dest="group_collapse", default=True, |
79 | - help="won't collapse <g> elements") |
80 | - self.OptionParser.add_option("--create-groups", type="inkbool", |
81 | - action="store", dest="group_create", default=False, |
82 | - help="create <g> elements for runs of elements with identical attributes") |
83 | - self.OptionParser.add_option("--enable-id-stripping", type="inkbool", |
84 | - action="store", dest="strip_ids", default=False, |
85 | - help="remove all un-referenced ID attributes") |
86 | - self.OptionParser.add_option("--shorten-ids", type="inkbool", |
87 | - action="store", dest="shorten_ids", default=False, |
88 | - help="shorten all ID attributes to the least number of letters possible") |
89 | - self.OptionParser.add_option("--embed-rasters", type="inkbool", |
90 | - action="store", dest="embed_rasters", default=True, |
91 | - help="won't embed rasters as base64-encoded data") |
92 | - self.OptionParser.add_option("--keep-editor-data", type="inkbool", |
93 | - action="store", dest="keep_editor_data", default=False, |
94 | - help="won't remove Inkscape, Sodipodi or Adobe Illustrator elements and attributes") |
95 | - self.OptionParser.add_option("--remove-metadata", type="inkbool", |
96 | - action="store", dest="remove_metadata", default=False, |
97 | - help="remove <metadata> elements (which may contain license metadata etc.)") |
98 | - self.OptionParser.add_option("--strip-xml-prolog", type="inkbool", |
99 | - action="store", dest="strip_xml_prolog", default=False, |
100 | - help="won't output the <?xml ?> prolog") |
101 | - self.OptionParser.add_option("-p", "--set-precision", |
102 | - action="store", type=int, dest="digits", default=5, |
103 | - help="set number of significant digits (default: %default)") |
104 | - self.OptionParser.add_option("--indent", |
105 | - action="store", type="string", dest="indent_type", default="space", |
106 | - help="indentation of the output: none, space, tab (default: %default)") |
107 | - self.OptionParser.add_option("--protect-ids-noninkscape", type="inkbool", |
108 | - action="store", dest="protect_ids_noninkscape", default=False, |
109 | - help="don't change IDs not ending with a digit") |
110 | - self.OptionParser.add_option("--protect-ids-list", |
111 | - action="store", type="string", dest="protect_ids_list", default=None, |
112 | - help="don't change IDs given in a comma-separated list") |
113 | - self.OptionParser.add_option("--protect-ids-prefix", |
114 | - action="store", type="string", dest="protect_ids_prefix", default=None, |
115 | - help="don't change IDs starting with the given prefix") |
116 | - self.OptionParser.add_option("--enable-viewboxing", type="inkbool", |
117 | - action="store", dest="enable_viewboxing", default=False, |
118 | - help="changes document width/height to 100%/100% and creates viewbox coordinates") |
119 | - self.OptionParser.add_option("--enable-comment-stripping", type="inkbool", |
120 | - action="store", dest="strip_comments", default=False, |
121 | - help="remove all <!-- --> comments") |
122 | - self.OptionParser.add_option("--renderer-workaround", type="inkbool", |
123 | - action="store", dest="renderer_workaround", default=False, |
124 | - help="work around various renderer bugs (currently only librsvg)") |
125 | + self.OptionParser.add_option("--tab", type="string", action="store", dest="tab") |
126 | + self.OptionParser.add_option("--simplify-colors", type="inkbool", action="store", dest="simple_colors") |
127 | + self.OptionParser.add_option("--style-to-xml", type="inkbool", action="store", dest="style_to_xml") |
128 | + self.OptionParser.add_option("--group-collapsing", type="inkbool", action="store", dest="group_collapse") |
129 | + self.OptionParser.add_option("--create-groups", type="inkbool", action="store", dest="group_create") |
130 | + self.OptionParser.add_option("--enable-id-stripping", type="inkbool", action="store", dest="strip_ids") |
131 | + self.OptionParser.add_option("--shorten-ids", type="inkbool", action="store", dest="shorten_ids") |
132 | + self.OptionParser.add_option("--shorten-ids-prefix", type="string", action="store", dest="shorten_ids_prefix", default="") |
133 | + self.OptionParser.add_option("--embed-rasters", type="inkbool", action="store", dest="embed_rasters") |
134 | + self.OptionParser.add_option("--keep-unreferenced-defs", type="inkbool", action="store", dest="keep_defs") |
135 | + self.OptionParser.add_option("--keep-editor-data", type="inkbool", action="store", dest="keep_editor_data") |
136 | + self.OptionParser.add_option("--remove-metadata", type="inkbool", action="store", dest="remove_metadata") |
137 | + self.OptionParser.add_option("--strip-xml-prolog", type="inkbool", action="store", dest="strip_xml_prolog") |
138 | + self.OptionParser.add_option("--set-precision", type=int, action="store", dest="digits") |
139 | + self.OptionParser.add_option("--indent", type="string", action="store", dest="indent_type") |
140 | + self.OptionParser.add_option("--nindent", type=int, action="store", dest="indent_depth") |
141 | + self.OptionParser.add_option("--line-breaks", type="inkbool", action="store", dest="newlines") |
142 | + self.OptionParser.add_option("--strip-xml-space", type="inkbool", action="store", dest="strip_xml_space_attribute") |
143 | + self.OptionParser.add_option("--protect-ids-noninkscape", type="inkbool", action="store", dest="protect_ids_noninkscape") |
144 | + self.OptionParser.add_option("--protect-ids-list", type="string", action="store", dest="protect_ids_list") |
145 | + self.OptionParser.add_option("--protect-ids-prefix", type="string", action="store", dest="protect_ids_prefix") |
146 | + self.OptionParser.add_option("--enable-viewboxing", type="inkbool", action="store", dest="enable_viewboxing") |
147 | + self.OptionParser.add_option("--enable-comment-stripping", type="inkbool", action="store", dest="strip_comments") |
148 | + self.OptionParser.add_option("--renderer-workaround", type="inkbool", action="store", dest="renderer_workaround") |
149 | |
150 | def effect(self): |
151 | - input = file(self.args[0], "r") |
152 | - self.options.infilename=self.args[0] |
153 | - sys.stdout.write(scourString(input.read(), self.options).encode("UTF-8")) |
154 | - input.close() |
155 | - sys.stdout.close() |
156 | - |
157 | + try: |
158 | + input = file(self.args[0], "r") |
159 | + self.options.infilename = self.args[0] |
160 | + sys.stdout.write(scourString(input.read(), self.options).encode("UTF-8")) |
161 | + input.close() |
162 | + sys.stdout.close() |
163 | + except Exception as e: |
164 | + inkex.errormsg("Error during optimization.") |
165 | + inkex.errormsg("\nDetails:\n" + str(e)) |
166 | + inkex.errormsg("\nOS version: " + platform.platform()) |
167 | + inkex.errormsg("Python version: " + sys.version) |
168 | + inkex.errormsg("Scour version: " + scour.__version__) |
169 | + sys.exit() |
170 | |
171 | if __name__ == '__main__': |
172 | e = ScourInkscape() |
173 | |
174 | === modified file 'share/extensions/scour.inx' |
175 | --- share/extensions/scour.inx 2015-07-06 08:49:46 +0000 |
176 | +++ share/extensions/scour.inx 2016-01-13 18:39:42 +0000 |
177 | @@ -2,60 +2,97 @@ |
178 | <inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension"> |
179 | <_name>Optimized SVG Output</_name> |
180 | <id>org.inkscape.output.scour</id> |
181 | - <dependency type="executable" location="extensions">scour/scour.py</dependency> |
182 | - <dependency type="executable" location="extensions">scour/svg_regex.py</dependency> |
183 | - <dependency type="executable" location="extensions">scour/yocto_css.py</dependency> |
184 | + <dependency type="executable" location="extensions">scour.inkscape.py</dependency> |
185 | <param name="tab" type="notebook"> |
186 | - <page name="Options" _gui-text="Options"> |
187 | - <param name="simplify-colors" type="boolean" _gui-text="Shorten color values">true</param> |
188 | - <param name="style-to-xml" type="boolean" _gui-text="Convert CSS attributes to XML attributes">true</param> |
189 | - <param name="group-collapsing" type="boolean" _gui-text="Group collapsing">true</param> |
190 | - <param name="create-groups" type="boolean" _gui-text="Create groups for similar attributes">true</param> |
191 | - <param name="embed-rasters" type="boolean" _gui-text="Embed rasters">true</param> |
192 | - <param name="keep-editor-data" type="boolean" _gui-text="Keep editor data">false</param> |
193 | - <param name="remove-metadata" type="boolean" _gui-text="Remove metadata">false</param> |
194 | - <param name="enable-comment-stripping" type="boolean" _gui-text="Remove comments">false</param> |
195 | - <param name="renderer-workaround" type="boolean" _gui-text="Work around renderer bugs">true</param> |
196 | - <param name="enable-viewboxing" type="boolean" _gui-text="Enable viewboxing">false</param> |
197 | - <param name="strip-xml-prolog" type="boolean" _gui-text="Remove the xml declaration">false</param> |
198 | - <param name="set-precision" type="int" _gui-text="Number of significant digits for coords:">5</param> |
199 | - <param name="indent" type="enum" _gui-text="XML indentation (pretty-printing):"> |
200 | + <page name="Options" _gui-text="Options"> |
201 | + <param _gui-text="Number of significant digits for coordinates:" |
202 | + _gui-description="Specifies the number of significant digits that should be output for coordinates. Note that significant digits are *not* the number of decimals but the overall number of digits in the output. For example if a value of "3" is specified, the coordinate 3.14159 is output as 3.14 while the coordinate 123.675 is output as 124." |
203 | + name="set-precision" type="int">5</param> |
204 | + <param name="spacer" type="description"> </param> |
205 | + <param _gui-text="Shorten color values" |
206 | + _gui-description="Convert all color specifications to #RRGGBB (or #RGB where applicable) format." |
207 | + name="simplify-colors" type="boolean">true</param> |
208 | + <param _gui-text="Convert CSS attributes to XML attributes" |
209 | + _gui-description="Convert styles from style tags and inline style="" declarations into XML attributes." |
210 | + name="style-to-xml" type="boolean">true</param> |
211 | + <param name="spacer" type="description"> </param> |
212 | + <param _gui-text="Collapse groups" |
213 | + _gui-description="Remove useless groups, promoting their contents up one level. Requires "Remove unused IDs" to be set." |
214 | + name="group-collapsing" type="boolean">true</param> |
215 | + <param _gui-text="Create groups for similar attributes" |
216 | + _gui-description="Create groups for runs of elements having at least one attribute in common (e.g. fill-color, stroke-opacity, ...)." |
217 | + name="create-groups" type="boolean">true</param> |
218 | + <param name="spacer" type="description"> </param> |
219 | + <param _gui-text="Keep editor data" |
220 | + _gui-description="Don't remove editor-specific elements and attributes. Currently supported: Inkscape, Sodipodi and Adobe Illustrator." |
221 | + name="keep-editor-data" type="boolean">false</param> |
222 | + <param _gui-text="Keep unreferenced definitions" |
223 | + _gui-description="Keep element definitions that are not currently used in the SVG" |
224 | + name="keep-unreferenced-defs" type="boolean">false</param> |
225 | + <param name="spacer" type="description"> </param> |
226 | + <param _gui-text="Work around renderer bugs" |
227 | + _gui-description="Works around some common renderer bugs (mainly libRSVG) at the cost of a slightly larger SVG file." |
228 | + name="renderer-workaround" type="boolean">true</param> |
229 | + </page> |
230 | + <page name="Output" _gui-text="SVG Output"> |
231 | + <_param name="SVG_doc" type="description" appearance="header">Document options</_param> |
232 | + <param _gui-text="Remove the XML declaration" |
233 | + _gui-description="Removes the XML declaration (which is optional but should be provided, especially if special characters are used in the document) from the file header." |
234 | + name="strip-xml-prolog" type="boolean">false</param> |
235 | + <param _gui-text="Remove metadata" |
236 | + _gui-description="Remove metadata tags along with all the contained information, which may include license and author information, alternate versions for non-SVG-enabled browsers, etc." |
237 | + name="remove-metadata" type="boolean">false</param> |
238 | + <param _gui-text="Remove comments" |
239 | + _gui-description="Remove all XML comments from output." |
240 | + name="enable-comment-stripping" type="boolean">false</param> |
241 | + <param _gui-text="Embed raster images" |
242 | + _gui-description="Resolve external references to raster images and embed them as Base64-encoded data URLs." |
243 | + name="embed-rasters" type="boolean">true</param> |
244 | + <param _gui-text="Enable viewboxing" |
245 | + _gui-description="Set page size to 100%/100% (full width and height of the display area) and introduce a viewBox specifying the drawings dimensions." |
246 | + name="enable-viewboxing" type="boolean">false</param> |
247 | + <param name="spacer" type="description"> </param> |
248 | + <_param name="pretty_print" type="description" appearance="header">Pretty-printing</_param> |
249 | + <param _gui-text="Format output with line-breaks and indentation" |
250 | + _gui-description="Produce nicely formatted output including line-breaks. If you do not intend to hand-edit the SVG file you can disable this option to bring down the file size even more at the cost of clarity." |
251 | + name="line-breaks" type="boolean">true</param> |
252 | + <param _gui-text="Indentation characters:" |
253 | + _gui-description="The type of indentation used for each level of nesting in the output. Specify "None" to disable indentation. This option has no effect if "Format output with line-breaks and indentation" is disabled." |
254 | + name="indent" type="enum"> |
255 | <_item value="space">Space</_item> |
256 | <_item value="tab">Tab</_item> |
257 | <_item msgctxt="Indent" value="none">None</_item> |
258 | </param> |
259 | - </page> |
260 | - <page name="Ids" _gui-text="Ids"> |
261 | - <param name="enable-id-stripping" type="boolean" _gui-text="Remove unused ID names for elements">false</param> |
262 | - <param name="shorten-ids" type="boolean" _gui-text="Shorten IDs">false</param> |
263 | - <param name="protect-ids-noninkscape" type="boolean" _gui-text="Preserve manually created ID names not ending with digits">false</param> |
264 | - <param name="protect-ids-list" type="string" _gui-text="Preserve these ID names, comma-separated:"></param> |
265 | - <param name="protect-ids-prefix" type="string" _gui-text="Preserve ID names starting with:"></param> |
266 | - </page> |
267 | - <page name="OptionHelp" _gui-text="Help (Options)"> |
268 | - <_param name="OptionsInstructions" type="description" xml:space="preserve">This extension optimizes the SVG file according to the following options: |
269 | - * Shorten color names: convert all colors to #RRGGBB or #RGB format. |
270 | - * Convert CSS attributes to XML attributes: convert styles from style tags and inline style="" declarations into XML attributes. |
271 | - * Group collapsing: removes useless g elements, promoting their contents up one level. Requires "Remove unused ID names for elements" to be set. |
272 | - * Create groups for similar attributes: create g elements for runs of elements having at least one attribute in common (e.g. fill color, stroke opacity, ...). |
273 | - * Embed rasters: embed raster images as base64-encoded data URLs. |
274 | - * Keep editor data: don't remove Inkscape, Sodipodi or Adobe Illustrator elements and attributes. |
275 | - * Remove metadata: remove metadata tags along with all the information in them, which may include license metadata, alternate versions for non-SVG-enabled browsers, etc. |
276 | - * Remove comments: remove comment tags. |
277 | - * Work around renderer bugs: emits slightly larger SVG data, but works around a bug in librsvg's renderer, which is used in Eye of GNOME and other various applications. |
278 | - * Enable viewboxing: size image to 100%/100% and introduce a viewBox. |
279 | - * Number of significant digits for coords: all coordinates are output with that number of significant digits. For example, if 3 is specified, the coordinate 3.5153 is output as 3.51 and the coordinate 471.55 is output as 472. |
280 | - * XML indentation (pretty-printing): either None for no indentation, Space to use one space per nesting level, or Tab to use one tab per nesting level.</_param> |
281 | - </page> |
282 | - <page name="IdHelp" _gui-text="Help (Ids)"> |
283 | - <_param name="IDInstructions" type="description" xml:space="preserve">Ids specific options: |
284 | - * Remove unused ID names for elements: remove all unreferenced ID attributes. |
285 | - * Shorten IDs: reduce the length of all ID attributes, assigning the shortest to the most-referenced elements. For instance, #linearGradient5621, referenced 100 times, can become #a. |
286 | - * Preserve manually created ID names not ending with digits: usually, optimised SVG output removes these, but if they're needed for referencing (e.g. #middledot), you may use this option. |
287 | - * Preserve these ID names, comma-separated: you can use this in conjunction with the other preserve options if you wish to preserve some more specific ID names. |
288 | - * Preserve ID names starting with: usually, optimised SVG output removes all unused ID names, but if all of your preserved ID names start with the same prefix (e.g. #flag-mx, #flag-pt), you may use this option.</_param> |
289 | - </page> |
290 | - </param> |
291 | + <param _gui-text="Depth of indentation:" |
292 | + _gui-description="The depth of the chosen type of indentation. E.g. if you choose "2" every nesting level in the output will be indented by two additional spaces/tabs." |
293 | + name="nindent" type="int">1</param> |
294 | + <param _gui-text="Strip the "xml:space" attribute from the root SVG element" |
295 | + _gui-description="This is useful if the input file specifies "xml:space='preserve'" in the root SVG element which instructs the SVG editor not to change whitespace in the document at all (and therefore overrides the options above)." |
296 | + name="strip-xml-space" type="boolean">false</param> |
297 | + </page> |
298 | + <page name="IDs" _gui-text="IDs"> |
299 | + <param _gui-text="Remove unused IDs" |
300 | + _gui-description="Remove all unreferenced IDs from elements. Those are not needed for rendering." |
301 | + name="enable-id-stripping" type="boolean">true</param> |
302 | + <param name="spacer" type="description"> </param> |
303 | + <param _gui-text="Shorten IDs" |
304 | + _gui-description="Minimize the length of IDs using only lowercase letters, assigning the shortest values to the most-referenced elements. For instance, "linearGradient5621" will become "a" if it is the most used element." |
305 | + name="shorten-ids" type="boolean">false</param> |
306 | + <param _gui-text="Prefix shortened IDs with:" |
307 | + _gui-description="Prepend shortened IDs with the specified prefix." |
308 | + name="shorten-ids-prefix" type="string"></param> |
309 | + <param name="spacer" type="description"> </param> |
310 | + <param _gui-text="Preserve manually created IDs not ending with digits" |
311 | + _gui-description="Descriptive IDs which were manually created to reference or label specific elements or groups (e.g. #arrowStart, #arrowEnd or #textLabels) will be preserved while numbered IDs (as they are generated by most SVG editors including Inkscape) will be removed/shortened." |
312 | + name="protect-ids-noninkscape" type="boolean">true</param> |
313 | + <param _gui-text="Preserve the following IDs:" |
314 | + _gui-description="A comma-separated list of IDs that are to be preserved." |
315 | + name="protect-ids-list" type="string"></param> |
316 | + <param _gui-text="Preserve IDs starting with:" |
317 | + _gui-description="Preserve all IDs that start with the specified prefix (e.g. specify "flag" to preserve "flag-mx", "flag-pt", etc.)." |
318 | + name="protect-ids-prefix" type="string"></param> |
319 | + </page> |
320 | + </param> |
321 | <output> |
322 | <extension>.svg</extension> |
323 | <mimetype>image/svg+xml</mimetype> |
324 | @@ -63,6 +100,6 @@ |
325 | <_filetypetooltip>Scalable Vector Graphics</_filetypetooltip> |
326 | </output> |
327 | <script> |
328 | - <command reldir="extensions" interpreter="python">scour/scour.inkscape.py</command> |
329 | + <command reldir="extensions" interpreter="python">scour.inkscape.py</command> |
330 | </script> |
331 | </inkscape-extension> |
332 | |
333 | === removed file 'share/extensions/scour/Makefile.am' |
334 | --- share/extensions/scour/Makefile.am 2015-07-06 08:49:46 +0000 |
335 | +++ share/extensions/scour/Makefile.am 1970-01-01 00:00:00 +0000 |
336 | @@ -1,13 +0,0 @@ |
337 | - |
338 | -scourdir = $(datadir)/inkscape/extensions/scour |
339 | - |
340 | -scour_DATA = \ |
341 | - scour.py \ |
342 | - scour.inkscape.py \ |
343 | - svg_regex.py \ |
344 | - svg_transform.py \ |
345 | - yocto_css.py |
346 | - |
347 | -EXTRA_DIST = \ |
348 | - $(scour_DATA) |
349 | - |
350 | |
351 | === removed file 'share/extensions/scour/scour.py' |
352 | --- share/extensions/scour/scour.py 2015-09-13 17:09:56 +0000 |
353 | +++ share/extensions/scour/scour.py 1970-01-01 00:00:00 +0000 |
354 | @@ -1,3235 +0,0 @@ |
355 | -#!/usr/bin/env python |
356 | -# -*- coding: utf-8 -*- |
357 | - |
358 | -# Scour |
359 | -# |
360 | -# Copyright 2010 Jeff Schiller |
361 | -# Copyright 2010 Louis Simard |
362 | -# |
363 | -# This file is part of Scour, http://www.codedread.com/scour/ |
364 | -# |
365 | -# This library is free software; you can redistribute it and/or modify |
366 | -# it either under the terms of the Apache License, Version 2.0, or, at |
367 | -# your option, under the terms and conditions of the GNU General |
368 | -# Public License, Version 2 or newer as published by the Free Software |
369 | -# Foundation. You may obtain a copy of these Licenses at: |
370 | -# |
371 | -# http://www.apache.org/licenses/LICENSE-2.0 |
372 | -# https://www.gnu.org/licenses/old-licenses/gpl-2.0.html |
373 | -# |
374 | -# Unless required by applicable law or agreed to in writing, software |
375 | -# distributed under the License is distributed on an "AS IS" BASIS, |
376 | -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
377 | -# See the License for the specific language governing permissions and |
378 | -# limitations under the License. |
379 | - |
380 | -# Notes: |
381 | - |
382 | -# rubys' path-crunching ideas here: http://intertwingly.net/code/svgtidy/spec.rb |
383 | -# (and implemented here: http://intertwingly.net/code/svgtidy/svgtidy.rb ) |
384 | - |
385 | -# Yet more ideas here: http://wiki.inkscape.org/wiki/index.php/Save_Cleaned_SVG |
386 | -# |
387 | -# * Process Transformations |
388 | -# * Collapse all group based transformations |
389 | - |
390 | -# Even more ideas here: http://esw.w3.org/topic/SvgTidy |
391 | -# * analysis of path elements to see if rect can be used instead? (must also need to look |
392 | -# at rounded corners) |
393 | - |
394 | -# Next Up: |
395 | -# - why are marker-start, -end not removed from the style attribute? |
396 | -# - why are only overflow style properties considered and not attributes? |
397 | -# - only remove unreferenced elements if they are not children of a referenced element |
398 | -# - add an option to remove ids if they match the Inkscape-style of IDs |
399 | -# - investigate point-reducing algorithms |
400 | -# - parse transform attribute |
401 | -# - if a <g> has only one element in it, collapse the <g> (ensure transform, etc are carried down) |
402 | - |
403 | -# necessary to get true division |
404 | -from __future__ import division |
405 | - |
406 | -import os |
407 | -import sys |
408 | -import xml.dom.minidom |
409 | -import re |
410 | -import math |
411 | -from svg_regex import svg_parser |
412 | -from svg_transform import svg_transform_parser |
413 | -import optparse |
414 | -from yocto_css import parseCssString |
415 | - |
416 | -# Python 2.3- did not have Decimal |
417 | -try: |
418 | - from decimal import * |
419 | -except ImportError: |
420 | - print >>sys.stderr, "Scour requires Python 2.4." |
421 | - |
422 | -# Import Psyco if available |
423 | -try: |
424 | - import psyco |
425 | - psyco.full() |
426 | -except ImportError: |
427 | - pass |
428 | - |
429 | -APP = 'scour' |
430 | -VER = '0.26+r220' |
431 | -COPYRIGHT = 'Copyright Jeff Schiller, Louis Simard, 2012' |
432 | - |
433 | -NS = { 'SVG': 'http://www.w3.org/2000/svg', |
434 | - 'XLINK': 'http://www.w3.org/1999/xlink', |
435 | - 'SODIPODI': 'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd', |
436 | - 'INKSCAPE': 'http://www.inkscape.org/namespaces/inkscape', |
437 | - 'ADOBE_ILLUSTRATOR': 'http://ns.adobe.com/AdobeIllustrator/10.0/', |
438 | - 'ADOBE_GRAPHS': 'http://ns.adobe.com/Graphs/1.0/', |
439 | - 'ADOBE_SVG_VIEWER': 'http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/', |
440 | - 'ADOBE_VARIABLES': 'http://ns.adobe.com/Variables/1.0/', |
441 | - 'ADOBE_SFW': 'http://ns.adobe.com/SaveForWeb/1.0/', |
442 | - 'ADOBE_EXTENSIBILITY': 'http://ns.adobe.com/Extensibility/1.0/', |
443 | - 'ADOBE_FLOWS': 'http://ns.adobe.com/Flows/1.0/', |
444 | - 'ADOBE_IMAGE_REPLACEMENT': 'http://ns.adobe.com/ImageReplacement/1.0/', |
445 | - 'ADOBE_CUSTOM': 'http://ns.adobe.com/GenericCustomNamespace/1.0/', |
446 | - 'ADOBE_XPATH': 'http://ns.adobe.com/XPath/1.0/' |
447 | - } |
448 | - |
449 | -unwanted_ns = [ NS['SODIPODI'], NS['INKSCAPE'], NS['ADOBE_ILLUSTRATOR'], |
450 | - NS['ADOBE_GRAPHS'], NS['ADOBE_SVG_VIEWER'], NS['ADOBE_VARIABLES'], |
451 | - NS['ADOBE_SFW'], NS['ADOBE_EXTENSIBILITY'], NS['ADOBE_FLOWS'], |
452 | - NS['ADOBE_IMAGE_REPLACEMENT'], NS['ADOBE_CUSTOM'], NS['ADOBE_XPATH'] ] |
453 | - |
454 | -svgAttributes = [ |
455 | - 'clip-rule', |
456 | - 'display', |
457 | - 'fill', |
458 | - 'fill-opacity', |
459 | - 'fill-rule', |
460 | - 'filter', |
461 | - 'font-family', |
462 | - 'font-size', |
463 | - 'font-stretch', |
464 | - 'font-style', |
465 | - 'font-variant', |
466 | - 'font-weight', |
467 | - 'line-height', |
468 | - 'marker', |
469 | - 'marker-end', |
470 | - 'marker-mid', |
471 | - 'marker-start', |
472 | - 'opacity', |
473 | - 'overflow', |
474 | - 'stop-color', |
475 | - 'stop-opacity', |
476 | - 'stroke', |
477 | - 'stroke-dasharray', |
478 | - 'stroke-dashoffset', |
479 | - 'stroke-linecap', |
480 | - 'stroke-linejoin', |
481 | - 'stroke-miterlimit', |
482 | - 'stroke-opacity', |
483 | - 'stroke-width', |
484 | - 'visibility' |
485 | - ] |
486 | - |
487 | -colors = { |
488 | - 'aliceblue': 'rgb(240, 248, 255)', |
489 | - 'antiquewhite': 'rgb(250, 235, 215)', |
490 | - 'aqua': 'rgb( 0, 255, 255)', |
491 | - 'aquamarine': 'rgb(127, 255, 212)', |
492 | - 'azure': 'rgb(240, 255, 255)', |
493 | - 'beige': 'rgb(245, 245, 220)', |
494 | - 'bisque': 'rgb(255, 228, 196)', |
495 | - 'black': 'rgb( 0, 0, 0)', |
496 | - 'blanchedalmond': 'rgb(255, 235, 205)', |
497 | - 'blue': 'rgb( 0, 0, 255)', |
498 | - 'blueviolet': 'rgb(138, 43, 226)', |
499 | - 'brown': 'rgb(165, 42, 42)', |
500 | - 'burlywood': 'rgb(222, 184, 135)', |
501 | - 'cadetblue': 'rgb( 95, 158, 160)', |
502 | - 'chartreuse': 'rgb(127, 255, 0)', |
503 | - 'chocolate': 'rgb(210, 105, 30)', |
504 | - 'coral': 'rgb(255, 127, 80)', |
505 | - 'cornflowerblue': 'rgb(100, 149, 237)', |
506 | - 'cornsilk': 'rgb(255, 248, 220)', |
507 | - 'crimson': 'rgb(220, 20, 60)', |
508 | - 'cyan': 'rgb( 0, 255, 255)', |
509 | - 'darkblue': 'rgb( 0, 0, 139)', |
510 | - 'darkcyan': 'rgb( 0, 139, 139)', |
511 | - 'darkgoldenrod': 'rgb(184, 134, 11)', |
512 | - 'darkgray': 'rgb(169, 169, 169)', |
513 | - 'darkgreen': 'rgb( 0, 100, 0)', |
514 | - 'darkgrey': 'rgb(169, 169, 169)', |
515 | - 'darkkhaki': 'rgb(189, 183, 107)', |
516 | - 'darkmagenta': 'rgb(139, 0, 139)', |
517 | - 'darkolivegreen': 'rgb( 85, 107, 47)', |
518 | - 'darkorange': 'rgb(255, 140, 0)', |
519 | - 'darkorchid': 'rgb(153, 50, 204)', |
520 | - 'darkred': 'rgb(139, 0, 0)', |
521 | - 'darksalmon': 'rgb(233, 150, 122)', |
522 | - 'darkseagreen': 'rgb(143, 188, 143)', |
523 | - 'darkslateblue': 'rgb( 72, 61, 139)', |
524 | - 'darkslategray': 'rgb( 47, 79, 79)', |
525 | - 'darkslategrey': 'rgb( 47, 79, 79)', |
526 | - 'darkturquoise': 'rgb( 0, 206, 209)', |
527 | - 'darkviolet': 'rgb(148, 0, 211)', |
528 | - 'deeppink': 'rgb(255, 20, 147)', |
529 | - 'deepskyblue': 'rgb( 0, 191, 255)', |
530 | - 'dimgray': 'rgb(105, 105, 105)', |
531 | - 'dimgrey': 'rgb(105, 105, 105)', |
532 | - 'dodgerblue': 'rgb( 30, 144, 255)', |
533 | - 'firebrick': 'rgb(178, 34, 34)', |
534 | - 'floralwhite': 'rgb(255, 250, 240)', |
535 | - 'forestgreen': 'rgb( 34, 139, 34)', |
536 | - 'fuchsia': 'rgb(255, 0, 255)', |
537 | - 'gainsboro': 'rgb(220, 220, 220)', |
538 | - 'ghostwhite': 'rgb(248, 248, 255)', |
539 | - 'gold': 'rgb(255, 215, 0)', |
540 | - 'goldenrod': 'rgb(218, 165, 32)', |
541 | - 'gray': 'rgb(128, 128, 128)', |
542 | - 'grey': 'rgb(128, 128, 128)', |
543 | - 'green': 'rgb( 0, 128, 0)', |
544 | - 'greenyellow': 'rgb(173, 255, 47)', |
545 | - 'honeydew': 'rgb(240, 255, 240)', |
546 | - 'hotpink': 'rgb(255, 105, 180)', |
547 | - 'indianred': 'rgb(205, 92, 92)', |
548 | - 'indigo': 'rgb( 75, 0, 130)', |
549 | - 'ivory': 'rgb(255, 255, 240)', |
550 | - 'khaki': 'rgb(240, 230, 140)', |
551 | - 'lavender': 'rgb(230, 230, 250)', |
552 | - 'lavenderblush': 'rgb(255, 240, 245)', |
553 | - 'lawngreen': 'rgb(124, 252, 0)', |
554 | - 'lemonchiffon': 'rgb(255, 250, 205)', |
555 | - 'lightblue': 'rgb(173, 216, 230)', |
556 | - 'lightcoral': 'rgb(240, 128, 128)', |
557 | - 'lightcyan': 'rgb(224, 255, 255)', |
558 | - 'lightgoldenrodyellow': 'rgb(250, 250, 210)', |
559 | - 'lightgray': 'rgb(211, 211, 211)', |
560 | - 'lightgreen': 'rgb(144, 238, 144)', |
561 | - 'lightgrey': 'rgb(211, 211, 211)', |
562 | - 'lightpink': 'rgb(255, 182, 193)', |
563 | - 'lightsalmon': 'rgb(255, 160, 122)', |
564 | - 'lightseagreen': 'rgb( 32, 178, 170)', |
565 | - 'lightskyblue': 'rgb(135, 206, 250)', |
566 | - 'lightslategray': 'rgb(119, 136, 153)', |
567 | - 'lightslategrey': 'rgb(119, 136, 153)', |
568 | - 'lightsteelblue': 'rgb(176, 196, 222)', |
569 | - 'lightyellow': 'rgb(255, 255, 224)', |
570 | - 'lime': 'rgb( 0, 255, 0)', |
571 | - 'limegreen': 'rgb( 50, 205, 50)', |
572 | - 'linen': 'rgb(250, 240, 230)', |
573 | - 'magenta': 'rgb(255, 0, 255)', |
574 | - 'maroon': 'rgb(128, 0, 0)', |
575 | - 'mediumaquamarine': 'rgb(102, 205, 170)', |
576 | - 'mediumblue': 'rgb( 0, 0, 205)', |
577 | - 'mediumorchid': 'rgb(186, 85, 211)', |
578 | - 'mediumpurple': 'rgb(147, 112, 219)', |
579 | - 'mediumseagreen': 'rgb( 60, 179, 113)', |
580 | - 'mediumslateblue': 'rgb(123, 104, 238)', |
581 | - 'mediumspringgreen': 'rgb( 0, 250, 154)', |
582 | - 'mediumturquoise': 'rgb( 72, 209, 204)', |
583 | - 'mediumvioletred': 'rgb(199, 21, 133)', |
584 | - 'midnightblue': 'rgb( 25, 25, 112)', |
585 | - 'mintcream': 'rgb(245, 255, 250)', |
586 | - 'mistyrose': 'rgb(255, 228, 225)', |
587 | - 'moccasin': 'rgb(255, 228, 181)', |
588 | - 'navajowhite': 'rgb(255, 222, 173)', |
589 | - 'navy': 'rgb( 0, 0, 128)', |
590 | - 'oldlace': 'rgb(253, 245, 230)', |
591 | - 'olive': 'rgb(128, 128, 0)', |
592 | - 'olivedrab': 'rgb(107, 142, 35)', |
593 | - 'orange': 'rgb(255, 165, 0)', |
594 | - 'orangered': 'rgb(255, 69, 0)', |
595 | - 'orchid': 'rgb(218, 112, 214)', |
596 | - 'palegoldenrod': 'rgb(238, 232, 170)', |
597 | - 'palegreen': 'rgb(152, 251, 152)', |
598 | - 'paleturquoise': 'rgb(175, 238, 238)', |
599 | - 'palevioletred': 'rgb(219, 112, 147)', |
600 | - 'papayawhip': 'rgb(255, 239, 213)', |
601 | - 'peachpuff': 'rgb(255, 218, 185)', |
602 | - 'peru': 'rgb(205, 133, 63)', |
603 | - 'pink': 'rgb(255, 192, 203)', |
604 | - 'plum': 'rgb(221, 160, 221)', |
605 | - 'powderblue': 'rgb(176, 224, 230)', |
606 | - 'purple': 'rgb(128, 0, 128)', |
607 | - 'rebeccapurple': 'rgb(102, 51, 153)', |
608 | - 'red': 'rgb(255, 0, 0)', |
609 | - 'rosybrown': 'rgb(188, 143, 143)', |
610 | - 'royalblue': 'rgb( 65, 105, 225)', |
611 | - 'saddlebrown': 'rgb(139, 69, 19)', |
612 | - 'salmon': 'rgb(250, 128, 114)', |
613 | - 'sandybrown': 'rgb(244, 164, 96)', |
614 | - 'seagreen': 'rgb( 46, 139, 87)', |
615 | - 'seashell': 'rgb(255, 245, 238)', |
616 | - 'sienna': 'rgb(160, 82, 45)', |
617 | - 'silver': 'rgb(192, 192, 192)', |
618 | - 'skyblue': 'rgb(135, 206, 235)', |
619 | - 'slateblue': 'rgb(106, 90, 205)', |
620 | - 'slategray': 'rgb(112, 128, 144)', |
621 | - 'slategrey': 'rgb(112, 128, 144)', |
622 | - 'snow': 'rgb(255, 250, 250)', |
623 | - 'springgreen': 'rgb( 0, 255, 127)', |
624 | - 'steelblue': 'rgb( 70, 130, 180)', |
625 | - 'tan': 'rgb(210, 180, 140)', |
626 | - 'teal': 'rgb( 0, 128, 128)', |
627 | - 'thistle': 'rgb(216, 191, 216)', |
628 | - 'tomato': 'rgb(255, 99, 71)', |
629 | - 'turquoise': 'rgb( 64, 224, 208)', |
630 | - 'violet': 'rgb(238, 130, 238)', |
631 | - 'wheat': 'rgb(245, 222, 179)', |
632 | - 'white': 'rgb(255, 255, 255)', |
633 | - 'whitesmoke': 'rgb(245, 245, 245)', |
634 | - 'yellow': 'rgb(255, 255, 0)', |
635 | - 'yellowgreen': 'rgb(154, 205, 50)', |
636 | - } |
637 | - |
638 | -default_attributes = { # excluded all attributes with 'auto' as default |
639 | - # SVG 1.1 presentation attributes |
640 | - 'baseline-shift': 'baseline', |
641 | - 'clip-path': 'none', |
642 | - 'clip-rule': 'nonzero', |
643 | - 'color': '#000', |
644 | - 'color-interpolation-filters': 'linearRGB', |
645 | - 'color-interpolation': 'sRGB', |
646 | - 'direction': 'ltr', |
647 | - 'display': 'inline', |
648 | - 'enable-background': 'accumulate', |
649 | - 'fill': '#000', |
650 | - 'fill-opacity': '1', |
651 | - 'fill-rule': 'nonzero', |
652 | - 'filter': 'none', |
653 | - 'flood-color': '#000', |
654 | - 'flood-opacity': '1', |
655 | - 'font-size-adjust': 'none', |
656 | - 'font-size': 'medium', |
657 | - 'font-stretch': 'normal', |
658 | - 'font-style': 'normal', |
659 | - 'font-variant': 'normal', |
660 | - 'font-weight': 'normal', |
661 | - 'glyph-orientation-horizontal': '0deg', |
662 | - 'letter-spacing': 'normal', |
663 | - 'lighting-color': '#fff', |
664 | - 'marker': 'none', |
665 | - 'marker-start': 'none', |
666 | - 'marker-mid': 'none', |
667 | - 'marker-end': 'none', |
668 | - 'mask': 'none', |
669 | - 'opacity': '1', |
670 | - 'pointer-events': 'visiblePainted', |
671 | - 'stop-color': '#000', |
672 | - 'stop-opacity': '1', |
673 | - 'stroke': 'none', |
674 | - 'stroke-dasharray': 'none', |
675 | - 'stroke-dashoffset': '0', |
676 | - 'stroke-linecap': 'butt', |
677 | - 'stroke-linejoin': 'miter', |
678 | - 'stroke-miterlimit': '4', |
679 | - 'stroke-opacity': '1', |
680 | - 'stroke-width': '1', |
681 | - 'text-anchor': 'start', |
682 | - 'text-decoration': 'none', |
683 | - 'unicode-bidi': 'normal', |
684 | - 'visibility': 'visible', |
685 | - 'word-spacing': 'normal', |
686 | - 'writing-mode': 'lr-tb', |
687 | - # SVG 1.2 tiny properties |
688 | - 'audio-level': '1', |
689 | - 'solid-color': '#000', |
690 | - 'solid-opacity': '1', |
691 | - 'text-align': 'start', |
692 | - 'vector-effect': 'none', |
693 | - 'viewport-fill': 'none', |
694 | - 'viewport-fill-opacity': '1', |
695 | - } |
696 | - |
697 | -def isSameSign(a,b): return (a <= 0 and b <= 0) or (a >= 0 and b >= 0) |
698 | - |
699 | -scinumber = re.compile(r"[-+]?(\d*\.?)?\d+[eE][-+]?\d+") |
700 | -number = re.compile(r"[-+]?(\d*\.?)?\d+") |
701 | -sciExponent = re.compile(r"[eE]([-+]?\d+)") |
702 | -unit = re.compile("(em|ex|px|pt|pc|cm|mm|in|%){1,1}$") |
703 | - |
704 | -class Unit(object): |
705 | - # Integer constants for units. |
706 | - INVALID = -1 |
707 | - NONE = 0 |
708 | - PCT = 1 |
709 | - PX = 2 |
710 | - PT = 3 |
711 | - PC = 4 |
712 | - EM = 5 |
713 | - EX = 6 |
714 | - CM = 7 |
715 | - MM = 8 |
716 | - IN = 9 |
717 | - |
718 | - # String to Unit. Basically, converts unit strings to their integer constants. |
719 | - s2u = { |
720 | - '': NONE, |
721 | - '%': PCT, |
722 | - 'px': PX, |
723 | - 'pt': PT, |
724 | - 'pc': PC, |
725 | - 'em': EM, |
726 | - 'ex': EX, |
727 | - 'cm': CM, |
728 | - 'mm': MM, |
729 | - 'in': IN, |
730 | - } |
731 | - |
732 | - # Unit to String. Basically, converts unit integer constants to their corresponding strings. |
733 | - u2s = { |
734 | - NONE: '', |
735 | - PCT: '%', |
736 | - PX: 'px', |
737 | - PT: 'pt', |
738 | - PC: 'pc', |
739 | - EM: 'em', |
740 | - EX: 'ex', |
741 | - CM: 'cm', |
742 | - MM: 'mm', |
743 | - IN: 'in', |
744 | - } |
745 | - |
746 | -# @staticmethod |
747 | - def get(unitstr): |
748 | - if unitstr is None: return Unit.NONE |
749 | - try: |
750 | - return Unit.s2u[unitstr] |
751 | - except KeyError: |
752 | - return Unit.INVALID |
753 | - |
754 | -# @staticmethod |
755 | - def str(unitint): |
756 | - try: |
757 | - return Unit.u2s[unitint] |
758 | - except KeyError: |
759 | - return 'INVALID' |
760 | - |
761 | - get = staticmethod(get) |
762 | - str = staticmethod(str) |
763 | - |
764 | -class SVGLength(object): |
765 | - def __init__(self, str): |
766 | - try: # simple unitless and no scientific notation |
767 | - self.value = float(str) |
768 | - if int(self.value) == self.value: |
769 | - self.value = int(self.value) |
770 | - self.units = Unit.NONE |
771 | - except ValueError: |
772 | - # we know that the length string has an exponent, a unit, both or is invalid |
773 | - |
774 | - # parse out number, exponent and unit |
775 | - self.value = 0 |
776 | - unitBegin = 0 |
777 | - scinum = scinumber.match(str) |
778 | - if scinum != None: |
779 | - # this will always match, no need to check it |
780 | - numMatch = number.match(str) |
781 | - expMatch = sciExponent.search(str, numMatch.start(0)) |
782 | - self.value = (float(numMatch.group(0)) * |
783 | - 10 ** float(expMatch.group(1))) |
784 | - unitBegin = expMatch.end(1) |
785 | - else: |
786 | - # unit or invalid |
787 | - numMatch = number.match(str) |
788 | - if numMatch != None: |
789 | - self.value = float(numMatch.group(0)) |
790 | - unitBegin = numMatch.end(0) |
791 | - |
792 | - if int(self.value) == self.value: |
793 | - self.value = int(self.value) |
794 | - |
795 | - if unitBegin != 0 : |
796 | - unitMatch = unit.search(str, unitBegin) |
797 | - if unitMatch != None : |
798 | - self.units = Unit.get(unitMatch.group(0)) |
799 | - |
800 | - # invalid |
801 | - else: |
802 | - # TODO: this needs to set the default for the given attribute (how?) |
803 | - self.value = 0 |
804 | - self.units = Unit.INVALID |
805 | - |
806 | -def findElementsWithId(node, elems=None): |
807 | - """ |
808 | - Returns all elements with id attributes |
809 | - """ |
810 | - if elems is None: |
811 | - elems = {} |
812 | - id = node.getAttribute('id') |
813 | - if id != '' : |
814 | - elems[id] = node |
815 | - if node.hasChildNodes() : |
816 | - for child in node.childNodes: |
817 | - # from http://www.w3.org/TR/DOM-Level-2-Core/idl-definitions.html |
818 | - # we are only really interested in nodes of type Element (1) |
819 | - if child.nodeType == 1 : |
820 | - findElementsWithId(child, elems) |
821 | - return elems |
822 | - |
823 | -referencingProps = ['fill', 'stroke', 'filter', 'clip-path', 'mask', 'marker-start', |
824 | - 'marker-end', 'marker-mid'] |
825 | - |
826 | -def findReferencedElements(node, ids=None): |
827 | - """ |
828 | - Returns the number of times an ID is referenced as well as all elements |
829 | - that reference it. node is the node at which to start the search. The |
830 | - return value is a map which has the id as key and each value is an array |
831 | - where the first value is a count and the second value is a list of nodes |
832 | - that referenced it. |
833 | - |
834 | - Currently looks at fill, stroke, clip-path, mask, marker, and |
835 | - xlink:href attributes. |
836 | - """ |
837 | - global referencingProps |
838 | - if ids is None: |
839 | - ids = {} |
840 | - # TODO: input argument ids is clunky here (see below how it is called) |
841 | - # GZ: alternative to passing dict, use **kwargs |
842 | - |
843 | - # if this node is a style element, parse its text into CSS |
844 | - if node.nodeName == 'style' and node.namespaceURI == NS['SVG']: |
845 | - # one stretch of text, please! (we could use node.normalize(), but |
846 | - # this actually modifies the node, and we don't want to keep |
847 | - # whitespace around if there's any) |
848 | - stylesheet = "".join([child.nodeValue for child in node.childNodes]) |
849 | - if stylesheet != '': |
850 | - cssRules = parseCssString(stylesheet) |
851 | - for rule in cssRules: |
852 | - for propname in rule['properties']: |
853 | - propval = rule['properties'][propname] |
854 | - findReferencingProperty(node, propname, propval, ids) |
855 | - return ids |
856 | - |
857 | - # else if xlink:href is set, then grab the id |
858 | - href = node.getAttributeNS(NS['XLINK'],'href') |
859 | - if href != '' and len(href) > 1 and href[0] == '#': |
860 | - # we remove the hash mark from the beginning of the id |
861 | - id = href[1:] |
862 | - if id in ids: |
863 | - ids[id][0] += 1 |
864 | - ids[id][1].append(node) |
865 | - else: |
866 | - ids[id] = [1,[node]] |
867 | - |
868 | - # now get all style properties and the fill, stroke, filter attributes |
869 | - styles = node.getAttribute('style').split(';') |
870 | - for attr in referencingProps: |
871 | - styles.append(':'.join([attr, node.getAttribute(attr)])) |
872 | - |
873 | - for style in styles: |
874 | - propval = style.split(':') |
875 | - if len(propval) == 2 : |
876 | - prop = propval[0].strip() |
877 | - val = propval[1].strip() |
878 | - findReferencingProperty(node, prop, val, ids) |
879 | - |
880 | - if node.hasChildNodes() : |
881 | - for child in node.childNodes: |
882 | - if child.nodeType == 1 : |
883 | - findReferencedElements(child, ids) |
884 | - return ids |
885 | - |
886 | -def findReferencingProperty(node, prop, val, ids): |
887 | - global referencingProps |
888 | - if prop in referencingProps and val != '' : |
889 | - if len(val) >= 7 and val[0:5] == 'url(#' : |
890 | - id = val[5:val.find(')')] |
891 | - if ids.has_key(id) : |
892 | - ids[id][0] += 1 |
893 | - ids[id][1].append(node) |
894 | - else: |
895 | - ids[id] = [1,[node]] |
896 | - # if the url has a quote in it, we need to compensate |
897 | - elif len(val) >= 8 : |
898 | - id = None |
899 | - # double-quote |
900 | - if val[0:6] == 'url("#' : |
901 | - id = val[6:val.find('")')] |
902 | - # single-quote |
903 | - elif val[0:6] == "url('#" : |
904 | - id = val[6:val.find("')")] |
905 | - if id != None: |
906 | - if ids.has_key(id) : |
907 | - ids[id][0] += 1 |
908 | - ids[id][1].append(node) |
909 | - else: |
910 | - ids[id] = [1,[node]] |
911 | - |
912 | -numIDsRemoved = 0 |
913 | -numElemsRemoved = 0 |
914 | -numAttrsRemoved = 0 |
915 | -numRastersEmbedded = 0 |
916 | -numPathSegmentsReduced = 0 |
917 | -numCurvesStraightened = 0 |
918 | -numBytesSavedInPathData = 0 |
919 | -numBytesSavedInColors = 0 |
920 | -numBytesSavedInIDs = 0 |
921 | -numBytesSavedInLengths = 0 |
922 | -numBytesSavedInTransforms = 0 |
923 | -numPointsRemovedFromPolygon = 0 |
924 | -numCommentBytes = 0 |
925 | - |
926 | -def flattenDefs(doc): |
927 | - """ |
928 | - Puts all defined elements into a newly created defs in the document. This function |
929 | - handles recursive defs elements. |
930 | - """ |
931 | - defs = doc.documentElement.getElementsByTagName('defs') |
932 | - |
933 | - if defs.length > 1: |
934 | - topDef = doc.createElementNS(NS['SVG'], 'defs') |
935 | - |
936 | - for defElem in defs: |
937 | - # Remove all children of this defs and put it into the topDef. |
938 | - while defElem.hasChildNodes(): |
939 | - topDef.appendChild(defElem.firstChild) |
940 | - defElem.parentNode.removeChild(defElem) |
941 | - |
942 | - if topDef.hasChildNodes(): |
943 | - doc.documentElement.insertBefore(topDef, doc.documentElement.firstChild) |
944 | - |
945 | -def removeUnusedDefs(doc, defElem, elemsToRemove=None): |
946 | - if elemsToRemove is None: |
947 | - elemsToRemove = [] |
948 | - |
949 | - identifiedElements = findElementsWithId(doc.documentElement) |
950 | - referencedIDs = findReferencedElements(doc.documentElement) |
951 | - |
952 | - keepTags = ['font', 'style', 'metadata', 'script', 'title', 'desc'] |
953 | - for elem in defElem.childNodes: |
954 | - # only look at it if an element and not referenced anywhere else |
955 | - if elem.nodeType == 1 and (elem.getAttribute('id') == '' or \ |
956 | - (not elem.getAttribute('id') in referencedIDs)): |
957 | - |
958 | - # we only inspect the children of a group in a defs if the group |
959 | - # is not referenced anywhere else |
960 | - if elem.nodeName == 'g' and elem.namespaceURI == NS['SVG']: |
961 | - elemsToRemove = removeUnusedDefs(doc, elem, elemsToRemove) |
962 | - # we only remove if it is not one of our tags we always keep (see above) |
963 | - elif not elem.nodeName in keepTags: |
964 | - elemsToRemove.append(elem) |
965 | - return elemsToRemove |
966 | - |
967 | -def removeUnreferencedElements(doc): |
968 | - """ |
969 | - Removes all unreferenced elements except for <svg>, <font>, <metadata>, <title>, and <desc>. |
970 | - Also vacuums the defs of any non-referenced renderable elements. |
971 | - |
972 | - Returns the number of unreferenced elements removed from the document. |
973 | - """ |
974 | - global numElemsRemoved |
975 | - num = 0 |
976 | - |
977 | - # Remove certain unreferenced elements outside of defs |
978 | - removeTags = ['linearGradient', 'radialGradient', 'pattern'] |
979 | - identifiedElements = findElementsWithId(doc.documentElement) |
980 | - referencedIDs = findReferencedElements(doc.documentElement) |
981 | - |
982 | - for id in identifiedElements: |
983 | - if not id in referencedIDs: |
984 | - goner = identifiedElements[id] |
985 | - if goner != None and goner.parentNode != None and goner.nodeName in removeTags: |
986 | - goner.parentNode.removeChild(goner) |
987 | - num += 1 |
988 | - numElemsRemoved += 1 |
989 | - |
990 | - # Remove most unreferenced elements inside defs |
991 | - defs = doc.documentElement.getElementsByTagName('defs') |
992 | - for aDef in defs: |
993 | - elemsToRemove = removeUnusedDefs(doc, aDef) |
994 | - for elem in elemsToRemove: |
995 | - elem.parentNode.removeChild(elem) |
996 | - numElemsRemoved += 1 |
997 | - num += 1 |
998 | - return num |
999 | - |
1000 | -def shortenIDs(doc, unprotectedElements=None): |
1001 | - """ |
1002 | - Shortens ID names used in the document. ID names referenced the most often are assigned the |
1003 | - shortest ID names. |
1004 | - If the list unprotectedElements is provided, only IDs from this list will be shortened. |
1005 | - |
1006 | - Returns the number of bytes saved by shortening ID names in the document. |
1007 | - """ |
1008 | - num = 0 |
1009 | - |
1010 | - identifiedElements = findElementsWithId(doc.documentElement) |
1011 | - if unprotectedElements is None: |
1012 | - unprotectedElements = identifiedElements |
1013 | - referencedIDs = findReferencedElements(doc.documentElement) |
1014 | - |
1015 | - # Make idList (list of idnames) sorted by reference count |
1016 | - # descending, so the highest reference count is first. |
1017 | - # First check that there's actually a defining element for the current ID name. |
1018 | - # (Cyn: I've seen documents with #id references but no element with that ID!) |
1019 | - idList = [(referencedIDs[rid][0], rid) for rid in referencedIDs |
1020 | - if rid in unprotectedElements] |
1021 | - idList.sort(reverse=True) |
1022 | - idList = [rid for count, rid in idList] |
1023 | - |
1024 | - curIdNum = 1 |
1025 | - |
1026 | - for rid in idList: |
1027 | - curId = intToID(curIdNum) |
1028 | - # First make sure that *this* element isn't already using |
1029 | - # the ID name we want to give it. |
1030 | - if curId != rid: |
1031 | - # Then, skip ahead if the new ID is already in identifiedElement. |
1032 | - while curId in identifiedElements: |
1033 | - curIdNum += 1 |
1034 | - curId = intToID(curIdNum) |
1035 | - # Then go rename it. |
1036 | - num += renameID(doc, rid, curId, identifiedElements, referencedIDs) |
1037 | - curIdNum += 1 |
1038 | - |
1039 | - return num |
1040 | - |
1041 | -def intToID(idnum): |
1042 | - """ |
1043 | - Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z, |
1044 | - then from aa to az, ba to bz, etc., until zz. |
1045 | - """ |
1046 | - rid = '' |
1047 | - |
1048 | - while idnum > 0: |
1049 | - idnum -= 1 |
1050 | - rid = chr((idnum % 26) + ord('a')) + rid |
1051 | - idnum = int(idnum / 26) |
1052 | - |
1053 | - return rid |
1054 | - |
1055 | -def renameID(doc, idFrom, idTo, identifiedElements, referencedIDs): |
1056 | - """ |
1057 | - Changes the ID name from idFrom to idTo, on the declaring element |
1058 | - as well as all references in the document doc. |
1059 | - |
1060 | - Updates identifiedElements and referencedIDs. |
1061 | - Does not handle the case where idTo is already the ID name |
1062 | - of another element in doc. |
1063 | - |
1064 | - Returns the number of bytes saved by this replacement. |
1065 | - """ |
1066 | - |
1067 | - num = 0 |
1068 | - |
1069 | - definingNode = identifiedElements[idFrom] |
1070 | - definingNode.setAttribute("id", idTo) |
1071 | - del identifiedElements[idFrom] |
1072 | - identifiedElements[idTo] = definingNode |
1073 | - |
1074 | - referringNodes = referencedIDs[idFrom] |
1075 | - |
1076 | - # Look for the idFrom ID name in each of the referencing elements, |
1077 | - # exactly like findReferencedElements would. |
1078 | - # Cyn: Duplicated processing! |
1079 | - |
1080 | - for node in referringNodes[1]: |
1081 | - # if this node is a style element, parse its text into CSS |
1082 | - if node.nodeName == 'style' and node.namespaceURI == NS['SVG']: |
1083 | - # node.firstChild will be either a CDATA or a Text node now |
1084 | - if node.firstChild != None: |
1085 | - # concatenate the value of all children, in case |
1086 | - # there's a CDATASection node surrounded by whitespace |
1087 | - # nodes |
1088 | - # (node.normalize() will NOT work here, it only acts on Text nodes) |
1089 | - oldValue = "".join([child.nodeValue for child in node.childNodes]) |
1090 | - # not going to reparse the whole thing |
1091 | - newValue = oldValue.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')') |
1092 | - newValue = newValue.replace("url(#'" + idFrom + "')", 'url(#' + idTo + ')') |
1093 | - newValue = newValue.replace('url(#"' + idFrom + '")', 'url(#' + idTo + ')') |
1094 | - # and now replace all the children with this new stylesheet. |
1095 | - # again, this is in case the stylesheet was a CDATASection |
1096 | - node.childNodes[:] = [node.ownerDocument.createTextNode(newValue)] |
1097 | - num += len(oldValue) - len(newValue) |
1098 | - |
1099 | - # if xlink:href is set to #idFrom, then change the id |
1100 | - href = node.getAttributeNS(NS['XLINK'],'href') |
1101 | - if href == '#' + idFrom: |
1102 | - node.setAttributeNS(NS['XLINK'],'href', '#' + idTo) |
1103 | - num += len(idFrom) - len(idTo) |
1104 | - |
1105 | - # if the style has url(#idFrom), then change the id |
1106 | - styles = node.getAttribute('style') |
1107 | - if styles != '': |
1108 | - newValue = styles.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')') |
1109 | - newValue = newValue.replace("url('#" + idFrom + "')", 'url(#' + idTo + ')') |
1110 | - newValue = newValue.replace('url("#' + idFrom + '")', 'url(#' + idTo + ')') |
1111 | - node.setAttribute('style', newValue) |
1112 | - num += len(styles) - len(newValue) |
1113 | - |
1114 | - # now try the fill, stroke, filter attributes |
1115 | - for attr in referencingProps: |
1116 | - oldValue = node.getAttribute(attr) |
1117 | - if oldValue != '': |
1118 | - newValue = oldValue.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')') |
1119 | - newValue = newValue.replace("url('#" + idFrom + "')", 'url(#' + idTo + ')') |
1120 | - newValue = newValue.replace('url("#' + idFrom + '")', 'url(#' + idTo + ')') |
1121 | - node.setAttribute(attr, newValue) |
1122 | - num += len(oldValue) - len(newValue) |
1123 | - |
1124 | - del referencedIDs[idFrom] |
1125 | - referencedIDs[idTo] = referringNodes |
1126 | - |
1127 | - return num |
1128 | - |
1129 | -def unprotected_ids(doc, options): |
1130 | - u"""Returns a list of unprotected IDs within the document doc.""" |
1131 | - identifiedElements = findElementsWithId(doc.documentElement) |
1132 | - if not (options.protect_ids_noninkscape or |
1133 | - options.protect_ids_list or |
1134 | - options.protect_ids_prefix): |
1135 | - return identifiedElements |
1136 | - if options.protect_ids_list: |
1137 | - protect_ids_list = options.protect_ids_list.split(",") |
1138 | - if options.protect_ids_prefix: |
1139 | - protect_ids_prefixes = options.protect_ids_prefix.split(",") |
1140 | - for id in identifiedElements.keys(): |
1141 | - protected = False |
1142 | - if options.protect_ids_noninkscape and not id[-1].isdigit(): |
1143 | - protected = True |
1144 | - if options.protect_ids_list and id in protect_ids_list: |
1145 | - protected = True |
1146 | - if options.protect_ids_prefix: |
1147 | - for prefix in protect_ids_prefixes: |
1148 | - if id.startswith(prefix): |
1149 | - protected = True |
1150 | - if protected: |
1151 | - del identifiedElements[id] |
1152 | - return identifiedElements |
1153 | - |
1154 | -def removeUnreferencedIDs(referencedIDs, identifiedElements): |
1155 | - """ |
1156 | - Removes the unreferenced ID attributes. |
1157 | - |
1158 | - Returns the number of ID attributes removed |
1159 | - """ |
1160 | - global numIDsRemoved |
1161 | - keepTags = ['font'] |
1162 | - num = 0; |
1163 | - for id in identifiedElements.keys(): |
1164 | - node = identifiedElements[id] |
1165 | - if referencedIDs.has_key(id) == False and not node.nodeName in keepTags: |
1166 | - node.removeAttribute('id') |
1167 | - numIDsRemoved += 1 |
1168 | - num += 1 |
1169 | - return num |
1170 | - |
1171 | -def removeNamespacedAttributes(node, namespaces): |
1172 | - global numAttrsRemoved |
1173 | - num = 0 |
1174 | - if node.nodeType == 1 : |
1175 | - # remove all namespace'd attributes from this element |
1176 | - attrList = node.attributes |
1177 | - attrsToRemove = [] |
1178 | - for attrNum in xrange(attrList.length): |
1179 | - attr = attrList.item(attrNum) |
1180 | - if attr != None and attr.namespaceURI in namespaces: |
1181 | - attrsToRemove.append(attr.nodeName) |
1182 | - for attrName in attrsToRemove : |
1183 | - num += 1 |
1184 | - numAttrsRemoved += 1 |
1185 | - node.removeAttribute(attrName) |
1186 | - |
1187 | - # now recurse for children |
1188 | - for child in node.childNodes: |
1189 | - num += removeNamespacedAttributes(child, namespaces) |
1190 | - return num |
1191 | - |
1192 | -def removeNamespacedElements(node, namespaces): |
1193 | - global numElemsRemoved |
1194 | - num = 0 |
1195 | - if node.nodeType == 1 : |
1196 | - # remove all namespace'd child nodes from this element |
1197 | - childList = node.childNodes |
1198 | - childrenToRemove = [] |
1199 | - for child in childList: |
1200 | - if child != None and child.namespaceURI in namespaces: |
1201 | - childrenToRemove.append(child) |
1202 | - for child in childrenToRemove : |
1203 | - num += 1 |
1204 | - numElemsRemoved += 1 |
1205 | - node.removeChild(child) |
1206 | - |
1207 | - # now recurse for children |
1208 | - for child in node.childNodes: |
1209 | - num += removeNamespacedElements(child, namespaces) |
1210 | - return num |
1211 | - |
1212 | -def removeMetadataElements(doc): |
1213 | - global numElemsRemoved |
1214 | - num = 0 |
1215 | - # clone the list, as the tag list is live from the DOM |
1216 | - elementsToRemove = [element for element in doc.documentElement.getElementsByTagName('metadata')] |
1217 | - |
1218 | - for element in elementsToRemove: |
1219 | - element.parentNode.removeChild(element) |
1220 | - num += 1 |
1221 | - numElemsRemoved += 1 |
1222 | - |
1223 | - return num |
1224 | - |
1225 | -def removeNestedGroups(node): |
1226 | - """ |
1227 | - This walks further and further down the tree, removing groups |
1228 | - which do not have any attributes or a title/desc child and |
1229 | - promoting their children up one level |
1230 | - """ |
1231 | - global numElemsRemoved |
1232 | - num = 0 |
1233 | - |
1234 | - groupsToRemove = [] |
1235 | - # Only consider <g> elements for promotion if this element isn't a <switch>. |
1236 | - # (partial fix for bug 594930, required by the SVG spec however) |
1237 | - if not (node.nodeType == 1 and node.nodeName == 'switch'): |
1238 | - for child in node.childNodes: |
1239 | - if child.nodeName == 'g' and child.namespaceURI == NS['SVG'] and len(child.attributes) == 0: |
1240 | - # only collapse group if it does not have a title or desc as a direct descendant, |
1241 | - for grandchild in child.childNodes: |
1242 | - if grandchild.nodeType == 1 and grandchild.namespaceURI == NS['SVG'] and \ |
1243 | - grandchild.nodeName in ['title','desc']: |
1244 | - break |
1245 | - else: |
1246 | - groupsToRemove.append(child) |
1247 | - |
1248 | - for g in groupsToRemove: |
1249 | - while g.childNodes.length > 0: |
1250 | - g.parentNode.insertBefore(g.firstChild, g) |
1251 | - g.parentNode.removeChild(g) |
1252 | - numElemsRemoved += 1 |
1253 | - num += 1 |
1254 | - |
1255 | - # now recurse for children |
1256 | - for child in node.childNodes: |
1257 | - if child.nodeType == 1: |
1258 | - num += removeNestedGroups(child) |
1259 | - return num |
1260 | - |
1261 | -def moveCommonAttributesToParentGroup(elem, referencedElements): |
1262 | - """ |
1263 | - This recursively calls this function on all children of the passed in element |
1264 | - and then iterates over all child elements and removes common inheritable attributes |
1265 | - from the children and places them in the parent group. But only if the parent contains |
1266 | - nothing but element children and whitespace. The attributes are only removed from the |
1267 | - children if the children are not referenced by other elements in the document. |
1268 | - """ |
1269 | - num = 0 |
1270 | - |
1271 | - childElements = [] |
1272 | - # recurse first into the children (depth-first) |
1273 | - for child in elem.childNodes: |
1274 | - if child.nodeType == 1: |
1275 | - # only add and recurse if the child is not referenced elsewhere |
1276 | - if not child.getAttribute('id') in referencedElements: |
1277 | - childElements.append(child) |
1278 | - num += moveCommonAttributesToParentGroup(child, referencedElements) |
1279 | - # else if the parent has non-whitespace text children, do not |
1280 | - # try to move common attributes |
1281 | - elif child.nodeType == 3 and child.nodeValue.strip(): |
1282 | - return num |
1283 | - |
1284 | - # only process the children if there are more than one element |
1285 | - if len(childElements) <= 1: return num |
1286 | - |
1287 | - commonAttrs = {} |
1288 | - # add all inheritable properties of the first child element |
1289 | - # FIXME: Note there is a chance that the first child is a set/animate in which case |
1290 | - # its fill attribute is not what we want to look at, we should look for the first |
1291 | - # non-animate/set element |
1292 | - attrList = childElements[0].attributes |
1293 | - for num in xrange(attrList.length): |
1294 | - attr = attrList.item(num) |
1295 | - # this is most of the inheritable properties from http://www.w3.org/TR/SVG11/propidx.html |
1296 | - # and http://www.w3.org/TR/SVGTiny12/attributeTable.html |
1297 | - if attr.nodeName in ['clip-rule', |
1298 | - 'display-align', |
1299 | - 'fill', 'fill-opacity', 'fill-rule', |
1300 | - 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', |
1301 | - 'font-style', 'font-variant', 'font-weight', |
1302 | - 'letter-spacing', |
1303 | - 'pointer-events', 'shape-rendering', |
1304 | - 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', |
1305 | - 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', |
1306 | - 'text-anchor', 'text-decoration', 'text-rendering', 'visibility', |
1307 | - 'word-spacing', 'writing-mode']: |
1308 | - # we just add all the attributes from the first child |
1309 | - commonAttrs[attr.nodeName] = attr.nodeValue |
1310 | - |
1311 | - # for each subsequent child element |
1312 | - for childNum in xrange(len(childElements)): |
1313 | - # skip first child |
1314 | - if childNum == 0: |
1315 | - continue |
1316 | - |
1317 | - child = childElements[childNum] |
1318 | - # if we are on an animateXXX/set element, ignore it (due to the 'fill' attribute) |
1319 | - if child.localName in ['set', 'animate', 'animateColor', 'animateTransform', 'animateMotion']: |
1320 | - continue |
1321 | - |
1322 | - distinctAttrs = [] |
1323 | - # loop through all current 'common' attributes |
1324 | - for name in commonAttrs.keys(): |
1325 | - # if this child doesn't match that attribute, schedule it for removal |
1326 | - if child.getAttribute(name) != commonAttrs[name]: |
1327 | - distinctAttrs.append(name) |
1328 | - # remove those attributes which are not common |
1329 | - for name in distinctAttrs: |
1330 | - del commonAttrs[name] |
1331 | - |
1332 | - # commonAttrs now has all the inheritable attributes which are common among all child elements |
1333 | - for name in commonAttrs.keys(): |
1334 | - for child in childElements: |
1335 | - child.removeAttribute(name) |
1336 | - elem.setAttribute(name, commonAttrs[name]) |
1337 | - |
1338 | - # update our statistic (we remove N*M attributes and add back in M attributes) |
1339 | - num += (len(childElements)-1) * len(commonAttrs) |
1340 | - return num |
1341 | - |
1342 | -def createGroupsForCommonAttributes(elem): |
1343 | - """ |
1344 | - Creates <g> elements to contain runs of 3 or more |
1345 | - consecutive child elements having at least one common attribute. |
1346 | - |
1347 | - Common attributes are not promoted to the <g> by this function. |
1348 | - This is handled by moveCommonAttributesToParentGroup. |
1349 | - |
1350 | - If all children have a common attribute, an extra <g> is not created. |
1351 | - |
1352 | - This function acts recursively on the given element. |
1353 | - """ |
1354 | - num = 0 |
1355 | - global numElemsRemoved |
1356 | - |
1357 | - # TODO perhaps all of the Presentation attributes in http://www.w3.org/TR/SVG/struct.html#GElement |
1358 | - # could be added here |
1359 | - # Cyn: These attributes are the same as in moveAttributesToParentGroup, and must always be |
1360 | - for curAttr in ['clip-rule', |
1361 | - 'display-align', |
1362 | - 'fill', 'fill-opacity', 'fill-rule', |
1363 | - 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', |
1364 | - 'font-style', 'font-variant', 'font-weight', |
1365 | - 'letter-spacing', |
1366 | - 'pointer-events', 'shape-rendering', |
1367 | - 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', |
1368 | - 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', |
1369 | - 'text-anchor', 'text-decoration', 'text-rendering', 'visibility', |
1370 | - 'word-spacing', 'writing-mode']: |
1371 | - # Iterate through the children in reverse order, so item(i) for |
1372 | - # items we have yet to visit still returns the correct nodes. |
1373 | - curChild = elem.childNodes.length - 1 |
1374 | - while curChild >= 0: |
1375 | - childNode = elem.childNodes.item(curChild) |
1376 | - |
1377 | - if childNode.nodeType == 1 and childNode.getAttribute(curAttr) != '': |
1378 | - # We're in a possible run! Track the value and run length. |
1379 | - value = childNode.getAttribute(curAttr) |
1380 | - runStart, runEnd = curChild, curChild |
1381 | - # Run elements includes only element tags, no whitespace/comments/etc. |
1382 | - # Later, we calculate a run length which includes these. |
1383 | - runElements = 1 |
1384 | - |
1385 | - # Backtrack to get all the nodes having the same |
1386 | - # attribute value, preserving any nodes in-between. |
1387 | - while runStart > 0: |
1388 | - nextNode = elem.childNodes.item(runStart - 1) |
1389 | - if nextNode.nodeType == 1: |
1390 | - if nextNode.getAttribute(curAttr) != value: break |
1391 | - else: |
1392 | - runElements += 1 |
1393 | - runStart -= 1 |
1394 | - else: runStart -= 1 |
1395 | - |
1396 | - if runElements >= 3: |
1397 | - # Include whitespace/comment/etc. nodes in the run. |
1398 | - while runEnd < elem.childNodes.length - 1: |
1399 | - if elem.childNodes.item(runEnd + 1).nodeType == 1: break |
1400 | - else: runEnd += 1 |
1401 | - |
1402 | - runLength = runEnd - runStart + 1 |
1403 | - if runLength == elem.childNodes.length: # Every child has this |
1404 | - # If the current parent is a <g> already, |
1405 | - if elem.nodeName == 'g' and elem.namespaceURI == NS['SVG']: |
1406 | - # do not act altogether on this attribute; all the |
1407 | - # children have it in common. |
1408 | - # Let moveCommonAttributesToParentGroup do it. |
1409 | - curChild = -1 |
1410 | - continue |
1411 | - # otherwise, it might be an <svg> element, and |
1412 | - # even if all children have the same attribute value, |
1413 | - # it's going to be worth making the <g> since |
1414 | - # <svg> doesn't support attributes like 'stroke'. |
1415 | - # Fall through. |
1416 | - |
1417 | - # Create a <g> element from scratch. |
1418 | - # We need the Document for this. |
1419 | - document = elem.ownerDocument |
1420 | - group = document.createElementNS(NS['SVG'], 'g') |
1421 | - # Move the run of elements to the group. |
1422 | - # a) ADD the nodes to the new group. |
1423 | - group.childNodes[:] = elem.childNodes[runStart:runEnd + 1] |
1424 | - for child in group.childNodes: |
1425 | - child.parentNode = group |
1426 | - # b) REMOVE the nodes from the element. |
1427 | - elem.childNodes[runStart:runEnd + 1] = [] |
1428 | - # Include the group in elem's children. |
1429 | - elem.childNodes.insert(runStart, group) |
1430 | - group.parentNode = elem |
1431 | - num += 1 |
1432 | - curChild = runStart - 1 |
1433 | - numElemsRemoved -= 1 |
1434 | - else: |
1435 | - curChild -= 1 |
1436 | - else: |
1437 | - curChild -= 1 |
1438 | - |
1439 | - # each child gets the same treatment, recursively |
1440 | - for childNode in elem.childNodes: |
1441 | - if childNode.nodeType == 1: |
1442 | - num += createGroupsForCommonAttributes(childNode) |
1443 | - |
1444 | - return num |
1445 | - |
1446 | -def removeUnusedAttributesOnParent(elem): |
1447 | - """ |
1448 | - This recursively calls this function on all children of the element passed in, |
1449 | - then removes any unused attributes on this elem if none of the children inherit it |
1450 | - """ |
1451 | - num = 0 |
1452 | - |
1453 | - childElements = [] |
1454 | - # recurse first into the children (depth-first) |
1455 | - for child in elem.childNodes: |
1456 | - if child.nodeType == 1: |
1457 | - childElements.append(child) |
1458 | - num += removeUnusedAttributesOnParent(child) |
1459 | - |
1460 | - # only process the children if there are more than one element |
1461 | - if len(childElements) <= 1: return num |
1462 | - |
1463 | - # get all attribute values on this parent |
1464 | - attrList = elem.attributes |
1465 | - unusedAttrs = {} |
1466 | - for num in xrange(attrList.length): |
1467 | - attr = attrList.item(num) |
1468 | - if attr.nodeName in ['clip-rule', |
1469 | - 'display-align', |
1470 | - 'fill', 'fill-opacity', 'fill-rule', |
1471 | - 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', |
1472 | - 'font-style', 'font-variant', 'font-weight', |
1473 | - 'letter-spacing', |
1474 | - 'pointer-events', 'shape-rendering', |
1475 | - 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', |
1476 | - 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', |
1477 | - 'text-anchor', 'text-decoration', 'text-rendering', 'visibility', |
1478 | - 'word-spacing', 'writing-mode']: |
1479 | - unusedAttrs[attr.nodeName] = attr.nodeValue |
1480 | - |
1481 | - # for each child, if at least one child inherits the parent's attribute, then remove |
1482 | - for childNum in xrange(len(childElements)): |
1483 | - child = childElements[childNum] |
1484 | - inheritedAttrs = [] |
1485 | - for name in unusedAttrs.keys(): |
1486 | - val = child.getAttribute(name) |
1487 | - if val == '' or val == None or val == 'inherit': |
1488 | - inheritedAttrs.append(name) |
1489 | - for a in inheritedAttrs: |
1490 | - del unusedAttrs[a] |
1491 | - |
1492 | - # unusedAttrs now has all the parent attributes that are unused |
1493 | - for name in unusedAttrs.keys(): |
1494 | - elem.removeAttribute(name) |
1495 | - num += 1 |
1496 | - |
1497 | - return num |
1498 | - |
1499 | -def removeDuplicateGradientStops(doc): |
1500 | - global numElemsRemoved |
1501 | - num = 0 |
1502 | - |
1503 | - for gradType in ['linearGradient', 'radialGradient']: |
1504 | - for grad in doc.getElementsByTagName(gradType): |
1505 | - stops = {} |
1506 | - stopsToRemove = [] |
1507 | - for stop in grad.getElementsByTagName('stop'): |
1508 | - # convert percentages into a floating point number |
1509 | - offsetU = SVGLength(stop.getAttribute('offset')) |
1510 | - if offsetU.units == Unit.PCT: |
1511 | - offset = offsetU.value / 100.0 |
1512 | - elif offsetU.units == Unit.NONE: |
1513 | - offset = offsetU.value |
1514 | - else: |
1515 | - offset = 0 |
1516 | - # set the stop offset value to the integer or floating point equivalent |
1517 | - if int(offset) == offset: stop.setAttribute('offset', str(int(offset))) |
1518 | - else: stop.setAttribute('offset', str(offset)) |
1519 | - |
1520 | - color = stop.getAttribute('stop-color') |
1521 | - opacity = stop.getAttribute('stop-opacity') |
1522 | - style = stop.getAttribute('style') |
1523 | - if stops.has_key(offset) : |
1524 | - oldStop = stops[offset] |
1525 | - if oldStop[0] == color and oldStop[1] == opacity and oldStop[2] == style: |
1526 | - stopsToRemove.append(stop) |
1527 | - stops[offset] = [color, opacity, style] |
1528 | - |
1529 | - for stop in stopsToRemove: |
1530 | - stop.parentNode.removeChild(stop) |
1531 | - num += 1 |
1532 | - numElemsRemoved += 1 |
1533 | - |
1534 | - # linear gradients |
1535 | - return num |
1536 | - |
1537 | -def collapseSinglyReferencedGradients(doc): |
1538 | - global numElemsRemoved |
1539 | - num = 0 |
1540 | - |
1541 | - identifiedElements = findElementsWithId(doc.documentElement) |
1542 | - |
1543 | - # make sure to reset the ref'ed ids for when we are running this in testscour |
1544 | - for rid,nodeCount in findReferencedElements(doc.documentElement).iteritems(): |
1545 | - count = nodeCount[0] |
1546 | - nodes = nodeCount[1] |
1547 | - # Make sure that there's actually a defining element for the current ID name. |
1548 | - # (Cyn: I've seen documents with #id references but no element with that ID!) |
1549 | - if count == 1 and rid in identifiedElements: |
1550 | - elem = identifiedElements[rid] |
1551 | - if elem != None and elem.nodeType == 1 and elem.nodeName in ['linearGradient', 'radialGradient'] \ |
1552 | - and elem.namespaceURI == NS['SVG']: |
1553 | - # found a gradient that is referenced by only 1 other element |
1554 | - refElem = nodes[0] |
1555 | - if refElem.nodeType == 1 and refElem.nodeName in ['linearGradient', 'radialGradient'] \ |
1556 | - and refElem.namespaceURI == NS['SVG']: |
1557 | - # elem is a gradient referenced by only one other gradient (refElem) |
1558 | - |
1559 | - # add the stops to the referencing gradient (this removes them from elem) |
1560 | - if len(refElem.getElementsByTagName('stop')) == 0: |
1561 | - stopsToAdd = elem.getElementsByTagName('stop') |
1562 | - for stop in stopsToAdd: |
1563 | - refElem.appendChild(stop) |
1564 | - |
1565 | - # adopt the gradientUnits, spreadMethod, gradientTransform attributes if |
1566 | - # they are unspecified on refElem |
1567 | - for attr in ['gradientUnits','spreadMethod','gradientTransform']: |
1568 | - if refElem.getAttribute(attr) == '' and not elem.getAttribute(attr) == '': |
1569 | - refElem.setAttributeNS(None, attr, elem.getAttribute(attr)) |
1570 | - |
1571 | - # if both are radialGradients, adopt elem's fx,fy,cx,cy,r attributes if |
1572 | - # they are unspecified on refElem |
1573 | - if elem.nodeName == 'radialGradient' and refElem.nodeName == 'radialGradient': |
1574 | - for attr in ['fx','fy','cx','cy','r']: |
1575 | - if refElem.getAttribute(attr) == '' and not elem.getAttribute(attr) == '': |
1576 | - refElem.setAttributeNS(None, attr, elem.getAttribute(attr)) |
1577 | - |
1578 | - # if both are linearGradients, adopt elem's x1,y1,x2,y2 attributes if |
1579 | - # they are unspecified on refElem |
1580 | - if elem.nodeName == 'linearGradient' and refElem.nodeName == 'linearGradient': |
1581 | - for attr in ['x1','y1','x2','y2']: |
1582 | - if refElem.getAttribute(attr) == '' and not elem.getAttribute(attr) == '': |
1583 | - refElem.setAttributeNS(None, attr, elem.getAttribute(attr)) |
1584 | - |
1585 | - # now remove the xlink:href from refElem |
1586 | - refElem.removeAttributeNS(NS['XLINK'], 'href') |
1587 | - |
1588 | - # now delete elem |
1589 | - elem.parentNode.removeChild(elem) |
1590 | - numElemsRemoved += 1 |
1591 | - num += 1 |
1592 | - return num |
1593 | - |
1594 | -def removeDuplicateGradients(doc): |
1595 | - global numElemsRemoved |
1596 | - num = 0 |
1597 | - |
1598 | - gradientsToRemove = {} |
1599 | - duplicateToMaster = {} |
1600 | - |
1601 | - for gradType in ['linearGradient', 'radialGradient']: |
1602 | - grads = doc.getElementsByTagName(gradType) |
1603 | - for grad in grads: |
1604 | - # TODO: should slice grads from 'grad' here to optimize |
1605 | - for ograd in grads: |
1606 | - # do not compare gradient to itself |
1607 | - if grad == ograd: continue |
1608 | - |
1609 | - # compare grad to ograd (all properties, then all stops) |
1610 | - # if attributes do not match, go to next gradient |
1611 | - someGradAttrsDoNotMatch = False |
1612 | - for attr in ['gradientUnits','spreadMethod','gradientTransform','x1','y1','x2','y2','cx','cy','fx','fy','r']: |
1613 | - if grad.getAttribute(attr) != ograd.getAttribute(attr): |
1614 | - someGradAttrsDoNotMatch = True |
1615 | - break; |
1616 | - |
1617 | - if someGradAttrsDoNotMatch: continue |
1618 | - |
1619 | - # compare xlink:href values too |
1620 | - if grad.getAttributeNS(NS['XLINK'], 'href') != ograd.getAttributeNS(NS['XLINK'], 'href'): |
1621 | - continue |
1622 | - |
1623 | - # all gradient properties match, now time to compare stops |
1624 | - stops = grad.getElementsByTagName('stop') |
1625 | - ostops = ograd.getElementsByTagName('stop') |
1626 | - |
1627 | - if stops.length != ostops.length: continue |
1628 | - |
1629 | - # now compare stops |
1630 | - stopsNotEqual = False |
1631 | - for i in xrange(stops.length): |
1632 | - if stopsNotEqual: break |
1633 | - stop = stops.item(i) |
1634 | - ostop = ostops.item(i) |
1635 | - for attr in ['offset', 'stop-color', 'stop-opacity', 'style']: |
1636 | - if stop.getAttribute(attr) != ostop.getAttribute(attr): |
1637 | - stopsNotEqual = True |
1638 | - break |
1639 | - if stopsNotEqual: continue |
1640 | - |
1641 | - # ograd is a duplicate of grad, we schedule it to be removed UNLESS |
1642 | - # ograd is ALREADY considered a 'master' element |
1643 | - if not gradientsToRemove.has_key(ograd): |
1644 | - if not duplicateToMaster.has_key(ograd): |
1645 | - if not gradientsToRemove.has_key(grad): |
1646 | - gradientsToRemove[grad] = [] |
1647 | - gradientsToRemove[grad].append( ograd ) |
1648 | - duplicateToMaster[ograd] = grad |
1649 | - |
1650 | - # get a collection of all elements that are referenced and their referencing elements |
1651 | - referencedIDs = findReferencedElements(doc.documentElement) |
1652 | - for masterGrad in gradientsToRemove.keys(): |
1653 | - master_id = masterGrad.getAttribute('id') |
1654 | -# print 'master='+master_id |
1655 | - for dupGrad in gradientsToRemove[masterGrad]: |
1656 | - # if the duplicate gradient no longer has a parent that means it was |
1657 | - # already re-mapped to another master gradient |
1658 | - if not dupGrad.parentNode: continue |
1659 | - dup_id = dupGrad.getAttribute('id') |
1660 | -# print 'dup='+dup_id |
1661 | -# print referencedIDs[dup_id] |
1662 | - # for each element that referenced the gradient we are going to remove |
1663 | - for elem in referencedIDs[dup_id][1]: |
1664 | - # find out which attribute referenced the duplicate gradient |
1665 | - for attr in ['fill', 'stroke']: |
1666 | - v = elem.getAttribute(attr) |
1667 | - if v == 'url(#'+dup_id+')' or v == 'url("#'+dup_id+'")' or v == "url('#"+dup_id+"')": |
1668 | - elem.setAttribute(attr, 'url(#'+master_id+')') |
1669 | - if elem.getAttributeNS(NS['XLINK'], 'href') == '#'+dup_id: |
1670 | - elem.setAttributeNS(NS['XLINK'], 'href', '#'+master_id) |
1671 | - styles = _getStyle(elem) |
1672 | - for style in styles: |
1673 | - v = styles[style] |
1674 | - if v == 'url(#'+dup_id+')' or v == 'url("#'+dup_id+'")' or v == "url('#"+dup_id+"')": |
1675 | - styles[style] = 'url(#'+master_id+')' |
1676 | - _setStyle(elem, styles) |
1677 | - |
1678 | - # now that all referencing elements have been re-mapped to the master |
1679 | - # it is safe to remove this gradient from the document |
1680 | - dupGrad.parentNode.removeChild(dupGrad) |
1681 | - numElemsRemoved += 1 |
1682 | - num += 1 |
1683 | - return num |
1684 | - |
1685 | -def _getStyle(node): |
1686 | - u"""Returns the style attribute of a node as a dictionary.""" |
1687 | - if node.nodeType == 1 and len(node.getAttribute('style')) > 0 : |
1688 | - styleMap = { } |
1689 | - rawStyles = node.getAttribute('style').split(';') |
1690 | - for style in rawStyles: |
1691 | - propval = style.split(':') |
1692 | - if len(propval) == 2 : |
1693 | - styleMap[propval[0].strip()] = propval[1].strip() |
1694 | - return styleMap |
1695 | - else: |
1696 | - return {} |
1697 | - |
1698 | -def _setStyle(node, styleMap): |
1699 | - u"""Sets the style attribute of a node to the dictionary ``styleMap``.""" |
1700 | - fixedStyle = ';'.join([prop + ':' + styleMap[prop] for prop in styleMap.keys()]) |
1701 | - if fixedStyle != '' : |
1702 | - node.setAttribute('style', fixedStyle) |
1703 | - elif node.getAttribute('style'): |
1704 | - node.removeAttribute('style') |
1705 | - return node |
1706 | - |
1707 | -def repairStyle(node, options): |
1708 | - num = 0 |
1709 | - styleMap = _getStyle(node) |
1710 | - if styleMap: |
1711 | - |
1712 | - # I've seen this enough to know that I need to correct it: |
1713 | - # fill: url(#linearGradient4918) rgb(0, 0, 0); |
1714 | - for prop in ['fill', 'stroke'] : |
1715 | - if styleMap.has_key(prop) : |
1716 | - chunk = styleMap[prop].split(') ') |
1717 | - 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)' : |
1718 | - styleMap[prop] = chunk[0] + ')' |
1719 | - num += 1 |
1720 | - |
1721 | - # Here is where we can weed out unnecessary styles like: |
1722 | - # opacity:1 |
1723 | - if styleMap.has_key('opacity') : |
1724 | - opacity = float(styleMap['opacity']) |
1725 | - # if opacity='0' then all fill and stroke properties are useless, remove them |
1726 | - if opacity == 0.0 : |
1727 | - for uselessStyle in ['fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-linejoin', |
1728 | - 'stroke-opacity', 'stroke-miterlimit', 'stroke-linecap', 'stroke-dasharray', |
1729 | - 'stroke-dashoffset', 'stroke-opacity'] : |
1730 | - if styleMap.has_key(uselessStyle): |
1731 | - del styleMap[uselessStyle] |
1732 | - num += 1 |
1733 | - |
1734 | - # if stroke:none, then remove all stroke-related properties (stroke-width, etc) |
1735 | - # TODO: should also detect if the computed value of this element is stroke="none" |
1736 | - if styleMap.has_key('stroke') and styleMap['stroke'] == 'none' : |
1737 | - for strokestyle in [ 'stroke-width', 'stroke-linejoin', 'stroke-miterlimit', |
1738 | - 'stroke-linecap', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-opacity'] : |
1739 | - if styleMap.has_key(strokestyle) : |
1740 | - del styleMap[strokestyle] |
1741 | - num += 1 |
1742 | - # TODO: This is actually a problem if a parent element has a specified stroke |
1743 | - # we need to properly calculate computed values |
1744 | - del styleMap['stroke'] |
1745 | - |
1746 | - # if fill:none, then remove all fill-related properties (fill-rule, etc) |
1747 | - if styleMap.has_key('fill') and styleMap['fill'] == 'none' : |
1748 | - for fillstyle in [ 'fill-rule', 'fill-opacity' ] : |
1749 | - if styleMap.has_key(fillstyle) : |
1750 | - del styleMap[fillstyle] |
1751 | - num += 1 |
1752 | - |
1753 | - # fill-opacity: 0 |
1754 | - if styleMap.has_key('fill-opacity') : |
1755 | - fillOpacity = float(styleMap['fill-opacity']) |
1756 | - if fillOpacity == 0.0 : |
1757 | - for uselessFillStyle in [ 'fill', 'fill-rule' ] : |
1758 | - if styleMap.has_key(uselessFillStyle): |
1759 | - del styleMap[uselessFillStyle] |
1760 | - num += 1 |
1761 | - |
1762 | - # stroke-opacity: 0 |
1763 | - if styleMap.has_key('stroke-opacity') : |
1764 | - strokeOpacity = float(styleMap['stroke-opacity']) |
1765 | - if strokeOpacity == 0.0 : |
1766 | - for uselessStrokeStyle in [ 'stroke', 'stroke-width', 'stroke-linejoin', 'stroke-linecap', |
1767 | - 'stroke-dasharray', 'stroke-dashoffset' ] : |
1768 | - if styleMap.has_key(uselessStrokeStyle): |
1769 | - del styleMap[uselessStrokeStyle] |
1770 | - num += 1 |
1771 | - |
1772 | - # stroke-width: 0 |
1773 | - if styleMap.has_key('stroke-width') : |
1774 | - strokeWidth = SVGLength(styleMap['stroke-width']) |
1775 | - if strokeWidth.value == 0.0 : |
1776 | - for uselessStrokeStyle in [ 'stroke', 'stroke-linejoin', 'stroke-linecap', |
1777 | - 'stroke-dasharray', 'stroke-dashoffset', 'stroke-opacity' ] : |
1778 | - if styleMap.has_key(uselessStrokeStyle): |
1779 | - del styleMap[uselessStrokeStyle] |
1780 | - num += 1 |
1781 | - |
1782 | - # remove font properties for non-text elements |
1783 | - # I've actually observed this in real SVG content |
1784 | - if not mayContainTextNodes(node): |
1785 | - for fontstyle in [ 'font-family', 'font-size', 'font-stretch', 'font-size-adjust', |
1786 | - 'font-style', 'font-variant', 'font-weight', |
1787 | - 'letter-spacing', 'line-height', 'kerning', |
1788 | - 'text-align', 'text-anchor', 'text-decoration', |
1789 | - 'text-rendering', 'unicode-bidi', |
1790 | - 'word-spacing', 'writing-mode'] : |
1791 | - if styleMap.has_key(fontstyle) : |
1792 | - del styleMap[fontstyle] |
1793 | - num += 1 |
1794 | - |
1795 | - # remove inkscape-specific styles |
1796 | - # TODO: need to get a full list of these |
1797 | - for inkscapeStyle in ['-inkscape-font-specification']: |
1798 | - if styleMap.has_key(inkscapeStyle): |
1799 | - del styleMap[inkscapeStyle] |
1800 | - num += 1 |
1801 | - |
1802 | - if styleMap.has_key('overflow') : |
1803 | - # overflow specified on element other than svg, marker, pattern |
1804 | - if not node.nodeName in ['svg','marker','pattern']: |
1805 | - del styleMap['overflow'] |
1806 | - num += 1 |
1807 | - # it is a marker, pattern or svg |
1808 | - # as long as this node is not the document <svg>, then only |
1809 | - # remove overflow='hidden'. See |
1810 | - # http://www.w3.org/TR/2010/WD-SVG11-20100622/masking.html#OverflowProperty |
1811 | - elif node != node.ownerDocument.documentElement: |
1812 | - if styleMap['overflow'] == 'hidden': |
1813 | - del styleMap['overflow'] |
1814 | - num += 1 |
1815 | - # else if outer svg has a overflow="visible", we can remove it |
1816 | - elif styleMap['overflow'] == 'visible': |
1817 | - del styleMap['overflow'] |
1818 | - num += 1 |
1819 | - |
1820 | - # now if any of the properties match known SVG attributes we prefer attributes |
1821 | - # over style so emit them and remove them from the style map |
1822 | - if options.style_to_xml: |
1823 | - for propName in styleMap.keys() : |
1824 | - if propName in svgAttributes : |
1825 | - node.setAttribute(propName, styleMap[propName]) |
1826 | - del styleMap[propName] |
1827 | - |
1828 | - _setStyle(node, styleMap) |
1829 | - |
1830 | - # recurse for our child elements |
1831 | - for child in node.childNodes : |
1832 | - num += repairStyle(child,options) |
1833 | - |
1834 | - return num |
1835 | - |
1836 | -def mayContainTextNodes(node): |
1837 | - """ |
1838 | - Returns True if the passed-in node is probably a text element, or at least |
1839 | - one of its descendants is probably a text element. |
1840 | - |
1841 | - If False is returned, it is guaranteed that the passed-in node has no |
1842 | - business having text-based attributes. |
1843 | - |
1844 | - If True is returned, the passed-in node should not have its text-based |
1845 | - attributes removed. |
1846 | - """ |
1847 | - # Cached result of a prior call? |
1848 | - try: |
1849 | - return node.mayContainTextNodes |
1850 | - except AttributeError: |
1851 | - pass |
1852 | - |
1853 | - result = True # Default value |
1854 | - # Comment, text and CDATA nodes don't have attributes and aren't containers |
1855 | - if node.nodeType != 1: |
1856 | - result = False |
1857 | - # Non-SVG elements? Unknown elements! |
1858 | - elif node.namespaceURI != NS['SVG']: |
1859 | - result = True |
1860 | - # Blacklisted elements. Those are guaranteed not to be text elements. |
1861 | - elif node.nodeName in ['rect', 'circle', 'ellipse', 'line', 'polygon', |
1862 | - 'polyline', 'path', 'image', 'stop']: |
1863 | - result = False |
1864 | - # Group elements. If we're missing any here, the default of True is used. |
1865 | - elif node.nodeName in ['g', 'clipPath', 'marker', 'mask', 'pattern', |
1866 | - 'linearGradient', 'radialGradient', 'symbol']: |
1867 | - result = False |
1868 | - for child in node.childNodes: |
1869 | - if mayContainTextNodes(child): |
1870 | - result = True |
1871 | - # Everything else should be considered a future SVG-version text element |
1872 | - # at best, or an unknown element at worst. result will stay True. |
1873 | - |
1874 | - # Cache this result before returning it. |
1875 | - node.mayContainTextNodes = result |
1876 | - return result |
1877 | - |
1878 | -def taint(taintedSet, taintedAttribute): |
1879 | - u"""Adds an attribute to a set of attributes. |
1880 | - |
1881 | - Related attributes are also included.""" |
1882 | - taintedSet.add(taintedAttribute) |
1883 | - if taintedAttribute == 'marker': |
1884 | - taintedSet |= set(['marker-start', 'marker-mid', 'marker-end']) |
1885 | - if taintedAttribute in ['marker-start', 'marker-mid', 'marker-end']: |
1886 | - taintedSet.add('marker') |
1887 | - return taintedSet |
1888 | - |
1889 | -def removeDefaultAttributeValues(node, options, tainted=set()): |
1890 | - u"""'tainted' keeps a set of attributes defined in parent nodes. |
1891 | - |
1892 | - For such attributes, we don't delete attributes with default values.""" |
1893 | - num = 0 |
1894 | - if node.nodeType != 1: return 0 |
1895 | - |
1896 | - # gradientUnits: objectBoundingBox |
1897 | - if node.getAttribute('gradientUnits') == 'objectBoundingBox': |
1898 | - node.removeAttribute('gradientUnits') |
1899 | - num += 1 |
1900 | - |
1901 | - # spreadMethod: pad |
1902 | - if node.getAttribute('spreadMethod') == 'pad': |
1903 | - node.removeAttribute('spreadMethod') |
1904 | - num += 1 |
1905 | - |
1906 | - # x1: 0% |
1907 | - if node.getAttribute('x1') != '': |
1908 | - x1 = SVGLength(node.getAttribute('x1')) |
1909 | - if x1.value == 0: |
1910 | - node.removeAttribute('x1') |
1911 | - num += 1 |
1912 | - |
1913 | - # y1: 0% |
1914 | - if node.getAttribute('y1') != '': |
1915 | - y1 = SVGLength(node.getAttribute('y1')) |
1916 | - if y1.value == 0: |
1917 | - node.removeAttribute('y1') |
1918 | - num += 1 |
1919 | - |
1920 | - # x2: 100% |
1921 | - if node.getAttribute('x2') != '': |
1922 | - x2 = SVGLength(node.getAttribute('x2')) |
1923 | - if (x2.value == 100 and x2.units == Unit.PCT) or (x2.value == 1 and x2.units == Unit.NONE): |
1924 | - node.removeAttribute('x2') |
1925 | - num += 1 |
1926 | - |
1927 | - # y2: 0% |
1928 | - if node.getAttribute('y2') != '': |
1929 | - y2 = SVGLength(node.getAttribute('y2')) |
1930 | - if y2.value == 0: |
1931 | - node.removeAttribute('y2') |
1932 | - num += 1 |
1933 | - |
1934 | - # fx: equal to rx |
1935 | - if node.getAttribute('fx') != '': |
1936 | - if node.getAttribute('fx') == node.getAttribute('cx'): |
1937 | - node.removeAttribute('fx') |
1938 | - num += 1 |
1939 | - |
1940 | - # fy: equal to ry |
1941 | - if node.getAttribute('fy') != '': |
1942 | - if node.getAttribute('fy') == node.getAttribute('cy'): |
1943 | - node.removeAttribute('fy') |
1944 | - num += 1 |
1945 | - |
1946 | - # cx: 50% |
1947 | - if node.getAttribute('cx') != '': |
1948 | - cx = SVGLength(node.getAttribute('cx')) |
1949 | - if (cx.value == 50 and cx.units == Unit.PCT) or (cx.value == 0.5 and cx.units == Unit.NONE): |
1950 | - node.removeAttribute('cx') |
1951 | - num += 1 |
1952 | - |
1953 | - # cy: 50% |
1954 | - if node.getAttribute('cy') != '': |
1955 | - cy = SVGLength(node.getAttribute('cy')) |
1956 | - if (cy.value == 50 and cy.units == Unit.PCT) or (cy.value == 0.5 and cy.units == Unit.NONE): |
1957 | - node.removeAttribute('cy') |
1958 | - num += 1 |
1959 | - |
1960 | - # r: 50% |
1961 | - if node.getAttribute('r') != '': |
1962 | - r = SVGLength(node.getAttribute('r')) |
1963 | - if (r.value == 50 and r.units == Unit.PCT) or (r.value == 0.5 and r.units == Unit.NONE): |
1964 | - node.removeAttribute('r') |
1965 | - num += 1 |
1966 | - |
1967 | - # Summarily get rid of some more attributes |
1968 | - attributes = [node.attributes.item(i).nodeName |
1969 | - for i in range(node.attributes.length)] |
1970 | - for attribute in attributes: |
1971 | - if attribute not in tainted: |
1972 | - if attribute in default_attributes.keys(): |
1973 | - if node.getAttribute(attribute) == default_attributes[attribute]: |
1974 | - node.removeAttribute(attribute) |
1975 | - num += 1 |
1976 | - else: |
1977 | - tainted = taint(tainted, attribute) |
1978 | - # These attributes might also occur as styles |
1979 | - styles = _getStyle(node) |
1980 | - for attribute in styles.keys(): |
1981 | - if attribute not in tainted: |
1982 | - if attribute in default_attributes.keys(): |
1983 | - if styles[attribute] == default_attributes[attribute]: |
1984 | - del styles[attribute] |
1985 | - num += 1 |
1986 | - else: |
1987 | - tainted = taint(tainted, attribute) |
1988 | - _setStyle(node, styles) |
1989 | - |
1990 | - # recurse for our child elements |
1991 | - for child in node.childNodes : |
1992 | - num += removeDefaultAttributeValues(child, options, tainted.copy()) |
1993 | - |
1994 | - return num |
1995 | - |
1996 | -rgb = re.compile(r"\s*rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*") |
1997 | -rgbp = re.compile(r"\s*rgb\(\s*(\d*\.?\d+)%\s*,\s*(\d*\.?\d+)%\s*,\s*(\d*\.?\d+)%\s*\)\s*") |
1998 | -def convertColor(value): |
1999 | - """ |
2000 | - Converts the input color string and returns a #RRGGBB (or #RGB if possible) string |
2001 | - """ |
2002 | - s = value |
2003 | - |
2004 | - if s in colors.keys(): |
2005 | - s = colors[s] |
2006 | - |
2007 | - rgbpMatch = rgbp.match(s) |
2008 | - if rgbpMatch != None : |
2009 | - r = int(float(rgbpMatch.group(1)) * 255.0 / 100.0) |
2010 | - g = int(float(rgbpMatch.group(2)) * 255.0 / 100.0) |
2011 | - b = int(float(rgbpMatch.group(3)) * 255.0 / 100.0) |
2012 | - s = '#%02x%02x%02x' % (r, g, b) |
2013 | - else: |
2014 | - rgbMatch = rgb.match(s) |
2015 | - if rgbMatch != None : |
2016 | - r = int( rgbMatch.group(1) ) |
2017 | - g = int( rgbMatch.group(2) ) |
2018 | - b = int( rgbMatch.group(3) ) |
2019 | - s = '#%02x%02x%02x' % (r, g, b) |
2020 | - |
2021 | - if s[0] == '#': |
2022 | - s = s.lower() |
2023 | - if len(s)==7 and s[1]==s[2] and s[3]==s[4] and s[5]==s[6]: |
2024 | - s = '#'+s[1]+s[3]+s[5] |
2025 | - |
2026 | - return s |
2027 | - |
2028 | -def convertColors(element) : |
2029 | - """ |
2030 | - Recursively converts all color properties into #RRGGBB format if shorter |
2031 | - """ |
2032 | - numBytes = 0 |
2033 | - |
2034 | - if element.nodeType != 1: return 0 |
2035 | - |
2036 | - # set up list of color attributes for each element type |
2037 | - attrsToConvert = [] |
2038 | - if element.nodeName in ['rect', 'circle', 'ellipse', 'polygon', \ |
2039 | - 'line', 'polyline', 'path', 'g', 'a']: |
2040 | - attrsToConvert = ['fill', 'stroke'] |
2041 | - elif element.nodeName in ['stop']: |
2042 | - attrsToConvert = ['stop-color'] |
2043 | - elif element.nodeName in ['solidColor']: |
2044 | - attrsToConvert = ['solid-color'] |
2045 | - |
2046 | - # now convert all the color formats |
2047 | - styles = _getStyle(element) |
2048 | - for attr in attrsToConvert: |
2049 | - oldColorValue = element.getAttribute(attr) |
2050 | - if oldColorValue != '': |
2051 | - newColorValue = convertColor(oldColorValue) |
2052 | - oldBytes = len(oldColorValue) |
2053 | - newBytes = len(newColorValue) |
2054 | - if oldBytes > newBytes: |
2055 | - element.setAttribute(attr, newColorValue) |
2056 | - numBytes += (oldBytes - len(element.getAttribute(attr))) |
2057 | - # colors might also hide in styles |
2058 | - if attr in styles.keys(): |
2059 | - oldColorValue = styles[attr] |
2060 | - newColorValue = convertColor(oldColorValue) |
2061 | - oldBytes = len(oldColorValue) |
2062 | - newBytes = len(newColorValue) |
2063 | - if oldBytes > newBytes: |
2064 | - styles[attr] = newColorValue |
2065 | - numBytes += (oldBytes - len(element.getAttribute(attr))) |
2066 | - _setStyle(element, styles) |
2067 | - |
2068 | - # now recurse for our child elements |
2069 | - for child in element.childNodes : |
2070 | - numBytes += convertColors(child) |
2071 | - |
2072 | - return numBytes |
2073 | - |
2074 | -# TODO: go over what this method does and see if there is a way to optimize it |
2075 | -# TODO: go over the performance of this method and see if I can save memory/speed by |
2076 | -# reusing data structures, etc |
2077 | -def cleanPath(element, options) : |
2078 | - """ |
2079 | - Cleans the path string (d attribute) of the element |
2080 | - """ |
2081 | - global numBytesSavedInPathData |
2082 | - global numPathSegmentsReduced |
2083 | - global numCurvesStraightened |
2084 | - |
2085 | - # this gets the parser object from svg_regex.py |
2086 | - oldPathStr = element.getAttribute('d') |
2087 | - path = svg_parser.parse(oldPathStr) |
2088 | - |
2089 | - # This determines whether the stroke has round linecaps. If it does, |
2090 | - # we do not want to collapse empty segments, as they are actually rendered. |
2091 | - withRoundLineCaps = element.getAttribute('stroke-linecap') == 'round' |
2092 | - |
2093 | - # The first command must be a moveto, and whether it's relative (m) |
2094 | - # or absolute (M), the first set of coordinates *is* absolute. So |
2095 | - # the first iteration of the loop below will get x,y and startx,starty. |
2096 | - |
2097 | - # convert absolute coordinates into relative ones. |
2098 | - # Reuse the data structure 'path', since we're not adding or removing subcommands. |
2099 | - # Also reuse the coordinate lists since we're not adding or removing any. |
2100 | - for pathIndex in xrange(0, len(path)): |
2101 | - cmd, data = path[pathIndex] # Changes to cmd don't get through to the data structure |
2102 | - i = 0 |
2103 | - # adjust abs to rel |
2104 | - # only the A command has some values that we don't want to adjust (radii, rotation, flags) |
2105 | - if cmd == 'A': |
2106 | - for i in xrange(i, len(data), 7): |
2107 | - data[i+5] -= x |
2108 | - data[i+6] -= y |
2109 | - x += data[i+5] |
2110 | - y += data[i+6] |
2111 | - path[pathIndex] = ('a', data) |
2112 | - elif cmd == 'a': |
2113 | - x += sum(data[5::7]) |
2114 | - y += sum(data[6::7]) |
2115 | - elif cmd == 'H': |
2116 | - for i in xrange(i, len(data)): |
2117 | - data[i] -= x |
2118 | - x += data[i] |
2119 | - path[pathIndex] = ('h', data) |
2120 | - elif cmd == 'h': |
2121 | - x += sum(data) |
2122 | - elif cmd == 'V': |
2123 | - for i in xrange(i, len(data)): |
2124 | - data[i] -= y |
2125 | - y += data[i] |
2126 | - path[pathIndex] = ('v', data) |
2127 | - elif cmd == 'v': |
2128 | - y += sum(data) |
2129 | - elif cmd == 'M': |
2130 | - startx, starty = data[0], data[1] |
2131 | - # If this is a path starter, don't convert its first |
2132 | - # coordinate to relative; that would just make it (0, 0) |
2133 | - if pathIndex != 0: |
2134 | - data[0] -= x |
2135 | - data[1] -= y |
2136 | - |
2137 | - x, y = startx, starty |
2138 | - i = 2 |
2139 | - for i in xrange(i, len(data), 2): |
2140 | - data[i] -= x |
2141 | - data[i+1] -= y |
2142 | - x += data[i] |
2143 | - y += data[i+1] |
2144 | - path[pathIndex] = ('m', data) |
2145 | - elif cmd in ['L','T']: |
2146 | - for i in xrange(i, len(data), 2): |
2147 | - data[i] -= x |
2148 | - data[i+1] -= y |
2149 | - x += data[i] |
2150 | - y += data[i+1] |
2151 | - path[pathIndex] = (cmd.lower(), data) |
2152 | - elif cmd in ['m']: |
2153 | - if pathIndex == 0: |
2154 | - # START OF PATH - this is an absolute moveto |
2155 | - # followed by relative linetos |
2156 | - startx, starty = data[0], data[1] |
2157 | - x, y = startx, starty |
2158 | - i = 2 |
2159 | - else: |
2160 | - startx = x + data[0] |
2161 | - starty = y + data[1] |
2162 | - for i in xrange(i, len(data), 2): |
2163 | - x += data[i] |
2164 | - y += data[i+1] |
2165 | - elif cmd in ['l','t']: |
2166 | - x += sum(data[0::2]) |
2167 | - y += sum(data[1::2]) |
2168 | - elif cmd in ['S','Q']: |
2169 | - for i in xrange(i, len(data), 4): |
2170 | - data[i] -= x |
2171 | - data[i+1] -= y |
2172 | - data[i+2] -= x |
2173 | - data[i+3] -= y |
2174 | - x += data[i+2] |
2175 | - y += data[i+3] |
2176 | - path[pathIndex] = (cmd.lower(), data) |
2177 | - elif cmd in ['s','q']: |
2178 | - x += sum(data[2::4]) |
2179 | - y += sum(data[3::4]) |
2180 | - elif cmd == 'C': |
2181 | - for i in xrange(i, len(data), 6): |
2182 | - data[i] -= x |
2183 | - data[i+1] -= y |
2184 | - data[i+2] -= x |
2185 | - data[i+3] -= y |
2186 | - data[i+4] -= x |
2187 | - data[i+5] -= y |
2188 | - x += data[i+4] |
2189 | - y += data[i+5] |
2190 | - path[pathIndex] = ('c', data) |
2191 | - elif cmd == 'c': |
2192 | - x += sum(data[4::6]) |
2193 | - y += sum(data[5::6]) |
2194 | - elif cmd in ['z','Z']: |
2195 | - x, y = startx, starty |
2196 | - path[pathIndex] = ('z', data) |
2197 | - |
2198 | - # remove empty segments |
2199 | - # Reuse the data structure 'path' and the coordinate lists, even if we're |
2200 | - # deleting items, because these deletions are relatively cheap. |
2201 | - if not withRoundLineCaps: |
2202 | - for pathIndex in xrange(0, len(path)): |
2203 | - cmd, data = path[pathIndex] |
2204 | - i = 0 |
2205 | - if cmd in ['m','l','t']: |
2206 | - if cmd == 'm': |
2207 | - # remove m0,0 segments |
2208 | - if pathIndex > 0 and data[0] == data[i+1] == 0: |
2209 | - # 'm0,0 x,y' can be replaces with 'lx,y', |
2210 | - # except the first m which is a required absolute moveto |
2211 | - path[pathIndex] = ('l', data[2:]) |
2212 | - numPathSegmentsReduced += 1 |
2213 | - else: # else skip move coordinate |
2214 | - i = 2 |
2215 | - while i < len(data): |
2216 | - if data[i] == data[i+1] == 0: |
2217 | - del data[i:i+2] |
2218 | - numPathSegmentsReduced += 1 |
2219 | - else: |
2220 | - i += 2 |
2221 | - elif cmd == 'c': |
2222 | - while i < len(data): |
2223 | - if data[i] == data[i+1] == data[i+2] == data[i+3] == data[i+4] == data[i+5] == 0: |
2224 | - del data[i:i+6] |
2225 | - numPathSegmentsReduced += 1 |
2226 | - else: |
2227 | - i += 6 |
2228 | - elif cmd == 'a': |
2229 | - while i < len(data): |
2230 | - if data[i+5] == data[i+6] == 0: |
2231 | - del data[i:i+7] |
2232 | - numPathSegmentsReduced += 1 |
2233 | - else: |
2234 | - i += 7 |
2235 | - elif cmd == 'q': |
2236 | - while i < len(data): |
2237 | - if data[i] == data[i+1] == data[i+2] == data[i+3] == 0: |
2238 | - del data[i:i+4] |
2239 | - numPathSegmentsReduced += 1 |
2240 | - else: |
2241 | - i += 4 |
2242 | - elif cmd in ['h','v']: |
2243 | - oldLen = len(data) |
2244 | - path[pathIndex] = (cmd, [coord for coord in data if coord != 0]) |
2245 | - numPathSegmentsReduced += len(path[pathIndex][1]) - oldLen |
2246 | - |
2247 | - # fixup: Delete subcommands having no coordinates. |
2248 | - path = [elem for elem in path if len(elem[1]) > 0 or elem[0] == 'z'] |
2249 | - |
2250 | - # convert straight curves into lines |
2251 | - newPath = [path[0]] |
2252 | - for (cmd,data) in path[1:]: |
2253 | - i = 0 |
2254 | - newData = data |
2255 | - if cmd == 'c': |
2256 | - newData = [] |
2257 | - while i < len(data): |
2258 | - # since all commands are now relative, we can think of previous point as (0,0) |
2259 | - # and new point (dx,dy) is (data[i+4],data[i+5]) |
2260 | - # eqn of line will be y = (dy/dx)*x or if dx=0 then eqn of line is x=0 |
2261 | - (p1x,p1y) = (data[i],data[i+1]) |
2262 | - (p2x,p2y) = (data[i+2],data[i+3]) |
2263 | - dx = data[i+4] |
2264 | - dy = data[i+5] |
2265 | - |
2266 | - foundStraightCurve = False |
2267 | - |
2268 | - if dx == 0: |
2269 | - if p1x == 0 and p2x == 0: |
2270 | - foundStraightCurve = True |
2271 | - else: |
2272 | - m = dy/dx |
2273 | - if p1y == m*p1x and p2y == m*p2x: |
2274 | - foundStraightCurve = True |
2275 | - |
2276 | - if foundStraightCurve: |
2277 | - # flush any existing curve coords first |
2278 | - if newData: |
2279 | - newPath.append( (cmd,newData) ) |
2280 | - newData = [] |
2281 | - # now create a straight line segment |
2282 | - newPath.append( ('l', [dx,dy]) ) |
2283 | - numCurvesStraightened += 1 |
2284 | - else: |
2285 | - newData.extend(data[i:i+6]) |
2286 | - |
2287 | - i += 6 |
2288 | - if newData or cmd == 'z' or cmd == 'Z': |
2289 | - newPath.append( (cmd,newData) ) |
2290 | - path = newPath |
2291 | - |
2292 | - # collapse all consecutive commands of the same type into one command |
2293 | - prevCmd = '' |
2294 | - prevData = [] |
2295 | - newPath = [] |
2296 | - for (cmd,data) in path: |
2297 | - # flush the previous command if it is not the same type as the current command |
2298 | - if prevCmd != '': |
2299 | - if cmd != prevCmd or cmd == 'm': |
2300 | - newPath.append( (prevCmd, prevData) ) |
2301 | - prevCmd = '' |
2302 | - prevData = [] |
2303 | - |
2304 | - # if the previous and current commands are the same type, |
2305 | - # or the previous command is moveto and the current is lineto, collapse, |
2306 | - # but only if they are not move commands (since move can contain implicit lineto commands) |
2307 | - if (cmd == prevCmd or (cmd == 'l' and prevCmd == 'm')) and cmd != 'm': |
2308 | - prevData.extend(data) |
2309 | - |
2310 | - # save last command and data |
2311 | - else: |
2312 | - prevCmd = cmd |
2313 | - prevData = data |
2314 | - # flush last command and data |
2315 | - if prevCmd != '': |
2316 | - newPath.append( (prevCmd, prevData) ) |
2317 | - path = newPath |
2318 | - |
2319 | - # convert to shorthand path segments where possible |
2320 | - newPath = [] |
2321 | - for (cmd,data) in path: |
2322 | - # convert line segments into h,v where possible |
2323 | - if cmd == 'l': |
2324 | - i = 0 |
2325 | - lineTuples = [] |
2326 | - while i < len(data): |
2327 | - if data[i] == 0: |
2328 | - # vertical |
2329 | - if lineTuples: |
2330 | - # flush the existing line command |
2331 | - newPath.append( ('l', lineTuples) ) |
2332 | - lineTuples = [] |
2333 | - # append the v and then the remaining line coords |
2334 | - newPath.append( ('v', [data[i+1]]) ) |
2335 | - numPathSegmentsReduced += 1 |
2336 | - elif data[i+1] == 0: |
2337 | - if lineTuples: |
2338 | - # flush the line command, then append the h and then the remaining line coords |
2339 | - newPath.append( ('l', lineTuples) ) |
2340 | - lineTuples = [] |
2341 | - newPath.append( ('h', [data[i]]) ) |
2342 | - numPathSegmentsReduced += 1 |
2343 | - else: |
2344 | - lineTuples.extend(data[i:i+2]) |
2345 | - i += 2 |
2346 | - if lineTuples: |
2347 | - newPath.append( ('l', lineTuples) ) |
2348 | - # also handle implied relative linetos |
2349 | - elif cmd == 'm': |
2350 | - i = 2 |
2351 | - lineTuples = [data[0], data[1]] |
2352 | - while i < len(data): |
2353 | - if data[i] == 0: |
2354 | - # vertical |
2355 | - if lineTuples: |
2356 | - # flush the existing m/l command |
2357 | - newPath.append( (cmd, lineTuples) ) |
2358 | - lineTuples = [] |
2359 | - cmd = 'l' # dealing with linetos now |
2360 | - # append the v and then the remaining line coords |
2361 | - newPath.append( ('v', [data[i+1]]) ) |
2362 | - numPathSegmentsReduced += 1 |
2363 | - elif data[i+1] == 0: |
2364 | - if lineTuples: |
2365 | - # flush the m/l command, then append the h and then the remaining line coords |
2366 | - newPath.append( (cmd, lineTuples) ) |
2367 | - lineTuples = [] |
2368 | - cmd = 'l' # dealing with linetos now |
2369 | - newPath.append( ('h', [data[i]]) ) |
2370 | - numPathSegmentsReduced += 1 |
2371 | - else: |
2372 | - lineTuples.extend(data[i:i+2]) |
2373 | - i += 2 |
2374 | - if lineTuples: |
2375 | - newPath.append( (cmd, lineTuples) ) |
2376 | - # convert Bézier curve segments into s where possible |
2377 | - elif cmd == 'c': |
2378 | - bez_ctl_pt = (0,0) |
2379 | - i = 0 |
2380 | - curveTuples = [] |
2381 | - while i < len(data): |
2382 | - # rotate by 180deg means negate both coordinates |
2383 | - # if the previous control point is equal then we can substitute a |
2384 | - # shorthand bezier command |
2385 | - if bez_ctl_pt[0] == data[i] and bez_ctl_pt[1] == data[i+1]: |
2386 | - if curveTuples: |
2387 | - newPath.append( ('c', curveTuples) ) |
2388 | - curveTuples = [] |
2389 | - # append the s command |
2390 | - newPath.append( ('s', [data[i+2], data[i+3], data[i+4], data[i+5]]) ) |
2391 | - numPathSegmentsReduced += 1 |
2392 | - else: |
2393 | - j = 0 |
2394 | - while j <= 5: |
2395 | - curveTuples.append(data[i+j]) |
2396 | - j += 1 |
2397 | - |
2398 | - # set up control point for next curve segment |
2399 | - bez_ctl_pt = (data[i+4]-data[i+2], data[i+5]-data[i+3]) |
2400 | - i += 6 |
2401 | - |
2402 | - if curveTuples: |
2403 | - newPath.append( ('c', curveTuples) ) |
2404 | - # convert quadratic curve segments into t where possible |
2405 | - elif cmd == 'q': |
2406 | - quad_ctl_pt = (0,0) |
2407 | - i = 0 |
2408 | - curveTuples = [] |
2409 | - while i < len(data): |
2410 | - if quad_ctl_pt[0] == data[i] and quad_ctl_pt[1] == data[i+1]: |
2411 | - if curveTuples: |
2412 | - newPath.append( ('q', curveTuples) ) |
2413 | - curveTuples = [] |
2414 | - # append the t command |
2415 | - newPath.append( ('t', [data[i+2], data[i+3]]) ) |
2416 | - numPathSegmentsReduced += 1 |
2417 | - else: |
2418 | - j = 0; |
2419 | - while j <= 3: |
2420 | - curveTuples.append(data[i+j]) |
2421 | - j += 1 |
2422 | - |
2423 | - quad_ctl_pt = (data[i+2]-data[i], data[i+3]-data[i+1]) |
2424 | - i += 4 |
2425 | - |
2426 | - if curveTuples: |
2427 | - newPath.append( ('q', curveTuples) ) |
2428 | - else: |
2429 | - newPath.append( (cmd, data) ) |
2430 | - path = newPath |
2431 | - |
2432 | - # for each h or v, collapse unnecessary coordinates that run in the same direction |
2433 | - # i.e. "h-100-100" becomes "h-200" but "h300-100" does not change |
2434 | - # Reuse the data structure 'path', since we're not adding or removing subcommands. |
2435 | - # Also reuse the coordinate lists, even if we're deleting items, because these |
2436 | - # deletions are relatively cheap. |
2437 | - for pathIndex in xrange(1, len(path)): |
2438 | - cmd, data = path[pathIndex] |
2439 | - if cmd in ['h','v'] and len(data) > 1: |
2440 | - coordIndex = 1 |
2441 | - while coordIndex < len(data): |
2442 | - if isSameSign(data[coordIndex - 1], data[coordIndex]): |
2443 | - data[coordIndex - 1] += data[coordIndex] |
2444 | - del data[coordIndex] |
2445 | - numPathSegmentsReduced += 1 |
2446 | - else: |
2447 | - coordIndex += 1 |
2448 | - |
2449 | - # it is possible that we have consecutive h, v, c, t commands now |
2450 | - # so again collapse all consecutive commands of the same type into one command |
2451 | - prevCmd = '' |
2452 | - prevData = [] |
2453 | - newPath = [path[0]] |
2454 | - for (cmd,data) in path[1:]: |
2455 | - # flush the previous command if it is not the same type as the current command |
2456 | - if prevCmd != '': |
2457 | - if cmd != prevCmd or cmd == 'm': |
2458 | - newPath.append( (prevCmd, prevData) ) |
2459 | - prevCmd = '' |
2460 | - prevData = [] |
2461 | - |
2462 | - # if the previous and current commands are the same type, collapse |
2463 | - if cmd == prevCmd and cmd != 'm': |
2464 | - prevData.extend(data) |
2465 | - |
2466 | - # save last command and data |
2467 | - else: |
2468 | - prevCmd = cmd |
2469 | - prevData = data |
2470 | - # flush last command and data |
2471 | - if prevCmd != '': |
2472 | - newPath.append( (prevCmd, prevData) ) |
2473 | - path = newPath |
2474 | - |
2475 | - newPathStr = serializePath(path, options) |
2476 | - numBytesSavedInPathData += ( len(oldPathStr) - len(newPathStr) ) |
2477 | - element.setAttribute('d', newPathStr) |
2478 | - |
2479 | -def parseListOfPoints(s): |
2480 | - """ |
2481 | - Parse string into a list of points. |
2482 | - |
2483 | - Returns a list of containing an even number of coordinate strings |
2484 | - """ |
2485 | - i = 0 |
2486 | - |
2487 | - # (wsp)? comma-or-wsp-separated coordinate pairs (wsp)? |
2488 | - # coordinate-pair = coordinate comma-or-wsp coordinate |
2489 | - # coordinate = sign? integer |
2490 | - # comma-wsp: (wsp+ comma? wsp*) | (comma wsp*) |
2491 | - ws_nums = re.split(r"\s*,?\s*", s.strip()) |
2492 | - nums = [] |
2493 | - |
2494 | - # also, if 100-100 is found, split it into two also |
2495 | - # <polygon points="100,-100,100-100,100-100-100,-100-100" /> |
2496 | - for i in xrange(len(ws_nums)): |
2497 | - negcoords = ws_nums[i].split("-") |
2498 | - |
2499 | - # this string didn't have any negative coordinates |
2500 | - if len(negcoords) == 1: |
2501 | - nums.append(negcoords[0]) |
2502 | - # we got negative coords |
2503 | - else: |
2504 | - for j in xrange(len(negcoords)): |
2505 | - if j == 0: |
2506 | - # first number could be positive |
2507 | - if negcoords[0] != '': |
2508 | - nums.append(negcoords[0]) |
2509 | - # but it could also be negative |
2510 | - elif len(nums) == 0: |
2511 | - nums.append('-' + negcoords[j]) |
2512 | - # otherwise all other strings will be negative |
2513 | - else: |
2514 | - # unless we accidentally split a number that was in scientific notation |
2515 | - # and had a negative exponent (500.00e-1) |
2516 | - prev = nums[len(nums)-1] |
2517 | - if prev[len(prev)-1] in ['e', 'E']: |
2518 | - nums[len(nums)-1] = prev + '-' + negcoords[j] |
2519 | - else: |
2520 | - nums.append( '-'+negcoords[j] ) |
2521 | - |
2522 | - # if we have an odd number of points, return empty |
2523 | - if len(nums) % 2 != 0: return [] |
2524 | - |
2525 | - # now resolve into Decimal values |
2526 | - i = 0 |
2527 | - while i < len(nums): |
2528 | - try: |
2529 | - nums[i] = getcontext().create_decimal(nums[i]) |
2530 | - nums[i + 1] = getcontext().create_decimal(nums[i + 1]) |
2531 | - except decimal.InvalidOperation: # one of the lengths had a unit or is an invalid number |
2532 | - return [] |
2533 | - |
2534 | - i += 2 |
2535 | - |
2536 | - return nums |
2537 | - |
2538 | -def cleanPolygon(elem, options): |
2539 | - """ |
2540 | - Remove unnecessary closing point of polygon points attribute |
2541 | - """ |
2542 | - global numPointsRemovedFromPolygon |
2543 | - |
2544 | - pts = parseListOfPoints(elem.getAttribute('points')) |
2545 | - N = len(pts)/2 |
2546 | - if N >= 2: |
2547 | - (startx,starty) = pts[:2] |
2548 | - (endx,endy) = pts[-2:] |
2549 | - if startx == endx and starty == endy: |
2550 | - del pts[-2:] |
2551 | - numPointsRemovedFromPolygon += 1 |
2552 | - elem.setAttribute('points', scourCoordinates(pts, options, True)) |
2553 | - |
2554 | -def cleanPolyline(elem, options): |
2555 | - """ |
2556 | - Scour the polyline points attribute |
2557 | - """ |
2558 | - pts = parseListOfPoints(elem.getAttribute('points')) |
2559 | - elem.setAttribute('points', scourCoordinates(pts, options, True)) |
2560 | - |
2561 | -def serializePath(pathObj, options): |
2562 | - """ |
2563 | - Reserializes the path data with some cleanups. |
2564 | - """ |
2565 | - # elliptical arc commands must have comma/wsp separating the coordinates |
2566 | - # this fixes an issue outlined in Fix https://bugs.launchpad.net/scour/+bug/412754 |
2567 | - return ''.join([cmd + scourCoordinates(data, options, (cmd == 'a')) for cmd, data in pathObj]) |
2568 | - |
2569 | -def serializeTransform(transformObj): |
2570 | - """ |
2571 | - Reserializes the transform data with some cleanups. |
2572 | - """ |
2573 | - return ' '.join( |
2574 | - [command + '(' + ' '.join( |
2575 | - [scourUnitlessLength(number) for number in numbers] |
2576 | - ) + ')' |
2577 | - for command, numbers in transformObj] |
2578 | - ) |
2579 | - |
2580 | -def scourCoordinates(data, options, forceCommaWsp = False): |
2581 | - """ |
2582 | - Serializes coordinate data with some cleanups: |
2583 | - - removes all trailing zeros after the decimal |
2584 | - - integerize coordinates if possible |
2585 | - - removes extraneous whitespace |
2586 | - - adds spaces between values in a subcommand if required (or if forceCommaWsp is True) |
2587 | - """ |
2588 | - if data != None: |
2589 | - newData = [] |
2590 | - c = 0 |
2591 | - previousCoord = '' |
2592 | - for coord in data: |
2593 | - scouredCoord = scourUnitlessLength(coord, needsRendererWorkaround=options.renderer_workaround) |
2594 | - # only need the comma if the current number starts with a digit |
2595 | - # (numbers can start with - without needing a comma before) |
2596 | - # or if forceCommaWsp is True |
2597 | - # or if this number starts with a dot and the previous number |
2598 | - # had *no* dot or exponent (so we can go like -5.5.5 for -5.5,0.5 |
2599 | - # and 4e4.5 for 40000,0.5) |
2600 | - if c > 0 and (forceCommaWsp |
2601 | - or scouredCoord[0].isdigit() |
2602 | - or (scouredCoord[0] == '.' and not ('.' in previousCoord or 'e' in previousCoord)) |
2603 | - ): |
2604 | - newData.append( ' ' ) |
2605 | - |
2606 | - # add the scoured coordinate to the path string |
2607 | - newData.append( scouredCoord ) |
2608 | - previousCoord = scouredCoord |
2609 | - c += 1 |
2610 | - |
2611 | - # What we need to do to work around GNOME bugs 548494, 563933 and |
2612 | - # 620565, which are being fixed and unfixed in Ubuntu, is |
2613 | - # to make sure that a dot doesn't immediately follow a command |
2614 | - # (so 'h50' and 'h0.5' are allowed, but not 'h.5'). |
2615 | - # Then, we need to add a space character after any coordinates |
2616 | - # having an 'e' (scientific notation), so as to have the exponent |
2617 | - # separate from the next number. |
2618 | - if options.renderer_workaround: |
2619 | - if len(newData) > 0: |
2620 | - for i in xrange(1, len(newData)): |
2621 | - if newData[i][0] == '-' and 'e' in newData[i - 1]: |
2622 | - newData[i - 1] += ' ' |
2623 | - return ''.join(newData) |
2624 | - else: |
2625 | - return ''.join(newData) |
2626 | - |
2627 | - return '' |
2628 | - |
2629 | -def scourLength(length): |
2630 | - """ |
2631 | - Scours a length. Accepts units. |
2632 | - """ |
2633 | - length = SVGLength(length) |
2634 | - |
2635 | - return scourUnitlessLength(length.value) + Unit.str(length.units) |
2636 | - |
2637 | -def scourUnitlessLength(length, needsRendererWorkaround=False): # length is of a numeric type |
2638 | - """ |
2639 | - Scours the numeric part of a length only. Does not accept units. |
2640 | - |
2641 | - This is faster than scourLength on elements guaranteed not to |
2642 | - contain units. |
2643 | - """ |
2644 | - # reduce to the proper number of digits |
2645 | - if not isinstance(length, Decimal): |
2646 | - length = getcontext().create_decimal(str(length)) |
2647 | - # if the value is an integer, it may still have .0[...] attached to it for some reason |
2648 | - # remove those |
2649 | - if int(length) == length: |
2650 | - length = getcontext().create_decimal(int(length)) |
2651 | - |
2652 | - # gather the non-scientific notation version of the coordinate. |
2653 | - # this may actually be in scientific notation if the value is |
2654 | - # sufficiently large or small, so this is a misnomer. |
2655 | - nonsci = unicode(length).lower().replace("e+", "e") |
2656 | - if not needsRendererWorkaround: |
2657 | - if len(nonsci) > 2 and nonsci[:2] == '0.': |
2658 | - nonsci = nonsci[1:] # remove the 0, leave the dot |
2659 | - elif len(nonsci) > 3 and nonsci[:3] == '-0.': |
2660 | - nonsci = '-' + nonsci[2:] # remove the 0, leave the minus and dot |
2661 | - |
2662 | - if len(nonsci) > 3: # avoid calling normalize unless strictly necessary |
2663 | - # and then the scientific notation version, with E+NUMBER replaced with |
2664 | - # just eNUMBER, since SVG accepts this. |
2665 | - sci = unicode(length.normalize()).lower().replace("e+", "e") |
2666 | - |
2667 | - if len(sci) < len(nonsci): return sci |
2668 | - else: return nonsci |
2669 | - else: return nonsci |
2670 | - |
2671 | -def reducePrecision(element) : |
2672 | - """ |
2673 | - Because opacities, letter spacings, stroke widths and all that don't need |
2674 | - to be preserved in SVG files with 9 digits of precision. |
2675 | - |
2676 | - Takes all of these attributes, in the given element node and its children, |
2677 | - and reduces their precision to the current Decimal context's precision. |
2678 | - Also checks for the attributes actually being lengths, not 'inherit', 'none' |
2679 | - or anything that isn't an SVGLength. |
2680 | - |
2681 | - Returns the number of bytes saved after performing these reductions. |
2682 | - """ |
2683 | - num = 0 |
2684 | - |
2685 | - styles = _getStyle(element) |
2686 | - for lengthAttr in ['opacity', 'flood-opacity', 'fill-opacity', |
2687 | - 'stroke-opacity', 'stop-opacity', 'stroke-miterlimit', |
2688 | - 'stroke-dashoffset', 'letter-spacing', 'word-spacing', |
2689 | - 'kerning', 'font-size-adjust', 'font-size', |
2690 | - 'stroke-width']: |
2691 | - val = element.getAttribute(lengthAttr) |
2692 | - if val != '': |
2693 | - valLen = SVGLength(val) |
2694 | - if valLen.units != Unit.INVALID: # not an absolute/relative size or inherit, can be % though |
2695 | - newVal = scourLength(val) |
2696 | - if len(newVal) < len(val): |
2697 | - num += len(val) - len(newVal) |
2698 | - element.setAttribute(lengthAttr, newVal) |
2699 | - # repeat for attributes hidden in styles |
2700 | - if lengthAttr in styles.keys(): |
2701 | - val = styles[lengthAttr] |
2702 | - valLen = SVGLength(val) |
2703 | - if valLen.units != Unit.INVALID: |
2704 | - newVal = scourLength(val) |
2705 | - if len(newVal) < len(val): |
2706 | - num += len(val) - len(newVal) |
2707 | - styles[lengthAttr] = newVal |
2708 | - _setStyle(element, styles) |
2709 | - |
2710 | - for child in element.childNodes: |
2711 | - if child.nodeType == 1: |
2712 | - num += reducePrecision(child) |
2713 | - |
2714 | - return num |
2715 | - |
2716 | -def optimizeAngle(angle): |
2717 | - """ |
2718 | - Because any rotation can be expressed within 360 degrees |
2719 | - of any given number, and since negative angles sometimes |
2720 | - are one character longer than corresponding positive angle, |
2721 | - we shorten the number to one in the range to [-90, 270[. |
2722 | - """ |
2723 | - # First, we put the new angle in the range ]-360, 360[. |
2724 | - # The modulo operator yields results with the sign of the |
2725 | - # divisor, so for negative dividends, we preserve the sign |
2726 | - # of the angle. |
2727 | - if angle < 0: angle %= -360 |
2728 | - else: angle %= 360 |
2729 | - # 720 degrees is unneccessary, as 360 covers all angles. |
2730 | - # As "-x" is shorter than "35x" and "-xxx" one character |
2731 | - # longer than positive angles <= 260, we constrain angle |
2732 | - # range to [-90, 270[ (or, equally valid: ]-100, 260]). |
2733 | - if angle >= 270: angle -= 360 |
2734 | - elif angle < -90: angle += 360 |
2735 | - return angle |
2736 | - |
2737 | - |
2738 | -def optimizeTransform(transform): |
2739 | - """ |
2740 | - Optimises a series of transformations parsed from a single |
2741 | - transform="" attribute. |
2742 | - |
2743 | - The transformation list is modified in-place. |
2744 | - """ |
2745 | - # FIXME: reordering these would optimize even more cases: |
2746 | - # first: Fold consecutive runs of the same transformation |
2747 | - # extra: Attempt to cast between types to create sameness: |
2748 | - # "matrix(0 1 -1 0 0 0) rotate(180) scale(-1)" all |
2749 | - # are rotations (90, 180, 180) -- thus "rotate(90)" |
2750 | - # second: Simplify transforms where numbers are optional. |
2751 | - # third: Attempt to simplify any single remaining matrix() |
2752 | - # |
2753 | - # if there's only one transformation and it's a matrix, |
2754 | - # try to make it a shorter non-matrix transformation |
2755 | - # NOTE: as matrix(a b c d e f) in SVG means the matrix: |
2756 | - # |¯ a c e ¯| make constants |¯ A1 A2 A3 ¯| |
2757 | - # | b d f | translating them | B1 B2 B3 | |
2758 | - # |_ 0 0 1 _| to more readable |_ 0 0 1 _| |
2759 | - if len(transform) == 1 and transform[0][0] == 'matrix': |
2760 | - matrix = A1, B1, A2, B2, A3, B3 = transform[0][1] |
2761 | - # |¯ 1 0 0 ¯| |
2762 | - # | 0 1 0 | Identity matrix (no transformation) |
2763 | - # |_ 0 0 1 _| |
2764 | - if matrix == [1, 0, 0, 1, 0, 0]: |
2765 | - del transform[0] |
2766 | - # |¯ 1 0 X ¯| |
2767 | - # | 0 1 Y | Translation by (X, Y). |
2768 | - # |_ 0 0 1 _| |
2769 | - elif (A1 == 1 and A2 == 0 |
2770 | - and B1 == 0 and B2 == 1): |
2771 | - transform[0] = ('translate', [A3, B3]) |
2772 | - # |¯ X 0 0 ¯| |
2773 | - # | 0 Y 0 | Scaling by (X, Y). |
2774 | - # |_ 0 0 1 _| |
2775 | - elif ( A2 == 0 and A3 == 0 |
2776 | - and B1 == 0 and B3 == 0): |
2777 | - transform[0] = ('scale', [A1, B2]) |
2778 | - # |¯ cos(A) -sin(A) 0 ¯| Rotation by angle A, |
2779 | - # | sin(A) cos(A) 0 | clockwise, about the origin. |
2780 | - # |_ 0 0 1 _| A is in degrees, [-180...180]. |
2781 | - elif (A1 == B2 and -1 <= A1 <= 1 and A3 == 0 |
2782 | - and -B1 == A2 and -1 <= B1 <= 1 and B3 == 0 |
2783 | - # as cos² A + sin² A == 1 and as decimal trig is approximate: |
2784 | - # FIXME: the "epsilon" term here should really be some function |
2785 | - # of the precision of the (sin|cos)_A terms, not 1e-15: |
2786 | - and abs((B1 ** 2) + (A1 ** 2) - 1) < Decimal("1e-15")): |
2787 | - sin_A, cos_A = B1, A1 |
2788 | - # while asin(A) and acos(A) both only have an 180° range |
2789 | - # the sign of sin(A) and cos(A) varies across quadrants, |
2790 | - # letting us hone in on the angle the matrix represents: |
2791 | - # -- => < -90 | -+ => -90..0 | ++ => 0..90 | +- => >= 90 |
2792 | - # |
2793 | - # http://en.wikipedia.org/wiki/File:Sine_cosine_plot.svg |
2794 | - # shows asin has the correct angle the middle quadrants: |
2795 | - A = Decimal(str(math.degrees(math.asin(float(sin_A))))) |
2796 | - if cos_A < 0: # otherwise needs adjusting from the edges |
2797 | - if sin_A < 0: |
2798 | - A = -180 - A |
2799 | - else: |
2800 | - A = 180 - A |
2801 | - transform[0] = ('rotate', [A]) |
2802 | - |
2803 | - # Simplify transformations where numbers are optional. |
2804 | - for type, args in transform: |
2805 | - if type == 'translate': |
2806 | - # Only the X coordinate is required for translations. |
2807 | - # If the Y coordinate is unspecified, it's 0. |
2808 | - if len(args) == 2 and args[1] == 0: |
2809 | - del args[1] |
2810 | - elif type == 'rotate': |
2811 | - args[0] = optimizeAngle(args[0]) # angle |
2812 | - # Only the angle is required for rotations. |
2813 | - # If the coordinates are unspecified, it's the origin (0, 0). |
2814 | - if len(args) == 3 and args[1] == args[2] == 0: |
2815 | - del args[1:] |
2816 | - elif type == 'scale': |
2817 | - # Only the X scaling factor is required. |
2818 | - # If the Y factor is unspecified, it's the same as X. |
2819 | - if len(args) == 2 and args[0] == args[1]: |
2820 | - del args[1] |
2821 | - |
2822 | - # Attempt to coalesce runs of the same transformation. |
2823 | - # Translations followed immediately by other translations, |
2824 | - # rotations followed immediately by other rotations, |
2825 | - # scaling followed immediately by other scaling, |
2826 | - # are safe to add. |
2827 | - # Identity skewX/skewY are safe to remove, but how do they accrete? |
2828 | - # |¯ 1 0 0 ¯| |
2829 | - # | tan(A) 1 0 | skews X coordinates by angle A |
2830 | - # |_ 0 0 1 _| |
2831 | - # |
2832 | - # |¯ 1 tan(A) 0 ¯| |
2833 | - # | 0 1 0 | skews Y coordinates by angle A |
2834 | - # |_ 0 0 1 _| |
2835 | - # |
2836 | - # FIXME: A matrix followed immediately by another matrix |
2837 | - # would be safe to multiply together, too. |
2838 | - i = 1 |
2839 | - while i < len(transform): |
2840 | - currType, currArgs = transform[i] |
2841 | - prevType, prevArgs = transform[i - 1] |
2842 | - if currType == prevType == 'translate': |
2843 | - prevArgs[0] += currArgs[0] # x |
2844 | - # for y, only add if the second translation has an explicit y |
2845 | - if len(currArgs) == 2: |
2846 | - if len(prevArgs) == 2: |
2847 | - prevArgs[1] += currArgs[1] # y |
2848 | - elif len(prevArgs) == 1: |
2849 | - prevArgs.append(currArgs[1]) # y |
2850 | - del transform[i] |
2851 | - if prevArgs[0] == prevArgs[1] == 0: |
2852 | - # Identity translation! |
2853 | - i -= 1 |
2854 | - del transform[i] |
2855 | - elif (currType == prevType == 'rotate' |
2856 | - and len(prevArgs) == len(currArgs) == 1): |
2857 | - # Only coalesce if both rotations are from the origin. |
2858 | - prevArgs[0] = optimizeAngle(prevArgs[0] + currArgs[0]) |
2859 | - del transform[i] |
2860 | - elif currType == prevType == 'scale': |
2861 | - prevArgs[0] *= currArgs[0] # x |
2862 | - # handle an implicit y |
2863 | - if len(prevArgs) == 2 and len(currArgs) == 2: |
2864 | - # y1 * y2 |
2865 | - prevArgs[1] *= currArgs[1] |
2866 | - elif len(prevArgs) == 1 and len(currArgs) == 2: |
2867 | - # create y2 = uniformscalefactor1 * y2 |
2868 | - prevArgs.append(prevArgs[0] * currArgs[1]) |
2869 | - elif len(prevArgs) == 2 and len(currArgs) == 1: |
2870 | - # y1 * uniformscalefactor2 |
2871 | - prevArgs[1] *= currArgs[0] |
2872 | - del transform[i] |
2873 | - if prevArgs[0] == prevArgs[1] == 1: |
2874 | - # Identity scale! |
2875 | - i -= 1 |
2876 | - del transform[i] |
2877 | - else: |
2878 | - i += 1 |
2879 | - |
2880 | - # Some fixups are needed for single-element transformation lists, since |
2881 | - # the loop above was to coalesce elements with their predecessors in the |
2882 | - # list, and thus it required 2 elements. |
2883 | - i = 0 |
2884 | - while i < len(transform): |
2885 | - currType, currArgs = transform[i] |
2886 | - if ((currType == 'skewX' or currType == 'skewY') |
2887 | - and len(currArgs) == 1 and currArgs[0] == 0): |
2888 | - # Identity skew! |
2889 | - del transform[i] |
2890 | - elif ((currType == 'rotate') |
2891 | - and len(currArgs) == 1 and currArgs[0] == 0): |
2892 | - # Identity rotation! |
2893 | - del transform[i] |
2894 | - else: |
2895 | - i += 1 |
2896 | - |
2897 | -def optimizeTransforms(element, options) : |
2898 | - """ |
2899 | - Attempts to optimise transform specifications on the given node and its children. |
2900 | - |
2901 | - Returns the number of bytes saved after performing these reductions. |
2902 | - """ |
2903 | - num = 0 |
2904 | - |
2905 | - for transformAttr in ['transform', 'patternTransform', 'gradientTransform']: |
2906 | - val = element.getAttribute(transformAttr) |
2907 | - if val != '': |
2908 | - transform = svg_transform_parser.parse(val) |
2909 | - |
2910 | - optimizeTransform(transform) |
2911 | - |
2912 | - newVal = serializeTransform(transform) |
2913 | - |
2914 | - if len(newVal) < len(val): |
2915 | - if len(newVal): |
2916 | - element.setAttribute(transformAttr, newVal) |
2917 | - else: |
2918 | - element.removeAttribute(transformAttr) |
2919 | - num += len(val) - len(newVal) |
2920 | - |
2921 | - for child in element.childNodes: |
2922 | - if child.nodeType == 1: |
2923 | - num += optimizeTransforms(child, options) |
2924 | - |
2925 | - return num |
2926 | - |
2927 | -def removeComments(element) : |
2928 | - """ |
2929 | - Removes comments from the element and its children. |
2930 | - """ |
2931 | - global numCommentBytes |
2932 | - |
2933 | - if isinstance(element, xml.dom.minidom.Document): |
2934 | - # must process the document object separately, because its |
2935 | - # documentElement's nodes have None as their parentNode |
2936 | - # iterate in reverse order to prevent mess-ups with renumbering |
2937 | - for index in xrange(len(element.childNodes) - 1, -1, -1): |
2938 | - subelement = element.childNodes[index] |
2939 | - if isinstance(subelement, xml.dom.minidom.Comment): |
2940 | - numCommentBytes += len(subelement.data) |
2941 | - element.removeChild(subelement) |
2942 | - else: |
2943 | - removeComments(subelement) |
2944 | - elif isinstance(element, xml.dom.minidom.Comment): |
2945 | - numCommentBytes += len(element.data) |
2946 | - element.parentNode.removeChild(element) |
2947 | - else: |
2948 | - # iterate in reverse order to prevent mess-ups with renumbering |
2949 | - for index in xrange(len(element.childNodes) - 1, -1, -1): |
2950 | - subelement = element.childNodes[index] |
2951 | - removeComments(subelement) |
2952 | - |
2953 | -def embedRasters(element, options) : |
2954 | - import base64 |
2955 | - import urllib |
2956 | - """ |
2957 | - Converts raster references to inline images. |
2958 | - NOTE: there are size limits to base64-encoding handling in browsers |
2959 | - """ |
2960 | - global numRastersEmbedded |
2961 | - |
2962 | - href = element.getAttributeNS(NS['XLINK'],'href') |
2963 | - |
2964 | - # if xlink:href is set, then grab the id |
2965 | - if href != '' and len(href) > 1: |
2966 | - # find if href value has filename ext |
2967 | - ext = os.path.splitext(os.path.basename(href))[1].lower()[1:] |
2968 | - |
2969 | - # look for 'png', 'jpg', and 'gif' extensions |
2970 | - if ext == 'png' or ext == 'jpg' or ext == 'gif': |
2971 | - |
2972 | - # file:// URLs denote files on the local system too |
2973 | - if href[:7] == 'file://': |
2974 | - href = href[7:] |
2975 | - # does the file exist? |
2976 | - if os.path.isfile(href): |
2977 | - # if this is not an absolute path, set path relative |
2978 | - # to script file based on input arg |
2979 | - infilename = '.' |
2980 | - if options.infilename: infilename = options.infilename |
2981 | - href = os.path.join(os.path.dirname(infilename), href) |
2982 | - |
2983 | - rasterdata = '' |
2984 | - # test if file exists locally |
2985 | - if os.path.isfile(href): |
2986 | - # open raster file as raw binary |
2987 | - raster = open( href, "rb") |
2988 | - rasterdata = raster.read() |
2989 | - elif href[:7] == 'http://': |
2990 | - webFile = urllib.urlopen( href ) |
2991 | - rasterdata = webFile.read() |
2992 | - webFile.close() |
2993 | - |
2994 | - # ... should we remove all images which don't resolve? |
2995 | - if rasterdata != '' : |
2996 | - # base64-encode raster |
2997 | - b64eRaster = base64.b64encode( rasterdata ) |
2998 | - |
2999 | - # set href attribute to base64-encoded equivalent |
3000 | - if b64eRaster != '': |
3001 | - # PNG and GIF both have MIME Type 'image/[ext]', but |
3002 | - # JPEG has MIME Type 'image/jpeg' |
3003 | - if ext == 'jpg': |
3004 | - ext = 'jpeg' |
3005 | - |
3006 | - element.setAttributeNS(NS['XLINK'], 'href', 'data:image/' + ext + ';base64,' + b64eRaster) |
3007 | - numRastersEmbedded += 1 |
3008 | - del b64eRaster |
3009 | - |
3010 | -def properlySizeDoc(docElement, options): |
3011 | - # get doc width and height |
3012 | - w = SVGLength(docElement.getAttribute('width')) |
3013 | - h = SVGLength(docElement.getAttribute('height')) |
3014 | - |
3015 | - # if width/height are not unitless or px then it is not ok to rewrite them into a viewBox. |
3016 | - # well, it may be OK for Web browsers and vector editors, but not for librsvg. |
3017 | - if options.renderer_workaround: |
3018 | - if ((w.units != Unit.NONE and w.units != Unit.PX) or |
3019 | - (h.units != Unit.NONE and h.units != Unit.PX)): |
3020 | - return |
3021 | - |
3022 | - # else we have a statically sized image and we should try to remedy that |
3023 | - |
3024 | - # parse viewBox attribute |
3025 | - vbSep = re.split("\\s*\\,?\\s*", docElement.getAttribute('viewBox'), 3) |
3026 | - # if we have a valid viewBox we need to check it |
3027 | - vbWidth,vbHeight = 0,0 |
3028 | - if len(vbSep) == 4: |
3029 | - try: |
3030 | - # if x or y are specified and non-zero then it is not ok to overwrite it |
3031 | - vbX = float(vbSep[0]) |
3032 | - vbY = float(vbSep[1]) |
3033 | - if vbX != 0 or vbY != 0: |
3034 | - return |
3035 | - |
3036 | - # if width or height are not equal to doc width/height then it is not ok to overwrite it |
3037 | - vbWidth = float(vbSep[2]) |
3038 | - vbHeight = float(vbSep[3]) |
3039 | - if vbWidth != w.value or vbHeight != h.value: |
3040 | - return |
3041 | - # if the viewBox did not parse properly it is invalid and ok to overwrite it |
3042 | - except ValueError: |
3043 | - pass |
3044 | - |
3045 | - # at this point it's safe to set the viewBox and remove width/height |
3046 | - docElement.setAttribute('viewBox', '0 0 %s %s' % (w.value, h.value)) |
3047 | - docElement.removeAttribute('width') |
3048 | - docElement.removeAttribute('height') |
3049 | - |
3050 | -def remapNamespacePrefix(node, oldprefix, newprefix): |
3051 | - if node == None or node.nodeType != 1: return |
3052 | - |
3053 | - if node.prefix == oldprefix: |
3054 | - localName = node.localName |
3055 | - namespace = node.namespaceURI |
3056 | - doc = node.ownerDocument |
3057 | - parent = node.parentNode |
3058 | - |
3059 | - # create a replacement node |
3060 | - newNode = None |
3061 | - if newprefix != '': |
3062 | - newNode = doc.createElementNS(namespace, newprefix+":"+localName) |
3063 | - else: |
3064 | - newNode = doc.createElement(localName); |
3065 | - |
3066 | - # add all the attributes |
3067 | - attrList = node.attributes |
3068 | - for i in xrange(attrList.length): |
3069 | - attr = attrList.item(i) |
3070 | - newNode.setAttributeNS( attr.namespaceURI, attr.localName, attr.nodeValue) |
3071 | - |
3072 | - # clone and add all the child nodes |
3073 | - for child in node.childNodes: |
3074 | - newNode.appendChild(child.cloneNode(True)) |
3075 | - |
3076 | - # replace old node with new node |
3077 | - parent.replaceChild( newNode, node ) |
3078 | - # set the node to the new node in the remapped namespace prefix |
3079 | - node = newNode |
3080 | - |
3081 | - # now do all child nodes |
3082 | - for child in node.childNodes : |
3083 | - remapNamespacePrefix(child, oldprefix, newprefix) |
3084 | - |
3085 | -def makeWellFormed(str): |
3086 | - xml_ents = { '<':'<', '>':'>', '&':'&', "'":''', '"':'"'} |
3087 | - |
3088 | -# starr = [] |
3089 | -# for c in str: |
3090 | -# if c in xml_ents: |
3091 | -# starr.append(xml_ents[c]) |
3092 | -# else: |
3093 | -# starr.append(c) |
3094 | - |
3095 | - # this list comprehension is short-form for the above for-loop: |
3096 | - return ''.join([xml_ents[c] if c in xml_ents else c for c in str]) |
3097 | - |
3098 | -# hand-rolled serialization function that has the following benefits: |
3099 | -# - pretty printing |
3100 | -# - somewhat judicious use of whitespace |
3101 | -# - ensure id attributes are first |
3102 | -def serializeXML(element, options, ind = 0, preserveWhitespace = False): |
3103 | - outParts = [] |
3104 | - |
3105 | - indent = ind |
3106 | - I='' |
3107 | - if options.indent_type == 'tab': I='\t' |
3108 | - elif options.indent_type == 'space': I=' ' |
3109 | - |
3110 | - outParts.extend([(I * ind), '<', element.nodeName]) |
3111 | - |
3112 | - # always serialize the id or xml:id attributes first |
3113 | - if element.getAttribute('id') != '': |
3114 | - id = element.getAttribute('id') |
3115 | - quot = '"' |
3116 | - if id.find('"') != -1: |
3117 | - quot = "'" |
3118 | - outParts.extend([' id=', quot, id, quot]) |
3119 | - if element.getAttribute('xml:id') != '': |
3120 | - id = element.getAttribute('xml:id') |
3121 | - quot = '"' |
3122 | - if id.find('"') != -1: |
3123 | - quot = "'" |
3124 | - outParts.extend([' xml:id=', quot, id, quot]) |
3125 | - |
3126 | - # now serialize the other attributes |
3127 | - attrList = element.attributes |
3128 | - for num in xrange(attrList.length) : |
3129 | - attr = attrList.item(num) |
3130 | - if attr.nodeName == 'id' or attr.nodeName == 'xml:id': continue |
3131 | - # if the attribute value contains a double-quote, use single-quotes |
3132 | - quot = '"' |
3133 | - if attr.nodeValue.find('"') != -1: |
3134 | - quot = "'" |
3135 | - |
3136 | - attrValue = makeWellFormed( attr.nodeValue ) |
3137 | - |
3138 | - outParts.append(' ') |
3139 | - # preserve xmlns: if it is a namespace prefix declaration |
3140 | - if attr.prefix != None: |
3141 | - outParts.extend([attr.prefix, ':']) |
3142 | - elif attr.namespaceURI != None: |
3143 | - if attr.namespaceURI == 'http://www.w3.org/2000/xmlns/' and attr.nodeName.find('xmlns') == -1: |
3144 | - outParts.append('xmlns:') |
3145 | - elif attr.namespaceURI == 'http://www.w3.org/1999/xlink': |
3146 | - outParts.append('xlink:') |
3147 | - outParts.extend([attr.localName, '=', quot, attrValue, quot]) |
3148 | - |
3149 | - if attr.nodeName == 'xml:space': |
3150 | - if attrValue == 'preserve': |
3151 | - preserveWhitespace = True |
3152 | - elif attrValue == 'default': |
3153 | - preserveWhitespace = False |
3154 | - |
3155 | - # if no children, self-close |
3156 | - children = element.childNodes |
3157 | - if children.length > 0: |
3158 | - outParts.append('>') |
3159 | - |
3160 | - onNewLine = False |
3161 | - for child in element.childNodes: |
3162 | - # element node |
3163 | - if child.nodeType == 1: |
3164 | - if preserveWhitespace: |
3165 | - outParts.append(serializeXML(child, options, 0, preserveWhitespace)) |
3166 | - else: |
3167 | - outParts.extend(['\n', serializeXML(child, options, indent + 1, preserveWhitespace)]) |
3168 | - onNewLine = True |
3169 | - # text node |
3170 | - elif child.nodeType == 3: |
3171 | - # trim it only in the case of not being a child of an element |
3172 | - # where whitespace might be important |
3173 | - if preserveWhitespace: |
3174 | - outParts.append(makeWellFormed(child.nodeValue)) |
3175 | - else: |
3176 | - outParts.append(makeWellFormed(child.nodeValue.strip())) |
3177 | - # CDATA node |
3178 | - elif child.nodeType == 4: |
3179 | - outParts.extend(['<![CDATA[', child.nodeValue, ']]>']) |
3180 | - # Comment node |
3181 | - elif child.nodeType == 8: |
3182 | - outParts.extend(['<!--', child.nodeValue, '-->']) |
3183 | - # TODO: entities, processing instructions, what else? |
3184 | - else: # ignore the rest |
3185 | - pass |
3186 | - |
3187 | - if onNewLine: outParts.append(I * ind) |
3188 | - outParts.extend(['</', element.nodeName, '>']) |
3189 | - if indent > 0: outParts.append('\n') |
3190 | - else: |
3191 | - outParts.append('/>') |
3192 | - if indent > 0: outParts.append('\n') |
3193 | - |
3194 | - return "".join(outParts) |
3195 | - |
3196 | -# this is the main method |
3197 | -# input is a string representation of the input XML |
3198 | -# returns a string representation of the output XML |
3199 | -def scourString(in_string, options=None): |
3200 | - if options is None: |
3201 | - options = _options_parser.get_default_values() |
3202 | - getcontext().prec = options.digits |
3203 | - global numAttrsRemoved |
3204 | - global numStylePropsFixed |
3205 | - global numElemsRemoved |
3206 | - global numBytesSavedInColors |
3207 | - global numCommentsRemoved |
3208 | - global numBytesSavedInIDs |
3209 | - global numBytesSavedInLengths |
3210 | - global numBytesSavedInTransforms |
3211 | - doc = xml.dom.minidom.parseString(in_string) |
3212 | - |
3213 | - # for whatever reason this does not always remove all inkscape/sodipodi attributes/elements |
3214 | - # on the first pass, so we do it multiple times |
3215 | - # does it have to do with removal of children affecting the childlist? |
3216 | - if options.keep_editor_data == False: |
3217 | - while removeNamespacedElements( doc.documentElement, unwanted_ns ) > 0 : |
3218 | - pass |
3219 | - while removeNamespacedAttributes( doc.documentElement, unwanted_ns ) > 0 : |
3220 | - pass |
3221 | - |
3222 | - # remove the xmlns: declarations now |
3223 | - xmlnsDeclsToRemove = [] |
3224 | - attrList = doc.documentElement.attributes |
3225 | - for num in xrange(attrList.length) : |
3226 | - if attrList.item(num).nodeValue in unwanted_ns : |
3227 | - xmlnsDeclsToRemove.append(attrList.item(num).nodeName) |
3228 | - |
3229 | - for attr in xmlnsDeclsToRemove : |
3230 | - doc.documentElement.removeAttribute(attr) |
3231 | - numAttrsRemoved += 1 |
3232 | - |
3233 | - # ensure namespace for SVG is declared |
3234 | - # TODO: what if the default namespace is something else (i.e. some valid namespace)? |
3235 | - if doc.documentElement.getAttribute('xmlns') != 'http://www.w3.org/2000/svg': |
3236 | - doc.documentElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg') |
3237 | - # TODO: throw error or warning? |
3238 | - |
3239 | - # check for redundant SVG namespace declaration |
3240 | - attrList = doc.documentElement.attributes |
3241 | - xmlnsDeclsToRemove = [] |
3242 | - redundantPrefixes = [] |
3243 | - for i in xrange(attrList.length): |
3244 | - attr = attrList.item(i) |
3245 | - name = attr.nodeName |
3246 | - val = attr.nodeValue |
3247 | - if name[0:6] == 'xmlns:' and val == 'http://www.w3.org/2000/svg': |
3248 | - redundantPrefixes.append(name[6:]) |
3249 | - xmlnsDeclsToRemove.append(name) |
3250 | - |
3251 | - for attrName in xmlnsDeclsToRemove: |
3252 | - doc.documentElement.removeAttribute(attrName) |
3253 | - |
3254 | - for prefix in redundantPrefixes: |
3255 | - remapNamespacePrefix(doc.documentElement, prefix, '') |
3256 | - |
3257 | - if options.strip_comments: |
3258 | - numCommentsRemoved = removeComments(doc) |
3259 | - |
3260 | - # repair style (remove unnecessary style properties and change them into XML attributes) |
3261 | - numStylePropsFixed = repairStyle(doc.documentElement, options) |
3262 | - |
3263 | - # convert colors to #RRGGBB format |
3264 | - if options.simple_colors: |
3265 | - numBytesSavedInColors = convertColors(doc.documentElement) |
3266 | - |
3267 | - # remove <metadata> if the user wants to |
3268 | - if options.remove_metadata: |
3269 | - removeMetadataElements(doc) |
3270 | - |
3271 | - # flattend defs elements into just one defs element |
3272 | - flattenDefs(doc) |
3273 | - |
3274 | - # remove unreferenced gradients/patterns outside of defs |
3275 | - # and most unreferenced elements inside of defs |
3276 | - while removeUnreferencedElements(doc) > 0: |
3277 | - pass |
3278 | - |
3279 | - # remove empty defs, metadata, g |
3280 | - # NOTE: these elements will be removed if they just have whitespace-only text nodes |
3281 | - for tag in ['defs', 'metadata', 'g'] : |
3282 | - for elem in doc.documentElement.getElementsByTagName(tag) : |
3283 | - removeElem = not elem.hasChildNodes() |
3284 | - if removeElem == False : |
3285 | - for child in elem.childNodes : |
3286 | - if child.nodeType in [1, 4, 8]: |
3287 | - break |
3288 | - elif child.nodeType == 3 and not child.nodeValue.isspace(): |
3289 | - break |
3290 | - else: |
3291 | - removeElem = True |
3292 | - if removeElem : |
3293 | - elem.parentNode.removeChild(elem) |
3294 | - numElemsRemoved += 1 |
3295 | - |
3296 | - if options.strip_ids: |
3297 | - bContinueLooping = True |
3298 | - while bContinueLooping: |
3299 | - identifiedElements = unprotected_ids(doc, options) |
3300 | - referencedIDs = findReferencedElements(doc.documentElement) |
3301 | - bContinueLooping = (removeUnreferencedIDs(referencedIDs, identifiedElements) > 0) |
3302 | - |
3303 | - while removeDuplicateGradientStops(doc) > 0: |
3304 | - pass |
3305 | - |
3306 | - # remove gradients that are only referenced by one other gradient |
3307 | - while collapseSinglyReferencedGradients(doc) > 0: |
3308 | - pass |
3309 | - |
3310 | - # remove duplicate gradients |
3311 | - while removeDuplicateGradients(doc) > 0: |
3312 | - pass |
3313 | - |
3314 | - # create <g> elements if there are runs of elements with the same attributes. |
3315 | - # this MUST be before moveCommonAttributesToParentGroup. |
3316 | - if options.group_create: |
3317 | - createGroupsForCommonAttributes(doc.documentElement) |
3318 | - |
3319 | - # move common attributes to parent group |
3320 | - # NOTE: the if the <svg> element's immediate children |
3321 | - # all have the same value for an attribute, it must not |
3322 | - # get moved to the <svg> element. The <svg> element |
3323 | - # doesn't accept fill=, stroke= etc.! |
3324 | - referencedIds = findReferencedElements(doc.documentElement) |
3325 | - for child in doc.documentElement.childNodes: |
3326 | - numAttrsRemoved += moveCommonAttributesToParentGroup(child, referencedIds) |
3327 | - |
3328 | - # remove unused attributes from parent |
3329 | - numAttrsRemoved += removeUnusedAttributesOnParent(doc.documentElement) |
3330 | - |
3331 | - # Collapse groups LAST, because we've created groups. If done before |
3332 | - # moveAttributesToParentGroup, empty <g>'s may remain. |
3333 | - if options.group_collapse: |
3334 | - while removeNestedGroups(doc.documentElement) > 0: |
3335 | - pass |
3336 | - |
3337 | - # remove unnecessary closing point of polygons and scour points |
3338 | - for polygon in doc.documentElement.getElementsByTagName('polygon') : |
3339 | - cleanPolygon(polygon, options) |
3340 | - |
3341 | - # scour points of polyline |
3342 | - for polyline in doc.documentElement.getElementsByTagName('polyline') : |
3343 | - cleanPolyline(polyline, options) |
3344 | - |
3345 | - # clean path data |
3346 | - for elem in doc.documentElement.getElementsByTagName('path') : |
3347 | - if elem.getAttribute('d') == '': |
3348 | - elem.parentNode.removeChild(elem) |
3349 | - else: |
3350 | - cleanPath(elem, options) |
3351 | - |
3352 | - # shorten ID names as much as possible |
3353 | - if options.shorten_ids: |
3354 | - numBytesSavedInIDs += shortenIDs(doc, unprotected_ids(doc, options)) |
3355 | - |
3356 | - # scour lengths (including coordinates) |
3357 | - for type in ['svg', 'image', 'rect', 'circle', 'ellipse', 'line', 'linearGradient', 'radialGradient', 'stop', 'filter']: |
3358 | - for elem in doc.getElementsByTagName(type): |
3359 | - for attr in ['x', 'y', 'width', 'height', 'cx', 'cy', 'r', 'rx', 'ry', |
3360 | - 'x1', 'y1', 'x2', 'y2', 'fx', 'fy', 'offset']: |
3361 | - if elem.getAttribute(attr) != '': |
3362 | - elem.setAttribute(attr, scourLength(elem.getAttribute(attr))) |
3363 | - |
3364 | - # more length scouring in this function |
3365 | - numBytesSavedInLengths = reducePrecision(doc.documentElement) |
3366 | - |
3367 | - # remove default values of attributes |
3368 | - numAttrsRemoved += removeDefaultAttributeValues(doc.documentElement, options) |
3369 | - |
3370 | - # reduce the length of transformation attributes |
3371 | - numBytesSavedInTransforms = optimizeTransforms(doc.documentElement, options) |
3372 | - |
3373 | - # convert rasters references to base64-encoded strings |
3374 | - if options.embed_rasters: |
3375 | - for elem in doc.documentElement.getElementsByTagName('image') : |
3376 | - embedRasters(elem, options) |
3377 | - |
3378 | - # properly size the SVG document (ideally width/height should be 100% with a viewBox) |
3379 | - if options.enable_viewboxing: |
3380 | - properlySizeDoc(doc.documentElement, options) |
3381 | - |
3382 | - # output the document as a pretty string with a single space for indent |
3383 | - # NOTE: removed pretty printing because of this problem: |
3384 | - # http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/ |
3385 | - # rolled our own serialize function here to save on space, put id first, customize indentation, etc |
3386 | -# out_string = doc.documentElement.toprettyxml(' ') |
3387 | - out_string = serializeXML(doc.documentElement, options) + '\n' |
3388 | - |
3389 | - # now strip out empty lines |
3390 | - lines = [] |
3391 | - # Get rid of empty lines |
3392 | - for line in out_string.splitlines(True): |
3393 | - if line.strip(): |
3394 | - lines.append(line) |
3395 | - |
3396 | - # return the string with its XML prolog and surrounding comments |
3397 | - if options.strip_xml_prolog == False: |
3398 | - total_output = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n' |
3399 | - else: |
3400 | - total_output = "" |
3401 | - |
3402 | - for child in doc.childNodes: |
3403 | - if child.nodeType == 1: |
3404 | - total_output += "".join(lines) |
3405 | - else: # doctypes, entities, comments |
3406 | - total_output += child.toxml() + '\n' |
3407 | - |
3408 | - return total_output |
3409 | - |
3410 | -# used mostly by unit tests |
3411 | -# input is a filename |
3412 | -# returns the minidom doc representation of the SVG |
3413 | -def scourXmlFile(filename, options=None): |
3414 | - in_string = open(filename).read() |
3415 | - out_string = scourString(in_string, options) |
3416 | - return xml.dom.minidom.parseString(out_string.encode('utf-8')) |
3417 | - |
3418 | -# GZ: Seems most other commandline tools don't do this, is it really wanted? |
3419 | -class HeaderedFormatter(optparse.IndentedHelpFormatter): |
3420 | - """ |
3421 | - Show application name, version number, and copyright statement |
3422 | - above usage information. |
3423 | - """ |
3424 | - def format_usage(self, usage): |
3425 | - return "%s %s\n%s\n%s" % (APP, VER, COPYRIGHT, |
3426 | - optparse.IndentedHelpFormatter.format_usage(self, usage)) |
3427 | - |
3428 | -# GZ: would prefer this to be in a function or class scope, but tests etc need |
3429 | -# access to the defaults anyway |
3430 | -_options_parser = optparse.OptionParser( |
3431 | - usage="%prog [-i input.svg] [-o output.svg] [OPTIONS]", |
3432 | - description=("If the input/output files are specified with a svgz" |
3433 | - " extension, then compressed SVG is assumed. If the input file is not" |
3434 | - " specified, stdin is used. If the output file is not specified, " |
3435 | - " stdout is used."), |
3436 | - formatter=HeaderedFormatter(max_help_position=30), |
3437 | - version=VER) |
3438 | - |
3439 | -_options_parser.add_option("--disable-simplify-colors", |
3440 | - action="store_false", dest="simple_colors", default=True, |
3441 | - help="won't convert all colors to #RRGGBB format") |
3442 | -_options_parser.add_option("--disable-style-to-xml", |
3443 | - action="store_false", dest="style_to_xml", default=True, |
3444 | - help="won't convert styles into XML attributes") |
3445 | -_options_parser.add_option("--disable-group-collapsing", |
3446 | - action="store_false", dest="group_collapse", default=True, |
3447 | - help="won't collapse <g> elements") |
3448 | -_options_parser.add_option("--create-groups", |
3449 | - action="store_true", dest="group_create", default=False, |
3450 | - help="create <g> elements for runs of elements with identical attributes") |
3451 | -_options_parser.add_option("--enable-id-stripping", |
3452 | - action="store_true", dest="strip_ids", default=False, |
3453 | - help="remove all un-referenced ID attributes") |
3454 | -_options_parser.add_option("--enable-comment-stripping", |
3455 | - action="store_true", dest="strip_comments", default=False, |
3456 | - help="remove all <!-- --> comments") |
3457 | -_options_parser.add_option("--shorten-ids", |
3458 | - action="store_true", dest="shorten_ids", default=False, |
3459 | - help="shorten all ID attributes to the least number of letters possible") |
3460 | -_options_parser.add_option("--disable-embed-rasters", |
3461 | - action="store_false", dest="embed_rasters", default=True, |
3462 | - help="won't embed rasters as base64-encoded data") |
3463 | -_options_parser.add_option("--keep-editor-data", |
3464 | - action="store_true", dest="keep_editor_data", default=False, |
3465 | - help="won't remove Inkscape, Sodipodi or Adobe Illustrator elements and attributes") |
3466 | -_options_parser.add_option("--remove-metadata", |
3467 | - action="store_true", dest="remove_metadata", default=False, |
3468 | - help="remove <metadata> elements (which may contain license metadata etc.)") |
3469 | -_options_parser.add_option("--renderer-workaround", |
3470 | - action="store_true", dest="renderer_workaround", default=True, |
3471 | - help="work around various renderer bugs (currently only librsvg) (default)") |
3472 | -_options_parser.add_option("--no-renderer-workaround", |
3473 | - action="store_false", dest="renderer_workaround", default=True, |
3474 | - help="do not work around various renderer bugs (currently only librsvg)") |
3475 | -_options_parser.add_option("--strip-xml-prolog", |
3476 | - action="store_true", dest="strip_xml_prolog", default=False, |
3477 | - help="won't output the <?xml ?> prolog") |
3478 | -_options_parser.add_option("--enable-viewboxing", |
3479 | - action="store_true", dest="enable_viewboxing", default=False, |
3480 | - help="changes document width/height to 100%/100% and creates viewbox coordinates") |
3481 | - |
3482 | -# GZ: this is confusing, most people will be thinking in terms of |
3483 | -# decimal places, which is not what decimal precision is doing |
3484 | -_options_parser.add_option("-p", "--set-precision", |
3485 | - action="store", type=int, dest="digits", default=5, |
3486 | - help="set number of significant digits (default: %default)") |
3487 | -_options_parser.add_option("-i", |
3488 | - action="store", dest="infilename", help=optparse.SUPPRESS_HELP) |
3489 | -_options_parser.add_option("-o", |
3490 | - action="store", dest="outfilename", help=optparse.SUPPRESS_HELP) |
3491 | -_options_parser.add_option("-q", "--quiet", |
3492 | - action="store_true", dest="quiet", default=False, |
3493 | - help="suppress non-error output") |
3494 | -_options_parser.add_option("--indent", |
3495 | - action="store", type="string", dest="indent_type", default="space", |
3496 | - help="indentation of the output: none, space, tab (default: %default)") |
3497 | -_options_parser.add_option("--protect-ids-noninkscape", |
3498 | - action="store_true", dest="protect_ids_noninkscape", default=False, |
3499 | - help="Don't change IDs not ending with a digit") |
3500 | -_options_parser.add_option("--protect-ids-list", |
3501 | - action="store", type="string", dest="protect_ids_list", default=None, |
3502 | - help="Don't change IDs given in a comma-separated list") |
3503 | -_options_parser.add_option("--protect-ids-prefix", |
3504 | - action="store", type="string", dest="protect_ids_prefix", default=None, |
3505 | - help="Don't change IDs starting with the given prefix") |
3506 | - |
3507 | -def maybe_gziped_file(filename, mode="r"): |
3508 | - if os.path.splitext(filename)[1].lower() in (".svgz", ".gz"): |
3509 | - import gzip |
3510 | - return gzip.GzipFile(filename, mode) |
3511 | - return file(filename, mode) |
3512 | - |
3513 | -def parse_args(args=None): |
3514 | - options, rargs = _options_parser.parse_args(args) |
3515 | - |
3516 | - if rargs: |
3517 | - _options_parser.error("Additional arguments not handled: %r, see --help" % rargs) |
3518 | - if options.digits < 0: |
3519 | - _options_parser.error("Can't have negative significant digits, see --help") |
3520 | - if not options.indent_type in ["tab", "space", "none"]: |
3521 | - _options_parser.error("Invalid value for --indent, see --help") |
3522 | - if options.infilename and options.outfilename and options.infilename == options.outfilename: |
3523 | - _options_parser.error("Input filename is the same as output filename") |
3524 | - |
3525 | - if options.infilename: |
3526 | - infile = maybe_gziped_file(options.infilename) |
3527 | - # GZ: could catch a raised IOError here and report |
3528 | - else: |
3529 | - # GZ: could sniff for gzip compression here |
3530 | - infile = sys.stdin |
3531 | - if options.outfilename: |
3532 | - outfile = maybe_gziped_file(options.outfilename, "wb") |
3533 | - else: |
3534 | - outfile = sys.stdout |
3535 | - |
3536 | - return options, [infile, outfile] |
3537 | - |
3538 | -def getReport(): |
3539 | - return ' Number of elements removed: ' + str(numElemsRemoved) + os.linesep + \ |
3540 | - ' Number of attributes removed: ' + str(numAttrsRemoved) + os.linesep + \ |
3541 | - ' Number of unreferenced id attributes removed: ' + str(numIDsRemoved) + os.linesep + \ |
3542 | - ' Number of style properties fixed: ' + str(numStylePropsFixed) + os.linesep + \ |
3543 | - ' Number of raster images embedded inline: ' + str(numRastersEmbedded) + os.linesep + \ |
3544 | - ' Number of path segments reduced/removed: ' + str(numPathSegmentsReduced) + os.linesep + \ |
3545 | - ' Number of bytes saved in path data: ' + str(numBytesSavedInPathData) + os.linesep + \ |
3546 | - ' Number of bytes saved in colors: ' + str(numBytesSavedInColors) + os.linesep + \ |
3547 | - ' Number of points removed from polygons: ' + str(numPointsRemovedFromPolygon) + os.linesep + \ |
3548 | - ' Number of bytes saved in comments: ' + str(numCommentBytes) + os.linesep + \ |
3549 | - ' Number of bytes saved in id attributes: ' + str(numBytesSavedInIDs) + os.linesep + \ |
3550 | - ' Number of bytes saved in lengths: ' + str(numBytesSavedInLengths) + os.linesep + \ |
3551 | - ' Number of bytes saved in transformations: ' + str(numBytesSavedInTransforms) |
3552 | - |
3553 | -if __name__ == '__main__': |
3554 | - if sys.platform == "win32": |
3555 | - from time import clock as get_tick |
3556 | - else: |
3557 | - # GZ: is this different from time.time() in any way? |
3558 | - def get_tick(): |
3559 | - return os.times()[0] |
3560 | - |
3561 | - start = get_tick() |
3562 | - |
3563 | - options, (input, output) = parse_args() |
3564 | - |
3565 | - if not options.quiet: |
3566 | - print >>sys.stderr, "%s %s\n%s" % (APP, VER, COPYRIGHT) |
3567 | - |
3568 | - # do the work |
3569 | - in_string = input.read() |
3570 | - out_string = scourString(in_string, options).encode("UTF-8") |
3571 | - output.write(out_string) |
3572 | - |
3573 | - # Close input and output files |
3574 | - input.close() |
3575 | - output.close() |
3576 | - |
3577 | - end = get_tick() |
3578 | - |
3579 | - # GZ: not using globals would be good too |
3580 | - if not options.quiet: |
3581 | - print >>sys.stderr, ' File:', input.name, \ |
3582 | - os.linesep + ' Time taken:', str(end-start) + 's' + os.linesep, \ |
3583 | - getReport() |
3584 | - |
3585 | - oldsize = len(in_string) |
3586 | - newsize = len(out_string) |
3587 | - sizediff = (newsize / oldsize) * 100 |
3588 | - print >>sys.stderr, ' Original file size:', oldsize, 'bytes;', \ |
3589 | - 'new file size:', newsize, 'bytes (' + str(sizediff)[:5] + '%)' |
3590 | |
3591 | === removed file 'share/extensions/scour/svg_regex.py' |
3592 | --- share/extensions/scour/svg_regex.py 2015-09-13 17:09:56 +0000 |
3593 | +++ share/extensions/scour/svg_regex.py 1970-01-01 00:00:00 +0000 |
3594 | @@ -1,285 +0,0 @@ |
3595 | -# This software is OSI Certified Open Source Software. |
3596 | -# OSI Certified is a certification mark of the Open Source Initiative. |
3597 | -# |
3598 | -# Copyright (c) 2006, Enthought, Inc. |
3599 | -# All rights reserved. |
3600 | -# |
3601 | -# Redistribution and use in source and binary forms, with or without |
3602 | -# modification, are permitted provided that the following conditions are met: |
3603 | -# |
3604 | -# * Redistributions of source code must retain the above copyright notice, this |
3605 | -# list of conditions and the following disclaimer. |
3606 | -# * Redistributions in binary form must reproduce the above copyright notice, |
3607 | -# this list of conditions and the following disclaimer in the documentation |
3608 | -# and/or other materials provided with the distribution. |
3609 | -# * Neither the name of Enthought, Inc. nor the names of its contributors may |
3610 | -# be used to endorse or promote products derived from this software without |
3611 | -# specific prior written permission. |
3612 | -# |
3613 | -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
3614 | -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
3615 | -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
3616 | -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR |
3617 | -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
3618 | -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
3619 | -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON |
3620 | -# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
3621 | -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
3622 | -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
3623 | - |
3624 | -""" Small hand-written recursive descent parser for SVG <path> data. |
3625 | - |
3626 | - |
3627 | -In [1]: from svg_regex import svg_parser |
3628 | - |
3629 | -In [3]: svg_parser.parse('M 10,20 30,40V50 60 70') |
3630 | -Out[3]: [('M', [(10.0, 20.0), (30.0, 40.0)]), ('V', [50.0, 60.0, 70.0])] |
3631 | - |
3632 | -In [4]: svg_parser.parse('M 0.6051.5') # An edge case |
3633 | -Out[4]: [('M', [(0.60509999999999997, 0.5)])] |
3634 | - |
3635 | -In [5]: svg_parser.parse('M 100-200') # Another edge case |
3636 | -Out[5]: [('M', [(100.0, -200.0)])] |
3637 | -""" |
3638 | - |
3639 | -import re |
3640 | -from decimal import * |
3641 | - |
3642 | - |
3643 | -# Sentinel. |
3644 | -class _EOF(object): |
3645 | - def __repr__(self): |
3646 | - return 'EOF' |
3647 | -EOF = _EOF() |
3648 | - |
3649 | -lexicon = [ |
3650 | - ('float', r'[-+]?(?:(?:[0-9]*\.[0-9]+)|(?:[0-9]+\.?))(?:[Ee][-+]?[0-9]+)?'), |
3651 | - ('int', r'[-+]?[0-9]+'), |
3652 | - ('command', r'[AaCcHhLlMmQqSsTtVvZz]'), |
3653 | -] |
3654 | - |
3655 | - |
3656 | -class Lexer(object): |
3657 | - """ Break SVG path data into tokens. |
3658 | - |
3659 | - The SVG spec requires that tokens are greedy. This lexer relies on Python's |
3660 | - regexes defaulting to greediness. |
3661 | - |
3662 | - This style of implementation was inspired by this article: |
3663 | - |
3664 | - http://www.gooli.org/blog/a-simple-lexer-in-python/ |
3665 | - """ |
3666 | - def __init__(self, lexicon): |
3667 | - self.lexicon = lexicon |
3668 | - parts = [] |
3669 | - for name, regex in lexicon: |
3670 | - parts.append('(?P<%s>%s)' % (name, regex)) |
3671 | - self.regex_string = '|'.join(parts) |
3672 | - self.regex = re.compile(self.regex_string) |
3673 | - |
3674 | - def lex(self, text): |
3675 | - """ Yield (token_type, str_data) tokens. |
3676 | - |
3677 | - The last token will be (EOF, None) where EOF is the singleton object |
3678 | - defined in this module. |
3679 | - """ |
3680 | - for match in self.regex.finditer(text): |
3681 | - for name, _ in self.lexicon: |
3682 | - m = match.group(name) |
3683 | - if m is not None: |
3684 | - yield (name, m) |
3685 | - break |
3686 | - yield (EOF, None) |
3687 | - |
3688 | -svg_lexer = Lexer(lexicon) |
3689 | - |
3690 | - |
3691 | -class SVGPathParser(object): |
3692 | - """ Parse SVG <path> data into a list of commands. |
3693 | - |
3694 | - Each distinct command will take the form of a tuple (command, data). The |
3695 | - `command` is just the character string that starts the command group in the |
3696 | - <path> data, so 'M' for absolute moveto, 'm' for relative moveto, 'Z' for |
3697 | - closepath, etc. The kind of data it carries with it depends on the command. |
3698 | - For 'Z' (closepath), it's just None. The others are lists of individual |
3699 | - argument groups. Multiple elements in these lists usually mean to repeat the |
3700 | - command. The notable exception is 'M' (moveto) where only the first element |
3701 | - is truly a moveto. The remainder are implicit linetos. |
3702 | - |
3703 | - See the SVG documentation for the interpretation of the individual elements |
3704 | - for each command. |
3705 | - |
3706 | - The main method is `parse(text)`. It can only consume actual strings, not |
3707 | - filelike objects or iterators. |
3708 | - """ |
3709 | - |
3710 | - def __init__(self, lexer=svg_lexer): |
3711 | - self.lexer = lexer |
3712 | - |
3713 | - self.command_dispatch = { |
3714 | - 'Z': self.rule_closepath, |
3715 | - 'z': self.rule_closepath, |
3716 | - 'M': self.rule_moveto_or_lineto, |
3717 | - 'm': self.rule_moveto_or_lineto, |
3718 | - 'L': self.rule_moveto_or_lineto, |
3719 | - 'l': self.rule_moveto_or_lineto, |
3720 | - 'H': self.rule_orthogonal_lineto, |
3721 | - 'h': self.rule_orthogonal_lineto, |
3722 | - 'V': self.rule_orthogonal_lineto, |
3723 | - 'v': self.rule_orthogonal_lineto, |
3724 | - 'C': self.rule_curveto3, |
3725 | - 'c': self.rule_curveto3, |
3726 | - 'S': self.rule_curveto2, |
3727 | - 's': self.rule_curveto2, |
3728 | - 'Q': self.rule_curveto2, |
3729 | - 'q': self.rule_curveto2, |
3730 | - 'T': self.rule_curveto1, |
3731 | - 't': self.rule_curveto1, |
3732 | - 'A': self.rule_elliptical_arc, |
3733 | - 'a': self.rule_elliptical_arc, |
3734 | - } |
3735 | - |
3736 | -# self.number_tokens = set(['int', 'float']) |
3737 | - self.number_tokens = list(['int', 'float']) |
3738 | - |
3739 | - def parse(self, text): |
3740 | - """ Parse a string of SVG <path> data. |
3741 | - """ |
3742 | - next = self.lexer.lex(text).next |
3743 | - token = next() |
3744 | - return self.rule_svg_path(next, token) |
3745 | - |
3746 | - def rule_svg_path(self, next, token): |
3747 | - commands = [] |
3748 | - while token[0] is not EOF: |
3749 | - if token[0] != 'command': |
3750 | - raise SyntaxError("expecting a command; got %r" % (token,)) |
3751 | - rule = self.command_dispatch[token[1]] |
3752 | - command_group, token = rule(next, token) |
3753 | - commands.append(command_group) |
3754 | - return commands |
3755 | - |
3756 | - def rule_closepath(self, next, token): |
3757 | - command = token[1] |
3758 | - token = next() |
3759 | - return (command, []), token |
3760 | - |
3761 | - def rule_moveto_or_lineto(self, next, token): |
3762 | - command = token[1] |
3763 | - token = next() |
3764 | - coordinates = [] |
3765 | - while token[0] in self.number_tokens: |
3766 | - pair, token = self.rule_coordinate_pair(next, token) |
3767 | - coordinates.extend(pair) |
3768 | - return (command, coordinates), token |
3769 | - |
3770 | - def rule_orthogonal_lineto(self, next, token): |
3771 | - command = token[1] |
3772 | - token = next() |
3773 | - coordinates = [] |
3774 | - while token[0] in self.number_tokens: |
3775 | - coord, token = self.rule_coordinate(next, token) |
3776 | - coordinates.append(coord) |
3777 | - return (command, coordinates), token |
3778 | - |
3779 | - def rule_curveto3(self, next, token): |
3780 | - command = token[1] |
3781 | - token = next() |
3782 | - coordinates = [] |
3783 | - while token[0] in self.number_tokens: |
3784 | - pair1, token = self.rule_coordinate_pair(next, token) |
3785 | - pair2, token = self.rule_coordinate_pair(next, token) |
3786 | - pair3, token = self.rule_coordinate_pair(next, token) |
3787 | - coordinates.extend(pair1) |
3788 | - coordinates.extend(pair2) |
3789 | - coordinates.extend(pair3) |
3790 | - return (command, coordinates), token |
3791 | - |
3792 | - def rule_curveto2(self, next, token): |
3793 | - command = token[1] |
3794 | - token = next() |
3795 | - coordinates = [] |
3796 | - while token[0] in self.number_tokens: |
3797 | - pair1, token = self.rule_coordinate_pair(next, token) |
3798 | - pair2, token = self.rule_coordinate_pair(next, token) |
3799 | - coordinates.extend(pair1) |
3800 | - coordinates.extend(pair2) |
3801 | - return (command, coordinates), token |
3802 | - |
3803 | - def rule_curveto1(self, next, token): |
3804 | - command = token[1] |
3805 | - token = next() |
3806 | - coordinates = [] |
3807 | - while token[0] in self.number_tokens: |
3808 | - pair1, token = self.rule_coordinate_pair(next, token) |
3809 | - coordinates.extend(pair1) |
3810 | - return (command, coordinates), token |
3811 | - |
3812 | - def rule_elliptical_arc(self, next, token): |
3813 | - command = token[1] |
3814 | - token = next() |
3815 | - arguments = [] |
3816 | - while token[0] in self.number_tokens: |
3817 | - rx = Decimal(token[1]) * 1 |
3818 | - if rx < Decimal("0.0"): |
3819 | - raise SyntaxError("expecting a nonnegative number; got %r" % (token,)) |
3820 | - |
3821 | - token = next() |
3822 | - if token[0] not in self.number_tokens: |
3823 | - raise SyntaxError("expecting a number; got %r" % (token,)) |
3824 | - ry = Decimal(token[1]) * 1 |
3825 | - if ry < Decimal("0.0"): |
3826 | - raise SyntaxError("expecting a nonnegative number; got %r" % (token,)) |
3827 | - |
3828 | - token = next() |
3829 | - if token[0] not in self.number_tokens: |
3830 | - raise SyntaxError("expecting a number; got %r" % (token,)) |
3831 | - axis_rotation = Decimal(token[1]) * 1 |
3832 | - |
3833 | - token = next() |
3834 | - if token[1] not in ('0', '1'): |
3835 | - raise SyntaxError("expecting a boolean flag; got %r" % (token,)) |
3836 | - large_arc_flag = Decimal(token[1]) * 1 |
3837 | - |
3838 | - token = next() |
3839 | - if token[1] not in ('0', '1'): |
3840 | - raise SyntaxError("expecting a boolean flag; got %r" % (token,)) |
3841 | - sweep_flag = Decimal(token[1]) * 1 |
3842 | - |
3843 | - token = next() |
3844 | - if token[0] not in self.number_tokens: |
3845 | - raise SyntaxError("expecting a number; got %r" % (token,)) |
3846 | - x = Decimal(token[1]) * 1 |
3847 | - |
3848 | - token = next() |
3849 | - if token[0] not in self.number_tokens: |
3850 | - raise SyntaxError("expecting a number; got %r" % (token,)) |
3851 | - y = Decimal(token[1]) * 1 |
3852 | - |
3853 | - token = next() |
3854 | - arguments.extend([rx, ry, axis_rotation, large_arc_flag, sweep_flag, x, y]) |
3855 | - |
3856 | - return (command, arguments), token |
3857 | - |
3858 | - def rule_coordinate(self, next, token): |
3859 | - if token[0] not in self.number_tokens: |
3860 | - raise SyntaxError("expecting a number; got %r" % (token,)) |
3861 | - x = getcontext().create_decimal(token[1]) |
3862 | - token = next() |
3863 | - return x, token |
3864 | - |
3865 | - |
3866 | - def rule_coordinate_pair(self, next, token): |
3867 | - # Inline these since this rule is so common. |
3868 | - if token[0] not in self.number_tokens: |
3869 | - raise SyntaxError("expecting a number; got %r" % (token,)) |
3870 | - x = getcontext().create_decimal(token[1]) |
3871 | - token = next() |
3872 | - if token[0] not in self.number_tokens: |
3873 | - raise SyntaxError("expecting a number; got %r" % (token,)) |
3874 | - y = getcontext().create_decimal(token[1]) |
3875 | - token = next() |
3876 | - return [x, y], token |
3877 | - |
3878 | - |
3879 | -svg_parser = SVGPathParser() |
3880 | |
3881 | === removed file 'share/extensions/scour/svg_transform.py' |
3882 | --- share/extensions/scour/svg_transform.py 2015-09-13 17:09:56 +0000 |
3883 | +++ share/extensions/scour/svg_transform.py 1970-01-01 00:00:00 +0000 |
3884 | @@ -1,235 +0,0 @@ |
3885 | -# -*- coding: utf-8 -*- |
3886 | - |
3887 | -# SVG transformation list parser |
3888 | -# |
3889 | -# Copyright 2010 Louis Simard |
3890 | -# |
3891 | -# This file is part of Scour, http://www.codedread.com/scour/ |
3892 | -# |
3893 | -# This library is free software; you can redistribute it and/or modify |
3894 | -# it either under the terms of the Apache License, Version 2.0, or, at |
3895 | -# your option, under the terms and conditions of the GNU General |
3896 | -# Public License, Version 2 or newer as published by the Free Software |
3897 | -# Foundation. You may obtain a copy of these Licenses at: |
3898 | -# |
3899 | -# http://www.apache.org/licenses/LICENSE-2.0 |
3900 | -# https://www.gnu.org/licenses/old-licenses/gpl-2.0.html |
3901 | -# |
3902 | -# Unless required by applicable law or agreed to in writing, software |
3903 | -# distributed under the License is distributed on an "AS IS" BASIS, |
3904 | -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
3905 | -# See the License for the specific language governing permissions and |
3906 | -# limitations under the License. |
3907 | - |
3908 | -""" Small recursive descent parser for SVG transform="" data. |
3909 | - |
3910 | - |
3911 | -In [1]: from svg_transform import svg_transform_parser |
3912 | - |
3913 | -In [3]: svg_transform_parser.parse('translate(50, 50)') |
3914 | -Out[3]: [('translate', [50.0, 50.0])] |
3915 | - |
3916 | -In [4]: svg_transform_parser.parse('translate(50)') |
3917 | -Out[4]: [('translate', [50.0])] |
3918 | - |
3919 | -In [5]: svg_transform_parser.parse('rotate(36 50,50)') |
3920 | -Out[5]: [('rotate', [36.0, 50.0, 50.0])] |
3921 | - |
3922 | -In [6]: svg_transform_parser.parse('rotate(36)') |
3923 | -Out[6]: [('rotate', [36.0])] |
3924 | - |
3925 | -In [7]: svg_transform_parser.parse('skewX(20)') |
3926 | -Out[7]: [('skewX', [20.0])] |
3927 | - |
3928 | -In [8]: svg_transform_parser.parse('skewY(40)') |
3929 | -Out[8]: [('skewX', [20.0])] |
3930 | - |
3931 | -In [9]: svg_transform_parser.parse('scale(2 .5)') |
3932 | -Out[9]: [('scale', [2.0, 0.5])] |
3933 | - |
3934 | -In [10]: svg_transform_parser.parse('scale(.5)') |
3935 | -Out[10]: [('scale', [0.5])] |
3936 | - |
3937 | -In [11]: svg_transform_parser.parse('matrix(1 0 50 0 1 80)') |
3938 | -Out[11]: [('matrix', [1.0, 0.0, 50.0, 0.0, 1.0, 80.0])] |
3939 | - |
3940 | -Multiple transformations are supported: |
3941 | - |
3942 | -In [12]: svg_transform_parser.parse('translate(30 -30) rotate(36)') |
3943 | -Out[12]: [('translate', [30.0, -30.0]), ('rotate', [36.0])] |
3944 | -""" |
3945 | - |
3946 | -import re |
3947 | -from decimal import * |
3948 | - |
3949 | - |
3950 | -# Sentinel. |
3951 | -class _EOF(object): |
3952 | - def __repr__(self): |
3953 | - return 'EOF' |
3954 | -EOF = _EOF() |
3955 | - |
3956 | -lexicon = [ |
3957 | - ('float', r'[-+]?(?:(?:[0-9]*\.[0-9]+)|(?:[0-9]+\.?))(?:[Ee][-+]?[0-9]+)?'), |
3958 | - ('int', r'[-+]?[0-9]+'), |
3959 | - ('command', r'(?:matrix|translate|scale|rotate|skew[XY])'), |
3960 | - ('coordstart', r'\('), |
3961 | - ('coordend', r'\)'), |
3962 | -] |
3963 | - |
3964 | - |
3965 | -class Lexer(object): |
3966 | - """ Break SVG path data into tokens. |
3967 | - |
3968 | - The SVG spec requires that tokens are greedy. This lexer relies on Python's |
3969 | - regexes defaulting to greediness. |
3970 | - |
3971 | - This style of implementation was inspired by this article: |
3972 | - |
3973 | - http://www.gooli.org/blog/a-simple-lexer-in-python/ |
3974 | - """ |
3975 | - def __init__(self, lexicon): |
3976 | - self.lexicon = lexicon |
3977 | - parts = [] |
3978 | - for name, regex in lexicon: |
3979 | - parts.append('(?P<%s>%s)' % (name, regex)) |
3980 | - self.regex_string = '|'.join(parts) |
3981 | - self.regex = re.compile(self.regex_string) |
3982 | - |
3983 | - def lex(self, text): |
3984 | - """ Yield (token_type, str_data) tokens. |
3985 | - |
3986 | - The last token will be (EOF, None) where EOF is the singleton object |
3987 | - defined in this module. |
3988 | - """ |
3989 | - for match in self.regex.finditer(text): |
3990 | - for name, _ in self.lexicon: |
3991 | - m = match.group(name) |
3992 | - if m is not None: |
3993 | - yield (name, m) |
3994 | - break |
3995 | - yield (EOF, None) |
3996 | - |
3997 | -svg_lexer = Lexer(lexicon) |
3998 | - |
3999 | - |
4000 | -class SVGTransformationParser(object): |
4001 | - """ Parse SVG transform="" data into a list of commands. |
4002 | - |
4003 | - Each distinct command will take the form of a tuple (type, data). The |
4004 | - `type` is the character string that defines the type of transformation in the |
4005 | - transform data, so either of "translate", "rotate", "scale", "matrix", |
4006 | - "skewX" and "skewY". Data is always a list of numbers contained within the |
4007 | - transformation's parentheses. |
4008 | - |
4009 | - See the SVG documentation for the interpretation of the individual elements |
4010 | - for each transformation. |
4011 | - |
4012 | - The main method is `parse(text)`. It can only consume actual strings, not |
4013 | - filelike objects or iterators. |
4014 | - """ |
4015 | - |
4016 | - def __init__(self, lexer=svg_lexer): |
4017 | - self.lexer = lexer |
4018 | - |
4019 | - self.command_dispatch = { |
4020 | - 'translate': self.rule_1or2numbers, |
4021 | - 'scale': self.rule_1or2numbers, |
4022 | - 'skewX': self.rule_1number, |
4023 | - 'skewY': self.rule_1number, |
4024 | - 'rotate': self.rule_1or3numbers, |
4025 | - 'matrix': self.rule_6numbers, |
4026 | - } |
4027 | - |
4028 | -# self.number_tokens = set(['int', 'float']) |
4029 | - self.number_tokens = list(['int', 'float']) |
4030 | - |
4031 | - def parse(self, text): |
4032 | - """ Parse a string of SVG transform="" data. |
4033 | - """ |
4034 | - next = self.lexer.lex(text).next |
4035 | - commands = [] |
4036 | - token = next() |
4037 | - while token[0] is not EOF: |
4038 | - command, token = self.rule_svg_transform(next, token) |
4039 | - commands.append(command) |
4040 | - return commands |
4041 | - |
4042 | - def rule_svg_transform(self, next, token): |
4043 | - if token[0] != 'command': |
4044 | - raise SyntaxError("expecting a transformation type; got %r" % (token,)) |
4045 | - command = token[1] |
4046 | - rule = self.command_dispatch[command] |
4047 | - token = next() |
4048 | - if token[0] != 'coordstart': |
4049 | - raise SyntaxError("expecting '('; got %r" % (token,)) |
4050 | - numbers, token = rule(next, token) |
4051 | - if token[0] != 'coordend': |
4052 | - raise SyntaxError("expecting ')'; got %r" % (token,)) |
4053 | - token = next() |
4054 | - return (command, numbers), token |
4055 | - |
4056 | - def rule_1or2numbers(self, next, token): |
4057 | - numbers = [] |
4058 | - # 1st number is mandatory |
4059 | - token = next() |
4060 | - number, token = self.rule_number(next, token) |
4061 | - numbers.append(number) |
4062 | - # 2nd number is optional |
4063 | - number, token = self.rule_optional_number(next, token) |
4064 | - if number is not None: |
4065 | - numbers.append(number) |
4066 | - |
4067 | - return numbers, token |
4068 | - |
4069 | - def rule_1number(self, next, token): |
4070 | - # this number is mandatory |
4071 | - token = next() |
4072 | - number, token = self.rule_number(next, token) |
4073 | - numbers = [number] |
4074 | - return numbers, token |
4075 | - |
4076 | - def rule_1or3numbers(self, next, token): |
4077 | - numbers = [] |
4078 | - # 1st number is mandatory |
4079 | - token = next() |
4080 | - number, token = self.rule_number(next, token) |
4081 | - numbers.append(number) |
4082 | - # 2nd number is optional |
4083 | - number, token = self.rule_optional_number(next, token) |
4084 | - if number is not None: |
4085 | - # but, if the 2nd number is provided, the 3rd is mandatory. |
4086 | - # we can't have just 2. |
4087 | - numbers.append(number) |
4088 | - |
4089 | - number, token = self.rule_number(next, token) |
4090 | - numbers.append(number) |
4091 | - |
4092 | - return numbers, token |
4093 | - |
4094 | - def rule_6numbers(self, next, token): |
4095 | - numbers = [] |
4096 | - token = next() |
4097 | - # all numbers are mandatory |
4098 | - for i in xrange(6): |
4099 | - number, token = self.rule_number(next, token) |
4100 | - numbers.append(number) |
4101 | - return numbers, token |
4102 | - |
4103 | - def rule_number(self, next, token): |
4104 | - if token[0] not in self.number_tokens: |
4105 | - raise SyntaxError("expecting a number; got %r" % (token,)) |
4106 | - x = Decimal(token[1]) * 1 |
4107 | - token = next() |
4108 | - return x, token |
4109 | - |
4110 | - def rule_optional_number(self, next, token): |
4111 | - if token[0] not in self.number_tokens: |
4112 | - return None, token |
4113 | - else: |
4114 | - x = Decimal(token[1]) * 1 |
4115 | - token = next() |
4116 | - return x, token |
4117 | - |
4118 | - |
4119 | -svg_transform_parser = SVGTransformationParser() |
4120 | |
4121 | === removed file 'share/extensions/scour/yocto_css.py' |
4122 | --- share/extensions/scour/yocto_css.py 2015-09-13 17:09:56 +0000 |
4123 | +++ share/extensions/scour/yocto_css.py 1970-01-01 00:00:00 +0000 |
4124 | @@ -1,74 +0,0 @@ |
4125 | -# -*- coding: utf-8 -*- |
4126 | - |
4127 | -# yocto-css, an extremely bare minimum CSS parser |
4128 | -# |
4129 | -# Copyright 2009 Jeff Schiller |
4130 | -# |
4131 | -# This file is part of Scour, http://www.codedread.com/scour/ |
4132 | -# |
4133 | -# This library is free software; you can redistribute it and/or modify |
4134 | -# it either under the terms of the Apache License, Version 2.0, or, at |
4135 | -# your option, under the terms and conditions of the GNU General |
4136 | -# Public License, Version 2 or newer as published by the Free Software |
4137 | -# Foundation. You may obtain a copy of these Licenses at: |
4138 | -# |
4139 | -# http://www.apache.org/licenses/LICENSE-2.0 |
4140 | -# https://www.gnu.org/licenses/old-licenses/gpl-2.0.html |
4141 | -# |
4142 | -# Unless required by applicable law or agreed to in writing, software |
4143 | -# distributed under the License is distributed on an "AS IS" BASIS, |
4144 | -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
4145 | -# See the License for the specific language governing permissions and |
4146 | -# limitations under the License. |
4147 | - |
4148 | -# In order to resolve Bug 368716 (https://bugs.launchpad.net/scour/+bug/368716) |
4149 | -# scour needed a bare-minimum CSS parser in order to determine if some elements |
4150 | -# were still referenced by CSS properties. |
4151 | - |
4152 | -# I looked at css-py (a CSS parser built in Python), but that library |
4153 | -# is about 35k of Python and requires ply to be installed. I just need |
4154 | -# something very basic to suit scour's needs. |
4155 | - |
4156 | -# yocto-css takes a string of CSS and tries to spit out a list of rules |
4157 | -# A rule is an associative array (dictionary) with the following keys: |
4158 | -# - selector: contains the string of the selector (see CSS grammar) |
4159 | -# - properties: contains an associative array of CSS properties for this rule |
4160 | - |
4161 | -# TODO: need to build up some unit tests for yocto_css |
4162 | - |
4163 | -# stylesheet : [ CDO | CDC | S | statement ]*; |
4164 | -# statement : ruleset | at-rule; |
4165 | -# at-rule : ATKEYWORD S* any* [ block | ';' S* ]; |
4166 | -# block : '{' S* [ any | block | ATKEYWORD S* | ';' S* ]* '}' S*; |
4167 | -# ruleset : selector? '{' S* declaration? [ ';' S* declaration? ]* '}' S*; |
4168 | -# selector : any+; |
4169 | -# declaration : property S* ':' S* value; |
4170 | -# property : IDENT; |
4171 | -# value : [ any | block | ATKEYWORD S* ]+; |
4172 | -# any : [ IDENT | NUMBER | PERCENTAGE | DIMENSION | STRING |
4173 | -# | DELIM | URI | HASH | UNICODE-RANGE | INCLUDES |
4174 | -# | DASHMATCH | FUNCTION S* any* ')' |
4175 | -# | '(' S* any* ')' | '[' S* any* ']' ] S*; |
4176 | - |
4177 | -def parseCssString(str): |
4178 | - rules = [] |
4179 | - # first, split on } to get the rule chunks |
4180 | - chunks = str.split('}') |
4181 | - for chunk in chunks: |
4182 | - # second, split on { to get the selector and the list of properties |
4183 | - bits = chunk.split('{') |
4184 | - if len(bits) != 2: continue |
4185 | - rule = {} |
4186 | - rule['selector'] = bits[0].strip() |
4187 | - # third, split on ; to get the property declarations |
4188 | - bites = bits[1].strip().split(';') |
4189 | - if len(bites) < 1: continue |
4190 | - props = {} |
4191 | - for bite in bites: |
4192 | - # fourth, split on : to get the property name and value |
4193 | - nibbles = bite.strip().split(':') |
4194 | - if len(nibbles) != 2: continue |
4195 | - props[nibbles[0].strip()] = nibbles[1].strip() |
4196 | - rule['properties'] = props |
4197 | - rules.append(rule) |
4198 | - return rules |
For reviewers: Please note this diff contains a file move: extensions/ scour/scour. inkscape. py' => 'share/ extensions/ scour.inkscape. py'
'share/
Please make sure the file is properly moved when manually applying the patch.