diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 18:24:48 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 18:24:48 +0000 |
commit | cca66b9ec4e494c1d919bff0f71a820d8afab1fa (patch) | |
tree | 146f39ded1c938019e1ed42d30923c2ac9e86789 /share/extensions/inkex/deprecated | |
parent | Initial commit. (diff) | |
download | inkscape-12fc8abae6d434cac7670a59ed3a67301cc2eb10.tar.xz inkscape-12fc8abae6d434cac7670a59ed3a67301cc2eb10.zip |
Adding upstream version 1.2.2.upstream/1.2.2upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
-rw-r--r-- | share/extensions/inkex/deprecated-simple/README.rst | 4 | ||||
-rw-r--r-- | share/extensions/inkex/deprecated-simple/bezmisc.py | 46 | ||||
-rw-r--r-- | share/extensions/inkex/deprecated-simple/cspsubdiv.py | 25 | ||||
-rw-r--r-- | share/extensions/inkex/deprecated-simple/cubicsuperpath.py | 52 | ||||
-rw-r--r-- | share/extensions/inkex/deprecated-simple/ffgeom.py | 92 | ||||
-rwxr-xr-x | share/extensions/inkex/deprecated-simple/run_command.py | 79 | ||||
-rw-r--r-- | share/extensions/inkex/deprecated-simple/simplepath.py | 68 | ||||
-rw-r--r-- | share/extensions/inkex/deprecated-simple/simplestyle.py | 55 | ||||
-rw-r--r-- | share/extensions/inkex/deprecated-simple/simpletransform.py | 122 | ||||
-rw-r--r-- | share/extensions/inkex/deprecated/__init__.py | 3 | ||||
-rw-r--r-- | share/extensions/inkex/deprecated/deprecatedeffect.py | 313 | ||||
-rw-r--r-- | share/extensions/inkex/deprecated/main.py | 178 | ||||
-rw-r--r-- | share/extensions/inkex/deprecated/meta.py | 109 |
13 files changed, 1146 insertions, 0 deletions
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() |