first commit

This commit is contained in:
afoucaultc 2026-06-05 13:11:08 +02:00
commit 205faf4224
5471 changed files with 973850 additions and 0 deletions

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,238 @@
#!/usr/bin/env python3
#
# License: GPL2
# Copyright Mark "Klowner" Riedesel
# https://github.com/Klowner/inkscape-applytransforms
# Modified by David Burghoff <burghoff@utexas.edu>
import inkex
from inkex.paths import CubicSuperPath, Path
from inkex.transforms import Transform
from inkex import Rectangle, Ellipse, Circle
import math
import dhelpers as dh
from inkex.text.cache import BaseElementCache
Itr = Transform([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
# @staticmethod
def remove_attrs(el):
if el.tag == inkex.addNS("g", "svg"):
return el
if el.tag == inkex.addNS("path", "svg") or el.tag == "path":
for attName in el.attrib.keys():
if (
(("sodipodi" in attName) or ("inkscape" in attName))
and "inkscape-academic" not in attName
and "inkscape-scientific" not in attName
):
del el.attrib[attName]
return el
return el
# Scale stroke width and dashes
def applyToStrokes(el, tf):
if "style" in el.attrib:
style = el.cstyle
update = False
if "stroke-width" in style:
try:
stroke_width = dh.ipx(style.get("stroke-width"))
stroke_width *= math.sqrt(abs(tf.a * tf.d - tf.b * tf.c))
style["stroke-width"] = str(stroke_width)
update = True
except AttributeError:
pass
if "stroke-dasharray" in style:
try:
strokedasharray = style.get("stroke-dasharray")
if strokedasharray.lower() != "none":
strokedasharray = dh.listsplit(style.get("stroke-dasharray"))
strokedasharray = [
sdv * math.sqrt(abs(tf.a * tf.d - tf.b * tf.c))
for sdv in strokedasharray
]
style["stroke-dasharray"] = (
str(strokedasharray).strip("[").strip("]")
)
update = True
except AttributeError:
pass
if update:
el.cstyle = style
def transform_clipmask(el, mask=False):
if not (mask):
cm = "clip-path"
else:
cm = "mask"
clippathurl = el.get(cm)
if clippathurl is not None and el.ctransform is not None:
svg = el.croot
clippath = svg.getElementById(clippathurl[5:-1])
if clippath is not None:
d = clippath.duplicate()
clippathurl = "url(#" + d.get_id() + ")"
el.set(cm, clippathurl)
dh.fix_css_clipmask(el, mask=mask)
for k in d.getchildren():
if k.ctransform is not None:
tr = el.ctransform @ k.ctransform
else:
tr = el.ctransform
k.ctransform = tr
poly_tags = {inkex.Polygon.ctag, inkex.Polyline.ctag}
round_tags = {inkex.Ellipse.ctag, inkex.Circle.ctag}
line_tag = inkex.Line.ctag
rect_tag = inkex.Rectangle.ctag
def fuseTransform(el, transf=Itr, irange=None, trange=None, applytostroke=True):
# Fuses an object's transform to its path, adding the additional transformation transf
# When applytostroke enabled, transform goes onto stroke/dashes, keeping it looking the same
# Without it, it is applied to the points only
if el.tag in BaseElementCache.otp_support_tags: # supported types
# Since transforms apply to an object's clips, before applying the transform
# we will need to duplicate the clip path and transform it
transform_clipmask(el, mask=False)
transform_clipmask(el, mask=True)
transf = Transform(transf) @ el.ctransform
el.ctransform = None
el = remove_attrs(el)
if not (transf.b == 0 and transf.c == 0) and isinstance(
el, (Rectangle, Ellipse, Circle)
):
# Rectangles, Ellipses, and Circles need to be converted to paths if there is shear/rotation
el.object_to_path()
if not (transf == Itr and irange is None and trange is None):
# Don't do anything if there is effectively no transform applied
if el.tag in poly_tags:
points = []
for p in el.cpath.end_points:
p = transf.apply_to_point([p[0],p[1]])
points.append(f"{p[0]},{p[1]}")
points = " ".join(points)
el.set("points", points)
elif el.tag in round_tags:
def isequal(a, b):
return abs(a - b) <= transf.absolute_tolerance
if el.tag == inkex.addNS(
"ellipse", "svg"
): # "{http://www.w3.org/2000/svg}ellipse":
rx = dh.ipx(el.get("rx"))
ry = dh.ipx(el.get("ry"))
else:
rx = dh.ipx(el.get("r"))
ry = rx
cx = dh.ipx(el.get("cx"))
cy = dh.ipx(el.get("cy"))
sqxy1 = (cx - rx, cy - ry)
sqxy2 = (cx + rx, cy - ry)
sqxy3 = (cx + rx, cy + ry)
newxy1 = transf.apply_to_point(sqxy1)
newxy2 = transf.apply_to_point(sqxy2)
newxy3 = transf.apply_to_point(sqxy3)
el.set("cx", (newxy1[0] + newxy3[0]) / 2)
el.set("cy", (newxy1[1] + newxy3[1]) / 2)
edgex = math.sqrt(
abs(newxy1[0] - newxy2[0]) ** 2 + abs(newxy1[1] - newxy2[1]) ** 2
)
edgey = math.sqrt(
abs(newxy2[0] - newxy3[0]) ** 2 + abs(newxy2[1] - newxy3[1]) ** 2
)
if isequal(edgex, edgey):
el.tag = inkex.addNS("circle", "svg")
el.set("rx", None)
el.set("ry", None)
el.set("r", edgex / 2)
else:
el.tag = inkex.addNS("ellipse", "svg")
el.set("rx", edgex / 2)
el.set("ry", edgey / 2)
el.set("r", None)
elif el.tag in line_tag:
x1 = dh.ipx(el.get("x1"))
x2 = dh.ipx(el.get("x2"))
y1 = dh.ipx(el.get("y1"))
y2 = dh.ipx(el.get("y2"))
p1 = transf.apply_to_point([x1, y1])
p2 = transf.apply_to_point([x2, y2])
el.set("x1", str(p1[0]))
el.set("y1", str(p1[1]))
el.set("x2", str(p2[0]))
el.set("y2", str(p2[1]))
elif el.tag in rect_tag:
x = dh.ipx(el.get("x"))
y = dh.ipx(el.get("y"))
w = dh.ipx(el.get("width"))
h = dh.ipx(el.get("height"))
pts = [[x, y], [x + w, y], [x + w, y + h], [x, y + h], [x, y]]
xs = []
ys = []
for p in pts:
p = transf.apply_to_point(p)
xs.append(p.x)
ys.append(p.y)
el.set("x", str(min(xs)))
el.set("y", str(min(ys)))
el.set("width", str(max(xs) - min(xs)))
el.set("height", str(max(ys) - min(ys)))
else:
if "d" in el.attrib:
# inkex.utils.debug(el.get('d'))
d = el.get("d")
try:
p = CubicSuperPath(d)
except ZeroDivisionError:
p = Path(d)
if irange is None:
p = Path(p).to_absolute().transform(transf, True)
if irange is not None:
p = Path(p).to_absolute()
pnew = []
for ii in range(len(irange)):
xf = (
trange[ii] @ el.ctransform
) # Transform(el.get("transform", None))
pnew += Path(p[irange[ii][0] : irange[ii][1]]).transform(
xf, True
)
p = pnew
try:
p2 = str(Path(CubicSuperPath(p).to_path()))
except ZeroDivisionError:
p2 = str(Path(p))
el.set("d", p2)
el.cpath = None
if applytostroke:
applyToStrokes(el, transf)
# Duplicate any gradient and apply the transform
for sf in ["fill", "stroke"]:
sfel = el.cstyle.get_link(sf, svg=el.croot)
if sfel is not None and "gradient" in sfel.tag.lower():
d = sfel.duplicate()
el.cstyle[sf] = "url(#{0})".format(d.get_id())
gt = d.get("gradientTransform")
gt = Transform(gt) if gt is not None else Itr
d.set("gradientTransform", str(transf @ gt))
for child in list(el):
fuseTransform(child, transf)

View file

@ -0,0 +1,98 @@
<?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<name>Autoexporter</name>
<id>burghoff.autoexporter</id>
<param name="tab" type="notebook">
<page name="scaling" gui-text="Options">
<label>Launches the Autoexporter, a background program that watches a directory for changes to any SVG and then writes exports in the selected formats.</label>
<label>If you encounter a security prompt, please be sure to allow the program to run.</label>
<label appearance="header">Formats to export</label>
<param name="usepdf" type="bool" gui-text="PDF"
gui-description="Filters and gradients will be rasterized.">true</param>
<param name="usepng" type="bool" gui-text="PNG">false</param>
<param name="useemf" type="bool" gui-text="EMF"
gui-description="Recommended for older versions of Microsoft Office that do not support SVG.">false</param>
<param name="useeps" type="bool" gui-text="EPS">false</param>
<param name="usepsvg" type="bool" gui-text="Plain SVG"
gui-description="Plain SVG that has been optimized for compatibility. &#13;Recommended for newer versions of Microsoft Office that support SVG.">false</param>
<label appearance="header">What to export</label>
<param name="exportwhat" type="optiongroup" appearance="combo"
gui-text=""
gui-description="Autoexport runs in the background watching for changes to a directory. Single export is similar to Save a Copy.">
<option value="1">Autoexport to locations below</option>
<option value="2">Autoexport to this document's location</option>
<option value="3">Single export now</option>
</param>
<param type="path" name="watchdir" gui-text="Watch directory" mode="folder"/>
<param type="path" name="writedir" gui-text="Write directory" mode="folder"/>
<spacer/>
<label>Scientific Inkscape v1.4.23</label>
<label appearance="url">https://github.com/burghoff/Scientific-Inkscape</label>
<label>David Burghoff, University of Texas at Austin</label>
</page>
<page name="advanced" gui-text="Advanced">
<label appearance="header">Rasterization DPI</label>
<label>Resolution for PNG output and objects converted to raster formats</label>
<param name="dpi" type="float" precision="0" min="1" max="9999" gui-text="Rasterization DPI"
gui-description="Certain objects may be rasterized, including filters in PDFs and anything marked for it using the Rasterizer tab.">600</param>
<label appearance="header">Embedded image handling</label>
<label>Cropping and resampling of embedded images can reduce output file sizes.</label>
<param name="imagemode2" type="bool" gui-text="Crop and resample images?"
gui-description="Resample embedded Images at the rasterization DPI if doing so makes the file size smaller. This avoids unnecessarily large files created by high-DPI images.">true</param>
<label appearance="header">Other options</label>
<param name="texttopath" type="bool" gui-text="Convert text to paths"
gui-description="Conversion of text to paths can help guarantee that it looks identical on all platforms.">false</param>
<param name="thinline" type="bool" gui-text="Prevent thin line enhancement"
gui-description="Some PDF readers thicken lines at certain zooms; this option makes your lines impervious to this feature.">true</param>
<param name="stroketopath" type="bool" gui-text="Convert all strokes to paths"
gui-description="Most PDF readers draw stroked lines differently than equivalent filled paths. By converting strokes to paths, this can be prevented. (This uses Inkscape's Stroke to Path, which has some unresolved bugs. Double-check the final output.)">false</param>
<param name="backingrect" type="bool" gui-text="Add transparent backing rectangle"
gui-description="A transparent rectangle behind the image makes it easier to select in certain programs">true</param>
<param name="margin" type="float" precision="1" min="-9999" max="9999" gui-text="Extra margin (mm)"
gui-description="Adds a margin to the export. A small margin can ensure that edges are not clipped off.">0.3</param>
<label appearance="header">PDF options</label>
<param name="latexpdf" type="bool" gui-text="Omit text in PDF and create LaTeX file"
gui-description="Equivalent to same option when saving as PDF">false</param>
<spacer/>
<label>Scientific Inkscape v1.4.23</label>
<label appearance="url">https://github.com/burghoff/Scientific-Inkscape</label>
<label>David Burghoff, University of Texas at Austin</label>
</page>
<page name="rasterizer" gui-text="Rasterizer">
<label appearance="header">Object rasterizer</label>
<label>By running the extension with this tab selected, selected objects can be marked for rasterization (conversion to bitmap). They will remain as normal objects in your SVG, but the Autoexporter will rasterize them during export.</label>
<label> </label>
<label>This can be useful for certain objects that make the export large and sluggish, such as paths that contain tens of thousands of nodes.</label>
<label> </label>
<param name="rasterizermode" type="optiongroup" appearance="combo"
gui-text="Mark selected objects to be">
<option value="1">Rasterized as PNG</option>
<option value="2">Rasterized as JPG</option>
<option value="3">Converted to path</option>
<option value="4">Left unchanged</option>
</param>
<spacer/>
<label>Scientific Inkscape v1.4.23</label>
<label appearance="url">https://github.com/burghoff/Scientific-Inkscape</label>
<label>David Burghoff, University of Texas at Austin</label>
</page>
</param>
<effect needs-live-preview="false">
<object-type>text</object-type>
<effects-menu>
<submenu name="Scientific"/>
</effects-menu>
</effect>
<script>
<command location="inx" interpreter="python">autoexporter.py</command>
</script>
</inkscape-extension>

View file

@ -0,0 +1,911 @@
# Inkscape Auto-Exporter, by David Burghoff
# Service that checks a folder for changes in svg files, and then exports them
# automatically to another folder in multiple formats.
DEBUG = False
WHILESLEEP = 0.5
MAXTHREADS = 1000
import sys, platform, os, threading, time, copy, pickle
import tempfile
systmpdir = os.path.abspath(tempfile.gettempdir())
aes = os.path.join(systmpdir, "si_ae_settings.p")
with open(aes, "rb") as f:
input_options = pickle.load(f)
os.remove(aes)
bfn = input_options.inkscape_bfn
sys.path += input_options.syspath
guitype = input_options.guitype
import dhelpers as dh # noqa
import inkex
import inkex.text.parser # needed to prevent GTK crashing
import autoexporter
from autoexporter import Exporter
def mprint(*args, **kwargs):
if guitype == "gtk":
global win
GLib.idle_add(win.print_text, args[0])
else:
print(*args, **kwargs)
# Get svg files in directory
def get_files(dirin):
import re
from datetime import datetime
def ends_with_date(s):
pattern = r"\.(\d{4}_\d{2}_\d{2}_\d{2}_\d{2}_\d{2}\.\d{1,6})\.svg$"
match = re.search(pattern, s)
if match:
date_string = match.group(1)
custom_format = "%Y_%m_%d_%H_%M_%S.%f"
try:
datetime.strptime(date_string, custom_format)
return True
except ValueError:
return False
return False
fs = []
try:
for f in os.scandir(dirin):
excludes = ["_portable.svg", "_plain.svg"]
if (
f.name.endswith(".svg")
and all([not (f.name.endswith(ex)) for ex in excludes])
and not (ends_with_date(f.name))
):
fs.append(os.path.join(os.path.abspath(dirin), f.name))
return fs
except: # (FileNotFoundError, OSError):
return None # directory missing (cloud drive error?)
class Watcher:
"""Class that watches a folder for changes to SVGs"""
def __init__(self, directory_to_watch, createfcn=None, modfcn=None, deletefcn=None):
import re, sys
from threading import Timer
import warnings
warnings.filterwarnings(
"ignore", message="Failed to import fsevents. Fall back to kqueue"
)
mydir = os.path.dirname(os.path.abspath(__file__))
packages = os.path.join(mydir, "packages")
if packages not in sys.path:
sys.path.append(packages)
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class Handler(FileSystemEventHandler):
def __init__(self, createfcn=None, modfcn=None, deletefcn=None):
# Dictionary to store the last event and debounce timers for each file
self.debounce_timers = {}
self.last_event = {}
self.file_mod_times = {}
self.createfcn = createfcn
self.modfcn = modfcn
self.deletefcn = deletefcn
# Initialize file modification times
self.initialize_mod_times(directory_to_watch)
@staticmethod
def is_target_file(file_name):
excludes = ["_portable.svg", "_plain.svg"]
pattern = r"\.(\d{4}_\d{2}_\d{2}_\d{2}_\d{2}_\d{2}\.\d{1,6})\.svg$"
if any(file_name.endswith(ex) for ex in excludes):
return False
if re.search(pattern, file_name):
return False
return file_name.endswith(".svg")
@staticmethod
def get_mod_time(file_path):
try:
return os.path.getmtime(file_path)
except FileNotFoundError:
return None
def initialize_mod_times(self, directory):
for file in os.listdir(directory):
file_path = os.path.join(directory, file)
if os.path.isfile(file_path) and self.is_target_file(file_path):
mod_time = self.get_mod_time(file_path)
if mod_time:
self.file_mod_times[file_path] = mod_time
def debounce(self, event):
# Process the last event
if event.event_type == "created":
if self.createfcn is not None:
self.createfcn(event.src_path)
elif event.event_type == "modified":
if self.modfcn is not None:
self.modfcn(event.src_path)
elif event.event_type == "deleted":
if self.deletefcn is not None:
self.deletefcn(event.src_path)
def handle_event(self, event):
if event.is_directory:
return None
if self.is_target_file(event.src_path):
# Cancel existing timer if present
if event.src_path in self.debounce_timers:
self.debounce_timers[event.src_path].cancel()
# Store the event
self.last_event[event.src_path] = event
# Set a new timer
self.debounce_timers[event.src_path] = Timer(
1.0, self.debounce, [event]
)
self.debounce_timers[event.src_path].start()
def on_created(self, event):
self.handle_event(event)
def on_modified(self, event):
if event.is_directory:
return None
if self.is_target_file(event.src_path):
new_mod_time = self.get_mod_time(event.src_path)
old_mod_time = self.file_mod_times.get(event.src_path)
# Only handle the event if the file modification time has changed
if new_mod_time and new_mod_time != old_mod_time:
self.file_mod_times[event.src_path] = new_mod_time
self.handle_event(event)
def on_deleted(self, event):
if event.src_path in self.file_mod_times:
del self.file_mod_times[event.src_path]
self.handle_event(event)
self.Handler = Handler # Make Handler an attribute of Watcher
self.observer = Observer()
self.directory_to_watch = directory_to_watch
self.createfcn = createfcn
self.modfcn = modfcn
self.deletefcn = deletefcn
self.start()
def start(self):
event_handler = self.Handler(
createfcn=self.createfcn, modfcn=self.modfcn, deletefcn=self.deletefcn
)
self.observer.schedule(event_handler, self.directory_to_watch, recursive=False)
self.observer.start()
def stop(self):
self.observer.stop()
self.observer.join()
# Threading class
class FileCheckerThread(threading.Thread):
def __init__(self, watchdir, writedir):
threading.Thread.__init__(self)
self.stopped = False
self.nf = True # new folder
self.ea = False # export all
self.es = False # export selected
self.dm = False # debug mode
self.promptpending = True
self.watcher = None
self.watchdir = input_options.watchdir
self.writedir = input_options.writedir
self.thread_queue = []
self.running_threads = []
self.finished_threads = []
def queue_thread(self, f):
for t in self.thread_queue + self.running_threads:
if t.file == f:
t.stopped = True
fthr = AutoExporterThread()
fthr.file = f
fthr.outtemplate = autoexporter.joinmod(self.writedir, os.path.split(f)[1])
self.thread_queue.append(fthr)
def start_watcher(self):
if self.watcher is not None: # Stop existing watcher
self.watcher.stop()
mfcn = lambda x: self.queue_thread(os.path.abspath(x))
self.watcher = Watcher(self.watchdir, createfcn=mfcn, modfcn=mfcn)
def run(self):
self.start_watcher()
while not self.stopped:
self.checkongoing = True
if self.nf:
if guitype == "terminal":
mprint(
"Export formats: "
+ ", ".join([v.upper() for v in input_options.formats])
)
mprint("Rasterization DPI: " + str(input_options.dpi))
mprint("Watch directory: " + self.watchdir)
mprint("Write directory: " + self.writedir)
self.nf = False
if self.watcher.directory_to_watch != self.watchdir:
self.start_watcher()
if self.ea: # export all
self.ea = False
updatefiles = get_files(self.watchdir)
if updatefiles is None:
mprint("Cannot access watch directory.")
updatefiles = []
elif self.es:
self.es = False
updatefiles = [self.selectedfile]
else:
updatefiles = []
loopme = True
while loopme:
for f in sorted(updatefiles):
self.queue_thread(f)
while (
len(self.thread_queue) > 0
and len(self.running_threads) < MAXTHREADS
and not self.stopped
):
self.thread_queue[0].start()
self.running_threads.append(self.thread_queue[0])
self.thread_queue.remove(self.thread_queue[0])
time.sleep(WHILESLEEP)
for thr in reversed(self.running_threads):
if not thr.is_alive():
self.running_threads.remove(thr)
self.finished_threads.append(thr)
self.promptpending = True
while self.dm and any([thr.is_alive() for thr in self.running_threads]):
time.sleep(WHILESLEEP)
loopme = self.dm
if self.promptpending and len(self.running_threads) + len(self.thread_queue) == 0:
if guitype == "terminal":
mprint(promptstring)
self.promptpending = False
time.sleep(WHILESLEEP)
self.watcher.stop()
for t in self.running_threads:
t.stopped = True
while any([thr.is_alive() for thr in self.running_threads]):
time.sleep(WHILESLEEP)
for thr in reversed(self.running_threads):
self.running_threads.remove(thr)
self.finished_threads.append(thr)
class PromptThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.ui = None # user input
def run(self):
self.ui = input("")
class AutoExporterThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.file = None
self.outtemplate = None
self.stopped = False
def run(self):
fname = os.path.split(self.file)[1]
try:
offset = round(os.get_terminal_size().columns / 2)
except:
offset = 40
fname = fname + " " * max(0, offset - len(fname))
mprint(fname + ": Beginning export")
opts = copy.copy(input_options)
opts.debug = DEBUG
opts.prints = mprint
opts.aeThread = self
opts.original_file = self.file
opts.formats = [
fmt
for fmt, use in zip(
["pdf", "png", "emf", "eps", "psvg"],
[opts.usepdf, opts.usepng, opts.useemf, opts.useeps, opts.usepsvg],
)
if use
]
opts.outtemplate = self.outtemplate
opts.bfn = bfn
try:
Exporter(self.file, opts).export_all()
except SystemExit:
pass
except:
import traceback
error_message = f"Exception in {fname}\n"
error_message += traceback.format_exc()
mprint(error_message)
if guitype == "gtk":
import warnings
with warnings.catch_warnings():
# Ignore ImportWarning for Gtk
warnings.simplefilter("ignore")
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GLib, Gdk
class AutoexporterWindow(Gtk.Window):
def __init__(self, ct):
Gtk.Window.__init__(self, title="Autoexporter")
WINDOW_WIDTH = 450
MARGIN = 10
self.set_default_size(WINDOW_WIDTH, -1)
self.set_position(Gtk.WindowPosition.CENTER)
self.notebook = Gtk.Notebook()
self.notebook.set_margin_start(MARGIN)
self.notebook.set_margin_end(MARGIN)
self.notebook.set_margin_top(MARGIN)
self.notebook.set_margin_bottom(MARGIN)
self.add(self.notebook)
# Tab 1: Controls
tab1_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
self.notebook.append_page(tab1_box, Gtk.Label(label="Controls"))
# Top message window
self.selected_file_label = Gtk.TextView()
self.selected_file_label.set_editable(False)
self.selected_file_label.set_wrap_mode(Gtk.WrapMode.CHAR)
self.selected_file_label.get_buffer().set_text("No file selected.")
self.message_scrolled_window = Gtk.ScrolledWindow() # Renamed for clarity
self.message_scrolled_window.set_size_request(WINDOW_WIDTH-2*MARGIN, 150)
self.message_scrolled_window.set_hexpand(True)
self.message_scrolled_window.set_vexpand(True)
self.message_scrolled_window.add(self.selected_file_label)
tab1_box.pack_start(self.message_scrolled_window, True, True, 0)
# Bottom file log window
self.filelogstore = Gtk.ListStore(str, str)
self.treeview = Gtk.TreeView(model=self.filelogstore)
renderer_text = Gtk.CellRendererText()
column_text = Gtk.TreeViewColumn("Filename", renderer_text, text=0)
column_text.set_fixed_width((WINDOW_WIDTH-2*MARGIN)*0.49) # Set your desired fixed width
self.treeview.append_column(column_text)
renderer_text = Gtk.CellRendererText()
column_text = Gtk.TreeViewColumn("Message", renderer_text, text=1)
self.treeview.append_column(column_text)
self.file_log_scrolled_window = Gtk.ScrolledWindow() # Renamed for clarity
self.file_log_scrolled_window.set_policy(
Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC
)
self.file_log_scrolled_window.set_size_request(WINDOW_WIDTH-2*MARGIN, 350)
self.file_log_scrolled_window.set_vexpand(True)
self.file_log_scrolled_window.add(self.treeview)
self.filelogstore.connect("row-inserted", self.on_row_inserted)
self.maxlsrows = 100
self.treeview.connect("size-allocate", self.on_treeview_size_allocate)
tab1_box.pack_start(self.file_log_scrolled_window, True, True, 0)
# Separator
separator = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
tab1_box.pack_start(separator, False, True, 0)
# Watch directory
LABEL_WIDTH = 16
watch_file_chooser_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
watch_file_chooser_label = Gtk.Label(label="Watch directory", xalign=0.5) # Center text
watch_file_chooser_label.set_width_chars(LABEL_WIDTH) # Set fixed width
self.watch_file_chooser_button = Gtk.FileChooserButton(title="Choose watch directory", action=Gtk.FileChooserAction.SELECT_FOLDER)
self.watch_file_chooser_button.set_filename(input_options.watchdir) # Set the initial folder here
self.watch_file_chooser_button.connect("file-set", self.watch_folder_button_clicked)
self.watch_file_chooser_button.set_hexpand(True)
self.watch_file_chooser_button.set_halign(Gtk.Align.FILL)
watch_file_chooser_box.pack_start(watch_file_chooser_label, False, False, 0)
watch_file_chooser_box.pack_start(self.watch_file_chooser_button, True, True, 0)
tab1_box.pack_start(watch_file_chooser_box, False, False, 0)
# Write directory
write_file_chooser_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
write_file_chooser_label = Gtk.Label(label="Write directory", xalign=0.5) # Center text
write_file_chooser_label.set_width_chars(LABEL_WIDTH) # Set fixed width
self.write_file_chooser_button = Gtk.FileChooserButton(title="Choose write directory", action=Gtk.FileChooserAction.SELECT_FOLDER)
self.write_file_chooser_button.set_filename(input_options.writedir) # Set the initial folder here
self.write_file_chooser_button.connect("file-set", self.write_folder_button_clicked)
self.write_file_chooser_button.set_hexpand(True)
self.write_file_chooser_button.set_halign(Gtk.Align.FILL)
write_file_chooser_box.pack_start(write_file_chooser_label, False, False, 0)
write_file_chooser_box.pack_start(self.write_file_chooser_button, True, True, 0)
tab1_box.pack_start(write_file_chooser_box, False, False, 0)
# Export all button
self.ea_button = Gtk.Button(label="Export all")
self.ea_button.connect("clicked", self.export_all_clicked)
tab1_box.pack_start(self.ea_button, False, False, 0)
# Export file button
self.ef_button = Gtk.Button(label="Export file")
self.ef_button.connect("clicked", self.export_file_clicked)
tab1_box.pack_start(self.ef_button, False, False, 0)
# Exit button
self.exit_button = Gtk.Button(label="Exit")
self.exit_button.connect("clicked", self.exit_clicked)
tab1_box.pack_start(self.exit_button, False, False, 0)
# Tab 2: Options
tab2_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
tab2_box.set_margin_start(10)
tab2_box.set_margin_end(10)
tab2_box.set_margin_top(10)
tab2_box.set_margin_bottom(10)
self.notebook.append_page(tab2_box, Gtk.Label(label="Options"))
css_provider = Gtk.CssProvider()
css_provider.load_from_data(b".label-bold { font-weight: bold; }")
Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
# Formats to export
export_label = Gtk.Label(label="Formats to export", xalign=0)
export_label.get_style_context().add_class("label-bold")
tab2_box.pack_start(export_label, False, False, 5)
export_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
tab2_box.pack_start(export_box, False, False, 10)
vbox_formats = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
export_box.pack_start(vbox_formats, True, True, 0)
self.pdf_check = Gtk.CheckButton(label="PDF")
self.png_check = Gtk.CheckButton(label="PNG")
self.emf_check = Gtk.CheckButton(label="EMF")
self.eps_check = Gtk.CheckButton(label="EPS")
self.svg_check = Gtk.CheckButton(label="Plain SVG")
vbox_formats.pack_start(self.pdf_check, False, False, 0)
vbox_formats.pack_start(self.png_check, False, False, 0)
vbox_formats.pack_start(self.emf_check, False, False, 0)
vbox_formats.pack_start(self.eps_check, False, False, 0)
vbox_formats.pack_start(self.svg_check, False, False, 0)
# Rasterization DPI
dpi_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
export_box.pack_start(dpi_box, False, False, 0)
dpi_label = Gtk.Label(label="Rasterization DPI")
adj = Gtk.Adjustment(value=1.0, lower=1, upper=10000, step_increment=1,
page_increment=10, page_size=0)
self.dpi_spin = Gtk.SpinButton(adjustment=adj, digits=0)
dpi_box.pack_start(dpi_label, False, False, 0)
dpi_box.pack_start(self.dpi_spin, False, False, 0)
# Embedded image handling options
image_handling_label = Gtk.Label(label="Embedded image handling", xalign=0)
image_handling_label.get_style_context().add_class("label-bold")
tab2_box.pack_start(image_handling_label, False, False, 5)
self.crop_check = Gtk.CheckButton(label="Crop and resample images?")
tab2_box.pack_start(self.crop_check, False, False, 5)
# Other options
other_options_label = Gtk.Label(label="Other options", xalign=0)
other_options_label.get_style_context().add_class("label-bold")
tab2_box.pack_start(other_options_label, False, False, 5)
other_options_box = Gtk.Box(
orientation=Gtk.Orientation.HORIZONTAL, spacing=10
)
tab2_box.pack_start(other_options_box, False, False, 10)
vbox_other_options = Gtk.Box(
orientation=Gtk.Orientation.VERTICAL, spacing=5
)
other_options_box.pack_start(vbox_other_options, True, True, 0)
self.convert_text_check = Gtk.CheckButton(label="Convert text to paths")
self.prevent_thin_lines_check = Gtk.CheckButton(
label="Prevent thin line enhancement"
)
self.convert_strokes_check = Gtk.CheckButton(
label="Convert all strokes to paths"
)
self.transparent_back_check = Gtk.CheckButton(
label="Add transparent backing rectangle"
)
vbox_other_options.pack_start(self.convert_text_check, False, False, 0)
vbox_other_options.pack_start(
self.prevent_thin_lines_check, False, False, 0
)
vbox_other_options.pack_start(self.convert_strokes_check, False, False, 0)
vbox_other_options.pack_start(self.transparent_back_check, False, False, 0)
extra_margin_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5)
other_options_box.pack_start(extra_margin_box, False, False, 0)
self.extra_margin_label = Gtk.Label(label="Extra margin (mm)")
adj = Gtk.Adjustment(value=1.0, lower=0, upper=10, step_increment=0.1, page_increment=1, page_size=0)
self.extra_margin_spin = Gtk.SpinButton(adjustment=adj, digits=1)
extra_margin_box.pack_start(self.extra_margin_label, False, False, 0)
extra_margin_box.pack_start(self.extra_margin_spin, False, False, 0)
# PDF options
pdf_options_label = Gtk.Label(label="PDF options", xalign=0)
pdf_options_label.get_style_context().add_class("label-bold")
tab2_box.pack_start(pdf_options_label, False, False, 5)
self.omit_text_check = Gtk.CheckButton(
label="Omit text in PDF and create LaTeX file"
)
tab2_box.pack_start(self.omit_text_check, False, False, 5)
# Initialize from input_options
self.pdf_check.set_active(input_options.usepdf)
self.png_check.set_active(input_options.usepng)
self.emf_check.set_active(input_options.useemf)
self.eps_check.set_active(input_options.useeps)
self.svg_check.set_active(input_options.usepsvg)
self.dpi_spin.set_value(float(input_options.dpi))
self.crop_check.set_active(input_options.imagemode2)
self.convert_text_check.set_active(input_options.texttopath)
self.prevent_thin_lines_check.set_active(input_options.thinline)
self.convert_strokes_check.set_active(input_options.stroketopath)
self.transparent_back_check.set_active(input_options.backingrect)
self.extra_margin_spin.set_value(float(input_options.margin))
self.omit_text_check.set_active(input_options.latexpdf)
# Connect options buttons to callbacks
self.pdf_check.connect("toggled", self.on_pdf_toggled)
self.png_check.connect("toggled", self.on_png_toggled)
self.emf_check.connect("toggled", self.on_emf_toggled)
self.eps_check.connect("toggled", self.on_eps_toggled)
self.svg_check.connect("toggled", self.on_svg_toggled)
self.dpi_spin.connect("value-changed", self.on_dpi_changed)
self.crop_check.connect("toggled", self.on_crop_toggled)
self.convert_text_check.connect("toggled", self.on_convert_text_toggled)
self.prevent_thin_lines_check.connect(
"toggled", self.on_prevent_thin_lines_toggled
)
self.convert_strokes_check.connect(
"toggled", self.on_convert_strokes_toggled
)
self.transparent_back_check.connect(
"toggled", self.on_transparent_back_toggled
)
self.extra_margin_spin.connect("value-changed", self.on_margin_changed)
self.omit_text_check.connect("toggled", self.on_omit_text_toggled)
self.ct = ct
def on_treeview_size_allocate(self, widget, allocation):
'''
Scroll to end after file inserted to File Log window
Seems to sometimes cause GTK to crash
'''
if len(self.filelogstore)>0:
path = Gtk.TreePath.new_from_string(str(len(self.filelogstore)-1))
column = None
self.treeview.scroll_to_cell(path, column, False, 0.0, 1.0)
# def on_text_buffer_insert_text(self, buffer, iter, text, length):
# # Scroll to end after text printed
# mark = buffer.get_insert()
# self.selected_file_label.scroll_to_mark(mark, 0.0, True, 0.0, 1.0)
def on_row_inserted(self, store, path, iter):
# Count the number of rows currently in the store
num_rows = len(self.filelogstore)
# If the number of rows exceeds 100, remove the oldest rows
if num_rows > self.maxlsrows:
for i in range(num_rows - self.maxlsrows):
self.filelogstore.remove(self.filelogstore.get_iter_first())
def print_text(self, text):
lns = text.split("\n")
tor = []
exception = text.startswith("Exception")
for ln in lns:
if "Export formats: " in ln or "Rasterization DPI: " in ln or exception:
continue
if (
":" in ln
and len(ln.split(":")) == 2
and "Inkscape binary" not in ln
and "Python interpreter" not in ln
):
ln2 = [v.strip(" ") for v in ln.split(":")]
self.filelogstore.append(ln2)
tor.append(ln)
lns = [item for item in lns if item not in tor]
text = "\n".join(lns)
if len(text) > 0:
buffer = self.selected_file_label.get_buffer()
self.selected_file_label.get_buffer()
start, end = buffer.get_bounds()
if buffer.get_text(start, end, False) == "No file selected.":
buffer.set_text("")
buffer.insert(buffer.get_end_iter(), text + "\n")
def exit_clicked(self, widget):
self.destroy()
def watch_folder_button_clicked(self, widget):
selected_file = self.watch_file_chooser_button.get_filename()
# Check if selected_file is None, which indicates the user clicked 'Cancel'
if selected_file is not None:
self.ct.watchdir = selected_file
self.ct.nf = True
def write_folder_button_clicked(self, widget):
selected_file = self.write_file_chooser_button.get_filename()
# Check if selected_file is None, which indicates the user clicked 'Cancel'
if selected_file is not None:
self.ct.writedir = selected_file
self.ct.nf = True
def export_all_clicked(self, widget):
self.ct.ea = True
# self.ct.dm = True
def export_file_clicked(self, widget):
native = Gtk.FileChooserNative.new(
"Please choose a file", self, Gtk.FileChooserAction.OPEN, None, None
)
filter_ppt = Gtk.FileFilter()
filter_ppt.set_name("SVG files")
filter_ppt.add_pattern("*.svg")
native.add_filter(filter_ppt)
response = native.run()
if response == Gtk.ResponseType.ACCEPT:
selected_file = native.get_filename()
self.ct.selectedfile = selected_file
self.ct.es = True
native.destroy()
def on_pdf_toggled(self, widget):
input_options.usepdf = widget.get_active()
print("PDF option toggled:", widget.get_active())
def on_png_toggled(self, widget):
input_options.usepng = widget.get_active()
print("PNG option toggled:", widget.get_active())
def on_emf_toggled(self, widget):
input_options.useemf = widget.get_active()
print("EMF option toggled:", widget.get_active())
def on_eps_toggled(self, widget):
input_options.useeps = widget.get_active()
print("EPS option toggled:", widget.get_active())
def on_svg_toggled(self, widget):
input_options.usepsvg = widget.get_active()
print("SVG option toggled:", widget.get_active())
def on_dpi_changed(self, widget):
input_options.dpi = widget.get_value_as_int()
print("Rasterization DPI changed:", widget.get_value_as_int())
def on_crop_toggled(self, widget):
input_options.imagemode2 = widget.get_active()
print("Crop and resample images option toggled:", widget.get_active())
def on_convert_text_toggled(self, widget):
input_options.texttopath = widget.get_active()
print("Convert text to paths option toggled:", widget.get_active())
def on_prevent_thin_lines_toggled(self, widget):
input_options.thinline = widget.get_active()
print("Prevent thin line enhancement option toggled:", widget.get_active())
def on_convert_strokes_toggled(self, widget):
input_options.stroketopath = widget.get_active()
print("Convert all strokes to paths option toggled:", widget.get_active())
def on_transparent_back_toggled(self, widget):
input_options.backingrect = widget.get_active()
print(
"Add transparent backing rectangle option toggled:", widget.get_active()
)
def on_margin_changed(self, widget):
input_options.margin = widget.get_value()
print("Extra margin changed:", widget.get_value())
def on_omit_text_toggled(self, widget):
input_options.latexpdf = widget.get_active()
print(
"Omit text in PDF and create LaTeX file option toggled:",
widget.get_active(),
)
fc = FileCheckerThread(input_options.watchdir,input_options.writedir)
global win
win = AutoexporterWindow(fc)
win.set_keep_above(True)
mprint("Scientific Inkscape Autoexporter")
mprint("\nPython interpreter: " + sys.executable)
mprint("Inkscape binary: " + bfn + "")
import image_helpers as ih
mprint("Python does not have PIL, images will not be cropped"
" or converted to JPG\n" if not ih.hasPIL else "Python has PIL\n")
fc.start()
def quit_and_close(self):
fc.stopped = True
Gtk.main_quit()
win.connect("destroy", quit_and_close)
win.show_all()
win.set_keep_above(False)
Gtk.main()
else:
try:
import tkinter
promptstring = ("\nEnter D to change directories, R to change DPI, F to"
" export a file, A to export all now, and Q to quit: ")
hastkinter = True
except:
promptstring = "\nEnter A to export all now, R to change DPI, and Q to quit: "
hastkinter = False
if platform.system().lower() == "darwin":
mprint(" ")
elif platform.system().lower() == "windows":
# Disable QuickEdit, which I think causes the occasional freezes
# From https://stackoverflow.com/questions/37500076/
# how-to-enable-windows-console-quickedit-mode-from-python
def quickedit(enabled=1):
import ctypes
"""
Enable or disable quick edit mode to prevent system hangs,
sometimes when using remote desktop
Param (Enabled)
enabled = 1(default), enable quick edit mode in python console
enabled = 0, disable quick edit mode in python console
"""
# -10 is input handle => STD_INPUT_HANDLE (DWORD) -10 |
# https://docs.microsoft.com/en-us/windows/console/getstdhandle
# default = (0x4|0x80|0x20|0x2|0x10|0x1|0x40|0x200)
# 0x40 is quick edit, #0x20 is insert mode
# 0x8 is disabled by default
# https://docs.microsoft.com/en-us/windows/console/setconsolemode
kernel32 = ctypes.windll.kernel32
if enabled:
kernel32.SetConsoleMode(
kernel32.GetStdHandle(-10),
(0x4 | 0x80 | 0x20 | 0x2 | 0x10 | 0x1 | 0x40 | 0x100),
)
# mprint("Console Quick Edit Enabled")
else:
kernel32.SetConsoleMode(
kernel32.GetStdHandle(-10),
(0x4 | 0x80 | 0x20 | 0x2 | 0x10 | 0x1 | 0x00 | 0x100),
)
# mprint("Console Quick Edit Disabled")
quickedit(0) # Disable quick edit in terminal
mprint("Scientific Inkscape Autoexporter")
mprint("\nPython interpreter: " + sys.executable)
mprint("Inkscape binary: " + bfn + "")
import image_helpers as ih
mprint("Python does not have PIL, images will not be cropped"
" or converted to JPG\n" if not ih.hasPIL else "Python has PIL\n")
def Get_Directories():
root = tkinter.Tk()
root.geometry("1x1")
root.lift()
root.overrideredirect(1)
mprint("Select a directory to watch")
watchdir = tkinter.filedialog.askdirectory(title="Select a directory to watch")
root.destroy()
if watchdir == "":
raise
root = tkinter.Tk()
root.geometry("1x1")
root.lift()
root.overrideredirect(1)
mprint("Select a directory to write to")
writedir = tkinter.filedialog.askdirectory(
title="Select a directory to write to"
)
root.destroy()
if writedir == "":
raise
return watchdir, writedir
def Get_File(initdir):
root = tkinter.Tk()
root.geometry("1x1")
root.lift()
root.overrideredirect(1)
mprint("Select a file to export")
selectedfile = tkinter.filedialog.askopenfile(title="Select a file")
root.destroy()
selectedfile.close()
return selectedfile.name
def get_defs(svg):
for k in list(svg):
if isinstance(k, (inkex.Defs)):
return k
d = inkex.Defs()
# no Defs, make one
svg.insert(len(list(svg)), d)
return d
# Main loop
fc = FileCheckerThread(input_options.watchdir,input_options.writedir)
if fc.watchdir is None or fc.writedir is None:
fc.watchdir, fc.writedir = Get_Directories()
fc.start()
while fc.nf: # wait until it's done initializing
pass
t2 = PromptThread()
t2.start()
keeprunning = True
while keeprunning:
if not (t2.is_alive()):
if t2.ui in ["Q", "q"]:
fc.stopped = True
keeprunning = False
elif t2.ui in ["D", "d"]:
if hastkinter:
try:
fc.watchdir, fc.writedir = Get_Directories()
fc.nf = True
except:
pass
elif t2.ui in ["R", "r"]:
input_options.dpi = int(input("Enter new rasterization DPI: "))
elif t2.ui in ["A", "a"]:
fc.ea = True
elif t2.ui in ["F", "f"]:
if hastkinter:
try:
fc.selectedfile = Get_File(fc.watchdir)
fc.es = True
except:
pass
elif t2.ui in ["#"]:
fc.dm = True
# entering # starts an infinite export loop in the current dir
fc.ea = True
else:
mprint("Invalid input!")
if keeprunning:
t2 = PromptThread()
t2.start()
fc.promptpending = True
time.sleep(WHILESLEEP)
# On macOS close the terminal we opened
# https://superuser.com/questions/158375/
# how-do-i-close-the-terminal-in-osx-from-the-command-line
if platform.system().lower() == "darwin":
os.system(
"osascript -e 'tell application \"Terminal\" to close first window' & exit"
)

View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<name>Combine by color</name>
<id>burghoff.combinebycolor</id>
<param name="tab" type="notebook">
<page name="scaling" gui-text="Options">
<label>Combines all selected paths of the same color (and style) into a single path, ignoring lines that are darker than a certain threshold. Clips and masks will be released.
</label>
<label>Useful when:</label>
<label indent="1">1. You would like to reduce the number of elements, improving responsivity and shrinking the file size.</label>
<label indent="1">2. Your plot rendering program has split your data into multiple paths.</label>
<label>Note: Inkscape may freeze if you try to pass thousands of elements to an extension. If necessary, temporarily group them.</label>
<label appearance="header">Lightness threshold</label>
<label>If the stroke Lightness is less than the Lightness threshold, combining will not occur. This can be used to exclude axes and ticks, which are usually black.</label>
<param name="lightnessth" type="float" precision="0" min="0" max="100" gui-text="Lightness threshold (%)">15</param>
<spacer/>
<label>Scientific Inkscape v1.4.23</label>
<label appearance="url">https://github.com/burghoff/Scientific-Inkscape</label>
<label>David Burghoff, University of Texas at Austin</label>
</page>
</param>
<effect needs-live-preview="false">
<object-type>text</object-type>
<effects-menu>
<submenu name="Scientific"/>
</effects-menu>
</effect>
<script>
<command location="inx" interpreter="python">combine_by_color.py</command>
</script>
</inkscape-extension>

View file

@ -0,0 +1,130 @@
#!/usr/bin/env python
# coding=utf-8
#
# Copyright (C) 2021 David Burghoff, dburghoff@nd.edu
#
# 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.
#
import dhelpers as dh
import inkex
from inkex import NamedView, Defs, Metadata, ForeignObject, Group, MissingGlyph
import math
class CombineByColor(inkex.EffectExtension):
# def document_path(self):
# return 'test'
def add_arguments(self, pars):
pars.add_argument("--tab", help="The selected UI-tab when OK was pressed")
pars.add_argument(
"--lightnessth", type=float, default=15, help="Lightness threshold"
)
def effect(self):
lightness_threshold = self.options.lightnessth / 100
sel = [self.svg.selection[ii] for ii in range(len(self.svg.selection))]
# should work with both v1.0 and v1.1
sel = [v for el in sel for v in el.descendants2()]
allel = [v for v in self.svg.descendants2()]
elord = [allel.index(v) for v in sel]
# order of selected elements in svg
els = [
el
for el in sel
if not (
isinstance(
el, (NamedView, Defs, Metadata, ForeignObject, Group, MissingGlyph)
)
)
and (
el.get("d") is not None
or el.get("points") is not None
or el.get("x1") is not None
)
]
merged = [False for el in els]
# stys = [(el.cspecified_style) for el in els]
sfs = [dh.get_strokefill(els[ii]) for ii in range(len(els))]
# dh.debug(lightness_threshold)
for ii in reversed(range(len(els))): # reversed so that order is preserved
sf1 = sfs[ii]
# if (
# sf1.stroke is not None
# and sf1.stroke.efflightness >= lightness_threshold
# ):
if (
sf1.stroke is None or sf1.stroke.efflightness >= lightness_threshold
) and (sf1.fill is None or sf1.fill.efflightness >= lightness_threshold):
merges = [ii]
merged[ii] = True
for jj in range(ii):
if not (merged[jj]):
sf2 = sfs[jj]
samesw = (
sf1.strokewidth is None and sf2.strokewidth is None
) or (
sf1.strokewidth is not None
and sf2.strokewidth is not None
and abs(sf1.strokewidth - sf2.strokewidth) < 0.001
)
samestrk = (sf1.stroke is None and sf2.stroke is None) or (
sf1.stroke is not None
and sf2.stroke is not None
and sf1.stroke.red == sf2.stroke.red
and sf1.stroke.blue == sf2.stroke.blue
and sf1.stroke.green == sf2.stroke.green
and abs(sf1.stroke.alpha - sf2.stroke.alpha) < 0.001
)
# RGB are 0-255, alpha are 0-1
samefill = (sf1.fill is None and sf2.fill is None) or (
sf1.fill is not None
and sf2.fill is not None
and sf1.fill.red == sf2.fill.red
and sf1.fill.blue == sf2.fill.blue
and sf1.fill.green == sf2.fill.green
and abs(sf1.fill.alpha - sf2.fill.alpha) < 0.001
)
if (
samestrk
and samefill
and samesw
and sf1.strokedasharray == sf2.strokedasharray
and sf1.markerstart == sf2.markerstart
and sf1.markermid == sf2.markermid
and sf1.markerend == sf2.markerend
):
merges.append(jj)
merged[jj] = True
if len(merges) > 1:
ords = [elord[kk] for kk in merges]
ords.sort()
medord = ords[math.floor((len(ords) - 1) / 2)]
topord = ords[-1]
mergeii = [
kk for kk in range(len(merges)) if elord[merges[kk]] == topord
][
0
] # use the median
dh.combine_paths([els[kk] for kk in merges], mergeii)
# dh.flush_stylesheet_entries(self.svg) # since we removed clips
if __name__ == "__main__":
dh.Run_SI_Extension(CombineByColor(), "Combine by color")

View file

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<name>Favorite markers</name>
<id>burghoff.favoritemarkers</id>
<param name="tab" type="notebook">
<page name="markers" gui-text="Markers">
<label>Stores your favorite markers for convenient access.</label>
<param name="template" type="optiongroup" appearance="combo" gui-text="Template">
<option value="0">Arrow</option>
<option value="1">Triangle</option>
<option value="2">Distance</option></param>
<param name="smarker" type="bool" gui-text="Start marker?">false</param>
<param name="mmarker" type="bool" gui-text="Mid marker?">false</param>
<param name="emarker" type="bool" gui-text="End marker?">true</param>
<param name="size" type="float" precision="1" min="0" max="10000"
gui-text="Size (%)">100</param>
<spacer/>
<label>Scientific Inkscape v1.4.23</label>
<label appearance="url">https://github.com/burghoff/Scientific-Inkscape</label>
<label>David Burghoff, University of Texas at Austin</label>
</page>
<page name="addremove" gui-text="Add/remove templates">
<param name="addt" type="bool" gui-text="Add selected path markers as new template?">false</param>
<param name="template_name" type="string" gui-text="New template name"></param>
<param name="remt" type="bool" gui-text="Remove template?">false</param>
<param name="template_rem" type="optiongroup" appearance="combo" gui-text="Template to remove">
<option value="0">Arrow</option>
<option value="1">Triangle</option>
<option value="2">Distance</option></param>
</page>
</param>
<effect needs-live-preview="false">
<object-type>text</object-type>
<effects-menu>
<submenu name="Scientific"/>
</effects-menu>
</effect>
<script>
<command location="inx" interpreter="python">favorite_markers.py</command>
</script>
</inkscape-extension>

View file

@ -0,0 +1,491 @@
#!/usr/bin/env python
# coding=utf-8
#
# Copyright (C) 2021 David Burghoff, dburghoff@nd.edu
#
# 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.
# Note that this function modifies its own .inx file by editing the options in the "template"
# parameter and the "template_rem" parameter.
# dflt = {'Arrow': [[{'style': 'overflow:visible', 'id': 'Arrow2Lstart', 'refX': '0.0', 'refY': '0.0', 'orient': 'auto', '{http://www.inkscape.org/namespaces/inkscape}stockid': 'Arrow2Lstart', '{http://www.inkscape.org/namespaces/inkscape}isstock': 'true'}, [{'transform': 'matrix(1.1 0 0 1.1 1.1 0)', 'd': 'M 8.7185878,4.0337352 L -2.2072895,0.016013256 L 8.7185884,-4.0017078 C 6.9730900,-1.6296469 6.9831476,1.6157441 8.7185878,4.0337352 z ', 'style': 'stroke:context-stroke;fill-rule:evenodd;fill:context-stroke;stroke-width:0.62500000;stroke-linejoin:round', 'id': 'path1068'}]], [{'style': 'overflow:visible', 'id': 'Arrow2Lend', 'refX': '0.0', 'refY': '0.0', 'orient': 'auto', '{http://www.inkscape.org/namespaces/inkscape}stockid': 'Arrow2Lend', '{http://www.inkscape.org/namespaces/inkscape}isstock': 'true'}, [{'transform': 'matrix(-1.1 1.34707e-16 -1.34707e-16 -1.1 -1.1 1.34707e-16)', 'd': 'M 8.7185878,4.0337352 L -2.2072895,0.016013256 L 8.7185884,-4.0017078 C 6.9730900,-1.6296469 6.9831476,1.6157441 8.7185878,4.0337352 z ', 'style': 'stroke:context-stroke;fill-rule:evenodd;fill:context-stroke;stroke-width:0.62500000;stroke-linejoin:round', 'id': 'path1071'}]], [{'style': 'overflow:visible', 'id': 'marker1328', 'refX': '0.0', 'refY': '0.0', 'orient': 'auto', '{http://www.inkscape.org/namespaces/inkscape}stockid': 'Arrow2Lend', '{http://www.inkscape.org/namespaces/inkscape}isstock': 'true'}, [{'transform': 'matrix(-1.1 1.34707e-16 -1.34707e-16 -1.1 -1.1 1.34707e-16)', 'd': 'M 8.7185878,4.0337352 L -2.2072895,0.016013256 L 8.7185884,-4.0017078 C 6.9730900,-1.6296469 6.9831476,1.6157441 8.7185878,4.0337352 z ', 'style': 'stroke:context-stroke;fill-rule:evenodd;fill:context-stroke;stroke-width:0.62500000;stroke-linejoin:round', 'id': 'path1326'}]]], 'Triangle': [[{'style': 'overflow:visible', 'id': 'TriangleInL', 'refX': '0.0', 'refY': '0.0', 'orient': 'auto', '{http://www.inkscape.org/namespaces/inkscape}stockid': 'TriangleInL', '{http://www.inkscape.org/namespaces/inkscape}isstock': 'true'}, [{'transform': 'scale(-0.8, -0.8)', 'style': 'fill-rule:evenodd;fill:context-stroke;stroke:context-stroke;stroke-width:1.0pt', 'd': 'M 5.77,0.0 L -2.88,5.0 L -2.88,-5.0 L 5.77,0.0 z ', 'id': 'path1183'}]], [{'style': 'overflow:visible', 'id': 'marker1395', 'refX': '0.0', 'refY': '0.0', 'orient': 'auto', '{http://www.inkscape.org/namespaces/inkscape}stockid': 'TriangleOutL', '{http://www.inkscape.org/namespaces/inkscape}isstock': 'true'}, [{'transform': 'scale(0.8, 0.8)', 'style': 'fill-rule:evenodd;fill:context-stroke;stroke:context-stroke;stroke-width:1.0pt', 'd': 'M 5.77,0.0 L -2.88,5.0 L -2.88,-5.0 L 5.77,0.0 z ', 'id': 'path1393'}]], [{'style': 'overflow:visible', 'id': 'TriangleOutL', 'refX': '0.0', 'refY': '0.0', 'orient': 'auto', '{http://www.inkscape.org/namespaces/inkscape}stockid': 'TriangleOutL', '{http://www.inkscape.org/namespaces/inkscape}isstock': 'true'}, [{'transform': 'scale(0.8, 0.8)', 'style': 'fill-rule:evenodd;fill:context-stroke;stroke:context-stroke;stroke-width:1.0pt', 'd': 'M 5.77,0.0 L -2.88,5.0 L -2.88,-5.0 L 5.77,0.0 z ', 'id': 'path1192'}]]]}
dflt = {
"Arrow": [
[
{
"style": "overflow:visible",
"refX": "0.0",
"refY": "0.0",
"orient": "auto",
"{http://www.inkscape.org/namespaces/inkscape}stockid": "Arrow2Mstart",
"{http://www.inkscape.org/namespaces/inkscape}isstock": "true",
},
[
{
"transform": "scale(0.6, 0.6)",
"d": "M 8.7185878,4.0337352 L -2.2072895,0.016013256 L 8.7185884,-4.0017078 C 6.9730900,-1.6296469 6.9831476,1.6157441 8.7185878,4.0337352 z ",
"style": "stroke:context-stroke;fill-rule:evenodd;fill:context-stroke;stroke-width:0.62500000;stroke-linejoin:round",
"id": "path961",
}
],
],
[
{
"style": "overflow:visible",
"refX": "0.0",
"refY": "0.0",
"orient": "auto",
"{http://www.inkscape.org/namespaces/inkscape}stockid": "Arrow2Mend",
"{http://www.inkscape.org/namespaces/inkscape}isstock": "true",
},
[
{
"transform": "scale(-0.6, -0.6)",
"d": "M 8.7185878,4.0337352 L -2.2072895,0.016013256 L 8.7185884,-4.0017078 C 6.9730900,-1.6296469 6.9831476,1.6157441 8.7185878,4.0337352 z ",
"style": "stroke:context-stroke;fill-rule:evenodd;fill:context-stroke;stroke-width:0.62500000;stroke-linejoin:round",
"id": "path964",
}
],
],
[
{
"style": "overflow:visible",
"refX": "0.0",
"refY": "0.0",
"orient": "auto",
"{http://www.inkscape.org/namespaces/inkscape}stockid": "Arrow2Mend",
"{http://www.inkscape.org/namespaces/inkscape}isstock": "true",
},
[
{
"transform": "scale(-0.6, -0.6)",
"d": "M 8.7185878,4.0337352 L -2.2072895,0.016013256 L 8.7185884,-4.0017078 C 6.9730900,-1.6296469 6.9831476,1.6157441 8.7185878,4.0337352 z ",
"style": "stroke:context-stroke;fill-rule:evenodd;fill:context-stroke;stroke-width:0.62500000;stroke-linejoin:round",
"id": "path1354",
}
],
],
],
"Triangle": [
[
{
"style": "overflow:visible",
"refX": "0.0",
"refY": "0.0",
"orient": "auto",
"{http://www.inkscape.org/namespaces/inkscape}stockid": "TriangleInM",
"{http://www.inkscape.org/namespaces/inkscape}isstock": "true",
},
[
{
"transform": "scale(-0.4, -0.4)",
"style": "fill-rule:evenodd;fill:context-stroke;stroke:context-stroke;stroke-width:1.0pt",
"d": "M 5.77,0.0 L -2.88,5.0 L -2.88,-5.0 L 5.77,0.0 z ",
"id": "path1073",
}
],
],
[
{
"style": "overflow:visible",
"refX": "0.0",
"refY": "0.0",
"orient": "auto",
"{http://www.inkscape.org/namespaces/inkscape}stockid": "TriangleOutM",
"{http://www.inkscape.org/namespaces/inkscape}isstock": "true",
},
[
{
"transform": "scale(0.4, 0.4)",
"style": "fill-rule:evenodd;fill:context-stroke;stroke:context-stroke;stroke-width:1.0pt",
"d": "M 5.77,0.0 L -2.88,5.0 L -2.88,-5.0 L 5.77,0.0 z ",
"id": "path1082",
}
],
],
[
{
"style": "overflow:visible",
"refX": "0.0",
"refY": "0.0",
"orient": "auto",
"{http://www.inkscape.org/namespaces/inkscape}stockid": "TriangleOutM",
"{http://www.inkscape.org/namespaces/inkscape}isstock": "true",
},
[
{
"transform": "scale(0.4, 0.4)",
"style": "fill-rule:evenodd;fill:context-stroke;stroke:context-stroke;stroke-width:1.0pt",
"d": "M 5.77,0.0 L -2.88,5.0 L -2.88,-5.0 L 5.77,0.0 z ",
"id": "path1213",
}
],
],
],
"Distance": [
[
{
"{http://www.inkscape.org/namespaces/inkscape}stockid": "DistanceStart",
"orient": "auto",
"refY": "0.0",
"refX": "0.0",
"id": "DistanceStart",
"style": "overflow:visible",
"{http://www.inkscape.org/namespaces/inkscape}isstock": "true",
},
[
{
"id": "path2306",
"d": "M 0,0 L 2,0",
"style": "fill:none;stroke:context-fill;stroke-width:1.15;stroke-linecap:square",
},
{
"id": "path2302",
"d": "M 0,0 L 13,4 L 9,0 13,-4 L 0,0 z ",
"style": "fill:context-stroke;fill-rule:evenodd;stroke:none",
},
{
"id": "path2304",
"d": "M 0,-4 L 0,40",
"style": "fill:none;stroke:context-stroke;stroke-width:1;stroke-linecap:square",
},
],
],
[
{
"style": "overflow:visible",
"id": "StopL",
"refX": "0.0",
"refY": "0.0",
"orient": "auto",
"{http://www.inkscape.org/namespaces/inkscape}stockid": "StopL",
"{http://www.inkscape.org/namespaces/inkscape}isstock": "true",
},
[
{
"transform": "scale(0.8, 0.8)",
"style": "fill:none;fill-opacity:0.75000000;fill-rule:evenodd;stroke:context-stroke;stroke-width:1.0pt",
"d": "M 0.0,5.65 L 0.0,-5.65",
"id": "path2127",
}
],
],
[
{
"{http://www.inkscape.org/namespaces/inkscape}stockid": "DistanceEnd",
"orient": "auto",
"refY": "0.0",
"refX": "0.0",
"id": "DistanceEnd",
"style": "overflow:visible",
"{http://www.inkscape.org/namespaces/inkscape}isstock": "true",
},
[
{
"id": "path2316",
"d": "M 0,0 L -2,0",
"style": "fill:none;stroke:context-fill;stroke-width:1.15;stroke-linecap:square",
},
{
"id": "path2312",
"d": "M 0,0 L -13,4 L -9,0 -13,-4 L 0,0 z ",
"style": "fill:context-stroke;fill-rule:evenodd;stroke:none",
},
{
"id": "path2314",
"d": "M 0,-4 L 0,40",
"style": "fill:none;stroke:context-stroke;stroke-width:1;stroke-linecap:square",
},
],
],
],
}
import dhelpers as dh
import inkex
from inkex import (
TextElement,
FlowRoot,
FlowPara,
Tspan,
TextPath,
Rectangle,
addNS,
Transform,
PathElement,
Line,
Rectangle,
Path,
Vector2d,
Use,
NamedView,
Defs,
Metadata,
ForeignObject,
Group,
FontFace,
StyleElement,
StyleSheets,
SvgDocumentElement,
ShapeElement,
BaseElement,
FlowSpan,
Ellipse,
Circle,
)
import os, sys
def get_script_path():
return os.path.dirname(os.path.realpath(sys.argv[0]))
dispprofile = False
class FavoriteMarkers(inkex.EffectExtension):
# def document_path(self):
# return 'test'
def add_arguments(self, pars):
pars.add_argument("--tab", help="The selected UI-tab when OK was pressed")
pars.add_argument("--template", type=int, default=1, help="Template")
pars.add_argument(
"--smarker", type=inkex.Boolean, default=False, help="Start marker?"
)
pars.add_argument(
"--mmarker", type=inkex.Boolean, default=False, help="Mid marker?"
)
pars.add_argument(
"--emarker", type=inkex.Boolean, default=False, help="End marker?"
)
pars.add_argument("--size", type=float, default=100, help="Size (%)")
pars.add_argument(
"--addt", type=inkex.Boolean, default=True, help="Add template?"
)
pars.add_argument(
"--template_name", type=str, default="untitled", help="New template name"
)
pars.add_argument(
"--remt", type=inkex.Boolean, default=True, help="Remove template?"
)
pars.add_argument(
"--template_rem", type=int, default=1, help="Template to remove"
)
def get_marker_props(self, murl):
if murl is not None and murl != "" and murl != "none":
mkr = self.svg.getElementById(murl.strip("#url(").strip(")"))
mkratt = dict()
for att in mkr.attrib:
if att != "id":
mkratt[att] = mkr.get(att)
patts = []
if len(mkr.getchildren()) > 0:
if isinstance(mkr.getchildren()[0], (Group)):
pparent = mkr.getchildren()[0]
else:
pparent = mkr
for k in pparent.getchildren():
if isinstance(k, (PathElement)):
patt = dict()
for att in k.attrib:
patt[att] = k.get(att)
patts.append(patt)
return [mkratt, patts]
else:
return None
else:
return None
def set_marker_props(self, el, mkrname, mtype, mkrdat):
if mkrdat is not None:
newname = (mkrname + mtype).translate({ord(c): None for c in " \n\t\r"})
# strip white space
mysize = self.options.size / 100
existing = [
v for v in self.svg.defs.descendants2() if newname in v.get_id()
]
previousmkr = None
for eel in existing:
if len(eel.getchildren()) > 0 and isinstance(
eel.getchildren()[0], (Group)
):
trn = Transform(eel.getchildren()[0].get("transform"))
if abs(trn.a - mysize) < 0.01 and abs(trn.d - mysize) < 0.01:
previousmkr = eel
if previousmkr is None:
mkratt = mkrdat[0]
patt = mkrdat[1]
m = inkex.elements._groups.Marker()
for att in mkratt.keys():
if att != "id":
m.set(att, mkratt[att])
g = Group()
m.append(g)
g.set("transform", "scale(" + str(mysize) + ")")
for ii in range(len(patt)):
p = PathElement()
for att in patt[ii].keys():
if att != "id":
p.set(att, patt[ii][att])
g.append(p)
self.svg.defs.append(m)
m.set_random_id(prefix=newname)
else:
m = previousmkr
el.cstyle["marker-" + mtype] = "url(#" + m.get_id() + ")"
else:
el.cstyle["marker-" + mtype] = None
# dh.debug(mkrname+mtype)
# dh.debug(mkrdat)
def effect(self):
if dispprofile:
import cProfile, pstats, io
from pstats import SortKey
pr = cProfile.Profile()
pr.enable()
sel = [self.svg.selection[ii] for ii in range(len(self.svg.selection))]
# should work with both v1.0 and v1.1
sel = [v for el in sel for v in el.descendants2()]
import pickle, os
fmsettings = os.path.abspath(
os.path.join(get_script_path(), "favorite_markers.settings")
)
try:
f = open(fmsettings, "rb")
except:
f = open(fmsettings, "wb")
pickle.dump(dflt, f)
f.close()
f = open(fmsettings, "rb")
s = pickle.load(f)
f.close()
# dh.debug(s)
if self.options.tab == "addremove":
if self.options.addt:
sel = [
x
for x in sel
if isinstance(
x,
(
inkex.PathElement,
inkex.Line,
inkex.Polyline,
inkex.Rectangle,
inkex.Circle,
inkex.Ellipse,
),
)
]
sty = sel[0].cspecified_style
ms = self.get_marker_props(sty.get("marker-start"))
mm = self.get_marker_props(sty.get("marker-mid"))
me = self.get_marker_props(sty.get("marker-end"))
s[self.options.template_name] = [ms, mm, me]
if self.options.remt:
templates = list(s.keys())
if self.options.template_rem < len(templates):
del s[templates[self.options.template_rem]]
f = open(fmsettings, "wb")
pickle.dump(s, f)
f.close()
fminx = os.path.abspath(
os.path.join(get_script_path(), "favorite_markers.inx")
)
f = open(fminx)
inxd = f.read()
f.close()
opts = ""
ts = list(s.keys())
for ii in range(len(ts)):
opts += '\n<option value="' + str(ii) + '">' + ts[ii] + "</option>"
ss1 = '<param name="template" type="optiongroup" appearance="combo" gui-text="Template">'
ss1loc = inxd.find(ss1)
ss1srt = ss1loc + len(ss1)
ss1end = inxd[ss1loc:].find("</param>") + ss1loc
ss2 = '<param name="template_rem" type="optiongroup" appearance="combo" gui-text="Template to remove">'
ss2loc = inxd.find(ss2)
ss2srt = ss2loc + len(ss2)
ss2end = inxd[ss2loc:].find("</param>") + ss2loc
newinx = inxd[0:ss1srt] + opts + inxd[ss1end:ss2srt] + opts + inxd[ss2end:]
f = open(fminx, "w")
inxd = f.write(newinx)
f.close()
dh.idebug(
"Templates successfully updated! Update will take effect when Inkscape is restarted."
)
else:
for el in sel:
if isinstance(
el,
(
inkex.PathElement,
inkex.Line,
inkex.Polyline,
inkex.Rectangle,
inkex.Circle,
inkex.Ellipse,
),
):
ts = list(s.keys())
tname = ts[self.options.template]
tval = s[tname]
if self.options.smarker:
self.set_marker_props(el, "FM" + tname, "start", tval[0])
else:
self.set_marker_props(el, "FM" + tname, "start", None)
if self.options.mmarker:
self.set_marker_props(el, "FM" + tname, "mid", tval[1])
else:
self.set_marker_props(el, "FM" + tname, "mid", None)
if self.options.emarker:
self.set_marker_props(el, "FM" + tname, "end", tval[2])
else:
self.set_marker_props(el, "FM" + tname, "end", None)
# pickle.dump(s,open(os.path.join(get_script_path(),'ae_settings.p'),'wb'));
# for el in sela:
# if
# dh.debug(el.get_id())
# dh.debug(bb[el.get_id()]);
if dispprofile:
pr.disable()
s = io.StringIO()
sortby = SortKey.CUMULATIVE
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
dh.debug(s.getvalue())
if __name__ == "__main__":
dh.Run_SI_Extension(FavoriteMarkers(), "Favorite markers")

View file

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<name>Flattener</name>
<id>burghoff.flattenplots1</id>
<param name="tab" type="notebook">
<page name="Options" gui-text="Main options">
<label appearance="header">Recommended options</label>
<param name="deepungroup" type="bool" gui-text="Deep ungroup?"
gui-description="Remove all groupings, leaving individual objects on canvas"
>true</param>
<param name="fixtext" type="bool" gui-text="Apply text fixes?">true</param>
<param name="revertpaths" type="bool" gui-text="Revert simple paths to strokes?"
gui-description="Reverts certain strokes that have been converted to paths back to strokes"
>true</param>
<param name="removeduppaths" type="bool" gui-text="Remove overlapping duplicates?"
gui-description="When two identical elements overlap, removes the one on the bottom"
>true</param>
<label appearance="header">Other options</label>
<param name="removerectw" type="bool" gui-text="Remove white background rectangles?"
gui-description="Removes white-filled rectangles that are behind other objects"
>true</param>
<label appearance="header">Note</label>
<label>For anyone using Inkscape to prepare figures, it is strongly recommended that you change the transformation preferences from Optimized to Preserved in Edit > Preferences > Behavior > Transforms. The Optimized setting can distort certain paths.</label>
<spacer/>
<label>Scientific Inkscape v1.4.23</label>
<label appearance="url">https://github.com/burghoff/Scientific-Inkscape</label>
<label>David Burghoff, University of Texas at Austin</label>
</page>
<page name="Options2" gui-text="Text fix options">
<label appearance="header">Recommended options</label>
<param name="splitdistant" type="bool" gui-text="Split distant text and lines">true</param>
<param name="mergenearby" type="bool" gui-text="Merge nearby text">true</param>
<param name="removemanualkerning" type="bool" gui-text="Remove manual kerning">true</param>
<param name="mergesubsuper" type="bool" gui-text="Merge superscripts and subscripts">true</param>
<param name="reversions" type="bool" gui-text="Revert known paths to characters">true</param>
<param name="removetextclips" type="bool" gui-text="Remove text clips and masks">true</param>
<param name="justification" type="optiongroup" appearance="combo"
gui-text="Final text justification">
<option value="1">Centered</option>
<option value="2">Left</option>
<option value="3">Right</option>
<option value="4">Unchanged</option>
</param>
<label appearance="header">Other options</label>
<param name="setreplacement" type="bool" gui-text="Replace missing fonts">false</param>
<param name="replacement" type="string" gui-text="Missing font replacement">Arial</param>
<spacer/>
<label>Scientific Inkscape v1.4.23</label>
<label appearance="url">https://github.com/burghoff/Scientific-Inkscape</label>
<label>David Burghoff, University of Texas at Austin</label>
</page>
<page name="Exclusions" gui-text="Exclusions">
<label appearance="header">Exclusions</label>
<label>To mark objects to be excluded from flattening, select them and run the extension with this tab selected.</label>
<param name="markexc" type="optiongroup" appearance="combo"
gui-text="Selected objects should be">
<option value="1">Not flattened</option>
<option value="2">Flattened</option>
</param>
<spacer/>
<label>Scientific Inkscape v1.4.23</label>
<label appearance="url">https://github.com/burghoff/Scientific-Inkscape</label>
<label>David Burghoff, University of Texas at Austin</label>
</page>
</param>
<effect needs-live-preview="false">
<object-type>text</object-type>
<effects-menu>
<submenu name="Scientific"/>
</effects-menu>
</effect>
<script>
<command location="inx" interpreter="python">flatten_plots.py</command>
</script>
</inkscape-extension>

View file

@ -0,0 +1,538 @@
#!/usr/bin/env python
# coding=utf-8
#
# Copyright (c) 2023 David Burghoff <burghoff@utexas.edu>
#
# 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.
#
import dhelpers as dh
import inkex
from inkex import (
TextElement,
FlowRoot,
FlowPara,
FlowRegion,
FlowSpan,
Tspan,
TextPath,
Rectangle,
PathElement,
Line,
StyleElement,
NamedView,
Defs,
Metadata,
ForeignObject,
Group,
)
from inkex.text.utils import isrectangle
import lxml
from remove_kerning import remove_kerning
class FlattenPlots(inkex.EffectExtension):
def add_arguments(self, pars):
pars.add_argument("--tab", help="The selected UI-tab when OK was pressed")
pars.add_argument(
"--deepungroup", type=inkex.Boolean, default=True, help="Deep ungroup"
)
pars.add_argument(
"--fixtext", type=inkex.Boolean, default=True, help="Text fixes"
)
pars.add_argument(
"--removerectw",
type=inkex.Boolean,
default=True,
help="Remove white rectangles",
)
pars.add_argument(
"--splitdistant",
type=inkex.Boolean,
default=True,
help="Split distant text",
)
pars.add_argument(
"--mergenearby", type=inkex.Boolean, default=True, help="Merge nearby text"
)
pars.add_argument(
"--removemanualkerning",
type=inkex.Boolean,
default=True,
help="Fix text shattering",
)
pars.add_argument(
"--mergesubsuper",
type=inkex.Boolean,
default=True,
help="Import superscripts and subscripts",
)
pars.add_argument(
"--setreplacement",
type=inkex.Boolean,
default=False,
help="Replace missing fonts",
)
pars.add_argument(
"--reversions",
type=inkex.Boolean,
default=True,
help="Revert known paths to text",
)
pars.add_argument(
"--revertpaths",
type=inkex.Boolean,
default=True,
help="Revert certain paths to strokes?",
)
pars.add_argument(
"--removeduppaths",
type=inkex.Boolean,
default=True,
help="Delete overlapping duplicate paths?",
)
pars.add_argument(
"--removetextclips",
type=inkex.Boolean,
default=True,
help="Remove clips and masks from text?",
)
pars.add_argument(
"--replacement", type=str, default="Arial", help="Missing font replacement"
)
pars.add_argument(
"--justification", type=int, default=1, help="Text justification"
)
pars.add_argument("--markexc", type=int, default=1, help="Exclude objects")
pars.add_argument(
"--testmode", type=inkex.Boolean, default=False, help="Test mode"
)
pars.add_argument("--v", type=str, default="1.2", help="Version for debugging")
pars.add_argument(
"--debugparser",
type=inkex.Boolean,
default=False,
help="Use parser debugger?",
)
def duplicate_layer1(self):
# For testing, duplicate selection and flatten its elements
sel = [self.svg.selection[ii] for ii in range(len(self.svg.selection))]
# should work with both v1.0 and v1.1
for el in sel:
d = el.duplicate()
el.getparent().insert(list(el.getparent()).index(el), d)
if d.get("inkscape:label") is not None:
el.set("inkscape:label", el.get("inkscape:label") + " flat")
d.set("inkscape:label", d.get("inkscape:label") + " original")
d.set("sodipodi:insensitive", "true")
# lock original
d.set("opacity", 0.3)
sel = [list(el) for el in sel]
import itertools
sel = list(itertools.chain.from_iterable(sel))
return sel
def effect(self):
if self.options.testmode:
if not hasattr(self.options, "enabled_profile"):
self.options.enabled_profile = True
self.options.lyr1 = self.duplicate_layer1()
dh.ctic()
self.effect()
dh.ctoc()
return
else:
sel = self.options.lyr1
self.options.deepungroup = True
self.options.fixtext = True
self.options.removerectw = True
self.options.revertpaths = True
self.options.splitdistant = True
self.options.mergenearby = True
self.options.removemanualkerning = True
self.options.mergesubsuper = True
self.options.setreplacement = True
self.options.reversions = True
self.options.removetextclips = True
self.options.replacement = "sans-serif"
self.options.justification = 1
else:
sel = [self.svg.selection[ii] for ii in range(len(self.svg.selection))]
splitdistant = self.options.splitdistant and self.options.fixtext
removemanualkerning = self.options.removemanualkerning and self.options.fixtext
mergesubsuper = self.options.mergesubsuper and self.options.fixtext
mergenearby = self.options.mergenearby and self.options.fixtext
setreplacement = self.options.setreplacement and self.options.fixtext
reversions = self.options.reversions and self.options.fixtext
removetextclips = self.options.removetextclips and self.options.fixtext
sel = [el for el in self.svg.descendants2() if el in sel] # doc order
if self.options.tab == "Exclusions":
self.options.markexc = {1: True, 2: False}[self.options.markexc]
for el in sel:
if self.options.markexc:
el.set("inkscape-scientific-flattenexclude", self.options.markexc)
else:
el.set("inkscape-scientific-flattenexclude", None)
return
for el in sel:
if el.get("inkscape-scientific-flattenexclude"):
sel.remove(el)
seld = [v for el in sel for v in el.descendants2()]
for el in seld:
if el.get("inkscape-scientific-flattenexclude"):
seld.remove(el)
# Move selected defs/clips/mask into global defs
defstag = inkex.Defs.ctag
clipmask = {inkex.addNS("mask", "svg"), inkex.ClipPath.ctag}
if self.options.deepungroup:
seldefs = [el for el in seld if el.tag == defstag]
for el in seldefs:
self.svg.cdefs.append(el)
for d in el.descendants2():
if d in seld:
seld.remove(d) # no longer selected
selcm = [el for el in seld if el.tag in clipmask]
for el in selcm:
self.svg.cdefs.append(el)
for d in el.descendants2():
if d in seld:
seld.remove(d) # no longer selected
gtag = inkex.Group.ctag
gigtags = dh.tags((NamedView, Defs, Metadata, ForeignObject) + (Group,))
gs = [el for el in seld if el.tag == gtag]
ngs = [el for el in seld if el.tag not in gigtags]
if len(gs) == 0 and len(ngs) == 0:
inkex.utils.errormsg("No objects selected!")
return
if self.options.deepungroup:
# Unlink all clones
nels = []
oels = []
for el in seld:
if isinstance(el, inkex.Use):
useel = el.get_link("xlink:href")
if useel is not None and not (isinstance(useel, (inkex.Symbol))):
ul = dh.unlink2(el)
nels.append(ul)
oels.append(el)
for nel in nels:
seld += nel.descendants2()
for oel in oels:
seld.remove(oel)
gs = [el for el in seld if el.tag == gtag]
ngs = [el for el in seld if el.tag not in gigtags]
commenttag = lxml.etree.Comment
commentdefs = {commenttag, defstag}
sorted_gs = sorted(gs, key=lambda group: len(list(group)))
# ascending order of size to reduce number of calls
for g in sorted_gs:
ks = g.getchildren()
if any([k.tag == commenttag for k in ks]) and all(
[
k.tag in commentdefs or dh.EBget(k, "unlinked_clone") == "True"
for k in ks
]
):
# Leave Matplotlib text glyphs grouped together
cmnt = ";".join(
[
str(k).strip("<!-- ").strip(" -->")
for k in ks
if k.tag == commenttag
]
)
g.set("mpl_comment", cmnt)
[g.remove(k) for k in ks if isinstance(k, lxml.etree._Comment)]
# remove comment, but leave grouped
elif dh.EBget(g, "mpl_comment") is not None:
pass
else:
dh.ungroup(g, removetextclips)
# dh.flush_stylesheet_entries(self.svg)
prltag = dh.tags((PathElement, Rectangle, Line))
if self.options.removerectw or reversions or self.options.revertpaths:
from inkex.text.utils import default_style_atts as dsa
fltag = dh.tags((FlowPara, FlowRegion, FlowRoot))
nones = {None, "none"}
wrects = []
minusp = inkex.Path(
"M 106,355 H 732 V 272 H 106 Z"
) # Matplotlib minus sign
RECT_THRESHOLD = 2.49 # threshold ratio for rectangle reversion
for ii, el in enumerate(ngs):
if el.tag in prltag:
myp = el.getparent()
if (
myp is not None
and not (myp.tag in fltag)
and isrectangle(el, includingtransform=False)
):
sty = el.cspecified_style
strk = sty.get("stroke", dsa.get("stroke"))
fill = sty.get("fill", dsa.get("fill"))
if strk in nones and fill not in nones:
sf = dh.get_strokefill(el)
if sf.fill is not None and tuple(sf.fill) == (
255,
255,
255,
1,
):
wrects.append(el)
if reversions:
dv = el.get("d")
if (
dv is not None
and inkex.Path(dv)[0:3] == minusp[0:3]
):
t0 = el.ccomposed_transform
if t0.a * t0.d - t0.b * t0.c < 0:
bb = dh.bounding_box2(
el, includestroke=False, dotransform=False
)
trl = inkex.Transform(
"translate({0},{1})".format(bb.xc, bb.yc)
)
scl = inkex.Transform("scale(1,-1)")
t0 = t0 @ trl @ scl @ (-trl)
nt = inkex.TextElement()
nt.set("id", el.get_id())
myi = list(myp).index(el)
el.delete()
myp.insert(myi, nt)
nt.text = chr(0x2212) # minus sign
nt.ctransform = (-myp.ccomposed_transform) @ t0
nt.set("x", str(19.3964))
nt.set("y", str(626.924))
nt.cstyle = "font-size:999.997; font-family:sans-serif; fill:{0};".format(
sf.fill
)
ngs.append(nt)
ngs.remove(el)
if self.options.revertpaths:
bb = dh.bounding_box2(
el, includestroke=False, dotransform=False, includeclipmask=False
)
if not bb.isnull:
if bb.w < bb.h / RECT_THRESHOLD and not sf.fill_isurl:
el.object_to_path()
npv = "m {0},{1} v {2}".format(bb.xc, bb.y1, bb.h)
el.set("d", npv)
el.cstyle["stroke"] = sf.fill.to_rgb()
if sf.fill.alpha != 1.0:
el.cstyle["stroke-opacity"] = sf.fill.alpha
el.cstyle["opacity"] = 1
el.cstyle["fill"] = "none"
el.cstyle["stroke-width"] = str(bb.w)
el.cstyle["stroke-linecap"] = "butt"
elif bb.h < bb.w / RECT_THRESHOLD and not sf.fill_isurl:
el.object_to_path()
npv = "m {0},{1} h {2}".format(bb.x1, bb.yc, bb.w)
el.set("d", npv)
el.cstyle["stroke"] = sf.fill.to_rgb()
if sf.fill.alpha != 1.0:
el.cstyle["stroke-opacity"] = sf.fill.alpha
el.cstyle["opacity"] = 1
el.cstyle["fill"] = "none"
el.cstyle["stroke-width"] = str(bb.h)
el.cstyle["stroke-linecap"] = "butt"
TE_TAG = TextElement.ctag;
if self.options.fixtext:
if setreplacement:
repl = self.options.replacement
ttags = dh.tags((TextElement, Tspan))
for el in ngs:
if el.tag in ttags and el.getparent() is not None:
# textelements not deleted
ff = el.cspecified_style.get("font-family")
el.cstyle["-inkscape-font-specification"] = None
if ff == None or ff == "none" or ff == "":
el.cstyle["font-family"] = repl
elif ff == repl:
pass
else:
ff = [
x.strip("'").strip('"').strip() for x in ff.split(",")
]
if not (ff[-1].lower() == repl.lower()):
ff.append(repl)
el.cstyle["font-family"] = ",".join(ff)
if removemanualkerning or mergesubsuper or splitdistant or mergenearby:
jdict = {1: "middle", 2: "start", 3: "end", 4: None}
justification = jdict[self.options.justification]
ngs = remove_kerning(
ngs,
removemanualkerning,
mergesubsuper,
splitdistant,
mergenearby,
justification,
self.options.debugparser,
)
if removetextclips:
for el in ngs:
if el.tag in dh.ttags:
el.set("clip-path", None)
el.set("mask", None)
if self.options.removerectw or self.options.removeduppaths:
ngset = set(ngs)
ngs2 = [
el for el in self.svg.descendants2() if el in ngset and dh.isdrawn(el)
]
bbs = dh.BB2(self.svg, ngs2, roughpath=True, parsed=True)
if self.options.removeduppaths:
# Prune identical overlapping paths
bbsp = {el:bbs[el.get_id()] for el in ngs2 if el.get_id() in bbs}
txts = [el for el in self.svg.descendants2() if el.tag==TE_TAG and 'shape-inside' in el.cspecified_style]
txt_inside = [el.cspecified_style.get_link("shape-inside",el.croot) for el in txts]
bbsp = {el:v for el,v in bbsp.items() if el.tag in prltag and el not in txt_inside}
els = list(bbsp.keys())
sfs = [None]*len(els)
import numpy as np
if len(els)>0:
bbox_values = np.array(list(bbsp.values()))
left = bbox_values[:, 0]
top = bbox_values[:, 1]
width = bbox_values[:, 2]
height = bbox_values[:, 3]
right = left + width
bottom = top + height
size = np.maximum(width, height)
is_empty = (width == 0) | (height == 0)
left_diff = np.abs(left[:, np.newaxis] - left[np.newaxis, :])
top_diff = np.abs(top[:, np.newaxis] - top[np.newaxis, :])
right_diff = np.abs(right[:, np.newaxis] - right[np.newaxis, :])
bottom_diff = np.abs(bottom[:, np.newaxis] - bottom[np.newaxis, :])
size_i = size[:, np.newaxis]
size_j = size[np.newaxis, :]
size_max = np.maximum(size_i, size_j)
tol = 1e-6 * size_max
is_empty_pair = is_empty[:, np.newaxis] | is_empty[np.newaxis, :]
equal = (~is_empty_pair) & \
(left_diff <= tol) & \
(top_diff <= tol) & \
(right_diff <= tol) & \
(bottom_diff <= tol)
else:
equal = np.zeros((0, 0), dtype=bool)
for jj in reversed(range(len(els))):
for ii in range(jj):
if equal[ii,jj]:
for kk in [ii,jj]:
if sfs[kk] is None:
sfs[kk] = dh.get_strokefill(els[kk])
mysf = sfs[jj]
othsf = sfs[ii]
if mysf.stroke is None and mysf.fill is None:
continue
if mysf.stroke is not None:
if mysf.stroke.alpha != 1.0 or othsf.stroke is None:
continue
if not mysf.stroke == othsf.stroke:
continue
if mysf.fill is not None:
if mysf.fill.alpha != 1.0 or othsf.fill is None:
continue
if not mysf.fill == othsf.fill:
continue
if not els[jj].cspecified_style == els[ii].cspecified_style:
continue
mypth = els[jj].cpath.transform(els[jj].ccomposed_transform).to_absolute();
othpth= els[ii].cpath.transform(els[ii].ccomposed_transform).to_absolute();
if mypth!=othpth and mypth!=othpth.reverse():
continue
# dh.idebug(els[ii].get_id())
els[ii].delete(deleteup=True)
equal[ii,:] = False
ngs2.remove(els[ii])
if self.options.removerectw:
ngs3 = [el for el in ngs2 if el.get_id() in bbs]
bbs3 = [dh.bbox(bbs.get(el.get_id())) for el in ngs3]
wriis = [ii for ii, el in enumerate(ngs3) if el in wrects]
wrbbs = [bbs3[ii] for ii in wriis]
intrscts = dh.bb_intersects(bbs3, wrbbs)
for jj, ii in enumerate(wriis):
if not any(intrscts[:ii, jj]):
ngs3[ii].delete(deleteup=True)
intrscts[ii, :] = False
ngs2.remove(ngs3[ii])
# Remove any unused clips we made, unnecessary white space in document
ds = self.svg.iddict.descendants
clips = [dh.EBget(el, "clip-path") for el in ds]
masks = [dh.EBget(el, "mask") for el in ds]
clips = [url[5:-1] for url in clips if url is not None]
masks = [url[5:-1] for url in masks if url is not None]
ctag = inkex.ClipPath.ctag
if hasattr(self.svg, "newclips"):
for el in self.svg.newclips:
if el.tag == ctag and not (el.get_id() in clips):
el.delete(deleteup=True)
elif dh.isMask(el) and not (el.get_id() in masks):
el.delete(deleteup=True)
ttags = dh.tags((Tspan, TextPath, FlowPara, FlowRegion, FlowSpan))
ttags2 = dh.tags(
(
StyleElement,
TextElement,
Tspan,
TextPath,
inkex.FlowRoot,
inkex.FlowPara,
inkex.FlowRegion,
inkex.FlowSpan,
)
)
for el in reversed(ds):
if not (el.tag in ttags):
if el.tail is not None:
el.tail = None
if not (el.tag in ttags2):
if el.text is not None:
el.text = None
if __name__ == "__main__":
dh.Run_SI_Extension(FlattenPlots(), "Flattener")

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<name>Gallery viewer</name>
<id>burghoff.gallery_viewer</id>
<param name="tab" type="notebook">
<page name="scaling" gui-text="Options">
<label>The Gallery Viewer lets you view and edit the SVG contents of a Powerpoint file, Word file, or directory:</label>
<label>- Each page is shown independently.</label>
<label>- If the file is an export made by the Autoexporter, a link to the original file will be available provided the file still exists.</label>
<label>- The viewer runs on a local server.</label>
<param name="portnum" type="int" min="0" max="65535" gui-text="Port number"
gui-description="Port for the Gallery Viewer server. &#13;If the default does not work, try another.">5001</param>
<spacer/>
<label>Scientific Inkscape v1.4.23</label>
<label appearance="url">https://github.com/burghoff/Scientific-Inkscape</label>
<label>David Burghoff, University of Texas at Austin</label></page>
</param>
<effect needs-live-preview="false">
<object-type>text</object-type>
<effects-menu>
<submenu name="Scientific"/>
</effects-menu>
</effect>
<script>
<command location="inx" interpreter="python">gallery_viewer.py</command>
</script>
</inkscape-extension>

View file

@ -0,0 +1,132 @@
#!/usr/bin/env python
# coding=utf-8
#
# Copyright (c) 2023 David Burghoff <burghoff@utexas.edu>
#
# 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.
DEBUGGING = False
dispprofile = False
import dhelpers as dh
import inkex
import os, sys, copy, subprocess, platform
# Convenience functions
def joinmod(dirc, f):
return os.path.join(os.path.abspath(dirc), f)
# Runs a Python script using a Python binary in a working directory
# It detaches from Inkscape, allowing it to continue running after the extension has finished
def run_python(python_bin, python_script, python_wd, interminal=False):
if platform.system() == "Windows":
DEVNULL = "nul"
else:
DEVNULL = "/dev/null"
# DEVNULL = dh.si_tmp(filename="si_gv_output.txt")
# dh.idebug(DEVNULL)
with open(DEVNULL, "w") as devnull:
subprocess.Popen([python_bin, python_script], stdout=devnull, stderr=devnull)
class GalleryViewer(inkex.EffectExtension):
def add_arguments(self, pars):
pars.add_argument("--tab", help="The selected UI-tab when OK was pressed")
pars.add_argument("--portnum", help="Port number for server")
def effect(self):
if dispprofile:
import cProfile, pstats, io
from pstats import SortKey
pr = cProfile.Profile()
pr.enable()
# Make an options copy we can pass to the external program
optcopy = copy.copy(self.options)
delattr(optcopy, "output")
delattr(optcopy, "input_file")
bfn = inkex.inkscape_system_info.binary_location
bloc, bnm = os.path.split(bfn)
pyloc, pybin = os.path.split(sys.executable)
aepy = os.path.join(dh.si_dir, "gallery_viewer_script.py")
# Pass settings using a config file. Include the current path so Inkex can be called if needed.
import pickle
optcopy.inkscape_bfn = bfn
optcopy.syspath = sys.path
optcopy.inshell = False
optcopy.logfile = dh.shared_temp(filename="si_gv_output.txt")
import tempfile
settings = os.path.join(
os.path.abspath(tempfile.gettempdir()), "si_gv_settings.p"
)
with open(settings, "wb") as f:
pickle.dump(optcopy, f)
import warnings
warnings.simplefilter("ignore", ResourceWarning) # prevent process open warning
run_python(pybin, aepy, pyloc, optcopy.inshell)
# Make a batch file that can run the Gallery Viewer directly on Windows
# Hardcodes the pickled settings
if platform.system() == "Windows":
python_cwd = os.getcwd()
pickled_file_path = settings
with open(pickled_file_path, "rb") as f:
pickled_data = f.read()
import base64
pickled_data_base64 = base64.b64encode(pickled_data).decode('utf-8')
current_script_dir = os.path.dirname(os.path.abspath(__file__))
batch_file_path = os.path.join(current_script_dir, "Gallery Viewer.bat")
batch_content = '''@echo off
cd "{python_cwd}"
SET PYBIN="{pybin}"
SET AEPY="{aepy}"
SET PICKLED_FILE="{pickled_file}"
REM Use PowerShell to decode the base64 string and write the binary pickled data
powershell -Command "[System.IO.File]::WriteAllBytes('%PICKLED_FILE%', [Convert]::FromBase64String('{pickled_data_base64}'))"
REM Start the Python script in a new process without opening a new window
start "" %PYBIN% %AEPY%
'''.format(
python_cwd=python_cwd, # Add the current working directory
pybin=sys.executable,
aepy=aepy,
pickled_file=pickled_file_path.replace('\\', '\\\\'),
pickled_data_base64=pickled_data_base64
)
with open(batch_file_path, "w") as batch_file:
batch_file.write(batch_content)
if dispprofile:
pr.disable()
s = io.StringIO()
sortby = SortKey.CUMULATIVE
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
dh.debug(s.getvalue())
if __name__ == "__main__":
dh.Run_SI_Extension(GalleryViewer(), "Gallery Viewer")

View file

@ -0,0 +1,382 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="google" content="notranslate">
<title>Gallery Viewer</title>
<style>
/* Your CSS styles */
div.gallery {
margin: 5px;
border: 1px solid #ccc;
float: none;
width: {{ image_width }}px;
display: inline-block;
vertical-align: top;
}
div.gallery:hover {
border: 1px solid #777;
}
div.gallery img {
object-fit: contain;
width: {{ image_width }}px;
height: {{ image_height }}px;
}
div.desc {
padding: 15px;
text-align: center;
word-wrap: break-word;
}
body {
font-family: Roboto, Arial, sans-serif;
font-size: 14px;
margin: 10; /* Remove default margins */
padding: 0; /* Remove default padding */
}
h2 {
margin: 0; /* Remove all margins from the h2 element */
padding: 0; /* Remove any padding */
}
.serverdown {
color: #e41a1cff;
margin: 0; /* Remove all margins from the serverdown div */
padding: 0; /* Remove any padding */
}
a.show-file svg {
vertical-align: middle;
/* Add any additional styling here */
}
@supports not (-ms-ime-align: auto) {
details summary {
cursor: pointer;
}
details summary > * {
display: inline;
}
}
</style>
<script>
const port = {{ port | tojson }};
var mylastupdate = 0; // Initialize the last update time
var showRasterGraphics = false; // Default to showing vector images
function toggleRasterGraphics() {
showRasterGraphics = document.getElementById('show-raster-checkbox').checked;
fetchGalleryData(true); // Force re-render
}
</script>
</head>
<body>
<h2>Gallery Viewer</h2>
<div class="serverdown"></div>
<div class="filter-container">
<input type="checkbox" id="show-raster-checkbox" onclick="toggleRasterGraphics()" title="When checked, non-vector graphics will also be shown in the gallery">
<label for="show-raster-checkbox" title="When checked, non-vector graphics will also be shown in the gallery">Show raster graphics in gallery</label>
</div>
<div id="gallery-container">
<!-- The gallery content will be dynamically inserted here -->
</div>
<!-- JavaScript code -->
<script>
// Store the existing groups and their data
let existingGroups = {};
let existingGroupData = {};
let existingGroupNeedsRefresh = {}; // New object to track groups that need refresh
// Function to render or update a group
function renderGroup(group) {
const header = group.header;
let details = existingGroups[header];
// Serialize the group's data for comparison
const groupDataString = JSON.stringify(group);
const existingGroupDataString = existingGroupData[header] ? JSON.stringify(existingGroupData[header]) : null;
// Check if the group needs to be refreshed
const needsRefresh = existingGroupNeedsRefresh[header] || false;
// Flag to indicate if data has changed
let dataChanged = false;
if (!details) {
// New group, create it
details = document.createElement('details');
// Set the initial open state
details.open = true;
const summary = document.createElement('summary');
const title = document.createElement('h2');
title.textContent = header;
title.style.margin = '0'; // Remove margin from group headers
summary.appendChild(title);
details.appendChild(summary);
// Add processing text element
const processingText = document.createElement('div');
processingText.className = 'processing-text';
details.appendChild(processingText);
const divContainer = document.createElement('div');
divContainer.className = 'gallery-container';
details.appendChild(divContainer);
// Add the new details to the gallery container
document.getElementById('gallery-container').appendChild(details);
// Store in existingGroups and existingGroupData
existingGroups[header] = details;
existingGroupData[header] = group;
// Since this is a new group, data has "changed"
dataChanged = true;
} else {
// Group exists, check if data has changed or needs refresh
if (existingGroupDataString !== groupDataString || needsRefresh) {
dataChanged = true;
existingGroupData[header] = group;
// Preserve the open/closed state
const isOpen = details.open;
// Clear existing content
const divContainer = details.querySelector('.gallery-container');
divContainer.innerHTML = '';
// Restore the state
details.open = isOpen;
} else {
// Data hasn't changed and no refresh needed
dataChanged = false;
}
}
// Update the processing text
const processingText = details.querySelector('.processing-text');
if (group.processing) {
processingText.textContent = 'Processing';
processingText.style.display = 'block';
processingText.style.marginLeft = '15px'; // Optional indentation
} else {
processingText.textContent = '';
processingText.style.display = 'none';
}
if (dataChanged) {
// After re-rendering, reset the needsRefresh flag
existingGroupNeedsRefresh[header] = false;
// Render the files inside the group
const divContainer = details.querySelector('.gallery-container');
group.files.forEach(file => {
const fileExtension = file.file_uri.toLowerCase().split('.').pop();
const isRaster = ['png', 'jpg', 'jpeg', 'gif'].includes(fileExtension);
if (!showRasterGraphics && isRaster) return;
const galleryDiv = document.createElement('div');
galleryDiv.className = 'gallery';
const link = document.createElement('a');
link.href = file.thumbnail_url;
link.target = '_blank';
const img = document.createElement('img');
img.src = file.thumbnail_url;
link.appendChild(img);
// Add error event listener to the image
img.addEventListener('error', () => {
console.log(`Image failed to load in group "${header}". Marking group for refresh.`);
existingGroupNeedsRefresh[header] = true;
});
const descDiv = document.createElement('div');
descDiv.className = 'desc';
descDiv.innerHTML = `
<div>${file.label}</div>
<div>
<a href="http://localhost:${port}/process?param=${encodeURIComponent(file.file_uri)}" class="open">${file.currenttype}</a>
<a href="http://localhost:${port}/show_file?param=${encodeURIComponent(file.file_uri)}" class="show-file" style="margin-left:5px;">
<!-- Folder SVG Icon -->
<svg width="13.938748" height="11.034863" viewBox="0 0 20.908124 16.552295" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path
id="path5"
style="font-variation-settings:normal;fill:none;fill-opacity:1;stroke:#000000;stroke-width:2.11176515;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;stop-color:#000000"
transform="matrix(0.3054317,0,0,0.3054317,-91.790233,-99.984673)"
d="m 311.31639,336.75961 c 0.96177,-2.24271 1.29727,-4.79155 2.33598,-5.87152 1.03871,-1.07997 4.14072,-0.95467 4.14072,-0.95467 l 9.7597,0.008 c 0,0 4.89538,-0.36509 6.05009,0.94701 1.15471,1.31211 1.64149,6.06092 1.64149,6.06092 m 30.25546,0.82173 c 1.14479,1.14479 0.80357,4.19344 0.80357,4.19344 v 37.09523 h -63.09438 v -37.43878 c 0,0 -0.33462,-2.75634 0.75893,-3.84989 1.09355,-1.09355 3.91132,-0.75893 3.91132,-0.75893 h 53.66265 c 0,0 2.81312,-0.38586 3.95791,0.75893 z" />
</svg>
</a>
</div>
`;
if (file.embed) {
descDiv.innerHTML += `
<div>
<a href="http://localhost:${port}/process?param=${encodeURIComponent(file.embed)}" class="open">Original</a>
<a href="http://localhost:${port}/show_file?param=${encodeURIComponent(file.embed)}" class="show-file" style="margin-left:5px;">
<!-- Folder SVG Icon -->
<svg width="13.938748" height="11.034863" viewBox="0 0 20.908124 16.552295" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path
id="path5"
style="font-variation-settings:normal;fill:none;fill-opacity:1;stroke:#000000;stroke-width:2.11176515;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;stop-color:#000000"
transform="matrix(0.3054317,0,0,0.3054317,-91.790233,-99.984673)"
d="m 311.31639,336.75961 c 0.96177,-2.24271 1.29727,-4.79155 2.33598,-5.87152 1.03871,-1.07997 4.14072,-0.95467 4.14072,-0.95467 l 9.7597,0.008 c 0,0 4.89538,-0.36509 6.05009,0.94701 1.15471,1.31211 1.64149,6.06092 1.64149,6.06092 m 30.25546,0.82173 c 1.14479,1.14479 0.80357,4.19344 0.80357,4.19344 v 37.09523 h -63.09438 v -37.43878 c 0,0 -0.33462,-2.75634 0.75893,-3.84989 1.09355,-1.09355 3.91132,-0.75893 3.91132,-0.75893 h 53.66265 c 0,0 2.81312,-0.38586 3.95791,0.75893 z" />
</svg>
</a>
</div>
`;
}
galleryDiv.appendChild(link);
galleryDiv.appendChild(descDiv);
divContainer.appendChild(galleryDiv);
});
// Re-attach event listeners to the new links
attachEventListeners(details);
// Print to console
console.log(`Refreshing "${header}"`);
} else {
// No changes, do nothing
console.log(`No changes in "${header}"`);
}
}
// Function to attach event listeners to links with class 'open' and 'show-file' within a given details element
function attachEventListeners(detailsElement) {
// Existing code for 'open' class links
detailsElement.querySelectorAll("a.open").forEach(function(link) {
// Remove existing event listeners to avoid duplicates
const newLink = link.cloneNode(true);
link.parentNode.replaceChild(newLink, link);
});
detailsElement.querySelectorAll("a.open").forEach(function(link) {
link.addEventListener("click", function(event) {
// Prevent the default link behavior
event.preventDefault();
// Store the original color of the link
const originalColor = this.style.color;
// Change the link color before the request is made
this.style.color = "red"; // Change to any color you prefer
// Use fetch API to send the GET request
fetch(this.href)
.then(response => {
if (response.ok) {
console.log("Request successful, staying on the same page.");
} else {
console.error("Request failed with status:", response.status);
}
// Ensure color stays changed for at least 500ms before restoring it
setTimeout(() => {
this.style.color = originalColor;
}, 500); // Delay the restoration by 500ms
})
.catch(error => {
console.error("Network error:", error);
// Delay the restoration of the original color even in case of an error
setTimeout(() => {
this.style.color = originalColor;
}, 500); // Delay the restoration by 500ms
});
});
});
// New code for 'show-file' class links
detailsElement.querySelectorAll("a.show-file").forEach(function(link) {
// Remove existing event listeners to avoid duplicates
const newLink = link.cloneNode(true);
link.parentNode.replaceChild(newLink, link);
});
detailsElement.querySelectorAll("a.show-file").forEach(function(link) {
link.addEventListener("click", function(event) {
// Prevent the default link behavior
event.preventDefault();
// Use fetch API to send the GET request
fetch(this.href)
.then(response => {
if (response.ok) {
console.log("Request successful, staying on the same page.");
} else {
console.error("Request failed with status:", response.status);
}
})
.catch(error => {
console.error("Network error:", error);
});
});
});
}
// Function to render the gallery from the JSON data
function renderGallery(data, forceRender = false) {
// Create a set of headers from the new data
const newHeaders = new Set(data.map(group => group.header));
// Remove groups that are no longer present
Object.keys(existingGroups).forEach(header => {
if (!newHeaders.has(header) || forceRender) {
const details = existingGroups[header];
details.remove();
delete existingGroups[header];
delete existingGroupData[header];
delete existingGroupNeedsRefresh[header];
}
});
// Render or update groups
data.forEach(group => {
renderGroup(group);
});
}
// Fetch the gallery data from the server and render it dynamically
function fetchGalleryData(forceRender = false) {
fetch('/gallery_data')
.then(response => response.json())
.then(data => {
renderGallery(data.gallery_data, forceRender);
})
.catch(error => console.error('Error fetching gallery data:', error));
}
// Function to check for refresh
function checkForRefresh() {
fetch('/check_for_refresh')
.then(response => response.json())
.then(data => {
if (data.lastupdate > mylastupdate) {
mylastupdate = data.lastupdate;
fetchGalleryData();
} else {
// Even if no data change, we need to re-render groups that need refresh
Object.keys(existingGroupNeedsRefresh).forEach(header => {
if (existingGroupNeedsRefresh[header]) {
const group = existingGroupData[header];
if (group) {
renderGroup(group);
}
}
});
}
document.querySelector('.serverdown').innerHTML = "";
})
.catch(error => {
console.error('Error checking for refresh:', error);
document.querySelector('.serverdown').innerHTML = "Server is not running, files cannot be opened.";
});
}
// Fetch gallery data on page load
document.addEventListener('DOMContentLoaded', () => {
fetchGalleryData();
setInterval(checkForRefresh, 1000); // Check for refresh every 1 second
});
</script>
</body>
</html>

View file

@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<name>Homogenizer</name>
<id>burghoff.homogenizer</id>
<param name="tab" type="notebook">
<page name="scaling" gui-text="Options">
<label>Sets the properties of all selected objects without changing objects' center position. For best results, imported PDFs should be Flattened before running.
</label>
<label appearance="header">Text options</label>
<param name="fixtextdistortion" type="bool" gui-text="Correct distorted text?">true</param>
<param name="setfontfamily" type="bool" gui-text="Set font?">true</param>
<param name="fontfamily" type="string" gui-text="New font"
gui-description="Can be used to set Font Family and Font Style. If specifying both, separate them with a space."></param>
<param name="setfontsize" type="bool" gui-text="Set font size?">true</param>
<param name="fontmodes" type="optiongroup" appearance="combo"
gui-text="Font size options:">
<option value="2">Fixed size (pt)</option>
<option value="3">Scale (%)</option>
<option value="5">Mean selected</option>
<option value="6">Median selected</option>
<option value="7">Min selected</option>
<option value="8">Max selected</option>
<option value="4">Scale max to (pt)</option>
</param>
<param name="fontsize" type="float" precision="1" min="0" max="10000"
gui-text="Font size value (if applicable)">8</param>
<param name="plotaware" type="bool" gui-text="Plot-aware text adjustments?" gui-description="When adjusting text, maintain distance to a plot. Requires that each selected item be a grouped plot with a well-defined plot area.">false</param>
<label appearance="header">Stroke options</label>
<param name="fusetransforms" type="bool" gui-text="Correct distorted paths?"
gui-description="Fuses transforms to paths, ensuring stroke width is constant">true</param>
<param name="setstroke" type="bool" gui-text="Set stroke width?">true</param>
<param name="strokemodes" type="optiongroup" appearance="combo"
gui-text="Stroke width options:">
<option value="2">Fixed size (px)</option>
<option value="3">Scale (%)</option>
<option value="5">Mean selected</option>
<option value="6">Median selected</option>
<option value="7">Min selected</option>
<option value="8">Max selected</option>
</param>
<param name="setstrokew" type="float" precision="2" min="0" max="10000" gui-text="Stroke width value (if applicable)">1</param>
<label appearance="header">Other options</label>
<param name="clearclipmasks" type="bool" gui-text="Remove clips and masks?"
gui-description="Deletes all clips and masks without releasing them">false</param>
<spacer/>
<label>Scientific Inkscape v1.4.23</label>
<label appearance="url">https://github.com/burghoff/Scientific-Inkscape</label>
<label>David Burghoff, University of Texas at Austin</label>
</page>
</param>
<effect needs-live-preview="false">
<object-type>text</object-type>
<effects-menu>
<submenu name="Scientific"/>
</effects-menu>
</effect>
<script>
<command location="inx" interpreter="python">homogenizer.py</command>
</script>
</inkscape-extension>

View file

@ -0,0 +1,396 @@
#!/usr/bin/env python
# coding=utf-8
#
# Copyright (c) 2023 David Burghoff <burghoff@utexas.edu>
#
# 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.
#
import dhelpers as dh
import inkex
from inkex import TextElement, FlowRoot, FlowPara, Tspan, Transform, Group, FlowSpan
from inkex.text.cache import BaseElementCache
otp_support_tags = BaseElementCache.otp_support_tags
from inkex.text.utils import default_style_atts
from applytransform_mod import fuseTransform
import math
badels = (
inkex.NamedView,
inkex.Defs,
inkex.Metadata,
inkex.ForeignObject,
inkex.SVGfont,
inkex.FontFace,
inkex.MissingGlyph,
)
dispprofile = False
class Homogenizer(inkex.EffectExtension):
# def document_path(self):
# return 'test'
def add_arguments(self, pars):
pars.add_argument("--tab", help="The selected UI-tab when OK was pressed")
pars.add_argument(
"--setfontsize", type=inkex.Boolean, default=False, help="Set font size?"
)
pars.add_argument("--fontsize", type=float, default=8, help="New font size")
pars.add_argument(
"--fixtextdistortion",
type=inkex.Boolean,
default=False,
help="Fix distorted text?",
)
pars.add_argument("--fontmodes", type=int, default=1, help="Font size options")
pars.add_argument(
"--setfontfamily",
type=inkex.Boolean,
default=False,
help="Set font family?",
)
pars.add_argument("--fontfamily", type=str, default="", help="New font family")
# pars.add_argument("--setreplacement", type=inkex.Boolean, default=False,help="Replace missing fonts?")
# pars.add_argument("--replacement", type=str, default='', help="Missing fon replacement");
pars.add_argument(
"--setstroke", type=inkex.Boolean, default=False, help="Set stroke width?"
)
pars.add_argument(
"--setstrokew", type=float, default=1, help="New stroke width"
)
pars.add_argument(
"--strokemodes", type=int, default=1, help="Stroke width options"
)
pars.add_argument(
"--clearclipmasks", type=inkex.Boolean, default=False, help="Clear clips and masks"
)
pars.add_argument(
"--fusetransforms",
type=inkex.Boolean,
default=False,
help="Fuse transforms to paths?",
)
pars.add_argument(
"--plotaware",
type=inkex.Boolean,
default=False,
help="Plot-aware text scaling?",
)
def effect(self):
if dispprofile:
import cProfile, pstats, io
from pstats import SortKey
pr = cProfile.Profile()
pr.enable()
setfontsize = self.options.setfontsize
# setfontsize = (self.options.fontmodes>1);
fontsize = self.options.fontsize
setfontfamily = self.options.setfontfamily
fontfamily = self.options.fontfamily
setstroke = self.options.setstroke
setstrokew = self.options.setstrokew
fixtextdistortion = self.options.fixtextdistortion
sel0 = [self.svg.selection[ii] for ii in range(len(self.svg.selection))]
# should work with both v1.0 and v1.1
sel = [v for el in sel0 for v in el.descendants2()]
itag = inkex.Image.ctag
if all([el.tag == itag for el in sel]):
inkex.utils.errormsg(
"""Thanks for using Scientific Inkscape!
It appears that you're attempting to homogenize a raster Image object. Please note that Inkscape is mainly for working with vector images, not raster images. Vector images preserve all of the information used to generate them, whereas raster images do not. Read about the difference here:
https://en.wikipedia.org/wiki/Vector_graphics
Unfortunately, this means that there is not much the Homogenizer can do to edit raster images. If you want to edit a raster image, you will need to use a program like Photoshop or GIMP.
"""
)
quit()
elif self.options.plotaware and any([not isinstance(k, Group) for k in sel0]):
inkex.utils.errormsg(
"Plot-aware scaling requires that every selected object be a grouped plot."
)
return
sela = [el for el in sel if not (isinstance(el, badels))]
sel = [
el
for el in sel
if isinstance(el, (TextElement, Tspan, FlowRoot, FlowPara, FlowSpan))
]
if setfontfamily or setfontsize or fixtextdistortion:
tels = [d for d in sel if isinstance(d, (TextElement, FlowRoot))]
if not self.options.plotaware:
bbs = dh.BB2(self.svg, tels, False)
else:
aels = [d for el in sel0 for d in el.descendants2()]
bbs = dh.BB2(self.svg, aels, False)
if setfontsize:
# Get all font sizes and scale factors
onept = self.svg.cdocsize.unittouu("1pt")
szs = dict()
for el in tels:
cszs = [c.tfs / onept for ln in el.parsed_text.lns for c in ln.chrs]
if len(cszs) > 0:
szs[el] = max(cszs)
# Determine scale and/or size
fixedscale = False
try:
if self.options.fontmodes == 3:
fixedscale = True
elif self.options.fontmodes == 4:
fixedscale = True
fontsize = fontsize / max(szs.values()) * 100
elif self.options.fontmodes == 5:
from statistics import mean
fontsize = mean(szs.values())
elif self.options.fontmodes == 6:
from statistics import median
fontsize = median(szs.values())
elif self.options.fontmodes == 7:
fontsize = min(szs.values())
elif self.options.fontmodes == 8:
fontsize = max(szs.values())
except ValueError:
fontsize = 12
from inkex.text import parser
for el in szs:
for d in reversed(el.descendants2()):
sty = d.cspecified_style
if el == d or "font-size" in sty:
dfs, sf, utdfs = dh.composed_width(d, "font-size")
if dfs==0:
continue
bshift = parser.TChar.get_baseline(sty, d.getparent())
if bshift != 0 or "%" in sty.get("font-size", ""):
# Convert sub/superscripts into relative size
pfs, sf, _ = dh.composed_width(d.getparent(), "font-size")
d.cstyle["font-size"] = f"{dfs / pfs * 100:.2f}%"
else:
# Set absolute size
scl = (
fontsize * onept / dfs
if not fixedscale
else fontsize / 100
)
nfs = utdfs * scl
nfs = f"{nfs:.2f}" if abs(nfs) > 1 else "{:.3g}".format(nfs)
d.cstyle["font-size"] = nfs.rstrip("0").rstrip(".") + "px"
if fixtextdistortion:
# make a new transform that removes bad scaling and shearing (see General_affine_transformation.nb)
for el in sel:
ct = el.ccomposed_transform
detv = ct.a * ct.d - ct.b * ct.c
if detv!=0:
signdet = -1 * (detv < 0) + (detv >= 0)
sqrtdet = math.sqrt(abs(detv))
magv = math.sqrt(ct.b**2 + ct.a**2)
ctnew = Transform(
[
[ct.a * sqrtdet / magv, -ct.b * sqrtdet * signdet / magv, ct.e],
[ct.b * sqrtdet / magv, ct.a * sqrtdet * signdet / magv, ct.f],
]
)
dh.global_transform(el, (ctnew @ (-ct)))
if setfontfamily:
from inkex.text.font_properties import inkscape_spec_to_css
sty = inkscape_spec_to_css(fontfamily)
if sty is None:
dh.idebug('Font seems to be invalid—check its spelling.')
import sys
sys.exit()
# If any type of Font Style is being set, reset the others to default
if any(k in sty for k in ["font-weight", "font-style", "font-stretch"]):
for k in ["font-weight", "font-style", "font-stretch"]:
sty.setdefault(k, default_style_atts[k])
for el in reversed(sel):
for k,v in sty.items():
el.cstyle[k] = v
el.cstyle["-inkscape-font-specification"] = None
from inkex.text import parser
dh.character_fixer(tels)
if setfontfamily or setfontsize or fixtextdistortion:
bbs2 = dh.BB2(self.svg, tels, True)
if not self.options.plotaware:
for el in sel:
myid = el.get_id()
if (
isinstance(el, (TextElement, FlowRoot))
and myid in bbs
and myid in bbs2
):
bb = bbs[el.get_id()]
bb2 = bbs2[el.get_id()]
tx = (bb2[0] + bb2[2] / 2) - (bb[0] + bb[2] / 2)
ty = (bb2[1] + bb2[3] / 2) - (bb[1] + bb[3] / 2)
trl = Transform("translate({0}, {1})".format(-tx, -ty))
dh.global_transform(el, trl)
else:
from scale_plots import (
geometric_bbox,
Find_Plot_Area,
trtf,
appendInt,
)
gbbs = {elid: geometric_bbox(el, fbb).sbb for elid, fbb in bbs.items()}
for i0, g in enumerate(sel0):
pels = [k for k in g if k.get_id() in bbs] # plot elements list
vl, hl, lvel, lhel = Find_Plot_Area(pels, gbbs)
if lvel is None or lhel is None:
lvel = None
lhel = None
# Display warning and proceed
numgroup = str(i0 + 1) + appendInt(i0 + 1)
inkex.utils.errormsg(
"A box-like plot area could not be automatically detected on the "
+ numgroup
+ " selected plot (group ID "
+ g.get_id()
+ ").\n\nDraw a box with a stroke to define the plot area."
+ "\nAdjustment will still be performed, but the results may not be ideal."
)
bbp = dh.bbox(None)
# plot area
for el in pels:
if el.get_id() in [lvel, lhel]:
bbp = bbp.union(gbbs[el.get_id()])
for el in g.descendants2():
if el in tels:
bb1 = dh.bbox(bbs[el.get_id()])
bb2 = dh.bbox(bbs2[el.get_id()])
if bbp.isnull:
dx = bb1.xc - bb2.xc
dy = bb1.yc - bb2.yc
else:
# For elements outside the plot area, adjust position to maintain
# the scaled distance to the plot area
if bb1.xc < bbp.x1:
dx = (bbp.x1 - bb2.x2) - (
bbp.x1 - bb1.x2
) * bb2.w / bb1.w
elif bb1.xc > bbp.x2:
dx = (bb1.x1 - bbp.x2) * bb2.w / bb1.w - (
bb2.x1 - bbp.x2
)
else:
dx = bb1.xc - bb2.xc
if bb1.yc < bbp.y1:
dy = (bbp.y1 - bb2.y2) - (
bbp.y1 - bb1.y2
) * bb2.h / bb1.h
elif bb1.yc > bbp.y2:
dy = (bb1.y1 - bbp.y2) * bb2.h / bb1.h - (
bb2.y1 - bbp.y2
)
else:
dy = bb1.yc - bb2.yc
tr2 = trtf(dx, dy)
dh.global_transform(el, tr2)
if setstroke:
szd = dict()
sfd = dict()
szs = []
for el in sela:
sw, sf, _ = dh.composed_width(el, "stroke-width")
elid = el.get_id()
szd[elid] = sw
sfd[elid] = sf
if sw is not None:
szs.append(sw)
fixedscale = False
if self.options.strokemodes == 2:
setstrokew = self.svg.cdocsize.unittouu(str(setstrokew) + "px")
elif self.options.strokemodes == 3:
fixedscale = True
elif self.options.strokemodes == 5:
from statistics import mean
setstrokew = mean(szs)
elif self.options.strokemodes == 6:
from statistics import median
setstrokew = median(szs)
elif self.options.strokemodes == 7:
setstrokew = min(szs)
elif self.options.strokemodes == 8:
setstrokew = max(szs)
for el in sela:
elid = el.get_id()
if not (szd[elid] is None):
if not (fixedscale):
newsize = setstrokew
else:
newsize = szd[elid] * (setstrokew / 100)
if sfd[elid]==0:
continue
el.cstyle["stroke-width"] = str(newsize / sfd[elid]) + "px"
if self.options.fusetransforms:
for el in sela:
if el.tag in otp_support_tags:
# Fuse the composed transform onto the path
el.ctransform = el.ccomposed_transform
fuseTransform(el)
el.ctransform = -el.getparent().ccomposed_transform
if self.options.clearclipmasks:
for el in sela:
el.cstyle['clip-path'] = 'none'
el.cstyle['mask'] = 'none'
if dispprofile:
pr.disable()
s = io.StringIO()
sortby = SortKey.CUMULATIVE
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
dh.debug(s.getvalue())
if __name__ == "__main__":
dh.Run_SI_Extension(Homogenizer(), "Homogenizer")

View file

@ -0,0 +1,675 @@
# Stuff copied from image_extract and image_embed
#!/usr/bin/env python
# coding=utf-8
#
# Copyright (C) 2005,2007 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.
#
"""
Extract embedded images.
"""
from __future__ import unicode_literals
import os
import dhelpers # noqa
import inkex
from inkex import Image
try:
from base64 import decodebytes
from base64 import b64encode
except ImportError:
from base64 import decodestring as decodebytes
from base64 import b64encode
def mime_to_ext(mime):
"""Return an extension based on the mime type"""
# Most extensions are automatic (i.e. extension is same as minor part of mime type)
part = mime.split("/", 1)[1].split("+")[0]
return "." + {
# These are the non-matching ones.
"svg+xml": ".svg",
"jpeg": ".jpg",
"icon": ".ico",
}.get(part, part)
def extract_image(node, save_to):
"""Extract the node as if it were an image."""
xlink = node.get("xlink:href")
if not xlink.startswith("data:"):
return # Not embedded image data
# This call will raise AbortExtension if the document wasn't saved
# and the user is trying to extract them to a relative directory.
# save_to = self.absolute_href(self.options.filepath, default=None)
# Make the target directory if it doesn't exist yet.
if not os.path.isdir(save_to):
os.makedirs(save_to)
try:
data = xlink[5:]
(mimetype, data) = data.split(";", 1)
(base, data) = data.split(",", 1)
except ValueError:
inkex.errormsg("Invalid image format found")
return
if base != "base64":
inkex.errormsg("Can't decode encoding: {}".format(base))
return
file_ext = mime_to_ext(mimetype)
pathwext = os.path.join(save_to, node.get("id") + file_ext)
if os.path.isfile(pathwext):
inkex.errormsg(
"Can't extract image, filename already used: {}".format(pathwext)
)
return
# self.msg('Image extracted to: {}'.format(pathwext))
with open(pathwext, "wb") as fhl:
fhl.write(decodebytes(data.encode("utf-8")))
# absolute for making in-mem cycles work
node.set("xlink:href", os.path.realpath(pathwext))
"""
Embed images so they are base64 encoded data inside the svg.
"""
from inkex.localization import inkex_gettext as _
try:
import urllib.request as urllib
import urllib.parse as urlparse
from base64 import encodebytes
except ImportError:
# python2 compatibility, remove when python3 only.
import urllib
import urlparse
from base64 import encodestring as encodebytes
def embed_image(node, svg_dir):
"""Embed the data of the selected Image Tag element"""
xlink = node.get("xlink:href")
if xlink is not None and xlink[:5] == "data:":
# No need, data already embedded
return
if xlink is None:
inkex.errormsg(
_('Attribute "xlink:href" not set on node {}.'.format(node.get_id()))
)
return
url = urlparse.urlparse(xlink)
href = urllib.url2pathname(url.path)
# Primary location always the filename itself, we allow this
# call to search the user's home folder too.
path = absolute_href2(href or "", svg_dir)
# Backup directory where we can find the image
if not os.path.isfile(path):
path = node.get("sodipodi:absref", path)
if not os.path.isfile(path):
inkex.errormsg(_('File not found "{}". Unable to embed image.').format(path))
return
with open(path, "rb") as handle:
# Don't read the whole file to check the header
file_type = get_type(path, handle.read(10))
handle.seek(0)
if file_type:
# Future: Change encodestring to encodebytes when python3 only
node.set(
"xlink:href",
"data:{};base64,{}".format(
file_type, encodebytes(handle.read()).decode("ascii")
),
)
node.pop("sodipodi:absref")
else:
inkex.errormsg(
_(
"%s is not of type image/png, image/jpeg, "
"image/bmp, image/gif, image/tiff, or image/x-icon"
)
% path
)
def embed_external_image(el, filename):
"""Embed the data of the selected Image Tag element"""
if filename is not None:
with open(filename, "rb") as handle:
# Don't read the whole file to check the header
file_type = get_type(filename, handle.read(10))
handle.seek(0)
if file_type:
# Future: Change encodestring to encodebytes when python3 only
el.set(
"xlink:href",
"data:{};base64,{}".format(
file_type, encodebytes(handle.read()).decode("ascii")
),
)
el.pop("sodipodi:absref")
else:
inkex.errormsg(
_(
"%s is not of type image/png, image/jpeg, "
"image/bmp, image/gif, image/tiff, or image/x-icon"
)
% filename
)
# Check if image is linked or embedded. If linked, check if path is valid
def check_linked(node, svg_dir):
"""Embed the data of the selected Image Tag element"""
xlink = node.get("xlink:href")
if xlink is not None and xlink[:5] == "data:":
return False, None
url = urlparse.urlparse(xlink)
href = urllib.url2pathname(url.path)
path = absolute_href2(href or "", svg_dir)
if not os.path.isfile(path):
path = node.get("sodipodi:absref", path)
fileexists = os.path.isfile(path)
if not (fileexists):
return True, None
else:
return True, path
# Gets the type of an image element
def get_image_type(node, svg_dir):
xlink = node.get("xlink:href")
if not xlink.startswith("data:"):
# Linked image
xlink = node.get("xlink:href")
if xlink is not None and xlink[:5] == "data:":
# No need, data already embedded
return None
if xlink is None:
print(_('Attribute "xlink:href" not set on node {}.'.format(node.get_id())))
return None
url = urlparse.urlparse(xlink)
href = urllib.url2pathname(url.path)
# Primary location always the filename itself, we allow this
# call to search the user's home folder too.
path = absolute_href2(href or "", svg_dir)
# Backup directory where we can find the image
if not os.path.isfile(path):
path = node.get("sodipodi:absref", path)
if not os.path.isfile(path):
print(_('File not found "{}". Unable to embed image.').format(path))
return None
with open(path, "rb") as handle:
# Don't read the whole file to check the header
file_type = get_type(path, handle.read(10))
return file_type
else:
try:
data = xlink[5:]
(mimetype, data) = data.split(";", 1)
(base, data) = data.split(",", 1)
except ValueError:
print("Invalid image format found")
return None
if base != "base64":
print("Can't decode encoding: {}".format(base))
return None
return mimetype
def get_type(path, header):
"""Basic magic header checker, returns mime type"""
for head, mime in (
(b"\x89PNG", "image/png"),
(b"\xff\xd8", "image/jpeg"),
(b"BM", "image/bmp"),
(b"GIF87a", "image/gif"),
(b"GIF89a", "image/gif"),
(b"MM\x00\x2a", "image/tiff"),
(b"II\x2a\x00", "image/tiff"),
):
if header.startswith(head):
return mime
# ico files lack any magic... therefore we check the filename instead
for ext, mime in (
# official IANA registered MIME is 'image/vnd.microsoft.icon' tho
(".ico", "image/x-icon"),
(".svg", "image/svg+xml"),
):
if path.endswith(ext):
return mime
return None
# if __name__ == '__main__':
# EmbedImage().run()
# Modification to the built-in absolute_href function that doesn't require an
# extension class
def absolute_href2(filename, svg_dir, default="~/"):
"""
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, 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):
filename = os.path.join(svg_dir, filename)
return os.path.realpath(os.path.expanduser(filename))
# Stuff by David Burghoff
try:
from PIL import Image as ImagePIL
hasPIL = True
except:
hasPIL = False
# def remove_alpha(imin):
# background = ImagePIL.new('RGBA', imin.size, (255,255,255))
# alpha_composite = ImagePIL.alpha_composite(background, imin)
# alpha_composite_3 = alpha_composite.convert('RGB')
# return alpha_composite_3
# def remove_alpha(imin, background):
# # background = ImagePIL.new('RGBA', imin.size, (255,255,255))
# alpha_composite = ImagePIL.alpha_composite(background, imin)
# alpha_composite_3 = alpha_composite.convert("RGB")
# return alpha_composite_3
# Convert and crop transparent image to JPG
# Requires the transparent version (imin) as well as the opaque version (opaqueimin)
# def to_jpeg(imin, opaqueimin, imout):
# with ImagePIL.open(imin) as im:
# with ImagePIL.open(opaqueimin) as oim:
# bbox = im.getbbox()
# # # Composite to remove transparent regions
# # compim = remove_alpha(im, imb)
# # Crop to non-transparent region only
# # left,upper,right,lower (left & upper pixel is non-zero corner, right-1 & lower-1 is non-zero corner)
# if bbox is not None:
# oim = oim.crop(bbox)
# bbox = [
# bbox[0] / im.size[0],
# bbox[1] / im.size[1],
# bbox[2] / im.size[0],
# bbox[3] / im.size[1],
# ]
# # normalize to original size
# oim.convert('RGB').save(imout)
# return imout, bbox
def to_jpeg(imin, imout):
with ImagePIL.open(imin) as im:
im.convert("RGB").save(imout)
def crop_image(imin):
with ImagePIL.open(imin) as im:
bbox = im.getbbox()
# left,upper,right,lower (left & upper pixel is non-zero corner, right-1 & lower-1 is non-zero corner)
if bbox is not None:
cropim = im.crop(bbox)
bbox = [
bbox[0] / im.size[0],
bbox[1] / im.size[1],
bbox[2] / im.size[0],
bbox[3] / im.size[1],
]
# normalized to original size
cropim.save(imin)
return imin, bbox
# Extract an embedded image
def extract_image_simple(node, save_to_base):
"""Extract the node as if it were an image."""
xlink = node.get("xlink:href")
data = xlink[5:]
try:
data = xlink[5:]
(mimetype, data) = data.split(";", 1)
(base, data) = data.split(",", 1)
except ValueError:
return None
file_ext = mime_to_ext(mimetype)
pathwext = save_to_base + file_ext
# inkex.utils.debug(pathwext)
with open(pathwext, "wb") as fhl:
fhl.write(decodebytes(data.encode("utf-8")))
return pathwext
# Get the size of an embedded image
def embedded_size(node):
xlink = node.get("xlink:href")
try:
data = xlink[5:]
(mimetype, data) = data.split(";", 1)
(base, data) = data.split(",", 1)
return len(decodebytes(data.encode("utf-8")))
except (ValueError, TypeError):
return None
# Get the data string of an embedded image with the alpha stripped out
# This allows images to be identified after conversion to PDF
def Stripped_Alpha_String(el):
import tempfile
tf = tempfile.NamedTemporaryFile().name
fullpath = extract_image_simple(el, tf)
with ImagePIL.open(fullpath) as im:
newfile = strip_ext(fullpath) + ".png"
return str(im.size)
# im.convert('RGB').save(newfile)
# with open(newfile, "rb") as handle:
# # Don't read the whole file to check the header
# file_type = get_type(newfile, handle.read(10))
# handle.seek(0)
# if file_type:
# return "data:{};base64,{}".format(
# file_type, encodebytes(handle.read()).decode("ascii"))
# return None
def Make_Data_Image(datastr):
data = [ord(c) for c in datastr]
# inkex.utils.debug(data)
import numpy as np
im = ImagePIL.fromarray(np.array([data], dtype="uint8"))
import tempfile
tf = tempfile.NamedTemporaryFile().name
newfile = tf + ".png"
im.save(newfile)
with open(newfile, "rb") as handle:
# Don't read the whole file to check the header
file_type = get_type(newfile, handle.read(10))
handle.seek(0)
if file_type:
return "data:{};base64,{}".format(
file_type, encodebytes(handle.read()).decode("ascii")
)
return None
def Read_Data_Image(imstr):
data = imstr[5:]
(mimetype, data) = data.split(";", 1)
(base, data) = data.split(",", 1)
import io
im = ImagePIL.open(io.BytesIO(decodebytes(data.encode("utf-8"))))
import numpy as np
npa = np.asarray(im)
if len(npa.shape) == 3:
data = npa[:, :, 0]
else:
data = npa
return "".join([chr(v) for v in list(data.ravel())])
import io
def str_to_ImagePIL(imstr):
try:
data = imstr[5:]
(mimetype, data) = data.split(";", 1)
(base, data) = data.split(",", 1)
im = ImagePIL.open(io.BytesIO(decodebytes(data.encode("utf-8"))))
return im
except:
return None
def ImagePIL_to_str(im):
try:
img_byte_arr = io.BytesIO()
im.save(img_byte_arr, format="png")
vals = img_byte_arr.getvalue()
file_type = get_type(None, vals[0:10])
if file_type:
return "data:{};base64,{}".format(
file_type, encodebytes(vals).decode("ascii")
)
except:
return None
# Get just the alpha channel of an image, which can be turned into a mask
# def make_alpha_mask(fin,maskout):
# from PIL import Image, ImageOps
# with Image.open(fin) as im:
# (r,g,b,a)=im.split()
# # (r,g,b)=Image.new('RGB',im.size,'black').split()
# # nim = Image.merge('RGBA',(r,g,b,ImageOps.invert(a)))
# # (r,g,b)=Image.new('RGB',im.size,'black').split()
# nim = Image.merge('L',(a,))
# nim.save(maskout)
# # Get just the alpha channel of an image, which can be turned into a mask
# def make_rgb(fin,rgbout):
# from PIL import Image, ImageOps
# with Image.open(fin) as im:
# (r,g,b,a)=im.split()
# # (r,g,b)=Image.new('RGB',im.size,'black').split()
# # nim = Image.merge('RGBA',(r,g,b,ImageOps.invert(a)))
# # (r,g,b)=Image.new('RGB',im.size,'black').split()
# nim = Image.merge('RGB',(r,g,b))
# nim.save(rgbout)
# Strips image extensions
def strip_ext(fnin):
# strip existing extension
if fnin[-4:].lower() in [".png", ".gif", "jpg", "tif"]:
fnin = fnin[0:-4]
if fnin[-5:].lower() in ["jpeg", "tiff"]:
fnin = fnin[0:-5]
return fnin
# Extracts embedded images or returns the path of linked ones
def extract_img_file(el, svg_dir, newpath):
islinked, validpath = check_linked(el, svg_dir)
if islinked and validpath is not None:
impath = validpath
madenew = False
elif islinked and validpath is None:
impath = None
madenew = False
else:
# inkex.utils.debug(newpath)
extract = extract_image_simple(el, strip_ext(newpath))
if extract is not None:
impath = extract
madenew = True
else:
impath = None
madenew = False
return impath, islinked
# For images with alpha=0 pixels, set the RGB of those pixels based on another
# image. This is usually the same image with a background and with other objects.
# For those pixels, alpha is then set to 1 (out of 255), which prevents the PDF
# renderer from replacing those pixels with black. This avoids the 'gray ring'
# issue that can happen on PDF exports.
def Set_Alpha0_RGB(img, imgref):
im1 = ImagePIL.open(img).convert("RGBA")
im2 = ImagePIL.open(imgref).convert("RGBA")
import numpy as np
d1 = np.asarray(im1)
d2 = np.asarray(im2)
a = d1[:, :, 3]
nd = np.stack(
(
np.where(a == 0, d2[:, :, 0], d1[:, :, 0]),
np.where(a == 0, d2[:, :, 1], d1[:, :, 1]),
np.where(a == 0, d2[:, :, 2], d1[:, :, 2]),
np.where(a == 0, 1 * np.ones_like(a), a),
),
2,
)
ImagePIL.fromarray(nd).save(img)
# inkex.utils.debug(img)
anyalpha0 = np.where(a == 0, True, False).any()
return anyalpha0
# Crop a list of images based on the transparency of the first one
# Returns the normalized bounding box, which we need later
def crop_images(ims_in):
bbox = None
with ImagePIL.open(ims_in[0]) as ref_im:
bbox = ref_im.getbbox()
nsz = ref_im.size
if bbox is not None:
# left,upper,right,lower (left & upper pixel is non-zero corner, right-1 & lower-1 is non-zero corner)
nbbox = [
bbox[0] / nsz[0],
bbox[1] / nsz[1],
bbox[2] / nsz[0],
bbox[3] / nsz[1],
] # normalize to original size
for imf in ims_in:
with ImagePIL.open(imf) as im:
im.crop(bbox).save(imf)
return nbbox
else:
return None
# Get the absolute locations of all linked images when called by an extension
# Needed because the temp file has a different location from the actual one
def get_linked_locations(slf):
llocations = dict()
images = slf.svg.xpath("//svg:image")
for node in images:
xlink = node.get("xlink:href")
if xlink is not None and xlink[:5] != "data:":
try:
import urllib.request as urllib
import urllib.parse as urlparse
except ImportError:
# python2 compatibility, remove when python3 only.
import urllib
import urlparse
url = urlparse.urlparse(xlink)
href = urllib.url2pathname(url.path)
# Look relative to the *temporary* filename instead of the original filename.
try: # v1.2 forward
path = slf.absolute_href(
href or "", cwd=os.path.dirname(slf.options.input_file)
)
except: # pre-v1.2
# Primary location always the filename itself, we allow this
# call to search the user's home folder too.
path = slf.absolute_href(href or "")
# Backup directory where we can find the image
if not os.path.isfile(path):
path = node.get("sodipodi:absref", path)
if os.path.isfile(path):
llocations[node.get_id()] = path
else:
llocations[node.get_id()] = None
return llocations
# Get the absolute locations of all linked images when the absolute path is known
def get_linked_locations_file(fin, svg):
llocations = dict()
images = svg.xpath("//svg:image")
for node in images:
xlink = node.get("xlink:href")
if xlink is not None and xlink[:5] != "data:":
try:
import urllib.request as urllib
import urllib.parse as urlparse
except ImportError:
# python2 compatibility, remove when python3 only.
import urllib
import urlparse
url = urlparse.urlparse(xlink)
href = urllib.url2pathname(url.path)
path = absolute_href2(href or "", os.path.dirname(fin))
# Backup directory where we can find the image
if not os.path.isfile(path):
path = node.get("sodipodi:absref", path)
if os.path.isfile(path):
llocations[node.get_id()] = path
else:
llocations[node.get_id()] = None
return llocations

View file

@ -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, 7)
if sys.version_info < MIN_VERSION:
sys.exit("Inkscape extensions require Python 3.7 or greater.")
__version__ = "1.3.0" # Version number for inkex; may differ from Inkscape version.

View file

@ -0,0 +1,562 @@
# 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 io
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
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]
# Provide a unique value to allow detection of no argument specified
# for `output` parameter of `run()`, not even `None`; this has to be an io
# type for type checking purposes:
output_unspecified = io.StringIO("")
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=output_unspecified):
# 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
self.bin_stdout = None
if self.options.output is None:
# If no output was specified, attempt to extract a binary
# output from stdout, and if that doesn't seem possible,
# punt and try whatever stream stdout is:
if output is InkscapeExtension.output_unspecified:
output = sys.stdout
if "b" not in getattr(output, "mode", "") and not isinstance(
output, (io.RawIOBase, io.BufferedIOBase)
):
if hasattr(output, "buffer"):
output = output.buffer # type: ignore
elif hasattr(output, "fileno"):
self.bin_stdout = os.fdopen(
output.fileno(), "wb", closefd=False
)
output = self.bin_stdout
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 hasattr(self, "bin_stdout"):
if self.bin_stdout is not None:
self.bin_stdout.close()
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
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
# if the file does not exist, _tempdir is never set.
if self._tempdir is not 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

View file

@ -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) P_3 + x_4
to the a form which can be differentiated more easily
P(t) = a + b + 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

View file

@ -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

View file

@ -0,0 +1,347 @@
# 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 re
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 Keyword 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().
Returns the stdout of the call.
.. versionchanged:: 1.3
If the "actions" kwargs parameter is passed, it is checked whether the length of
the action string might lead to issues with the Windows CLI call character
limit. In this case, Inkscape is called in `--shell`
mode and the actions are fed in via stdin. This avoids violating the character
limit for command line arguments on Windows, which results in errors like this:
`[WinError 206] The filename or extension is too long`.
This workaround is also possible when calling Inkscape with long arguments
to `--export-id` and `--query-id`, by converting the call to the appropriate
action sequence. The stdout is cleaned to resemble non-interactive mode.
"""
os.environ["SELF_CALL"] = "true"
actions = kwargs.get("actions", None)
strip_stdout = False
# Keep some safe margin to the 8191 character limit.
if actions is not None and len(actions) > 7000:
args = args + ("--shell",)
kwargs["stdin"] = actions
kwargs.pop("actions")
strip_stdout = True
stdout = call(INKSCAPE_EXECUTABLE_NAME, svg_file, *args, **kwargs)
if strip_stdout:
split = re.split(r"\n> ", stdout)
if len(split) > 1:
if "\n" in split[1]:
stdout = "\n".join(split[1].split("\n")[1:])
else:
stdout = ""
return stdout
def inkscape_command(svg, select=None, actions=None, *args, **kwargs):
"""
Executes Inkscape batch actions with the given <svg> input and returns a new <svg>.
inkscape_command('<svg...>', [select=...], [actions=...], [...])
"""
with TemporaryDirectory(prefix="inkscape-command") as tmpdir:
svg_file = write_svg(svg, tmpdir, "input.svg")
select = ("select", select) if select else None
inkscape(
svg_file,
select,
batch_process=True,
export_overwrite=True,
actions=actions,
*args,
**kwargs,
)
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

View file

@ -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()

View file

@ -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'

View file

@ -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."""
)

View file

@ -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)

View file

@ -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)

View file

@ -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)

View file

@ -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

View file

@ -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()

View file

@ -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)))

View file

@ -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)

View file

@ -0,0 +1,3 @@
from .main import *
from .meta import deprecate, _deprecated
from .deprecatedeffect import DeprecatedEffect, Effect

View file

@ -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"""

View file

@ -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

View file

@ -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()

View file

@ -0,0 +1,56 @@
"""
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
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,
Mask,
Gradient,
LinearGradient,
RadialGradient,
PathEffect,
Stop,
MeshGradient,
MeshRow,
MeshPatch,
)
from ._image import Image

View file

@ -0,0 +1,811 @@
# -*- 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
import re
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, ShorthandValue, 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("href") or 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()
if self.get("href"):
self.set("href", "#" + elem)
else:
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]
and not issubclass(all_properties[key][0], ShorthandValue)
):
# Shorthands cannot be set by presentation attributes
result = BaseStyleValue.factory_errorhandled(
key=key, value=self.attrib[key]
)
if result is not None: # parsing error
style[key] = result[1]
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 other and isinstance(parent, BaseElement):
return parent.composed_transform(other) @ 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). May be set through CSS.
.. versionadded:: 1.1"""
ref = self.get("clip-path")
if not ref:
return self.specified_style()("clip-path")
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 this object is invisible
.. versionchanged:: 1.3
rely on cascaded_style() to include CSS and presentation attributes
include `visibility` attribute with check for inherit
include ancestors
.. versionadded:: 1.1"""
return self._is_visible()
def _is_visible(self, inherit_visibility=True):
# iterate over self and ancestors
for element in [self] + list(self.ancestors()):
get_style = element.cascaded_style().get
# case display:none
if get_style("display", "inline") == "none":
return False
# case opacity:0
if not float(get_style("opacity", 1.0)):
return False
# only check if childs visibility is inherited
if inherit_visibility:
# case visibility:hidden
if get_style("visibility", "inherit") in (
"hidden",
"collapse",
):
return False
# case visibility: not inherit
elif get_style("visibility", "inherit") != "inherit":
inherit_visibility = 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)
class ViewboxMixin:
"""Mixin for elements with viewboxes, such as <svg>, <marker>"""
def parse_viewbox(self, vbox: Optional[str]) -> Optional[List[float]]:
"""Parses a viewbox. If an error occurs during parsing,
(0, 0, 0, 0) is returned. If the viewbox is None, None is returned.
.. versionadded:: 1.3"""
if vbox is not None and isinstance(vbox, str):
try:
result = [float(unit) for unit in re.split(r",\s*|\s+", vbox)]
except ValueError:
result = []
if len(result) != 4:
result = [0, 0, 0, 0]
return result
return None

View file

@ -0,0 +1,516 @@
# -*- 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 ..utils import parse_percent
from ..transforms import Transform
from ..styles import Style
from ._utils import addNS
from ._base import BaseElement, ViewboxMixin
from ._groups import GroupBase
from ..units import convert_unit
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"""
value = self.get("offset", default="0")
return parse_percent(value)
@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, ViewboxMixin):
"""Pattern element which is used in the def to control repeating fills"""
tag_name = "pattern"
WRAPPED_ATTRS = BaseElement.WRAPPED_ATTRS + (("patternTransform", Transform),)
def get_fallback(self, prop, default="0"):
val = self.get(prop, None)
if val is None:
if isinstance(self.href, Pattern):
return getattr(self.href, prop)
val = default
return val
x = property(lambda self: self.get_fallback("x"))
y = property(lambda self: self.get_fallback("y"))
width = property(lambda self: self.get_fallback("width"))
height = property(lambda self: self.get_fallback("height"))
patternUnits = property(
lambda self: self.get_fallback("patternUnits", "objectBoundingBox")
)
def get_viewbox(self) -> Optional[List[float]]:
"""Get the viewbox of the pattern, falling back to the href's viewbox
.. versionadded:: 1.3"""
vbox = self.get("viewBox", None)
if vbox is None:
if isinstance(self.href, Pattern):
return self.href.get_viewbox()
return self.parse_viewbox(vbox)
def get_effective_parent(self, depth=0, maxDepth=10):
"""If a pattern has no children, but a href, it uses the children from the href.
Avoids infinite recursion.
.. versionadded:: 1.3"""
if (
len(self) == 0
and self.href is not None
and isinstance(self.href, Pattern)
and depth < maxDepth
):
return self.href.get_effective_parent(depth + 1, maxDepth)
return self
class Mask(GroupBase):
"""A structural object that serves as opacity mask
.. versionadded:: 1.3"""
tag_name = "mask"
def get_fallback(self, prop, default="0"):
return self.to_dimensionless(self.get(prop, default))
x = property(lambda self: self.get_fallback("x"))
y = property(lambda self: self.get_fallback("y"))
width = property(lambda self: self.get_fallback("width"))
height = property(lambda self: self.get_fallback("height"))
maskUnits = property(lambda self: self.get("maskUnits", "objectBoundingBox"))
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 [child for child in gradcolor if isinstance(child, Stop)]
@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
def get_percentage_parsed_unit(self, attribute, value, svg=None):
"""Parses an attribute of a gradient, respecting percentage values of
"userSpaceOnUse" as percentages of document size. See
https://www.w3.org/TR/SVG2/pservers.html#LinearGradientAttributes for details
.. versionadded:: 1.3"""
if isinstance(value, (float, int)):
return value
value = value.strip()
if len(value) > 0 and value[-1] == "%":
try:
value = float(value.strip()[0:-1]) / 100.0
gradientunits = self.get("gradientUnits", "objectBoundingBox")
if gradientunits == "userSpaceOnUse":
if svg is None:
raise ValueError("Need root SVG to determine percentage value")
bbox = svg.get_page_bbox()
if attribute in ("cx", "fx", "x1", "x2"):
return bbox.width * value
if attribute in ("cy", "fy", "y1", "y2"):
return bbox.height * value
if attribute in ("r"):
return bbox.diagonal_length * value
if gradientunits == "objectBoundingBox":
return value
except ValueError:
value = None
return convert_unit(value, "px")
def _get_or_href(self, attr, default, svg=None):
val = self.get(attr)
if val is None:
if type(self.href) is type(self):
return getattr(self.href, attr)()
val = default
return self.get_percentage_parsed_unit(attr, val, svg)
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]),
)
def x1(self, svg=None):
"""Get the x1 attribute
.. versionadded:: 1.3"""
return self._get_or_href("x1", "0%", svg)
def x2(self, svg=None):
"""Get the x2 attribute
.. versionadded:: 1.3"""
return self._get_or_href("x2", "100%", svg)
def y1(self, svg=None):
"""Get the y1 attribute
.. versionadded:: 1.3"""
return self._get_or_href("y1", "0%", svg)
def y2(self, svg=None):
"""Get the y2 attribute
.. versionadded:: 1.3"""
return self._get_or_href("y2", "0%", svg)
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]),
)
def cx(self, svg=None):
"""Get the effective cx (horizontal center) attribute in user units
.. versionadded:: 1.3"""
return self._get_or_href("cx", "50%", svg)
def cy(self, svg=None):
"""Get the effective cy (vertical center) attribute in user units
.. versionadded:: 1.3"""
return self._get_or_href("cy", "50%", svg)
def fx(self, svg=None):
"""Get the effective fx (horizontal focal point) attribute in user units
.. versionadded:: 1.3"""
return self._get_or_href("fx", self.cx(svg), svg)
def fy(self, svg=None):
"""Get the effective fx (vertical focal point) attribute in user units
.. versionadded:: 1.3"""
return self._get_or_href("fy", self.cy(svg), svg)
def r(self, svg=None):
"""Get the effective r (gradient radius) attribute in user units
.. versionadded:: 1.3"""
return self._get_or_href("r", "50%", svg)
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])

