summaryrefslogtreecommitdiffstats
path: root/share/extensions/inkex
diff options
context:
space:
mode:
Diffstat (limited to 'share/extensions/inkex')
-rw-r--r--share/extensions/inkex/__init__.py32
-rw-r--r--share/extensions/inkex/base.py537
-rw-r--r--share/extensions/inkex/bezier.py488
-rw-r--r--share/extensions/inkex/colors.py535
-rw-r--r--share/extensions/inkex/command.py309
-rw-r--r--share/extensions/inkex/css.py61
-rw-r--r--share/extensions/inkex/deprecated-simple/README.rst4
-rw-r--r--share/extensions/inkex/deprecated-simple/bezmisc.py46
-rw-r--r--share/extensions/inkex/deprecated-simple/cspsubdiv.py25
-rw-r--r--share/extensions/inkex/deprecated-simple/cubicsuperpath.py52
-rw-r--r--share/extensions/inkex/deprecated-simple/ffgeom.py92
-rwxr-xr-xshare/extensions/inkex/deprecated-simple/run_command.py79
-rw-r--r--share/extensions/inkex/deprecated-simple/simplepath.py68
-rw-r--r--share/extensions/inkex/deprecated-simple/simplestyle.py55
-rw-r--r--share/extensions/inkex/deprecated-simple/simpletransform.py122
-rw-r--r--share/extensions/inkex/deprecated/__init__.py3
-rw-r--r--share/extensions/inkex/deprecated/deprecatedeffect.py313
-rw-r--r--share/extensions/inkex/deprecated/main.py178
-rw-r--r--share/extensions/inkex/deprecated/meta.py109
-rw-r--r--share/extensions/inkex/elements/__init__.py55
-rw-r--r--share/extensions/inkex/elements/_base.py755
-rw-r--r--share/extensions/inkex/elements/_filters.py367
-rw-r--r--share/extensions/inkex/elements/_groups.py126
-rw-r--r--share/extensions/inkex/elements/_image.py29
-rw-r--r--share/extensions/inkex/elements/_meta.py293
-rw-r--r--share/extensions/inkex/elements/_parser.py118
-rw-r--r--share/extensions/inkex/elements/_polygons.py507
-rw-r--r--share/extensions/inkex/elements/_selected.py237
-rw-r--r--share/extensions/inkex/elements/_svg.py371
-rw-r--r--share/extensions/inkex/elements/_text.py202
-rw-r--r--share/extensions/inkex/elements/_use.py81
-rw-r--r--share/extensions/inkex/elements/_utils.py144
-rw-r--r--share/extensions/inkex/extensions.py475
-rw-r--r--share/extensions/inkex/gui/README.md15
-rw-r--r--share/extensions/inkex/gui/__init__.py50
-rw-r--r--share/extensions/inkex/gui/app.py176
-rw-r--r--share/extensions/inkex/gui/asyncme.py330
-rw-r--r--share/extensions/inkex/gui/listview.py562
-rw-r--r--share/extensions/inkex/gui/pixmap.py346
-rw-r--r--share/extensions/inkex/gui/tester.py78
-rw-r--r--share/extensions/inkex/gui/window.py201
-rw-r--r--share/extensions/inkex/interfaces/IElement.py39
-rw-r--r--share/extensions/inkex/interfaces/__init__.py0
-rw-r--r--share/extensions/inkex/inx.py244
-rw-r--r--share/extensions/inkex/localization.py117
-rw-r--r--share/extensions/inkex/paths.py2018
-rw-r--r--share/extensions/inkex/ports.py105
-rw-r--r--share/extensions/inkex/properties.py800
-rw-r--r--share/extensions/inkex/styles.py621
-rw-r--r--share/extensions/inkex/tester/__init__.py437
-rw-r--r--share/extensions/inkex/tester/decorators.py9
-rw-r--r--share/extensions/inkex/tester/filters.py180
-rw-r--r--share/extensions/inkex/tester/inx.py128
-rw-r--r--share/extensions/inkex/tester/mock.py455
-rw-r--r--share/extensions/inkex/tester/svg.py55
-rw-r--r--share/extensions/inkex/tester/word.py42
-rw-r--r--share/extensions/inkex/tester/xmldiff.py124
-rw-r--r--share/extensions/inkex/transforms.py1250
-rw-r--r--share/extensions/inkex/turtle.py255
-rw-r--r--share/extensions/inkex/tween.py847
-rw-r--r--share/extensions/inkex/units.py150
-rw-r--r--share/extensions/inkex/utils.py271
62 files changed, 16773 insertions, 0 deletions
diff --git a/share/extensions/inkex/__init__.py b/share/extensions/inkex/__init__.py
new file mode 100644
index 0000000..4e0748c
--- /dev/null
+++ b/share/extensions/inkex/__init__.py
@@ -0,0 +1,32 @@
+# coding=utf-8
+"""
+This describes the core API for the inkex core modules.
+
+This provides the basis from which you can develop your inkscape extension.
+"""
+
+# pylint: disable=wildcard-import
+import sys
+
+from .extensions import *
+from .utils import AbortExtension, DependencyError, Boolean, errormsg
+from .styles import *
+from .paths import Path, CubicSuperPath # Path commands are not exported
+from .colors import *
+from .transforms import *
+from .elements import *
+
+# legacy proxies
+from .deprecated import Effect
+from .deprecated import localize
+from .deprecated import debug
+
+# legacy functions
+from .deprecated import are_near_relative
+from .deprecated import unittouu
+
+MIN_VERSION = (3, 6)
+if sys.version_info < MIN_VERSION:
+ sys.exit("Inkscape extensions require Python 3.6 or greater.")
+
+__version__ = "1.2.0" # Version number for inkex; may differ from Inkscape version.
diff --git a/share/extensions/inkex/base.py b/share/extensions/inkex/base.py
new file mode 100644
index 0000000..63f9218
--- /dev/null
+++ b/share/extensions/inkex/base.py
@@ -0,0 +1,537 @@
+# coding=utf-8
+#
+# Copyright (c) 2018 - Martin Owens <doctormo@gmail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+The ultimate base functionality for every Inkscape extension.
+"""
+
+import os
+import re
+import sys
+import copy
+
+from typing import (
+ Dict,
+ List,
+ Tuple,
+ Type,
+ Optional,
+ Callable,
+ Any,
+ Union,
+ IO,
+ TYPE_CHECKING,
+ cast,
+)
+
+from argparse import ArgumentParser, Namespace
+from lxml import etree
+
+from .interfaces.IElement import IBaseElement, ISVGDocumentElement
+from .utils import filename_arg, AbortExtension, ABORT_STATUS, errormsg, do_nothing
+from .elements._parser import load_svg
+from .elements._utils import NSS
+from .localization import localize
+
+stdout = sys.stdout.buffer # type: ignore
+
+
+class InkscapeExtension:
+ """
+ The base class extension, provides argument parsing and basic
+ variable handling features.
+ """
+
+ multi_inx = False # Set to true if this class is used by multiple inx files.
+ extra_nss = {} # type: Dict[str, str]
+
+ def __init__(self):
+ # type: () -> None
+ NSS.update(self.extra_nss)
+ self.file_io = None # type: Optional[IO]
+ self.options = Namespace()
+ self.document = None # type: Union[None, bytes, str, etree.element]
+ self.arg_parser = ArgumentParser(description=self.__doc__)
+
+ self.arg_parser.add_argument(
+ "input_file",
+ nargs="?",
+ metavar="INPUT_FILE",
+ type=filename_arg,
+ help="Filename of the input file (default is stdin)",
+ default=None,
+ )
+
+ self.arg_parser.add_argument(
+ "--output",
+ type=str,
+ default=None,
+ help="Optional output filename for saving the result (default is stdout).",
+ )
+
+ self.add_arguments(self.arg_parser)
+
+ localize()
+
+ def add_arguments(self, pars):
+ # type: (ArgumentParser) -> None
+ """Add any extra arguments to your extension handle, use:
+
+ def add_arguments(self, pars):
+ pars.add_argument("--num-cool-things", type=int, default=3)
+ pars.add_argument("--pos-in-doc", type=str, default="doobry")
+ """
+ # No extra arguments by default so super is not required
+
+ def parse_arguments(self, args):
+ # type: (List[str]) -> None
+ """Parse the given arguments and set 'self.options'"""
+ self.options = self.arg_parser.parse_args(args)
+
+ def arg_method(self, prefix="method"):
+ # type: (str) -> Callable[[str], Callable[[Any], Any]]
+ """Used by add_argument to match a tab selection with an object method
+
+ pars.add_argument("--tab", type=self.arg_method(), default="foo")
+ ...
+ self.options.tab(arguments)
+ ...
+ .. code-block:: python
+ .. def method_foo(self, arguments):
+ .. # do something
+ """
+
+ def _inner(value):
+ name = f"""{prefix}_{value.strip('"').lower()}""".replace("-", "_")
+ try:
+ return getattr(self, name)
+ except AttributeError as error:
+ if name.startswith("_"):
+ return do_nothing
+ raise AbortExtension(f"Can not find method {name}") from error
+
+ return _inner
+
+ @staticmethod
+ def arg_number_ranges():
+
+ """Parses a number descriptor. e.g:
+ ``1,2,4-5,7,9-`` is parsed to ``1, 2, 4, 5, 7, 9, 10, ..., lastvalue``
+
+ .. versionadded:: 1.2
+
+ Usage:
+
+ .. code-block:: python
+
+ # in add_arguments()
+ pars.add_argument("--pages", type=self.arg_number_ranges(), default=1-)
+ # later on, pages is then a list of ints
+ pages = self.options.pages(lastvalue)
+
+ """
+
+ def _inner(value):
+ def method(pages, lastvalue, startvalue=1):
+ # replace ranges, such as -3, 10- with startvalue,2,3,10..lastvalue
+ pages = re.sub(
+ r"(\d+|)\s?-\s?(\d+|)",
+ lambda m: ",".join(
+ map(
+ str,
+ range(
+ int(m.group(1) or startvalue),
+ int(m.group(2) or lastvalue) + 1,
+ ),
+ )
+ )
+ if not (m.group(1) or m.group(2)) == ""
+ else "",
+ pages,
+ )
+
+ pages = map(int, re.findall(r"(\d+)", pages))
+ pages = tuple({i for i in pages if i <= lastvalue})
+ return pages
+
+ return lambda lastvalue, startvalue=1: method(
+ value, lastvalue, startvalue=startvalue
+ )
+
+ return _inner
+
+ @staticmethod
+ def arg_class(options: List[Type]) -> Callable[[str], Any]:
+ """Used by add_argument to match an option with a class
+
+ Types to choose from are given by the options list
+
+ .. versionadded:: 1.2
+
+ Usage:
+
+ .. code-block:: python
+
+ pars.add_argument("--class", type=self.arg_class([ClassA, ClassB]),
+ default="ClassA")
+ """
+
+ def _inner(value: str):
+ name = value.strip('"')
+ for i in options:
+ if name == i.__name__:
+ return i
+ raise AbortExtension(f"Can not find class {name}")
+
+ return _inner
+
+ def debug(self, msg):
+ # type: (str) -> None
+ """Write a debug message"""
+ errormsg(f"DEBUG<{type(self).__name__}> {msg}\n")
+
+ @staticmethod
+ def msg(msg):
+ # type: (str) -> None
+ """Write a non-error message"""
+ errormsg(msg)
+
+ def run(self, args=None, output=stdout):
+ # type: (Optional[List[str]], Union[str, IO]) -> None
+ """Main entrypoint for any Inkscape Extension"""
+ try:
+ if args is None:
+ args = sys.argv[1:]
+
+ self.parse_arguments(args)
+ if self.options.input_file is None:
+ self.options.input_file = sys.stdin
+ elif "DOCUMENT_PATH" not in os.environ:
+ os.environ["DOCUMENT_PATH"] = self.options.input_file
+
+ if self.options.output is None:
+ self.options.output = output
+
+ self.load_raw()
+ self.save_raw(self.effect())
+ except AbortExtension as err:
+ errormsg(str(err))
+ sys.exit(ABORT_STATUS)
+ finally:
+ self.clean_up()
+
+ def load_raw(self):
+ # type: () -> None
+ """Load the input stream or filename, save everything to self"""
+ if isinstance(self.options.input_file, str):
+ # pylint: disable=consider-using-with
+ self.file_io = open(self.options.input_file, "rb")
+ document = self.load(self.file_io)
+ else:
+ document = self.load(self.options.input_file)
+ self.document = document
+
+ def save_raw(self, ret):
+ # type: (Any) -> None
+ """Save to the output stream, use everything from self"""
+ if self.has_changed(ret):
+ if isinstance(self.options.output, str):
+ with open(self.options.output, "wb") as stream:
+ self.save(stream)
+ else:
+ if sys.platform == "win32" and not "PYTEST_CURRENT_TEST" in os.environ:
+ # When calling an extension from within Inkscape on Windows,
+ # Python thinks that the output stream is seekable
+ # (https://gitlab.com/inkscape/inkscape/-/issues/3273)
+ self.options.output.seekable = lambda self: False
+
+ def seek_replacement(offset: int, whence: int = 0):
+ raise AttributeError(
+ "We can't seek in the stream passed by Inkscape on Windows"
+ )
+
+ def tell_replacement():
+ raise AttributeError(
+ "We can't tell in the stream passed by Inkscape on Windows"
+ )
+
+ # Some libraries (e.g. ZipFile) don't query seekable, but check for an error
+ # on seek
+ self.options.output.seek = seek_replacement
+ self.options.output.tell = tell_replacement
+ self.save(self.options.output)
+
+ def load(self, stream):
+ # type: (IO) -> str
+ """Takes the input stream and creates a document for parsing"""
+ raise NotImplementedError(f"No input handle for {self.name}")
+
+ def save(self, stream):
+ # type: (IO) -> None
+ """Save the given document to the output file"""
+ raise NotImplementedError(f"No output handle for {self.name}")
+
+ def effect(self):
+ # type: () -> Any
+ """Apply some effects on the document or local context"""
+ raise NotImplementedError(f"No effect handle for {self.name}")
+
+ def has_changed(self, ret): # pylint: disable=no-self-use
+ # type: (Any) -> bool
+ """Return true if the output should be saved"""
+ return ret is not False
+
+ def clean_up(self):
+ # type: () -> None
+ """Clean up any open handles and other items"""
+ if self.file_io is not None:
+ self.file_io.close()
+
+ @classmethod
+ def svg_path(cls, default=None):
+ # type: (Optional[str]) -> Optional[str]
+ """
+ Return the folder the svg is contained in.
+ Returns None if there is no file.
+
+ .. versionchanged:: 1.1
+ A default path can be given which is returned in case no path to the
+ SVG file can be determined.
+ """
+ path = cls.document_path()
+ if path:
+ return os.path.dirname(path)
+ if default:
+ return default
+ return path # Return None or '' for context
+
+ @classmethod
+ def ext_path(cls):
+ # type: () -> str
+ """Return the folder the extension script is in"""
+ return os.path.dirname(sys.modules[cls.__module__].__file__ or "")
+
+ @classmethod
+ def get_resource(cls, name, abort_on_fail=True):
+ # type: (str, bool) -> str
+ """Return the full filename of the resource in the extension's dir
+
+ .. versionadded:: 1.1"""
+ filename = cls.absolute_href(name, cwd=cls.ext_path())
+ if abort_on_fail and not os.path.isfile(filename):
+ raise AbortExtension(f"Could not find resource file: {filename}")
+ return filename
+
+ @classmethod
+ def document_path(cls):
+ # type: () -> Optional[str]
+ """Returns the saved location of the document
+
+ * Normal return is a string containing the saved location
+ * Empty string means the document was never saved
+ * 'None' means this version of Inkscape doesn't support DOCUMENT_PATH
+
+ DO NOT READ OR WRITE TO THE DOCUMENT FILENAME!
+
+ * Inkscape may have not written the latest changes, leaving you reading old
+ data.
+ * Inkscape will not respect anything you write to the file, causing data loss.
+
+ .. versionadded:: 1.1
+ """
+ return os.environ.get("DOCUMENT_PATH", None)
+
+ @classmethod
+ def absolute_href(cls, filename, default="~/", cwd=None):
+ # type: (str, str, Optional[str]) -> str
+ """
+ Process the filename such that it's turned into an absolute filename
+ with the working directory being the directory of the loaded svg.
+
+ User's home folder is also resolved. So '~/a.png` will be `/home/bob/a.png`
+
+ Default is a fallback working directory to use if the svg's filename is not
+ available.
+
+ .. versionchanged:: 1.1
+ If you set default to None, then the user will be given errors if
+ there's no working directory available from Inkscape.
+ """
+ filename = os.path.expanduser(filename)
+ if not os.path.isabs(filename):
+ filename = os.path.expanduser(filename)
+ if not os.path.isabs(filename):
+ if cwd is None:
+ cwd = cls.svg_path(default)
+ if cwd is None:
+ raise AbortExtension(
+ "Can not use relative path, Inkscape isn't telling us the "
+ "current working directory."
+ )
+ if cwd == "":
+ raise AbortExtension(
+ "The SVG must be saved before you can use relative paths."
+ )
+ filename = os.path.join(cwd, filename)
+ return os.path.realpath(os.path.expanduser(filename))
+
+ @property
+ def name(self):
+ # type: () -> str
+ """Return a fixed name for this extension"""
+ return type(self).__name__
+
+
+if TYPE_CHECKING:
+ _Base = InkscapeExtension
+else:
+ _Base = object
+
+
+class TempDirMixin(_Base): # pylint: disable=abstract-method
+ """
+ Provide a temporary directory for extensions to stash files.
+ """
+
+ dir_suffix = ""
+ dir_prefix = "inktmp"
+
+ def __init__(self, *args, **kwargs):
+ self.tempdir = None
+ super().__init__(*args, **kwargs)
+
+ def load_raw(self):
+ # type: () -> None
+ """Create the temporary directory"""
+ # pylint: disable=import-outside-toplevel
+ from tempfile import TemporaryDirectory
+
+ # Need to hold a reference to the Directory object or else it might get GC'd
+ self._tempdir = TemporaryDirectory( # pylint: disable=consider-using-with
+ prefix=self.dir_prefix, suffix=self.dir_suffix
+ )
+ self.tempdir = os.path.realpath(self._tempdir.name)
+ super().load_raw()
+
+ def clean_up(self):
+ # type: () -> None
+ """Delete the temporary directory"""
+ self.tempdir = None
+ self._tempdir.cleanup()
+ super().clean_up()
+
+
+class SvgInputMixin(_Base): # pylint: disable=too-few-public-methods, abstract-method
+ """
+ Expects the file input to be an svg document and will parse it.
+ """
+
+ # Select all objects if none are selected
+ select_all: Tuple[Type[IBaseElement], ...] = ()
+
+ def __init__(self):
+ super().__init__()
+
+ self.arg_parser.add_argument(
+ "--id",
+ action="append",
+ type=str,
+ dest="ids",
+ default=[],
+ help="id attribute of object to manipulate",
+ )
+
+ self.arg_parser.add_argument(
+ "--selected-nodes",
+ action="append",
+ type=str,
+ dest="selected_nodes",
+ default=[],
+ help="id:subpath:position of selected nodes, if any",
+ )
+
+ def load(self, stream):
+ # type: (IO) -> etree
+ """Load the stream as an svg xml etree and make a backup"""
+ document = load_svg(stream)
+ self.original_document = copy.deepcopy(document)
+ self.svg: ISVGDocumentElement = document.getroot()
+ self.svg.selection.set(*self.options.ids)
+ if not self.svg.selection and self.select_all:
+ self.svg.selection = self.svg.descendants().filter(*self.select_all)
+ return document
+
+
+class SvgOutputMixin(_Base): # pylint: disable=too-few-public-methods, abstract-method
+ """
+ Expects the output document to be an svg document and will write an etree xml.
+
+ A template can be specified to kick off the svg document building process.
+ """
+
+ template = """<svg viewBox="0 0 {width} {height}"
+ width="{width}{unit}" height="{height}{unit}"
+ xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns:xlink="http://www.w3.org/1999/xlink"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape">
+ </svg>"""
+
+ @classmethod
+ def get_template(cls, **kwargs):
+ """
+ Opens a template svg document for building, the kwargs
+ MUST include all the replacement values in the template, the
+ default template has 'width' and 'height' of the document.
+ """
+ kwargs.setdefault("unit", "")
+ return load_svg(str(cls.template.format(**kwargs)))
+
+ def save(self, stream):
+ # type: (IO) -> None
+ """Save the svg document to the given stream"""
+ if isinstance(self.document, (bytes, str)):
+ document = self.document
+ elif "Element" in type(self.document).__name__:
+ # isinstance can't be used here because etree is broken
+ doc = cast(etree, self.document)
+ document = doc.getroot().tostring()
+ else:
+ raise ValueError(
+ f"Unknown type of document: {type(self.document).__name__} can not"
+ + "save."
+ )
+
+ try:
+ stream.write(document)
+ except TypeError:
+ # we hope that this happens only when document needs to be encoded
+ stream.write(document.encode("utf-8")) # type: ignore
+
+
+class SvgThroughMixin(SvgInputMixin, SvgOutputMixin): # pylint: disable=abstract-method
+ """
+ Combine the input and output svg document handling (usually for effects).
+ """
+
+ def has_changed(self, ret): # pylint: disable=unused-argument
+ # type: (Any) -> bool
+ """Return true if the svg document has changed"""
+ original = etree.tostring(self.original_document)
+ result = etree.tostring(self.document)
+ return original != result
diff --git a/share/extensions/inkex/bezier.py b/share/extensions/inkex/bezier.py
new file mode 100644
index 0000000..976fdab
--- /dev/null
+++ b/share/extensions/inkex/bezier.py
@@ -0,0 +1,488 @@
+# coding=utf-8
+#
+# Copyright (C) 2010 Nick Drobchenko, nick@cnc-club.ru
+# Copyright (C) 2005 Aaron Spike, aaron@ekips.org
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=invalid-name,too-many-locals
+#
+"""
+Bezier calculations
+"""
+
+import cmath
+import math
+
+import numpy
+
+from .transforms import DirectedLineSegment
+from .localization import inkex_gettext as _
+
+# bez = ((bx0,by0),(bx1,by1),(bx2,by2),(bx3,by3))
+
+
+def pointdistance(point_a, point_b):
+ """The straight line distance between two points"""
+ return math.sqrt(
+ ((point_b[0] - point_a[0]) ** 2) + ((point_b[1] - point_a[1]) ** 2)
+ )
+
+
+def between_point(point_a, point_b, time=0.5):
+ """Returns the point between point a and point b"""
+ return point_a[0] + time * (point_b[0] - point_a[0]), point_a[1] + time * (
+ point_b[1] - point_a[1]
+ )
+
+
+def percent_point(point_a, point_b, percent=50.0):
+ """Returns between_point but takes percent instead of 0.0-1.0"""
+ return between_point(point_a, point_b, percent / 100.0)
+
+
+def root_wrapper(root_a, root_b, root_c, root_d):
+ """Get the Cubic function, moic formular of roots, simple root"""
+ if root_a:
+ # Monics formula, see
+ # http://en.wikipedia.org/wiki/Cubic_function#Monic_formula_of_roots
+ mono_a, mono_b, mono_c = (root_b / root_a, root_c / root_a, root_d / root_a)
+ m = 2.0 * mono_a**3 - 9.0 * mono_a * mono_b + 27.0 * mono_c
+ k = mono_a**2 - 3.0 * mono_b
+ n = m**2 - 4.0 * k**3
+ w1 = -0.5 + 0.5 * cmath.sqrt(-3.0)
+ w2 = -0.5 - 0.5 * cmath.sqrt(-3.0)
+ if n < 0:
+ m1 = pow(complex((m + cmath.sqrt(n)) / 2), 1.0 / 3)
+ n1 = pow(complex((m - cmath.sqrt(n)) / 2), 1.0 / 3)
+ else:
+ if m + math.sqrt(n) < 0:
+ m1 = -pow(-(m + math.sqrt(n)) / 2, 1.0 / 3)
+ else:
+ m1 = pow((m + math.sqrt(n)) / 2, 1.0 / 3)
+ if m - math.sqrt(n) < 0:
+ n1 = -pow(-(m - math.sqrt(n)) / 2, 1.0 / 3)
+ else:
+ n1 = pow((m - math.sqrt(n)) / 2, 1.0 / 3)
+ return (
+ -1.0 / 3 * (mono_a + m1 + n1),
+ -1.0 / 3 * (mono_a + w1 * m1 + w2 * n1),
+ -1.0 / 3 * (mono_a + w2 * m1 + w1 * n1),
+ )
+ if root_b:
+ det = root_c**2.0 - 4.0 * root_b * root_d
+ if det:
+ return (
+ (-root_c + cmath.sqrt(det)) / (2.0 * root_b),
+ (-root_c - cmath.sqrt(det)) / (2.0 * root_b),
+ )
+ return (-root_c / (2.0 * root_b),)
+ if root_c:
+ return (1.0 * (-root_d / root_c),)
+ return ()
+
+
+def bezlenapprx(sp1, sp2):
+ """Return the aproximate length between two beziers"""
+ return (
+ pointdistance(sp1[1], sp1[2])
+ + pointdistance(sp1[2], sp2[0])
+ + pointdistance(sp2[0], sp2[1])
+ )
+
+
+def cspbezsplit(sp1, sp2, time=0.5):
+ """Split a cubic bezier at the time period"""
+ m1 = tpoint(sp1[1], sp1[2], time)
+ m2 = tpoint(sp1[2], sp2[0], time)
+ m3 = tpoint(sp2[0], sp2[1], time)
+ m4 = tpoint(m1, m2, time)
+ m5 = tpoint(m2, m3, time)
+ m = tpoint(m4, m5, time)
+ return [[sp1[0][:], sp1[1][:], m1], [m4, m, m5], [m3, sp2[1][:], sp2[2][:]]]
+
+
+def cspbezsplitatlength(sp1, sp2, length=0.5, tolerance=0.001):
+ """Split a cubic bezier at length"""
+ bez = (sp1[1][:], sp1[2][:], sp2[0][:], sp2[1][:])
+ time = beziertatlength(bez, length, tolerance)
+ return cspbezsplit(sp1, sp2, time)
+
+
+def cspseglength(sp1, sp2, tolerance=0.001):
+ """Get cubic bezier segment length"""
+ bez = (sp1[1][:], sp1[2][:], sp2[0][:], sp2[1][:])
+ return bezierlength(bez, tolerance)
+
+
+def csplength(csp):
+ """Get cubic bezier length"""
+ total = 0
+ lengths = []
+ for sp in csp:
+ lengths.append([])
+ for i in range(1, len(sp)):
+ l = cspseglength(sp[i - 1], sp[i])
+ lengths[-1].append(l)
+ total += l
+ return lengths, total
+
+
+def bezierparameterize(bez):
+ """Return the bezier parameter size
+ Converts the bezier parametrisation from the default form
+ P(t) = (1-t)³ P_1 + 3(1-t)²t P_2 + 3(1-t)t² P_3 + t³ x_4
+ to the a form which can be differentiated more easily
+ P(t) = a t³ + b t² + c t + P0
+
+ Args:
+ bez (List[Tuple[float, float]]): the Bezier curve. The elements of the list the
+ coordinates of the points (in this order): Start point, Start control point,
+ End control point, End point.
+
+ Returns:
+ Tuple[float, float, float, float, float, float, float, float]:
+ the values ax, ay, bx, by, cx, cy, x0, y0
+ """
+ ((bx0, by0), (bx1, by1), (bx2, by2), (bx3, by3)) = bez
+ # parametric bezier
+ x0 = bx0
+ y0 = by0
+ cx = 3 * (bx1 - x0)
+ bx = 3 * (bx2 - bx1) - cx
+ ax = bx3 - x0 - cx - bx
+ cy = 3 * (by1 - y0)
+ by = 3 * (by2 - by1) - cy
+ ay = by3 - y0 - cy - by
+
+ return ax, ay, bx, by, cx, cy, x0, y0
+
+
+def linebezierintersect(arg_a, bez):
+ """Where a line and bezier intersect"""
+ ((lx1, ly1), (lx2, ly2)) = arg_a
+ # parametric line
+ dd = lx1
+ cc = lx2 - lx1
+ bb = ly1
+ aa = ly2 - ly1
+
+ if aa:
+ coef1 = cc / aa
+ coef2 = 1
+ else:
+ coef1 = 1
+ coef2 = aa / cc
+
+ ax, ay, bx, by, cx, cy, x0, y0 = bezierparameterize(bez)
+ # cubic intersection coefficients
+ a = coef1 * ay - coef2 * ax
+ b = coef1 * by - coef2 * bx
+ c = coef1 * cy - coef2 * cx
+ d = coef1 * (y0 - bb) - coef2 * (x0 - dd)
+
+ roots = root_wrapper(a, b, c, d)
+ retval = []
+ for i in roots:
+ if isinstance(i, complex) and i.imag == 0:
+ i = i.real
+ if not isinstance(i, complex) and 0 <= i <= 1:
+ retval.append(bezierpointatt(bez, i))
+ return retval
+
+
+def bezierpointatt(bez, t):
+ """Get coords at the given time point along a bezier curve"""
+ ax, ay, bx, by, cx, cy, x0, y0 = bezierparameterize(bez)
+ x = ax * (t**3) + bx * (t**2) + cx * t + x0
+ y = ay * (t**3) + by * (t**2) + cy * t + y0
+ return x, y
+
+
+def bezierslopeatt(bez, t):
+ """Get slope at the given time point along a bezier curve
+ The slope is computed as (dx, dy) where dx = df_x(t)/dt and dy = df_y(t)/dt.
+ Note that for lines P1=P2 and P3=P4, so the slope at the end points is dx=dy=0
+ (slope not defined).
+
+ Args:
+ bez (List[Tuple[float, float]]): the Bezier curve. The elements of the list the
+ coordinates of the points (in this order): Start point, Start control point,
+ End control point, End point.
+ t (float): time in the interval [0, 1]
+
+ Returns:
+ Tuple[float, float]: x and y increment
+ """
+ ax, ay, bx, by, cx, cy, _, _ = bezierparameterize(bez)
+ dx = 3 * ax * (t**2) + 2 * bx * t + cx
+ dy = 3 * ay * (t**2) + 2 * by * t + cy
+ return dx, dy
+
+
+def beziertatslope(bez, d):
+ """Reverse; get time from slope along a bezier curve"""
+ ax, ay, bx, by, cx, cy, _, _ = bezierparameterize(bez)
+ (dy, dx) = d
+ # quadratic coefficients of slope formula
+ if dx:
+ slope = 1.0 * (dy / dx)
+ a = 3 * ay - 3 * ax * slope
+ b = 2 * by - 2 * bx * slope
+ c = cy - cx * slope
+ elif dy:
+ slope = 1.0 * (dx / dy)
+ a = 3 * ax - 3 * ay * slope
+ b = 2 * bx - 2 * by * slope
+ c = cx - cy * slope
+ else:
+ return []
+
+ roots = root_wrapper(0, a, b, c)
+ retval = []
+ for i in roots:
+ if isinstance(i, complex) and i.imag == 0:
+ i = i.real
+ if not isinstance(i, complex) and 0 <= i <= 1:
+ retval.append(i)
+ return retval
+
+
+def tpoint(p1, p2, t):
+ """Linearly interpolate between p1 and p2.
+
+ t = 0.0 returns p1, t = 1.0 returns p2.
+
+ :return: Interpolated point
+ :rtype: tuple
+
+ :param p1: First point as sequence of two floats
+ :param p2: Second point as sequence of two floats
+ :param t: Number between 0.0 and 1.0
+ :type t: float
+ """
+ x1, y1 = p1
+ x2, y2 = p2
+ return x1 + t * (x2 - x1), y1 + t * (y2 - y1)
+
+
+def beziersplitatt(bez, t):
+ """Split bezier at given time"""
+ ((bx0, by0), (bx1, by1), (bx2, by2), (bx3, by3)) = bez
+ m1 = tpoint((bx0, by0), (bx1, by1), t)
+ m2 = tpoint((bx1, by1), (bx2, by2), t)
+ m3 = tpoint((bx2, by2), (bx3, by3), t)
+ m4 = tpoint(m1, m2, t)
+ m5 = tpoint(m2, m3, t)
+ m = tpoint(m4, m5, t)
+
+ return ((bx0, by0), m1, m4, m), (m, m5, m3, (bx3, by3))
+
+
+def addifclose(bez, l, error=0.001):
+ """Gravesen, Add if the line is closed, in-place addition to array l"""
+ box = 0
+ for i in range(1, 4):
+ box += pointdistance(bez[i - 1], bez[i])
+ chord = pointdistance(bez[0], bez[3])
+ if (box - chord) > error:
+ first, second = beziersplitatt(bez, 0.5)
+ addifclose(first, l, error)
+ addifclose(second, l, error)
+ else:
+ l[0] += (box / 2.0) + (chord / 2.0)
+
+
+# balfax, balfbx, balfcx, balfay, balfby, balfcy = 0, 0, 0, 0, 0, 0
+
+
+def balf(t, args):
+ """Bezier Arc Length Function"""
+ ax, bx, cx, ay, by, cy = args
+ retval = (ax * (t**2) + bx * t + cx) ** 2 + (ay * (t**2) + by * t + cy) ** 2
+ return math.sqrt(retval)
+
+
+def simpson(start, end, maxiter, tolerance, bezier_args):
+ """Calculate the length of a bezier curve using Simpson's algorithm:
+ http://steve.hollasch.net/cgindex/curves/cbezarclen.html
+
+ Args:
+ start (int): Start time (between 0 and 1)
+ end (int): End time (between start time and 1)
+ maxiter (int): Maximum number of iterations. If not a power of 2, the algorithm
+ will behave like the value is set to the next power of 2.
+ tolerance (float): maximum error ratio
+ bezier_args (list): arguments as computed by bezierparametrize()
+
+ Returns:
+ float: the appoximate length of the bezier curve
+ """
+
+ n = 2
+ multiplier = (end - start) / 6.0
+ endsum = balf(start, bezier_args) + balf(end, bezier_args)
+ interval = (end - start) / 2.0
+ asum = 0.0
+ bsum = balf(start + interval, bezier_args)
+ est1 = multiplier * (endsum + (2.0 * asum) + (4.0 * bsum))
+ est0 = 2.0 * est1
+ # print(multiplier, endsum, interval, asum, bsum, est1, est0)
+ while n < maxiter and abs(est1 - est0) > tolerance:
+ n *= 2
+ multiplier /= 2.0
+ interval /= 2.0
+ asum += bsum
+ bsum = 0.0
+ est0 = est1
+ for i in range(1, n, 2):
+ bsum += balf(start + (i * interval), bezier_args)
+ est1 = multiplier * (endsum + (2.0 * asum) + (4.0 * bsum))
+ # print(multiplier, endsum, interval, asum, bsum, est1, est0)
+ return est1
+
+
+def bezierlength(bez, tolerance=0.001, time=1.0):
+ """Get length of bezier curve"""
+ ax, ay, bx, by, cx, cy, _, _ = bezierparameterize(bez)
+ return simpson(0.0, time, 4096, tolerance, [3 * ax, 2 * bx, cx, 3 * ay, 2 * by, cy])
+
+
+def beziertatlength(bez, l=0.5, tolerance=0.001):
+ """Get bezier curve time at the length specified"""
+ curlen = bezierlength(bez, tolerance, 1.0)
+ time = 1.0
+ tdiv = time
+ targetlen = l * curlen
+ diff = curlen - targetlen
+ while abs(diff) > tolerance:
+ tdiv /= 2.0
+ if diff < 0:
+ time += tdiv
+ else:
+ time -= tdiv
+ curlen = bezierlength(bez, tolerance, time)
+ diff = curlen - targetlen
+ return time
+
+
+def maxdist(bez):
+ """Get maximum distance within bezier curve"""
+ seg = DirectedLineSegment(bez[0], bez[3])
+ return max(seg.distance_to_point(*bez[1]), seg.distance_to_point(*bez[2]))
+
+
+def cspsubdiv(csp, flat):
+ """Sub-divide cubic sub-paths"""
+ for sp in csp:
+ subdiv(sp, flat)
+
+
+def subdiv(sp, flat, i=1):
+ """sub divide bezier curve"""
+ while i < len(sp):
+ p0 = sp[i - 1][1]
+ p1 = sp[i - 1][2]
+ p2 = sp[i][0]
+ p3 = sp[i][1]
+
+ bez = (p0, p1, p2, p3)
+ mdist = maxdist(bez)
+ if mdist <= flat:
+ i += 1
+ else:
+ one, two = beziersplitatt(bez, 0.5)
+ sp[i - 1][2] = one[1]
+ sp[i][0] = two[2]
+ p = [one[2], one[3], two[1]]
+ sp[i:1] = [p]
+
+
+def csparea(csp):
+ """Get area in cubic sub-path"""
+ MAT_AREA = numpy.array(
+ [[0, 2, 1, -3], [-2, 0, 1, 1], [-1, -1, 0, 2], [3, -1, -2, 0]]
+ )
+ area = 0.0
+ for sp in csp:
+ if len(sp) < 2:
+ continue
+ for x, coord in enumerate(sp): # calculate polygon area
+ area += 0.5 * sp[x - 1][1][0] * (coord[1][1] - sp[x - 2][1][1])
+ for i in range(1, len(sp)): # add contribution from cubic Bezier
+ vec_x = numpy.array(
+ [sp[i - 1][1][0], sp[i - 1][2][0], sp[i][0][0], sp[i][1][0]]
+ )
+ vec_y = numpy.array(
+ [sp[i - 1][1][1], sp[i - 1][2][1], sp[i][0][1], sp[i][1][1]]
+ )
+ vex = numpy.matmul(vec_x, MAT_AREA)
+ area += 0.15 * numpy.matmul(vex, vec_y.T)
+ return -area
+
+
+def cspcofm(csp):
+ """Get cubic sub-path coefficient"""
+ MAT_COFM_0 = numpy.array(
+ [[0, 35, 10, -45], [-35, 0, 12, 23], [-10, -12, 0, 22], [45, -23, -22, 0]]
+ )
+
+ MAT_COFM_1 = numpy.array(
+ [[0, 15, 3, -18], [-15, 0, 9, 6], [-3, -9, 0, 12], [18, -6, -12, 0]]
+ )
+
+ MAT_COFM_2 = numpy.array(
+ [[0, 12, 6, -18], [-12, 0, 9, 3], [-6, -9, 0, 15], [18, -3, -15, 0]]
+ )
+
+ MAT_COFM_3 = numpy.array(
+ [[0, 22, 23, -45], [-22, 0, 12, 10], [-23, -12, 0, 35], [45, -10, -35, 0]]
+ )
+ area = csparea(csp)
+ xc = 0.0
+ yc = 0.0
+ if abs(area) < 1.0e-8:
+ raise ValueError(_("Area is zero, cannot calculate Center of Mass"))
+ for sp in csp:
+ for x, coord in enumerate(sp): # calculate polygon moment
+ xc += (
+ sp[x - 1][1][1]
+ * (sp[x - 2][1][0] - coord[1][0])
+ * (sp[x - 2][1][0] + sp[x - 1][1][0] + coord[1][0])
+ / 6
+ )
+ yc += (
+ sp[x - 1][1][0]
+ * (coord[1][1] - sp[x - 2][1][1])
+ * (sp[x - 2][1][1] + sp[x - 1][1][1] + coord[1][1])
+ / 6
+ )
+ for i in range(1, len(sp)): # add contribution from cubic Bezier
+ vec_x = numpy.array(
+ [sp[i - 1][1][0], sp[i - 1][2][0], sp[i][0][0], sp[i][1][0]]
+ )
+ vec_y = numpy.array(
+ [sp[i - 1][1][1], sp[i - 1][2][1], sp[i][0][1], sp[i][1][1]]
+ )
+
+ def _mul(MAT, vec_x=vec_x, vec_y=vec_y):
+ return numpy.matmul(numpy.matmul(vec_x, MAT), vec_y.T)
+
+ vec_t = numpy.array(
+ [_mul(MAT_COFM_0), _mul(MAT_COFM_1), _mul(MAT_COFM_2), _mul(MAT_COFM_3)]
+ )
+ xc += numpy.matmul(vec_x, vec_t.T) / 280
+ yc += numpy.matmul(vec_y, vec_t.T) / 280
+ return -xc / area, -yc / area
diff --git a/share/extensions/inkex/colors.py b/share/extensions/inkex/colors.py
new file mode 100644
index 0000000..9a583ff
--- /dev/null
+++ b/share/extensions/inkex/colors.py
@@ -0,0 +1,535 @@
+# coding=utf-8
+#
+# Copyright (C) 2006 Jos Hirth, kaioa.com
+# Copyright (C) 2007 Aaron C. Spike
+# Copyright (C) 2009 Monash University
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Basic color controls
+"""
+
+
+# All the names that get added to the inkex API itself.
+__all__ = ("Color", "ColorError", "ColorIdError")
+
+SVG_COLOR = {
+ "aliceblue": "#f0f8ff",
+ "antiquewhite": "#faebd7",
+ "aqua": "#00ffff",
+ "aquamarine": "#7fffd4",
+ "azure": "#f0ffff",
+ "beige": "#f5f5dc",
+ "bisque": "#ffe4c4",
+ "black": "#000000",
+ "blanchedalmond": "#ffebcd",
+ "blue": "#0000ff",
+ "blueviolet": "#8a2be2",
+ "brown": "#a52a2a",
+ "burlywood": "#deb887",
+ "cadetblue": "#5f9ea0",
+ "chartreuse": "#7fff00",
+ "chocolate": "#d2691e",
+ "coral": "#ff7f50",
+ "cornflowerblue": "#6495ed",
+ "cornsilk": "#fff8dc",
+ "crimson": "#dc143c",
+ "cyan": "#00ffff",
+ "darkblue": "#00008b",
+ "darkcyan": "#008b8b",
+ "darkgoldenrod": "#b8860b",
+ "darkgray": "#a9a9a9",
+ "darkgreen": "#006400",
+ "darkgrey": "#a9a9a9",
+ "darkkhaki": "#bdb76b",
+ "darkmagenta": "#8b008b",
+ "darkolivegreen": "#556b2f",
+ "darkorange": "#ff8c00",
+ "darkorchid": "#9932cc",
+ "darkred": "#8b0000",
+ "darksalmon": "#e9967a",
+ "darkseagreen": "#8fbc8f",
+ "darkslateblue": "#483d8b",
+ "darkslategray": "#2f4f4f",
+ "darkslategrey": "#2f4f4f",
+ "darkturquoise": "#00ced1",
+ "darkviolet": "#9400d3",
+ "deeppink": "#ff1493",
+ "deepskyblue": "#00bfff",
+ "dimgray": "#696969",
+ "dimgrey": "#696969",
+ "dodgerblue": "#1e90ff",
+ "firebrick": "#b22222",
+ "floralwhite": "#fffaf0",
+ "forestgreen": "#228b22",
+ "fuchsia": "#ff00ff",
+ "gainsboro": "#dcdcdc",
+ "ghostwhite": "#f8f8ff",
+ "gold": "#ffd700",
+ "goldenrod": "#daa520",
+ "gray": "#808080",
+ "grey": "#808080",
+ "green": "#008000",
+ "greenyellow": "#adff2f",
+ "honeydew": "#f0fff0",
+ "hotpink": "#ff69b4",
+ "indianred": "#cd5c5c",
+ "indigo": "#4b0082",
+ "ivory": "#fffff0",
+ "khaki": "#f0e68c",
+ "lavender": "#e6e6fa",
+ "lavenderblush": "#fff0f5",
+ "lawngreen": "#7cfc00",
+ "lemonchiffon": "#fffacd",
+ "lightblue": "#add8e6",
+ "lightcoral": "#f08080",
+ "lightcyan": "#e0ffff",
+ "lightgoldenrodyellow": "#fafad2",
+ "lightgray": "#d3d3d3",
+ "lightgreen": "#90ee90",
+ "lightgrey": "#d3d3d3",
+ "lightpink": "#ffb6c1",
+ "lightsalmon": "#ffa07a",
+ "lightseagreen": "#20b2aa",
+ "lightskyblue": "#87cefa",
+ "lightslategray": "#778899",
+ "lightslategrey": "#778899",
+ "lightsteelblue": "#b0c4de",
+ "lightyellow": "#ffffe0",
+ "lime": "#00ff00",
+ "limegreen": "#32cd32",
+ "linen": "#faf0e6",
+ "magenta": "#ff00ff",
+ "maroon": "#800000",
+ "mediumaquamarine": "#66cdaa",
+ "mediumblue": "#0000cd",
+ "mediumorchid": "#ba55d3",
+ "mediumpurple": "#9370db",
+ "mediumseagreen": "#3cb371",
+ "mediumslateblue": "#7b68ee",
+ "mediumspringgreen": "#00fa9a",
+ "mediumturquoise": "#48d1cc",
+ "mediumvioletred": "#c71585",
+ "midnightblue": "#191970",
+ "mintcream": "#f5fffa",
+ "mistyrose": "#ffe4e1",
+ "moccasin": "#ffe4b5",
+ "navajowhite": "#ffdead",
+ "navy": "#000080",
+ "oldlace": "#fdf5e6",
+ "olive": "#808000",
+ "olivedrab": "#6b8e23",
+ "orange": "#ffa500",
+ "orangered": "#ff4500",
+ "orchid": "#da70d6",
+ "palegoldenrod": "#eee8aa",
+ "palegreen": "#98fb98",
+ "paleturquoise": "#afeeee",
+ "palevioletred": "#db7093",
+ "papayawhip": "#ffefd5",
+ "peachpuff": "#ffdab9",
+ "peru": "#cd853f",
+ "pink": "#ffc0cb",
+ "plum": "#dda0dd",
+ "powderblue": "#b0e0e6",
+ "purple": "#800080",
+ "rebeccapurple": "#663399",
+ "red": "#ff0000",
+ "rosybrown": "#bc8f8f",
+ "royalblue": "#4169e1",
+ "saddlebrown": "#8b4513",
+ "salmon": "#fa8072",
+ "sandybrown": "#f4a460",
+ "seagreen": "#2e8b57",
+ "seashell": "#fff5ee",
+ "sienna": "#a0522d",
+ "silver": "#c0c0c0",
+ "skyblue": "#87ceeb",
+ "slateblue": "#6a5acd",
+ "slategray": "#708090",
+ "slategrey": "#708090",
+ "snow": "#fffafa",
+ "springgreen": "#00ff7f",
+ "steelblue": "#4682b4",
+ "tan": "#d2b48c",
+ "teal": "#008080",
+ "thistle": "#d8bfd8",
+ "tomato": "#ff6347",
+ "turquoise": "#40e0d0",
+ "violet": "#ee82ee",
+ "wheat": "#f5deb3",
+ "white": "#ffffff",
+ "whitesmoke": "#f5f5f5",
+ "yellow": "#ffff00",
+ "yellowgreen": "#9acd32",
+ "none": None,
+}
+COLOR_SVG = {value: name for name, value in SVG_COLOR.items()}
+
+
+def is_color(color):
+ """Determine if it is a color that we can use. If not, leave it unchanged."""
+ try:
+ return bool(Color(color))
+ except ColorError:
+ return False
+
+
+def constrain(minim, value, maxim, channel):
+ """Returns the value so long as it is between min and max values"""
+ if channel == "h": # Hue
+ return value % maxim # Wrap around hue value
+ return min([maxim, max([minim, value])])
+
+
+class ColorError(KeyError):
+ """Specific color parsing error"""
+
+
+class ColorIdError(ColorError):
+ """Special color error for gradient and color stop ids"""
+
+
+class Color(list):
+ """An RGB array for the color
+
+ Can be constructed from valid CSS color attributes, as well as
+ tuple/list + color space. Percentage values are supported.
+
+ .. versionchanged:: 1.2
+ Clarification with respect to values denoting unity: For RGB color channels,
+ "1.0", 1.0 and "100%" are treated as 255, while "1" and 1 are treated as 1.
+
+ """
+
+ red = property(
+ lambda self: self.to_rgb()[0], lambda self, value: self._set(0, value)
+ )
+ green = property(
+ lambda self: self.to_rgb()[1], lambda self, value: self._set(1, value)
+ )
+ blue = property(
+ lambda self: self.to_rgb()[2], lambda self, value: self._set(2, value)
+ )
+ alpha = property(
+ lambda self: self.to_rgba()[3],
+ lambda self, value: self._set(3, value, ("rgba",)),
+ )
+ hue = property(
+ lambda self: self.to_hsl()[0], lambda self, value: self._set(0, value, ("hsl",))
+ )
+ saturation = property(
+ lambda self: self.to_hsl()[1], lambda self, value: self._set(1, value, ("hsl",))
+ )
+ lightness = property(
+ lambda self: self.to_hsl()[2], lambda self, value: self._set(2, value, ("hsl",))
+ )
+
+ def __init__(self, color=None, space="rgb"):
+ super().__init__()
+ if isinstance(color, Color):
+ space, color = color.space, list(color)
+
+ if isinstance(color, str):
+ # String from xml or css attributes
+ space, color = self.parse_str(color.strip())
+
+ if isinstance(color, int):
+ # Number from arg parser colour value
+ space, color = self.parse_int(color)
+
+ # Empty list means 'none', or no color
+ if color is None:
+ color = []
+
+ if not isinstance(color, (list, tuple)):
+ raise ColorError("Not a known a color value")
+
+ self.space = space
+ try:
+ for val in color:
+ self.append(val)
+ except ValueError as error:
+ raise ColorError("Bad color list") from error
+
+ def __hash__(self):
+ """Allow colors to be hashable"""
+ return tuple(self.to_rgba()).__hash__()
+
+ def _set(self, index, value, spaces=("rgb", "rgba")):
+ """Set the color value in place, limits setter to specific color space"""
+ # Named colors are just rgb, so dump name memory
+ if self.space == "named":
+ self.space = "rgb"
+ if not self.space in spaces:
+ if index == 3 and self.space == "rgb":
+ # Special, add alpha, don't convert back to rgb
+ self.space = "rgba"
+ self.append(constrain(0.0, float(value), 1.0, "a"))
+ return
+ # Set in other colour space and convert back and forth
+ target = self.to(spaces[0])
+ target[index] = constrain(0, int(value), 255, spaces[0][index])
+ self[:] = target.to(self.space)
+ return
+ self[index] = constrain(0, int(value), 255, spaces[0][index])
+
+ def append(self, val):
+ """Append a value to the local list"""
+ if len(self) == len(self.space):
+ raise ValueError("Can't add any more values to color.")
+
+ if isinstance(val, str):
+ val = val.strip()
+ if val.endswith("%"):
+ val = float(val.strip("%")) / 100
+ elif "." in val:
+ val = float(val)
+ else:
+ val = int(val)
+
+ end_type = int
+ if len(self) == 3: # Alpha value
+ val = min([1.0, val])
+ end_type = float
+ elif isinstance(val, float) and val <= 1.0:
+ val *= 255
+
+ if isinstance(val, (int, float)):
+ super().append(max(end_type(val), 0))
+
+ @staticmethod
+ def parse_str(color):
+ """Creates a rgb int array"""
+ # Handle pre-defined svg color values
+ if color and color.lower() in SVG_COLOR:
+ return "named", Color.parse_str(SVG_COLOR[color.lower()])[1]
+
+ if color is None:
+ return "rgb", None
+
+ if color.startswith("url("):
+ raise ColorIdError("Color references other element id, e.g. a gradient")
+
+ # Next handle short colors (css: #abc -> #aabbcc)
+ if color.startswith("#"):
+ # Remove any icc or ilab directives
+ # FUTURE: We could use icc or ilab information
+ col = color.split(" ")[0]
+ if len(col) == 4:
+ # pylint: disable=consider-using-f-string
+ col = "#{1}{1}{2}{2}{3}{3}".format(*col)
+
+ # Convert hex to integers
+ try:
+ return "rgb", (int(col[1:3], 16), int(col[3:5], 16), int(col[5:], 16))
+ except ValueError as error:
+ raise ColorError(f"Bad RGB hex color value {col}") from error
+
+ # Handle other css color values
+ elif "(" in color and ")" in color:
+ space, values = color.lower().strip().strip(")").split("(")
+ return space, values.split(",")
+
+ try:
+ return Color.parse_int(int(color))
+ except ValueError:
+ pass
+
+ raise ColorError(f"Unknown color format: {color}")
+
+ @staticmethod
+ def parse_int(color):
+ """Creates an rgb or rgba from a long int"""
+ space = "rgb"
+ color = [
+ ((color >> 24) & 255), # red
+ ((color >> 16) & 255), # green
+ ((color >> 8) & 255), # blue
+ ((color & 255) / 255.0), # opacity
+ ]
+ if color[-1] == 1.0:
+ color.pop()
+ else:
+ space = "rgba"
+ return space, color
+
+ def __str__(self):
+ """int array to #rrggbb"""
+ # pylint: disable=consider-using-f-string
+ if not self:
+ return "none"
+ if self.space == "named":
+ rgbhex = "#{0:02x}{1:02x}{2:02x}".format(*self)
+ if rgbhex in COLOR_SVG:
+ return COLOR_SVG[rgbhex]
+ self.space = "rgb"
+ if self.space == "rgb":
+ return "#{0:02x}{1:02x}{2:02x}".format(*self)
+ if self.space == "rgba":
+ if self[3] == 1.0:
+ return "rgb({:g}, {:g}, {:g})".format(*self[:3])
+ return "rgba({:g}, {:g}, {:g}, {:g})".format(*self)
+ if self.space == "hsl":
+ return "hsl({0:g}, {1:g}, {2:g})".format(*self)
+ raise ColorError(f"Can't print colour space '{self.space}'")
+
+ def __int__(self):
+ """int array to large integer"""
+ if not self:
+ return -1
+ color = self.to_rgba()
+ return (
+ (color[0] << 24)
+ + (color[1] << 16)
+ + (color[2] << 8)
+ + (int(color[3] * 255))
+ )
+
+ def to(self, space): # pylint: disable=invalid-name
+ """Dynamic caller for to_hsl, to_rgb, etc"""
+ return getattr(self, "to_" + space)()
+
+ def to_hsl(self):
+ """Turn this color into a Hue/Saturation/Lightness colour space"""
+ if not self and self.space in ("rgb", "named"):
+ return self.to_rgb().to_hsl()
+ if self.space == "hsl":
+ return self
+ if self.space in ("named"):
+ return self.to_rgb().to_hsl()
+ if self.space == "rgb":
+ return Color(rgb_to_hsl(*self.to_floats()), space="hsl")
+ raise ColorError(f"Unknown color conversion {self.space}->hsl")
+
+ def to_rgb(self):
+ """Turn this color into a Red/Green/Blue colour space"""
+ if not self and self.space in ("rgb", "named"):
+ return Color([0, 0, 0])
+ if self.space == "rgb":
+ return self
+ if self.space in ("rgba", "named"):
+ return Color(self[:3], space="rgb")
+ if self.space == "hsl":
+ return Color(hsl_to_rgb(*self.to_floats()), space="rgb")
+ raise ColorError(f"Unknown color conversion {self.space}->rgb")
+
+ def to_rgba(self, alpha=1.0):
+ """Turn this color isn't an RGB with Alpha colour space"""
+ if self.space == "rgba":
+ return self
+ return Color(self.to_rgb() + [alpha], "rgba")
+
+ def to_floats(self):
+ """Returns the colour values as percentage floats (0.0 - 1.0)"""
+ return [val / 255.0 for val in self]
+
+ def to_named(self):
+ """Convert this color to a named color if possible"""
+ if not self:
+ return Color()
+ return Color(COLOR_SVG.get(str(self), str(self)))
+
+ def interpolate(self, other, fraction):
+ """Interpolate two colours by the given fraction
+
+ .. versionadded:: 1.1"""
+ from .tween import ColorInterpolator # pylint: disable=import-outside-toplevel
+
+ return ColorInterpolator(self, other).interpolate(fraction)
+
+ @staticmethod
+ def isnone(x):
+ """Checks if a given color is none
+
+ .. versionadded:: 1.2"""
+
+ if x is None or (isinstance(x, str) and x.lower() == "none"):
+ return True
+ return False
+
+ @staticmethod
+ def iscolor(x, accept_none=False):
+ """Checks if a given value can be parsed as a color
+
+ .. versionadded:: 1.2"""
+ if isinstance(x, str) and (accept_none or not (Color.isnone(x))):
+ try:
+ Color(x)
+ return True
+ except (ColorError):
+ pass
+ if isinstance(x, Color):
+ return True
+ return False
+
+
+def rgb_to_hsl(red, green, blue):
+ """RGB to HSL colour conversion"""
+ rgb_max = max(red, green, blue)
+ rgb_min = min(red, green, blue)
+ delta = rgb_max - rgb_min
+ hsl = [0.0, 0.0, (rgb_max + rgb_min) / 2.0]
+ if delta != 0:
+ if hsl[2] <= 0.5:
+ hsl[1] = delta / (rgb_max + rgb_min)
+ else:
+ hsl[1] = delta / (2 - rgb_max - rgb_min)
+
+ if red == rgb_max:
+ hsl[0] = (green - blue) / delta
+ elif green == rgb_max:
+ hsl[0] = 2.0 + (blue - red) / delta
+ elif blue == rgb_max:
+ hsl[0] = 4.0 + (red - green) / delta
+
+ hsl[0] /= 6.0
+ if hsl[0] < 0:
+ hsl[0] += 1
+ if hsl[0] > 1:
+ hsl[0] -= 1
+ return hsl
+
+
+def hsl_to_rgb(hue, sat, light):
+ """HSL to RGB Color Conversion"""
+ if sat == 0:
+ return [light, light, light] # Gray
+
+ if light < 0.5:
+ val2 = light * (1 + sat)
+ else:
+ val2 = light + sat - light * sat
+ val1 = 2 * light - val2
+ return [
+ _hue_to_rgb(val1, val2, hue * 6 + 2.0),
+ _hue_to_rgb(val1, val2, hue * 6),
+ _hue_to_rgb(val1, val2, hue * 6 - 2.0),
+ ]
+
+
+def _hue_to_rgb(val1, val2, hue):
+ if hue < 0:
+ hue += 6.0
+ if hue > 6:
+ hue -= 6.0
+ if hue < 1:
+ return val1 + (val2 - val1) * hue
+ if hue < 3:
+ return val2
+ if hue < 4:
+ return val1 + (val2 - val1) * (4 - hue)
+ return val1
diff --git a/share/extensions/inkex/command.py b/share/extensions/inkex/command.py
new file mode 100644
index 0000000..8f9abbc
--- /dev/null
+++ b/share/extensions/inkex/command.py
@@ -0,0 +1,309 @@
+# coding=utf-8
+#
+# Copyright (C) 2019 Martin Owens
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA.
+#
+"""
+This API provides methods for calling Inkscape to execute a given
+Inkscape command. This may be needed for various compiling options
+(e.g., png), running other extensions or performing other options only
+available via the shell API.
+
+Best practice is to avoid using this API except when absolutely necessary,
+since it is resource-intensive to invoke a new Inkscape instance.
+
+However, in any circumstance when it is necessary to call Inkscape, it
+is strongly recommended that you do so through this API, rather than calling
+it yourself, to take advantage of the security settings and testing functions.
+
+"""
+
+import os
+import sys
+from shutil import which as warlock
+
+from subprocess import Popen, PIPE
+from tempfile import TemporaryDirectory
+from typing import List
+from lxml.etree import ElementTree
+
+from .elements import SvgDocumentElement
+
+INKSCAPE_EXECUTABLE_NAME = os.environ.get("INKSCAPE_COMMAND")
+if INKSCAPE_EXECUTABLE_NAME is None:
+ if sys.platform == "win32":
+ # prefer inkscape.exe over inkscape.com which spawns a command window
+ INKSCAPE_EXECUTABLE_NAME = "inkscape.exe"
+ else:
+ INKSCAPE_EXECUTABLE_NAME = "inkscape"
+
+
+class CommandNotFound(IOError):
+ """Command is not found"""
+
+
+class ProgramRunError(ValueError):
+ """A specialized ValueError that is raised when a call to an external command fails.
+ It stores additional information about a failed call to an external program.
+
+ If only the ``program`` parameter is given, it is interpreted as the error message.
+ Otherwise, the error message is compiled from all constructor parameters."""
+
+ program: str
+ """The absolute path to the called executable"""
+
+ returncode: int
+ """Return code of the program call"""
+
+ stderr: str
+ """stderr stream output of the call"""
+
+ stdout: str
+ """stdout stream output of the call"""
+
+ arguments: List
+ """Arguments of the call"""
+
+ def __init__(self, program, returncode=None, stderr=None, stdout=None, args=None):
+ self.program = program
+ self.returncode = returncode
+ self.stderr = stderr
+ self.stdout = stdout
+ self.arguments = args
+ super().__init__(str(self))
+
+ def __str__(self):
+ if self.returncode is None:
+ return self.program
+ return (
+ f"Return Code: {self.returncode}: {self.stderr}\n{self.stdout}"
+ f"\nargs: {self.args}"
+ )
+
+
+def which(program):
+ """
+ Attempt different methods of trying to find if the program exists.
+ """
+ if os.path.isabs(program) and os.path.isfile(program):
+ return program
+ # On Windows, shutil.which may give preference to .py files in the current directory
+ # (such as pdflatex.py), e.g. if .PY is in pathext, because the current directory is
+ # prepended to PATH. This can be suppressed by explicitly appending the current
+ # directory.
+
+ try:
+ if sys.platform == "win32":
+ prog = warlock(program, path=os.environ["PATH"] + ";" + os.curdir)
+ if prog:
+ return prog
+ except ImportError:
+ pass
+
+ try:
+ # Python3 only version of which
+ prog = warlock(program)
+ if prog:
+ return prog
+ except ImportError:
+ pass # python2
+
+ # There may be other methods for doing a `which` command for other
+ # operating systems; These should go here as they are discovered.
+
+ raise CommandNotFound(f"Can not find the command: '{program}'")
+
+
+def write_svg(svg, *filename):
+ """Writes an svg to the given filename"""
+ filename = os.path.join(*filename)
+ if os.path.isfile(filename):
+ return filename
+ with open(filename, "wb") as fhl:
+ if isinstance(svg, SvgDocumentElement):
+ svg = ElementTree(svg)
+ if hasattr(svg, "write"):
+ # XML document
+ svg.write(fhl)
+ elif isinstance(svg, bytes):
+ fhl.write(svg)
+ else:
+ raise ValueError("Not sure what type of SVG data this is.")
+ return filename
+
+
+def to_arg(arg, oldie=False):
+ """Convert a python argument to a command line argument"""
+ if isinstance(arg, (tuple, list)):
+ (arg, val) = arg
+ arg = "-" + arg
+ if len(arg) > 2 and not oldie:
+ arg = "-" + arg
+ if val is True:
+ return arg
+ if val is False:
+ return None
+ return f"{arg}={str(val)}"
+ return str(arg)
+
+
+def to_args(prog, *positionals, **arguments):
+ """Compile arguments and keyword arguments into a list of strings which Popen will
+ understand.
+
+ :param prog:
+ Program executable prepended to the output.
+ :type first: ``str``
+
+ :Arguments:
+ * (``str``) -- String added as given
+ * (``tuple``) -- Ordered version of Kwyward Arguments, see below
+
+ :Keyword Arguments:
+ * *name* (``str``) --
+ Becomes ``--name="val"``
+ * *name* (``bool``) --
+ Becomes ``--name``
+ * *name* (``list``) --
+ Becomes ``--name="val1"`` ...
+ * *n* (``str``) --
+ Becomes ``-n=val``
+ * *n* (``bool``) --
+ Becomes ``-n``
+
+ :return: Returns a list of compiled arguments ready for Popen.
+ :rtype: ``list[str]``
+ """
+ args = [prog]
+ oldie = arguments.pop("oldie", False)
+ for arg, value in arguments.items():
+ arg = arg.replace("_", "-").strip()
+
+ if isinstance(value, tuple):
+ value = list(value)
+ elif not isinstance(value, list):
+ value = [value]
+
+ for val in value:
+ args.append(to_arg((arg, val), oldie))
+
+ args += [to_arg(pos, oldie) for pos in positionals if pos is not None]
+ # Filter out empty non-arguments
+ return [arg for arg in args if arg is not None]
+
+
+def to_args_sorted(prog, *positionals, **arguments):
+ """same as :func:`to_args`, but keyword arguments are sorted beforehand
+
+ .. versionadded:: 1.2"""
+ return to_args(prog, *positionals, **dict(sorted(arguments.items())))
+
+
+def _call(program, *args, **kwargs):
+ stdin = kwargs.pop("stdin", None)
+ if isinstance(stdin, str):
+ stdin = stdin.encode("utf-8")
+ inpipe = PIPE if stdin else None
+
+ args = to_args(which(program), *args, **kwargs)
+
+ kwargs = {}
+ if sys.platform == "win32":
+ kwargs["creationflags"] = 0x08000000 # create no console window
+
+ with Popen(
+ args,
+ shell=False, # Never have shell=True
+ stdin=inpipe, # StdIn not used (yet)
+ stdout=PIPE, # Grab any output (return it)
+ stderr=PIPE, # Take all errors, just incase
+ **kwargs,
+ ) as process:
+ (stdout, stderr) = process.communicate(input=stdin)
+ if process.returncode == 0:
+ return stdout
+ raise ProgramRunError(program, process.returncode, stderr, stdout, args)
+
+
+def call(program, *args, **kwargs):
+ """
+ Generic caller to open any program and return its stdout::
+
+ stdout = call('executable', arg1, arg2, dash_dash_arg='foo', d=True, ...)
+
+ Will raise :class:`ProgramRunError` if return code is not 0.
+
+ Keyword arguments:
+ return_binary: Should stdout return raw bytes (default: False)
+
+ .. versionadded:: 1.1
+ stdin: The string or bytes containing the stdin (default: None)
+
+ All other arguments converted using :func:`to_args` function.
+ """
+ # We use this long input because it's less likely to conflict with --binary=
+ binary = kwargs.pop("return_binary", False)
+ stdout = _call(program, *args, **kwargs)
+ # Convert binary to string when we wish to have strings we do this here
+ # so the mock tests will also run the conversion (always returns bytes)
+ if not binary and isinstance(stdout, bytes):
+ return stdout.decode(sys.stdout.encoding or "utf-8")
+ return stdout
+
+
+def inkscape(svg_file, *args, **kwargs):
+ """
+ Call Inkscape with the given svg_file and the given arguments, see call()
+ """
+ return call(INKSCAPE_EXECUTABLE_NAME, svg_file, *args, **kwargs)
+
+
+def inkscape_command(svg, select=None, verbs=()):
+ """
+ Executes a list of commands, a mixture of verbs, selects etc.
+
+ inkscape_command('<svg...>', ('verb', 'VerbName'), ...)
+ """
+ with TemporaryDirectory(prefix="inkscape-command") as tmpdir:
+ svg_file = write_svg(svg, tmpdir, "input.svg")
+ select = ("select", select) if select else None
+ verbs += ("FileSave", "FileQuit")
+ inkscape(svg_file, select, batch_process=True, verb=";".join(verbs))
+ with open(svg_file, "rb") as fhl:
+ return fhl.read()
+
+
+def take_snapshot(svg, dirname, name="snapshot", ext="png", dpi=96, **kwargs):
+ """
+ Take a snapshot of the given svg file.
+
+ Resulting filename is yielded back, after generator finishes, the
+ file is deleted so you must deal with the file inside the for loop.
+ """
+ svg_file = write_svg(svg, dirname, name + ".svg")
+ ext_file = os.path.join(dirname, name + "." + str(ext).lower())
+ inkscape(
+ svg_file, export_dpi=dpi, export_filename=ext_file, export_type=ext, **kwargs
+ )
+ return ext_file
+
+
+def is_inkscape_available():
+ """Return true if the Inkscape executable is available."""
+ try:
+ return bool(which(INKSCAPE_EXECUTABLE_NAME))
+ except CommandNotFound:
+ return False
diff --git a/share/extensions/inkex/css.py b/share/extensions/inkex/css.py
new file mode 100644
index 0000000..ebb9234
--- /dev/null
+++ b/share/extensions/inkex/css.py
@@ -0,0 +1,61 @@
+# coding=utf-8
+#
+# Copyright (C) 2021 - Jonathan Neuhauser <jonathan.neuhauser@outlook.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+
+"""Toplevel CSS utils that do not depend on other inkex functionality
+
+.. versionadded:: 1.2
+ Previously a part of :py:mod:`inkex.styles`"""
+
+
+import re
+import cssselect
+
+
+class ConditionalRule:
+ """A single css rule
+
+ .. versionchanged:: 1.2
+ The CSS rule is now processed using cssselect."""
+
+ step_to_xpath = [
+ # namespace addition
+ (re.compile(r"(::|\/)([a-z]+)(?=\W)(?!-)"), r"\1svg:\2"),
+ ]
+
+ def __init__(self, rule):
+ self.rule = rule.strip()
+ self.selector = cssselect.parse(self.rule)[0]
+
+ def __str__(self):
+ return self.rule
+
+ def to_xpath(self):
+ """Attempt to convert the rule into a simplified xpath"""
+ # the space in the end is needed for the negative lookbehind in the regex, will
+ # be removed on return
+ ret = cssselect.HTMLTranslator().selector_to_xpath(self.selector) + " "
+ for matcher, replacer in self.step_to_xpath:
+ ret = matcher.sub(replacer, ret)
+ return ret.strip()
+
+ def get_specificity(self):
+ """gets the css specificity of this selector
+
+ .. versionadded:: 1.2"""
+ return self.selector.specificity()
diff --git a/share/extensions/inkex/deprecated-simple/README.rst b/share/extensions/inkex/deprecated-simple/README.rst
new file mode 100644
index 0000000..df3e2dc
--- /dev/null
+++ b/share/extensions/inkex/deprecated-simple/README.rst
@@ -0,0 +1,4 @@
+# coding=utf-8This directory contains compatibility layers for all the `simple` modules, such as `simplepath` and `simplestyle`
+
+This directory IS NOT a module path, to denote this we are using a dash in the name and there is no '__init__.py'
+
diff --git a/share/extensions/inkex/deprecated-simple/bezmisc.py b/share/extensions/inkex/deprecated-simple/bezmisc.py
new file mode 100644
index 0000000..92b63f6
--- /dev/null
+++ b/share/extensions/inkex/deprecated-simple/bezmisc.py
@@ -0,0 +1,46 @@
+# coding=utf-8
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=invalid-name,unused-argument
+"""Deprecated bezmisc API"""
+
+from inkex.deprecated import deprecate
+from inkex import bezier
+
+bezierparameterize = deprecate(bezier.bezierparameterize)
+linebezierintersect = deprecate(bezier.linebezierintersect)
+bezierpointatt = deprecate(bezier.bezierpointatt)
+bezierslopeatt = deprecate(bezier.bezierslopeatt)
+beziertatslope = deprecate(bezier.beziertatslope)
+tpoint = deprecate(bezier.tpoint)
+beziersplitatt = deprecate(bezier.beziersplitatt)
+pointdistance = deprecate(bezier.pointdistance)
+Gravesen_addifclose = deprecate(bezier.addifclose)
+balf = deprecate(bezier.balf)
+bezierlengthSimpson = deprecate(bezier.bezierlength)
+beziertatlength = deprecate(bezier.beziertatlength)
+bezierlength = bezierlengthSimpson
+
+
+@deprecate
+def Simpson(func, a, b, n_limit, tolerance):
+ """bezier.simpson(a, b, n_limit, tolerance, balf_arguments)"""
+ raise AttributeError(
+ """Because bezmisc.Simpson used global variables, it's not possible to
+ call the replacement code automatically. In fact it's unlikely you were
+ using the code or functionality you think you were since it's a highly
+ broken way of writing python."""
+ )
diff --git a/share/extensions/inkex/deprecated-simple/cspsubdiv.py b/share/extensions/inkex/deprecated-simple/cspsubdiv.py
new file mode 100644
index 0000000..91b2237
--- /dev/null
+++ b/share/extensions/inkex/deprecated-simple/cspsubdiv.py
@@ -0,0 +1,25 @@
+# coding=utf-8
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=invalid-name
+"""Deprecated cspsubdiv API"""
+
+from inkex.deprecated import deprecate
+from inkex import bezier
+
+maxdist = deprecate(bezier.maxdist)
+cspsubdiv = deprecate(bezier.cspsubdiv)
+subdiv = deprecate(bezier.subdiv)
diff --git a/share/extensions/inkex/deprecated-simple/cubicsuperpath.py b/share/extensions/inkex/deprecated-simple/cubicsuperpath.py
new file mode 100644
index 0000000..cb6f124
--- /dev/null
+++ b/share/extensions/inkex/deprecated-simple/cubicsuperpath.py
@@ -0,0 +1,52 @@
+# coding=utf-8
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=invalid-name
+"""Deprecated cubic super path API"""
+
+from inkex.deprecated import deprecate
+from inkex import paths
+
+
+@deprecate
+def ArcToPath(p1, params):
+ return paths.arc_to_path(p1, params)
+
+
+@deprecate
+def CubicSuperPath(simplepath):
+ return paths.Path(simplepath).to_superpath()
+
+
+@deprecate
+def unCubicSuperPath(csp):
+ return paths.CubicSuperPath(csp).to_path().to_arrays()
+
+
+@deprecate
+def parsePath(d):
+ return paths.CubicSuperPath(paths.Path(d))
+
+
+@deprecate
+def formatPath(p):
+ return str(paths.Path(unCubicSuperPath(p)))
+
+
+matprod = deprecate(paths.matprod)
+rotmat = deprecate(paths.rotmat)
+applymat = deprecate(paths.applymat)
+norm = deprecate(paths.norm)
diff --git a/share/extensions/inkex/deprecated-simple/ffgeom.py b/share/extensions/inkex/deprecated-simple/ffgeom.py
new file mode 100644
index 0000000..2feb3bd
--- /dev/null
+++ b/share/extensions/inkex/deprecated-simple/ffgeom.py
@@ -0,0 +1,92 @@
+# coding=utf-8
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=invalid-name,missing-docstring
+"""Deprecated ffgeom API"""
+
+from collections import namedtuple
+
+from inkex.deprecated import deprecate
+from inkex.transforms import DirectedLineSegment as NewSeg
+
+try:
+ NaN = float("NaN")
+except ValueError:
+ PosInf = 1e300000
+ NaN = PosInf / PosInf
+
+
+class Point(namedtuple("Point", "x y")):
+ __slots__ = ()
+
+ def __getitem__(self, key):
+ if isinstance(key, str):
+ key = "xy".index(key)
+ return super(Point, self).__getitem__(key)
+
+
+class Segment(NewSeg):
+ @deprecate
+ def __init__(self, e0, e1):
+ """inkex.transforms.Segment(((x1, y1), (x2, y2)))"""
+ if isinstance(e0, dict):
+ e0 = (e0["x"], e0["y"])
+ if isinstance(e1, dict):
+ e1 = (e1["x"], e1["y"])
+ super(Segment, self).__init__((e0, e1))
+
+ def __getitem__(self, key):
+ if key:
+ return {"x": self.x.maximum, "y": self.y.maximum}
+ return {"x": self.x.minimum, "y": self.y.minimum}
+
+ delta_x = lambda self: self.width
+ delta_y = lambda self: self.height
+ run = delta_x
+ rise = delta_y
+
+ def distanceToPoint(self, p):
+ return self.distance_to_point(p["x"], p["y"])
+
+ def perpDistanceToPoint(self, p):
+ return self.perp_distance(p["x"], p["y"])
+
+ def angle(self):
+ return super(Segment, self).angle
+
+ def length(self):
+ return super(Segment, self).length
+
+ def pointAtLength(self, length):
+ return self.point_at_length(length)
+
+ def pointAtRatio(self, ratio):
+ return self.point_at_ratio(ratio)
+
+ def createParallel(self, p):
+ self.parallel(p["x"], p["y"])
+
+
+@deprecate
+def intersectSegments(s1, s2):
+ """transforms.Segment(s1).intersect(s2)"""
+ return Point(*s1.intersect(s2))
+
+
+@deprecate
+def dot(s1, s2):
+ """transforms.Segment(s1).dot(s2)"""
+ return s1.dot(s2)
diff --git a/share/extensions/inkex/deprecated-simple/run_command.py b/share/extensions/inkex/deprecated-simple/run_command.py
new file mode 100755
index 0000000..84f4a4b
--- /dev/null
+++ b/share/extensions/inkex/deprecated-simple/run_command.py
@@ -0,0 +1,79 @@
+# coding=utf-8
+#
+# Copyright (C) 2008 Stephen Silver
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
+#
+"""
+Deprecated module for running SVG-generating commands in Inkscape extensions
+"""
+import os
+import sys
+import tempfile
+from subprocess import Popen, PIPE
+
+from inkex.deprecated import deprecate
+
+
+def run(command_format, prog_name):
+ """inkex.commands.call(...)"""
+ svgfile = tempfile.mktemp(".svg")
+ command = command_format % svgfile
+ msg = None
+ # ps2pdf may attempt to write to the current directory, which may not
+ # be writeable, so we switch to the temp directory first.
+ try:
+ os.chdir(tempfile.gettempdir())
+ except IOError:
+ pass
+
+ try:
+ proc = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
+ return_code = proc.wait()
+ out = proc.stdout.read()
+ err = proc.stderr.read()
+
+ if msg is None:
+ if return_code:
+ msg = "{} failed:\n{}\n{}\n".format(prog_name, out, err)
+ elif err:
+ sys.stderr.write(
+ "{} executed but logged the following error:\n{}\n{}\n".format(
+ prog_name, out, err
+ )
+ )
+ except Exception as inst:
+ msg = "Error attempting to run {}: {}".format(prog_name, str(inst))
+
+ # If successful, copy the output file to stdout.
+ if msg is None:
+ if os.name == "nt": # make stdout work in binary on Windows
+ import msvcrt
+
+ msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
+ try:
+ with open(svgfile, "rb") as fhl:
+ sys.stdout.write(fhl.read().decode(sys.stdout.encoding))
+ except IOError as inst:
+ msg = "Error reading temporary file: {}".format(str(inst))
+
+ try:
+ # Clean up.
+ os.remove(svgfile)
+ except (IOError, OSError):
+ pass
+
+ # Output error message (if any) and exit.
+ return msg
diff --git a/share/extensions/inkex/deprecated-simple/simplepath.py b/share/extensions/inkex/deprecated-simple/simplepath.py
new file mode 100644
index 0000000..6eaaf3b
--- /dev/null
+++ b/share/extensions/inkex/deprecated-simple/simplepath.py
@@ -0,0 +1,68 @@
+# coding=utf-8
+# COPYRIGHT
+#
+# pylint: disable=invalid-name
+#
+"""
+Depreicated simplepath replacements with documentation
+"""
+
+import math
+from inkex.deprecated import deprecate, DeprecatedDict
+from inkex.transforms import Transform
+from inkex.paths import Path
+
+pathdefs = DeprecatedDict(
+ {
+ "M": ["L", 2, [float, float], ["x", "y"]],
+ "L": ["L", 2, [float, float], ["x", "y"]],
+ "H": ["H", 1, [float], ["x"]],
+ "V": ["V", 1, [float], ["y"]],
+ "C": [
+ "C",
+ 6,
+ [float, float, float, float, float, float],
+ ["x", "y", "x", "y", "x", "y"],
+ ],
+ "S": ["S", 4, [float, float, float, float], ["x", "y", "x", "y"]],
+ "Q": ["Q", 4, [float, float, float, float], ["x", "y", "x", "y"]],
+ "T": ["T", 2, [float, float], ["x", "y"]],
+ "A": [
+ "A",
+ 7,
+ [float, float, float, int, int, float, float],
+ ["r", "r", "a", 0, "s", "x", "y"],
+ ],
+ "Z": ["L", 0, [], []],
+ }
+)
+
+
+@deprecate
+def parsePath(d):
+ """element.path.to_arrays()"""
+ return Path(d).to_arrays()
+
+
+@deprecate
+def formatPath(a):
+ """str(element.path) or str(Path(array))"""
+ return str(Path(a))
+
+
+@deprecate
+def translatePath(p, x, y):
+ """Path(array).translate(x, y)"""
+ p[:] = Path(p).translate(x, y).to_arrays()
+
+
+@deprecate
+def scalePath(p, x, y):
+ """Path(array).scale(x, y)"""
+ p[:] = Path(p).scale(x, y).to_arrays()
+
+
+@deprecate
+def rotatePath(p, a, cx=0, cy=0):
+ """Path(array).rotate(angle_degrees, (center_x, center_y))"""
+ p[:] = Path(p).rotate(math.degrees(a), (cx, cy)).to_arrays()
diff --git a/share/extensions/inkex/deprecated-simple/simplestyle.py b/share/extensions/inkex/deprecated-simple/simplestyle.py
new file mode 100644
index 0000000..cab6d9d
--- /dev/null
+++ b/share/extensions/inkex/deprecated-simple/simplestyle.py
@@ -0,0 +1,55 @@
+# coding=utf-8
+# COPYRIGHT
+"""DOCSTRING"""
+
+import inkex
+from inkex.colors import SVG_COLOR as svgcolors
+from inkex.deprecated import deprecate
+
+
+@deprecate
+def parseStyle(s):
+ """dict(inkex.Style.parse_str(s))"""
+ return dict(inkex.Style.parse_str(s))
+
+
+@deprecate
+def formatStyle(a):
+ """str(inkex.Style(a))"""
+ return str(inkex.Style(a))
+
+
+@deprecate
+def isColor(c):
+ """inkex.colors.is_color(c)"""
+ return inkex.colors.is_color(c)
+
+
+@deprecate
+def parseColor(c):
+ """inkex.Color(c).to_rgb()"""
+ return tuple(inkex.Color(c).to_rgb())
+
+
+@deprecate
+def formatColoria(a):
+ """str(inkex.Color(a))"""
+ return str(inkex.Color(a))
+
+
+@deprecate
+def formatColorfa(a):
+ """str(inkex.Color(a))"""
+ return str(inkex.Color(a))
+
+
+@deprecate
+def formatColor3i(r, g, b):
+ """str(inkex.Color((r, g, b)))"""
+ return str(inkex.Color((r, g, b)))
+
+
+@deprecate
+def formatColor3f(r, g, b):
+ """str(inkex.Color((r, g, b)))"""
+ return str(inkex.Color((r, g, b)))
diff --git a/share/extensions/inkex/deprecated-simple/simpletransform.py b/share/extensions/inkex/deprecated-simple/simpletransform.py
new file mode 100644
index 0000000..f408cd0
--- /dev/null
+++ b/share/extensions/inkex/deprecated-simple/simpletransform.py
@@ -0,0 +1,122 @@
+# coding=utf-8
+#
+# pylint: disable=invalid-name
+#
+"""
+Depreicated simpletransform replacements with documentation
+"""
+
+import warnings
+
+from inkex.deprecated import deprecate
+from inkex.transforms import Transform, BoundingBox, cubic_extrema
+from inkex.paths import Path
+
+import inkex, cubicsuperpath
+
+
+def _lists(mat):
+ return [list(row) for row in mat]
+
+
+@deprecate
+def parseTransform(transf, mat=None):
+ """Transform(str).matrix"""
+ t = Transform(transf)
+ if mat is not None:
+ t = Transform(mat) @ t
+ return _lists(t.matrix)
+
+
+@deprecate
+def formatTransform(mat):
+ """str(Transform(mat))"""
+ if len(mat) == 3:
+ warnings.warn("3x3 matrices not suported")
+ mat = mat[:2]
+ return str(Transform(mat))
+
+
+@deprecate
+def invertTransform(mat):
+ """-Transform(mat)"""
+ return _lists((-Transform(mat)).matrix)
+
+
+@deprecate
+def composeTransform(mat1, mat2):
+ """Transform(M1) * Transform(M2)"""
+ return _lists((Transform(mat1) @ Transform(mat2)).matrix)
+
+
+@deprecate
+def composeParents(node, mat):
+ """elem.composed_transform() or elem.transform * Transform(mat)"""
+ return (node.transform @ Transform(mat)).matrix
+
+
+@deprecate
+def applyTransformToNode(mat, node):
+ """elem.transform = Transform(mat) * elem.transform"""
+ node.transform = Transform(mat) @ node.transform
+
+
+@deprecate
+def applyTransformToPoint(mat, pt):
+ """Transform(mat).apply_to_point(pt)"""
+ pt2 = Transform(mat).apply_to_point(pt)
+ # Apply in place as original method was modifying arrays in place.
+ # but don't do this in your code! This is not good code design.
+ pt[0] = pt2[0]
+ pt[1] = pt2[1]
+
+
+@deprecate
+def applyTransformToPath(mat, path):
+ """Path(path).transform(mat)"""
+ return Path(path).transform(Transform(mat)).to_arrays()
+
+
+@deprecate
+def fuseTransform(node):
+ """node.apply_transform()"""
+ return node.apply_transform()
+
+
+@deprecate
+def boxunion(b1, b2):
+ """list(BoundingBox(b1) + BoundingBox(b2))"""
+ bbox = BoundingBox(b1[:2], b1[2:]) + BoundingBox(b2[:2], b2[2:])
+ return bbox.x.minimum, bbox.x.maximum, bbox.y.minimum, bbox.y.maximum
+
+
+@deprecate
+def roughBBox(path):
+ """list(Path(path)).bounding_box())"""
+ bbox = Path(path).bounding_box()
+ return bbox.x.minimum, bbox.x.maximum, bbox.y.minimum, bbox.y.maximum
+
+
+@deprecate
+def refinedBBox(path):
+ """list(Path(path)).bounding_box())"""
+ bbox = Path(path).bounding_box()
+ return bbox.x.minimum, bbox.x.maximum, bbox.y.minimum, bbox.y.maximum
+
+
+@deprecate
+def cubicExtrema(y0, y1, y2, y3):
+ """from inkex.transforms import cubic_extrema"""
+ return cubic_extrema(y0, y1, y2, y3)
+
+
+@deprecate
+def computeBBox(aList, mat=[[1, 0, 0], [0, 1, 0]]):
+ """sum([node.bounding_box() for node in aList])"""
+ return sum([node.bounding_box() for node in aList], None)
+
+
+@deprecate
+def computePointInNode(pt, node, mat=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]):
+ """(-Transform(node.transform * mat)).apply_to_point(pt)"""
+ return (-Transform(node.transform * mat)).apply_to_point(pt)
diff --git a/share/extensions/inkex/deprecated/__init__.py b/share/extensions/inkex/deprecated/__init__.py
new file mode 100644
index 0000000..180a1c2
--- /dev/null
+++ b/share/extensions/inkex/deprecated/__init__.py
@@ -0,0 +1,3 @@
+from .main import *
+from .meta import deprecate, _deprecated
+from .deprecatedeffect import DeprecatedEffect, Effect
diff --git a/share/extensions/inkex/deprecated/deprecatedeffect.py b/share/extensions/inkex/deprecated/deprecatedeffect.py
new file mode 100644
index 0000000..ee13670
--- /dev/null
+++ b/share/extensions/inkex/deprecated/deprecatedeffect.py
@@ -0,0 +1,313 @@
+# coding=utf-8
+#
+# Copyright (C) 2018 - Martin Owens <doctormo@mgail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Deprecation functionality for the pre-1.0 Inkex main effect class.
+"""
+#
+# We ignore a lot of pylint warnings here:
+#
+# pylint: disable=invalid-name,unused-argument,missing-docstring,too-many-public-methods
+#
+
+import sys
+import argparse
+from argparse import ArgumentParser
+
+from .. import utils
+from .. import base
+from ..base import SvgThroughMixin, InkscapeExtension
+from ..localization import inkex_gettext as _
+from .meta import _deprecated
+
+
+class DeprecatedEffect:
+ """An Inkscape effect, takes SVG in and outputs SVG, providing a deprecated layer"""
+
+ options = argparse.Namespace()
+
+ def __init__(self):
+ super().__init__()
+ self._doc_ids = None
+ self._args = None
+
+ # These are things we reference in the deprecated code, they are provided
+ # by the new effects code, but we want to keep this as a Mixin so these
+ # items will keep pylint happy and let use check our code as we write.
+ if not hasattr(self, "svg"):
+ from ..elements import SvgDocumentElement
+
+ self.svg = SvgDocumentElement()
+ if not hasattr(self, "arg_parser"):
+ self.arg_parser = ArgumentParser()
+ if not hasattr(self, "run"):
+ self.run = self.affect
+
+ @classmethod
+ def _deprecated(
+ cls, name, msg=_("{} is deprecated and should be removed"), stack=3
+ ):
+ """Give the user a warning about their extension using a deprecated API"""
+ _deprecated(
+ msg.format("Effect." + name, cls=cls.__module__ + "." + cls.__name__),
+ stack=stack,
+ )
+
+ @property
+ def OptionParser(self):
+ self._deprecated(
+ "OptionParser",
+ _(
+ "{} or `optparse` has been deprecated and replaced with `argparser`. "
+ "You must change `self.OptionParser.add_option` to "
+ "`self.arg_parser.add_argument`; the arguments are similar."
+ ),
+ )
+ return self
+
+ def add_option(self, *args, **kw):
+ # Convert type string into type method as needed
+ if "type" in kw:
+ kw["type"] = {
+ "string": str,
+ "int": int,
+ "float": float,
+ "inkbool": utils.Boolean,
+ }.get(kw["type"])
+ if kw.get("action", None) == "store":
+ # Default store action not required, removed.
+ kw.pop("action")
+ args = [arg for arg in args if arg != ""]
+ self.arg_parser.add_argument(*args, **kw)
+
+ def effect(self):
+ self._deprecated(
+ "effect",
+ _(
+ "{} method is now a required method. It should "
+ "be created on {cls}, even if it does nothing."
+ ),
+ )
+
+ @property
+ def current_layer(self):
+ self._deprecated(
+ "current_layer",
+ _(
+ "{} is now a method in the SvgDocumentElement class. "
+ "Use `self.svg.get_current_layer()` instead."
+ ),
+ )
+ return self.svg.get_current_layer()
+
+ @property
+ def view_center(self):
+ self._deprecated(
+ "view_center",
+ _(
+ "{} is now a method in the SvgDocumentElement class. "
+ "Use `self.svg.get_center_position()` instead."
+ ),
+ )
+ return self.svg.namedview.center
+
+ @property
+ def selected(self):
+ self._deprecated(
+ "selected",
+ _(
+ "{} is now a dict in the SvgDocumentElement class. "
+ "Use `self.svg.selected`."
+ ),
+ )
+ return {elem.get("id"): elem for elem in self.svg.selected}
+
+ @property
+ def doc_ids(self):
+ self._deprecated(
+ "doc_ids",
+ _(
+ "{} is now a method in the SvgDocumentElement class. "
+ "Use `self.svg.get_ids()` instead."
+ ),
+ )
+ if self._doc_ids is None:
+ self._doc_ids = dict.fromkeys(self.svg.get_ids())
+ return self._doc_ids
+
+ def getdocids(self):
+ self._deprecated(
+ "getdocids", _("Use `self.svg.get_ids()` instead of {} and `doc_ids`.")
+ )
+ self._doc_ids = None
+ self.svg.ids.clear()
+
+ def getselected(self):
+ self._deprecated("getselected", _("{} has been removed"))
+
+ def getElementById(self, eid):
+ self._deprecated(
+ "getElementById",
+ _(
+ "{} is now a method in the SvgDocumentElement class. "
+ "Use `self.svg.getElementById(eid)` instead."
+ ),
+ )
+ return self.svg.getElementById(eid)
+
+ def xpathSingle(self, xpath):
+ self._deprecated(
+ "xpathSingle",
+ _(
+ "{} is now a new method in the SvgDocumentElement class. "
+ "Use `self.svg.getElement(path)` instead."
+ ),
+ )
+ return self.svg.getElement(xpath)
+
+ def getParentNode(self, node):
+ self._deprecated(
+ "getParentNode",
+ _("{} is no longer in use. Use the lxml `.getparent()` method instead."),
+ )
+ return node.getparent()
+
+ def getNamedView(self):
+ self._deprecated(
+ "getNamedView",
+ _(
+ "{} is now a property of the SvgDocumentElement class. "
+ "Use `self.svg.namedview` to access this element."
+ ),
+ )
+ return self.svg.namedview
+
+ def createGuide(self, posX, posY, angle):
+ from ..elements import Guide
+
+ self._deprecated(
+ "createGuide",
+ _(
+ "{} is now a method of the namedview element object. "
+ "Use `self.svg.namedview.add(Guide().move_to(x, y, a))` instead."
+ ),
+ )
+ return self.svg.namedview.add(Guide().move_to(posX, posY, angle))
+
+ def affect(
+ self, args=sys.argv[1:], output=True
+ ): # pylint: disable=dangerous-default-value
+ # We need a list as the default value to preserve backwards compatibility
+ self._deprecated(
+ "affect", _("{} is now `Effect.run()`. The `output` argument has changed.")
+ )
+ self._args = args[-1:]
+ return self.run(args=args)
+
+ @property
+ def args(self):
+ self._deprecated("args", _("self.args[-1] is now self.options.input_file."))
+ return self._args
+
+ @property
+ def svg_file(self):
+ self._deprecated("svg_file", _("self.svg_file is now self.options.input_file."))
+ return self.options.input_file
+
+ def save_raw(self, ret):
+ # Derived class may implement "output()"
+ # Attention: 'cubify.py' implements __getattr__ -> hasattr(self, 'output')
+ # returns True
+ if hasattr(self.__class__, "output"):
+ self._deprecated("output", "Use `save()` or `save_raw()` instead.", stack=5)
+ return getattr(self, "output")()
+ return base.InkscapeExtension.save_raw(self, ret)
+
+ def uniqueId(self, old_id, make_new_id=True):
+ self._deprecated(
+ "uniqueId",
+ _(
+ "{} is now a method in the SvgDocumentElement class. "
+ " Use `self.svg.get_unique_id(old_id)` instead."
+ ),
+ )
+ return self.svg.get_unique_id(old_id)
+
+ def getDocumentWidth(self):
+ self._deprecated(
+ "getDocumentWidth",
+ _(
+ "{} is now a property of the SvgDocumentElement class. "
+ "Use `self.svg.width` instead."
+ ),
+ )
+ return self.svg.get("width")
+
+ def getDocumentHeight(self):
+ self._deprecated(
+ "getDocumentHeight",
+ _(
+ "{} is now a property of the SvgDocumentElement class. "
+ "Use `self.svg.height` instead."
+ ),
+ )
+ return self.svg.get("height")
+
+ def getDocumentUnit(self):
+ self._deprecated(
+ "getDocumentUnit",
+ _(
+ "{} is now a property of the SvgDocumentElement class. "
+ "Use `self.svg.unit` instead."
+ ),
+ )
+ return self.svg.unit
+
+ def unittouu(self, string):
+ self._deprecated(
+ "unittouu",
+ _(
+ "{} is now a method in the SvgDocumentElement class. "
+ "Use `self.svg.unittouu(str)` instead."
+ ),
+ )
+ return self.svg.unittouu(string)
+
+ def uutounit(self, val, unit):
+ self._deprecated(
+ "uutounit",
+ _(
+ "{} is now a method in the SvgDocumentElement class. "
+ "Use `self.svg.uutounit(value, unit)` instead."
+ ),
+ )
+ return self.svg.uutounit(val, unit)
+
+ def addDocumentUnit(self, value):
+ self._deprecated(
+ "addDocumentUnit",
+ _(
+ "{} is now a method in the SvgDocumentElement class. "
+ "Use `self.svg.add_unit(value)` instead."
+ ),
+ )
+ return self.svg.add_unit(value)
+
+
+class Effect(SvgThroughMixin, DeprecatedEffect, InkscapeExtension):
+ """An Inkscape effect, takes SVG in and outputs SVG"""
diff --git a/share/extensions/inkex/deprecated/main.py b/share/extensions/inkex/deprecated/main.py
new file mode 100644
index 0000000..a747bda
--- /dev/null
+++ b/share/extensions/inkex/deprecated/main.py
@@ -0,0 +1,178 @@
+# coding=utf-8
+#
+# Copyright (C) 2018 - Martin Owens <doctormo@mgail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Provide some documentation to existing extensions about why they're failing.
+"""
+#
+# We ignore a lot of pylint warnings here:
+#
+# pylint: disable=invalid-name,unused-argument,missing-docstring,too-many-public-methods
+#
+
+import os
+import sys
+import warnings
+import argparse
+
+from ..transforms import Transform
+from .. import utils
+from .. import units
+from ..elements._base import BaseElement, ShapeElement
+from ..elements._selected import ElementList
+from .meta import deprecate, _deprecated
+
+warnings.simplefilter("default")
+# To load each of the deprecated sub-modules (the ones without a namespace)
+# we will add the directory to our pythonpath so older scripts can find them
+
+INKEX_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
+SIMPLE_DIR = os.path.join(INKEX_DIR, "deprecated-simple")
+
+if os.path.isdir(SIMPLE_DIR):
+ sys.path.append(SIMPLE_DIR)
+
+
+class DeprecatedDict(dict):
+ @deprecate
+ def __getitem__(self, key):
+ return super().__getitem__(key)
+
+ @deprecate
+ def __iter__(self):
+ return super().__iter__()
+
+
+# legacy inkex members
+
+
+class lazyproxy:
+ """Proxy, use as decorator on a function with provides the wrapped object.
+ The decorated function is called when a member is accessed on the proxy.
+ """
+
+ def __init__(self, getwrapped):
+ """
+ :param getwrapped: Callable which returns the wrapped object
+ """
+ self._getwrapped = getwrapped
+
+ def __getattr__(self, name):
+ return getattr(self._getwrapped(), name)
+
+ def __call__(self, *args, **kwargs):
+ return self._getwrapped()(*args, **kwargs)
+
+
+@lazyproxy
+def localize():
+ _deprecated("inkex.localize was moved to inkex.localization.localize.", stack=3)
+ from ..localization import localize as wrapped
+
+ return wrapped
+
+
+def are_near_relative(a, b, eps):
+ _deprecated(
+ "inkex.are_near_relative was moved to " "inkex.units.are_near_relative", stack=2
+ )
+ return units.are_near_relative(a, b, eps)
+
+
+def debug(what):
+ _deprecated("inkex.debug was moved to inkex.utils.debug.", stack=2)
+ return utils.debug(what)
+
+
+# legacy inkex members <= 0.48.x
+
+
+def unittouu(string):
+ _deprecated(
+ "inkex.unittouu is now a method in the SvgDocumentElement class. "
+ "Use `self.svg.unittouu(str)` instead.",
+ stack=2,
+ )
+ return units.convert_unit(string, "px")
+
+
+# optparse.Values.ensure_value
+
+
+def ensure_value(self, attr, value):
+ _deprecated("Effect().options.ensure_value was removed.", stack=2)
+ if getattr(self, attr, None) is None:
+ setattr(self, attr, value)
+ return getattr(self, attr)
+
+
+argparse.Namespace.ensure_value = ensure_value # type: ignore
+
+
+@deprecate
+def zSort(inNode, idList):
+ """self.svg.get_z_selected()"""
+ sortedList = []
+ theid = inNode.get("id")
+ if theid in idList:
+ sortedList.append(theid)
+ for child in inNode:
+ if len(sortedList) == len(idList):
+ break
+ sortedList += zSort(child, idList)
+ return sortedList
+
+
+# This can't be handled as a mixin class because of circular importing.
+def description(self, value):
+ """Use elem.desc = value"""
+ self.desc = value
+
+
+BaseElement.description = deprecate(description, "1.1")
+
+
+def composed_style(element: ShapeElement):
+ """Calculate the final styles applied to this element
+ This function has been deprecated in favor of BaseElement.specified_style()"""
+ return element.specified_style()
+
+
+ShapeElement.composed_style = deprecate(composed_style, "1.2")
+
+
+def paint_order(selection: ElementList):
+ """Use :func:`rendering_order`"""
+ return selection.rendering_order()
+
+
+ElementList.paint_order = deprecate(paint_order, "1.2") # type: ignore
+
+
+def transform_imul(self, matrix):
+ """Use @= operator instead"""
+ return self.__imatmul__(matrix)
+
+
+def transform_mul(self, matrix):
+ """Use @ operator instead"""
+ return self.__matmul__(matrix)
+
+
+Transform.__imul__ = deprecate(transform_imul, "1.2") # type: ignore
+Transform.__mul__ = deprecate(transform_mul, "1.2") # type: ignore
diff --git a/share/extensions/inkex/deprecated/meta.py b/share/extensions/inkex/deprecated/meta.py
new file mode 100644
index 0000000..cebd93c
--- /dev/null
+++ b/share/extensions/inkex/deprecated/meta.py
@@ -0,0 +1,109 @@
+# coding=utf-8
+#
+# Copyright (C) 2018 - Martin Owens <doctormo@gmail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Deprecation functionality which does not require imports from Inkex.
+"""
+
+import os
+import traceback
+import warnings
+from typing import Optional
+
+try:
+ DEPRECATION_LEVEL = int(os.environ.get("INKEX_DEPRECATION_LEVEL", 1))
+except ValueError:
+ DEPRECATION_LEVEL = 1
+
+
+def _deprecated(msg, stack=2, level=DEPRECATION_LEVEL):
+ """Internal method for raising a deprecation warning"""
+ if level > 1:
+ msg += " ; ".join(traceback.format_stack())
+ if level:
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=stack + 1)
+
+
+def deprecate(func, version: Optional[str] = None):
+ r"""Function decorator for deprecation functions which have a one-liner
+ equivalent in the new API. The one-liner has to passed as a string
+ to the decorator.
+
+ >>> @deprecate
+ >>> def someOldFunction(*args):
+ >>> '''Example replacement code someNewFunction('foo', ...)'''
+ >>> someNewFunction('foo', *args)
+
+ Or if the args API is the same:
+
+ >>> someOldFunction = deprecate(someNewFunction)
+
+ """
+
+ def _inner(*args, **kwargs):
+ _deprecated(f"{func.__module__}.{func.__name__} -> {func.__doc__}", stack=2)
+ return func(*args, **kwargs)
+
+ _inner.__name__ = func.__name__
+ if func.__doc__:
+ if version is None:
+ _inner.__doc__ = "Deprecated -> " + func.__doc__
+ else:
+ _inner.__doc__ = f"""{func.__doc__}\n\n.. deprecated:: {version}\n"""
+ return _inner
+
+
+class DeprecatedSvgMixin:
+ """Mixin which adds deprecated API elements to the SvgDocumentElement"""
+
+ @property
+ def selected(self):
+ """svg.selection"""
+ return self.selection
+
+ @deprecate
+ def set_selected(self, *ids):
+ r"""svg.selection.set(\*ids)"""
+ return self.selection.set(*ids)
+
+ @deprecate
+ def get_z_selected(self):
+ """svg.selection.rendering_order()"""
+ return self.selection.rendering_order()
+
+ @deprecate
+ def get_selected(self, *types):
+ r"""svg.selection.filter(\*types).values()"""
+ return self.selection.filter(*types).values()
+
+ @deprecate
+ def get_selected_or_all(self, *types):
+ """Set select_all = True in extension class"""
+ if not self.selection:
+ self.selection.set_all()
+ return self.selection.filter(*types)
+
+ @deprecate
+ def get_selected_bbox(self):
+ """selection.bounding_box()"""
+ return self.selection.bounding_box()
+
+ @deprecate
+ def get_first_selected(self, *types):
+ r"""selection.filter(\*types).first() or [0] if you'd like an error"""
+ return self.selection.filter(*types).first()
diff --git a/share/extensions/inkex/elements/__init__.py b/share/extensions/inkex/elements/__init__.py
new file mode 100644
index 0000000..021d47b
--- /dev/null
+++ b/share/extensions/inkex/elements/__init__.py
@@ -0,0 +1,55 @@
+"""
+Element based interface provides the bulk of features that allow you to
+interact directly with the SVG xml interface.
+
+See the documentation for each of the elements for details on how it works.
+"""
+
+from ._utils import addNS, NSS
+from ._parser import SVG_PARSER, load_svg
+from ._base import ShapeElement, BaseElement
+from ._svg import SvgDocumentElement
+from ._groups import Group, Layer, Anchor, Marker, ClipPath, Mask
+from ._polygons import PathElement, Polyline, Polygon, Line, Rectangle, Circle, Ellipse
+from ._text import (
+ FlowRegion,
+ FlowRoot,
+ FlowPara,
+ FlowDiv,
+ FlowSpan,
+ TextElement,
+ TextPath,
+ Tspan,
+ SVGfont,
+ FontFace,
+ Glyph,
+ MissingGlyph,
+)
+from ._use import Symbol, Use
+from ._meta import (
+ Defs,
+ StyleElement,
+ Script,
+ Desc,
+ Title,
+ NamedView,
+ Guide,
+ Metadata,
+ ForeignObject,
+ Switch,
+ Grid,
+ Page,
+)
+from ._filters import (
+ Filter,
+ Pattern,
+ Gradient,
+ LinearGradient,
+ RadialGradient,
+ PathEffect,
+ Stop,
+ MeshGradient,
+ MeshRow,
+ MeshPatch,
+)
+from ._image import Image
diff --git a/share/extensions/inkex/elements/_base.py b/share/extensions/inkex/elements/_base.py
new file mode 100644
index 0000000..492278e
--- /dev/null
+++ b/share/extensions/inkex/elements/_base.py
@@ -0,0 +1,755 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2020 Martin Owens <doctormo@gmail.com>
+# Sergei Izmailov <sergei.a.izmailov@gmail.com>
+# Thomas Holder <thomas.holder@schrodinger.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=arguments-differ
+"""
+Provide extra utility to each svg element type specific to its type.
+
+This is useful for having a common interface for each element which can
+give path, transform, and property access easily.
+"""
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import Any, Tuple, Optional, overload, TypeVar, List
+from lxml import etree
+
+from ..interfaces.IElement import IBaseElement, ISVGDocumentElement
+
+from ..base import SvgOutputMixin
+from ..paths import Path
+from ..styles import Style, Classes
+from ..transforms import Transform, BoundingBox
+from ..utils import FragmentError
+from ..units import convert_unit, render_unit, parse_unit
+from ._utils import ChildToProperty, NSS, addNS, removeNS, splitNS
+from ..properties import BaseStyleValue, all_properties
+from ._selected import ElementList
+from ._parser import NodeBasedLookup, SVG_PARSER
+
+T = TypeVar("T", bound="BaseElement") # pylint: disable=invalid-name
+
+
+class BaseElement(IBaseElement):
+ """Provide automatic namespaces to all calls"""
+
+ # pylint: disable=too-many-public-methods
+
+ def __init_subclass__(cls):
+ if cls.tag_name:
+ NodeBasedLookup.register_class(cls)
+
+ @classmethod
+ def is_class_element( # pylint: disable=unused-argument
+ cls, elem: etree.Element
+ ) -> bool:
+ """Hook to do more restrictive check in addition to (ns,tag) match
+
+ .. versionadded:: 1.2
+ The function has been made public."""
+ return True
+
+ tag_name = ""
+
+ @property
+ def TAG(self): # pylint: disable=invalid-name
+ """Return the tag_name without NS"""
+ if not self.tag_name:
+ return removeNS(super().tag)[-1]
+ return removeNS(self.tag_name)[-1]
+
+ @classmethod
+ def new(cls, *children, **attrs):
+ """Create a new element, converting attrs values to strings."""
+ obj = cls(*children)
+ obj.update(**attrs)
+ return obj
+
+ NAMESPACE = property(lambda self: splitNS(self.tag_name)[0])
+ """Get namespace of element"""
+
+ PARSER = SVG_PARSER
+ """A reference to the :attr:`inkex.elements._parser.SVG_PARSER`"""
+ WRAPPED_ATTRS = (
+ # (prop_name, [optional: attr_name], cls)
+ ("transform", Transform),
+ ("style", Style),
+ ("classes", "class", Classes),
+ ) # type: Tuple[Tuple[Any, ...], ...]
+ """A list of attributes that are automatically converted to objects."""
+
+ # We do this because python2 and python3 have different ways
+ # of combining two dictionaries that are incompatible.
+ # This allows us to update these with inheritance.
+ @property
+ def wrapped_attrs(self):
+ """Map attributes to property name and wrapper class"""
+ return {row[-2]: (row[0], row[-1]) for row in self.WRAPPED_ATTRS}
+
+ @property
+ def wrapped_props(self):
+ """Map properties to attribute name and wrapper class"""
+ return {row[0]: (row[-2], row[-1]) for row in self.WRAPPED_ATTRS}
+
+ typename = property(lambda self: type(self).__name__)
+ """Type name of the element"""
+ xml_path = property(lambda self: self.getroottree().getpath(self))
+ """XPath representation of the element in its tree
+
+ .. versionadded:: 1.1"""
+ desc = ChildToProperty("svg:desc", prepend=True)
+ """The element's long-form description (for accessibility purposes)
+
+ .. versionadded:: 1.1"""
+ title = ChildToProperty("svg:title", prepend=True)
+ """The element's short-form description (for accessibility purposes)
+
+ .. versionadded:: 1.1"""
+
+ def __getattr__(self, name):
+ """Get the attribute, but load it if it is not available yet"""
+ if name in self.wrapped_props:
+ (attr, cls) = self.wrapped_props[name]
+ # The reason we do this here and not in _init is because lxml
+ # is inconsistant about when elements are initialised.
+ # So we make this a lazy property.
+ def _set_attr(new_item):
+ if new_item:
+ self.set(attr, str(new_item))
+ else:
+ self.attrib.pop(attr, None) # pylint: disable=no-member
+
+ # pylint: disable=no-member
+ value = cls(self.attrib.get(attr, None), callback=_set_attr)
+ if name == "style":
+ value.element = self
+ setattr(self, name, value)
+ return value
+ raise AttributeError(f"Can't find attribute {self.typename}.{name}")
+
+ def __setattr__(self, name, value):
+ """Set the attribute, update it if needed"""
+ if name in self.wrapped_props:
+ (attr, cls) = self.wrapped_props[name]
+ # Don't call self.set or self.get (infinate loop)
+ if value:
+ if not isinstance(value, cls):
+ value = cls(value)
+ self.attrib[attr] = str(value)
+ else:
+ self.attrib.pop(attr, None) # pylint: disable=no-member
+ else:
+ super().__setattr__(name, value)
+
+ def get(self, attr, default=None):
+ """Get element attribute named, with addNS support."""
+ if attr in self.wrapped_attrs:
+ (prop, _) = self.wrapped_attrs[attr]
+ value = getattr(self, prop, None)
+ # We check the boolean nature of the value, because empty
+ # transformations and style attributes are equiv to not-existing
+ ret = str(value) if value else (default or None)
+ return ret
+ return super().get(addNS(attr), default)
+
+ def set(self, attr, value):
+ """Set element attribute named, with addNS support"""
+ if attr in self.wrapped_attrs:
+ # Always keep the local wrapped class up to date.
+ (prop, cls) = self.wrapped_attrs[attr]
+ setattr(self, prop, cls(value))
+ value = getattr(self, prop)
+ if not value:
+ return
+ if value is None:
+ self.attrib.pop(addNS(attr), None) # pylint: disable=no-member
+ else:
+ value = str(value)
+ super().set(addNS(attr), value)
+
+ def update(self, **kwargs):
+ """
+ Update element attributes using keyword arguments
+
+ Note: double underscore is used as namespace separator,
+ i.e. "namespace__attr" argument name will be treated as "namespace:attr"
+
+ :param kwargs: dict with name=value pairs
+ :return: self
+ """
+ for name, value in kwargs.items():
+ self.set(name, value)
+ return self
+
+ def pop(self, attr, default=None):
+ """Delete/remove the element attribute named, with addNS support."""
+ if attr in self.wrapped_attrs:
+ # Always keep the local wrapped class up to date.
+ (prop, cls) = self.wrapped_attrs[attr]
+ value = getattr(self, prop)
+ setattr(self, prop, cls(None))
+ return value
+ return self.attrib.pop(addNS(attr), default) # pylint: disable=no-member
+
+ @overload
+ def add(
+ self, child1: BaseElement, child2: BaseElement, *children: BaseElement
+ ) -> Tuple[BaseElement]:
+ ...
+
+ @overload
+ def add(self, child: T) -> T:
+ ...
+
+ def add(self, *children):
+ """
+ Like append, but will do multiple children and will return
+ children or only child
+ """
+ for child in children:
+ self.append(child)
+ return children if len(children) != 1 else children[0]
+
+ def tostring(self):
+ """Return this element as it would appear in an svg document"""
+ # This kind of hack is pure maddness, but etree provides very little
+ # in the way of fragment printing, prefering to always output valid xml
+
+ svg = SvgOutputMixin.get_template(width=0, height=0).getroot()
+ svg.append(self.copy())
+ return svg.tostring().split(b">\n ", 1)[-1][:-6]
+
+ def set_random_id(
+ self,
+ prefix: Optional[str] = None,
+ size: Optional[int] = None,
+ backlinks: bool = False,
+ blacklist: Optional[List[str]] = None,
+ ):
+ """Sets the id attribute if it is not already set.
+
+ The id consists of a prefix and an appended random integer of length size.
+ Args:
+ prefix (str, optional): the prefix of the new ID. Defaults to the tag name.
+ size (Optional[int], optional): number of digits of the second part of the
+ id. If None, the length is chosen based on the amount of existing
+ objects. Defaults to None.
+
+ .. versionchanged:: 1.2
+ The default of this value has been changed from 4 to None.
+ backlinks (bool, optional): Whether to update the links in existing objects
+ that reference this element. Defaults to False.
+ blacklist (List[str], optional): An additional list of ids that are not
+ allowed to be used. This is useful when bulk inserting objects.
+ Defaults to None.
+
+ .. versionadded:: 1.2
+ """
+ prefix = str(self) if prefix is None else prefix
+ self.set_id(
+ self.root.get_unique_id(prefix, size=size, blacklist=blacklist),
+ backlinks=backlinks,
+ )
+
+ def set_random_ids(
+ self,
+ prefix: Optional[str] = None,
+ levels: int = -1,
+ backlinks: bool = False,
+ blacklist: Optional[List[str]] = None,
+ ):
+ """Same as set_random_id, but will apply also to children
+
+ The id consists of a prefix and an appended random integer of length size.
+ Args:
+ prefix (str, optional): the prefix of the new ID. Defaults to the tag name.
+ levels (int, optional): the depth of the tree traversion, if negative, no
+ limit is imposed. Defaults to -1.
+ backlinks (bool, optional): Whether to update the links in existing objects
+ that reference this element. Defaults to False.
+ blacklist (List[str], optional): An additional list of ids that are not
+ allowed to be used. This is useful when bulk inserting objects.
+ Defaults to None.
+
+ .. versionadded:: 1.2
+ """
+ self.set_random_id(prefix=prefix, backlinks=backlinks, blacklist=blacklist)
+ if levels != 0:
+ for child in self:
+ if hasattr(child, "set_random_ids"):
+ child.set_random_ids(
+ prefix=prefix, levels=levels - 1, backlinks=backlinks
+ )
+
+ eid = property(lambda self: self.get_id())
+ """Property to access the element's id; will set a new unique id if not set."""
+
+ def get_id(self, as_url=0) -> str:
+ """Get the id for the element, will set a new unique id if not set.
+
+ as_url - If set to 1, returns #{id} as a string
+ If set to 2, returns url(#{id}) as a string
+
+ Args:
+ as_url (int, optional):
+ - If set to 1, returns #{id} as a string
+ - If set to 2, returns url(#{id}) as a string.
+
+ Defaults to 0.
+
+ .. versionadded:: 1.1
+
+ Returns:
+ str: formatted id
+ """
+ if "id" not in self.attrib:
+ self.set_random_id(self.TAG)
+ eid = self.get("id")
+ if as_url > 0:
+ eid = "#" + eid
+ if as_url > 1:
+ eid = f"url({eid})"
+ return eid
+
+ def set_id(self, new_id, backlinks=False):
+ """Set the id and update backlinks to xlink and style urls if needed"""
+ old_id = self.get("id", None)
+ self.set("id", new_id)
+ if backlinks and old_id:
+ for elem in self.root.getElementsByHref(old_id):
+ elem.href = self
+ for attr in ["clip-path", "mask"]:
+ for elem in self.root.getElementsByHref(old_id, attribute=attr):
+ elem.set(attr, self.get_id(2))
+ for elem in self.root.getElementsByStyleUrl(old_id):
+ elem.style.update_urls(old_id, new_id)
+
+ @property
+ def root(self):
+ """Get the root document element from any element descendent"""
+ root, parent = self, self
+ while parent is not None:
+ root, parent = parent, parent.getparent()
+
+ if not isinstance(root, ISVGDocumentElement):
+ raise FragmentError("Element fragment does not have a document root!")
+ return root
+
+ def get_or_create(self, xpath, nodeclass=None, prepend=False):
+ """Get or create the given xpath, pre/append new node if not found.
+
+ .. versionchanged:: 1.1
+ The ``nodeclass`` attribute is optional; if not given, it is looked up
+ using :func:`~inkex.elements._parser.NodeBasedLookup.find_class`"""
+ node = self.findone(xpath)
+ if node is None:
+ if nodeclass is None:
+ nodeclass = NodeBasedLookup.find_class(xpath)
+ node = nodeclass()
+ if prepend:
+ self.insert(0, node)
+ else:
+ self.append(node)
+ return node
+
+ def descendants(self):
+ """Walks the element tree and yields all elements, parent first
+
+ .. versionchanged:: 1.1
+ The ``*types`` attribute was removed
+
+ """
+
+ return ElementList(
+ self.root,
+ [
+ element
+ for element in self.iter()
+ if isinstance(element, (BaseElement, str))
+ ],
+ )
+
+ def ancestors(self, elem=None, stop_at=()):
+ """
+ Walk the parents and yield all the ancestor elements, parent first
+
+ Args:
+ elem (BaseElement, optional): If provided, it will stop at the last common
+ ancestor. Defaults to None.
+
+ .. versionadded:: 1.1
+
+ stop_at (tuple, optional): If provided, it will stop at the first parent
+ that is in this list. Defaults to ().
+
+ .. versionadded:: 1.1
+
+ Returns:
+ ElementList: list of ancestors
+ """
+
+ return ElementList(self.root, self._ancestors(elem=elem, stop_at=stop_at))
+
+ def _ancestors(self, elem, stop_at):
+ if isinstance(elem, BaseElement):
+ stop_at = list(elem.ancestors())
+ for parent in self.iterancestors():
+ yield parent
+ if parent in stop_at:
+ break
+
+ def backlinks(self, *types):
+ """Get elements which link back to this element, like ancestors but via
+ xlinks"""
+ if not types or isinstance(self, types):
+ yield self
+ my_id = self.get("id")
+ if my_id is not None:
+ elems = list(self.root.getElementsByHref(my_id)) + list(
+ self.root.getElementsByStyleUrl(my_id)
+ )
+ for elem in elems:
+ if hasattr(elem, "backlinks"):
+ for child in elem.backlinks(*types):
+ yield child
+
+ def xpath(self, pattern, namespaces=NSS): # pylint: disable=dangerous-default-value
+ """Wrap xpath call and add svg namespaces"""
+ return super().xpath(pattern, namespaces=namespaces)
+
+ def findall(
+ self, pattern, namespaces=NSS
+ ): # pylint: disable=dangerous-default-value
+ """Wrap findall call and add svg namespaces"""
+ return super().findall(pattern, namespaces=namespaces)
+
+ def findone(self, xpath):
+ """Gets a single element from the given xpath or returns None"""
+ el_list = self.xpath(xpath)
+ return el_list[0] if el_list else None
+
+ def delete(self):
+ """Delete this node from it's parent node"""
+ if self.getparent() is not None:
+ self.getparent().remove(self)
+
+ def remove_all(self, *types):
+ """Remove all children or child types
+
+ .. versionadded:: 1.1"""
+ types = tuple(NodeBasedLookup.find_class(t) for t in types)
+ for child in self:
+ if not types or isinstance(child, types):
+ self.remove(child)
+
+ def replace_with(self, elem):
+ """Replace this element with the given element"""
+ self.addnext(elem)
+ if not elem.get("id") and self.get("id"):
+ elem.set("id", self.get("id"))
+ if not elem.label and self.label:
+ elem.label = self.label
+ self.delete()
+ return elem
+
+ def copy(self):
+ """Make a copy of the element and return it"""
+ elem = deepcopy(self)
+ elem.set("id", None)
+ return elem
+
+ def duplicate(self):
+ """Like copy(), but the copy stays in the tree and sets a random id on the
+ duplicate.
+
+ .. versionchanged:: 1.2
+ A random id is also set on all the duplicate's descendants"""
+ elem = self.copy()
+ self.addnext(elem)
+ elem.set_random_ids()
+ return elem
+
+ def __str__(self):
+ # We would do more here, but lxml is VERY unpleseant when it comes to
+ # namespaces, basically over printing details and providing no
+ # supression mechanisms to turn off xml's over engineering.
+ return str(self.tag).split("}", maxsplit=1)[-1]
+
+ @property
+ def href(self):
+ """Returns the referred-to element if available
+
+ .. versionchanged:: 1.1
+ A setter for href was added."""
+ ref = self.get("xlink:href")
+ if not ref:
+ return None
+ return self.root.getElementById(ref.strip("#"))
+
+ @href.setter
+ def href(self, elem):
+ """Set the href object"""
+ if isinstance(elem, BaseElement):
+ elem = elem.get_id()
+ self.set("xlink:href", "#" + elem)
+
+ @property
+ def label(self):
+ """Returns the inkscape label"""
+ return self.get("inkscape:label", None)
+
+ @label.setter
+ def label(self, value):
+ """Sets the inkscape label"""
+ self.set("inkscape:label", str(value))
+
+ def is_sensitive(self):
+ """Return true if this element is sensitive in inkscape
+
+ .. versionadded:: 1.1"""
+ return self.get("sodipodi:insensitive", None) != "true"
+
+ def set_sensitive(self, sensitive=True):
+ """Set the sensitivity of the element/layer
+
+ .. versionadded:: 1.1"""
+ # Sensitive requires None instead of 'false'
+ self.set("sodipodi:insensitive", ["true", None][sensitive])
+
+ @property
+ def unit(self):
+ """Return the unit being used by the owning document, cached
+
+ .. versionadded:: 1.1"""
+ try:
+ return self.root.unit
+ except FragmentError:
+ return "px" # Don't cache.
+
+ @staticmethod
+ def to_dimensional(value, to_unit="px"):
+ """Convert a value given in user units (px) the given unit type
+
+ .. versionadded:: 1.2"""
+ return convert_unit(value, to_unit)
+
+ @staticmethod
+ def to_dimensionless(value):
+ """Convert a length value into user units (px)
+
+ .. versionadded:: 1.2"""
+ return convert_unit(value, "px")
+
+ def uutounit(self, value, to_unit="px"):
+ """Convert a unit value to a given unit. If the value does not have a unit,
+ "Document" units are assumed. "Document units" are an Inkscape-specific concept.
+ For most use-cases, :func:`to_dimensional` is more appropriate.
+
+ .. versionadded:: 1.1"""
+ return convert_unit(value, to_unit, default=self.unit)
+
+ def unittouu(self, value):
+ """Convert a unit value into document units. "Document unit" is an
+ Inkscape-specific concept. For most use-cases, :func:`viewport_to_unit` (when
+ the size of an object given in viewport units is needed) or
+ :func:`to_dimensionless` (when the equivalent value without unit is needed) is
+ more appropriate.
+
+ .. versionadded:: 1.1"""
+ return convert_unit(value, self.unit)
+
+ def unit_to_viewport(self, value, unit="px"):
+ """Converts a length value to viewport units, as defined by the width/height
+ element on the root (i.e. applies the equivalent transform of the viewport)
+
+ .. versionadded:: 1.2"""
+ return self.to_dimensional(
+ self.to_dimensionless(value) * self.root.equivalent_transform_scale, unit
+ )
+
+ def viewport_to_unit(self, value, unit="px"):
+ """Converts a length given on the viewport to the specified unit in the user
+ coordinate system
+
+ .. versionadded:: 1.2"""
+ return self.to_dimensional(
+ self.to_dimensionless(value) / self.root.equivalent_transform_scale, unit
+ )
+
+ def add_unit(self, value):
+ """Add document unit when no unit is specified in the string.
+
+ .. versionadded:: 1.1"""
+ return render_unit(value, self.unit)
+
+ def cascaded_style(self):
+ """Returns the cascaded style of an element (all rules that apply the element
+ itself), based on the stylesheets, the presentation attributes and the inline
+ style using the respective specificity of the style.
+
+ see https://www.w3.org/TR/CSS22/cascade.html#cascading-order
+
+ .. versionadded:: 1.2
+
+ Returns:
+ Style: the cascaded style
+
+ """
+ return Style.cascaded_style(self)
+
+ def specified_style(self):
+ """Returns the specified style of an element, i.e. the cascaded style +
+ inheritance, see https://www.w3.org/TR/CSS22/cascade.html#specified-value.
+
+ Returns:
+ Style: the specified style
+
+ .. versionadded:: 1.2
+ """
+ return Style.specified_style(self)
+
+ def presentation_style(self):
+ """Return presentation attributes of an element as style
+
+ .. versionadded:: 1.2"""
+ style = Style()
+ for key in self.keys():
+ if key in all_properties and all_properties[key][2]:
+ style[key] = BaseStyleValue.factory(
+ declaration=key + ": " + self.attrib[key]
+ )
+ return style
+
+ def composed_transform(self, other=None):
+ """Calculate every transform down to the other element
+ if none specified the transform is to the root document element
+ """
+ parent = self.getparent()
+ if parent is not None and isinstance(parent, BaseElement):
+ return parent.composed_transform() @ self.transform
+ return self.transform
+
+
+NodeBasedLookup.default = BaseElement
+
+
+class ShapeElement(BaseElement):
+ """Elements which have a visible representation on the canvas"""
+
+ @property
+ def path(self):
+ """Gets the outline or path of the element, this may be a simple bounding box"""
+ return Path(self.get_path())
+
+ @path.setter
+ def path(self, path):
+ self.set_path(path)
+
+ @property
+ def clip(self):
+ """Gets the clip path element (if any)
+
+ .. versionadded:: 1.1"""
+ ref = self.get("clip-path")
+ if not ref:
+ return None
+ return self.root.getElementById(ref)
+
+ @clip.setter
+ def clip(self, elem):
+ self.set("clip-path", elem.get_id(as_url=2))
+
+ def get_path(self) -> Path:
+ """Generate a path for this object which can inform the bounding box"""
+ raise NotImplementedError(
+ f"Path should be provided by svg elem {self.typename}."
+ )
+
+ def set_path(self, path):
+ """Set the path for this object (if possible)"""
+ raise AttributeError(
+ f"Path can not be set on this element: {self.typename} <- {path}."
+ )
+
+ def to_path_element(self):
+ """Replace this element with a path element"""
+ from ._polygons import PathElement
+
+ elem = PathElement()
+ elem.path = self.path
+ elem.style = self.effective_style()
+ elem.transform = self.transform
+ return elem
+
+ def effective_style(self):
+ """Without parent styles, what is the effective style is"""
+ return self.style
+
+ def bounding_box(self, transform=None):
+ # type: (Optional[Transform]) -> Optional[BoundingBox]
+ """BoundingBox of the shape
+
+ .. versionchanged:: 1.1
+ result adjusted for element's clip path if applicable."""
+ shape_box = self.shape_box(transform)
+ clip = self.clip
+ if clip is None or shape_box is None:
+ return shape_box
+ return shape_box & clip.bounding_box(Transform(transform) @ self.transform)
+
+ def shape_box(self, transform=None):
+ # type: (Optional[Transform]) -> Optional[BoundingBox]
+ """BoundingBox of the unclipped shape
+
+ .. versionadded:: 1.1
+ Previous :func:`bounding_box` function, returning the bounding box
+ without computing the effect of a possible clip."""
+ path = self.path.to_absolute()
+ if transform is True:
+ path = path.transform(self.composed_transform())
+ else:
+ path = path.transform(self.transform)
+ if transform: # apply extra transformation
+ path = path.transform(transform)
+ return path.bounding_box()
+
+ def is_visible(self):
+ """Returns false if the css says this object is invisible
+
+ .. versionadded:: 1.1"""
+ if self.style.get("display", "") == "none":
+ return False
+ if not float(self.style.get("opacity", 1.0)):
+ return False
+ return True
+
+ def get_line_height_uu(self):
+ """Returns the specified value of line-height, in user units
+
+ .. versionadded:: 1.1"""
+ style = self.specified_style()
+ font_size = style("font-size") # already in uu
+ line_height = style("line-height")
+ parsed = parse_unit(line_height)
+ if parsed is None:
+ return font_size * 1.2
+ if parsed[1] == "%":
+ return font_size * parsed[0] * 0.01
+ return self.to_dimensionless(line_height)
diff --git a/share/extensions/inkex/elements/_filters.py b/share/extensions/inkex/elements/_filters.py
new file mode 100644
index 0000000..ce86507
--- /dev/null
+++ b/share/extensions/inkex/elements/_filters.py
@@ -0,0 +1,367 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2020 Martin Owens <doctormo@gmail.com>
+# Sergei Izmailov <sergei.a.izmailov@gmail.com>
+# Thomas Holder <thomas.holder@schrodinger.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=arguments-differ
+"""
+Element interface for patterns, filters, gradients and path effects.
+"""
+from __future__ import annotations
+from typing import List, Tuple, TYPE_CHECKING, Optional
+
+from lxml import etree
+
+from ..transforms import Transform
+from ..utils import parse_percent
+
+from ..styles import Style
+
+from ._utils import addNS
+from ._base import BaseElement
+
+
+if TYPE_CHECKING:
+ from ._svg import SvgDocumentElement
+
+
+class Filter(BaseElement):
+ """A filter (usually in defs)"""
+
+ tag_name = "filter"
+
+ def add_primitive(self, fe_type, **args):
+ """Create a filter primitive with the given arguments"""
+ elem = etree.SubElement(self, addNS(fe_type, "svg"))
+ elem.update(**args)
+ return elem
+
+ class Primitive(BaseElement):
+ """Any filter primitive"""
+
+ class Blend(Primitive):
+ """Blend Filter element"""
+
+ tag_name = "feBlend"
+
+ class ColorMatrix(Primitive):
+ """ColorMatrix Filter element"""
+
+ tag_name = "feColorMatrix"
+
+ class ComponentTransfer(Primitive):
+ """ComponentTransfer Filter element"""
+
+ tag_name = "feComponentTransfer"
+
+ class Composite(Primitive):
+ """Composite Filter element"""
+
+ tag_name = "feComposite"
+
+ class ConvolveMatrix(Primitive):
+ """ConvolveMatrix Filter element"""
+
+ tag_name = "feConvolveMatrix"
+
+ class DiffuseLighting(Primitive):
+ """DiffuseLightning Filter element"""
+
+ tag_name = "feDiffuseLighting"
+
+ class DisplacementMap(Primitive):
+ """Flood Filter element"""
+
+ tag_name = "feDisplacementMap"
+
+ class Flood(Primitive):
+ """DiffuseLightning Filter element"""
+
+ tag_name = "feFlood"
+
+ class GaussianBlur(Primitive):
+ """GaussianBlur Filter element"""
+
+ tag_name = "feGaussianBlur"
+
+ class Image(Primitive):
+ """Image Filter element"""
+
+ tag_name = "feImage"
+
+ class Merge(Primitive):
+ """Merge Filter element"""
+
+ tag_name = "feMerge"
+
+ class Morphology(Primitive):
+ """Morphology Filter element"""
+
+ tag_name = "feMorphology"
+
+ class Offset(Primitive):
+ """Offset Filter element"""
+
+ tag_name = "feOffset"
+
+ class SpecularLighting(Primitive):
+ """SpecularLighting Filter element"""
+
+ tag_name = "feSpecularLighting"
+
+ class Tile(Primitive):
+ """Tile Filter element"""
+
+ tag_name = "feTile"
+
+ class Turbulence(Primitive):
+ """Turbulence Filter element"""
+
+ tag_name = "feTurbulence"
+
+
+class Stop(BaseElement):
+ """Gradient stop
+
+ .. versionadded:: 1.1"""
+
+ tag_name = "stop"
+
+ @property
+ def offset(self) -> float:
+ """The offset of the gradient stop"""
+ return self.get("offset")
+
+ @offset.setter
+ def offset(self, number):
+ self.set("offset", number)
+
+ def interpolate(self, other, fraction):
+ """Interpolate gradient stops"""
+ from ..tween import StopInterpolator
+
+ return StopInterpolator(self, other).interpolate(fraction)
+
+
+class Pattern(BaseElement):
+ """Pattern element which is used in the def to control repeating fills"""
+
+ tag_name = "pattern"
+ WRAPPED_ATTRS = BaseElement.WRAPPED_ATTRS + (("patternTransform", Transform),)
+
+
+class Gradient(BaseElement):
+ """A gradient instruction usually in the defs."""
+
+ WRAPPED_ATTRS = BaseElement.WRAPPED_ATTRS + (("gradientTransform", Transform),)
+ """Additional to the :attr:`~inkex.elements._base.BaseElement.WRAPPED_ATTRS` of
+ :class:`~inkex.elements._base.BaseElement`, ``gradientTransform`` is wrapped."""
+
+ orientation_attributes = () # type: Tuple[str, ...]
+ """
+ .. versionadded:: 1.1
+ """
+
+ @property
+ def stops(self):
+ """Return an ordered list of own or linked stop nodes
+
+ .. versionadded:: 1.1"""
+ gradcolor = (
+ self.href
+ if isinstance(self.href, (LinearGradient, RadialGradient))
+ else self
+ )
+ return sorted(
+ [child for child in gradcolor if isinstance(child, Stop)],
+ key=lambda x: parse_percent(x.offset),
+ )
+
+ @property
+ def stop_offsets(self):
+ # type: () -> List[float]
+ """Return a list of own or linked stop offsets
+
+ .. versionadded:: 1.1"""
+ return [child.offset for child in self.stops]
+
+ @property
+ def stop_styles(self): # type: () -> List[Style]
+ """Return a list of own or linked offset styles
+
+ .. versionadded:: 1.1"""
+ return [child.style for child in self.stops]
+
+ def remove_orientation(self):
+ """Remove all orientation attributes from this element
+
+ .. versionadded:: 1.1"""
+ for attr in self.orientation_attributes:
+ self.pop(attr)
+
+ def interpolate(
+ self,
+ other: LinearGradient,
+ fraction: float,
+ svg: Optional[SvgDocumentElement] = None,
+ ):
+ """Interpolate with another gradient.
+
+ .. versionadded:: 1.1"""
+ from ..tween import GradientInterpolator
+
+ return GradientInterpolator(self, other, svg).interpolate(fraction)
+
+ def stops_and_orientation(self):
+ """Return a copy of all the stops in this gradient
+
+ .. versionadded:: 1.1"""
+ stops = self.copy()
+ stops.remove_orientation()
+ orientation = self.copy()
+ orientation.remove_all(Stop)
+ return stops, orientation
+
+
+class LinearGradient(Gradient):
+ """LinearGradient element"""
+
+ tag_name = "linearGradient"
+ orientation_attributes = ("x1", "y1", "x2", "y2")
+ """
+ .. versionadded:: 1.1
+ """
+
+ def apply_transform(self): # type: () -> None
+ """Apply transform to orientation points and set it to identity.
+ .. versionadded:: 1.1
+ """
+ trans = self.pop("gradientTransform")
+ pt1 = (
+ self.to_dimensionless(self.get("x1")),
+ self.to_dimensionless(self.get("y1")),
+ )
+ pt2 = (
+ self.to_dimensionless(self.get("x2")),
+ self.to_dimensionless(self.get("y2")),
+ )
+ p1t = trans.apply_to_point(pt1)
+ p2t = trans.apply_to_point(pt2)
+ self.update(
+ x1=self.to_dimensionless(p1t[0]),
+ y1=self.to_dimensionless(p1t[1]),
+ x2=self.to_dimensionless(p2t[0]),
+ y2=self.to_dimensionless(p2t[1]),
+ )
+
+
+class RadialGradient(Gradient):
+ """RadialGradient element"""
+
+ tag_name = "radialGradient"
+ orientation_attributes = ("cx", "cy", "fx", "fy", "r")
+ """
+ .. versionadded:: 1.1
+ """
+
+ def apply_transform(self): # type: () -> None
+ """Apply transform to orientation points and set it to identity.
+
+ .. versionadded:: 1.1
+ """
+ trans = self.pop("gradientTransform")
+ pt1 = (
+ self.to_dimensionless(self.get("cx")),
+ self.to_dimensionless(self.get("cy")),
+ )
+ pt2 = (
+ self.to_dimensionless(self.get("fx")),
+ self.to_dimensionless(self.get("fy")),
+ )
+ p1t = trans.apply_to_point(pt1)
+ p2t = trans.apply_to_point(pt2)
+ self.update(
+ cx=self.to_dimensionless(p1t[0]),
+ cy=self.to_dimensionless(p1t[1]),
+ fx=self.to_dimensionless(p2t[0]),
+ fy=self.to_dimensionless(p2t[1]),
+ )
+
+
+class PathEffect(BaseElement):
+ """Inkscape LPE element"""
+
+ tag_name = "inkscape:path-effect"
+
+
+class MeshGradient(Gradient):
+ """Usable MeshGradient XML base class
+
+ .. versionadded:: 1.1"""
+
+ tag_name = "meshgradient"
+
+ @classmethod
+ def new_mesh(cls, pos=None, rows=1, cols=1, autocollect=True):
+ """Return skeleton of 1x1 meshgradient definition."""
+ # initial point
+ if pos is None or len(pos) != 2:
+ pos = [0.0, 0.0]
+ # create nested elements for rows x cols mesh
+ meshgradient = cls()
+ for _ in range(rows):
+ meshrow: BaseElement = meshgradient.add(MeshRow())
+ for _ in range(cols):
+ meshrow.append(MeshPatch())
+ # set meshgradient attributes
+ meshgradient.set("gradientUnits", "userSpaceOnUse")
+ meshgradient.set("x", pos[0])
+ meshgradient.set("y", pos[1])
+ if autocollect:
+ meshgradient.set("inkscape:collect", "always")
+ return meshgradient
+
+
+class MeshRow(BaseElement):
+ """Each row of a mesh gradient
+
+ .. versionadded:: 1.1"""
+
+ tag_name = "meshrow"
+
+
+class MeshPatch(BaseElement):
+ """Each column or 'patch' in a mesh gradient
+
+ .. versionadded:: 1.1"""
+
+ tag_name = "meshpatch"
+
+ def stops(self, edges, colors):
+ """Add or edit meshpatch stops with path and stop-color."""
+ # iterate stops based on number of edges (path data)
+ for i, edge in enumerate(edges):
+ if i < len(self):
+ stop = self[i]
+ else:
+ stop = self.add(Stop())
+
+ # set edge path data
+ stop.set("path", str(edge))
+ # set stop color
+ stop.style["stop-color"] = str(colors[i % 2])
diff --git a/share/extensions/inkex/elements/_groups.py b/share/extensions/inkex/elements/_groups.py
new file mode 100644
index 0000000..c66bfe3
--- /dev/null
+++ b/share/extensions/inkex/elements/_groups.py
@@ -0,0 +1,126 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2020 Martin Owens <doctormo@gmail.com>
+# Sergei Izmailov <sergei.a.izmailov@gmail.com>
+# Ryan Jarvis <ryan@shopboxretail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=arguments-differ
+"""
+Interface for all group based elements such as Groups, Use, Markers etc.
+"""
+
+from lxml import etree # pylint: disable=unused-import
+
+from ..paths import Path
+from ..transforms import Transform
+
+from ._utils import addNS
+from ._base import ShapeElement
+
+try:
+ from typing import Optional # pylint: disable=unused-import
+except ImportError:
+ pass
+
+
+class GroupBase(ShapeElement):
+ """Base Group element"""
+
+ def get_path(self):
+ ret = Path()
+ for child in self:
+ if isinstance(child, ShapeElement):
+ ret += child.path.transform(child.transform)
+ return ret
+
+ def shape_box(self, transform=None):
+ bbox = None
+ effective_transform = Transform(transform) @ self.transform
+ for child in self:
+ if isinstance(child, ShapeElement):
+ child_bbox = child.bounding_box(transform=effective_transform)
+ if child_bbox is not None:
+ bbox += child_bbox
+ return bbox
+
+
+class Group(GroupBase):
+ """Any group element (layer or regular group)"""
+
+ tag_name = "g"
+
+ @classmethod
+ def new(cls, label, *children, **attrs):
+ attrs["inkscape:label"] = label
+ return super().new(*children, **attrs)
+
+ def effective_style(self):
+ """A blend of each child's style mixed together (last child wins)"""
+ style = self.style
+ for child in self:
+ style.update(child.effective_style())
+ return style
+
+ @property
+ def groupmode(self):
+ """Return the type of group this is"""
+ return self.get("inkscape:groupmode", "group")
+
+
+class Layer(Group):
+ """Inkscape extension of svg:g"""
+
+ def _init(self):
+ self.set("inkscape:groupmode", "layer")
+
+ @classmethod
+ def is_class_element(cls, elem):
+ # type: (etree.Element) -> bool
+ return elem.attrib.get(addNS("inkscape:groupmode"), None) == "layer"
+
+
+class Anchor(GroupBase):
+ """An anchor or link tag"""
+
+ tag_name = "a"
+
+ @classmethod
+ def new(cls, href, *children, **attrs):
+ attrs["xlink:href"] = href
+ return super().new(*children, **attrs)
+
+
+class ClipPath(GroupBase):
+ """A path used to clip objects"""
+
+ tag_name = "clipPath"
+
+
+class Marker(GroupBase):
+ """The <marker> element defines the graphic that is to be used for drawing
+ arrowheads or polymarkers on a given <path>, <line>, <polyline> or <polygon>
+ element."""
+
+ tag_name = "marker"
+
+
+class Mask(GroupBase):
+ """An alpha mask for compositing an object into the background
+
+ .. versionadded:: 1.2"""
+
+ tag_name = "mask"
diff --git a/share/extensions/inkex/elements/_image.py b/share/extensions/inkex/elements/_image.py
new file mode 100644
index 0000000..9294d73
--- /dev/null
+++ b/share/extensions/inkex/elements/_image.py
@@ -0,0 +1,29 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2020 - Martin Owens <doctormo@gmail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Image element interface.
+"""
+
+from ._polygons import RectangleBase
+
+
+class Image(RectangleBase):
+ """Provide a useful extension for image elements"""
+
+ tag_name = "image"
diff --git a/share/extensions/inkex/elements/_meta.py b/share/extensions/inkex/elements/_meta.py
new file mode 100644
index 0000000..e9eeb0f
--- /dev/null
+++ b/share/extensions/inkex/elements/_meta.py
@@ -0,0 +1,293 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2020 Martin Owens <doctormo@gmail.com>
+# Maren Hachmann <moini>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=arguments-differ
+"""
+Provide extra utility to each svg element type specific to its type.
+
+This is useful for having a common interface for each element which can
+give path, transform, and property access easily.
+"""
+
+from __future__ import annotations
+import math
+
+from typing import Optional
+
+from lxml import etree
+
+from ..styles import StyleSheet
+from ..transforms import Vector2d, VectorLike, DirectedLineSegment
+
+from ._base import BaseElement
+
+
+class Defs(BaseElement):
+ """A header defs element, one per document"""
+
+ tag_name = "defs"
+
+
+class StyleElement(BaseElement):
+ """A CSS style element containing multiple style definitions"""
+
+ tag_name = "style"
+
+ def set_text(self, content):
+ """Sets the style content text as a CDATA section"""
+ self.text = etree.CDATA(str(content))
+
+ def stylesheet(self):
+ """Return the StyleSheet() object for the style tag"""
+ return StyleSheet(self.text, callback=self.set_text)
+
+
+class Script(BaseElement):
+ """A javascript tag in SVG"""
+
+ tag_name = "script"
+
+ def set_text(self, content):
+ """Sets the style content text as a CDATA section"""
+ self.text = etree.CDATA(str(content))
+
+
+class Desc(BaseElement):
+ """Description element"""
+
+ tag_name = "desc"
+
+
+class Title(BaseElement):
+ """Title element"""
+
+ tag_name = "title"
+
+
+class NamedView(BaseElement):
+ """The NamedView element is Inkscape specific metadata about the file"""
+
+ tag_name = "sodipodi:namedview"
+
+ current_layer = property(lambda self: self.get("inkscape:current-layer"))
+
+ @property
+ def center(self):
+ """Returns view_center in terms of document units"""
+ return Vector2d(
+ self.root.viewport_to_unit(self.get("inkscape:cx") or 0),
+ self.root.viewport_to_unit(self.get("inkscape:cy") or 0),
+ )
+
+ def get_guides(self):
+ """Returns a list of guides"""
+ return self.findall("sodipodi:guide")
+
+ def new_guide(self, position, orient=True, name=None):
+ """Creates a new guide in this namedview
+
+ Args:
+ position: a float containing the y position for ``orient is True``, or
+ the x position for ``orient is False``
+
+ .. versionchanged:: 1.2
+ Alternatively, the position may be given as Tuple (or VectorLike)
+ orient: True for horizontal, False for Vertical
+
+ .. versionchanged:: 1.2
+ Tuple / Vector specifying x and y coordinates of the normal vector
+ of the guide.
+ name: label of the guide
+
+ Returns:
+ the created guide"""
+ if orient is True:
+ elem = Guide().move_to(0, position, (0, 1))
+ elif orient is False:
+ elem = Guide().move_to(position, 0, (1, 0))
+ else:
+ elem = Guide().move_to(*position, orient)
+ if name:
+ elem.set("inkscape:label", str(name))
+ return self.add(elem)
+
+ def new_unique_guide(
+ self, position: VectorLike, orientation: VectorLike
+ ) -> Optional[Guide]:
+ """Add a guide iif there is no guide that looks the same.
+
+ .. versionadded:: 1.2"""
+ elem = Guide().move_to(position[0], position[1], orientation)
+ return self.add(elem) if self.get_similar_guide(elem) is None else None
+
+ def get_similar_guide(self, other: Guide) -> Optional[Guide]:
+ """Check if the namedview contains a guide that looks identical to one
+ defined by (position, orientation). If such a guide exists, return it;
+ otherwise, return None.
+
+ .. versionadded:: 1.2"""
+ for guide in self.get_guides():
+ if Guide.guides_coincident(guide, other):
+ return guide
+ return None
+
+ def get_pages(self):
+ """Returns a list of pages
+
+ .. versionadded:: 1.2"""
+ return self.findall("inkscape:page")
+
+ def new_page(self, x, y, width, height, label=None):
+ """Creates a new page in this namedview
+
+ .. versionadded:: 1.2"""
+ elem = Page(width=width, height=height, x=x, y=y)
+ if label:
+ elem.set("inkscape:label", str(label))
+ return self.add(elem)
+
+
+class Guide(BaseElement):
+ """An inkscape guide"""
+
+ tag_name = "sodipodi:guide"
+
+ @property
+ def orientation(self) -> Vector2d:
+ """Vector normal to the guide
+
+ .. versionadded:: 1.2"""
+ return Vector2d(self.get("orientation"), fallback=(1, 0))
+
+ is_horizontal = property(
+ lambda self: self.orientation[0] == 0 and self.orientation[1] != 0
+ )
+ is_vertical = property(
+ lambda self: self.orientation[0] != 0 and self.orientation[1] == 0
+ )
+
+ @property
+ def point(self) -> Vector2d:
+ """Position of the guide handle. The y coordinate is flipped and relative
+ to the bottom of the viewbox, this is a remnant of the pre-1.0 coordinate system
+ """
+ return Vector2d(self.get("position"), fallback=(0, 0))
+
+ @classmethod
+ def new(cls, pos_x, pos_y, angle, **attrs):
+ guide = super().new(**attrs)
+ guide.move_to(pos_x, pos_y, angle=angle)
+ return guide
+
+ def move_to(self, pos_x, pos_y, angle=None):
+ """
+ Move this guide to the given x,y position,
+
+ Angle may be a float or integer, which will change the orientation. Alternately,
+ it may be a pair of numbers (tuple) which will set the orientation directly.
+ If not given at all, the orientation remains unchanged.
+ """
+ self.set("position", f"{float(pos_x):g},{float(pos_y):g}")
+ if isinstance(angle, str):
+ if "," not in angle:
+ angle = float(angle)
+
+ if isinstance(angle, (float, int)):
+ # Generate orientation from angle
+ angle = (math.sin(math.radians(angle)), -math.cos(math.radians(angle)))
+
+ if isinstance(angle, (tuple, list)) and len(angle) == 2:
+ angle = ",".join(f"{i:g}" for i in angle)
+
+ if angle is not None:
+ self.set("orientation", angle)
+ return self
+
+ @staticmethod
+ def guides_coincident(guide1, guide2):
+ """Check if two guides defined by (position, orientation) and (opos, oor) look
+ identical (i.e. the position lies on the other guide AND the guide is
+ (anti)parallel to the other guide).
+
+ .. versionadded:: 1.2"""
+ # normalize orientations first
+ orientation = guide1.orientation / guide1.orientation.length
+ oor = guide2.orientation / guide2.orientation.length
+
+ position = guide1.point
+ opos = guide2.point
+
+ return (
+ DirectedLineSegment(
+ position, position + Vector2d(orientation[1], -orientation[0])
+ ).perp_distance(*opos)
+ < 1e-6
+ and abs(abs(orientation[1] * oor[0]) - abs(orientation[0] * oor[1])) < 1e-6
+ )
+
+
+class Metadata(BaseElement):
+ """Inkscape Metadata element"""
+
+ tag_name = "metadata"
+
+
+class ForeignObject(BaseElement):
+ """SVG foreignObject element"""
+
+ tag_name = "foreignObject"
+
+
+class Switch(BaseElement):
+ """A switch element"""
+
+ tag_name = "switch"
+
+
+class Grid(BaseElement):
+ """A namedview grid child"""
+
+ tag_name = "inkscape:grid"
+
+
+class Page(BaseElement):
+ """A namedview page child
+
+ .. versionadded:: 1.2"""
+
+ tag_name = "inkscape:page"
+
+ width = property(lambda self: self.to_dimensionless(self.get("width") or 0))
+ height = property(lambda self: self.to_dimensionless(self.get("height") or 0))
+ x = property(lambda self: self.to_dimensionless(self.get("x") or 0))
+ y = property(lambda self: self.to_dimensionless(self.get("y") or 0))
+
+ @classmethod
+ def new(cls, width, height, x, y):
+ """Creates a new page element in the namedview"""
+ page = super().new()
+ page.move_to(x, y)
+ page.set("width", width)
+ page.set("height", height)
+ return page
+
+ def move_to(self, x, y):
+ """Move this page to the given x,y position"""
+ self.set("position", f"{float(x):g},{float(y):g}")
+ return self
diff --git a/share/extensions/inkex/elements/_parser.py b/share/extensions/inkex/elements/_parser.py
new file mode 100644
index 0000000..0357eec
--- /dev/null
+++ b/share/extensions/inkex/elements/_parser.py
@@ -0,0 +1,118 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2020 Martin Owens <doctormo@gmail.com>
+# Sergei Izmailov <sergei.a.izmailov@gmail.com>
+# Thomas Holder <thomas.holder@schrodinger.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+
+"""Utilities for parsing SVG documents.
+
+.. versionadded:: 1.2
+ Separated out from :py:mod:`inkex.elements._base`"""
+
+from collections import defaultdict
+from typing import DefaultDict, List, Any, Type
+
+from lxml import etree
+
+from ..interfaces.IElement import IBaseElement
+
+from ._utils import splitNS
+from ..utils import errormsg
+from ..localization import inkex_gettext as _
+
+
+class NodeBasedLookup(etree.PythonElementClassLookup):
+ """
+ We choose what kind of Elements we should return for each element, providing useful
+ SVG based API to our extensions system.
+ """
+
+ default: Type[IBaseElement]
+
+ # (ns,tag) -> list(cls) ; ascending priority
+ lookup_table = defaultdict(list) # type: DefaultDict[str, List[Any]]
+
+ @classmethod
+ def register_class(cls, klass):
+ """Register the given class using it's attached tag name"""
+ cls.lookup_table[splitNS(klass.tag_name)].append(klass)
+
+ @classmethod
+ def find_class(cls, xpath):
+ """Find the class for this type of element defined by an xpath
+
+ .. versionadded:: 1.1"""
+ if isinstance(xpath, type):
+ return xpath
+ for kls in cls.lookup_table[splitNS(xpath.split("/")[-1])]:
+ # TODO: We could create a apply the xpath attrs to the test element
+ # to narrow the search, but this does everything we need right now.
+ test_element = kls()
+ if kls.is_class_element(test_element):
+ return kls
+ raise KeyError(f"Could not find svg tag for '{xpath}'")
+
+ def lookup(self, doc, element): # pylint: disable=unused-argument
+ """Lookup called by lxml when assigning elements their object class"""
+ try:
+ for kls in reversed(self.lookup_table[splitNS(element.tag)]):
+ if kls.is_class_element(element): # pylint: disable=protected-access
+ return kls
+ except TypeError:
+ # Handle non-element proxies case
+ # The documentation implies that it's not possible
+ # Didn't found a reliable way to check whether proxy corresponds to element
+ # or not
+ # Look like lxml issue to me.
+ # The troubling element is "<!--Comment-->"
+ return None
+ return NodeBasedLookup.default
+
+
+SVG_PARSER = etree.XMLParser(huge_tree=True, strip_cdata=False, recover=True)
+SVG_PARSER.set_element_class_lookup(NodeBasedLookup())
+
+
+def load_svg(stream):
+ """Load SVG file using the SVG_PARSER"""
+ if (isinstance(stream, str) and stream.lstrip().startswith("<")) or (
+ isinstance(stream, bytes) and stream.lstrip().startswith(b"<")
+ ):
+ parsed = etree.ElementTree(etree.fromstring(stream, parser=SVG_PARSER))
+ else:
+ parsed = etree.parse(stream, parser=SVG_PARSER)
+ if len(SVG_PARSER.error_log) > 0:
+ errormsg(
+ _(
+ "A parsing error occured, which means you are likely working with "
+ "a non-conformant SVG file. The following errors were found:\n"
+ )
+ )
+ for __, element in enumerate(SVG_PARSER.error_log):
+ errormsg(
+ _("{}. Line {}, column {}").format(
+ element.message, element.line, element.column
+ )
+ )
+ errormsg(
+ _(
+ "\nProcessing will continue; however we encourage you to fix your"
+ " file manually."
+ )
+ )
+ return parsed
diff --git a/share/extensions/inkex/elements/_polygons.py b/share/extensions/inkex/elements/_polygons.py
new file mode 100644
index 0000000..4f88a3a
--- /dev/null
+++ b/share/extensions/inkex/elements/_polygons.py
@@ -0,0 +1,507 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2020 Martin Owens <doctormo@gmail.com>
+# Sergei Izmailov <sergei.a.izmailov@gmail.com>
+# Thomas Holder <thomas.holder@schrodinger.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=arguments-differ
+"""
+Interface for all shapes/polygons such as lines, paths, rectangles, circles etc.
+"""
+
+from math import cos, pi, sin
+from typing import Optional, Tuple
+from ..paths import Arc, Curve, Move, Path, ZoneClose
+from ..paths import Line as PathLine
+from ..transforms import Transform, ImmutableVector2d, Vector2d
+from ..bezier import pointdistance
+
+from ._utils import addNS
+from ._base import ShapeElement
+
+
+class PathElementBase(ShapeElement):
+ """Base element for path based shapes"""
+
+ get_path = lambda self: Path(self.get("d"))
+
+ @classmethod
+ def new(cls, path, **attrs):
+ return super().new(d=Path(path), **attrs)
+
+ def set_path(self, path):
+ """Set the given data as a path as the 'd' attribute"""
+ self.set("d", str(Path(path)))
+
+ def apply_transform(self):
+ """Apply the internal transformation to this node and delete"""
+ if "transform" in self.attrib:
+ self.path = self.path.transform(self.transform)
+ self.set("transform", Transform())
+
+ @property
+ def original_path(self):
+ """Returns the original path if this is a LPE, or the path if not"""
+ return Path(self.get("inkscape:original-d", self.path))
+
+ @original_path.setter
+ def original_path(self, path):
+ if addNS("inkscape:original-d") in self.attrib:
+ self.set("inkscape:original-d", str(Path(path)))
+ else:
+ self.path = path
+
+
+class PathElement(PathElementBase):
+ """Provide a useful extension for path elements"""
+
+ tag_name = "path"
+
+ @staticmethod
+ def _arcpath(
+ cx: float,
+ cy: float,
+ rx: float,
+ ry: float,
+ start: float,
+ end: float,
+ arctype: str,
+ ) -> Optional[Path]:
+ """Compute the path for an arc defined by Inkscape-specific attributes.
+
+ For details on arguments, see :func:`arc`.
+
+ .. versionadded:: 1.2"""
+ if abs(rx) < 1e-8 or abs(ry) < 1e-8:
+ return None
+ incr = end - start
+ if incr < 0:
+ incr += 2 * pi
+ numsegs = min(1 + int(incr * 2.0 / pi), 4)
+ incr = incr / numsegs
+
+ computed = Path()
+ computed.append(Move(cos(start), sin(start)))
+ for seg in range(1, numsegs + 1):
+ computed.append(
+ Arc(1, 1, 0, 0, 1, cos(start + seg * incr), sin(start + seg * incr))
+ )
+ if abs(incr * numsegs - 2 * pi) > 1e-8 and (
+ arctype in ("slice", "")
+ ): # slice is default
+ computed.append(PathLine(0, 0))
+ if arctype != "arc":
+ computed.append(ZoneClose())
+ computed.transform(
+ Transform().add_translate(cx, cy).add_scale(rx, ry), inplace=True
+ )
+ return computed.to_relative()
+
+ @classmethod
+ def arc(
+ cls, center, rx, ry=None, arctype="", pathonly=False, **kw
+ ): # pylint: disable=invalid-name
+ """Generates a sodipodi elliptical arc (special type). Also computes the path
+ that Inkscape uses under the hood.
+ All data may be given as parseable strings or using numeric data types.
+
+ Args:
+ center (tuple-like): Coordinates of the star/polygon center as tuple or
+ Vector2d
+ rx (Union[float, str]): Radius in x direction
+ ry (Union[float, str], optional): Radius in y direction. If not given,
+ ry=rx. Defaults to None.
+ arctype (str, optional): "arc", "chord" or "slice". Defaults to "", i.e.
+ "slice".
+
+ .. versionadded:: 1.2
+ Previously set to "arc" as fixed value
+ pathonly (bool, optional): Whether to create the path without
+ Inkscape-specific attributes. Defaults to False.
+
+ .. versionadded:: 1.2
+ Keyword args:
+ start (Union[float, str]): start angle in radians
+ end (Union[float, str]): end angle in radians
+ open (str): whether the path should be open (true/false). Not used in
+ Inkscape > 1.1
+
+ Returns:
+ PathElement : the created star/polygon
+ """
+ others = [(name, kw.pop(name, None)) for name in ("start", "end", "open")]
+ elem = cls(**kw)
+ elem.set("sodipodi:cx", center[0])
+ elem.set("sodipodi:cy", center[1])
+ elem.set("sodipodi:rx", rx)
+ elem.set("sodipodi:ry", ry or rx)
+ elem.set("sodipodi:type", "arc")
+ if arctype != "":
+ elem.set("sodipodi:arc-type", arctype)
+ for name, value in others:
+ if value is not None:
+ elem.set("sodipodi:" + name, str(value).lower())
+
+ path = cls._arcpath(
+ float(center[0]),
+ float(center[1]),
+ float(rx),
+ float(ry or rx),
+ float(elem.get("sodipodi:start", 0)),
+ float(elem.get("sodipodi:end", 2 * pi)),
+ arctype,
+ )
+ if pathonly:
+ elem = cls(**kw)
+ if path is not None:
+ elem.path = path
+ return elem
+
+ @staticmethod
+ def _starpath(
+ c: Tuple[float, float],
+ sides: int,
+ r: Tuple[float, float], # pylint: disable=invalid-name
+ arg: Tuple[float, float],
+ rounded: float,
+ flatsided: bool,
+ ):
+ """Helper method to generate the path for an Inkscape star/ polygon; randomized
+ is ignored.
+
+ For details on arguments, see :func:`star`.
+
+ .. versionadded:: 1.2"""
+
+ def _star_get_xy(point, index):
+ cur_arg = arg[point] + 2 * pi / sides * (index % sides)
+ return Vector2d(*c) + r[point] * Vector2d(cos(cur_arg), sin(cur_arg))
+
+ def _rot90_rel(origin, other):
+ """Returns a unit length vector at 90 deg from origin to other"""
+ return (
+ 1
+ / pointdistance(other, origin)
+ * Vector2d(other.y - origin.y, other.x - origin.x)
+ )
+
+ def _star_get_curvepoint(point, index, is_prev: bool):
+ index = index % sides
+ orig = _star_get_xy(point, index)
+ previ = (index - 1 + sides) % sides
+ nexti = (index + 1) % sides
+ # neighbors of the current point depend on polygon or star
+ prev = (
+ _star_get_xy(point, previ)
+ if flatsided
+ else _star_get_xy(1 - point, index if point == 1 else previ)
+ )
+ nextp = (
+ _star_get_xy(point, nexti)
+ if flatsided
+ else _star_get_xy(1 - point, index if point == 0 else nexti)
+ )
+ mid = 0.5 * (prev + nextp)
+ # direction of bezier handles
+ rot = _rot90_rel(orig, mid + 100000 * _rot90_rel(mid, nextp))
+ ret = (
+ rounded
+ * rot
+ * (
+ -1 * pointdistance(prev, orig)
+ if is_prev
+ else pointdistance(nextp, orig)
+ )
+ )
+ return orig + ret
+
+ pointy = abs(rounded) < 1e-4
+ result = Path()
+ result.append(Move(*_star_get_xy(0, 0)))
+ for i in range(0, sides):
+ # draw to point type 1 for stars
+ if not flatsided:
+ if pointy:
+ result.append(PathLine(*_star_get_xy(1, i)))
+ else:
+ result.append(
+ Curve(
+ *_star_get_curvepoint(0, i, False),
+ *_star_get_curvepoint(1, i, True),
+ *_star_get_xy(1, i),
+ )
+ )
+ # draw to point type 0 for both stars and rectangles
+ if pointy and i < sides - 1:
+ result.append(PathLine(*_star_get_xy(0, i + 1)))
+ if not pointy:
+ if not flatsided:
+ result.append(
+ Curve(
+ *_star_get_curvepoint(1, i, False),
+ *_star_get_curvepoint(0, i + 1, True),
+ *_star_get_xy(0, i + 1),
+ )
+ )
+ else:
+ result.append(
+ Curve(
+ *_star_get_curvepoint(0, i, False),
+ *_star_get_curvepoint(0, i + 1, True),
+ *_star_get_xy(0, i + 1),
+ )
+ )
+
+ result.append(ZoneClose())
+ return result.to_relative()
+
+ @classmethod
+ def star(
+ cls,
+ center,
+ radii,
+ sides=5,
+ rounded=0,
+ args=(0, 0),
+ flatsided=False,
+ pathonly=False,
+ ):
+ """Generate a sodipodi star / polygon. Also computes the path that Inkscape uses
+ under the hood. The arguments for center, radii, sides, rounded and args can be
+ given as strings or as numeric data.
+
+ .. versionadded:: 1.1
+
+ Args:
+ center (Tuple-like): Coordinates of the star/polygon center as tuple or
+ Vector2d
+ radii (tuple): Radii of the control points, i.e. their distances from the
+ center. The control points are specified in polar coordinates. Only the
+ first control point is used for polygons.
+ sides (int, optional): Number of sides / tips of the polygon / star.
+ Defaults to 5.
+ rounded (int, optional): Controls the rounding radius of the polygon / star.
+ For `rounded=0`, only straight lines are used. Defaults to 0.
+ args (tuple, optional): Angle between horizontal axis and control points.
+ Defaults to (0,0).
+
+ .. versionadded:: 1.2
+ Previously fixed to (0.85, 1.3)
+ flatsided (bool, optional): True for polygons, False for stars.
+ Defaults to False.
+
+ .. versionadded:: 1.2
+ pathonly (bool, optional): Whether to create the path without
+ Inkscape-specific attributes. Defaults to False.
+
+ .. versionadded:: 1.2
+
+ Returns:
+ PathElement : the created star/polygon
+ """
+ elem = cls()
+ elem.set("sodipodi:cx", center[0])
+ elem.set("sodipodi:cy", center[1])
+ elem.set("sodipodi:r1", radii[0])
+ elem.set("sodipodi:r2", radii[1])
+ elem.set("sodipodi:arg1", args[0])
+ elem.set("sodipodi:arg2", args[1])
+ elem.set("sodipodi:sides", max(sides, 3) if flatsided else max(sides, 2))
+ elem.set("inkscape:rounded", rounded)
+ elem.set("inkscape:flatsided", str(flatsided).lower())
+ elem.set("sodipodi:type", "star")
+
+ path = cls._starpath(
+ (float(center[0]), float(center[1])),
+ int(sides),
+ (float(radii[0]), float(radii[1])),
+ (float(args[0]), float(args[1])),
+ float(rounded),
+ flatsided,
+ )
+ if pathonly:
+ elem = cls()
+ # inkex.errormsg(path)
+ if path is not None:
+ elem.path = path
+
+ return elem
+
+
+class Polyline(ShapeElement):
+ """Like a path, but made up of straight line segments only"""
+
+ tag_name = "polyline"
+
+ def get_path(self):
+ return Path("M" + self.get("points"))
+
+ def set_path(self, path):
+ points = [f"{x:g},{y:g}" for x, y in Path(path).end_points]
+ self.set("points", " ".join(points))
+
+
+class Polygon(ShapeElement):
+ """A closed polyline"""
+
+ tag_name = "polygon"
+ get_path = lambda self: Path("M" + self.get("points") + " Z")
+
+
+class Line(ShapeElement):
+ """A line segment connecting two points"""
+
+ tag_name = "line"
+ x1 = property(lambda self: self.to_dimensionless(self.get("x1", 0)))
+ y1 = property(lambda self: self.to_dimensionless(self.get("y1", 0)))
+ x2 = property(lambda self: self.to_dimensionless(self.get("x2", 0)))
+ y2 = property(lambda self: self.to_dimensionless(self.get("y2", 0)))
+ get_path = lambda self: Path(f"M{self.x1},{self.y1} L{self.x2},{self.y2}")
+
+ @classmethod
+ def new(cls, start, end, **attrs):
+ start = Vector2d(start)
+ end = Vector2d(end)
+ return super().new(x1=start.x, y1=start.y, x2=end.x, y2=end.y, **attrs)
+
+
+class RectangleBase(ShapeElement):
+ """Provide a useful extension for rectangle elements"""
+
+ left = property(lambda self: self.to_dimensionless(self.get("x", "0")))
+ top = property(lambda self: self.to_dimensionless(self.get("y", "0")))
+ right = property(lambda self: self.left + self.width)
+ bottom = property(lambda self: self.top + self.height)
+ width = property(lambda self: self.to_dimensionless(self.get("width", "0")))
+ height = property(lambda self: self.to_dimensionless(self.get("height", "0")))
+ rx = property(
+ lambda self: self.to_dimensionless(self.get("rx", self.get("ry", 0.0)))
+ )
+ ry = property(
+ lambda self: self.to_dimensionless(self.get("ry", self.get("rx", 0.0)))
+ ) # pylint: disable=invalid-name
+
+ def get_path(self):
+ """Calculate the path as the box around the rect"""
+ if self.rx:
+ rx, ry = self.rx, self.ry # pylint: disable=invalid-name
+ cpts = [self.left + rx, self.right - rx, self.top + ry, self.bottom - ry]
+ return (
+ f"M {cpts[0]},{self.top}"
+ f"L {cpts[1]},{self.top} "
+ f"A {self.rx},{self.ry} 0 0 1 {self.right},{cpts[2]}"
+ f"L {self.right},{cpts[3]} "
+ f"A {self.rx},{self.ry} 0 0 1 {cpts[1]},{self.bottom}"
+ f"L {cpts[0]},{self.bottom} "
+ f"A {self.rx},{self.ry} 0 0 1 {self.left},{cpts[3]}"
+ f"L {self.left},{cpts[2]} "
+ f"A {self.rx},{self.ry} 0 0 1 {cpts[0]},{self.top} z"
+ )
+
+ return f"M {self.left},{self.top} h{self.width}v{self.height}h{-self.width} z"
+
+
+class Rectangle(RectangleBase):
+ """Provide a useful extension for rectangle elements"""
+
+ tag_name = "rect"
+
+ @classmethod
+ def new(cls, left, top, width, height, **attrs):
+ return super().new(x=left, y=top, width=width, height=height, **attrs)
+
+
+class EllipseBase(ShapeElement):
+ """Absorbs common part of Circle and Ellipse classes"""
+
+ def get_path(self):
+ """Calculate the arc path of this circle"""
+ rx, ry = self._rxry()
+ cx, y = self.center.x, self.center.y - ry
+ return (
+ "M {cx},{y} "
+ "a {rx},{ry} 0 1 0 {rx}, {ry} "
+ "a {rx},{ry} 0 0 0 -{rx}, -{ry} z"
+ ).format(cx=cx, y=y, rx=rx, ry=ry)
+
+ @property
+ def center(self):
+ """Return center of circle/ellipse"""
+ return ImmutableVector2d(
+ self.to_dimensionless(self.get("cx", "0")),
+ self.to_dimensionless(self.get("cy", "0")),
+ )
+
+ @center.setter
+ def center(self, value):
+ value = Vector2d(value)
+ self.set("cx", value.x)
+ self.set("cy", value.y)
+
+ def _rxry(self):
+ # type: () -> Vector2d
+ """Helper function"""
+ raise NotImplementedError()
+
+ @classmethod
+ def new(cls, center, radius, **attrs):
+ circle = super().new(**attrs)
+ circle.center = center
+ circle.radius = radius
+ return circle
+
+
+class Circle(EllipseBase):
+ """Provide a useful extension for circle elements"""
+
+ tag_name = "circle"
+
+ @property
+ def radius(self) -> float:
+ """Return radius of circle"""
+ return self.to_dimensionless(self.get("r", "0"))
+
+ @radius.setter
+ def radius(self, value):
+ self.set("r", self.to_dimensionless(value))
+
+ def _rxry(self):
+ r = self.radius
+ return Vector2d(r, r)
+
+
+class Ellipse(EllipseBase):
+ """Provide a similar extension to the Circle interface for ellipses"""
+
+ tag_name = "ellipse"
+
+ @property
+ def radius(self) -> ImmutableVector2d:
+ """Return radii of ellipse"""
+ return ImmutableVector2d(
+ self.to_dimensionless(self.get("rx", "0")),
+ self.to_dimensionless(self.get("ry", "0")),
+ )
+
+ @radius.setter
+ def radius(self, value):
+ value = Vector2d(value)
+ self.set("rx", str(value.x))
+ self.set("ry", str(value.y))
+
+ def _rxry(self):
+ return self.radius
diff --git a/share/extensions/inkex/elements/_selected.py b/share/extensions/inkex/elements/_selected.py
new file mode 100644
index 0000000..9f23e59
--- /dev/null
+++ b/share/extensions/inkex/elements/_selected.py
@@ -0,0 +1,237 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2020 Martin Owens <doctormo@gmail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc.,Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+When elements are selected, these structures provide an advanced API.
+
+.. versionadded:: 1.1
+"""
+
+from collections import OrderedDict
+from typing import Any, overload, Union, Optional
+
+from ..interfaces.IElement import IBaseElement
+from ._utils import natural_sort_key
+from ..localization import inkex_gettext
+from ..utils import AbortExtension
+
+
+class ElementList(OrderedDict):
+ """
+ A list of elements, selected by id, iterator or xpath
+
+ This may look like a dictionary, but it is really a list of elements.
+ The default iterator is the element objects themselves (not keys) and it is
+ possible to key elements by their numerical index.
+
+ It is also possible to look up items by their id and the element object itself.
+ """
+
+ def __init__(self, svg, _iter=None):
+ self.svg = svg
+ self.ids = OrderedDict()
+ super().__init__()
+ if _iter is not None:
+ self.set(*list(_iter))
+
+ def __iter__(self):
+ return self.values().__iter__()
+
+ def __getitem__(self, key):
+ return super().__getitem__(self._to_key(key))
+
+ def __contains__(self, key):
+ return super().__contains__(self._to_key(key))
+
+ def __setitem__(self, orig_key, elem):
+
+ if orig_key != elem and orig_key != elem.get("id"):
+ raise ValueError(f"Refusing to set bad key in ElementList {orig_key}")
+ if isinstance(elem, str):
+ key = elem
+ elem = self.svg.getElementById(elem, literal=True)
+ if elem is None:
+ return
+ if isinstance(elem, IBaseElement):
+ # Selection is a list of elements to select
+ key = elem.xml_path
+ element_id = elem.get("id")
+ if element_id is not None:
+ self.ids[element_id] = key
+ super().__setitem__(key, elem)
+ else:
+ kind = type(elem).__name__
+ raise ValueError(f"Unknown element type: {kind}")
+
+ @overload
+ def _to_key(self, key: None, default: Any) -> Any:
+ ...
+
+ @overload
+ def _to_key(self, key: Union[int, IBaseElement, str], default: Any) -> str:
+ ...
+
+ def _to_key(self, key, default=None) -> str:
+ """Takes a key (id, element, etc) and returns an xml_path key"""
+
+ if self and key is None:
+ key = default
+ if isinstance(key, int):
+ return list(self.keys())[key]
+ if isinstance(key, IBaseElement):
+ return key.xml_path
+ if isinstance(key, str) and key[0] != "/":
+ return self.ids.get(key, key)
+ return key
+
+ def clear(self):
+ """Also clear ids"""
+ self.ids.clear()
+ super().clear()
+
+ def set(self, *ids):
+ """
+ Sets the currently selected elements to these ids, any existing
+ selection is cleared.
+
+ Arguments a list of element ids, element objects or
+ a single xpath expression starting with ``//``.
+
+ All element objects must have an id to be correctly set.
+
+ >>> selection.set("rect123", "path456", "text789")
+ >>> selection.set(elem1, elem2, elem3)
+ >>> selection.set("//rect")
+ """
+ self.clear()
+ self.add(*ids)
+
+ def pop(self, key=None):
+ """Remove the key item or remove the last item selected"""
+ item = super().pop(self._to_key(key, default=-1))
+ self.ids.pop(item.get("id"))
+ return item
+
+ def add(self, *ids):
+ """Like set() but does not clear first"""
+ # Allow selecting of xpath elements directly
+ if len(ids) == 1 and isinstance(ids[0], str) and ids[0].startswith("//"):
+ ids = self.svg.xpath(ids[0])
+
+ for elem in ids:
+ self[elem] = elem # This doesn't matter
+
+ def rendering_order(self):
+ """Get the selected elements by z-order (stacking order), ordered from bottom to
+ top
+
+ .. versionadded:: 1.2
+ :func:`paint_order` has been renamed to :func:`rendering_order`"""
+ new_list = ElementList(self.svg)
+ # the elements are stored with their xpath index, so a natural sort order
+ # '3' < '20' < '100' has to be applied
+ new_list.set(
+ *[
+ elem
+ for _, elem in sorted(
+ self.items(), key=lambda x: natural_sort_key(x[0])
+ )
+ ]
+ )
+ return new_list
+
+ def filter(self, *types):
+ """Filter selected elements of the given type, returns a new SelectedElements
+ object"""
+ return ElementList(
+ self.svg, [e for e in self if not types or isinstance(e, types)]
+ )
+
+ def filter_nonzero(self, *types, error_msg: Optional[str] = None):
+ """Filter selected elements of the given type, returns a new SelectedElements
+ object. If the selection is empty, abort the extension.
+
+ .. versionadded:: 1.2
+
+ :param error_msg: e
+ :type error_msg: str, optional
+
+ Args:
+ *types (Type) : type(s) to filter the selection by
+ error_msg (str, optional): error message that is displayed if the selection
+ is empty, defaults to
+ ``_("Please select at least one element of type(s) {}")``.
+ Defaults to None.
+
+ Raises:
+ AbortExtension: if the selection is empty
+
+ Returns:
+ ElementList: filtered selection
+ """
+ filtered = self.filter(*types)
+ if not filtered:
+ if error_msg is None:
+ error_msg = inkex_gettext(
+ "Please select at least one element of the following type(s): {}"
+ ).format(", ".join([type.__name__ for type in types]))
+ raise AbortExtension(error_msg)
+ return filtered
+
+ def get(self, *types):
+ """Like filter, but will enter each element searching for any child of the given
+ types"""
+
+ def _recurse(elem):
+ if not types or isinstance(elem, types):
+ yield elem
+ for child in elem:
+ yield from _recurse(child)
+
+ return ElementList(
+ self.svg,
+ [
+ r
+ for e in self
+ for r in _recurse(e)
+ if isinstance(r, (IBaseElement, str))
+ ],
+ )
+
+ def id_dict(self):
+ """For compatibility, return regular dictionary of id -> element pairs"""
+ return {eid: self[xid] for eid, xid in self.ids.items()}
+
+ def bounding_box(self):
+ """
+ Gets a :class:`inkex.transforms.BoundingBox` object for the selected items.
+
+ Text objects have a bounding box without width or height that only
+ reflects the coordinate of their anchor. If a text object is a part of
+ the selection's boundary, the bounding box may be inaccurate.
+
+ When no object is selected or when the object's location cannot be
+ determined (e.g. empty group or layer), all coordinates will be None.
+ """
+ return sum([elem.bounding_box() for elem in self], None)
+
+ def first(self):
+ """Returns the first item in the selected list"""
+ for elem in self:
+ return elem
+ return None
diff --git a/share/extensions/inkex/elements/_svg.py b/share/extensions/inkex/elements/_svg.py
new file mode 100644
index 0000000..00228b1
--- /dev/null
+++ b/share/extensions/inkex/elements/_svg.py
@@ -0,0 +1,371 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2020 Martin Owens <doctormo@gmail.com>
+# Thomas Holder <thomas.holder@schrodinger.com>
+# Sergei Izmailov <sergei.a.izmailov@gmail.com>
+# Windell Oskay <windell@oskay.net>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=attribute-defined-outside-init
+#
+"""
+Provide a way to load lxml attributes with an svg API on top.
+"""
+
+import random
+import math
+import re
+
+from lxml import etree
+
+from ..css import ConditionalRule
+from ..interfaces.IElement import ISVGDocumentElement
+
+from ..deprecated.meta import DeprecatedSvgMixin, deprecate
+from ..units import discover_unit, parse_unit
+from ._selected import ElementList
+from ..transforms import BoundingBox
+from ..styles import StyleSheets
+
+from ._base import BaseElement
+from ._meta import StyleElement
+
+from typing import Optional, List
+
+if False: # pylint: disable=using-constant-test
+ import typing # pylint: disable=unused-import
+
+
+class SvgDocumentElement(DeprecatedSvgMixin, ISVGDocumentElement, BaseElement):
+ """Provide access to the document level svg functionality"""
+
+ # pylint: disable=too-many-public-methods
+ tag_name = "svg"
+
+ selection: ElementList
+ """The selection as passed by Inkscape (readonly)"""
+
+ def _init(self):
+ self.current_layer = None
+ self.view_center = (0.0, 0.0)
+ self.selection = ElementList(self)
+ self.ids = {}
+
+ def tostring(self):
+ """Convert document to string"""
+ return etree.tostring(etree.ElementTree(self))
+
+ def get_ids(self):
+ """Returns a set of unique document ids"""
+ if not self.ids:
+ self.ids = set(self.xpath("//@id"))
+ return self.ids
+
+ def get_unique_id(
+ self,
+ prefix: str,
+ size: Optional[int] = None,
+ blacklist: Optional[List[str]] = None,
+ ):
+ """Generate a new id from an existing old_id
+
+ The id consists of a prefix and an appended random integer with size digits.
+
+ If size is not given, it is determined automatically from the length of
+ existing ids, i.e. those in the document plus those in the blacklist.
+
+ Args:
+ prefix (str): the prefix of the new ID.
+ size (Optional[int], optional): number of digits of the second part of the
+ id. If None, the length is chosen based on the amount of existing
+ objects. Defaults to None.
+
+ .. versionchanged:: 1.1
+ The default of this parameter has been changed from 4 to None.
+ blacklist (Optional[Iterable[str]], optional): An additional iterable of ids
+ that are not allowed to be used. This is useful when bulk inserting
+ objects.
+ Defaults to None.
+
+ .. versionadded:: 1.2
+
+ Returns:
+ _type_: _description_
+ """
+ ids = self.get_ids()
+ if size is None:
+ size = max(math.ceil(math.log10(len(ids) or 1000)) + 1, 4)
+ if blacklist is not None:
+ ids.update(blacklist)
+ new_id = None
+ _from = 10**size - 1
+ _to = 10**size
+ while new_id is None or new_id in ids:
+ # Do not use randint because py2/3 incompatibility
+ new_id = prefix + str(int(random.random() * _from - _to) + _to)
+ self.ids.add(new_id)
+ return new_id
+
+ def get_page_bbox(self):
+ """Gets the page dimensions as a bbox"""
+ return BoundingBox(
+ (0, float(self.viewbox_width)), (0, float(self.viewbox_height))
+ )
+
+ def get_current_layer(self):
+ """Returns the currently selected layer"""
+ layer = self.getElementById(self.namedview.current_layer, "svg:g")
+ if layer is None:
+ return self
+ return layer
+
+ def getElement(self, xpath): # pylint: disable=invalid-name
+ """Gets a single element from the given xpath or returns None"""
+ return self.findone(xpath)
+
+ def getElementById(
+ self, eid: str, elm="*", literal=False
+ ): # pylint: disable=invalid-name
+ """Get an element in this svg document by it's ID attribute.
+
+ Args:
+ eid (str): element id
+ elm (str, optional): element type, including namespace, e.g. ``svg:path``.
+ Defaults to "*".
+ literal (bool, optional): If ``False``, ``#url()`` is stripped from ``eid``.
+ Defaults to False.
+
+ .. versionadded:: 1.1
+
+ Returns:
+ Union[BaseElement, None]: found element
+ """
+ if eid is not None and not literal:
+ eid = eid.strip()[4:-1] if eid.startswith("url(") else eid
+ eid = eid.lstrip("#")
+ return self.getElement(f'//{elm}[@id="{eid}"]')
+
+ def getElementByName(self, name, elm="*"): # pylint: disable=invalid-name
+ """Get an element by it's inkscape:label (aka name)"""
+ return self.getElement(f'//{elm}[@inkscape:label="{name}"]')
+
+ def getElementsByClass(self, class_name): # pylint: disable=invalid-name
+ """Get elements by it's class name"""
+
+ return self.xpath(ConditionalRule(f".{class_name}").to_xpath())
+
+ def getElementsByHref(
+ self, eid: str, attribute="xlink:href"
+ ): # pylint: disable=invalid-name
+ """Get elements that reference the element with id eid.
+
+ Args:
+ eid (str): _description_
+ attribute (str, optional): Attribute to look for.
+ Valid choices: "xlink:href", "mask", "clip-path".
+ Defaults to "xlink:href".
+
+ .. versionadded:: 1.2
+
+ Returns:
+ Any: list of elements
+ """
+ if attribute == "xlink:href":
+ return self.xpath(f'//*[@xlink:href="#{eid}"]')
+ elif attribute == "mask":
+ return self.xpath(f'//*[@mask="url(#{eid})"]')
+ elif attribute == "clip-path":
+ return self.xpath(f'//*[@clip-path="url(#{eid})"]')
+
+ def getElementsByStyleUrl(self, eid, style=None): # pylint: disable=invalid-name
+ """Get elements by a style attribute url"""
+ url = f"url(#{eid})"
+ if style is not None:
+ url = style + ":" + url
+ return self.xpath(f'//*[contains(@style,"{url}")]')
+
+ @property
+ def name(self):
+ """Returns the Document Name"""
+ return self.get("sodipodi:docname", "")
+
+ @property
+ def namedview(self):
+ """Return the sp namedview meta information element"""
+ return self.get_or_create("//sodipodi:namedview", prepend=True)
+
+ @property
+ def metadata(self):
+ """Return the svg metadata meta element container"""
+ return self.get_or_create("//svg:metadata", prepend=True)
+
+ @property
+ def defs(self):
+ """Return the svg defs meta element container"""
+ return self.get_or_create("//svg:defs", prepend=True)
+
+ def get_viewbox(self):
+ """Parse and return the document's viewBox attribute"""
+ try:
+ ret = [
+ float(unit) for unit in re.split(r",\s*|\s+", self.get("viewBox", "0"))
+ ]
+ except ValueError:
+ ret = ""
+ if len(ret) != 4:
+ return [0, 0, 0, 0]
+ return ret
+
+ @property
+ def viewbox_width(self) -> float: # getDocumentWidth(self):
+ """Returns the width of the `user coordinate system
+ <https://www.w3.org/TR/SVG2/coords.html#Introduction>`_ in user units, i.e.
+ the width of the viewbox, as defined in the SVG file. If no viewbox is defined,
+ the value of the width attribute is returned. If the height is not defined,
+ returns 0.
+
+ .. versionadded:: 1.2"""
+ return self.get_viewbox()[2] or self.viewport_width
+
+ @property
+ def viewport_width(self) -> float:
+ """Returns the width of the `viewport coordinate system
+ <https://www.w3.org/TR/SVG2/coords.html#Introduction>`_ in user units, i.e. the
+ width attribute of the svg element converted to px
+
+ .. versionadded:: 1.2"""
+ return self.to_dimensionless(self.get("width")) or self.get_viewbox()[2]
+
+ @property
+ def viewbox_height(self) -> float: # getDocumentHeight(self):
+ """Returns the height of the `user coordinate system
+ <https://www.w3.org/TR/SVG2/coords.html#Introduction>`_ in user units, i.e. the
+ height of the viewbox, as defined in the SVG file. If no viewbox is defined, the
+ value of the height attribute is returned. If the height is not defined,
+ returns 0.
+
+ .. versionadded:: 1.2"""
+ return self.get_viewbox()[3] or self.viewport_height
+
+ @property
+ def viewport_height(self) -> float:
+ """Returns the width of the `viewport coordinate system
+ <https://www.w3.org/TR/SVG2/coords.html#Introduction>`_ in user units, i.e. the
+ height attribute of the svg element converted to px
+
+ .. versionadded:: 1.2"""
+ return self.to_dimensionless(self.get("height")) or self.get_viewbox()[3]
+
+ @property
+ def scale(self):
+ """Returns the ratio between the viewBox width and the page width.
+
+ .. versionchanged:: 1.2
+ Previously, the scale as shown by the document properties was computed,
+ but the computation of this in core Inkscape changed in Inkscape 1.2, so
+ this was moved to :attr:`inkscape_scale`."""
+ return self._base_scale()
+
+ @property
+ def inkscape_scale(self):
+ """Returns the ratio between the viewBox width (in width/height units) and the
+ page width, which is displayed as "scale" in the Inkscape document
+ properties.
+
+ .. versionadded:: 1.2"""
+
+ viewbox_unit = (
+ parse_unit(self.get("width")) or parse_unit(self.get("height")) or (0, "px")
+ )[1]
+ return self._base_scale(viewbox_unit)
+
+ def _base_scale(self, unit="px"):
+ """Returns what Inkscape shows as "user units per `unit`"
+
+ .. versionadded:: 1.2"""
+ try:
+ scale_x = (
+ self.to_dimensional(self.viewport_width, unit) / self.viewbox_width
+ )
+ scale_y = (
+ self.to_dimensional(self.viewport_height, unit) / self.viewbox_height
+ )
+ value = max([scale_x, scale_y])
+ return 1.0 if value == 0 else value
+ except (ValueError, ZeroDivisionError):
+ return 1.0
+
+ @property
+ def equivalent_transform_scale(self) -> float:
+ """Return the scale of the equivalent transform of the svg tag, as defined by
+ https://www.w3.org/TR/SVG2/coords.html#ComputingAViewportsTransform
+ (highly simplified)
+
+ .. versionadded:: 1.2"""
+ return self.scale
+
+ @property
+ def unit(self):
+ """Returns the unit used for in the SVG document.
+ In the case the SVG document lacks an attribute that explicitly
+ defines what units are used for SVG coordinates, it tries to calculate
+ the unit from the SVG width and viewBox attributes.
+ Defaults to 'px' units."""
+ if not hasattr(self, "_unit"):
+ self._unit = "px" # Default is px
+ viewbox = self.get_viewbox()
+ if viewbox and set(viewbox) != {0}:
+ self._unit = discover_unit(self.get("width"), viewbox[2], default="px")
+ return self._unit
+
+ @property
+ def document_unit(self):
+ """Returns the display unit (Inkscape-specific attribute) of the document
+
+ .. versionadded:: 1.2"""
+ return self.namedview.get("inkscape:document-units", "px")
+
+ @property
+ def stylesheets(self):
+ """Get all the stylesheets, bound together to one, (for reading)"""
+ sheets = StyleSheets(self)
+ for node in self.xpath("//svg:style"):
+ sheets.append(node.stylesheet())
+ return sheets
+
+ @property
+ def stylesheet(self):
+ """Return the first stylesheet or create one if needed (for writing)"""
+ for sheet in self.stylesheets:
+ return sheet
+
+ style_node = StyleElement()
+ self.defs.append(style_node)
+ return style_node.stylesheet()
+
+
+def width(self):
+ """Use :func:`viewport_width` instead"""
+ return self.viewport_width
+
+
+def height(self):
+ """Use :func:`viewport_height` instead"""
+ return self.viewport_height
+
+
+SvgDocumentElement.width = property(deprecate(width, "1.2"))
+SvgDocumentElement.height = property(deprecate(height, "1.2"))
diff --git a/share/extensions/inkex/elements/_text.py b/share/extensions/inkex/elements/_text.py
new file mode 100644
index 0000000..8fc1756
--- /dev/null
+++ b/share/extensions/inkex/elements/_text.py
@@ -0,0 +1,202 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2020 Martin Owens <doctormo@gmail.com>
+# Thomas Holder <thomas.holder@schrodinger.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=arguments-differ
+"""
+Provide text based element classes interface.
+
+Because text is not rendered at all, no information about a text's path
+size or actual location can be generated yet.
+"""
+from __future__ import annotations
+
+from tempfile import TemporaryDirectory
+
+from ..interfaces.IElement import BaseElementProtocol
+from ..paths import Path
+from ..transforms import Transform, BoundingBox
+from ..command import inkscape, write_svg
+from ._base import BaseElement, ShapeElement
+from ._polygons import PathElementBase
+
+
+class TextBBMixin: # pylint: disable=too-few-public-methods
+ """Mixin to query the bounding box from Inkscape
+
+ .. versionadded:: 1.2"""
+
+ def get_inkscape_bbox(self: BaseElementProtocol) -> BoundingBox:
+ """Query the bbbox of a single object. This calls the Inkscape command,
+ so it is rather slow to use in a loop."""
+ with TemporaryDirectory(prefix="inkscape-command") as tmpdir:
+ svg_file = write_svg(self.root, tmpdir, "input.svg")
+ out = inkscape(svg_file, "-X", "-Y", "-W", "-H", query_id=self.get_id())
+ out = list(map(self.root.viewport_to_unit, out.splitlines()))
+ if len(out) != 4:
+ raise ValueError("Error: Bounding box computation failed")
+ return BoundingBox.new_xywh(*out)
+
+
+class FlowRegion(ShapeElement):
+ """SVG Flow Region (SVG 2.0)"""
+
+ tag_name = "flowRegion"
+
+ def get_path(self):
+ # This ignores flowRegionExcludes
+ return sum([child.path for child in self], Path())
+
+
+class FlowRoot(ShapeElement, TextBBMixin):
+ """SVG Flow Root (SVG 2.0)"""
+
+ tag_name = "flowRoot"
+
+ @property
+ def region(self):
+ """Return the first flowRegion in this flowRoot"""
+ return self.findone("svg:flowRegion")
+
+ def get_path(self):
+ region = self.region
+ return region.get_path() if region is not None else Path()
+
+
+class FlowPara(ShapeElement):
+ """SVG Flow Paragraph (SVG 2.0)"""
+
+ tag_name = "flowPara"
+
+ def get_path(self):
+ # XXX: These empty paths mean the bbox for text elements will be nothing.
+ return Path()
+
+
+class FlowDiv(ShapeElement):
+ """SVG Flow Div (SVG 2.0)"""
+
+ tag_name = "flowDiv"
+
+ def get_path(self):
+ # XXX: These empty paths mean the bbox for text elements will be nothing.
+ return Path()
+
+
+class FlowSpan(ShapeElement):
+ """SVG Flow Span (SVG 2.0)"""
+
+ tag_name = "flowSpan"
+
+ def get_path(self):
+ # XXX: These empty paths mean the bbox for text elements will be nothing.
+ return Path()
+
+
+class TextElement(ShapeElement, TextBBMixin):
+ """A Text element"""
+
+ tag_name = "text"
+ x = property(lambda self: self.to_dimensionless(self.get("x", 0)))
+ y = property(lambda self: self.to_dimensionless(self.get("y", 0)))
+
+ def get_path(self):
+ return Path()
+
+ def tspans(self):
+ """Returns all children that are tspan elements"""
+ return self.findall("svg:tspan")
+
+ def get_text(self, sep="\n"):
+ """Return the text content including tspans"""
+ nodes = [self] + list(self.tspans())
+ return sep.join([elem.text for elem in nodes if elem.text is not None])
+
+ def shape_box(self, transform=None):
+ """
+ Returns a horrible bounding box that just contains the coord points
+ of the text without width or height (which is impossible to calculate)
+ """
+ effective_transform = Transform(transform) @ self.transform
+ x, y = effective_transform.apply_to_point((self.x, self.y))
+ bbox = BoundingBox(x, y)
+ for tspan in self.tspans():
+ bbox += tspan.bounding_box(effective_transform)
+ return bbox
+
+
+class TextPath(ShapeElement, TextBBMixin):
+ """A textPath element"""
+
+ tag_name = "textPath"
+
+ def get_path(self):
+ return Path()
+
+
+class Tspan(ShapeElement, TextBBMixin):
+ """A tspan text element"""
+
+ tag_name = "tspan"
+ x = property(lambda self: self.to_dimensionless(self.get("x", 0)))
+ y = property(lambda self: self.to_dimensionless(self.get("y", 0)))
+
+ @classmethod
+ def superscript(cls, text):
+ """Adds a superscript tspan element"""
+ return cls(text, style="font-size:65%;baseline-shift:super")
+
+ def get_path(self):
+ return Path()
+
+ def shape_box(self, transform=None):
+ """
+ Returns a horrible bounding box that just contains the coord points
+ of the text without width or height (which is impossible to calculate)
+ """
+ effective_transform = Transform(transform) @ self.transform
+ x1, y1 = effective_transform.apply_to_point((self.x, self.y))
+ fontsize = self.to_dimensionless(self.style.get("font-size", "12px"))
+ x2 = self.x + 0 # XXX This is impossible to calculate!
+ y2 = self.y + float(fontsize)
+ x2, y2 = effective_transform.apply_to_point((x2, y2))
+ return BoundingBox((x1, x2), (y1, y2))
+
+
+class SVGfont(BaseElement):
+ """An svg font element"""
+
+ tag_name = "font"
+
+
+class FontFace(BaseElement):
+ """An svg font font-face element"""
+
+ tag_name = "font-face"
+
+
+class Glyph(PathElementBase):
+ """An svg font glyph element"""
+
+ tag_name = "glyph"
+
+
+class MissingGlyph(BaseElement):
+ """An svg font missing-glyph element"""
+
+ tag_name = "missing-glyph"
diff --git a/share/extensions/inkex/elements/_use.py b/share/extensions/inkex/elements/_use.py
new file mode 100644
index 0000000..78acb61
--- /dev/null
+++ b/share/extensions/inkex/elements/_use.py
@@ -0,0 +1,81 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2020 Martin Owens <doctormo@gmail.com>
+# Thomas Holder <thomas.holder@schrodinger.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Interface for the Use and Symbol elements
+"""
+
+from ..transforms import Transform
+
+from ._groups import Group, GroupBase
+from ._base import ShapeElement
+
+
+class Symbol(GroupBase):
+ """SVG symbol element"""
+
+ tag_name = "symbol"
+
+
+class Use(ShapeElement):
+ """A 'use' element that links to another in the document"""
+
+ tag_name = "use"
+
+ @classmethod
+ def new(cls, elem, x, y, **attrs): # pylint: disable=arguments-differ
+ ret = super().new(x=x, y=y, **attrs)
+ ret.href = elem
+ return ret
+
+ def get_path(self):
+ """Returns the path of the cloned href plus any transformation"""
+ path = self.href.path
+ path.transform(self.href.transform)
+ return path
+
+ def effective_style(self):
+ """Href's style plus this object's own styles"""
+ style = self.href.effective_style()
+ style.update(self.style)
+ return style
+
+ def unlink(self):
+ """Unlink this clone, replacing it with a copy of the original"""
+ copy = self.href.copy()
+ if isinstance(copy, Symbol):
+ group = Group(**copy.attrib)
+ group.extend(copy)
+ copy = group
+ copy.transform = self.transform @ copy.transform
+ copy.transform.add_translate(
+ self.to_dimensionless(self.get("x", 0)),
+ self.to_dimensionless(self.get("y", 0)),
+ )
+ copy.style = self.style + copy.style
+ self.replace_with(copy)
+ copy.set_random_ids()
+ return copy
+
+ def shape_box(self, transform=None):
+ """BoundingBox of the unclipped shape
+
+ .. versionadded:: 1.1"""
+ effective_transform = Transform(transform) @ self.transform
+ return self.href.bounding_box(effective_transform)
diff --git a/share/extensions/inkex/elements/_utils.py b/share/extensions/inkex/elements/_utils.py
new file mode 100644
index 0000000..56e1e12
--- /dev/null
+++ b/share/extensions/inkex/elements/_utils.py
@@ -0,0 +1,144 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2021 Martin Owens <doctormo@gmail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Useful utilities specifically for elements (that aren't base classes)
+
+.. versionadded:: 1.1
+ Most of the methods in this module were moved from inkex.utils.
+"""
+
+from collections import defaultdict
+import re
+
+# a dictionary of all of the xmlns prefixes in a standard inkscape doc
+NSS = {
+ "sodipodi": "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd",
+ "cc": "http://creativecommons.org/ns#",
+ "ccOLD": "http://web.resource.org/cc/",
+ "svg": "http://www.w3.org/2000/svg",
+ "dc": "http://purl.org/dc/elements/1.1/",
+ "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
+ "inkscape": "http://www.inkscape.org/namespaces/inkscape",
+ "xlink": "http://www.w3.org/1999/xlink",
+ "xml": "http://www.w3.org/XML/1998/namespace",
+}
+SSN = dict((b, a) for (a, b) in NSS.items())
+
+
+def addNS(tag, ns=None): # pylint: disable=invalid-name
+ """Add a known namespace to a name for use with lxml"""
+ if tag.startswith("{") and ns:
+ _, tag = removeNS(tag)
+ if not tag.startswith("{"):
+ tag = tag.replace("__", ":")
+ if ":" in tag:
+ (ns, tag) = tag.rsplit(":", 1)
+ ns = NSS.get(ns, None) or ns
+ if ns is not None:
+ return f"{{{ns}}}{tag}"
+ return tag
+
+
+def removeNS(name): # pylint: disable=invalid-name
+ """The reverse of addNS, finds any namespace and returns tuple (ns, tag)"""
+ if name[0] == "{":
+ (url, tag) = name[1:].split("}", 1)
+ return SSN.get(url, "svg"), tag
+ if ":" in name:
+ return name.rsplit(":", 1)
+ return "svg", name
+
+
+def splitNS(name): # pylint: disable=invalid-name
+ """Like removeNS, but returns a url instead of a prefix"""
+ (prefix, tag) = removeNS(name)
+ return (NSS[prefix], tag)
+
+
+def natural_sort_key(key, _nsre=re.compile("([0-9]+)")):
+ """Helper for a natural sort, see
+ https://stackoverflow.com/a/16090640/3298143"""
+ return [int(text) if text.isdigit() else text.lower() for text in _nsre.split(key)]
+
+
+class ChildToProperty(property):
+ """Use when you have a singleton child element who's text
+ content is the canonical value for the property"""
+
+ def __init__(self, tag, prepend=False):
+ super().__init__()
+ self.tag = tag
+ self.prepend = prepend
+
+ def __get__(self, obj, klass=None):
+ elem = obj.findone(self.tag)
+ return elem.text if elem is not None else None
+
+ def __set__(self, obj, value):
+ elem = obj.get_or_create(self.tag, prepend=self.prepend)
+ elem.text = value
+
+ def __delete__(self, obj):
+ obj.remove_all(self.tag)
+
+ @property
+ def __doc__(self):
+ return f"Get, set or delete the {self.tag} property."
+
+
+class CloningVat:
+ """
+ When modifying defs, sometimes we want to know if every backlink would have
+ needed changing, or it was just some of them.
+
+ This tracks the def elements, their promises and creates clones if needed.
+ """
+
+ def __init__(self, svg):
+ self.svg = svg
+ self.tracks = defaultdict(set)
+ self.set_ids = defaultdict(list)
+
+ def track(self, elem, parent, set_id=None, **kwargs):
+ """Track the element and connected parent"""
+ elem_id = elem.get("id")
+ parent_id = parent.get("id")
+ self.tracks[elem_id].add(parent_id)
+ self.set_ids[elem_id].append((set_id, kwargs))
+
+ def process(self, process, types=(), make_clones=True, **kwargs):
+ """
+ Process each tracked item if the backlinks match the parents
+
+ Optionally make clones, process the clone and set the new id.
+ """
+ for elem_id in list(self.tracks):
+ parents = self.tracks[elem_id]
+ elem = self.svg.getElementById(elem_id)
+ backlinks = {blk.get("id") for blk in elem.backlinks(*types)}
+ if backlinks == parents:
+ # No need to clone, we're processing on-behalf of all parents
+ process(elem, **kwargs)
+ elif make_clones:
+ clone = elem.copy()
+ elem.getparent().append(clone)
+ clone.set_random_id()
+ for update, upkw in self.set_ids.get(elem_id, ()):
+ update(elem.get("id"), clone.get("id"), **upkw)
+ process(clone, **kwargs)
diff --git a/share/extensions/inkex/extensions.py b/share/extensions/inkex/extensions.py
new file mode 100644
index 0000000..37ead3d
--- /dev/null
+++ b/share/extensions/inkex/extensions.py
@@ -0,0 +1,475 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2018 Martin Owens <doctormo@gmail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+A helper module for creating Inkscape effect extensions
+
+This provides the basic generic types of extensions which most writers should
+use in their code. See below for the different types.
+"""
+
+import os
+import re
+import sys
+import types
+from abc import ABC
+
+from .utils import errormsg, Boolean
+from .colors import Color, ColorError
+from .elements import (
+ load_svg,
+ BaseElement,
+ ShapeElement,
+ Group,
+ Layer,
+ Grid,
+ TextElement,
+ FlowPara,
+ FlowDiv,
+ Pattern,
+)
+from .elements._utils import CloningVat
+from .base import (
+ InkscapeExtension,
+ SvgThroughMixin,
+ SvgInputMixin,
+ SvgOutputMixin,
+ TempDirMixin,
+)
+from .transforms import Transform
+from .elements import LinearGradient, RadialGradient
+
+# All the names that get added to the inkex API itself.
+__all__ = (
+ "EffectExtension",
+ "GenerateExtension",
+ "InputExtension",
+ "OutputExtension",
+ "RasterOutputExtension",
+ "CallExtension",
+ "TemplateExtension",
+ "ColorExtension",
+ "TextExtension",
+)
+
+stdout = sys.stdout
+
+
+class EffectExtension(SvgThroughMixin, InkscapeExtension, ABC):
+ """
+ Takes the SVG from Inkscape, modifies the selection or the document
+ and returns an SVG to Inkscape.
+ """
+
+
+class OutputExtension(SvgInputMixin, InkscapeExtension):
+ """
+ Takes the SVG from Inkscape and outputs it to something that's not an SVG.
+
+ Used in functions for `Save As`
+ """
+
+ def effect(self):
+ """Effect isn't needed for a lot of Output extensions"""
+
+ def save(self, stream):
+ """But save certainly is, we give a more exact message here"""
+ raise NotImplementedError("Output extensions require a save(stream) method!")
+
+
+class RasterOutputExtension(InkscapeExtension):
+ """
+ Takes a PNG from Inkscape and outputs it to another rather format.
+
+ .. versionadded:: 1.1
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.img = None
+
+ def load(self, stream):
+ from PIL import Image
+
+ # disable the PIL decompression bomb DOS attack check.
+ Image.MAX_IMAGE_PIXELS = None
+
+ self.img = Image.open(stream)
+
+ def effect(self):
+ """Not needed since image isn't being changed"""
+
+ def save(self, stream):
+ """Implement raster image saving here from PIL"""
+ raise NotImplementedError("Raster Output extension requires a save method!")
+
+
+class InputExtension(SvgOutputMixin, InkscapeExtension):
+ """
+ Takes any type of file as input and outputs SVG which Inkscape can read.
+
+ Used in functions for `Open`
+ """
+
+ def effect(self):
+ """Effect isn't needed for a lot of Input extensions"""
+
+ def load(self, stream):
+ """But load certainly is, we give a more exact message here"""
+ raise NotImplementedError("Input extensions require a load(stream) method!")
+
+
+class CallExtension(TempDirMixin, InputExtension):
+ """Call an external program to get the output"""
+
+ input_ext = "svg"
+ output_ext = "svg"
+
+ def load(self, stream):
+ pass # Not called (load_raw instead)
+
+ def load_raw(self):
+ # Don't call InputExtension.load_raw
+ TempDirMixin.load_raw(self)
+ input_file = self.options.input_file
+
+ if not isinstance(input_file, str):
+ data = input_file.read()
+ input_file = os.path.join(self.tempdir, "input." + self.input_ext)
+ with open(input_file, "wb") as fhl:
+ fhl.write(data)
+
+ output_file = os.path.join(self.tempdir, "output." + self.output_ext)
+ document = self.call(input_file, output_file) or output_file
+ if isinstance(document, str):
+ if not os.path.isfile(document):
+ raise IOError(f"Can't find generated document: {document}")
+
+ if self.output_ext == "svg":
+ with open(document, "r", encoding="utf-8") as fhl:
+ document = fhl.read()
+ if "<" in document:
+ document = load_svg(document.encode("utf-8"))
+ else:
+ with open(document, "rb") as fhl:
+ document = fhl.read()
+
+ self.document = document
+
+ def call(self, input_file, output_file):
+ """Call whatever programs are needed to get the desired result."""
+ raise NotImplementedError("Call extensions require a call(in, out) method!")
+
+
+class GenerateExtension(EffectExtension):
+ """
+ Does not need any SVG, but instead just outputs an SVG fragment which is
+ inserted into Inkscape, centered on the selection.
+ """
+
+ container_label = ""
+ container_layer = False
+
+ def generate(self):
+ """
+ Return an SVG fragment to be inserted into the selected layer of the document
+ OR yield multiple elements which will be grouped into a container group
+ element which will be given an automatic label and transformation.
+ """
+ raise NotImplementedError("Generate extensions must provide generate()")
+
+ def container_transform(self):
+ """
+ Generate the transformation for the container group, the default is
+ to return the center position of the svg document or view port.
+ """
+ (pos_x, pos_y) = self.svg.namedview.center
+ if pos_x is None:
+ pos_x = 0
+ if pos_y is None:
+ pos_y = 0
+ return Transform(translate=(pos_x, pos_y))
+
+ def create_container(self):
+ """
+ Return the container the generated elements will go into.
+
+ Default is a new layer or current layer depending on the :attr:`container_layer`
+ flag.
+
+ .. versionadded:: 1.1
+ """
+ container = (Layer if self.container_layer else Group).new(self.container_label)
+ if self.container_layer:
+ self.svg.append(container)
+ else:
+ container.transform = self.container_transform()
+ parent = self.svg.get_current_layer()
+ try:
+ parent_transform = parent.composed_transform()
+ except AttributeError:
+ pass
+ else:
+ container.transform = -parent_transform @ container.transform
+ parent.append(container)
+ return container
+
+ def effect(self):
+ layer = self.svg.get_current_layer()
+ fragment = self.generate()
+ if isinstance(fragment, types.GeneratorType):
+ container = self.create_container()
+ for child in fragment:
+ if isinstance(child, BaseElement):
+ container.append(child)
+ elif isinstance(fragment, BaseElement):
+ layer.append(fragment)
+ else:
+ errormsg("Nothing was generated\n")
+
+
+class TemplateExtension(EffectExtension):
+ """
+ Provide a standard way of creating templates.
+ """
+
+ size_rex = re.compile(r"([\d.]*)(\w\w)?x([\d.]*)(\w\w)?")
+ template_id = "SVGRoot"
+
+ def __init__(self):
+ self.svg = None
+ super().__init__()
+ # Arguments added on after add_arguments so it can be overloaded cleanly.
+ self.arg_parser.add_argument("--size", type=self.arg_size(), dest="size")
+ self.arg_parser.add_argument("--width", type=int, default=800)
+ self.arg_parser.add_argument("--height", type=int, default=600)
+ self.arg_parser.add_argument("--orientation", default=None)
+ self.arg_parser.add_argument("--unit", default="px")
+ self.arg_parser.add_argument("--grid", type=Boolean)
+ # self.svg = None
+
+ def get_template(self, **kwargs):
+ """Can be over-ridden with custom svg loading here"""
+ return self.document
+
+ def arg_size(self, unit="px"):
+ """Argument is a string of the form X[unit]xY[unit], default units apply
+ when missing"""
+
+ def _inner(value):
+ try:
+ value = float(value)
+ return (value, unit, value, unit)
+ except ValueError:
+ pass
+ match = self.size_rex.match(str(value))
+ if match is not None:
+ size = match.groups()
+ return (
+ float(size[0]),
+ size[1] or unit,
+ float(size[2]),
+ size[3] or unit,
+ )
+ return None
+
+ return _inner
+
+ def get_size(self):
+ """Get the size of the new template (defaults to size options)"""
+ size = self.options.size
+ if self.options.size is None:
+ size = (
+ self.options.width,
+ self.options.unit,
+ self.options.height,
+ self.options.unit,
+ )
+ if (
+ self.options.orientation == "horizontal"
+ and size[0] < size[2]
+ or self.options.orientation == "vertical"
+ and size[0] > size[2]
+ ):
+ size = size[2:4] + size[0:2]
+ return size
+
+ def effect(self):
+ """Creates a template, do not over-ride"""
+ (width, width_unit, height, height_unit) = self.get_size()
+ width_px = int(self.svg.uutounit(width, "px"))
+ height_px = int(self.svg.uutounit(height, "px"))
+
+ self.document = self.get_template()
+ self.svg = self.document.getroot()
+ self.svg.set("id", self.template_id)
+ self.svg.set("width", str(width) + width_unit)
+ self.svg.set("height", str(height) + height_unit)
+ self.svg.set("viewBox", f"0 0 {width} {height}")
+ self.set_namedview(width_px, height_px, width_unit)
+
+ def set_namedview(self, width, height, unit):
+ """Setup the document namedview"""
+ self.svg.namedview.set("inkscape:document-units", unit)
+ self.svg.namedview.set("inkscape:zoom", "0.25")
+ self.svg.namedview.set("inkscape:cx", str(width / 2.0))
+ self.svg.namedview.set("inkscape:cy", str(height / 2.0))
+ if self.options.grid:
+ self.svg.namedview.set("showgrid", "true")
+ self.svg.namedview.add(Grid(type="xygrid"))
+
+
+class ColorExtension(EffectExtension):
+ """
+ A standard way to modify colours in an svg document.
+ """
+
+ process_none = False # should we call modify_color for the "none" color.
+ select_all = (ShapeElement,)
+ pass_rgba = False
+ """
+ If true, color and opacity are processed together (as RGBA color)
+ by :func:`modify_color`.
+
+ If false (default), they are processed independently by `modify_color` and
+ `modify_opacity`.
+
+ .. versionadded:: 1.2
+ """
+
+ def __init__(self):
+ super().__init__()
+ self._renamed = {}
+
+ def effect(self):
+ # Limiting to shapes ignores Gradients (and other things) from the select_all
+ # this prevents defs from being processed twice.
+ self._renamed = {}
+ gradients = CloningVat(self.svg)
+ for elem in self.svg.selection.get(ShapeElement):
+ self.process_element(elem, gradients)
+ gradients.process(self.process_elements, types=(ShapeElement,))
+
+ def process_elements(self, elem):
+ """Process multiple elements (gradients)"""
+ for child in elem.descendants():
+ self.process_element(child)
+
+ def process_element(self, elem, gradients=None):
+ """Process one of the selected elements"""
+ style = elem.specified_style()
+ # Colours first
+ for name in (
+ elem.style.associated_props if self.pass_rgba else elem.style.color_props
+ ):
+ if name not in style:
+ continue # we don't want to process default values
+ try:
+ value = style(name)
+ except ColorError:
+ continue # bad color value, don't touch.
+ if isinstance(value, Color):
+ col = Color(value)
+ if self.pass_rgba:
+ col = col.to_rgba(
+ alpha=elem.style(elem.style.associated_props[name])
+ )
+ rgba_result = self._modify_color(name, col)
+ elem.style.set_color(rgba_result, name)
+
+ if isinstance(value, (LinearGradient, RadialGradient, Pattern)):
+ gradients.track(value, elem, self._ref_cloned, style=style, name=name)
+ if value.href is not None:
+ gradients.track(value.href, elem, self._xlink_cloned, linker=value)
+ # Then opacities (usually does nothing)
+ if self.pass_rgba:
+ return
+ for name in elem.style.opacity_props:
+ value = style(name)
+ result = self.modify_opacity(name, value)
+ if result not in (value, 1): # only modify if not equal to old or default
+ elem.style[name] = result
+
+ def _ref_cloned(self, old_id, new_id, style, name):
+ self._renamed[old_id] = new_id
+ style[name] = f"url(#{new_id})"
+
+ def _xlink_cloned(self, old_id, new_id, linker): # pylint: disable=unused-argument
+ lid = linker.get("id")
+ linker = self.svg.getElementById(self._renamed.get(lid, lid))
+ linker.set("xlink:href", "#" + new_id)
+
+ def _modify_color(self, name, color):
+ """Pre-process color value to filter out bad colors"""
+ if color or self.process_none:
+ return self.modify_color(name, color)
+ return color
+
+ def modify_color(self, name, color):
+ """Replace this method with your colour modifier method"""
+ raise NotImplementedError("Provide a modify_color method.")
+
+ def modify_opacity(
+ self, name, opacity
+ ): # pylint: disable=no-self-use, unused-argument
+ """Optional opacity modification"""
+ return opacity
+
+
+class TextExtension(EffectExtension):
+ """
+ A base effect for changing text in a document.
+ """
+
+ newline = True
+ newpar = True
+
+ def effect(self):
+ nodes = self.svg.selection or {None: self.document.getroot()}
+ for elem in nodes.values():
+ self.process_element(elem)
+
+ def process_element(self, node):
+ """Reverse the node text"""
+ if node.get("sodipodi:role") == "line":
+ self.newline = True
+ elif isinstance(node, (TextElement, FlowPara, FlowDiv)):
+ self.newline = True
+ self.newpar = True
+
+ if node.text is not None:
+ node.text = self.process_chardata(node.text)
+ self.newline = False
+ self.newpar = False
+
+ for child in node:
+ self.process_element(child)
+
+ if node.tail is not None:
+ node.tail = self.process_chardata(node.tail)
+
+ def process_chardata(self, text):
+ """Replaceable chardata method for processing the text"""
+ return "".join(map(self.map_char, text))
+
+ @staticmethod
+ def map_char(char):
+ """Replaceable map_char method for processing each letter"""
+ raise NotImplementedError(
+ "Please provide a process_chardata or map_char static method."
+ )
diff --git a/share/extensions/inkex/gui/README.md b/share/extensions/inkex/gui/README.md
new file mode 100644
index 0000000..fb176da
--- /dev/null
+++ b/share/extensions/inkex/gui/README.md
@@ -0,0 +1,15 @@
+# What is inkex.gui
+
+This module is a Gtk based GUI creator. It helps extensions launch their own user interfaces and can help make sure those interfaces will work on all platforms that inkscape ships with.
+
+# How do I use it
+
+You can create custom user interfaces by using the Gnome glade builder program. Once you have a layout of all th widgets you want, you then make a GtkApp and Window classes inside your python program, when the GtkApp is run, th windows will be shown to the user and all signals specified for the widgets will call functions on your window class.
+
+Please see the existing code for examples of how to do this.
+
+# This is a fork
+
+This code was originally part of the package 'gtkme' which contained some part we didn't want to ship. Such as ubuntu indicators and internet pixmaps. To avoid conflicts, our stripped down version of the gtkme module is renamed and placed inside of inkscape's inkex module.
+
+
diff --git a/share/extensions/inkex/gui/__init__.py b/share/extensions/inkex/gui/__init__.py
new file mode 100644
index 0000000..27e1b0b
--- /dev/null
+++ b/share/extensions/inkex/gui/__init__.py
@@ -0,0 +1,50 @@
+#
+# Copyright 2011-2022 Martin Owens <doctormo@geek-2.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>
+#
+# pylint: disable=wrong-import-position
+"""
+This a wrapper layer to make interacting with Gtk a little less painful.
+The main issues with Gtk is that it expects an aweful lot of the developer,
+code which is repeated over and over and patterns which every single developer
+will use are not given easy to use convience functions.
+
+This makes Gtk programming WET, unattractive and error prone. This module steps
+inbetween and adds in all those missing bits. It's not meant to replace Gtk and
+certainly it's possible to use Gtk and threading directly.
+
+.. versionadded:: 1.2
+"""
+
+import threading
+import os
+import logging
+
+from ..utils import DependencyError
+
+try:
+ import gi
+
+ gi.require_version("Gtk", "3.0")
+except ImportError: # pragma: no cover
+ raise DependencyError(
+ "You are missing the required libraries for Gtk."
+ " Please report this problem to the Inkscape developers."
+ )
+
+from .app import GtkApp
+from .window import Window, ChildWindow, FakeWidget
+from .listview import TreeView, IconView, ViewColumn, ViewSort, Separator
+from .pixmap import PixmapManager
diff --git a/share/extensions/inkex/gui/app.py b/share/extensions/inkex/gui/app.py
new file mode 100644
index 0000000..6b2a0ab
--- /dev/null
+++ b/share/extensions/inkex/gui/app.py
@@ -0,0 +1,176 @@
+# coding=utf-8
+#
+# Copyright 2011-2022 Martin Owens <doctormo@geek-2.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>
+#
+"""
+Gtk Application base classes, providing a way to load a GtkBuilder
+with a specific glade/ui file conaining windows, and building
+a usable pythonic interface from them.
+"""
+import os
+import signal
+import logging
+
+from gi.repository import Gtk, GLib
+
+
+class GtkApp:
+ """
+ This wraps gtk builder and allows for some extra functionality with
+ windows, especially the management of gtk main loops.
+
+ Args:
+ start_loop (bool, optional): If set to true will start a new gtk main loop.
+ Defaults to False.
+ start_gui (bool, optional): Used as local propertes if unset and passed to
+ primary window when loaded. Defaults to True.
+ """
+
+ @property
+ def prefix(self):
+ """Folder prefix added to ui_dir"""
+ return self.kwargs.get("prefix", "")
+
+ @property
+ def windows(self):
+ """Returns a list of windows for this app"""
+ return self.kwargs.get("windows", [])
+
+ @property
+ def ui_dir(self):
+ """This is often the local directory"""
+ return self.kwargs.get("ui_dir", "./")
+
+ @property
+ def ui_file(self):
+ """If a single file is used for multiple windows"""
+ return self.kwargs.get("ui_file", None)
+
+ @property
+ def app_name(self):
+ """Set this variable in your class"""
+ try:
+ return self.kwargs["app_name"]
+ except KeyError:
+ raise NotImplementedError(
+ "App name is not set, pass in or set 'app_name' in class."
+ )
+
+ @property
+ def window(self):
+ """Return the primary window"""
+ return self._primary
+
+ def __init__(self, start_loop=False, start_gui=True, **kwargs):
+ """Creates a new GtkApp."""
+ self.kwargs = kwargs
+ self._loaded = {}
+ self._initial = {}
+ self._primary = None
+
+ self.main_loop = GLib.main_depth()
+
+ # Start with creating all the defined windows.
+ if start_gui:
+ self.init_gui()
+ # Start up a gtk main loop when requested
+ if start_loop:
+ self.run()
+
+ def run(self):
+ """Run the gtk mainloop with ctrl+C and keyboard interupt additions"""
+ if not Gtk.init_check()[0]: # pragma: no cover
+ raise RuntimeError(
+ "Gtk failed to start." " Make sure $DISPLAY variable is set.\n"
+ )
+ try:
+ # Add a signal to force quit on Ctrl+C (just like the old days)
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
+ Gtk.main()
+ except KeyboardInterrupt: # pragma: no cover
+ logging.info("User Interputed")
+ logging.debug("Exiting %s", self.app_name)
+
+ def get_ui_file(self, window):
+ """Load any given gtk builder file from a standard location."""
+ paths = [
+ os.path.join(self.ui_dir, self.prefix, f"{window}.ui"),
+ os.path.join(self.ui_dir, self.prefix, f"{self.ui_file}.ui"),
+ ]
+ for path in paths:
+ if os.path.isfile(path):
+ return path
+ raise FileNotFoundError(f"Gtk Builder file is missing: {paths}")
+
+ def init_gui(self):
+ """Initalise all of our windows and load their signals"""
+ if self.windows:
+ for cls in self.windows:
+ window = cls
+ logging.debug("Adding window %s to GtkApp", window.name)
+ self._initial[window.name] = window
+ for window in self._initial.values():
+ if window.primary:
+ if not self._primary:
+ self._primary = self.load_window(window.name)
+ if not self.windows or not self._primary:
+ raise KeyError(f"No primary window found for '{self.app_name}' app.")
+
+ def load_window(self, name, *args, **kwargs):
+ """Load a specific window from our group of windows"""
+ window = self.proto_window(name)
+ window.init(*args, **kwargs)
+ return window
+
+ def load_window_extract(self, name, **kwargs):
+ """Load a child window as a widget container"""
+ window = self.proto_window(name)
+ window.load_widgets(**kwargs)
+ return window.extract()
+
+ def proto_window(self, name):
+ """
+ Loads a glade window as a window without initialisation, used for
+ extracting widgets from windows without loading them as windows.
+ """
+ logging.debug("Loading '%s' from %s", name, self._initial)
+ if name in self._initial:
+ # Create a new instance of this window
+ window = self._initial[name](self)
+ # Save the window object linked against the gtk window instance
+ self._loaded[window.wid] = window
+ return window
+ raise KeyError(f"Can't load window '{name}', class not found.")
+
+ def remove_window(self, window):
+ """Remove the window from the list and exit if none remain"""
+ if window.wid in self._loaded:
+ self._loaded.pop(window.wid)
+ else:
+ logging.warning("Missing window '%s' on exit.", window.name)
+ logging.debug("Loaded windows: %s", self._loaded)
+ if not self._loaded:
+ self.exit()
+
+ def exit(self):
+ """Exit our gtk application and kill gtk main if we have to"""
+ if self.main_loop < GLib.main_depth():
+ # Quit Gtk loop if we started one.
+ tag = self._primary.name if self._primary else "program"
+ logging.debug("Quit '%s' Main Loop.", tag)
+ Gtk.main_quit()
+ # You have to return in order for the loop to exit
+ return 0
diff --git a/share/extensions/inkex/gui/asyncme.py b/share/extensions/inkex/gui/asyncme.py
new file mode 100644
index 0000000..5011c17
--- /dev/null
+++ b/share/extensions/inkex/gui/asyncme.py
@@ -0,0 +1,330 @@
+#
+# Copyright 2015 Ian Denhardt <ian@zenhack.net>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>
+#
+"""Convienience library for concurrency
+
+GUI apps frequently need concurrency, for example to avoid blocking UI while
+doing some long running computation. This module provides helpers for doing
+this kind of thing.
+
+The functions/methods here which spawn callables asynchronously
+don't supply a direct way to provide arguments. Instead, the user is
+expected to use a lambda, e.g::
+
+ holding(lck, lambda: do_stuff(1,2,3, x='hello'))
+
+This is because the calling function may have additional arguments which
+could obscure the user's ability to pass arguments expected by the called
+function. For example, in the call::
+
+ holding(lck, lambda: run_task(blocking=True), blocking=False)
+
+the blocking argument to holding might otherwise conflict with the
+blocking argument to run_task.
+"""
+import time
+import threading
+from datetime import datetime, timedelta
+
+from functools import wraps
+from typing import Any, Tuple
+from gi.repository import Gdk, GLib
+
+
+class Future:
+ """A deferred result
+
+ A `Future` is a result-to-be; it can be used to deliver a result
+ asynchronously. Typical usage:
+
+ >>> def background_task(task):
+ ... ret = Future()
+ ... def _task(x):
+ ... return x - 4 + 2
+ ... thread = threading.Thread(target=lambda: ret.run(lambda: _task(7)))
+ ... thread.start()
+ ... return ret
+ >>> # Do other stuff
+ >>> print(ret.wait())
+ 5
+
+ :func:`run` will also propogate exceptions; see it's docstring for details.
+ """
+
+ def __init__(self):
+ self._lock = threading.Lock()
+ self._value = None
+ self._exception = None
+ self._lock.acquire()
+
+ def is_ready(self):
+ """Return whether the result is ready"""
+ result = self._lock.acquire(False)
+ if result:
+ self._lock.release()
+ return result
+
+ def wait(self):
+ """Wait for the result.
+
+ `wait` blocks until the result is ready (either :func:`result` or
+ :func:`exception` has been called), and then returns it (in the case
+ of :func:`result`), or raises it (in the case of :func:`exception`).
+ """
+ with self._lock:
+ if self._exception is None:
+ return self._value
+ else:
+ raise self._exception # pylint: disable=raising-bad-type
+
+ def result(self, value):
+ """Supply the result as a return value.
+
+ ``value`` is the result to supply; it will be returned when
+ :func:`wait` is called.
+ """
+ self._value = value
+ self._lock.release()
+
+ def exception(self, err):
+ """Supply an exception as the result.
+
+ Args:
+ err (Exception): an exception, which will be raised when :func:`wait`
+ is called.
+ """
+ self._exception = err
+ self._lock.release()
+
+ def run(self, task):
+ """Calls task(), and supplies the result.
+
+ If ``task`` raises an exception, pass it to :func:`exception`.
+ Otherwise, pass the return value to :func:`result`.
+ """
+ try:
+ self.result(task())
+ except Exception as err: # pylint: disable=broad-except
+ self.exception(err)
+
+
+class DebouncedSyncVar:
+ """A synchronized variable, which debounces its value
+
+ :class:`DebouncedSyncVar` supports three operations: put, replace, and get.
+ get will only retrieve a value once it has "settled," i.e. at least
+ a certain amount of time has passed since the last time the value
+ was modified.
+ """
+
+ def __init__(self, delay_seconds=0):
+ """Create a new dsv with the supplied delay, and no initial value."""
+ self._cv = threading.Condition()
+ self._delay = timedelta(seconds=delay_seconds)
+
+ self._deadline = None
+ self._value = None
+
+ self._have_value = False
+
+ def set_delay(self, delay_seconds):
+ """Set the delay in seconds of the debounce."""
+ with self._cv:
+ self._delay = timedelta(seconds=delay_seconds)
+
+ def get(self, blocking=True, remove=True) -> Tuple[Any, bool]:
+ """Retrieve a value.
+
+ Args:
+ blocking (bool, optional): if True, block until (1) the dsv has a value
+ and (2) the value has been unchanged for an amount of time greater
+ than or equal to the dsv's delay. Otherwise, if these conditions
+ are not met, return ``(None, False)`` immediately. Defaults to True.
+ remove (bool, optional): if True, remove the value when returning it.
+ Otherwise, leave it where it is.. Defaults to True.
+
+ Returns:
+ Tuple[Any, bool]: Tuple (value, ok). ``value`` is the value of the variable
+ (if successful, see above), and ok indicates whether or not a value was
+ successfully retrieved.
+ """
+ while True:
+ with self._cv:
+
+ # If there's no value, either wait for one or return
+ # failure.
+ while not self._have_value:
+ if blocking:
+ self._cv.wait()
+ else:
+ return None, False # pragma: no cover
+
+ now = datetime.now()
+ deadline = self._deadline
+ value = self._value
+ if deadline <= now:
+ # Okay, we're good. Remove the value if necessary, and
+ # return it.
+ if remove:
+ self._have_value = False
+ self._value = None
+ self._cv.notify()
+ return value, True
+
+ # Deadline hasn't passed yet. Either wait or return failure.
+ if blocking:
+ time.sleep((deadline - now).total_seconds())
+ else:
+ return None, False # pragma: no cover
+
+ def replace(self, value):
+ """Replace the current value of the dsv (if any) with ``value``.
+
+ replace never blocks (except briefly to aquire the lock). It does not
+ wait for any unit of time to pass (though it does reset the timer on
+ completion), nor does it wait for the dsv's value to appear or
+ disappear.
+ """
+ with self._cv:
+ self._replace(value)
+
+ def put(self, value):
+ """Set the dsv's value to ``value``.
+
+ If the dsv already has a value, this blocks until the value is removed.
+ Upon completion, this resets the timer.
+ """
+ with self._cv:
+ while self._have_value:
+ self._cv.wait()
+ self._replace(value)
+
+ def _replace(self, value):
+ self._have_value = True
+ self._value = value
+ self._deadline = datetime.now() + self._delay
+ self._cv.notify()
+
+
+def spawn_thread(func):
+ """Call ``func()`` in a separate thread
+
+ Returns the corresponding :class:`threading.Thread` object.
+ """
+ thread = threading.Thread(target=func)
+ thread.start()
+ return thread
+
+
+def in_mainloop(func):
+ """Run f() in the gtk main loop
+
+ Returns a :class:`Future` object which can be used to retrieve the return
+ value of the function call.
+
+ :func:`in_mainloop` exists because Gtk isn't threadsafe, and therefore cannot be
+ manipulated except in the thread running the Gtk main loop. :func:`in_mainloop`
+ can be used by other threads to manipulate Gtk safely.
+ """
+ future = Future()
+
+ def handler(*_args, **_kwargs):
+ """Function to be called in the future"""
+ future.run(func)
+
+ Gdk.threads_add_idle(0, handler, None)
+ return future
+
+
+def mainloop_only(f):
+ """A decorator which forces a function to only be run in Gtk's main loop.
+
+ Invoking a decorated function as ``f(*args, **kwargs)`` is equivalent to
+ using the undecorated function (from a thread other than the one running
+ the Gtk main loop) as::
+
+ in_mainloop(lambda: f(*args, **kwargs)).wait()
+
+ :func:`mainloop_only` should be used to decorate functions which are unsafe
+ to run outside of the Gtk main loop.
+ """
+
+ @wraps(f)
+ def wrapper(*args, **kwargs):
+ if GLib.main_depth():
+ # Already in a mainloop, so just run it.
+ return f(*args, **kwargs)
+ return in_mainloop(lambda: f(*args, **kwargs)).wait()
+
+ return wrapper
+
+
+def holding(lock, task, blocking=True):
+ """Run task() while holding ``lock``.
+
+ Args:
+ blocking (bool, optional): if True, wait for the lock before running.
+ Otherwise, if the lock is busy, return None immediately, and don't
+ spawn `task`. Defaults to True.
+
+ Returns:
+ Union[Future, None]: The return value is a future which can be used to retrieve
+ the result of running task (or None if the task was not run).
+ """
+ if not lock.acquire(False):
+ return None
+ ret = Future()
+
+ def _target():
+ ret.run(task)
+ if ret._exception: # pragma: no cover
+ ret.wait()
+ lock.release()
+
+ threading.Thread(target=_target).start()
+ return ret
+
+
+def run_or_wait(func):
+ """A decorator which runs the function using :func:`holding`
+
+ This function creates a single lock for this function and
+ waits for the lock to release before returning.
+
+ See :func:`holding` above, with ``blocking=True``
+ """
+ lock = threading.Lock()
+
+ def _inner(*args, **kwargs):
+ return holding(lock, lambda: func(*args, **kwargs), blocking=True)
+
+ return _inner
+
+
+def run_or_none(func):
+ """A decorator which runs the function using :func:`holding`
+
+ This function creates a single lock for this function and
+ returns None if the process is already running (locked)
+
+ See :func:`holding` above with ``blocking=True``
+ """
+ lock = threading.Lock()
+
+ def _inner(*args, **kwargs):
+ return holding(lock, lambda: func(*args, **kwargs), blocking=False)
+
+ return _inner
diff --git a/share/extensions/inkex/gui/listview.py b/share/extensions/inkex/gui/listview.py
new file mode 100644
index 0000000..56939e7
--- /dev/null
+++ b/share/extensions/inkex/gui/listview.py
@@ -0,0 +1,562 @@
+#
+# Copyright 2011-2022 Martin Owens <doctormo@geek-2.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>
+#
+"""
+Wraps the gtk treeview and iconview in something a little nicer.
+"""
+
+import logging
+
+from typing import Tuple, Type, Optional
+from gi.repository import Gtk, Gdk, GObject, GdkPixbuf, Pango
+
+from .pixmap import PixmapManager, SizeFilter
+
+GOBJ = GObject.TYPE_PYOBJECT
+
+
+def default(item, attr, d=None):
+ """Python logic to choose an attribute, call it if required and return"""
+ if hasattr(item, attr):
+ prop = getattr(item, attr)
+ if callable(prop):
+ prop = prop()
+ return prop
+ return d
+
+
+def cmp(a, b):
+ """Compare two objects"""
+ return (a > b) - (a < b)
+
+
+def item_property(name, d=None):
+ def inside(item):
+ return default(item, name, d)
+
+ return inside
+
+
+def label(obj):
+ if isinstance(obj, tuple):
+ return " or ".join([label(o) for o in obj])
+ if not isinstance(obj, type):
+ obj = type(obj)
+ return obj.__name__
+
+
+class BaseView:
+ """Controls for tree and icon views, a base class"""
+
+ widget_type: Optional[Type[Gtk.Widget]] = None
+
+ def __init__(self, widget, liststore=None, **kwargs):
+ if not isinstance(widget, self.widget_type):
+ lbl1 = label(self.widget_type)
+ lbl2 = label(widget)
+ raise TypeError(f"Wrong widget type: Expected {lbl1} got {lbl2}")
+
+ self.selected_signal = kwargs.get("selected", None)
+ self._iids = []
+ self._list = widget
+ self.args = kwargs
+ self.selected = None
+ self._data = None
+ self.no_dupes = True
+ self._model = self.create_model(liststore or widget.get_model())
+ self._list.set_model(self._model)
+ self.setup()
+
+ self._list.connect(self.changed_signal, self.item_selected_signal)
+
+ def get_model(self):
+ """Returns the current data store model"""
+ return self._model
+
+ def create_model(self, liststore):
+ """Setup the model and list"""
+ if not isinstance(liststore, (Gtk.ListStore, Gtk.TreeStore)):
+ lbl = label(liststore)
+ raise TypeError(f"Expected List or TreeStore, got {lbl}")
+ return liststore
+
+ def refresh(self):
+ """Attempt to refresh the listview"""
+ self._list.queue_draw()
+
+ def setup(self):
+ """Setup columns, views, sorting etc"""
+ pass
+
+ def get_item_id(self, item):
+ """
+ Return an id set against this item.
+
+ If item.get_id() is set then duplicates will be ignored.
+ """
+ if hasattr(item, "get_id"):
+ return item.get_id()
+ return None
+
+ def replace(self, new_item, item_iter=None):
+ """Replace all items, or a single item with object"""
+ if item_iter:
+ self.remove_item(item_iter)
+ self.add_item(new_item)
+ else:
+ self.clear()
+ self._data = new_item
+ self.add_item(new_item)
+
+ def item_selected(self, item=None, *others):
+ """Base method result, called as an item is selected"""
+ if self.selected != item:
+ self.selected = item
+ if self.selected_signal and item:
+ self.selected_signal(item)
+
+ def remove_item(self, item=None):
+ """Remove an item from this view"""
+ return self._model.remove(self.get_iter(item))
+
+ def check_item_id(self, item):
+ """Item id is recorded to guard against duplicates"""
+ iid = self.get_item_id(item)
+ if iid in self._iids and self.no_dupes:
+ raise ValueError(f"Will not add duplicate row {iid}")
+ if iid:
+ self._iids.append(iid)
+
+ def __iter__(self):
+ ret = []
+
+ def collect_all(store, treepath, treeiter):
+ ret.append((self.get_item(treeiter), treepath, treeiter))
+
+ self._model.foreach(collect_all)
+ return ret.__iter__()
+
+ def set_sensitive(self, sen=True):
+ """Proxy the GTK property for sensitivity"""
+ self._list.set_sensitive(sen)
+
+ def clear(self):
+ """Clear all items from this treeview"""
+ self._iids = []
+ self._model.clear()
+
+ def item_double_clicked(self, *items):
+ """What happens when you double click an item"""
+ return items # Nothing
+
+ def get_item(self, item_iter):
+ """Return the object of attention from an iter"""
+ return self._model[self.get_iter(item_iter)][0]
+
+ def get_iter(self, item, path=False):
+ """Return the iter given the item"""
+ if isinstance(item, Gtk.TreePath):
+ return item if path else self._model.get_iter(item)
+ if isinstance(item, Gtk.TreeIter):
+ return self._model.get_path(item) if path else item
+ for src_item, src_path, src_iter in self:
+ if item == src_item:
+ return src_path if path else src_iter
+ return None
+
+
+class TreeView(BaseView):
+ """Controls and operates a tree view."""
+
+ column_size = 16
+ widget_type = Gtk.TreeView
+ changed_signal = "cursor_changed"
+
+ def setup(self):
+ """Setup the treeview"""
+ self._sel = self._list.get_selection()
+ self._sel.set_mode(Gtk.SelectionMode.MULTIPLE)
+ self._list.connect("button-press-event", self.item_selected_signal)
+ # Separators should do something
+ self._list.set_row_separator_func(TreeView.is_separator, None)
+ super().setup()
+
+ @staticmethod
+ def is_separator(model, item_iter, data):
+ """Internal function for seperator checking"""
+ return isinstance(model.get_value(item_iter, 0), Separator)
+
+ def get_selected_items(self):
+ """Return a list of selected item objects"""
+ return [self.get_item(row) for row in self._sel.get_selected_rows()[1]]
+
+ def set_selected_items(self, *items):
+ """Select the given items"""
+ self._sel.unselect_all()
+ for item in items:
+ path_item = self.get_iter(item, path=True)
+ if path_item is not None:
+ self._sel.select_path(path_item)
+
+ def is_selected(self, item):
+ """Return true if the item is selected"""
+ return self._sel.iter_is_selected(self.get_iter(item))
+
+ def add(self, target, parent=None):
+ """Add all items from the target to the treeview"""
+ for item in target:
+ self.add_item(item, parent=parent)
+
+ def add_item(self, item, parent=None):
+ """Add a single item image to the control, returns the TreePath"""
+ if item is not None:
+ self.check_item_id(item)
+ return self._add_item([item], self.get_iter(parent))
+ raise ValueError("Item can not be None.")
+
+ def _add_item(self, item, parent):
+ return self.get_iter(self._model.append(parent, item), path=True)
+
+ def item_selected_signal(self, *args, **kwargs):
+ """Signal for selecting an item"""
+ return self.item_selected(*self.get_selected_items())
+
+ def item_button_clicked(self, _, event):
+ """Signal for mouse button click"""
+ if event is None or event.type == Gdk.EventType._2BUTTON_PRESS:
+ self.item_double_clicked(*self.get_selected_items())
+
+ def expand_item(self, item, expand=True):
+ """Expand one of our nodes"""
+ self._list.expand_row(self.get_iter(item, path=True), expand)
+
+ def create_model(self, liststore=None):
+ """Set up an icon view for showing gallery images"""
+ if liststore is None:
+ liststore = Gtk.TreeStore(GOBJ)
+ return super().create_model(liststore)
+
+ def create_column(self, name, expand=True):
+ """
+ Create and pack a new column to this list.
+
+ name - Label in the column header
+ expand - Should the column expand
+ """
+ return ViewColumn(self._list, name, expand=expand)
+
+ def create_sort(self, *args, **kwargs):
+ """
+ Create and attach a sorting view to this list.
+
+ see ViewSort arguments for details.
+ """
+ return ViewSort(self._list, *args, **kwargs)
+
+
+class ComboBox(TreeView):
+ """Controls and operates a combo box list."""
+
+ widget_type = Gtk.ComboBox
+ changed_signal = "changed"
+
+ def setup(self):
+ pass
+
+ def get_selected_item(self):
+ """Return the selected item of this combo box"""
+ return self.get_item(self._list.get_active_iter())
+
+ def set_selected_item(self, item):
+ """Set the given item as the selected item"""
+ self._list.set_active_iter(self.get_iter(item))
+
+ def is_selected(self, item):
+ """Returns true if this item is the selected item"""
+ return self.get_selected_item() == item
+
+ def get_selected_items(self):
+ """Return a list of selected items (one)"""
+ return [self.get_selected_item()]
+
+
+class IconView(BaseView):
+ """Allows a simpler IconView for DBus List Objects"""
+
+ widget_type = Gtk.IconView
+ changed_signal = "selection-changed"
+
+ def __init__(self, widget, pixmaps, *args, **kwargs):
+ super().__init__(widget, *args, **kwargs)
+ self.pixmaps = pixmaps
+
+ def set_selected_item(self, item):
+ """Sets the selected item to this item"""
+ path = self.get_iter(item, path=True)
+ if path:
+ self._list.set_cursor(path, None, False)
+
+ def get_selected_items(self):
+ """Return the seleced item"""
+ return [self.get_item(path) for path in self._list.get_selected_items()]
+
+ def create_model(self, liststore):
+ """Setup the icon view control and model"""
+ if not liststore:
+ liststore = Gtk.ListStore(GOBJ, str, GdkPixbuf.Pixbuf)
+ return super().create_model(liststore)
+
+ def setup(self):
+ """Setup the columns for the iconview"""
+ self._list.set_markup_column(1)
+ self._list.set_pixbuf_column(2)
+ super().setup()
+
+ def add(self, target):
+ """Add all items from the target to the iconview"""
+ for item in target:
+ self.add_item(item)
+
+ def add_item(self, item):
+ """Add a single item image to the control"""
+ if item is not None:
+ self.check_item_id(item)
+ return self._add_item(item)
+ raise ValueError("Item can not be None.")
+
+ def get_markup(self, item):
+ """Default text return for markup."""
+ return default(item, "name", str(item))
+
+ def get_icon(self, item):
+ """Default icon return, pixbuf or gnome theme name"""
+ return default(item, "icon", None)
+
+ def _get_icon(self, item):
+ return self.pixmaps.get(self.get_icon(item), item=item)
+
+ def _add_item(self, item):
+ """
+ Each item's properties must be stuffed into the ListStore directly
+ or the IconView won't see them, but only if on auto.
+ """
+ if not isinstance(item, (tuple, list)):
+ item = [item, self.get_markup(item), self._get_icon(item)]
+ return self._model.append(item)
+
+ def item_selected_signal(self, *args, **kwargs):
+ """Item has been selected"""
+ return self.item_selected(*self.get_selected_items())
+
+
+class ViewSort(object):
+ """
+ A sorting function for use is ListViews
+
+ ascending - Boolean which direction to sort
+ contains - Contains this string
+ data - A string or function to get data from each item.
+ exact - Compare to this exact string instead.
+ """
+
+ def __init__(self, widget, data=None, ascending=False, exact=None, contains=None):
+ self.tree = None
+ self.data = data
+ self.asc = ascending
+ self.comp = exact.lower() if exact else None
+ self.cont = contains
+ self.tree = widget
+ self.resort()
+
+ def get_data(self, model, list_iter):
+ """Generate sortable data from the item"""
+ item = model.get_value(list_iter, 0)
+ if isinstance(self.data, str):
+ value = getattr(item, self.data)
+ elif callable(self.data):
+ value = self.data(item)
+ return value
+
+ def sort_func(self, model, iter1, iter2, data):
+ """Called by Gtk to sort items"""
+ value1 = self.get_data(model, iter1)
+ value2 = self.get_data(model, iter2)
+ if value1 == None or value2 == None:
+ return 0
+ if self.comp:
+ if cmp(self.comp, value1.lower()) == 0:
+ return 1
+ elif cmp(self.comp, value2.lower()) == 0:
+ return -1
+ return 0
+ elif self.cont:
+ if self.cont in value1.lower():
+ return 1
+ elif self.cont in value2.lower():
+ return -1
+ return 0
+ if value1 < value2:
+ return 1
+ if value2 < value1:
+ return -1
+ return 0
+
+ def resort(self):
+ model = self.tree.get_model()
+ model.set_sort_func(0, self.sort_func, None)
+ if self.asc:
+ model.set_sort_column_id(0, Gtk.SortType.ASCENDING)
+ else:
+ model.set_sort_column_id(0, Gtk.SortType.DESCENDING)
+
+
+class ViewColumn(object):
+ """
+ Add a column to a gtk treeview.
+
+ name - The column name used as a label.
+ expand - Set column expansion.
+ """
+
+ def __init__(self, widget, name, expand=False):
+ if isinstance(widget, Gtk.TreeView):
+ column = Gtk.TreeViewColumn((name))
+ column.set_sizing(Gtk.TreeViewColumnSizing.AUTOSIZE)
+ column.set_expand(expand)
+ self._column = column
+ widget.append_column(self._column)
+ else:
+ # Deal with possible drop down lists
+ self._column = widget
+
+ def add_renderer(self, renderer, func, expand=True):
+ """Set a custom renderer"""
+ self._column.pack_start(renderer, expand)
+ self._column.set_cell_data_func(renderer, func, None)
+ return renderer
+
+ def add_image_renderer(self, icon, pad=0, pixmaps=None, size=None):
+ """
+ Set the image renderer
+
+ icon - The function that returns the image to be dsplayed.
+ pad - The amount of padding around the image.
+ pixmaps - The pixmap manager to use to get images.
+ size - Restrict the images to this size.
+ """
+ # Manager where icons will be pulled from
+ filters = [SizeFilter] if size else []
+ pixmaps = pixmaps or PixmapManager(
+ "", pixmap_dir="./", filters=filters, size=size
+ )
+
+ renderer = Gtk.CellRendererPixbuf()
+ renderer.set_property("ypad", pad)
+ renderer.set_property("xpad", pad)
+ func = self.image_func(icon or self.default_icon, pixmaps)
+ return self.add_renderer(renderer, func, expand=False)
+
+ def add_text_renderer(self, text, wrap=None, template=None):
+ """
+ Set the text renderer.
+
+ text - the function that returns the text to be displayed.
+ wrap - The wrapping setting for this renderer.
+ template - A standard template used for this text markup.
+ """
+
+ renderer = Gtk.CellRendererText()
+ if wrap is not None:
+ renderer.props.wrap_width = wrap
+ renderer.props.wrap_mode = Pango.WrapMode.WORD
+
+ renderer.props.background_set = True
+ renderer.props.foreground_set = True
+
+ func = self.text_func(text or self.default_text, template)
+ return self.add_renderer(renderer, func, expand=True)
+
+ @classmethod
+ def clean(cls, text, markup=False):
+ """Clean text of any pango markup confusing chars"""
+ if text is None:
+ text = ""
+ if isinstance(text, (str, int, float)):
+ if markup:
+ text = str(text).replace("<", "&lt;").replace(">", "&gt;")
+ return str(text).replace("&", "&amp;")
+ elif isinstance(text, dict):
+ return dict([(k, cls.clean(v)) for k, v in text.items()])
+ elif isinstance(text, (list, tuple)):
+ return tuple([cls.clean(value) for value in text])
+ raise TypeError("Unknown value type for text: %s" % str(type(text)))
+
+ def get_callout(self, call, default=None):
+ """Returns the right kind of method"""
+ if isinstance(call, str):
+ call = item_property(call, default)
+ return call
+
+ def text_func(self, call, template=None):
+ """Wrap up our text functionality"""
+ callout = self.get_callout(call)
+
+ def internal(column, cell, model, item_iter, data):
+ if TreeView.is_separator(model, item_iter, data):
+ return
+ item = model.get_value(item_iter, 0)
+ markup = template is not None
+ text = callout(item)
+ if isinstance(template, str):
+ text = template.format(self.clean(text, markup=True))
+ else:
+ text = self.clean(text)
+ cell.set_property("markup", str(text))
+
+ return internal
+
+ def image_func(self, call, pixmaps=None):
+ """Wrap, wrap wrap the func"""
+ callout = self.get_callout(call)
+
+ def internal(column, cell, model, item_iter, data):
+ if TreeView.is_separator(model, item_iter, data):
+ return
+ item = model.get_value(item_iter, 0)
+ icon = callout(item)
+ # The or blank asks for the default icon from the pixmaps
+ if isinstance(icon or "", str) and pixmaps:
+ # Expect a Gnome theme icon
+ icon = pixmaps.get(icon)
+ elif icon:
+ icon = pixmaps.apply_filters(icon)
+
+ cell.set_property("pixbuf", icon)
+ cell.set_property("visible", True)
+
+ return internal
+
+ def default_text(self, item):
+ """Default text return for markup."""
+ return default(item, "name", str(item))
+
+ def default_icon(self, item):
+ """Default icon return, pixbuf or gnome theme name"""
+ return default(item, "icon", None)
+
+
+class Separator:
+ """Reprisentation of a separator in a list"""
diff --git a/share/extensions/inkex/gui/pixmap.py b/share/extensions/inkex/gui/pixmap.py
new file mode 100644
index 0000000..02f4ce8
--- /dev/null
+++ b/share/extensions/inkex/gui/pixmap.py
@@ -0,0 +1,346 @@
+#
+# Copyright 2011-2022 Martin Owens <doctormo@geek-2.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>
+#
+"""
+Provides wrappers for pixmap access.
+"""
+
+import os
+import logging
+
+from typing import List
+from collections.abc import Iterable
+from gi.repository import Gtk, GLib, GdkPixbuf
+
+ICON_THEME = Gtk.IconTheme.get_default()
+BILINEAR = GdkPixbuf.InterpType.BILINEAR
+HYPER = GdkPixbuf.InterpType.HYPER
+
+SIZE_ASPECT = 0
+SIZE_ASPECT_GROW = 1
+SIZE_ASPECT_CROP = 2
+SIZE_STRETCH = 3
+
+
+class PixmapLoadError(ValueError):
+ """Failed to load a pixmap"""
+
+
+class PixmapFilter: # pylint: disable=too-few-public-methods
+ """Base class for filtering the pixmaps in a manager's output.
+
+ required - List of values required for this filter.
+
+ Use:
+
+ class Foo(PixmapManager):
+ filters = [ PixmapFilterFoo ]
+
+ """
+
+ required: List[str] = []
+ optional: List[str] = []
+
+ def __init__(self, **kwargs):
+ self.enabled = True
+ for key in self.required:
+ if key not in kwargs:
+ self.enabled = False
+ else:
+ setattr(self, key, kwargs[key])
+
+ for key in self.optional:
+ if key in kwargs:
+ setattr(self, key, kwargs[key])
+
+ def filter(self, img, **kwargs):
+ """Run filter, replace this methodwith your own"""
+ raise NotImplementedError(
+ "Please add 'filter' method to your PixmapFilter class %s."
+ % type(self).__name__
+ )
+
+ @staticmethod
+ def to_size(dat):
+ """Tries to calculate a size that will work for the data"""
+ if isinstance(dat, (int, float)):
+ return (dat, dat)
+ if isinstance(dat, Iterable) and len(dat) >= 2:
+ return (dat[0], dat[1])
+ return None
+
+
+class OverlayFilter(PixmapFilter):
+ """Adds an overlay to output images, overlay can be any name that
+ the owning pixmap manager can find.
+
+ overlay : Name of overlay image
+ position : Location of the image:
+ 0 - Full size (1 to 1 overlay, default)
+ (x,y) - Percentage from one end to the other position 0-1
+ alpha : Blending alpha, 0 - 255
+
+ """
+
+ optional = ["position", "overlay", "alpha"]
+
+ def __init__(self, *args, **kwargs):
+ self.position = (0, 0)
+ self.overlay = None
+ self.alpha = 255
+ super().__init__(*args, **kwargs)
+ self.pad_x, self.pad_y = self.to_size(self.position)
+
+ def get_overlay(self, **kwargs):
+ if "manager" not in kwargs:
+ raise ValueError("PixmapManager must be provided when adding an overlay.")
+ return kwargs["manager"].get(
+ kwargs.get("overlay", None) or self.overlay, no_overlay=True
+ )
+
+ def filter(self, img, no_overlay=False, **kwargs):
+ # Recursion protection
+ if no_overlay:
+ return img
+
+ overlay = self.get_overlay(**kwargs)
+ if overlay:
+ img = img.copy()
+
+ (x, y, width, height) = self.set_position(overlay, img)
+ overlay.composite(
+ img, x, y, width, height, x, y, 1, 1, BILINEAR, self.alpha
+ )
+ return img
+
+ def set_position(self, overlay, img):
+ """Sets the position of img on the given width and height"""
+ img_w, img_h = img.get_width(), img.get_height()
+ ovl_w, ovl_h = overlay.get_width(), overlay.get_height()
+ return (
+ max([0, (img_w - ovl_w) * self.pad_x]),
+ max([0, (img_h - ovl_h) * self.pad_y]),
+ min([ovl_w, img_w]),
+ min([ovl_h, img_h]),
+ )
+
+
+class SizeFilter(PixmapFilter):
+ """Resizes images to a certain size:
+
+ resize_mode - Way in which the size is calculated
+ 0 - Best Aspect, don't grow
+ 1 - Best Aspect, grow
+ 2 - Cropped Aspect
+ 3 - Stretch
+ """
+
+ required = ["size"]
+ optional = ["resize_mode"]
+
+ def __init__(self, *args, **kwargs):
+ self.size = None
+ self.resize_mode = SIZE_ASPECT
+ super().__init__(*args, **kwargs)
+ self.img_w, self.img_h = self.to_size(self.size) or (0, 0)
+
+ def aspect(self, img_w, img_h):
+ """Get the aspect ratio of the image resized"""
+ if self.resize_mode == SIZE_STRETCH:
+ return (self.img_w, self.img_h)
+
+ if (
+ self.resize_mode == SIZE_ASPECT
+ and img_w < self.img_w
+ and img_h < self.img_h
+ ):
+ return (img_w, img_h)
+ (pcw, pch) = (self.img_w / img_w, self.img_h / img_h)
+ factor = (
+ max(pcw, pch) if self.resize_mode == SIZE_ASPECT_CROP else min(pcw, pch)
+ )
+ return (int(img_w * factor), int(img_h * factor))
+
+ def filter(self, img, **kwargs):
+ if self.size is not None:
+ (width, height) = self.aspect(img.get_width(), img.get_height())
+ return img.scale_simple(width, height, HYPER)
+ return img
+
+
+class PadFilter(SizeFilter):
+ """Add padding to the image to make it a standard size"""
+
+ optional = ["padding"]
+
+ def __init__(self, *args, **kwargs):
+ self.size = None
+ self.padding = 0.5
+ super().__init__(*args, **kwargs)
+ self.pad_x, self.pad_y = self.to_size(self.padding)
+
+ def filter(self, img, **kwargs):
+ (width, height) = (img.get_width(), img.get_height())
+ if width < self.img_w or height < self.img_h:
+ target = GdkPixbuf.Pixbuf.new(
+ img.get_colorspace(),
+ True,
+ img.get_bits_per_sample(),
+ max([width, self.img_w]),
+ max([height, self.img_h]),
+ )
+ target.fill(0x0) # Transparent black
+
+ x = (target.get_width() - width) * self.pad_x
+ y = (target.get_height() - height) * self.pad_y
+
+ img.composite(target, x, y, width, height, x, y, 1, 1, BILINEAR, 255)
+ return target
+ return img
+
+
+class PixmapManager:
+ """Manage a set of cached pixmaps, returns the default image
+ if it can't find one or the missing image if that's available."""
+
+ missing_image = "image-missing"
+ default_image = "application-default-icon"
+ icon_theme = ICON_THEME
+ theme_size = 32
+ filters: List[type] = []
+ pixmap_dir = None
+
+ def __init__(self, location="", **kwargs):
+ self.location = location
+ if self.pixmap_dir and not os.path.isabs(location):
+ self.location = os.path.join(self.pixmap_dir, location)
+
+ self.loader_size = PixmapFilter.to_size(kwargs.pop("load_size", None))
+
+ # Add any instance specified filters first
+ self._filters = []
+ for item in kwargs.get("filters", []) + self.filters:
+ if isinstance(item, PixmapFilter):
+ self._filters.append(item)
+ elif callable(item):
+ # Now add any class specified filters with optional kwargs
+ self._filters.append(item(**kwargs))
+
+ self.cache = {}
+ self.get_pixmap(self.default_image)
+
+ def get(self, *args, **kwargs):
+ """Get a pixmap of any kind"""
+ return self.get_pixmap(*args, **kwargs)
+
+ def get_missing_image(self):
+ """Get a missing image when other images aren't found"""
+ return self.get(self.missing_image)
+
+ @staticmethod
+ def data_is_file(data):
+ """Test the file to see if it's a filename or not"""
+ return isinstance(data, str) and "<svg" not in data
+
+ def get_pixmap(self, data, **kwargs):
+ """
+ There are three types of images this might return.
+
+ 1. A named gtk-image such as "gtk-stop"
+ 2. A file on the disk such as "/tmp/a.png"
+ 3. Data as either svg or binary png
+
+ All pixmaps are cached for multiple use.
+ """
+ if "manager" not in kwargs:
+ kwargs["manager"] = self
+
+ if not data:
+ if not self.default_image:
+ return None
+ data = self.default_image
+
+ key = data[-30:] # bytes or string
+ if not key in self.cache:
+ # load the image from data or a filename/theme icon
+ img = None
+ try:
+ if self.data_is_file(data):
+ img = self.load_from_name(data)
+ else:
+ img = self.load_from_data(data)
+ except PixmapLoadError as err:
+ logging.warning(str(err))
+ return self.get_missing_image()
+
+ if img is not None:
+ self.cache[key] = self.apply_filters(img, **kwargs)
+
+ return self.cache[key]
+
+ def apply_filters(self, img, **kwargs):
+ """Apply all the filters to the given image"""
+ for lens in self._filters:
+ if lens.enabled:
+ img = lens.filter(img, **kwargs)
+ return img
+
+ def load_from_data(self, data):
+ """Load in memory picture file (jpeg etc)"""
+ # This doesn't work yet, returns None *shrug*
+ loader = GdkPixbuf.PixbufLoader()
+ if self.loader_size:
+ loader.set_size(*self.loader_size)
+ try:
+ if isinstance(data, str):
+ data = data.encode("utf-8")
+ loader.write(data)
+ loader.close()
+ except GLib.GError as err:
+ raise PixmapLoadError(f"Faled to load pixbuf from data: {err}")
+ return loader.get_pixbuf()
+
+ def load_from_name(self, name):
+ """Load a pixbuf from a name, filename or theme icon name"""
+ pixmap_path = self.pixmap_path(name)
+ if os.path.exists(pixmap_path):
+ try:
+ return GdkPixbuf.Pixbuf.new_from_file(pixmap_path)
+ except RuntimeError as msg:
+ raise PixmapLoadError(f"Faild to load pixmap '{pixmap_path}', {msg}")
+ elif (
+ self.icon_theme and "/" not in name and "." not in name and "<" not in name
+ ):
+ return self.theme_pixmap(name, size=self.theme_size)
+ raise PixmapLoadError(f"Failed to find pixmap '{name}' in {self.location}")
+
+ def theme_pixmap(self, name, size=32):
+ """Internal user: get image from gnome theme"""
+ size = size or 32
+ if not self.icon_theme.has_icon(name):
+ name = "image-missing"
+ return self.icon_theme.load_icon(name, size, 0)
+
+ def pixmap_path(self, name):
+ """Returns the pixmap path based on stored location"""
+ for filename in (
+ name,
+ os.path.join(self.location, f"{name}.svg"),
+ os.path.join(self.location, f"{name}.png"),
+ ):
+ if os.path.exists(filename) and os.path.isfile(filename):
+ return name
+ return os.path.join(self.location, name)
diff --git a/share/extensions/inkex/gui/tester.py b/share/extensions/inkex/gui/tester.py
new file mode 100644
index 0000000..c8ce5e7
--- /dev/null
+++ b/share/extensions/inkex/gui/tester.py
@@ -0,0 +1,78 @@
+# coding=utf-8
+#
+# Copyright 2022 Martin Owens <doctormo@geek-2.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>
+#
+"""
+Structures for consistant testing of Gtk GUI programs.
+"""
+
+import sys
+from gi.repository import Gtk, GLib
+
+
+class MainLoopProtection:
+ """
+ This protection class provides a way to launch the Gtk mainloop in a test
+ friendly way.
+
+ Exception handling hooks provide a way to see errors that happen
+ inside the main loop, raising them back to the caller.
+ A full timeout in seconds stops the gtk mainloop from operating
+ beyond a set time, acting as a kill switch in the event something
+ has gone horribly wrong.
+
+ Use:
+ with MainLoopProtection(timeout=10s):
+ app.run()
+ """
+
+ def __init__(self, timeout=10):
+ self.timeout = timeout * 1000
+ self._hooked = None
+ self._old_excepthook = None
+
+ def __enter__(self):
+ # replace sys.excepthook with our own and remember hooked raised error
+ self._old_excepthook = sys.excepthook
+ sys.excepthook = self.excepthook
+ # Remove mainloop by force if it doesn't die within 10 seconds
+ self._timeout = GLib.timeout_add(self.timeout, self.idle_exit)
+
+ def __exit__(self, exc, value, traceback): # pragma: no cover
+ """Put the except handler back, cancel the timer and raise if needed"""
+ if self._old_excepthook:
+ sys.excepthook = self._old_excepthook
+ # Remove the timeout, so we don't accidentally kill later mainloops
+ if self._timeout:
+ GLib.source_remove(self._timeout)
+ # Raise an exception if one happened during the test run
+ if self._hooked:
+ exc, value, traceback = self._hooked
+ if value and traceback:
+ raise value.with_traceback(traceback)
+
+ def idle_exit(self): # pragma: no cover
+ """Try to going to kill any running mainloop."""
+ GLib.idle_add(Gtk.main_quit)
+
+ def excepthook(self, ex_type, ex_value, traceback): # pragma: no cover
+ """Catch errors thrown by the Gtk mainloop"""
+ self.idle_exit()
+ # Remember the exception data for raising inside the test context
+ if ex_value is not None:
+ self._hooked = [ex_type, ex_value, traceback]
+ # Fallback and double print the exception (remove if double printing is problematic)
+ return self._old_excepthook(ex_type, ex_value, traceback)
diff --git a/share/extensions/inkex/gui/window.py b/share/extensions/inkex/gui/window.py
new file mode 100644
index 0000000..a5c1ef6
--- /dev/null
+++ b/share/extensions/inkex/gui/window.py
@@ -0,0 +1,201 @@
+#
+# Copyright 2012-2022 Martin Owens <doctormo@geek-2.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>
+#
+# pylint: disable=too-many-instance-attributes
+"""
+Wraps the gtk windows with something a little nicer.
+"""
+import logging
+
+from gi.repository import Gtk
+
+PROPS = {
+ "Box": ["expand", "fill", "padding", "pack-type"],
+ "Grid": ["top-attach", "left-attach", "height", "width"],
+ "Table": ["top-attach", "left-attach", "bottom-attach", "right-attach"],
+}
+
+
+def protect(cls, *methods):
+ """Simple check for protecting an inherrited class from having
+ certain methods over-ridden"""
+ if not isinstance(cls, type):
+ cls = type(cls)
+ for method in methods:
+ if method in cls.__dict__: # pragma: no cover
+ raise RuntimeError(
+ f"{cls.__name__} in {cls.__module__} has" f" protected def {method}()"
+ )
+
+
+class Window:
+ """
+ This wraps gtk windows and allows for having parent windows
+
+ name = 'name-of-the-window'
+
+ Should the window be the first loaded and end gtk when closed:
+
+ primary = True/False
+ """
+
+ primary = True
+ name = None
+
+ def __init__(self, gapp):
+ self.gapp = gapp
+ self.dead = False
+ self.parent = None
+ self.args = ()
+ ui_file = gapp.get_ui_file(self.name)
+
+ # Setup the gtk app connection
+ self.w_tree = Gtk.Builder()
+ self.widget = self.w_tree.get_object
+ self.w_tree.set_translation_domain(gapp.app_name)
+ self.w_tree.add_from_file(ui_file)
+
+ # Setup the gtk builder window
+ self.window = self.widget(self.name)
+ if not self.window: # pragma: no cover
+ raise KeyError(f"Missing window widget '{self.name}' from '{ui_file}'")
+
+ # Give us a window id to track this window
+ self.wid = str(hash(self.window))
+
+ def extract(self):
+ """Extract this window's container for use in other apps"""
+ for child in self.window.get_children():
+ self.window.remove(child)
+ return child
+
+ def init(self, parent=None, **kwargs):
+ """Initialise the window within the GtkApp"""
+ if "replace" not in kwargs:
+ protect(self, "destroy", "exit", "load_window", "proto_window")
+ self.args = kwargs
+ # Set object defaults
+ self.parent = parent
+
+ self.w_tree.connect_signals(self)
+
+ # These are some generic convience signals
+ self.window.connect("destroy", self.exit)
+
+ # If we have a parent window, then we expect not to quit
+ if self.parent:
+ self.window.set_transient_for(self.parent)
+ self.parent.set_sensitive(False)
+
+ # We may have some more gtk widgets to setup
+ self.load_widgets(**self.args)
+ self.window.show()
+
+ def load_window(self, name, *args, **kwargs):
+ """Load child window, automatically sets parent"""
+ kwargs["parent"] = self.window
+ return self.gapp.load_window(name, *args, **kwargs)
+
+ def load_widgets(self):
+ """Child class should use this to create widgets"""
+
+ def destroy(self, widget=None): # pylint: disable=unused-argument
+ """Destroy the window"""
+ logging.debug("Destroying Window '%s'", self.name)
+ self.window.destroy()
+ # We don't need to call self.exit(), handeled by window event.
+
+ def pre_exit(self):
+ """Internal method for what to do when the window has died"""
+
+ def exit(self, widget=None):
+ """Called when the window needs to exit."""
+ # Is the signal called by the window or by something else?
+ if not widget or not isinstance(widget, Gtk.Window):
+ self.destroy()
+ # Clean up any required processes
+ self.pre_exit()
+ if self.parent:
+ # We assume the parent didn't load another gtk loop
+ self.parent.set_sensitive(True)
+ # Exit our entire app if this is the primary window
+ # Or just remove from parent window list, which may still exit.
+ if self.primary:
+ logging.debug("Exiting the application")
+ self.gapp.exit()
+ else:
+ logging.debug("Removing Window %s from parent", self.name)
+ self.gapp.remove_window(self)
+ # Now finish up what ever is left to do now the window is dead.
+ self.dead = True
+ self.post_exit()
+ return widget
+
+ def post_exit(self):
+ """Called after we've killed the window"""
+
+ def if_widget(self, name):
+ """
+ Attempt to get the widget from gtk, but if not return a fake that won't
+ cause any trouble if we don't further check if it's real.
+ """
+ return self.widget(name) or FakeWidget(name)
+
+ def replace(self, old, new):
+ """Replace the old widget with the new widget"""
+ if isinstance(old, str):
+ old = self.widget(old)
+ if isinstance(new, str):
+ new = self.widget(new)
+ target = old.get_parent()
+ source = new.get_parent()
+ if target is not None:
+ if source is not None:
+ source.remove(new)
+ target.remove(old)
+ target.add(new)
+
+ @staticmethod
+ def get_widget_name(obj):
+ """Return the widget's name in the builder file"""
+ return Gtk.Buildable.get_name(obj)
+
+
+class ChildWindow(Window):
+ """
+ Base class for child window objects, these child windows are typically
+ window objects in the same gtk builder file as their parents. If you just want
+ to make a window that interacts with a parent window, use the normal
+ Window class and call with the optional parent attribute.
+ """
+
+ primary = False
+
+
+class FakeWidget:
+ """A fake widget class that can take calls"""
+
+ def __init__(self, name):
+ self._name = name
+
+ def __getattr__(self, name):
+ def _fake(*args, **kwargs):
+ logging.info("Calling fake method: %s:%s", args, kwargs)
+
+ return _fake
+
+ def __bool__(self):
+ return False
diff --git a/share/extensions/inkex/interfaces/IElement.py b/share/extensions/inkex/interfaces/IElement.py
new file mode 100644
index 0000000..3e9df53
--- /dev/null
+++ b/share/extensions/inkex/interfaces/IElement.py
@@ -0,0 +1,39 @@
+"""Element abstractions for type comparisons without circular imports
+
+.. versionadded:: 1.2"""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+
+import sys
+from lxml import etree
+
+if sys.version_info >= (3, 8):
+ from typing import Protocol
+else:
+ from typing_extensions import Protocol
+
+
+class IBaseElement(ABC, etree.ElementBase):
+ """Abstraction for BaseElement to avoid circular imports"""
+
+ @abstractmethod
+ def get_id(self, as_url=0):
+ """Returns the element ID. If not set, generates a unique ID."""
+ raise NotImplementedError
+
+
+class BaseElementProtocol(Protocol):
+ """Abstraction for BaseElement, to be used as typehint in mixin classes"""
+
+ def get_id(self, as_url=0) -> str:
+ """Returns the element ID. If not set, generates a unique ID."""
+
+ @property
+ def root(self) -> ISVGDocumentElement:
+ """Returns the element's root."""
+
+
+class ISVGDocumentElement(IBaseElement):
+ """Abstraction for SVGDocumentElement"""
diff --git a/share/extensions/inkex/interfaces/__init__.py b/share/extensions/inkex/interfaces/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/share/extensions/inkex/interfaces/__init__.py
diff --git a/share/extensions/inkex/inx.py b/share/extensions/inkex/inx.py
new file mode 100644
index 0000000..2360bc6
--- /dev/null
+++ b/share/extensions/inkex/inx.py
@@ -0,0 +1,244 @@
+# coding=utf-8
+#
+# Copyright (C) 2018 Martin Owens <doctormo@gmail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Parsing inx files for checking and generating.
+"""
+
+import os
+from inspect import isclass
+from importlib import util
+from lxml import etree
+
+from .base import InkscapeExtension
+from .utils import Boolean
+
+NSS = {
+ "inx": "http://www.inkscape.org/namespace/inkscape/extension",
+ "inkscape": "http://www.inkscape.org/namespaces/inkscape",
+}
+SSN = {b: a for (a, b) in NSS.items()}
+
+
+class InxLookup(etree.CustomElementClassLookup):
+ """Custom inx xml file lookup"""
+
+ def lookup(
+ self, node_type, document, namespace, name
+ ): # pylint: disable=unused-argument
+ if name == "param":
+ return ParamElement
+ return InxElement
+
+
+INX_PARSER = etree.XMLParser()
+INX_PARSER.set_element_class_lookup(InxLookup())
+
+
+class InxFile:
+ """Open an INX file and provide useful functions"""
+
+ name = property(lambda self: self.xml.get_text("name"))
+ ident = property(lambda self: self.xml.get_text("id"))
+ slug = property(lambda self: self.ident.split(".")[-1].title().replace("_", ""))
+ kind = property(lambda self: self.metadata["type"])
+ warnings = property(lambda self: sorted(list(set(self.xml.warnings))))
+
+ def __init__(self, filename):
+ if isinstance(filename, str) and "<" in filename:
+ filename = filename.encode("utf8")
+ if isinstance(filename, bytes) and b"<" in filename:
+ self.filename = None
+ self.doc = etree.ElementTree(etree.fromstring(filename, parser=INX_PARSER))
+ else:
+ self.filename = os.path.basename(filename)
+ self.doc = etree.parse(filename, parser=INX_PARSER)
+ self.xml = self.doc.getroot()
+ self.xml.warnings = []
+
+ def __repr__(self):
+ return f"<inx '{self.filename}' '{self.name}'>"
+
+ @property
+ def script(self):
+ """Returns information about the called script"""
+ command = self.xml.find_one("script/command")
+ if command is None:
+ return {}
+ return {
+ "interpreter": command.get("interpreter", None),
+ "location": command.get("location", None),
+ "script": command.text,
+ }
+
+ @property
+ def extension_class(self):
+ """Attempt to get the extension class"""
+ script = self.script.get("script", None)
+ if script is not None:
+ name = script[:-3].replace("/", ".")
+ spec = util.spec_from_file_location(name, script)
+ mod = util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ for value in mod.__dict__.values():
+ if (
+ "Base" not in name
+ and isclass(value)
+ and value.__module__ == name
+ and issubclass(value, InkscapeExtension)
+ ):
+ return value
+ return None
+
+ @property
+ def metadata(self):
+ """Returns information about what type of extension this is"""
+ effect = self.xml.find_one("effect")
+ output = self.xml.find_one("output")
+ inputs = self.xml.find_one("input")
+ data = {}
+ if effect is not None:
+ template = self.xml.find_one("inkscape:templateinfo")
+ if template is not None:
+ data["type"] = "template"
+ data["desc"] = self.xml.get_text(
+ "templateinfo/shortdesc", nss="inkscape"
+ )
+ data["author"] = self.xml.get_text(
+ "templateinfo/author", nss="inkscape"
+ )
+ else:
+ data["type"] = "effect"
+ data["preview"] = Boolean(effect.get("needs-live-preview", "true"))
+ data["objects"] = effect.get_text("object-type", "all")
+ elif inputs is not None:
+ data["type"] = "input"
+ data["extension"] = inputs.get_text("extension")
+ data["mimetype"] = inputs.get_text("mimetype")
+ data["tooltip"] = inputs.get_text("filetypetooltip")
+ data["name"] = inputs.get_text("filetypename")
+ elif output is not None:
+ data["type"] = "output"
+ data["dataloss"] = Boolean(output.get_text("dataloss", "false"))
+ data["extension"] = output.get_text("extension")
+ data["mimetype"] = output.get_text("mimetype")
+ data["tooltip"] = output.get_text("filetypetooltip")
+ data["name"] = output.get_text("filetypename")
+ return data
+
+ @property
+ def menu(self):
+ """Return the menu this effect ends up in"""
+
+ def _recurse_menu(parent):
+ for child in parent.xpath("submenu"):
+ yield child.get("name")
+ for subchild in _recurse_menu(child):
+ yield subchild
+ break # Not more than one menu chain?
+
+ menu = self.xml.find_one("effect/effects-menu")
+ return list(_recurse_menu(menu)) + [self.name]
+
+ @property
+ def params(self):
+ """Get all params at all levels"""
+ # Returns any params at any levels
+ return list(self.xml.xpath("//param"))
+
+
+class InxElement(etree.ElementBase):
+ """Any element in an inx file
+
+ .. versionadded:: 1.1"""
+
+ def set_warning(self, msg):
+ """Set a warning for slightly incorrect inx contents"""
+ root = self.get_root()
+ if hasattr(root, "warnings"):
+ root.warnings.append(msg)
+
+ def get_root(self):
+ """Get the root document element from any element descendent"""
+ if self.getparent() is not None:
+ return self.getparent().get_root()
+ return self
+
+ def get_default_prefix(self):
+ """Set default xml namespace prefix. If none is defined, set warning"""
+ tag = self.get_root().tag
+ if "}" in tag:
+ (url, tag) = tag[1:].split("}", 1)
+ return SSN.get(url, "inx")
+ self.set_warning("No inx xml prefix.")
+ return None # no default prefix
+
+ def apply_nss(self, xpath, nss=None):
+ """Add prefixes to any xpath string"""
+ if nss is None:
+ nss = self.get_default_prefix()
+
+ def _process(seg):
+ if ":" in seg or not seg or not nss:
+ return seg
+ return f"{nss}:{seg}"
+
+ return "/".join([_process(seg) for seg in xpath.split("/")])
+
+ def xpath(self, xpath, nss=None):
+ """Namespace specific xpath searches
+
+ .. versionadded:: 1.1"""
+ return super().xpath(self.apply_nss(xpath, nss=nss), namespaces=NSS)
+
+ def find_one(self, name, nss=None):
+ """Return the first element matching the given name
+
+ .. versionadded:: 1.1"""
+ for elem in self.xpath(name, nss=nss):
+ return elem
+ return None
+
+ def get_text(self, name, default=None, nss=None):
+ """Get text content agnostically"""
+ for pref in ("", "_"):
+ elem = self.find_one(pref + name, nss=nss)
+ if elem is not None and elem.text:
+ if pref == "_":
+ self.set_warning(f"Use of old translation scheme: <_{name}...>")
+ return elem.text
+ return default
+
+
+class ParamElement(InxElement):
+ """
+ A param in an inx file.
+ """
+
+ name = property(lambda self: self.get("name"))
+ param_type = property(lambda self: self.get("type", "string"))
+
+ @property
+ def options(self):
+ """Return a list of option values"""
+ if self.param_type == "notebook":
+ return [option.get("name") for option in self.xpath("page")]
+ return [option.get("value") for option in self.xpath("option")]
+
+ def __repr__(self):
+ return f"<param name='{self.name}' type='{self.param_type}'>"
diff --git a/share/extensions/inkex/localization.py b/share/extensions/inkex/localization.py
new file mode 100644
index 0000000..7de6c57
--- /dev/null
+++ b/share/extensions/inkex/localization.py
@@ -0,0 +1,117 @@
+# coding=utf-8
+#
+# Copyright (C) 2010 Nick Drobchenko, nick@cnc-club.ru
+# Copyright (C) 2005 Aaron Spike, aaron@ekips.org
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Allow extensions to translate messages.
+"""
+
+import gettext
+import os, sys
+
+# Get gettext domain and matching locale directory for translation of extensions strings
+# (both environment variables are set by Inkscape)
+GETTEXT_DOMAIN = os.environ.get("INKEX_GETTEXT_DOMAIN")
+GETTEXT_DIRECTORY = os.environ.get("INKEX_GETTEXT_DIRECTORY")
+
+# INKSCAPE_LOCALEDIR can be used to override the default locale directory Inkscape uses
+INKSCAPE_LOCALEDIR = os.environ.get("INKSCAPE_LOCALEDIR")
+
+
+def localize(domain=GETTEXT_DOMAIN, localedir=GETTEXT_DIRECTORY):
+ """Configure gettext and install _() function into builtins namespace for easy
+ access"""
+
+ # Do not enable translation if GETTEXT_DOMAIN is unset.
+ # This is the case when translationdomain="none", but also when no catalog was
+ # found.
+ # Install a NullTranslation just to be sure
+ # (so we do not get errors about undefined '_')
+ if domain is None:
+ gettext.NullTranslations().install()
+ return
+
+ # Use the default system locale by default,
+ # but prefer LANGUAGE environment variable
+ # (which is set by Inkscape according to UI language)
+ languages = None
+
+ trans = gettext.translation(domain, localedir, languages, fallback=True)
+ trans.install()
+
+
+def inkex_localize():
+ """
+ Return internal Translations instance for translation of the inkex module itself
+ Those will always use the 'inkscape' domain and attempt to lookup the same catalog
+ Inkscape uses
+ """
+
+ domain = "inkscape"
+ localedir = INKSCAPE_LOCALEDIR
+ languages = None
+
+ return gettext.translation(domain, localedir, languages, fallback=True)
+
+
+inkex_gettext = inkex_localize().gettext # pylint: disable=invalid-name
+"""
+Shortcut for gettext. Import as::
+
+ from inkex.localize import inkex_gettext as _
+
+"""
+
+inkex_ngettext = inkex_localize().ngettext
+"""
+Shortcut for ngettext
+
+ .. versionadded:: 1.2
+"""
+
+
+def inkex_fgettext(message, *args, **kwargs):
+ """
+ Shortcut for gettext and subsequent formatting. Import as::
+
+ from inkex.localize import inkex_fgettext as _f
+
+ The positionals and keyword arguments are passed to ``str.format()``.
+
+ The call to xgettext must contain::
+
+ --keyword=_f
+ """
+ return inkex_gettext(message).format(*args, **kwargs)
+
+
+if sys.version_info >= (3, 8):
+ inkex_pgettext = inkex_localize().pgettext
+ """
+ Gettext with context. Import as::
+
+ from inkex.localize import inkex_pgettext as pgettext
+
+ Both parameters **must** be string literals. The call to xgettext must contain::
+
+ --keyword=pgettext:1c,2
+
+ .. versionadded:: 1.2
+ """
+else:
+ inkex_pgettext = lambda context, message: message
diff --git a/share/extensions/inkex/paths.py b/share/extensions/inkex/paths.py
new file mode 100644
index 0000000..a0624d0
--- /dev/null
+++ b/share/extensions/inkex/paths.py
@@ -0,0 +1,2018 @@
+# coding=utf-8
+#
+# Copyright (C) 2018 Martin Owens <doctormo@gmail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+functions for digesting paths
+"""
+from __future__ import annotations
+
+import re
+import copy
+import abc
+
+from math import atan2, cos, pi, sin, sqrt, acos, tan
+from typing import (
+ Any,
+ Type,
+ Dict,
+ Optional,
+ Union,
+ Tuple,
+ List,
+ Generator,
+ TypeVar,
+)
+from .transforms import (
+ Transform,
+ BoundingBox,
+ Vector2d,
+ cubic_extrema,
+ quadratic_extrema,
+)
+from .utils import classproperty, strargs
+
+
+Pathlike = TypeVar("Pathlike", bound="PathCommand")
+AbsolutePathlike = TypeVar("AbsolutePathlike", bound="AbsolutePathCommand")
+
+# All the names that get added to the inkex API itself.
+__all__ = (
+ "Path",
+ "CubicSuperPath",
+ "PathCommand",
+ "AbsolutePathCommand",
+ "RelativePathCommand",
+ # Path commands:
+ "Line",
+ "line",
+ "Move",
+ "move",
+ "ZoneClose",
+ "zoneClose",
+ "Horz",
+ "horz",
+ "Vert",
+ "vert",
+ "Curve",
+ "curve",
+ "Smooth",
+ "smooth",
+ "Quadratic",
+ "quadratic",
+ "TepidQuadratic",
+ "tepidQuadratic",
+ "Arc",
+ "arc",
+ # errors
+ "InvalidPath",
+)
+
+LEX_REX = re.compile(r"([MLHVCSQTAZmlhvcsqtaz])([^MLHVCSQTAZmlhvcsqtaz]*)")
+NONE = lambda obj: obj is not None
+
+
+class InvalidPath(ValueError):
+ """Raised when given an invalid path string"""
+
+
+class PathCommand(abc.ABC):
+ """
+ Base class of all path commands
+ """
+
+ # Number of arguments that follow this path commands letter
+ nargs = -1
+
+ @classproperty # From python 3.9 on, just combine @classmethod and @property
+ def name(cls): # pylint: disable=no-self-argument
+ """The full name of the segment (i.e. Line, Arc, etc)"""
+ return cls.__name__ # pylint: disable=no-member
+
+ @classproperty
+ def letter(cls): # pylint: disable=no-self-argument
+ """The single letter representation of this command (i.e. L, A, etc)"""
+ return cls.name[0]
+
+ @classproperty
+ def next_command(self):
+ """The implicit next command. This is for automatic chains where the next
+ command isn't given, just a bunch on numbers which we automatically parse."""
+ return self
+
+ @property
+ def is_relative(self): # type: () -> bool
+ """Whether the command is defined in relative coordinates, i.e. relative to
+ the previous endpoint (lower case path command letter)"""
+ raise NotImplementedError
+
+ @property
+ def is_absolute(self): # type: () -> bool
+ """Whether the command is defined in absolute coordinates (upper case path
+ command letter)"""
+ raise NotImplementedError
+
+ def to_relative(self, prev): # type: (Vector2d) -> RelativePathCommand
+ """Return absolute counterpart for absolute commands or copy for relative"""
+ raise NotImplementedError
+
+ def to_absolute(self, prev): # type: (Vector2d) -> AbsolutePathCommand
+ """Return relative counterpart for relative commands or copy for absolute"""
+ raise NotImplementedError
+
+ def reverse(self, first, prev):
+ """Reverse path command
+
+ .. versionadded:: 1.1"""
+
+ def to_non_shorthand(self, prev, prev_control): # pylint: disable=unused-argument
+ # type: (Vector2d, Vector2d) -> AbsolutePathCommand
+ """Return an absolute non-shorthand command
+
+ .. versionadded:: 1.1"""
+ return self.to_absolute(prev)
+
+ # The precision of the numbers when converting to string
+ number_template = "{:.6g}"
+
+ # Maps single letter path command to corresponding class
+ # (filled at the bottom of file, when all classes already defined)
+ _letter_to_class = {} # type: Dict[str, Type[Any]]
+
+ @staticmethod
+ def letter_to_class(letter):
+ """Returns class for given path command letter"""
+ return PathCommand._letter_to_class[letter]
+
+ @property
+ def args(self): # type: () -> List[float]
+ """Returns path command arguments as tuple of floats"""
+ raise NotImplementedError()
+
+ def control_points(
+ self, first: Vector2d, prev: Vector2d, prev_prev: Vector2d
+ ) -> Union[List[Vector2d], Generator[Vector2d, None, None]]:
+ """Returns list of path command control points"""
+ raise NotImplementedError
+
+ @classmethod
+ def _argt(cls, sep):
+ return sep.join([cls.number_template] * cls.nargs)
+
+ def __str__(self):
+ return f"{self.letter} {self._argt(' ').format(*self.args)}".strip()
+
+ def __repr__(self):
+ # pylint: disable=consider-using-f-string
+ return "{{}}({})".format(self._argt(", ")).format(self.name, *self.args)
+
+ def __eq__(self, other):
+ previous = Vector2d()
+ if type(self) == type(other): # pylint: disable=unidiomatic-typecheck
+ return self.args == other.args
+ if isinstance(other, tuple):
+ return self.args == other
+ if not isinstance(other, PathCommand):
+ raise ValueError("Can't compare types")
+ try:
+ if self.is_relative == other.is_relative:
+ return self.to_curve(previous) == other.to_curve(previous)
+ except ValueError:
+ pass
+ return False
+
+ def end_point(self, first, prev): # type: (Vector2d, Vector2d) -> Vector2d
+ """Returns last control point of path command"""
+ raise NotImplementedError()
+
+ def update_bounding_box(
+ self, first: Vector2d, last_two_points: List[Vector2d], bbox: BoundingBox
+ ):
+ # pylint: disable=unused-argument
+ """Enlarges given bbox to contain path element.
+
+ Args:
+ first (Vector2d): first point of path. Required to calculate Z segment
+ last_two_points (List[Vector2d]): list with last two control points in abs
+ coords.
+ bbox (BoundingBox): bounding box to update
+ """
+
+ raise NotImplementedError(f"Bounding box is not implemented for {self.name}")
+
+ def to_curve(self, prev, prev_prev=Vector2d()):
+ # type: (Vector2d, Vector2d) -> Curve
+ """Convert command to :py:class:`Curve`
+
+ Curve().to_curve() returns a copy
+ """
+ raise NotImplementedError(f"To curve not supported for {self.name}")
+
+ def to_curves(self, prev, prev_prev=Vector2d()):
+ # type: (Vector2d, Vector2d) -> List[Curve]
+ """Convert command to list of :py:class:`Curve` commands"""
+ return [self.to_curve(prev, prev_prev)]
+
+ def to_line(self, prev):
+ # type: (Vector2d) -> Line
+ """Converts this segment to a line (copies if already a line)"""
+ return Line(*self.end_point(Vector2d(), prev))
+
+
+class RelativePathCommand(PathCommand):
+ """
+ Abstract base class for relative path commands.
+
+ Implements most of methods of :py:class:`PathCommand` through
+ conversion to :py:class:`AbsolutePathCommand`
+ """
+
+ @property
+ def is_relative(self):
+ return True
+
+ @property
+ def is_absolute(self):
+ return False
+
+ def control_points(
+ self, first: Vector2d, prev: Vector2d, prev_prev: Vector2d
+ ) -> Union[List[Vector2d], Generator[Vector2d, None, None]]:
+ return self.to_absolute(prev).control_points(first, prev, prev_prev)
+
+ def to_relative(self, prev):
+ # type: (Pathlike, Vector2d) -> Pathlike
+ return self.__class__(*self.args)
+
+ def update_bounding_box(self, first, last_two_points, bbox):
+ self.to_absolute(last_two_points[-1]).update_bounding_box(
+ first, last_two_points, bbox
+ )
+
+ def end_point(self, first, prev):
+ # type: (Vector2d, Vector2d) -> Vector2d
+ return self.to_absolute(prev).end_point(first, prev)
+
+ def to_curve(self, prev, prev_prev=Vector2d()):
+ # type: (Vector2d, Vector2d) -> Curve
+ return self.to_absolute(prev).to_curve(prev, prev_prev)
+
+ def to_curves(self, prev, prev_prev=Vector2d()):
+ # type: (Vector2d, Vector2d) -> List[Curve]
+ return self.to_absolute(prev).to_curves(prev, prev_prev)
+
+
+class AbsolutePathCommand(PathCommand):
+ """Absolute path command. Unlike :py:class:`RelativePathCommand` can be transformed
+ directly."""
+
+ @property
+ def is_relative(self):
+ return False
+
+ @property
+ def is_absolute(self):
+ return True
+
+ def to_absolute(
+ self, prev
+ ): # type: (AbsolutePathlike, Vector2d) -> AbsolutePathlike
+ return self.__class__(*self.args)
+
+ def transform(
+ self, transform
+ ): # type: (AbsolutePathlike, Transform) -> AbsolutePathlike
+ """Returns new transformed segment
+
+ :param transform: a transformation to apply
+ """
+ raise NotImplementedError()
+
+ def rotate(
+ self, degrees, center
+ ): # type: (AbsolutePathlike, float, Vector2d) -> AbsolutePathlike
+ """
+ Returns new transformed segment
+
+ :param degrees: rotation angle in degrees
+ :param center: invariant point of rotation
+ """
+ return self.transform(Transform(rotate=(degrees, center[0], center[1])))
+
+ def translate(self, dr): # type: (AbsolutePathlike, Vector2d) -> AbsolutePathlike
+ """Translate or scale this path command by dr"""
+ return self.transform(Transform(translate=dr))
+
+ def scale(
+ self, factor
+ ): # type: (AbsolutePathlike, Union[float, Tuple[float,float]]) -> AbsolutePathlike
+ """Returns new transformed segment
+
+ :param factor: scale or (scale_x, scale_y)
+ """
+ return self.transform(Transform(scale=factor))
+
+
+class Line(AbsolutePathCommand):
+ """Line segment"""
+
+ nargs = 2
+
+ @property
+ def args(self):
+ return self.x, self.y
+
+ def __init__(self, x, y):
+ self.x = x
+ self.y = y
+
+ def update_bounding_box(self, first, last_two_points, bbox):
+ bbox += BoundingBox(
+ (last_two_points[-1].x, self.x), (last_two_points[-1].y, self.y)
+ )
+
+ def control_points(self, first, prev, prev_prev):
+ # type: (Vector2d, Vector2d, Vector2d) -> Generator[Vector2d, None, None]
+ yield Vector2d(self.x, self.y)
+
+ def to_relative(self, prev):
+ # type: (Vector2d) -> line
+ return line(self.x - prev.x, self.y - prev.y)
+
+ def transform(self, transform):
+ # type: (Line, Transform) -> Line
+ return Line(*transform.apply_to_point((self.x, self.y)))
+
+ def end_point(self, first, prev):
+ # type: (Vector2d, Vector2d) -> Vector2d
+ return Vector2d(self.x, self.y)
+
+ def to_curve(self, prev, prev_prev=Vector2d()):
+ # type: (Vector2d, Optional[Vector2d]) -> Curve
+ return Curve(prev.x, prev.y, self.x, self.y, self.x, self.y)
+
+ def reverse(self, first, prev):
+ return Line(prev.x, prev.y)
+
+
+class line(RelativePathCommand): # pylint: disable=invalid-name
+ """Relative line segment"""
+
+ nargs = 2
+
+ @property
+ def args(self):
+ return self.dx, self.dy
+
+ def __init__(self, dx, dy):
+ self.dx = dx
+ self.dy = dy
+
+ def to_absolute(self, prev): # type: (Vector2d) -> Line
+ return Line(prev.x + self.dx, prev.y + self.dy)
+
+ def reverse(self, first, prev):
+ return line(-self.dx, -self.dy)
+
+
+class Move(AbsolutePathCommand):
+ """Move pen segment without a line"""
+
+ nargs = 2
+ next_command = Line
+
+ @property
+ def args(self):
+ return self.x, self.y
+
+ def __init__(self, x, y):
+ self.x = x
+ self.y = y
+
+ def update_bounding_box(self, first, last_two_points, bbox):
+ bbox += BoundingBox(self.x, self.y)
+
+ def control_points(self, first, prev, prev_prev):
+ # type: (Vector2d, Vector2d, Vector2d) -> Generator[Vector2d, None, None]
+ yield Vector2d(self.x, self.y)
+
+ def to_relative(self, prev):
+ # type: (Vector2d) -> move
+ return move(self.x - prev.x, self.y - prev.y)
+
+ def transform(self, transform):
+ # type: (Transform) -> Move
+ return Move(*transform.apply_to_point((self.x, self.y)))
+
+ def end_point(self, first, prev):
+ # type: (Vector2d, Vector2d) -> Vector2d
+ return Vector2d(self.x, self.y)
+
+ def to_curve(self, prev, prev_prev=Vector2d()):
+ # type: (Vector2d, Optional[Vector2d]) -> Curve
+ raise ValueError("Move segments can not be changed into curves.")
+
+ def reverse(self, first, prev):
+ return Move(prev.x, prev.y)
+
+
+class move(RelativePathCommand): # pylint: disable=invalid-name
+ """Relative move segment"""
+
+ nargs = 2
+ next_command = line
+
+ @property
+ def args(self):
+ return self.dx, self.dy
+
+ def __init__(self, dx, dy):
+ self.dx = dx
+ self.dy = dy
+
+ def to_absolute(self, prev): # type: (Vector2d) -> Move
+ return Move(prev.x + self.dx, prev.y + self.dy)
+
+ def reverse(self, first, prev):
+ return move(prev.x - first.x, prev.y - first.y)
+
+
+class ZoneClose(AbsolutePathCommand):
+ """Close segment to finish a path"""
+
+ nargs = 0
+ next_command = Move
+
+ @property
+ def args(self):
+ return ()
+
+ def update_bounding_box(self, first, last_two_points, bbox):
+ pass
+
+ def transform(self, transform):
+ # type: (Transform) -> ZoneClose
+ return ZoneClose()
+
+ def control_points(self, first, prev, prev_prev):
+ # type: (Vector2d, Vector2d, Vector2d) -> Generator[Vector2d, None, None]
+ yield first
+
+ def to_relative(self, prev):
+ # type: (Vector2d) -> zoneClose
+ return zoneClose()
+
+ def end_point(self, first, prev):
+ # type: (Vector2d, Vector2d) -> Vector2d
+ return first
+
+ def to_curve(self, prev, prev_prev=Vector2d()):
+ # type: (Vector2d, Optional[Vector2d]) -> Curve
+ raise ValueError("ZoneClose segments can not be changed into curves.")
+
+ def reverse(self, first, prev):
+ return Line(prev.x, prev.y)
+
+
+class zoneClose(RelativePathCommand): # pylint: disable=invalid-name
+ """Same as above (svg says no difference)"""
+
+ nargs = 0
+ next_command = Move
+
+ @property
+ def args(self):
+ return ()
+
+ def to_absolute(self, prev):
+ return ZoneClose()
+
+ def reverse(self, first, prev):
+ return line(prev.x - first.x, prev.y - first.y)
+
+
+class Horz(AbsolutePathCommand):
+ """Horizontal Line segment"""
+
+ nargs = 1
+
+ @property
+ def args(self):
+ return (self.x,)
+
+ def __init__(self, x):
+ self.x = x
+
+ def update_bounding_box(self, first, last_two_points, bbox):
+ bbox += BoundingBox((last_two_points[-1].x, self.x), last_two_points[-1].y)
+
+ def control_points(self, first, prev, prev_prev):
+ # type: (Vector2d, Vector2d, Vector2d) -> Generator[Vector2d, None, None]
+ yield Vector2d(self.x, prev.y)
+
+ def to_relative(self, prev):
+ # type: (Vector2d) -> horz
+ return horz(self.x - prev.x)
+
+ def to_non_shorthand(self, prev, prev_control):
+ # type: (Vector2d, Vector2d) -> Line
+ return self.to_line(prev)
+
+ def transform(self, transform):
+ # type: (Pathlike, Transform) -> Pathlike
+ raise ValueError("Horizontal lines can't be transformed directly.")
+
+ def end_point(self, first, prev):
+ # type: (Vector2d, Vector2d) -> Vector2d
+ return Vector2d(self.x, prev.y)
+
+ def to_curve(self, prev, prev_prev=Vector2d()):
+ # type: (Vector2d, Optional[Vector2d]) -> Curve
+ """Convert a horizontal line into a curve"""
+ return self.to_line(prev).to_curve(prev)
+
+ def to_line(self, prev):
+ # type: (Vector2d) -> Line
+ """Return this path command as a Line instead"""
+ return Line(self.x, prev.y)
+
+ def reverse(self, first, prev):
+ return Horz(prev.x)
+
+
+class horz(RelativePathCommand): # pylint: disable=invalid-name
+ """Relative horz line segment"""
+
+ nargs = 1
+
+ @property
+ def args(self):
+ return (self.dx,)
+
+ def __init__(self, dx):
+ self.dx = dx
+
+ def to_absolute(self, prev): # type: (Vector2d) -> Horz
+ return Horz(prev.x + self.dx)
+
+ def to_non_shorthand(self, prev, prev_control):
+ # type: (Vector2d, Vector2d) -> Line
+ return self.to_line(prev)
+
+ def to_line(self, prev): # type: (Vector2d) -> Line
+ """Return this path command as a Line instead"""
+ return Line(prev.x + self.dx, prev.y)
+
+ def reverse(self, first, prev):
+ return horz(-self.dx)
+
+
+class Vert(AbsolutePathCommand):
+ """Vertical Line segment"""
+
+ nargs = 1
+
+ @property
+ def args(self):
+ return (self.y,)
+
+ def __init__(self, y):
+ self.y = y
+
+ def update_bounding_box(self, first, last_two_points, bbox):
+ bbox += BoundingBox(last_two_points[-1].x, (last_two_points[-1].y, self.y))
+
+ def transform(self, transform): # type: (Pathlike, Transform) -> Pathlike
+ raise ValueError("Vertical lines can't be transformed directly.")
+
+ def control_points(self, first, prev, prev_prev):
+ # type: (Vector2d, Vector2d, Vector2d) -> Generator[Vector2d, None, None]
+ yield Vector2d(prev.x, self.y)
+
+ def to_non_shorthand(self, prev, prev_control):
+ # type: (Vector2d, Vector2d) -> Line
+ return self.to_line(prev)
+
+ def to_relative(self, prev):
+ # type: (Vector2d) -> vert
+ return vert(self.y - prev.y)
+
+ def end_point(self, first, prev):
+ # type: (Vector2d, Vector2d) -> Vector2d
+ return Vector2d(prev.x, self.y)
+
+ def to_line(self, prev):
+ # type: (Vector2d) -> Line
+ """Return this path command as a line instead"""
+ return Line(prev.x, self.y)
+
+ def to_curve(
+ self, prev, prev_prev=Vector2d()
+ ): # type: (Vector2d, Optional[Vector2d]) -> Curve
+ """Convert a horizontal line into a curve"""
+ return self.to_line(prev).to_curve(prev)
+
+ def reverse(self, first, prev):
+ return Vert(prev.y)
+
+
+class vert(RelativePathCommand): # pylint: disable=invalid-name
+ """Relative vertical line segment"""
+
+ nargs = 1
+
+ @property
+ def args(self):
+ return (self.dy,)
+
+ def __init__(self, dy):
+ self.dy = dy
+
+ def to_absolute(self, prev): # type: (Vector2d) -> Vert
+ return Vert(prev.y + self.dy)
+
+ def to_non_shorthand(self, prev, prev_control):
+ # type: (Vector2d, Vector2d) -> Line
+ return self.to_line(prev)
+
+ def to_line(self, prev): # type: (Vector2d) -> Line
+ """Return this path command as a line instead"""
+ return Line(prev.x, prev.y + self.dy)
+
+ def reverse(self, first, prev):
+ return vert(-self.dy)
+
+
+class Curve(AbsolutePathCommand):
+ """Absolute Curved Line segment"""
+
+ nargs = 6
+
+ @property
+ def args(self):
+ return self.x2, self.y2, self.x3, self.y3, self.x4, self.y4
+
+ def __init__(self, x2, y2, x3, y3, x4, y4): # pylint: disable=too-many-arguments
+ self.x2 = x2
+ self.y2 = y2
+
+ self.x3 = x3
+ self.y3 = y3
+
+ self.x4 = x4
+ self.y4 = y4
+
+ def update_bounding_box(self, first, last_two_points, bbox):
+
+ x1, x2, x3, x4 = last_two_points[-1].x, self.x2, self.x3, self.x4
+ y1, y2, y3, y4 = last_two_points[-1].y, self.y2, self.y3, self.y4
+
+ if not (x1 in bbox.x and x2 in bbox.x and x3 in bbox.x and x4 in bbox.x):
+ bbox.x += cubic_extrema(x1, x2, x3, x4)
+
+ if not (y1 in bbox.y and y2 in bbox.y and y3 in bbox.y and y4 in bbox.y):
+ bbox.y += cubic_extrema(y1, y2, y3, y4)
+
+ def transform(self, transform):
+ # type: (Transform) -> Curve
+ x2, y2 = transform.apply_to_point((self.x2, self.y2))
+ x3, y3 = transform.apply_to_point((self.x3, self.y3))
+ x4, y4 = transform.apply_to_point((self.x4, self.y4))
+ return Curve(x2, y2, x3, y3, x4, y4)
+
+ def control_points(self, first, prev, prev_prev):
+ # type: (Vector2d, Vector2d, Vector2d) -> Generator[Vector2d, None, None]
+ yield Vector2d(self.x2, self.y2)
+ yield Vector2d(self.x3, self.y3)
+ yield Vector2d(self.x4, self.y4)
+
+ def to_relative(self, prev): # type: (Vector2d) -> curve
+ return curve(
+ self.x2 - prev.x,
+ self.y2 - prev.y,
+ self.x3 - prev.x,
+ self.y3 - prev.y,
+ self.x4 - prev.x,
+ self.y4 - prev.y,
+ )
+
+ def end_point(self, first, prev):
+ return Vector2d(self.x4, self.y4)
+
+ def to_curve(
+ self, prev, prev_prev=Vector2d()
+ ): # type: (Vector2d, Optional[Vector2d]) -> Curve
+ """No conversion needed, pass-through, returns self"""
+ return Curve(*self.args)
+
+ def to_bez(self):
+ """Returns the list of coords for SuperPath"""
+ return [list(self.args[:2]), list(self.args[2:4]), list(self.args[4:6])]
+
+ def reverse(self, first, prev):
+ return Curve(self.x3, self.y3, self.x2, self.y2, prev.x, prev.y)
+
+
+class curve(RelativePathCommand): # pylint: disable=invalid-name
+ """Relative curved line segment"""
+
+ nargs = 6
+
+ @property
+ def args(self):
+ return self.dx2, self.dy2, self.dx3, self.dy3, self.dx4, self.dy4
+
+ def __init__(
+ self, dx2, dy2, dx3, dy3, dx4, dy4
+ ): # pylint: disable=too-many-arguments
+ self.dx2 = dx2
+ self.dy2 = dy2
+
+ self.dx3 = dx3
+ self.dy3 = dy3
+
+ self.dx4 = dx4
+ self.dy4 = dy4
+
+ def to_absolute(self, prev): # type: (Vector2d) -> Curve
+ return Curve(
+ self.dx2 + prev.x,
+ self.dy2 + prev.y,
+ self.dx3 + prev.x,
+ self.dy3 + prev.y,
+ self.dx4 + prev.x,
+ self.dy4 + prev.y,
+ )
+
+ def reverse(self, first, prev):
+ return curve(
+ -self.dx4 + self.dx3,
+ -self.dy4 + self.dy3,
+ -self.dx4 + self.dx2,
+ -self.dy4 + self.dy2,
+ -self.dx4,
+ -self.dy4,
+ )
+
+
+class Smooth(AbsolutePathCommand):
+ """Absolute Smoothed Curved Line segment"""
+
+ nargs = 4
+
+ @property
+ def args(self):
+ return self.x3, self.y3, self.x4, self.y4
+
+ def __init__(self, x3, y3, x4, y4):
+
+ self.x3 = x3
+ self.y3 = y3
+
+ self.x4 = x4
+ self.y4 = y4
+
+ def update_bounding_box(self, first, last_two_points, bbox):
+ self.to_curve(last_two_points[-1], last_two_points[-2]).update_bounding_box(
+ first, last_two_points, bbox
+ )
+
+ def control_points(self, first, prev, prev_prev):
+ # type: (Vector2d, Vector2d, Vector2d) -> Generator[Vector2d, None, None]
+
+ x1, x2, x3, x4 = prev_prev.x, prev.x, self.x3, self.x4
+ y1, y2, y3, y4 = prev_prev.y, prev.y, self.y3, self.y4
+
+ # infer reflected point
+ x2 = 2 * x2 - x1
+ y2 = 2 * y2 - y1
+
+ yield Vector2d(x2, y2)
+ yield Vector2d(x3, y3)
+ yield Vector2d(x4, y4)
+
+ def to_non_shorthand(self, prev, prev_control):
+ # type: (Vector2d, Vector2d) -> Curve
+ return self.to_curve(prev, prev_control)
+
+ def to_relative(self, prev): # type: (Vector2d) -> smooth
+ return smooth(
+ self.x3 - prev.x, self.y3 - prev.y, self.x4 - prev.x, self.y4 - prev.y
+ )
+
+ def transform(self, transform):
+ # type: (Transform) -> Smooth
+ x3, y3 = transform.apply_to_point((self.x3, self.y3))
+ x4, y4 = transform.apply_to_point((self.x4, self.y4))
+ return Smooth(x3, y3, x4, y4)
+
+ def end_point(self, first, prev):
+ return Vector2d(self.x4, self.y4)
+
+ def to_curve(self, prev, prev_prev=Vector2d()):
+ # type: (Vector2d, Vector2d) -> Curve
+ """
+ Convert this Smooth curve to a regular curve by creating a mirror
+ set of nodes based on the previous node. Previous should be a curve.
+ """
+ (x2, y2), (x3, y3), (x4, y4) = self.control_points(prev, prev, prev_prev)
+ return Curve(x2, y2, x3, y3, x4, y4)
+
+ def reverse(self, first, prev):
+ return Smooth(self.x3, self.y3, prev.x, prev.y)
+
+
+class smooth(RelativePathCommand): # pylint: disable=invalid-name
+ """Relative smoothed curved line segment"""
+
+ nargs = 4
+
+ @property
+ def args(self):
+ return self.dx3, self.dy3, self.dx4, self.dy4
+
+ def __init__(self, dx3, dy3, dx4, dy4):
+ self.dx3 = dx3
+ self.dy3 = dy3
+
+ self.dx4 = dx4
+ self.dy4 = dy4
+
+ def to_absolute(self, prev): # type: (Vector2d) -> Smooth
+ return Smooth(
+ self.dx3 + prev.x, self.dy3 + prev.y, self.dx4 + prev.x, self.dy4 + prev.y
+ )
+
+ def to_non_shorthand(self, prev, prev_control):
+ # type: (Vector2d, Vector2d) -> Curve
+ return self.to_absolute(prev).to_non_shorthand(prev, prev_control)
+
+ def reverse(self, first, prev):
+ return smooth(-self.dx4 + self.dx3, -self.dy4 + self.dy3, -self.dx4, -self.dy4)
+
+
+class Quadratic(AbsolutePathCommand):
+ """Absolute Quadratic Curved Line segment"""
+
+ nargs = 4
+
+ @property
+ def args(self):
+ return self.x2, self.y2, self.x3, self.y3
+
+ def __init__(self, x2, y2, x3, y3):
+
+ self.x2 = x2
+ self.y2 = y2
+
+ self.x3 = x3
+ self.y3 = y3
+
+ def update_bounding_box(self, first, last_two_points, bbox):
+
+ x1, x2, x3 = last_two_points[-1].x, self.x2, self.x3
+ y1, y2, y3 = last_two_points[-1].y, self.y2, self.y3
+
+ if not (x1 in bbox.x and x2 in bbox.x and x3 in bbox.x):
+ bbox.x += quadratic_extrema(x1, x2, x3)
+
+ if not (y1 in bbox.y and y2 in bbox.y and y3 in bbox.y):
+ bbox.y += quadratic_extrema(y1, y2, y3)
+
+ def control_points(self, first, prev, prev_prev):
+ # type: (Vector2d, Vector2d, Vector2d) -> Generator[Vector2d, None, None]
+ yield Vector2d(self.x2, self.y2)
+ yield Vector2d(self.x3, self.y3)
+
+ def to_relative(self, prev):
+ # type: (Vector2d) -> quadratic
+ return quadratic(
+ self.x2 - prev.x, self.y2 - prev.y, self.x3 - prev.x, self.y3 - prev.y
+ )
+
+ def transform(self, transform):
+ # type: (Transform) -> Quadratic
+ x2, y2 = transform.apply_to_point((self.x2, self.y2))
+ x3, y3 = transform.apply_to_point((self.x3, self.y3))
+ return Quadratic(x2, y2, x3, y3)
+
+ def end_point(self, first, prev):
+ # type: (Vector2d, Vector2d) -> Vector2d
+ return Vector2d(self.x3, self.y3)
+
+ def to_curve(self, prev, prev_prev=Vector2d()):
+ # type: (Vector2d, Vector2d) -> Curve
+ """Attempt to convert a quadratic to a curve"""
+ prev = Vector2d(prev)
+ x1 = 1.0 / 3 * prev.x + 2.0 / 3 * self.x2
+ x2 = 2.0 / 3 * self.x2 + 1.0 / 3 * self.x3
+ y1 = 1.0 / 3 * prev.y + 2.0 / 3 * self.y2
+ y2 = 2.0 / 3 * self.y2 + 1.0 / 3 * self.y3
+ return Curve(x1, y1, x2, y2, self.x3, self.y3)
+
+ def reverse(self, first, prev):
+ return Quadratic(self.x2, self.y2, prev.x, prev.y)
+
+
+class quadratic(RelativePathCommand): # pylint: disable=invalid-name
+ """Relative quadratic line segment"""
+
+ nargs = 4
+
+ @property
+ def args(self):
+ return self.dx2, self.dy2, self.dx3, self.dy3
+
+ def __init__(self, dx2, dy2, dx3, dy3):
+ self.dx2 = dx2
+ self.dx3 = dx3
+ self.dy2 = dy2
+ self.dy3 = dy3
+
+ def to_absolute(self, prev): # type: (Vector2d) -> Quadratic
+ return Quadratic(
+ self.dx2 + prev.x, self.dy2 + prev.y, self.dx3 + prev.x, self.dy3 + prev.y
+ )
+
+ def reverse(self, first, prev):
+ return quadratic(
+ -self.dx3 + self.dx2, -self.dy3 + self.dy2, -self.dx3, -self.dy3
+ )
+
+
+class TepidQuadratic(AbsolutePathCommand):
+ """Continued Quadratic Line segment"""
+
+ nargs = 2
+
+ @property
+ def args(self):
+ return self.x3, self.y3
+
+ def __init__(self, x3, y3):
+ self.x3 = x3
+ self.y3 = y3
+
+ def update_bounding_box(self, first, last_two_points, bbox):
+ self.to_quadratic(last_two_points[-1], last_two_points[-2]).update_bounding_box(
+ first, last_two_points, bbox
+ )
+
+ def control_points(self, first, prev, prev_prev):
+ # type: (Vector2d, Vector2d, Vector2d) -> Generator[Vector2d, None, None]
+
+ x1, x2, x3 = prev_prev.x, prev.x, self.x3
+ y1, y2, y3 = prev_prev.y, prev.y, self.y3
+
+ # infer reflected point
+ x2 = 2 * x2 - x1
+ y2 = 2 * y2 - y1
+
+ yield Vector2d(x2, y2)
+ yield Vector2d(x3, y3)
+
+ def to_non_shorthand(self, prev, prev_control):
+ # type: (Vector2d, Vector2d) -> AbsolutePathCommand
+ return self.to_quadratic(prev, prev_control)
+
+ def to_relative(self, prev): # type: (Vector2d) -> tepidQuadratic
+ return tepidQuadratic(self.x3 - prev.x, self.y3 - prev.y)
+
+ def transform(self, transform):
+ # type: (Transform) -> TepidQuadratic
+ x3, y3 = transform.apply_to_point((self.x3, self.y3))
+ return TepidQuadratic(x3, y3)
+
+ def end_point(self, first, prev):
+ # type: (Vector2d, Vector2d) -> Vector2d
+ return Vector2d(self.x3, self.y3)
+
+ def to_curve(self, prev, prev_prev=Vector2d()):
+ # type: (Vector2d, Vector2d) -> Curve
+ return self.to_quadratic(prev, prev_prev).to_curve(prev)
+
+ def to_quadratic(self, prev, prev_prev):
+ # type: (Vector2d, Vector2d) -> Quadratic
+ """
+ Convert this continued quadratic into a full quadratic
+ """
+ (x2, y2), (x3, y3) = self.control_points(prev, prev, prev_prev)
+ return Quadratic(x2, y2, x3, y3)
+
+ def reverse(self, first, prev):
+ return TepidQuadratic(prev.x, prev.y)
+
+
+class tepidQuadratic(RelativePathCommand): # pylint: disable=invalid-name
+ """Relative continued quadratic line segment"""
+
+ nargs = 2
+
+ @property
+ def args(self):
+ return self.dx3, self.dy3
+
+ def __init__(self, dx3, dy3):
+ self.dx3 = dx3
+ self.dy3 = dy3
+
+ def to_absolute(self, prev):
+ # type: (Vector2d) -> TepidQuadratic
+ return TepidQuadratic(self.dx3 + prev.x, self.dy3 + prev.y)
+
+ def to_non_shorthand(self, prev, prev_control):
+ # type: (Vector2d, Vector2d) -> AbsolutePathCommand
+ return self.to_absolute(prev).to_non_shorthand(prev, prev_control)
+
+ def reverse(self, first, prev):
+ return tepidQuadratic(-self.dx3, -self.dy3)
+
+
+class Arc(AbsolutePathCommand):
+ """Special Arc segment"""
+
+ nargs = 7
+
+ @property
+ def args(self):
+ return (
+ self.rx,
+ self.ry,
+ self.x_axis_rotation,
+ self.large_arc,
+ self.sweep,
+ self.x,
+ self.y,
+ )
+
+ def __init__(
+ self, rx, ry, x_axis_rotation, large_arc, sweep, x, y
+ ): # pylint: disable=too-many-arguments
+ self.rx = rx
+ self.ry = ry
+ self.x_axis_rotation = x_axis_rotation
+ self.large_arc = large_arc
+ self.sweep = sweep
+ self.x = x
+ self.y = y
+
+ def update_bounding_box(self, first, last_two_points, bbox):
+ prev = last_two_points[-1]
+ for seg in self.to_curves(prev=prev):
+ seg.update_bounding_box(first, [None, prev], bbox)
+ prev = seg.end_point(first, prev)
+
+ def control_points(self, first, prev, prev_prev):
+ # type: (Vector2d, Vector2d, Vector2d) -> Generator[Vector2d, None, None]
+ yield Vector2d(self.x, self.y)
+
+ def to_curves(self, prev, prev_prev=Vector2d()):
+ # type: (Vector2d, Vector2d) -> List[Curve]
+ """Convert this arc into bezier curves"""
+ path = CubicSuperPath([arc_to_path(list(prev), self.args)]).to_path(
+ curves_only=True
+ )
+ # Ignore the first move command from to_path()
+ return list(path)[1:]
+
+ def transform(self, transform):
+ # type: (Transform) -> Arc
+ # pylint: disable=invalid-name, too-many-locals
+ x_, y_ = transform.apply_to_point((self.x, self.y))
+
+ T = transform # type: Transform
+ if self.x_axis_rotation != 0:
+ T = T @ Transform(rotate=self.x_axis_rotation)
+ a, c, b, d, _, _ = list(T.to_hexad())
+ # T = | a b |
+ # | c d |
+
+ detT = a * d - b * c
+ detT2 = detT**2
+
+ rx = float(self.rx)
+ ry = float(self.ry)
+
+ if rx == 0.0 or ry == 0.0 or detT2 == 0.0:
+ # invalid Arc parameters
+ # transform only last point
+ return Arc(
+ self.rx,
+ self.ry,
+ self.x_axis_rotation,
+ self.large_arc,
+ self.sweep,
+ x_,
+ y_,
+ )
+
+ A = (d**2 / rx**2 + c**2 / ry**2) / detT2
+ B = -(d * b / rx**2 + c * a / ry**2) / detT2
+ D = (b**2 / rx**2 + a**2 / ry**2) / detT2
+
+ theta = atan2(-2 * B, D - A) / 2
+ theta_deg = theta * 180.0 / pi
+ DA = D - A
+ l2 = 4 * B**2 + DA**2
+
+ if l2 == 0:
+ delta = 0.0
+ else:
+ delta = 0.5 * (-(DA**2) - 4 * B**2) / sqrt(l2)
+
+ half = (A + D) / 2
+
+ rx_ = 1.0 / sqrt(half + delta)
+ ry_ = 1.0 / sqrt(half - delta)
+
+ x_, y_ = transform.apply_to_point((self.x, self.y))
+
+ if detT > 0:
+ sweep = self.sweep
+ else:
+ sweep = 0 if self.sweep > 0 else 1
+
+ return Arc(rx_, ry_, theta_deg, self.large_arc, sweep, x_, y_)
+
+ def to_relative(self, prev):
+ # type: (Vector2d) -> arc
+ return arc(
+ self.rx,
+ self.ry,
+ self.x_axis_rotation,
+ self.large_arc,
+ self.sweep,
+ self.x - prev.x,
+ self.y - prev.y,
+ )
+
+ def end_point(self, first, prev):
+ # type: (Vector2d, Vector2d) -> Vector2d
+ return Vector2d(self.x, self.y)
+
+ def reverse(self, first, prev):
+ return Arc(
+ self.rx,
+ self.ry,
+ self.x_axis_rotation,
+ self.large_arc,
+ 1 - self.sweep,
+ prev.x,
+ prev.y,
+ )
+
+
+class arc(RelativePathCommand): # pylint: disable=invalid-name
+ """Relative Arc line segment"""
+
+ nargs = 7
+
+ @property
+ def args(self):
+ return (
+ self.rx,
+ self.ry,
+ self.x_axis_rotation,
+ self.large_arc,
+ self.sweep,
+ self.dx,
+ self.dy,
+ )
+
+ def __init__(
+ self, rx, ry, x_axis_rotation, large_arc, sweep, dx, dy
+ ): # pylint: disable=too-many-arguments
+ self.rx = rx
+ self.ry = ry
+ self.x_axis_rotation = x_axis_rotation
+ self.large_arc = large_arc
+ self.sweep = sweep
+ self.dx = dx
+ self.dy = dy
+
+ def to_absolute(self, prev): # type: (Vector2d) -> "Arc"
+ x1, y1 = prev
+ return Arc(
+ self.rx,
+ self.ry,
+ self.x_axis_rotation,
+ self.large_arc,
+ self.sweep,
+ self.dx + x1,
+ self.dy + y1,
+ )
+
+ def reverse(self, first, prev):
+ return arc(
+ self.rx,
+ self.ry,
+ self.x_axis_rotation,
+ self.large_arc,
+ 1 - self.sweep,
+ -self.dx,
+ -self.dy,
+ )
+
+
+PathCommand._letter_to_class = { # pylint: disable=protected-access
+ "M": Move,
+ "L": Line,
+ "V": Vert,
+ "H": Horz,
+ "A": Arc,
+ "C": Curve,
+ "S": Smooth,
+ "Z": ZoneClose,
+ "Q": Quadratic,
+ "T": TepidQuadratic,
+ "m": move,
+ "l": line,
+ "v": vert,
+ "h": horz,
+ "a": arc,
+ "c": curve,
+ "s": smooth,
+ "z": zoneClose,
+ "q": quadratic,
+ "t": tepidQuadratic,
+}
+
+
+class Path(list):
+ """A list of segment commands which combine to draw a shape"""
+
+ class PathCommandProxy:
+ """
+ A handy class for Path traverse and coordinate access
+
+ Reduces number of arguments in user code compared to bare
+ :class:`PathCommand` methods
+ """
+
+ def __init__(
+ self, command, first_point, previous_end_point, prev2_control_point
+ ):
+ self.command = command # type: PathCommand
+ self.first_point = first_point # type: Vector2d
+ self.previous_end_point = previous_end_point # type: Vector2d
+ self.prev2_control_point = prev2_control_point # type: Vector2d
+
+ @property
+ def name(self):
+ """The full name of the segment (i.e. Line, Arc, etc)"""
+ return self.command.name
+
+ @property
+ def letter(self):
+ """The single letter representation of this command (i.e. L, A, etc)"""
+ return self.command.letter
+
+ @property
+ def next_command(self):
+ """The implicit next command."""
+ return self.command.next_command
+
+ @property
+ def is_relative(self):
+ """Whether the command is defined in relative coordinates, i.e. relative to
+ the previous endpoint (lower case path command letter)"""
+ return self.command.is_relative
+
+ @property
+ def is_absolute(self):
+ """Whether the command is defined in absolute coordinates (upper case path
+ command letter)"""
+ return self.command.is_absolute
+
+ @property
+ def args(self):
+ """Returns path command arguments as tuple of floats"""
+ return self.command.args
+
+ @property
+ def control_points(self):
+ """Returns list of path command control points"""
+ return self.command.control_points(
+ self.first_point, self.previous_end_point, self.prev2_control_point
+ )
+
+ @property
+ def end_point(self):
+ """Returns last control point of path command"""
+ return self.command.end_point(self.first_point, self.previous_end_point)
+
+ def reverse(self):
+ """Reverse path command"""
+ return self.command.reverse(self.end_point, self.previous_end_point)
+
+ def to_curve(self):
+ """Convert command to :py:class:`Curve`
+ Curve().to_curve() returns a copy
+ """
+ return self.command.to_curve(
+ self.previous_end_point, self.prev2_control_point
+ )
+
+ def to_curves(self):
+ """Convert command to list of :py:class:`Curve` commands"""
+ return self.command.to_curves(
+ self.previous_end_point, self.prev2_control_point
+ )
+
+ def to_absolute(self):
+ """Return relative counterpart for relative commands or copy for absolute"""
+ return self.command.to_absolute(self.previous_end_point)
+
+ def __str__(self):
+ return str(self.command)
+
+ def __repr__(self):
+ return "<" + self.__class__.__name__ + ">" + repr(self.command)
+
+ def __init__(self, path_d=None):
+ super().__init__()
+ if isinstance(path_d, str):
+ # Returns a generator returning PathCommand objects
+ path_d = self.parse_string(path_d)
+ elif isinstance(path_d, CubicSuperPath):
+ path_d = path_d.to_path()
+
+ for item in path_d or ():
+ if isinstance(item, PathCommand):
+ self.append(item)
+ elif isinstance(item, (list, tuple)) and len(item) == 2:
+ if isinstance(item[1], (list, tuple)):
+ self.append(PathCommand.letter_to_class(item[0])(*item[1]))
+ else:
+ self.append(Line(*item))
+ else:
+ raise TypeError(
+ f"Bad path type: {type(path_d).__name__}"
+ f"({type(item).__name__}, ...): {item}"
+ )
+
+ @classmethod
+ def parse_string(cls, path_d):
+ """Parse a path string and generate segment objects"""
+ for cmd, numbers in LEX_REX.findall(path_d):
+ args = list(strargs(numbers))
+ cmd = PathCommand.letter_to_class(cmd)
+ i = 0
+ while i < len(args) or cmd.nargs == 0:
+ if len(args[i : i + cmd.nargs]) != cmd.nargs:
+ return
+ seg = cmd(*args[i : i + cmd.nargs])
+ i += cmd.nargs
+ cmd = seg.next_command
+ yield seg
+
+ def bounding_box(self):
+ # type: () -> Optional[BoundingBox]
+ """Return bounding box of the Path"""
+ if not self:
+ return None
+ iterator = self.proxy_iterator()
+ proxy = next(iterator)
+ bbox = BoundingBox(proxy.first_point.x, proxy.first_point.y)
+ try:
+ while True:
+ proxy = next(iterator)
+ proxy.command.update_bounding_box(
+ proxy.first_point,
+ [
+ proxy.prev2_control_point,
+ proxy.previous_end_point,
+ ],
+ bbox,
+ )
+ except StopIteration:
+ return bbox
+
+ def append(self, cmd):
+ """Append a command to this path including any chained commands"""
+ if isinstance(cmd, list):
+ self.extend(cmd)
+ elif isinstance(cmd, PathCommand):
+ super().append(cmd)
+
+ def translate(self, x, y, inplace=False): # pylint: disable=invalid-name
+ """Move all coords in this path by the given amount"""
+ return self.transform(Transform(translate=(x, y)), inplace=inplace)
+
+ def scale(self, x, y, inplace=False): # pylint: disable=invalid-name
+ """Scale all coords in this path by the given amounts"""
+ return self.transform(Transform(scale=(x, y)), inplace=inplace)
+
+ def rotate(self, deg, center=None, inplace=False):
+ """Rotate the path around the given point"""
+ if center is None:
+ # Default center is center of bbox
+ bbox = self.bounding_box()
+ if bbox:
+ center = bbox.center
+ else:
+ center = Vector2d()
+ center = Vector2d(center)
+ return self.transform(
+ Transform(rotate=(deg, center.x, center.y)), inplace=inplace
+ )
+
+ @property
+ def control_points(self):
+ """Returns all control points of the Path"""
+ prev = Vector2d()
+ prev_prev = Vector2d()
+ first = Vector2d()
+
+ for seg in self: # type: PathCommand
+ cpts = list(seg.control_points(first, prev, prev_prev))
+ if isinstance(seg, (zoneClose, ZoneClose, move, Move)):
+ first = cpts[-1]
+ for cpt in cpts:
+ prev_prev = prev
+ prev = cpt
+ yield cpt
+
+ @property
+ def end_points(self):
+ """Returns all endpoints of all path commands (i.e. the nodes)"""
+ prev = Vector2d()
+ first = Vector2d()
+
+ for seg in self: # type: PathCommand
+ end_point = seg.end_point(first, prev)
+ if isinstance(seg, (zoneClose, ZoneClose, move, Move)):
+ first = end_point
+ prev = end_point
+ yield end_point
+
+ def transform(self, transform, inplace=False):
+ """Convert to new path"""
+ result = Path()
+ previous = Vector2d()
+ previous_new = Vector2d()
+ start_zone = True
+ first = Vector2d()
+ first_new = Vector2d()
+
+ for i, seg in enumerate(self): # type: PathCommand
+ if start_zone:
+ first = seg.end_point(first, previous)
+
+ if isinstance(seg, (horz, Horz, Vert, vert)):
+ seg = seg.to_line(previous)
+
+ if seg.is_relative:
+ new_seg = (
+ seg.to_absolute(previous)
+ .transform(transform)
+ .to_relative(previous_new)
+ )
+ else:
+ new_seg = seg.transform(transform)
+
+ if start_zone:
+ first_new = new_seg.end_point(first_new, previous_new)
+
+ if inplace:
+ self[i] = new_seg
+ else:
+ result.append(new_seg)
+ previous = seg.end_point(first, previous)
+ previous_new = new_seg.end_point(first_new, previous_new)
+ start_zone = isinstance(seg, (zoneClose, ZoneClose))
+ if inplace:
+ return self
+ return result
+
+ def reverse(self):
+ """Returns a reversed path"""
+ result = Path()
+ *_, first = self.end_points
+ closer = None
+
+ # Go through the path in reverse order
+ for index, prcom in reversed(list(enumerate(self.proxy_iterator()))):
+ if isinstance(prcom.command, (Move, move, ZoneClose, zoneClose)):
+ if closer is not None:
+ if len(result) > 0 and isinstance(
+ result[-1], (Line, line, Vert, vert, Horz, horz)
+ ):
+ result.pop() # We can replace simple lines with Z
+ result.append(closer) # replace with same type (rel or abs)
+ if isinstance(prcom.command, (ZoneClose, zoneClose)):
+ closer = prcom.command
+ else:
+ closer = None
+
+ if index == 0:
+ if prcom.letter == "M":
+ result.insert(0, Move(first.x, first.y))
+ elif prcom.letter == "m":
+ result.insert(0, move(first.x, first.y))
+ else:
+ result.append(prcom.reverse())
+
+ return result
+
+ def close(self):
+ """Attempt to close the last path segment"""
+ if self and not isinstance(self[-1], (zoneClose, ZoneClose)):
+ self.append(ZoneClose())
+
+ def proxy_iterator(self):
+ """
+ Yields :py:class:`AugmentedPathIterator`
+
+ :rtype: Iterator[ Path.PathCommandProxy ]
+ """
+
+ previous = Vector2d()
+ prev_prev = Vector2d()
+ first = Vector2d()
+
+ for seg in self: # type: PathCommand#
+ if isinstance(seg, (zoneClose, ZoneClose, move, Move)):
+ first = seg.end_point(first, previous)
+ yield Path.PathCommandProxy(seg, first, previous, prev_prev)
+ if isinstance(
+ seg,
+ (
+ curve,
+ tepidQuadratic,
+ quadratic,
+ smooth,
+ Curve,
+ TepidQuadratic,
+ Quadratic,
+ Smooth,
+ ),
+ ):
+ prev_prev = list(seg.control_points(first, previous, prev_prev))[-2]
+ previous = seg.end_point(first, previous)
+
+ def to_absolute(self):
+ """Convert this path to use only absolute coordinates"""
+ return self._to_absolute(True)
+
+ def to_non_shorthand(self):
+ # type: () -> Path
+ """Convert this path to use only absolute non-shorthand coordinates
+
+ .. versionadded:: 1.1"""
+ return self._to_absolute(False)
+
+ def _to_absolute(self, shorthand: bool) -> Path:
+ """Make entire Path absolute.
+
+ Args:
+ shorthand (bool): If false, then convert all shorthand commands to
+ non-shorthand.
+
+ Returns:
+ Path: the input path, converted to absolute coordinates.
+ """
+
+ abspath = Path()
+
+ previous = Vector2d()
+ first = Vector2d()
+
+ for seg in self: # type: PathCommand
+ if isinstance(seg, (move, Move)):
+ first = seg.end_point(first, previous)
+
+ if shorthand:
+ abspath.append(seg.to_absolute(previous))
+ else:
+ if abspath and isinstance(abspath[-1], (Curve, Quadratic)):
+ prev_control = list(
+ abspath[-1].control_points(Vector2d(), Vector2d(), Vector2d())
+ )[-2]
+ else:
+ prev_control = previous
+
+ abspath.append(seg.to_non_shorthand(previous, prev_control))
+
+ previous = seg.end_point(first, previous)
+
+ return abspath
+
+ def to_relative(self):
+ """Convert this path to use only relative coordinates"""
+ abspath = Path()
+
+ previous = Vector2d()
+ first = Vector2d()
+
+ for seg in self: # type: PathCommand
+ if isinstance(seg, (move, Move)):
+ first = seg.end_point(first, previous)
+
+ abspath.append(seg.to_relative(previous))
+ previous = seg.end_point(first, previous)
+
+ return abspath
+
+ def __str__(self):
+ return " ".join([str(seg) for seg in self])
+
+ def __add__(self, other):
+ acopy = copy.deepcopy(self)
+ if isinstance(other, str):
+ other = Path(other)
+ if isinstance(other, list):
+ acopy.extend(other)
+ return acopy
+
+ def to_arrays(self):
+ """Returns path in format of parsePath output, returning arrays of absolute
+ command data
+
+ .. deprecated:: 1.0
+ This is compatibility function for older API. Should not be used in new code
+
+ """
+ return [[seg.letter, list(seg.args)] for seg in self.to_non_shorthand()]
+
+ def to_superpath(self):
+ """Convert this path into a cubic super path"""
+ return CubicSuperPath(self)
+
+ def copy(self):
+ """Make a copy"""
+ return copy.deepcopy(self)
+
+
+class CubicSuperPath(list):
+ """
+ A conversion of a path into a predictable list of cubic curves which
+ can be operated on as a list of simplified instructions.
+
+ When converting back into a path, all lines, arcs etc will be converted
+ to curve instructions.
+
+ Structure is held as [SubPath[(point_a, bezier, point_b), ...]], ...]
+ """
+
+ def __init__(self, items):
+ super().__init__()
+ self._closed = True
+ self._prev = Vector2d()
+ self._prev_prev = Vector2d()
+
+ if isinstance(items, str):
+ items = Path(items)
+
+ if isinstance(items, Path):
+ items = items.to_absolute()
+
+ for item in items:
+ self.append(item)
+
+ def __str__(self):
+ return str(self.to_path())
+
+ def append(self, item, force_shift=False):
+ """Accept multiple different formats for the data
+
+ .. versionchanged:: 1.2
+ ``force_shift`` parameter has been added
+ """
+ if isinstance(item, list) and len(item) == 2 and isinstance(item[0], str):
+ item = PathCommand.letter_to_class(item[0])(*item[1])
+ coordinate_shift = True
+ if isinstance(item, list) and len(item) == 3 and not force_shift:
+ coordinate_shift = False
+ is_quadratic = False
+ if isinstance(item, PathCommand):
+ if isinstance(item, Move):
+ if self._closed is False:
+ super().append([])
+ item = [list(item.args), list(item.args), list(item.args)]
+ elif isinstance(item, ZoneClose) and self and self[-1]:
+ # This duplicates the first segment to 'close' the path, it's appended
+ # directly because we don't want to last coord to change for the final
+ # segment.
+ self[-1].append(
+ [self[-1][0][0][:], self[-1][0][1][:], self[-1][0][2][:]]
+ )
+ # Then adds a new subpath for the next shape (if any)
+ self._closed = True
+ self._prev.assign(self._first)
+ return
+ elif isinstance(item, Arc):
+ # Arcs are made up of three curves (approximated)
+ for arc_curve in item.to_curves(self._prev, self._prev_prev):
+ x2, y2, x3, y3, x4, y4 = arc_curve.args
+ self.append([[x2, y2], [x3, y3], [x4, y4]], force_shift=True)
+ self._prev_prev.assign(x3, y3)
+ return
+ else:
+ is_quadratic = isinstance(
+ item, (Quadratic, TepidQuadratic, quadratic, tepidQuadratic)
+ )
+ if isinstance(item, (Horz, Vert)):
+ item = item.to_line(self._prev)
+ prp = self._prev_prev
+ if is_quadratic:
+ self._prev_prev = list(
+ item.control_points(self._first, self._prev, prp)
+ )[-2:-1][0]
+ item = item.to_curve(self._prev, prp)
+
+ if isinstance(item, Curve):
+ # Curves are cut into three tuples for the super path.
+ item = item.to_bez()
+
+ if not isinstance(item, list):
+ raise ValueError(f"Unknown super curve item type: {item}")
+
+ if len(item) != 3 or not all(len(bit) == 2 for bit in item):
+ # The item is already a subpath (usually from some other process)
+ if len(item[0]) == 3 and all(len(bit) == 2 for bit in item[0]):
+ super().append(self._clean(item))
+ self._prev_prev = Vector2d(self[-1][-1][0])
+ self._prev = Vector2d(self[-1][-1][1])
+ return
+ raise ValueError(f"Unknown super curve list format: {item}")
+
+ if self._closed:
+ # Closed means that the previous segment is closed so we need a new one
+ # We always append to the last open segment. CSP starts out closed.
+ self._closed = False
+ super().append([])
+
+ if coordinate_shift:
+ if self[-1]:
+ # The last tuple is replaced, it's the coords of where the next segment
+ # will land.
+ self[-1][-1][-1] = item[0][:]
+ # The last coord is duplicated, but is expected to be replaced
+ self[-1].append(item[1:] + copy.deepcopy(item)[-1:])
+ else:
+ # Item is already a csp segment and has already been shifted.
+ self[-1].append(copy.deepcopy(item))
+
+ self._prev = Vector2d(self[-1][-1][1])
+ if not is_quadratic:
+ self._prev_prev = Vector2d(self[-1][-1][0])
+
+ def _clean(self, lst):
+ """Recursively clean lists so they have the same type"""
+ if isinstance(lst, (tuple, list)):
+ return [self._clean(child) for child in lst]
+ return lst
+
+ @property
+ def _first(self):
+ try:
+ return Vector2d(self[-1][0][0])
+ except IndexError:
+ return Vector2d()
+
+ def to_path(self, curves_only=False, rtol=1e-5, atol=1e-8):
+ """Convert the super path back to an svg path
+
+ Arguments: see :func:`to_segments` for parameters"""
+ return Path(list(self.to_segments(curves_only, rtol, atol)))
+
+ def to_segments(self, curves_only=False, rtol=1e-5, atol=1e-8):
+ """Generate a set of segments for this cubic super path
+
+ Arguments:
+ curves_only (bool, optional): If False, curves that can be represented
+ by Lineto / ZoneClose commands, will be. Defaults to False.
+ rtol (float, optional): relative tolerance, passed to :func:`is_line` and
+ :func:`inkex.transforms.ImmutableVector2d.is_close` for checking if a
+ line can be replaced by a ZoneClose command. Defaults to 1e-5.
+
+ .. versionadded:: 1.2
+ atol: absolute tolerance, passed to :func:`is_line` and
+ :func:`inkex.transforms.ImmutableVector2d.is_close`. Defaults to 1e-8.
+
+ .. versionadded:: 1.2"""
+ for subpath in self:
+ previous = []
+ for segment in subpath:
+ if not previous:
+ yield Move(*segment[1][:])
+ elif self.is_line(previous, segment, rtol, atol) and not curves_only:
+ if segment is subpath[-1] and Vector2d(segment[1]).is_close(
+ subpath[0][1], rtol, atol
+ ):
+ yield ZoneClose()
+ else:
+ yield Line(*segment[1][:])
+ else:
+ yield Curve(*(previous[2][:] + segment[0][:] + segment[1][:]))
+ previous = segment
+
+ def transform(self, transform):
+ """Apply a transformation matrix to this super path"""
+ return self.to_path().transform(transform).to_superpath()
+
+ @staticmethod
+ def is_on(pt_a, pt_b, pt_c, tol=1e-8):
+ """Checks if point pt_a is on the line between points pt_b and pt_c
+
+ .. versionadded:: 1.2"""
+ return CubicSuperPath.collinear(pt_a, pt_b, pt_c, tol) and (
+ CubicSuperPath.within(pt_a[0], pt_b[0], pt_c[0])
+ if pt_a[0] != pt_b[0]
+ else CubicSuperPath.within(pt_a[1], pt_b[1], pt_c[1])
+ )
+
+ @staticmethod
+ def collinear(pt_a, pt_b, pt_c, tol=1e-8):
+ """Checks if points pt_a, pt_b, pt_c lie on the same line,
+ i.e. that the cross product (b-a) x (c-a) < tol
+
+ .. versionadded:: 1.2"""
+ return (
+ abs(
+ (pt_b[0] - pt_a[0]) * (pt_c[1] - pt_a[1])
+ - (pt_c[0] - pt_a[0]) * (pt_b[1] - pt_a[1])
+ )
+ < tol
+ )
+
+ @staticmethod
+ def within(val_b, val_a, val_c):
+ """Checks if float val_b is between val_a and val_c
+
+ .. versionadded:: 1.2"""
+ return val_a <= val_b <= val_c or val_c <= val_b <= val_a
+
+ @staticmethod
+ def is_line(previous, segment, rtol=1e-5, atol=1e-8):
+ """Check whether csp segment (two points) can be expressed as a line has retracted handles or the handles
+ can be retracted without loss of information (i.e. both handles lie on the
+ line)
+
+ .. versionchanged:: 1.2
+ Previously, it was only checked if both control points have retracted
+ handles. Now it is also checked if the handles can be retracted without
+ (visible) loss of information (i.e. both handles lie on the line connecting
+ the nodes).
+
+ Arguments:
+ previous: first node in superpath notation
+ segment: second node in superpath notation
+ rtol (float, optional): relative tolerance, passed to
+ :func:`inkex.transforms.ImmutableVector2d.is_close` for checking handle
+ retraction. Defaults to 1e-5.
+
+ .. versionadded:: 1.2
+ atol (float, optional): absolute tolerance, passed to
+ :func:`inkex.transforms.ImmutableVector2d.is_close` for checking handle
+ retraction and
+ :func:`inkex.paths.CubicSuperPath.is_on` for checking if all points
+ (nodes + handles) lie on a line. Defaults to 1e-8.
+
+ .. versionadded:: 1.2
+ """
+
+ retracted = Vector2d(previous[1]).is_close(
+ previous[2], rtol, atol
+ ) and Vector2d(segment[0]).is_close(segment[1], rtol, atol)
+
+ if retracted:
+ return True
+
+ # Can both handles be retracted without loss of information?
+ # Definitely the case if the handles lie on the same line as the two nodes and
+ # in the correct order
+ # E.g. cspbezsplitatlength outputs non-retracted handles when splitting a
+ # straight line
+ return CubicSuperPath.is_on(
+ segment[0], segment[1], previous[2], atol
+ ) and CubicSuperPath.is_on(previous[2], previous[1], segment[0], atol)
+
+
+def arc_to_path(point, params):
+ """Approximates an arc with cubic bezier segments.
+
+ Arguments:
+ point: Starting point (absolute coords)
+ params: Arcs parameters as per
+ https://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands
+
+ Returns a list of triplets of points :
+ [control_point_before, node, control_point_after]
+ (first and last returned triplets are [p1, p1, *] and [*, p2, p2])
+ """
+
+ # pylint: disable=invalid-name, too-many-locals
+ A = point[:]
+ rx, ry, teta, longflag, sweepflag, x2, y2 = params[:]
+ teta = teta * pi / 180.0
+ B = [x2, y2]
+ # Degenerate ellipse
+ if rx == 0 or ry == 0 or A == B:
+ return [[A[:], A[:], A[:]], [B[:], B[:], B[:]]]
+
+ # turn coordinates so that the ellipse morph into a *unit circle* (not 0-centered)
+ mat = matprod((rotmat(teta), [[1.0 / rx, 0.0], [0.0, 1.0 / ry]], rotmat(-teta)))
+ applymat(mat, A)
+ applymat(mat, B)
+
+ k = [-(B[1] - A[1]), B[0] - A[0]]
+ d = k[0] * k[0] + k[1] * k[1]
+ k[0] /= sqrt(d)
+ k[1] /= sqrt(d)
+ d = sqrt(max(0, 1 - d / 4.0))
+ # k is the unit normal to AB vector, pointing to center O
+ # d is distance from center to AB segment (distance from O to the midpoint of AB)
+ # for the last line, remember this is a unit circle, and kd vector is ortogonal to
+ # AB (Pythagorean thm)
+
+ if longflag == sweepflag:
+ # top-right ellipse in SVG example
+ # https://www.w3.org/TR/SVG/images/paths/arcs02.svg
+ d *= -1
+
+ O = [(B[0] + A[0]) / 2.0 + d * k[0], (B[1] + A[1]) / 2.0 + d * k[1]]
+ OA = [A[0] - O[0], A[1] - O[1]]
+ OB = [B[0] - O[0], B[1] - O[1]]
+ start = acos(OA[0] / norm(OA))
+ if OA[1] < 0:
+ start *= -1
+ end = acos(OB[0] / norm(OB))
+ if OB[1] < 0:
+ end *= -1
+ # start and end are the angles from center of the circle to A and to B respectively
+
+ if sweepflag and start > end:
+ end += 2 * pi
+ if (not sweepflag) and start < end:
+ end -= 2 * pi
+
+ NbSectors = int(abs(start - end) * 2 / pi) + 1
+ dTeta = (end - start) / NbSectors
+ v = 4 * tan(dTeta / 4.0) / 3.0
+ # I would use v = tan(dTeta/2)*4*(sqrt(2)-1)/3 ?
+ p = []
+ for i in range(0, NbSectors + 1, 1):
+ angle = start + i * dTeta
+ v1 = [
+ O[0] + cos(angle) - (-v) * sin(angle),
+ O[1] + sin(angle) + (-v) * cos(angle),
+ ]
+ pt = [O[0] + cos(angle), O[1] + sin(angle)]
+ v2 = [O[0] + cos(angle) - v * sin(angle), O[1] + sin(angle) + v * cos(angle)]
+ p.append([v1, pt, v2])
+ p[0][0] = p[0][1][:]
+ p[-1][2] = p[-1][1][:]
+
+ # go back to the original coordinate system
+ mat = matprod((rotmat(teta), [[rx, 0], [0, ry]], rotmat(-teta)))
+ for pts in p:
+ applymat(mat, pts[0])
+ applymat(mat, pts[1])
+ applymat(mat, pts[2])
+ return p
+
+
+def matprod(mlist):
+ """Get the product of the mat"""
+ prod = mlist[0]
+ for mat in mlist[1:]:
+ a00 = prod[0][0] * mat[0][0] + prod[0][1] * mat[1][0]
+ a01 = prod[0][0] * mat[0][1] + prod[0][1] * mat[1][1]
+ a10 = prod[1][0] * mat[0][0] + prod[1][1] * mat[1][0]
+ a11 = prod[1][0] * mat[0][1] + prod[1][1] * mat[1][1]
+ prod = [[a00, a01], [a10, a11]]
+ return prod
+
+
+def rotmat(teta):
+ """Rotate the mat"""
+ return [[cos(teta), -sin(teta)], [sin(teta), cos(teta)]]
+
+
+def applymat(mat, point):
+ """Apply the given mat"""
+ x = mat[0][0] * point[0] + mat[0][1] * point[1]
+ y = mat[1][0] * point[0] + mat[1][1] * point[1]
+ point[0] = x
+ point[1] = y
+
+
+def norm(point):
+ """Normalise"""
+ return sqrt(point[0] * point[0] + point[1] * point[1])
diff --git a/share/extensions/inkex/ports.py b/share/extensions/inkex/ports.py
new file mode 100644
index 0000000..7595231
--- /dev/null
+++ b/share/extensions/inkex/ports.py
@@ -0,0 +1,105 @@
+# coding=utf-8
+#
+# Copyright (C) 2019 Martin Owens <doctormo@gmail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Common access to serial and other computer ports.
+"""
+
+import os
+import sys
+import time
+from .utils import DependencyError, AbortExtension
+
+try:
+ import serial
+ from serial.tools import list_ports
+except ImportError:
+ serial = None
+
+
+class Serial:
+ """
+ Attempt to get access to the computer's serial port.
+
+ with Serial(port_name, ...) as com:
+ com.write(...)
+
+ Provides access to the debug/testing ports which are pretend ports
+ able to accept the same input but allow for debugging.
+ """
+
+ def __init__(self, port, baud=9600, timeout=0.1, **options):
+ self.test = port == "[test]"
+ if self.test:
+ import pty # This does not work on windows #pylint: disable=import-outside-toplevel
+
+ self.controller, self.peripheral = pty.openpty()
+ port = os.ttyname(self.peripheral)
+
+ self.has_serial()
+ self.com = serial.Serial()
+ self.com.port = port
+ self.com.baudrate = int(baud)
+ self.com.timeout = timeout
+ self.set_options(**options)
+
+ def set_options(self, stop=1, size=8, flow=None, parity=None):
+ """Set further options on the serial port"""
+ size = {5: "five", 6: "six", 7: "seven", 8: "eight"}.get(size, size)
+ stop = {"onepointfive": 1.5}.get(stop.lower(), stop)
+ stop = {1: "one", 1.5: "one_point_five", 2: "two"}.get(stop, stop)
+ self.com.bytesize = getattr(serial, str(str(size).upper()) + "BITS")
+ self.com.stopbits = getattr(serial, "STOPBITS_" + str(stop).upper())
+ self.com.parity = getattr(serial, "PARITY_" + str(parity).upper())
+ # set flow control
+ self.com.xonxoff = flow == "xonxoff"
+ self.com.rtscts = flow in ("rtscts", "dsrdtrrtscts")
+ self.com.dsrdtr = flow == "dsrdtrrtscts"
+
+ def __enter__(self):
+ try:
+ # try to establish connection
+ self.com.open()
+ except serial.SerialException as error:
+ raise AbortExtension(
+ "Could not open serial port. Please check your device"
+ " is running, connected and the settings are correct"
+ ) from error
+ return self.com
+
+ def __exit__(self, exc, value, traceback):
+ if not traceback and self.test:
+ output = " " * 1024
+ while len(output) == 1024:
+ time.sleep(0.01)
+ output = os.read(self.controller, 1024)
+ sys.stderr.write(output.decode("utf8"))
+ # self.com.read(2)
+ self.com.close()
+
+ @staticmethod
+ def has_serial():
+ """Late importing of pySerial module"""
+ if serial is None:
+ raise DependencyError("pySerial is required to open serial ports.")
+
+ @staticmethod
+ def list_ports():
+ """Return a list of available serial ports"""
+ Serial.has_serial() # Cause DependencyError error
+ return [hw.name for hw in list_ports.comports(True)]
diff --git a/share/extensions/inkex/properties.py b/share/extensions/inkex/properties.py
new file mode 100644
index 0000000..713e288
--- /dev/null
+++ b/share/extensions/inkex/properties.py
@@ -0,0 +1,800 @@
+# coding=utf-8
+#
+# Copyright (C) 2021 Jonathan Neuhauser, jonathan.neuhauser@outlook.com
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Property management and parsing, CSS cascading, default value storage
+
+.. versionadded:: 1.2
+
+.. data:: all_properties
+
+ A list of all properties, their parser class, and additional information
+ such as whether they are inheritable or can be given as presentation attributes
+"""
+
+from abc import ABC, abstractmethod
+
+import re
+from typing import Tuple, Dict, Type, Union, List, Optional
+from .interfaces.IElement import IBaseElement, ISVGDocumentElement
+
+from .units import parse_unit, convert_unit
+
+from .colors import Color, ColorError
+
+
+class BaseStyleValue:
+ """A class encapsuling a single CSS declaration / presentation_attribute"""
+
+ def __init__(self, declaration=None, attr_name=None, value=None, important=False):
+ self.attr_name: str
+ self.value: str
+ self.important: bool
+ if declaration is not None and ":" in declaration:
+ (
+ self.attr_name,
+ self.value,
+ self.important,
+ ) = BaseStyleValue.parse_declaration(declaration)
+ elif attr_name is not None:
+ self.attr_name = attr_name.strip().lower()
+ if isinstance(value, str):
+ self.value = value.strip()
+ else:
+ # maybe its already parsed? then set it
+ self.value = self.unparse_value(value)
+ self.important = important
+ _ = self.parse_value() # check that we can parse this value
+
+ @classmethod
+ def parse_declaration(cls, declaration: str) -> Tuple[str, str, bool]:
+ """Parse a single css declaration
+
+ Args:
+ declaration (str): a css declaration such as:
+ ``fill: #000 !important;``. The trailing semicolon may be ommitted.
+
+ Raises:
+ ValueError: Unable to parse the declaration
+
+ Returns:
+ Tuple[str, str, bool]: a tuple with key, value and importance
+ """
+ if declaration != "" and ":" in declaration:
+ declaration = declaration.replace(";", "")
+ (name, value) = declaration.split(":", 1)
+ # check whether this is an important declaration
+ important = False
+ if "!important" in value:
+ value = value.replace("!important", "")
+ important = True
+ return (name.strip().lower(), value.strip(), important)
+ raise ValueError("Invalid declaration")
+
+ def parse_value(self, element=None):
+ """Get parsed property value with resolved urls, color, etc.
+
+ Args:
+ element (BaseElement): the SVG element to which this style is applied to
+ currently used for resolving gradients / masks, could be used for
+ computing percentage attributes or calc() attributes [optional]
+
+ Returns:
+ object: parsed property value
+ """
+ if self.value == "inherit":
+ if self.attr_name in all_properties:
+ return self._parse_value(all_properties[self.attr_name][1], element)
+ return None
+ return self._parse_value(self.value, element)
+
+ def _parse_value( # pylint: disable=unused-argument, no-self-use
+ self, value: str, element=None
+ ) -> object:
+ """internal parse method, to be overwritten by derived classes
+
+ Args:
+ value (str): unparsed value
+ element (BaseElement): the SVG element to which this style is applied to
+ [optional]
+
+ Returns:
+ object: the parsed value
+ """
+ return value
+
+ def unparse_value(self, value: object) -> str:
+ """ "Unparses" an object, i.e. converts an object back to an attribute.
+ If the result is invalid, i.e. can't be parsed, an exception is raised.
+
+ Args:
+ value (object): the object to be unparsed
+
+ Returns:
+ str: the attribute value
+ """
+ result = self._unparse_value(value)
+ self._parse_value(result) # check if value can be parsed (value is valid)
+ return result
+
+ def _unparse_value(self, value: object) -> str: # pylint: disable=no-self-use
+ return str(value)
+
+ @property
+ def declaration(self) -> str:
+ """The css declaration corresponding to the StyleValue object
+
+ Returns:
+ str: the css declaration, such as "fill: #000 !important;"
+ """
+ return (
+ self.attr_name
+ + ":"
+ + self.value
+ + (" !important" if self.important else "")
+ )
+
+ @classmethod
+ def factory(
+ cls,
+ declaration: Optional[str] = None,
+ attr_name: Optional[str] = None,
+ value: Optional[object] = None,
+ important: Optional[bool] = False,
+ ):
+ """Create an attribute
+
+ Args:
+ declaration (str, optional): the CSS declaration to parse. Defaults to None.
+ attr_name (str, optional): the attribute name. Defaults to None.
+ value (object, optional): the attribute value. Defaults to None.
+ important (bool, optional): whether the attribute is marked !important.
+ Defaults to False.
+
+ Raises:
+ Errors may also be raised on parsing, so make sure to handle them
+
+ Returns:
+ BaseStyleValue: the parsed style
+ """
+ if declaration is not None and ":" in declaration:
+ attr_name, value, important = BaseStyleValue.parse_declaration(declaration)
+ elif attr_name is not None and value is not None:
+ attr_name = attr_name.strip().lower()
+ if isinstance(value, str):
+ value = value.strip()
+
+ if attr_name in all_properties:
+ valuetype = all_properties[attr_name][0]
+ return valuetype(declaration, attr_name, value, important)
+ return BaseStyleValue(declaration, attr_name, value, important)
+
+ def __eq__(self, other):
+ if not (isinstance(other, BaseStyleValue)):
+ return False
+ if self.declaration != other.declaration:
+ return False
+ return True
+
+ @staticmethod
+ def factory_errorhandled(element=None, declaration="", key="", value=""):
+ """Error handling for the factory method: if something goes wrong during
+ parsing, ignore the attribute
+
+ Args:
+ element (BaseElement, optional): The element this declaration is affecting,
+ for finding gradients ect. Defaults to None.
+ declaration (str, optional): the CSS declaration to parse. Defaults to "".
+ key (str, optional): the attribute name. Defaults to "".
+ value (str, optional): the attribute value. Defaults to "".
+
+ Returns:
+ BaseStyleValue: The parsed style
+ """
+ try:
+ value = BaseStyleValue.factory(
+ declaration=declaration, attr_name=key, value=value
+ )
+ key = value.attr_name
+ # Try to parse the attribute
+ _ = value.parse_value(element)
+ return (key, value)
+ except ValueError:
+ # something went wrong during parsing, e.g. a bad attribute format
+ # or an attribute referencing a missing gradient
+ # -> ignore this declaration
+ pass
+ except ColorError:
+ # The color parsing methods have their own error type
+ pass
+
+
+class AlphaValue(BaseStyleValue):
+ """Stores an alpha value (such as opacity), which may be specified as
+ as percentage or absolute value.
+
+ Reference: https://www.w3.org/TR/css-color/#typedef-alpha-value"""
+
+ def _parse_value(self, value: str, element=None):
+ if value[-1] == "%": # percentage
+ parsed_value = float(value[:-1]) * 0.01
+ else:
+ parsed_value = float(value)
+ if parsed_value < 0:
+ return 0
+ if parsed_value > 1:
+ return 1
+ return parsed_value
+
+ def _unparse_value(self, value: object) -> str:
+ if isinstance(value, (float, int)):
+ if value < 0:
+ return "0"
+ if value > 1:
+ return "1"
+ return str(value)
+ raise ValueError("Value must be number")
+
+
+class ColorValue(BaseStyleValue):
+ """Stores a color value
+
+ Reference: https://drafts.csswg.org/css-color-3/#valuea-def-color"""
+
+ def _parse_value(self, value: str, element=None):
+ if value == "currentColor":
+ if element is not None:
+ style = element.specified_style()
+ return style("color")
+ return None
+ return Color(value)
+
+
+# https://www.w3.org/TR/css3-values/#url-value
+# matches anything inside url() enclosed with single/double quotes
+# (technically a fragment url) or no quotes at all
+URLREGEX = r"url\(\s*('.*?'|\".*?\"|[^\"'].*?)\s*\)"
+
+
+def match_url_and_return_element(string: str, svg):
+ """Parses a string containing an url, e.g. "url(#rect1234)",
+ looks up the element in the svg document and returns it.
+
+ Args:
+ string (str): the string to parse
+ svg (SvgDocumentElement): document referenced in the URL
+
+ Raises:
+ ValueError: if the string has invalid format
+ ValueError: if the referenced element is not found
+
+ Returns:
+ BaseElement: the referenced element
+ """
+ regex = re.compile(URLREGEX)
+ match = regex.match(string)
+ if match:
+ url = match.group(1)
+ paint_server = svg.getElementById(url)
+ return paint_server
+ raise ValueError("invalid URL format")
+
+
+class URLNoneValue(BaseStyleValue):
+ """Stores a value that is either none or an url, such as markers or masks.
+
+ Reference: https://www.w3.org/TR/SVG2/painting.html#VertexMarkerProperties"""
+
+ def _parse_value(self, value: str, element=None):
+ if value == "none":
+ return None
+ if value[0:4] == "url(":
+ if element is not None and self.element_has_root(element):
+ return match_url_and_return_element(value, element.root)
+ return None
+ raise ValueError("Invalid property value")
+
+ def _unparse_value(self, value: object):
+ if isinstance(value, IBaseElement):
+ return f"url(#{value.get_id()})"
+ return super()._unparse_value(value)
+
+ @staticmethod
+ def element_has_root(element) -> bool:
+ "Checks if an element has a root, i.e. if element.root will fail"
+
+ return not (
+ element.getparent() is None and not isinstance(element, ISVGDocumentElement)
+ )
+
+
+class PaintValue(ColorValue, URLNoneValue):
+ """Stores a paint value (such as fill and stroke), which may be specified
+ as color, or url.
+
+ Reference: https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint"""
+
+ def _parse_value(self, value: str, element=None):
+ if value == "none":
+ return None
+ if value in ["context-fill", "context-stroke"]:
+ return value
+ if value == "currentColor":
+ return super()._parse_value(value, element)
+ if value[0:4] == "url(":
+ # First part: fragment url
+ # second part: a fallback color if the url is not found. Colors start with
+ # a letter or a #
+ regex = re.compile(URLREGEX + r"\s*([#\w].*?)?$")
+ match = regex.match(value)
+ if match:
+ url = match.group(1)
+ if element is not None and self.element_has_root(element):
+ paint_server = element.root.getElementById(url)
+ else:
+ return None
+ if paint_server is not None:
+ return paint_server
+ if match.group(2) is None:
+ raise ValueError("Paint server not found")
+ return Color(match.group(2))
+ return Color(value)
+
+ def _unparse_value(self, value: object):
+ if value is None:
+ return "none"
+ return super()._unparse_value(value)
+
+
+class EnumValue(BaseStyleValue):
+ """Stores a value that can only have a finite set of options"""
+
+ def __init__(self, declaration=None, attr_name=None, value=None, important=False):
+ self.valueset = all_properties[attr_name][4]
+ super().__init__(declaration, attr_name, value, important)
+
+ def _parse_value(self, value: str, element=None):
+ if value in self.valueset:
+ return value
+ raise ValueError(
+ f"Value '{value}' is invalid for the property {self.attr_name}. "
+ + f"Allowed values are: {self.valueset + ['inherit']}"
+ )
+
+
+class ShorthandValue(BaseStyleValue, ABC):
+ """Stores a value that sets other values (e.g. the font shorthand)"""
+
+ def apply_shorthand(self, style):
+ """Applies a shorthand attribute to its style, respecting the
+ importance state of the individual attributes.
+
+ Args:
+ style (Style): the style that the shorthand attribute is contained in,
+ and that the shorthand attribute will be applied on
+ """
+ if self.attr_name not in style:
+ return
+
+ dct = self.get_shorthand_changes()
+ importance = self.important
+
+ # they are ordered in the order of adding the style elements.
+ current_keys = list(style.keys())
+ for curkey in dct:
+ perform = False
+ if curkey not in current_keys:
+ # this is the easiest case, just set the element and the importance
+ perform = True
+ else:
+ if importance != style.get_importance(curkey):
+ # different importance, result independent of position
+ perform = importance
+ else:
+ # only apply if style overwrites previous with same importance
+ perform = current_keys.index(curkey) < current_keys.index(
+ self.attr_name
+ )
+
+ if perform:
+ style[curkey] = dct[curkey]
+ style.set_importance(curkey, importance)
+ style.pop(self.attr_name)
+
+ @abstractmethod
+ def get_shorthand_changes(self) -> Dict[str, str]:
+ """calculates the value of affected attributes for this shorthand
+
+ Returns:
+ Dict[str, str]: a dictionary containing the new values of the
+ affected attributes
+ """
+
+
+class FontValue(ShorthandValue):
+ """Logic for the shorthand font property"""
+
+ def get_shorthand_changes(self):
+ keys = [
+ "font-style",
+ "font-variant",
+ "font-weight",
+ "font-stretch",
+ "font-size",
+ "line-height",
+ "font-family",
+ ]
+ options = {
+ key: all_properties[key][4]
+ for key in keys
+ if isinstance(all_properties[key][4], list)
+ }
+ result = {key: all_properties[key][1] for key in keys}
+
+ tokens = [i for i in self.value.split(" ") if i != ""]
+
+ if len(tokens) == 0:
+ return {} # shorthand not set, nothing to do
+
+ while not (len(tokens) == 0):
+ cur = tokens[0]
+ if cur in options["font-style"]:
+ result["font-style"] = cur
+ elif cur in options["font-variant"]:
+ result["font-variant"] = cur
+ elif cur in options["font-weight"]:
+ result["font-weight"] = cur
+ elif cur in options["font-stretch"]:
+ result["font-stretch"] = cur
+ else:
+ if "/" in cur:
+ result["font-size"], result["line-height"] = cur.split("/")
+ else:
+ result["font-size"] = cur
+ result["font-family"] = " ".join(tokens[1:])
+ break
+ tokens = tokens[1:] # remove first element
+ return result
+
+
+class MarkerShorthandValue(ShorthandValue, URLNoneValue):
+ """Logic for the marker shorthand property"""
+
+ def get_shorthand_changes(self):
+ if self.value == "":
+ return {} # shorthand not set, nothing to do
+ return {k: self.value for k in ["marker-start", "marker-end", "marker-mid"]}
+
+ def _parse_value(self, value: str, element=None):
+ # Make sure the parsing routine doesn't choke on an empty shorthand
+ if value == "":
+ return ""
+ return super()._parse_value(value, element)
+
+
+class FontSizeValue(BaseStyleValue):
+ """Logic for the font-size property"""
+
+ def _parse_value(self, value: str, element=None):
+ if element is None:
+ return value # no additional logic in this case
+ try:
+ return element.to_dimensionless(value)
+ except ValueError: # unable to parse font size, e.g. font-size:normal
+ return element.to_dimensionless("12pt")
+
+
+class StrokeDasharrayValue(BaseStyleValue):
+ """Logic for the stroke-dasharray property"""
+
+ def _parse_value(self, value: str, element=None):
+ dashes = re.findall(r"[^,\s]+", value)
+ if len(dashes) == 0 or value == "none":
+ return None # no dasharray applied
+ if not any(parse_unit(i) is None for i in dashes):
+ dashes = [convert_unit(i, "px") for i in dashes]
+ else:
+ return None
+ if any(i < 0 for i in dashes):
+ return None # one negative value makes the dasharray invalid
+ if len(dashes) % 2 == 1:
+ dashes = 2 * dashes
+ return dashes
+
+ def _unparse_value(self, value: object) -> str:
+ if value is None:
+ return "none"
+ if isinstance(value, list):
+ return " ".join(map(str, value))
+ return str(value)
+
+
+# keys: attributes, right side:
+# - Subclass of BaseStyleValue used for instantiating
+# - default value
+# - is presentation attribute
+# - inherited
+# - additional information, such as valid enum values
+# For properties which have no special implementation yet:
+# "(BaseStyleValue, <default>, <inheritance>, None)"
+
+# Source for this list: https://www.w3.org/TR/SVG2/styling.html#PresentationAttributes
+
+
+all_properties: Dict[
+ str, Tuple[Type[BaseStyleValue], str, bool, bool, Union[List[str], None]]
+] = {
+ "alignment-baseline": (
+ EnumValue,
+ "baseline",
+ True,
+ False,
+ [
+ "baseline",
+ "text-bottom",
+ "alphabetic",
+ "ideographic",
+ "middle",
+ "central",
+ "mathematical",
+ "text-top",
+ ],
+ ),
+ "baseline-shift": (BaseStyleValue, "0", True, False, None),
+ "clip": (BaseStyleValue, "auto", True, False, None),
+ "clip-path": (URLNoneValue, "none", True, False, None),
+ "clip-rule": (EnumValue, "nonzero", True, True, ["nonzero", "evenodd"]),
+ # only used for currentColor, which is not yet implemented
+ "color": (PaintValue, "black", True, True, None),
+ "color-interpolation": (
+ EnumValue,
+ "sRGB",
+ True,
+ True,
+ ["sRGB", "auto", "linearRGB"],
+ ),
+ "color-interpolation-filters": (
+ EnumValue,
+ "linearRGB",
+ True,
+ True,
+ ["auto", "sRGB", "linearRGB"],
+ ),
+ "color-rendering": (
+ EnumValue,
+ "auto",
+ True,
+ True,
+ ["auto", "optimizeSpeed", "optimizeQuality"],
+ ),
+ "cursor": (BaseStyleValue, "auto", True, True, None),
+ "direction": (EnumValue, "ltr", True, True, ["ltr", "rtl"]),
+ "display": (
+ EnumValue,
+ "inline",
+ True,
+ False,
+ [
+ "inline",
+ "block",
+ "list-item",
+ "inline-block",
+ "table",
+ "inline-table",
+ "table-row-group",
+ "table-header-group",
+ "table-footer-group",
+ "table-row",
+ "table-column-group",
+ "table-column",
+ "table-cell",
+ "table-caption",
+ "none",
+ ],
+ ), # every value except none is rendered normally
+ "dominant-baseline": (
+ EnumValue,
+ "auto",
+ True,
+ True,
+ [
+ "auto",
+ "text-bottom",
+ "alphabetic",
+ "ideographic",
+ "middle",
+ "central",
+ "mathematical",
+ "hanging",
+ "text-top",
+ ],
+ ),
+ "fill": (
+ PaintValue,
+ "black",
+ True,
+ True,
+ None,
+ ), # the normal fill, not the <animation> one
+ "fill-opacity": (AlphaValue, "1", True, True, None),
+ "fill-rule": (EnumValue, "nonzero", True, True, ["nonzero", "evenodd"]),
+ "filter": (BaseStyleValue, "none", True, False, None),
+ "flood-color": (PaintValue, "black", True, False, None),
+ "flood-opacity": (AlphaValue, "1", True, False, None),
+ "font": (FontValue, "", True, False, None),
+ "font-family": (BaseStyleValue, "sans-serif", True, True, None),
+ "font-size": (FontSizeValue, "medium", True, True, None),
+ "font-size-adjust": (BaseStyleValue, "none", True, True, None),
+ "font-stretch": (
+ EnumValue,
+ "normal",
+ True,
+ True,
+ [
+ "normal",
+ "ultra-condensed",
+ "extra-condensed",
+ "condensed",
+ "semi-condensed",
+ "semi-expanded",
+ "expanded",
+ "extra-expanded",
+ "ultra-expanded",
+ ],
+ ),
+ "font-style": (EnumValue, "normal", True, True, ["normal", "italic", "oblique"]),
+ # a lot more values and subproperties in SVG2 / CSS-Fonts3
+ "font-variant": (EnumValue, "normal", True, True, ["normal", "small-caps"]),
+ "font-weight": (
+ EnumValue,
+ "normal",
+ True,
+ True,
+ ["normal", "bold"] + [str(i) for i in range(100, 901, 100)],
+ ),
+ "glyph-orientation-horizontal": (BaseStyleValue, "0deg", True, True, None),
+ "glyph-orientation-vertical": (BaseStyleValue, "auto", True, True, None),
+ "image-rendering": (
+ EnumValue,
+ "auto",
+ True,
+ True,
+ ["auto", "optimizeQuality", "optimizeSpeed"],
+ ),
+ "letter-spacing": (BaseStyleValue, "normal", True, True, None),
+ "lighting-color": (ColorValue, "normal", True, False, None),
+ "line-height": (BaseStyleValue, "normal", False, True, None),
+ "marker": (MarkerShorthandValue, "", True, True, None),
+ "marker-end": (URLNoneValue, "none", True, True, None),
+ "marker-mid": (URLNoneValue, "none", True, True, None),
+ "marker-start": (URLNoneValue, "none", True, True, None),
+ # is a shorthand for a lot of mask-related properties which Inkscape doesn't support
+ "mask": (URLNoneValue, "none", True, False, None),
+ "opacity": (AlphaValue, "1", True, False, None),
+ "overflow": (
+ EnumValue,
+ "visible",
+ True,
+ False,
+ ["visible", "hidden", "scroll", "auto"],
+ ),
+ "paint-order": (BaseStyleValue, "normal", True, False, None),
+ "pointer-events": (
+ EnumValue,
+ "visiblePainted",
+ True,
+ True,
+ [
+ "bounding-box",
+ "visiblePainted",
+ "visibleFill",
+ "visibleStroke",
+ "visible",
+ "painted",
+ "fill",
+ "stroke",
+ "all",
+ "none",
+ ],
+ ),
+ "shape-rendering": (
+ EnumValue,
+ "visiblePainted",
+ True,
+ True,
+ ["auto", "optimizeSpeed", "crispEdges", "geometricPrecision"],
+ ),
+ "stop-color": (ColorValue, "black", True, False, None),
+ "stop-opacity": (AlphaValue, "1", True, False, None),
+ "stroke": (PaintValue, "none", True, True, None),
+ "stroke-dasharray": (StrokeDasharrayValue, "none", True, True, None),
+ "stroke-dashoffset": (BaseStyleValue, "0", True, True, None),
+ "stroke-linecap": (EnumValue, "butt", True, True, ["butt", "round", "square"]),
+ "stroke-linejoin": (
+ EnumValue,
+ "miter",
+ True,
+ True,
+ ["miter", "miter-clip", "round", "bevel", "arcs"],
+ ),
+ "stroke-miterlimit": (BaseStyleValue, "4", True, True, None),
+ "stroke-opacity": (AlphaValue, "1", True, True, None),
+ "stroke-width": (BaseStyleValue, "1", True, True, None),
+ "text-align": (
+ BaseStyleValue,
+ "start",
+ True,
+ True,
+ None,
+ ), # only HTML property, but used by some unit tests
+ "text-anchor": (EnumValue, "start", True, True, ["start", "middle", "end"]),
+ # shorthand for text-decoration-line, *-style, *-color
+ "text-decoration": (BaseStyleValue, "none", True, True, None),
+ "text-overflow": (EnumValue, "clip", True, False, ["clip", "ellipsis"]),
+ "text-rendering": (
+ EnumValue,
+ "auto",
+ True,
+ True,
+ ["auto", "optimizeSpeed", "optimizeLegibility", "geometricPrecision"],
+ ),
+ "unicode-bidi": (
+ EnumValue,
+ "normal",
+ True,
+ False,
+ [
+ "normal",
+ "embed",
+ "isolate",
+ "bidi-override",
+ "isolate-override",
+ "plaintext",
+ ],
+ ),
+ "vector-effect": (BaseStyleValue, "none", True, False, None),
+ "vertical-align": (BaseStyleValue, "baseline", False, False, None),
+ "visibility": (EnumValue, "visible", True, True, ["visible", "hidden", "collapse"]),
+ "white-space": (
+ EnumValue,
+ "normal",
+ True,
+ True,
+ ["normal", "pre", "nowrap", "pre-wrap", "break-spaces", "pre-line"],
+ ),
+ "word-spacing": (BaseStyleValue, "normal", True, True, None),
+ # including obsolete SVG 1.1 values
+ "writing-mode": (
+ EnumValue,
+ "horizontal-tb",
+ True,
+ True,
+ [
+ "horizontal-tb",
+ "vertical-rl",
+ "vertical-lr",
+ "lr",
+ "lr-tb",
+ "rl",
+ "rl-tb",
+ "tb",
+ "tb-rl",
+ ],
+ ),
+ "-inkscape-font-specification": (BaseStyleValue, "sans-serif", False, True, None),
+}
diff --git a/share/extensions/inkex/styles.py b/share/extensions/inkex/styles.py
new file mode 100644
index 0000000..ae0d334
--- /dev/null
+++ b/share/extensions/inkex/styles.py
@@ -0,0 +1,621 @@
+# coding=utf-8
+#
+# Copyright (C) 2005 Aaron Spike, aaron@ekips.org
+# 2019-2020 Martin Owens
+# 2021 Jonathan Neuhauser, jonathan.neuhauser@outlook.com
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Functions for handling styles and embedded css
+"""
+
+import re
+from collections import OrderedDict
+from typing import MutableMapping, Union, Iterable, TYPE_CHECKING
+
+from .interfaces.IElement import IBaseElement
+
+from .colors import Color
+from .properties import BaseStyleValue, all_properties, ShorthandValue
+from .css import ConditionalRule
+
+if TYPE_CHECKING:
+ from .elements._svg import SvgDocumentElement
+
+
+class Classes(list):
+ """A list of classes applied to an element (used in css and js)"""
+
+ def __init__(self, classes=None, callback=None):
+ self.callback = None
+ if isinstance(classes, str):
+ classes = classes.split()
+ super().__init__(classes or ())
+ self.callback = callback
+
+ def __str__(self):
+ return " ".join(self)
+
+ def _callback(self):
+ if self.callback is not None:
+ self.callback(self)
+
+ def __setitem__(self, index, value):
+ super().__setitem__(index, value)
+ self._callback()
+
+ def append(self, value):
+ value = str(value)
+ if value not in self:
+ super().append(value)
+ self._callback()
+
+ def remove(self, value):
+ value = str(value)
+ if value in self:
+ super().remove(value)
+ self._callback()
+
+ def toggle(self, value):
+ """If exists, remove it, if not, add it"""
+ value = str(value)
+ if value in self:
+ return self.remove(value)
+ return self.append(value)
+
+
+class Style(OrderedDict, MutableMapping[str, Union[str, BaseStyleValue]]):
+ """A list of style directives
+
+ .. versionchanged:: 1.2
+ The Style API now allows for access to parsed / processed styles via the
+ :func:`call` method.
+
+ .. automethod:: __call__
+ .. automethod:: __getitem__
+ .. automethod:: __setitem__
+ """
+
+ color_props = ("stroke", "fill", "stop-color", "flood-color", "lighting-color")
+ opacity_props = ("stroke-opacity", "fill-opacity", "opacity", "stop-opacity")
+ unit_props = "stroke-width"
+ """Dictionary of attributes with units.
+
+ ..versionadded:: 1.2
+ """
+ associated_props = {
+ "fill": "fill-opacity",
+ "stroke": "stroke-opacity",
+ "stop-color": "stop-opacity",
+ }
+ """Dictionary of association between color and opacity attributes.
+
+ .. versionadded:: 1.2
+ """
+
+ def __init__(self, style=None, callback=None, element=None, **kw):
+ self.element = element
+ # This callback is set twice because this is 'pre-initial' data (no callback)
+ self.callback = None
+ # Either a string style or kwargs (with dashes as underscores).
+ style = style or [(k.replace("_", "-"), v) for k, v in kw.items()]
+ if isinstance(style, str):
+ style = self._parse_str(style)
+ # Order raw dictionaries so tests can be made reliable
+ if isinstance(style, dict) and not isinstance(style, OrderedDict):
+ style = [(name, style[name]) for name in sorted(style)]
+ # Should accept dict, Style, parsed string, list etc.
+ super().__init__(style)
+ # Now after the initial data, the callback makes sense.
+ self.callback = callback
+
+ @staticmethod
+ def _parse_str(style: str, element=None) -> Iterable[BaseStyleValue]:
+ """Create a dictionary from the value of a CSS rule (such as an inline style or
+ from an embedded style sheet), including its !important state, parsing the value
+ if possible.
+
+ Args:
+ style: the content of a CSS rule to parse
+ element: the element this style is working on (can be the root SVG, is used
+ for parsing gradients etc.)
+
+ Yields:
+ :class:`~inkex.properties.BaseStyleValue`: the parsed attribute
+ """
+ for declaration in style.split(";"):
+ if ":" in declaration:
+ result = BaseStyleValue.factory_errorhandled(
+ element, declaration=declaration.strip()
+ )
+ if result is not None:
+ yield result
+
+ @staticmethod
+ def parse_str(style: str, element=None):
+ """Parse a style passed as string"""
+ return Style(style, element=element)
+
+ def __str__(self):
+ """Format an inline style attribute from a dictionary"""
+ return self.to_str()
+
+ def to_str(self, sep=";"):
+ """Convert to string using a custom delimiter"""
+ return sep.join([self.get_store(key).declaration for key in self])
+
+ def __add__(self, other):
+ """Add two styles together to get a third, composing them"""
+ ret = self.copy()
+ ret.update(Style(other))
+ return ret
+
+ def __iadd__(self, other):
+ """Add style to this style, the same as ``style.update(dict)``"""
+ self.update(other)
+ return self
+
+ def __sub__(self, other):
+ """Remove keys and return copy"""
+ ret = self.copy()
+ ret.__isub__(other)
+ return ret
+
+ def __isub__(self, other):
+ """Remove keys from this style, list of keys or other style dictionary"""
+ for key in other:
+ self.pop(key, None)
+ return self
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+ def copy(self):
+ """Create a copy of the style.
+
+ .. versionadded:: 1.2"""
+ ret = Style({}, element=self.element)
+ for key, value in super().items():
+ ret[key] = value
+ return ret
+
+ def update(self, other):
+ """Update, while respecting ``!important`` declarations."""
+ if not isinstance(other, Style):
+ other = Style(other)
+ # only update
+ if isinstance(other, Style):
+ for key in other.keys():
+ if not (self.get_importance(key) and not other.get_importance(key)):
+ self[key] = other.get_store(key)
+
+ if self.callback is not None:
+ self.callback(self)
+
+ def add_inherited(self, parent):
+ """Creates a new Style containing all parent styles with importance "!important"
+ and current styles with importance "!important"
+
+ .. versionadded:: 1.2
+
+ Args:
+ parent: the parent style that will be merged into this one (will not be
+ altered)
+
+ Returns:
+ Style: the merged Style object
+ """
+ ret = self.copy()
+ ret.apply_shorthands() # parent should already have its shortcuts applied
+
+ if not (isinstance(parent, Style)):
+ return ret
+
+ for key in parent.keys():
+ apply = False
+ if key in all_properties and all_properties[key][3]:
+ # only set parent value if value is not set or parent importance is
+ # higher
+ if key not in ret:
+ apply = True
+ elif self.get_importance(key) != parent.get_importance(key):
+ apply = parent.get_importance(key)
+ if key in ret and ret[key] == "inherit":
+ apply = True
+ if apply:
+ ret[key] = parent[key]
+ return ret
+
+ def apply_shorthands(self):
+ """Apply all shorthands in this style."""
+ for element in list(self.values()):
+ if isinstance(element, ShorthandValue):
+ element.apply_shorthand(self)
+
+ def __delitem__(self, key):
+ super().__delitem__(key)
+ if self.callback is not None:
+ self.callback(self)
+
+ def __setitem__(self, key, value):
+ """Sets a style value.
+
+ .. versionchanged:: 1.2
+ ``value`` can now also be non-string objects such as a Gradient.
+
+ Args:
+ key (str): the attribute name
+ value (Any):
+
+ - a :class:`BaseStyleValue`
+ - a string with the value
+ - any other object. The :class:`~inkex.properties.BaseStyleValue`
+ subclass of the provided key will attempt to create a string out of
+ the passed value.
+ Raises:
+ ValueError: when ``value`` is a :class:`~inkex.properties.BaseStyleValue`
+ for a different attribute than `key`
+ Error: Other exceptions may be raised when converting non-string objects."""
+ if not isinstance(value, BaseStyleValue) or value is None:
+ # try to convert the value using the factory
+ value = BaseStyleValue.factory(attr_name=key, value=value)
+ # check if the set attribute is valid
+ _ = value.parse_value(self.element)
+ elif key != value.attr_name:
+ raise ValueError(
+ """You're trying to save a value into a style attribute, but the
+ provided key is different from the attribute name given in the value"""
+ )
+ super().__setitem__(key, value)
+ if self.callback is not None:
+ self.callback(self)
+
+ def __getitem__(self, key):
+ """Returns the unparsed value of the element (minus a possible ``!important``)
+
+ .. versionchanged:: 1.2
+ ``!important`` is removed from the value.
+ """
+ return self.get_store(key).value
+
+ def get(self, key, default=None):
+ if key in self:
+ return self.__getitem__(key)
+ return default
+
+ def get_store(self, key):
+ """Gets the :class:`~inkex.properties.BaseStyleValue` of this key, since the
+ other interfaces - :func:`__getitem__` and :func:`__call__` - return the
+ original and parsed value, respectively.
+
+ .. versionadded:: 1.2
+
+ Args:
+ key (str): the attribute name
+
+ Returns:
+ BaseStyleValue: the BaseStyleValue struct of this attribute
+ """
+ return super().__getitem__(key)
+
+ def __call__(self, key, element=None):
+ """Return the parsed value of a style. Optionally, an element can be passed
+ that will be used to find gradient definitions ect.
+
+ .. versionadded:: 1.2"""
+ # check if there are shorthand properties defined. If so, apply them to a copy
+ copy = self
+ for value in super().values():
+ if isinstance(value, ShorthandValue):
+ copy = self.copy()
+ copy.apply_shorthands()
+ if key in copy:
+ return copy.get_store(key).parse_value(element or self.element)
+ # style is not set, return the default value
+ if key in all_properties:
+ defvalue = BaseStyleValue.factory(
+ attr_name=key, value=all_properties[key][1]
+ )
+ return (
+ defvalue.parse_value()
+ ) # default values are independent of the element
+ raise KeyError("Unknown attribute")
+
+ def __eq__(self, other):
+ if not isinstance(other, Style):
+ other = Style(other)
+ if self.keys() != other.keys():
+ return False
+ for arg in set(self) | set(other):
+ if self.get_store(arg) != other.get_store(arg):
+ return False
+ return True
+
+ def items(self):
+ """The styles's parsed items
+
+ .. versionadded:: 1.2"""
+ for key, value in super().items():
+ yield key, value.value
+
+ def get_importance(self, key, default=False):
+ """Returns whether the declaration with ``key`` is marked as ``!important``
+
+ .. versionadded:: 1.2"""
+ if key in self:
+ return super().__getitem__(key).important
+ return default
+
+ def set_importance(self, key, importance):
+ """Sets the ``!important`` state of a declaration with key ``key``
+
+ .. versionadded:: 1.2"""
+ if key in self:
+ super().__getitem__(key).important = importance
+ else:
+ raise KeyError()
+ if self.callback is not None:
+ self.callback(self)
+
+ def get_color(self, name="fill"):
+ """Get the color AND opacity as one Color object"""
+ color = Color(self.get(name, "none"))
+ return color.to_rgba(self.get(name + "-opacity", 1.0))
+
+ def set_color(self, color, name="fill"):
+ """Sets the given color AND opacity as rgba to the fill or stroke style
+ properties."""
+ color = Color(color)
+ if color.space == "rgba" and name in Style.associated_props:
+ self[Style.associated_props[name]] = color.alpha
+ self[name] = color.to_rgb()
+ else:
+ self[name] = color
+
+ def update_urls(self, old_id, new_id):
+ """Find urls in this style and replace them with the new id"""
+ for (name, value) in self.items():
+ if value == f"url(#{old_id})":
+ self[name] = f"url(#{new_id})"
+
+ def interpolate(self, other, fraction):
+ # type: (Style, Style, float) -> Style
+ """Interpolate all properties.
+
+ .. versionadded:: 1.1"""
+ from .tween import StyleInterpolator
+ from inkex.elements import PathElement
+
+ if self.element is None:
+ self.element = PathElement(style=str(self))
+ if other.element is None:
+ other.element = PathElement(style=str(other))
+ return StyleInterpolator(self.element, other.element).interpolate(fraction)
+
+ @classmethod
+ def cascaded_style(cls, element):
+ """Returns the cascaded style of an element (all rules that apply the element
+ itself), based on the stylesheets, the presentation attributes and the inline
+ style using the respective specificity of the style
+
+ see https://www.w3.org/TR/CSS22/cascade.html#cascading-order
+
+ .. versionadded:: 1.2
+
+ Args:
+ element (BaseElement): the element that the cascaded style will be
+ computed for
+
+ Returns:
+ Style: the cascaded style
+ """
+ styles = list(element.root.stylesheets.lookup_specificity(element.get_id()))
+
+ # presentation attributes have specificity 0,
+ # see https://www.w3.org/TR/SVG/styling.html#PresentationAttributes
+ styles.append([element.presentation_style(), (0, 0, 0)])
+
+ # would be (1, 0, 0, 0), but then we'd have to extend every entry
+ styles.append([element.style, (float("inf"), 0, 0)])
+
+ # sort styles by specificity (ascending, so when overwriting it's correct)
+ styles = sorted(styles, key=lambda item: item[1])
+
+ result = styles[0][0].copy()
+ for style, _ in styles[1:]:
+ result.update(style)
+ result.element = element
+ return result
+
+ @classmethod
+ def specified_style(cls, element):
+ """Returns the specified style of an element, i.e. the cascaded style +
+ inheritance, see https://www.w3.org/TR/CSS22/cascade.html#specified-value
+
+ .. versionadded:: 1.2
+
+ Args:
+ element (BaseElement): the element that the specified style will be computed
+ for
+
+ Returns:
+ Style: the specified style
+ """
+
+ # We currently dont treat the case where parent=absolute value and
+ # element=relative value, i.e. specified = relative * absolute.
+ cascaded = Style.cascaded_style(element)
+
+ parent = element.getparent()
+
+ if parent is not None and isinstance(parent, IBaseElement):
+ cascaded = Style.add_inherited(cascaded, parent.specified_style())
+ cascaded.element = element
+ return cascaded # doesn't have a parent
+
+
+class StyleSheets(list):
+ """
+ Special mechanism which contains all the stylesheets for an svg document
+ while also caching lookups for specific elements.
+
+ This caching is needed because data can't be attached to elements as they are
+ re-created on the fly by lxml so lookups have to be centralised.
+ """
+
+ def __init__(self, svg=None):
+ super().__init__()
+ self.svg = svg
+
+ def lookup(self, element_id, svg=None):
+ """
+ Find all styles for this element.
+ """
+ # This is aweful, but required because we can't know for sure
+ # what might have changed in the xml tree.
+ if svg is None:
+ svg = self.svg
+ for sheet in self:
+ for style in sheet.lookup(element_id, svg=svg):
+ yield style
+
+ def lookup_specificity(self, element_id, svg=None):
+ """
+ Find all styles for this element and return the specificity of the match.
+
+ .. versionadded:: 1.2
+ """
+ # This is aweful, but required because we can't know for sure
+ # what might have changed in the xml tree.
+ if svg is None:
+ svg = self.svg
+ for sheet in self:
+ for style in sheet.lookup_specificity(element_id, svg=svg):
+ yield style
+
+
+class StyleSheet(list):
+ """
+ A style sheet, usually the CDATA contents of a style tag, but also
+ a css file used with a css. Will yield multiple Style() classes.
+ """
+
+ comment_strip = re.compile(r"(\/\/.*?\n)|(\/\*.*?\*\/)|@.*;")
+
+ def __init__(self, content=None, callback=None):
+ super().__init__()
+ self.callback = None
+ # Remove comments
+ content = self.comment_strip.sub("", (content or ""))
+ # Parse rules
+ for block in content.split("}"):
+ if block:
+ self.append(block)
+ self.callback = callback
+
+ def __str__(self):
+ return "\n" + "\n".join([str(style) for style in self]) + "\n"
+
+ def _callback(self, style=None): # pylint: disable=unused-argument
+ if self.callback is not None:
+ self.callback(self)
+
+ def add(self, rule, style):
+ """Append a rule and style combo to this stylesheet"""
+ self.append(
+ ConditionalStyle(rules=rule, style=str(style), callback=self._callback)
+ )
+
+ def append(self, other):
+ """Make sure callback is called when updating"""
+ if isinstance(other, str):
+ if "{" not in other:
+ return # Warning?
+ rules, style = other.strip("}").split("{", 1)
+ if rules.strip().startswith("@"): # ignore @font-face and @import
+ return
+ other = ConditionalStyle(
+ rules=rules, style=style.strip(), callback=self._callback
+ )
+ super().append(other)
+ self._callback()
+
+ def lookup(self, element_id, svg):
+ """Lookup the element_id against all the styles in this sheet"""
+ for style in self:
+ for elem in svg.xpath(style.to_xpath()):
+ if elem.get("id", None) == element_id:
+ yield style
+
+ def lookup_specificity(self, element_id, svg):
+ """Lookup the element_id against all the styles in this sheet
+ and return the specificity of the match
+
+ Args:
+ element_id (str): the id of the element that styles are being queried for
+ svg (SvgDocumentElement): The document that contains both element and the
+ styles
+
+ Yields:
+ Tuple[ConditionalStyle, Tuple[int, int, int]]: all matched styles and the
+ specificity of the match
+ """
+ for style in self:
+ for rule, spec in zip(style.to_xpaths(), style.get_specificities()):
+ for elem in svg.xpath(rule):
+ if elem.get("id", None) == element_id:
+ yield (style, spec)
+
+
+class ConditionalStyle(Style):
+ """
+ Just like a Style object, but includes one or more
+ conditional rules which places this style in a stylesheet
+ rather than being an attribute style.
+ """
+
+ def __init__(self, rules="*", style=None, callback=None, **kwargs):
+ super().__init__(style=style, callback=callback, **kwargs)
+ self.rules = [ConditionalRule(rule) for rule in rules.split(",")]
+
+ def __str__(self):
+ """Return this style as a css entry with class"""
+ content = self.to_str(";\n ")
+ rules = ",\n".join(str(rule) for rule in self.rules)
+ if content:
+ return f"{rules} {{\n {content};\n}}"
+ return f"{rules} {{}}"
+
+ def to_xpath(self):
+ """Convert all rules to an xpath"""
+ # This can be converted to cssselect.CSSSelector (lxml.cssselect) later if we
+ # have coverage problems. The main reason we're not is that cssselect is doing
+ # exactly this xpath transform and provides no extra functionality for reverse
+ # lookups.
+ return "|".join(self.to_xpaths())
+
+ def to_xpaths(self):
+ """Gets a list of xpaths for all rules of this ConditionalStyle
+
+ .. versionadded:: 1.2"""
+ return [rule.to_xpath() for rule in self.rules]
+
+ def get_specificities(self):
+ """Gets an iterator of the specificity of all rules in this ConditionalStyle
+
+ .. versionadded:: 1.2"""
+ for rule in self.rules:
+ yield rule.get_specificity()
diff --git a/share/extensions/inkex/tester/__init__.py b/share/extensions/inkex/tester/__init__.py
new file mode 100644
index 0000000..f7e1d4b
--- /dev/null
+++ b/share/extensions/inkex/tester/__init__.py
@@ -0,0 +1,437 @@
+# coding=utf-8
+#
+# Copyright (C) 2018-2019 Martin Owens
+# 2019 Thomas Holder
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA.
+#
+"""
+Testing module. See :ref:`unittests` for details.
+"""
+
+import os
+import re
+import sys
+import shutil
+import tempfile
+import hashlib
+import random
+import uuid
+from typing import List, Union, Tuple, Type, TYPE_CHECKING
+
+from io import BytesIO, StringIO
+import xml.etree.ElementTree as xml
+
+from unittest import TestCase as BaseCase
+from inkex.base import InkscapeExtension
+
+from .. import Transform
+from ..utils import to_bytes
+from .xmldiff import xmldiff
+from .mock import MockCommandMixin, Capture
+
+if TYPE_CHECKING:
+ from .filters import Compare
+
+COMPARE_DELETE, COMPARE_CHECK, COMPARE_WRITE, COMPARE_OVERWRITE = range(4)
+
+
+class NoExtension(InkscapeExtension): # pylint: disable=too-few-public-methods
+ """Test case must specify 'self.effect_class' to assertEffect."""
+
+ def __init__(self, *args, **kwargs): # pylint: disable=super-init-not-called
+ raise NotImplementedError(self.__doc__)
+
+ def run(self, args=None, output=None):
+ """Fake run"""
+
+
+class TestCase(MockCommandMixin, BaseCase):
+ """
+ Base class for all effects tests, provides access to data_files and
+ test_without_parameters
+ """
+
+ effect_class = NoExtension # type: Type[InkscapeExtension]
+ effect_name = property(lambda self: self.effect_class.__module__)
+
+ # If set to true, the output is not expected to be the stdout SVG document, but
+ # rather text or a message sent to the stderr, this is highly weird. But sometimes
+ # happens.
+ stderr_output = False
+ stdout_protect = True
+ stderr_protect = True
+
+ def __init__(self, *args, **kw):
+ super().__init__(*args, **kw)
+ self._temp_dir = None
+ self._effect = None
+
+ def setUp(self): # pylint: disable=invalid-name
+ """Make sure every test is seeded the same way"""
+ self._effect = None
+ super().setUp()
+ random.seed(0x35F)
+
+ def tearDown(self):
+ super().tearDown()
+ if self._temp_dir and os.path.isdir(self._temp_dir):
+ shutil.rmtree(self._temp_dir)
+
+ @classmethod
+ def __file__(cls):
+ """Create a __file__ property which acts much like the module version"""
+ return os.path.abspath(sys.modules[cls.__module__].__file__)
+
+ @classmethod
+ def _testdir(cls):
+ """Get's the folder where the test exists (so data can be found)"""
+ return os.path.dirname(cls.__file__())
+
+ @classmethod
+ def rootdir(cls):
+ """Return the full path to the extensions directory"""
+ return os.path.dirname(cls._testdir())
+
+ @classmethod
+ def datadir(cls):
+ """Get the data directory (can be over-ridden if needed)"""
+ return os.path.join(cls._testdir(), "data")
+
+ @property
+ def tempdir(self):
+ """Generate a temporary location to store files"""
+ if self._temp_dir is None:
+ self._temp_dir = os.path.realpath(tempfile.mkdtemp(prefix="inkex-tests-"))
+ if not os.path.isdir(self._temp_dir):
+ raise IOError("The temporary directory has disappeared!")
+ return self._temp_dir
+
+ def temp_file(
+ self, prefix="file-", template="{prefix}{name}{suffix}", suffix=".tmp"
+ ):
+ """Generate the filename of a temporary file"""
+ filename = template.format(prefix=prefix, suffix=suffix, name=uuid.uuid4().hex)
+ return os.path.join(self.tempdir, filename)
+
+ @classmethod
+ def data_file(cls, filename, *parts, check_exists=True):
+ """Provide a data file from a filename, can accept directories as arguments.
+
+ .. versionchanged:: 1.2
+ ``check_exists`` parameter added"""
+ if os.path.isabs(filename):
+ # Absolute root was passed in, so we trust that (it might be a tempdir)
+ full_path = os.path.join(filename, *parts)
+ else:
+ # Otherwise we assume it's relative to the test data dir.
+ full_path = os.path.join(cls.datadir(), filename, *parts)
+
+ if not os.path.isfile(full_path) and check_exists:
+ raise IOError(f"Can't find test data file: {full_path}")
+ return full_path
+
+ @property
+ def empty_svg(self):
+ """Returns a common minimal svg file"""
+ return self.data_file("svg", "default-inkscape-SVG.svg")
+
+ def assertAlmostTuple(
+ self, found, expected, precision=8, msg=""
+ ): # pylint: disable=invalid-name
+ """
+ Floating point results may vary with computer architecture; use
+ assertAlmostEqual to allow a tolerance in the result.
+ """
+ self.assertEqual(len(found), len(expected), msg)
+ for fon, exp in zip(found, expected):
+ self.assertAlmostEqual(fon, exp, precision, msg)
+
+ def assertEffectEmpty(self, effect, **kwargs): # pylint: disable=invalid-name
+ """Assert calling effect without any arguments"""
+ self.assertEffect(effect=effect, **kwargs)
+
+ def assertEffect(self, *filename, **kwargs): # pylint: disable=invalid-name
+ """Assert an effect, capturing the output to stdout.
+
+ filename should point to a starting svg document, default is empty_svg
+ """
+ if filename:
+ data_file = self.data_file(*filename)
+ else:
+ data_file = self.empty_svg
+
+ os.environ["DOCUMENT_PATH"] = data_file
+ args = [data_file] + list(kwargs.pop("args", []))
+ args += [f"--{kw[0]}={kw[1]}" for kw in kwargs.items()]
+
+ effect = kwargs.pop("effect", self.effect_class)()
+
+ # Output is redirected to this string io buffer
+ if self.stderr_output:
+ with Capture("stderr") as stderr:
+ effect.run(args, output=BytesIO())
+ effect.test_output = stderr
+ else:
+ output = BytesIO()
+ with Capture(
+ "stdout", kwargs.get("stdout_protect", self.stdout_protect)
+ ) as stdout:
+ with Capture(
+ "stderr", kwargs.get("stderr_protect", self.stderr_protect)
+ ) as stderr:
+ effect.run(args, output=output)
+ self.assertEqual(
+ "", stdout.getvalue(), "Extra print statements detected"
+ )
+ self.assertEqual(
+ "", stderr.getvalue(), "Extra error or warnings detected"
+ )
+ effect.test_output = output
+
+ if os.environ.get("FAIL_ON_DEPRECATION", False):
+ warnings = getattr(effect, "warned_about", set())
+ effect.warned_about = set() # reset for next test
+ self.assertFalse(warnings, "Deprecated API is still being used!")
+
+ return effect
+
+ # pylint: disable=invalid-name
+ def assertDeepAlmostEqual(self, first, second, places=None, msg=None, delta=None):
+ """Asserts that two objects, possible nested lists, are almost equal."""
+ if delta is None and places is None:
+ places = 7
+ if isinstance(first, (list, tuple)):
+ assert len(first) == len(second)
+ for (f, s) in zip(first, second):
+ self.assertDeepAlmostEqual(f, s, places, msg, delta)
+ else:
+ self.assertAlmostEqual(first, second, places, msg, delta)
+
+ def assertTransformEqual(self, lhs, rhs, places=7):
+ """Assert that two transform expressions evaluate to the same
+ transformation matrix.
+
+ .. versionadded:: 1.1
+ """
+ self.assertAlmostTuple(
+ tuple(Transform(lhs).to_hexad()), tuple(Transform(rhs).to_hexad()), places
+ )
+
+ # pylint: enable=invalid-name
+
+ @property
+ def effect(self):
+ """Generate an effect object"""
+ if self._effect is None:
+ self._effect = self.effect_class()
+ return self._effect
+
+
+class InkscapeExtensionTestMixin:
+ """Automatically setup self.effect for each test and test with an empty svg"""
+
+ def setUp(self): # pylint: disable=invalid-name
+ """Check if there is an effect_class set and create self.effect if it is"""
+ super().setUp()
+ if self.effect_class is None:
+ self.skipTest("self.effect_class is not defined for this this test")
+
+ def test_default_settings(self):
+ """Extension works with empty svg file"""
+ self.effect.run([self.empty_svg])
+
+
+class ComparisonMixin:
+ """
+ Add comparison tests to any existing test suite.
+ """
+
+ compare_file: Union[List[str], Tuple[str], str] = "svg/shapes.svg"
+ """This input svg file sent to the extension (if any)"""
+
+ compare_filters = [] # type: List[Compare]
+ """The ways in which the output is filtered for comparision (see filters.py)"""
+
+ compare_filter_save = False
+ """If true, the filtered output will be saved and only applied to the
+ extension output (and not to the reference file)"""
+
+ comparisons = [
+ (),
+ ("--id=p1", "--id=r3"),
+ ]
+ """A list of comparison runs, each entry will cause the extension to be run."""
+
+ compare_file_extension = "svg"
+
+ @property
+ def _compare_file_extension(self):
+ """The default extension to use when outputting check files in COMPARE_CHECK
+ mode."""
+ if self.stderr_output:
+ return "txt"
+ return self.compare_file_extension
+
+ def test_all_comparisons(self):
+ """Testing all comparisons"""
+ if not isinstance(self.compare_file, (list, tuple)):
+ self._test_comparisons(self.compare_file)
+ else:
+ for compare_file in self.compare_file:
+ self._test_comparisons(
+ compare_file, addout=os.path.basename(compare_file)
+ )
+
+ def _test_comparisons(self, compare_file, addout=None):
+ for args in self.comparisons:
+ self.assertCompare(
+ compare_file,
+ self.get_compare_cmpfile(args, addout),
+ args,
+ )
+
+ def assertCompare(
+ self, infile, cmpfile, args, outfile=None
+ ): # pylint: disable=invalid-name
+ """
+ Compare the output of a previous run against this one.
+
+ Args:
+ infile: The filename of the pre-processed svg (or other type of file)
+ cmpfile: The filename of the data we expect to get, if not set
+ the filename will be generated from the effect name and kwargs.
+ args: All the arguments to be passed to the effect run
+ outfile: Optional, instead of returning a regular output, this extension
+ dumps it's output to this filename instead.
+
+ """
+ compare_mode = int(os.environ.get("EXPORT_COMPARE", COMPARE_DELETE))
+
+ effect = self.assertEffect(infile, args=args)
+
+ if cmpfile is None:
+ cmpfile = self.get_compare_cmpfile(args)
+
+ if not os.path.isfile(cmpfile) and compare_mode == COMPARE_DELETE:
+ raise IOError(
+ f"Comparison file {cmpfile} not found, set EXPORT_COMPARE=1 to create "
+ "it."
+ )
+
+ if outfile:
+ if not os.path.isabs(outfile):
+ outfile = os.path.join(self.tempdir, outfile)
+ self.assertTrue(
+ os.path.isfile(outfile), f"No output file created! {outfile}"
+ )
+ with open(outfile, "rb") as fhl:
+ data_a = fhl.read()
+ else:
+ data_a = effect.test_output.getvalue()
+
+ write_output = None
+ if compare_mode == COMPARE_CHECK:
+ _file = cmpfile[:-4] if cmpfile.endswith(".out") else cmpfile
+ write_output = f"{_file}.{self._compare_file_extension}"
+ elif (
+ compare_mode == COMPARE_WRITE and not os.path.isfile(cmpfile)
+ ) or compare_mode == COMPARE_OVERWRITE:
+ write_output = cmpfile
+
+ try:
+ if write_output and not os.path.isfile(cmpfile):
+ raise AssertionError(f"Check the output: {write_output}")
+ with open(cmpfile, "rb") as fhl:
+ data_b = self._apply_compare_filters(fhl.read(), False)
+ self._base_compare(data_a, data_b, compare_mode)
+ except AssertionError:
+ if write_output:
+ if isinstance(data_a, str):
+ data_a = data_a.encode("utf-8")
+ with open(write_output, "wb") as fhl:
+ fhl.write(self._apply_compare_filters(data_a, True))
+ print(f"Written output: {write_output}")
+ # This only reruns if the original test failed.
+ # The idea here is to make sure the new output file is "stable"
+ # Because some tests can produce random changes and we don't
+ # want test authors to be too reassured by a simple write.
+ if write_output == cmpfile:
+ effect = self.assertEffect(infile, args=args)
+ self._base_compare(data_a, cmpfile, COMPARE_CHECK)
+ if not write_output == cmpfile:
+ raise
+
+ def _base_compare(self, data_a, data_b, compare_mode):
+ data_a = self._apply_compare_filters(data_a)
+
+ if (
+ isinstance(data_a, bytes)
+ and isinstance(data_b, bytes)
+ and data_a.startswith(b"<")
+ and data_b.startswith(b"<")
+ ):
+ # Late importing
+ diff_xml, delta = xmldiff(data_a, data_b)
+ if not delta and compare_mode == COMPARE_DELETE:
+ print(
+ "The XML is different, you can save the output using the "
+ "EXPORT_COMPARE envionment variable. Set it to 1 to save a file "
+ "you can check, set it to 3 to overwrite this comparison, setting "
+ "the new data as the correct one.\n"
+ )
+ diff = "SVG Differences\n\n"
+ if os.environ.get("XML_DIFF", False):
+ diff = "<- " + diff_xml
+ else:
+ for x, (value_a, value_b) in enumerate(delta):
+ try:
+ # Take advantage of better text diff in testcase's own asserts.
+ self.assertEqual(value_a, value_b)
+ except AssertionError as err:
+ diff += f" {x}. {str(err)}\n"
+ self.assertTrue(delta, diff)
+ else:
+ # compare any content (non svg)
+ self.assertEqual(data_a, data_b)
+
+ def _apply_compare_filters(self, data, is_saving=None):
+ data = to_bytes(data)
+ # Applying filters flips depending if we are saving the filtered content
+ # to disk, or filtering during the test run. This is because some filters
+ # are destructive others are useful for diagnostics.
+ if is_saving is self.compare_filter_save or is_saving is None:
+ for cfilter in self.compare_filters:
+ data = cfilter(data)
+ return data
+
+ def get_compare_cmpfile(self, args, addout=None):
+ """Generate an output file for the arguments given"""
+ if addout is not None:
+ args = list(args) + [str(addout)]
+ opstr = (
+ "__".join(args)
+ .replace(self.tempdir, "TMP_DIR")
+ .replace(self.datadir(), "DAT_DIR")
+ )
+ opstr = re.sub(r"[^\w-]", "__", opstr)
+ if opstr:
+ if len(opstr) > 127:
+ # avoid filename-too-long error
+ opstr = hashlib.md5(opstr.encode("latin1")).hexdigest()
+ opstr = "__" + opstr
+ return self.data_file(
+ "refs", f"{self.effect_name}{opstr}.out", check_exists=False
+ )
diff --git a/share/extensions/inkex/tester/decorators.py b/share/extensions/inkex/tester/decorators.py
new file mode 100644
index 0000000..f27e638
--- /dev/null
+++ b/share/extensions/inkex/tester/decorators.py
@@ -0,0 +1,9 @@
+"""
+Useful decorators for tests.
+"""
+import pytest
+from inkex.command import is_inkscape_available
+
+requires_inkscape = pytest.mark.skipif( # pylint: disable=invalid-name
+ not is_inkscape_available(), reason="Test requires inkscape, but it's not available"
+)
diff --git a/share/extensions/inkex/tester/filters.py b/share/extensions/inkex/tester/filters.py
new file mode 100644
index 0000000..281adfc
--- /dev/null
+++ b/share/extensions/inkex/tester/filters.py
@@ -0,0 +1,180 @@
+#
+# Copyright (C) 2019 Thomas Holder
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# pylint: disable=too-few-public-methods
+#
+"""
+Comparison filters for use with the ComparisonMixin.
+
+Each filter should be initialised in the list of
+filters that are being used.
+
+.. code-block:: python
+
+ compare_filters = [
+ CompareNumericFuzzy(),
+ CompareOrderIndependentLines(option=yes),
+ ]
+
+"""
+
+import re
+from ..utils import to_bytes
+
+
+class Compare:
+ """
+ Comparison base class, this acts as a passthrough unless
+ the filter staticmethod is overwritten.
+ """
+
+ def __init__(self, **options):
+ self.options = options
+
+ def __call__(self, content):
+ return self.filter(content)
+
+ @staticmethod
+ def filter(contents):
+ """Replace this filter method with your own filtering"""
+ return contents
+
+
+class CompareNumericFuzzy(Compare):
+ """
+ Turn all numbers into shorter standard formats
+
+ 1.2345678 -> 1.2346
+ 1.2300 -> 1.23, 50.0000 -> 50.0
+ 50.0 -> 50
+ """
+
+ @staticmethod
+ def filter(contents):
+ func = lambda m: b"%.3f" % (float(m.group(0)))
+ contents = re.sub(rb"\d+\.\d+(e[+-]\d+)?", func, contents)
+ contents = re.sub(rb"(\d\.\d+?)0+\b", rb"\1", contents)
+ contents = re.sub(rb"(\d)\.0+(?=\D|\b)", rb"\1", contents)
+ return contents
+
+
+class CompareWithoutIds(Compare):
+ """Remove all ids from the svg"""
+
+ @staticmethod
+ def filter(contents):
+ return re.sub(rb' id="([^"]*)"', b"", contents)
+
+
+class CompareWithPathSpace(Compare):
+ """Make sure that path segment commands have spaces around them"""
+
+ @staticmethod
+ def filter(contents):
+ def func(match):
+ """We've found a path command, process it"""
+ new = re.sub(rb"\s*([LZMHVCSQTAatqscvhmzl])\s*", rb" \1 ", match.group(1))
+ return b' d="' + new.replace(b",", b" ") + b'"'
+
+ return re.sub(rb' d="([^"]*)"', func, contents)
+
+
+class CompareSize(Compare):
+ """Compare the length of the contents instead of the contents"""
+
+ @staticmethod
+ def filter(contents):
+ return len(contents)
+
+
+class CompareOrderIndependentBytes(Compare):
+ """Take all the bytes and sort them"""
+
+ @staticmethod
+ def filter(contents):
+ return b"".join([bytes(i) for i in sorted(contents)])
+
+
+class CompareOrderIndependentLines(Compare):
+ """Take all the lines and sort them"""
+
+ @staticmethod
+ def filter(contents):
+ return b"\n".join(sorted(contents.splitlines()))
+
+
+class CompareOrderIndependentStyle(Compare):
+ """Take all styles and sort the results"""
+
+ @staticmethod
+ def filter(contents):
+ contents = CompareNumericFuzzy.filter(contents)
+
+ def func(match):
+ """Search and replace function for sorting"""
+ sty = b";".join(sorted(match.group(1).split(b";")))
+ return b'style="%s"' % (sty,)
+
+ return re.sub(rb'style="([^"]*)"', func, contents)
+
+
+class CompareOrderIndependentStyleAndPath(Compare):
+ """Take all styles and paths and sort them both"""
+
+ @staticmethod
+ def filter(contents):
+ contents = CompareOrderIndependentStyle.filter(contents)
+
+ def func(match):
+ """Search and replace function for sorting"""
+ path = b"X".join(sorted(re.split(rb"[A-Z]", match.group(1))))
+ return b'd="%s"' % (path,)
+
+ return re.sub(rb'\bd="([^"]*)"', func, contents)
+
+
+class CompareOrderIndependentTags(Compare):
+ """Sorts all the XML tags"""
+
+ @staticmethod
+ def filter(contents):
+ return b"\n".join(sorted(re.split(rb">\s*<", contents)))
+
+
+class CompareReplacement(Compare):
+ """Replace pieces to make output more comparable
+
+ .. versionadded:: 1.1"""
+
+ def __init__(self, *replacements):
+ self.deltas = replacements
+ super().__init__()
+
+ def filter(self, contents):
+ contents = to_bytes(contents)
+ for _from, _to in self.deltas:
+ contents = contents.replace(to_bytes(_from), to_bytes(_to))
+ return contents
+
+
+class WindowsTextCompat(CompareReplacement):
+ """Normalize newlines so tests comparing plain text work
+
+ .. versionadded:: 1.2"""
+
+ def __init__(self):
+ super().__init__(("\r\n", "\n"))
diff --git a/share/extensions/inkex/tester/inx.py b/share/extensions/inkex/tester/inx.py
new file mode 100644
index 0000000..bad6d81
--- /dev/null
+++ b/share/extensions/inkex/tester/inx.py
@@ -0,0 +1,128 @@
+#!/usr/bin/env python
+# coding=utf-8
+"""
+Test elements extra logic from svg xml lxml custom classes.
+"""
+
+from ..utils import PY3
+from ..inx import InxFile
+
+INTERNAL_ARGS = ("help", "output", "id", "selected-nodes")
+ARG_TYPES = {
+ "Boolean": "bool",
+ "Color": "color",
+ "str": "string",
+ "int": "int",
+ "float": "float",
+}
+
+
+class InxMixin:
+ """Tools for Testing INX files, use as a mixin class:
+
+ class MyTests(InxMixin, TestCase):
+ def test_inx_file(self):
+ self.assertInxIsGood("some_inx_file.inx")
+ """
+
+ def assertInxIsGood(self, inx_file): # pylint: disable=invalid-name
+ """Test the inx file for consistancy and correctness"""
+ self.assertTrue(PY3, "INX files can only be tested in python3")
+
+ inx = InxFile(inx_file)
+ if "help" in inx.ident or inx.script.get("interpreter", None) != "python":
+ return
+ cls = inx.extension_class
+ # Check class can be matched in python file
+ self.assertTrue(cls, f"Can not find class for {inx.filename}")
+ # Check name is reasonable for the class
+ if not cls.multi_inx:
+ self.assertEqual(
+ cls.__name__,
+ inx.slug,
+ f"Name of extension class {cls.__module__}.{cls.__name__} "
+ f"is different from ident {inx.slug}",
+ )
+ self.assertParams(inx, cls)
+
+ def assertParams(self, inx, cls): # pylint: disable=invalid-name
+ """Confirm the params in the inx match the python script
+
+ .. versionchanged:: 1.2
+ Also checks that the default values are identical"""
+ params = {param.name: self.parse_param(param) for param in inx.params}
+ args = dict(self.introspect_arg_parser(cls().arg_parser))
+ mismatch_a = list(set(params) ^ set(args) & set(params))
+ mismatch_b = list(set(args) ^ set(params) & set(args))
+ self.assertFalse(
+ mismatch_a, f"{inx.filename}: Inx params missing from arg parser"
+ )
+ self.assertFalse(
+ mismatch_b, f"{inx.filename}: Script args missing from inx xml"
+ )
+
+ for param in args:
+ if params[param]["type"] and args[param]["type"]:
+ self.assertEqual(
+ params[param]["type"],
+ args[param]["type"],
+ f"Type is not the same for {inx.filename}:param:{param}",
+ )
+ inxdefault = params[param]["default"]
+ argsdefault = args[param]["default"]
+ if inxdefault and argsdefault:
+ # for booleans, the inx is lowercase and the param is uppercase
+ if params[param]["type"] == "bool":
+ argsdefault = str(argsdefault).lower()
+ elif params[param]["type"] not in ["string", None, "color"] or args[
+ param
+ ]["type"] in ["int", "float"]:
+ # try to parse the inx value to compare numbers to numbers
+ inxdefault = float(inxdefault)
+ if args[param]["type"] == "color" or callable(args[param]["default"]):
+ # skip color, method types
+ continue
+ self.assertEqual(
+ argsdefault,
+ inxdefault,
+ f"Default value is not the same for {inx.filename}:param:{param}",
+ )
+
+ def introspect_arg_parser(self, arg_parser):
+ """Pull apart the arg parser to find out what we have in it"""
+ for (
+ action
+ ) in arg_parser._optionals._actions: # pylint: disable=protected-access
+ for opt in action.option_strings:
+ # Ignore params internal to inkscape (thus not in the inx)
+ if opt.startswith("--") and opt[2:] not in INTERNAL_ARGS:
+ yield (opt[2:], self.introspect_action(action))
+
+ @staticmethod
+ def introspect_action(action):
+ """Pull apart a single action to get at the juicy insides"""
+ return {
+ "type": ARG_TYPES.get((action.type or str).__name__, "string"),
+ "default": action.default,
+ "choices": action.choices,
+ "help": action.help,
+ }
+
+ @staticmethod
+ def parse_param(param):
+ """Pull apart the param element in the inx file"""
+ if param.param_type in ("optiongroup", "notebook"):
+ options = param.options
+ return {
+ "type": None,
+ "choices": options,
+ "default": options and options[0] or None,
+ }
+ param_type = param.param_type
+ if param.param_type in ("path",):
+ param_type = "string"
+ return {
+ "type": param_type,
+ "default": param.text,
+ "choices": None,
+ }
diff --git a/share/extensions/inkex/tester/mock.py b/share/extensions/inkex/tester/mock.py
new file mode 100644
index 0000000..3b75dcd
--- /dev/null
+++ b/share/extensions/inkex/tester/mock.py
@@ -0,0 +1,455 @@
+# coding=utf-8
+#
+# Copyright (C) 2018 Martin Owens
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA.
+#
+# pylint: disable=protected-access,too-few-public-methods
+"""
+Any mocking utilities required by testing. Mocking is when you need the test
+to exercise a piece of code, but that code may or does call on something
+outside of the target code that either takes too long to run, isn't available
+during the test running process or simply shouldn't be running at all.
+"""
+
+import io
+import os
+import sys
+import logging
+import hashlib
+import tempfile
+from typing import List, Tuple, Any
+
+from email.mime.application import MIMEApplication
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+from email.parser import Parser as EmailParser
+
+import inkex.command
+
+
+FIXED_BOUNDARY = "--CALLDATA--//--CALLDATA--"
+
+
+class Capture:
+ """Capture stdout or stderr. Used as `with Capture('stdout') as stream:`"""
+
+ def __init__(self, io_name="stdout", swap=True):
+ self.io_name = io_name
+ self.original = getattr(sys, io_name)
+ self.stream = io.StringIO()
+ self.swap = swap
+
+ def __enter__(self):
+ if self.swap:
+ setattr(sys, self.io_name, self.stream)
+ return self.stream
+
+ def __exit__(self, exc, value, traceback):
+ if exc is not None and self.swap:
+ # Dump content back to original if there was an error.
+ self.original.write(self.stream.getvalue())
+ setattr(sys, self.io_name, self.original)
+
+
+class ManualVerbosity:
+ """Change the verbosity of the test suite manually"""
+
+ result = property(lambda self: self.test._current_result)
+
+ def __init__(self, test, okay=True, dots=False):
+ self.test = test
+ self.okay = okay
+ self.dots = dots
+
+ def flip(
+ self, exc_type=None, exc_val=None, exc_tb=None
+ ): # pylint: disable=unused-argument
+ """Swap the stored verbosity with the original"""
+ self.okay, self.result.showAll = self.result.showAll, self.okay
+ self.dots, self.result.dots = self.result.dots, self.okay
+
+ __enter__ = flip
+ __exit__ = flip
+
+
+class MockMixin:
+ """
+ Add mocking ability to any test base class, will set up mock on setUp
+ and remove it on tearDown.
+
+ Mocks are stored in an array attached to the test class (not instance!) which
+ ensures that mocks can only ever be setUp once and can never be reset over
+ themselves. (just in case this looks weird at first glance)
+
+ class SomeTest(MockingMixin, TestBase):
+ mocks = [(sys, 'exit', NoSystemExit("Nope!")]
+ """
+
+ mocks = [] # type: List[Tuple[Any, str, Any]]
+
+ def setUpMock(self, owner, name, new): # pylint: disable=invalid-name
+ """Setup the mock here, taking name and function and returning (name, old)"""
+ old = getattr(owner, name)
+ if isinstance(new, str):
+ if hasattr(self, new):
+ new = getattr(self, new)
+ if isinstance(new, Exception):
+
+ def _error_function(*args2, **kw2): # pylint: disable=unused-argument
+ raise type(new)(str(new))
+
+ setattr(owner, name, _error_function)
+ elif new is None or isinstance(new, (str, int, float, list, tuple)):
+
+ def _value_function(*args, **kw): # pylint: disable=unused-argument
+ return new
+
+ setattr(owner, name, _value_function)
+ else:
+ setattr(owner, name, new)
+ # When we start, mocks contains length 3 tuples, when we're finished, it
+ # contains length 4, this stops remocking and reunmocking from taking place.
+ return (owner, name, old, False)
+
+ def setUp(self): # pylint: disable=invalid-name
+ """For each mock instruction, set it up and store the return"""
+ super().setUp()
+ for x, mock in enumerate(self.mocks):
+ if len(mock) == 4:
+ logging.error(
+ "Mock was already set up, so it wasn't cleared previously!"
+ )
+ continue
+ self.mocks[x] = self.setUpMock(*mock)
+
+ def tearDown(self): # pylint: disable=invalid-name
+ """For each returned stored, tear it down and restore mock instruction"""
+ super().tearDown()
+ try:
+ for x, (owner, name, old, _) in enumerate(self.mocks):
+ self.mocks[x] = (owner, name, getattr(owner, name))
+ setattr(owner, name, old)
+ except ValueError:
+ logging.warning("Was never mocked, did something go wrong?")
+
+ def old_call(self, name):
+ """Get the original caller"""
+ for arg in self.mocks:
+ if arg[1] == name:
+ return arg[2]
+ return lambda: None
+
+
+class MockCommandMixin(MockMixin):
+ """
+ Replace all the command functions with testable replacements.
+
+ This stops the pipeline and people without the programs, running into problems.
+ """
+
+ mocks = [
+ (inkex.command, "_call", "mock_call"),
+ (tempfile, "mkdtemp", "record_tempdir"),
+ ]
+ recorded_tempdirs = [] # type:List[str]
+
+ def setUp(self): # pylint: disable=invalid-name
+ super().setUp()
+ # This is a the daftest thing I've ever seen, when in the middle
+ # of a mock, the 'self' variable magically turns from a FooTest
+ # into a TestCase, this makes it impossible to find the datadir.
+ from . import TestCase
+
+ TestCase._mockdatadir = self.datadir()
+
+ @classmethod
+ def cmddir(cls):
+ """Returns the location of all the mocked command results"""
+ from . import TestCase
+
+ return os.path.join(TestCase._mockdatadir, "cmd")
+
+ def record_tempdir(self, *args, **kwargs):
+ """Record any attempts to make tempdirs"""
+ newdir = self.old_call("mkdtemp")(*args, **kwargs)
+ self.recorded_tempdirs.append(os.path.realpath(newdir))
+ return newdir
+
+ def clean_paths(self, data, files):
+ """Clean a string of any files or tempdirs"""
+
+ def replace(indata, replaced, replacement):
+ if isinstance(indata, str):
+ indata = indata.replace(replaced, replacement)
+ else:
+ indata = [i.replace(replaced, replacement) for i in indata]
+ return indata
+
+ try:
+ for fdir in self.recorded_tempdirs:
+ data = replace(data, fdir, ".")
+ files = replace(files, fdir, ".")
+ for fname in files:
+ data = replace(data, fname, os.path.basename(fname))
+ except (UnicodeDecodeError, TypeError):
+ pass
+ return data
+
+ def get_all_tempfiles(self):
+ """Returns a set() of all files currently in any of the tempdirs"""
+ ret = set([])
+ for fdir in self.recorded_tempdirs:
+ if not os.path.isdir(fdir):
+ continue
+ for fname in os.listdir(fdir):
+ if fname in (".", ".."):
+ continue
+ path = os.path.join(fdir, fname)
+ # We store the modified time so if a program modifies
+ # the input file in-place, it will look different.
+ ret.add(path + f";{os.path.getmtime(path)}")
+
+ return ret
+
+ def ignore_command_mock(self, program, arglst):
+ """Return true if the mock is ignored"""
+ if self and program and arglst:
+ return os.environ.get("NO_MOCK_COMMANDS")
+ return False
+
+ def mock_call(self, program, *args, **kwargs):
+ """
+ Replacement for the inkex.command.call() function, instead of calling
+ an external program, will compile all arguments into a hash and use the
+ hash to find a command result.
+ """
+ # Remove stdin first because it needs to NOT be in the Arguments list.
+ stdin = kwargs.pop("stdin", None)
+ args = list(args)
+
+ # We use email
+ msg = MIMEMultipart(boundary=FIXED_BOUNDARY)
+ msg["Program"] = MockCommandMixin.get_program_name(program)
+
+ # Gather any output files and add any input files to msg, args and kwargs
+ # may be modified to strip out filename directories (which change)
+ inputs, outputs = self.add_call_files(msg, args, kwargs)
+
+ arglst = inkex.command.to_args_sorted(program, *args, **kwargs)[1:]
+ arglst = self.clean_paths(arglst, inputs + outputs)
+ argstr = " ".join(arglst)
+ msg["Arguments"] = argstr.strip()
+
+ if stdin is not None:
+ # The stdin is counted as the msg body
+ cleanin = (
+ self.clean_paths(stdin, inputs + outputs)
+ .replace("\r\n", "\n")
+ .replace(".\\", "./")
+ )
+ msg.attach(MIMEText(cleanin, "plain", "utf-8"))
+
+ keystr = msg.as_string()
+ # On Windows, output is separated by CRLF
+ keystr = keystr.replace("\r\n", "\n")
+ # There is a difference between python2 and python3 output
+ keystr = keystr.replace("\n\n", "\n")
+ keystr = keystr.replace("\n ", " ")
+ if "verb" in keystr:
+ # Verbs seperated by colons cause diff in py2/3
+ keystr = keystr.replace("; ", ";")
+ # Generate a unique key for this call based on _all_ it's inputs
+ key = hashlib.md5(keystr.encode("utf-8")).hexdigest()
+
+ if self.ignore_command_mock(program, arglst):
+ # Call original code. This is so programmers can run the test suite
+ # against the external programs too, to see how their fair.
+ if stdin is not None:
+ kwargs["stdin"] = stdin
+
+ before = self.get_all_tempfiles()
+ stdout = self.old_call("_call")(program, *args, **kwargs)
+ outputs += list(self.get_all_tempfiles() - before)
+ # Remove the modified time from the call
+ outputs = [out.rsplit(";", 1)[0] for out in outputs]
+
+ # After the program has run, we collect any file outputs and store
+ # them, then store any stdout or stderr created during the run.
+ # A developer can then use this to build new test cases.
+ reply = MIMEMultipart(boundary=FIXED_BOUNDARY)
+ reply["Program"] = MockCommandMixin.get_program_name(program)
+ reply["Arguments"] = argstr
+ self.save_call(program, key, stdout, outputs, reply)
+ self.save_key(program, key, keystr, "key")
+ return stdout
+
+ try:
+ return self.load_call(program, key, outputs)
+ except IOError as err:
+ self.save_key(program, key, keystr, "bad-key")
+ raise IOError(
+ f"Problem loading call: {program}/{key} use the environment variable "
+ "NO_MOCK_COMMANDS=1 to call out to the external program and generate "
+ f"the mock call file for call {program} {argstr}."
+ ) from err
+
+ def add_call_files(self, msg, args, kwargs):
+ """
+ Gather all files, adding input files to the msg (for hashing) and
+ output files to the returned files list (for outputting in debug)
+ """
+ # Gather all possible string arguments together.
+ loargs = sorted(kwargs.items(), key=lambda i: i[0])
+ values = []
+ for arg in args:
+ if isinstance(arg, (tuple, list)):
+ loargs.append(arg)
+ else:
+ values.append(str(arg))
+
+ for (_, value) in loargs:
+ if isinstance(value, (tuple, list)):
+ for val in value:
+ if val is not True:
+ values.append(str(val))
+ elif value is not True:
+ values.append(str(value))
+
+ # See if any of the strings could be filenames, either going to be
+ # or are existing files on the disk.
+ files = [[], []]
+ for value in values:
+ if os.path.isfile(value): # Input file
+ files[0].append(value)
+ self.add_call_file(msg, value)
+ elif os.path.isdir(os.path.dirname(value)): # Output file
+ files[1].append(value)
+ return files
+
+ def add_call_file(self, msg, filename):
+ """Add a single file to the given mime message"""
+ fname = os.path.basename(filename)
+ with open(filename, "rb") as fhl:
+ if filename.endswith(".svg"):
+ value = self.clean_paths(fhl.read().decode("utf8"), [])
+ else:
+ value = fhl.read()
+ try:
+ value = value.decode()
+ except UnicodeDecodeError:
+ pass # do not attempt to process binary files further
+ if isinstance(value, str):
+ value = value.replace("\r\n", "\n").replace(".\\", "./")
+ part = MIMEApplication(value, Name=fname)
+ # After the file is closed
+ part["Content-Disposition"] = "attachment"
+ part["Filename"] = fname
+ msg.attach(part)
+
+ def get_call_filename(self, program, key, create=False):
+ """
+ Get the filename for the call testing information.
+ """
+ path = self.get_call_path(program, create=create)
+ fname = os.path.join(path, key + ".msg")
+ if not create and not os.path.isfile(fname):
+ raise IOError(f"Attempted to find call test data {key}")
+ return fname
+
+ @staticmethod
+ def get_program_name(program):
+ """Takes a program and returns a program name"""
+ if program == inkex.command.INKSCAPE_EXECUTABLE_NAME:
+ return "inkscape"
+ return program
+
+ def get_call_path(self, program, create=True):
+ """Get where this program would store it's test data"""
+ command_dir = os.path.join(
+ self.cmddir(), MockCommandMixin.get_program_name(program)
+ )
+ if not os.path.isdir(command_dir):
+ if create:
+ os.makedirs(command_dir)
+ else:
+ raise IOError(
+ "A test is attempting to use an external program in a test:"
+ f" {program}; but there is not a command data directory which "
+ f"should contain the results of the command here: {command_dir}"
+ )
+ return command_dir
+
+ def load_call(self, program, key, files):
+ """
+ Load the given call
+ """
+ fname = self.get_call_filename(program, key, create=False)
+ with open(fname, "rb") as fhl:
+ msg = EmailParser().parsestr(fhl.read().decode("utf-8"))
+
+ stdout = None
+ for part in msg.walk():
+ if "attachment" in part.get("Content-Disposition", ""):
+ base_name = part["Filename"]
+ for out_file in files:
+ if out_file.endswith(base_name):
+ with open(out_file, "wb") as fhl:
+ fhl.write(part.get_payload(decode=True))
+ part = None
+ if part is not None:
+ # Was not caught by any normal outputs, so we will
+ # save the file to EVERY tempdir in the hopes of
+ # hitting on of them.
+ for fdir in self.recorded_tempdirs:
+ if os.path.isdir(fdir):
+ with open(os.path.join(fdir, base_name), "wb") as fhl:
+ fhl.write(part.get_payload(decode=True))
+ elif part.get_content_type() == "text/plain":
+ stdout = part.get_payload(decode=True)
+
+ return stdout
+
+ def save_call(
+ self, program, key, stdout, files, msg, ext="output"
+ ): # pylint: disable=too-many-arguments
+ """
+ Saves the results from the call into a debug output file, the resulting files
+ should be a Mime msg file format with each attachment being one of the input
+ files as well as any stdin and arguments used in the call.
+ """
+ if stdout is not None and stdout.strip():
+ # The stdout is counted as the msg body here
+ msg.attach(MIMEText(stdout.decode("utf-8"), "plain", "utf-8"))
+
+ for fname in set(files):
+ if os.path.isfile(fname):
+ # print("SAVING FILE INTO MSG: {}".format(fname))
+ self.add_call_file(msg, fname)
+ else:
+ part = MIMEText("Missing File", "plain", "utf-8")
+ part.add_header("Filename", os.path.basename(fname))
+ msg.attach(part)
+
+ fname = self.get_call_filename(program, key, create=True) + "." + ext
+ with open(fname, "wb") as fhl:
+ fhl.write(msg.as_string().encode("utf-8"))
+
+ def save_key(self, program, key, keystr, ext="key"):
+ """Save the key file if we are debugging the key data"""
+ if os.environ.get("DEBUG_KEY"):
+ fname = self.get_call_filename(program, key, create=True) + "." + ext
+ with open(fname, "wb") as fhl:
+ fhl.write(keystr.encode("utf-8"))
diff --git a/share/extensions/inkex/tester/svg.py b/share/extensions/inkex/tester/svg.py
new file mode 100644
index 0000000..c601c81
--- /dev/null
+++ b/share/extensions/inkex/tester/svg.py
@@ -0,0 +1,55 @@
+# coding=utf-8
+#
+# Copyright (C) 2018 Martin Owens
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA.
+#
+"""
+SVG specific utilities for tests.
+"""
+
+from lxml import etree
+
+from inkex import SVG_PARSER
+
+
+def svg(svg_attrs=""):
+ """Returns xml etree based on a simple SVG element.
+
+ svg_attrs: A string containing attributes to add to the
+ root <svg> element of a minimal SVG document.
+ """
+ return etree.fromstring(
+ str.encode(
+ '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'
+ f"<svg {svg_attrs}></svg>"
+ ),
+ parser=SVG_PARSER,
+ )
+
+
+def svg_unit_scaled(width_unit):
+ """Same as svg, but takes a width unit (top-level transform) for the new document.
+
+ The transform is the ratio between the SVG width and the viewBox width.
+ """
+ return svg(f'width="1{width_unit}" viewBox="0 0 1 1"')
+
+
+def svg_file(filename):
+ """Parse an svg file and return it's document root"""
+ with open(filename, "r", encoding="utf-8") as fhl:
+ doc = etree.parse(fhl, parser=SVG_PARSER)
+ return doc.getroot()
diff --git a/share/extensions/inkex/tester/word.py b/share/extensions/inkex/tester/word.py
new file mode 100644
index 0000000..bf395d7
--- /dev/null
+++ b/share/extensions/inkex/tester/word.py
@@ -0,0 +1,42 @@
+# coding=utf-8
+#
+# Unknown author
+#
+"""
+Generate words for testing.
+"""
+
+import string
+import random
+
+
+def word_generator(text_length):
+ """
+ Generate a word of text_length size
+ """
+ word = ""
+
+ for _ in range(0, text_length):
+ word += random.choice(
+ string.ascii_lowercase
+ + string.ascii_uppercase
+ + string.digits
+ + string.punctuation
+ )
+
+ return word
+
+
+def sentencecase(word):
+ """Make a word standace case"""
+ word_new = ""
+ lower_letters = list(string.ascii_lowercase)
+ first = True
+ for letter in word:
+ if letter in lower_letters and first is True:
+ word_new += letter.upper()
+ first = False
+ else:
+ word_new += letter
+
+ return word_new
diff --git a/share/extensions/inkex/tester/xmldiff.py b/share/extensions/inkex/tester/xmldiff.py
new file mode 100644
index 0000000..1864530
--- /dev/null
+++ b/share/extensions/inkex/tester/xmldiff.py
@@ -0,0 +1,124 @@
+#
+# Copyright 2011 (c) Ian Bicking <ianb@colorstudy.com>
+# 2019 (c) Martin Owens <doctormo@gmail.com>
+#
+# Taken from http://formencode.org under the GPL compatible PSF License.
+# Modified to produce more output as a diff.
+#
+"""
+Allow two xml files/lxml etrees to be compared, returning their differences.
+"""
+import xml.etree.ElementTree as xml
+from io import BytesIO
+
+from inkex.paths import Path
+
+
+def text_compare(test1, test2):
+ """
+ Compare two text strings while allowing for '*' to match
+ anything on either lhs or rhs.
+ """
+ if not test1 and not test2:
+ return True
+ if test1 == "*" or test2 == "*":
+ return True
+ return (test1 or "").strip() == (test2 or "").strip()
+
+
+class DeltaLogger(list):
+ """A record keeper of the delta between two svg files"""
+
+ def append_tag(self, tag_a, tag_b):
+ """Record a tag difference"""
+ if tag_a:
+ tag_a = f"<{tag_a}.../>"
+ if tag_b:
+ tag_b = f"<{tag_b}.../>"
+ self.append((tag_a, tag_b))
+
+ def append_attr(self, attr, value_a, value_b):
+ """Record an attribute difference"""
+
+ def _prep(val):
+ if val:
+ if attr == "d":
+ return [attr] + Path(val).to_arrays()
+ return (attr, val)
+ return val
+
+ # Only append a difference if the preprocessed values are different.
+ # This solves the issue that -0 != 0 in path data.
+ prep_a = _prep(value_a)
+ prep_b = _prep(value_b)
+ if prep_a != prep_b:
+ self.append((prep_a, prep_b))
+
+ def append_text(self, text_a, text_b):
+ """Record a text difference"""
+ self.append((text_a, text_b))
+
+ def __bool__(self):
+ """Returns True if there's no log, i.e. the delta is clean"""
+ return not self.__len__()
+
+ __nonzero__ = __bool__
+
+ def __repr__(self):
+ if self:
+ return "No differences detected"
+ return f"{len(self)} xml differences"
+
+
+def to_xml(data):
+ """Convert string or bytes to xml parsed root node"""
+ if isinstance(data, str):
+ data = data.encode("utf8")
+ if isinstance(data, bytes):
+ return xml.parse(BytesIO(data)).getroot()
+ return data
+
+
+def xmldiff(data1, data2):
+ """Create an xml difference, will modify the first xml structure with a diff"""
+ xml1, xml2 = to_xml(data1), to_xml(data2)
+ delta = DeltaLogger()
+ _xmldiff(xml1, xml2, delta)
+ return xml.tostring(xml1).decode("utf-8"), delta
+
+
+def _xmldiff(xml1, xml2, delta):
+ if xml1.tag != xml2.tag:
+ xml1.tag = f"{xml1.tag}XXX{xml2.tag}"
+ delta.append_tag(xml1.tag, xml2.tag)
+ for name, value in xml1.attrib.items():
+ if name not in xml2.attrib:
+ delta.append_attr(name, xml1.attrib[name], None)
+ xml1.attrib[name] += "XXX"
+ elif xml2.attrib.get(name) != value:
+ delta.append_attr(name, xml1.attrib.get(name), xml2.attrib.get(name))
+ xml1.attrib[name] = f"{xml1.attrib.get(name)}XXX{xml2.attrib.get(name)}"
+ for name, value in xml2.attrib.items():
+ if name not in xml1.attrib:
+ delta.append_attr(name, None, value)
+ xml1.attrib[name] = "XXX" + value
+ if not text_compare(xml1.text, xml2.text):
+ delta.append_text(xml1.text, xml2.text)
+ xml1.text = f"{xml1.text}XXX{xml2.text}"
+ if not text_compare(xml1.tail, xml2.tail):
+ delta.append_text(xml1.tail, xml2.tail)
+ xml1.tail = f"{xml1.tail}XXX{xml2.tail}"
+
+ # Get children and pad with nulls
+ children_a = list(xml1)
+ children_b = list(xml2)
+ children_a += [None] * (len(children_b) - len(children_a))
+ children_b += [None] * (len(children_a) - len(children_b))
+
+ for child_a, child_b in zip(children_a, children_b):
+ if child_a is None: # child_b exists
+ delta.append_tag(child_b.tag, None)
+ elif child_b is None: # child_a exists
+ delta.append_tag(None, child_a.tag)
+ else:
+ _xmldiff(child_a, child_b, delta)
diff --git a/share/extensions/inkex/transforms.py b/share/extensions/inkex/transforms.py
new file mode 100644
index 0000000..3a37a38
--- /dev/null
+++ b/share/extensions/inkex/transforms.py
@@ -0,0 +1,1250 @@
+# coding=utf-8
+#
+# Copyright (C) 2006 Jean-Francois Barraud, barraud@math.univ-lille1.fr
+# Copyright (C) 2010 Alvin Penner, penner@vaxxine.com
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+# barraud@math.univ-lille1.fr
+#
+# This code defines several functions to make handling of transform
+# attribute easier.
+#
+"""
+Provide transformation parsing to extensions
+"""
+from __future__ import annotations
+import re
+from decimal import Decimal
+from math import cos, radians, sin, sqrt, tan, fabs, atan2, hypot, pi, isfinite
+from typing import (
+ overload,
+ cast,
+ Callable,
+ Generator,
+ Iterator,
+ Tuple,
+ Union,
+ Optional,
+ List,
+)
+
+
+from .utils import strargs, KeyDict
+
+
+VectorLike = Union[
+ "ImmutableVector2d", Tuple[float, float]
+] # pylint: disable=invalid-name
+MatrixLike = Union[
+ str,
+ Tuple[Tuple[float, float, float], Tuple[float, float, float]],
+ Tuple[float, float, float, float, float, float],
+ "Transform",
+]
+BoundingIntervalArgs = Union[
+ "BoundingInterval", Tuple[float, float], float
+] # pylint: disable=invalid-name
+
+# All the names that get added to the inkex API itself.
+__all__ = (
+ "BoundingBox",
+ "DirectedLineSegment",
+ "ImmutableVector2d",
+ "Transform",
+ "Vector2d",
+)
+
+
+# Old settings, supported because users click 'ok' without looking.
+XAN = KeyDict({"l": "left", "r": "right", "m": "center_x"})
+YAN = KeyDict({"t": "top", "b": "bottom", "m": "center_y"})
+# Anchoring objects with given directions (see inx options)
+CUSTOM_DIRECTION = {270: "tb", 90: "bt", 0: "lr", 360: "lr", 180: "rl"}
+DIRECTION = ["tb", "bt", "lr", "rl", "ro", "ri"]
+
+
+class ImmutableVector2d:
+ """Represents an immutable element of 2-dimensional Euclidean space"""
+
+ _x = 0.0
+ _y = 0.0
+
+ x = property(lambda self: self._x)
+ y = property(lambda self: self._y)
+
+ @overload
+ def __init__(self):
+ # type: () -> None
+ pass
+
+ @overload
+ def __init__(self, v, fallback=None):
+ # type: (Union[VectorLike, str], Optional[Union[VectorLike, str]]) -> None
+ pass
+
+ @overload
+ def __init__(self, x, y):
+ # type: (float, float) -> None
+ pass
+
+ def __init__(self, *args, fallback=None):
+ try:
+ if len(args) == 0:
+ x, y = 0.0, 0.0
+ elif len(args) == 1:
+ x, y = self._parse(args[0])
+ elif len(args) == 2:
+ x, y = map(float, args)
+ else:
+ raise ValueError("too many arguments")
+ except (ValueError, TypeError) as error:
+ if fallback is None:
+ raise ValueError("Cannot parse vector and no fallback given") from error
+ x, y = ImmutableVector2d(fallback)
+ self._x, self._y = float(x), float(y)
+
+ @staticmethod
+ def _parse(point):
+ # type: (Union[VectorLike, str]) -> Tuple[float, float]
+ if isinstance(point, ImmutableVector2d):
+ x, y = point.x, point.y
+ elif isinstance(point, (tuple, list)) and len(point) == 2:
+ x, y = map(float, point)
+ elif isinstance(point, str) and point.count(",") == 1:
+ x, y = map(float, point.split(","))
+ else:
+ raise ValueError(f"Can't parse {repr(point)}")
+ return x, y
+
+ def __add__(self, other):
+ # type: (VectorLike) -> Vector2d
+ other = Vector2d(other)
+ return Vector2d(self.x + other.x, self.y + other.y)
+
+ def __radd__(self, other):
+ # type: (VectorLike) -> Vector2d
+ other = Vector2d(other)
+ return Vector2d(self.x + other.x, self.y + other.y)
+
+ def __sub__(self, other):
+ # type: (VectorLike) -> Vector2d
+ other = Vector2d(other)
+ return Vector2d(self.x - other.x, self.y - other.y)
+
+ def __rsub__(self, other):
+ # type: (VectorLike) -> Vector2d
+ other = Vector2d(other)
+ return Vector2d(-self.x + other.x, -self.y + other.y)
+
+ def __neg__(self):
+ # type: () -> Vector2d
+ return Vector2d(-self.x, -self.y)
+
+ def __pos__(self):
+ # type: () -> Vector2d
+ return Vector2d(self.x, self.y)
+
+ def __floordiv__(self, factor):
+ # type: (float) -> Vector2d
+ return Vector2d(self.x / float(factor), self.y / float(factor))
+
+ def __truediv__(self, factor):
+ # type: (float) -> Vector2d
+ return Vector2d(self.x / float(factor), self.y / float(factor))
+
+ def __div__(self, factor):
+ # type: (float) -> Vector2d
+ return Vector2d(self.x / float(factor), self.y / float(factor))
+
+ def __mul__(self, factor):
+ # type: (float) -> Vector2d
+ return Vector2d(self.x * factor, self.y * factor)
+
+ def __abs__(self):
+ # type: () -> float
+ return self.length
+
+ def __rmul__(self, factor):
+ # type: (float) -> VectorLike
+ return Vector2d(self.x * factor, self.y * factor)
+
+ def __repr__(self):
+ # type: () -> str
+ return f"Vector2d({self.x:.6g}, {self.y:.6g})"
+
+ def __str__(self):
+ # type: () -> str
+ return f"{self.x:.6g}, {self.y:.6g}"
+
+ def __iter__(self) -> Generator[float, None, None]:
+ yield self.x
+ yield self.y
+
+ def __len__(self):
+ # type: () -> int
+ return 2
+
+ def __getitem__(self, item):
+ # type: (int) -> float
+ return (self.x, self.y)[item]
+
+ def to_tuple(self) -> Tuple[float, float]:
+ """A tuple of the vector's components"""
+ return cast(Tuple[float, float], tuple(self))
+
+ def to_polar_tuple(self):
+ # type: () -> Tuple[float, Optional[float]]
+ """A tuple of the vector's magnitude and direction
+
+ .. versionadded:: 1.1"""
+ return self.length, self.angle
+
+ def dot(self, other: VectorLike) -> float:
+ """Multiply Vectors component-wise"""
+ other = Vector2d(other)
+ return self.x * other.x + self.y * other.y
+
+ def cross(self, other):
+ # type: (VectorLike) -> float
+ """Z component of the cross product of the vectors extended into 3D
+
+ .. versionadded:: 1.1"""
+ other = Vector2d(other)
+ return self.x * other.y - self.y * other.x
+
+ def is_close(
+ self,
+ other: Union[VectorLike, str, Tuple[float, float]],
+ rtol: float = 1e-5,
+ atol: float = 1e-8,
+ ) -> float:
+ """Checks if two vectors are (almost) identical, up to both absolute and
+ relative tolerance."""
+ other = Vector2d(other)
+ delta = (self - other).length
+ return delta < (atol + rtol * other.length)
+
+ @property
+ def length(self) -> float:
+ """Returns the length of the vector"""
+ return sqrt(self.dot(self))
+
+ @property
+ def angle(self):
+ # type: () -> Optional[float]
+ """The angle of the vector when represented in polar coordinates
+
+ .. versionadded:: 1.1"""
+ if self.x == 0 and self.y == 0:
+ return None
+ return atan2(self.y, self.x)
+
+
+class Vector2d(ImmutableVector2d):
+ """Represents an element of 2-dimensional Euclidean space"""
+
+ @staticmethod
+ def from_polar(radius, theta):
+ # type: (float, Optional[float]) -> Optional[Vector2d]
+ """Creates a Vector2d from polar coordinates
+
+ None is returned when theta is None and radius is not zero.
+
+ .. versionadded:: 1.1
+ """
+ if radius == 0.0:
+ return Vector2d(0.0, 0.0)
+ if theta is not None:
+ return Vector2d(radius * cos(theta), radius * sin(theta))
+ # A vector with a radius but no direction is invalid
+ return None
+
+ @ImmutableVector2d.x.setter
+ def x(self, value):
+ # type: (Union[float, int, str]) -> None
+ self._x = float(value)
+
+ @ImmutableVector2d.y.setter
+ def y(self, value):
+ # type: (Union[float, int, str]) -> None
+ self._y = float(value)
+
+ def __iadd__(self, other):
+ # type: (VectorLike) -> Vector2d
+ other = Vector2d(other)
+ self.x += other.x
+ self.y += other.y
+ return self
+
+ def __isub__(self, other):
+ # type: (VectorLike) -> Vector2d
+ other = Vector2d(other)
+ self.x -= other.x
+ self.y -= other.y
+ return self
+
+ def __imul__(self, factor):
+ # type: (float) -> Vector2d
+ self.x *= factor
+ self.y *= factor
+ return self
+
+ def __idiv__(self, factor):
+ # type: (float) -> Vector2d
+ self.x /= factor
+ self.y /= factor
+ return self
+
+ def __itruediv__(self, factor):
+ # type: (float) -> Vector2d
+ self.x /= factor
+ self.y /= factor
+ return self
+
+ def __ifloordiv__(self, factor):
+ # type: (float) -> Vector2d
+ self.x /= factor
+ self.y /= factor
+ return self
+
+ @overload
+ def assign(self, x, y):
+ # type: (float, float) -> VectorLike
+ pass
+
+ @overload
+ def assign(self, other):
+ # type: (VectorLike, str) -> VectorLike
+ pass
+
+ def assign(self, *args):
+ """Assigns a different vector in place"""
+ self.x, self.y = Vector2d(*args)
+ return self
+
+
+class Transform:
+ """A transformation object which will always reduce to a matrix and can
+ then be used in combination with other transformations for reducing
+ finding a point and printing svg ready output.
+
+ Use with svg transform attribute input:
+
+ tr = Transform("scale(45, 32)")
+
+ Use with triad matrix input (internal representation):
+
+ tr = Transform(((1.0, 0.0, 0.0), (0.0, 1.0, 0.0)))
+
+ Use with hexad matrix input (i.e. svg matrix(...)):
+
+ tr = Transform((1.0, 0.0, 0.0, 1.0, 0.0, 0.0))
+
+ Once you have a transformation you can operate tr * tr to compose,
+ any of the above inputs are also valid operators for composing.
+ """
+
+ TRM = re.compile(r"(translate|scale|rotate|skewX|skewY|matrix)\s*\(([^)]*)\)\s*,?")
+ absolute_tolerance = 1e-5 # type: float
+
+ def __init__(
+ self,
+ matrix=None, # type: Optional[MatrixLike]
+ callback=None, # type: Optional[Callable[[Transform], Transform]]
+ **extra,
+ ):
+ # type: (...) -> None
+ self.callback = None
+ self.matrix = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0))
+ if matrix is not None:
+ self._set_matrix(matrix)
+
+ self.add_kwargs(**extra)
+ # Set callback last, so it doesn't kick off just setting up the internal value
+ self.callback = callback
+
+ def _set_matrix(self, matrix):
+ # type: (MatrixLike) -> None
+ """Parse a given string as an svg transformation instruction.
+
+ .. versionadded:: 1.1"""
+ if isinstance(matrix, str):
+ for func, values in self.TRM.findall(matrix.strip()):
+ getattr(self, "add_" + func.lower())(*strargs(values))
+ elif isinstance(matrix, Transform):
+ self.matrix = matrix.matrix
+ elif isinstance(matrix, (tuple, list)) and len(matrix) == 2:
+ row1 = matrix[0]
+ row2 = matrix[1]
+ if isinstance(row1, (tuple, list)) and isinstance(row2, (tuple, list)):
+ if len(row1) == 3 and len(row2) == 3:
+ row1 = cast(Tuple[float, float, float], tuple(map(float, row1)))
+ row2 = cast(Tuple[float, float, float], tuple(map(float, row2)))
+ self.matrix = row1, row2
+ else:
+ raise ValueError(
+ f"Matrix '{matrix}' is not a valid transformation matrix"
+ )
+ else:
+ raise ValueError(
+ f"Matrix '{matrix}' is not a valid transformation matrix"
+ )
+ elif isinstance(matrix, (list, tuple)) and len(matrix) == 6:
+ tmatrix = cast(
+ Union[List[float], Tuple[float, float, float, float, float, float]],
+ matrix,
+ )
+ row1 = (float(tmatrix[0]), float(tmatrix[2]), float(tmatrix[4]))
+ row2 = (float(tmatrix[1]), float(tmatrix[3]), float(tmatrix[5]))
+ self.matrix = row1, row2
+ elif not isinstance(matrix, (list, tuple)):
+ raise ValueError(f"Invalid transform type: {type(matrix).__name__}")
+ else:
+ raise ValueError(f"Matrix '{matrix}' is not a valid transformation matrix")
+
+ # These provide quick access to the svg matrix:
+ #
+ # [ a, c, e ]
+ # [ b, d, f ]
+ #
+ a = property(lambda self: self.matrix[0][0]) # pylint: disable=invalid-name
+ b = property(lambda self: self.matrix[1][0]) # pylint: disable=invalid-name
+ c = property(lambda self: self.matrix[0][1]) # pylint: disable=invalid-name
+ d = property(lambda self: self.matrix[1][1]) # pylint: disable=invalid-name
+ e = property(lambda self: self.matrix[0][2]) # pylint: disable=invalid-name
+ f = property(lambda self: self.matrix[1][2]) # pylint: disable=invalid-name
+
+ def __bool__(self):
+ # type: () -> bool
+ return not self.__eq__(Transform())
+
+ __nonzero__ = __bool__
+
+ @overload
+ def add_matrix(self, a):
+ # type: (MatrixLike) -> Transform
+ pass
+
+ @overload
+ def add_matrix( # pylint: disable=too-many-arguments
+ self, a: float, b: float, c: float, d: float, e: float, f: float
+ ) -> Transform:
+ pass
+
+ @overload
+ def add_matrix(self, a, b):
+ # type: (Tuple[float, float, float], Tuple[float, float, float]) -> Transform
+ pass
+
+ def add_matrix(self, *args):
+ """Add matrix in order they appear in the svg hexad"""
+ if len(args) == 1:
+ self.__imatmul__(Transform(args[0]))
+ elif len(args) == 2 or len(args) == 6:
+ self.__imatmul__(Transform(args))
+ else:
+ raise ValueError(f"Invalid number of arguments {args}")
+ return self
+
+ def add_kwargs(self, **kwargs):
+ """Add translations, scales, rotations etc using key word arguments"""
+ for key, value in reversed(list(kwargs.items())):
+ func = getattr(self, "add_" + key)
+ if isinstance(value, tuple):
+ func(*value)
+ elif value is not None:
+ func(value)
+ return self
+
+ @overload
+ def add_translate(self, dr):
+ # type: (VectorLike) -> Transform
+ pass
+
+ @overload
+ def add_translate(self, tr_x, tr_y=0.0):
+ # type: (float, Optional[float]) -> Transform
+ pass
+
+ def add_translate(self, *args):
+ """Add translate to this transformation"""
+ if len(args) == 1 and isinstance(args[0], (int, float)):
+ tr_x, tr_y = args[0], 0.0
+ else:
+ tr_x, tr_y = Vector2d(*args)
+ self.__imatmul__(((1.0, 0.0, tr_x), (0.0, 1.0, tr_y)))
+ return self
+
+ def add_scale(self, sc_x, sc_y=None):
+ """Add scale to this transformation"""
+ sc_y = sc_x if sc_y is None else sc_y
+ self.__imatmul__(((sc_x, 0.0, 0.0), (0.0, sc_y, 0.0)))
+ return self
+
+ @overload
+ def add_rotate(self, deg, center):
+ # type: (float, VectorLike) -> Transform
+ pass
+
+ @overload
+ def add_rotate(self, deg, center_x, center_y):
+ # type: (float, float, float) -> Transform
+ pass
+
+ @overload
+ def add_rotate(self, deg):
+ # type: (float) -> Transform
+ pass
+
+ @overload
+ def add_rotate(self, deg, a):
+ # type: (float, Union[VectorLike, str]) -> Transform
+ pass
+
+ @overload
+ def add_rotate(self, deg, a, b):
+ # type: (float, float, float) -> Transform
+ pass
+
+ def add_rotate(self, deg, *args):
+ """Add rotation to this transformation"""
+ center_x, center_y = Vector2d(*args)
+ _cos, _sin = cos(radians(deg)), sin(radians(deg))
+ self.__imatmul__(((_cos, -_sin, center_x), (_sin, _cos, center_y)))
+ self.__imatmul__(((1.0, 0.0, -center_x), (0.0, 1.0, -center_y)))
+ return self
+
+ def add_skewx(self, deg):
+ # type: (float) -> Transform
+ """Add skew x to this transformation"""
+ self.__imatmul__(((1.0, tan(radians(deg)), 0.0), (0.0, 1.0, 0.0)))
+ return self
+
+ def add_skewy(self, deg):
+ # type: (float) -> Transform
+ """Add skew y to this transformation"""
+ self.__imatmul__(((1.0, 0.0, 0.0), (tan(radians(deg)), 1.0, 0.0)))
+ return self
+
+ def to_hexad(self):
+ # type: () -> Iterator[float]
+ """Returns the transform as a hexad matrix (used in svg)"""
+ return (val for lst in zip(*self.matrix) for val in lst)
+
+ def is_translate(self, exactly=False):
+ # type: (bool) -> bool
+ """Returns True if this transformation is ONLY translate"""
+ tol = self.absolute_tolerance if not exactly else 0.0
+ return (
+ fabs(self.a - 1) <= tol
+ and abs(self.d - 1) <= tol
+ and fabs(self.b) <= tol
+ and fabs(self.c) <= tol
+ )
+
+ def is_scale(self, exactly=False):
+ # type: (bool) -> bool
+ """Returns True if this transformation is ONLY scale"""
+ tol = self.absolute_tolerance if not exactly else 0.0
+ return (
+ fabs(self.e) <= tol
+ and fabs(self.f) <= tol
+ and fabs(self.b) <= tol
+ and fabs(self.c) <= tol
+ )
+
+ def is_rotate(self, exactly=False):
+ # type: (bool) -> bool
+ """Returns True if this transformation is ONLY rotate"""
+ tol = self.absolute_tolerance if not exactly else 0.0
+ return (
+ self._is_URT(exactly=exactly)
+ and fabs(self.e) <= tol
+ and fabs(self.f) <= tol
+ and fabs(self.a**2 + self.b**2 - 1) <= tol
+ )
+
+ def rotation_degrees(self):
+ # type: () -> float
+ """Return the amount of rotation in this transform"""
+ if not self._is_URT(exactly=False):
+ raise ValueError(
+ "Rotation angle is undefined for non-uniformly scaled or skewed "
+ "matrices"
+ )
+ return atan2(self.b, self.a) * 180 / pi
+
+ def __str__(self):
+ # type: () -> str
+ """Format the given matrix into a string representation for svg"""
+ hexad = tuple(self.to_hexad())
+ if self.is_translate():
+ if not self:
+ return ""
+ return f"translate({self.e:.6g}, {self.f:.6g})"
+ if self.is_scale():
+ return f"scale({self.a:.6g}, {self.d:.6g})"
+ if self.is_rotate():
+ return f"rotate({self.rotation_degrees():.6g})"
+ return f"matrix({' '.join(f'{var:.6g}' for var in hexad)})"
+
+ def __repr__(self) -> str:
+ """String representation of this object"""
+ return (
+ f"{type(self).__name__}(("
+ f"({', '.join(f'{var:.6g}' for var in self.matrix[0])}), "
+ f"({', '.join(f'{var:.6g}' for var in self.matrix[1])})))"
+ )
+
+ def __eq__(self, matrix):
+ # typing this requires writing a proof for mypy that matrix is really
+ # MatrixLike
+ """Test if this transformation is equal to the given matrix"""
+ if isinstance(matrix, (str, tuple, list, Transform)):
+ val = all(
+ fabs(l - r) <= self.absolute_tolerance
+ for l, r in zip(self.to_hexad(), Transform(matrix).to_hexad())
+ )
+ else:
+ val = False
+ return val
+
+ def __matmul__(self, matrix):
+ # type: (MatrixLike) -> Transform
+ """Combine this transform's internal matrix with the given matrix"""
+ # Conform the input to a known quantity (and convert if needed)
+ other = Transform(matrix)
+ # Return a transformation as the combined result
+ return Transform(
+ (
+ self.a * other.a + self.c * other.b,
+ self.b * other.a + self.d * other.b,
+ self.a * other.c + self.c * other.d,
+ self.b * other.c + self.d * other.d,
+ self.a * other.e + self.c * other.f + self.e,
+ self.b * other.e + self.d * other.f + self.f,
+ )
+ )
+
+ def __imatmul__(self, matrix):
+ # type: (MatrixLike) -> Transform
+ """In place multiplication of transform matrices"""
+ self.matrix = (self @ matrix).matrix
+ if self.callback is not None:
+ self.callback(self)
+ return self
+
+ def __neg__(self):
+ # type: () -> Transform
+ """Returns an inverted transformation"""
+ det = (self.a * self.d) - (self.c * self.b)
+ # invert the rotation/scaling part
+ new_a = self.d / det
+ new_d = self.a / det
+ new_c = -self.c / det
+ new_b = -self.b / det
+ # invert the translational part
+ new_e = -(new_a * self.e + new_c * self.f)
+ new_f = -(new_b * self.e + new_d * self.f)
+ return Transform((new_a, new_b, new_c, new_d, new_e, new_f))
+
+ def apply_to_point(self, point):
+ # type: (VectorLike) -> Vector2d
+ """Transform a tuple (X, Y)"""
+ if isinstance(point, str):
+ raise ValueError(f"Will not transform string '{point}'")
+ point = Vector2d(point)
+ return Vector2d(
+ self.a * point.x + self.c * point.y + self.e,
+ self.b * point.x + self.d * point.y + self.f,
+ )
+
+ def _is_URT(self, exactly=False):
+ # type: (bool) -> bool
+ """
+ Checks that transformation can be decomposed into product of
+ Uniform scale (U), Rotation around origin (R) and translation (T)
+
+ :return: decomposition as U*R*T is possible
+ """
+ tol = self.absolute_tolerance if not exactly else 0.0
+ return (fabs(self.a - self.d) <= tol) and (fabs(self.b + self.c) <= tol)
+
+ def interpolate(self, other, fraction):
+ # type: (Transform, float) -> Transform
+ """Interpolate with another Transform.
+
+ .. versionadded:: 1.1
+ """
+ from .tween import TransformInterpolator
+
+ return TransformInterpolator(self, other).interpolate(fraction)
+
+
+class BoundingInterval: # pylint: disable=too-few-public-methods
+ """A pair of numbers that represent the minimum and maximum values."""
+
+ @overload
+ def __init__(self, other=None):
+ # type: (Optional[BoundingInterval]) -> None
+ pass
+
+ @overload
+ def __init__(self, pair):
+ # type: (Tuple[float, float]) -> None
+ pass
+
+ @overload
+ def __init__(self, value):
+ # type: (float) -> None
+ pass
+
+ @overload
+ def __init__(self, x, y):
+ # type: (float, float) -> None
+ pass
+
+ def __init__(self, x=None, y=None):
+ self.x: Union[int, float, Decimal]
+ self.y: Union[int, float, Decimal]
+ self.minimum: float
+ self.maximum: float
+ if y is not None:
+ if isinstance(x, (int, float, Decimal)) and isinstance(
+ y, (int, float, Decimal)
+ ):
+ self.minimum = float(x)
+ self.maximum = float(y)
+ else:
+ raise ValueError(
+ f"Not a number for scaling: {str((x, y))} "
+ f"({type(x).__name__},{type(y).__name__})"
+ )
+
+ else:
+ value = x
+ if value is None:
+ # identity for addition, zero for intersection
+ self.minimum, self.maximum = float("+inf"), float("-inf")
+ elif isinstance(value, BoundingInterval):
+ self.minimum = value.minimum
+ self.maximum = value.maximum
+ elif isinstance(value, (tuple, list)) and len(value) == 2:
+ self.minimum, self.maximum = min(value), max(value)
+ elif isinstance(value, (int, float, Decimal)):
+ self.minimum = self.maximum = float(value)
+ else:
+ raise ValueError(
+ f"Not a number for scaling: {str(value)} ({type(value).__name__})"
+ )
+
+ def __bool__(self):
+ # type: () -> bool
+ return isfinite(self.minimum) and isfinite(self.maximum)
+
+ __nonzero__ = __bool__
+
+ def __neg__(self):
+ # type: () -> BoundingInterval
+ return BoundingInterval((-1 * self.maximum, -1 * self.minimum))
+
+ def __add__(self, other):
+ # type: (BoundingInterval) -> BoundingInterval
+ """Calculate the bounding interval that covers both given bounding intervals"""
+ new = BoundingInterval(self)
+ if other is not None:
+ new += other
+ return new
+
+ def __iadd__(self, other):
+ # type: (BoundingInterval) -> BoundingInterval
+ other = BoundingInterval(other)
+ self.minimum = min((self.minimum, other.minimum))
+ self.maximum = max((self.maximum, other.maximum))
+ return self
+
+ def __radd__(self, other):
+ # type: (BoundingInterval) -> BoundingInterval
+ if other is None:
+ return BoundingInterval(self)
+ return self + other
+
+ def __and__(self, other: BoundingInterval) -> BoundingInterval:
+ """Calculate the bounding interval where both given bounding intervals
+ overlap"""
+ new = BoundingInterval(self)
+ if other is not None:
+ new &= other
+ return new
+
+ def __iand__(self, other):
+ # type: (BoundingInterval) -> BoundingInterval
+ other = BoundingInterval(other)
+ self.minimum = max((self.minimum, other.minimum))
+ self.maximum = min((self.maximum, other.maximum))
+ if self.minimum > self.maximum:
+ self.minimum, self.maximum = float("+inf"), float("-inf")
+ return self
+
+ def __rand__(self, other):
+ # type: (BoundingInterval) -> BoundingInterval
+ if other is None:
+ return BoundingInterval(self)
+ return self & other
+
+ def __mul__(self, other: float) -> BoundingInterval:
+ new = BoundingInterval(self)
+ if other is not None:
+ new *= other
+ return new
+
+ def __imul__(self, other: float) -> BoundingInterval:
+ self.minimum *= other
+ self.maximum *= other
+ return self
+
+ def __iter__(self) -> Generator[float, None, None]:
+ yield self.minimum
+ yield self.maximum
+
+ def __eq__(self, other) -> bool:
+ return tuple(self) == tuple(BoundingInterval(other))
+
+ def __contains__(self, value: float) -> bool:
+ return self.minimum <= value <= self.maximum
+
+ def __repr__(self) -> str:
+ return f"BoundingInterval({self.minimum}, {self.maximum})"
+
+ @property
+ def center(self):
+ # type: () -> float
+ """Pick the middle of the line"""
+ return self.minimum + ((self.maximum - self.minimum) / 2)
+
+ @property
+ def size(self):
+ # type: () -> float
+ """Return the size difference minimum and maximum"""
+ return self.maximum - self.minimum
+
+
+class BoundingBox: # pylint: disable=too-few-public-methods
+ """
+ Some functions to compute a rough bbox of a given list of objects.
+
+ BoundingBox(other)
+ BoundingBox(x, y)
+ BoundingBox((x1, x2), (y1, y2))
+ """
+
+ width = property(lambda self: self.x.size)
+ height = property(lambda self: self.y.size)
+ top = property(lambda self: self.y.minimum)
+ left = property(lambda self: self.x.minimum)
+ bottom = property(lambda self: self.y.maximum)
+ right = property(lambda self: self.x.maximum)
+ center_x = property(lambda self: self.x.center)
+ center_y = property(lambda self: self.y.center)
+
+ @overload
+ def __init__(self, other=None):
+ # type: (Optional[BoundingBox]) -> None
+ pass
+
+ @overload
+ def __init__(self, x, y):
+ # type: (BoundingIntervalArgs, BoundingIntervalArgs) -> None
+ pass
+
+ def __init__(self, x=None, y=None):
+ if y is None:
+ if x is None:
+ # identity for addition, zero for intersection
+ pass
+ elif isinstance(x, BoundingBox):
+ x, y = x.x, x.y
+ else:
+ raise ValueError(
+ f"Not a number for scaling: {str(x)} ({type(x).__name__})"
+ )
+ self.x = BoundingInterval(x)
+ self.y = BoundingInterval(y)
+
+ @staticmethod
+ def new_xywh(x: float, y: float, width: float, height: float) -> BoundingBox:
+ """Create a bounding box using x, y, width and height
+
+ .. versionadded:: 1.2"""
+ return BoundingBox((x, x + width), (y, y + height))
+
+ def __bool__(self):
+ # type: () -> bool
+ return bool(self.x) and bool(self.y)
+
+ __nonzero__ = __bool__
+
+ def __neg__(self):
+ # type: () -> BoundingBox
+ return BoundingBox(-self.x, -self.y)
+
+ def __add__(self, other):
+ # type: (Optional[BoundingBox]) -> BoundingBox
+ """Calculate the bounding box that covers both given bounding boxes"""
+ new = BoundingBox(self)
+ new += BoundingBox(other)
+ return new
+
+ def __iadd__(self, other):
+ # type: (Optional[BoundingBox]) -> BoundingBox
+ other = BoundingBox(other)
+ self.x += other.x
+ self.y += other.y
+ return self
+
+ def __radd__(self, other):
+ # type: (Optional[BoundingBox]) -> BoundingBox
+ return self + other
+
+ def __and__(self, other):
+ # type: (Optional[BoundingBox]) -> BoundingBox
+ """Calculate the bounding box where both given bounding boxes overlap"""
+ new = BoundingBox(self)
+ new &= BoundingBox(other)
+ return new
+
+ def __iand__(self, other: Optional[BoundingBox]) -> BoundingBox:
+ other = BoundingBox(other)
+ self.x = self.x & other.x
+ self.y = self.y & other.y
+ if not self.x or not self.y:
+ self.x, self.y = BoundingInterval(), BoundingInterval()
+ return self
+
+ def __rand__(self, other):
+ # type: (Optional[BoundingBox]) -> BoundingBox
+ return self & other
+
+ def __mul__(self, factor):
+ # type: (float) -> BoundingBox
+ new = BoundingBox(self)
+ new *= factor
+ return new
+
+ def __imul__(self, factor):
+ # type: (float) -> BoundingBox
+ self.x *= factor
+ self.y *= factor
+ return self
+
+ def __eq__(self, other):
+ # type (object) -> bool
+ if isinstance(other, BoundingBox):
+ return tuple(self) == tuple(other)
+ return False
+
+ def __iter__(self) -> Generator[BoundingBox, None, None]:
+ yield self.x
+ yield self.y
+
+ @property
+ def area(self):
+ """Return area of the bounding box
+
+ .. versionadded:: 1.2"""
+ return self.width * self.height
+
+ @property
+ def minimum(self):
+ # type: () -> Vector2d
+ """Return the minimum x,y coords"""
+ return Vector2d(self.x.minimum, self.y.minimum)
+
+ @property
+ def maximum(self):
+ # type: () -> Vector2d
+ """Return the maximum x,y coords"""
+ return Vector2d(self.x.maximum, self.y.maximum)
+
+ def __repr__(self):
+ # type: () -> str
+ return f"BoundingBox({tuple(self.x)},{tuple(self.y)})"
+
+ @property
+ def center(self):
+ # type: () -> Vector2d
+ """Returns the middle of the bounding box"""
+ return Vector2d(self.x.center, self.y.center)
+
+ @property
+ def size(self):
+ """Returns a vector containing width and height of the bounding box
+
+ .. versionadded:: 1.2"""
+ return Vector2d(self.x.size, self.y.size)
+
+ def get_anchor(self, xanchor, yanchor, direction=0, selbox=None):
+ # type: (str, str, Union[int, str], Optional[BoundingBox]) -> float
+ """Calls get_distance with the given anchor options"""
+ return self.anchor_distance(
+ getattr(self, XAN[xanchor]),
+ getattr(self, YAN[yanchor]),
+ direction=direction,
+ selbox=selbox,
+ )
+
+ @staticmethod
+ def anchor_distance(
+ x: float,
+ y: float,
+ direction: Union[int, str] = 0,
+ selbox: Optional[BoundingBox] = None,
+ ) -> float:
+ """Using the x,y returns a single sortable value based on direction and angle
+
+ Args:
+ x (float): input x coordinate
+ y (float): input y coordinate
+ direction (Union[int, str], optional): int/float (custom angle),
+ tb/bt (top/bottom), lr/rl (left/right), ri/ro (radial). Defaults to 0.
+ selbox (Optional[BoundingBox], optional): The bounding box of the whole
+ selection for radial anchors. Defaults to None.
+
+ Raises:
+ ValueError: if radial distance is requested without the optional selbox
+ parameter.
+
+ Returns:
+ float: the anchor distance with respect to the direction.
+ """
+
+ rot = 0.0
+ if isinstance(direction, (int, float)): # Angle
+ if direction not in CUSTOM_DIRECTION:
+ return hypot(x, y) * (cos(radians(-direction) - atan2(y, x)))
+ direction = CUSTOM_DIRECTION[direction]
+
+ if direction in ("ro", "ri"):
+ if selbox is None:
+ raise ValueError(
+ "Radial distance not available without selection bounding box"
+ )
+ rot = hypot(selbox.x.center - x, selbox.y.center - y)
+
+ return [y, -y, x, -x, rot, -rot][DIRECTION.index(direction)]
+
+ def resize(self, delta_x: float, delta_y: Optional[float] = None) -> BoundingBox:
+ """Enlarges / shrinks a bounding box by a constant value. If only delta_x
+ is given, each side is moved by the same amount; if delta_y is given,
+ different deltas are applied to horizontal and vertical intervals.
+
+ .. versionadded:: 1.2"""
+ delta_y = delta_y or delta_x
+ return BoundingBox(
+ (self.x.minimum - delta_x, self.x.maximum + delta_x),
+ (self.y.minimum - delta_y, self.y.maximum + delta_y),
+ )
+
+
+class DirectedLineSegment:
+ """
+ A directed line segment
+
+ DirectedLineSegment(((x0, y0), (x1, y1)))
+ """
+
+ start = Vector2d() # start point of segment
+ end = Vector2d() # end point of segment
+
+ x0 = property(lambda self: self.start.x) # pylint: disable=invalid-name
+ y0 = property(lambda self: self.start.y) # pylint: disable=invalid-name
+ x1 = property(lambda self: self.end.x)
+ y1 = property(lambda self: self.end.y)
+ dx = property(lambda self: self.vector.x) # pylint: disable=invalid-name
+ dy = property(lambda self: self.vector.y) # pylint: disable=invalid-name
+
+ @overload
+ def __init__(self):
+ # type: () -> None
+ pass
+
+ @overload
+ def __init__(self, other):
+ # type: (DirectedLineSegment) -> None
+ pass
+
+ @overload
+ def __init__(self, start, end):
+ # type: (VectorLike, VectorLike) -> None
+ pass
+
+ def __init__(self, *args):
+ if not args: # overload 0
+ start, end = Vector2d(), Vector2d()
+ elif len(args) == 1: # overload 1
+ (other,) = args
+ start, end = other.start, other.end
+ elif len(args) == 2: # overload 2
+ start, end = args
+ else:
+ raise ValueError(f"DirectedLineSegment() can't be constructed from {args}")
+
+ self.start = Vector2d(start)
+ self.end = Vector2d(end)
+
+ def __eq__(self, other):
+ # type: (object) -> bool
+ if isinstance(other, (tuple, DirectedLineSegment)):
+ return tuple(self) == tuple(other)
+ return False
+
+ def __iter__(self):
+ # type: () -> Generator[DirectedLineSegment, None, None]
+ yield self.x0
+ yield self.x1
+ yield self.y0
+ yield self.y1
+
+ @property
+ def vector(self):
+ # type: () -> Vector2d
+ """The vector of the directed line segment.
+
+ The vector of the directed line segment represents the length
+ and direction of segment, but not the starting point.
+
+ .. versionadded:: 1.1
+ """
+ return self.end - self.start
+
+ @property
+ def length(self):
+ # type: () -> float
+ """Get the length of the line segment"""
+ return self.vector.length
+
+ @property
+ def angle(self):
+ # type: () -> float
+ """Get the angle of the line created by this segment"""
+ return atan2(self.dy, self.dx)
+
+ def distance_to_point(self, x, y):
+ # type: (float, float) -> Union[DirectedLineSegment, Optional[float]]
+ """Get the distance to the given point (x, y)"""
+ segment2 = DirectedLineSegment(self.start, (x, y))
+ dot2 = segment2.dot(self)
+ if dot2 <= 0:
+ return DirectedLineSegment((x, y), self.start).length
+ if self.dot(self) <= dot2:
+ return DirectedLineSegment((x, y), self.end).length
+ return self.perp_distance(x, y)
+
+ def perp_distance(self, x, y):
+ # type: (float, float) -> Optional[float]
+ """Perpendicular distance to the given point"""
+ if self.length == 0:
+ return None
+ return fabs((self.dx * (self.y0 - y)) - ((self.x0 - x) * self.dy)) / self.length
+
+ def dot(self, other):
+ # type: (DirectedLineSegment) -> float
+ """Get the dot product with the segment with another"""
+ return self.vector.dot(other.vector)
+
+ def point_at_ratio(self, ratio):
+ # type: (float) -> Tuple[float, float]
+ """Get the point at the given ratio along the line"""
+ return self.x0 + ratio * self.dx, self.y0 + ratio * self.dy
+
+ def point_at_length(self, length):
+ # type: (float) -> Tuple[float, float]
+ """Get the point as the length along the line"""
+ return self.point_at_ratio(length / self.length)
+
+ def parallel(self, x, y):
+ # type: (float, float) -> DirectedLineSegment
+ """Create parallel Segment"""
+ return DirectedLineSegment((x + self.dx, y + self.dy), (x, y))
+
+ def intersect(self, other):
+ # type: (DirectedLineSegment) -> Optional[Vector2d]
+ """Get the intersection between two segments"""
+ other = DirectedLineSegment(other)
+ denom = self.vector.cross(other.vector)
+ num = other.vector.cross(self.start - other.start)
+
+ if denom != 0:
+ return Vector2d(self.point_at_ratio(num / denom))
+ return None
+
+ def __repr__(self):
+ # type: () -> str
+ return f"DirectedLineSegment(({self.start}), ({self.end}))"
+
+
+def cubic_extrema(py0, py1, py2, py3):
+ # type: (float, float, float, float) -> Tuple[float, float]
+ """Returns the extreme value, given a set of bezier coordinates"""
+
+ atol = 1e-9
+ cmin, cmax = min(py0, py3), max(py0, py3)
+ pd1 = py1 - py0
+ pd2 = py2 - py1
+ pd3 = py3 - py2
+
+ def _is_bigger(point):
+ if 0 < point < 1:
+ pyx = (
+ py0 * (1 - point) * (1 - point) * (1 - point)
+ + 3 * py1 * point * (1 - point) * (1 - point)
+ + 3 * py2 * point * point * (1 - point)
+ + py3 * point * point * point
+ )
+ return min(cmin, pyx), max(cmax, pyx)
+ return cmin, cmax
+
+ if fabs(pd1 - 2 * pd2 + pd3) > atol:
+ if pd2 * pd2 > pd1 * pd3:
+ pds = sqrt(pd2 * pd2 - pd1 * pd3)
+ cmin, cmax = _is_bigger((pd1 - pd2 + pds) / (pd1 - 2 * pd2 + pd3))
+ cmin, cmax = _is_bigger((pd1 - pd2 - pds) / (pd1 - 2 * pd2 + pd3))
+
+ elif fabs(pd2 - pd1) > atol:
+ cmin, cmax = _is_bigger(-pd1 / (2 * (pd2 - pd1)))
+
+ return cmin, cmax
+
+
+def quadratic_extrema(py0, py1, py2):
+ # type: (float, float, float) -> Tuple[float, float]
+ """Returns the extreme value, given a set of quadratic bezier coordinates"""
+ atol = 1e-9
+ cmin, cmax = min(py0, py2), max(py0, py2)
+
+ def _is_bigger(point):
+ if 0 < point < 1:
+ pyx = (
+ py0 * (1 - point) * (1 - point)
+ + 2 * py1 * point * (1 - point)
+ + py2 * point * point
+ )
+ return min(cmin, pyx), max(cmax, pyx)
+ return cmin, cmax
+
+ if fabs(py0 + py2 - 2 * py1) > atol:
+ cmin, cmax = _is_bigger((py0 - py1) / (py0 + py2 - 2 * py1))
+
+ return cmin, cmax
diff --git a/share/extensions/inkex/turtle.py b/share/extensions/inkex/turtle.py
new file mode 100644
index 0000000..40c9b60
--- /dev/null
+++ b/share/extensions/inkex/turtle.py
@@ -0,0 +1,255 @@
+# coding=utf-8
+#
+# Copyright (C) 2005 Aaron Spike, aaron@ekips.org
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""A Python path turtle for Inkscape extensions"""
+
+import math
+import random
+from typing import List, Union
+
+from .paths import Line, Move, Path, PathCommand
+from .elements import PathElement, Group, BaseElement
+from .styles import Style
+
+
+class PathTurtle:
+ """A Python path turtle
+
+ .. versionchanged:: 1.2
+ pTurtle has been renamed to PathTurtle."""
+
+ def __init__(self, home=(0, 0)):
+ self.__home = [home[0], home[1]]
+ self.__pos = self.__home[:]
+ self.__heading = -90
+ self.__path = ""
+ self.__draw = True
+ self.__new = True
+
+ def forward(self, mag: float):
+ """Move turtle forward by mag in the current direction."""
+ self.setpos(
+ (
+ self.__pos[0] + math.cos(math.radians(self.__heading)) * mag,
+ self.__pos[1] + math.sin(math.radians(self.__heading)) * mag,
+ )
+ )
+
+ def backward(self, mag):
+ """Move turtle backward by mag in the current direction."""
+ self.setpos(
+ (
+ self.__pos[0] - math.cos(math.radians(self.__heading)) * mag,
+ self.__pos[1] - math.sin(math.radians(self.__heading)) * mag,
+ )
+ )
+
+ def right(self, deg):
+ """Rotate turtle right by deg degrees.
+
+ Changed in inkex 1.2: The turtle now rotates right (previously left) when
+ calling this method."""
+ self.__heading += deg
+
+ def left(self, deg):
+ """Rotate turtle left by deg degrees.
+
+ Changed in inkex 1.2: The turtle now rotates left (previously right) when
+ calling this method."""
+ self.__heading -= deg
+
+ def penup(self):
+ """Enable non-drawing / moving mode"""
+ self.__draw = False
+ self.__new = False
+
+ def pendown(self):
+ """Enable drawing mode"""
+ if not self.__draw:
+ self.__new = True
+ self.__draw = True
+
+ def pentoggle(self):
+ """Switch between drawing and moving mode"""
+ if self.__draw:
+ self.penup()
+ else:
+ self.pendown()
+
+ def home(self):
+ """Move to home position"""
+ self.setpos(self.__home)
+
+ def clean(self):
+ """Delete current path"""
+ self.__path = ""
+
+ def clear(self):
+ """Delete current path and move to home"""
+ self.clean()
+ self.home()
+
+ def setpos(self, arg):
+ """Move/draw to position, depending on the current state"""
+ if self.__new:
+ self.__path += "M" + ",".join([str(i) for i in self.__pos])
+ self.__new = False
+ self.__pos = arg
+ if self.__draw:
+ self.__path += "L" + ",".join([str(i) for i in self.__pos])
+
+ def getpos(self):
+ """Returns the current position"""
+ return self.__pos[:]
+
+ def setheading(self, deg):
+ """Set the heading to deg degrees"""
+ self.__heading = deg
+
+ def getheading(self):
+ """Returns the heading in degrees"""
+ return self.__heading
+
+ def sethome(self, arg):
+ """Set home position"""
+ self.__home = list(arg)
+
+ def getPath(self):
+ """Returns the current path"""
+ return self.__path
+
+ def rtree(self, size, minimum, pt=False):
+ """Generates a random tree"""
+ if size < minimum:
+ return
+ self.fd(size)
+ turn = random.uniform(20, 40)
+ self.rt(turn)
+ self.rtree(size * random.uniform(0.5, 0.9), minimum, pt)
+ self.lt(turn)
+ turn = random.uniform(20, 40)
+ self.lt(turn)
+ self.rtree(size * random.uniform(0.5, 0.9), minimum, pt)
+ self.rt(turn)
+ if pt:
+ self.pu()
+ self.bk(size)
+ if pt:
+ self.pd()
+
+ # pylint: disable=invalid-name
+ fd = forward
+ bk = backward
+ rt = right
+ lt = left
+ pu = penup
+ pd = pendown
+
+
+pTurtle = PathTurtle # should be deprecated
+
+
+class PathBuilder:
+ """This helper class can be used to construct a path and insert it into a
+ document.
+
+ .. versionadded:: 1.2"""
+
+ def __init__(self, style: Style):
+ """Initializes a PathDrawHelper object
+
+ Args:
+ style (Style): Style of the path.
+ """
+ self.current = Path()
+ self.style = style
+
+ def add(self, command: Union[PathCommand, List[PathCommand]]):
+ """Add a Path command to the Helper
+
+ Args:
+ command (Union[PathCommand, List[PathCommand]]): A (list of) PathCommand(s)
+ to be appended.
+ """
+ self.current.append(command)
+
+ def terminate(self):
+ """Terminates current subpath. This method does nothing by default and is
+ supposed to be overridden in subclasses."""
+
+ def append_next(self, sibling_before: BaseElement):
+ """Insert the resulting Path as :class:`inkex.elements._polygons.PathElement`
+ into the document tree.
+
+ Args:
+ sibling_before (BaseElement): The element the resulting path will be
+ appended after.
+ """
+ pth = PathElement()
+ pth.path = self.current
+ pth.style = self.style
+ sibling_before.addnext(pth)
+
+ def Move_to(self, x, y): # pylint: disable=invalid-name
+ """Shorthand to insert an absolute move command: `M x y`.
+
+ Args:
+ x (Float): x coordinate to move to
+ y (Float): y coordinate to move to
+ """
+ self.add(Move(x, y))
+
+ def Line_to(self, x, y): # pylint: disable=invalid-name
+ """Shorthand to insert an absolute lineto command: `L x y`.
+
+ Args:
+ x (Float): x coordinate to draw a line to
+ y (Float): y coordinate to draw a line to
+ """
+ self.add(Line(x, y))
+
+
+class PathGroupBuilder(PathBuilder):
+ """This helper class can be used to construct a group of paths that all have the
+ same style.
+
+ .. versionadded:: 1.2"""
+
+ def __init__(self, style):
+ super().__init__(style)
+ self.result = Group()
+
+ def terminate(self):
+ """Terminates the current Path, and appends it to the group if it is not
+ empty."""
+ if len(self.current) > 1:
+ pth = PathElement()
+ pth.path = self.current.to_absolute()
+ pth.style = self.style
+ self.result.append(pth)
+ self.current = Path()
+
+ def append_next(self, sibling_before: BaseElement):
+ """Insert the resulting Path as :class:`inkex.elements._groups.Group` into the
+ document tree.
+
+ Args:
+ sibling_before (BaseElement): The element the resulting group will be
+ appended after.
+ """
+ sibling_before.addnext(self.result)
diff --git a/share/extensions/inkex/tween.py b/share/extensions/inkex/tween.py
new file mode 100644
index 0000000..75bd90c
--- /dev/null
+++ b/share/extensions/inkex/tween.py
@@ -0,0 +1,847 @@
+# coding=utf-8
+#
+# Copyright (C) 2005 Aaron Spike, aaron@ekips.org
+# 2020 Jonathan Neuhauser, jonathan.neuhauser@outlook.com
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""Module for interpolating attributes and styles
+
+.. versionchanged:: 1.2
+ Rewritten in inkex 1.2 in an object-oriented structure to support more attributes.
+"""
+from bisect import bisect_left
+import abc
+import copy
+
+from .styles import Style
+from .elements._filters import LinearGradient, RadialGradient, Stop
+from .transforms import Transform
+from .colors import Color
+from .units import convert_unit, parse_unit, render_unit
+from .bezier import bezlenapprx, cspbezsplit, cspbezsplitatlength, csplength
+from .paths import Path, CubicSuperPath
+from .elements import SvgDocumentElement
+from .utils import FragmentError
+
+
+try:
+ from typing import Tuple, TypeVar
+
+ Value = TypeVar("Value")
+ Number = TypeVar("Number", int, float)
+except ImportError:
+ pass
+
+
+def interpcoord(coord_a: Number, coord_b: Number, time: float):
+ """Interpolate single coordinate by the amount of time"""
+ return ValueInterpolator(coord_a, coord_b).interpolate(time)
+
+
+def interppoints(point1, point2, time):
+ # type: (Tuple[float, float], Tuple[float, float], float) -> Tuple[float, float]
+ """Interpolate coordinate points by amount of time"""
+ return ArrayInterpolator(point1, point2).interpolate(time)
+
+
+class AttributeInterpolator(abc.ABC):
+ """Interpolate between attributes"""
+
+ def __init__(self, start_value, end_value):
+ self.start_value = start_value
+ self.end_value = end_value
+
+ @staticmethod
+ def best_style(node):
+ """Gets the best possible approximation to a node's style. For nodes inside the
+ element tree of an SVG file, stylesheets defined in the defs of that file can be
+ taken into account. This should be the case for input elements, but is not
+ required - in that case, only the local inline style is used.
+
+ During the interpolation process, some nodes are created temporarily, such as
+ plain gradients of a single color to allow solid<->gradient interpolation. These
+ are not attached to the document tree and therefore have no root. Since the only
+ style relevant for them is the inline style, it is acceptable to fallback to it.
+
+ Args:
+ node (BaseElement): The node to get the best approximated style of
+
+ Returns:
+ Style: If the node is rooted, the CSS specified style. Else, the inline
+ style."""
+ try:
+ return node.specified_style()
+ except FragmentError:
+ return node.style
+
+ @staticmethod
+ def create_from_attribute(snode, enode, attribute, method=None):
+ """Creates an interpolator for an attribute. Currently, only path, transform and
+ style attributes are supported
+
+ Args:
+ snode (BaseElement): start element
+ enode (BaseElement): end element
+ attribute (str): attribute name (for styles, starting with "style/")
+ method (AttributeInterpolator, optional): (currently only used for paths).
+ Specifies a method used to interpolate the attribute. Defaults to None.
+
+ Raises:
+ ValueError: if an attribute is passed that is not a style, path or transform
+ attribute
+
+ Returns:
+ AttributeInterpolator: an interpolator whose type depends on attribute.
+ """
+ if attribute in Style.color_props:
+ return StyleInterpolator.create_from_fill_stroke(snode, enode, attribute)
+ if attribute == "d":
+ if method is None:
+ method = FirstNodesInterpolator
+ return method(snode.path, enode.path)
+ if attribute == "style":
+ return StyleInterpolator(snode, enode)
+ if attribute.startswith("style/"):
+ return StyleInterpolator.create(snode, enode, attribute[6:])
+ if attribute == "transform":
+ return TransformInterpolator(snode.transform, enode.transform)
+ if method is not None:
+ return method(snode.get(attribute), enode.get(attribute))
+ raise ValueError("only path and style attributes are supported")
+
+ @abc.abstractmethod
+ def interpolate(self, time=0):
+ """Interpolation method, needs to be implemented by subclasses"""
+ return
+
+
+class StyleInterpolator(AttributeInterpolator):
+ """Class to interpolate styles"""
+
+ def __init__(self, start_value, end_value):
+ super().__init__(start_value, end_value)
+ self.interpolators = {}
+ # some keys are always processed in a certain order, these provide alternative
+ # interpolation routes if e.g. Color<->none is interpolated
+ all_keys = list(
+ dict.fromkeys(
+ ["fill", "stroke", "fill-opacity", "stroke-opacity", "stroke-width"]
+ + list(self.best_style(start_value).keys())
+ + list(self.best_style(end_value).keys())
+ )
+ )
+ for attr in all_keys:
+ sstyle = self.best_style(start_value)
+ estyle = self.best_style(end_value)
+ if attr not in sstyle and attr not in estyle:
+ continue
+ try:
+ interp = StyleInterpolator.create(
+ self.start_value, self.end_value, attr
+ )
+ self.interpolators[attr] = interp
+ except ValueError:
+ # no interpolation method known for this attribute
+ pass
+
+ @staticmethod
+ def create(snode, enode, attribute):
+ """Creates an Interpolator for a given style attribute, depending on its type:
+
+ - Color properties (such as fill, stroke) -> :class:`ColorInterpolator`,
+ :class:`GradientInterpolator` ect.
+ - Unit properties -> :class:`UnitValueInterpolator`
+ - other properties -> :class:`ValueInterpolator`
+
+ Args:
+ snode (BaseElement): start element
+ enode (BaseElement): end element
+ attribute (str): attribute to interpolate
+
+ Raises:
+ ValueError: if the attribute is not in any of the lists
+
+ Returns:
+ AttributeInterpolator: an interpolator object whose type depends on the
+ attribute.
+ """
+ if attribute in Style.color_props:
+ return StyleInterpolator.create_from_fill_stroke(snode, enode, attribute)
+
+ if attribute in Style.unit_props:
+ return UnitValueInterpolator(
+ AttributeInterpolator.best_style(snode)(attribute),
+ AttributeInterpolator.best_style(enode)(attribute),
+ )
+
+ if attribute in Style.opacity_props:
+ return ValueInterpolator(
+ AttributeInterpolator.best_style(snode)(attribute),
+ AttributeInterpolator.best_style(enode)(attribute),
+ )
+
+ raise ValueError("Unknown attribute")
+
+ @staticmethod
+ def create_from_fill_stroke(snode, enode, attribute):
+ """Creates an Interpolator for a given color-like attribute
+
+ Args:
+ snode (BaseElement): start element
+ enode (BaseElement): end element
+ attribute (str): attribute to interpolate
+
+ Raises:
+ ValueError: if the attribute is not color-like
+ ValueError: if the attribute is unset on both start and end style
+
+ Returns:
+ AttributeInterpolator: an interpolator object whose type depends on the
+ attribute.
+ """
+ if attribute not in Style.color_props:
+ raise ValueError("attribute must be a color property")
+
+ sstyle = AttributeInterpolator.best_style(snode)
+ estyle = AttributeInterpolator.best_style(enode)
+
+ styles = [[snode, sstyle], [enode, estyle]]
+ for (cur, curstyle) in styles:
+ if curstyle(attribute) is None:
+ cur.style[attribute + "-opacity"] = 0.0
+ if attribute == "stroke":
+ cur.style["stroke-width"] = 0.0
+
+ # check if style is none, unset or a color
+ if isinstance(
+ sstyle(attribute), (LinearGradient, RadialGradient)
+ ) or isinstance(estyle(attribute), (LinearGradient, RadialGradient)):
+ # if one of the two styles is a gradient, use gradient interpolation.
+ try:
+ return GradientInterpolator.create(snode, enode, attribute)
+ except ValueError:
+ # different gradient types, just duplicate the first
+ return TrivialInterpolator(sstyle(attribute))
+ if sstyle(attribute) is None and estyle(attribute) is None:
+ return TrivialInterpolator("none")
+ return ColorInterpolator.create(sstyle, estyle, attribute)
+
+ def interpolate(self, time=0):
+ """Interpolates a style using the interpolators set in self.interpolators
+
+ Args:
+ time (int, optional): Interpolation position. If 0, start_value is returned,
+ if 1, end_value is returned. Defaults to 0.
+
+ Returns:
+ inkex.Style: interpolated style
+ """
+ style = Style()
+ for prop, interp in self.interpolators.items():
+ style[prop] = interp.interpolate(time)
+ return style
+
+
+class TrivialInterpolator(AttributeInterpolator):
+ """Trivial interpolator, returns value for every time"""
+
+ def __init__(self, value):
+ super().__init__(value, value)
+
+ def interpolate(self, time=0):
+ return self.start_value
+
+
+class ValueInterpolator(AttributeInterpolator):
+ """Class for interpolation of a single value"""
+
+ def __init__(self, start_value=0, end_value=0):
+ super().__init__(float(start_value), float(end_value))
+
+ def interpolate(self, time=0):
+ """(Linearly) interpolates a value
+
+ Args:
+ time (int, optional): Interpolation position. If 0, start_value is returned,
+ if 1, end_value is returned. Defaults to 0.
+
+ Returns:
+ int: interpolated value
+ """
+ return self.start_value + ((self.end_value - self.start_value) * time)
+
+
+class UnitValueInterpolator(ValueInterpolator):
+ """Class for interpolation of a value with unit"""
+
+ def __init__(self, start_value=0, end_value=0):
+ start_val, start_unit = parse_unit(start_value)
+ end_val = convert_unit(end_value, start_unit)
+ super().__init__(start_val, end_val)
+ self.unit = start_unit
+
+ def interpolate(self, time=0):
+ return render_unit(super().interpolate(time), self.unit)
+
+
+class ArrayInterpolator(AttributeInterpolator):
+ """Interpolates array-like objects element-wise, e.g. color, transform,
+ coordinate"""
+
+ def __init__(self, start_value, end_value):
+ super().__init__(start_value, end_value)
+ self.interpolators = [
+ ValueInterpolator(cur, other)
+ for (cur, other) in zip(start_value, end_value)
+ ]
+
+ def interpolate(self, time=0):
+ """Interpolates an array element-wise
+
+ Args:
+ time (int, optional): [description]. Defaults to 0.
+
+ Returns:
+ List: interpolated array
+ """
+ return [interp.interpolate(time) for interp in self.interpolators]
+
+
+class TransformInterpolator(ArrayInterpolator):
+ """Class for interpolation of transforms"""
+
+ def __init__(self, start_value=Transform(), end_value=Transform()):
+ """Creates a transform interpolator.
+
+ Args:
+ start_value (inkex.Transform, optional): start transform. Defaults to
+ inkex.Transform().
+ end_value (inkex.Transform, optional): end transform. Defaults to
+ inkex.Transform().
+ """
+ super().__init__(start_value.to_hexad(), end_value.to_hexad())
+
+ def interpolate(self, time=0):
+ """Interpolates a transform by interpolating each item in the transform hexad
+ separately.
+
+ Args:
+ time (int, optional): Interpolation position. If 0, start_value is returned,
+ if 1, end_value is returned. Defaults to 0.
+
+ Returns:
+ Transform: interpolated transform
+ """
+ return Transform(super().interpolate(time))
+
+
+class ColorInterpolator(ArrayInterpolator):
+ """Class for color interpolation"""
+
+ @staticmethod
+ def create(sst, est, attribute):
+ """Creates a ColorInterpolator for either Fill or stroke, depending on the
+ attribute.
+
+ Args:
+ sst (Style): Start style
+ est (Style): End style
+ attribute (string): either fill or stroke
+
+ Raises:
+ ValueError: if none of the start or end style is a color.
+
+ Returns:
+ ColorInterpolator: A ColorInterpolator object
+ """
+ styles = [sst, est]
+ for cur, other in zip(styles, reversed(styles)):
+ if not isinstance(cur(attribute), Color) or cur(attribute) is None:
+ cur[attribute] = other(attribute)
+ this = ColorInterpolator(
+ Color(styles[0](attribute)), Color(styles[1](attribute))
+ )
+ if this is None:
+ raise ValueError("One of the two attribute needs to be a plain color")
+ return this
+
+ def __init__(self, start_value=Color("#000000"), end_value=Color("#000000")):
+ super().__init__(start_value, end_value)
+
+ def interpolate(self, time=0):
+ """Interpolates a color by interpolating its r, g, b, a channels separately.
+
+ Args:
+ time (int, optional): Interpolation position. If 0, start_value is returned,
+ if 1, end_value is returned. Defaults to 0.
+
+ Returns:
+ Color: interpolated color
+ """
+ return Color(list(map(int, super().interpolate(time))))
+
+
+class GradientInterpolator(AttributeInterpolator):
+ """Base class for Gradient Interpolation"""
+
+ def __init__(self, start_value, end_value, svg=None):
+ super().__init__(start_value, end_value)
+ self.svg = svg
+ # If one of the styles is empty, set it to the gradient of the other
+ if start_value is None:
+ self.start_value = end_value
+ if end_value is None:
+ self.end_value = start_value
+ self.transform_interpolator = TransformInterpolator(
+ self.start_value.gradientTransform, self.end_value.gradientTransform
+ )
+ self.orientation_interpolator = {
+ attr: UnitValueInterpolator(
+ self.start_value.get(attr), self.end_value.get(attr)
+ )
+ for attr in self.start_value.orientation_attributes
+ if self.start_value.get(attr) is not None
+ and self.end_value.get(attr) is not None
+ }
+ if not (
+ self.start_value.href is not None
+ and self.start_value.href is self.end_value.href
+ ):
+ # the gradient link to different stops, interpolate between them
+ # add both start and end offsets, then take distict
+ newoffsets = sorted(
+ list(set(self.start_value.stop_offsets + self.end_value.stop_offsets))
+ )
+
+ def func(start, end, time):
+ return StopInterpolator(start, end).interpolate(time)
+
+ sstops = GradientInterpolator.interpolate_linear_list(
+ self.start_value.stop_offsets,
+ list(self.start_value.stops),
+ newoffsets,
+ func,
+ )
+ ostops = GradientInterpolator.interpolate_linear_list(
+ self.end_value.stop_offsets,
+ list(self.end_value.stops),
+ newoffsets,
+ func,
+ )
+ self.newstop_interpolator = [
+ StopInterpolator(s1, s2) for s1, s2 in zip(sstops, ostops)
+ ]
+ else:
+ self.newstop_interpolator = None
+
+ @staticmethod
+ def create(snode, enode, attribute):
+ """Creates a `GradientInterpolator` for either fill or stroke, depending on
+ attribute.
+
+ Cases: (A, B) -> Interpolator
+
+ - Linear Gradient, Linear Gradient -> LinearGradientInterpolator
+ - Color or None, Linear Gradient -> LinearGradientInterpolator
+ - Radial Gradient, Radial Gradient -> RadialGradientInterpolator
+ - Color or None, Radial Gradient -> RadialGradientInterpolator
+ - Radial Gradient, Linear Gradient -> ValueError
+ - Color or None, Color or None -> ValueError
+
+ Args:
+ snode (BaseElement): start element
+ enode (BaseElement): end element
+ attribute (string): either fill or stroke
+
+ Raises:
+ ValueError: if none of the styles are a gradient or if they are gradients
+ of different types
+
+ Returns:
+ GradientInterpolator: an Interpolator object
+ """
+ interpolator = None
+ gradienttype = None
+ # first find out which type of interpolator we need
+ sstyle = AttributeInterpolator.best_style(snode)
+ estyle = AttributeInterpolator.best_style(enode)
+ for cur in [sstyle, estyle]:
+ curgrad = None
+ if isinstance(cur(attribute), (LinearGradient, RadialGradient)):
+ curgrad = cur(attribute)
+ for gradtype, interp in [
+ [LinearGradient, LinearGradientInterpolator],
+ [RadialGradient, RadialGradientInterpolator],
+ ]:
+ if curgrad is not None and isinstance(curgrad, gradtype):
+ if interpolator is None:
+ interpolator = interp
+ gradienttype = gradtype
+ if not (interp == interpolator):
+ raise ValueError("Gradient types don't match")
+ # If one of the styles is empty, set it to the gradient of the other, but with
+ # zero opacity (and stroke-width for strokes)
+ # If one of the styles is a plain color, replace it by a gradient with a single
+ # stop
+ iterator = [[snode, gradienttype(), enode], [enode, gradienttype(), snode]]
+ for index in [0, 1]:
+ curstyle = AttributeInterpolator.best_style(iterator[index][0])
+ value = curstyle(attribute)
+ if value is None:
+ # if the attribute of one of the two ends is unset, set the opacity to
+ # zero.
+ iterator[index][0].style[attribute + "-opacity"] = 0.0
+ if attribute == "stroke":
+ iterator[index][0].style["stroke-width"] = 0.0
+ if isinstance(value, Color):
+ # if the attribute of one of the two ends is a color, convert it to a
+ # one-stop gradient. Type depends on the type of the other gradient.
+ interpolator.initialize_position(
+ iterator[index][1], iterator[index][0].bounding_box()
+ )
+ stop = Stop()
+ stop.style = Style()
+ stop.style["stop-color"] = value
+ stop.offset = 0
+ iterator[index][1].add(stop)
+ stop = Stop()
+ stop.style = Style()
+ stop.style["stop-color"] = value
+ stop.offset = 1
+ iterator[index][1].add(stop)
+ else:
+ iterator[index][1] = value # is a gradient
+ if interpolator is None:
+ raise ValueError("None of the two styles is a gradient")
+ if interpolator in [LinearGradientInterpolator, RadialGradientInterpolator]:
+ return interpolator(iterator[0][1], iterator[1][1], snode)
+ return interpolator(iterator[0][1], iterator[1][1])
+
+ @staticmethod
+ def interpolate_linear_list(positions, values, newpositions, func):
+ """Interpolates a list of values given at n positions to the best approximation
+ at m newpositions.
+
+ >>>
+ |
+ | x
+ | x
+ _________________
+ pq q p q
+ (x denotes function values, p: positions, q: newpositions)
+ A function may be given to interpolate between given values.
+
+ Args:
+ positions (list[number-like]): position of current function values
+ values (list[Type]): list of arbitrary type,
+ ``len(values) == len(positions)``
+ newpositions (list[number-like]): position of interpolated values
+ func (Callable[[Type, Type, float], Type]): Function to interpolate between
+ values
+
+ Returns:
+ list[Type]: interpolated function values at positions
+ """
+ newvalues = []
+ positions = list(map(float, positions))
+ newpositions = list(map(float, newpositions))
+ for pos in newpositions:
+ if len(positions) == 1:
+ newvalues.append(values[0])
+ else:
+ # current run:
+ # idxl pos idxr
+ # p p | p
+ # q q
+ idxl = max(0, bisect_left(positions, pos) - 1)
+ idxr = min(len(positions) - 1, idxl + 1)
+ fraction = (pos - positions[idxl]) / (positions[idxr] - positions[idxl])
+ vall = values[idxl]
+ valr = values[idxr]
+ newval = func(vall, valr, fraction)
+ newvalues.append(newval)
+ return newvalues
+
+ @staticmethod
+ def append_to_doc(element, gradient):
+ """Splits a gradient into stops and orientation, appends it to the document's
+ defs and returns the href to the orientation gradient.
+
+ Args:
+ element (BaseElement): an element inside the SVG that the gradient should be
+ added to
+ gradient (Gradient): the gradient to append to the document
+
+ Returns:
+ Gradient: the orientation gradient, or the gradient object if
+ element has no root or is None
+ """
+ stops, orientation = gradient.stops_and_orientation()
+ if element is None or (
+ element.getparent() is None and not isinstance(element, SvgDocumentElement)
+ ):
+ return gradient
+ element.root.defs.add(orientation)
+ if len(stops) > 0:
+ element.root.defs.add(stops, orientation)
+ orientation.set("xlink:href", f"#{stops.get_id()}")
+ return orientation
+
+ def interpolate(self, time=0):
+ """Interpolate with another gradient."""
+ newgrad = self.start_value.copy()
+ # interpolate transforms
+ newgrad.gradientTransform = self.transform_interpolator.interpolate(time)
+
+ # interpolate orientation
+ for attr in self.orientation_interpolator.keys():
+ newgrad.set(attr, self.orientation_interpolator[attr].interpolate(time))
+
+ # interpolate stops
+ if self.newstop_interpolator is not None:
+ newgrad.remove_all(Stop)
+ newgrad.add(
+ *[interp.interpolate(time) for interp in self.newstop_interpolator]
+ )
+ if self.svg is None:
+ return newgrad
+ return GradientInterpolator.append_to_doc(self.svg, newgrad)
+
+
+class LinearGradientInterpolator(GradientInterpolator):
+ """Class for interpolation of linear gradients"""
+
+ def __init__(
+ self, start_value=LinearGradient(), end_value=LinearGradient(), svg=None
+ ):
+ super().__init__(start_value, end_value, svg)
+
+ @staticmethod
+ def initialize_position(grad, bbox):
+ """Initializes a linear gradient's position"""
+ grad.set("x1", bbox.left)
+ grad.set("x2", bbox.right)
+ grad.set("y1", bbox.center.y)
+ grad.set("y2", bbox.center.y)
+
+
+class RadialGradientInterpolator(GradientInterpolator):
+ """Class to interpolate radial gradients"""
+
+ def __init__(
+ self, start_value=RadialGradient(), end_value=RadialGradient(), svg=None
+ ):
+ super().__init__(start_value, end_value, svg)
+
+ @staticmethod
+ def initialize_position(grad, bbox):
+ """Initializes a radial gradient's position"""
+ x, y = bbox.center
+ grad.set("cx", x)
+ grad.set("cy", y)
+ grad.set("fx", x)
+ grad.set("fy", y)
+ grad.set("r", bbox.right - bbox.center.x)
+
+
+class StopInterpolator(AttributeInterpolator):
+ """Class to interpolate gradient stops"""
+
+ def __init__(self, start_value, end_value):
+ super().__init__(start_value, end_value)
+ self.style_interpolator = StyleInterpolator(start_value, end_value)
+ self.position_interpolator = ValueInterpolator(
+ float(start_value.offset), float(end_value.offset)
+ )
+
+ def interpolate(self, time=0):
+ """Interpolates a gradient stop by interpolating style and offset separately
+
+ Args:
+ time (int, optional): Interpolation position. If 0, start_value is returned,
+ if 1, end_value is returned. Defaults to 0.
+
+ Returns:
+ Stop: interpolated gradient stop
+ """
+ newstop = Stop()
+ newstop.style = self.style_interpolator.interpolate(time)
+ newstop.offset = self.position_interpolator.interpolate(time)
+ return newstop
+
+
+class PathInterpolator(AttributeInterpolator):
+ """Base class for Path interpolation"""
+
+ def __init__(self, start_value=Path(), end_value=Path()):
+ super().__init__(start_value.to_superpath(), end_value.to_superpath())
+ self.processed_end_path = None
+ self.processed_start_path = None
+
+ def truncate_subpaths(self):
+ """Truncates the longer path so that all subpaths in both paths have an equal
+ number of bezier commands"""
+ s = [[]]
+ e = [[]]
+ # loop through all subpaths as long as there are remaining ones
+ while self.start_value and self.end_value:
+ # if both subpaths contain a bezier command, append it to s and e
+ if self.start_value[0] and self.end_value[0]:
+ s[-1].append(self.start_value[0].pop(0))
+ e[-1].append(self.end_value[0].pop(0))
+ # if the subpath of start_value is empty, add the remaining empty list as
+ # new subpath of s and one more item of end_value as new subpath of e.
+ # Afterwards, the loop terminates
+ elif self.end_value[0]:
+ s.append(self.start_value.pop(0))
+ e[-1].append(self.end_value[0][0])
+ e.append([self.end_value[0].pop(0)])
+ elif self.start_value[0]:
+ e.append(self.end_value.pop(0))
+ s[-1].append(self.start_value[0][0])
+ s.append([self.start_value[0].pop(0)])
+ # if there are no commands left in both start_value or end_value, add empty
+ # list to both start_value and end_value
+ else:
+ s.append(self.start_value.pop(0))
+ e.append(self.end_value.pop(0))
+ self.processed_start_path = s
+ self.processed_end_path = e
+
+ def interpolate(self, time=0):
+ # create an interpolated path for each interval
+ interp = []
+ # process subpaths
+ for ssubpath, esubpath in zip(
+ self.processed_start_path, self.processed_end_path
+ ):
+ if not (ssubpath or esubpath):
+ break
+ # add a new subpath to the interpolated path
+ interp.append([])
+ # process each bezier command in the subpaths (which now have equal length)
+ for sbezier, ebezier in zip(ssubpath, esubpath):
+ if not (sbezier or ebezier):
+ break
+ # add a new bezier command to the last subpath
+ interp[-1].append([])
+ # process points
+ for point1, point2 in zip(sbezier, ebezier):
+ if not (point1 or point2):
+ break
+ # add a new point to the last bezier command
+ interp[-1][-1].append(
+ ArrayInterpolator(point1, point2).interpolate(time)
+ )
+ # remove final subpath if empty.
+ if not interp[-1]:
+ del interp[-1]
+ return CubicSuperPath(interp)
+
+
+class EqualSubsegmentsInterpolator(PathInterpolator):
+ """Interpolates the path by rediscretizing the subpaths first."""
+
+ @staticmethod
+ def get_subpath_lenghts(path):
+ """prepare lengths for interpolation"""
+ sp_lenghts, total = csplength(path)
+ t = 0
+ lenghts = []
+ for sp in sp_lenghts:
+ for l in sp:
+ t += l / total
+ lenghts.append(t)
+ lenghts.sort()
+ return sp_lenghts, total, lenghts
+
+ @staticmethod
+ def process_path(path, other):
+ """Rediscretize path so that all subpaths have an equal number of segments,
+ so that there is a node at the path "times" where path or other have a node
+
+ Args:
+ path (Path): the first path
+ other (Path): the second path
+
+ Returns:
+ Array: the prepared path description for the intermediate path"""
+ sp_lenghts, total, _ = EqualSubsegmentsInterpolator.get_subpath_lenghts(path)
+ _, _, lenghts = EqualSubsegmentsInterpolator.get_subpath_lenghts(other)
+ t = 0
+ s = [[]]
+ for sp in sp_lenghts:
+ if not path[0]:
+ s.append(path.pop(0))
+ s[-1].append(path[0].pop(0))
+ for l in sp:
+ pt = t
+ t += l / total
+ if lenghts and t > lenghts[0]:
+ while lenghts and lenghts[0] < t:
+ nt = (lenghts[0] - pt) / (t - pt)
+ bezes = cspbezsplitatlength(s[-1][-1][:], path[0][0][:], nt)
+ s[-1][-1:] = bezes[:2]
+ path[0][0] = bezes[2]
+ pt = lenghts.pop(0)
+ s[-1].append(path[0].pop(0))
+ return s
+
+ def __init__(self, start_path=Path(), end_path=Path()):
+ super().__init__(start_path, end_path)
+ # rediscretisize both paths
+ start_copy = copy.deepcopy(self.start_value)
+ # TODO find out why self.start_value.copy() doesn't work
+ self.start_value = EqualSubsegmentsInterpolator.process_path(
+ self.start_value, self.end_value
+ )
+ self.end_value = EqualSubsegmentsInterpolator.process_path(
+ self.end_value, start_copy
+ )
+
+ self.truncate_subpaths()
+
+
+class FirstNodesInterpolator(PathInterpolator):
+ """Interpolates a path by discarding the trailing nodes of the longer subpath"""
+
+ def __init__(self, start_path=Path(), end_path=Path()):
+ super().__init__(start_path, end_path)
+ # which path has fewer segments?
+ lengthdiff = len(self.start_value) - len(self.end_value)
+ # swap shortest first
+ if lengthdiff > 0:
+ self.start_value, self.end_value = self.end_value, self.start_value
+ # subdivide the shorter path
+ for _ in range(abs(lengthdiff)):
+ maxlen = 0
+ subpath = 0
+ segment = 0
+ for y, _ in enumerate(self.start_value):
+ for z in range(1, len(self.start_value[y])):
+ leng = bezlenapprx(
+ self.start_value[y][z - 1], self.start_value[y][z]
+ )
+ if leng > maxlen:
+ maxlen = leng
+ subpath = y
+ segment = z
+ sp1, sp2 = self.start_value[subpath][segment - 1 : segment + 1]
+ self.start_value[subpath][segment - 1 : segment + 1] = cspbezsplit(sp1, sp2)
+ # if swapped, swap them back
+ if lengthdiff > 0:
+ self.start_value, self.end_value = self.end_value, self.start_value
+ self.truncate_subpaths()
diff --git a/share/extensions/inkex/units.py b/share/extensions/inkex/units.py
new file mode 100644
index 0000000..fec0e87
--- /dev/null
+++ b/share/extensions/inkex/units.py
@@ -0,0 +1,150 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) Aaron Spike <aaron@ekips.org>
+# Aurélio A. Heckert <aurium(a)gmail.com>
+# Bulia Byak <buliabyak@users.sf.net>
+# Nicolas Dufour, nicoduf@yahoo.fr
+# Peter J. R. Moulder <pjrm@users.sourceforge.net>
+# Martin Owens <doctormo@gmail.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Convert to and from various units and find the closest matching unit.
+"""
+
+import re
+
+# a dictionary of unit to user unit conversion factors
+CONVERSIONS = {
+ "in": 96.0,
+ "pt": 1.3333333333333333,
+ "px": 1.0,
+ "mm": 3.779527559055118,
+ "cm": 37.79527559055118,
+ "m": 3779.527559055118,
+ "km": 3779527.559055118,
+ "Q": 0.94488188976378,
+ "pc": 16.0,
+ "yd": 3456.0,
+ "ft": 1152.0,
+ "": 1.0, # Default px
+}
+
+# allowed unit types, including percentages, relative units, and others
+# that are not suitable for direct conversion to a length.
+# Note that this is _not_ an exhaustive list of allowed unit types.
+UNITS = [
+ "in",
+ "pt",
+ "px",
+ "mm",
+ "cm",
+ "m",
+ "km",
+ "Q",
+ "pc",
+ "yd",
+ "ft",
+ "",
+ "%",
+ "em",
+ "ex",
+ "ch",
+ "rem",
+ "vw",
+ "vh",
+ "vmin",
+ "vmax",
+ "deg",
+ "grad",
+ "rad",
+ "turn",
+ "s",
+ "ms",
+ "Hz",
+ "kHz",
+ "dpi",
+ "dpcm",
+ "dppx",
+]
+
+UNIT_MATCH = re.compile(rf"({'|'.join(UNITS)})")
+NUMBER_MATCH = re.compile(r"(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)")
+BOTH_MATCH = re.compile(rf"^\s*{NUMBER_MATCH.pattern}\s*{UNIT_MATCH.pattern}\s*$")
+
+
+def parse_unit(value, default_unit="px", default_value=None):
+ """
+ Takes a value such as 55.32px and returns (55.32, 'px')
+ Returns default (None) if no match can be found
+ """
+ ret = BOTH_MATCH.match(str(value))
+ if ret:
+ return float(ret.groups()[0]), ret.groups()[-1] or default_unit
+ return (default_value, default_unit) if default_value is not None else None
+
+
+def are_near_relative(point_a, point_b, eps=0.01):
+ """Return true if the points are near to eps"""
+ return (point_a - point_b <= point_a * eps) and (
+ point_a - point_b >= -point_a * eps
+ )
+
+
+def discover_unit(value, viewbox, default="px"):
+ """Attempt to detect the unit being used based on the viewbox"""
+ # Default 100px when width can't be parsed
+ (value, unit) = parse_unit(value, default_value=100.0)
+ if unit not in CONVERSIONS:
+ return default
+ this_factor = CONVERSIONS[unit] * value / viewbox
+
+ # try to find the svgunitfactor in the list of units known. If we don't find
+ # something, ...
+ for unit, unit_factor in CONVERSIONS.items():
+ if unit != "":
+ # allow 1% error in factor
+ if are_near_relative(this_factor, unit_factor, eps=0.01):
+ return unit
+ return default
+
+
+def convert_unit(value, to_unit, default="px"):
+ """Returns userunits given a string representation of units in another system
+
+ Args:
+ value: <length> string
+ to_unit: unit to convert to
+ default: if ``value`` contains no unit, what unit should be assumed.
+
+ .. versionadded:: 1.1
+ """
+ value, from_unit = parse_unit(value, default_unit=default, default_value=0.0)
+ if from_unit in CONVERSIONS and to_unit in CONVERSIONS:
+ return (
+ value * CONVERSIONS[from_unit] / CONVERSIONS.get(to_unit, CONVERSIONS["px"])
+ )
+ return 0.0
+
+
+def render_unit(value, unit):
+ """Checks and then renders a number with its unit"""
+ try:
+ if isinstance(value, str):
+ (value, unit) = parse_unit(value, default_unit=unit)
+ return f"{value:.6g}{ unit:s}"
+ except TypeError:
+ return ""
diff --git a/share/extensions/inkex/utils.py b/share/extensions/inkex/utils.py
new file mode 100644
index 0000000..2d1dd94
--- /dev/null
+++ b/share/extensions/inkex/utils.py
@@ -0,0 +1,271 @@
+# coding=utf-8
+#
+# Copyright (C) 2010 Nick Drobchenko, nick@cnc-club.ru
+# Copyright (C) 2005 Aaron Spike, aaron@ekips.org
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+"""
+Basic common utility functions for calculated things
+"""
+import os
+import sys
+import random
+import re
+import math
+from argparse import ArgumentTypeError
+from itertools import tee
+
+ABORT_STATUS = -5
+
+(X, Y) = range(2)
+PY3 = sys.version_info[0] == 3
+
+# pylint: disable=line-too-long
+# Taken from https://www.w3.org/Graphics/SVG/1.1/paths.html#PathDataBNF
+DIGIT_REX_PART = r"[0-9]"
+DIGIT_SEQUENCE_REX_PART = rf"(?:{DIGIT_REX_PART}+)"
+INTEGER_CONSTANT_REX_PART = DIGIT_SEQUENCE_REX_PART
+SIGN_REX_PART = r"[+-]"
+EXPONENT_REX_PART = rf"(?:[eE]{SIGN_REX_PART}?{DIGIT_SEQUENCE_REX_PART})"
+FRACTIONAL_CONSTANT_REX_PART = rf"(?:{DIGIT_SEQUENCE_REX_PART}?\.{DIGIT_SEQUENCE_REX_PART}|{DIGIT_SEQUENCE_REX_PART}\.)"
+FLOATING_POINT_CONSTANT_REX_PART = rf"(?:{FRACTIONAL_CONSTANT_REX_PART}{EXPONENT_REX_PART}?|{DIGIT_SEQUENCE_REX_PART}{EXPONENT_REX_PART})"
+NUMBER_REX = re.compile(
+ rf"(?:{SIGN_REX_PART}?{FLOATING_POINT_CONSTANT_REX_PART}|{SIGN_REX_PART}?{INTEGER_CONSTANT_REX_PART})"
+)
+# pylint: enable=line-too-long
+
+
+def _pythonpath():
+ for pth in os.environ.get("PYTHONPATH", "").split(":"):
+ if os.path.isdir(pth):
+ yield pth
+
+
+def get_user_directory():
+ """Return the user directory where extensions are stored.
+
+ .. versionadded:: 1.1"""
+ if "INKSCAPE_PROFILE_DIR" in os.environ:
+ return os.path.abspath(
+ os.path.expanduser(
+ os.path.join(os.environ["INKSCAPE_PROFILE_DIR"], "extensions")
+ )
+ )
+
+ home = os.path.expanduser("~")
+ for pth in _pythonpath():
+ if pth.startswith(home):
+ return pth
+ return None
+
+
+def get_inkscape_directory():
+ """Return the system directory where inkscape's core is.
+
+ .. versionadded:: 1.1"""
+ for pth in _pythonpath():
+ if os.path.isdir(os.path.join(pth, "inkex")):
+ return pth
+ raise ValueError("Unable to determine the location of Inkscape")
+
+
+class KeyDict(dict):
+ """
+ A normal dictionary, except asking for anything not in the dictionary
+ always returns the key itself. This is used for translation dictionaries.
+ """
+
+ def __getitem__(self, key):
+ try:
+ return super().__getitem__(key)
+ except KeyError:
+ return key
+
+
+def parse_percent(val: str):
+ """Parse strings that are either values (i.e., '3.14159') or percentages
+ (i.e. '75%') to a float.
+
+ .. versionadded:: 1.2"""
+ val = val.strip()
+ if val.endswith("%"):
+ return float(val[:-1]) / 100
+ return float(val)
+
+
+def Boolean(value):
+ """ArgParser function to turn a boolean string into a python boolean"""
+ if value.upper() == "TRUE":
+ return True
+ if value.upper() == "FALSE":
+ return False
+ return None
+
+
+def to_bytes(content):
+ """Ensures the content is bytes
+
+ .. versionadded:: 1.1"""
+ if isinstance(content, bytes):
+ return content
+ return str(content).encode("utf8")
+
+
+def debug(what):
+ """Print debug message if debugging is switched on"""
+ errormsg(what)
+ return what
+
+
+def do_nothing(*args, **kwargs): # pylint: disable=unused-argument
+ """A blank function to do nothing
+
+ .. versionadded:: 1.1"""
+
+
+def errormsg(msg):
+ """Intended for end-user-visible error messages.
+
+ (Currently just writes to stderr with an appended newline, but could do
+ something better in future: e.g. could add markup to distinguish error
+ messages from status messages or debugging output.)
+
+ Note that this should always be combined with translation::
+
+ import inkex
+ ...
+ inkex.errormsg(_("This extension requires two selected paths."))
+ """
+ try:
+ sys.stderr.write(msg)
+ except TypeError:
+ sys.stderr.write(str(msg))
+ except UnicodeEncodeError:
+ # Python 2:
+ # Fallback for cases where sys.stderr.encoding is not Unicode.
+ # Python 3:
+ # This will not work as write() does not accept byte strings, but AFAIK
+ # we should never reach this point as the default error handler is
+ # 'backslashreplace'.
+
+ # This will be None by default if stderr is piped, so use ASCII as a
+ # last resort.
+ encoding = sys.stderr.encoding or "ascii"
+ sys.stderr.write(msg.encode(encoding, "backslashreplace"))
+
+ # Write '\n' separately to avoid dealing with different string types.
+ sys.stderr.write("\n")
+
+
+class AbortExtension(Exception):
+ """Raised to print a message to the user without backtrace"""
+
+
+class DependencyError(NotImplementedError):
+ """Raised when we need an external python module that isn't available"""
+
+
+class FragmentError(Exception):
+ """Raised when trying to do rooty things on an xml fragment"""
+
+
+def to(kind): # pylint: disable=invalid-name
+ """
+ Decorator which will turn a generator into a list, tuple or other object type.
+ """
+
+ def _inner(call):
+ def _outer(*args, **kw):
+ return kind(call(*args, **kw))
+
+ return _outer
+
+ return _inner
+
+
+def strargs(string, kind=float):
+ """Returns a list of floats from a string
+
+ .. versionchanged:: 1.1
+ also splits at -(minus) signs by adding a space in front of the - sign
+
+ .. versionchanged:: 1.2
+ Full support for the `SVG Path data BNF
+ <https://www.w3.org/Graphics/SVG/1.1/paths.html#PathDataBNF>`_
+ """
+ return [kind(val) for val in NUMBER_REX.findall(string)]
+
+
+class classproperty: # pylint: disable=invalid-name, too-few-public-methods
+ """Combine classmethod and property decorators"""
+
+ def __init__(self, func):
+ self.func = func
+
+ def __get__(self, obj, owner):
+ return self.func(owner)
+
+
+def filename_arg(name):
+ """Existing file to read or option used in script arguments"""
+ filename = os.path.abspath(os.path.expanduser(name))
+ if not os.path.isfile(filename):
+ raise ArgumentTypeError(f"File not found: {name}")
+ return filename
+
+
+def pairwise(iterable, start=True):
+ "Iterate over a list with overlapping pairs (see itertools recipes)"
+ first, then = tee(iterable)
+ starter = [(None, next(then, None))]
+ if not start:
+ starter = []
+ return starter + list(zip(first, then))
+
+
+EVAL_GLOBALS = {}
+EVAL_GLOBALS.update(random.__dict__)
+EVAL_GLOBALS.update(math.__dict__)
+
+
+def math_eval(function, variable="x"):
+ """Interpret a function string. All functions from math and random may be used.
+
+ .. versionadded:: 1.1
+
+ Returns:
+ a lambda expression if sucessful; otherwise None.
+ """
+ try:
+ if function != "":
+ return eval(
+ f"lambda {variable}: " + (function.strip('"') or "t"), EVAL_GLOBALS, {}
+ )
+ # handle incomplete/invalid function gracefully
+ except SyntaxError:
+ pass
+ return None
+
+
+def is_number(string):
+ """Checks if a value is a number
+
+ .. versionadded:: 1.2"""
+ try:
+ float(string)
+ return True
+ except ValueError:
+ return False