"""
``polyline`` and the point lists it is built from.
"""
from __future__ import annotations
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any, ClassVar
import numpy as np
from ...._internal._constants import DEFAULT_PRECISION
from ...._internal._numbers import format_number
from ...._internal._typing import Self
from ...pathdata.builder import PathBuilder
from ...pathdata.data import BBox, PathData
from ._base import Shape, parse_points
from ._constants import DEFAULT_SIDES, EMPTY_POINTS, FULL_CIRCLE
# region generated by `python scripts/dev.py svgwriter signatures write`: names used by the signatures
if TYPE_CHECKING:
from collections.abc import Mapping
from ...._internal._typing import FillRule, LineCap, LineJoin, Opacity
from ....ops.typeface import Typeface
from ...attributes.style import StyleLike
from ...color.color import Color
from ...color.paint import PaintValue
from ...transform.transform import TransformLike
from ...units.lengths import LengthLike
from .._behavior import Pivot, XmlSpace
from ..core import AttrValue, Element
from ..text import TextDecoration
# endregion
__all__ = ["PointList", "PointsLike", "Polyline", "as_points"]
PointsLike = np.ndarray | Sequence[Sequence[float]]
class PointList:
"""Immutable ``points`` attribute value wrapping an ``(N, 2)`` array.
Parameters
----------
array : numpy.ndarray
Read-only ``(N, 2)`` float array of vertices.
See Also
--------
as_points : Build such an array from other inputs.
Examples
--------
>>> import numpy as np
>>> from svgwriter.model.elements.shapes._poly import PointList
>>> PointList(np.array([[0.0, 0.0], [1.0, 2.0]]))
PointList([[0.0, 0.0], [1.0, 2.0]])
"""
__slots__ = ("array",)
def __init__(self, array: np.ndarray) -> None:
self.array = array
def __eq__(self, other: object) -> bool:
return isinstance(other, PointList) and np.array_equal(self.array, other.array)
def __hash__(self) -> int:
return hash(self.array.tobytes())
def __array__(self, dtype: Any = None, copy: Any = None) -> np.ndarray:
return self.array if dtype is None else self.array.astype(dtype)
def svg_value(self, precision: int = DEFAULT_PRECISION) -> str:
"""Serialize as SVG ``points`` text.
Parameters
----------
precision : int, optional
Maximum decimal places. Defaults to the library default.
Returns
-------
str
Space-separated ``x,y`` pairs.
Examples
--------
>>> import numpy as np
>>> from svgwriter.model.elements.shapes._poly import PointList
>>> PointList(np.array([[0.0, 0.0], [1.5, 2.0]])).svg_value()
'0,0 1.5,2'
"""
return " ".join(f"{format_number(x, precision)},{format_number(y, precision)}" for x, y in self.array.tolist())
def __repr__(self) -> str:
return f"PointList({self.array.tolist()!r})"
def as_points(value: PointsLike | str) -> np.ndarray:
"""Convert point input to a read-only ``(N, 2)`` float array.
Parameters
----------
value : array-like or str
Vertices as a sequence of pairs, an array or SVG points text.
Returns
-------
numpy.ndarray
Read-only float array of shape ``(N, 2)``; empty input gives ``(0, 2)``.
Raises
------
ValueError
If the input does not have shape ``(N, 2)``.
Examples
--------
>>> from svgwriter.model.elements.shapes._poly import as_points
>>> as_points("0,0 1,2").tolist()
[[0.0, 0.0], [1.0, 2.0]]
"""
array = np.array(parse_points(value) if isinstance(value, str) else value, dtype=float)
if array.size == 0:
return EMPTY_POINTS
if array.ndim != 2 or array.shape[1] != 2:
raise ValueError(f"points must have shape (N, 2), got {array.shape}")
array.flags.writeable = False
return array
[docs]
class Polyline(Shape, tag="polyline"):
"""``<polyline>``: an open sequence of straight segments.
Parameters
----------
points : array-like or str, optional
Vertices as ``(N, 2)`` pairs or SVG points text. Defaults to no points.
**kwargs
Presentation, core and other SVG attributes in Python spelling.
See Also
--------
Polygon : The closed variant.
Path.from_points : The same outline as a ``<path>``.
Examples
--------
>>> import svgwriter as svg
>>> str(svg.Polyline([(0, 0), (1, 2)]))
'<polyline points="0,0 1,2"/>'
"""
geometry_attributes: ClassVar[frozenset[str]] = frozenset({"points"})
# region generated by `python scripts/dev.py svgwriter signatures write`
def __init__(
self,
points: PointsLike | str = (),
*,
transform: TransformLike | None = None,
anchor: Pivot | None = None,
fill: PaintValue = None,
fill_opacity: Opacity | None = None,
fill_rule: FillRule | None = None,
stroke: PaintValue = None,
stroke_width: LengthLike | None = None,
stroke_opacity: Opacity | None = None,
stroke_linecap: LineCap | None = None,
stroke_linejoin: LineJoin | None = None,
stroke_miterlimit: float | None = None,
stroke_dasharray: Sequence[float] | str | None = None,
stroke_dashoffset: LengthLike | None = None,
opacity: Opacity | None = None,
display: str | None = None,
visibility: str | None = None,
color: str | None = None,
clip_path: str | Element | None = None,
mask: str | Element | None = None,
filter: str | Element | None = None,
font_family: str | None = None,
font_size: LengthLike | None = None,
font_weight: str | int | None = None,
text_anchor: str | None = None,
alignment_baseline: str | None = None,
baseline_shift: LengthLike | str | None = None,
clip: str | None = None,
clip_rule: FillRule | None = None,
color_interpolation: str | None = None,
color_interpolation_filters: str | None = None,
color_profile: str | None = None,
color_rendering: str | None = None,
direction: str | None = None,
dominant_baseline: str | None = None,
enable_background: str | None = None,
flood_color: Color | str | None = None,
flood_opacity: Opacity | None = None,
font: Typeface | str | None = None,
font_size_adjust: float | str | None = None,
font_stretch: str | None = None,
font_style: str | None = None,
font_variant: str | None = None,
glyph_orientation_horizontal: float | str | None = None,
glyph_orientation_vertical: float | str | None = None,
image_rendering: str | None = None,
kerning: LengthLike | str | None = None,
letter_spacing: LengthLike | str | None = None,
lighting_color: Color | str | None = None,
marker: str | Element | None = None,
marker_end: str | Element | None = None,
marker_mid: str | Element | None = None,
marker_start: str | Element | None = None,
overflow: str | None = None,
pointer_events: str | None = None,
shape_rendering: str | None = None,
stop_color: Color | str | None = None,
stop_opacity: Opacity | None = None,
text_decoration: TextDecoration | str | None = None,
text_rendering: str | None = None,
unicode_bidi: str | None = None,
word_spacing: LengthLike | str | None = None,
writing_mode: str | None = None,
class_: str | Sequence[str] | None = None,
style: StyleLike | None = None,
required_features: str | Sequence[str] | None = None,
required_extensions: str | Sequence[str] | None = None,
system_language: str | Sequence[str] | None = None,
external_resources_required: bool | None = None,
xml_base: str | None = None,
xml_lang: str | None = None,
xml_space: XmlSpace | None = None,
id: str | None = None,
attrs: Mapping[str, AttrValue] | None = None,
**kwargs: Any,
) -> None:
"""Create a ``<polyline>`` element.
Parameters
----------
points
See the class docstring.
transform, anchor, fill, fill_opacity, fill_rule, stroke, stroke_width, stroke_opacity, stroke_linecap, stroke_linejoin, stroke_miterlimit, stroke_dasharray, stroke_dashoffset, opacity, display, visibility, color, clip_path, mask, filter, font_family, font_size, font_weight, text_anchor, alignment_baseline, baseline_shift, clip, clip_rule, color_interpolation, color_interpolation_filters, color_profile, color_rendering, direction, dominant_baseline, enable_background, flood_color, flood_opacity, font, font_size_adjust, font_stretch, font_style, font_variant, glyph_orientation_horizontal, glyph_orientation_vertical, image_rendering, kerning, letter_spacing, lighting_color, marker, marker_end, marker_mid, marker_start, overflow, pointer_events, shape_rendering, stop_color, stop_opacity, text_decoration, text_rendering, unicode_bidi, word_spacing, writing_mode, class_, style, required_features, required_extensions, system_language, external_resources_required, xml_base, xml_lang, xml_space, id, attrs
The attribute groups of :class:`~svgwriter.Transformable`, :class:`~svgwriter.PresentationAttributes`, :class:`~svgwriter.StyleAttributes`, :class:`~svgwriter.ConditionalAttributes`, :class:`~svgwriter.ExternalResourcesAttribute`, :class:`~svgwriter.CoreAttributes`, :class:`~svgwriter.Element`. Defaults to None (unset).
**kwargs
Any other SVG attribute in Python spelling, including namespaced and open ones
(``inkscape_label``, ``data_*``).
"""
self._forward_common(
kwargs, id, attrs, xml_base, xml_lang, xml_space, required_features, required_extensions,
system_language, external_resources_required, None, None, None, None, None, None, class_, style, fill,
fill_opacity, fill_rule, stroke, stroke_width, stroke_opacity, stroke_linecap, stroke_linejoin,
stroke_miterlimit, stroke_dasharray, stroke_dashoffset, opacity, display, visibility, color, clip_path,
mask, filter, font_family, font_size, font_weight, text_anchor, alignment_baseline, baseline_shift,
clip, clip_rule, color_interpolation, color_interpolation_filters, color_profile, color_rendering,
direction, dominant_baseline, enable_background, flood_color, flood_opacity, font, font_size_adjust,
font_stretch, font_style, font_variant, glyph_orientation_horizontal, glyph_orientation_vertical,
image_rendering, kerning, letter_spacing, lighting_color, marker, marker_end, marker_mid, marker_start,
overflow, pointer_events, shape_rendering, stop_color, stop_opacity, text_decoration, text_rendering,
unicode_bidi, word_spacing, writing_mode, transform, anchor
)
# endregion
super().__init__(**kwargs)
self.points = points # type: ignore[assignment]
@property
def points(self) -> np.ndarray:
"""Vertices as a read-only ``(N, 2)`` float array.
Assign any ``(N, 2)`` array-like or SVG points text to replace them.
Examples
--------
>>> import svgwriter as svg
>>> line = svg.Polyline("0,0 1,2")
>>> line.points.tolist()
[[0.0, 0.0], [1.0, 2.0]]
>>> line.points = [(5, 5), (6, 6)]
>>> str(line)
'<polyline points="5,5 6,6"/>'
"""
raw = self.attributes.get("points")
if raw is None:
return EMPTY_POINTS
if not isinstance(raw, PointList):
raw = PointList(as_points(raw))
self.attributes["points"] = raw
return raw.array
@points.setter
def points(self, value: PointsLike | str) -> None:
self.attributes["points"] = PointList(as_points(value))
[docs]
@classmethod
def regular(cls, cx: float, cy: float, radius: float, sides: int = DEFAULT_SIDES, **kwargs: Any) -> Self:
"""Create the vertices of a regular polygon.
The first vertex is at the top and the rest follow clockwise.
Parameters
----------
cx, cy : float
Center.
radius : float
Distance from the center to each vertex.
sides : int, optional
Number of vertices. Defaults to 6.
**kwargs
Presentation, core and other SVG attributes in Python spelling.
Returns
-------
Polyline
The new element; on :class:`Polygon` it is closed.
Examples
--------
>>> import svgwriter as svg
>>> str(svg.Polygon.regular(0, 0, 10, 4))
'<polygon points="0,-10 10,0 0,10 -10,0"/>'
"""
step = FULL_CIRCLE / sides
angles = np.radians(np.arange(sides) * step)
return cls(np.column_stack((cx + radius * np.sin(angles), cy - radius * np.cos(angles))), **kwargs)
@property
def bbox(self) -> BBox:
"""Geometric bounding box of the vertices; no points give a zero box.
Examples
--------
>>> import svgwriter as svg
>>> svg.Polyline([(0, 0), (4, 3)]).bbox
BBox(x=0.0, y=0.0, width=4.0, height=3.0)
"""
pts = self.points
if not len(pts):
return BBox(0.0, 0.0, 0.0, 0.0)
low, high = pts.min(axis=0), pts.max(axis=0)
return BBox(float(low[0]), float(low[1]), float(high[0] - low[0]), float(high[1] - low[1]))
def _builder(self) -> PathBuilder:
builder = PathBuilder()
for index, (x, y) in enumerate(self.points.tolist()):
if index == 0:
builder.move_to(x, y)
else:
builder.line_to(x, y)
return builder
[docs]
def local_outline(self) -> PathData:
return self._builder().build()