View file

@ -0,0 +1,159 @@
# -*- 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, ViewboxMixin
from ._polygons import PathElement
try:
from typing import Optional, List # 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
def bake_transforms_recursively(self, apply_to_paths=True):
"""Bake transforms, i.e. each leaf node has the effective transform (starting
from this group) set, and parent transforms are removed.
.. versionadded:: 1.4
Args:
apply_to_paths (bool, optional): For path elements, the
path data is transformed with its effective transform. Nodes and handles
will have the same position as before, but visual appearance of the
stroke may change (stroke-width is not touched). Defaults to True.
"""
# pylint: disable=attribute-defined-outside-init
self.transform: Transform
for element in self:
if isinstance(element, PathElement) and apply_to_paths:
element.path = element.path.transform(self.transform)
else:
element.transform = self.transform @ element.transform
if isinstance(element, GroupBase):
element.bake_transforms_recursively(apply_to_paths)
self.transform = None
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, ViewboxMixin):
"""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"
def get_viewbox(self) -> List[float]:
"""Returns the viewbox of the Marker, falling back to
[0 0 markerWidth markerHeight]
.. versionadded:: 1.3"""
vbox = self.get("viewBox", None)
result = self.parse_viewbox(vbox)
if result is None:
# use viewport, https://www.w3.org/TR/SVG11/painting.html#MarkerElement
return [
0,
0,
self.to_dimensionless(self.get("markerWidth")),
self.to_dimensionless(self.get("markerHeight")),
]
return result

View file

@ -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"

View file

@ -0,0 +1,466 @@
# -*- 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 List, Optional
from lxml import etree
from inkex.deprecated.meta import deprecate
from ..styles import StyleSheet
from ..transforms import BoundingBox, 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 add_guide(self, position, orient=True, name=None) -> Guide:
"""Creates a new guide in this namedview
.. versionadded:: 1.3
Args:
position: a float containing the y position for ``orient is True``, or
the x position for ``orient is False``. The position is specified in the
post-1.0 coordinate system, i.e. y=0 is at the top left of the viewbox,
positive y axis pointing down.
Alternatively, the position may be given as Tuple (or VectorLike)
orient: True for horizontal, False for Vertical
alternatively: Tuple / Vector specifying x and y coordinates of the
normal vector of the guide, or the (clockwise) angle between the
horizontal axis and the guide. Defaults to True (horizontal)
name: label of the guide
Returns:
the created guide"""
elem = self.add(Guide())
if orient is True:
elem.set_position(0, position, (0, -1))
elif orient is False:
elem.set_position(position, self.root.viewbox_height, (1, 0))
else:
pos = Vector2d(position)
elem.set_position(pos.x, pos.y, orient)
if name:
elem.set("inkscape:label", str(name))
return elem
@deprecate
def new_guide(self, position, orient=True, name=None):
"""
.. deprecated:: 1.3
Use :func:`add_guide` instead.
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)
@deprecate
def new_unique_guide(
self, position: VectorLike, orientation: VectorLike
) -> Optional[Guide]:
"""
.. deprecated:: 1.3
Use :func:`add_unique_guide` instead.
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 add_unique_guide(
self, position: VectorLike, orientation: VectorLike
) -> Optional[Guide]:
"""Add a guide iif there is no guide that looks the same.
.. versionadded:: 1.3
Args:
position: Position as Tuple / Vector
orientation: Tuple / Vector specifying x and y coordinates of the normal
vector of the guide.
name: label of the guide
"""
elem = self.add(Guide()).set_position(position[0], position[1], orientation)
if self.get_similar_guide(elem) is not None:
self.remove(elem)
return None
return elem
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) and is not identity (same element) as the
first one. 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) and guide != other:
return guide
return None
def _get_pages(self) -> List[Page]:
"""Returns all page elements"""
return self.findall("inkscape:page")
def _equivalent_page(self) -> Page:
"""Returns an unrooted page based on the viewbox dimensions"""
return Page.new(self.root.viewbox_width, self.root.viewbox_height, 0, 0)
def get_pages(self) -> List[Page]:
"""Returns a list of pages within the document. For single page documents,
a detached page element with dimensions according to the viewbox will be
returned.
.. versionadded:: 1.2
.. versionchanged:: 1.3
For single-page documents, this function now returns the viewbox
dimensions.
"""
pages = self._get_pages()
if len(pages) < 2:
return [self._equivalent_page()]
return pages
def new_page(self, x, y, width, height, label=None):
"""Creates a new page in this namedview. Always add pages through this
function to ensure that single-page documents are treated correctly.
.. versionadded:: 1.2
.. versionchanged:: 1.3
If none exists, a page element with the viewbox dimensions will be
inserted before the new page."""
if len(self._get_pages()) == 0:
self.add(self._equivalent_page())
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, in the pre-1.0 coordinate system (y axis upwards)
.. versionadded:: 1.2"""
return Vector2d(self.get("orientation"), fallback=(1, 0))
@property
def angle(self) -> float:
"""(Clockwise) angle between the guide and the horizontal axis in degrees
(i.e. what Inkscape 1.2+ shows as "Angle" in the guide properties)
.. versionadded:: 1.3"""
return math.degrees(math.atan2(*self.orientation))
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 raw_position(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))
def point(self):
"""Use raw_position or position instead"""
return self.raw_position
point = property(deprecate(point)) # type: ignore
@property
def position(self) -> Vector2d:
"""Position of the guide handle in normal coordinates, i.e. (0,0) is at
the top left corner of the viewbox, positive y axis pointing downwards.
This function can only be used for guides which are attached to a root
svg element."""
pos = self.raw_position
return Vector2d(pos.x, self.root.viewbox_height - pos.y)
@classmethod
def new(cls, pos_x, pos_y, angle, **attrs):
guide = super().new(**attrs)
guide.set_position(pos_x, pos_y, angle=angle)
return guide
def set_position(self, pos_x, pos_y, angle=None):
"""
Move this guide to the given x,y position and optionally set its orientation.
The coordinate system used is the post-1.0 coordinate system (origin in the
top left corner, y axis pointing down), which also defines the sense of
rotation.
The guide must be rooted for this function to be used. Preferably, use
:func:`inkex.elements._meta.add_guide` to create a new guide.
.. versionadded:: 1.3
Args:
pos_x (Union[str, int, float]): x position of the guide's reference point
pos_y (Union[str, int, float]): y position of the guide's reference point
angle (Union[str, float, int, tuple, list], optional): Angle may be a
string, float or integer, which will set the clockwise angle between the
horizontal axis and the guide.
Alternatively, it may be a pair of numbers (tuple) which will be set
as normal vector.
If not given at all, the orientation remains unchanged.
Defaults to None.
Returns:
Guide: the modified guide
"""
pos_y = self.root.viewbox_height - float(pos_y)
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[0], -angle[1]])
if angle is not None:
self.set("orientation", angle)
return self
@deprecate
def move_to(self, pos_x, pos_y, angle=None):
"""
.. deprecated:: 1.3
Use :func:`set_position` instead.
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.raw_position
opos = guide2.raw_position
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("x", f"{float(x):g}")
self.set("y", f"{float(y):g}")
return self
@property
def bounding_box(self) -> BoundingBox:
"""Returns the bounding box of the page."""
return BoundingBox(
(self.x, self.x + self.width), (self.y, self.y + self.height)
)

View file

@ -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 occurred, 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

View file

@ -0,0 +1,509 @@
# -*- 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 or self.ry:
# pylint: disable=invalid-name
rx = min(self.rx if self.rx > 0 else self.ry, self.width / 2)
ry = min(self.ry if self.ry > 0 else self.rx, self.height / 2)
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 {rx},{ry} 0 0 1 {self.right},{cpts[2]}"
f"L {self.right},{cpts[3]} "
f"A {rx},{ry} 0 0 1 {cpts[1]},{self.bottom}"
f"L {cpts[0]},{self.bottom} "
f"A {rx},{ry} 0 0 1 {self.left},{cpts[3]}"
f"L {self.left},{cpts[2]} "
f"A {rx},{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

View file

@ -0,0 +1,236 @@
# -*- 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

View file

@ -0,0 +1,415 @@
# -*- 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, ViewboxMixin
from ._meta import StyleElement, NamedView
from ._utils import registerNS
from typing import Optional, List, Tuple
if False: # pylint: disable=using-constant-test
import typing # pylint: disable=unused-import
class SvgDocumentElement(
DeprecatedSvgMixin, ISVGDocumentElement, BaseElement, ViewboxMixin
):
"""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, page=None) -> BoundingBox:
"""Gets the page dimensions as a bbox. For single-page documents, the viewbox
dimensions are returned.
Args:
page (int, optional): Page number. Defaults to the first page.
.. versionadded:: 1.3
Raises:
IndexError: if the page number provided does not exist in the document.
Returns:
BoundingBox: the bounding box of the page
"""
if page is None:
page = 0
pages = self.namedview.get_pages()
if 0 <= page < len(pages):
return pages[page].bounding_box
raise IndexError("Invalid page number")
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 add_namespace(self, prefix, url):
"""Adds an xml namespace to the xml parser with the desired prefix.
If the prefix or url are already in use with different values, this
function will raise an error. Remove any attributes or elements using
this namespace before calling this function in order to rename it.
.. versionadded:: 1.3
"""
if self.nsmap.get(prefix, None) == url:
registerNS(prefix, url)
return
# Attempt to clean any existing namespaces
if prefix in self.nsmap or url in self.nsmap.values():
nskeep = [k for k, v in self.nsmap.items() if k != prefix and v != url]
etree.cleanup_namespaces(self, keep_ns_prefixes=nskeep)
if prefix in self.nsmap:
raise KeyError("ns prefix already used with a different url")
if url in self.nsmap.values():
raise ValueError("ns url already used with a different prefix")
# These are globals, but both will overwrite previous uses.
registerNS(prefix, url)
etree.register_namespace(prefix, url)
# Set and unset an attribute to add the namespace to this root element.
self.set(f"{prefix}:temp", "1")
self.set(f"{prefix}:temp", None)
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="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: "href", "xlink:href", "mask", "clip-path".
Defaults to "href".
.. versionadded:: 1.2
attribute set to "href" or "xlink:href" handles both cases.
.. versionchanged:: 1.3
Returns:
Any: list of elements
"""
if attribute == "href" or attribute == "xlink:href":
return self.xpath(f'//*[@href|@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) -> NamedView:
"""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) -> List[float]:
"""Parse and return the document's viewBox attribute"""
return self.parse_viewbox(self.get("viewBox", "0")) or [0, 0, 0, 0]
@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"))

