Repository navigation
Expand file tree
/
Copy pathflatternpattern.py
More file actions
417 lines (353 loc) · 17.2 KB
/
Copy pathflatternpattern.py
File metadata and controls
417 lines (353 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#!/usr/bin/env python
"""FlatternPattern: replace pattern fills and strokes with real, tiled geometry."""
import math
from typing import NamedTuple
import inkex
from inkex.styles import Style
from fp_cleanup import remove_unused
from fp_clipped import SHAPES, Part, effect_chain, flatten_element, inherited
from fp_merged import MergeError, merge_fills, merged_layer
from fp_resolve import ResolvedPattern, SkipError, chain, resolve
from fp_svg import NON_RENDERED, renamed_copy, set_props, url_id
from fp_tiling import TileLimitError, inkscape_view_differs, plan, shape_path, stroke_region
TEXT_ROOTS = (inkex.TextElement, inkex.FlowRoot)
STROKE_NOTE = "merged mode does not merge pattern strokes."
# Merged mode notes tile content with a lower opacity. Inkscape stock patterns
# have values such as fill-opacity:0.994819, which show as opaque.
NOTE_OPACITY = 0.99
class Target(NamedTuple):
elem: inkex.BaseElement
prop: str # "fill" or "stroke"
pattern: inkex.Pattern
class Skip(NamedTuple):
elem: inkex.BaseElement
reason: str
def walk(elem, parent_style: Style):
"""Yield (element, specified style) for elem and its rendered descendants.
Each style comes from the parent style, so every element gets one cascade."""
if not isinstance(elem.tag, str) or elem.TAG in NON_RENDERED:
return # comments, processing instructions, non-rendered containers
style = Style.add_inherited(Style.cascaded_style(elem), parent_style)
style.element = elem
yield elem, style
for child in elem:
yield from walk(child, style)
def paint(style: Style, prop: str):
"""Return the parsed paint of prop: a paint server element, a color, None,
or the ValueError that inkex raises for a url() to a missing element.
The url() lookup uses style.element, which walk() sets."""
try:
return style(prop)
except ValueError as err:
return err
def text_root(elem):
"""Return the text or flowRoot element that holds elem (or elem itself), else None.
Text children such as tspan, and the shapes in a flowRegion, belong to their text."""
return next((a for a in (elem, *elem.ancestors()) if isinstance(a, TEXT_ROOTS)), None)
def classify(elem, prop: str, style: Style) -> Target | Skip | None:
"""Make a Target for a pattern paint, a Skip for an unsupported one,
or None when there is nothing to flatten."""
match paint(style, prop), elem:
case ValueError(), _:
return Skip(elem, f"The {prop} refers to an element that is not in the document.")
case inkex.BaseElement(TAG="hatch"), _:
return Skip(elem, f"The {prop} is a hatch. The extension does not support hatches.")
case inkex.MeshGradient(), _:
return Skip(
elem,
f"The {prop} is a mesh gradient. The extension does not support mesh gradients.",
)
case inkex.Pattern(), _ if (text := text_root(elem)) is not None:
return Skip(
text,
"This is a text object. Use Path > Object to Path, then run the extension again.",
)
case inkex.Pattern(), inkex.Use():
return Skip(
elem,
"This is a clone. Use Edit > Clone > Unlink Clone, then run the extension again.",
)
case inkex.Pattern() as server, _ if isinstance(elem, SHAPES):
return Target(elem, prop, server)
case inkex.Pattern() | inkex.Gradient(), _:
# Gradients need no flattening. A group gives the pattern to its
# children, and an image or other element does not use the paint.
return None
case inkex.BaseElement() as server, _ if server.TAG.lower() != "solidcolor":
return Skip(
elem, f"The {prop} refers to a {server.TAG} element, which is not a paint server."
)
case _:
# Colors, none, context-fill and solid colors need no flattening.
return None
def collect(selection, stroke_patterns: bool):
"""Find the pattern-painted shapes in the selection and its groups."""
chosen = set(selection)
# A selected element inside a selected group comes from the walk of the group.
tops = [e for e in selection if not any(a in chosen for a in e.ancestors())]
props = ("fill", "stroke") if stroke_patterns else ("fill",)
results = [
classify(elem, prop, style)
for top in tops
for elem, style in walk(top, parent_style(top))
for prop in props
]
# The children of one text give the same Skip, so keep each one only once.
return (
[r for r in results if isinstance(r, Target)],
list(dict.fromkeys(r for r in results if isinstance(r, Skip))),
)
def parent_style(elem) -> Style:
"""Return the specified style of the parent, or an empty style for the root."""
parent = elem.getparent()
return Style() if parent is None else parent.specified_style()
def label(elem) -> str:
"""Name elem in a message by its id, or by its tag when it has no id."""
# get_id() writes a new id onto an element without one, so use get("id").
eid = elem.get("id")
return f"#{eid}" if eid else f"a <{elem.TAG}> element"
class Job(NamedTuple):
target: Target
part: Part
bbox: inkex.BoundingBox # the geometric box of the target before the flattening
def region_of(target: Target, path, bbox, viewport) -> inkex.BoundingBox | None:
"""Return the area that the paint of target covers, or None when it paints nothing."""
if target.prop == "fill":
return bbox
style = target.elem.specified_style()
if str(style.get("vector-effect", "none")) == "non-scaling-stroke":
raise SkipError(
"The stroke does not scale with the object. "
"The extension does not support vector-effect:non-scaling-stroke."
)
return stroke_region(path, style, viewport)
def prepare(targets, viewport, limit: int, inkscape_obb: bool = False):
"""Resolve and plan each target, with no change to the document.
Return (jobs, skips, empty). empty holds the targets whose pattern paints
nothing. If all targets together need more than limit tiles, raise
TileLimitError with a lower bound of the total. inkscape_obb goes to plan()."""
cache: dict = {}
jobs, skips, empty = [], [], []
used = 0
for target in targets:
try:
rp = resolve_once(cache, target.pattern)
job = plan_target(target, rp, viewport, limit - used, inkscape_obb)
except SkipError as err:
skips.append(Skip(target.elem, str(err)))
continue
except TileLimitError as err:
raise TileLimitError(used + err.args[0]) from err
if job is None:
empty.append(target)
else:
jobs.append(job)
used += len(job.part.plan.cells)
return jobs, skips, empty
def resolve_once(cache: dict, pattern) -> ResolvedPattern:
"""Resolve pattern, or raise its SkipError.
cache holds the ResolvedPattern or the SkipError of each pattern element, so
the function resolves each pattern only one time."""
if pattern not in cache:
try:
cache[pattern] = resolve(pattern)
except SkipError as err:
cache[pattern] = err
if isinstance(cache[pattern], SkipError):
raise cache[pattern]
return cache[pattern]
def plan_target(target: Target, rp: ResolvedPattern, viewport, limit: int, inkscape_obb: bool):
"""Return the Job for target, or None when its pattern paints nothing."""
path = shape_path(target.elem, viewport)
bbox = path.bounding_box()
if not rp.content or not bbox:
return None
region = region_of(target, path, bbox, viewport)
if region is None:
return None
tile_plan = plan(rp, bbox, region, viewport, limit, inkscape_obb)
return None if tile_plan is None else Job(target, Part(rp, tile_plan, region), bbox)
def moved_elements(jobs) -> list:
"""Return each element whose pattern Inkscape 1.4 shows at another place
than the SVG standard."""
return list(
dict.fromkeys(
job.target.elem
for job in jobs
if inkscape_view_differs(job.part.pattern, job.part.plan.tile, job.bbox)
)
)
def keep_originals(elems):
"""Put a hidden copy of each element in elems after it, with the id ID-original.
The copy keeps the patterns, the transform and all other properties of the
element (see renamed_copy()). The copy goes after the element: in a <switch>,
the first child renders, and a hidden first child would hide the output."""
for elem in elems:
copy = renamed_copy(elem, "original")
set_props(copy, {"display": "none"})
elem.addnext(copy)
def apply(
jobs, empty, tolerance: float | None = None, keep_original: bool = False, bleed: float = 0.0
):
"""Change the document: flatten the jobs and remove the paints in empty.
An element with a pattern fill and a pattern stroke gets one output group.
tolerance is the seam overlap of merged mode, or None for clipped mode.
bleed is the seam bleed of the clipped copies in user units, 0 for none
(see fp_clipped.tile_group()).
With keep_original, each changed element gets a hidden copy (see keep_originals()).
Return (notes, empty): the notes about merged mode for the user, and empty
with the merged fills that paint nothing."""
parts: dict = {}
boxes = {job.target.elem: job.bbox for job in jobs}
for job in jobs:
parts.setdefault(job.target.elem, {})[job.target.prop] = job.part
if keep_original:
keep_originals(dict.fromkeys([*parts, *(t.elem for t in empty)]))
# All elements are in one document, so one search for a stylesheet is enough.
reset = bool(parts) and bool(next(iter(parts)).root.xpath("//svg:style"))
no_merge = ({}, [], [])
layers, removed, notes = (
no_merge if tolerance is None else merged_layers(parts, tolerance, reset)
)
for elem in removed:
del parts[elem]["fill"]
empty = empty + [Target(elem, "fill", None) for elem in removed]
for elem, paints in parts.items():
if paints:
fill, stroke = paints.get("fill"), paints.get("stroke")
flatten_element(elem, fill, stroke, reset, layers.get(elem), boxes[elem], bleed)
for target in empty:
set_props(target.elem, {target.prop: "none"})
return notes, empty
def merged_layers(parts: dict, tolerance: float, reset: bool):
"""Return (layers, removed, notes) for merged mode. layers maps each element
to its merged fill layer. removed holds the elements whose fill paints
nothing. An element without a layer gets clipped copies. reset goes to
merge_fills()."""
layers, removed, notes = {}, [], []
fills = {elem: paints["fill"] for elem, paints in parts.items() if "fill" in paints}
failed: dict = {} # the elements for each error text, for one note per error
for elem, merged in merge_fills(fills, tolerance, reset).items():
if isinstance(merged, MergeError):
failed.setdefault(str(merged), []).append(label(elem))
elif merged is None:
removed.append(elem)
else:
layers[elem] = merged_layer(elem, merged, reset)
notes += merge_notes(elem, merged.content)
notes += [
f"Made clipped copies for the fill of {', '.join(labels)}: {error}"
for error, labels in failed.items()
]
notes += [
f"Made clipped copies for the stroke of {label(elem)}: {STROKE_NOTE}"
for elem, paints in parts.items()
if "stroke" in paints
]
return layers, removed, notes
def merge_notes(elem, content) -> list[str]:
"""Return the notes about what a merged path of content cannot show."""
notes = []
if len(set(content.colors)) > 1:
notes.append(
f"The tile content of {label(elem)} has more than one color. "
f"The merged path uses the first color, {content.colors[0]}."
)
if content.opacity < NOTE_OPACITY:
notes.append(
f"The lowest opacity in the tile content of {label(elem)} is "
f"{opacity_text(content.opacity)}. The merged path is opaque."
)
return notes
def opacity_text(opacity: float) -> str:
"""Return opacity with at most 4 decimals, rounded down, so that a value
below NOTE_OPACITY never shows as NOTE_OPACITY. A value above 0 shows as
0.0001 or more."""
shown = max(math.floor(round(opacity * 10000, 6)) / 10000, 0.0001)
return f"{shown:.4f}".rstrip("0").rstrip(".")
def processed_patterns(jobs, empty) -> list:
"""Return the pattern elements in the href chains of the processed targets."""
starts = [j.target.pattern for j in jobs] + [t.pattern for t in empty if t.pattern is not None]
return list(dict.fromkeys(p for start in starts for p in chain(start)))
def target_effects(jobs) -> list:
"""Return (target, effect) for each clip, mask and filter of the flattened
targets. The output groups can get copies of these effects (see
fp_clipped.output_group()), so the cleanup checks the originals too."""
found = []
for elem in dict.fromkeys(j.target.elem for j in jobs):
style = Style.cascaded_style(elem)
for prop in ("clip-path", "mask", "filter"):
effect = elem.root.getElementById(eid) if (eid := url_id(style.get(prop, ""))) else None
if effect is not None:
found.append((elem, effect))
return found
def primitive_notes(effects) -> list[str]:
"""Return a note for each filter with primitiveUnits="objectBoundingBox".
The extension does not convert these units (see user_space_effect())."""
return [
f"Note for {label(elem)}: the filter uses primitiveUnits=objectBoundingBox. "
"The output can look different, because the extension does not convert these units."
for elem, effect in effects
if effect.TAG == "filter"
and inherited(effect_chain(effect), "primitiveUnits") == "objectBoundingBox"
]
def report(jobs, empty, skips, moved, notes) -> list[str]:
"""Return the message lines for the user."""
lines = list(notes)
lines += [
f"Removed the {t.prop} of {label(t.elem)}: the pattern paints nothing." for t in empty
]
lines += [
f"Note for {label(e)}: Inkscape 1.4 shows this pattern at another place. "
"The output follows the SVG standard. To keep the Inkscape view, select "
'"Match the Inkscape view, not the SVG standard", then run the extension again.'
for e in moved
]
lines += [f"Skipped {label(s.elem)}: {s.reason}" for s in skips]
if not jobs and not empty and not skips:
lines.append("The selection has no pattern fill or pattern stroke to flatten.")
return lines
class FlatternPattern(inkex.EffectExtension):
def add_arguments(self, pars):
pars.add_argument("--tab", default="options")
pars.add_argument("--mode", default="clipped", choices=("clipped", "merged"))
pars.add_argument("--stroke_patterns", type=inkex.Boolean, default=True)
pars.add_argument("--keep_original", type=inkex.Boolean, default=False)
pars.add_argument("--cleanup_defs", type=inkex.Boolean, default=True)
pars.add_argument("--tile_limit", type=int, default=2000)
pars.add_argument("--tolerance", type=float, default=0.01)
pars.add_argument("--inkscape_obb", type=inkex.Boolean, default=False)
pars.add_argument("--seam_bleed", type=inkex.Boolean, default=False)
pars.add_argument("--bleed_px", type=float, default=0.2)
def effect(self):
if not self.svg.selection:
raise inkex.AbortExtension(
"Select one or more objects with a pattern fill or a pattern stroke, "
"then run the extension again."
)
targets, skips = collect(list(self.svg.selection.values()), self.options.stroke_patterns)
viewport = (self.svg.viewbox_width, self.svg.viewbox_height)
limit = self.options.tile_limit
inkscape_obb = self.options.inkscape_obb
try:
jobs, more_skips, empty = prepare(targets, viewport, limit, inkscape_obb)
except TileLimitError as err:
raise inkex.AbortExtension(
f"The selection needs at least {err.args[0]} tiles. The limit is {limit}. "
"Increase the maximum number of tiles, then run the extension again."
) from err
moved = [] if inkscape_obb else moved_elements(jobs)
tolerance = self.options.tolerance if self.options.mode == "merged" else None
effects = target_effects(jobs)
effect_notes = primitive_notes(effects) # before the cleanup removes effects
bleed = self.svg.unittouu(f"{self.options.bleed_px}px") if self.options.seam_bleed else 0.0
notes, empty = apply(jobs, empty, tolerance, self.options.keep_original, bleed)
if self.options.cleanup_defs:
candidates = processed_patterns(jobs, empty) + [e for _, e in effects]
remove_unused(self.svg, list(dict.fromkeys(candidates)))
notes = effect_notes + notes
lines = report(jobs, empty, skips + more_skips, moved, notes)
if lines:
self.msg("\n".join(lines))
if __name__ == "__main__":
FlatternPattern().run()