add config from gitlab

This commit is contained in:
afoucaultc 2026-07-03 09:15:37 +02:00
commit e02f7f00f9
842 changed files with 297362 additions and 0 deletions

58
README.md Normal file
View file

@ -0,0 +1,58 @@
# How to use
## Structure :
```shell
~/nixos-config/
├── flake.nix # pour fixer la source/version des packages utilisés
│ # permet de fixer la source/version des packages utilisés
├── flake.lock
├── hosts/
│ # configuration système
│ ├── nixos-home/
│ │ # mon host personnel (spécifique à ma machine)
│ └── nixos/
│ ├── configuration.nix # entrée des fichiers de configuration
│ ├── hardware-configuration.nix # fichier hardware généré à l'installation
│ └── config/ # tous fichiers config
│ └── ...
├── home/
│ # configuration user
│ └── afoucaultc/
│ # mon user personnel
│ ├── home.nix # point d'entrée home-manager
│ ├── dotfiles_apps.nix # liens vers mes dossier de configuration
│ └── packages/ # lien vers les packages installés sur mon user
└── ...
```
## Installation :
1. Installer NixOS sur clé USB (via Rufus sous windows par exemple)
2. Boot sur clé USB
3. Suivre les indications (perso: chiffrement LUKS + swap activé + formatage auto)
4. Reboot dans NixOS
5. Cloner le repo git en utilisant git temporairement via nix shell : `nix-shell -p git --run "git clone https://gitlab.com/afoucaultc/nixos-config.git ~/nixos-config"`
6. Lancer le `./install` (copie hardware-configuration dans le host, ajoute le host, lance un rebuild)
7. C'est fini, reboot et lancer la nouvelle version avec Grub
> [!WARNING]
> Il peut y avoir besoin d'ajouter un utilisateur pour git, à voir par la suite
> Pour les GPU ou CPU spécifiques, des changements peuvent être nécessaires, à adapter
## Installer un nouveau package et mettre à jour
### Pour update
```nix
nix flake update
sudo nixos-rebuild switch --flake ~/nixos-config#nixos-home
```
### Pour trouver un nouveau package :
```nix
nix search nixpkgs nom_du_package
```
### Pour savoir où le déclarer :
1. system wide : dans hosts
2. user-level : dans home
### Pour savoir comment le déclarer :
1. Avec un module `programs.*` s'il existe (à préférer, voir [lien](https://home-manager-options.extranix.com/))
2. Avec `home.packages` (`home.packages = [ pkgs.xxx ];`)
### Pour gérer la version
1. version trop ancienne : référencer `pkgs-unstable.xxx`
2. Package pas encore dans nixpkgs : chercher un flake upstream officiel (packages.<system>.degault), ajouter comme input et le référencer

View file