View file

@ -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"

View file

@ -0,0 +1,89 @@
# -*- 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
.. versionchanged:: 1.3
include transform of the referenced element
"""
path = self.href.path
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
# Preserve the id of the clone to not break links that link the <use>
# As we replace exactly one element by exactly one, this should be safe.
old_id = self.get_id()
self.replace_with(copy)
copy.set_random_ids()
copy.set_id(old_id)
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)

View file

@ -0,0 +1,152 @@
# -*- 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 registerNS(prefix, url):
"""Register the given prefix as a namespace url."""
NSS[prefix] = url
SSN[url] = prefix
def addNS(tag, ns=None, namespaces=NSS): # 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 = namespaces.get(ns, None) or ns
if ns is not None:
return f"{{{ns}}}{tag}"
return tag
def removeNS(
name, reverse_namespaces=SSN, default="svg"
): # 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 reverse_namespaces.get(url, default), tag
if ":" in name:
return name.rsplit(":", 1)
return default, name
def splitNS(name, namespaces=NSS): # pylint: disable=invalid-name
"""Like removeNS, but returns a url instead of a prefix"""
(prefix, tag) = removeNS(name)
return (namespaces[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)

View file

@ -0,0 +1,534 @@
# -*- 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
from .command import write_svg, inkscape, ProgramRunError
from .utils import errormsg
from .localization import inkex_gettext as _
# 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, TempDirMixin, 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!")
def preprocess(self, types_to_path=None, unlink_clones=True):
"""Preprocess the SVG into an export-friendly document by converting
certain objects to path beforehand.
Args:
types_to_path (List[str], optional): List of element types to convert to
path. Defaults to all text elements and all non-path shape elements.
unlink_clones (bool, optional): If clones should be unlinked. Defaults to
True.
Returns:
_type_: _description_
"""
if types_to_path is None:
types_to_path = [
"flowRoot",
"rect",
"circle",
"ellipse",
"line",
"polyline",
"polygon",
"text",
]
actions = ["unlock-all"]
if "flowRoot" in types_to_path:
# Flow roots contain rectangles inside them, so they need to be
# converted to paths separately from other shapes
actions += [
"select-by-element:flowRoot",
"object-to-path",
"select-clear",
]
types_to_path.remove("flowRoot")
# Now convert all non-paths to paths
actions += ["select-by-element:" + i for i in types_to_path]
actions += ["object-to-path", "select-clear"]
# unlink clones
if unlink_clones:
actions += ["select-by-element:use", "object-unlink-clones"]
# save and overwrite
actions += ["export-overwrite", "export-do"]
infile = os.path.join(self.tempdir, "input.svg")
write_svg(self.document, infile)
try:
inkscape(infile, actions=";".join(actions))
except ProgramRunError as err:
errormsg(_("An error occurred during document preparation"))
errormsg(err.stderr.decode("utf-8"))
with open(infile, "r") as stream:
self.document = load_svg(stream)
self.svg = self.document.getroot()
class RasterOutputExtension(InkscapeExtension):
"""
Takes a PNG from Inkscape and outputs it to another raster 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.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."
)

