vec-io 0.7.0__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- vec_io/__init__.py +60 -0
- vec_io/__main__.py +8 -0
- vec_io/arrays.py +99 -0
- vec_io/canvas.py +2059 -0
- vec_io/cells.py +538 -0
- vec_io/cli.py +1161 -0
- vec_io/convert.py +481 -0
- vec_io/css_tokens.py +313 -0
- vec_io/document.py +2060 -0
- vec_io/draw.py +1246 -0
- vec_io/eps/__init__.py +597 -0
- vec_io/eps/fonts.py +302 -0
- vec_io/errors.py +26 -0
- vec_io/filter.py +1025 -0
- vec_io/flate.py +87 -0
- vec_io/flatten.py +707 -0
- vec_io/fonts/__init__.py +562 -0
- vec_io/fonts/cff.py +681 -0
- vec_io/fonts/cff2.py +210 -0
- vec_io/fonts/charstring.py +523 -0
- vec_io/fonts/colr.py +591 -0
- vec_io/fonts/ctan.py +74 -0
- vec_io/fonts/download.py +796 -0
- vec_io/fonts/encodings.py +255 -0
- vec_io/fonts/fontdb.py +806 -0
- vec_io/fonts/fontshare.py +109 -0
- vec_io/fonts/fontshare_families.txt +102 -0
- vec_io/fonts/fontsource.py +70 -0
- vec_io/fonts/fontsource_families.txt +121 -0
- vec_io/fonts/glyphlist.txt +3764 -0
- vec_io/fonts/google.py +464 -0
- vec_io/fonts/google_families.txt +1961 -0
- vec_io/fonts/opentype.py +1556 -0
- vec_io/fonts/program.py +155 -0
- vec_io/fonts/sfnt.py +1255 -0
- vec_io/fonts/type1.py +912 -0
- vec_io/fonts/urw.py +141 -0
- vec_io/fonts/variations.py +759 -0
- vec_io/fonts/web.py +153 -0
- vec_io/fonts/woff2.py +369 -0
- vec_io/geometry.py +1250 -0
- vec_io/image/__init__.py +305 -0
- vec_io/image/avif.py +269 -0
- vec_io/image/bmp.py +308 -0
- vec_io/image/codecs.py +121 -0
- vec_io/image/gif.py +122 -0
- vec_io/image/icc.py +242 -0
- vec_io/image/jbig2.py +278 -0
- vec_io/image/jpx.py +349 -0
- vec_io/image/jxl.py +443 -0
- vec_io/image/resource.py +925 -0
- vec_io/image/tiff.py +263 -0
- vec_io/image/webp.py +183 -0
- vec_io/items.py +250 -0
- vec_io/limits.py +369 -0
- vec_io/lines.py +384 -0
- vec_io/native/__init__.py +469 -0
- vec_io/native/__main__.py +184 -0
- vec_io/native/_api.py +1218 -0
- vec_io/native/bin/windows-x86_64.dll +0 -0
- vec_io/native/brotli.py +37 -0
- vec_io/native/emit.py +348 -0
- vec_io/native/filters.py +206 -0
- vec_io/native/jpeg.py +179 -0
- vec_io/native/manifest.json +54 -0
- vec_io/native/pdfread.py +237 -0
- vec_io/native/png.py +514 -0
- vec_io/native/woff2.py +35 -0
- vec_io/network.py +190 -0
- vec_io/notebook.py +37 -0
- vec_io/options.py +515 -0
- vec_io/output_plan.py +173 -0
- vec_io/paint.py +1291 -0
- vec_io/pdf/__init__.py +1 -0
- vec_io/pdf/copier.py +141 -0
- vec_io/pdf/images.py +252 -0
- vec_io/pdf/objects.py +326 -0
- vec_io/pdf/pdfa.py +212 -0
- vec_io/pdf/writer.py +215 -0
- vec_io/pdffile.py +962 -0
- vec_io/pdfread/__init__.py +226 -0
- vec_io/pdfread/ccitt.py +38 -0
- vec_io/pdfread/cmap.py +694 -0
- vec_io/pdfread/cmap_resources.txt +210 -0
- vec_io/pdfread/cmaps.zip +0 -0
- vec_io/pdfread/colors.py +385 -0
- vec_io/pdfread/content.py +929 -0
- vec_io/pdfread/convert.py +45 -0
- vec_io/pdfread/errors.py +25 -0
- vec_io/pdfread/file.py +717 -0
- vec_io/pdfread/fonts.py +1099 -0
- vec_io/pdfread/functions.py +345 -0
- vec_io/pdfread/images.py +805 -0
- vec_io/pdfread/meshes.py +80 -0
- vec_io/pdfread/origin.py +334 -0
- vec_io/pdfread/parser.py +232 -0
- vec_io/pdfread/reader.py +810 -0
- vec_io/pdfread/resources.py +527 -0
- vec_io/pdfread/security.py +296 -0
- vec_io/pdfread/shadings.py +470 -0
- vec_io/pdfread/strings.py +58 -0
- vec_io/py.typed +0 -0
- vec_io/raster/__init__.py +893 -0
- vec_io/raster/groups.py +392 -0
- vec_io/raster/resources.py +447 -0
- vec_io/recorder.py +1199 -0
- vec_io/records.py +411 -0
- vec_io/resample.py +232 -0
- vec_io/resources.py +70 -0
- vec_io/scene.py +916 -0
- vec_io/shapes.py +308 -0
- vec_io/simplify.py +442 -0
- vec_io/svg/__init__.py +11 -0
- vec_io/svg/basic_shapes.py +386 -0
- vec_io/svg/clipmask.py +277 -0
- vec_io/svg/common.py +188 -0
- vec_io/svg/css.py +1246 -0
- vec_io/svg/filters.py +813 -0
- vec_io/svg/fontface.py +177 -0
- vec_io/svg/images.py +139 -0
- vec_io/svg/markers.py +68 -0
- vec_io/svg/painter.py +271 -0
- vec_io/svg/parse.py +624 -0
- vec_io/svg/properties.py +1038 -0
- vec_io/svg/references.py +84 -0
- vec_io/svg/render.py +584 -0
- vec_io/svg/servers.py +164 -0
- vec_io/svg/text.py +1034 -0
- vec_io/svg/text_paint.py +330 -0
- vec_io/svg/tree.py +491 -0
- vec_io/svg/values.py +741 -0
- vec_io/svg/writer.py +1001 -0
- vec_io/text/__init__.py +1861 -0
- vec_io/text/bidi.py +410 -0
- vec_io/text/breaking.py +1056 -0
- vec_io/text/harfbuzz.py +222 -0
- vec_io/text/hyph_en_us.py +387 -0
- vec_io/text/hyph_fr.py +123 -0
- vec_io/text/hyphenation.py +165 -0
- vec_io/text/mirroring.py +92 -0
- vec_io/text/path.py +116 -0
- vec_io/text/segment.py +139 -0
- vec_io/text/shaping.py +700 -0
- vec_io/text/ucd_grapheme.py +338 -0
- vec_io/text/ucd_ignorable.py +19 -0
- vec_io/text/ucd_linebreak.py +608 -0
- vec_io/text/ucd_scripts.py +514 -0
- vec_io/threads.py +133 -0
- vec_io/transfer.py +477 -0
- vec_io/trim.py +170 -0
- vec_io/types.py +167 -0
- vec_io/units.py +738 -0
- vec_io-0.7.0.dist-info/METADATA +133 -0
- vec_io-0.7.0.dist-info/RECORD +157 -0
- vec_io-0.7.0.dist-info/WHEEL +4 -0
- vec_io-0.7.0.dist-info/entry_points.txt +2 -0
- vec_io-0.7.0.dist-info/licenses/LICENSE +28 -0
vec_io/canvas.py
ADDED
|
@@ -0,0 +1,2059 @@
|
|
|
1
|
+
"""The drawing API of a page over a recorded scene: a drawing state named as SVG's
|
|
2
|
+
properties, and calls that take the same names for one call.
|
|
3
|
+
|
|
4
|
+
The coordinate system of a page has its origin at the top-left corner with y pointing down
|
|
5
|
+
(like SVG and HTML canvas), in the document's unit. Angles are in degrees.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import array
|
|
9
|
+
import contextlib
|
|
10
|
+
import copy
|
|
11
|
+
import logging
|
|
12
|
+
import math
|
|
13
|
+
import numbers
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
|
|
18
|
+
from typing import IO, TYPE_CHECKING, Any, Self, TypeAlias, Unpack, cast, overload
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
from .errors import ArgumentError, StateError
|
|
22
|
+
from . import scene as _scene
|
|
23
|
+
from .native import emit as _emit
|
|
24
|
+
from .paint import CMYK, ColorLike, as_rgba, to_rgba
|
|
25
|
+
from .geometry import (Matrix, Path, ellipse_path, parse_path_data, rect_path, transform_bbox,
|
|
26
|
+
view_box_transform)
|
|
27
|
+
from .pdf.objects import Name, Obj
|
|
28
|
+
from .native import _api
|
|
29
|
+
from .recorder import LINECAPS as _LINECAPS, LINEJOINS as _LINEJOINS, Recorder, line_style
|
|
30
|
+
from .scene import SP, Palette, Scene
|
|
31
|
+
from .text import _STRETCH_KEYWORDS, Font, GlyphRun, css_variations
|
|
32
|
+
from .text.shaping import feature_settings
|
|
33
|
+
from .units import PT_PER_PX, parse_angle, parse_length
|
|
34
|
+
from .types import (ArrayLike, Dashes, ItemStyle, LineStyle, PaintLike, SegmentStyle,
|
|
35
|
+
SimplifyLike, Style)
|
|
36
|
+
|
|
37
|
+
if TYPE_CHECKING:
|
|
38
|
+
from .filter import Filter
|
|
39
|
+
from .image import Image
|
|
40
|
+
from .limits import Limits
|
|
41
|
+
from .svg import SVGDocument
|
|
42
|
+
from .text import Content, Paragraphs
|
|
43
|
+
from .text.breaking import TextLayout
|
|
44
|
+
from .paint import blend_index
|
|
45
|
+
from .paint import (STATE, Marker, Mask, Paint, PathMarker, Pattern,
|
|
46
|
+
_alpha, _compact, _Gradient)
|
|
47
|
+
from .items import ColorList, _all_opaque, _flat_rgba, per_point_arguments
|
|
48
|
+
from .simplify import _MARKERS, _NEVER, _check_simplify
|
|
49
|
+
|
|
50
|
+
__all__ = ["Canvas"]
|
|
51
|
+
|
|
52
|
+
#: Default resolution of rasterized groups, in dots per inch.
|
|
53
|
+
DEFAULT_DPI = 300
|
|
54
|
+
DEFAULT_JPEG_QUALITY = 90
|
|
55
|
+
|
|
56
|
+
#: A file given by path.
|
|
57
|
+
PathLike: TypeAlias = str | os.PathLike[str]
|
|
58
|
+
|
|
59
|
+
_log = logging.getLogger("vec_io")
|
|
60
|
+
|
|
61
|
+
_ANCHORS = ("start", "middle", "end")
|
|
62
|
+
#: CSS ``text-align`` values of text layout.
|
|
63
|
+
_TEXT_ALIGNS = ("start", "end", "left", "right", "center", "justify")
|
|
64
|
+
|
|
65
|
+
_STATE_DEFAULTS = {
|
|
66
|
+
"fill": "black", "stroke": None, "stroke_width": 1.0, "stroke_linecap": "butt",
|
|
67
|
+
"stroke_linejoin": "miter", "stroke_miterlimit": 4.0, "stroke_dasharray": None,
|
|
68
|
+
"stroke_dashoffset": 0.0, "opacity": 1.0, "fill_opacity": 1.0, "stroke_opacity": 1.0,
|
|
69
|
+
"font_family": "system-ui", "font_size": 12.0,
|
|
70
|
+
"font_weight": "normal", "font_style": "normal", "text_anchor": "start",
|
|
71
|
+
"letter_spacing": 0.0, "word_spacing": 0.0, "fill_rule": "nonzero",
|
|
72
|
+
"font_stretch": "normal", "font_variation_settings": "", "font_optical_sizing": "auto",
|
|
73
|
+
"font_kerning": "auto", "font_embed": True, "font_variant": "normal",
|
|
74
|
+
"font_feature_settings": "", "direction": "ltr", "lang": None,
|
|
75
|
+
}
|
|
76
|
+
_STATE_ATTRS = tuple(_STATE_DEFAULTS)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class _FilterHolder:
|
|
80
|
+
"""The filtered group a body is drawn in, once recorded (``group``): what the filtered
|
|
81
|
+
groups inside it are made with."""
|
|
82
|
+
|
|
83
|
+
__slots__ = ("group",)
|
|
84
|
+
|
|
85
|
+
def __init__(self):
|
|
86
|
+
self.group = None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class _Style:
|
|
90
|
+
"""The drawing attributes of a canvas (one record, copied by ``with``
|
|
91
|
+
:meth:`Canvas.state`)."""
|
|
92
|
+
|
|
93
|
+
__slots__ = _STATE_ATTRS
|
|
94
|
+
|
|
95
|
+
def __init__(self):
|
|
96
|
+
for key, value in _STATE_DEFAULTS.items():
|
|
97
|
+
setattr(self, key, value)
|
|
98
|
+
|
|
99
|
+
def copy(self) -> "_Style":
|
|
100
|
+
new = _Style.__new__(_Style)
|
|
101
|
+
for key in _STATE_ATTRS:
|
|
102
|
+
setattr(new, key, getattr(self, key))
|
|
103
|
+
return new
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _number(name, value, low=None, high=None, low_open=False):
|
|
107
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) and not (
|
|
108
|
+
hasattr(value, "__float__") and not isinstance(value, (str, bytes))):
|
|
109
|
+
raise ArgumentError(f"{name} must be a number, not {value!r}")
|
|
110
|
+
v = float(value)
|
|
111
|
+
if not math.isfinite(v) or (low is not None and (v <= low if low_open else v < low)) \
|
|
112
|
+
or (high is not None and v > high):
|
|
113
|
+
bound = "" if low is None else (" > " if low_open else " >= ") + f"{low:g}"
|
|
114
|
+
raise ArgumentError(f"{name} must be a finite number{bound}, not {value!r}")
|
|
115
|
+
return v
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _numbers(exc, **values):
|
|
119
|
+
"""Raise an ``ArgumentError`` naming the first of ``values`` that is not a finite
|
|
120
|
+
number (``None`` passes); else ``exc``, the error a call met."""
|
|
121
|
+
for name, value in values.items():
|
|
122
|
+
if value is not None:
|
|
123
|
+
_number(name, value)
|
|
124
|
+
raise exc
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _path(name, value):
|
|
128
|
+
"""``value``, a :class:`Path` or SVG path data, as a Path."""
|
|
129
|
+
if isinstance(value, str):
|
|
130
|
+
return parse_path_data(value, strict=True)
|
|
131
|
+
if not isinstance(value, Path):
|
|
132
|
+
raise ArgumentError(f"{name} must be a Path or SVG path data, not {value!r}")
|
|
133
|
+
return value
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _keyword(*words):
|
|
137
|
+
def check(name, value):
|
|
138
|
+
if value not in words:
|
|
139
|
+
raise ArgumentError(f"{name} must be one of {', '.join(map(repr, words))}, "
|
|
140
|
+
f"not {value!r}")
|
|
141
|
+
return value
|
|
142
|
+
return check
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _check_paint(name, value):
|
|
146
|
+
if value is None or isinstance(value, (_Gradient, Pattern, CMYK)):
|
|
147
|
+
return value
|
|
148
|
+
if isinstance(value, (str, tuple, list)) or hasattr(value, "__len__"):
|
|
149
|
+
try:
|
|
150
|
+
to_rgba(value) # raises for what is not a color
|
|
151
|
+
except ArgumentError as exc:
|
|
152
|
+
raise ArgumentError(f"{name}: {exc}") from None
|
|
153
|
+
return value
|
|
154
|
+
raise ArgumentError(f"{name} must be a color, gradient, pattern or None, not {value!r}")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _check_anchor(name, value):
|
|
158
|
+
if value in _ANCHORS:
|
|
159
|
+
return value
|
|
160
|
+
hint = {"left": "start", "center": "middle", "right": "end"}.get(value)
|
|
161
|
+
raise ArgumentError(f"{name} must be 'start', 'middle' or 'end', not {value!r}"
|
|
162
|
+
+ (f" (use {hint!r})" if hint else ""))
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _check_dash(name, value):
|
|
166
|
+
if value is None:
|
|
167
|
+
return None
|
|
168
|
+
if isinstance(value, str):
|
|
169
|
+
text = value.strip()
|
|
170
|
+
if text.lower() in ("", "none"):
|
|
171
|
+
return None
|
|
172
|
+
try:
|
|
173
|
+
values = [float(v) for v in text.replace(",", " ").split()]
|
|
174
|
+
except ValueError:
|
|
175
|
+
raise ArgumentError(f"{name} must be numbers separated by spaces or commas, "
|
|
176
|
+
f"not {value!r}") from None
|
|
177
|
+
else:
|
|
178
|
+
try:
|
|
179
|
+
values = [_number(name, v) for v in value]
|
|
180
|
+
except TypeError:
|
|
181
|
+
raise ArgumentError(f"{name} must be a sequence of numbers, not {value!r}") from None
|
|
182
|
+
if not all(math.isfinite(v) and v >= 0 for v in values):
|
|
183
|
+
raise ArgumentError(f"{name} values must be finite and non-negative, not {value!r}")
|
|
184
|
+
return tuple(values) or None
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
_WEIGHT_WORDS = ("normal", "bold", "bolder", "lighter")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _check_weight(name, value):
|
|
191
|
+
v = value.strip().lower() if isinstance(value, str) else value
|
|
192
|
+
if v in _WEIGHT_WORDS:
|
|
193
|
+
return value
|
|
194
|
+
try:
|
|
195
|
+
_number(name, float(v) if isinstance(v, str) else v, 1, 1000)
|
|
196
|
+
except ValueError:
|
|
197
|
+
raise ArgumentError(f"{name} must be 'normal', 'bold', 'bolder', 'lighter' or a number "
|
|
198
|
+
f"from 1 to 1000, not {value!r}") from None
|
|
199
|
+
return value
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _check_font_style(name, value):
|
|
203
|
+
v = value.strip().lower() if isinstance(value, str) else None
|
|
204
|
+
if v in ("normal", "italic", "oblique") or (
|
|
205
|
+
v is not None and v.startswith("oblique ")
|
|
206
|
+
and parse_angle(v[8:].strip()) is not None):
|
|
207
|
+
return value
|
|
208
|
+
raise ArgumentError(f"{name} must be 'normal', 'italic', 'oblique' or 'oblique <angle>', "
|
|
209
|
+
f"not {value!r}")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _check_stretch(name, value):
|
|
213
|
+
if isinstance(value, str) and value.strip().lower() in _STRETCH_KEYWORDS:
|
|
214
|
+
return value
|
|
215
|
+
try:
|
|
216
|
+
text = value.strip().rstrip("%") if isinstance(value, str) else value
|
|
217
|
+
_number(name, float(text) if isinstance(text, str) else text, 0, low_open=True)
|
|
218
|
+
except ValueError:
|
|
219
|
+
raise ArgumentError(f"{name} must be a CSS font-stretch keyword or percentage, "
|
|
220
|
+
f"not {value!r}") from None
|
|
221
|
+
return value
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _check_with(parse):
|
|
225
|
+
def check(name, value):
|
|
226
|
+
try:
|
|
227
|
+
parse(value)
|
|
228
|
+
except (TypeError, ValueError):
|
|
229
|
+
raise ArgumentError(f"invalid {name} {value!r}") from None
|
|
230
|
+
return value
|
|
231
|
+
return check
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _check_family(name, value):
|
|
235
|
+
if not isinstance(value, str) or not value.strip():
|
|
236
|
+
raise ArgumentError(f"{name} must be a CSS font family list, not {value!r}")
|
|
237
|
+
return value
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _check_bool(name, value):
|
|
241
|
+
if not isinstance(value, bool):
|
|
242
|
+
raise ArgumentError(f"{name} must be True or False, not {value!r}")
|
|
243
|
+
return value
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _check_variant(name, value):
|
|
247
|
+
if not isinstance(value, str):
|
|
248
|
+
raise ArgumentError(f"{name} must be CSS font-variant keywords, not {value!r}")
|
|
249
|
+
return value
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
_NUMERIC = re.compile(r"\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*")
|
|
253
|
+
_LANG = re.compile(r"[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*")
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _check_lang(name, value):
|
|
257
|
+
if value is None or isinstance(value, str) and _LANG.fullmatch(value):
|
|
258
|
+
return value
|
|
259
|
+
raise ArgumentError(f"{name} must be a BCP 47 language tag such as 'en' or 'fr-CA', or "
|
|
260
|
+
f"None, not {value!r}")
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
_STATE_CHECKS: dict[str, Callable[[str, Any], Any]] = {
|
|
264
|
+
"fill": _check_paint, "stroke": _check_paint,
|
|
265
|
+
"stroke_width": lambda n, v: _number(n, v, 0),
|
|
266
|
+
"stroke_linecap": _keyword(*_LINECAPS), "stroke_linejoin": _keyword(*_LINEJOINS),
|
|
267
|
+
"stroke_miterlimit": lambda n, v: _number(n, v, 1),
|
|
268
|
+
"stroke_dasharray": _check_dash, "stroke_dashoffset": _number,
|
|
269
|
+
"opacity": _number, "fill_opacity": _number, "stroke_opacity": _number,
|
|
270
|
+
"font_family": _check_family,
|
|
271
|
+
"font_size": lambda n, v: _number(n, float(v) if isinstance(v, str) and
|
|
272
|
+
_NUMERIC.fullmatch(v) else v, 0),
|
|
273
|
+
"font_weight": _check_weight, "font_style": _check_font_style,
|
|
274
|
+
"text_anchor": _check_anchor, "letter_spacing": _number, "word_spacing": _number,
|
|
275
|
+
"fill_rule": _keyword("nonzero", "evenodd"), "font_stretch": _check_stretch,
|
|
276
|
+
"font_variation_settings": _check_with(css_variations),
|
|
277
|
+
"font_optical_sizing": _keyword("auto", "none"),
|
|
278
|
+
"font_kerning": _keyword("auto", "normal", "none"), "font_embed": _check_bool,
|
|
279
|
+
"font_variant": _check_variant, "font_feature_settings": _check_with(feature_settings),
|
|
280
|
+
"direction": _keyword("ltr", "rtl", "auto"), "lang": _check_lang,
|
|
281
|
+
}
|
|
282
|
+
#: Public attributes a canvas sets in ``__init__`` (besides the drawing state).
|
|
283
|
+
_INSTANCE_ATTRS = frozenset({"document", "index", "page_width", "page_height"})
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
_STATE_DOCS = {
|
|
287
|
+
"fill": "The paint of fills: a color, gradient, pattern or ``None``.",
|
|
288
|
+
"stroke": "The paint of strokes: a color, gradient, pattern or ``None``.",
|
|
289
|
+
"stroke_width": "The stroke width, in the document's unit (0: no stroke).",
|
|
290
|
+
"stroke_linecap": "``butt``, ``round`` or ``square``.",
|
|
291
|
+
"stroke_linejoin": "``miter``, ``miter-clip``, ``arcs``, ``round`` or ``bevel``.",
|
|
292
|
+
"stroke_miterlimit": "The miter limit (>= 1).",
|
|
293
|
+
"stroke_dasharray": "Dash lengths: a sequence or CSS text (``\"4 2\"``); read back as a "
|
|
294
|
+
"tuple.",
|
|
295
|
+
"stroke_dashoffset": "Where the dash pattern starts along each subpath.",
|
|
296
|
+
"opacity": "A factor on every paint's alpha, clamped to 0-1.",
|
|
297
|
+
"fill_opacity": "A factor on the alpha of fills, clamped to 0-1.",
|
|
298
|
+
"stroke_opacity": "A factor on the alpha of strokes, clamped to 0-1.",
|
|
299
|
+
"font_family": "A CSS font family list.",
|
|
300
|
+
"font_size": "The font size, in the document's unit.",
|
|
301
|
+
"font_weight": "``normal``, ``bold``, ``bolder``, ``lighter`` or 1-1000.",
|
|
302
|
+
"font_style": "``normal``, ``italic``, ``oblique`` or ``oblique <angle>``.",
|
|
303
|
+
"text_anchor": "``start``, ``middle`` or ``end``: where text lines up with its x.",
|
|
304
|
+
"letter_spacing": "Extra space after each character, in the document's unit.",
|
|
305
|
+
"word_spacing": "Extra space after each space, in the document's unit.",
|
|
306
|
+
"fill_rule": "``nonzero`` or ``evenodd``.",
|
|
307
|
+
"font_stretch": "A CSS font-stretch keyword or percentage.",
|
|
308
|
+
"font_variation_settings": "Variable font axes: CSS text or a ``{tag: value}`` dict.",
|
|
309
|
+
"font_optical_sizing": "``auto`` (the ``opsz`` axis follows the size) or ``none``.",
|
|
310
|
+
"font_kerning": "``auto``, ``normal`` or ``none``.",
|
|
311
|
+
"font_embed": "``False``: a standard 14 font named by the family is not embedded.",
|
|
312
|
+
"font_variant": "CSS ``font-variant`` keywords (``no-common-ligatures``: no ligatures).",
|
|
313
|
+
"font_feature_settings": "OpenType features: CSS text or a ``{tag: value}`` dict.",
|
|
314
|
+
"direction": "``ltr``, ``rtl`` or ``auto``: the paragraph direction of bidi text.",
|
|
315
|
+
"lang": "The text's language, a BCP 47 tag (``None``: the document's ``lang``): the "
|
|
316
|
+
"fonts' forms for it (``locl``) and ``hyphens=\"auto\"``'s patterns.",
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _unknown_style(where, name):
|
|
321
|
+
"""The error of an unknown style keyword (with the closest name)."""
|
|
322
|
+
import difflib
|
|
323
|
+
|
|
324
|
+
close = difflib.get_close_matches(name, _STATE_ATTRS, 1)
|
|
325
|
+
hint = f" (did you mean {close[0]!r}?)" if close else ""
|
|
326
|
+
return ArgumentError(f"{where}() got an unknown style keyword {name!r}{hint}")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _state_property(name):
|
|
330
|
+
check = _STATE_CHECKS[name]
|
|
331
|
+
|
|
332
|
+
def get(self):
|
|
333
|
+
return getattr(self._style, name)
|
|
334
|
+
|
|
335
|
+
def set_(self, value):
|
|
336
|
+
setattr(self._style, name, check(name, value))
|
|
337
|
+
|
|
338
|
+
return property(get, set_, doc=_STATE_DOCS[name])
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
class Canvas:
|
|
342
|
+
"""The drawing surface of a page (:class:`~vec_io.document.Page`), in the document's
|
|
343
|
+
unit, origin at the top-left corner, y down.
|
|
344
|
+
|
|
345
|
+
Drawing state (attributes, saved with the transform and the clip by ``with``
|
|
346
|
+
:meth:`state`), named as SVG's properties: ``fill``, ``stroke`` (a color, gradient,
|
|
347
|
+
pattern or ``None``), ``stroke_width``, ``stroke_linecap``, ``stroke_linejoin``,
|
|
348
|
+
``stroke_miterlimit``, ``stroke_dasharray``, ``stroke_dashoffset``, ``opacity``,
|
|
349
|
+
``fill_opacity``, ``stroke_opacity``, ``font_family``, ``font_size``, ``font_weight``,
|
|
350
|
+
``font_style``, ``font_stretch``, ``font_variation_settings``, ``font_optical_sizing``,
|
|
351
|
+
``font_kerning``, ``font_embed``, ``font_variant``, ``font_feature_settings``,
|
|
352
|
+
``direction`` (``ltr``, ``rtl``, ``auto``), ``lang`` (``None``: the document's),
|
|
353
|
+
``text_anchor``, ``letter_spacing``, ``word_spacing``, ``fill_rule``.
|
|
354
|
+
|
|
355
|
+
Every drawing call takes these as keywords (``**style``) for that call only. Bulk
|
|
356
|
+
calls take ``fill``, ``stroke``, ``stroke_width`` and ``opacity`` as one value or a
|
|
357
|
+
column of one per item.
|
|
358
|
+
"""
|
|
359
|
+
|
|
360
|
+
# Drawing state (set by _reset_state).
|
|
361
|
+
fill: Paint
|
|
362
|
+
stroke: Paint
|
|
363
|
+
stroke_width: float
|
|
364
|
+
stroke_linecap: str
|
|
365
|
+
stroke_linejoin: str
|
|
366
|
+
stroke_miterlimit: float
|
|
367
|
+
stroke_dasharray: Iterable[float] | None
|
|
368
|
+
stroke_dashoffset: float
|
|
369
|
+
opacity: float
|
|
370
|
+
fill_opacity: float
|
|
371
|
+
stroke_opacity: float
|
|
372
|
+
font_family: str
|
|
373
|
+
font_size: float
|
|
374
|
+
font_weight: str
|
|
375
|
+
font_style: str
|
|
376
|
+
font_stretch: str
|
|
377
|
+
font_variation_settings: str | Mapping[str, float]
|
|
378
|
+
font_optical_sizing: str
|
|
379
|
+
font_kerning: str
|
|
380
|
+
font_embed: bool
|
|
381
|
+
font_variant: str
|
|
382
|
+
font_feature_settings: str | Mapping[str, int]
|
|
383
|
+
direction: str
|
|
384
|
+
lang: str | None
|
|
385
|
+
text_anchor: str
|
|
386
|
+
letter_spacing: float
|
|
387
|
+
word_spacing: float
|
|
388
|
+
fill_rule: str
|
|
389
|
+
|
|
390
|
+
def __init__(self, document, index, page_width, page_height, unit_scale):
|
|
391
|
+
self.document = document
|
|
392
|
+
self.index = index
|
|
393
|
+
self.page_width = page_width
|
|
394
|
+
self.page_height = page_height
|
|
395
|
+
self._recorder = Recorder(self, document, page_width, page_height, unit_scale)
|
|
396
|
+
self._font_cache = None
|
|
397
|
+
self._reset_state()
|
|
398
|
+
|
|
399
|
+
if not TYPE_CHECKING: # (type checkers check attribute names themselves)
|
|
400
|
+
def __setattr__(self, name, value):
|
|
401
|
+
if name.startswith("_") or isinstance(getattr(type(self), name, None), property):
|
|
402
|
+
object.__setattr__(self, name, value)
|
|
403
|
+
return
|
|
404
|
+
if name in _INSTANCE_ATTRS and name in self.__dict__ or hasattr(type(self), name):
|
|
405
|
+
raise AttributeError(f"{type(self).__name__}.{name} is read-only")
|
|
406
|
+
if name not in _INSTANCE_ATTRS:
|
|
407
|
+
import difflib
|
|
408
|
+
close = difflib.get_close_matches(name, [n for n in dir(type(self))
|
|
409
|
+
if not n.startswith("_")]
|
|
410
|
+
+ sorted(_INSTANCE_ATTRS), 1)
|
|
411
|
+
hint = f" (did you mean {close[0]!r}?)" if close else ""
|
|
412
|
+
raise AttributeError(f"{type(self).__name__} has no attribute "
|
|
413
|
+
f"{name!r}{hint}")
|
|
414
|
+
object.__setattr__(self, name, value)
|
|
415
|
+
|
|
416
|
+
def _reset_state(self):
|
|
417
|
+
"""Reset the drawing attributes to their defaults (not the transform)."""
|
|
418
|
+
self._style = _Style()
|
|
419
|
+
self._font_cache = None
|
|
420
|
+
|
|
421
|
+
def _attributes(self):
|
|
422
|
+
return self._style.copy()
|
|
423
|
+
|
|
424
|
+
def _set_attributes(self, attributes):
|
|
425
|
+
self._style = attributes
|
|
426
|
+
|
|
427
|
+
def _push_state(self, reset=False):
|
|
428
|
+
"""Save the drawing attributes (for bodies that must not change them); ``reset``
|
|
429
|
+
starts from the defaults."""
|
|
430
|
+
state = self._attributes()
|
|
431
|
+
if reset:
|
|
432
|
+
self._reset_state()
|
|
433
|
+
return state
|
|
434
|
+
|
|
435
|
+
def _pop_state(self, saved):
|
|
436
|
+
self._set_attributes(saved)
|
|
437
|
+
|
|
438
|
+
def _apply(self, where, style):
|
|
439
|
+
"""Set the call's ``style`` on the state, checked; returns what :meth:`_restore`
|
|
440
|
+
puts back."""
|
|
441
|
+
st = self._style
|
|
442
|
+
saved: list[tuple[str, Any]] = []
|
|
443
|
+
try:
|
|
444
|
+
for name, value in style.items():
|
|
445
|
+
check = _STATE_CHECKS.get(name)
|
|
446
|
+
if check is None:
|
|
447
|
+
raise _unknown_style(where, name)
|
|
448
|
+
value = check(name, value)
|
|
449
|
+
saved.append((name, getattr(st, name)))
|
|
450
|
+
setattr(st, name, value)
|
|
451
|
+
except BaseException:
|
|
452
|
+
self._restore(saved)
|
|
453
|
+
raise
|
|
454
|
+
return saved
|
|
455
|
+
|
|
456
|
+
def _restore(self, saved):
|
|
457
|
+
st = self._style
|
|
458
|
+
for name, value in reversed(saved):
|
|
459
|
+
setattr(st, name, value)
|
|
460
|
+
|
|
461
|
+
@property
|
|
462
|
+
def width(self) -> float:
|
|
463
|
+
"""Page width in the document's unit."""
|
|
464
|
+
return self.page_width / self._recorder.unit_scale
|
|
465
|
+
|
|
466
|
+
@property
|
|
467
|
+
def height(self) -> float:
|
|
468
|
+
"""Page height in the document's unit."""
|
|
469
|
+
return self.page_height / self._recorder.unit_scale
|
|
470
|
+
|
|
471
|
+
# -- state -------------------------------------------------------------
|
|
472
|
+
|
|
473
|
+
@contextlib.contextmanager
|
|
474
|
+
def state(self, **style: Unpack[Style]) -> Generator[Self]:
|
|
475
|
+
"""The body with the graphics state (transform, clip, drawing attributes) saved
|
|
476
|
+
before and restored after; ``style`` sets drawing attributes for the body."""
|
|
477
|
+
self._push()
|
|
478
|
+
stack = self._recorder.state_stack
|
|
479
|
+
depth = len(stack)
|
|
480
|
+
try:
|
|
481
|
+
if style:
|
|
482
|
+
self._apply("state", style)
|
|
483
|
+
yield self
|
|
484
|
+
finally:
|
|
485
|
+
if self._recorder.state_stack is stack and len(stack) == depth:
|
|
486
|
+
self._pop() # (not when a group closed it already)
|
|
487
|
+
|
|
488
|
+
def _push(self):
|
|
489
|
+
self._recorder.save()
|
|
490
|
+
self._recorder.state_stack.append(self._attributes())
|
|
491
|
+
|
|
492
|
+
def _pop(self):
|
|
493
|
+
self._set_attributes(self._recorder.state_stack.pop())
|
|
494
|
+
self._recorder.restore()
|
|
495
|
+
|
|
496
|
+
def translate(self, tx: float, ty: float) -> None:
|
|
497
|
+
"""Move the origin to ``(tx, ty)``."""
|
|
498
|
+
self._recorder.concat(Matrix.translate(tx, ty))
|
|
499
|
+
|
|
500
|
+
def scale(self, sx: float, sy: float | None = None) -> None:
|
|
501
|
+
"""Scale by ``sx`` and ``sy`` (default ``sx``)."""
|
|
502
|
+
self._recorder.concat(Matrix.scale(sx, sy))
|
|
503
|
+
|
|
504
|
+
def rotate(self, degrees: float, cx: float = 0.0, cy: float = 0.0) -> None:
|
|
505
|
+
"""Rotate clockwise (y points down) by ``degrees`` around ``(cx, cy)``."""
|
|
506
|
+
self._recorder.concat(Matrix.rotate(degrees, cx, cy))
|
|
507
|
+
|
|
508
|
+
def skew(self, x_degrees: float = 0.0, y_degrees: float = 0.0) -> None:
|
|
509
|
+
"""Skew along x by ``x_degrees`` then along y by ``y_degrees``."""
|
|
510
|
+
self._recorder.concat(Matrix.skew_x(x_degrees) @ Matrix.skew_y(y_degrees))
|
|
511
|
+
|
|
512
|
+
@overload
|
|
513
|
+
def transform(self, a: Matrix) -> None: ...
|
|
514
|
+
|
|
515
|
+
@overload
|
|
516
|
+
def transform(self, a: float, b: float, c: float, d: float, e: float, f: float) -> None: ...
|
|
517
|
+
|
|
518
|
+
def transform(self, a: Matrix | float, b: float | None = None, c: float | None = None,
|
|
519
|
+
d: float | None = None, e: float | None = None,
|
|
520
|
+
f: float | None = None) -> None:
|
|
521
|
+
"""Concatenate a matrix (a Matrix or its six numbers)."""
|
|
522
|
+
if isinstance(a, Matrix):
|
|
523
|
+
m = a
|
|
524
|
+
elif b is None or c is None or d is None or e is None or f is None:
|
|
525
|
+
raise ArgumentError("transform takes a Matrix or six numbers")
|
|
526
|
+
else:
|
|
527
|
+
m = Matrix(a, b, c, d, e, f)
|
|
528
|
+
self._recorder.concat(m)
|
|
529
|
+
|
|
530
|
+
# -- clipping and shapes ---------------------------------------------------------
|
|
531
|
+
|
|
532
|
+
def clip(self, path: Path | str, *, clip_rule: str | None = None) -> None:
|
|
533
|
+
"""Intersect the clip with ``path`` (a Path or SVG path data) filled with
|
|
534
|
+
``clip_rule`` (default ``fill_rule``), until the enclosing :meth:`state` ends (a
|
|
535
|
+
clip for a body only: :meth:`group` with ``clip_path=``)."""
|
|
536
|
+
path = _path("path", path)
|
|
537
|
+
if clip_rule is not None and clip_rule not in ("nonzero", "evenodd"):
|
|
538
|
+
raise ArgumentError(f"clip_rule must be 'nonzero' or 'evenodd', not {clip_rule!r}")
|
|
539
|
+
self._clip(path, clip_rule or self.fill_rule)
|
|
540
|
+
|
|
541
|
+
def _clip(self, path, rule):
|
|
542
|
+
self._recorder.path(path)
|
|
543
|
+
self._recorder.scene.paint("W* n" if rule == "evenodd" else "W n")
|
|
544
|
+
|
|
545
|
+
def _clip_rect(self, x, y, width, height):
|
|
546
|
+
"""Intersect the clip with a rectangle (``x y w h re W n``)."""
|
|
547
|
+
self._recorder.scene.rect(x, y, width, height, self._recorder.decimals())
|
|
548
|
+
self._recorder.scene.paint("W n", SP)
|
|
549
|
+
|
|
550
|
+
def draw_rect(self, x: float, y: float, width: float, height: float, *, rx: float = 0.0,
|
|
551
|
+
ry: float | None = None, **style: Unpack[Style]) -> None:
|
|
552
|
+
"""Fill and stroke a rectangle, its corners rounded by ``rx`` and ``ry`` (default
|
|
553
|
+
``rx``)."""
|
|
554
|
+
try:
|
|
555
|
+
if rx or ry:
|
|
556
|
+
path = Path().rect(x, y, width, height, rx=rx, ry=ry)
|
|
557
|
+
else:
|
|
558
|
+
path = rect_path(x, y, width, height)
|
|
559
|
+
self._draw(path, style, "draw_rect")
|
|
560
|
+
except (TypeError, ValueError) as exc:
|
|
561
|
+
_numbers(exc, x=x, y=y, width=width, height=height, rx=rx, ry=ry)
|
|
562
|
+
|
|
563
|
+
def draw_circle(self, cx: float, cy: float, r: float, **style: Unpack[Style]) -> None:
|
|
564
|
+
"""Fill and stroke a circle centered on ``(cx, cy)``."""
|
|
565
|
+
try:
|
|
566
|
+
self._draw(ellipse_path(cx, cy, r, r), style, "draw_circle")
|
|
567
|
+
except (TypeError, ValueError) as exc:
|
|
568
|
+
_numbers(exc, cx=cx, cy=cy, r=r)
|
|
569
|
+
|
|
570
|
+
def draw_ellipse(self, cx: float, cy: float, rx: float, ry: float,
|
|
571
|
+
**style: Unpack[Style]) -> None:
|
|
572
|
+
"""Fill and stroke an ellipse centered on ``(cx, cy)``."""
|
|
573
|
+
try:
|
|
574
|
+
self._draw(ellipse_path(cx, cy, rx, ry), style, "draw_ellipse")
|
|
575
|
+
except (TypeError, ValueError) as exc:
|
|
576
|
+
_numbers(exc, cx=cx, cy=cy, rx=rx, ry=ry)
|
|
577
|
+
|
|
578
|
+
def draw_path(self, path: Path | str, *, markers: PathMarker | None = None,
|
|
579
|
+
marker_start: PathMarker | None = None, marker_mid: PathMarker | None = None,
|
|
580
|
+
marker_end: PathMarker | None = None, **style: Unpack[Style]) -> None:
|
|
581
|
+
"""Fill and stroke ``path`` (a Path or SVG path data).
|
|
582
|
+
|
|
583
|
+
:class:`~vec_io.paint.PathMarker` objects are drawn after the path at its vertices:
|
|
584
|
+
``marker_start`` at the first, ``marker_end`` at the last, ``marker_mid`` at the
|
|
585
|
+
ones between (as SVG's), ``markers`` at every vertex without one of those. Markers
|
|
586
|
+
in ``stroke_width`` units are scaled by ``stroke_width``."""
|
|
587
|
+
path = _path("path", path)
|
|
588
|
+
slots = None
|
|
589
|
+
if markers is not None or marker_start is not None or marker_mid is not None \
|
|
590
|
+
or marker_end is not None:
|
|
591
|
+
slots = tuple(markers if m is None else m
|
|
592
|
+
for m in (marker_start, marker_mid, marker_end))
|
|
593
|
+
for m in slots:
|
|
594
|
+
if m is not None and not isinstance(m, PathMarker):
|
|
595
|
+
raise ArgumentError(f"markers are PathMarker objects, not {m!r}")
|
|
596
|
+
if slots is None:
|
|
597
|
+
self._draw(path, style, "draw_path")
|
|
598
|
+
return
|
|
599
|
+
saved = self._apply("draw_path", style) if style else None
|
|
600
|
+
try:
|
|
601
|
+
self._draw_path(path, STATE, STATE)
|
|
602
|
+
self._path_markers(path, slots)
|
|
603
|
+
finally:
|
|
604
|
+
if saved:
|
|
605
|
+
self._restore(saved)
|
|
606
|
+
|
|
607
|
+
def _draw(self, path, style, where):
|
|
608
|
+
"""Fill and stroke ``path`` with the state and the call's ``style``."""
|
|
609
|
+
if not style:
|
|
610
|
+
self._draw_path(path, STATE, STATE)
|
|
611
|
+
return
|
|
612
|
+
fill = style.pop("fill", STATE)
|
|
613
|
+
stroke = style.pop("stroke", STATE)
|
|
614
|
+
try:
|
|
615
|
+
if not style:
|
|
616
|
+
self._draw_path(path, fill, stroke)
|
|
617
|
+
return
|
|
618
|
+
saved = self._apply(where, style)
|
|
619
|
+
try:
|
|
620
|
+
self._draw_path(path, fill, stroke)
|
|
621
|
+
finally:
|
|
622
|
+
self._restore(saved)
|
|
623
|
+
except (TypeError, ValueError):
|
|
624
|
+
for name, value in (("fill", fill), ("stroke", stroke)):
|
|
625
|
+
if value is not STATE:
|
|
626
|
+
_check_paint(name, value)
|
|
627
|
+
raise
|
|
628
|
+
|
|
629
|
+
def _path_markers(self, shape, slots, width=None):
|
|
630
|
+
"""``(start, mid, end)`` markers at the vertices of ``shape``, for a stroke
|
|
631
|
+
``width`` wide (default ``stroke_width``)."""
|
|
632
|
+
if not any(slots):
|
|
633
|
+
return
|
|
634
|
+
verts = shape.vertices()
|
|
635
|
+
width = self.stroke_width if width is None else float(width)
|
|
636
|
+
last = len(verts) - 1
|
|
637
|
+
for index, (x, y, a_in, a_out) in enumerate(verts):
|
|
638
|
+
marker = slots[0] if index == 0 else slots[2] if index == last else slots[1]
|
|
639
|
+
if marker is not None:
|
|
640
|
+
self._place_marker(marker, x, y, a_in, a_out, index == 0, width)
|
|
641
|
+
|
|
642
|
+
def _place_marker(self, marker, x, y, a_in, a_out, first, stroke_width):
|
|
643
|
+
"""One :class:`PathMarker` at vertex ``(x, y)`` between directions ``a_in`` and
|
|
644
|
+
``a_out`` (degrees; ``None``: none)."""
|
|
645
|
+
orient = marker.orient
|
|
646
|
+
if isinstance(orient, str):
|
|
647
|
+
if a_in is None:
|
|
648
|
+
angle = a_out or 0.0
|
|
649
|
+
elif a_out is None:
|
|
650
|
+
angle = a_in
|
|
651
|
+
else:
|
|
652
|
+
diff = (a_out - a_in + 180.0) % 360.0 - 180.0
|
|
653
|
+
angle = a_in + diff / 2.0
|
|
654
|
+
if orient == "auto-start-reverse" and first:
|
|
655
|
+
angle += 180.0
|
|
656
|
+
else:
|
|
657
|
+
angle = orient
|
|
658
|
+
mw, mh = marker.width, marker.height
|
|
659
|
+
if mw <= 0 or mh <= 0:
|
|
660
|
+
return
|
|
661
|
+
m = Matrix.translate(x, y) @ Matrix.rotate(angle)
|
|
662
|
+
if marker.units == "stroke_width":
|
|
663
|
+
m = m @ Matrix.scale(stroke_width)
|
|
664
|
+
vb = marker.view_box
|
|
665
|
+
if vb and not (vb[2] > 0 and vb[3] > 0):
|
|
666
|
+
return # an empty view box disables the marker, as in SVG
|
|
667
|
+
vbm = (view_box_transform(vb, 0, 0, mw, mh, marker.preserve_aspect_ratio) if vb
|
|
668
|
+
else Matrix())
|
|
669
|
+
rx, ry = vbm.apply(*marker.ref)
|
|
670
|
+
self._recorder.save()
|
|
671
|
+
state = self._push_state(reset=True)
|
|
672
|
+
try:
|
|
673
|
+
self._recorder.concat(m @ Matrix.translate(-rx, -ry))
|
|
674
|
+
if marker.clip:
|
|
675
|
+
self._clip_rect(0, 0, mw, mh)
|
|
676
|
+
self._recorder.concat(vbm)
|
|
677
|
+
if isinstance(marker.draw, Marker):
|
|
678
|
+
if marker.draw._form is not None:
|
|
679
|
+
self._recorder.scene.do(marker.draw._form)
|
|
680
|
+
else:
|
|
681
|
+
marker.draw(self)
|
|
682
|
+
finally:
|
|
683
|
+
self._pop_state(state)
|
|
684
|
+
self._recorder.restore()
|
|
685
|
+
|
|
686
|
+
def _draw_path(self, path, fill, stroke):
|
|
687
|
+
st = self._style
|
|
688
|
+
fill = st.fill if fill is STATE else fill
|
|
689
|
+
stroke = st.stroke if stroke is STATE else stroke
|
|
690
|
+
decimals = self._recorder.decimals()
|
|
691
|
+
evenodd = st.fill_rule == "evenodd"
|
|
692
|
+
|
|
693
|
+
def shape(op):
|
|
694
|
+
self._recorder.scene.path(path, decimals)
|
|
695
|
+
self._recorder.scene.paint({"fill": "f*" if evenodd else "f", "stroke": "S",
|
|
696
|
+
"fill_stroke": "B*" if evenodd else "B"}[op])
|
|
697
|
+
|
|
698
|
+
opacity = st.opacity
|
|
699
|
+
self._recorder.paint(shape, fill, stroke, self._line_style(),
|
|
700
|
+
fill_opacity=opacity * st.fill_opacity,
|
|
701
|
+
stroke_opacity=opacity * st.stroke_opacity)
|
|
702
|
+
|
|
703
|
+
def _line_style(self):
|
|
704
|
+
st = self._style
|
|
705
|
+
if st.stroke_width <= 0:
|
|
706
|
+
return None
|
|
707
|
+
return line_style(st.stroke_width, st.stroke_linecap, st.stroke_linejoin,
|
|
708
|
+
st.stroke_miterlimit, st.stroke_dasharray, st.stroke_dashoffset)
|
|
709
|
+
|
|
710
|
+
# -- text ---------------------------------------------------------------
|
|
711
|
+
|
|
712
|
+
@property
|
|
713
|
+
def font(self) -> Font:
|
|
714
|
+
"""The :class:`~vec_io.text.Font` of the current state (``font_family``,
|
|
715
|
+
``font_size``, ``font_weight``, ``font_style``, ``font_stretch``,
|
|
716
|
+
``font_variation_settings``, ``font_optical_sizing``, ``font_embed``,
|
|
717
|
+
``font_variant``, ``font_feature_settings``, ``lang``, else the document's);
|
|
718
|
+
setting it sets those attributes. Sizes are in page units; PDF/A documents embed
|
|
719
|
+
every font."""
|
|
720
|
+
lang = self.lang if self.lang is not None else self.document.lang
|
|
721
|
+
key = (self.font_family, self.font_size, self.font_weight, self.font_style,
|
|
722
|
+
self.font_stretch, self.font_variation_settings, self.font_optical_sizing,
|
|
723
|
+
self.font_embed, self.font_variant, str(self.font_feature_settings), lang)
|
|
724
|
+
cached = self._font_cache
|
|
725
|
+
if cached is not None and cached[0] == key:
|
|
726
|
+
return cached[1]
|
|
727
|
+
font = Font(self.font_family, self.font_size, weight=self.font_weight,
|
|
728
|
+
style=self.font_style, stretch=self.font_stretch,
|
|
729
|
+
variations=self.font_variation_settings or None,
|
|
730
|
+
optical_sizing=self.font_optical_sizing,
|
|
731
|
+
embed=self.font_embed or self.document._pdf_a is not None,
|
|
732
|
+
unit=self._recorder.unit_scale / PT_PER_PX, variant=self.font_variant,
|
|
733
|
+
features=self.font_feature_settings or None, lang=lang)
|
|
734
|
+
self._font_cache = (key, font)
|
|
735
|
+
return font
|
|
736
|
+
|
|
737
|
+
@font.setter
|
|
738
|
+
def font(self, font: Font | str) -> None:
|
|
739
|
+
if isinstance(font, str):
|
|
740
|
+
self._set_font_shorthand(font)
|
|
741
|
+
return
|
|
742
|
+
if not isinstance(font, Font):
|
|
743
|
+
raise ArgumentError(f"font must be a Font or a CSS font shorthand, not {font!r}")
|
|
744
|
+
self.font_family = font.family
|
|
745
|
+
self.font_size = font.size
|
|
746
|
+
self.font_weight = str(font.weight)
|
|
747
|
+
self.font_style = font.style
|
|
748
|
+
self.font_stretch = f"{font.stretch:g}%"
|
|
749
|
+
self.font_variation_settings = dict(font.variations)
|
|
750
|
+
self.font_optical_sizing = font.optical_sizing
|
|
751
|
+
self.font_embed = font.embed
|
|
752
|
+
self.font_variant = font.variant
|
|
753
|
+
self.font_feature_settings = dict(font.features)
|
|
754
|
+
self.lang = font.lang
|
|
755
|
+
|
|
756
|
+
def _set_font_shorthand(self, text):
|
|
757
|
+
"""The CSS ``font`` shorthand (``"italic bold 12px DejaVu Sans"``), as the HTML
|
|
758
|
+
canvas: the size in CSS units (``px``, ``pt``, ``mm``…, ``em`` and ``%`` of the
|
|
759
|
+
current size, keywords); the line height is ignored."""
|
|
760
|
+
from .svg.properties import FONT_SIZES, parse_font
|
|
761
|
+
|
|
762
|
+
longhands = parse_font(text)
|
|
763
|
+
if not longhands:
|
|
764
|
+
raise ArgumentError(f"invalid font {text!r}: give [style] [variant] [weight] "
|
|
765
|
+
f"[stretch] size family, e.g. 'bold 12px DejaVu Sans'")
|
|
766
|
+
px_per_unit = self._recorder.unit_scale / PT_PER_PX
|
|
767
|
+
current = self.font_size * px_per_unit
|
|
768
|
+
size = longhands["font-size"].lower()
|
|
769
|
+
if size in FONT_SIZES:
|
|
770
|
+
px = FONT_SIZES[size]
|
|
771
|
+
elif size == "larger":
|
|
772
|
+
px = current * 1.2
|
|
773
|
+
elif size == "smaller":
|
|
774
|
+
px = current / 1.2
|
|
775
|
+
else:
|
|
776
|
+
px = parse_length(size, current, current, math.nan)
|
|
777
|
+
if not math.isfinite(px) or px < 0:
|
|
778
|
+
raise ArgumentError(f"invalid font size {longhands['font-size']!r}")
|
|
779
|
+
saved = self._style.copy()
|
|
780
|
+
try:
|
|
781
|
+
self.font_style = longhands["font-style"]
|
|
782
|
+
self.font_variant = longhands["font-variant"]
|
|
783
|
+
self.font_weight = longhands["font-weight"]
|
|
784
|
+
self.font_stretch = longhands["font-stretch"]
|
|
785
|
+
self.font_family = longhands["font-family"]
|
|
786
|
+
self.font_size = px / px_per_unit
|
|
787
|
+
except ValueError:
|
|
788
|
+
self._style = saved
|
|
789
|
+
raise ArgumentError(f"invalid font {text!r}") from None
|
|
790
|
+
|
|
791
|
+
def shape_text(self, text: "str | Content", **style: Unpack[Style]) -> GlyphRun:
|
|
792
|
+
"""``text`` (a string or rich content) shaped on one line with the font state
|
|
793
|
+
(:func:`vec_io.text.shape`, with ``letter_spacing``, ``word_spacing``,
|
|
794
|
+
``font_kerning`` and ``direction``); ``style`` for this call."""
|
|
795
|
+
from . import text as _text
|
|
796
|
+
|
|
797
|
+
saved = self._apply("shape_text", style) if style else None
|
|
798
|
+
try:
|
|
799
|
+
return _text.shape(text, self.font, self.document.font_db,
|
|
800
|
+
font_kerning=self.font_kerning,
|
|
801
|
+
letter_spacing=float(self.letter_spacing),
|
|
802
|
+
word_spacing=float(self.word_spacing), direction=self.direction)
|
|
803
|
+
finally:
|
|
804
|
+
if saved:
|
|
805
|
+
self._restore(saved)
|
|
806
|
+
|
|
807
|
+
def measure_text(self, text: "str | Content | GlyphRun",
|
|
808
|
+
**style: Unpack[Style]) -> float:
|
|
809
|
+
"""Width of ``text`` (a string, rich content or shaped run) with the font state;
|
|
810
|
+
``style`` for this call."""
|
|
811
|
+
return (text if isinstance(text, GlyphRun) else self.shape_text(text, **style)).width
|
|
812
|
+
|
|
813
|
+
def text_extent(self, text: "str | Content | GlyphRun",
|
|
814
|
+
**style: Unpack[Style]) -> tuple[float, float, float]:
|
|
815
|
+
"""``(width, ascent, descent)`` of ``text`` (a string, rich content or shaped run)
|
|
816
|
+
on one line: the advance width and the largest ascent and descent (positive) of the
|
|
817
|
+
fonts used, shifted spans included; ``style`` for this call."""
|
|
818
|
+
run = text if isinstance(text, GlyphRun) else self.shape_text(text, **style)
|
|
819
|
+
return run.width, run.ascent, run.descent
|
|
820
|
+
|
|
821
|
+
def draw_text(self, text: "str | Content | GlyphRun", x: float, y: float,
|
|
822
|
+
**style: Unpack[Style]) -> None:
|
|
823
|
+
"""Draw one line of text at ``(x, y)`` (baseline), lined up by ``text_anchor``
|
|
824
|
+
(``start`` is the right end in right-to-left text: ``direction="rtl"``, or
|
|
825
|
+
``"auto"`` and a first strong character right to left); fonts are chosen and
|
|
826
|
+
embedded as needed. ``text`` is a string, rich content (strings and :class:`Span`
|
|
827
|
+
objects; spans without a color use ``fill``) or a :class:`~vec_io.text.GlyphRun`
|
|
828
|
+
(shaped with any font database)."""
|
|
829
|
+
try:
|
|
830
|
+
if not style:
|
|
831
|
+
self._draw_text(text, x, y, STATE, STATE)
|
|
832
|
+
return
|
|
833
|
+
fill = style.pop("fill", STATE)
|
|
834
|
+
stroke = style.pop("stroke", STATE)
|
|
835
|
+
saved = self._apply("draw_text", style) if style else None
|
|
836
|
+
try:
|
|
837
|
+
self._draw_text(text, x, y, fill, stroke)
|
|
838
|
+
finally:
|
|
839
|
+
if saved:
|
|
840
|
+
self._restore(saved)
|
|
841
|
+
except (TypeError, ValueError) as exc:
|
|
842
|
+
_numbers(exc, x=x, y=y)
|
|
843
|
+
|
|
844
|
+
def _draw_text(self, text, x, y, fill, stroke):
|
|
845
|
+
from .text import draw_glyphs
|
|
846
|
+
from .text.bidi import base_level
|
|
847
|
+
|
|
848
|
+
st = self._style
|
|
849
|
+
fill = st.fill if fill is STATE else fill
|
|
850
|
+
stroke = st.stroke if stroke is STATE else stroke
|
|
851
|
+
run = text if isinstance(text, GlyphRun) else self.shape_text(text)
|
|
852
|
+
anchor = st.text_anchor
|
|
853
|
+
if anchor != "middle" and (st.direction == "rtl" or st.direction == "auto"
|
|
854
|
+
and base_level(run.text) == 1):
|
|
855
|
+
anchor = "end" if anchor == "start" else "start"
|
|
856
|
+
x -= run.width / 2.0 if anchor == "middle" else run.width if anchor == "end" else 0.0
|
|
857
|
+
draw_glyphs(self, run.segments, x, y, fill, stroke, self._line_style())
|
|
858
|
+
|
|
859
|
+
def draw_text_on_path(self, text: "str | Content | GlyphRun", path: Path | str, *,
|
|
860
|
+
offset: float | str = 0.0, side: str = "left",
|
|
861
|
+
method: str = "align", **style: Unpack[Style]) -> None:
|
|
862
|
+
"""Draw ``text`` along ``path`` (a Path or SVG path data), as SVG's ``<textPath>``.
|
|
863
|
+
|
|
864
|
+
The text is shaped as :meth:`draw_text` shapes it (kerning, spacing) and starts at
|
|
865
|
+
``offset`` along the path (a length, or a percentage of the path's length:
|
|
866
|
+
``"50%"``), lined up there by ``text_anchor``. Each glyph is drawn where the path
|
|
867
|
+
is under its middle, rotated with the path's direction there; glyphs whose middle
|
|
868
|
+
is past either end are left out. ``side="right"`` runs the path the other way (the
|
|
869
|
+
text on its other side). ``method="stretch"`` bends each glyph's outline along the
|
|
870
|
+
path, drawn as a path (not text); ``"align"`` keeps glyphs rigid. Underlines and
|
|
871
|
+
links of spans are not drawn.
|
|
872
|
+
"""
|
|
873
|
+
if side not in ("left", "right"):
|
|
874
|
+
raise ArgumentError("side is 'left' or 'right'")
|
|
875
|
+
if method not in ("align", "stretch"):
|
|
876
|
+
raise ArgumentError("method is 'align' or 'stretch'")
|
|
877
|
+
fill = style.pop("fill", STATE)
|
|
878
|
+
stroke = style.pop("stroke", STATE)
|
|
879
|
+
saved = self._apply("draw_text_on_path", style) if style else None
|
|
880
|
+
try:
|
|
881
|
+
self._text_on_path(text, path, offset, side, method, fill, stroke)
|
|
882
|
+
finally:
|
|
883
|
+
if saved:
|
|
884
|
+
self._restore(saved)
|
|
885
|
+
|
|
886
|
+
def _text_on_path(self, text, path, offset, side, method, fill, stroke):
|
|
887
|
+
from .geometry import PathMeasure
|
|
888
|
+
from .text import path as text_path
|
|
889
|
+
|
|
890
|
+
line_path: Path = _path("path", path)
|
|
891
|
+
if side == "right":
|
|
892
|
+
line_path = text_path.reverse(line_path)
|
|
893
|
+
fill = self.fill if fill is STATE else fill
|
|
894
|
+
stroke = self.stroke if stroke is STATE else stroke
|
|
895
|
+
measure = PathMeasure(line_path)
|
|
896
|
+
if measure.length <= 0:
|
|
897
|
+
return
|
|
898
|
+
run = text if isinstance(text, GlyphRun) else self.shape_text(text)
|
|
899
|
+
x = text_path.start_offset(offset, measure.length)
|
|
900
|
+
anchor = self.text_anchor
|
|
901
|
+
x -= run.width / 2.0 if anchor == "middle" else run.width if anchor == "end" else 0.0
|
|
902
|
+
line = self._line_style()
|
|
903
|
+
for seg in run.segments:
|
|
904
|
+
style, size = seg.style, seg.style.size
|
|
905
|
+
color = fill if style.color is None else style.color
|
|
906
|
+
placed = []
|
|
907
|
+
for gid, chars, advance, adjust in zip(seg.gids, seg.texts, seg.advances,
|
|
908
|
+
seg.adjusts):
|
|
909
|
+
# (a glyph's middle counts its kerning or word spacing, as SVG text's)
|
|
910
|
+
m = text_path.place(measure, x, advance + adjust, -style.rise)
|
|
911
|
+
if m is not None:
|
|
912
|
+
placed.append((gid, chars, x, m))
|
|
913
|
+
x += advance + adjust
|
|
914
|
+
if not placed or size <= 0:
|
|
915
|
+
continue
|
|
916
|
+
outline = getattr(seg.face, "glyph_path", None)
|
|
917
|
+
if method == "stretch" and outline is not None:
|
|
918
|
+
self._bent_glyphs(seg, placed, measure, outline, color, stroke)
|
|
919
|
+
continue
|
|
920
|
+
flip = Matrix(1, 0, 0, -1, 0, 0)
|
|
921
|
+
|
|
922
|
+
def show(mode, seg=seg, placed=placed, size=size):
|
|
923
|
+
for gid, chars, _, m in placed:
|
|
924
|
+
self._recorder.show_glyphs(seg.face, size, [(gid, chars, 0.0)],
|
|
925
|
+
m @ flip, mode,
|
|
926
|
+
synth_italic=seg.synth[1],
|
|
927
|
+
request=seg.style.chain.request)
|
|
928
|
+
|
|
929
|
+
self._recorder.paint_text(show, color, stroke, line, synth_bold=seg.synth[0],
|
|
930
|
+
size=size, opacity=self.opacity,
|
|
931
|
+
fill_opacity=self.opacity * self.fill_opacity,
|
|
932
|
+
stroke_opacity=self.opacity * self.stroke_opacity)
|
|
933
|
+
|
|
934
|
+
def _bent_glyphs(self, seg, placed, measure, outline, fill, stroke):
|
|
935
|
+
"""Glyphs of a segment bent along a path (``method="stretch"``), as one path."""
|
|
936
|
+
from .text import path as text_path
|
|
937
|
+
|
|
938
|
+
size = seg.style.size
|
|
939
|
+
face = seg.face
|
|
940
|
+
s = size / face.units_per_em
|
|
941
|
+
glyph = Matrix(s, 0, 0, -s, 0, 0)
|
|
942
|
+
if seg.synth[1]:
|
|
943
|
+
glyph = glyph @ Matrix(1, 0, 0.21, 1, 0, 0)
|
|
944
|
+
shape = Path()
|
|
945
|
+
for gid, _, x, _ in placed:
|
|
946
|
+
shape.extend(outline(gid).transformed(
|
|
947
|
+
Matrix.translate(x, -seg.style.rise) @ glyph))
|
|
948
|
+
bent = text_path.bend(measure, shape, size / 32.0)
|
|
949
|
+
saved = self.fill_rule
|
|
950
|
+
self.fill_rule = "nonzero"
|
|
951
|
+
try:
|
|
952
|
+
self._draw_path(bent, fill, stroke)
|
|
953
|
+
finally:
|
|
954
|
+
self.fill_rule = saved
|
|
955
|
+
|
|
956
|
+
def layout_text(self, content: "Content", width: float, height: float | None = None, *,
|
|
957
|
+
text_align: str = "start", line_height: float = 1.2,
|
|
958
|
+
overflow: str = "visible", breaking: str = "greedy",
|
|
959
|
+
paragraph_spacing: float = 0.0, text_indent: float = 0.0,
|
|
960
|
+
hyphens: str = "manual", **style: Unpack[Style]) -> "TextLayout":
|
|
961
|
+
"""Lay out a paragraph (or several) in a box ``width`` wide, with the font state
|
|
962
|
+
(``style`` for this call).
|
|
963
|
+
|
|
964
|
+
``content`` is a string or a list of strings and :class:`Span`
|
|
965
|
+
objects; a blank line separates paragraphs, ``\\n`` forces a line
|
|
966
|
+
break; lines break where UAX #14 allows, U+00AD (soft hyphen) and U+200B mark
|
|
967
|
+
extra break points, ``hyphens="auto"`` hyphenates words of the state's ``lang`` (a
|
|
968
|
+
BCP 47 tag, also the font's forms for it, ``locl``; else the document's; English
|
|
969
|
+
hyphenation when neither is given).
|
|
970
|
+
``text_align``: CSS's (``start``, ``end``, ``left``, ``right``, ``center``,
|
|
971
|
+
``justify``). Kerning follows ``font_kerning``; ``font_variant`` with
|
|
972
|
+
``no-common-ligatures`` turns ligatures off.
|
|
973
|
+
Returns a :class:`TextLayout`; call its ``draw(x, y)`` to place it.
|
|
974
|
+
See docs/api.md for the options.
|
|
975
|
+
"""
|
|
976
|
+
from .text.breaking import layout_text
|
|
977
|
+
|
|
978
|
+
if text_align not in _TEXT_ALIGNS:
|
|
979
|
+
hint = " (use 'center')" if text_align == "middle" else ""
|
|
980
|
+
raise ArgumentError(f"text_align must be one of {', '.join(map(repr, _TEXT_ALIGNS))}, "
|
|
981
|
+
f"not {text_align!r}{hint}")
|
|
982
|
+
saved = self._apply("layout_text", style) if style else None
|
|
983
|
+
try:
|
|
984
|
+
return layout_text(self, content, width, height, text_align, line_height,
|
|
985
|
+
overflow, breaking, paragraph_spacing, text_indent, hyphens,
|
|
986
|
+
self.font.lang)
|
|
987
|
+
finally:
|
|
988
|
+
if saved:
|
|
989
|
+
self._restore(saved)
|
|
990
|
+
|
|
991
|
+
def draw_text_box(self, content: "Content", x: float, y: float, width: float,
|
|
992
|
+
height: float | None = None, *, text_align: str = "start",
|
|
993
|
+
line_height: float = 1.2, overflow: str = "visible",
|
|
994
|
+
breaking: str = "greedy", paragraph_spacing: float = 0.0,
|
|
995
|
+
text_indent: float = 0.0, hyphens: str = "manual",
|
|
996
|
+
**style: Unpack[Style]) -> "TextLayout":
|
|
997
|
+
"""Lay out ``content`` (see :meth:`layout_text`) and draw it with the box's top-left
|
|
998
|
+
corner at ``(x, y)`` (text without a color of its own in ``fill``); returns the
|
|
999
|
+
:class:`TextLayout`."""
|
|
1000
|
+
saved = self._apply("draw_text_box", style) if style else None
|
|
1001
|
+
try:
|
|
1002
|
+
layout = self.layout_text(content, width, height, text_align=text_align,
|
|
1003
|
+
line_height=line_height, overflow=overflow,
|
|
1004
|
+
breaking=breaking, paragraph_spacing=paragraph_spacing,
|
|
1005
|
+
text_indent=text_indent, hyphens=hyphens)
|
|
1006
|
+
if height is not None and overflow == "clip":
|
|
1007
|
+
with self.group(clip_path=rect_path(x, y, width, height)):
|
|
1008
|
+
layout.draw(x, y)
|
|
1009
|
+
else:
|
|
1010
|
+
layout.draw(x, y)
|
|
1011
|
+
finally:
|
|
1012
|
+
if saved:
|
|
1013
|
+
self._restore(saved)
|
|
1014
|
+
return layout
|
|
1015
|
+
|
|
1016
|
+
def draw_paragraphs(self, paragraphs: "Paragraphs", x: float, y: float,
|
|
1017
|
+
**style: Unpack[Style]) -> None:
|
|
1018
|
+
"""Draw text laid out by :func:`vec_io.text.layout` with the top-left corner of its
|
|
1019
|
+
box at ``(x, y)``; glyphs without a color use ``fill`` (default: the state's);
|
|
1020
|
+
``style`` for this call."""
|
|
1021
|
+
from .text import draw_glyphs
|
|
1022
|
+
|
|
1023
|
+
fill = style.pop("fill", STATE)
|
|
1024
|
+
saved = self._apply("draw_paragraphs", style) if style else None
|
|
1025
|
+
try:
|
|
1026
|
+
if fill is STATE:
|
|
1027
|
+
fill = self._style.fill
|
|
1028
|
+
for line in paragraphs.line_cells():
|
|
1029
|
+
if line.glyphs:
|
|
1030
|
+
draw_glyphs(self, line.glyphs, x + line.offset, y + line.baseline, fill,
|
|
1031
|
+
top=y + line.top, height=line.height)
|
|
1032
|
+
finally:
|
|
1033
|
+
if saved:
|
|
1034
|
+
self._restore(saved)
|
|
1035
|
+
|
|
1036
|
+
# -- images, groups, masks -------------------------------------------------
|
|
1037
|
+
|
|
1038
|
+
def _bulk_paints(self, fill, stroke, black=False):
|
|
1039
|
+
"""``fill`` and ``stroke`` (one paint or a column) faded by the state's
|
|
1040
|
+
``fill_opacity`` and ``stroke_opacity``; ``black``: the stroke of a line call
|
|
1041
|
+
(black when the state has none)."""
|
|
1042
|
+
st = self._style
|
|
1043
|
+
if st.fill_opacity != 1 and fill is not None:
|
|
1044
|
+
fill = _fade(st.fill if fill is STATE else fill, st.fill_opacity)
|
|
1045
|
+
if st.stroke_opacity != 1 and stroke is not None:
|
|
1046
|
+
if stroke is STATE:
|
|
1047
|
+
stroke = st.stroke or ("black" if black else None)
|
|
1048
|
+
stroke = _fade(stroke, st.stroke_opacity)
|
|
1049
|
+
return fill, stroke
|
|
1050
|
+
|
|
1051
|
+
def draw_markers(self, x: ArrayLike, y: ArrayLike, *,
|
|
1052
|
+
marker: "Path | str | Marker | Sequence[Path | str] | None" = None,
|
|
1053
|
+
size: float | ArrayLike = 6.0, fill: PaintLike = STATE,
|
|
1054
|
+
stroke: PaintLike = STATE, stroke_width: float | ArrayLike | None = None,
|
|
1055
|
+
opacity: float | ArrayLike = 1.0,
|
|
1056
|
+
simplify: SimplifyLike = None,
|
|
1057
|
+
**style: Unpack[ItemStyle]) -> None:
|
|
1058
|
+
"""Draw a marker at many points (fast, for large scatter plots).
|
|
1059
|
+
|
|
1060
|
+
``marker`` is a :class:`Path` or SVG path data in a unit box centered on the origin
|
|
1061
|
+
(scaled by ``size``; default: the unit circle), or a :class:`~vec_io.paint.Marker`
|
|
1062
|
+
recorded with :meth:`marker` (drawn as recorded, at every point).
|
|
1063
|
+
|
|
1064
|
+
``marker``, ``size``, ``fill``, ``stroke``, ``stroke_width`` (default: the state's)
|
|
1065
|
+
and ``opacity`` each take one value for all points or a column with
|
|
1066
|
+
one value per point (colors as CSS strings, ``(r, g, b[, a])`` tuples of floats in
|
|
1067
|
+
[0, 1] or :class:`CMYK` values, or an ``(n, 3)`` / ``(n, 4)`` buffer of floats in
|
|
1068
|
+
[0, 1]; ``None`` entries paint nothing). ``opacity`` multiplies the fill and stroke
|
|
1069
|
+
alpha, as the state's ``opacity`` does. Points with a NaN, infinite or ``None``
|
|
1070
|
+
coordinate are skipped. ``style``: other drawing attributes for this call.
|
|
1071
|
+
|
|
1072
|
+
Markers are stored once in the PDF and placed at each point.
|
|
1073
|
+
``simplify=True`` and ``"auto"`` (300 dpi) or a resolution leave out
|
|
1074
|
+
the markers that later content on the page hides at that resolution
|
|
1075
|
+
(see :meth:`group`);
|
|
1076
|
+
``None`` follows the enclosing group and the output (:meth:`Document.write`);
|
|
1077
|
+
``False`` never leaves any out.
|
|
1078
|
+
"""
|
|
1079
|
+
saved = self._apply("draw_markers", style) if style else None
|
|
1080
|
+
try:
|
|
1081
|
+
fill, stroke = self._bulk_paints(fill, stroke)
|
|
1082
|
+
with self._recorder.simplified(simplify, _MARKERS):
|
|
1083
|
+
self._markers(x, y, marker, size, fill, stroke, stroke_width, opacity)
|
|
1084
|
+
finally:
|
|
1085
|
+
if saved:
|
|
1086
|
+
self._restore(saved)
|
|
1087
|
+
|
|
1088
|
+
def _markers(self, xs: Any, ys: Any, marker: Any, size: Any, fill: Any, stroke: Any,
|
|
1089
|
+
stroke_width: Any, opacity: Any) -> None:
|
|
1090
|
+
fill = self.fill if fill is STATE else fill
|
|
1091
|
+
stroke = self.stroke if stroke is STATE else stroke
|
|
1092
|
+
stroke_width = self.stroke_width if stroke_width is None else stroke_width
|
|
1093
|
+
(xs, ys), (fills, strokes, shapes, sizes, widths, opacities) = per_point_arguments(
|
|
1094
|
+
(xs, ys), "x and y", [(fill, "fill", "color"), (stroke, "stroke", "color"),
|
|
1095
|
+
(marker, "marker", "shape"), (size, "size", "number"),
|
|
1096
|
+
(stroke_width, "stroke_width", "number"),
|
|
1097
|
+
(opacity, "opacity", "number")])
|
|
1098
|
+
if not xs:
|
|
1099
|
+
return
|
|
1100
|
+
uniform = (shapes is None and sizes is None and widths is None and opacities is None
|
|
1101
|
+
and strokes is None and (fills is None or _all_opaque(fills)))
|
|
1102
|
+
if not uniform:
|
|
1103
|
+
self._draw_varying_markers(xs, ys, marker, size, fill, stroke, stroke_width,
|
|
1104
|
+
opacity, shapes, sizes, fills, strokes, widths,
|
|
1105
|
+
opacities)
|
|
1106
|
+
return
|
|
1107
|
+
if fills is not None and isinstance(marker, Marker):
|
|
1108
|
+
raise ArgumentError("per-point colors need a shape marker, not a recorded Marker")
|
|
1109
|
+
alpha = cast(float, opacity) * self.opacity # per-point opacity went above
|
|
1110
|
+
if not _alpha(alpha) > 0:
|
|
1111
|
+
return
|
|
1112
|
+
name = self._marker_form(marker, size, fill, stroke, stroke_width,
|
|
1113
|
+
per_point_fill=fills is not None, alpha=alpha)
|
|
1114
|
+
if name is None:
|
|
1115
|
+
return
|
|
1116
|
+
doc = self.document
|
|
1117
|
+
sc = self._recorder.scene
|
|
1118
|
+
gs = doc._opacity_gs(alpha)
|
|
1119
|
+
decimals = self._recorder.decimals()
|
|
1120
|
+
px = _scene.quantize(cast(array.array, xs), decimals) # from per_point_arguments
|
|
1121
|
+
py = _scene.quantize(cast(array.array, ys), decimals)
|
|
1122
|
+
x, y = sc.column(px), sc.column(py)
|
|
1123
|
+
if fills is None:
|
|
1124
|
+
sc.markers(name, -1 if gs is None else gs, decimals, _api.MARKERS_PLAIN, x, y)
|
|
1125
|
+
elif (doc._plain()
|
|
1126
|
+
and (isinstance(fills, ColorList) or set(map(type, fills)) <= {tuple})):
|
|
1127
|
+
flat = _flat_rgba(fills)
|
|
1128
|
+
rgb = [_scene.quantize(flat[k::4], 4) for k in range(3)]
|
|
1129
|
+
sc.markers(name, -1 if gs is None else gs, decimals, _api.MARKERS_RGB, x, y,
|
|
1130
|
+
tuple(sc.column(c) for c in rgb))
|
|
1131
|
+
else:
|
|
1132
|
+
palette = Palette()
|
|
1133
|
+
specs: dict[Any, int] = {}
|
|
1134
|
+
index = array.array("i", bytes(4 * len(fills)))
|
|
1135
|
+
for i, c in enumerate(fills):
|
|
1136
|
+
k = specs.get(c)
|
|
1137
|
+
if k is None:
|
|
1138
|
+
k = specs[c] = palette.add(doc._color_spec(_compact(c)))
|
|
1139
|
+
index[i] = k
|
|
1140
|
+
sc.markers(name, -1 if gs is None else gs, decimals, _api.MARKERS_PALETTE, x, y,
|
|
1141
|
+
(sc.column(index), *palette.columns(sc)))
|
|
1142
|
+
|
|
1143
|
+
def _draw_varying_markers(self, xs, ys, marker, size, fill, stroke, stroke_width, opacity,
|
|
1144
|
+
shapes, sizes, fills, strokes, widths, opacities):
|
|
1145
|
+
"""Markers whose shape, size, colors, width or opacity vary per point.
|
|
1146
|
+
|
|
1147
|
+
Each shape is stored once at unit size per paint kind (fill, stroke
|
|
1148
|
+
or both); every point sets its own colors, alphas and line width.
|
|
1149
|
+
"""
|
|
1150
|
+
if isinstance(marker, Marker) or (shapes is not None and any(
|
|
1151
|
+
isinstance(s, Marker) for s in shapes)):
|
|
1152
|
+
raise ArgumentError("varying marker parameters need shape markers, not recorded "
|
|
1153
|
+
"Markers")
|
|
1154
|
+
n = len(xs)
|
|
1155
|
+
|
|
1156
|
+
def flat(value, what):
|
|
1157
|
+
if isinstance(value, (_Gradient, Pattern)):
|
|
1158
|
+
raise ArgumentError(f"{what} must be a flat color")
|
|
1159
|
+
rgba = to_rgba(value) if value is not None else None
|
|
1160
|
+
if value is not None and rgba is None:
|
|
1161
|
+
raise ArgumentError(f"{what} must be a flat color")
|
|
1162
|
+
return rgba
|
|
1163
|
+
|
|
1164
|
+
fill0 = None if fills is not None else flat(fill, "marker fill")
|
|
1165
|
+
stroke0 = None if strokes is not None else flat(stroke, "marker stroke")
|
|
1166
|
+
shape_keys = []
|
|
1167
|
+
shape_index = {}
|
|
1168
|
+
|
|
1169
|
+
def shape_id(shape):
|
|
1170
|
+
key = (shape if isinstance(shape, str) or shape is None else
|
|
1171
|
+
(bytes(shape.verbs), shape.coords.tobytes()) if isinstance(shape, Path)
|
|
1172
|
+
else id(shape))
|
|
1173
|
+
if key not in shape_index:
|
|
1174
|
+
marker_path(shape) # validate early
|
|
1175
|
+
shape_index[key] = len(shape_keys)
|
|
1176
|
+
shape_keys.append(shape)
|
|
1177
|
+
return shape_index[key]
|
|
1178
|
+
|
|
1179
|
+
if shapes is not None:
|
|
1180
|
+
shape_ids = array.array("i", map(shape_id, shapes))
|
|
1181
|
+
base_shape = 0
|
|
1182
|
+
else:
|
|
1183
|
+
shape_ids, base_shape = None, shape_id(marker)
|
|
1184
|
+
g_opacity = min(1.0, self.opacity) if self.opacity > 0 else 0.0
|
|
1185
|
+
doc = self.document
|
|
1186
|
+
plain = doc._plain()
|
|
1187
|
+
|
|
1188
|
+
def colors_of(given, one):
|
|
1189
|
+
"""(per-item colors, components or None): plain tuples in bulk."""
|
|
1190
|
+
if given is None:
|
|
1191
|
+
if one is None or type(one) is tuple:
|
|
1192
|
+
return [one] * n, array.array("d", one or (math.nan,) * 4) * n
|
|
1193
|
+
return [one] * n, None
|
|
1194
|
+
if set(map(type, given)) <= {tuple, type(None), ColorList}:
|
|
1195
|
+
return given, _flat_rgba(given)
|
|
1196
|
+
return given, None
|
|
1197
|
+
|
|
1198
|
+
fill_list, fill_flat = colors_of(fills, fill0)
|
|
1199
|
+
stroke_list, stroke_flat = colors_of(strokes, stroke0)
|
|
1200
|
+
sc = self._recorder.scene
|
|
1201
|
+
|
|
1202
|
+
def alpha_column(colors, flat):
|
|
1203
|
+
if flat is not None:
|
|
1204
|
+
return flat[3::4]
|
|
1205
|
+
return array.array("d", [math.nan if c is None else as_rgba(c)[3] for c in colors])
|
|
1206
|
+
|
|
1207
|
+
plan = _emit.markers_plan(
|
|
1208
|
+
_emit.Columns(sizes if sizes is not None else float(size),
|
|
1209
|
+
opacities if opacities is not None else float(opacity),
|
|
1210
|
+
alpha_column(fill_list, fill_flat),
|
|
1211
|
+
alpha_column(stroke_list, stroke_flat),
|
|
1212
|
+
widths if widths is not None else float(stroke_width)),
|
|
1213
|
+
shape_ids, base_shape, g_opacity, n)
|
|
1214
|
+
drawn, kind, opacity_id, form_id, opacities, form_keys, events, rel_max = plan
|
|
1215
|
+
if not drawn:
|
|
1216
|
+
return
|
|
1217
|
+
palette = Palette()
|
|
1218
|
+
|
|
1219
|
+
def paints(colors, flat, bit, stroking):
|
|
1220
|
+
"""Colour columns (r, g, b, -1), or (-1, -1, -1, per-item palette indices) of
|
|
1221
|
+
their selections (in item order, as they may create resources)."""
|
|
1222
|
+
if plain and flat is not None:
|
|
1223
|
+
return tuple(sc.qcolumn(flat[k::4], 4) for k in range(3)) + (-1,)
|
|
1224
|
+
used = [c if kind[i] & bit else None for i, c in enumerate(colors)]
|
|
1225
|
+
specs = doc._color_specs(used)
|
|
1226
|
+
index = array.array("i", [-1 if sp is None else palette.add(sp, stroking)
|
|
1227
|
+
for sp in specs])
|
|
1228
|
+
return (-1, -1, -1, sc.column(index))
|
|
1229
|
+
|
|
1230
|
+
fill_cols = paints(fill_list, fill_flat, 1, False)
|
|
1231
|
+
stroke_cols = paints(stroke_list, stroke_flat, 2, True)
|
|
1232
|
+
opacity_gs = array.array("i", bytes(4 * len(opacities)))
|
|
1233
|
+
translucent = any(min(pair) < 1 for pair in opacities)
|
|
1234
|
+
forms = array.array("i", bytes(4 * len(form_keys)))
|
|
1235
|
+
for what, i in events:
|
|
1236
|
+
if what == 0:
|
|
1237
|
+
gs = doc._opacity_gs(*opacities[i])
|
|
1238
|
+
opacity_gs[i] = -1 if gs is None else gs
|
|
1239
|
+
else:
|
|
1240
|
+
shape, k = form_keys[i]
|
|
1241
|
+
path = marker_path(shape_keys[shape])
|
|
1242
|
+
b = path.bbox() or (0, 0, 0, 0)
|
|
1243
|
+
pad = 2 * rel_max + 0.01
|
|
1244
|
+
# under an alpha below 1, f then S (B would be a knockout)
|
|
1245
|
+
ops = {1: ("f",), 2: ("S",), 3: ("f", "S") if translucent else ("B",)}[k]
|
|
1246
|
+
form = Scene()
|
|
1247
|
+
if ops != ("f",):
|
|
1248
|
+
form.line((_scene.LINE_MITER, 0.0, 0, 0, 4.0, None, 0.0))
|
|
1249
|
+
for op in ops:
|
|
1250
|
+
# (unit size, scaled per point: full precision)
|
|
1251
|
+
form.path(path, 6)
|
|
1252
|
+
form.paint(op)
|
|
1253
|
+
forms[i] = doc._form(form, [b[0] - pad, b[1] - pad, b[2] + pad, b[3] + pad],
|
|
1254
|
+
prefix="Mk")
|
|
1255
|
+
decimals = self._recorder.decimals()
|
|
1256
|
+
pal = palette.columns(sc) if palette.index else (-1, -1)
|
|
1257
|
+
sc.markers_v(decimals, (
|
|
1258
|
+
sc.column(bytes(kind)), sc.qcolumn(cast(array.array, xs), decimals),
|
|
1259
|
+
sc.qcolumn(cast(array.array, ys), decimals),
|
|
1260
|
+
sc.column(sizes if sizes is not None else array.array("d", [float(size)])),
|
|
1261
|
+
sc.column(widths if widths is not None else array.array("d", [float(stroke_width)])),
|
|
1262
|
+
*fill_cols, *stroke_cols, *pal, sc.column(opacity_id), sc.column(opacity_gs),
|
|
1263
|
+
sc.column(form_id), sc.column(forms)))
|
|
1264
|
+
|
|
1265
|
+
def _marker_form(self, marker, size, fill, stroke, stroke_width, per_point_fill,
|
|
1266
|
+
alpha=1.0):
|
|
1267
|
+
"""Form XObject drawing one marker centered on the origin (drawn under ``alpha``)."""
|
|
1268
|
+
if isinstance(marker, Marker):
|
|
1269
|
+
return marker._form
|
|
1270
|
+
saved = self._recorder.begin_substream(self._recorder.absolute_ctm())
|
|
1271
|
+
state = self._push_state(reset=True)
|
|
1272
|
+
try:
|
|
1273
|
+
path = marker_path(marker).transformed(Matrix.scale(size))
|
|
1274
|
+
line = line_style(stroke_width) if stroke is not None and stroke_width > 0 else None
|
|
1275
|
+
fill_sel = None
|
|
1276
|
+
if per_point_fill:
|
|
1277
|
+
fill_sel = (None, 1.0, None) # color comes from the caller
|
|
1278
|
+
elif fill is not None:
|
|
1279
|
+
fill_sel = self._recorder.paint_selection(fill, False)
|
|
1280
|
+
stroke_sel = self._recorder.paint_selection(stroke, True) if line else None
|
|
1281
|
+
for sel in (fill_sel, stroke_sel):
|
|
1282
|
+
if sel is not None and sel[2] is not None:
|
|
1283
|
+
raise ArgumentError("marker colors must be flat colors")
|
|
1284
|
+
if fill_sel is None and stroke_sel is None:
|
|
1285
|
+
return None
|
|
1286
|
+
self._recorder.set_opacity(fill_sel[1] if fill_sel else 1.0,
|
|
1287
|
+
stroke_sel[1] if stroke_sel else 1.0)
|
|
1288
|
+
if fill_sel and fill_sel[0]:
|
|
1289
|
+
self._recorder.scene.color(fill_sel[0])
|
|
1290
|
+
if stroke_sel:
|
|
1291
|
+
self._recorder.scene.color(stroke_sel[0], True)
|
|
1292
|
+
self._recorder.scene.line(line)
|
|
1293
|
+
if fill_sel and stroke_sel and min(alpha, fill_sel[1], stroke_sel[1]) < 1:
|
|
1294
|
+
self._recorder.path(path) # (B would be a knockout)
|
|
1295
|
+
self._recorder.scene.paint("f")
|
|
1296
|
+
self._recorder.path(path)
|
|
1297
|
+
self._recorder.scene.paint("S")
|
|
1298
|
+
else:
|
|
1299
|
+
self._recorder.path(path)
|
|
1300
|
+
self._recorder.scene.paint("B" if fill_sel and stroke_sel else
|
|
1301
|
+
"f" if fill_sel else "S")
|
|
1302
|
+
b = path.bbox() or (0, 0, 0, 0)
|
|
1303
|
+
pad = (stroke_width if stroke_sel else 0) * 2 + 1
|
|
1304
|
+
bbox = [b[0] - pad, b[1] - pad, b[2] + pad, b[3] + pad]
|
|
1305
|
+
finally:
|
|
1306
|
+
self._pop_state(state)
|
|
1307
|
+
content = self._recorder.end_substream(saved)
|
|
1308
|
+
return self.document._form(content, bbox, prefix="Mk")
|
|
1309
|
+
|
|
1310
|
+
def draw_image(self, source: "PathLike | bytes | Image", x: float, y: float,
|
|
1311
|
+
width: float | None = None, height: float | None = None, *,
|
|
1312
|
+
preserve_aspect_ratio: str = "xMidYMid meet", opacity: float = 1.0,
|
|
1313
|
+
smooth: bool | None = None) -> None:
|
|
1314
|
+
"""Draw an image: a path, ``data:`` URI or bytes of a format SVG's ``<image>`` takes
|
|
1315
|
+
or TIFF, or an :class:`~vec_io.image.Image` (:meth:`~vec_io.document.Page.render`).
|
|
1316
|
+
|
|
1317
|
+
A relative path is resolved against the document's ``base_dir``.
|
|
1318
|
+
Without ``width``/``height`` the image's pixel size is used (in page
|
|
1319
|
+
units); with only one of them the aspect ratio is kept.
|
|
1320
|
+
``smooth=False`` keeps pixels sharp when scaled (pixel art, data
|
|
1321
|
+
images). Raises :class:`~vec_io.ImageError` for an image that cannot be read,
|
|
1322
|
+
``FileNotFoundError`` for a missing file.
|
|
1323
|
+
"""
|
|
1324
|
+
from .image import Image
|
|
1325
|
+
from .image.resource import EncodedImage
|
|
1326
|
+
|
|
1327
|
+
if not isinstance(source, (str, os.PathLike, bytes, bytearray, Image, EncodedImage)):
|
|
1328
|
+
raise ArgumentError(f"source must be a path, a data: URI, bytes or an Image, not "
|
|
1329
|
+
f"{type(source).__name__}" + (" (Image(width, height, "
|
|
1330
|
+
"channels, data) takes a buffer)" if hasattr(
|
|
1331
|
+
source, "__buffer__") else ""))
|
|
1332
|
+
x, y = _number("x", x), _number("y", y)
|
|
1333
|
+
width = None if width is None else _number("width", width)
|
|
1334
|
+
height = None if height is None else _number("height", height)
|
|
1335
|
+
opacity = _number("opacity", opacity)
|
|
1336
|
+
name, iw, ih, unit = self.document._image(source, smooth=smooth, strict=True)
|
|
1337
|
+
if width is None:
|
|
1338
|
+
width = float(iw) if height is None else height * iw / ih
|
|
1339
|
+
if height is None:
|
|
1340
|
+
height = width * ih / iw
|
|
1341
|
+
alpha = opacity * self.opacity
|
|
1342
|
+
if width <= 0 or height <= 0 or not _alpha(alpha) > 0:
|
|
1343
|
+
return
|
|
1344
|
+
self._recorder.save()
|
|
1345
|
+
try:
|
|
1346
|
+
if "slice" in (preserve_aspect_ratio or ""):
|
|
1347
|
+
self._clip_rect(x, y, width, height)
|
|
1348
|
+
self._recorder.concat(view_box_transform((0, 0, iw, ih), x, y, width, height,
|
|
1349
|
+
preserve_aspect_ratio))
|
|
1350
|
+
self._recorder.set_opacity(alpha)
|
|
1351
|
+
self._recorder.concat(unit)
|
|
1352
|
+
self._recorder.scene.do(name)
|
|
1353
|
+
finally:
|
|
1354
|
+
self._recorder.restore()
|
|
1355
|
+
|
|
1356
|
+
def draw_lines(self, x: ArrayLike | Sequence[ArrayLike],
|
|
1357
|
+
y: ArrayLike | Sequence[ArrayLike], *, stroke: PaintLike = STATE,
|
|
1358
|
+
stroke_width: float | ArrayLike | None = None,
|
|
1359
|
+
stroke_dasharray: Dashes | Sequence[Dashes] = None,
|
|
1360
|
+
opacity: float | ArrayLike = 1.0,
|
|
1361
|
+
stroke_linecap: str | None = None, stroke_linejoin: str | None = None,
|
|
1362
|
+
simplify: SimplifyLike = None,
|
|
1363
|
+
interpolation: str | Sequence[str] = "linear", missing: str = "break",
|
|
1364
|
+
**style: Unpack[LineStyle]) -> None:
|
|
1365
|
+
"""Draw one or many polylines fast (time series, many series).
|
|
1366
|
+
|
|
1367
|
+
``y`` is a sequence (one line) or a sequence of sequences / 2-D
|
|
1368
|
+
array (one line per row); ``x`` is shared or one per series. NaN or
|
|
1369
|
+
``None`` breaks a line. ``stroke``, ``stroke_width``, ``stroke_dasharray`` and
|
|
1370
|
+
``opacity`` take one value or one per series; they default to the state's (the
|
|
1371
|
+
stroke black when the state has none). ``simplify=True`` (300
|
|
1372
|
+
dpi) or a dpi keeps only the points that matter at that resolution for series
|
|
1373
|
+
whose x values increase (M4 decimation, made for each output), and leaves out
|
|
1374
|
+
what later content hides (see :meth:`group`); ``None``: the enclosing group's,
|
|
1375
|
+
or the output's; ``False`` draws every point.
|
|
1376
|
+
|
|
1377
|
+
``interpolation`` (one value or one per series): ``"linear"``,
|
|
1378
|
+
``"step-pre"``, ``"step-post"``, ``"step-mid"``, ``"monotone"``
|
|
1379
|
+
(Fritsch-Carlson; the spline where x is not strictly monotonic within a
|
|
1380
|
+
run) or ``"spline"`` (centripetal Catmull-Rom); curves pass through every
|
|
1381
|
+
point and are never decimated. ``missing``: ``"break"`` (each run of
|
|
1382
|
+
finite points on its own) or ``"skip"`` (missing points left out, the
|
|
1383
|
+
rest joined). ``style``: other drawing attributes for this call.
|
|
1384
|
+
"""
|
|
1385
|
+
from .lines import draw_lines
|
|
1386
|
+
|
|
1387
|
+
saved = self._apply("draw_lines", style) if style else None
|
|
1388
|
+
try:
|
|
1389
|
+
_, stroke = self._bulk_paints(None, stroke, black=True)
|
|
1390
|
+
thin = self._recorder.thin(simplify)
|
|
1391
|
+
with self._recorder.simplified(simplify, _NEVER):
|
|
1392
|
+
draw_lines(self, x, y, stroke, stroke_width, stroke_dasharray, opacity,
|
|
1393
|
+
stroke_linecap, stroke_linejoin, thin, interpolation=interpolation,
|
|
1394
|
+
missing=missing)
|
|
1395
|
+
finally:
|
|
1396
|
+
if saved:
|
|
1397
|
+
self._restore(saved)
|
|
1398
|
+
|
|
1399
|
+
def draw_segments(self, x0: float | ArrayLike, y0: float | ArrayLike,
|
|
1400
|
+
x1: float | ArrayLike, y1: float | ArrayLike, *,
|
|
1401
|
+
stroke: PaintLike = STATE, stroke_width: float | ArrayLike | None = None,
|
|
1402
|
+
opacity: float | ArrayLike = 1.0, stroke_linecap: str | None = None,
|
|
1403
|
+
simplify: SimplifyLike = None,
|
|
1404
|
+
**style: Unpack[SegmentStyle]) -> None:
|
|
1405
|
+
"""Draw many independent segments ``(x0, y0) -> (x1, y1)``.
|
|
1406
|
+
|
|
1407
|
+
``stroke``, ``stroke_width`` and ``opacity`` take one value or one per segment;
|
|
1408
|
+
a coordinate given as a number applies to every segment. Segments
|
|
1409
|
+
with a NaN, infinite or ``None`` coordinate are skipped.
|
|
1410
|
+
``simplify``: as in :meth:`draw_markers`; ``style``: other drawing attributes.
|
|
1411
|
+
"""
|
|
1412
|
+
from .lines import draw_segments
|
|
1413
|
+
|
|
1414
|
+
saved = self._apply("draw_segments", style) if style else None
|
|
1415
|
+
try:
|
|
1416
|
+
_, stroke = self._bulk_paints(None, stroke, black=True)
|
|
1417
|
+
with self._recorder.simplified(simplify, _NEVER):
|
|
1418
|
+
draw_segments(self, x0, y0, x1, y1, stroke, stroke_width, opacity,
|
|
1419
|
+
stroke_linecap)
|
|
1420
|
+
finally:
|
|
1421
|
+
if saved:
|
|
1422
|
+
self._restore(saved)
|
|
1423
|
+
|
|
1424
|
+
def draw_rects(self, x: float | ArrayLike, y: float | ArrayLike,
|
|
1425
|
+
width: float | ArrayLike, height: float | ArrayLike, *,
|
|
1426
|
+
fill: PaintLike = STATE, stroke: PaintLike = STATE,
|
|
1427
|
+
stroke_width: float | ArrayLike | None = None,
|
|
1428
|
+
opacity: float | ArrayLike = 1.0,
|
|
1429
|
+
simplify: SimplifyLike = None,
|
|
1430
|
+
**style: Unpack[ItemStyle]) -> None:
|
|
1431
|
+
"""Draw many axis-aligned rectangles (bars, cells, histograms).
|
|
1432
|
+
|
|
1433
|
+
Every argument takes one value or one per rectangle (a number for ``x``, ``y``,
|
|
1434
|
+
``width`` or ``height`` applies to all). ``fill`` and ``stroke`` default to the
|
|
1435
|
+
state's; per rectangle they are colors (a list, or an
|
|
1436
|
+
``(n, 3)``/``(n, 4)`` buffer; ``None`` paints nothing). Rectangles with a NaN,
|
|
1437
|
+
infinite or ``None`` value are skipped. One paint for all may be a gradient or a
|
|
1438
|
+
pattern; values per rectangle need flat colors. ``simplify``: as in
|
|
1439
|
+
:meth:`draw_markers` (culling only); ``style``: other drawing attributes.
|
|
1440
|
+
"""
|
|
1441
|
+
from .shapes import draw_rects
|
|
1442
|
+
|
|
1443
|
+
saved = self._apply("draw_rects", style) if style else None
|
|
1444
|
+
try:
|
|
1445
|
+
fill, stroke = self._bulk_paints(fill, stroke)
|
|
1446
|
+
with self._recorder.simplified(simplify, _NEVER):
|
|
1447
|
+
draw_rects(self, x, y, width, height, fill, stroke, stroke_width, opacity)
|
|
1448
|
+
finally:
|
|
1449
|
+
if saved:
|
|
1450
|
+
self._restore(saved)
|
|
1451
|
+
|
|
1452
|
+
def draw_polygons(self, paths: "Sequence[Path | str] | tuple[ArrayLike, ...]", *,
|
|
1453
|
+
fill: PaintLike = STATE, stroke: PaintLike = None,
|
|
1454
|
+
stroke_width: float | ArrayLike | None = None,
|
|
1455
|
+
opacity: float | ArrayLike = 1.0,
|
|
1456
|
+
simplify: SimplifyLike = None,
|
|
1457
|
+
**style: Unpack[ItemStyle]) -> None:
|
|
1458
|
+
"""Fill (and optionally stroke) many polygons or paths.
|
|
1459
|
+
|
|
1460
|
+
``paths`` is a list of :class:`Path` objects or SVG path data (curves allowed), or
|
|
1461
|
+
the arrays ``(x, y, ring_starts[, path_starts])`` for large inputs: ring ``k``
|
|
1462
|
+
has the points ``ring_starts[k]`` to ``ring_starts[k + 1] - 1`` (``ring_starts``
|
|
1463
|
+
ends with the total), path ``p`` the rings ``path_starts[p]`` to
|
|
1464
|
+
``path_starts[p + 1] - 1`` (default: all rings in one path). The rings of a path
|
|
1465
|
+
are filled together with ``fill_rule``, so holes work. ``fill``, ``stroke``,
|
|
1466
|
+
``stroke_width``, ``opacity`` and ``simplify`` take what they take in
|
|
1467
|
+
:meth:`draw_rects`; ``style``: other drawing attributes.
|
|
1468
|
+
"""
|
|
1469
|
+
from .shapes import fill_polygons
|
|
1470
|
+
|
|
1471
|
+
saved = self._apply("draw_polygons", style) if style else None
|
|
1472
|
+
try:
|
|
1473
|
+
fill, stroke = self._bulk_paints(fill, stroke)
|
|
1474
|
+
thin = self._recorder.thin(simplify)
|
|
1475
|
+
with self._recorder.simplified(simplify, _NEVER):
|
|
1476
|
+
fill_polygons(self, paths, fill, stroke, stroke_width, opacity,
|
|
1477
|
+
self.fill_rule, thin)
|
|
1478
|
+
finally:
|
|
1479
|
+
if saved:
|
|
1480
|
+
self._restore(saved)
|
|
1481
|
+
|
|
1482
|
+
def draw_area(self, x: ArrayLike, y1: ArrayLike, y2: float | ArrayLike = 0.0, *,
|
|
1483
|
+
fill: Paint = STATE, stroke: Paint = None, stroke_width: float | None = None,
|
|
1484
|
+
opacity: float = 1.0, simplify: SimplifyLike = None,
|
|
1485
|
+
interpolation: str = "linear", missing: str = "break",
|
|
1486
|
+
**style: Unpack[ItemStyle]) -> None:
|
|
1487
|
+
"""Fill the area between ``y1`` and ``y2`` (a sequence or a constant).
|
|
1488
|
+
|
|
1489
|
+
NaN or ``None`` splits the area. ``fill`` defaults to the state's; ``stroke``
|
|
1490
|
+
optionally outlines it (``stroke_width``: default the state's). ``simplify``,
|
|
1491
|
+
``interpolation`` and ``missing``: as in :meth:`draw_lines` (both edges
|
|
1492
|
+
are interpolated alike; a constant ``y2`` stays straight); ``style``: other
|
|
1493
|
+
drawing attributes.
|
|
1494
|
+
"""
|
|
1495
|
+
from .lines import fill_between
|
|
1496
|
+
|
|
1497
|
+
saved = self._apply("draw_area", style) if style else None
|
|
1498
|
+
try:
|
|
1499
|
+
fill, stroke = self._bulk_paints(fill, stroke)
|
|
1500
|
+
thin = self._recorder.thin(simplify)
|
|
1501
|
+
with self._recorder.simplified(simplify, _NEVER):
|
|
1502
|
+
fill_between(self, x, y1, y2, fill, opacity, stroke, stroke_width, thin,
|
|
1503
|
+
interpolation=interpolation, missing=missing)
|
|
1504
|
+
finally:
|
|
1505
|
+
if saved:
|
|
1506
|
+
self._restore(saved)
|
|
1507
|
+
|
|
1508
|
+
def draw_cells(self, x_edges: ArrayLike, y_edges: ArrayLike,
|
|
1509
|
+
fill: "ArrayLike | Sequence[ColorLike | None] | Sequence[ArrayLike]", *,
|
|
1510
|
+
palette: Sequence[ColorLike] | None = None, bounds: ArrayLike | None = None,
|
|
1511
|
+
bad: ColorLike | None = None, mode: str = "image",
|
|
1512
|
+
opacity: float = 1.0) -> None:
|
|
1513
|
+
"""Draw a grid of cells, each with its own color (heatmaps, 2-D histograms).
|
|
1514
|
+
|
|
1515
|
+
``x_edges`` (columns + 1 values) and ``y_edges`` (rows + 1 values) are the cell
|
|
1516
|
+
edges, finite and strictly monotonic. ``fill`` gives the cells row by row, row 0
|
|
1517
|
+
between ``y_edges[0]`` and ``y_edges[1]``:
|
|
1518
|
+
|
|
1519
|
+
* without ``palette``: colors, an ``(n, 3|4)`` or ``(rows, columns, 3|4)`` buffer of
|
|
1520
|
+
floats in [0, 1] or a sequence of n colors (``None``: bad);
|
|
1521
|
+
* with ``palette`` (at most 256 colors): palette indices (NaN or negative: bad);
|
|
1522
|
+
* in ``smooth`` mode with ``palette``: positions in [0, 1] along the palette, a color
|
|
1523
|
+
table sampled evenly over [0, 1] and interpolated linearly, or constant between
|
|
1524
|
+
``bounds`` (``len(palette) - 1`` increasing positions); NaN: bad.
|
|
1525
|
+
|
|
1526
|
+
``mode``: ``"image"`` (one sharp image pixel per cell; even edges only), ``"cells"``
|
|
1527
|
+
(rectangles, one per run of equal cells) or ``"smooth"`` (interpolated between cell
|
|
1528
|
+
centres, positions before coloring). ``bad`` is the color of bad cells (default:
|
|
1529
|
+
none). ``opacity`` applies to the grid as a whole.
|
|
1530
|
+
"""
|
|
1531
|
+
from .cells import draw_cells
|
|
1532
|
+
|
|
1533
|
+
draw_cells(self, x_edges, y_edges, fill, palette, bounds, bad, mode, opacity)
|
|
1534
|
+
|
|
1535
|
+
def _bytes(self, simplify=STATE):
|
|
1536
|
+
"""The content bytes of the page as the PDF has them (``simplify``: as
|
|
1537
|
+
:meth:`Document.write`; by default the output's)."""
|
|
1538
|
+
doc = self.document
|
|
1539
|
+
from .document import Output
|
|
1540
|
+
|
|
1541
|
+
with doc._output(Output() if simplify is STATE else Output(simplify=simplify),
|
|
1542
|
+
[self]):
|
|
1543
|
+
return _scene.write(self._scene, doc._res.names())
|
|
1544
|
+
|
|
1545
|
+
@contextlib.contextmanager
|
|
1546
|
+
def group(self, *, opacity: float = 1.0, mix_blend_mode: str = "normal",
|
|
1547
|
+
isolation: str = "auto", filter: "Filter | None" = None,
|
|
1548
|
+
clip_path: Path | str | None = None, mask: Mask | None = None,
|
|
1549
|
+
transform: Matrix | None = None, rasterize: bool = False,
|
|
1550
|
+
dpi: float | None = None, quality: int | bool | None = None,
|
|
1551
|
+
simplify: SimplifyLike = None) -> Generator[Self]:
|
|
1552
|
+
"""Draw the body as one group: in a saved graphics state (drawing attributes, the
|
|
1553
|
+
transform and the clip changed in the body are restored afterwards), with the
|
|
1554
|
+
group's effects. If the body raises an exception, nothing is drawn.
|
|
1555
|
+
|
|
1556
|
+
``transform`` (a :class:`~vec_io.Matrix`) and ``clip_path`` (a Path or SVG path
|
|
1557
|
+
data, filled with ``fill_rule``) apply to the body, in that order. ``opacity``
|
|
1558
|
+
draws the body as one transparency group with that opacity; ``mask`` (a
|
|
1559
|
+
:class:`~vec_io.paint.Mask` recorded with :meth:`mask`) shows it through the
|
|
1560
|
+
mask's luminance; ``mix_blend_mode`` (a CSS ``mix-blend-mode`` name,
|
|
1561
|
+
:data:`~vec_io.paint.BLEND_MODES`) blends it with what is under it;
|
|
1562
|
+
``isolation="isolate"`` makes it isolated without a blend mode of its own (blend
|
|
1563
|
+
modes inside it then blend with the group's content only). A group with blended
|
|
1564
|
+
content is isolated. EPS output draws blended content as images. Without these
|
|
1565
|
+
effects the body is drawn directly.
|
|
1566
|
+
|
|
1567
|
+
With ``rasterize=True`` a PDF holds the body as an image at ``dpi`` (default 300)
|
|
1568
|
+
aligned with the device pixel grid, made when it is written; image output draws
|
|
1569
|
+
the body itself. ``quality`` (1-100) stores the image as JPEG; ``False`` forces
|
|
1570
|
+
lossless; ``None`` follows the output's :class:`~vec_io.options.ImagePolicy`.
|
|
1571
|
+
|
|
1572
|
+
``simplify=True`` (300 dpi) or a resolution leaves out what later
|
|
1573
|
+
content on the page hides at that resolution, across every call in
|
|
1574
|
+
the body, while no pixel changes by more than half a level; lines and
|
|
1575
|
+
areas whose x values increase are also decimated (see
|
|
1576
|
+
:meth:`draw_lines`). ``False`` keeps the body whole:
|
|
1577
|
+
nothing in it is left out or decimated,
|
|
1578
|
+
whatever the output's ``simplify`` (see :meth:`Document.write`).
|
|
1579
|
+
Rasterized groups are not culled (rasterizing hidden content is
|
|
1580
|
+
faster); their lines are decimated, at the group's ``dpi`` for
|
|
1581
|
+
``True``. ``"auto"``: each bulk call in the body decides for itself
|
|
1582
|
+
(nothing is culled across calls). What is left out is decided when the
|
|
1583
|
+
PDF is written; image output only decimates.
|
|
1584
|
+
|
|
1585
|
+
``filter`` (a :class:`~vec_io.filter.Filter`) runs the filter on the pixels of the
|
|
1586
|
+
body, in its region (by default the bounds of what the body draws, 10 % wider and
|
|
1587
|
+
higher on each side), when the output is made: image output on its own pixel grid,
|
|
1588
|
+
PDF and EPS at ``dpi`` (default 300); where the body is drawn unchanged on top
|
|
1589
|
+
(drop shadows, glows, :class:`~vec_io.filter.Merge` with ``"SourceGraphic"`` last)
|
|
1590
|
+
they draw the image of what is under it and the body itself as vectors. SVG output
|
|
1591
|
+
writes a ``<filter>`` element (``svg_filters`` of :meth:`Document.write
|
|
1592
|
+
<vec_io.Document.write>`).
|
|
1593
|
+
"""
|
|
1594
|
+
simplify = _check_simplify(simplify)
|
|
1595
|
+
if blend_index(mix_blend_mode) == 0 and str(mix_blend_mode).strip().lower() != "normal":
|
|
1596
|
+
raise ArgumentError(f"unknown blend mode {mix_blend_mode!r}")
|
|
1597
|
+
if isolation not in ("auto", "isolate"):
|
|
1598
|
+
raise ArgumentError(f"isolation must be 'auto' or 'isolate', not {isolation!r}")
|
|
1599
|
+
if mask is not None and not isinstance(mask, Mask):
|
|
1600
|
+
raise ArgumentError(f"mask must be a Mask recorded with mask(), not "
|
|
1601
|
+
f"{type(mask).__name__}")
|
|
1602
|
+
if transform is not None and not isinstance(transform, Matrix):
|
|
1603
|
+
raise ArgumentError(f"transform must be a vec_io.Matrix, not "
|
|
1604
|
+
f"{type(transform).__name__}")
|
|
1605
|
+
opacity = _number("opacity", opacity)
|
|
1606
|
+
if clip_path is not None:
|
|
1607
|
+
clip_path = _path("clip_path", clip_path)
|
|
1608
|
+
effects = dict(opacity=opacity, blend=mix_blend_mode, isolate=isolation == "isolate",
|
|
1609
|
+
filter=filter, rasterize=rasterize, dpi=dpi, quality=quality,
|
|
1610
|
+
simplify=simplify)
|
|
1611
|
+
if transform is None and clip_path is None:
|
|
1612
|
+
with self._group(mask, **effects):
|
|
1613
|
+
yield self
|
|
1614
|
+
return
|
|
1615
|
+
self._push()
|
|
1616
|
+
depth = len(self._recorder.state_stack)
|
|
1617
|
+
try:
|
|
1618
|
+
if transform is not None:
|
|
1619
|
+
self._recorder.concat(transform)
|
|
1620
|
+
if clip_path is not None:
|
|
1621
|
+
self._clip(clip_path, self.fill_rule)
|
|
1622
|
+
if (mask is None and opacity == 1 and not effects["isolate"] and filter is None
|
|
1623
|
+
and not rasterize and simplify is None
|
|
1624
|
+
and not blend_index(mix_blend_mode)):
|
|
1625
|
+
yield self
|
|
1626
|
+
else:
|
|
1627
|
+
with self._group(mask, **effects):
|
|
1628
|
+
yield self
|
|
1629
|
+
finally:
|
|
1630
|
+
self._unwind(depth)
|
|
1631
|
+
self._pop()
|
|
1632
|
+
|
|
1633
|
+
def _unwind(self, depth):
|
|
1634
|
+
"""Close what :meth:`state` opened in a body drawn directly
|
|
1635
|
+
(:class:`~vec_io.StateError` when nothing else is raised)."""
|
|
1636
|
+
if len(self._recorder.state_stack) == depth:
|
|
1637
|
+
return
|
|
1638
|
+
while len(self._recorder.state_stack) > depth:
|
|
1639
|
+
self._pop()
|
|
1640
|
+
if sys.exc_info()[1] is None:
|
|
1641
|
+
raise StateError("a state() left open in a group, mask or pattern")
|
|
1642
|
+
|
|
1643
|
+
@contextlib.contextmanager
|
|
1644
|
+
def _group(self, mask, opacity, blend, isolate, filter, rasterize, dpi, quality, simplify):
|
|
1645
|
+
"""The effects of :meth:`group`: ``mask`` outside the others."""
|
|
1646
|
+
if mask is not None:
|
|
1647
|
+
blended = blend_index(blend) > 0
|
|
1648
|
+
if blended:
|
|
1649
|
+
self._recorder.save()
|
|
1650
|
+
try:
|
|
1651
|
+
if blended:
|
|
1652
|
+
self._recorder.set_blend(blend)
|
|
1653
|
+
with self._recorder.masked(mask):
|
|
1654
|
+
if (opacity == 1 and not isolate and filter is None and not rasterize
|
|
1655
|
+
and simplify is None):
|
|
1656
|
+
yield self
|
|
1657
|
+
else:
|
|
1658
|
+
with self._group(None, opacity, "normal", isolate, filter, rasterize,
|
|
1659
|
+
dpi, quality, simplify):
|
|
1660
|
+
yield self
|
|
1661
|
+
finally:
|
|
1662
|
+
if blended:
|
|
1663
|
+
self._recorder.restore()
|
|
1664
|
+
return
|
|
1665
|
+
if blend_index(blend) and (filter is not None or rasterize):
|
|
1666
|
+
self._recorder.save()
|
|
1667
|
+
try:
|
|
1668
|
+
self._recorder.set_blend(blend)
|
|
1669
|
+
if filter is not None:
|
|
1670
|
+
with self._filtered(filter, dpi, opacity, quality, simplify, blend):
|
|
1671
|
+
yield self
|
|
1672
|
+
else:
|
|
1673
|
+
with self._group(None, opacity, "normal", False, filter, rasterize, dpi,
|
|
1674
|
+
quality, simplify):
|
|
1675
|
+
yield self
|
|
1676
|
+
finally:
|
|
1677
|
+
self._recorder.restore()
|
|
1678
|
+
return
|
|
1679
|
+
if filter is not None:
|
|
1680
|
+
with self._filtered(filter, dpi, opacity, quality, simplify):
|
|
1681
|
+
yield self
|
|
1682
|
+
return
|
|
1683
|
+
if rasterize:
|
|
1684
|
+
with self._rasterized(dpi=dpi, opacity=opacity, quality=quality,
|
|
1685
|
+
simplify=simplify):
|
|
1686
|
+
yield self
|
|
1687
|
+
return
|
|
1688
|
+
isolated = isolate or blend_index(blend) > 0
|
|
1689
|
+
if opacity == 1 and not isolated:
|
|
1690
|
+
start = self._recorder.scene.mark()
|
|
1691
|
+
self._recorder.save()
|
|
1692
|
+
state = self._push_state()
|
|
1693
|
+
depth = len(self._recorder.state_stack)
|
|
1694
|
+
ok = False
|
|
1695
|
+
try:
|
|
1696
|
+
if simplify is None:
|
|
1697
|
+
yield self
|
|
1698
|
+
else:
|
|
1699
|
+
with self._recorder.simplified(simplify):
|
|
1700
|
+
yield self
|
|
1701
|
+
ok = True
|
|
1702
|
+
finally:
|
|
1703
|
+
try:
|
|
1704
|
+
self._unwind(depth)
|
|
1705
|
+
except RuntimeError:
|
|
1706
|
+
ok = False
|
|
1707
|
+
raise
|
|
1708
|
+
finally:
|
|
1709
|
+
self._pop_state(state)
|
|
1710
|
+
self._recorder.restore()
|
|
1711
|
+
if not ok:
|
|
1712
|
+
# an exception: the partial body is dropped
|
|
1713
|
+
self._recorder.scene.truncate(start)
|
|
1714
|
+
return
|
|
1715
|
+
saved = self._recorder.begin_group(None if simplify is None else ("group", simplify))
|
|
1716
|
+
state = self._push_state()
|
|
1717
|
+
ok = False
|
|
1718
|
+
try:
|
|
1719
|
+
yield self
|
|
1720
|
+
ok = True
|
|
1721
|
+
finally:
|
|
1722
|
+
self._pop_state(state)
|
|
1723
|
+
if ok:
|
|
1724
|
+
name = self._recorder.end_group(saved, isolated=isolated)
|
|
1725
|
+
else:
|
|
1726
|
+
self._recorder.end_substream(saved) # an exception: the partial body is dropped
|
|
1727
|
+
if name is not None and _alpha(opacity) > 0:
|
|
1728
|
+
gs = self.document._opacity_gs(opacity)
|
|
1729
|
+
if gs is not None or blend_index(blend):
|
|
1730
|
+
self._recorder.scene.save()
|
|
1731
|
+
if gs is not None:
|
|
1732
|
+
self._recorder.scene.gs(gs, SP)
|
|
1733
|
+
self._recorder.set_blend(blend, SP)
|
|
1734
|
+
self._recorder.scene.do(name, SP)
|
|
1735
|
+
self._recorder.scene.restore(SP)
|
|
1736
|
+
else:
|
|
1737
|
+
self._recorder.scene.do(name)
|
|
1738
|
+
|
|
1739
|
+
@contextlib.contextmanager
|
|
1740
|
+
def _filtered(self, flt, dpi, opacity, quality, simplify, blended=None):
|
|
1741
|
+
"""The body drawn through filter ``flt`` (see :meth:`group`; ``blended``: the blend
|
|
1742
|
+
mode it is drawn with): a filtered group made per output
|
|
1743
|
+
(:class:`~vec_io.raster.groups.FilterGroup`)."""
|
|
1744
|
+
from .filter import Filter
|
|
1745
|
+
|
|
1746
|
+
if not isinstance(flt, Filter):
|
|
1747
|
+
raise ArgumentError(f"filter must be a vec_io.Filter, not {type(flt).__name__}")
|
|
1748
|
+
quality = _check_raster_quality(quality)
|
|
1749
|
+
dpi = DEFAULT_DPI if dpi is None else float(dpi)
|
|
1750
|
+
if not (dpi > 0 and math.isfinite(dpi)):
|
|
1751
|
+
raise ArgumentError("dpi must be positive")
|
|
1752
|
+
rec = self._recorder
|
|
1753
|
+
ctm = rec.absolute_ctm()
|
|
1754
|
+
region = flt.region
|
|
1755
|
+
page_region = None
|
|
1756
|
+
if region is not None:
|
|
1757
|
+
x, y, w, h = region
|
|
1758
|
+
if not (w > 0 and h > 0):
|
|
1759
|
+
region = () # an empty region: the group shows nothing
|
|
1760
|
+
else:
|
|
1761
|
+
page_region = transform_bbox((x, y, x + w, y + h), ctm)
|
|
1762
|
+
doc = self.document
|
|
1763
|
+
reused = doc._mask_depth > 0 or doc._reused_depth > 0
|
|
1764
|
+
holder = _FilterHolder()
|
|
1765
|
+
outer = doc._filter_holders[-1] if doc._filter_holders else None
|
|
1766
|
+
doc._filter_holders.append(holder)
|
|
1767
|
+
saved = rec.begin_group(("rasterized", _check_simplify(simplify), dpi), cull=False)
|
|
1768
|
+
state = self._push_state()
|
|
1769
|
+
ok = False
|
|
1770
|
+
try:
|
|
1771
|
+
yield self
|
|
1772
|
+
ok = True
|
|
1773
|
+
finally:
|
|
1774
|
+
doc._filter_holders.pop()
|
|
1775
|
+
self._pop_state(state)
|
|
1776
|
+
stream_to_page = rec.base
|
|
1777
|
+
content = rec.end_substream(saved)
|
|
1778
|
+
if ok and region != ():
|
|
1779
|
+
holder.group = rec.filter_group(
|
|
1780
|
+
content, stream_to_page, dpi, opacity, flt, ctm, page_region, quality,
|
|
1781
|
+
None if region is not None else 0.1, reused, outer, blended)
|
|
1782
|
+
|
|
1783
|
+
@contextlib.contextmanager
|
|
1784
|
+
def _rasterized(self, dpi: float | None = None, opacity: float = 1.0,
|
|
1785
|
+
region: tuple[float, float, float, float] | None = None,
|
|
1786
|
+
quality: int | bool | None = None,
|
|
1787
|
+
simplify: SimplifyLike = None) -> Generator[Self]:
|
|
1788
|
+
"""Rasterize everything drawn in the body (:meth:`group` with ``rasterize``).
|
|
1789
|
+
|
|
1790
|
+
``region`` (``(x0, y0, x1, y1)`` in user space) fixes the area that is rasterized
|
|
1791
|
+
instead of using the drawing's extent. ``quality`` and ``simplify``: see
|
|
1792
|
+
:meth:`group`.
|
|
1793
|
+
|
|
1794
|
+
A PDF holds the body as an image at ``dpi``, made when the PDF is written; image
|
|
1795
|
+
output (:meth:`render`) draws the body itself, as vectors (a transparency group when
|
|
1796
|
+
``opacity`` is below 1), clipped to ``region``.
|
|
1797
|
+
"""
|
|
1798
|
+
quality = _check_raster_quality(quality)
|
|
1799
|
+
dpi = DEFAULT_DPI if dpi is None else float(dpi)
|
|
1800
|
+
if not (dpi > 0 and math.isfinite(dpi)):
|
|
1801
|
+
raise ArgumentError("dpi must be positive")
|
|
1802
|
+
page_region = None
|
|
1803
|
+
if region is not None:
|
|
1804
|
+
page_region = transform_bbox(region, self._recorder.absolute_ctm())
|
|
1805
|
+
saved = self._recorder.begin_group(("rasterized", _check_simplify(simplify), dpi),
|
|
1806
|
+
cull=False)
|
|
1807
|
+
state = self._push_state()
|
|
1808
|
+
ok = False
|
|
1809
|
+
try:
|
|
1810
|
+
yield self
|
|
1811
|
+
ok = True
|
|
1812
|
+
finally:
|
|
1813
|
+
self._pop_state(state)
|
|
1814
|
+
stream_to_page = self._recorder.base
|
|
1815
|
+
content = self._recorder.end_substream(saved)
|
|
1816
|
+
if ok: # (an exception: the partial body is dropped)
|
|
1817
|
+
self._recorder.raster_group(content, stream_to_page, dpi, opacity, region,
|
|
1818
|
+
page_region, quality)
|
|
1819
|
+
|
|
1820
|
+
@contextlib.contextmanager
|
|
1821
|
+
def mask(self) -> Generator[Mask]:
|
|
1822
|
+
"""``with mask() as m``: record a luminosity mask: what the body draws, from the
|
|
1823
|
+
default drawing state and in the current user space, is the mask (white keeps what
|
|
1824
|
+
it covers visible, black hides it); nothing is drawn on the page. ``with
|
|
1825
|
+
group(mask=m)``: a body seen through it."""
|
|
1826
|
+
mask = Mask()
|
|
1827
|
+
saved = self._recorder.begin_group()
|
|
1828
|
+
state = self._push_state(reset=True)
|
|
1829
|
+
self.document._mask_depth += 1
|
|
1830
|
+
ok = False
|
|
1831
|
+
try:
|
|
1832
|
+
yield mask
|
|
1833
|
+
ok = True
|
|
1834
|
+
finally:
|
|
1835
|
+
self.document._mask_depth -= 1
|
|
1836
|
+
self._pop_state(state)
|
|
1837
|
+
form = self._recorder.end_group(saved, mask=True)
|
|
1838
|
+
if ok and form is not None:
|
|
1839
|
+
mask._smask = Obj({"Type": Name("Mask"), "S": Name("Luminosity"),
|
|
1840
|
+
"G": self.document._res.obj(form)})
|
|
1841
|
+
|
|
1842
|
+
@contextlib.contextmanager
|
|
1843
|
+
def pattern(self, width: float, height: float, x: float = 0.0, y: float = 0.0, *,
|
|
1844
|
+
transform: Matrix | None = None) -> Generator[Pattern]:
|
|
1845
|
+
"""Record the tile of a :class:`~vec_io.paint.Pattern`: the body draws one tile
|
|
1846
|
+
``width`` x ``height``, origin at its top-left corner, from the default drawing
|
|
1847
|
+
state; ``x``, ``y`` offset the tiling and ``transform`` transforms it. The pattern
|
|
1848
|
+
paints like a color (``fill``, ``stroke``) in the user space it was recorded
|
|
1849
|
+
in. Nothing is drawn on the page."""
|
|
1850
|
+
pat = Pattern(width, height, x, y, transform)
|
|
1851
|
+
tile = pat.transform @ Matrix.translate(pat.x, pat.y)
|
|
1852
|
+
saved = self._recorder.begin_substream(self._recorder.absolute_ctm() @ tile)
|
|
1853
|
+
state = self._push_state(reset=True)
|
|
1854
|
+
self.document._reused_depth += 1
|
|
1855
|
+
ok = False
|
|
1856
|
+
try:
|
|
1857
|
+
yield pat
|
|
1858
|
+
ok = True
|
|
1859
|
+
finally:
|
|
1860
|
+
self.document._reused_depth -= 1
|
|
1861
|
+
self._pop_state(state)
|
|
1862
|
+
content = self._recorder.end_substream(saved)
|
|
1863
|
+
if ok:
|
|
1864
|
+
pat._scene = content
|
|
1865
|
+
|
|
1866
|
+
@contextlib.contextmanager
|
|
1867
|
+
def marker(self) -> Generator[Marker]:
|
|
1868
|
+
"""Record a :class:`~vec_io.paint.Marker` for :meth:`draw_markers`: the body draws
|
|
1869
|
+
one marker centered on the origin, from the default drawing state. Nothing is drawn
|
|
1870
|
+
on the page."""
|
|
1871
|
+
m = Marker()
|
|
1872
|
+
saved = self._recorder.begin_substream(self._recorder.absolute_ctm())
|
|
1873
|
+
state = self._push_state(reset=True)
|
|
1874
|
+
self.document._reused_depth += 1
|
|
1875
|
+
ok = False
|
|
1876
|
+
try:
|
|
1877
|
+
yield m
|
|
1878
|
+
ok = True
|
|
1879
|
+
finally:
|
|
1880
|
+
self.document._reused_depth -= 1
|
|
1881
|
+
self._pop_state(state)
|
|
1882
|
+
content = self._recorder.end_substream(saved)
|
|
1883
|
+
if ok:
|
|
1884
|
+
pad = 1e5
|
|
1885
|
+
m._form = self.document._form(content, [-pad, -pad, pad, pad], prefix="Mk")
|
|
1886
|
+
|
|
1887
|
+
def link(self, x: float, y: float, width: float, height: float, *, url: str | None = None,
|
|
1888
|
+
page: "Canvas | int | None" = None, page_y: float | None = None) -> None:
|
|
1889
|
+
"""Make a rectangle clickable: open ``url`` or go to ``page``
|
|
1890
|
+
(a page of this document or a page index, optionally at
|
|
1891
|
+
``page_y``). An index may name a page added later."""
|
|
1892
|
+
if (url is None) == (page is None):
|
|
1893
|
+
raise ArgumentError("give exactly one of url= or page=")
|
|
1894
|
+
x, y = _number("x", x), _number("y", y)
|
|
1895
|
+
width, height = _number("width", width), _number("height", height)
|
|
1896
|
+
if url is not None and not isinstance(url, str):
|
|
1897
|
+
raise ArgumentError(f"url must be a string, not {url!r}")
|
|
1898
|
+
if page_y is not None:
|
|
1899
|
+
page_y = _number("page_y", page_y)
|
|
1900
|
+
if page is not None:
|
|
1901
|
+
page = self.document._page(page, check_range=False)
|
|
1902
|
+
m = self._recorder.absolute_ctm()
|
|
1903
|
+
rect = transform_bbox((x, y, x + width, y + height), m)
|
|
1904
|
+
self._recorder.links.append((rect, url, page, page_y))
|
|
1905
|
+
self._recorder.scene.link(rect, len(self._recorder.links) - 1)
|
|
1906
|
+
|
|
1907
|
+
def draw_svg(self, svg: "str | bytes | PathLike | SVGDocument", x: float = 0.0,
|
|
1908
|
+
y: float = 0.0, width: float | None = None,
|
|
1909
|
+
height: float | None = None, *, base_dir: PathLike | None = None,
|
|
1910
|
+
clip: bool = True, media: str = "print",
|
|
1911
|
+
color_scheme: str = "light", files: str = "base_dir",
|
|
1912
|
+
root_background: bool = True, limits: "Limits | None" = None) -> None:
|
|
1913
|
+
"""Draw an SVG document (text, bytes, path or :class:`~vec_io.svg.SVGDocument`).
|
|
1914
|
+
|
|
1915
|
+
Placed at ``(x, y)`` with the given size in page units; by default
|
|
1916
|
+
its CSS pixel size (1px = 0.75pt) is used, and the aspect ratio is
|
|
1917
|
+
kept when only one dimension is given. A relative path is resolved
|
|
1918
|
+
against the document's ``base_dir``. References in the SVG resolve
|
|
1919
|
+
against ``base_dir``, by default the SVG file's directory (or the
|
|
1920
|
+
document's ``base_dir``). ``files``: ``"base_dir"`` reads only local files under
|
|
1921
|
+
that folder (others warn and are not drawn), ``"any"`` any file the process can
|
|
1922
|
+
read. ``media`` (``"print"`` or ``"screen"``) and ``color_scheme`` (``"light"`` or
|
|
1923
|
+
``"dark"``): what its ``@media`` rules are evaluated for (not used for an
|
|
1924
|
+
:class:`~vec_io.svg.SVGDocument`). ``root_background``: fill its viewport with the
|
|
1925
|
+
root element's ``background-color`` (as browsers do). ``limits``: a
|
|
1926
|
+
:class:`~vec_io.Limits` (default ``Limits()``).
|
|
1927
|
+
"""
|
|
1928
|
+
from .convert import is_svg_text
|
|
1929
|
+
from .svg.parse import SVGDocument
|
|
1930
|
+
from .limits import budget
|
|
1931
|
+
from .svg.render import Renderer
|
|
1932
|
+
|
|
1933
|
+
with budget(limits):
|
|
1934
|
+
document = self.document
|
|
1935
|
+
doc = None
|
|
1936
|
+
if isinstance(svg, SVGDocument):
|
|
1937
|
+
doc = svg
|
|
1938
|
+
else:
|
|
1939
|
+
data = svg
|
|
1940
|
+
if not (isinstance(svg, (bytes, bytearray)) or is_svg_text(svg)):
|
|
1941
|
+
path = document._resolve_path(svg)
|
|
1942
|
+
with open(path, "rb") as fh:
|
|
1943
|
+
data = fh.read()
|
|
1944
|
+
if base_dir is None:
|
|
1945
|
+
base_dir = os.path.dirname(os.path.abspath(path))
|
|
1946
|
+
if base_dir is None:
|
|
1947
|
+
base_dir = document.base_dir
|
|
1948
|
+
resources = document._gate.at(base_dir, files)
|
|
1949
|
+
if doc is None:
|
|
1950
|
+
doc = SVGDocument.load(data, resources, media=media, color_scheme=color_scheme)
|
|
1951
|
+
renderer = Renderer(doc, self, base_dir=resources.base)
|
|
1952
|
+
w_px, h_px = renderer.document_size()
|
|
1953
|
+
px = PT_PER_PX / self._recorder.unit_scale # page units per CSS pixel
|
|
1954
|
+
if width is None and height is None:
|
|
1955
|
+
width, height = w_px * px, h_px * px
|
|
1956
|
+
elif width is None:
|
|
1957
|
+
width = height * w_px / h_px
|
|
1958
|
+
elif height is None:
|
|
1959
|
+
height = width * h_px / w_px
|
|
1960
|
+
placement = Matrix(width / w_px, 0, 0, height / h_px, x, y)
|
|
1961
|
+
if placement.is_identity():
|
|
1962
|
+
renderer.draw(clip=clip, background=root_background)
|
|
1963
|
+
return
|
|
1964
|
+
self._recorder.save()
|
|
1965
|
+
try:
|
|
1966
|
+
self._recorder.concat(placement)
|
|
1967
|
+
renderer.draw(clip=clip, background=root_background)
|
|
1968
|
+
finally:
|
|
1969
|
+
self._recorder.restore()
|
|
1970
|
+
|
|
1971
|
+
def draw_pdf(self, source: "str | bytes | PathLike | IO[bytes]", x: float = 0.0,
|
|
1972
|
+
y: float = 0.0,
|
|
1973
|
+
width: float | None = None, height: float | None = None, *, page: int = 0,
|
|
1974
|
+
box: str = "crop", annotations: bool = True,
|
|
1975
|
+
password: str | bytes | None = None,
|
|
1976
|
+
intent: str = "view", limits: "Limits | None" = None) -> None:
|
|
1977
|
+
"""Draw page ``page`` of a PDF (a path, bytes or a binary file) as a form: its
|
|
1978
|
+
``box`` (``"crop"``, ``"media"``, ``"bleed"``, ``"trim"``, ``"art"``) at ``(x, y)``,
|
|
1979
|
+
by default in its size in points (rotated), the aspect ratio kept when only one
|
|
1980
|
+
dimension is given, clipped to the box. ``annotations=False``: page content only.
|
|
1981
|
+
``intent``: ``"view"`` (default) or ``"print"``, the event whose layer states apply.
|
|
1982
|
+
``limits``: a :class:`~vec_io.Limits` (default ``Limits()``). A page drawn again in
|
|
1983
|
+
this document is the same form. PDF output places the page as the file has it (a
|
|
1984
|
+
copy of its content and resources) unless it draws annotations, its file has layers
|
|
1985
|
+
or an option changes content (see :func:`~vec_io.open_pdf`). Raises
|
|
1986
|
+
:class:`~vec_io.pdfread.PDFReadError` for a file that cannot be read and
|
|
1987
|
+
:class:`~vec_io.LimitError` past a limit."""
|
|
1988
|
+
from .pdfread import draw_page
|
|
1989
|
+
|
|
1990
|
+
draw_page(self, source, page, x, y, width, height, box, annotations, password,
|
|
1991
|
+
intent, limits)
|
|
1992
|
+
|
|
1993
|
+
|
|
1994
|
+
for _name in _STATE_ATTRS:
|
|
1995
|
+
setattr(Canvas, _name, _state_property(_name))
|
|
1996
|
+
getattr(Canvas, _name).fget.__annotations__["return"] = Canvas.__annotations__[_name]
|
|
1997
|
+
del _name
|
|
1998
|
+
|
|
1999
|
+
|
|
2000
|
+
def marker_path(marker):
|
|
2001
|
+
"""Path of a marker (unit size, centered on the origin): a Path, SVG path data, or
|
|
2002
|
+
``None`` for the unit circle."""
|
|
2003
|
+
if isinstance(marker, Path):
|
|
2004
|
+
return marker
|
|
2005
|
+
if marker is None:
|
|
2006
|
+
return ellipse_path(0, 0, 0.5, 0.5)
|
|
2007
|
+
if isinstance(marker, str) and marker.lstrip()[:1] in "Mm":
|
|
2008
|
+
return parse_path_data(marker, strict=True)
|
|
2009
|
+
raise ArgumentError(f"invalid marker {marker!r}: give a Path or SVG path data in a unit box "
|
|
2010
|
+
f"centered on the origin, e.g. 'M-0.5 -0.5 H0.5 V0.5 H-0.5 Z' for a "
|
|
2011
|
+
f"square (named shapes are in plot_io)")
|
|
2012
|
+
|
|
2013
|
+
|
|
2014
|
+
def _check_raster_quality(value):
|
|
2015
|
+
"""``None`` (inherit), ``False`` (lossless) or a quality 1-100."""
|
|
2016
|
+
if value is None or value is False:
|
|
2017
|
+
return value
|
|
2018
|
+
if value is True:
|
|
2019
|
+
return DEFAULT_JPEG_QUALITY
|
|
2020
|
+
if not isinstance(value, numbers.Integral) and not (
|
|
2021
|
+
isinstance(value, float) and value.is_integer()):
|
|
2022
|
+
raise ArgumentError(f"quality must be a whole number from 1 to 100, not {value!r}")
|
|
2023
|
+
q = int(value)
|
|
2024
|
+
if not 1 <= q <= 100:
|
|
2025
|
+
raise ArgumentError("quality must be between 1 and 100")
|
|
2026
|
+
return q
|
|
2027
|
+
|
|
2028
|
+
|
|
2029
|
+
def _with_opacity(paint, opacity):
|
|
2030
|
+
"""A paint with its alpha multiplied by ``opacity``: a color, a gradient (its stops) or a
|
|
2031
|
+
pattern."""
|
|
2032
|
+
if paint is None or opacity >= 1:
|
|
2033
|
+
return paint
|
|
2034
|
+
if isinstance(paint, _Gradient):
|
|
2035
|
+
faded = copy.copy(paint)
|
|
2036
|
+
faded.stops = [(t, c, a * max(0.0, opacity)) for t, c, a in paint.stops]
|
|
2037
|
+
return faded
|
|
2038
|
+
if isinstance(paint, Pattern):
|
|
2039
|
+
faded = copy.copy(paint)
|
|
2040
|
+
faded._alpha = paint._alpha * max(0.0, opacity)
|
|
2041
|
+
return faded
|
|
2042
|
+
if not isinstance(paint, (str, tuple, list, CMYK)):
|
|
2043
|
+
return paint
|
|
2044
|
+
rgba = to_rgba(paint)
|
|
2045
|
+
if rgba is None:
|
|
2046
|
+
return paint
|
|
2047
|
+
if isinstance(rgba, CMYK):
|
|
2048
|
+
return rgba.with_alpha(rgba.alpha * opacity)
|
|
2049
|
+
return (rgba[0], rgba[1], rgba[2], rgba[3] * max(0.0, opacity))
|
|
2050
|
+
|
|
2051
|
+
|
|
2052
|
+
def _fade(value, opacity):
|
|
2053
|
+
"""One paint or a column of colors with their alpha multiplied by ``opacity``."""
|
|
2054
|
+
from .items import _single_color
|
|
2055
|
+
|
|
2056
|
+
if isinstance(value, (_Gradient, Pattern)) or _single_color(value):
|
|
2057
|
+
return _with_opacity(value, opacity)
|
|
2058
|
+
return [_with_opacity(tuple(c) if hasattr(c, "__len__") and not isinstance(c, str) else c,
|
|
2059
|
+
opacity) for c in value]
|