@ -0,0 +1,4 @@
source = ~/.config/hypr/hyprland_config/variables.conf
source = ~/.config/hypr/hyprland_config/*

View file

@ -0,0 +1,72 @@
source = ~/.config/hypr/variables.conf
# BACKGROUND
background {
monitor =
color = #000000
blur_passes = 0
contrast = 1
brightness = 0.5
vibrancy = 0.2
vibrancy_darkness = 0.2
}
# GENERAL
general {
no_fade_in = true
no_fade_out = true
hide_cursor = false
grace = 0
disable_loading_bar = true
}
# INPUT FIELD
input-field {
monitor =
size = 250, 60
outline_thickness = 2
dots_size = 0.2 # Scale of input-field height, 0.2 - 0.8
dots_spacing = 0.35 # Scale of dots' absolute size, 0.0 - 1.0
dots_center = true
outer_color = rgba(1, 1, 1, 0)
inner_color = rgba(1, 1, 1, 0.2)
font_color = #000000
fade_on_empty = false
rounding = -1
check_color = rgb(204, 136, 34)
placeholder_text = <i><span foreground="##cdd6f4">Input Password...</span></i>
hide_input = false
position = 0, -200
halign = center
valign = center
}
# DATE
label {
monitor =
text = cmd[update:1000] echo "$(date +"%A, %B %d")"
color = rgba(255,255,255, 0.75)
font_size = 22
font_family = Luciole
position = 0, 100
halign = center
valign = center
}
# TIME
label {
monitor =
text = cmd[update:1000] echo "$(date +"%-I:%M")"
color = rgba(255,255,255, 0.75)
font_size = 95
font_family = Luciole
position = 0, 200
halign = center
valign = center
}
auth {
fingerprint:enabled=true
}

View file

@ -0,0 +1,11 @@
wallpaper {
monitor = eDP-1
path = /home/Antoine/.config/hypr/wallpaper/wallpaper_nightmode.jpg
fit_mode = cover
}
wallpaper {
monitor = HDMI-A-1
path = /home/Antoine/.config/hypr/wallpaper/vertical.jpg
fit_mode = cover
}
splash = false

View file

@ -0,0 +1,7 @@
background = rgba(1a1b26ff)
base = rgba(1a1b26ff)
text = rgba(c0caf5ff)
alternate_base = rgba(24283bff)
bright_text = rgba(16161eff)
accent = rgba(7aa2f7ff)
accent_secondary = rgba(bb9af7ff)

View file

@ -0,0 +1,57 @@
-- shutdown hyprland and lock
hl.bind(
"CTRL + ALT + M",
hl.dsp.exec_cmd("command -v hyprshutdown >/dev/null 2>&1 && hyprshutdown || hyprctl dispatch 'hl.dsp.exit()'"),
{ description = "hyprland shutdown" }
)
hl.bind("CTRL + ALT + L", hl.dsp.exec_cmd(lockscreen))
-- launchers
hl.bind("ALT + D", hl.dsp.exec_cmd(fileManager))
hl.bind("ALT + Q", hl.dsp.exec_cmd(terminal))
hl.bind("ALT + N", hl.dsp.exec_cmd("kitty -e nvim"))
hl.bind("ALT + W", hl.dsp.exec_cmd(app_launcher))
hl.bind("ALT + F", hl.dsp.exec_cmd(browser))
hl.bind("ALT + Z", hl.dsp.exec_cmd("zotero"))
-- window management
hl.bind("ALT + V", hl.dsp.window.float({ action = "toggle" }))
hl.bind("ALT + F4", hl.dsp.window.close())
-- move focus
hl.bind("ALT + L", hl.dsp.focus({ direction = "right" }))
hl.bind("ALT + H", hl.dsp.focus({ direction = "left" }))
hl.bind("ALT + J", hl.dsp.focus({ direction = "up" }))
hl.bind("ALT + K", hl.dsp.focus({ direction = "down" }))
-- move window
hl.bind("CTRL + SUPER + L", hl.dsp.window.move({ direction = "right" }))
hl.bind("CTRL + SUPER + H", hl.dsp.window.move({ direction = "left" }))
hl.bind("CTRL + SUPER + K", hl.dsp.window.move({ direction = "up" }))
hl.bind("CTRL + SUPER + J", hl.dsp.window.move({ direction = "down" }))
-- move to monitor
hl.bind("SUPER + A", hl.dsp.focus({ monitor = monitorA }))
hl.bind("SUPER + B", hl.dsp.focus({ monitor = monitorB }))
hl.bind("CTRL + SUPER + A", hl.dsp.window.move({ monitor = monitorA }))
hl.bind("CTRL + SUPER + B", hl.dsp.window.move({ monitor = monitorB }))
-- change workspace
hl.bind("SUPER + L", hl.dsp.focus({ workspace = "r+1" }))
hl.bind("SUPER + H", hl.dsp.focus({ workspace = "r-1" }))
hl.bind("SUPER + K", hl.dsp.window.move({ workspace = "r+1" }))
hl.bind("SUPER + J", hl.dsp.window.move({ workspace = "r-1" }))
-- screenshot
hl.bind(
"Print",
hl.dsp.exec_cmd(
[[mkdir -p ~/Screenshots && filename=~/Screenshots/"$(date +'%F-%T').png" && grim -g "$(slurp)" "$filename" && wl-copy < "$filename" && gwenview "$filename"]]
)
)
hl.bind("SUPER + V", hl.dsp.exec_cmd("cliphist list | rofi -dmenu -display-columns 2 | cliphist decode | wl-copy"))
-- mouse resize
hl.bind("ALT + mouse:272", hl.dsp.window.drag(), { mouse = true })
hl.bind("ALT + mouse:273", hl.dsp.window.resize(), { mouse = true })
-- brightness
hl.bind("XF86MonBrightnessUp", hl.dsp.exec_cmd("brightnessctl -e4 -n2 set 5%+"))
hl.bind("XF86MonBrightnessDown", hl.dsp.exec_cmd("brightnessctl -e4 -n2 set 5%-"))
hl.bind("XF86AudioRaiseVolume", hl.dsp.exec_cmd("wpctl set-volume -l 1 @DEFAULT_AUDIO_SINK@ 5%+"))
hl.bind("XF86AudioLowerVolume", hl.dsp.exec_cmd("wpctl set-volume @DEFAULT_AUDIO_SINK@ 5%-"))
hl.bind("XF86AudioMute", hl.dsp.exec_cmd("wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle"))
hl.bind("XF86AudioMicMute", hl.dsp.exec_cmd("wpctl set-mute @DEFAULT_AUDIO_SOURCE@ toggle"))

View file

@ -0,0 +1,9 @@
-- environment variables
hl.env("LIBVA_DRIVER_NAME", "nvidia")
hl.env("__GLX_VENDOR_LIBRARY_NAME", "nvidia")
hl.env("XDG_CURRENT_DESKTOP", "Hyprland")
hl.env("XDG_SESSION_TYPE", "wayland")
hl.env("NVD_BACKEND", "direct")
hl.env("ELECTRON_OZONE_PLATFORM_HINT", "auto")
hl.env("SCREENSHOT_DIR", "$home/Screenshots")
hl.env("GDK_SCALE", 1)

View file

@ -0,0 +1,23 @@
hl.config({
input = {
kb_layout = "fr",
numlock_by_default = true,
accel_profile = "adaptive",
follow_mouse = 1,
sensitivity = -0.3,
touchpad = {
disable_while_typing = true,
scroll_factor = 1.2,
natural_scroll = false,
middle_button_emulation = false,
},
},
})
hl.device({
name = "elan1203:00-04f3:307a-touchpad",
enabled = false,
})

View file

@ -0,0 +1,13 @@
hl.monitor({
output = monitorA,
mode = "1920x1080@120.00200",
position = "0x0",
scale = "1",
})
hl.monitor({
output = monitorB,
mode = "1920x1080@60",
position = "1920x0",
scale = "1",
})

View file

@ -0,0 +1,6 @@
hl.misc({
force_default_wallpaper = 0,
disable_hyprland_logo = true,
disable_splash_rendering = true,
vrr = 1,
})

View file

@ -0,0 +1,13 @@
hl.on("hyprland.start", function()
hl.exec_cmd("hyprpaper")
hl.exec_cmd("wl-paste --type text --watch cliphist store")
hl.exec_cmd("wl-paste --type image --watch cliphist store")
hl.exec_cmd("systemctl --user start hyprpolkitagent")
hl.exec_cmd("hyprctl setcursor Bibata-Modern-Ice 24")
hl.exec_cmd("noctalia-shell")
-- hl.exec_cmd("hyprpanel")
-- hl.exec_cmd("hyprsunset")
-- hl.exec_cmd("xsettingsd")
-- hl.exec_cmd("nwg-look -a")
hl.exec_cmd("protonmail-bridge")
end)

View file

@ -0,0 +1,68 @@
hl.config({
general = {
gaps_in = 4,
gaps_out = 2,
border_size = 2,
col = {
active_border = { colors = { "rgba(7aa2f7ee)", "rgba(bb9af7ee)" }, angle = 45 },
inactive_border = "rgba(414868aa)",
},
resize_on_border = true,
hover_icon_on_border = true,
allow_tearing = true,
layout = "dwindle",
snap = {
enabled = true,
},
},
decoration = {
rounding = 5,
rounding_power = 10,
-- Change transparency of focused and unfocused windows
active_opacity = 1.0,
inactive_opacity = 1.0,
shadow = {
enabled = false,
range = 4,
render_power = 3,
color = 0xee1a1a1a,
},
blur = {
enabled = false,
size = 3,
passes = 1,
vibrancy = 0.1696,
},
},
animations = {
enabled = false,
},
})
-- tiling managers
hl.config({
dwindle = {
preserve_split = true,
},
master = {
new_status = "master",
orientation = "center",
mfact = "0.5",
},
scrolling = {
fullscreen_on_one_column = true,
column_width = 0.9,
direction = right,
},
})
-- others
hl.config({
misc = {
force_default_wallpaper = 0,
disable_hyprland_logo = true,
vrr = 0,
disable_splash_rendering = true,
},
})

View file

@ -0,0 +1,9 @@
terminal = "kitty"
fileManager = "dolphin"
menu = "wofi --show drun"
home = "/home/afoucaultc/"
lockscreen = "hyprlock"
browser = "zen-beta"
app_launcher = "~/.config/rofi/launchers/type-1/launcher.sh"
monitorA = "eDP-1"
monitorB = "HDMI-A-1"

View file

@ -0,0 +1,7 @@
hl.window_rule({
name = "opacity kitty",
match = {
class = "kitty",
},
opacity = "0.9",
})

View file

@ -0,0 +1,12 @@
local workspaces = {
{
id = 1,
layout = "scroll",
persistent = "true",
},
{
id = 2,
layout = "dwindle",
persistent = "true",
},
}

View file

@ -0,0 +1,15 @@
require("conf.variables")
require("conf.env")
require("conf.binding")
require("conf.input")
require("conf.monitor")
require("conf.startup")
require("conf.style")
require("conf.windowrules")
require("conf.workspace")
-- For Noctalia Color templates
require("noctalia")
-- This loads Noctalia-generated Hyprland colors.
dofile("/home/afoucaultc/.config/hypr/noctalia/noctalia-colors.lua")

View file

@ -0,0 +1,7 @@
background = rgba(010409ff)
base = rgba(010409ff)
text = rgba(c9d1d9ff)
alternate_base = rgba(161b22ff)
bright_text = rgba(010409ff)
accent = rgba(58a6ffff)
accent_secondary = rgba(bc8cffff)

View file

@ -0,0 +1,33 @@
-- Generated by Noctalia
local primary = "rgb(7a88cf)"
local surface = "rgb(1f2335)"
local secondary = "rgb(d7729f)"
local error = "rgb(f7768e)"
hl.config({
general = {
col = {
active_border = primary,
inactive_border = surface,
},
},
group = {
col = {
border_active = secondary,
border_inactive = surface,
border_locked_active = error,
border_locked_inactive = surface,
},
groupbar = {
col = {
active = secondary,
inactive = surface,
locked_active = error,
locked_inactive = surface,
},
},
},
})

View file

@ -0,0 +1,25 @@
$primary = rgb(58a6ff)
$surface = rgb(010409)
$secondary = rgb(bc8cff)
$error = rgb(f85149)
$tertiary = rgb(bc8cff)
$surface_lowest = rgb(05080e)
general {
col.active_border = $primary
col.inactive_border = $surface
}
group {
col.border_active = $secondary
col.border_inactive = $surface
col.border_locked_active = $error
col.border_locked_inactive = $surface
groupbar {
col.active = $secondary
col.inactive = $surface
col.locked_active = $error
col.locked_inactive = $surface
}
}

View file

@ -0,0 +1,35 @@
-- Colors template generated by Noctalia
-- Source command is:
-- dofile(os.getenv("HOME") .. "/.config/hypr/noctalia/noctalia-colors.lua")
local primary = "rgb(58a6ff)"
local surface = "rgb(010409)"
local secondary = "rgb(bc8cff)"
local error = "rgb(f85149)"
hl.config({
general = {
col = {
active_border = primary,
inactive_border = surface,
},
},
group = {
col = {
border_active = secondary,
border_inactive = surface,
border_locked_active = error,
border_locked_inactive = surface,
},
groupbar = {
col = {
active = secondary,
inactive = surface,
locked_active = error,
locked_inactive = surface,
},
},
},
})

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

View file

@ -0,0 +1,25 @@
Light mode :
Lumineux
#73020C
#D9C49C
#F2E2CE
#BF895A
#0D0000
Sombre
#73020C
#010D00
#F2E2CE
#BF895A
#260101
Dark mode :
#1C1D26
#222940
#2F4C73
#4681A6
#56ACBF
sombre
#1C1D26
#242426
#222940
#253659
#3A668C

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 MiB

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cphistory>
<operations />
<params />
</cphistory>

View file

@ -0,0 +1,37 @@
[Windows]
Count=1
[Window0Column0]
Notebook0Dialogs=ObjectProperties;FillStroke;Export;AlignDistribute;Text;Trace;
Notebook0Height=887
Notebook0ActiveTab=2
ColumnWidth=577
NotebookCount=1
BeforeCanvas=false
[Window0]
ColumnCount=1
Floating=false
[transient]
state1=
dialogs1=CloneTiler;
state2=[Windows]\nCount=1\n\n[Window0Column0]\nNotebook0Dialogs=DocumentProperties;\nNotebookCount=1\n\n[Window0]\nColumnCount=1\nPosition=true\nx=0\ny=0\nwidth=831\nheight=673\n
dialogs2=DocumentProperties;
state3=[Windows]\nCount=1\n\n[Window0Column0]\nNotebook0Dialogs=DocumentResources;\nNotebookCount=1\n\n[Window0]\nColumnCount=1\nPosition=true\nx=0\ny=0\nwidth=613\nheight=678\n
dialogs3=DocumentResources;
state4=[Windows]\nCount=1\n\n[Window0Column0]\nNotebook0Dialogs=ExtensionsGallery;\nNotebookCount=1\n\n[Window0]\nColumnCount=1\nPosition=true\nx=0\ny=0\nwidth=1186\nheight=777\n
dialogs4=ExtensionsGallery;
state5=
dialogs5=FilterEffects;
state6=
dialogs6=FilterGallery;
state7=
dialogs7=FontCollections;
state8=[Windows]\nCount=1\n\n[Window0Column0]\nNotebook0Dialogs=Objects;\nNotebookCount=1\n\n[Window0]\nColumnCount=1\nPosition=true\nx=0\ny=0\nwidth=360\nheight=520\n
dialogs8=Objects;
state9=[Windows]\nCount=1\n\n[Window0Column0]\nNotebook0Dialogs=Preferences;\nNotebookCount=1\n\n[Window0]\nColumnCount=1\nPosition=true\nx=0\ny=0\nwidth=1447\nheight=672\n
dialogs9=Preferences;
state10=
dialogs10=XMLEditor;
count=10

View file

@ -0,0 +1,20 @@
L'extension « Optimized PNG » n'a pas été chargée, car une dépendance est manquante. Dépendance:
type: executable
emplacement: chemin
chaîne: optipng
L'extension « Formula (typst) » n'a pas été chargée, car une dépendance est manquante. Dépendance:
type: executable
emplacement: chemin
chaîne: typst
L'extension « Export to PDF via Scribus » n'a pas été chargée, car une dépendance est manquante. Dépendance:
type: executable
emplacement: chemin
chaîne: scribus
L'extension « XFIG Input » n'a pas été chargée, car une dépendance est manquante. Dépendance:
type: executable
emplacement: chemin
chaîne: fig2dev

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
)

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