View file

@ -0,0 +1,13 @@
# 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](https://gitlab.gnome.org/GNOME/glade). Once you have a layout of all the widgets you want, you then make a GtkApp and Window classes inside your Python program, when the GtkApp is run, the 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 parts we didn't want to ship&mdash;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.

View file

@ -0,0 +1,58 @@
#
# 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 is a wrapper layer to make interacting with Gtk a little less painful.
The main issues with Gtk is that it expects an awful 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 convenience 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 os
import sys
import logging
import threading
from ..utils import DependencyError
try:
import gi
gi.require_version("Gtk", "3.0")
# Importing while covering stderr because pygobject has broken
# warnings support and will force import warnings on our users.
tmp, sys.stderr = sys.stderr, None # type: ignore
from gi.repository import Gtk, GLib
sys.stderr = tmp # type: ignore
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

View file

@ -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 containing 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 interrupt 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 Interrupted")
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):
"""Initialise 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

View file

@ -0,0 +1,329 @@
#
# 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/>
#
"""Convenience 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 propagate exceptions; see its 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 acquire 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

View file

@ -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"""

View file

@ -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)

View file

@ -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)

View file

@ -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

View file

@ -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"""

View file

@ -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}'>"

View file

@ -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

View file

@ -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)]

View file

@ -0,0 +1,850 @@
# 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)
}
# Font stretch can be specified in percent, but for the
# shorthand, only a keyword value is allowed
options["font-stretch"] = (
"normal",
"ultra-condensed",
"extra-condensed",
"condensed",
"semi-condensed",
"semi-expanded",
"expanded",
"extra-expanded",
"ultra-expanded",
)
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 TextDecorationValue(ShorthandValue):
"""Logic for the shorthand font property
.. versionadded:: 1.3"""
def get_shorthand_changes(self):
options = {
"text-decoration-" + key: all_properties["text-decoration-" + key][4]
for key in ("line", "style", "color")
if isinstance(all_properties["text-decoration-" + key][4], list)
}
result = {
"text-decoration-style": all_properties["text-decoration-style"][1],
"text-decoration-color": "currentcolor",
"text-decoration-line": [],
}
tokens = [i for i in self.value.split() if i != ""]
if len(tokens) == 0:
return {} # shorthand not set, nothing to do
for cur in tokens:
if cur in ["underline", "overline", "line-through", "blink"]:
result["text-decoration-line"] += [cur]
elif cur in options["text-decoration-style"]:
result["text-decoration-style"] = cur
else:
result["text-decoration-color"] = cur
if len(result["text-decoration-line"]) == 0:
result["text-decoration-line"] = all_properties["text-decoration-line"][4]
else:
# Text-decoration-line can have multiple values.
result["text-decoration-line"] = " ".join(result["text-decoration-line"])
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("12")
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": (URLNoneValue, "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": (BaseStyleValue, "normal", True, True, None),
"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),
"inline-size": (BaseStyleValue, "0", False, False, 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-inside": (URLNoneValue, "none", False, False, 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": (TextDecorationValue, "", True, True, None),
# multiple enum values are allowed
"text-decoration-line": (BaseStyleValue, "none", False, False, None),
"text-decoration-style": (
EnumValue,
"solid",
False,
False,
["solid", "double", "dotted", "dashed", "wavy"],
),
# This currently cannot be a ColorValue because currentcolor and other special
# colors are not supported by the Color class
"text-decoration-color": (BaseStyleValue, "currentcolor", False, False, 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),
}

