Retagging <line>, <rect>, <circle> and the other shapes as <path> broke
<style> rules that select by element name. In t2.svg, line.css{stroke:
#e33} and circle{fill:#3c6} stopped matching, so the red line vanished
and the green circle went black. Rules for path went the other way:
path{fill:none} began to empty every converted circle and rect.
Copying each rule to a selector that matches the converted path cannot
keep its specificity: :where() and :is() would, but librsvg 2.63 ignores
both. A copied rule path[data-rough-shape="circle"] (0,1,1) then beats a
class rule (0,1,0), so in
<style>circle{fill:#c00} .blue{fill:#06c}</style>
<circle cx="75" cy="75" r="50"/>
<circle class="blue" cx="225" cy="75" r="50"/>
both circles came out red. Rewriting path to path:not([data-rough-shape])
raised path rules from (0,0,1) to (0,1,1) in the same way, so with
path{fill:#c00} .x{fill:#06c}, a real <path class="x"> turned red as soon
as the drawing also had a shape to convert.
The stylesheet is now left as it is. Each element's matching rules are
found once before any shape changes and once after, and where they
differ, the value the original cascade gave each property those rules
declare is written back onto the element: the first circle above gets
fill="#c00", the blue one is left alone. If a rule the matcher sees
still sets the property on the path, the value goes into the style
attribute instead, with !important when such a rule is !important, so
path{stroke-dasharray:4} does not reach converted shapes. A property the
original did not get at all is written as inherit, or as its initial
value (opacity:1) if it is not inherited; unset and initial are not
used, because librsvg 2.63 ignores both and cairosvg reads unset as
initial. Values rough.py sets itself, fill:none on lines and marker:none
on shapes, are kept.
Writing the value as a presentation attribute where possible keeps it
below any rule the matcher does not see. A rule with another
pseudo-class that still matches the path, such as .a:nth-child(3) or
.a:not(.b), still wins over it. A rule that names the old tag with such a
pseudo-class, circle:nth-child(2){fill:#0a0}, is still lost, as before.
Rules inside @media blocks are not matched, as in librsvg and cairosvg,
so a type rule in one, such as circle{fill:#fff} in
@media (prefers-color-scheme: dark), stops reaching converted shapes in
a browser.
A size given with the font shorthand, as in .head { font: bold 40px/1
serif } or style="font: italic 36px serif", was not read, so both
headlines were handled as 16px text: calm shaking and no edge filter.
Worse, style="font: 12px sans-serif" next to font-size="40" was treated
as 40-unit text, although the shorthand in the style attribute wins and
the text renders at 12.
The shorthand now counts as a font-size declaration, in the style
attribute and in stylesheet rules alike: the first word that is a size
keyword (large, smaller and so on) or a length with a unit, with any
/line-height after it dropped.
The text, marker, fill and rem fixes only saw the style attribute,
presentation attributes and inheritance, so values set by a <style>
rule were missed:
- poster.svg sets font-size: 72px on its title through the .title class,
and the title was handled as 16px text: calm shaking and no edge
filter.
- In r11.svg a polyline gets its markers from .m { marker: url(#dot) },
and its 2 mid dots grew to 20 as the jitter cut its edges into
pieces.
- In f1.svg the straight paths without a fill came out with black
slivers along them, because any document with a stylesheet was left
without fill="none", in case a rule filled an ancestor.
- With :root { font-size: 40px }, rem still counted as 16 px, so tspans
with dy="1rem" stepped 16 units instead of 40 and overlapped.
Stylesheet rules are now matched against elements with a small engine
for type, class, id, attribute, :root, :first-child and :last-child with
any combinator. Each element is matched once, against the document as
it was read, so a shape that has already turned into a path does not
change what its siblings match. A property comes from the cascade:
!important in the style attribute, then !important rules by specificity
and order, then the style attribute, then the other rules, then the
presentation attribute, then the parent.
Not matched: rules with other pseudo-classes (:hover, :nth-child,
:not() and so on), and rules inside @media or any other at-rule block.
librsvg 2.63 and cairosvg both ignore @media blocks, even @media screen,
so leaving them out follows what they draw. With rules resolved, the
fill check sees a fill set by a stylesheet (f1.svg: the .blue class)
and leaves it, and only fills the matcher cannot see are left to the
renderer: a fill set only by a :hover rule, say, still overrides the
added attribute, as it should.
ElementTree opens the output in text mode, so on Windows every newline in the SVG became CRLF and the same input and seed gave different bytes than on Linux (209 of 242 test files differed only in line endings). Open the file ourselves as UTF-8 with newline='\n' and hand it to ElementTree.
On Windows, stdout through a pipe uses the ANSI code page. When the output path has a character outside it, such as 'Łódź.svg' under cp1252, the closing 'wrote ...' line raised UnicodeEncodeError and rough.py exited 1 after the file had already been written, so a caller trusting the exit code thought it failed. moves.py and check.py already write stdout as UTF-8; do the same here.
rem lengths were always 16 px. With style="font-size: 40px" on the root
<svg>, a circle with r="1.5rem" should have radius 60 and tspans with
dy="1rem" should step 40 units; rough.py drew radius 24 and stepped 16,
and the two lines of text overlapped.
The root <svg>'s font-size is now read once, from its style attribute or
its font-size attribute, and every rem in coordinates, dy and font sizes
is resolved against it. Without one it stays 16 px. Checked: a
font-size="20" attribute gives 20, style="font-size:2rem" gives 32,
none gives 16.
librsvg 2.63 does not draw rem in geometry attributes at all (the
original renders without its circle and rect), so the converted output,
which has plain numbers, now shows them at the size a browser would.
shake() returned early when dy held more than one value, a check from
upstream 7f92b83, so text whose author had placed letters one by one
(dy.svg: dy="0 -10 -10 20 20 -20" on WAVE ON, dy="0,0.25em,..." on
STEPS AND) got no baseline jitter at all.
Each listed value is now resolved as a length (em against the element's
font-size, % against the canvas height) and the small offsets are added
on top of it. When the list is shorter than the text the missing entries
count as 0, as SVG says for dx/dy (the last value does not repeat);
values beyond the last character are kept as they are, since SVG ignores
them. x, y, dx and rotate lists are not changed; rotate is still only
added when the author has none.
Rendered with cairosvg, because librsvg ignores per-letter dy lists: the
author's wave and steps are unchanged and the letters get the same small
shake as single-valued text.
Bad input ended in a traceback: an empty file (empty.svg), an undefined
entity such as (nbsp.svg) or an external one (ext.svg), a
billion-laughs file (laughs.svg) and a gzip-compressed .svgz all died
with xml.etree.ElementTree.ParseError, and a missing input or an output
in a missing folder with FileNotFoundError.
The input is now read as bytes and parsed in read_svg(), which uses the
same wording check.py uses on branch fix/check: "cannot open <file>:
<reason>", "<file> is gzip-compressed (svgz); unzip it to a plain .svg
first" and "<file> is not valid SVG XML: <parser message>". Writing
the output reports "cannot write <file>: <reason>". Each message starts
with rough.py: like the script's other errors, and the exit code is 1.
Checked on Python 3.9 and 3.15 with the files above, a directory given
as input or output, a file without read permission and a read-only
output folder.
An open <path> or <polyline> with no fill set anywhere is filled black by
default, but draws nothing while its points lie on one line, because the
fill encloses no area. Once jitter moves the points off that line the
fill appears: M40 580 L360 580 in scaled.svg came out as a hairline with
black slivers along it.
Such an element now gets fill="none" before it is roughened, but only
when every subpath is open (no Z) and all its points, control points
included, lie on one straight line, and no fill comes from an attribute,
the style attribute or an ancestor.
Left alone on purpose: any fill that is set (a fill="#c33" attribute,
fill inherited from a group), because the author asked for it even if it
was invisible; open curves and bent polylines, which do enclose area and
already render filled; and closed subpaths. A document with a non-empty
<style> element is left alone entirely, f1.svg among them: a rule there
may fill an ancestor, and without reading the rules the added attribute
could override the fill the element inherits from it.
<use> elements were walked past without change, so marks repeated with
<use>, the usual way to stamp the same tick, dot or tile many times,
stayed on their exact even spacing (r13d.svg: twelve ticks every 20
units), although visuals.md says rough.py moves repeated marks off it.
Each <use> now gets the same small whole-shape offset that small circles
and lines get: a translate in its parent's coordinates, sized by the
parent's scale, put in front of any transform it already has. The
referenced content itself is shared by all copies, so the copies move
but do not change shape.
Circles and ellipses became closed polygons of 12 to 160 straight
segments. At full size the facets show (r13c.svg: the r=150 circle's
outline is a ring of visible corners and kinks), which reads as a
plotted polygon rather than a hand-drawn curve.
They are now 8 to 24 jittered points joined by a closed Catmull-Rom
spline written as cubic Beziers, so the outline stays round between the
points. The radial noise is the same as before; the three-lobe
distortion of 1.5% now grows with --amount, so --amount 0 leaves the
shape round (renders within 0.02% of the pixels of the original circle)
instead of keeping the lobes. The files stay about the same size.
rect() returned early whenever rx or ry was set, so every rounded rect,
a common shape in posters and cards, stayed perfectly clean (r13b.svg:
five rounded rects, none touched).
A rounded rect is now built as four straight sides and four quarter-
ellipse cubics, with rx and ry resolved as lengths, a missing or auto
radius taken from the other one, and both clamped to half the width and
height as SVG does. The outline then goes through the same jitter as a
path. At --amount 0 it renders the same as the original rect.
Two details found on the way: a side of zero length (a pill whose
straight part vanishes) is dropped, since jittering the same point twice
drew a spike; and in any path, a segment that ends exactly at the start
of its subpath now reuses the jittered start point, which removes the
small kink where a closed outline met itself.
Arc commands were copied through with only their end point moved, so
every A in a path stayed a perfect circular or elliptical arc, while
visuals.md says rough.py breaks curves. In r13a.svg the half circle, the
rotated ellipse and the chain of arcs came out machine smooth.
parse_path() now converts each arc to cubic Beziers of at most a quarter
turn, using the centre parameterisation from the SVG implementation
notes (radii scaled up when too small, zero radii drawn as a straight
segment). The cubics then go through the same jitter as other curves.
At --amount 0 the converted arcs render the same as the originals. An arc
with non-finite or absurd radii falls under the existing size check and
leaves the path unchanged.
Every point the jitter inserts is a vertex, and marker-mid draws a marker
at every vertex. In marker.svg the polyline with marker-mid="url(#dot)"
went from 2 mid dots to about 20, and in r11.svg the same happened to a
path whose marker-mid was inherited from its group. Circles and rects
inside that group, which never draw markers, sprouted a dot at every
point once they became paths.
A path, line, polyline or polygon whose marker-mid is set, directly, in
its style attribute (also through the marker shorthand) or inherited, now
keeps its own vertices: they are still jittered, but edges are not cut
into pieces and curves are not split. Rects, circles and ellipses that
inherit any marker get marker:none in their style when they become
paths, as they never showed markers before. Markers set by <style> rules
are not seen yet.
Text was sorted into calm, medium and strong shaking by fixed sizes (16
and 32 user units) and got the rough-edge filter from 28 units, with
baseFrequency fixed at 0.9 per user unit. So the same design drawn at
0.25x, 1x and 10x coordinates (sc025.svg, sc1.svg, sc10.svg) was treated
three ways: at 0.25x the 44-unit title shrank to 11 units, was kept calm
and got no edge filter.
Sizes are now measured against a 720-unit canvas diagonal in the text's
local units, so the thresholds keep their meaning on a 400x600 poster and
scale with everything else. The filter's baseFrequency and displacement
follow the same scale, with one filter per distinct scale. Font sizes
come from the style attribute, then the font-size attribute, then the
parent, through nested tspans as well; keywords such as large and smaller
count. After the change the three sc files get identical rotations and
the same filter relative to their size.
Points within 1 user unit of the canvas edge were pushed out by their
jitter plus 1 unit, and every coordinate was rounded to 2 decimals. Both
are absolute. In unit.svg (viewBox 0 0 1 1) the whole canvas counts as
the edge: the white line and the green square were pushed off the
canvas, and 0.01 rounding put visible steps in the circle. In icon24.svg
(viewBox 0 0 24 24) a 1-unit push is 4% of the icon.
The edge band is now 1/720 of the current viewport's diagonal (1 unit on
a 400x600 canvas, as before), and numbers keep enough decimals for
1/72000 of the canvas diagonal in the local units: 2 on 400x600, 5 on a
1x1 viewBox, 1 on a 10x canvas. The amp in the closing message is shown
to 3 significant digits instead of 2 decimals, so it no longer reads
0.00 on small canvases.
The amplitude came from the root viewBox only, in root user units, and
was applied unchanged in every local coordinate system. In scaled.svg a
24-unit icon drawn inside scale(6), and the same icon in a nested
<svg viewBox="0 0 24 24"> 240 wide, got 6 and 10 times the intended
shake: the square turned into a skewed quad and the circle into a blob.
The nested <svg> also kept the outer canvas for its edge rule and for
resolving %.
The walk now tracks how large one local unit is in root units. Each
transform list is multiplied out and its largest singular value taken,
so a non-uniform scale never shakes harder than intended in any
direction; a nested <svg> adds its viewBox scale (meet, slice or none),
becomes the box for % lengths and edge snapping, and counts as a free
canvas edge again since it clips. Jitter, the step floor and the size
limit are divided by that scale. The small whole-shape offset is a
translate in the parent's system, so it uses the parent's scale.
Groups with a singular transform such as scale(0) draw nothing and are
skipped.
line x1..y2, rect x/y/width/height and circle or ellipse cx/cy/r/rx/ry
were read with fnum(), which drops the unit. In r4.svg a line from 5% to
95% across a 400-wide canvas became a line from 5 to 95, and a circle
with r=10% shrank to radius 10. t2.svg had the same with x2="100%".
Rects with a % width were skipped outright.
These attributes now go through the same length resolver as dy: % against
the canvas width or height, or for r against the diagonal divided by
sqrt 2 as SVG defines it, em and ex against the element's font-size, and
the absolute units converted to user units. Full-canvas rects given as
100% are still recognised as the background and left alone.
shake() read a tspan's own dy with fnum(), which keeps only the number,
so dy="1.2em" in t1.svg (font-size 40) became 1.2 user units instead of
48. The three lines FIRST, SECOND and THIRD were drawn on top of each
other.
dy is now resolved as a length: em and ex against the element's own
font-size, % against the canvas height, and px, pt, pc, mm, cm, in, Q
and rem converted to user units. An unknown unit counts as 0, as SVG
does for an invalid length. Font sizes given in em or % are resolved
against the inherited size the same way, instead of being read as bare
numbers.
A <line> is never filled, but the <path> it was turned into is. With the
default black fill, or a fill inherited from a group or set in its own
style, the jittered line drew a filled sliver between its points (r2.svg
at --amount 2: black, red and blue wedges along three hairlines).
The converted line now gets fill:none in its style attribute. It goes in
the style attribute rather than a fill attribute, so that a stylesheet
rule such as path{fill:red} cannot fill it again.
The finding also named <polyline>, but a polyline is filled in SVG just
like the open path it becomes (the black wedge under the polyline in
r2.svg renders the same before and after), so it is left as it is.
to_path() called el.clear(), which also drops child elements, text and
tail. In t2.svg the <title>tooltip</title> inside a circle was lost, and
so were <desc>, <animate> and <set> children; the cleared tail also
pulled every following element onto one line.
Only the geometry attributes are now removed before the tag changes, so
children and whitespace stay. A shape whose geometry is animated (an
<animate> or <set> child whose attributeName is r, x1, width, points
and so on) is left as it is, because the animation would target an
attribute the path no longer has.
deep.svg, 3000 nested <g>, ended in a RecursionError traceback. Both
walk() and ElementTree's own writer recurse once per level, so anything
past about 1000 levels fails, and the writer cannot be made iterative
without replacing it.
The depth is now measured with a loop before any work, and a file nested
more than 500 levels deep stops with a message that says so. 500 leaves
room under Python's default limit of 1000 for both recursions on every
supported version; real drawings nest a few tens of levels at most.
Checked: 498 groups (500 levels with the root and the line) still runs on
Python 3.9 and 3.15, 499 and 3000 get the message.
A path with L1e300 1e300 (hugepath.svg) hung, a line to x2=1e9
(huge.svg) died with MemoryError and a rect with width=1e999 (inf.svg)
with OverflowError: the number of points per edge grew with the length,
and int() of an infinite count failed.
Shapes whose numbers are not finite or lie more than a million canvas
diagonals from the origin are now left as they are, since jitter means
nothing at that size and the output would be hundreds of KB of digits.
Each edge is also cut into at most 200 pieces, so a long line that does
fit (x2=1e7) stays small. A viewBox or width/height that is infinite or
not positive now stops the run with a message naming the size instead of
writing inf and nan coordinates.
steps() divided each edge length by amp*18 + 1e-6. With --amount 0 the
divisor was 1e-6, so a 400-unit line asked for 400 million points and
the run never finished (poster400.svg timed out after 10 s), and
--amount 0.001 turned a 1.3 KB poster into a 1.6 MB file.
The shortest piece an edge is cut into is now also at least 1/160 of the
canvas diagonal. At the default amount this floor is lower than amp*18,
so --amount 1 output is byte-identical to before; at 0 or tiny amounts
the poster now comes out at about 15 KB.
--amount was a plain float, so "--amount nan" crashed with "ValueError:
cannot convert float NaN to integer", "--amount inf" wrote paths such as
d="Minf,nan Linf,inf ..." that no renderer can draw, and "--amount -1"
was accepted with a negative amplitude. The value now goes through an
argparse type that stops with a usage error for anything that is not a
finite number of 0 or more.
rough.py now leaves any element marked data-rough="off", and everything
inside it, untouched. This keeps chart marks, numbers and must-read text
exact while the rest of the piece is roughened.
check.py now reports a problem when the SVG contains Japanese text but
fontconfig lists no Japanese font, since rsvg/cairo would render it as
empty boxes and the other checks would not catch that.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NCDY4KVLusg6S2pAP3Fi4C