View file

@ -0,0 +1,636 @@
# 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
import sys
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
from .utils import FragmentError
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 pop(self, key, default=None):
super().pop(key, default)
# On Python < 3.11, pop internally calls __delitem__.
# This does not happen in 3.11. To avoid
# calling the callback twice, we need to check the Python version.
if sys.version_info >= (3, 11):
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, default=None):
"""Return the parsed value of a style. Optionally, an element can be passed
that will be used to find gradient definitions etc.
.. 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 or default is not None:
defvalue = BaseStyleValue.factory(
attr_name=key, value=default or 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
"""
try:
styles = list(element.root.stylesheets.lookup_specificity(element.get_id()))
except FragmentError:
styles = []
# 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)|(\/\*.*?\*\/|@import .*;)")
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()

View file

@ -0,0 +1,454 @@
# 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
import io
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, load_svg, SvgDocumentElement
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
def import_string(self, string, *args) -> SvgDocumentElement:
"""Runs a string through an import extension, with optional arguments
provided as "--arg=value" arguments"""
stream = io.BytesIO(string.encode())
reader = self.effect_class()
out = io.BytesIO()
reader.parse_arguments([*args])
reader.options.input_file = stream
reader.options.output = out
reader.load_raw()
reader.save_raw(reader.effect())
out.seek(0)
decoded = out.read().decode("utf-8")
document = load_svg(decoded)
return document
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
)

View file

@ -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"
)

View file

@ -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"))

View file

@ -0,0 +1,577 @@
<?xml version="1.0" encoding="UTF-8"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0" datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes" ns="http://www.inkscape.org/namespace/inkscape/extension">
<!-- START EXTENSION DESCRIPTION (uses defines below) -->
<start>
<element name="inkscape-extension">
<optional>
<attribute name="translationdomain"/>
</optional>
<element name="name">
<text/>
</element>
<element name="id">
<text/>
</element>
<zeroOrMore>
<element name="description"><text/></element>
</zeroOrMore>
<zeroOrMore>
<element name="category">
<text/>
<optional>
<attribute name="context"/>
</optional>
</element>
</zeroOrMore>
<zeroOrMore>
<ref name="inx.dependency"/>
</zeroOrMore>
<zeroOrMore>
<ref name="inx.widget"/>
</zeroOrMore>
<choice>
<ref name="inx.input_extension"/>
<ref name="inx.output_extension"/>
<ref name="inx.effect_extension"/>
<ref name="inx.path-effect_extension"/>
<ref name="inx.print_extension"/>
<ref name="inx.template_extension"/>
</choice>
<choice>
<ref name="inx.script"/>
<ref name="inx.xslt"/>
<ref name="inx.plugin"/>
</choice>
</element>
</start>
<!-- END EXTENSION DESCRIPTION (uses defines below) -->
<!-- DEPENDENCIES (INCLDUING SCRIPTS, XSLT AND PLUGINS) -->
<define name="inx.dependency">
<element name="dependency">
<optional>
<attribute name="type">
<choice>
<value>file</value> <!-- default if missing -->
<value>executable</value>
<value>extension</value>
</choice>
</attribute>
</optional>
<ref name="inx.dependency.location_attribute"/>
<optional>
<attribute name="description"/>
</optional>
<text/>
</element>
</define>
<define name="inx.script">
<element name="script">
<group>
<element name="command">
<ref name="inx.dependency.location_attribute"/>
<optional>
<attribute name="interpreter">
<choice>
<value>python</value>
<value>perl</value>
</choice>
</attribute>
</optional>
<text/>
</element>
<optional>
<element name="helper_extension">
<data type="NMTOKEN"/>
</element>
</optional>
</group>
</element>
</define>
<define name="inx.xslt">
<element name="xslt">
<element name="file">
<ref name="inx.dependency.location_attribute"/>
<text/>
</element>
</element>
</define>
<define name="inx.plugin">
<!-- TODO: What's this? How/where is it used? -->
<element name="plugin">
<element name="name">
<text/>
</element>
</element>
</define>
<define name="inx.dependency.location_attribute">
<optional>
<attribute name="location">
<choice>
<value>path</value> <!-- default if missing -->
<value>extensions</value>
<value>inx</value>
<value>absolute</value>
</choice>
</attribute>
</optional>
</define>
<!-- EXTENSION TYPES -->
<define name="inx.input_extension">
<element name="input">
<ref name="inx.input_output_extension.common"/>
</element>
</define>
<define name="inx.output_extension">
<element name="output">
<ref name="inx.input_output_extension.common"/>
<optional>
<attribute name="raster">
<ref name="data_type_boolean_strict"/>
</attribute>
</optional>
<optional>
<element name="dataloss">
<ref name="data_type_boolean_strict"/>
</element>
</optional>
<optional>
<element name="savecopyonly">
<ref name="data_type_boolean_strict"/>
</element>
</optional>
</element>
</define>
<define name="inx.input_output_extension.common">
<optional>
<attribute name="priority">
<data type="integer"/>
</attribute>
</optional>
<element name="extension">
<text/>
</element>
<element name="mimetype">
<text/>
</element>
<optional>
<element name="filetypename">
<text/>
</element>
</optional>
<optional>
<element name="filetypetooltip">
<text/>
</element>
</optional>
</define>
<define name="inx.effect_extension">
<element name="effect">
<optional>
<attribute name="needs-document">
<ref name="data_type_boolean_strict"/>
</attribute>
</optional>
<optional>
<attribute name="needs-live-preview">
<ref name="data_type_boolean_strict"/>
</attribute>
</optional>
<optional>
<attribute name="implements-custom-gui">
<ref name="data_type_boolean_strict"/>
</attribute>
</optional>
<element name="object-type">
<choice>
<value type="token">all</value>
<value type="token">g</value>
<value type="token">path</value>
<value type="token">rect</value>
<value type="token">text</value>
</choice>
</element>
<element name="effects-menu">
<choice>
<attribute name="hidden">
<ref name="data_type_boolean_strict"/>
</attribute>
<ref name="inx.effect_extension.submenu"/>
</choice>
</element>
<optional>
<element name="menu-tip">
<text/>
</element>
</optional>
</element>
</define>
<define name="inx.effect_extension.submenu">
<element name="submenu">
<attribute name="name"/>
<optional>
<!-- TODO: This allows arbitrarily deep menu nesting - could/should we limit this? -->
<ref name="inx.effect_extension.submenu"/>
</optional>
</element>
</define>
<define name="inx.path-effect_extension">
<!-- TODO: Are we still using these? -->
<element name="path-effect">
<empty/>
</element>
</define>
<define name="inx.print_extension">
<!-- TODO: Are we still using these? -->
<element name="print">
<empty/>
</element>
</define>
<define name="inx.template_extension">
<element name="template">
<zeroOrMore>
<attribute>
<anyName/>
</attribute>
</zeroOrMore>
<zeroOrMore>
<element name="preset">
<zeroOrMore>
<attribute>
<anyName/>
</attribute>
</zeroOrMore>
</element>
</zeroOrMore>
</element>
</define>
<!-- WIDGETS AND PARAMETERS -->
<define name="inx.widget">
<choice>
<element name="param">
<ref name="inx.widget.common_attributes"/>
<ref name="inx.parameter"/>
</element>
<element name="label">
<ref name="inx.widget.common_attributes"/>
<optional>
<attribute name="appearance">
<choice>
<value>header</value>
<value>url</value>
</choice>
</attribute>
</optional>
<optional>
<attribute name="xml:space">
<choice>
<value>default</value>
<value>preserve</value>
</choice>
</attribute>
</optional>
<text/>
</element>
<element name="hbox">
<ref name="inx.widget.common_attributes"/>
<oneOrMore>
<ref name="inx.widget"/>
</oneOrMore>
</element>
<element name="vbox">
<ref name="inx.widget.common_attributes"/>
<oneOrMore>
<ref name="inx.widget"/>
</oneOrMore>
</element>
<element name="separator">
<ref name="inx.widget.common_attributes"/>
<empty/>
</element>
<element name="spacer">
<ref name="inx.widget.common_attributes"/>
<optional>
<attribute name="size">
<choice>
<data type="integer"/>
<value>expand</value>
</choice>
</attribute>
</optional>
<empty/>
</element>
<element name="image">
<ref name="inx.widget.common_attributes"/>
<optional>
<attribute name="width">
<data type="integer"/>
</attribute>
<attribute name="height">
<data type="integer"/>
</attribute>
</optional>
<text/>
</element>
</choice>
</define>
<define name="inx.parameter">
<ref name="inx.parameter.common_attributes"/>
<choice>
<group>
<attribute name="type">
<value>int</value>
</attribute>
<optional>
<attribute name="min">
<data type="integer"/>
</attribute>
</optional>
<optional>
<attribute name="max">
<data type="integer"/>
</attribute>
</optional>
<optional>
<attribute name="appearance">
<value>full</value>
</attribute>
</optional>
<choice>
<empty/>
<data type="integer"/>
</choice>
</group>
<group>
<attribute name="type">
<value>float</value>
</attribute>
<optional>
<attribute name="precision">
<data type="integer"/>
</attribute>
</optional>
<optional>
<attribute name="min">
<data type="float"/>
</attribute>
</optional>
<optional>
<attribute name="max">
<data type="float"/>
</attribute>
</optional>
<optional>
<attribute name="appearance">
<value>full</value>
</attribute>
</optional>
<data type="float"/>
</group>
<group>
<attribute name="type">
<value>bool</value>
</attribute>
<ref name="data_type_boolean_strict"/>
</group>
<group>
<attribute name="type">
<value>color</value>
</attribute>
<optional>
<attribute name="appearance">
<choice>
<value>colorbutton</value>
</choice>
</attribute>
</optional>
<choice>
<empty/>
<data type="integer"/>
<data type="string"/> <!-- TODO: We want to support unsigned integers in hex notation (e.g. 0x12345678),
and possibly other representations valid for strtoul, not random strings -->
</choice>
</group>
<group>
<attribute name="type">
<value>string</value>
</attribute>
<optional>
<attribute name="max_length">
<data type="integer"/>
</attribute>
</optional>
<optional>
<attribute name="appearance">
<choice>
<value>multiline</value>
</choice>
</attribute>
</optional>
<choice>
<empty/>
<text/>
</choice>
</group>
<group>
<attribute name="type">
<value>path</value>
</attribute>
<attribute name="mode">
<!-- Note: "mode" is actually optional and defaults to "file".
For semantic reasons it makes sense to always include, though. -->
<choice>
<value>file</value>
<value>files</value>
<value>folder</value>
<value>folders</value>
<value>file_new</value>
<value>folder_new</value>
</choice>
</attribute>
<optional>
<attribute name="filetypes"/>
</optional>
<choice>
<empty/>
<text/>
</choice>
</group>
<group>
<attribute name="type">
<value>optiongroup</value>
</attribute>
<attribute name="appearance">
<!-- Note: "appearance" is actually optional and defaults to "radio".
For semantic reasons it makes sense to always include, though. -->
<choice>
<value>combo</value>
<value>radio</value>
</choice>
</attribute>
<oneOrMore>
<choice>
<element name="option">
<optional>
<attribute name="value"/>
</optional>
<optional>
<attribute name="translatable">
<ref name="data_type_boolean_yes_no"/>
</attribute>
</optional>
<optional>
<attribute name="context"/>
</optional>
<text/>
</element>
</choice>
</oneOrMore>
</group>
<group>
<attribute name="type">
<value>notebook</value>
</attribute>
<oneOrMore>
<element name="page">
<attribute name="name"/>
<attribute name="gui-text"/>
<oneOrMore>
<ref name="inx.widget"/>
</oneOrMore>
<optional>
<attribute name="translatable">
<ref name="data_type_boolean_yes_no"/>
</attribute>
</optional>
</element>
</oneOrMore>
</group>
</choice>
</define>
<define name="inx.widget.common_attributes">
<optional>
<attribute name="gui-hidden">
<ref name="data_type_boolean_strict"/>
</attribute>
</optional>
<optional>
<attribute name="indent">
<data type="integer"/>
</attribute>
</optional>
<optional>
<attribute name="translatable">
<ref name="data_type_boolean_yes_no"/>
</attribute>
</optional>
<optional>
<attribute name="context"/>
</optional>
</define>
<define name="inx.parameter.common_attributes">
<attribute name="name">
<data type="token"/>
</attribute>
<optional>
<!-- TODO: gui-text is mandatory for visible parameters -->
<attribute name="gui-text"/>
</optional>
<optional>
<attribute name="gui-description"/>
</optional>
</define>
<!-- GENERAL DEFINES -->
<define name="data_type_boolean_strict">
<data type="boolean">
<except>
<value>0</value>
<value>1</value>
</except>
</data>
</define>
<define name="data_type_boolean_yes_no">
<choice>
<value>yes</value>
<value>no</value>
</choice>
</define>
</grammar>

View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<sch:schema xmlns:sch="http://www.ascc.net/xml/schematron">
<sch:ns uri="http://www.inkscape.org/namespace/inkscape/extension" prefix="inx"/>
<sch:pattern name="duplicateOptionValues">
<sch:rule context="//inx:param/inx:option">
<sch:report test="preceding-sibling::inx:option/@value = @value">Warning: @value values should be unique for a given option.</sch:report>
</sch:rule>
</sch:pattern>
</sch:schema>

View file

@ -0,0 +1,162 @@
#!/usr/bin/env python3
# coding=utf-8
"""
Test elements extra logic from svg xml lxml custom classes.
"""
import os
from importlib import resources
from lxml import etree
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,
}
def assertInxSchemaValid(self, inx_file): # pylint: disable=invalid-name
"""Validate inx file schema."""
self.assertTrue(INX_SCHEMAS, "no schema files found")
with open(inx_file, "rb") as fp:
inx_doc = etree.parse(fp)
for schema_name, schema in INX_SCHEMAS.items():
with self.subTest(schema_file=schema_name):
schema.assert_(inx_doc)
def _load_inx_schemas():
_SCHEMA_CLASSES = {
".rng": etree.RelaxNG,
".schema": etree.Schematron, # "pre-ISO-Schematron"
}
for name in resources.contents(__package__):
_, ext = os.path.splitext(name)
schema_class = _SCHEMA_CLASSES.get(ext)
if schema_class is None:
continue
with resources.open_binary(__package__, name) as fp:
schema_doc = etree.parse(fp)
yield name, schema_class(schema_doc)
INX_SCHEMAS = dict(_load_inx_schemas())

View file

@ -0,0 +1,463 @@
# 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 + os.sep, "./")
data = replace(data, fdir, ".")
files = replace(files, fdir + os.sep, "./")
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, path):
"""Return true if the mock is ignored"""
if self and program and arglst:
env = os.environ.get("NO_MOCK_COMMANDS", 0)
if (not os.path.exists(path) and int(env) == 1) or int(env) == 2:
return True
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, self.get_call_filename(program, key, create=True)
):
# 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"))
if int(os.environ.get("NO_MOCK_COMMANDS", 0)) == 1:
print(f"Saved mock call as {fname}, remove .{ext}")
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"))

View file

@ -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()

View file

@ -0,0 +1,63 @@
"""Check .inx file(s).
This is meant to be run an executable module, e.g.
python -m inkex.tester.test_inx_file *.inx
"""
import argparse
import sys
import unittest
from typing import List
from .inx import InxMixin
class InxTestCase(InxMixin, unittest.TestCase):
inx_files: List[str] = []
def test_inx_file_parameters(self):
for inx_file in self.inx_files:
with self.subTest(inx_file=inx_file):
self.assertInxIsGood(inx_file)
def test_inx_file_schema(self):
for inx_file in self.inx_files:
with self.subTest(inx_file=inx_file):
self.assertInxSchemaValid(inx_file)
def main(args=None):
"""Check .inx file(s)"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-v",
"--verbose",
dest="verbosity",
action="store_const",
const=2,
help="Verbose output",
)
parser.add_argument(
"-q",
"--quiet",
dest="verbosity",
action="store_const",
const=0,
help="Quiet output",
)
parser.add_argument(
"inx_files", metavar="INX-FILE", nargs="+", help="An .inx file to check"
)
args = parser.parse_args(args, namespace=argparse.Namespace(verbosity=1))
InxTestCase.inx_files = args.inx_files
runner = unittest.TextTestRunner(verbosity=args.verbosity)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(InxTestCase)
result = runner.run(suite)
sys.exit(not result.wasSuccessful())
if __name__ == "__main__":
main()

View file

@ -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

View file

@ -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)

View file

@ -0,0 +1,81 @@
#!/usr/bin/env python
# coding=utf-8
#
# Copyright (c) 2023 David Burghoff <burghoff@utexas.edu>
#
# 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.
"""
This submodule gives all TextElements and FlowRoots the parsed_text property,
which is a cached instance of ParsedText. To use, simply run
import text
Following this, text properties will be available at el.parsed_text. For more
details, see parser.py. To check if it is working properly, run the
following on some text:
el.parsed_text.Make_Highlights('char')
Rectangles should appear surrounding the logical extents of each character.
Before parsing is done, a character table must be generated to determine the properties
of all the characters present. This is done automatically by the first invocation of
.parsed_text, which automatically analyzes the whole document and adds it to the SVG.
If you are only parsing a few text elements, this can be sped up by calling
svg.make_char_table(els). On the rare occasions this fails, a command call may
be performed as a fallback.
"""
# Give inkex an inkex.text submodule that refers to this directory
import sys
import os
import inspect
import inkex
if not hasattr(inkex, "text"):
import importlib
mydir = os.path.dirname(os.path.abspath(__file__))
myloc, myname = os.path.split(mydir)
oldpath = sys.path
sys.path.append(myloc)
inkex.text = importlib.import_module(myname)
sys.modules["inkex.text"] = inkex.text
sys.path = oldpath
# Gives inkex elements some additional cached attributes, for further speedups
import inkex.text.cache # pylint: disable=wrong-import-position
def add_cache(base, derived):
"""
Adds the cache capabilities from a derived class to a base class by dynamically
attaching methods, properties, and data descriptors that are unique to the derived
class to the base class.
"""
predfn = (
lambda x: isinstance(x, property)
or inspect.isfunction(x)
or inspect.isdatadescriptor(x)
)
base_m = dict(inspect.getmembers(base, predicate=predfn))
for name, memb in inspect.getmembers(derived, predicate=predfn):
if memb not in base_m.values():
setattr(base, name, memb)
add_cache(inkex.BaseElement, inkex.text.cache.BaseElementCache)
add_cache(inkex.SvgDocumentElement, inkex.text.cache.SvgDocumentElementCache)
add_cache(inkex.Style, inkex.text.cache.StyleCache)

View file

@ -0,0 +1,639 @@
# coding=utf-8
#
# Copyright (c) 2023 David Burghoff <burghoff@utexas.edu>
# Martin Owens <doctormo@gmail.com>
# Sergei Izmailov <sergei.a.izmailov@gmail.com>
# Thomas Holder <thomas.holder@schrodinger.com>
# 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.
"""
Utilities for text parsing
"""
import math
import re
import sys
import os
from functools import lru_cache
import lxml
from lxml import etree
import inkex
import inkex.command
from inkex.properties import all_properties
from inkex.units import CONVERSIONS, BOTH_MATCH
# For style components that represent a size (stroke-width, font-size, etc),
# calculate the true size reported by Inkscape in user units, inheriting
# any styles/transforms/document scaling
flookup = {"small": "10px", "medium": "12px", "large": "14px"}
def composed_width(elem, comp):
"""
Gets the transformed size of a style component and the scale factor representing
the scale of the composed transform, accounting for relative sizes.
Parameters:
elem (Element): The element whose style to compute.
comp (str): The component of the style to compute, such as 'stroke-width'
or 'font-size'.
Returns:
tuple: A tuple containing the true size in user units, the scale factor,
and the untransformed size
"""
sty = elem.cspecified_style
ctf = elem.ccomposed_transform
satt = sty.get(comp)
# Get default attribute if empty
if satt is None:
satt = default_style_atts[comp]
if "%" in satt: # relative width, get ancestor width
cel = elem
while satt != cel.cstyle.get(comp) and satt != cel.get(comp):
cel = cel.getparent()
# figure out ancestor where % is coming from
satt = float(satt.strip("%")) / 100
tsz, scf, utsz = composed_width(cel.getparent(), comp)
# Since relative widths have no untransformed width, we assign
# it to be a scaled version of the ancestor's ut width
return tsz * satt, scf, utsz * satt
utsz = ipx(satt)
if utsz is None:
utsz = (
utsz
or ipx(flookup.get(satt) if comp == "font-size" else None)
or ipx(default_style_atts[comp])
)
scf = math.sqrt(abs(ctf.a * ctf.d - ctf.b * ctf.c)) # scale factor
return utsz * scf, scf, utsz
def composed_lineheight(elem):
"""
Get absolute line-height in user units based on an element's specified style.
Parameters:
elem (Element): The element whose line-height to compute.
Returns:
float: The computed line-height in user units.
"""
sty = elem.cspecified_style
satt = sty.get("line-height", default_style_atts["line-height"])
if satt == "normal":
satt = 1.25
elif "%" in satt: # relative width, get parent width
satt = float(satt.strip("%")) / 100
else:
try:
# Lines have no unit, em treated the same
satt = float(satt.strip("em"))
except ValueError:
fsz, scf, _ = composed_width(elem, "font-size")
satt = ipx(satt) / (fsz / scf)
fsz, _, _ = composed_width(elem, "font-size")
return satt * fsz
def unique(lst):
"""
Returns a list of unique items from the given list while preserving order.
Parameters:
lst (list): The list from which to remove duplicates.
Returns:
list: A list of unique items in the order they appeared in the input list.
"""
return list(dict.fromkeys(lst))
def uniquetol(x, tol):
"""
Like unique, but for numeric values and accepts a tolerance.
Parameters:
x (list of float): List of numeric values from which to remove near-duplicates.
tol (float): The tolerance within which two numbers are considered the same.
Returns:
list of float: A list of unique numbers within the specified tolerance.
"""
if not x: # Check if the input list is empty
return []
x_sorted = sorted((y for y in x if y is not None)) # Sort, ignoring None values
ret = (
[x_sorted[0]] if x_sorted else []
) # Start with the first value if there are any non-None values
for i in range(1, len(x_sorted)):
if abs(x_sorted[i] - ret[-1]) > tol:
ret.append(x_sorted[i])
# If there were any None values in the original list, append None to the result list
if None in x:
ret.append(None)
return ret
# Adds ctag to the inkex classes, which holds each class's corresponding tag
# Checking the tag is usually much faster than instance checking, which can
# substantially speed up low-level functions.
# pylint:disable=protected-access
lt = dict(inkex.elements._parser.NodeBasedLookup.lookup_table)
shapetags = set()
for key, v in lt.items():
for v2 in v:
v2.ctag = inkex.addNS(key[1], key[0]) if isinstance(key, tuple) else key
if issubclass(v2, inkex.ShapeElement):
shapetags.add(v2.ctag)
tags = lambda x: {v.ctag for v in x} # converts class tuple to set of tags
# pylint:enable=protected-access
rectlike_tags = tags((inkex.PathElement, inkex.Rectangle, inkex.Line, inkex.Polyline))
rect_tag = inkex.Rectangle.ctag
pel_tag = inkex.PathElement.ctag
usetag = inkex.Use.ctag
PTH_CMDS = "".join(list(inkex.paths.PathCommand._letter_to_class.keys()))
pth_cmd_pat = re.compile("[" + re.escape(PTH_CMDS) + "]")
cnt_pth_cmds = lambda d: len(pth_cmd_pat.findall(d)) # count path commands
def isrectangle(elem, includingtransform=True):
"""
Determines if an element is rectangle-like, considering transformations if
specified.
Parameters:
elem (Element): The element to check.
includingtransform (bool): Whether to consider transformations in the
determination.
Returns:
tuple: A tuple containing a boolean indicating if the element is a rectangle and
the path if it is.
"""
ret = True
if not includingtransform and elem.tag == rect_tag:
pth = elem.cpath
elif elem.tag in rectlike_tags:
if elem.tag == pel_tag and not (1 <= cnt_pth_cmds(elem.get("d", "")) <= 6):
# Allow up to 6 (initial M + 4 lines + redundant close path)
return False
pth = elem.cpath
if includingtransform:
tmat = elem.ctransform.matrix
x, y = list(
zip(
*[
(
tmat[0][0] * pt.x + tmat[0][1] * pt.y + tmat[0][2],
tmat[1][0] * pt.x + tmat[1][1] * pt.y + tmat[1][2],
)
for pt in pth.end_points
]
)
)
else:
x, y = list(zip(*[(pt.x, pt.y) for pt in pth.end_points]))
maxsz = max(max(x) - min(x), max(y) - min(y))
tol = 1e-3 * maxsz
if len(uniquetol(x, tol)) != 2 or len(uniquetol(y, tol)) != 2:
ret = False
elif elem.tag == usetag:
useel = elem.get_link("xlink:href")
if useel is not None:
return isrectangle(useel)
ret = True
else:
ret = False
if ret:
if (
elem.get_link("mask", llget=True) is not None
or elem.cspecified_style.get_link("filter", elem.croot) is not None
):
ret = False
elif elem.get_link("clip-path", llget=True) is not None and any(
not isrectangle(k) for k in list(elem.get_link("clip-path", llget=True))
):
ret = False
return ret
class InkscapeSystemInfo:
"""
Discovers and caches Inkscape System info.
"""
_UNSET = object() # Sentinel value for unset attributes
def __init__(self):
"""Initialize InkscapeSystemInfo."""
self._language = self._UNSET
self._preferences = self._UNSET
self._binary_location = self._UNSET
self._binary_version = self._UNSET
@property
def language(self):
"""Get the language used by Inkscape."""
if self._language is self._UNSET:
self._language = self.determine_language()
return self._language
@property
def preferences(self):
"""Get the preferences file location."""
if self._preferences is self._UNSET:
self._preferences = self.find_preferences()
return self._preferences
@property
def binary_location(self):
"""Get the Inkscape binary location."""
if self._binary_location is self._UNSET:
self._binary_location = self.get_binary_location()
return self._binary_location
@property
def binary_version(self):
"""Get the Inkscape binary version."""
if self._binary_version is self._UNSET:
self._binary_version = self.get_binary_version()
return self._binary_version
def get_binary_version(self):
"""Gets the binary location by calling with --version (slow)"""
proc = subprocess_repeat([self.binary_location, "--version"])
match = re.search(r"Inkscape\s+(\S+)\s+\(", str(proc.stdout))
return match.group(1) if match else None
@staticmethod
def get_binary_location():
"""
Gets the location of the Inkscape binary, checking the system
path if necessary.
"""
program = inkex.command.INKSCAPE_EXECUTABLE_NAME
try:
return inkex.command.which(program)
except inkex.command.CommandNotFound as excp:
# Search the path as a backup (primarily for testing)
try:
from shutil import which as warlock
for sysp in sys.path:
if sys.platform == "win32":
prog = warlock(program, path=os.environ["PATH"] + ";" + sysp)
if prog:
return prog
except ImportError as impe:
raise ImportError("Failed to import the 'which' function.") from impe
raise inkex.command.CommandNotFound(
f"Can not find the command: '{program}'"
) from excp
@staticmethod
def find_preferences():
"""Attempt to discover preferences.xml"""
prefspaths = []
# First check the location of the user extensions directory
mydir = os.path.dirname(os.path.abspath(__file__))
file_path = mydir
while "extensions" in file_path and os.path.basename(file_path) != "extensions":
file_path = os.path.dirname(file_path)
prefspaths.append(os.path.join(os.path.dirname(file_path), "preferences.xml"))
# Try some common default locations based on the home directory
home = os.path.expanduser("~")
if sys.platform == "win32":
appdata = os.getenv("APPDATA")
if appdata is not None:
# https://wiki.inkscape.org/wiki/Preferences_subsystem
prefspaths.append(
os.path.join(
os.path.abspath(appdata), "inkscape", "preferences.xml"
)
)
# https://en.wikipedia.org/wiki/Environment_variable#Default_Values_on_Microsoft_Windows
prefspaths.append(
os.path.join(home, "AppData", "Roaming", "inkscape", "preferences.xml")
)
# https://en.wikipedia.org/wiki/Environment_variable#Default_Values_on_Microsoft_Windows
# http://tavmjong.free.fr/INKSCAPE/MANUAL/html/Customize-Files.html
prefspaths.append(
os.path.join(home, "­Application Data", "­Inkscape", "preferences.xml")
)
else:
if sys.platform == "darwin":
# test Mac
prefspaths.append(
os.path.join(
home,
"Library",
"Application Support",
"org.inkscape.Inkscape",
"config",
"inkscape",
"preferences.xml",
)
)
# test Linux
prefspaths.append(
os.path.join(home, ".config", "inkscape", "preferences.xml")
)
# https://wiki.inkscape.org/wiki/Preferences_subsystem#Where_preferences_are_stored
prefspaths.append(
os.path.join(home, ".config", "Inkscape", "preferences.xml")
)
# https://wiki.inkscape.org/wiki/Preferences_subsystem#Where_preferences_are_stored
# https://alpha.inkscape.org/vectors/www.inkscapeforum.com/viewtopicc8ae.html?t=1712
prefspaths.append(os.path.join(home, ".inkscape", "preferences.xml"))
# Try finding from snap location
file_path = mydir
while "snap" in file_path and os.path.basename(file_path) != "snap":
file_path = os.path.dirname(file_path)
prefspaths.append(
os.path.join(
os.path.dirname(file_path), ".config", "inkscape", "preferences.xml"
)
)
# Iterate over potential paths and return the first existing one
for path in prefspaths:
if os.path.exists(path):
return path
return None # failed
@staticmethod
def determine_language(verbose=False):
"""Try to find the language Inkscape is using"""
def get_ui_language(prefspath):
proot = etree.parse(prefspath).getroot()
for k in proot:
if k.get("id") == "ui" and k.get("language") is not None:
return k.get("language")
return None
def getlocale_mod():
# pylint:disable=import-outside-toplevel
import warnings
import locale
# pylint:enable=import-outside-toplevel
with warnings.catch_warnings():
# temporary work-around for
# https://github.com/python/cpython/issues/82986
# by continuing to use getdefaultlocale() even though it has been
# deprecated.
if sys.version_info.minor >= 13:
warnings.warn(
"This function may not behave as expected in"
" Python versions beyond 3.12",
FutureWarning,
)
warnings.simplefilter("ignore", category=DeprecationWarning)
language_code = locale.getdefaultlocale()[0]
if language_code:
return language_code
return "en-US"
# First, try to get the language from preferences.xml
pxml = InkscapeSystemInfo().find_preferences()
if verbose:
inkex.utils.debug("Found preferences.xml: " + str(pxml))
if pxml is not None:
prefslang = get_ui_language(pxml)
if verbose:
inkex.utils.debug("preferences.xml language: " + str(prefslang))
# If it can't be found or is set to use the system lang, use locale
if pxml is None or prefslang in ["", None]:
lcle = getlocale_mod()
prefslang = lcle.split("_")[0]
if verbose:
inkex.utils.debug("locale language: " + str(prefslang))
return prefslang
inkex.inkscape_system_info = InkscapeSystemInfo() # type: ignore
def subprocess_repeat(argin,cwd=None):
"""
In the event of a timeout, repeats a subprocess call several times.
Parameters:
argin (list): The command and arguments to run in the subprocess.
Returns:
CompletedProcess: The result from the subprocess call.
"""
base_timeout = 60
nattempts = 6
import subprocess
nfails = 0
ntime = 0
for i in range(nattempts):
timeout = base_timeout * 2**i
try:
os.environ["SELF_CALL"] = "true" # seems to be needed for 1.3
proc = subprocess.run(
argin,
shell=False,
timeout=timeout,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=True, cwd=cwd
)
break
except subprocess.TimeoutExpired:
nfails += 1
ntime += timeout
if nfails == nattempts:
raise TimeoutError(
"\nThe call to the Inkscape binary timed out "
+ str(nattempts)
+ " times in "
+ str(ntime)
+ " seconds.\n\n"
+ "This may be a temporary issue; try running the extension again."
)
else:
return proc
# Get default style attributes
try:
default_style_atts = {a: v[1] for a, v in all_properties.items()} # type: ignore
except TypeError:
default_style_atts = {
a: "".join([str(t.value) for t in v.default_value])
for a, v in all_properties.items()
} # type: ignore
default_style_atts["font-variant-ligatures"] = "normal" # missing
comment_tag = lxml.etree.Comment("").tag
def list2(elem):
"""Returns non-comment children of an element."""
return [k for k in list(elem) if not (k.tag == comment_tag)]
conv2 = {k: v / CONVERSIONS["px"] for k, v in CONVERSIONS.items()}
@lru_cache(maxsize=None)
def ipx(strin):
"""
Implicit pixel function
For many properties, a size specification of '1px' actually means '1uu'
Even if the size explicitly says '1mm' and the user units are mm, this will be
first converted to px and then interpreted to mean user units. (So '1mm' would
up being bigger than 1 mm). This returns the size as Inkscape will interpret it
(in uu).
No unit: Assumes 'px'
Invalid unit: Returns None
"""
try:
ret = BOTH_MATCH.match(strin)
value = float(ret.groups()[0])
from_unit = ret.groups()[-1] or "px"
return value * conv2[from_unit]
except (AttributeError, TypeError):
return None
# pylint:disable=invalid-name
class bbox:
"""
A modified bounding box class.
"""
__slots__ = ("isnull", "x1", "x2", "y1", "y2", "xc", "yc", "w", "h", "sbb")
def __init__(self, bb):
"""Initialize bbox."""
if bb is not None:
self.isnull = False
if len(bb) == 2: # allow tuple of two points ((x1,y1),(x2,y2))
self.sbb = [
min(bb[0][0], bb[1][0]),
min(bb[0][1], bb[1][1]),
abs(bb[0][0] - bb[1][0]),
abs(bb[0][1] - bb[1][1]),
]
else:
self.sbb = bb[:] # standard bbox
self.x1, self.y1, self.w, self.h = self.sbb
self.x2 = self.x1 + self.w
self.y2 = self.y1 + self.h
self.xc = (self.x1 + self.x2) / 2
self.yc = (self.y1 + self.y2) / 2
else:
self.isnull = True
def copy(self):
"""Copy the bounding box."""
ret = bbox.__new__(bbox)
ret.isnull = self.isnull
if not self.isnull:
ret.x1 = self.x1
ret.x2 = self.x2
ret.y1 = self.y1
ret.y2 = self.y2
ret.xc = self.xc
ret.yc = self.yc
ret.w = self.w
ret.h = self.h
ret.sbb = self.sbb[:]
return ret
def transform(self, xform):
"""Transform the bounding box."""
if not (self.isnull) and xform is not None:
tr1 = xform.apply_to_point([self.x1, self.y1])
tr2 = xform.apply_to_point([self.x2, self.y2])
tr3 = xform.apply_to_point([self.x1, self.y2])
tr4 = xform.apply_to_point([self.x2, self.y1])
return bbox(
[
min(tr1[0], tr2[0], tr3[0], tr4[0]),
min(tr1[1], tr2[1], tr3[1], tr4[1]),
max(tr1[0], tr2[0], tr3[0], tr4[0])
- min(tr1[0], tr2[0], tr3[0], tr4[0]),
max(tr1[1], tr2[1], tr3[1], tr4[1])
- min(tr1[1], tr2[1], tr3[1], tr4[1]),
]
)
return bbox(None)
def intersect(self, bb2):
"""Check if bounding boxes intersect."""
return (abs(self.xc - bb2.xc) * 2 < (self.w + bb2.w)) and (
abs(self.yc - bb2.yc) * 2 < (self.h + bb2.h)
)
def union(self, bb2):
"""Get the union of two bounding boxes."""
if isinstance(bb2, list):
bb2 = bbox(bb2)
if not (self.isnull) and not bb2.isnull:
minx = min((self.x1, self.x2, bb2.x1, bb2.x2))
maxx = max((self.x1, self.x2, bb2.x1, bb2.x2))
miny = min((self.y1, self.y2, bb2.y1, bb2.y2))
maxy = max((self.y1, self.y2, bb2.y1, bb2.y2))
return bbox([minx, miny, maxx - minx, maxy - miny])
if self.isnull and not bb2.isnull:
return bb2
return self # bb2 is empty
def intersection(self, bb2):
"""Get the intersection of two bounding boxes."""
if isinstance(bb2, list):
bb2 = bbox(bb2)
if not (self.isnull):
minx = max([self.x1, bb2.x1])
maxx = min([self.x2, bb2.x2])
miny = max([self.y1, bb2.y1])
maxy = min([self.y2, bb2.y2])
if maxx < minx or maxy < miny:
return bbox(None)
return bbox([minx, miny, maxx - minx, maxy - miny])
return bbox(bb2.sbb)
def __mul__(self, scl):
"""Scale the bounding box."""
return bbox([self.x1 * scl, self.y1 * scl, self.w * scl, self.h * scl])
# pylint:enable=invalid-name

View file

@ -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)

View file

@ -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.href = 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()

View file

@ -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 ""

View file

@ -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

View file

@ -0,0 +1 @@
This directory is for contents of the site-packages associated with the packaged version of Inkex.

View file

@ -0,0 +1,115 @@
######################## BEGIN LICENSE BLOCK ########################
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from typing import List, Union
from .charsetgroupprober import CharSetGroupProber
from .charsetprober import CharSetProber
from .enums import InputState
from .resultdict import ResultDict
from .universaldetector import UniversalDetector
from .version import VERSION, __version__
__all__ = ["UniversalDetector", "detect", "detect_all", "__version__", "VERSION"]
def detect(
byte_str: Union[bytes, bytearray], should_rename_legacy: bool = False
) -> ResultDict:
"""
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
:param should_rename_legacy: Should we rename legacy encodings
to their more modern equivalents?
:type should_rename_legacy: ``bool``
"""
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError(
f"Expected object of type bytes or bytearray, got: {type(byte_str)}"
)
byte_str = bytearray(byte_str)
detector = UniversalDetector(should_rename_legacy=should_rename_legacy)
detector.feed(byte_str)
return detector.close()
def detect_all(
byte_str: Union[bytes, bytearray],
ignore_threshold: bool = False,
should_rename_legacy: bool = False,
) -> List[ResultDict]:
"""
Detect all the possible encodings of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
:param ignore_threshold: Include encodings that are below
``UniversalDetector.MINIMUM_THRESHOLD``
in results.
:type ignore_threshold: ``bool``
:param should_rename_legacy: Should we rename legacy encodings
to their more modern equivalents?
:type should_rename_legacy: ``bool``
"""
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError(
f"Expected object of type bytes or bytearray, got: {type(byte_str)}"
)
byte_str = bytearray(byte_str)
detector = UniversalDetector(should_rename_legacy=should_rename_legacy)
detector.feed(byte_str)
detector.close()
if detector.input_state == InputState.HIGH_BYTE:
results: List[ResultDict] = []
probers: List[CharSetProber] = []
for prober in detector.charset_probers:
if isinstance(prober, CharSetGroupProber):
probers.extend(p for p in prober.probers)
else:
probers.append(prober)
for prober in probers:
if ignore_threshold or prober.get_confidence() > detector.MINIMUM_THRESHOLD:
charset_name = prober.charset_name or ""
lower_charset_name = charset_name.lower()
# Use Windows encoding name instead of ISO-8859 if we saw any
# extra Windows-specific bytes
if lower_charset_name.startswith("iso-8859") and detector.has_win_bytes:
charset_name = detector.ISO_WIN_MAP.get(
lower_charset_name, charset_name
)
# Rename legacy encodings with superset encodings if asked
if should_rename_legacy:
charset_name = detector.LEGACY_MAP.get(
charset_name.lower(), charset_name
)
results.append(
{
"encoding": charset_name,
"confidence": prober.get_confidence(),
"language": prober.language,
}
)
if len(results) > 0:
return sorted(results, key=lambda result: -result["confidence"])
return [detector.result]

View file

@ -0,0 +1,6 @@
"""Wrapper so people can run python -m chardet"""
from .cli.chardetect import main
if __name__ == "__main__":
main()

View file

@ -0,0 +1,386 @@
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
# Big5 frequency table
# by Taiwan's Mandarin Promotion Council
# <http://www.edu.tw:81/mandr/>
#
# 128 --> 0.42261
# 256 --> 0.57851
# 512 --> 0.74851
# 1024 --> 0.89384
# 2048 --> 0.97583
#
# Ideal Distribution Ratio = 0.74851/(1-0.74851) =2.98
# Random Distribution Ration = 512/(5401-512)=0.105
#
# Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR
BIG5_TYPICAL_DISTRIBUTION_RATIO = 0.75
# Char to FreqOrder table
BIG5_TABLE_SIZE = 5376
# fmt: off
BIG5_CHAR_TO_FREQ_ORDER = (
1,1801,1506, 255,1431, 198, 9, 82, 6,5008, 177, 202,3681,1256,2821, 110, # 16
3814, 33,3274, 261, 76, 44,2114, 16,2946,2187,1176, 659,3971, 26,3451,2653, # 32
1198,3972,3350,4202, 410,2215, 302, 590, 361,1964, 8, 204, 58,4510,5009,1932, # 48
63,5010,5011, 317,1614, 75, 222, 159,4203,2417,1480,5012,3555,3091, 224,2822, # 64
3682, 3, 10,3973,1471, 29,2787,1135,2866,1940, 873, 130,3275,1123, 312,5013, # 80
4511,2052, 507, 252, 682,5014, 142,1915, 124, 206,2947, 34,3556,3204, 64, 604, # 96
5015,2501,1977,1978, 155,1991, 645, 641,1606,5016,3452, 337, 72, 406,5017, 80, # 112
630, 238,3205,1509, 263, 939,1092,2654, 756,1440,1094,3453, 449, 69,2987, 591, # 128
179,2096, 471, 115,2035,1844, 60, 50,2988, 134, 806,1869, 734,2036,3454, 180, # 144
995,1607, 156, 537,2907, 688,5018, 319,1305, 779,2145, 514,2379, 298,4512, 359, # 160
2502, 90,2716,1338, 663, 11, 906,1099,2553, 20,2441, 182, 532,1716,5019, 732, # 176
1376,4204,1311,1420,3206, 25,2317,1056, 113, 399, 382,1950, 242,3455,2474, 529, # 192
3276, 475,1447,3683,5020, 117, 21, 656, 810,1297,2300,2334,3557,5021, 126,4205, # 208
706, 456, 150, 613,4513, 71,1118,2037,4206, 145,3092, 85, 835, 486,2115,1246, # 224
1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,5022,2128,2359, 347,3815, 221, # 240
3558,3135,5023,1956,1153,4207, 83, 296,1199,3093, 192, 624, 93,5024, 822,1898, # 256
2823,3136, 795,2065, 991,1554,1542,1592, 27, 43,2867, 859, 139,1456, 860,4514, # 272
437, 712,3974, 164,2397,3137, 695, 211,3037,2097, 195,3975,1608,3559,3560,3684, # 288
3976, 234, 811,2989,2098,3977,2233,1441,3561,1615,2380, 668,2077,1638, 305, 228, # 304
1664,4515, 467, 415,5025, 262,2099,1593, 239, 108, 300, 200,1033, 512,1247,2078, # 320
5026,5027,2176,3207,3685,2682, 593, 845,1062,3277, 88,1723,2038,3978,1951, 212, # 336
266, 152, 149, 468,1899,4208,4516, 77, 187,5028,3038, 37, 5,2990,5029,3979, # 352
5030,5031, 39,2524,4517,2908,3208,2079, 55, 148, 74,4518, 545, 483,1474,1029, # 368
1665, 217,1870,1531,3138,1104,2655,4209, 24, 172,3562, 900,3980,3563,3564,4519, # 384
32,1408,2824,1312, 329, 487,2360,2251,2717, 784,2683, 4,3039,3351,1427,1789, # 400
188, 109, 499,5032,3686,1717,1790, 888,1217,3040,4520,5033,3565,5034,3352,1520, # 416
3687,3981, 196,1034, 775,5035,5036, 929,1816, 249, 439, 38,5037,1063,5038, 794, # 432
3982,1435,2301, 46, 178,3278,2066,5039,2381,5040, 214,1709,4521, 804, 35, 707, # 448
324,3688,1601,2554, 140, 459,4210,5041,5042,1365, 839, 272, 978,2262,2580,3456, # 464
2129,1363,3689,1423, 697, 100,3094, 48, 70,1231, 495,3139,2196,5043,1294,5044, # 480
2080, 462, 586,1042,3279, 853, 256, 988, 185,2382,3457,1698, 434,1084,5045,3458, # 496
314,2625,2788,4522,2335,2336, 569,2285, 637,1817,2525, 757,1162,1879,1616,3459, # 512
287,1577,2116, 768,4523,1671,2868,3566,2526,1321,3816, 909,2418,5046,4211, 933, # 528
3817,4212,2053,2361,1222,4524, 765,2419,1322, 786,4525,5047,1920,1462,1677,2909, # 544
1699,5048,4526,1424,2442,3140,3690,2600,3353,1775,1941,3460,3983,4213, 309,1369, # 560
1130,2825, 364,2234,1653,1299,3984,3567,3985,3986,2656, 525,1085,3041, 902,2001, # 576
1475, 964,4527, 421,1845,1415,1057,2286, 940,1364,3141, 376,4528,4529,1381, 7, # 592
2527, 983,2383, 336,1710,2684,1846, 321,3461, 559,1131,3042,2752,1809,1132,1313, # 608
265,1481,1858,5049, 352,1203,2826,3280, 167,1089, 420,2827, 776, 792,1724,3568, # 624
4214,2443,3281,5050,4215,5051, 446, 229, 333,2753, 901,3818,1200,1557,4530,2657, # 640
1921, 395,2754,2685,3819,4216,1836, 125, 916,3209,2626,4531,5052,5053,3820,5054, # 656
5055,5056,4532,3142,3691,1133,2555,1757,3462,1510,2318,1409,3569,5057,2146, 438, # 672
2601,2910,2384,3354,1068, 958,3043, 461, 311,2869,2686,4217,1916,3210,4218,1979, # 688
383, 750,2755,2627,4219, 274, 539, 385,1278,1442,5058,1154,1965, 384, 561, 210, # 704
98,1295,2556,3570,5059,1711,2420,1482,3463,3987,2911,1257, 129,5060,3821, 642, # 720
523,2789,2790,2658,5061, 141,2235,1333, 68, 176, 441, 876, 907,4220, 603,2602, # 736
710, 171,3464, 404, 549, 18,3143,2398,1410,3692,1666,5062,3571,4533,2912,4534, # 752
5063,2991, 368,5064, 146, 366, 99, 871,3693,1543, 748, 807,1586,1185, 22,2263, # 768
379,3822,3211,5065,3212, 505,1942,2628,1992,1382,2319,5066, 380,2362, 218, 702, # 784
1818,1248,3465,3044,3572,3355,3282,5067,2992,3694, 930,3283,3823,5068, 59,5069, # 800
585, 601,4221, 497,3466,1112,1314,4535,1802,5070,1223,1472,2177,5071, 749,1837, # 816
690,1900,3824,1773,3988,1476, 429,1043,1791,2236,2117, 917,4222, 447,1086,1629, # 832
5072, 556,5073,5074,2021,1654, 844,1090, 105, 550, 966,1758,2828,1008,1783, 686, # 848
1095,5075,2287, 793,1602,5076,3573,2603,4536,4223,2948,2302,4537,3825, 980,2503, # 864
544, 353, 527,4538, 908,2687,2913,5077, 381,2629,1943,1348,5078,1341,1252, 560, # 880
3095,5079,3467,2870,5080,2054, 973, 886,2081, 143,4539,5081,5082, 157,3989, 496, # 896
4224, 57, 840, 540,2039,4540,4541,3468,2118,1445, 970,2264,1748,1966,2082,4225, # 912
3144,1234,1776,3284,2829,3695, 773,1206,2130,1066,2040,1326,3990,1738,1725,4226, # 928
279,3145, 51,1544,2604, 423,1578,2131,2067, 173,4542,1880,5083,5084,1583, 264, # 944
610,3696,4543,2444, 280, 154,5085,5086,5087,1739, 338,1282,3096, 693,2871,1411, # 960
1074,3826,2445,5088,4544,5089,5090,1240, 952,2399,5091,2914,1538,2688, 685,1483, # 976
4227,2475,1436, 953,4228,2055,4545, 671,2400, 79,4229,2446,3285, 608, 567,2689, # 992
3469,4230,4231,1691, 393,1261,1792,2401,5092,4546,5093,5094,5095,5096,1383,1672, # 1008
3827,3213,1464, 522,1119, 661,1150, 216, 675,4547,3991,1432,3574, 609,4548,2690, # 1024
2402,5097,5098,5099,4232,3045, 0,5100,2476, 315, 231,2447, 301,3356,4549,2385, # 1040
5101, 233,4233,3697,1819,4550,4551,5102, 96,1777,1315,2083,5103, 257,5104,1810, # 1056
3698,2718,1139,1820,4234,2022,1124,2164,2791,1778,2659,5105,3097, 363,1655,3214, # 1072
5106,2993,5107,5108,5109,3992,1567,3993, 718, 103,3215, 849,1443, 341,3357,2949, # 1088
1484,5110,1712, 127, 67, 339,4235,2403, 679,1412, 821,5111,5112, 834, 738, 351, # 1104
2994,2147, 846, 235,1497,1881, 418,1993,3828,2719, 186,1100,2148,2756,3575,1545, # 1120
1355,2950,2872,1377, 583,3994,4236,2581,2995,5113,1298,3699,1078,2557,3700,2363, # 1136
78,3829,3830, 267,1289,2100,2002,1594,4237, 348, 369,1274,2197,2178,1838,4552, # 1152
1821,2830,3701,2757,2288,2003,4553,2951,2758, 144,3358, 882,4554,3995,2759,3470, # 1168
4555,2915,5114,4238,1726, 320,5115,3996,3046, 788,2996,5116,2831,1774,1327,2873, # 1184
3997,2832,5117,1306,4556,2004,1700,3831,3576,2364,2660, 787,2023, 506, 824,3702, # 1200
534, 323,4557,1044,3359,2024,1901, 946,3471,5118,1779,1500,1678,5119,1882,4558, # 1216
165, 243,4559,3703,2528, 123, 683,4239, 764,4560, 36,3998,1793, 589,2916, 816, # 1232
626,1667,3047,2237,1639,1555,1622,3832,3999,5120,4000,2874,1370,1228,1933, 891, # 1248
2084,2917, 304,4240,5121, 292,2997,2720,3577, 691,2101,4241,1115,4561, 118, 662, # 1264
5122, 611,1156, 854,2386,1316,2875, 2, 386, 515,2918,5123,5124,3286, 868,2238, # 1280
1486, 855,2661, 785,2216,3048,5125,1040,3216,3578,5126,3146, 448,5127,1525,5128, # 1296
2165,4562,5129,3833,5130,4242,2833,3579,3147, 503, 818,4001,3148,1568, 814, 676, # 1312
1444, 306,1749,5131,3834,1416,1030, 197,1428, 805,2834,1501,4563,5132,5133,5134, # 1328
1994,5135,4564,5136,5137,2198, 13,2792,3704,2998,3149,1229,1917,5138,3835,2132, # 1344
5139,4243,4565,2404,3580,5140,2217,1511,1727,1120,5141,5142, 646,3836,2448, 307, # 1360
5143,5144,1595,3217,5145,5146,5147,3705,1113,1356,4002,1465,2529,2530,5148, 519, # 1376
5149, 128,2133, 92,2289,1980,5150,4003,1512, 342,3150,2199,5151,2793,2218,1981, # 1392
3360,4244, 290,1656,1317, 789, 827,2365,5152,3837,4566, 562, 581,4004,5153, 401, # 1408
4567,2252, 94,4568,5154,1399,2794,5155,1463,2025,4569,3218,1944,5156, 828,1105, # 1424
4245,1262,1394,5157,4246, 605,4570,5158,1784,2876,5159,2835, 819,2102, 578,2200, # 1440
2952,5160,1502, 436,3287,4247,3288,2836,4005,2919,3472,3473,5161,2721,2320,5162, # 1456
5163,2337,2068, 23,4571, 193, 826,3838,2103, 699,1630,4248,3098, 390,1794,1064, # 1472
3581,5164,1579,3099,3100,1400,5165,4249,1839,1640,2877,5166,4572,4573, 137,4250, # 1488
598,3101,1967, 780, 104, 974,2953,5167, 278, 899, 253, 402, 572, 504, 493,1339, # 1504
5168,4006,1275,4574,2582,2558,5169,3706,3049,3102,2253, 565,1334,2722, 863, 41, # 1520
5170,5171,4575,5172,1657,2338, 19, 463,2760,4251, 606,5173,2999,3289,1087,2085, # 1536
1323,2662,3000,5174,1631,1623,1750,4252,2691,5175,2878, 791,2723,2663,2339, 232, # 1552
2421,5176,3001,1498,5177,2664,2630, 755,1366,3707,3290,3151,2026,1609, 119,1918, # 1568
3474, 862,1026,4253,5178,4007,3839,4576,4008,4577,2265,1952,2477,5179,1125, 817, # 1584
4254,4255,4009,1513,1766,2041,1487,4256,3050,3291,2837,3840,3152,5180,5181,1507, # 1600
5182,2692, 733, 40,1632,1106,2879, 345,4257, 841,2531, 230,4578,3002,1847,3292, # 1616
3475,5183,1263, 986,3476,5184, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562, # 1632
4010,4011,2954, 967,2761,2665,1349, 592,2134,1692,3361,3003,1995,4258,1679,4012, # 1648
1902,2188,5185, 739,3708,2724,1296,1290,5186,4259,2201,2202,1922,1563,2605,2559, # 1664
1871,2762,3004,5187, 435,5188, 343,1108, 596, 17,1751,4579,2239,3477,3709,5189, # 1680
4580, 294,3582,2955,1693, 477, 979, 281,2042,3583, 643,2043,3710,2631,2795,2266, # 1696
1031,2340,2135,2303,3584,4581, 367,1249,2560,5190,3585,5191,4582,1283,3362,2005, # 1712
240,1762,3363,4583,4584, 836,1069,3153, 474,5192,2149,2532, 268,3586,5193,3219, # 1728
1521,1284,5194,1658,1546,4260,5195,3587,3588,5196,4261,3364,2693,1685,4262, 961, # 1744
1673,2632, 190,2006,2203,3841,4585,4586,5197, 570,2504,3711,1490,5198,4587,2633, # 1760
3293,1957,4588, 584,1514, 396,1045,1945,5199,4589,1968,2449,5200,5201,4590,4013, # 1776
619,5202,3154,3294, 215,2007,2796,2561,3220,4591,3221,4592, 763,4263,3842,4593, # 1792
5203,5204,1958,1767,2956,3365,3712,1174, 452,1477,4594,3366,3155,5205,2838,1253, # 1808
2387,2189,1091,2290,4264, 492,5206, 638,1169,1825,2136,1752,4014, 648, 926,1021, # 1824
1324,4595, 520,4596, 997, 847,1007, 892,4597,3843,2267,1872,3713,2405,1785,4598, # 1840
1953,2957,3103,3222,1728,4265,2044,3714,4599,2008,1701,3156,1551, 30,2268,4266, # 1856
5207,2027,4600,3589,5208, 501,5209,4267, 594,3478,2166,1822,3590,3479,3591,3223, # 1872
829,2839,4268,5210,1680,3157,1225,4269,5211,3295,4601,4270,3158,2341,5212,4602, # 1888
4271,5213,4015,4016,5214,1848,2388,2606,3367,5215,4603, 374,4017, 652,4272,4273, # 1904
375,1140, 798,5216,5217,5218,2366,4604,2269, 546,1659, 138,3051,2450,4605,5219, # 1920
2254, 612,1849, 910, 796,3844,1740,1371, 825,3845,3846,5220,2920,2562,5221, 692, # 1936
444,3052,2634, 801,4606,4274,5222,1491, 244,1053,3053,4275,4276, 340,5223,4018, # 1952
1041,3005, 293,1168, 87,1357,5224,1539, 959,5225,2240, 721, 694,4277,3847, 219, # 1968
1478, 644,1417,3368,2666,1413,1401,1335,1389,4019,5226,5227,3006,2367,3159,1826, # 1984
730,1515, 184,2840, 66,4607,5228,1660,2958, 246,3369, 378,1457, 226,3480, 975, # 2000
4020,2959,1264,3592, 674, 696,5229, 163,5230,1141,2422,2167, 713,3593,3370,4608, # 2016
4021,5231,5232,1186, 15,5233,1079,1070,5234,1522,3224,3594, 276,1050,2725, 758, # 2032
1126, 653,2960,3296,5235,2342, 889,3595,4022,3104,3007, 903,1250,4609,4023,3481, # 2048
3596,1342,1681,1718, 766,3297, 286, 89,2961,3715,5236,1713,5237,2607,3371,3008, # 2064
5238,2962,2219,3225,2880,5239,4610,2505,2533, 181, 387,1075,4024, 731,2190,3372, # 2080
5240,3298, 310, 313,3482,2304, 770,4278, 54,3054, 189,4611,3105,3848,4025,5241, # 2096
1230,1617,1850, 355,3597,4279,4612,3373, 111,4280,3716,1350,3160,3483,3055,4281, # 2112
2150,3299,3598,5242,2797,4026,4027,3009, 722,2009,5243,1071, 247,1207,2343,2478, # 2128
1378,4613,2010, 864,1437,1214,4614, 373,3849,1142,2220, 667,4615, 442,2763,2563, # 2144
3850,4028,1969,4282,3300,1840, 837, 170,1107, 934,1336,1883,5244,5245,2119,4283, # 2160
2841, 743,1569,5246,4616,4284, 582,2389,1418,3484,5247,1803,5248, 357,1395,1729, # 2176
3717,3301,2423,1564,2241,5249,3106,3851,1633,4617,1114,2086,4285,1532,5250, 482, # 2192
2451,4618,5251,5252,1492, 833,1466,5253,2726,3599,1641,2842,5254,1526,1272,3718, # 2208
4286,1686,1795, 416,2564,1903,1954,1804,5255,3852,2798,3853,1159,2321,5256,2881, # 2224
4619,1610,1584,3056,2424,2764, 443,3302,1163,3161,5257,5258,4029,5259,4287,2506, # 2240
3057,4620,4030,3162,2104,1647,3600,2011,1873,4288,5260,4289, 431,3485,5261, 250, # 2256
97, 81,4290,5262,1648,1851,1558, 160, 848,5263, 866, 740,1694,5264,2204,2843, # 2272
3226,4291,4621,3719,1687, 950,2479, 426, 469,3227,3720,3721,4031,5265,5266,1188, # 2288
424,1996, 861,3601,4292,3854,2205,2694, 168,1235,3602,4293,5267,2087,1674,4622, # 2304
3374,3303, 220,2565,1009,5268,3855, 670,3010, 332,1208, 717,5269,5270,3603,2452, # 2320
4032,3375,5271, 513,5272,1209,2882,3376,3163,4623,1080,5273,5274,5275,5276,2534, # 2336
3722,3604, 815,1587,4033,4034,5277,3605,3486,3856,1254,4624,1328,3058,1390,4035, # 2352
1741,4036,3857,4037,5278, 236,3858,2453,3304,5279,5280,3723,3859,1273,3860,4625, # 2368
5281, 308,5282,4626, 245,4627,1852,2480,1307,2583, 430, 715,2137,2454,5283, 270, # 2384
199,2883,4038,5284,3606,2727,1753, 761,1754, 725,1661,1841,4628,3487,3724,5285, # 2400
5286, 587, 14,3305, 227,2608, 326, 480,2270, 943,2765,3607, 291, 650,1884,5287, # 2416
1702,1226, 102,1547, 62,3488, 904,4629,3489,1164,4294,5288,5289,1224,1548,2766, # 2432
391, 498,1493,5290,1386,1419,5291,2056,1177,4630, 813, 880,1081,2368, 566,1145, # 2448
4631,2291,1001,1035,2566,2609,2242, 394,1286,5292,5293,2069,5294, 86,1494,1730, # 2464
4039, 491,1588, 745, 897,2963, 843,3377,4040,2767,2884,3306,1768, 998,2221,2070, # 2480
397,1827,1195,1970,3725,3011,3378, 284,5295,3861,2507,2138,2120,1904,5296,4041, # 2496
2151,4042,4295,1036,3490,1905, 114,2567,4296, 209,1527,5297,5298,2964,2844,2635, # 2512
2390,2728,3164, 812,2568,5299,3307,5300,1559, 737,1885,3726,1210, 885, 28,2695, # 2528
3608,3862,5301,4297,1004,1780,4632,5302, 346,1982,2222,2696,4633,3863,1742, 797, # 2544
1642,4043,1934,1072,1384,2152, 896,4044,3308,3727,3228,2885,3609,5303,2569,1959, # 2560
4634,2455,1786,5304,5305,5306,4045,4298,1005,1308,3728,4299,2729,4635,4636,1528, # 2576
2610, 161,1178,4300,1983, 987,4637,1101,4301, 631,4046,1157,3229,2425,1343,1241, # 2592
1016,2243,2570, 372, 877,2344,2508,1160, 555,1935, 911,4047,5307, 466,1170, 169, # 2608
1051,2921,2697,3729,2481,3012,1182,2012,2571,1251,2636,5308, 992,2345,3491,1540, # 2624
2730,1201,2071,2406,1997,2482,5309,4638, 528,1923,2191,1503,1874,1570,2369,3379, # 2640
3309,5310, 557,1073,5311,1828,3492,2088,2271,3165,3059,3107, 767,3108,2799,4639, # 2656
1006,4302,4640,2346,1267,2179,3730,3230, 778,4048,3231,2731,1597,2667,5312,4641, # 2672
5313,3493,5314,5315,5316,3310,2698,1433,3311, 131, 95,1504,4049, 723,4303,3166, # 2688
1842,3610,2768,2192,4050,2028,2105,3731,5317,3013,4051,1218,5318,3380,3232,4052, # 2704
4304,2584, 248,1634,3864, 912,5319,2845,3732,3060,3865, 654, 53,5320,3014,5321, # 2720
1688,4642, 777,3494,1032,4053,1425,5322, 191, 820,2121,2846, 971,4643, 931,3233, # 2736
135, 664, 783,3866,1998, 772,2922,1936,4054,3867,4644,2923,3234, 282,2732, 640, # 2752
1372,3495,1127, 922, 325,3381,5323,5324, 711,2045,5325,5326,4055,2223,2800,1937, # 2768
4056,3382,2224,2255,3868,2305,5327,4645,3869,1258,3312,4057,3235,2139,2965,4058, # 2784
4059,5328,2225, 258,3236,4646, 101,1227,5329,3313,1755,5330,1391,3314,5331,2924, # 2800
2057, 893,5332,5333,5334,1402,4305,2347,5335,5336,3237,3611,5337,5338, 878,1325, # 2816
1781,2801,4647, 259,1385,2585, 744,1183,2272,4648,5339,4060,2509,5340, 684,1024, # 2832
4306,5341, 472,3612,3496,1165,3315,4061,4062, 322,2153, 881, 455,1695,1152,1340, # 2848
660, 554,2154,4649,1058,4650,4307, 830,1065,3383,4063,4651,1924,5342,1703,1919, # 2864
5343, 932,2273, 122,5344,4652, 947, 677,5345,3870,2637, 297,1906,1925,2274,4653, # 2880
2322,3316,5346,5347,4308,5348,4309, 84,4310, 112, 989,5349, 547,1059,4064, 701, # 2896
3613,1019,5350,4311,5351,3497, 942, 639, 457,2306,2456, 993,2966, 407, 851, 494, # 2912
4654,3384, 927,5352,1237,5353,2426,3385, 573,4312, 680, 921,2925,1279,1875, 285, # 2928
790,1448,1984, 719,2168,5354,5355,4655,4065,4066,1649,5356,1541, 563,5357,1077, # 2944
5358,3386,3061,3498, 511,3015,4067,4068,3733,4069,1268,2572,3387,3238,4656,4657, # 2960
5359, 535,1048,1276,1189,2926,2029,3167,1438,1373,2847,2967,1134,2013,5360,4313, # 2976
1238,2586,3109,1259,5361, 700,5362,2968,3168,3734,4314,5363,4315,1146,1876,1907, # 2992
4658,2611,4070, 781,2427, 132,1589, 203, 147, 273,2802,2407, 898,1787,2155,4071, # 3008
4072,5364,3871,2803,5365,5366,4659,4660,5367,3239,5368,1635,3872, 965,5369,1805, # 3024
2699,1516,3614,1121,1082,1329,3317,4073,1449,3873, 65,1128,2848,2927,2769,1590, # 3040
3874,5370,5371, 12,2668, 45, 976,2587,3169,4661, 517,2535,1013,1037,3240,5372, # 3056
3875,2849,5373,3876,5374,3499,5375,2612, 614,1999,2323,3877,3110,2733,2638,5376, # 3072
2588,4316, 599,1269,5377,1811,3735,5378,2700,3111, 759,1060, 489,1806,3388,3318, # 3088
1358,5379,5380,2391,1387,1215,2639,2256, 490,5381,5382,4317,1759,2392,2348,5383, # 3104
4662,3878,1908,4074,2640,1807,3241,4663,3500,3319,2770,2349, 874,5384,5385,3501, # 3120
3736,1859, 91,2928,3737,3062,3879,4664,5386,3170,4075,2669,5387,3502,1202,1403, # 3136
3880,2969,2536,1517,2510,4665,3503,2511,5388,4666,5389,2701,1886,1495,1731,4076, # 3152
2370,4667,5390,2030,5391,5392,4077,2702,1216, 237,2589,4318,2324,4078,3881,4668, # 3168
4669,2703,3615,3504, 445,4670,5393,5394,5395,5396,2771, 61,4079,3738,1823,4080, # 3184
5397, 687,2046, 935, 925, 405,2670, 703,1096,1860,2734,4671,4081,1877,1367,2704, # 3200
3389, 918,2106,1782,2483, 334,3320,1611,1093,4672, 564,3171,3505,3739,3390, 945, # 3216
2641,2058,4673,5398,1926, 872,4319,5399,3506,2705,3112, 349,4320,3740,4082,4674, # 3232
3882,4321,3741,2156,4083,4675,4676,4322,4677,2408,2047, 782,4084, 400, 251,4323, # 3248
1624,5400,5401, 277,3742, 299,1265, 476,1191,3883,2122,4324,4325,1109, 205,5402, # 3264
2590,1000,2157,3616,1861,5403,5404,5405,4678,5406,4679,2573, 107,2484,2158,4085, # 3280
3507,3172,5407,1533, 541,1301, 158, 753,4326,2886,3617,5408,1696, 370,1088,4327, # 3296
4680,3618, 579, 327, 440, 162,2244, 269,1938,1374,3508, 968,3063, 56,1396,3113, # 3312
2107,3321,3391,5409,1927,2159,4681,3016,5410,3619,5411,5412,3743,4682,2485,5413, # 3328
2804,5414,1650,4683,5415,2613,5416,5417,4086,2671,3392,1149,3393,4087,3884,4088, # 3344
5418,1076, 49,5419, 951,3242,3322,3323, 450,2850, 920,5420,1812,2805,2371,4328, # 3360
1909,1138,2372,3885,3509,5421,3243,4684,1910,1147,1518,2428,4685,3886,5422,4686, # 3376
2393,2614, 260,1796,3244,5423,5424,3887,3324, 708,5425,3620,1704,5426,3621,1351, # 3392
1618,3394,3017,1887, 944,4329,3395,4330,3064,3396,4331,5427,3744, 422, 413,1714, # 3408
3325, 500,2059,2350,4332,2486,5428,1344,1911, 954,5429,1668,5430,5431,4089,2409, # 3424
4333,3622,3888,4334,5432,2307,1318,2512,3114, 133,3115,2887,4687, 629, 31,2851, # 3440
2706,3889,4688, 850, 949,4689,4090,2970,1732,2089,4335,1496,1853,5433,4091, 620, # 3456
3245, 981,1242,3745,3397,1619,3746,1643,3326,2140,2457,1971,1719,3510,2169,5434, # 3472
3246,5435,5436,3398,1829,5437,1277,4690,1565,2048,5438,1636,3623,3116,5439, 869, # 3488
2852, 655,3890,3891,3117,4092,3018,3892,1310,3624,4691,5440,5441,5442,1733, 558, # 3504
4692,3747, 335,1549,3065,1756,4336,3748,1946,3511,1830,1291,1192, 470,2735,2108, # 3520
2806, 913,1054,4093,5443,1027,5444,3066,4094,4693, 982,2672,3399,3173,3512,3247, # 3536
3248,1947,2807,5445, 571,4694,5446,1831,5447,3625,2591,1523,2429,5448,2090, 984, # 3552
4695,3749,1960,5449,3750, 852, 923,2808,3513,3751, 969,1519, 999,2049,2325,1705, # 3568
5450,3118, 615,1662, 151, 597,4095,2410,2326,1049, 275,4696,3752,4337, 568,3753, # 3584
3626,2487,4338,3754,5451,2430,2275, 409,3249,5452,1566,2888,3514,1002, 769,2853, # 3600
194,2091,3174,3755,2226,3327,4339, 628,1505,5453,5454,1763,2180,3019,4096, 521, # 3616
1161,2592,1788,2206,2411,4697,4097,1625,4340,4341, 412, 42,3119, 464,5455,2642, # 3632
4698,3400,1760,1571,2889,3515,2537,1219,2207,3893,2643,2141,2373,4699,4700,3328, # 3648
1651,3401,3627,5456,5457,3628,2488,3516,5458,3756,5459,5460,2276,2092, 460,5461, # 3664
4701,5462,3020, 962, 588,3629, 289,3250,2644,1116, 52,5463,3067,1797,5464,5465, # 3680
5466,1467,5467,1598,1143,3757,4342,1985,1734,1067,4702,1280,3402, 465,4703,1572, # 3696
510,5468,1928,2245,1813,1644,3630,5469,4704,3758,5470,5471,2673,1573,1534,5472, # 3712
5473, 536,1808,1761,3517,3894,3175,2645,5474,5475,5476,4705,3518,2929,1912,2809, # 3728
5477,3329,1122, 377,3251,5478, 360,5479,5480,4343,1529, 551,5481,2060,3759,1769, # 3744
2431,5482,2930,4344,3330,3120,2327,2109,2031,4706,1404, 136,1468,1479, 672,1171, # 3760
3252,2308, 271,3176,5483,2772,5484,2050, 678,2736, 865,1948,4707,5485,2014,4098, # 3776
2971,5486,2737,2227,1397,3068,3760,4708,4709,1735,2931,3403,3631,5487,3895, 509, # 3792
2854,2458,2890,3896,5488,5489,3177,3178,4710,4345,2538,4711,2309,1166,1010, 552, # 3808
681,1888,5490,5491,2972,2973,4099,1287,1596,1862,3179, 358, 453, 736, 175, 478, # 3824
1117, 905,1167,1097,5492,1854,1530,5493,1706,5494,2181,3519,2292,3761,3520,3632, # 3840
4346,2093,4347,5495,3404,1193,2489,4348,1458,2193,2208,1863,1889,1421,3331,2932, # 3856
3069,2182,3521, 595,2123,5496,4100,5497,5498,4349,1707,2646, 223,3762,1359, 751, # 3872
3121, 183,3522,5499,2810,3021, 419,2374, 633, 704,3897,2394, 241,5500,5501,5502, # 3888
838,3022,3763,2277,2773,2459,3898,1939,2051,4101,1309,3122,2246,1181,5503,1136, # 3904
2209,3899,2375,1446,4350,2310,4712,5504,5505,4351,1055,2615, 484,3764,5506,4102, # 3920
625,4352,2278,3405,1499,4353,4103,5507,4104,4354,3253,2279,2280,3523,5508,5509, # 3936
2774, 808,2616,3765,3406,4105,4355,3123,2539, 526,3407,3900,4356, 955,5510,1620, # 3952
4357,2647,2432,5511,1429,3766,1669,1832, 994, 928,5512,3633,1260,5513,5514,5515, # 3968
1949,2293, 741,2933,1626,4358,2738,2460, 867,1184, 362,3408,1392,5516,5517,4106, # 3984
4359,1770,1736,3254,2934,4713,4714,1929,2707,1459,1158,5518,3070,3409,2891,1292, # 4000
1930,2513,2855,3767,1986,1187,2072,2015,2617,4360,5519,2574,2514,2170,3768,2490, # 4016
3332,5520,3769,4715,5521,5522, 666,1003,3023,1022,3634,4361,5523,4716,1814,2257, # 4032
574,3901,1603, 295,1535, 705,3902,4362, 283, 858, 417,5524,5525,3255,4717,4718, # 4048
3071,1220,1890,1046,2281,2461,4107,1393,1599, 689,2575, 388,4363,5526,2491, 802, # 4064
5527,2811,3903,2061,1405,2258,5528,4719,3904,2110,1052,1345,3256,1585,5529, 809, # 4080
5530,5531,5532, 575,2739,3524, 956,1552,1469,1144,2328,5533,2329,1560,2462,3635, # 4096
3257,4108, 616,2210,4364,3180,2183,2294,5534,1833,5535,3525,4720,5536,1319,3770, # 4112
3771,1211,3636,1023,3258,1293,2812,5537,5538,5539,3905, 607,2311,3906, 762,2892, # 4128
1439,4365,1360,4721,1485,3072,5540,4722,1038,4366,1450,2062,2648,4367,1379,4723, # 4144
2593,5541,5542,4368,1352,1414,2330,2935,1172,5543,5544,3907,3908,4724,1798,1451, # 4160
5545,5546,5547,5548,2936,4109,4110,2492,2351, 411,4111,4112,3637,3333,3124,4725, # 4176
1561,2674,1452,4113,1375,5549,5550, 47,2974, 316,5551,1406,1591,2937,3181,5552, # 4192
1025,2142,3125,3182, 354,2740, 884,2228,4369,2412, 508,3772, 726,3638, 996,2433, # 4208
3639, 729,5553, 392,2194,1453,4114,4726,3773,5554,5555,2463,3640,2618,1675,2813, # 4224
919,2352,2975,2353,1270,4727,4115, 73,5556,5557, 647,5558,3259,2856,2259,1550, # 4240
1346,3024,5559,1332, 883,3526,5560,5561,5562,5563,3334,2775,5564,1212, 831,1347, # 4256
4370,4728,2331,3909,1864,3073, 720,3910,4729,4730,3911,5565,4371,5566,5567,4731, # 4272
5568,5569,1799,4732,3774,2619,4733,3641,1645,2376,4734,5570,2938, 669,2211,2675, # 4288
2434,5571,2893,5572,5573,1028,3260,5574,4372,2413,5575,2260,1353,5576,5577,4735, # 4304
3183, 518,5578,4116,5579,4373,1961,5580,2143,4374,5581,5582,3025,2354,2355,3912, # 4320
516,1834,1454,4117,2708,4375,4736,2229,2620,1972,1129,3642,5583,2776,5584,2976, # 4336
1422, 577,1470,3026,1524,3410,5585,5586, 432,4376,3074,3527,5587,2594,1455,2515, # 4352
2230,1973,1175,5588,1020,2741,4118,3528,4737,5589,2742,5590,1743,1361,3075,3529, # 4368
2649,4119,4377,4738,2295, 895, 924,4378,2171, 331,2247,3076, 166,1627,3077,1098, # 4384
5591,1232,2894,2231,3411,4739, 657, 403,1196,2377, 542,3775,3412,1600,4379,3530, # 4400
5592,4740,2777,3261, 576, 530,1362,4741,4742,2540,2676,3776,4120,5593, 842,3913, # 4416
5594,2814,2032,1014,4121, 213,2709,3413, 665, 621,4380,5595,3777,2939,2435,5596, # 4432
2436,3335,3643,3414,4743,4381,2541,4382,4744,3644,1682,4383,3531,1380,5597, 724, # 4448
2282, 600,1670,5598,1337,1233,4745,3126,2248,5599,1621,4746,5600, 651,4384,5601, # 4464
1612,4385,2621,5602,2857,5603,2743,2312,3078,5604, 716,2464,3079, 174,1255,2710, # 4480
4122,3645, 548,1320,1398, 728,4123,1574,5605,1891,1197,3080,4124,5606,3081,3082, # 4496
3778,3646,3779, 747,5607, 635,4386,4747,5608,5609,5610,4387,5611,5612,4748,5613, # 4512
3415,4749,2437, 451,5614,3780,2542,2073,4388,2744,4389,4125,5615,1764,4750,5616, # 4528
4390, 350,4751,2283,2395,2493,5617,4391,4126,2249,1434,4127, 488,4752, 458,4392, # 4544
4128,3781, 771,1330,2396,3914,2576,3184,2160,2414,1553,2677,3185,4393,5618,2494, # 4560
2895,2622,1720,2711,4394,3416,4753,5619,2543,4395,5620,3262,4396,2778,5621,2016, # 4576
2745,5622,1155,1017,3782,3915,5623,3336,2313, 201,1865,4397,1430,5624,4129,5625, # 4592
5626,5627,5628,5629,4398,1604,5630, 414,1866, 371,2595,4754,4755,3532,2017,3127, # 4608
4756,1708, 960,4399, 887, 389,2172,1536,1663,1721,5631,2232,4130,2356,2940,1580, # 4624
5632,5633,1744,4757,2544,4758,4759,5634,4760,5635,2074,5636,4761,3647,3417,2896, # 4640
4400,5637,4401,2650,3418,2815, 673,2712,2465, 709,3533,4131,3648,4402,5638,1148, # 4656
502, 634,5639,5640,1204,4762,3649,1575,4763,2623,3783,5641,3784,3128, 948,3263, # 4672
121,1745,3916,1110,5642,4403,3083,2516,3027,4132,3785,1151,1771,3917,1488,4133, # 4688
1987,5643,2438,3534,5644,5645,2094,5646,4404,3918,1213,1407,2816, 531,2746,2545, # 4704
3264,1011,1537,4764,2779,4405,3129,1061,5647,3786,3787,1867,2897,5648,2018, 120, # 4720
4406,4407,2063,3650,3265,2314,3919,2678,3419,1955,4765,4134,5649,3535,1047,2713, # 4736
1266,5650,1368,4766,2858, 649,3420,3920,2546,2747,1102,2859,2679,5651,5652,2000, # 4752
5653,1111,3651,2977,5654,2495,3921,3652,2817,1855,3421,3788,5655,5656,3422,2415, # 4768
2898,3337,3266,3653,5657,2577,5658,3654,2818,4135,1460, 856,5659,3655,5660,2899, # 4784
2978,5661,2900,3922,5662,4408, 632,2517, 875,3923,1697,3924,2296,5663,5664,4767, # 4800
3028,1239, 580,4768,4409,5665, 914, 936,2075,1190,4136,1039,2124,5666,5667,5668, # 4816
5669,3423,1473,5670,1354,4410,3925,4769,2173,3084,4137, 915,3338,4411,4412,3339, # 4832
1605,1835,5671,2748, 398,3656,4413,3926,4138, 328,1913,2860,4139,3927,1331,4414, # 4848
3029, 937,4415,5672,3657,4140,4141,3424,2161,4770,3425, 524, 742, 538,3085,1012, # 4864
5673,5674,3928,2466,5675, 658,1103, 225,3929,5676,5677,4771,5678,4772,5679,3267, # 4880
1243,5680,4142, 963,2250,4773,5681,2714,3658,3186,5682,5683,2596,2332,5684,4774, # 4896
5685,5686,5687,3536, 957,3426,2547,2033,1931,2941,2467, 870,2019,3659,1746,2780, # 4912
2781,2439,2468,5688,3930,5689,3789,3130,3790,3537,3427,3791,5690,1179,3086,5691, # 4928
3187,2378,4416,3792,2548,3188,3131,2749,4143,5692,3428,1556,2549,2297, 977,2901, # 4944
2034,4144,1205,3429,5693,1765,3430,3189,2125,1271, 714,1689,4775,3538,5694,2333, # 4960
3931, 533,4417,3660,2184, 617,5695,2469,3340,3539,2315,5696,5697,3190,5698,5699, # 4976
3932,1988, 618, 427,2651,3540,3431,5700,5701,1244,1690,5702,2819,4418,4776,5703, # 4992
3541,4777,5704,2284,1576, 473,3661,4419,3432, 972,5705,3662,5706,3087,5707,5708, # 5008
4778,4779,5709,3793,4145,4146,5710, 153,4780, 356,5711,1892,2902,4420,2144, 408, # 5024
803,2357,5712,3933,5713,4421,1646,2578,2518,4781,4782,3934,5714,3935,4422,5715, # 5040
2416,3433, 752,5716,5717,1962,3341,2979,5718, 746,3030,2470,4783,4423,3794, 698, # 5056
4784,1893,4424,3663,2550,4785,3664,3936,5719,3191,3434,5720,1824,1302,4147,2715, # 5072
3937,1974,4425,5721,4426,3192, 823,1303,1288,1236,2861,3542,4148,3435, 774,3938, # 5088
5722,1581,4786,1304,2862,3939,4787,5723,2440,2162,1083,3268,4427,4149,4428, 344, # 5104
1173, 288,2316, 454,1683,5724,5725,1461,4788,4150,2597,5726,5727,4789, 985, 894, # 5120
5728,3436,3193,5729,1914,2942,3795,1989,5730,2111,1975,5731,4151,5732,2579,1194, # 5136
425,5733,4790,3194,1245,3796,4429,5734,5735,2863,5736, 636,4791,1856,3940, 760, # 5152
1800,5737,4430,2212,1508,4792,4152,1894,1684,2298,5738,5739,4793,4431,4432,2213, # 5168
479,5740,5741, 832,5742,4153,2496,5743,2980,2497,3797, 990,3132, 627,1815,2652, # 5184
4433,1582,4434,2126,2112,3543,4794,5744, 799,4435,3195,5745,4795,2113,1737,3031, # 5200
1018, 543, 754,4436,3342,1676,4796,4797,4154,4798,1489,5746,3544,5747,2624,2903, # 5216
4155,5748,5749,2981,5750,5751,5752,5753,3196,4799,4800,2185,1722,5754,3269,3270, # 5232
1843,3665,1715, 481, 365,1976,1857,5755,5756,1963,2498,4801,5757,2127,3666,3271, # 5248
433,1895,2064,2076,5758, 602,2750,5759,5760,5761,5762,5763,3032,1628,3437,5764, # 5264
3197,4802,4156,2904,4803,2519,5765,2551,2782,5766,5767,5768,3343,4804,2905,5769, # 5280
4805,5770,2864,4806,4807,1221,2982,4157,2520,5771,5772,5773,1868,1990,5774,5775, # 5296
5776,1896,5777,5778,4808,1897,4158, 318,5779,2095,4159,4437,5780,5781, 485,5782, # 5312
938,3941, 553,2680, 116,5783,3942,3667,5784,3545,2681,2783,3438,3344,2820,5785, # 5328
3668,2943,4160,1747,2944,2983,5786,5787, 207,5788,4809,5789,4810,2521,5790,3033, # 5344
890,3669,3943,5791,1878,3798,3439,5792,2186,2358,3440,1652,5793,5794,5795, 941, # 5360
2299, 208,3546,4161,2020, 330,4438,3944,2906,2499,3799,4439,4811,5796,5797,5798, # 5376
)
# fmt: on

View file

@ -0,0 +1,47 @@
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .chardistribution import Big5DistributionAnalysis
from .codingstatemachine import CodingStateMachine
from .mbcharsetprober import MultiByteCharSetProber
from .mbcssm import BIG5_SM_MODEL
class Big5Prober(MultiByteCharSetProber):
def __init__(self) -> None:
super().__init__()
self.coding_sm = CodingStateMachine(BIG5_SM_MODEL)
self.distribution_analyzer = Big5DistributionAnalysis()
self.reset()
@property
def charset_name(self) -> str:
return "Big5"
@property
def language(self) -> str:
return "Chinese"

View file

@ -0,0 +1,261 @@
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from typing import Tuple, Union
from .big5freq import (
BIG5_CHAR_TO_FREQ_ORDER,
BIG5_TABLE_SIZE,
BIG5_TYPICAL_DISTRIBUTION_RATIO,
)
from .euckrfreq import (
EUCKR_CHAR_TO_FREQ_ORDER,
EUCKR_TABLE_SIZE,
EUCKR_TYPICAL_DISTRIBUTION_RATIO,
)
from .euctwfreq import (
EUCTW_CHAR_TO_FREQ_ORDER,
EUCTW_TABLE_SIZE,
EUCTW_TYPICAL_DISTRIBUTION_RATIO,
)
from .gb2312freq import (
GB2312_CHAR_TO_FREQ_ORDER,
GB2312_TABLE_SIZE,
GB2312_TYPICAL_DISTRIBUTION_RATIO,
)
from .jisfreq import (
JIS_CHAR_TO_FREQ_ORDER,
JIS_TABLE_SIZE,
JIS_TYPICAL_DISTRIBUTION_RATIO,
)
from .johabfreq import JOHAB_TO_EUCKR_ORDER_TABLE
class CharDistributionAnalysis:
ENOUGH_DATA_THRESHOLD = 1024
SURE_YES = 0.99
SURE_NO = 0.01
MINIMUM_DATA_THRESHOLD = 3
def __init__(self) -> None:
# Mapping table to get frequency order from char order (get from
# GetOrder())
self._char_to_freq_order: Tuple[int, ...] = tuple()
self._table_size = 0 # Size of above table
# This is a constant value which varies from language to language,
# used in calculating confidence. See
# http://www.mozilla.org/projects/intl/UniversalCharsetDetection.html
# for further detail.
self.typical_distribution_ratio = 0.0
self._done = False
self._total_chars = 0
self._freq_chars = 0
self.reset()
def reset(self) -> None:
"""reset analyser, clear any state"""
# If this flag is set to True, detection is done and conclusion has
# been made
self._done = False
self._total_chars = 0 # Total characters encountered
# The number of characters whose frequency order is less than 512
self._freq_chars = 0
def feed(self, char: Union[bytes, bytearray], char_len: int) -> None:
"""feed a character with known length"""
if char_len == 2:
# we only care about 2-bytes character in our distribution analysis
order = self.get_order(char)
else:
order = -1
if order >= 0:
self._total_chars += 1
# order is valid
if order < self._table_size:
if 512 > self._char_to_freq_order[order]:
self._freq_chars += 1
def get_confidence(self) -> float:
"""return confidence based on existing data"""
# if we didn't receive any character in our consideration range,
# return negative answer
if self._total_chars <= 0 or self._freq_chars <= self.MINIMUM_DATA_THRESHOLD:
return self.SURE_NO
if self._total_chars != self._freq_chars:
r = self._freq_chars / (
(self._total_chars - self._freq_chars) * self.typical_distribution_ratio
)
if r < self.SURE_YES:
return r
# normalize confidence (we don't want to be 100% sure)
return self.SURE_YES
def got_enough_data(self) -> bool:
# It is not necessary to receive all data to draw conclusion.
# For charset detection, certain amount of data is enough
return self._total_chars > self.ENOUGH_DATA_THRESHOLD
def get_order(self, _: Union[bytes, bytearray]) -> int:
# We do not handle characters based on the original encoding string,
# but convert this encoding string to a number, here called order.
# This allows multiple encodings of a language to share one frequency
# table.
return -1
class EUCTWDistributionAnalysis(CharDistributionAnalysis):
def __init__(self) -> None:
super().__init__()
self._char_to_freq_order = EUCTW_CHAR_TO_FREQ_ORDER
self._table_size = EUCTW_TABLE_SIZE
self.typical_distribution_ratio = EUCTW_TYPICAL_DISTRIBUTION_RATIO
def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
# for euc-TW encoding, we are interested
# first byte range: 0xc4 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
first_char = byte_str[0]
if first_char >= 0xC4:
return 94 * (first_char - 0xC4) + byte_str[1] - 0xA1
return -1
class EUCKRDistributionAnalysis(CharDistributionAnalysis):
def __init__(self) -> None:
super().__init__()
self._char_to_freq_order = EUCKR_CHAR_TO_FREQ_ORDER
self._table_size = EUCKR_TABLE_SIZE
self.typical_distribution_ratio = EUCKR_TYPICAL_DISTRIBUTION_RATIO
def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
# for euc-KR encoding, we are interested
# first byte range: 0xb0 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
first_char = byte_str[0]
if first_char >= 0xB0:
return 94 * (first_char - 0xB0) + byte_str[1] - 0xA1
return -1
class JOHABDistributionAnalysis(CharDistributionAnalysis):
def __init__(self) -> None:
super().__init__()
self._char_to_freq_order = EUCKR_CHAR_TO_FREQ_ORDER
self._table_size = EUCKR_TABLE_SIZE
self.typical_distribution_ratio = EUCKR_TYPICAL_DISTRIBUTION_RATIO
def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
first_char = byte_str[0]
if 0x88 <= first_char < 0xD4:
code = first_char * 256 + byte_str[1]
return JOHAB_TO_EUCKR_ORDER_TABLE.get(code, -1)
return -1
class GB2312DistributionAnalysis(CharDistributionAnalysis):
def __init__(self) -> None:
super().__init__()
self._char_to_freq_order = GB2312_CHAR_TO_FREQ_ORDER
self._table_size = GB2312_TABLE_SIZE
self.typical_distribution_ratio = GB2312_TYPICAL_DISTRIBUTION_RATIO
def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
# for GB2312 encoding, we are interested
# first byte range: 0xb0 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
first_char, second_char = byte_str[0], byte_str[1]
if (first_char >= 0xB0) and (second_char >= 0xA1):
return 94 * (first_char - 0xB0) + second_char - 0xA1
return -1
class Big5DistributionAnalysis(CharDistributionAnalysis):
def __init__(self) -> None:
super().__init__()
self._char_to_freq_order = BIG5_CHAR_TO_FREQ_ORDER
self._table_size = BIG5_TABLE_SIZE
self.typical_distribution_ratio = BIG5_TYPICAL_DISTRIBUTION_RATIO
def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
# for big5 encoding, we are interested
# first byte range: 0xa4 -- 0xfe
# second byte range: 0x40 -- 0x7e , 0xa1 -- 0xfe
# no validation needed here. State machine has done that
first_char, second_char = byte_str[0], byte_str[1]
if first_char >= 0xA4:
if second_char >= 0xA1:
return 157 * (first_char - 0xA4) + second_char - 0xA1 + 63
return 157 * (first_char - 0xA4) + second_char - 0x40
return -1
class SJISDistributionAnalysis(CharDistributionAnalysis):
def __init__(self) -> None:
super().__init__()
self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER
self._table_size = JIS_TABLE_SIZE
self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO
def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
# for sjis encoding, we are interested
# first byte range: 0x81 -- 0x9f , 0xe0 -- 0xfe
# second byte range: 0x40 -- 0x7e, 0x81 -- oxfe
# no validation needed here. State machine has done that
first_char, second_char = byte_str[0], byte_str[1]
if 0x81 <= first_char <= 0x9F:
order = 188 * (first_char - 0x81)
elif 0xE0 <= first_char <= 0xEF:
order = 188 * (first_char - 0xE0 + 31)
else:
return -1
order = order + second_char - 0x40
if second_char > 0x7F:
order = -1
return order
class EUCJPDistributionAnalysis(CharDistributionAnalysis):
def __init__(self) -> None:
super().__init__()
self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER
self._table_size = JIS_TABLE_SIZE
self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO
def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
# for euc-JP encoding, we are interested
# first byte range: 0xa0 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
char = byte_str[0]
if char >= 0xA0:
return 94 * (char - 0xA1) + byte_str[1] - 0xA1
return -1

View file

@ -0,0 +1,106 @@
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from typing import List, Optional, Union
from .charsetprober import CharSetProber
from .enums import LanguageFilter, ProbingState
class CharSetGroupProber(CharSetProber):
def __init__(self, lang_filter: LanguageFilter = LanguageFilter.NONE) -> None:
super().__init__(lang_filter=lang_filter)
self._active_num = 0
self.probers: List[CharSetProber] = []
self._best_guess_prober: Optional[CharSetProber] = None
def reset(self) -> None:
super().reset()
self._active_num = 0
for prober in self.probers:
prober.reset()
prober.active = True
self._active_num += 1
self._best_guess_prober = None
@property
def charset_name(self) -> Optional[str]:
if not self._best_guess_prober:
self.get_confidence()
if not self._best_guess_prober:
return None
return self._best_guess_prober.charset_name
@property
def language(self) -> Optional[str]:
if not self._best_guess_prober:
self.get_confidence()
if not self._best_guess_prober:
return None
return self._best_guess_prober.language
def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
for prober in self.probers:
if not prober.active:
continue
state = prober.feed(byte_str)
if not state:
continue
if state == ProbingState.FOUND_IT:
self._best_guess_prober = prober
self._state = ProbingState.FOUND_IT
return self.state
if state == ProbingState.NOT_ME:
prober.active = False
self._active_num -= 1
if self._active_num <= 0:
self._state = ProbingState.NOT_ME
return self.state
return self.state
def get_confidence(self) -> float:
state = self.state
if state == ProbingState.FOUND_IT:
return 0.99
if state == ProbingState.NOT_ME:
return 0.01
best_conf = 0.0
self._best_guess_prober = None
for prober in self.probers:
if not prober.active:
self.logger.debug("%s not active", prober.charset_name)
continue
conf = prober.get_confidence()
self.logger.debug(
"%s %s confidence = %s", prober.charset_name, prober.language, conf
)
if best_conf < conf:
best_conf = conf
self._best_guess_prober = prober
if not self._best_guess_prober:
return 0.0
return best_conf

Some files were not shown because too many files have changed in this diff Show more