Compare commits

..

22 Commits

Author SHA1 Message Date
a5ddc33a27 bundle: update (2026-01-22)
All checks were successful
version / update-version (release) Successful in 13s
2026-01-22 15:00:45 +00:00
a9c87f2adf create version file for future use 2026-01-22 09:58:10 -05:00
5692f4bb08 force new release 2026-01-22 09:55:57 -05:00
9af24d49ee Merge branch 'main' of ssh://git.knoxmakers.org:2222/KnoxMakers/knoxmakers-inkscape 2026-01-22 09:53:29 -05:00
7211fd44ef release changes 2026-01-22 09:53:22 -05:00
b72b468ad4 bundle: update (2026-01-19)
All checks were successful
bundle / bundle (push) Successful in 18s
2026-01-19 09:23:04 +00:00
8a126fec7d bundle: update (2026-01-18)
All checks were successful
bundle / bundle (push) Successful in 16s
2026-01-18 09:23:06 +00:00
e0dc82c22d Merge branch 'main' of ssh://git.knoxmakers.org:2222/KnoxMakers/knoxmakers-inkscape
All checks were successful
bundle / bundle (push) Successful in 15s
2026-01-17 23:53:24 -05:00
c2fa54d3b4 readme 2026-01-17 23:53:16 -05:00
7597f2f156 bundle: update (2026-01-18) 2026-01-18 04:47:51 +00:00
822898e4a3 add km-hershey 2026-01-17 23:45:12 -05:00
22a55924e3 friendlier no-update 2026-01-17 22:04:59 -05:00
cf789ba0b8 Merge branch 'main' of ssh://git.knoxmakers.org:2222/KnoxMakers/knoxmakers-inkscape 2026-01-17 22:02:51 -05:00
74011e30ba rename releases/tags 2026-01-17 22:02:44 -05:00
f822f384e8 bundle: update (2026-01-18) 2026-01-18 02:57:46 +00:00
e65941bb8c Merge branch 'main' of ssh://git.knoxmakers.org:2222/KnoxMakers/knoxmakers-inkscape 2026-01-17 21:54:48 -05:00
eb411b5909 add km-hatch 2026-01-17 21:54:27 -05:00
03c5c75177 bundle: update (2026-01-18) 2026-01-18 01:20:18 +00:00
83c22af578 try a python script in runner 2026-01-17 20:15:31 -05:00
44af1518a3 testing 2026-01-15 19:28:54 -05:00
a4fd561e9f Merge branch 'main' of ssh://git.knoxmakers.org:2222/KnoxMakers/knoxmakers-inkscape 2026-01-15 19:25:37 -05:00
01edbfe859 create releases 2026-01-15 19:24:36 -05:00
323 changed files with 55647 additions and 104 deletions

View File

@@ -24,16 +24,73 @@ jobs:
- name: Run bundle script
run: |
bash scripts/bundle.sh
python3 scripts/bundle.py
- name: Push (if bundle update commit was created)
- name: Push + tag + create release with filtered bundle (if bundle update commit was created)
env:
HAXBOT_TOKEN: ${{ secrets.HAXBOT_TOKEN }}
run: |
set -euo pipefail
if git log -1 --pretty=%B | grep -q '^bundle: update'; then
REPO_URL="https://x-access-token:${HAXBOT_TOKEN}@git.knoxmakers.org/KnoxMakers/knoxmakers-inkscape.git"
OWNER="KnoxMakers"
REPO="knoxmakers-inkscape"
BASE_URL="https://git.knoxmakers.org"
# Authenticated push URL (PAT belongs to haxbot)
REPO_URL="https://x-access-token:${HAXBOT_TOKEN}@git.knoxmakers.org/${OWNER}/${REPO}.git"
git remote set-url origin "$REPO_URL"
# Push the commit to main
git push origin HEAD:main
# Create a unique tag for this bundle run
DATETIME="$(date -u +%Y%m%d)"
TAG="knoxmakers-inkscape-${DATETIME}"
SHA="$(git rev-parse HEAD)"
git tag -a "$TAG" -m "Automated bundle: $TAG ($SHA)"
git push origin "$TAG"
# Build a release artifact: include everything except scripts/ and .gitea/ and .git/
ART="${TAG}.zip"
rm -f "$ART"
zip -r "$ART" . \
-x "scripts/*" \
-x ".gitea/*" \
-x ".git/*"
# Create a Gitea Release for the tag
API_CREATE="${BASE_URL}/api/v1/repos/${OWNER}/${REPO}/releases"
CREATE_JSON="$(jq -n \
--arg tag "$TAG" \
--arg name "$TAG" \
--arg body "Automated bundle release." \
'{tag_name:$tag, name:$name, body:$body, draft:false, prerelease:false}')"
RELEASE_RESP="$(curl -fsS -X POST "$API_CREATE" \
-H "Authorization: token ${HAXBOT_TOKEN}" \
-H "Content-Type: application/json" \
-d "$CREATE_JSON")"
RELEASE_ID="$(printf '%s' "$RELEASE_RESP" | jq -r '.id')"
if [ -z "$RELEASE_ID" ] || [ "$RELEASE_ID" = "null" ]; then
echo "Failed to parse release id. Response:"
echo "$RELEASE_RESP"
exit 1
fi
# Upload the bundle as a release asset
API_UPLOAD="${BASE_URL}/api/v1/repos/${OWNER}/${REPO}/releases/${RELEASE_ID}/assets?name=$(printf '%s' "$ART" | jq -sRr @uri)"
curl -fsS -X POST "$API_UPLOAD" \
-H "Authorization: token ${HAXBOT_TOKEN}" \
-H "Content-Type: multipart/form-data" \
-F "attachment=@${ART};type=application/zip"
echo "Release created: $TAG (id=$RELEASE_ID) with asset: $ART"
else
echo "No update commit created."
fi

View File

@@ -0,0 +1,45 @@
name: version
on:
release:
types: [published]
jobs:
update-version:
runs-on: [ubuntu-24.04]
steps:
- name: Checkout repository
run: |
set -euo pipefail
rm -rf .git || true
rm -rf ./* ./.??* || true
git clone --depth 1 https://git.knoxmakers.org/KnoxMakers/knoxmakers-inkscape.git .
git checkout main
- name: Configure git identity
run: |
git config user.name "haxbot"
git config user.email "haxbot@knoxmakers.sh"
- name: Write version file
run: |
echo "${{ gitea.event.release.name }}" > version
- name: Commit and push version file
env:
HAXBOT_TOKEN: ${{ secrets.HAXBOT_TOKEN }}
run: |
set -euo pipefail
git add version
if git diff --cached --quiet; then
echo "No changes to version file"
exit 0
fi
git commit -m "version: ${{ gitea.event.release.name }}"
REPO_URL="https://x-access-token:${HAXBOT_TOKEN}@git.knoxmakers.org/KnoxMakers/knoxmakers-inkscape.git"
git remote set-url origin "$REPO_URL"
git push origin HEAD:main

View File

@@ -1,2 +1,27 @@
# knoxmakers-inkscape
A bundled collection of Inkscape extensions for Knox Makers makerspace.
## Installation
Download the latest release zip and extract into to your Inkscape extensions directory:
- **Linux**: `~/.config/inkscape/extensions/`
- **Linux (Flatpak)**: `~/.var/app/org.inkscape.Inkscape/config/inkscape/extensions/`
- **Linux (Snap)**: `~/snap/inkscape/current/.config/inkscape/extensions/`
- **macOS**: `~/Library/Application Support/org.inkscape.Inkscape/config/inkscape/extensions/`
- **Windows**: `%APPDATA%\inkscape\extensions\`
## Included Extensions
- **botbox3000** - Box generator for laser cutting
- **km-living-hinge** - Living hinge pattern generator
- **km-plot** - Detect and send designs to serial HPGL plotters/vinyl cutters
- **km-hatch** - Hatching/fill patterns
- **km-hershey** - Single Line text for plotting/engraving
Extensions appear under **Extensions > Knox Makers** in Inkscape.
## Releases
Automated bundles are created daily when upstream repositories have changes.

View File

@@ -1,12 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<?xml version='1.0' encoding='UTF-8'?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<name>Box Bot 3000</name>
<id>org.knoxmakers.botbox</id>
<param name="units" type="enum" gui-text="Units">
<item value="mm">mm</item>
<item value="in">in</item>
<item value="px">px</item>
</param>
<param name="notebook" type="notebook">
<page name="box" gui-text="Box">
<param name="generate_lid" type="bool" gui-text="Generate Lid">true</param>
@@ -15,7 +15,6 @@
<param name="top_hole_inset" type="float" min="0.0" max="1000" gui-text="Top Hole Inset">10.0</param>
<param name="kerf" type="float" min="0.0" max="10.0" gui-text="Kerf">0.1</param>
</page>
<page name="tabs" gui-text="Tabs">
<param name="num_tabs" type="int" min="0" max="1000" gui-text="Number of Tabs">8</param>
<param name="tab_inset" type="float" min="0.0" max="1000" gui-text="Tab Inset">5.0</param>
@@ -23,14 +22,12 @@
<param name="tab_start_offset" type="float" min="0.0" max="1000.0" gui-text="Tab Placement Offset">0.0</param>
<param name="tab_border_radius" type="float" min="0.0" max="10.0" gui-text="Tab Border Radius">0.5</param>
</page>
<page name="living_hinge" gui-text="Living Hinge">
<param name="generate_living_hinge" type="bool" gui-text="Generate Living Hinge">false</param>
<param name="hinge_length_percent" type="int" min="10" max="90" gui-text="Living Hinge Cut Length (%)">25</param>
<param name="hinge_gap" type="float" min="0.1" max="1000" gui-text="Living Hinge Gap">1.0</param>
<param name="hinge_spacing" type="float" min="0.1" max="1000" gui-text="Living Hinge Spacing">1.5</param>
</page>
<page name="magnets" gui-text="Magnets">
<param name="magnet_type" type="enum" gui-text="Magnet Type">
<item value="none">None</item>
@@ -45,17 +42,16 @@
<param name="hide_magnets" type="bool" gui-text="Hide Magnets">true</param>
</page>
</param>
<dependency type="executable" location="extensions">boxbot.py</dependency>
<script>
<command location="inx" interpreter="python">boxbot.py</command>
</script>
<effect needs-live-preview="true">
<object-type>path</object-type>
<effects-menu>
<submenu name="Laser Tools"/>
<submenu _name="Knox Makers">
<submenu _name="Laser" />
</submenu>
</effects-menu>
</effect>
</inkscape-extension>

View File

@@ -182,7 +182,7 @@ class Boxbot(inkex.EffectExtension):
self.top_hole_inset = PathElement()
self.top_hole_inset.set_id(self.svg.get_unique_id("top_hole_inset"))
self.top_hole_inset.set('d', top_hole_inset_d)
self.top_hole_inset.style = self.CUT_OUTER_STYLE
self.top_hole_inset.style = self.CUT_INNER_STYLE
top_tabs_group.append(self.top_hole_inset)
except ValueError:
pass

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

26
extensions/km-hatch/.gitignore vendored Normal file
View File

@@ -0,0 +1,26 @@
# Ignore anything that starts with a dot
.*
# But don't ignore .gitignore itself
!.gitignore
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
*.egg
*.egg-info/
dist/
build/
eggs/
.eggs/
# IDE
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db

668
extensions/km-hatch/LICENSE Normal file
View File

@@ -0,0 +1,668 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

View File

@@ -0,0 +1,22 @@
# KM Hatch Fill
An Inkscape extension that fills closed shapes with parallel hatch lines. The extension generates vector line patterns inside shapes that can be used for engraving fills, texturing surfaces, or creating visual effects.
## Manual Installation
1. Create the subdirectory `km-hatch/` in your Inkscape extensions folder:
- **Linux:** `~/.config/inkscape/extensions/`
- **Linux (Flatpak):** `~/.var/app/org.inkscape.Inkscape/config/inkscape/extensions/`
- **Linux (Snap):** `~/snap/inkscape/current/.config/inkscape/extensions/`
- **macOS:** `~/Library/Application Support/org.inkscape.Inkscape/config/inkscape/extensions/`
- **Windows:** `%APPDATA%\inkscape\extensions\`
2. Copy all files from this repository into your `km-hatch/` directory.
3. Restart Inkscape. The extension appears under **Extensions > Knox Makers > Laser > Hatch Fill**.
## Acknowledgements
Inspiration, examples, and code came from:
- **Hatch Fill** from Evil Mad Scientist Laboratories and their EggBot extensions
https://github.com/evil-mad/EggBot/

View File

@@ -0,0 +1,33 @@
# 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 Color, ColorError, ColorIdError, is_color
from .colors.spaces 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.4.0" # Version number for inkex; may differ from Inkscape version.

View File

@@ -0,0 +1,567 @@
# 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 .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
if TYPE_CHECKING:
from .elements._svg import SvgDocumentElement
from .elements._base import BaseElement
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["BaseElement"], ...] = ()
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: SvgDocumentElement = 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,582 @@
# coding=utf-8
#
# Copyright (C) 2010 Nick Drobchenko, nick@cnc-club.ru
# Copyright (C) 2005 Aaron Spike, aaron@ekips.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# pylint: disable=invalid-name,too-many-locals
#
"""
Bezier calculations
"""
import cmath
import math
import numpy
from .transforms import DirectedLineSegment
from .localization import inkex_gettext as _
# bez = ((bx0,by0),(bx1,by1),(bx2,by2),(bx3,by3))
def pointdistance(point_a, point_b):
"""The straight line distance between two points"""
return math.sqrt(
((point_b[0] - point_a[0]) ** 2) + ((point_b[1] - point_a[1]) ** 2)
)
def between_point(point_a, point_b, time=0.5):
"""Returns the point between point a and point b"""
return point_a[0] + time * (point_b[0] - point_a[0]), point_a[1] + time * (
point_b[1] - point_a[1]
)
def percent_point(point_a, point_b, percent=50.0):
"""Returns between_point but takes percent instead of 0.0-1.0"""
return between_point(point_a, point_b, percent / 100.0)
def root_wrapper(root_a, root_b, root_c, root_d):
"""Get the Cubic function, moic formular of roots, simple root"""
if root_a:
# Monics formula, see
# http://en.wikipedia.org/wiki/Cubic_function#Monic_formula_of_roots
mono_a, mono_b, mono_c = (root_b / root_a, root_c / root_a, root_d / root_a)
m = 2.0 * mono_a**3 - 9.0 * mono_a * mono_b + 27.0 * mono_c
k = mono_a**2 - 3.0 * mono_b
n = m**2 - 4.0 * k**3
w1 = -0.5 + 0.5 * cmath.sqrt(-3.0)
w2 = -0.5 - 0.5 * cmath.sqrt(-3.0)
if n < 0:
m1 = pow(complex((m + cmath.sqrt(n)) / 2), 1.0 / 3)
n1 = pow(complex((m - cmath.sqrt(n)) / 2), 1.0 / 3)
else:
if m + math.sqrt(n) < 0:
m1 = -pow(-(m + math.sqrt(n)) / 2, 1.0 / 3)
else:
m1 = pow((m + math.sqrt(n)) / 2, 1.0 / 3)
if m - math.sqrt(n) < 0:
n1 = -pow(-(m - math.sqrt(n)) / 2, 1.0 / 3)
else:
n1 = pow((m - math.sqrt(n)) / 2, 1.0 / 3)
return (
-1.0 / 3 * (mono_a + m1 + n1),
-1.0 / 3 * (mono_a + w1 * m1 + w2 * n1),
-1.0 / 3 * (mono_a + w2 * m1 + w1 * n1),
)
if root_b:
det = root_c**2.0 - 4.0 * root_b * root_d
if det:
return (
(-root_c + cmath.sqrt(det)) / (2.0 * root_b),
(-root_c - cmath.sqrt(det)) / (2.0 * root_b),
)
return (-root_c / (2.0 * root_b),)
if root_c:
return (1.0 * (-root_d / root_c),)
return ()
def bezlenapprx(sp1, sp2):
"""Return the aproximate length between two beziers"""
return (
pointdistance(sp1[1], sp1[2])
+ pointdistance(sp1[2], sp2[0])
+ pointdistance(sp2[0], sp2[1])
)
def cspbezsplit(sp1, sp2, time=0.5):
"""Split a cubic bezier at the time period"""
m1 = tpoint(sp1[1], sp1[2], time)
m2 = tpoint(sp1[2], sp2[0], time)
m3 = tpoint(sp2[0], sp2[1], time)
m4 = tpoint(m1, m2, time)
m5 = tpoint(m2, m3, time)
m = tpoint(m4, m5, time)
return [[sp1[0][:], sp1[1][:], m1], [m4, m, m5], [m3, sp2[1][:], sp2[2][:]]]
def cspbezsplitatlength(sp1, sp2, length=0.5, tolerance=0.001):
"""Split a cubic bezier at length"""
bez = (sp1[1][:], sp1[2][:], sp2[0][:], sp2[1][:])
time = beziertatlength(bez, length, tolerance)
return cspbezsplit(sp1, sp2, time)
def cspseglength(sp1, sp2, tolerance=0.001):
"""Get cubic bezier segment length"""
bez = (sp1[1][:], sp1[2][:], sp2[0][:], sp2[1][:])
return bezierlength(bez, tolerance)
def csplength(csp):
"""Get cubic bezier length"""
total = 0
lengths = []
for sp in csp:
lengths.append([])
for i in range(1, len(sp)):
l = cspseglength(sp[i - 1], sp[i])
lengths[-1].append(l)
total += l
return lengths, total
def bezierparameterize(bez):
"""Return the bezier parameter size
Converts the bezier parametrisation from the default form
P(t) = (1-t)³ P_1 + 3(1-t)²t P_2 + 3(1-t)t² P_3 + t³ x_4
to the a form which can be differentiated more easily
P(t) = a t³ + b t² + c t + P0
Args:
bez (List[Tuple[float, float]]): the Bezier curve. The elements of the list the
coordinates of the points (in this order): Start point, Start control point,
End control point, End point.
Returns:
Tuple[float, float, float, float, float, float, float, float]:
the values ax, ay, bx, by, cx, cy, x0, y0
"""
((bx0, by0), (bx1, by1), (bx2, by2), (bx3, by3)) = bez
# parametric bezier
x0 = bx0
y0 = by0
cx = 3 * (bx1 - x0)
bx = 3 * (bx2 - bx1) - cx
ax = bx3 - x0 - cx - bx
cy = 3 * (by1 - y0)
by = 3 * (by2 - by1) - cy
ay = by3 - y0 - cy - by
return ax, ay, bx, by, cx, cy, x0, y0
def linebezierintersect(arg_a, bez):
"""Where a line and bezier intersect"""
((lx1, ly1), (lx2, ly2)) = arg_a
# parametric line
dd = lx1
cc = lx2 - lx1
bb = ly1
aa = ly2 - ly1
if aa:
coef1 = cc / aa
coef2 = 1
else:
coef1 = 1
coef2 = aa / cc
ax, ay, bx, by, cx, cy, x0, y0 = bezierparameterize(bez)
# cubic intersection coefficients
a = coef1 * ay - coef2 * ax
b = coef1 * by - coef2 * bx
c = coef1 * cy - coef2 * cx
d = coef1 * (y0 - bb) - coef2 * (x0 - dd)
roots = root_wrapper(a, b, c, d)
retval = []
for i in roots:
if isinstance(i, complex) and i.imag == 0:
i = i.real
if not isinstance(i, complex) and 0 <= i <= 1:
retval.append(bezierpointatt(bez, i))
return retval
def bezierpointatt(bez, t):
"""Get coords at the given time point along a bezier curve"""
ax, ay, bx, by, cx, cy, x0, y0 = bezierparameterize(bez)
x = ax * (t**3) + bx * (t**2) + cx * t + x0
y = ay * (t**3) + by * (t**2) + cy * t + y0
return x, y
def bezierslopeatt(bez, t):
"""Get slope at the given time point along a bezier curve
The slope is computed as (dx, dy) where dx = df_x(t)/dt and dy = df_y(t)/dt.
Note that for lines P1=P2 and P3=P4, so the slope at the end points is dx=dy=0
(slope not defined).
Args:
bez (List[Tuple[float, float]]): the Bezier curve. The elements of the list the
coordinates of the points (in this order): Start point, Start control point,
End control point, End point.
t (float): time in the interval [0, 1]
Returns:
Tuple[float, float]: x and y increment
"""
ax, ay, bx, by, cx, cy, _, _ = bezierparameterize(bez)
dx = 3 * ax * (t**2) + 2 * bx * t + cx
dy = 3 * ay * (t**2) + 2 * by * t + cy
return dx, dy
def beziertatslope(bez, d):
"""Reverse; get time from slope along a bezier curve"""
ax, ay, bx, by, cx, cy, _, _ = bezierparameterize(bez)
(dy, dx) = d
# quadratic coefficients of slope formula
if dx:
slope = 1.0 * (dy / dx)
a = 3 * ay - 3 * ax * slope
b = 2 * by - 2 * bx * slope
c = cy - cx * slope
elif dy:
slope = 1.0 * (dx / dy)
a = 3 * ax - 3 * ay * slope
b = 2 * bx - 2 * by * slope
c = cx - cy * slope
else:
return []
roots = root_wrapper(0, a, b, c)
retval = []
for i in roots:
if isinstance(i, complex) and i.imag == 0:
i = i.real
if not isinstance(i, complex) and 0 <= i <= 1:
retval.append(i)
return retval
def tpoint(p1, p2, t):
"""Linearly interpolate between p1 and p2.
t = 0.0 returns p1, t = 1.0 returns p2.
:return: Interpolated point
:rtype: tuple
:param p1: First point as sequence of two floats
:param p2: Second point as sequence of two floats
:param t: Number between 0.0 and 1.0
:type t: float
"""
x1, y1 = p1
x2, y2 = p2
return x1 + t * (x2 - x1), y1 + t * (y2 - y1)
def beziersplitatt(bez, t):
"""Split bezier at given time"""
((bx0, by0), (bx1, by1), (bx2, by2), (bx3, by3)) = bez
m1 = tpoint((bx0, by0), (bx1, by1), t)
m2 = tpoint((bx1, by1), (bx2, by2), t)
m3 = tpoint((bx2, by2), (bx3, by3), t)
m4 = tpoint(m1, m2, t)
m5 = tpoint(m2, m3, t)
m = tpoint(m4, m5, t)
return ((bx0, by0), m1, m4, m), (m, m5, m3, (bx3, by3))
def addifclose(bez, l, error=0.001):
"""Gravesen, Add if the line is closed, in-place addition to array l"""
box = 0
for i in range(1, 4):
box += pointdistance(bez[i - 1], bez[i])
chord = pointdistance(bez[0], bez[3])
if (box - chord) > error:
first, second = beziersplitatt(bez, 0.5)
addifclose(first, l, error)
addifclose(second, l, error)
else:
l[0] += (box / 2.0) + (chord / 2.0)
# balfax, balfbx, balfcx, balfay, balfby, balfcy = 0, 0, 0, 0, 0, 0
def balf(t, args):
"""Bezier Arc Length Function"""
ax, bx, cx, ay, by, cy = args
retval = (ax * (t**2) + bx * t + cx) ** 2 + (ay * (t**2) + by * t + cy) ** 2
return math.sqrt(retval)
def simpson(start, end, maxiter, tolerance, bezier_args):
"""Calculate the length of a bezier curve using Simpson's algorithm:
http://steve.hollasch.net/cgindex/curves/cbezarclen.html
Args:
start (int): Start time (between 0 and 1)
end (int): End time (between start time and 1)
maxiter (int): Maximum number of iterations. If not a power of 2, the algorithm
will behave like the value is set to the next power of 2.
tolerance (float): maximum error ratio
bezier_args (list): arguments as computed by bezierparametrize()
Returns:
float: the appoximate length of the bezier curve
"""
n = 2
multiplier = (end - start) / 6.0
endsum = balf(start, bezier_args) + balf(end, bezier_args)
interval = (end - start) / 2.0
asum = 0.0
bsum = balf(start + interval, bezier_args)
est1 = multiplier * (endsum + (2.0 * asum) + (4.0 * bsum))
est0 = 2.0 * est1
# print(multiplier, endsum, interval, asum, bsum, est1, est0)
while n < maxiter and abs(est1 - est0) > tolerance:
n *= 2
multiplier /= 2.0
interval /= 2.0
asum += bsum
bsum = 0.0
est0 = est1
for i in range(1, n, 2):
bsum += balf(start + (i * interval), bezier_args)
est1 = multiplier * (endsum + (2.0 * asum) + (4.0 * bsum))
# print(multiplier, endsum, interval, asum, bsum, est1, est0)
return est1
def bezierlength(bez, tolerance=0.001, time=1.0):
"""Get length of bezier curve"""
ax, ay, bx, by, cx, cy, _, _ = bezierparameterize(bez)
return simpson(0.0, time, 4096, tolerance, [3 * ax, 2 * bx, cx, 3 * ay, 2 * by, cy])
def beziertatlength(bez, l=0.5, tolerance=0.001):
"""Get bezier curve time at the length specified"""
curlen = bezierlength(bez, tolerance, 1.0)
time = 1.0
tdiv = time
targetlen = l * curlen
diff = curlen - targetlen
while abs(diff) > tolerance:
tdiv /= 2.0
if diff < 0:
time += tdiv
else:
time -= tdiv
curlen = bezierlength(bez, tolerance, time)
diff = curlen - targetlen
return time
def maxdist(bez):
"""Get maximum distance within bezier curve"""
seg = DirectedLineSegment(bez[0], bez[3])
return max(seg.distance_to_point(*bez[1]), seg.distance_to_point(*bez[2]))
def cspsubdiv(csp, flat):
"""Sub-divide cubic sub-paths"""
for sp in csp:
subdiv(sp, flat)
def subdiv(sp, flat, i=1):
"""sub divide bezier curve"""
while i < len(sp):
p0 = sp[i - 1][1]
p1 = sp[i - 1][2]
p2 = sp[i][0]
p3 = sp[i][1]
bez = (p0, p1, p2, p3)
mdist = maxdist(bez)
if mdist <= flat:
i += 1
else:
one, two = beziersplitatt(bez, 0.5)
sp[i - 1][2] = one[1]
sp[i][0] = two[2]
p = [one[2], one[3], two[1]]
sp[i:1] = [p]
def csparea(csp):
r"""Get total area of cubic superpath.
.. hint::
The results may be slightly inaccurate for paths containing arcs due
to the loss of accuracy during arc -> cubic bezier conversion.
The function works as follows: For each subpath,
#. compute the area of the polygon created by the path's vertices:
For a line with coordinates :math:`(x_0, y_0)` and :math:`(x_1, y_1)`, the area
of the trapezoid of its projection on the x axis is given by
.. math::
\frac{1}{2} (y_1 + y_0) (x_1 - x_0)
Summing the contribution of all lines of the polygon yields the polygon's area
(lines from left to right have a positive contribution, while those right-to
left have a negative area contribution, canceling out the computed area not
inside the polygon), so we find (setting :math:`x_{0} = x_N` etc.):
.. math::
A = \frac{1}{2} * \sum_{i=1}^N (x_i y_i - x_{i-1} y_{i-1} + x_i y_{i-1}
- x_{i-1} y_{i})
The first two terms cancel out in the summation over all points, and the second
two terms can be regrouped as
.. math::
A = \frac{1}{2} * \sum_{i=1}^N x_i (y_{i+1} -y_{i-1})
#. The contribution by the bezier curve is considered: We compute
the integral :math:`\int_{x(t=0)}^{x(t=1)} y dx`, i.e. the area between the x
axis and the curve, where :math:`y = y(t)` (the Bezier curve). By substitution
:math:`dx = x'(t) dt`, performing the integration and
subtracting the trapezoid we already considered above, we find (with control
points :math:`(x_{c1}, y_{c1})` and :math:`(x_{c2}, y_{c2})`)
.. math::
\Delta A &= \int_0^1 y(t) x'(t) dt - \frac{1}{2} (y_1 + y_0) (x_1 - x_0) \\
&= \frac{3}{20} \cdot \begin{pmatrix}
& y_0(& & 2x_{c1} & + x_{c2} & -3x_1&) \\
+ & y_{c1}(& -2x_0 & & + x_{c2} &+ x_1&) \\
+ & y_{c2}(& -x_0 & -x_{c1} & & + 2x_1&) \\
+ & y_1(& 3x_0 & - x_{c1} & -2 x_{c2} &&)
\end{pmatrix}
This is computed for every bezier and added to the area. Again, this is a signed
area: convex beziers have a positive area and concave ones a negative area
contribution.
"""
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
# EXPLANATION: https://github.com/Pomax/BezierInfo-2/issues/238#issue-554619801
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):
r"""Get center of area / gravity for a cubic superpath.
.. hint::
The results may be slightly inaccurate for paths containing arcs due
to the loss of accuracy during arc -> cubic bezier conversion.
The function works similar to :func:`csparea`, only the computations are a bit more
difficult. Again all subpaths are considered. The total center of mass is given by
.. math::
C_y = \frac{1}{A} \int_A y dA
The integral can be expressed as a weighted sum; first, the contributions
of the polygon created by the path's nodes is computed. Second, we compute the
contribution of the Bezier curve; this is again done by an integral from which
the weighted CofM of the trapezoid between end points and horizontal axis is
removed. For the integrals, we have
.. math::
A * C_{y,bez} &= \int_A y dA = \int_{x(t=0)}^{y(t=1)} \int_{0}^{y(x)} y dy dx \\
&= \int_{x(t=0)}^{y(t=1)} \frac 12 y(x)^2 dx
= \int_0^1 \frac 12 y(t)^2 x'(t) dt \\
A * C_{x,bez} &= \int_A x dA = \int_{x(t=0)}^{y(t=1)} x \int_{0}^{y(x)} dy dx \\
&= \int_{x(t=0)}^{y(t=1)} x y(x) dx = \int_0^1 x(t) y(t) x'(t) dt
from which the trapezoids are removed, in case of the y-CofM this amounts to
.. math::
\frac{y_0}{2} (x_1-x_0)y_0 + \left(y_0 + \frac 13 (y_1 - y_0)\right)
\cdot \frac 12 (y_1 - y_0) (x_1 - x_0)
"""
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,49 @@
# coding=utf-8
"""
The color module allows for the parsing and printing of CSS colors in an SVG document.
Support formats are currently:
1. #RGB #RRGGBB #RGBA #RRGGBBAA formats
2. Named colors such as 'red'
3. icc-color(...) which is specific to SVG 1.1
4. rgb(...) and rgba(...) from CSS Color Module 3
5. hsl(...) and hsla(...) from CSS Color Module 3
6. hwb(...) from CSS Color Module 4, but encoded internally as hsv
7. device-cmyk(...) from CSS Color Module 4
Each color space has it's own class, such as ColorRGB. Each space will parse multiple
formats, for example ColorRGB supports hex and rgb CSS module formats.
Each color object is a list of numbers, each number is a channel in that color space
with alpha channel being held in it's own property which may be a unit number or None.
The numbers a color stores are typically in the range defined in the CSS module
specification so for example RGB, all the numbers are between 0-255 while for hsl
the hue channel is between 0-360 and the saturation and lightness are between 0-100.
To get normalised numbers you can use to the `to_units` function to get everything 0-1
Each Color space type has a name value which can be used to identify the color space,
if this is more useful than checking the class type. Either can be used when converting
the color values between spaces.
A color object may be converted into a different space by using the
`color.to(other_space)` function, which will return a new color object in the requested
space.
There are three special cases.
1. ColorNamed is a type of ColorRGB which will preferentially print the name instead
of the hex value if one is available.
2. ColorNone is a special value which indicates the keyword `none` and does not
allow any values or alpha.
3. ColorCMS can not be converted to other color spaces and contains a `fallback_color`
to access the RGB fallback if it was provided.
"""
from .color import Color, ColorError, ColorIdError
from .utils import is_color
from .spaces import *

View File

@@ -0,0 +1,295 @@
# coding=utf-8
#
# Copyright (C) 2020 Martin Owens
# 2021 Jonathan Neuhauser
#
# 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
"""
from typing import Dict, Optional, Tuple, Union
from .converters import Converters
Number = Union[int, float]
def round_by_type(kind, number):
"""Round a number to zero or five decimal places depending on it's type"""
return kind(round(number, kind == float and 5 or 0))
class ColorError(KeyError):
"""Specific color parsing error"""
class ColorIdError(ColorError):
"""Special color error for gradient and color stop ids"""
class Color(list):
"""A parsed color object which could be in many color spaces, the default is sRGB
Can be constructed from valid CSS color attributes, as well as
tuple/list + color space. Percentage values are supported.
"""
_spaces: Dict[str, type] = {}
name: Optional[str] = None
# A list of known channels
channels: Tuple[str, ...] = ()
# A list of scales for converting css color values to known qantities
scales: Tuple[
Union[Tuple[Number, Number, bool], Tuple[Number, Number]], ...
] = () # Min (int/float), Max (int/float), [wrap around (bool:False)]
# If alpha is not specified, this is the default for most color types.
default_alpha = 1.0
def __init_subclass__(cls):
if not cls.name:
return # It is a base class
# Add space to a dictionary of available color spaces
cls._spaces[cls.name] = cls
Converters.add_space(cls)
def __new__(cls, value=None, alpha=None, arg=None):
if not cls.name:
if value is None:
return super().__new__(cls._spaces["none"])
if isinstance(value, int):
return super().__new__(cls._spaces["rgb"])
if isinstance(value, str):
# String from xml or css attributes
for space in cls._spaces.values():
if space.can_parse(value.lower()):
return super().__new__(space, value)
if isinstance(value, Color):
return super().__new__(type(value), value)
if isinstance(value, (list, tuple)):
from ..deprecated.main import _deprecated
_deprecated(
"Anonymous lists of numbers for colors no longer default to rgb"
)
return super().__new__(cls._spaces["rgb"], value)
return super().__new__(cls, value, alpha=alpha, arg=arg)
def __init__(self, values, alpha=None, arg=None):
super().__init__()
if not self.name:
raise ColorError(f"Not a known color value: '{values}' {arg}")
if not isinstance(values, (list, tuple)):
raise ColorError(
f"Colors must be constructed with a list of values: '{values}'"
)
if alpha is not None and not isinstance(alpha, float):
raise ColorError("Color alpha property must be a float number")
if alpha is None and self.channels and len(values) == len(self.channels) + 1:
alpha = values.pop()
if isinstance(values, Color):
alpha = values.alpha
if self.channels and len(values) != len(self.channels):
raise ColorError(
f"You must have {len(self.channels)} channels for a {self.name} color"
)
self[:] = values
self.alpha = alpha
def __hash__(self):
"""Allow colors to be hashable"""
return tuple(self + [self.alpha, self.name]).__hash__()
def __str__(self):
raise NotImplementedError(
f"Color space {self.name} can not be printed to a string."
)
def __int__(self):
raise NotImplementedError(
f"Color space {self.name} can not be converted to a number."
)
def __getitem__(self, index):
"""Get the color value"""
space = self.name
if (
isinstance(index, slice)
and index.start is not None
and not isinstance(index.start, int)
):
# We support the format `value = color["space_name":index]` here
space = self._spaces[index.start]
index = int(index.stop)
# Allow regular slicing to fall through more freely than setitem
if space == self.name:
return super().__getitem__(index)
if not isinstance(index, int):
raise ColorError(f"Unknown color getter definition: '{index}'")
return self.to(space)[
index
] # Note: this calls Color.__getitem__ function again
def __setitem__(self, index, value):
"""Set the color value in place, limits setter to specific color space"""
space = self.name
if isinstance(index, slice):
# Support the format color[:] = [list of numbers] here
if index.start is None and index.stop is None:
super().__setitem__(
index, (self.constrain(ind, val) for ind, val in enumerate(value))
)
return
# We support the format `color["space_name":index] = value` here
space = self._spaces[index.start]
index = int(index.stop)
if not isinstance(index, int):
raise ColorError(f"Unknown color setter definition: '{index}'")
# Setting a channel in the existing space
if space == self.name:
super().__setitem__(index, self.constrain(index, value))
else:
# Set channel is another space, convert back and forth
values = self.to(space)
values[index] = value # Note: this calls Color.__setitem__ function again
self[:] = values.to(self.name)
def to(self, space): # pylint: disable=invalid-name
"""Get this color but in a specific color space"""
if space in self._spaces.values():
space = space.name
if space not in self._spaces:
raise AttributeError(
f"Unknown color space {space} when converting from {self.name}"
)
if not hasattr(type(self), f"to_{space}"):
setattr(
type(self),
f"to_{space}",
Converters.find_converter(type(self), self._spaces[space]),
)
return getattr(self, f"to_{space}")()
def __getattr__(self, name):
if name.startswith("to_") and name.count("_") == 1:
return lambda: self.to(name.split("_")[-1])
raise AttributeError(f"Can not find attribute {type(self).__name__}.{name}")
@property
def effective_alpha(self):
"""Get the alpha as set, or tell me what it would be by default"""
if self.alpha is None:
return self.default_alpha
return self.alpha
def get_values(self, alpha=True):
"""Returns all values, including alpha as a list"""
if alpha:
return list(self + [self.effective_alpha])
return list(self)
@classmethod
def to_units(cls, *values):
"""Convert the color values into floats scales from 0.0 to 1.0"""
return [cls.scale_down(ind, val) for ind, val in enumerate(values)]
@classmethod
def from_units(cls, *values):
"""Convert float values to the scales expected and return a new instance"""
return [cls.scale_up(ind, val) for ind, val in enumerate(values)]
@classmethod
def can_parse(cls, string): # pylint: disable=unused-argument
"""Returns true if this string can be parsed for this color type"""
return False
@classmethod
def scale_up(cls, index, value):
"""Convert from float 0.0 to 1.0 to an int used in css"""
(min_value, max_value) = cls.scales[index][:2]
return cls.constrain(
index, (value * (max_value - min_value)) + min_value
) # See inkscape/src/colors/spaces/base.h:SCALE_UP
@classmethod
def scale_down(cls, index, value):
"""Convert from int, often 0 to 255 to a float 0.0 to 1.0"""
(min_value, max_value) = cls.scales[index][:2]
return (cls.constrain(index, value) - min_value) / (
max_value - min_value
) # See inkscape/src/colors/spaces/base.h:SCALE_DOWN
@classmethod
def constrain(cls, index, value):
"""Constrains the value to the css scale"""
scale = cls.scales[index]
if len(scale) == 3 and scale[2] is True:
if value == scale[1]:
return value
return round_by_type(
type(scale[0]), value % scale[1]
) # Wrap around value (i.e. hue)
return min(max(round_by_type(type(scale[0]), value), scale[0]), scale[1])
def interpolate(self, other, fraction):
"""Interpolate two colours by the given fraction
.. versionadded:: 1.1"""
from ..tween import ColorInterpolator # pylint: disable=import-outside-toplevel
try:
other = other.to(type(self))
except ColorError:
raise ColorError("Can not convert color in interpolation.")
return ColorInterpolator(self, other).interpolate(fraction)
class AlphaNotAllowed:
"""Mixin class to indicate that alpha values are not permitted on this color space"""
alpha = property(
lambda self: None,
lambda self, value: None,
)
def get_values(self, alpha=False):
return super().get_values(False)

View File

@@ -0,0 +1,122 @@
# coding=utf-8
#
# Copyright (C) 2018-2024 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-1301, USA.
#
"""
Basic color errors and common functions
"""
from collections import defaultdict
from typing import Dict, List, Callable
ConverterFunc = Callable[[float], List[float]]
class Converters:
"""
Record how colors can be converted between different spaces and provides
a way to path-find between multiple step conversions.
"""
links: Dict[str, Dict[str, ConverterFunc]] = defaultdict(dict)
chains: Dict[str, List[List[str]]] = {}
@classmethod
def add_space(cls, color_cls):
"""
Records the stated links between this class and other color spaces
"""
for name, func in color_cls.__dict__.items():
if not name.startswith("convert_"):
continue
_, direction, space = name.split("_", 2)
from_name = color_cls.name if direction == "to" else space
to_name = color_cls.name if direction == "from" else space
if from_name != to_name:
if not isinstance(func, staticmethod):
raise TypeError(f"Method '{name}' must be a static method.")
cls.links[from_name][to_name] = func.__func__
@classmethod
def get_chain(cls, source, target):
"""
Get a chain of conversions between two color spaces, if possible.
"""
def build_chains(chains, space):
new_chains = []
for chain in chains:
for hop in cls.links[space]:
if hop not in chain:
new_chains += build_chains([chain + [hop]], hop)
return chains + new_chains
if source not in cls.chains:
cls.chains[source] = build_chains([[source]], source)
chosen = None
for chain in cls.chains[source] or ():
if chain[-1] == target and (not chosen or len(chain) < len(chosen)):
chosen = chain
return chosen
@classmethod
def find_converter(cls, source, target):
"""
Find a way to convert from source to target using any conversion functions.
Will hop from one space to another if needed.
"""
func = None
# Passthough
if source == target:
return lambda self: self
if func is None:
chain = cls.get_chain(source.name, target.name)
if chain:
return cls.generate_converter(chain, source, target)
# Returning a function means we only run this function once, even when not found
def _error(self):
raise NotImplementedError(
f"Color space {source} can not be converted to {target}."
)
return _error
@classmethod
def generate_converter(cls, chain, source_cls, target_cls):
"""
Put together a function that can do every step of the chain of conversions
"""
# Build a list of functions to run
funcs = [cls.links[a][b] for a, b in zip(chain, chain[1:])]
funcs.insert(0, source_cls.to_units)
funcs.append(target_cls.from_units)
def _inner(values):
if hasattr(values, "alpha") and values.alpha is not None:
values = list(values) + [values.alpha]
for func in funcs:
values = func(*values)
return target_cls(values)
return _inner

View File

@@ -0,0 +1,11 @@
"""
Each color space that this module supports such have one file in this module.
"""
from .cmyk import ColorDeviceCMYK
from .cms import ColorCMS
from .hsl import ColorHSL
from .hsv import ColorHSV
from .named import ColorNamed
from .none import ColorNone
from .rgb import ColorRGB

View File

@@ -0,0 +1,95 @@
# coding=utf-8
#
# Copyright (C) 2024 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-1301, USA.
#
"""
SVG icc-color parser
"""
from ..color import Color, AlphaNotAllowed, ColorError, round_by_type
from .css import CssColor
from .rgb import ColorRGB
class ColorCMS(CssColor, AlphaNotAllowed):
"""
Parse and print SVG icc-color objects into their values and the fallback RGB
"""
name = "cms"
css_func = "icc-color"
channels = ()
scales = ()
def __init__(self, values, icc_profile=None, fallback=None):
if isinstance(values, str):
if values.strip().startswith("#") and " " in values:
fallback, values = values.split(" ", 1)
fallback = Color(fallback)
icc_profile, values = self.parse_css_color(values)
if icc_profile is None:
raise ColorError("CMS Color requires an icc color profile name.")
self.icc_profile = icc_profile
self.fallback_rgb = fallback
super().__init__(values)
def __str__(self) -> str:
values = self.css_join.join([f"{v:g}" for v in self.get_css_values()])
fallback = str(ColorRGB(self.fallback_rgb)) + " " if self.fallback_rgb else ""
return f"{fallback}{self.css_func}({self.icc_profile}, {values})"
@classmethod
def can_parse(cls, string: str) -> bool:
# Custom detection because of RGB fallback prefix
return "icc-color" in string.replace("(", " ").split()
@classmethod
def constrain(cls, index, value):
return min(max(round_by_type(float, value), 0.0), 1.0)
@classmethod
def scale_up(cls, index, value):
return value # All cms values are already 0.0 to 1.0
@classmethod
def scale_down(cls, index, value):
return value # All cms values are already 0.0 to 1.0
@staticmethod
def convert_to_rgb(*data):
"""Catch attempted conversions to rgb"""
raise NotImplementedError("Can not convert to RGB from icc color")
@staticmethod
def convert_from_rgb(*data):
"""Catch attempted conversions from rgb"""
raise NotImplementedError("Can not convert from RGB to icc color")
# This is research code for a future developer to use. We already use PIL and this will
# allow icc colors to be converted in python. This isn't needed right now, so this work
# will be left undone.
# @staticmethod
# def convert_to_rgb():
# from PIL import Image, ImageCms
# pixel = Image.fromarray([[int(r * 255), int(g * 255), int(b * 255)]], 'RGB')
# transform = ImageCms.buildTransform(sRGB_profile, self.this_profile, "RGB",
# self.this_profile_mode, self.this_rendering_intent, 0)
# transform.apply_in_place(pixel)
# return [p / 255 for p in pixel[0]]

View File

@@ -0,0 +1,81 @@
# coding=utf-8
#
# Copyright (C) 2024 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-1301, USA.
#
# pylint: disable=W0223
"""
DeviceCMYK Color Space
"""
from .css import CssColorModule4
class ColorDeviceCMYK(CssColorModule4):
"""
Parse the device-cmyk CSS Color Module 4 format.
Note that this format is NOT true CMYK as you might expect in a printer and
is instead is an aproximation of the intended ink levels if this was converted
into a real CMYK color profile using a color management system.
"""
name = "cmyk"
channels = ("cyan", "magenta", "yellow", "black")
scales = ((0, 100), (0, 100), (0, 100), (0, 100), (0.0, 1.0))
css_either_prefix = "device-cmyk"
cyan = property(
lambda self: self[0], lambda self, value: self.__setitem__(0, value)
)
magenta = property(
lambda self: self[1], lambda self, value: self.__setitem__(1, value)
)
yellow = property(
lambda self: self[2], lambda self, value: self.__setitem__(2, value)
)
black = property(
lambda self: self[3], lambda self, value: self.__setitem__(3, value)
)
@staticmethod
def convert_to_rgb(cyan, magenta, yellow, black, *alpha):
"""
Convert a set of Device-CMYK identities into RGB
"""
white = 1.0 - black
return [
1.0 - min((1.0, cyan * white + black)),
1.0 - min((1.0, magenta * white + black)),
1.0 - min((1.0, yellow * white + black)),
] + list(alpha)
@staticmethod
def convert_from_rgb(red, green, blue, *alpha):
"""
Convert RGB into Device-CMYK
"""
white = max((red, green, blue))
black = 1.0 - white
return [
# Each channel is it's color chart oposite (cyan->red)
# with a bit of white removed.
(white and (1.0 - red - black) / white or 0.0),
(white and (1.0 - green - black) / white or 0.0),
(white and (1.0 - blue - black) / white or 0.0),
black,
] + list(alpha)

View File

@@ -0,0 +1,139 @@
# coding=utf-8
#
# Copyright (C) 2018-2024 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-1301, USA.
#
# pylint: disable=W0223
"""
Parsing CSS elements from colors
"""
from typing import Optional, Union
from ..color import Color, ColorError, ColorIdError
class CssColor(Color):
"""
A Color which is always parsed and printed from a css format.
"""
# A list of css prefixes which ar valid for this space
css_noalpha_prefix: Optional[str] = None
css_alpha_prefix: Optional[str] = None
css_either_prefix: Optional[str] = None
# Some CSS formats require commas, others do not
css_join: str = ", "
css_join_alpha: str = ", "
css_func = "color"
def __str__(self):
values = self.css_join.join([f"{v:g}" for v in self.get_css_values()])
prefix = self.css_noalpha_prefix or self.css_either_prefix
if self.alpha is not None:
# Alpha is stored as a percent for clarity
alpha = int(self.alpha * 100)
values += self.css_join_alpha + f"{alpha}%"
if not self.css_either_prefix:
prefix = self.css_alpha_prefix
if prefix is None:
raise ColorError(f"Can't encode color {self.name} into CSS color format.")
return f"{prefix}({values})"
@classmethod
def can_parse(cls, string: str):
string = string.replace(" ", "")
if "(" not in string or ")" not in string:
return False
for prefix in (
cls.css_noalpha_prefix,
cls.css_alpha_prefix,
cls.css_either_prefix,
):
if prefix and (prefix + "(" in string or "color(" + prefix in string):
return True
return False
def __init__(self, value, alpha=None):
if isinstance(value, str):
prefix, values = self.parse_css_color(value)
has_alpha = (
self.channels is not None and len(values) == len(self.channels) + 1
)
if prefix == self.css_noalpha_prefix or (
prefix == self.css_either_prefix and not has_alpha
):
super().__init__(values)
elif prefix == self.css_alpha_prefix or (
prefix == self.css_either_prefix and has_alpha
):
super().__init__(values, values.pop())
else:
raise ColorError(f"Could not parse {self.name} css color: '{value}'")
else:
super().__init__(value, alpha=alpha)
@classmethod
def parse_css_color(cls, value):
"""Parse a css string into a list of values and it's color space prefix"""
prefix, values = value.lower().strip().strip(")").split("(")
# Some css formats use commas, others do not
if "," in cls.css_join:
values = values.replace(",", " ")
if "/" in cls.css_join_alpha:
values = values.replace("/", " ")
# Split values by spaces
values = values.split()
prefix = prefix.strip()
if prefix == cls.css_func:
prefix = values.pop(0)
if prefix == "url":
raise ColorIdError("Can not parse url as if it was a color.")
return prefix, [cls.parse_css_value(i, v) for i, v in enumerate(values)]
def get_css_values(self):
"""Return a list of values used for css string output"""
return self
@classmethod
def parse_css_value(cls, index, value) -> Union[int, float]:
"""Parse a CSS value such as 100%, 360 or 0.4"""
if cls.scales and index >= len(cls.scales):
raise ValueError("Can't add any more values to color.")
if isinstance(value, str):
value = value.strip()
if value.endswith("%"):
value = float(value.strip("%")) / 100
elif "." in value:
value = float(value)
else:
value = int(value)
if isinstance(value, float) and value <= 1.0:
value = cls.scale_up(index, value)
return cls.constrain(index, value)
class CssColorModule4(CssColor):
"""Tweak the css parser for CSS Module Four formating"""
css_join = " "
css_join_alpha = " / "

View File

@@ -0,0 +1,107 @@
# coding=utf-8
#
# Copyright (C) 2024 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-1301, USA.
#
# pylint: disable=W0223
"""
HSL Color Space
"""
from .css import CssColor
class ColorHSL(CssColor):
"""
Parse the HSL CSS Module Module 3 format.
"""
name = "hsl"
channels = ("hue", "saturation", "lightness")
scales = ((0, 360, True), (0, 100), (0, 100), (0.0, 1.0))
css_noalpha_prefix = "hsl"
css_alpha_prefix = "hsla"
hue = property(lambda self: self[0], lambda self, value: self.__setitem__(0, value))
saturation = property(
lambda self: self[1], lambda self, value: self.__setitem__(1, value)
)
lightness = property(
lambda self: self[2], lambda self, value: self.__setitem__(2, value)
)
@staticmethod
def convert_from_rgb(red, green, blue, alpha=None):
"""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
if alpha is not None:
hsl.append(alpha)
return hsl
@staticmethod
def convert_to_rgb(hue, sat, light, *alpha):
"""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
ret = [
_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),
]
return ret + list(alpha)
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,88 @@
# coding=utf-8
#
# Copyright (C) 2024 Jonathan Neuhauser
# 2024 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-1301, USA.
#
# pylint: disable=W0223
"""
HSV Color Space
"""
from .css import CssColorModule4
class ColorHSV(CssColorModule4):
"""
Parse the HWB CSS Color Module 4 format and retain as HSV values.
"""
name = "hsv"
channels = ("hue", "saturation", "value")
scales = ((0, 360, True), (0, 100), (0, 100), (0.0, 1.0))
# We use HWB to store HSV as this makes the most sense to Inkscape
css_either_prefix = "hwb"
hue = property(lambda self: self[0], lambda self, value: self.__setitem__(0, value))
saturation = property(
lambda self: self[1], lambda self, value: self.__setitem__(1, value)
)
value = property(
lambda self: self[2], lambda self, value: self.__setitem__(2, value)
)
@classmethod
def parse_css_color(cls, value):
"""Parsing HWB as if it was HSV for css input"""
prefix, values = super().parse_css_color(value)
# See https://en.wikipedia.org/wiki/HWB_color_model#Converting_to_and_from_HSV
values[1] /= 100
values[2] /= 100
scale = values[1] + values[2]
if scale > 1.0:
values[1] /= scale
values[2] /= scale
values[1] = int(
(values[2] == 1.0 and 0.0 or (1.0 - (values[1] / (1.0 - values[2])))) * 100
)
values[2] = int((1.0 - values[2]) * 100)
return prefix, values
def get_css_values(self):
"""Convert our HSV values into HWB for css output"""
values = list(self)
values[1] = (100 - values[1]) * (values[2] / 100)
values[2] = 100 - values[2]
return values
@staticmethod
def convert_to_hsl(hue, saturation, value, *alpha):
"""Conversion according to
https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_HSL
.. versionadded:: 1.5"""
lum = value * (1 - saturation / 2)
sat = 0 if lum in (0, 1) else (value - lum) / min(lum, 1 - lum)
return [hue, sat, lum] + list(alpha)
@staticmethod
def convert_from_hsl(hue, saturation, lightness, *alpha):
"""Convertion according to Inkscape C++ codebase
.. versionadded:: 1.5"""
val = lightness + saturation * min(lightness, 1 - lightness)
sat = 0 if val == 0 else 2 * (1 - lightness / val)
return [hue, sat, val] + list(alpha)

View File

@@ -0,0 +1,236 @@
# coding=utf-8
#
# Copyright (C) 2024, 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-1301, USA.
#
"""
CSS Named colors
"""
from typing import Dict
from ..color import Color
from .rgb import ColorRGB
_COLORS = {
"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",
}
class ColorNamed(ColorRGB):
"""
Parse specific named colors, fall back to RGB parsing if it fails.
"""
_color_names: Dict[ColorRGB, str] = {}
_name_colors: Dict[str, ColorRGB] = {}
name = "named"
def __init__(self, name, alpha=None):
if isinstance(name, str):
super().__init__(self.name_colors()[name.lower().strip()])
else:
super().__init__(name, alpha=alpha)
@classmethod
def color_names(cls):
"""Cache a list of color names"""
if not cls._color_names:
cls._color_names = {
value: name for name, value in cls.name_colors().items()
}
return cls._color_names
@classmethod
def name_colors(cls):
"""Cache a list of color objects"""
if not cls._name_colors:
cls._name_colors = {name: Color(value) for name, value in _COLORS.items()}
return cls._name_colors
def __str__(self):
return self.color_names().get(self, super().__str__())
def __hash__(self):
"""Allow named colors to match rgb colors"""
return tuple(self + [self.alpha, super().name]).__hash__()
@classmethod
def can_parse(cls, string: str):
"""If the string is one of the color names, we can parse it"""
return string in cls.name_colors()
@staticmethod
def convert_to_rgb(*data):
"""Converting to RGB is transparent, already in RGB"""
return data
@staticmethod
def convert_from_rgb(*data):
"""Converting from RGB is transparent, the store is RGB"""
return data
def to_rgb(self):
"""Prevent masking by ColorRGB of to_rgb method"""
return ColorRGB(list(self), alpha=self.alpha)

View File

@@ -0,0 +1,55 @@
# coding=utf-8
#
# Copyright (C) 2021 Jonathan Neuhauser
# 2020 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-1301, USA.
#
# pylint: disable=W0223
"""
An empty color for 'none'
"""
from ..color import Color, AlphaNotAllowed
class ColorNone(Color, AlphaNotAllowed):
"""A special color for 'none' colors"""
name = "none"
# Override opacity since none can not have opacity
default_alpha = 0.0
def __init__(self, value=None):
pass
def __str__(self) -> str:
return "none"
@classmethod
def can_parse(cls, string: str) -> bool:
"""Returns true if this is the word 'none'"""
return string == "none"
@staticmethod
def convert_to_rgb(*_):
"""Converting to RGB means transparent black"""
return [0, 0, 0, 0]
@staticmethod
def convert_from_rgb(*_):
"""Converting from RGB means throwing out all data"""
return []

View File

@@ -0,0 +1,105 @@
# coding=utf-8
#
# Copyright (C) 2024, 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-1301, USA.
#
"""
RGB Colors
"""
from ..color import ColorError
from .css import CssColor
class ColorRGB(CssColor):
"""
Parse multiple versions of RGB from CSS module and standard hex formats.
"""
name = "rgb"
channels = ("red", "green", "blue")
scales = ((0, 255), (0, 255), (0, 255), (0.0, 1.0))
css_noalpha_prefix = "rgb"
css_alpha_prefix = "rgba"
red = property(lambda self: self[0], lambda self, value: self.__setitem__(0, value))
green = property(
lambda self: self[1], lambda self, value: self.__setitem__(1, value)
)
blue = property(
lambda self: self[2], lambda self, value: self.__setitem__(2, value)
)
@classmethod
def can_parse(cls, string: str) -> bool:
return "icc" not in string and (
string.startswith("#")
or string.lstrip("-").isdigit()
or super().can_parse(string)
)
def __init__(self, value, alpha=None):
# Not CSS, but inkscape, some old color values stores as 32bit int strings
if isinstance(value, str) and value.lstrip("-").isdigit():
value = int(value)
if isinstance(value, int):
super().__init__(
[
((value >> 24) & 255), # red
((value >> 16) & 255), # green
((value >> 8) & 255), # blue
((value & 255) / 255.0),
]
) # opacity
elif isinstance(value, str) and value.startswith("#") and " " not in value:
if len(value) == 4: # (css: #rgb -> #rrggbb)
# pylint: disable=consider-using-f-string
value = "#{1}{1}{2}{2}{3}{3}".format(*value)
elif len(value) == 5: # (css: #rgba -> #rrggbbaa)
# pylint: disable=consider-using-f-string
value = "#{1}{1}{2}{2}{3}{3}{4}{4}".format(*value)
# Convert hex to integers
try:
values = [int(value[i : i + 2], 16) for i in range(1, len(value), 2)]
if len(values) == 4:
values[3] /= 255
super().__init__(values)
except ValueError as error:
raise ColorError(f"Bad RGB hex color value '{value}'") from error
else:
super().__init__(value, alpha=alpha)
def __str__(self) -> str:
if self.alpha is not None:
return super().__str__()
if len(self) < len(self.channels):
raise ColorError(
f"Incorrect number of channels for Color Space {self.name}"
)
# Always hex values when outputting color
return "#{0:02x}{1:02x}{2:02x}".format(*(int(v) for v in self)) # pylint: disable=consider-using-f-string
def __int__(self) -> int:
return (
(self[0] << 24)
+ (self[1] << 16)
+ (self[2] << 8)
+ int((self.alpha or 1.0) * 255)
)

View File

@@ -0,0 +1,31 @@
# coding=utf-8
#
# Copyright (C) 2018-2024 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-1301, USA.
#
"""
Utilities for color support
"""
from .color import Color, ColorError
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

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,3 @@
"""CSS Processing module"""
from .compiler import CSSCompiler

View File

@@ -0,0 +1,483 @@
# coding=utf-8
#
# Copyright (C) 2023 - 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.
#
"""CSS evaluation logic, forked from cssselect2 (rewritten without eval, targeted to
our data structure). CSS selectors are compiled into boolean evaluator functions.
All HTML-specific code has been removed, and we don't duplicate the tree data structure
but work on the normal tree."""
import re
from lxml import etree
from typing import Union, List
from tinycss2.nth import parse_nth
from . import parser
from .parser import SelectorError
# http://dev.w3.org/csswg/selectors/#whitespace
split_whitespace = re.compile("[^ \t\r\n\f]+").findall
def ascii_lower(string): # from webencodings
r"""Transform (only) ASCII letters to lower case: A-Z is mapped to a-z."""
return string.encode("utf8").lower().decode("utf8")
# pylint: disable=protected-access,comparison-with-callable,invalid-name,bad-super-call
# pylint: disable=unnecessary-lambda-assignment
## Iterators without comments.
def iterancestors(element):
"""Iterate over ancestors but ignore comments."""
for e in element.iterancestors():
if isinstance(e, etree._Comment):
continue
yield e
def iterdescendants(element):
"""Iterate over descendants but ignore comments"""
for e in element.iterdescendants():
if isinstance(e, etree._Comment):
continue
yield e
def itersiblings(element, preceding=False):
"""Iterate over descendants but ignore comments"""
for e in element.itersiblings(preceding=preceding):
if isinstance(e, etree._Comment):
continue
yield e
def iterchildren(element):
"""Iterate over children but ignore comments"""
for e in element.iterchildren():
if isinstance(e, etree._Comment):
continue
yield e
def getprevious(element):
"""Get the previous non-comment element"""
for e in itersiblings(element, preceding=True):
return e
return None
def getnext(element):
"""Get the next non-comment element"""
for e in itersiblings(element, preceding=False):
return e
return None
def FALSE(_el):
"""Always returns 0"""
return 0
def TRUE(_el):
"""Always returns 1"""
return 1
class BooleanCompiler:
def __init__(self) -> None:
self._func_map = {
parser.CombinedSelector: self._compile_combined,
parser.CompoundSelector: self._compile_compound,
parser.NegationSelector: self._compile_negation,
parser.RelationalSelector: self._compile_relational,
parser.MatchesAnySelector: self._compile_any,
parser.SpecificityAdjustmentSelector: self._compile_any,
parser.LocalNameSelector: self._compile_local_name,
parser.NamespaceSelector: self._compile_namespace,
parser.ClassSelector: self._compile_class,
parser.IDSelector: self._compile_id,
parser.AttributeSelector: self._compile_attribute,
parser.PseudoClassSelector: self._compile_pseudoclass,
parser.FunctionalPseudoClassSelector: self._compile_functional_pseudoclass,
}
def _compile_combined(self, selector: parser.CombinedSelector):
left_inside = self.compile_node(selector.left)
if left_inside == FALSE:
return FALSE # 0 and x == 0
if left_inside == TRUE:
# 1 and x == x, but the element matching 1 still needs to exist.
if selector.combinator in (" ", ">"):
left = lambda el: el.getparent() is not None
elif selector.combinator in ("~", "+"):
left = lambda el: getprevious(el) is not None
else:
raise SelectorError("Unknown combinator", selector.combinator)
elif selector.combinator == " ":
left = lambda el: any((left_inside(e)) for e in el.ancestors())
elif selector.combinator == ">":
left = lambda el: el.getparent() is not None and left_inside(el.getparent())
elif selector.combinator == "+":
left = lambda el: getprevious(el) is not None and left_inside(
getprevious(el)
)
elif selector.combinator == "~":
left = lambda el: any(
(left_inside(e)) for e in itersiblings(el, preceding=True)
)
else:
raise SelectorError("Unknown combinator", selector.combinator)
right = self.compile_node(selector.right)
if right == FALSE:
return FALSE # 0 and x == 0
if right == TRUE:
return left # 1 and x == x
# Evaluate combinators right to left
return lambda el: right(el) and left(el)
def _compile_compound(self, selector: parser.CompoundSelector):
sub_expressions = [
expr
for expr in map(self.compile_node, selector.simple_selectors)
if expr != TRUE
]
if len(sub_expressions) == 1:
return sub_expressions[0]
if FALSE in sub_expressions:
return FALSE
if sub_expressions:
return lambda e: all(expr(e) for expr in sub_expressions)
return TRUE # all([]) == True
def _compile_negation(self, selector: parser.NegationSelector):
sub_expressions = [
expr
for expr in [
self.compile_node(selector.parsed_tree)
for selector in selector.selector_list
]
if expr != TRUE
]
if not sub_expressions:
return FALSE
return lambda el: not any(expr(el) for expr in sub_expressions)
@staticmethod
def _get_subexpr(expression, relative_selector):
"""Helper function for RelationalSelector"""
if relative_selector.combinator == " ":
return lambda el: any(expression(e) for e in iterdescendants(el))
if relative_selector.combinator == ">":
return lambda el: any(expression(e) for e in iterchildren(el))
if relative_selector.combinator == "+":
return lambda el: expression(next(itersiblings(el)))
if relative_selector.combinator == "~":
return lambda el: any(expression(e) for e in itersiblings(el))
raise SelectorError(
f"Unknown relational selector '{relative_selector.combinator}'"
)
def _compile_relational(self, selector: parser.RelationalSelector):
sub_expr = []
for relative_selector in selector.selector_list:
expression = self.compile_node(relative_selector.selector.parsed_tree)
if expression == FALSE:
continue
sub_expr.append(self._get_subexpr(expression, relative_selector))
return lambda el: any(expr(el) for expr in sub_expr)
def _compile_any(
self,
selector: Union[
parser.MatchesAnySelector, parser.SpecificityAdjustmentSelector
],
):
sub_expressions = [
expr
for expr in [
self.compile_node(selector.parsed_tree)
for selector in selector.selector_list
]
if expr != FALSE
]
if not sub_expressions:
return FALSE
return lambda el: any(expr(el) for expr in sub_expressions)
def _compile_local_name(self, selector: parser.LocalNameSelector):
return lambda el: el.TAG == selector.local_name
def _compile_namespace(self, selector: parser.NamespaceSelector):
return lambda el: el.NAMESPACE == selector.namespace
def _compile_class(self, selector: parser.ClassSelector):
return lambda el: selector.class_name in el.classes
def _compile_id(self, selector: parser.IDSelector):
return lambda el: super(etree.ElementBase, el).get("id", None) == selector.ident # type: ignore
def _compile_attribute(self, selector: parser.AttributeSelector):
if selector.namespace is not None:
if selector.namespace:
key_func = lambda el: (
f"{{{selector.namespace}}}{selector.name}"
if el.NAMESPACE != selector.namespace
else selector.name
)
else:
key_func = lambda el: selector.name
value = selector.value
if selector.case_sensitive is False:
value = value.lower()
attribute_value = (
lambda el: super(etree.ElementBase, el)
.get(key_func(el), "") # type: ignore
.lower()
)
else:
attribute_value = lambda el: super(etree.ElementBase, el).get( # type: ignore
key_func(el), ""
)
if selector.operator is None:
return lambda el: key_func(el) in el.attrib
if selector.operator == "=":
return lambda el: (
key_func(el) in el.attrib and attribute_value(el) == value
)
if selector.operator == "~=":
return (
FALSE
if len(value.split()) != 1 or value.strip() != value
else lambda el: value in split_whitespace(attribute_value(el))
)
if selector.operator == "|=":
return lambda el: (
key_func(el) in el.attrib
and (
attribute_value(el) == value
or attribute_value(el).startswith(value + "-")
)
)
if selector.operator == "^=":
if value:
return lambda el: attribute_value(el).startswith(value)
return FALSE
if selector.operator == "$=":
return (
(lambda el: attribute_value(el).endswith(value)) if value else FALSE
)
if selector.operator == "*=":
return (lambda el: value in attribute_value(el)) if value else FALSE
raise SelectorError("Unknown attribute operator", selector.operator)
# In any namespace
raise NotImplementedError # TODO
def _compile_pseudoclass(self, selector: parser.PseudoClassSelector):
if selector.name in ("link", "any-link", "local-link"):
def ancestors_or_self(el):
yield el
yield from iterancestors(el)
return lambda el: any(
e.TAG == "a" and super(etree.ElementBase, e).get("href", "") != "" # type: ignore
for e in ancestors_or_self(el)
)
if selector.name in (
"visited",
"hover",
"active",
"focus",
"focus-within",
"focus-visible",
"target",
"target-within",
"current",
"past",
"future",
"playing",
"paused",
"seeking",
"buffering",
"stalled",
"muted",
"volume-locked",
"user-valid",
"user-invalid",
):
# Not applicable in a static context: never match.
return FALSE
if selector.name in ("enabled", "disabled", "checked"):
# Not applicable to SVG
return FALSE
if selector.name in ("root", "scope"):
return lambda el: el.getparent() is None
if selector.name == "first-child":
return lambda el: getprevious(el) is None
if selector.name == "last-child":
return lambda el: getnext(el) is None
if selector.name == "first-of-type":
return lambda el: all(
s.tag != el.tag for s in itersiblings(el, preceding=True)
)
if selector.name == "last-of-type":
return lambda el: all(s.tag != el.tag for s in itersiblings(el))
if selector.name == "only-child":
return lambda el: getnext(el) is None and getprevious(el) is None
if selector.name == "only-of-type":
return lambda el: all(s.tag != el.tag for s in itersiblings(el)) and all(
s.tag != el.tag for s in itersiblings(el, preceding=True)
)
if selector.name == "empty":
return lambda el: not list(el) and el.text is None
raise SelectorError("Unknown pseudo-class", selector.name)
def _compile_lang(self, selector: parser.FunctionalPseudoClassSelector):
langs = []
tokens = [
token
for token in selector.arguments
if token.type not in ("whitespace", "comment")
]
while tokens:
token = tokens.pop(0)
if token.type == "ident":
langs.append(token.lower_value)
elif token.type == "string":
langs.append(ascii_lower(token.value))
else:
raise SelectorError("Invalid arguments for :lang()")
if tokens:
token = tokens.pop(0)
if token.type != "ident" and token.value != ",":
raise SelectorError("Invalid arguments for :lang()")
def haslang(el, lang):
print(
el.get("lang"),
lang,
el.get("lang", "") == lang or el.get("lang", "").startswith(lang + "-"),
)
return el.get("lang", "").lower() == lang or el.get(
"lang", ""
).lower().startswith(lang + "-")
return lambda el: any(
haslang(el, lang) or any(haslang(el2, lang) for el2 in iterancestors(el))
for lang in langs
)
def _compile_functional_pseudoclass(
self, selector: parser.FunctionalPseudoClassSelector
):
if selector.name == "lang":
return self._compile_lang(selector)
nth: List[str] = []
selector_list: List[str] = []
current_list = nth
for argument in selector.arguments:
if argument.type == "ident" and argument.value == "of":
if current_list is nth:
current_list = selector_list
continue
current_list.append(argument)
if selector_list:
compiled = tuple(
self.compile_node(selector.parsed_tree)
for selector in parser.parse(selector_list)
)
test = lambda el: all(expr(el) for expr in compiled)
else:
test = TRUE
if selector.name == "nth-child":
count = lambda el: sum(
1 for e in itersiblings(el, preceding=True) if test(e)
)
elif selector.name == "nth-last-child":
count = lambda el: sum(1 for e in itersiblings(el) if test(e))
elif selector.name == "nth-of-type":
count = lambda el: sum(
1
for s in (e for e in itersiblings(el, preceding=True) if test(e))
if s.tag == el.tag
)
elif selector.name == "nth-last-of-type":
count = lambda el: sum(
1 for s in (e for e in itersiblings(el) if test(e)) if s.tag == el.tag
)
else:
raise SelectorError("Unknown pseudo-class", selector.name)
count_func = lambda el: count(el) if test(el) else float("nan")
result = parse_nth(nth)
if result is None:
raise SelectorError(f"Invalid arguments for :{selector.name}()")
a, b = result
# x is the number of siblings before/after the element
# Matches if a positive or zero integer n exists so that:
# x = a*n + b-1
# x = a*n + B
B = b - 1
if a == 0:
# x = B
return lambda el: count_func(el) == B
# n = (x - B) / a
def evaluator(el):
n, r = divmod(count_func(el) - B, a)
return r == 0 and n >= 0
return evaluator
def compile_node(self, selector):
"""Return a boolean expression, as a callable.
When evaluated in a context where the `el` variable is an
:class:`cssselect2.tree.Element` object, tells whether the element is a
subject of `selector`.
"""
try:
return self._func_map[selector.__class__](selector)
except KeyError as e:
raise TypeError(type(selector), selector) from e
CSSCompiler = BooleanCompiler()

View File

@@ -0,0 +1,548 @@
# Forked from cssselect2, 1.2.1, BSD License
"""Parse CSS declarations."""
from tinycss2 import parse_component_value_list
__all__ = ["parse"]
SUPPORTED_PSEUDO_ELEMENTS = {
# As per CSS Pseudo-Elements Module Level 4
"first-line",
"first-letter",
"prefix",
"postfix",
"selection",
"target-text",
"spelling-error",
"grammar-error",
"before",
"after",
"marker",
"placeholder",
"file-selector-button",
# As per CSS Generated Content for Paged Media Module
"footnote-call",
"footnote-marker",
# As per CSS Scoping Module Level 1
"content",
"shadow",
}
def parse(input, namespaces=None, forgiving=False, relative=False):
"""Yield tinycss2 selectors found in given ``input``.
:param input:
A string, or an iterable of tinycss2 component values.
"""
if isinstance(input, str):
input = parse_component_value_list(input)
tokens = TokenStream(input)
namespaces = namespaces or {}
try:
yield parse_selector(tokens, namespaces, relative)
except SelectorError as exception:
if forgiving:
return
raise exception
while 1:
next = tokens.next()
if next is None:
return
elif next == ",":
try:
yield parse_selector(tokens, namespaces, relative)
except SelectorError as exception:
if not forgiving:
raise exception
else:
if not forgiving:
raise SelectorError(next, f"unexpected {next.type} token.")
def parse_selector(tokens, namespaces, relative=False):
tokens.skip_whitespace_and_comment()
if relative:
peek = tokens.peek()
if peek in (">", "+", "~"):
initial_combinator = peek.value
tokens.next()
else:
initial_combinator = " "
tokens.skip_whitespace_and_comment()
result, pseudo_element = parse_compound_selector(tokens, namespaces)
while 1:
has_whitespace = tokens.skip_whitespace()
while tokens.skip_comment():
has_whitespace = tokens.skip_whitespace() or has_whitespace
selector = Selector(result, pseudo_element)
if relative:
selector = RelativeSelector(initial_combinator, selector)
if pseudo_element is not None:
return selector
peek = tokens.peek()
if peek is None or peek == ",":
return selector
elif peek in (">", "+", "~"):
combinator = peek.value
tokens.next()
elif has_whitespace:
combinator = " "
else:
return selector
compound, pseudo_element = parse_compound_selector(tokens, namespaces)
result = CombinedSelector(result, combinator, compound)
def parse_compound_selector(tokens, namespaces):
type_selectors = parse_type_selector(tokens, namespaces)
simple_selectors = type_selectors if type_selectors is not None else []
while 1:
simple_selector, pseudo_element = parse_simple_selector(tokens, namespaces)
if pseudo_element is not None or simple_selector is None:
break
simple_selectors.append(simple_selector)
if simple_selectors or (type_selectors, pseudo_element) != (None, None):
return CompoundSelector(simple_selectors), pseudo_element
peek = tokens.peek()
peek_type = peek.type if peek else "EOF"
raise SelectorError(peek, f"expected a compound selector, got {peek_type}")
def parse_type_selector(tokens, namespaces):
tokens.skip_whitespace()
qualified_name = parse_qualified_name(tokens, namespaces)
if qualified_name is None:
return None
simple_selectors = []
namespace, local_name = qualified_name
if local_name is not None:
simple_selectors.append(LocalNameSelector(local_name))
if namespace is not None:
simple_selectors.append(NamespaceSelector(namespace))
return simple_selectors
def parse_simple_selector(tokens, namespaces):
peek = tokens.peek()
if peek is None:
return None, None
if peek.type == "hash" and peek.is_identifier:
tokens.next()
return IDSelector(peek.value), None
elif peek == ".":
tokens.next()
next = tokens.next()
if next is None or next.type != "ident":
raise SelectorError(next, f"Expected a class name, got {next}")
return ClassSelector(next.value), None
elif peek.type == "[] block":
tokens.next()
attr = parse_attribute_selector(TokenStream(peek.content), namespaces)
return attr, None
elif peek == ":":
tokens.next()
next = tokens.next()
if next == ":":
next = tokens.next()
if next is None or next.type != "ident":
raise SelectorError(next, f"Expected a pseudo-element name, got {next}")
value = next.lower_value
if value not in SUPPORTED_PSEUDO_ELEMENTS:
raise SelectorError(
next, f"Expected a supported pseudo-element, got {value}"
)
return None, value
elif next is not None and next.type == "ident":
name = next.lower_value
if name in ("before", "after", "first-line", "first-letter"):
return None, name
else:
return PseudoClassSelector(name), None
elif next is not None and next.type == "function":
name = next.lower_name
if name in ("is", "where", "not", "has"):
return parse_logical_combination(next, namespaces, name), None
else:
return (FunctionalPseudoClassSelector(name, next.arguments), None)
else:
raise SelectorError(next, f"unexpected {next} token.")
else:
return None, None
def parse_logical_combination(matches_any_token, namespaces, name):
forgiving = True
relative = False
if name == "is":
selector_class = MatchesAnySelector
elif name == "where":
selector_class = SpecificityAdjustmentSelector
elif name == "not":
forgiving = False
selector_class = NegationSelector
elif name == "has":
relative = True
selector_class = RelationalSelector
selectors = [
selector
for selector in parse(
matches_any_token.arguments, namespaces, forgiving, relative
)
if selector.pseudo_element is None
]
return selector_class(selectors)
def parse_attribute_selector(tokens, namespaces):
tokens.skip_whitespace()
qualified_name = parse_qualified_name(tokens, namespaces, is_attribute=True)
if qualified_name is None:
next = tokens.next()
raise SelectorError(next, f"expected attribute name, got {next}")
namespace, local_name = qualified_name
tokens.skip_whitespace()
peek = tokens.peek()
if peek is None:
operator = None
value = None
elif peek in ("=", "~=", "|=", "^=", "$=", "*="):
operator = peek.value
tokens.next()
tokens.skip_whitespace()
next = tokens.next()
if next is None or next.type not in ("ident", "string"):
next_type = "None" if next is None else next.type
raise SelectorError(next, f"expected attribute value, got {next_type}")
value = next.value
else:
raise SelectorError(peek, f"expected attribute selector operator, got {peek}")
tokens.skip_whitespace()
next = tokens.next()
case_sensitive = None
if next is not None:
if next.type == "ident" and next.value.lower() == "i":
case_sensitive = False
elif next.type == "ident" and next.value.lower() == "s":
case_sensitive = True
else:
raise SelectorError(next, f"expected ], got {next.type}")
return AttributeSelector(namespace, local_name, operator, value, case_sensitive)
def parse_qualified_name(tokens, namespaces, is_attribute=False):
"""Return ``(namespace, local)`` for given tokens.
Can also return ``None`` for a wildcard.
The empty string for ``namespace`` means "no namespace".
"""
peek = tokens.peek()
if peek is None:
return None
if peek.type == "ident":
first_ident = tokens.next()
peek = tokens.peek()
if peek != "|":
namespace = "" if is_attribute else namespaces.get(None, None)
return namespace, (first_ident.value, first_ident.lower_value)
tokens.next()
namespace = namespaces.get(first_ident.value)
if namespace is None:
raise SelectorError(
first_ident, f"undefined namespace prefix: {first_ident.value}"
)
elif peek == "*":
next = tokens.next()
peek = tokens.peek()
if peek != "|":
if is_attribute:
raise SelectorError(next, f"expected local name, got {next.type}")
return namespaces.get(None, None), None
tokens.next()
namespace = None
elif peek == "|":
tokens.next()
namespace = ""
else:
return None
# If we get here, we just consumed '|' and set ``namespace``
next = tokens.next()
if next.type == "ident":
return namespace, (next.value, next.lower_value)
elif next == "*" and not is_attribute:
return namespace, None
else:
raise SelectorError(next, f"expected local name, got {next.type}")
class SelectorError(ValueError):
"""A specialized ``ValueError`` for invalid selectors."""
class TokenStream:
def __init__(self, tokens):
self.tokens = iter(tokens)
self.peeked = [] # In reversed order
def next(self):
if self.peeked:
return self.peeked.pop()
else:
return next(self.tokens, None)
def peek(self):
if not self.peeked:
self.peeked.append(next(self.tokens, None))
return self.peeked[-1]
def skip(self, skip_types):
found = False
while 1:
peek = self.peek()
if peek is None or peek.type not in skip_types:
break
self.next()
found = True
return found
def skip_whitespace(self):
return self.skip(["whitespace"])
def skip_comment(self):
return self.skip(["comment"])
def skip_whitespace_and_comment(self):
return self.skip(["comment", "whitespace"])
class Selector:
def __init__(self, tree, pseudo_element=None):
self.parsed_tree = tree
self.pseudo_element = pseudo_element
if pseudo_element is None:
#: Tuple of 3 integers: http://www.w3.org/TR/selectors/#specificity
self.specificity = tree.specificity
else:
a, b, c = tree.specificity
self.specificity = a, b, c + 1
def __repr__(self):
pseudo = f"::{self.pseudo_element}" if self.pseudo_element else ""
return f"{self.parsed_tree!r}{pseudo}"
class RelativeSelector:
def __init__(self, combinator, selector):
self.combinator = combinator
self.selector = selector
@property
def specificity(self):
return self.selector.specificity
@property
def pseudo_element(self):
return self.selector.pseudo_element
def __repr__(self):
return (
f"{self.selector!r}"
if self.combinator == " "
else f"{self.combinator} {self.selector!r}"
)
class CombinedSelector:
def __init__(self, left, combinator, right):
#: Combined or compound selector
self.left = left
# One of `` `` (a single space), ``>``, ``+`` or ``~``.
self.combinator = combinator
#: compound selector
self.right = right
@property
def specificity(self):
a1, b1, c1 = self.left.specificity
a2, b2, c2 = self.right.specificity
return a1 + a2, b1 + b2, c1 + c2
def __repr__(self):
return f"{self.left!r}{self.combinator}{self.right!r}"
class CompoundSelector:
def __init__(self, simple_selectors):
self.simple_selectors = simple_selectors
@property
def specificity(self):
if self.simple_selectors:
# zip(*foo) turns [(a1, b1, c1), (a2, b2, c2), ...]
# into [(a1, a2, ...), (b1, b2, ...), (c1, c2, ...)]
return tuple(
map(sum, zip(*(sel.specificity for sel in self.simple_selectors)))
)
else:
return 0, 0, 0
def __repr__(self):
return "".join(map(repr, self.simple_selectors))
class LocalNameSelector:
specificity = 0, 0, 1
def __init__(self, local_name):
self.local_name, self.lower_local_name = local_name
def __repr__(self):
return self.local_name
class NamespaceSelector:
specificity = 0, 0, 0
def __init__(self, namespace):
#: The namespace URL as a string,
#: or the empty string for elements not in any namespace.
self.namespace = namespace
def __repr__(self):
if self.namespace == "":
return "|"
else:
return f"{{{self.namespace}}}|"
class IDSelector:
specificity = 1, 0, 0
def __init__(self, ident):
self.ident = ident
def __repr__(self):
return f"#{self.ident}"
class ClassSelector:
specificity = 0, 1, 0
def __init__(self, class_name):
self.class_name = class_name
def __repr__(self):
return f".{self.class_name}"
class AttributeSelector:
specificity = 0, 1, 0
def __init__(self, namespace, name, operator, value, case_sensitive):
self.namespace = namespace
self.name, self.lower_name = name
#: A string like ``=`` or ``~=``, or None for ``[attr]`` selectors
self.operator = operator
#: A string, or None for ``[attr]`` selectors
self.value = value
#: ``True`` if case-sensitive, ``False`` if case-insensitive, ``None``
#: if depends on the document language
self.case_sensitive = case_sensitive
def __repr__(self):
namespace = "*|" if self.namespace is None else f"{{{self.namespace}}}"
case_sensitive = (
""
if self.case_sensitive is None
else f" {'s' if self.case_sensitive else 'i'}"
)
return f"[{namespace}{self.name}{self.operator}{self.value!r}{case_sensitive}]"
class PseudoClassSelector:
specificity = 0, 1, 0
def __init__(self, name):
self.name = name
def __repr__(self):
return ":" + self.name
class FunctionalPseudoClassSelector:
specificity = 0, 1, 0
def __init__(self, name, arguments):
self.name = name
self.arguments = arguments
def __repr__(self):
return f":{self.name}{tuple(self.arguments)!r}"
class NegationSelector:
def __init__(self, selector_list):
self.selector_list = selector_list
@property
def specificity(self):
if self.selector_list:
return max(selector.specificity for selector in self.selector_list)
else:
return (0, 0, 0)
def __repr__(self):
return f":not({', '.join(repr(sel) for sel in self.selector_list)})"
class RelationalSelector:
def __init__(self, selector_list):
self.selector_list = selector_list
@property
def specificity(self):
if self.selector_list:
return max(selector.specificity for selector in self.selector_list)
else:
return (0, 0, 0)
def __repr__(self):
return f":has({', '.join(repr(sel) for sel in self.selector_list)})"
class MatchesAnySelector:
def __init__(self, selector_list):
self.selector_list = selector_list
@property
def specificity(self):
if self.selector_list:
return max(selector.specificity for selector in self.selector_list)
else:
return (0, 0, 0)
def __repr__(self):
return f":is({', '.join(repr(sel) for sel in self.selector_list)})"
class SpecificityAdjustmentSelector:
def __init__(self, selector_list):
self.selector_list = selector_list
@property
def specificity(self):
return (0, 0, 0)
def __repr__(self):
return f":where({', '.join(repr(sel) for sel in self.selector_list)})"

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.DirectedLineSegment((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,80 @@
# 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.spaces.named import _COLORS 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.ColorRGB(a))
@deprecate
def formatColorfa(a):
"""str(inkex.Color(a))"""
return str(inkex.ColorRGB([b * 255 for b in a]))
@deprecate
def formatColor3i(r, g, b):
"""str(inkex.Color((r, g, b)))"""
return str(inkex.ColorRGB((r, g, b)))
@deprecate
def formatColor3f(r, g, b):
"""str(inkex.Color((r, g, b)))"""
return str(inkex.ColorRGB((r * 255, g * 255, b * 255)))

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,304 @@
# 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 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,237 @@
# 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 re
import warnings
import argparse
import cssselect
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
from ..styles import ConditionalStyle, Style
from ..colors import Color
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
def to_xpath(self):
"""Depending on whether you need to apply the rule to an invididual element
or find all matches in a subtree, use
.. code::
style.matches(element)
style.all_matches(subtree)
"""
return "|".join(self.to_xpaths())
def to_xpaths(self):
"""Depending on whether you need to apply the rule to an invididual element
or find all matches in a subtree, use
.. code::
style.matches(element)
style.all_matches(subtree)
"""
result = []
for rule in self.rules:
ret = (
cssselect.HTMLTranslator().selector_to_xpath(cssselect.parse(str(rule))[0])
+ " "
)
ret = re.compile(r"(::|\/)([a-z]+)(?=\W)(?!-)").sub(r"\1svg:\2", ret)
result.append(ret.strip())
return result
ConditionalStyle.to_xpath = deprecate(to_xpath, "1.4") # type: ignore
ConditionalStyle.to_xpaths = deprecate(to_xpaths, "1.4") # type: ignore
def apply_shorthands(self):
"""Apply all shorthands in this style. Shorthands are now simplified automatically,
so this method does nothing"""
Style.apply_shorthands = deprecate(apply_shorthands, "1.4") # type: ignore
def to_rgba(self, alpha=1.0):
"""
Opacity is now controlled via alpha property regardless of color space being used.
"""
ret = self.to_rgb()
ret.alpha = float(alpha)
return ret
Color.to_rgba = deprecate(to_rgba, "1.5") # 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,939 @@
# -*- 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,
Callable,
TYPE_CHECKING,
)
from lxml import etree
import re
if TYPE_CHECKING:
from ._svg import SvgDocumentElement
from ..base import SvgOutputMixin
from ..paths import Path
from ..styles import Style, Classes, StyleValue
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 (
_ShorthandValueConverter,
_get_tokens_from_value,
all_properties,
)
from ._selected import ElementList
from ._parser import NodeBasedLookup, SVG_PARSER
T = TypeVar("T", bound="BaseElement") # pylint: disable=invalid-name
class BaseElement(etree.ElementBase):
"""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"""
_root: Optional["SvgDocumentElement"] = None
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, 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
return ret
return super().get(addNS(attr), default)
def set(self, attr, value):
"""Set element attribute named, with addNS support"""
if attr == "id" and value is not None:
try:
oldid = self.get("id", None)
if oldid is not None and oldid in self.root.ids:
self.root.ids.pop(oldid)
if value in self.root.ids:
raise ValueError(f"ID {value} already exists in this document")
self.root.ids[value] = self
except FragmentError: # element is unrooted
pass
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) -> "SvgDocumentElement":
"""Get the root document element from any element descendent"""
if self._root is not None:
return self._root
root, parent = self, self
while parent is not None:
root, parent = parent, parent.getparent()
from ._svg import SvgDocumentElement
if not isinstance(root, SvgDocumentElement):
raise FragmentError("Element fragment does not have a document root!")
self._root = 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
"""
try:
return ElementList(self.root, self._ancestors(elem=elem, stop_at=stop_at))
except FragmentError:
return ElementList(self, 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.getparent().replace(self, 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
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 get_computed_style(self, key):
"""Returns the computed style value with respect to
n element, i.e. the cascaded style +
inheritance, see https://www.w3.org/TR/CSS22/cascade.html#computed-value.
This is more efficient if only few style values per element are queried. If
many attributes are queried, use :func:`specified_style`.
.. versionadded:: 1.4
"""
return Style._get_style(key, 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
# Shorthands cannot be set by presentation attributes
and not isinstance(
all_properties[key].converter, _ShorthandValueConverter
)
and all_properties[key].presentation
):
style[key] = StyleValue(_get_tokens_from_value(self.attrib[key]))
return style
def composed_transform(self, other=None):
"""Calculate every transform down to the other element
if none specified the transform is to the root document element
"""
parent = self.getparent()
if parent is not other and isinstance(parent, BaseElement):
return parent.composed_transform(other) @ self.transform
return self.transform
def _add_to_tree_callback(self, element):
try:
element._root = self._root
self.root.add_to_tree_callback(element)
except (FragmentError, AttributeError):
pass
@staticmethod
def _remove_from_tree_callback(oldtree, element):
try:
oldtree.root.remove_from_tree_callback(element)
except (FragmentError, AttributeError):
pass
def __element_adder(
self, element: BaseElement, add_func: Callable[[BaseElement], None]
):
BaseElement._remove_from_tree_callback(element, element)
# Make sure that we have an ID cache before adding the element,
# otherwise we will try to add this element twice to the cache
try:
self.root.ids
except FragmentError:
pass
try:
add_func(element)
except Exception as err:
BaseElement._add_to_tree_callback(element, element)
raise err
self._add_to_tree_callback(element)
# Overrides to keep track of styles and IDs
def addnext(self, element):
self.__element_adder(element, super(etree.ElementBase, self).addnext)
def addprevious(self, element):
self.__element_adder(element, super(etree.ElementBase, self).addprevious)
def append(self, element):
self.__element_adder(element, super(etree.ElementBase, self).append)
def clear(self, keep_tail=False):
subelements = iter(self)
old_id = self.get("id", None)
super().clear(keep_tail)
for element in subelements:
BaseElement._remove_from_tree_callback(self, element)
if old_id is not None and old_id in self.root.ids:
self.root.ids.pop(old_id)
def extend(self, elements):
if not isinstance(elements, (list, tuple)):
elements = list(elements)
for element in elements:
BaseElement._remove_from_tree_callback(element, element)
try:
self.root.ids
except FragmentError:
pass
try:
super().extend(elements)
except Exception as err:
for element in elements:
BaseElement._add_to_tree_callback(element, element)
raise err
for element in elements:
self._add_to_tree_callback(element)
def insert(self, index, element):
self.__element_adder(
element,
lambda element: super(etree.ElementBase, self).insert(index, element),
)
def remove(self, element):
super().remove(element)
BaseElement._remove_from_tree_callback(self, element)
def replace(self, old_element, new_element):
def replacer(new_element):
super(etree.ElementBase, self).replace(old_element, new_element)
BaseElement._remove_from_tree_callback(self, old_element)
self.__element_adder(new_element, replacer)
NodeBasedLookup.default = BaseElement
class ShapeElement(BaseElement):
"""Elements which have a visible representation on the canvas"""
@property
def path(self) -> Path:
"""Gets the outline or path of the element, this may be a simple bounding box"""
return 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"""
return self.get_computed_style("clip-path")
@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
# This does not use :func:`get_computed_style` but its own iteration
# logic to avoid duplicate evaluation of styles: a child is also invisible
# if the parent has opacity:0, but opacity is not inherited - so we need
# to check the specified style of all parents and ignore inheritance
# altogether
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,581 @@
# -*- 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 DistantLight(Primitive):
"""DistanceLight Filter element
defines a light source for a DiffuseLighting or SpecularLighting Filter element
.. versionadded:: 1.4"""
tag_name = "feDistantLight"
class Flood(Primitive):
"""DiffuseLightning Filter element"""
tag_name = "feFlood"
class FuncA(Primitive):
"""FuncR Filter element
defines the alpha channel transfer for a ComponentTransfer Filter element
.. versionadded:: 1.4"""
tag_name = "feFuncA"
class FuncB(Primitive):
"""FuncR Filter element
defines the blue channel transfer for a ComponentTransfer Filter element
.. versionadded:: 1.4"""
tag_name = "feFuncB"
class FuncG(Primitive):
"""FuncR Filter element
defines the green channel transfer for a ComponentTransfer Filter element
.. versionadded:: 1.4"""
tag_name = "feFuncG"
class FuncR(Primitive):
"""FuncR Filter element
defines the red channel transfer for a ComponentTransfer Filter element
.. versionadded:: 1.4"""
tag_name = "feFuncR"
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 MergeNode(Primitive):
"""MergeNode Filter element
defines an input for a Merge Filter element
.. versionadded:: 1.4"""
tag_name = "feMergeNode"
class Morphology(Primitive):
"""Morphology Filter element"""
tag_name = "feMorphology"
class Offset(Primitive):
"""Offset Filter element"""
tag_name = "feOffset"
class PointLight(Primitive):
"""PointLight Filter elements
defines a light source for a DiffuseLighting or SpecularLighting Filter element
.. versionadded:: 1.4"""
tag_name = "fePointLight"
class SpecularLighting(Primitive):
"""SpecularLighting Filter element"""
tag_name = "feSpecularLighting"
class SpotLight(Primitive):
"""SpotLight Filter element
defines a light source for a DiffuseLighting or SpecularLighting Filter element
.. versionadded:: 1.4"""
tag_name = "feSpotLight"
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,196 @@
# -*- 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 BoundingBox, Transform, Vector2d
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):
child_path = child.path.transform(child.transform)
if child_path and child_path[0].is_relative:
child_path[0] = child_path[0].to_absolute(Vector2d(0, 0))
ret += child_path
return ret
def bounding_box(self, transform=None):
# type: (Optional[Transform]) -> Optional[BoundingBox]
"""BoundingBox of the shape
.. versionchanged:: 1.4
Exclude invisible child objects from bounding box computation
.. versionchanged:: 1.1
result adjusted for element's clip path if applicable.
"""
bbox = None
effective_transform = Transform(transform) @ self.transform
for child in self:
if isinstance(child, ShapeElement) and child.is_visible():
child_bbox = child.bounding_box(transform=effective_transform)
if child_bbox is not None:
bbox += child_bbox
clip = self.clip
if clip is None or bbox is None:
return bbox
return bbox & clip.bounding_box(Transform(transform) @ self.transform)
def shape_box(self, transform=None):
# type: (Optional[Transform]) -> Optional[BoundingBox]
"""BoundingBox of the unclipped shape
.. versionchanged:: 1.4
returns the bounding box without possible clip effects of child objects
.. versionadded:: 1.1
Previous :func:`bounding_box` function, returning the bounding box
without computing the effect of a possible clip."""
bbox = None
effective_transform = Transform(transform) @ self.transform
for child in self:
if isinstance(child, ShapeElement):
child_bbox = child.shape_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.get("{http://www.inkscape.org/namespaces/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,123 @@
# -*- 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.
"""
import os
import urllib.request as urllib
import urllib.parse as urlparse
from base64 import encodebytes
from ..base import InkscapeExtension
from ..localization import inkex_gettext as _
from ._polygons import RectangleBase
class Image(RectangleBase):
"""Provide a useful extension for image elements"""
tag_name = "image"
@staticmethod
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
def embed_image(self, file_path: str):
""" "Embed the data of the selected Image Tag element.
Relative image paths are interpreted relative to file_path.
.. versionadded:: 1.5
Args:
file_path (str): Relative image paths are interpreted relative to file_path.
"""
xlink = self.get("xlink:href")
if xlink is not None and xlink[:5] == "data:":
# No need, data already embedded
return
if xlink is None:
raise AttributeError(
_('Attribute "xlink:href" not set on node {}.'.format(self.get_id()))
)
url = urlparse.urlparse(xlink)
href = urllib.url2pathname(url.path)
# Look relative to the *temporary* filename instead of the original filename.
try:
cwd = os.path.dirname(file_path)
except TypeError:
# input_file was actually stdin, fall back.
cwd = None
path = InkscapeExtension.absolute_href(href or "", cwd=cwd)
# Backup directory where we can find the image
if not os.path.isfile(path):
path = self.get("sodipodi:absref", path)
if not os.path.isfile(path):
raise ValueError(
_('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 = self._get_type(path, handle.read(10))
handle.seek(0)
if file_type:
self.set(
"xlink:href",
"data:{};base64,{}".format(
file_type, encodebytes(handle.read()).decode("ascii")
),
)
self.pop("sodipodi:absref")
else:
raise ValueError(
_(
"%s is not of type image/png, image/jpeg, "
"image/bmp, image/gif, image/tiff, or image/x-icon"
)
% path
)

View File

@@ -0,0 +1,499 @@
# -*- 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: Vector2d, orientation: Vector2d
) -> 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: Vector2d, orientation: Vector2d
) -> 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):
"""Resource Description Framework (RDF) metadata"""
tag_name = "metadata"
doc_title = property(lambda self: self._first_text("dc:title"))
description = property(lambda self: self._first_text("dc:description"))
rights = property(lambda self: self._first_text("dc:rights/cc:Agent/dc:title"))
creator = property(lambda self: self._first_text("dc:creator/cc:Agent/dc:title"))
publisher = property(
lambda self: self._first_text("dc:publisher/cc:Agent/dc:title")
)
contributor = property(
lambda self: self._first_text("dc:contributor/cc:Agent/dc:title")
)
date = property(lambda self: self._first_text("dc:date"))
source = property(lambda self: self._first_text("dc:source"))
language = property(lambda self: self._first_text("dc:language"))
relation = property(lambda self: self._first_text("dc:relation"))
coverage = property(lambda self: self._first_text("dc:coverage"))
identifier = property(lambda self: self._first_text("dc:identifier"))
def _first_text(self, loc):
"""Get the work title"""
elem = self.findone(f"rdf:RDF/cc:Work/{loc}")
if elem:
return elem.text
return None
@property
def tags(self):
return [
elem.text
for elem in self.findall("rdf:RDF/cc:Work/dc:subject/rdf:Bag/rdf:li")
]
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,130 @@
# -*- 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, TYPE_CHECKING
from lxml import etree
if TYPE_CHECKING:
from ..elements._base import BaseElement
from ._utils import splitNS, addNS
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["BaseElement"]
# (ns,tag) -> list(cls) ; ascending priority
lookup_table: DefaultDict[str, List[Any]] = defaultdict()
@classmethod
def register_class(cls, klass):
"""Register the given class using it's attached tag name"""
key = addNS(*splitNS(klass.tag_name)[::-1])
old = cls.lookup_table.get(key, [])
old.append(klass)
cls.lookup_table[key] = old
@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[addNS(*splitNS(xpath.split("/")[-1])[::-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:
try:
options = self.lookup_table[element.tag]
except KeyError:
if not element.tag.startswith("{"):
tag = addNS(*splitNS(element.tag)[::-1])
options = self.lookup_table[tag]
else:
return self.default
for kls in reversed(options):
if kls.is_class_element(element): # pylint: disable=protected-access
return kls
except AttributeError:
# Handle <!-- Comment -->
return None
return self.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(
_(
"{error_message}. Line {line_number}, column {column_number}",
).format(
error_message=element.message,
line_number=element.line,
column_number=element.column,
)
)
errormsg(
_(
"\nProcessing will continue; however we encourage you to fix your"
" file manually."
)
)
return parsed

View File

@@ -0,0 +1,587 @@
# -*- 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 __future__ import annotations
from math import cos, pi, sin
import math
from typing import Optional, Tuple, Union
from ..paths.interfaces import PathCommand
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"""
def get_path(self) -> Path:
"""Gets the path of the element, which can also be used in a context manager"""
p = Path(self.get("d"))
p.callback = self.set_path
return p
@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"
MAX_ARC_SUBDIVISIONS = 4
@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), PathElement.MAX_ARC_SUBDIVISIONS)
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,
incr > pi,
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
@classmethod
def arc_from_3_points(
cls,
x: complex,
y: complex,
z: complex,
arctype="slice",
) -> PathElement:
"""
Create an arc through the points x, y, z.
If those points are specified clockwise, the order is not preserved.
This is indicated with the second return value (=clockwise)
Returns a PathElement. May be a line if x,y,z are collinear.
Idea: http://www.math.okstate.edu/~wrightd/INDRA/MobiusonCircles/node4.html
.. versionadded:: 1.4
"""
w = (z - x) / (y - x)
if abs(w.imag) > 1e-12:
c = -((x - y) * (w - abs(w) ** 2) / (2j * w.imag) - x)
r = abs(c - x)
# Now determine the arc flags by checking the angles
deltas = [x - c, y - c, z - c]
ang = [math.atan2(i.imag, i.real) for i in deltas]
# Check if the angles are "in order"
cw = int(any(ang[0 + i] < ang[-2 + i] < ang[-1 + i] for i in range(3)))
if not cw:
# Flip start and end angle
ang = ang[::-1]
return cls.arc(Vector2d(c), r, r, start=ang[0], end=ang[2], arctype=arctype)
else:
# Points lie on a line
# y between x and z -> draw a line, otherwise skip
if x.real <= y.real <= z.real or x.real >= y.real >= z.real:
return cls.new(Path([Move(x), PathLine(z)]))
else:
return cls.new(Path([Move(x), Move(z)]))
@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) -> Path:
p = Path("M" + self.get("points"))
p.callback = self.set_path
return p
def set_path(self, path):
if type(path) != Path:
path = Path("M" + str(path))
points = [f"{x:g},{y:g}" for x, y in path.end_points]
self.set("points", " ".join(points))
@classmethod
def new(cls, points=None, **attrs):
p = super().new(**attrs)
p.path = points
return p
class Polygon(Polyline):
"""A closed polyline"""
tag_name = "polygon"
def get_path(self) -> Path:
p = Path("M" + self.get("points") + " Z")
p.callback = self.set_path
return p
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) -> Path:
"""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 Path(
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 Path(
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) -> Path:
"""Calculate the arc path of this circle"""
rx, ry = self.rxry()
cx, y = self.center.x, self.center.y - ry
return Path(
(
"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,237 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 Martin Owens <doctormo@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc.,Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
"""
When elements are selected, these structures provide an advanced API.
.. versionadded:: 1.1
"""
from collections import OrderedDict
from typing import Any, overload, Union, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from ..elements._base import BaseElement
from ..elements import _base
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, _base.BaseElement):
# 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, "BaseElement", 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, _base.BaseElement):
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, (_base.BaseElement, 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,479 @@
# -*- 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
from functools import cached_property
from lxml import etree
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, ConditionalStyle
from ._base import BaseElement, ViewboxMixin
from ._meta import StyleElement, NamedView
from ._utils import registerNS, addNS, splitNS
from typing import Optional, List, Tuple
if False: # pylint: disable=using-constant-test
import typing # pylint: disable=unused-import
class SvgDocumentElement(DeprecatedSvgMixin, 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)
@cached_property
def ids(self):
result = {}
for el in self.iter():
try:
id = super(etree.ElementBase, el).get("id", None)
if id is not None:
result[id] = el
el._root = self
except TypeError:
pass # Comments
return result
@cached_property
def stylesheet_cache(self):
return {node: node.stylesheet() for node in self.xpath("//svg:style")}
def tostring(self):
"""Convert document to string"""
return etree.tostring(etree.ElementTree(self))
def get_ids(self):
"""Returns a set of unique document ids"""
return self.ids.keys()
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)
new_id = None
_from = 10**size - 1
_to = 10**size
while (
new_id is None
or new_id in ids
or (blacklist is not None and new_id in blacklist)
):
# Do not use randint because py2/3 incompatibility
new_id = prefix + str(int(random.random() * _from - _to) + _to)
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("#")
result = self.ids.get(eid, None)
if result is not None:
if elm != "*":
elm_with_ns = addNS(*splitNS(elm)[::-1])
if not super(etree.ElementBase, result).tag == elm_with_ns:
return None
return result
return None
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 ConditionalStyle(f".{class_name}").all_matches(self)
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()
for value in self.stylesheet_cache.values():
sheets.append(value)
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 add_to_tree_callback(self, element):
"""Callback called automatically when adding an element to the tree.
Updates the list of stylesheets and the ID tracker with the subtree of element.
.. versionadded:: 1.4
Args:
element (BaseElement): element added to the tree.
"""
for el in element.iter():
self._add_individual_to_tree(el)
def _add_individual_to_tree(self, element: BaseElement):
if isinstance(element, etree._Comment):
return
element._root = self
if element.TAG == "style":
self.stylesheet_cache[element] = element.stylesheet()
new_id = element.get("id", None)
if new_id is not None:
if new_id in self.ids:
while new_id in self.ids:
new_id += "-1"
super(etree.ElementBase, element).set("id", new_id) # type: ignore
self.ids[new_id] = element
def remove_from_tree_callback(self, element):
""" "Callback called automatically when removing an element from the tree.
Remove elements in the subtree of element from the the list of stylesheets
and the ID tracker.
.. versionadded:: 1.4
Args:
element (BaseElement): element added to the tree.
"""
for el in element.iter():
self._remove_individual_from_tree(el)
def _remove_individual_from_tree(self, element):
if isinstance(element, etree._Comment):
return
element._root = None
if element.TAG == "style" and element in self.stylesheet_cache:
self.stylesheet_cache.remove(element)
old_id = element.get("id", None)
if old_id is not None and old_id in self.ids:
self.ids.pop(old_id)
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,249 @@
# -*- 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 and their tail"""
# Stack of node and depth
stack = [(self, 0)]
result = []
def poptail():
"""Pop the tail from the tail stack and add it if necessary to results"""
tail = tail_stack.pop()
if tail is not None:
result.append(tail)
# Stack of the tail of nodes
tail_stack = []
previous_depth = -1
while stack:
# Get current node and depth
node, depth = stack.pop()
# Pop the previous tail if the depth do not increase
if previous_depth >= depth:
poptail()
# Pop as many times as the depth is reduced
for _ in range(previous_depth - depth):
poptail()
# Add a node text to the result, if any if node is text or tspan
if node.text and node.TAG in ["text", "tspan"]:
result.append(node.text)
# Add child elements
stack.extend(
map(
lambda tspan: (tspan, depth + 1),
node.iterchildren(reversed=True),
)
)
# Add the tail from node to the stack
tail_stack.append(node.tail)
previous_depth = depth
# Pop remaining tail elements
# Tail of the main text element should not be included
while len(tail_stack) > 1:
poptail()
return sep.join(result)
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,150 @@
# -*- 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,536 @@
# -*- 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, MeshGradient
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", encoding="utf-8") 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
target_space = None
"""
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.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, MeshGradient, Pattern)
):
gradients.track(value, elem, self._ref_cloned, element=elem, 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, element, name):
self._renamed[old_id] = new_id
element.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:
output_space = type(color)
if self.target_space:
color = color.to(self.target_space)
return self.modify_color(name, color).to(output_space)
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", "4.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
from .listview import TreeView, IconView, ViewColumn, ViewSort, Separator
from .pixmap import PixmapManager

View File

@@ -0,0 +1,62 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright 2011-2022 Martin Owens <doctormo@geek-2.com>
"""
Wraps Gtk.Application, providing a way to load a Gtk.Builder
with a specific ui file containing windows, and building
a usable pythonic interface from them.
"""
import os
import logging
from gi.repository import Gtk, Gdk, Gio
class GtkApp(Gtk.Application):
"""A very thin wrapper around Gtk.Application"""
app_name = None
"""The application id"""
prefix = ""
"""Folder prefix added to ui_dir"""
ui_dir = "./"
"""This is often the local directory"""
ui_file = None
"""If a single file is used for multiple windows"""
def __init__(self, **kwargs):
"""Creates a new GtkApp."""
self.kwargs = kwargs
super().__init__(
application_id=self.app_name, flags=Gio.ApplicationFlags.NON_UNIQUE
)
self.connect("activate", lambda _: self.on_activate())
if self.ui_dir:
icontheme = Gtk.IconTheme.get_for_display(Gdk.Display.get_default())
icontheme.add_search_path(self.ui_dir)
def run_wrapped(self):
"""Calls self.run() but catches keyboard interrupts"""
try:
self.run()
except KeyboardInterrupt: # pragma: no cover
logging.info("User Interrupted")
def on_activate(self):
"""Called when the application is activated"""
raise NotImplementedError("Must override on_activate in subclass")
def get_ui_file(self, window):
"""Load any given ui 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 ui file is missing: {paths}")

View File

@@ -0,0 +1,330 @@
#
# Copyright 2015 Ian Denhardt <ian@zenhack.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
"""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)
GLib.idle_add(handler, None, 0)
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("cursor-changed", 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,360 @@
#
# 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, Gdk, GLib, GdkPixbuf
import cairo
ICON_THEME = Gtk.IconTheme.get_for_display(Gdk.Display.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 isinstance(img, Gtk.IconPaintable):
# Temporary porting hack: rasterise iconpaintable to pixbuf
# https://discourse.gnome.org/t/convert-symbolic-icon-to-gdktexture-gdkpixbuf/29324/3
w = img.get_intrinsic_width()
h = img.get_intrinsic_height()
snapshot = Gtk.Snapshot()
img.snapshot(snapshot, w, h)
node = snapshot.to_node()
surface = cairo.ImageSurface(cairo.Format.ARGB32, w, h)
ctx = cairo.Context(surface)
node.draw(ctx)
img = Gdk.pixbuf_get_from_surface(surface, 0, 0, w, h)
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"Failed 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"Failed 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.lookup_icon(name, [], size, 1, Gtk.TextDirection.NONE, 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 Gio, 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.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 exit(self): # pragma: no cover
"""Try to going to kill any running mainloop."""
Gio.Application.get_default().quit()
def excepthook(self, ex_type, ex_value, traceback): # pragma: no cover
"""Catch errors thrown by the Gtk mainloop"""
self.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,38 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright 2012-2022 Martin Owens <doctormo@geek-2.com>
"""
Wraps Gtk.Window with something a little nicer.
"""
from gi.repository import Gtk
class Window:
"""A very thin wrapper around Gtk.Window"""
name = None
"""The name of the window to load from the ui file"""
def __init__(self, gapp):
"""Create a new Window and load its Gtk.Window from a ui file"""
self.gapp = gapp
ui_file = gapp.get_ui_file(self.name)
# Set up the builder and load ui
self.builder = Gtk.Builder(self)
self.builder.set_translation_domain(gapp.app_name)
self.builder.add_from_file(ui_file)
self.widget = self.builder.get_object
# Find the window in the ui
self.window = self.widget(self.name)
if not self.window: # pragma: no cover
raise KeyError(f"Missing window widget '{self.name}' from '{ui_file}'")
# Keep application alive
self.window.set_application(self.gapp)
def close(self, widget=None):
"""Closes the window. Can be connected to signals."""
self.window.close()

View File

@@ -0,0 +1,23 @@
"""Element abstractions for type comparisons without circular imports
.. versionadded:: 1.2"""
from __future__ import annotations
from typing import Protocol, TYPE_CHECKING
if TYPE_CHECKING:
from ..elements._svg import SvgDocumentElement
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) -> "SvgDocumentElement":
"""Returns the element's root."""
...

View File

@@ -0,0 +1,242 @@
# 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,122 @@
# coding=utf-8
#
# Copyright (C) 2018 Martin Owens <doctormo@gmail.com>
# Copyright (C) 2023 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.
#
"""Paths module.
Most of the functions derivative, unit_tangent, curvature, point, split, length, ilength
for the individual path commands are ported from
https://github.com/mathandy/svgpathtools/ (MIT licensed)
"""
from typing import Union
from ..transforms import ComplexLike
from .interfaces import (
PathCommand,
AbsolutePathCommand,
RelativePathCommand,
LengthSettings,
ILengthSettings,
)
from .lines import Line, line, Move, move, ZoneClose, zoneClose, Horz, horz, Vert, vert
from .curves import curve, Curve, smooth, Smooth
from .quadratic import quadratic, Quadratic, tepidQuadratic, TepidQuadratic
from .arc import Arc, arc, arc_to_path, matprod, rotmat, applymat, norm
from .path import CubicSuperPath, Path, InvalidPath
import numpy as np
np.seterr(invalid="raise")
# definitions that can't be inside the class due to circular dependencies
def to_curve(self, prev: ComplexLike, prev_prev: ComplexLike = 0) -> Curve:
"""Convert command to :py:class:`Curve`
Curve().to_curve() returns a copy
"""
return Curve(*self.ccurve_points(0 + 0j, complex(prev), complex(prev_prev)))
def to_line(self, prev: ComplexLike) -> Line:
"""Converts this segment to a line (copies if already a line)"""
return Line(self.cend_point(0, complex(prev)))
PathCommand.to_curve = to_curve # type: ignore
PathCommand.to_line = to_line # type: ignore
PathCommand._letter_to_class = { # pylint: disable=protected-access
"M": Move,
"L": Line,
"V": Vert,
"H": Horz,
"A": Arc,
"C": Curve,
"S": Smooth,
"Z": ZoneClose,
"Q": Quadratic,
"T": TepidQuadratic,
"m": move,
"l": line,
"v": vert,
"h": horz,
"a": arc,
"c": curve,
"s": smooth,
"z": zoneClose,
"q": quadratic,
"t": tepidQuadratic,
}
# All the names that get added to the inkex API itself.
__all__ = (
"Path",
"CubicSuperPath",
"PathCommand",
"AbsolutePathCommand",
"RelativePathCommand",
# Path commands:
"Line",
"line",
"Move",
"move",
"ZoneClose",
"zoneClose",
"Horz",
"horz",
"Vert",
"vert",
"Curve",
"curve",
"Smooth",
"smooth",
"Quadratic",
"quadratic",
"TepidQuadratic",
"tepidQuadratic",
"Arc",
"arc",
# errors
"InvalidPath",
# structs
"LengthSettings",
"ILengthSettings",
)

View File

@@ -0,0 +1,670 @@
# coding=utf-8
#
# Copyright (C) 2018 Martin Owens <doctormo@gmail.com>
# Copyright (C) 2023 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.
#
"""Arc path commands"""
from __future__ import annotations
from math import atan2, pi, sqrt, sin, cos, tan, acos, radians, degrees
from cmath import exp
from typing import overload, Tuple, List, Union, TYPE_CHECKING
import numpy as np
from ..transforms import Transform, Vector2d, ComplexLike
from .interfaces import (
AbsolutePathCommand,
RelativePathCommand,
LengthSettings,
ILengthSettings,
BezierArcComputationMixin,
)
if TYPE_CHECKING:
from .curves import Curve
class Arc(BezierArcComputationMixin, AbsolutePathCommand):
"""Special Arc segment"""
letter = "A"
nargs = 7
radius: complex
"""Radius of the Arc"""
x_axis_rotation: float
large_arc: bool
sweep: bool
endpoint: complex
"""Endpoint (absolute) of the Arc"""
@property
def rx(self) -> float:
"""x radius of the Arc"""
return self.radius.real
@property
def ry(self) -> float:
"""y radius of the Arc"""
return self.radius.imag
@property
def x(self) -> float:
"""x coordinate of the (absolute) endpoint of the Arc"""
return self.endpoint.real
@property
def y(self) -> float:
"""x coordinate of the (relative) endpoint of the Arc"""
return self.endpoint.imag
@property
def args(self):
return (
self.rx,
self.ry,
self.x_axis_rotation,
self.large_arc,
self.sweep,
self.x,
self.y,
)
@property
def cargs(self):
"""Set of arguments in complex form"""
return (
self.radius,
self.x_axis_rotation,
self.large_arc,
self.sweep,
self.endpoint,
)
@overload
def __init__(
self,
radius: ComplexLike,
x_axis_rotation: float,
large_arc: bool | int,
sweep: bool | int,
endpoint: ComplexLike,
) -> None: ...
@overload
def __init__(
self,
rx: float,
ry: float,
x_axis_rotation: float,
large_arc: bool | int,
sweep: bool | int,
x: float,
y: float,
) -> None: ... # pylint: disable=too-many-arguments
def __init__(self, *args):
if len(args) == 5:
(
self.radius,
self.x_axis_rotation,
self.large_arc,
self.sweep,
self.endpoint,
) = args
self.radius = complex(self.radius)
self.endpoint = complex(self.endpoint)
elif len(args) == 7:
self.radius = args[0] + args[1] * 1j
self.x_axis_rotation, self.large_arc, self.sweep = args[2:5]
self.endpoint = args[5] + args[6] * 1j
def parametrize(self, prev):
"""Return the parametrisation of the arc:
(radius, phi, rot_matrix, center, theta1, deltatheta)
See http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
.. versionadded:: 1.4"""
# my notation roughly follows theirs
phi = radians(self.x_axis_rotation)
rot_matrix = exp(1j * phi)
radius = self.radius
rx = self.radius.real
ry = self.radius.imag
rx_sqd = rx * rx
ry_sqd = ry * ry
# Transform z-> z' = x' + 1j*y'
# = self.rot_matrix**(-1)*(z - (end+start)/2)
# coordinates. This translates the ellipse so that the midpoint
# between self.end and self.start lies on the origin and rotates
# the ellipse so that the its axes align with the xy-coordinate axes.
# Note: This sends self.end to -self.start
zp1 = (1 / rot_matrix) * (prev - self.cend_point(0j, prev)) / 2
x1p, y1p = zp1.real, zp1.imag
x1p_sqd = x1p * x1p
y1p_sqd = y1p * y1p
# Correct out of range radii
radius_check = (x1p_sqd / rx_sqd) + (y1p_sqd / ry_sqd)
if radius_check > 1:
rx *= sqrt(radius_check)
ry *= sqrt(radius_check)
radius = rx + 1j * ry
rx_sqd = rx * rx
ry_sqd = ry * ry
# Compute c'=(c_x', c_y'), the center of the ellipse in (x', y') coords
# Noting that, in our new coord system, (x_2', y_2') = (-x_1', -x_2')
# and our ellipse is cut out by of the plane by the algebraic equation
# (x'-c_x')**2 / r_x**2 + (y'-c_y')**2 / r_y**2 = 1,
# we can find c' by solving the system of two quadratics given by
# plugging our transformed endpoints (x_1', y_1') and (x_2', y_2')
tmp = rx_sqd * y1p_sqd + ry_sqd * x1p_sqd
radicand = (rx_sqd * ry_sqd - tmp) / tmp
radical = 0 if np.isclose(radicand, 0) else sqrt(radicand)
if self.large_arc == self.sweep:
cp = -radical * (rx * y1p / ry - 1j * ry * x1p / rx)
else:
cp = radical * (rx * y1p / ry - 1j * ry * x1p / rx)
# The center in (x,y) coordinates is easy to find knowing c'
center = exp(1j * phi) * cp + (prev + self.cend_point(0j, prev)) / 2
# Now we do a second transformation, from (x', y') to (u_x, u_y)
# coordinates, which is a translation moving the center of the
# ellipse to the origin and a dilation stretching the ellipse to be
# the unit circle
u1 = (x1p - cp.real) / rx + 1j * (y1p - cp.imag) / ry # transformed start
u2 = (-x1p - cp.real) / rx + 1j * (-y1p - cp.imag) / ry # transformed end
# clip in case of floating point error
u1 = np.clip(u1.real, -1, 1) + 1j * np.clip(u1.imag, -1, 1)
u2 = np.clip(u2.real, -1, 1) + 1j * np.clip(u2.imag, -1, 1)
# Now compute theta and delta (we'll define them as we go)
# delta is the angular distance of the arc (w.r.t the circle)
# theta is the angle between the positive x'-axis and the start point
# on the circle
if u1.imag > 0:
theta1 = degrees(acos(u1.real))
elif u1.imag < 0:
theta1 = -degrees(acos(u1.real))
else:
if u1.real > 0: # start is on pos u_x axis
theta1 = 0
else: # start is on neg u_x axis
# Note: This behavior disagrees with behavior documented in
# http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
# where theta is set to 0 in this case.
theta1 = 180
det_uv = u1.real * u2.imag - u1.imag * u2.real
acosand = u1.real * u2.real + u1.imag * u2.imag
acosand = np.clip(acosand.real, -1, 1) + np.clip(acosand.imag, -1, 1)
if det_uv > 0:
deltatheta = degrees(acos(acosand))
elif det_uv < 0:
deltatheta = -degrees(acos(acosand))
else:
if u1.real * u2.real + u1.imag * u2.imag > 0:
# u1 == u2
deltatheta = 0
else:
# u1 == -u2
# Note: This behavior disagrees with behavior documented in
# http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
# where deltatheta is set to 0 in this case.
deltatheta = 180
if not self.sweep and deltatheta >= 0:
deltatheta -= 360
elif self.large_arc and deltatheta <= 0:
deltatheta += 360
return radius, phi, rot_matrix, center, theta1, deltatheta
def update_bounding_box(self, first, last_two_points, bbox):
prev = last_two_points[-1]
for seg in self.to_curves(prev=prev):
seg.update_bounding_box(first, [None, prev], bbox)
prev = seg.cend_point(first, prev)
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
return (self.endpoint,)
def ccurve_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
return NotImplemented
def to_curves(self, prev: ComplexLike, prev_prev: ComplexLike = 0j) -> List[Curve]:
"""Convert this arc into bezier curves"""
# TODO Refactor out CubicSuperPath
from .path import CubicSuperPath
path = CubicSuperPath(
[arc_to_path(Vector2d.c2t(complex(prev)), self.args)]
).to_path(curves_only=True)
# Ignore the first move command from to_path()
return list(path)[1:]
def transform(self, transform: Transform) -> Arc:
# pylint: disable=invalid-name, too-many-locals
newend = transform.capply_to_point(self.endpoint)
T: Transform = transform
if self.x_axis_rotation != 0:
T = T @ Transform(rotate=self.x_axis_rotation)
a, c, b, d, _, _ = list(T.to_hexad())
# T = | a b |
# | c d |
detT = a * d - b * c
detT2 = detT**2
rx = float(self.rx)
ry = float(self.ry)
def get_degen():
return Arc(
self.radius,
self.x_axis_rotation,
self.large_arc,
self.sweep,
newend,
)
if rx == 0.0 or ry == 0.0 or detT2 == 0.0:
# degenerate arc
# transform only last point
return get_degen()
A = (d**2 / rx**2 + c**2 / ry**2) / detT2
B = -(d * b / rx**2 + c * a / ry**2) / detT2
D = (b**2 / rx**2 + a**2 / ry**2) / detT2
theta = atan2(-2 * B, D - A) / 2
theta_deg = theta * 180.0 / pi
DA = D - A
l2 = 4 * B**2 + DA**2
if l2 == 0:
delta = 0.0
else:
delta = 0.5 * (-(DA**2) - 4 * B**2) / sqrt(l2)
half = (A + D) / 2
try:
rx_ = 1.0 / sqrt(half + delta)
ry_ = 1.0 / sqrt(half - delta)
if detT > 0:
sweep = self.sweep
else:
sweep = not self.sweep > 0
return Arc(rx_ + 1j * ry_, theta_deg, self.large_arc, sweep, newend)
except ZeroDivisionError:
return get_degen()
def to_relative(self, prev: ComplexLike) -> RelativePathCommand:
return arc(
self.radius,
self.x_axis_rotation,
self.large_arc,
self.sweep,
self.endpoint - prev,
)
def cend_point(self, first: complex, prev: complex) -> complex:
return self.endpoint
def reverse(self, first: ComplexLike, prev: ComplexLike) -> Arc:
return Arc(
self.radius, self.x_axis_rotation, self.large_arc, not self.sweep, prev
)
def _cpoint(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> complex:
# TODO surely this can be expressed in a shorter way using complex geometry?
radius, _, rot_matrix, center, theta1, deltatheta = self.parametrize(prev)
angle = (theta1 + t * deltatheta) * pi / 180
cosphi = rot_matrix.real
sinphi = rot_matrix.imag
rx = radius.real
ry = radius.imag
x = rx * cosphi * cos(angle) - ry * sinphi * sin(angle) + center.real
y = rx * sinphi * cos(angle) + ry * cosphi * sin(angle) + center.imag
return x + y * 1j
def _cderivative(
self, first: complex, prev: complex, prev_control: complex, t: float, n: int = 1
) -> complex:
"""returns the nth derivative of the segment at t."""
radius, phi, _, _, theta1, deltatheta = self.parametrize(prev)
angle = radians(theta1 + t * deltatheta)
rx = radius.real
ry = radius.imag
k = (deltatheta * pi / 180) ** n # ((d/dt)angle)**n
if n % 4 == 0 and n > 0:
return (
rx * cos(phi) * cos(angle)
- ry * sin(phi) * sin(angle)
+ 1j * (rx * sin(phi) * cos(angle) + ry * cos(phi) * sin(angle))
)
elif n % 4 == 1:
return k * (
-rx * cos(phi) * sin(angle)
- ry * sin(phi) * cos(angle)
+ 1j * (-rx * sin(phi) * sin(angle) + ry * cos(phi) * cos(angle))
)
elif n % 4 == 2:
return k * (
-rx * cos(phi) * cos(angle)
+ ry * sin(phi) * sin(angle)
+ 1j * (-rx * sin(phi) * cos(angle) - ry * cos(phi) * sin(angle))
)
elif n % 4 == 3:
return k * (
rx * cos(phi) * sin(angle)
+ ry * sin(phi) * cos(angle)
+ 1j * (rx * sin(phi) * sin(angle) - ry * cos(phi) * cos(angle))
)
else:
raise ValueError("n should be a positive integer.")
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[Arc, Arc]:
"""returns two segments, whose union is this segment and which join
at self.point(t)."""
radius, _, _, _, _, deltatheta = self.parametrize(prev)
def crop(t0, t1):
return Arc(
radius,
self.x_axis_rotation,
not abs(deltatheta * (t1 - t0)) <= 180,
self.sweep,
self.cpoint(0j, prev, 0j, t1),
)
return crop(0, t), crop(t, 1)
def _ilength(
self,
first: complex,
prev: complex,
prev_control: complex,
length: float,
settings: ILengthSettings = ILengthSettings(),
):
# ilength calls self.parametrize very often, so we cache the result
param = self.parametrize
params = param(prev)
def cached(prev): # pylint: disable=unused-argument
return params
self.parametrize = cached # type: ignore
try:
return super()._ilength(first, prev, prev_control, length, settings)
finally:
self.parametrize = param # type: ignore
class arc(RelativePathCommand, Arc): # pylint: disable=invalid-name
"""Relative Arc line segment"""
letter = "a"
nargs = 7
endpoint: complex
"""Endpoint (relative) of the arc"""
@property
def rx(self) -> float:
"""x radius of the arc"""
return self.radius.real
@property
def ry(self) -> float:
"""y radius of the arc"""
return self.radius.imag
@property
def dx(self) -> float:
"""x coordinate of the (relative) endpoint of the arc"""
return self.endpoint.real
@property
def dy(self) -> float:
"""x coordinate of the (relative) endpoint of the arc"""
return self.endpoint.imag
@property
def args(self):
return (
self.rx,
self.ry,
self.x_axis_rotation,
self.large_arc,
self.sweep,
self.dx,
self.dy,
)
@overload
def __init__(
self,
radius: ComplexLike,
x_axis_rotation: float,
large_arc: bool,
sweep: bool,
endpoint: ComplexLike,
) -> None: ...
@overload
def __init__(
self,
rx: float,
ry: float,
x_axis_rotation: float,
large_arc: bool,
sweep: bool,
dx: float,
dy: float,
) -> None: ... # pylint: disable=too-many-arguments
def __init__(self, *args):
if len(args) == 5:
(
self.radius,
self.x_axis_rotation,
self.large_arc,
self.sweep,
self.endpoint,
) = args
self.radius = complex(self.radius)
self.endpoint = complex(self.endpoint)
elif len(args) == 7:
self.radius = args[0] + args[1] * 1j
self.x_axis_rotation, self.large_arc, self.sweep = args[2:5]
self.endpoint = args[5] + args[6] * 1j
def to_absolute(self, prev: ComplexLike) -> Arc:
return Arc(
self.radius,
self.x_axis_rotation,
self.large_arc,
self.sweep,
self.endpoint + prev,
)
def cend_point(self, first: complex, prev: complex) -> complex:
return self.endpoint + prev
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
return (self.endpoint + prev,)
def ccurve_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
return NotImplemented
def reverse(self, first: ComplexLike, prev: ComplexLike) -> arc:
return arc(
self.radius,
self.x_axis_rotation,
self.large_arc,
not self.sweep,
-self.endpoint,
)
def to_curves(self, prev: ComplexLike, prev_prev: ComplexLike = 0j) -> List[Curve]:
return self.to_absolute(prev).to_curves(prev, prev_prev)
def arc_to_path(point, params):
"""Approximates an arc with cubic bezier segments.
Arguments:
point: Starting point (absolute coords)
params: Arcs parameters as per
https://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands
Returns a list of triplets of points :
[control_point_before, node, control_point_after]
(first and last returned triplets are [p1, p1, *] and [*, p2, p2])
"""
# pylint: disable=invalid-name, too-many-locals
A = point[:]
rx, ry, teta, longflag, sweepflag, x2, y2 = params[:]
teta = teta * pi / 180.0
B = [x2, y2]
# Degenerate ellipse
if rx == 0 or ry == 0 or A == B:
return [[A[:], A[:], A[:]], [B[:], B[:], B[:]]]
# turn coordinates so that the ellipse morph into a *unit circle* (not 0-centered)
mat = matprod((rotmat(teta), [[1.0 / rx, 0.0], [0.0, 1.0 / ry]], rotmat(-teta)))
applymat(mat, A)
applymat(mat, B)
k = [-(B[1] - A[1]), B[0] - A[0]]
d = k[0] * k[0] + k[1] * k[1]
k[0] /= sqrt(d)
k[1] /= sqrt(d)
d = sqrt(max(0, 1 - d / 4.0))
# k is the unit normal to AB vector, pointing to center O
# d is distance from center to AB segment (distance from O to the midpoint of AB)
# for the last line, remember this is a unit circle, and kd vector is ortogonal to
# AB (Pythagorean thm)
if longflag == sweepflag:
# top-right ellipse in SVG example
# https://www.w3.org/TR/SVG/images/paths/arcs02.svg
d *= -1
O = [(B[0] + A[0]) / 2.0 + d * k[0], (B[1] + A[1]) / 2.0 + d * k[1]]
OA = [A[0] - O[0], A[1] - O[1]]
OB = [B[0] - O[0], B[1] - O[1]]
start = acos(OA[0] / norm(OA))
if OA[1] < 0:
start *= -1
end = acos(OB[0] / norm(OB))
if OB[1] < 0:
end *= -1
# start and end are the angles from center of the circle to A and to B respectively
if sweepflag and start > end:
end += 2 * pi
if (not sweepflag) and start < end:
end -= 2 * pi
NbSectors = int(abs(start - end) * 2 / pi) + 1
dTeta = (end - start) / NbSectors
v = 4 * tan(dTeta / 4.0) / 3.0
# I would use v = tan(dTeta/2)*4*(sqrt(2)-1)/3 ?
p = []
for i in range(0, NbSectors + 1, 1):
angle = start + i * dTeta
v1 = [
O[0] + cos(angle) - (-v) * sin(angle),
O[1] + sin(angle) + (-v) * cos(angle),
]
pt = [O[0] + cos(angle), O[1] + sin(angle)]
v2 = [O[0] + cos(angle) - v * sin(angle), O[1] + sin(angle) + v * cos(angle)]
p.append([v1, pt, v2])
p[0][0] = p[0][1][:]
p[-1][2] = p[-1][1][:]
# go back to the original coordinate system
mat = matprod((rotmat(teta), [[rx, 0], [0, ry]], rotmat(-teta)))
for pts in p:
applymat(mat, pts[0])
applymat(mat, pts[1])
applymat(mat, pts[2])
return p
def matprod(mlist):
"""Get the product of the mat"""
prod = mlist[0]
for mat in mlist[1:]:
a00 = prod[0][0] * mat[0][0] + prod[0][1] * mat[1][0]
a01 = prod[0][0] * mat[0][1] + prod[0][1] * mat[1][1]
a10 = prod[1][0] * mat[0][0] + prod[1][1] * mat[1][0]
a11 = prod[1][0] * mat[0][1] + prod[1][1] * mat[1][1]
prod = [[a00, a01], [a10, a11]]
return prod
def rotmat(teta):
"""Rotate the mat"""
return [[cos(teta), -sin(teta)], [sin(teta), cos(teta)]]
def applymat(mat, point):
"""Apply the given mat"""
x = mat[0][0] * point[0] + mat[0][1] * point[1]
y = mat[1][0] * point[0] + mat[1][1] * point[1]
point[0] = x
point[1] = y
def norm(point):
"""Normalise"""
return sqrt(point[0] * point[0] + point[1] * point[1])

View File

@@ -0,0 +1,499 @@
# coding=utf-8
#
# Copyright (C) 2018 Martin Owens <doctormo@gmail.com>
# Copyright (C) 2023 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.
#
"""Curve and Smooth Path Commands"""
from __future__ import annotations
from typing import overload, Tuple, Callable, Union, cast
import numpy as np
from ..transforms import cubic_extrema, Transform, Vector2d, ComplexLike
from .interfaces import (
AbsolutePathCommand,
RelativePathCommand,
BezierArcComputationMixin,
BezierComputationMixin,
)
class CurveMixin(BezierComputationMixin, BezierArcComputationMixin):
"""Common functionality for curves"""
ccontrol_points: Callable[[complex, complex, complex], Tuple[complex, ...]]
def ccurve_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
"""Common implementation of ccurve_points for Curves"""
return self.ccontrol_points(first, prev, prev_prev)
def _cderivative(
self, first: complex, prev: complex, prev_control: complex, t: float, n: int = 1
) -> complex:
"""Returns the nth derivative of the segment at t.
.. hint:: Bezier curves can have points where their derivative vanishes.
If you are interested in the tangent direction, use the :func:`unit_tangent`
method instead."""
points = self.ccontrol_points(first, prev, prev_control)
if n == 1:
return (
3 * (points[0] - prev) * ((1 - t) ** 2)
+ 6 * (points[1] - points[0]) * (1 - t) * t
+ 3 * (points[2] - points[1]) * t**2
)
elif n == 2:
return 6 * (
(1 - t) * (points[1] - 2 * points[0] + prev)
+ t * (points[2] - 2 * points[1] + points[0])
)
elif n == 3:
return 6 * (points[2] - 3 * (points[1] - points[0]) - prev)
elif n > 3:
return complex(0, 0)
else:
raise ValueError("n should be a positive integer.")
def poly(self, prev, prev_control, return_coeffs=False):
"""Returns a the cubic as a complex Polynomial object.
.. versionadded:: 1.4"""
points = self.ccontrol_points(0j, prev, prev_control)
coeffs = (
-prev + 3 * (points[0] - points[1]) + points[2],
3 * (prev - 2 * points[0] + points[1]),
3 * (prev + points[0]),
prev,
)
if return_coeffs:
return coeffs
return np.poly1d(coeffs)
def _cunit_tangent(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> complex:
return self.bezier_unit_tangent(prev, prev_control, t)
def _curvature(
self, first: complex, prev: complex, prev_control: complex, t: float
):
return self.segment_curvature(prev, prev_control, t)
def _abssplit(
self, prev: complex, prev_control: complex, t: float
) -> Tuple[Curve, Curve]:
"""Split this curve and return two Curves using DeCasteljau's algorithm"""
p1, p2, p3 = self.ccontrol_points(0j, prev, prev_control)
p1_1 = (1 - t) * prev + t * p1
p1_2 = (1 - t) * p1 + t * p2
p1_3 = (1 - t) * p2 + t * p3
p2_1 = (1 - t) * p1_1 + t * p1_2
p2_2 = (1 - t) * p1_2 + t * p1_3
p3_1 = (1 - t) * p2_1 + t * p2_2
return Curve(p1_1, p2_1, p3_1), Curve(p2_2, p1_3, p3)
def _relsplit(self, prev: complex, prev_control: complex, t: float):
"""Split this curve and return two curves"""
c1abs, c2abs = self._abssplit(prev, prev_control, t)
return c1abs.to_relative(prev), c2abs.to_relative(c1abs.arg3)
def _cpoint(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> complex:
control1, control2, end = self.ccontrol_points(first, prev, prev_control)
return (
(1 - t) ** 3 * prev
+ 3 * t * (1 - t) ** 2 * control1
+ 3 * t**2 * (1 - t) * control2
+ t**3 * end
)
class Curve(CurveMixin, AbsolutePathCommand):
"""Absolute Curved Line segment"""
letter = "C"
nargs = 6
arg1: complex
"""The (absolute) first control point"""
arg2: complex
"""The (absolute) second control point"""
arg3: complex
"""The (absolute) end point"""
@property
def x2(self) -> float:
"""x coordinate of the (absolute) first control point"""
return self.arg1.real
@property
def y2(self) -> float:
"""y coordinate of the (absolute) first control point"""
return self.arg1.imag
@property
def x3(self) -> float:
"""x coordinate of the (absolute) second control point"""
return self.arg2.real
@property
def y3(self) -> float:
"""y coordinate of the (absolute) second control point"""
return self.arg2.imag
@property
def x4(self) -> float:
"""x coordinate of the (absolute) end point"""
return self.arg3.real
@property
def y4(self) -> float:
"""y coordinate of the (absolute) end point"""
return self.arg3.imag
@property
def args(self):
return (
self.arg1.real,
self.arg1.imag,
self.arg2.real,
self.arg2.imag,
self.arg3.real,
self.arg3.imag,
)
@overload
def __init__(self, x2: ComplexLike, x3: ComplexLike, x4: ComplexLike): ...
@overload
def __init__(
self, x2: float, y2: float, x3: float, y3: float, x4: float, y4: float
): ... # pylint: disable=too-many-arguments
def __init__(self, x2, y2, x3, y3=None, x4=None, y4=None): # pylint: disable=too-many-arguments
if y3 is not None:
self.arg1 = x2 + y2 * 1j
self.arg2 = x3 + y3 * 1j
self.arg3 = x4 + y4 * 1j
else:
self.arg1, self.arg2, self.arg3 = complex(x2), complex(y2), complex(x3)
def update_bounding_box(self, first, last_two_points, bbox):
x1, x2, x3, x4 = last_two_points[-1].real, self.x2, self.x3, self.x4
y1, y2, y3, y4 = last_two_points[-1].imag, self.y2, self.y3, self.y4
if not (x1 in bbox.x and x2 in bbox.x and x3 in bbox.x and x4 in bbox.x):
bbox.x += cubic_extrema(x1, x2, x3, x4)
if not (y1 in bbox.y and y2 in bbox.y and y3 in bbox.y and y4 in bbox.y):
bbox.y += cubic_extrema(y1, y2, y3, y4)
def transform(self, transform: Transform) -> Curve:
return Curve(
transform.capply_to_point(self.arg1),
transform.capply_to_point(self.arg2),
transform.capply_to_point(self.arg3),
)
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
# pylint: disable=unused-argument
return (self.arg1, self.arg2, self.arg3)
def to_relative(self, prev: ComplexLike) -> curve:
return curve(self.arg1 - prev, self.arg2 - prev, self.arg3 - prev)
def cend_point(self, first: complex, prev: complex) -> complex:
return self.arg3
def reverse(self, first: ComplexLike, prev: ComplexLike) -> Curve:
return Curve(self.arg2, self.arg1, prev)
def to_bez(self):
"""Convert to [[c1x, c1y], [c2x, c2y], [end_x, end_y]]"""
return [Vector2d.c2t(i) for i in self.ccontrol_points(0j, 0j, 0j)]
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[Curve, Curve]:
return self._abssplit(prev, prev_control, t)
class curve(CurveMixin, RelativePathCommand): # pylint: disable=invalid-name
"""Relative curved line segment"""
letter = "c"
nargs = 6
arg1: complex
"""The (relative) first control point"""
arg2: complex
"""The (relative) second control point"""
arg3: complex
"""The (relative) end point"""
@property
def dx2(self) -> float:
"""x coordinate of the (relative) first control point"""
return self.arg1.real
@property
def dy2(self) -> float:
"""y coordinate of the (relative) first control point"""
return self.arg1.imag
@property
def dx3(self) -> float:
"""x coordinate of the (relative) second control point"""
return self.arg2.real
@property
def dy3(self) -> float:
"""y coordinate of the (relative) second control point"""
return self.arg2.imag
@property
def dx4(self) -> float:
"""x coordinate of the (relative) end point"""
return self.arg3.real
@property
def dy4(self) -> float:
"""y coordinate of the (relative) end point"""
return self.arg3.imag
@overload
def __init__(self, dx2: ComplexLike, dx3: ComplexLike, dx4: ComplexLike): ...
@overload
def __init__(
self, dx2: float, dy2: float, dx3: float, dy3: float, dx4: float, dy4: float
): ... # pylint: disable=too-many-arguments
def __init__(self, dx2, dy2, dx3, dy3=None, dx4=None, dy4=None): # pylint: disable=too-many-arguments
if dy3 is not None:
self.arg1 = dx2 + dy2 * 1j
self.arg2 = dx3 + dy3 * 1j
self.arg3 = dx4 + dy4 * 1j
else:
self.arg1, self.arg2, self.arg3 = complex(dx2), complex(dy2), complex(dx3)
@property
def args(self):
return self.dx2, self.dy2, self.dx3, self.dy3, self.dx4, self.dy4
def to_absolute(self, prev: ComplexLike) -> Curve:
return Curve(*self.ccurve_points(0j, complex(prev), 0j))
def cend_point(self, first: complex, prev: complex) -> complex:
return self.arg3 + prev
def reverse(self, first: ComplexLike, prev: ComplexLike) -> curve:
return curve(-self.arg3 + self.arg2, -self.arg3 + self.arg1, -self.arg3)
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
# pylint: disable=unused-argument
return (
self.arg1 + prev,
self.arg2 + prev,
self.arg3 + prev,
)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[curve, curve]:
return self._relsplit(prev, prev_control, t)
class Smooth(CurveMixin, AbsolutePathCommand):
"""Absolute Smoothed Curved Line segment"""
letter = "S"
nargs = 4
arg1: complex
"""The (absolute) control point"""
arg2: complex
"""The (absolute) end point"""
@property
def x3(self) -> float:
"""x coordinate of the (absolute) control point"""
return self.arg1.real
@property
def y3(self) -> float:
"""y coordinate of the (absolute) control point"""
return self.arg1.imag
@property
def x4(self) -> float:
"""x coordinate of the (absolute) end point"""
return self.arg2.real
@property
def y4(self) -> float:
"""y coordinate of the (absolute) end point"""
return self.arg2.imag
@property
def args(self):
return self.x3, self.y3, self.x4, self.y4
@overload
def __init__(self, x3: ComplexLike, x4: ComplexLike): ...
@overload
def __init__(self, x3: float, y3: float, x4: float, y4: float): ...
def __init__(self, x3, y3, x4=None, y4=None):
if x4 is not None:
self.arg1 = x3 + y3 * 1j
self.arg2 = x4 + y4 * 1j
else:
self.arg1, self.arg2 = complex(x3), complex(y3)
def update_bounding_box(self, first, last_two_points, bbox):
# pylint: disable=no-member
self.to_curve(last_two_points[-1], last_two_points[-2]).update_bounding_box(
first, last_two_points, bbox
)
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
# pylint: disable=unused-argument
return (2 * prev - prev_prev, self.arg1, self.arg2)
def to_non_shorthand(self, prev: ComplexLike, prev_control: ComplexLike) -> Curve:
return self.to_curve(prev, prev_control)
def to_relative(self, prev: ComplexLike) -> smooth:
return smooth(self.arg1 - prev, self.arg2 - prev)
def transform(self, transform: Transform) -> Smooth:
return Smooth(
transform.capply_to_point(self.arg1), transform.capply_to_point(self.arg2)
)
def cend_point(self, first: complex, prev: complex) -> complex:
return self.arg2
def reverse(self, first: ComplexLike, prev: ComplexLike) -> Smooth:
return Smooth(self.arg1, prev)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[Curve, Curve]:
# We can't preserve the smooth type for a split because de Casteljau's
# algorithm changes the handles (obviously).
# Only in special cases such as splitting to subsequent smooth segments at
# t=1/2 such a preservation would be possible
crv = cast(Curve, self.to_non_shorthand(prev, prev_control))
return crv._split( # pylint: disable=protected-access, no-member
first, prev, prev_control, t
)
class smooth(CurveMixin, RelativePathCommand): # pylint: disable=invalid-name
"""Relative smoothed curved line segment"""
letter = "s"
nargs = 4
arg1: complex
"""The (absolute) control point"""
arg2: complex
"""The (absolute) end point"""
@property
def dx3(self) -> float:
"""x coordinate of the (relative) control point"""
return self.arg1.real
@property
def dy3(self) -> float:
"""y coordinate of the (relative) control point"""
return self.arg1.imag
@property
def dx4(self) -> float:
"""x coordinate of the (relative) end point"""
return self.arg2.real
@property
def dy4(self) -> float:
"""y coordinate of the (relative) end point"""
return self.arg2.imag
@property
def args(self):
return self.dx3, self.dy3, self.dx4, self.dy4
@overload
def __init__(self, dx3: ComplexLike, dx4: ComplexLike): ...
@overload
def __init__(self, dx3: float, dy3: float, dx4: float, dy4: float): ...
def __init__(self, dx3, dy3, dx4=None, dy4=None):
if dx4 is not None:
self.arg1 = dx3 + dy3 * 1j
self.arg2 = dx4 + dy4 * 1j
else:
self.arg1, self.arg2 = complex(dx3), complex(dy3)
def to_absolute(self, prev: ComplexLike) -> Smooth:
return Smooth(self.arg1 + prev, self.arg2 + prev)
def cend_point(self, first: complex, prev: complex) -> complex:
return self.arg2 + prev
def to_non_shorthand(self, prev: ComplexLike, prev_control: ComplexLike) -> Curve:
return self.to_absolute(prev).to_non_shorthand(prev, prev_control)
def reverse(self, first: ComplexLike, prev: ComplexLike):
return smooth(-self.arg2 + self.arg1, -self.arg2)
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
# pylint: disable=unused-argument
return (2 * prev - prev_prev, self.arg1 + prev, self.arg2 + prev)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[curve, curve]:
return self._relsplit(prev, prev_control, t)

View File

@@ -0,0 +1,731 @@
# coding=utf-8
#
# Copyright (C) 2018 Martin Owens <doctormo@gmail.com>
# Copyright (C) 2023 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.
#
"""Interfaces for path commands"""
from __future__ import annotations
import abc
import math
from typing import (
List,
Any,
Tuple,
Dict,
Type,
Generator,
Union,
TYPE_CHECKING,
Optional,
Callable,
)
from dataclasses import dataclass
import numpy as np
from ..utils import classproperty, rational_limit
from ..transforms import Vector2d, BoundingBox, Transform, ComplexLike
if TYPE_CHECKING:
from .curves import Curve
from .lines import Line
@dataclass
class LengthSettings:
"""Settings for :func:`PathCommand.length`
.. versionadded:: 1.4"""
min_depth: int = 5
error: float = 1e-5
@dataclass
class ILengthSettings:
"""Settings for :func:`PathCommand.ilength`
.. versionadded:: 1.4"""
min_depth: int = 5
error: float = 1e-5
"""
Error tolerance for the computations of the test segment that is performed
for each iteration.
The defaults from svgpathtools are ILENGTH_ERROR=ILENGTH_LENGTH_TOL=1e-12.
This is rather slow, particularly _length (which then subdivides the path into
2^12 or more segments and adds up the length). For visual editing, this is rather
irrelevant (and a lot more accurate than the previous methods)."""
length_tol: float = 1e-5
"""Total (absolute) tolerance of the resulting s value."""
maxits: int = 10000
class PathCommand(abc.ABC):
"""
Base class of all path commands
"""
letter = ""
# Number of arguments that follow this path commands letter
nargs = -1
@classproperty # From python 3.9 on, just combine @classmethod and @property
def name(cls): # pylint: disable=no-self-argument
"""The full name of the segment (i.e. Line, Arc, etc)"""
return cls.__name__ # pylint: disable=no-member
@classproperty
def next_command(self):
"""The implicit next command. This is for automatic chains where the next
command isn't given, just a bunch on numbers which we automatically parse."""
return self
@property
def is_relative(self) -> bool:
"""Whether the command is defined in relative coordinates, i.e. relative to
the previous endpoint (lower case path command letter)"""
raise NotImplementedError
@property
def is_absolute(self) -> bool:
"""Whether the command is defined in absolute coordinates (upper case path
command letter)"""
raise NotImplementedError
def to_relative(self, prev: ComplexLike) -> RelativePathCommand:
"""Return absolute counterpart for absolute commands or copy for relative"""
raise NotImplementedError
def to_absolute(self, prev: ComplexLike) -> AbsolutePathCommand:
"""Return relative counterpart for relative commands or copy for absolute"""
raise NotImplementedError
def reverse(self, first: ComplexLike, prev: ComplexLike) -> PathCommand:
"""Reverse path command
.. versionadded:: 1.1"""
raise NotImplementedError
def to_non_shorthand(
self,
prev: ComplexLike,
prev_control: ComplexLike, # pylint: disable=unused-argument
) -> AbsolutePathCommand:
"""Return an absolute non-shorthand command
.. versionadded:: 1.1"""
return self.to_absolute(prev)
# The precision of the numbers when converting to string
number_template = "{:.6g}"
# Maps single letter path command to corresponding class
# (filled at the bottom of file, when all classes already defined)
_letter_to_class: Dict[str, Type[Any]] = {}
@staticmethod
def letter_to_class(letter):
"""Returns class for given path command letter"""
return PathCommand._letter_to_class[letter]
@property
@abc.abstractmethod
def args(self) -> List[float]:
"""Returns path command arguments as tuple of floats"""
def control_points(
self,
first: ComplexLike,
prev: ComplexLike,
prev_prev: ComplexLike,
) -> Generator[Vector2d, None, None]:
"""Returns list of path command control points"""
first, prev, prev_prev = complex(first), complex(prev), complex(prev_prev)
yield from [Vector2d(i) for i in self.ccontrol_points(first, prev, prev_prev)]
@abc.abstractmethod
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
"""Returns list of path command control points"""
@classmethod
def _argt(cls, sep):
return sep.join([cls.number_template] * cls.nargs)
def __str__(self):
return f"{self.letter} {self._argt(' ').format(*self.args)}".strip()
def __repr__(self):
# pylint: disable=consider-using-f-string
return "{{}}({})".format(self._argt(", ")).format(self.name, *self.args)
def __eq__(self, other):
previous = 0j
if type(self) == type(other): # pylint: disable=unidiomatic-typecheck
return self.args == other.args
if isinstance(other, tuple):
return self.args == other
if not isinstance(other, PathCommand):
raise ValueError("Can't compare types")
try:
if self.is_relative == other.is_relative:
return self.to_curve(previous) == other.to_curve(previous)
except ValueError:
pass
return False
@abc.abstractmethod
def cend_point(self, first: complex, prev: complex) -> complex:
"""Complex version of end_point"""
def end_point(self, first: ComplexLike, prev: ComplexLike) -> Vector2d:
"""Returns last control point of path command"""
return Vector2d(self.cend_point(complex(first or 0), complex(prev or 0)))
@abc.abstractmethod
def update_bounding_box(
self, first: complex, last_two_points: List[complex], bbox: BoundingBox
):
"""Enlarges given bbox to contain path element.
Args:
first (complex): first point of path. Required to calculate Z segment
last_two_points (List[complex]): list with last two control points in abs
coords.
bbox (BoundingBox): bounding box to update
"""
def to_curve(self, prev: ComplexLike, prev_prev: ComplexLike = 0) -> Curve:
# pylint: disable=unused-argument
"""Convert command to :py:class:`Curve`
Curve().to_curve() returns a copy
"""
return NotImplemented
def to_curves(self, prev: ComplexLike, prev_prev: ComplexLike = 0) -> List[Curve]:
"""Convert command to list of :py:class:`Curve` commands"""
return [self.to_curve(prev, prev_prev)]
def to_line(self, prev: ComplexLike) -> Line:
# pylint: disable=unused-argument
"""Converts this segment to a line (copies if already a line)"""
return NotImplemented
@abc.abstractmethod
def ccurve_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
# pylint: disable=unused-argument
"""Converts the path element into a single cubic bezier"""
# Derivation functionality
def __check_t(self, t: Optional[float], allow_none=True):
if not allow_none and (t is None and self.letter not in "zZmMlLhHvV"):
raise ValueError("t=None only supported for Line-like commands")
if t is not None and not 0 <= t <= 1:
raise ValueError("t should be between 0 and 1")
return t if t is not None else 0.0
def cderivative(
self,
first: complex,
prev: complex,
prev_control: complex,
t: Optional[float] = None,
n: int = 1,
) -> complex:
"""Returns the nth derivative of the segment at t as a complex number.
.. versionadded:: 1.4
"""
if n < 1:
raise ValueError("n should be a positive integer")
# pylint: disable=protected-access
return self._cderivative(first, prev, prev_control, self.__check_t(t), n)
def derivative(
self,
first: ComplexLike,
prev: ComplexLike,
prev_control: ComplexLike,
t: Optional[float] = None,
n: int = 1,
) -> Vector2d:
"""Returns the nth derivative of the segment at t as a :class:`Vector2D`.
.. versionadded:: 1.4
"""
return Vector2d(
self.cderivative(
complex(first or 0),
complex(prev or 0),
complex(prev_control or 0),
t,
n,
)
)
@abc.abstractmethod
def _cderivative(
self, first: complex, prev: complex, prev_control: complex, t: float, n: int = 1
) -> complex: ...
def cunit_tangent(
self,
first: complex,
prev: complex,
prev_control: complex,
t: Optional[float] = None,
) -> complex:
"""Returns the unit tangent of the segment at t as a complex number.
..versionadded:: 1.4
"""
return self._cunit_tangent(first, prev, prev_control, self.__check_t(t))
def unit_tangent(
self,
first: ComplexLike,
prev: ComplexLike,
prev_control: ComplexLike,
t: Optional[float] = None,
) -> Vector2d:
"""Returns the unit tangent of the segment at t as a :class:`Vector2D`.
..versionadded:: 1.4
"""
return Vector2d(
self.cunit_tangent(
complex(first or 0), complex(prev or 0), complex(prev_control or 0), t
)
)
def _cunit_tangent(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> complex:
dseg = self._cderivative(first, prev, t, 1)
return dseg / abs(dseg)
def cnormal(
self,
first: complex,
prev: complex,
prev_control: complex,
t: Optional[float] = None,
) -> complex:
"""Returns the (right-hand-rule) normal vector of the segment at t as a complex
number.
..versionadded:: 1.4
"""
return self.cunit_tangent(first, prev, prev_control, t) * 1j
def normal(
self,
first: ComplexLike,
prev: ComplexLike,
prev_control: ComplexLike,
t: Optional[float] = None,
) -> Vector2d:
"""Returns the (right-hand-rule) normal vector of the segment at t as
:class:`Vector2D`.
..versionadded:: 1.4
"""
return Vector2d(
self.cnormal(
complex(first or 0), complex(prev or 0), complex(prev_control or 0), t
)
)
def curvature(
self,
first: ComplexLike,
prev: ComplexLike,
prev_control: ComplexLike,
t: Optional[float] = None,
) -> float:
"""Returns the curvature of the segment at t.
..versionadded:: 1.4
"""
# pylint: disable=protected-access
return self._curvature(
complex(first or 0),
complex(prev or 0),
complex(prev_control or 0),
self.__check_t(t),
)
@abc.abstractmethod
def _curvature(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> float: ...
# Point evaluation, splitting
def cpoint(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> complex:
"""Returns the coordinates of the Bezier curve evaluated at t as complex number.
.. versionadded:: 1.4"""
return self._cpoint(first, prev, prev_control, self.__check_t(t, False))
def point(
self, first: ComplexLike, prev: ComplexLike, prev_control: ComplexLike, t: float
) -> Vector2d:
"""Returns the coordinates of the Bezier curve evaluated at t as :class:`Vector2d`.
.. versionadded:: 1.4"""
return Vector2d(
self.cpoint(
complex(first or 0), complex(prev or 0), complex(prev_control or 0), t
)
)
@abc.abstractmethod
def _cpoint(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> complex: ...
def split(
self, first: ComplexLike, prev: ComplexLike, prev_control: ComplexLike, t: float
) -> Tuple[PathCommand, PathCommand]:
"""Returns two segments, whose union is this segment and which join at
self.point(t).
.. versionadded:: 1.4"""
# no simplification here, we want to preserve the original type
return self._split(
complex(first),
complex(prev),
complex(prev_control),
self.__check_t(t, False),
)
@abc.abstractmethod
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[PathCommand, PathCommand]: ...
# Line integration
def length(
self,
first: ComplexLike,
prev: ComplexLike,
prev_control: ComplexLike,
t0: float = 0,
t1: float = 1,
settings=LengthSettings(),
) -> float:
"""Returns the length of the segment between t0 and t1.
.. versionadded:: 1.4"""
# pylint: disable=protected-access
return self._length(
complex(first),
complex(prev),
complex(prev_control),
self.__check_t(t0, False),
self.__check_t(t1, False),
settings,
)
@abc.abstractmethod
def _length(
self,
first: complex,
prev: complex,
prev_control: complex,
t0: float = 0,
t1: float = 1,
settings=LengthSettings(),
) -> float: ...
def ilength(
self,
first: ComplexLike,
prev: ComplexLike,
prev_control: ComplexLike,
length: float,
settings: ILengthSettings = ILengthSettings(),
):
"""Returns a float ``t``, such that ``self.length(0, t)`` is approximately
``length``.
.. versionadded:: 1.4"""
# pylint: disable=protected-access
return self._ilength(
complex(first), complex(prev), complex(prev_control), length, settings
)
@abc.abstractmethod
def _ilength(
self,
first: complex,
prev: complex,
prev_control: complex,
length: float,
settings: ILengthSettings = ILengthSettings(),
): ...
class RelativePathCommand(PathCommand):
"""
Abstract base class for relative path commands.
Implements most of methods of :py:class:`PathCommand` through
conversion to :py:class:`AbsolutePathCommand`
"""
@property
def is_relative(self):
return True
@property
def is_absolute(self):
return False
def to_relative(self, prev: ComplexLike) -> RelativePathCommand:
return self.__class__(*self.args)
def update_bounding_box(self, first, last_two_points, bbox):
self.to_absolute(last_two_points[-1]).update_bounding_box(
first, last_two_points, bbox
)
class AbsolutePathCommand(PathCommand):
"""Absolute path command. Unlike :py:class:`RelativePathCommand` can be transformed
directly."""
@property
def is_relative(self):
return False
@property
def is_absolute(self):
return True
def to_absolute(self, prev: ComplexLike) -> AbsolutePathCommand:
return self.__class__(*self.args)
@abc.abstractmethod
def transform(self, transform: Transform) -> AbsolutePathCommand:
"""Returns new transformed segment
:param transform: a transformation to apply
"""
def rotate(self, degrees: float, center: Vector2d) -> AbsolutePathCommand:
"""
Returns new transformed segment
:param degrees: rotation angle in degrees
:param center: invariant point of rotation
"""
return self.transform(Transform(rotate=(degrees, center[0], center[1])))
def translate(self, dr: Vector2d) -> AbsolutePathCommand:
"""Translate or scale this path command by dr"""
return self.transform(Transform(translate=dr))
def scale(self, factor: Union[float, Tuple[float, float]]) -> AbsolutePathCommand:
"""Returns new transformed segment
:param factor: scale or (scale_x, scale_y)
"""
return self.transform(Transform(scale=factor))
class BezierArcComputationMixin:
"""Functionality that works the same way for Arcs, Cubic and Quadratic
.. versionadded:: 1.4"""
_cpoint: Callable[[complex, complex, complex, float], complex]
_cderivative: Callable[..., complex]
poly: Callable[[complex, complex, complex, Optional[bool]], np.poly1d]
def inv_arclength(self, prev, prev_control, s, settings=ILengthSettings()):
"""Ported from https://github.com/mathandy/svgpathtools/blob/19df25b99b405ec4fc7616b58384eca7879b6fd4/svgpathtools/path.py#L541
(MIT Licensed)"""
t_upper = 1
t_lower = 0
iteration = 0
while iteration < settings.maxits:
iteration += 1
t = (t_lower + t_upper) / 2
s_t = self._length(0j, prev, prev_control, t1=t, settings=settings)
if abs(s_t - s) < settings.length_tol:
return t
elif s_t < s: # t too small
t_lower = t
else: # s < s_t, t too big
t_upper = t
if t_upper == t_lower:
# warn("t is as close as a float can be to the correct value, "
# "but |s(t) - s| = {} > s_tol".format(abs(s_t-s)))
return t
raise Exception(f"Maximum iterations reached with s(t) - s = {s_t - s}.")
def segment_length(
self,
start,
end,
start_point,
end_point,
pos_eval,
settings=LengthSettings(),
depth=0,
):
"""
Ported from https://github.com/mathandy/svgpathtools/blob/19df25b99b405ec4fc7616b58384eca7879b6fd4/svgpathtools/path.py#L479
(MIT licensed)
# TODO better treatment of degenerate beziers from
# https://github.com/linebender/kurbo/blob/c229a914d303c5989c9e6b1d766def2df27a8185/src/cubicbez.rs#L431
"""
mid = (start + end) / 2
mid_point = pos_eval(mid)
length = abs(end_point - start_point)
first_half = abs(mid_point - start_point)
second_half = abs(end_point - mid_point)
length2 = first_half + second_half
if (length2 - length > settings.error) or (depth < settings.min_depth):
# Calculate the length of each segment:
depth += 1
return self.segment_length(
start, mid, start_point, mid_point, pos_eval, settings, depth
) + self.segment_length(
mid, end, mid_point, end_point, pos_eval, settings, depth
)
# This is accurate enough.
return length2
def segment_curvature(self, prev: complex, prev_prev: complex, t: float):
"""Returns the curvature of the segment at t.
Ported from https://github.com/mathandy/svgpathtools/blob/19df25b99b405ec4fc7616b58384eca7879b6fd4/svgpathtools/path.py#L386
(MIT licensed)
"""
dz = self._cderivative(0j, prev, prev_prev, t)
ddz = self._cderivative(0j, prev, prev_prev, t, n=2)
dx, dy = dz.real, dz.imag
ddx, ddy = ddz.real, ddz.imag
try:
kappa = abs(dx * ddy - dy * ddx) / math.sqrt(dx * dx + dy * dy) ** 3
except (ZeroDivisionError, FloatingPointError):
# tangent vector is zero at t, use polytools to find limit
p = self.poly(0j, prev, prev_prev, False)
dp = p.deriv()
ddp = dp.deriv()
dx2, dy2 = np.real(dp), np.imag(dp)
ddx2, ddy2 = np.real(ddp), np.imag(ddp)
f2 = (dx2 * ddy2 - dy2 * ddx2) ** 2
g2 = (dx2 * dx2 + dy2 * dy2) ** 3
lim2 = rational_limit(f2, g2, t)
if lim2 < 0: # impossible, must be numerical error
return 0
kappa = math.sqrt(lim2)
return kappa
def _length(
self,
first: complex,
prev: complex,
prev_control: complex,
t0=0,
t1=1,
settings=LengthSettings(),
) -> float:
return self.segment_length(
t0,
t1,
self._cpoint(first, prev, prev_control, t0),
self._cpoint(first, prev, prev_control, t1),
lambda t: self._cpoint(first, prev, prev_control, t),
settings,
0,
)
def _ilength(
self,
first: complex,
prev: complex,
prev_control: complex,
length,
settings=ILengthSettings(),
):
return self.inv_arclength(prev, prev_control, length, settings)
def _curvature(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> float:
return self.segment_curvature(prev, prev_control, t)
class BezierComputationMixin:
"""Functionality that works the same for all Beziers (Quadratic, Cubic)
.. versionadded:: 1.4"""
def _bpoints(self, prev, prev_prev):
return (prev,) + self.ccontrol_points(0j, prev, prev_prev)
def bezier_unit_tangent(self, prev, prev_prev, t):
"""Returns the unit tangent of the segment at t.
Ported from https://github.com/mathandy/svgpathtools/blob/19df25b99b405ec4fc7616b58384eca7879b6fd4/svgpathtools/path.py#L348
(MIT licensed)"""
dseg = self._cderivative(0j, prev, prev_prev, t)
try:
unit_tangent = dseg / abs(dseg)
except (ZeroDivisionError, FloatingPointError):
# This may be a removable singularity, if so we just need to compute
# the limit.
# Note: limit{{dseg / abs(dseg)} = sqrt(limit{dseg**2 / abs(dseg)**2})
dseg_poly = self.poly(prev, prev_prev).deriv()
dseg_abs_squared_poly = np.real(dseg_poly) ** 2 + np.imag(dseg_poly) ** 2
try:
unit_tangent = np.sqrt(
rational_limit(dseg_poly**2, dseg_abs_squared_poly, t)
)
except ValueError:
bef = self.poly(prev, prev_prev).deriv()(t - 1e-4)
aft = self.poly(prev, prev_prev).deriv()(t + 1e-4)
mes = (
"Unit tangent appears to not be well-defined at "
f"t = {t}, \n"
f"seg.poly().deriv()(t - 1e-4) = {bef}\n"
f"seg.poly().deriv()(t + 1e-4) = {aft}"
)
raise ValueError(mes)
return unit_tangent

View File

@@ -0,0 +1,601 @@
# coding=utf-8
#
# Copyright (C) 2018 Martin Owens <doctormo@gmail.com>
# Copyright (C) 2023 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.
#
"""Line-like path commands (Line, Horz, Vert, ZoneClose and their relative siblings)"""
from __future__ import annotations
from typing import overload, Tuple, Optional, TYPE_CHECKING, Callable, Union
from inkex.paths.interfaces import ILengthSettings, LengthSettings
from ..transforms import Transform, BoundingBox, ComplexLike
from .interfaces import AbsolutePathCommand, RelativePathCommand, ILengthSettings
if TYPE_CHECKING:
from .curves import Curve
class LineMixin:
"""Common Line functions"""
# pylint: disable=unused-argument
arg1: complex
cend_point: Callable[[complex, complex], complex]
def ccurve_points(self, first: complex, prev: complex, prev_prev: complex):
"""Common implementation of ccurve_points for Lines"""
arg1 = self.cend_point(first, prev)
return prev, arg1, arg1
def ccontrol_points(
self,
first: complex,
prev: complex,
prev_prev: complex, # pylint: disable=unused-argument
) -> Tuple[complex, ...]:
"""Common implementation of ccontrol_points for Lines"""
return (self.cend_point(first, prev),)
def _cderivative(
self, first: complex, prev: complex, prev_control: complex, t: float, n: int = 1
) -> complex:
start = self.cend_point(first, prev)
if prev == start:
raise ValueError("Derivative is not defined for zero-length segments")
if n == 1:
return start - prev
return 0j
def _curvature(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> float:
return 0
def _cpoint(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> complex:
return self.cend_point(first, prev) * t + (1 - t) * prev
def _length(
self,
first: complex,
prev: complex,
prev_control: complex,
t0: float = 0,
t1: float = 1,
settings=LengthSettings(),
) -> float:
return abs(self.cend_point(first, prev) - prev) * (t1 - t0)
def _ilength(
self,
first: complex,
prev: complex,
prev_control: complex,
length: float,
settings: ILengthSettings = ILengthSettings(),
):
return length / self._length(first, prev, prev_control)
class Line(LineMixin, AbsolutePathCommand):
"""Line segment"""
letter = "L"
nargs = 2
arg1: complex
"""The (absolute) end points of the line."""
@property
def x(self):
"""x coordinate of the line's (absolute) end point."""
return self.arg1.real
@property
def y(self):
"""y coordinate of the line's (absolute) end point."""
return self.arg1.imag
@property
def args(self):
return self.x, self.y
@overload
def __init__(self, x: ComplexLike): ...
@overload
def __init__(self, x: float, y: float): ...
def __init__(self, x, y=None):
if y is not None:
self.arg1 = x + y * 1j
else:
self.arg1 = complex(x)
def update_bounding_box(self, first, last_two_points, bbox):
bbox += BoundingBox(
(last_two_points[-1].real, self.x), (last_two_points[-1].imag, self.y)
)
def to_relative(self, prev: ComplexLike) -> line:
return line(self.arg1 - prev)
def transform(self, transform) -> Line:
return Line(transform.capply_to_point(self.arg1))
def cend_point(self, first: complex, prev: complex) -> complex:
# pylint: disable=unused-argument
return self.arg1
def reverse(self, first: ComplexLike, prev: ComplexLike) -> Line:
return Line(prev)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[Line, Line]:
return Line(self._cpoint(first, prev, prev_control, t)), Line(self.arg1)
class line(LineMixin, RelativePathCommand): # pylint: disable=invalid-name
"""Relative line segment"""
letter = "l"
nargs = 2
arg1: complex
"""The (relative) end points of the line."""
@property
def dx(self):
"""x coordinate of the line's (relative) end point."""
return self.arg1.real
@property
def dy(self):
"""y coordinate of the line's (relative) end point."""
return self.arg1.imag
@property
def args(self):
return self.dx, self.dy
@overload
def __init__(self, dx: ComplexLike): ...
@overload
def __init__(self, dx: float, dy: float): ...
def __init__(self, dx, dy=None):
if dy is not None:
self.arg1 = dx + dy * 1j
else:
self.arg1 = complex(dx)
def to_absolute(self, prev: ComplexLike) -> Line:
return Line(prev + self.arg1)
def cend_point(self, first: complex, prev: complex) -> complex:
# pylint: disable=unused-argument
return self.arg1 + prev
def reverse(self, first: ComplexLike, prev: ComplexLike) -> line:
return line(-self.arg1)
def to_curve(
self, prev: ComplexLike, prev_prev: Optional[ComplexLike] = 0j
) -> Curve:
raise ValueError("Move segments can not be changed into curves.")
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[line, line]:
dx1 = self.cpoint(first, prev, prev_control, t) - prev
return line(dx1), line(self.arg1 - dx1)
class MoveMixin:
"""Disable derivative / length method for Move command."""
def _cderivative(
self, first: complex, prev: complex, prev_control: complex, t: float, n: int = 1
) -> complex:
raise ValueError("Derivative is not supported for move/Move")
def _cunit_tangent(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> complex:
raise ValueError("Unit Tangent is not supported for move/Move")
def _curvature(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> float:
raise ValueError("Curvature is not supported for move/Move")
def _cpoint(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> complex:
raise ValueError("Point is not supported for move/Move")
def _length(
self,
first: complex,
prev: complex,
prev_control: complex,
t0: float = 0,
t1: float = 1,
settings=LengthSettings(),
) -> float:
raise ValueError("Length is not supported for move/Move")
def _ilength(
self,
first: complex,
prev: complex,
prev_control: complex,
length: float,
settings: ILengthSettings = ILengthSettings(),
):
raise ValueError("ILength is not supported for move/Move")
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[Move, Move]:
raise ValueError("Split is not supported for move/Move")
class Move(MoveMixin, AbsolutePathCommand):
"""Move pen segment without a line"""
letter = "M"
nargs = 2
next_command = Line
arg1: complex
"""The (absolute) end points of the Move command"""
@property
def x(self):
"""x coordinate of the Moves's (absolute) end point."""
return self.arg1.real
@property
def y(self):
"""y coordinate of the Move's (absolute) end point."""
return self.arg1.imag
@property
def args(self):
return self.x, self.y
@overload
def __init__(self, x: ComplexLike): ...
@overload
def __init__(self, x: float, y: float): ...
def __init__(self, x, y=None):
if y is not None:
self.arg1 = x + y * 1j
else:
self.arg1 = complex(x)
def update_bounding_box(self, first, last_two_points, bbox):
bbox += BoundingBox(self.x, self.y)
def ccurve_points(self, first: complex, prev: complex, prev_prev: complex):
return prev, self.arg1, self.arg1
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
return (self.arg1,)
def to_relative(self, prev: ComplexLike) -> move:
return move(self.arg1 - prev)
def transform(self, transform: Transform) -> Move:
return Move(transform.capply_to_point(self.arg1))
def cend_point(self, first: complex, prev: complex) -> complex:
return self.arg1
def to_curve(
self, prev: ComplexLike, prev_prev: Optional[ComplexLike] = 0j
) -> Curve:
raise ValueError("Move segments can not be changed into curves.")
def reverse(self, first: ComplexLike, prev: ComplexLike) -> Move:
return Move(prev)
class move(MoveMixin, RelativePathCommand): # pylint: disable=invalid-name
"""Relative move segment"""
letter = "m"
nargs = 2
next_command = line
@property
def dx(self):
"""x coordinate of the moves's (relative) end point."""
return self.arg1.real
@property
def dy(self):
"""y coordinate of the move's (relative) end point."""
return self.arg1.imag
@property
def args(self):
return self.dx, self.dy
@overload
def __init__(self, dx: ComplexLike): ...
@overload
def __init__(self, dx: float, dy: float): ...
def __init__(self, dx, dy=None):
if dy is not None:
self.arg1 = dx + dy * 1j
else:
self.arg1 = complex(dx)
def ccurve_points(self, first: complex, prev: complex, prev_prev: complex):
return prev, self.arg1 + prev, self.arg1 + prev
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
return (self.arg1 + prev,)
def cend_point(self, first: complex, prev: complex) -> complex:
return self.arg1 + prev
def to_absolute(self, prev: ComplexLike) -> Move:
return Move(prev + self.arg1)
def reverse(self, first: ComplexLike, prev: ComplexLike) -> move:
return move(prev - first)
def to_curve(
self, prev: ComplexLike, prev_prev: Optional[ComplexLike] = 0j
) -> Curve:
raise ValueError("Move segments can not be changed into curves.")
class ZoneClose(LineMixin, AbsolutePathCommand):
"""Close segment to finish a path"""
letter = "Z"
nargs = 0
next_command = Move
@property
def args(self):
return ()
def update_bounding_box(self, first, last_two_points, bbox):
pass
def transform(self, transform: Transform) -> ZoneClose:
return ZoneClose()
def to_relative(self, prev: ComplexLike) -> zoneClose:
return zoneClose()
def cend_point(self, first: complex, prev: complex) -> complex:
# pylint: disable=unused-argument
return first
def to_curve(
self, prev: ComplexLike, prev_prev: Optional[ComplexLike] = 0j
) -> Curve:
raise ValueError("ZoneClose segments can not be changed into curves.")
def reverse(self, first: ComplexLike, prev: ComplexLike) -> Line:
return Line(prev)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[Line, ZoneClose]:
return Line(self._cpoint(first, prev, prev_control, t)), ZoneClose()
class zoneClose(LineMixin, RelativePathCommand): # pylint: disable=invalid-name
"""Same as above (svg says no difference)"""
letter = "z"
nargs = 0
next_command = Move
@property
def args(self):
return ()
def to_absolute(self, prev: ComplexLike):
return ZoneClose()
def reverse(self, first: ComplexLike, prev: ComplexLike) -> line:
return line(prev - first)
def cend_point(self, first: complex, prev: complex) -> complex:
# pylint: disable=unused-argument
return first
def to_curve(
self, prev: ComplexLike, prev_prev: Optional[ComplexLike] = 0j
) -> Curve:
raise ValueError("ZoneClose segments can not be changed into curves.")
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[line, zoneClose]:
return line(self.cpoint(first, prev, prev_control, t) - prev), zoneClose()
class Horz(LineMixin, AbsolutePathCommand):
"""Horizontal Line segment"""
letter = "H"
nargs = 1
@property
def args(self):
return (self.x,)
def __init__(self, x):
self.x = x
def update_bounding_box(self, first, last_two_points, bbox):
bbox += BoundingBox(
(last_two_points[-1].real, self.x), last_two_points[-1].imag
)
def to_relative(self, prev: ComplexLike) -> horz:
return horz(self.x - complex(prev).real)
def to_non_shorthand(self, prev: ComplexLike, prev_control: ComplexLike) -> Line:
return self.to_line(prev)
def transform(self, transform: Transform) -> AbsolutePathCommand:
raise ValueError("Horizontal lines can't be transformed directly.")
def cend_point(self, first: complex, prev: complex) -> complex:
# pylint: disable=unused-argument
return self.x + prev.imag * 1j
def reverse(self, first: ComplexLike, prev: ComplexLike) -> Horz:
return Horz(complex(prev).real)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[Horz, Horz]:
return Horz(self.cpoint(first, prev, prev_control, t).real), Horz(self.x)
class horz(LineMixin, RelativePathCommand): # pylint: disable=invalid-name
"""Relative horz line segment"""
letter = "h"
nargs = 1
@property
def args(self):
return (self.dx,)
def __init__(self, dx):
self.dx = dx
def to_absolute(self, prev: ComplexLike) -> Horz:
return Horz(complex(prev).real + self.dx)
def to_non_shorthand(self, prev: ComplexLike, prev_control: ComplexLike) -> Line:
return self.to_line(prev)
def cend_point(self, first: complex, prev: complex) -> complex:
# pylint: disable=unused-argument
return (self.dx + prev.real) + prev.imag * 1j
def reverse(self, first: ComplexLike, prev: ComplexLike) -> horz:
return horz(-self.dx)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[horz, horz]:
dx1 = (self.cpoint(first, prev, prev_control, t) - prev).real
return horz(dx1), horz(self.dx - dx1)
class Vert(LineMixin, AbsolutePathCommand):
"""Vertical Line segment"""
letter = "V"
nargs = 1
@property
def args(self):
return (self.y,)
def __init__(self, y):
self.y = y
def update_bounding_box(self, first, last_two_points, bbox):
bbox += BoundingBox(
last_two_points[-1].real, (last_two_points[-1].imag, self.y)
)
def transform(self, transform: Transform) -> AbsolutePathCommand:
raise ValueError("Vertical lines can't be transformed directly.")
def to_non_shorthand(self, prev: ComplexLike, prev_control: ComplexLike) -> Line:
return self.to_line(prev)
def to_relative(self, prev: ComplexLike) -> vert:
return vert(self.y - complex(prev).imag)
def cend_point(self, first: complex, prev: complex) -> complex:
# pylint: disable=unused-argument
return prev.real + self.y * 1j
def reverse(self, first: ComplexLike, prev: ComplexLike) -> Vert:
return Vert(complex(prev).imag)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[Vert, Vert]:
return Vert(self.cpoint(first, prev, prev_control, t).imag), Vert(self.y)
class vert(LineMixin, RelativePathCommand): # pylint: disable=invalid-name
"""Relative vertical line segment"""
letter = "v"
nargs = 1
@property
def args(self):
return (self.dy,)
def __init__(self, dy):
self.dy = dy
def to_absolute(self, prev: ComplexLike) -> Vert:
return Vert(complex(prev).imag + self.dy)
def to_non_shorthand(self, prev: ComplexLike, prev_control: ComplexLike) -> Line:
return self.to_line(prev)
def cend_point(self, first: complex, prev: complex) -> complex:
# pylint: disable=unused-argument
return prev.real + (prev.imag + self.dy) * 1j
def reverse(self, first: ComplexLike, prev: ComplexLike) -> vert:
return vert(-self.dy)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[vert, vert]:
dy1 = (self.cpoint(first, prev, prev_control, t) - prev).imag
return vert(dy1), vert(self.dy - dy1)

View File

@@ -0,0 +1,937 @@
# coding=utf-8
#
# Copyright (C) 2018 Martin Owens <doctormo@gmail.com>
# Copyright (C) 2023 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.
#
"""
Path and CubicSuperPath classes
"""
from __future__ import annotations
import re
import copy
import warnings
from cmath import isclose
from typing import Optional, Tuple, List, TypeVar, Iterator, Callable, Union
from ..transforms import (
Transform,
BoundingBox,
Vector2d,
ComplexLike,
)
from ..utils import strargs
from .lines import Line, Move, move, ZoneClose, zoneClose
from .curves import Curve
from .interfaces import (
ILengthSettings,
LengthSettings,
PathCommand,
AbsolutePathCommand,
)
Pathlike = TypeVar("Pathlike", bound="PathCommand")
AbsolutePathlike = TypeVar("AbsolutePathlike", bound="AbsolutePathCommand")
LEX_REX = re.compile(r"([MLHVCSQTAZmlhvcsqtaz])([^MLHVCSQTAZmlhvcsqtaz]*)")
class InvalidPath(ValueError):
"""Raised when given an invalid path string"""
class Path(list):
"""A list of segment commands which combine to draw a shape"""
callback: Optional[Callable] = None
class PathCommandProxy:
"""
A handy class for Path traverse and coordinate access
Reduces number of arguments in user code compared to bare
:class:`PathCommand` methods
"""
def __init__(
self,
command: PathCommand,
first_point: ComplexLike,
previous_end_point: ComplexLike,
prev2_control_point: ComplexLike,
):
self.command = command
self.cfirst_point = complex(first_point)
self.cprevious_end_point = complex(previous_end_point)
self.cprev2_control_point = complex(prev2_control_point)
@property
def first_point(self) -> Vector2d:
"""First point of the current subpath"""
return Vector2d(self.cfirst_point)
@property
def previous_end_point(self) -> Vector2d:
"""End point of the previous command"""
return Vector2d(self.cprevious_end_point)
@property
def prev2_control_point(self) -> Vector2d:
"""Last control point of the previous command"""
return Vector2d(self.cprev2_control_point)
@property
def name(self) -> str:
"""The full name of the segment (i.e. Line, Arc, etc)"""
return self.command.name
@property
def letter(self) -> str:
"""The single letter representation of this command (i.e. L, A, etc)"""
return self.command.letter
@property
def next_command(self):
"""The implicit next command."""
return self.command.next_command
@property
def is_relative(self) -> bool:
"""Whether the command is defined in relative coordinates, i.e. relative to
the previous endpoint (lower case path command letter)"""
return self.command.is_relative
@property
def is_absolute(self) -> bool:
"""Whether the command is defined in absolute coordinates (upper case path
command letter)"""
return self.command.is_absolute
@property
def args(self) -> List[float]:
"""Returns path command arguments as tuple of floats"""
return self.command.args
@property
def control_points(self) -> List[Vector2d]:
"""Returns list of path command control points"""
return list(
self.command.control_points(
self.cfirst_point,
self.cprevious_end_point,
self.cprev2_control_point,
)
)
@property
def end_point(self) -> Vector2d:
"""Returns last control point of path command"""
return Vector2d(self.cend_point)
@property
def cend_point(self) -> complex:
"""Returns last control point of path command (in complex form)"""
return self.command.cend_point(self.cfirst_point, self.cprevious_end_point)
def reverse(self) -> PathCommand:
"""Reverse path command"""
return self.command.reverse(self.cend_point, self.cprevious_end_point)
def to_curve(self) -> Curve:
"""Convert command to :py:class:`Curve`
Curve().to_curve() returns a copy
"""
return self.command.to_curve(
self.cprevious_end_point, self.cprev2_control_point
)
def to_curves(self) -> List[Curve]:
"""Convert command to list of :py:class:`Curve` commands"""
return self.command.to_curves(
self.cprevious_end_point, self.cprev2_control_point
)
def to_absolute(self) -> AbsolutePathCommand:
"""Return relative counterpart for relative commands or copy for absolute"""
return self.command.to_absolute(self.cprevious_end_point)
def to_non_shorthand(self) -> AbsolutePathCommand:
"""Returns an absolute non-shorthand command
.. versionadded:: 1.4"""
return self.command.to_non_shorthand(
self.cprevious_end_point, self.cprev2_control_point
)
def split(self, time) -> Tuple[Path.PathCommandProxy, Path.PathCommandProxy]:
"""Split this path command into two PathCommandProxy segments.
Raises ValueError for Move commands.
.. versionadded:: 1.4"""
result = self.command.split(
self.cfirst_point,
self.cprevious_end_point,
self.cprev2_control_point,
time,
)
p1 = Path.PathCommandProxy(
result[0],
self.cfirst_point,
self.previous_end_point,
self.prev2_control_point,
)
prev2: ComplexLike = (
0j if len(p1.control_points) < 2 else p1.control_points[-2]
)
p2 = Path.PathCommandProxy(
result[1], self.cfirst_point, p1.end_point, prev2
)
return (p1, p2)
def cpoint(self, time) -> complex:
"""Returns the coordinates of the Bezier curve evaluated at t as complex number.
.. versionadded:: 1.4"""
return self.command.cpoint(
self.cfirst_point,
self.cprevious_end_point,
self.cprev2_control_point,
time,
)
def point(self, time) -> Vector2d:
"""Returns the coordinates of the Bezier curve evaluated at t as :class:`Vector2d`.
.. versionadded:: 1.4"""
return self.command.point(
self.cfirst_point,
self.cprevious_end_point,
self.cprev2_control_point,
time,
)
def length(self, t0=0, t1=1, settings=LengthSettings()) -> float:
"""Get the length of the command between t0 and t1 in user units
.. versionadded:: 1.4"""
return self.command.length(
self.cfirst_point,
self.cprevious_end_point,
self.cprev2_control_point,
t0,
t1,
settings,
)
def ilength(self, length, settings=ILengthSettings()) -> float:
"""Tries to compute the time t at which the path segment has the given
length along its trajectory
.. versionadded:: 1.4"""
return self.command.ilength(
self.cfirst_point,
self.cprevious_end_point,
self.cprev2_control_point,
length,
settings,
)
def cunit_tangent(self, t) -> complex:
"""Returns the unit tangent at t as complex number
.. versionadded:: 1.4"""
return self.command.cunit_tangent(
self.cfirst_point,
self.cprevious_end_point,
self.cprev2_control_point,
t,
)
def unit_tangent(self, t) -> Vector2d:
"""Returns the unit tangent at t as :class:`inkex.Vector2D`
.. versionadded:: 1.4"""
return self.command.unit_tangent(
self.cfirst_point,
self.cprevious_end_point,
self.cprev2_control_point,
t,
)
def __str__(self):
return str(self.command)
def __repr__(self):
return "<" + self.__class__.__name__ + ">" + repr(self.command)
def __init__(self, path_d=None) -> None:
super().__init__()
if isinstance(path_d, str):
# Returns a generator returning PathCommand objects
path_d = self.parse_string(path_d)
elif isinstance(path_d, CubicSuperPath):
path_d = path_d.to_path()
for item in path_d or ():
if isinstance(item, PathCommand):
self.append(item)
elif isinstance(item, (list, tuple)) and len(item) == 2:
if isinstance(item[1], (list, tuple)):
self.append(PathCommand.letter_to_class(item[0])(*item[1]))
else:
if len(self) == 0:
self.append(Move(*item))
else:
self.append(Line(*item))
else:
raise TypeError(
f"Bad path type: {type(path_d).__name__}"
f"({type(item).__name__}, ...): {item}"
)
@classmethod
def parse_string(cls, path_d):
"""Parse a path string and generate segment objects"""
for cmd, numbers in LEX_REX.findall(path_d):
args = list(strargs(numbers))
cmd = PathCommand.letter_to_class(cmd)
i = 0
while i < len(args) or cmd.nargs == 0:
if len(args[i : i + cmd.nargs]) != cmd.nargs:
return
seg = cmd(*args[i : i + cmd.nargs])
i += cmd.nargs
cmd = seg.next_command
yield seg
def bounding_box(self) -> Optional[BoundingBox]:
"""Return bounding box of the Path"""
if not self:
return None
iterator = self.proxy_iterator()
proxy = next(iterator)
bbox = BoundingBox(proxy.first_point.x, proxy.first_point.y)
try:
while True:
proxy = next(iterator)
proxy.command.update_bounding_box(
complex(proxy.first_point),
[
proxy.cprev2_control_point,
proxy.cprevious_end_point,
],
bbox,
)
except StopIteration:
return bbox
def append(self, cmd):
"""Append a command to this path."""
try:
cmd.letter # pylint: disable=pointless-statement
super().append(cmd)
except AttributeError:
self.extend(cmd)
warnings.warn(
"Passing a list to Path.add is deprecated, please use Path.extend",
category=DeprecationWarning,
)
def translate(self, x, y, inplace=False): # pylint: disable=invalid-name
"""Move all coords in this path by the given amount"""
return self.transform(Transform(translate=(x, y)), inplace=inplace)
def scale(self, x, y, inplace=False): # pylint: disable=invalid-name
"""Scale all coords in this path by the given amounts"""
return self.transform(Transform(scale=(x, y)), inplace=inplace)
def rotate(self, deg, center=None, inplace=False):
"""Rotate the path around the given point"""
if center is None:
# Default center is center of bbox
bbox = self.bounding_box()
if bbox:
center = bbox.center
else:
center = Vector2d()
center = Vector2d(center)
return self.transform(
Transform(rotate=(deg, center.x, center.y)), inplace=inplace
)
@property
def control_points(self) -> Iterator[Vector2d]:
"""Returns all control points of the Path"""
prev: complex = 0
prev_prev: complex = 0
first: complex = 0
seg: PathCommand
for seg in self:
cpts = seg.ccontrol_points(first, prev, prev_prev)
if seg.letter in "zZmM":
first = cpts[-1]
for cpt in cpts:
prev_prev = prev
prev = cpt
yield Vector2d(cpt)
@property
def cend_points(self) -> Iterator[complex]:
"""Complex version of end_points"""
prev = 0j
first = 0j
seg: PathCommand
for seg in self:
end_point = seg.cend_point(first, prev)
if seg.letter in "zZmM":
first = end_point
prev = end_point
yield end_point
@property
def end_points(self) -> Iterator[Vector2d]:
"""Returns all endpoints of all path commands (i.e. the nodes)"""
for i in self.cend_points:
yield Vector2d(i)
def transform(self, transform, inplace=False):
"""Convert to new path"""
result = Path()
previous = 0j
previous_new = 0j
start_zone = True
first = 0j
first_new = 0j
seg: PathCommand
for i, seg in enumerate(self):
if start_zone:
first = seg.cend_point(first, previous)
if seg.letter in "hHVv":
seg = seg.to_line(previous)
if seg.is_relative:
new_seg = (
seg.to_absolute(previous)
.transform(transform)
.to_relative(previous_new)
)
else:
new_seg = seg.transform(transform)
if start_zone:
first_new = new_seg.cend_point(first_new, previous_new)
if inplace:
self[i] = new_seg
else:
result.append(new_seg)
previous = seg.cend_point(first, previous)
previous_new = new_seg.cend_point(first_new, previous_new)
start_zone = seg.letter in "zZ"
if inplace:
return self
return result
def reverse(self):
"""Returns a reversed path"""
result = Path()
try:
*_, first = self.cend_points
except ValueError:
# Empty path, return empty path
return result
closer = None
# Go through the path in reverse order
for index, prcom in reversed(list(enumerate(self.proxy_iterator()))):
if prcom.letter in "MmZz":
if closer is not None:
if len(result) > 0 and result[-1].letter in "LlVvHh":
result.pop() # We can replace simple lines with Z
result.append(closer) # replace with same type (rel or abs)
if prcom.letter in "Zz":
closer = prcom.command
else:
closer = None
if index == 0:
if prcom.letter == "M":
result.insert(0, Move(first))
elif prcom.letter == "m":
result.insert(0, move(first))
else:
result.append(prcom.reverse())
return result
def break_apart(self) -> List[Path]:
"""Breaks apart a path into its subpaths
.. versionadded:: 1.3"""
result = [Path()]
current = result[0]
for cmnd in self.proxy_iterator():
if cmnd.letter.lower() == "m":
current = Path()
result.append(current)
current.append(Move(cmnd.cend_point))
else:
current.append(cmnd.command)
# Remove all subpaths that are empty or only contain move commands
return [
i
for i in result
if len(i) != 0 and not all(j.letter.lower() == "m" for j in i)
]
def close(self):
"""Attempt to close the last path segment"""
if self and not self[-1].letter in "zZ":
self.append(ZoneClose())
def proxy_iterator(self) -> Iterator[PathCommandProxy]:
"""
Yields :py:class:`AugmentedPathIterator`
:rtype: Iterator[ Path.PathCommandProxy ]
"""
previous = 0j
prev_prev = 0j
first = 0j
seg: PathCommand
for seg in self:
if seg.letter in "zZmM":
first = seg.cend_point(first, previous)
yield Path.PathCommandProxy(seg, first, previous, prev_prev)
if seg.letter in "ctqsCTQS":
prev_prev = seg.ccontrol_points(first, previous, prev_prev)[-2]
previous = seg.cend_point(first, previous)
def subpath_iterator(self):
"""Yield Path for each subpath."""
start_id = 0
for i, seg in enumerate(self):
if isinstance(seg, (move, Move)):
if start_id > -1 and i > 0: # add previous path (open path)
yield Path(self[start_id:i])
start_id = i
elif isinstance(seg, (zoneClose, ZoneClose)): # add current path (closed)
yield Path(self[start_id : i + 1])
start_id = -1
elif i == len(self) - 1 and start_id > -1: # add last path (open)
yield Path(self[start_id:])
def to_absolute(self):
"""Convert this path to use only absolute coordinates"""
return self._to_absolute(True)
def to_non_shorthand(self) -> Path:
"""Convert this path to use only absolute non-shorthand coordinates
.. versionadded:: 1.1"""
return self._to_absolute(False)
def _to_absolute(self, shorthand: bool) -> Path:
"""Make entire Path absolute.
Args:
shorthand (bool): If false, then convert all shorthand commands to
non-shorthand.
Returns:
Path: the input path, converted to absolute coordinates.
"""
abspath = Path()
previous = 0j
first = 0j
seg: PathCommand
for seg in self:
if seg.letter in "mM":
first = seg.cend_point(first, previous)
if shorthand:
abspath.append(seg.to_absolute(previous))
else:
if abspath and abspath[-1].letter in "QC":
prev_control = list(abspath[-1].control_points(0, 0, 0))[-2]
else:
prev_control = previous
abspath.append(seg.to_non_shorthand(previous, prev_control))
previous = seg.cend_point(first, previous)
return abspath
def to_relative(self):
"""Convert this path to use only relative coordinates"""
abspath = Path()
previous = 0j
first = 0j
seg: PathCommand
for seg in self:
if seg.letter in "mM":
first = seg.cend_point(first, previous)
abspath.append(seg.to_relative(previous))
previous = seg.cend_point(first, previous)
return abspath
def __str__(self):
return " ".join([str(seg) for seg in self])
@staticmethod
def __add_helper__(other):
"""Prepare a path for adding (either add or iadd)"""
if isinstance(other, str):
other = Path(other)
return other
def __iadd__(self, value):
return super().__iadd__(self.__add_helper__(value))
def __add__(self, other):
acopy = copy.deepcopy(self)
other = self.__add_helper__(other)
if isinstance(other, list):
acopy.extend(other)
return acopy
def to_arrays(self):
"""Returns path in format of parsePath output, returning arrays of absolute
command data
.. deprecated:: 1.0
This is compatibility function for older API. Should not be used in new code
"""
return [[seg.letter, list(seg.args)] for seg in self.to_non_shorthand()]
def to_superpath(self):
"""Convert this path into a cubic super path"""
return CubicSuperPath(self)
def copy(self):
"""Make a copy"""
return copy.deepcopy(self)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if self.callback is not None:
self.callback(self) # pylint: disable=not-callable
class CubicSuperPath(list):
"""
A conversion of a path into a predictable list of cubic curves which
can be operated on as a list of simplified instructions.
When converting back into a path, all lines, arcs etc will be converted
to curve instructions.
Structure is held as [SubPath[(point_a, bezier, point_b), ...], ...]
"""
def __init__(self, items):
super().__init__()
self._closed = True
self._prev = 0j
self._prev_prev = 0j
if isinstance(items, str):
items = Path(items)
if isinstance(items, Path):
for item in items:
self.append_path_command(item)
return
for item in items:
self.append(item)
def __str__(self):
return str(self.to_path())
def append_node_with_handles(self, command: List[Tuple[float, float]]):
"""First item: left handle, second item: node coords,
third item: right handle"""
if self._closed:
# Closed means that the previous segment is closed so we need a new one
# We always append to the last open segment. CSP starts out closed.
self._closed = False
super().append([])
self[-1].append(command)
self._prev_prev = command[0][0] + command[0][1] * 1j
self._prev = command[1][0] + command[1][1] * 1j
def append_path_command(self, command: PathCommand):
"""Append a path command.
For ordinary commands:
..code ::
old last entry -> [[.., ..], [.., ..], [x1, y1]]
new last entry -> [[x2, y2], [x3, y3], [x3, y3]]
The last tuple is duplicated (retracted handle): either it's the last command
of the subpath, then the handle will stay retracted, or it will be replaced
with the next path command.
"""
if command.letter in "mM":
carg = command.cend_point(self._first, self._prev)
arg = Vector2d.c2t(carg)
super().append([[arg[:], arg[:], arg[:]]])
self._prev = self._prev_prev = carg
self._closed = False
return
if command.letter in "zZ" and self:
# This duplicates the first segment to 'close' the path
self[-1].append([self[-1][0][0][:], self[-1][0][1][:], self[-1][0][2][:]])
# Then adds a new subpath for the next shape (if any)
# self._closed = True
self._prev = self._first
return
if command.letter in "aA":
# Arcs are made up of (possibly) more than one curve, depending on their
# angle (approximated)
for arc_curve in command.to_curves(self._prev, self._prev_prev):
self.append_path_command(arc_curve)
return
# Handle regular curves.
if self._closed:
# Previous segment is closed. Append a new segment first.
self._closed = False
super().append([])
cp1, cp2, cp3 = command.ccurve_points(0j, self._prev, self._prev_prev)
item = [Vector2d.c2t(cp1), Vector2d.c2t(cp2), Vector2d.c2t(cp3)]
self._prev = cp3
if not command.letter in "QT":
self._prev_prev = cp2
else:
self._prev_prev = command.ccontrol_points(0j, self._prev, self._prev_prev)[
0
]
if self[-1]: # There exists a previous segment, replace its outgoing handle.
self[-1][-1][-1] = item[0]
# Append the segment with the last coordinate (node pos) repeated.
self[-1].append(item[1:] + [item[-1][:]])
def append(self, item):
"""Append a segment/node to the superpath and update the internal state.
item may be specified in any of the following formats:
- PathCommand
- [str, List[float]] - A path command letter and its arguments
- [[float, float], [float, float], [float, float]] - Incoming handle, node,
outgoing handle.
- List[[float, float], [float, float], [float, float]] - An entire subpath.
"""
if isinstance(item, list) and len(item) == 2 and isinstance(item[0], str):
item = PathCommand.letter_to_class(item[0])(*item[1])
if isinstance(item, PathCommand):
self.append_path_command(item)
return
if isinstance(item, list):
# Item is a subpath: List[Handle, node, Handle]. Just append the
# subpath, and update the prev/ prev_prev positions.
if (
(len(item) != 3 or not all(len(bit) == 2 for bit in item))
and len(item[0]) == 3
and all(len(bit) == 2 for bit in item[0])
):
super().append(self._clean(item))
elif len(item) == 3 and all(len(bit) == 2 for bit in item):
# Item is already a csp segment [Handle, node, Handle].
if self._closed:
# Closed means that the previous segment is closed so we need a new
# one.
# We always append to the last open segment. CSP starts out closed.
self._closed = False
super().append([])
# Item is already a csp segment and has already been shifted.
self[-1].append([i.copy() for i in item])
else:
raise ValueError(f"Unknown super curve list format: {item}")
self._prev_prev = Vector2d.t2c(self[-1][-1][0])
self._prev = Vector2d.t2c(self[-1][-1][1])
else:
raise ValueError(f"Unknown super curve list format: {item}")
def _clean(self, lst):
"""Recursively clean lists so they have the same type"""
if isinstance(lst, (tuple, list)):
return [self._clean(child) for child in lst]
return lst
@property
def _first(self):
try:
return self[-1][0][0][0] + self[-1][0][0][1] * 1j
except IndexError:
return 0 + 0j
def to_path(self, curves_only=False, rtol=1e-5, atol=1e-8):
"""Convert the super path back to an svg path
Arguments: see :func:`to_segments` for parameters"""
return Path(list(self.to_segments(curves_only, rtol, atol)))
def to_segments(self, curves_only=False, rtol=1e-5, atol=1e-8):
"""Generate a set of segments for this cubic super path
Arguments:
curves_only (bool, optional): If False, curves that can be represented
by Lineto / ZoneClose commands, will be. Defaults to False.
rtol (float, optional): relative tolerance, passed to :func:`is_line` and
:func:`inkex.transforms.ImmutableVector2d.is_close` for checking if a
line can be replaced by a ZoneClose command. Defaults to 1e-5.
.. versionadded:: 1.2
atol: absolute tolerance, passed to :func:`is_line` and
:func:`inkex.transforms.ImmutableVector2d.is_close`. Defaults to 1e-8.
.. versionadded:: 1.2"""
for subpath in self:
previous = []
for segment in subpath:
if not previous:
yield Move(Vector2d(segment[1]))
elif self.is_line(previous, segment, rtol, atol) and not curves_only:
if segment is subpath[-1] and Vector2d(segment[1]).is_close(
Vector2d(subpath[0][1]), rtol, atol
):
yield ZoneClose()
else:
yield Line(Vector2d(segment[1]))
else:
yield Curve(
Vector2d(previous[2]),
Vector2d(segment[0]),
Vector2d(segment[1]),
)
previous = segment
def transform(self, transform):
"""Apply a transformation matrix to this super path"""
return self.to_path().transform(transform).to_superpath()
@staticmethod
def is_on(pt_a, pt_b, pt_c, tol=1e-8):
"""Checks if point pt_a is on the line between points pt_b and pt_c
.. versionadded:: 1.2"""
return CubicSuperPath.collinear(pt_a, pt_b, pt_c, tol) and (
CubicSuperPath.within(pt_a[0], pt_b[0], pt_c[0])
if abs(pt_a[0] - pt_b[0]) > 1e-13
else CubicSuperPath.within(pt_a[1], pt_b[1], pt_c[1])
)
@staticmethod
def collinear(pt_a, pt_b, pt_c, tol=1e-8):
"""Checks if points pt_a, pt_b, pt_c lie on the same line,
i.e. that the cross product (b-a) x (c-a) < tol
.. versionadded:: 1.2"""
return (
abs(
(pt_b[0] - pt_a[0]) * (pt_c[1] - pt_a[1])
- (pt_c[0] - pt_a[0]) * (pt_b[1] - pt_a[1])
)
< tol
)
@staticmethod
def within(val_b, val_a, val_c):
"""Checks if float val_b is between val_a and val_c
.. versionadded:: 1.2"""
return val_a <= val_b <= val_c or val_c <= val_b <= val_a
@staticmethod
def is_line(previous, segment, rtol=1e-5, atol=1e-8):
"""Check whether csp segment (two points) can be expressed as a line has
retracted handles or the handles can be retracted without loss of information
(i.e. both handles lie on the line)
.. versionchanged:: 1.2
Previously, it was only checked if both control points have retracted
handles. Now it is also checked if the handles can be retracted without
(visible) loss of information (i.e. both handles lie on the line connecting
the nodes).
Arguments:
previous: first node in superpath notation
segment: second node in superpath notation
rtol (float, optional): relative tolerance, passed to
:func:`inkex.transforms.ImmutableVector2d.is_close` for checking handle
retraction. Defaults to 1e-5.
.. versionadded:: 1.2
atol (float, optional): absolute tolerance, passed to
:func:`inkex.transforms.ImmutableVector2d.is_close` for checking handle
retraction and
:func:`inkex.paths.CubicSuperPath.is_on` for checking if all points
(nodes + handles) lie on a line. Defaults to 1e-8.
.. versionadded:: 1.2
"""
retracted = isclose(
Vector2d(previous[1]), Vector2d(previous[2]), rel_tol=rtol, abs_tol=atol
) and isclose(
Vector2d(segment[0]), Vector2d(segment[1]), rel_tol=rtol, abs_tol=atol
)
if retracted:
return True
# Can both handles be retracted without loss of information?
# Definitely the case if the handles lie on the same line as the two nodes and
# in the correct order
# E.g. cspbezsplitatlength outputs non-retracted handles when splitting a
# straight line
return CubicSuperPath.is_on(
segment[0], segment[1], previous[2], atol
) and CubicSuperPath.is_on(previous[2], previous[1], segment[0], atol)

View File

@@ -0,0 +1,456 @@
# coding=utf-8
#
# Copyright (C) 2018 Martin Owens <doctormo@gmail.com>
# Copyright (C) 2023 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.
#
"""Quadratic and TepidQuadratic path commands"""
from __future__ import annotations
from typing import overload, Tuple, Callable, Union
from math import sqrt
import numpy as np
from ..transforms import quadratic_extrema, Transform, ComplexLike
from .interfaces import (
AbsolutePathCommand,
RelativePathCommand,
BezierComputationMixin,
BezierArcComputationMixin,
LengthSettings,
)
class QuadraticMixin(BezierComputationMixin, BezierArcComputationMixin):
# pylint: disable=unused-argument
ccontrol_points: Callable[[complex, complex, complex], Tuple[complex, ...]]
def _cderivative(
self, first: complex, prev: complex, prev_control: complex, t: float, n: int = 1
) -> complex:
points = self.ccontrol_points(first, prev, prev_control)
if n == 1:
return 2 * ((points[0] - prev) * (1 - t) + (points[1] - points[0]) * t)
if n == 2:
return 2 * (prev - 2 * points[0] + points[1])
if n > 2:
return 0j
raise ValueError("n should be a positive integer.")
def _cunit_tangent(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> complex:
return self.bezier_unit_tangent(prev, prev_control, t)
def _cpoint(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> complex:
control, end = self.ccontrol_points(first, prev, prev_control)
return (1 - t) ** 2 * prev + 2 * t * (1 - t) * control + t**2 * end
# TODO maybe better treatment of degenerate beziers from
# https://github.com/linebender/kurbo/blob/c229a914d303c5989c9e6b1d766def2df27a8185/src/quadbez.rs#L239
# Ported from https://github.com/mathandy/svgpathtools/blob/19df25b99b405ec4fc7616b58384eca7879b6fd4/svgpathtools/path.py#L919
# (MIT licensed)
def _length(
self,
first: complex,
prev: complex,
prev_control: complex,
t0: float = 0,
t1: float = 1,
settings=LengthSettings(),
) -> float:
control, end = self.ccontrol_points(first, prev, prev_control)
a = prev - 2 * control + end
b = 2 * (control - prev)
if abs(a) < 1e-12:
s = abs(b) * (t1 - t0)
else:
c2 = 4 * (a.real**2 + a.imag**2)
c1 = 4 * (a.real * b.real + a.imag * b.imag)
c0 = b.real**2 + b.imag**2
beta = c1 / (2 * c2)
gamma = c0 / c2 - beta**2
dq1_mag = sqrt(c2 * t1**2 + c1 * t1 + c0)
dq0_mag = sqrt(c2 * t0**2 + c1 * t0 + c0)
# this implicitly handles division by zero
try:
logarand = (sqrt(c2) * (t1 + beta) + dq1_mag) / (
sqrt(c2) * (t0 + beta) + dq0_mag
)
s = (
(t1 + beta) * dq1_mag
- (t0 + beta) * dq0_mag
+ gamma * sqrt(c2) * np.log(logarand)
) / 2
except ZeroDivisionError:
s = np.nan
if np.isnan(s):
tstar = abs(b) / (2 * abs(a))
if t1 < tstar:
return abs(a) * (t0**2 - t1**2) - abs(b) * (t0 - t1)
elif tstar < t0:
return abs(a) * (t1**2 - t0**2) - abs(b) * (t1 - t0)
else:
return (
abs(a) * (t1**2 + t0**2)
- abs(b) * (t1 + t0)
+ abs(b) ** 2 / (2 * abs(a))
)
return s
def _abssplit(
self, prev: complex, prev_control: complex, t: float
) -> Tuple[Quadratic, Quadratic]:
"""Split this Quadratic and return two Quadratics using DeCasteljau's algorithm"""
p1, p2 = self.ccontrol_points(0j, prev, prev_control)
p1_1 = (1 - t) * prev + t * p1
p1_2 = (1 - t) * p1 + t * p2
p2_1 = (1 - t) * p1_1 + t * p1_2
return Quadratic(p1_1, p2_1), Quadratic(p1_2, p2)
def _relsplit(self, prev: complex, prev_control: complex, t: float):
"""Split this curve and return two curves"""
c1abs, c2abs = self._abssplit(prev, prev_control, t)
return c1abs.to_relative(prev), c2abs.to_relative(c1abs.arg2)
class Quadratic(QuadraticMixin, AbsolutePathCommand):
"""Absolute Quadratic Curved Line segment"""
letter = "Q"
nargs = 4
arg1: complex
"""The (absolute) control point"""
arg2: complex
"""The (absolute) end point"""
@property
def x2(self) -> float:
"""x coordinate of the (absolute) control point"""
return self.arg1.real
@property
def y2(self) -> float:
"""y coordinate of the (absolute) control point"""
return self.arg1.imag
@property
def x3(self) -> float:
"""x coordinate of the (absolute) end point"""
return self.arg2.real
@property
def y3(self) -> float:
"""y coordinate of the (absolute) end point"""
return self.arg2.imag
@property
def args(self):
return self.x2, self.y2, self.x3, self.y3
@overload
def __init__(self, x2: ComplexLike, x3: ComplexLike): ...
@overload
def __init__(self, x2: float, y2: float, x3: float, y3: float): ...
def __init__(self, x2, y2, x3=None, y3=None):
if x3 is not None:
self.arg1 = x2 + y2 * 1j
self.arg2 = x3 + y3 * 1j
else:
self.arg1, self.arg2 = complex(x2), complex(y2)
def update_bounding_box(self, first, last_two_points, bbox):
x1, x2, x3 = last_two_points[-1].real, self.x2, self.x3
y1, y2, y3 = last_two_points[-1].imag, self.y2, self.y3
if not (x1 in bbox.x and x2 in bbox.x and x3 in bbox.x):
bbox.x += quadratic_extrema(x1, x2, x3)
if not (y1 in bbox.y and y2 in bbox.y and y3 in bbox.y):
bbox.y += quadratic_extrema(y1, y2, y3)
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
return (self.arg1, self.arg2)
def to_relative(self, prev: ComplexLike) -> quadratic:
return quadratic(self.arg1 - prev, self.arg2 - prev)
def transform(self, transform: Transform) -> Quadratic:
return Quadratic(
transform.capply_to_point(self.arg1), transform.capply_to_point(self.arg2)
)
def cend_point(self, first: complex, prev: complex) -> complex:
return self.arg2
def ccurve_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
pt1 = 1.0 / 3 * prev + 2.0 / 3 * self.arg1
pt2 = 2.0 / 3 * self.arg1 + 1.0 / 3 * self.arg2
return pt1, pt2, self.arg2
def reverse(self, first: ComplexLike, prev: ComplexLike) -> Quadratic:
prev = complex(prev)
return Quadratic(self.x2, self.y2, prev.real, prev.imag)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[Quadratic, Quadratic]:
return self._abssplit(prev, prev_control, t)
class quadratic(QuadraticMixin, RelativePathCommand): # pylint: disable=invalid-name
"""Relative quadratic line segment"""
letter = "q"
nargs = 4
arg1: complex
"""The (relative) control point"""
arg2: complex
"""The (relative) end point"""
@property
def dx2(self) -> float:
"""x coordinate of the (relative) control point"""
return self.arg1.real
@property
def dy2(self) -> float:
"""y coordinate of the (relative) control point"""
return self.arg1.imag
@property
def dx3(self) -> float:
"""x coordinate of the (relative) end point"""
return self.arg2.real
@property
def dy3(self) -> float:
"""y coordinate of the (relative) end point"""
return self.arg2.imag
@property
def args(self):
return self.dx2, self.dy2, self.dx3, self.dy3
@overload
def __init__(self, dx2: ComplexLike, dx3: ComplexLike): ...
@overload
def __init__(self, dx2: float, dy2: float, dx3: float, dy3: float): ...
def __init__(self, dx2, dy2, dx3=None, dy3=None):
if dx3 is not None:
self.arg1 = dx2 + dy2 * 1j
self.arg2 = dx3 + dy3 * 1j
else:
self.arg1, self.arg2 = complex(dx2), complex(dy2)
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
return (self.arg1 + prev, self.arg2 + prev)
def to_absolute(self, prev: ComplexLike) -> Quadratic:
return Quadratic(self.arg1 + prev, self.arg2 + prev)
def ccurve_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
pt1 = 1.0 / 3 * prev + 2.0 / 3 * (prev + self.arg1)
pt2 = 2.0 / 3 * (prev + self.arg1) + 1.0 / 3 * (prev + self.arg2)
return pt1, pt2, prev + self.arg2
def cend_point(self, first: complex, prev: complex) -> complex:
return self.arg2 + prev
def reverse(self, first: ComplexLike, prev: ComplexLike) -> quadratic:
return quadratic(-self.arg2 + self.arg1, -self.arg2)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[quadratic, quadratic]:
return self._relsplit(prev, prev_control, t)
class TepidQuadratic(QuadraticMixin, AbsolutePathCommand):
"""Continued Quadratic Line segment"""
letter = "T"
nargs = 2
arg1: complex
"""The (absolute) control point"""
@property
def x3(self) -> float:
"""x coordinate of the (absolute) end point"""
return self.arg1.real
@property
def y3(self) -> float:
"""y coordinate of the (absolute) end point"""
return self.arg1.imag
@property
def args(self):
return self.x3, self.y3
@overload
def __init__(self, x3: ComplexLike): ...
@overload
def __init__(self, x3: float, y3: float): ...
def __init__(self, x3, y3=None):
if y3 is not None:
self.arg1 = x3 + y3 * 1j
else:
self.arg1 = complex(x3)
def update_bounding_box(self, first, last_two_points, bbox):
self.to_quadratic(last_two_points[-1], last_two_points[-2]).update_bounding_box(
first, last_two_points, bbox
)
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
return (2 * prev - prev_prev, self.arg1)
def to_non_shorthand(
self, prev: ComplexLike, prev_control: ComplexLike
) -> Quadratic:
return self.to_quadratic(prev, prev_control)
def to_relative(self, prev: ComplexLike) -> tepidQuadratic:
return tepidQuadratic(self.arg1 - prev)
def transform(self, transform: Transform) -> TepidQuadratic:
return TepidQuadratic(transform.capply_to_point(self.arg1))
def ccurve_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
qp1 = 2 * prev - prev_prev
qp2 = self.arg1
pt1 = 1.0 / 3 * prev + 2.0 / 3 * qp1
pt2 = 2.0 / 3 * qp1 + 1.0 / 3 * qp2
return pt1, pt2, qp2
def cend_point(self, first: complex, prev: complex) -> complex:
return self.arg1
def to_quadratic(self, prev: ComplexLike, prev_prev: ComplexLike) -> Quadratic:
"""Convert this continued quadratic into a full quadratic"""
return Quadratic(
*self.ccontrol_points(complex(prev), complex(prev), complex(prev_prev))
)
def reverse(self, first: ComplexLike, prev: ComplexLike) -> TepidQuadratic:
return TepidQuadratic(prev)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[Quadratic, Quadratic]:
return self._abssplit(prev, prev_control, t)
class tepidQuadratic(QuadraticMixin, RelativePathCommand): # pylint: disable=invalid-name
"""Relative continued quadratic line segment"""
letter = "t"
nargs = 2
arg1: complex
"""The (relative) control point"""
@property
def dx3(self) -> float:
"""x coordinate of the (relative) end point"""
return self.arg1.real
@property
def dy3(self) -> float:
"""y coordinate of the (relative) end point"""
return self.arg1.imag
@property
def args(self):
return self.dx3, self.dy3
@overload
def __init__(self, dx3: ComplexLike): ...
@overload
def __init__(self, dx3: float, dy3: float): ...
def __init__(self, dx3, dy3=None):
if dy3 is not None:
self.arg1 = dx3 + dy3 * 1j
else:
self.arg1 = complex(dx3)
def ccontrol_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
return (2 * prev - prev_prev, self.arg1 + prev)
def ccurve_points(
self, first: complex, prev: complex, prev_prev: complex
) -> Tuple[complex, ...]:
qp1 = 2 * prev - prev_prev
qp2 = self.arg1 + prev
pt1 = 1.0 / 3 * prev + 2.0 / 3 * qp1
pt2 = 2.0 / 3 * qp1 + 1.0 / 3 * qp2
return pt1, pt2, qp2
def to_absolute(self, prev: ComplexLike) -> TepidQuadratic:
return TepidQuadratic(self.arg1 + prev)
def to_non_shorthand(
self, prev: ComplexLike, prev_control: ComplexLike
) -> Quadratic:
return self.to_absolute(prev).to_non_shorthand(prev, prev_control)
def cend_point(self, first: complex, prev: complex) -> complex:
return self.arg1 + prev
def reverse(self, first: ComplexLike, prev: ComplexLike) -> tepidQuadratic:
return tepidQuadratic(-self.arg1)
def _split(
self, first: complex, prev: complex, prev_control: complex, t: float
) -> Tuple[quadratic, quadratic]:
return self._relsplit(prev, prev_control, t)

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,956 @@
# 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 __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import (
Dict,
List,
Optional,
TYPE_CHECKING,
cast,
)
import tinycss2
import tinycss2.ast
from .units import convert_unit
from .utils import FragmentError
from .colors import Color
if TYPE_CHECKING:
from .elements import BaseElement
from .elements import _base
TokenList = List[tinycss2.ast.Node]
def _make_number_token_dimless(token):
if isinstance(token, (tinycss2.ast.NumberToken, tinycss2.ast.PercentageToken)):
return token.value
if isinstance(token, tinycss2.ast.DimensionToken):
return convert_unit(token.serialize(), "px")
raise ValueError("Not a number")
def _get_tokens_from_value(value: str) -> TokenList:
return tinycss2.parse_one_declaration(f"a:{value}").value
def _is_ws(token: tinycss2.ast.Node) -> bool:
return isinstance(token, tinycss2.ast.WhitespaceToken)
def _strip_whitespace_nodes(value: TokenList) -> TokenList:
try:
while _is_ws(value[0]):
del value[0]
while _is_ws(value[-1]):
del value[-1]
return value
except IndexError:
return []
def _is_inherit(value: TokenList | None) -> bool:
return (
value is not None
and len(value) == 1
and isinstance(value[0], tinycss2.ast.IdentToken)
and value[0].value == "inherit"
)
class _StyleConverter:
"""Converter between str and computed value of a style, with context element"""
# pylint: disable=unused-argument
def convert(
self, value: TokenList, element: Optional[BaseElement] = None
) -> object:
"""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
"""
return tinycss2.serialize(value)
def raise_invalid_value(
self, value: TokenList, element: Optional[BaseElement] = None
) -> None:
"""Checks if the value str is valid in the context of element.
Args:
value (str): attribute value
element (Optional[BaseElement], optional): Context element. Defaults to
None.
Raises:
various exceptions if the property has a bad value
"""
self.convert(value, element)
def convert_back(
self, value: object, element: Optional[BaseElement] = None
) -> TokenList:
"""Converts value back to string in the context of element.
Args:
value (object): parsed value of attribute
element (_type_, optional): Context element. Defaults to None.
Returns:
str: _description_
"""
return _get_tokens_from_value(str(value))
class _AlphaValueConverter(_StyleConverter):
"""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 convert(
self, value: TokenList, element: Optional[BaseElement] = None
) -> object:
if isinstance(value[0], tinycss2.ast.NumberToken):
parsed_value = value[0].value
elif isinstance(value[0], tinycss2.ast.PercentageToken):
parsed_value = value[0].value / 100
else:
raise ValueError()
return min(max(parsed_value, 0), 1)
def convert_back(
self, value: object, element: Optional[BaseElement] = None
) -> TokenList:
if isinstance(value, (float, int)):
value = min(max(value, 0), 1)
return [tinycss2.ast.NumberToken(0, 0, value, value, f"{value}")]
raise ValueError("Value must be number")
class _ColorValueConverter(_StyleConverter):
"""Converts a color value
Reference: https://drafts.csswg.org/css-color-3/#valuea-def-color"""
def convert(
self, value: TokenList, element: Optional[BaseElement] = None
) -> object:
# Process this as string
vstr = _StyleConverter.convert(self, value, element)
if vstr == "currentColor":
if element is not None:
return element.get_computed_style("color")
return None
return Color(vstr)
class _URLNoneValueConverter(_StyleConverter):
"""Converts 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 convert(
self, value: TokenList, element: Optional[BaseElement] = None
) -> object:
if len(value) == 0:
return None
value = value[0]
if isinstance(value, tinycss2.ast.URLToken):
if element is not None and self.element_has_root(element):
return element.root.getElementById(value.value)
return value.serialize()
if isinstance(value, tinycss2.ast.IdentToken):
return None
raise ValueError("Invalid property value")
def convert_back(
self, value: object, element: Optional[BaseElement] = None
) -> TokenList:
if isinstance(value, _base.BaseElement):
if element is not None:
value = _URLNoneValueConverter._insert_if_necessary(element, value)
return [tinycss2.ast.URLToken(0, 0, value.get_id(), value.get_id(as_url=2))]
return [tinycss2.ast.IdentToken(0, 0, "none")]
@staticmethod
def element_has_root(element) -> bool:
"Checks if an element has a root"
try:
_ = element.root
return True
except FragmentError:
return False
@staticmethod
def _insert_if_necessary(element: BaseElement, value: BaseElement) -> BaseElement:
"""Ensures that the return (value or a deep copy of it) is inside the same
document as element.
if element is unrooted, don't do anything (just return value)
If element is attached to the same document as value, return value.
If value is not attached to a document, attach it to the defs of element's
document and return value.
If value is already attached to another document, create a copy and return the
copy.
.. versionadded:: 1.4"""
# Check if the element is rooted and has the same root as self.element.
try:
_ = element.root
try:
if value.root != element.root:
# Create a copy and attach it to the tree.
copy = value.copy()
element.root.defs.append(copy)
return copy
except FragmentError:
element.root.defs.append(value)
return value
except FragmentError:
pass
return value
class _PaintValueConverter(_ColorValueConverter, _URLNoneValueConverter):
"""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 convert(
self, value: TokenList, element: Optional[BaseElement] = None
) -> object:
v0 = value[0]
if isinstance(v0, tinycss2.ast.IdentToken):
if v0.value == "none":
return None
if v0.value == "currentColor":
return _ColorValueConverter.convert(self, value, element)
if v0.value in ["context-fill", "context-stroke"]:
return v0.value
else:
return Color(v0.value)
if isinstance(v0, tinycss2.ast.HashToken):
return Color("#" + v0.value)
if isinstance(v0, tinycss2.ast.URLToken):
if element is not None and self.element_has_root(element):
paint_server = element.root.getElementById(v0.value[1:])
else:
return None
if paint_server is not None:
return paint_server
for i in value[1:]:
if isinstance(i, tinycss2.ast.IdentToken):
return Color(i.value)
raise ValueError("Paint server not found")
if isinstance(v0, tinycss2.ast.FunctionBlock) and v0.name in [
"rgb",
"rgba",
"hsl",
"hsla",
]:
arguments = [str(argument.value) for argument in v0.arguments]
return Color(f"{v0.name}({''.join(arguments)})")
raise ValueError("Unknown color specification")
def convert_back(
self, value: object, element: Optional[BaseElement] = None
) -> TokenList:
if value is None:
return [tinycss2.ast.IdentToken(0, 0, "none")]
if isinstance(value, _base.BaseElement):
return _URLNoneValueConverter.convert_back(self, value, element=element)
return _ColorValueConverter.convert_back(self, value, element=element)
class _EnumValueConverter(_StyleConverter):
"""Stores a value that can only have a finite set of options"""
def __init__(self, options):
self.options = options
def raise_invalid_value(
self, value: TokenList, element: BaseElement | None = None
) -> None:
if tinycss2.serialize(value) not in self.options:
raise ValueError(
f"Value '{tinycss2.serialize(value)}' is invalid for the property"
)
class _ShorthandValueConverter(_StyleConverter):
"""Stores a value that sets other values (e.g. the font shorthand)"""
def __init__(self, keys) -> None:
super().__init__()
self.keys = keys
@abstractmethod
def get_shorthand_changes(self, value) -> 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 _FontValueShorthandConverter(_ShorthandValueConverter):
"""Logic for the shorthand font property"""
def __init__(self) -> None:
super().__init__(
[
"font-style",
"font-variant",
"font-weight",
"font-stretch",
"font-size",
"line-height",
"font-family",
]
)
self.options = {
key: all_properties[key].converter.options # type: ignore
for key in self.keys
if isinstance(all_properties[key].converter, _EnumValueConverter)
}
# Font stretch can be specified in percent, but for the
# shorthand, only a keyword value is allowed
self.options["font-stretch"] = (
"normal",
"ultra-condensed",
"extra-condensed",
"condensed",
"semi-condensed",
"semi-expanded",
"expanded",
"extra-expanded",
"ultra-expanded",
)
def get_shorthand_changes(self, value):
result = {key: all_properties[key].default_value for key in self.keys}
if len(value) == 0:
return result # shorthand not set, nothing to do
i = 0
while i < len(value):
cur = value[i]
matched = False
if isinstance(cur, tinycss2.ast.IdentToken):
matched = True
if cur.value in self.options["font-style"]:
result["font-style"] = [cur]
elif cur.value in self.options["font-variant"]:
result["font-variant"] = [cur]
elif cur.value in self.options["font-weight"]:
result["font-weight"] = [cur]
elif cur.value in self.options["font-stretch"]:
result["font-stretch"] = [cur]
else:
matched = False
if not matched and not isinstance(cur, tinycss2.ast.WhitespaceToken):
result["font-size"] = [cur]
if (
len(value) > i + 1
and isinstance(value[i + 1], tinycss2.ast.LiteralToken)
and value[i + 1].value == "/"
):
result["line-height"] = [value[i + 2]]
i += 2
if len(value[i + 1 :]) > 0:
result["font-family"] = _strip_whitespace_nodes(value[i + 1 :])
break
i += 1
return result
class _TextDecorationValueConverter(_ShorthandValueConverter):
"""Logic for the shorthand font property
.. versionadded:: 1.3"""
def __init__(self):
super().__init__(
["text-decoration-style", "text-decoration-color", "text-decoration-line"]
)
self.options = {
"text-decoration-" + key: all_properties[
"text-decoration-" + key
].converter.options
for key in ("line", "style", "color")
if isinstance(
all_properties["text-decoration-" + key].converter, _EnumValueConverter
)
}
def get_shorthand_changes(self, value):
result = {
"text-decoration-style": all_properties[
"text-decoration-style"
].default_value,
"text-decoration-color": _get_tokens_from_value("currentcolor"),
"text-decoration-line": [],
}
for token, cur in list((i, i.serialize()) for i in value):
if cur in ["underline", "overline", "line-through", "blink"]:
result["text-decoration-line"].extend(
[token, tinycss2.ast.WhitespaceToken(0, 0, value=" ")]
)
elif cur in self.options["text-decoration-style"]:
result["text-decoration-style"] = [token]
elif cur.strip():
result["text-decoration-color"] = [token]
if len(result["text-decoration-line"]) == 0:
result["text-decoration-line"] = all_properties[
"text-decoration-line"
].default_value
else:
result["text-decoration-line"] = result["text-decoration-line"][:-1]
return result
class _MarkerShorthandValueConverter(_ShorthandValueConverter, _URLNoneValueConverter):
"""Logic for the marker shorthand property"""
def __init__(self) -> None:
super().__init__(["marker-start", "marker-end", "marker-mid"])
def get_shorthand_changes(self, value):
if value == "":
return {} # shorthand not set, nothing to do
return {k: value for k in self.keys}
def convert_back(
self, value: object, element: Optional[BaseElement] = None
) -> TokenList:
"""Convert value back to a tokenlist"""
return _URLNoneValueConverter.convert_back(self, value, element)
class _FontSizeValueConverter(_StyleConverter):
"""Logic for the font-size property"""
def convert(
self, value: TokenList, element: Optional[BaseElement] = None
) -> object:
v0 = value[0].serialize()
if element is None:
return v0 # no additional logic in this case
if isinstance(
value[0],
(
tinycss2.ast.NumberToken,
tinycss2.ast.PercentageToken,
tinycss2.ast.DimensionToken,
),
):
return element.to_dimensionless(v0)
# unable to parse font size, e.g. font-size:normal
return v0
class _StrokeDasharrayValueConverter(_StyleConverter):
"""Logic for the stroke-dasharray property"""
def convert(
self, value: TokenList, element: Optional[BaseElement] = None
) -> object:
dashes = []
i = 0
for i, el in enumerate(value):
if (
i == 0
and isinstance(el, tinycss2.ast.IdentToken)
and el.value == "none"
):
return []
# whitespace or comma separated list
if isinstance(el, (tinycss2.ast.WhitespaceToken)) or (
isinstance(el, tinycss2.ast.LiteralToken) and el.value == ","
):
continue
if isinstance(el, (tinycss2.ast.DimensionToken, tinycss2.ast.NumberToken)):
dashes.append(_make_number_token_dimless(el))
else:
return []
if any(i < 0 for i in dashes):
# one negative value makes the dasharray invalid
return []
if len(dashes) % 2 == 1:
dashes = 2 * dashes
return dashes
def convert_back(
self, value: object, element: Optional[BaseElement] = None
) -> TokenList:
if value is None or not value:
value = "none"
if isinstance(value, list):
if len(value) == 0:
value = "none"
else:
value = " ".join(map(str, value))
return _get_tokens_from_value(str(value))
class _FilterListConverter(_URLNoneValueConverter):
"""Stores a list of Filters
.. versionadded:: 1.4"""
def convert(
self, value: TokenList, element: Optional[BaseElement] = None
) -> object:
if element is None or value == "none":
return []
try:
result = [
element.root.getElementById(item.value)
for item in value
if isinstance(item, tinycss2.ast.URLToken)
]
return [i for i in result if i is not None]
except FragmentError:
return [
item.serialize()
for item in value
if isinstance(item, tinycss2.ast.URLToken)
]
except ValueError: # broken link
return []
def convert_back(
self, value: object, element: Optional[BaseElement] = None
) -> TokenList:
if isinstance(value, _base.BaseElement) or not isinstance(value, (list, tuple)):
value = [value]
if all((isinstance(i, str) for i in value)):
return _get_tokens_from_value(" ".join(value)) # type: ignore
assert element is not None
value = cast("List[BaseElement]", value)
try:
_ = element.root
for i in value:
if i is None:
continue
# insert the element
inserted = self._insert_if_necessary(element, cast("BaseElement", i))
# if a copy was created, replace the original in the list with the copy
if inserted is not i:
for index, item in enumerate(value):
if item is i:
value[index] = inserted
except FragmentError:
# Element is unrooted, we skip this step.
pass
return _get_tokens_from_value(
" ".join(f"url(#{i.get_id()})" for i in value if i is not None)
)
@dataclass
class PropertyDescription:
"""Describes a CSS / presentation attribute"""
name: str
converter: _StyleConverter
default_value: TokenList
presentation: bool
inherited: bool
def __init__(
self,
name: str,
converter: _StyleConverter,
default_value: str,
presentation: bool = False,
inherited: bool = False,
):
self.presentation = presentation
self.inherited = inherited
self.default_value = _get_tokens_from_value(default_value)
self.name = name
self.converter = converter
# Source for this list: https://www.w3.org/TR/SVG2/styling.html#PresentationAttributes
properties_list: List[PropertyDescription] = [
PropertyDescription(
"alignment-baseline",
_EnumValueConverter(
[
"baseline",
"text-bottom",
"alphabetic",
"ideographic",
"middle",
"central",
"mathematical",
"text-top",
]
),
"baseline",
True,
False,
),
PropertyDescription("baseline-shift", _StyleConverter(), "0", True, False),
PropertyDescription("clip", _StyleConverter(), "auto", True, False),
PropertyDescription("clip-path", _URLNoneValueConverter(), "none", True, False),
PropertyDescription(
"clip-rule", _EnumValueConverter(["nonzero", "evenodd"]), "nonzero", True, True
),
PropertyDescription("color", _PaintValueConverter(), "black", True, True),
PropertyDescription(
"color-interpolation",
_EnumValueConverter(["sRGB", "auto", "linearRGB"]),
"sRGB",
True,
True,
),
PropertyDescription(
"color-interpolation-filters",
_EnumValueConverter(["auto", "sRGB", "linearRGB"]),
"linearRGB",
True,
True,
),
PropertyDescription(
"color-rendering",
_EnumValueConverter(
["auto", "optimizeSpeed", "optimizeQuality", "pixelated", "crisp-edges"]
),
"auto",
True,
True,
),
PropertyDescription("cursor", _StyleConverter(), "auto", True, True),
PropertyDescription(
"direction", _EnumValueConverter(["ltr", "rtl"]), "ltr", True, True
),
PropertyDescription(
"display",
_EnumValueConverter(
[
"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",
]
),
"inline",
True,
False,
),
PropertyDescription(
"dominant-baseline",
_EnumValueConverter(
[
"auto",
"text-bottom",
"alphabetic",
"ideographic",
"middle",
"central",
"mathematical",
"hanging",
"text-top",
]
),
"auto",
True,
True,
),
PropertyDescription("fill", _PaintValueConverter(), "black", True, True),
PropertyDescription("fill-opacity", _AlphaValueConverter(), "1", True, True),
PropertyDescription(
"fill-rule", _EnumValueConverter(["nonzero", "evenodd"]), "nonzero", True, True
),
PropertyDescription("filter", _FilterListConverter(), "none", True, False),
PropertyDescription("flood-color", _PaintValueConverter(), "black", True, False),
PropertyDescription("flood-opacity", _AlphaValueConverter(), "1", True, False),
PropertyDescription("font-family", _StyleConverter(), "sans-serif", True, True),
PropertyDescription("font-size", _FontSizeValueConverter(), "medium", True, True),
PropertyDescription("font-size-adjust", _StyleConverter(), "none", True, True),
PropertyDescription("font-stretch", _StyleConverter(), "normal", True, True),
PropertyDescription(
"font-style",
_EnumValueConverter(["normal", "italic", "oblique"]),
"normal",
True,
True,
),
PropertyDescription(
"font-variant",
_EnumValueConverter(["normal", "small-caps"]),
"normal",
True,
True,
),
PropertyDescription(
"font-weight",
_EnumValueConverter(
["normal", "bold"] + [str(i) for i in range(100, 901, 100)]
),
"normal",
True,
True,
),
PropertyDescription(
"glyph-orientation-horizontal", _StyleConverter(), "0deg", True, True
),
PropertyDescription(
"glyph-orientation-vertical", _StyleConverter(), "auto", True, True
),
PropertyDescription("inline-size", _StyleConverter(), "0", False, False),
PropertyDescription(
"image-rendering",
_EnumValueConverter(["auto", "optimizeQuality", "optimizeSpeed"]),
"auto",
True,
True,
),
PropertyDescription("letter-spacing", _StyleConverter(), "normal", True, True),
PropertyDescription(
"lighting-color", _ColorValueConverter(), "normal", True, False
),
PropertyDescription("line-height", _StyleConverter(), "normal", False, True),
PropertyDescription("marker", _MarkerShorthandValueConverter(), ""),
PropertyDescription("marker-end", _URLNoneValueConverter(), "none", True, True),
PropertyDescription("marker-mid", _URLNoneValueConverter(), "none", True, True),
PropertyDescription("marker-start", _URLNoneValueConverter(), "none", True, True),
PropertyDescription("mask", _URLNoneValueConverter(), "none", True, False),
PropertyDescription("opacity", _AlphaValueConverter(), "1", True, False),
PropertyDescription(
"overflow",
_EnumValueConverter(["visible", "hidden", "scroll", "auto"]),
"visible",
True,
False,
),
PropertyDescription("paint-order", _StyleConverter(), "normal", True, False),
PropertyDescription(
"pointer-events",
_EnumValueConverter(
[
"bounding-box",
"visiblePainted",
"visibleFill",
"visibleStroke",
"visible",
"painted",
"fill",
"stroke",
"all",
"none",
]
),
"visiblePainted",
True,
True,
),
PropertyDescription("shape-inside", _URLNoneValueConverter(), "none", False, False),
PropertyDescription(
"shape-rendering",
_EnumValueConverter(
["auto", "optimizeSpeed", "crispEdges", "geometricPrecision"]
),
"visiblePainted",
True,
True,
),
PropertyDescription("stop-color", _ColorValueConverter(), "black", True, False),
PropertyDescription("stop-opacity", _AlphaValueConverter(), "1", True, False),
PropertyDescription("stroke", _PaintValueConverter(), "none", True, True),
PropertyDescription(
"stroke-dasharray", _StrokeDasharrayValueConverter(), "none", True, True
),
PropertyDescription("stroke-dashoffset", _StyleConverter(), "0", True, True),
PropertyDescription(
"stroke-linecap",
_EnumValueConverter(["butt", "round", "square"]),
"butt",
True,
True,
),
PropertyDescription(
"stroke-linejoin",
_EnumValueConverter(["miter", "miter-clip", "round", "bevel", "arcs"]),
"miter",
True,
True,
),
PropertyDescription("stroke-miterlimit", _StyleConverter(), "4", True, True),
PropertyDescription("stroke-opacity", _AlphaValueConverter(), "1", True, True),
PropertyDescription("stroke-width", _StyleConverter(), "1", True, True),
PropertyDescription("text-align", _StyleConverter(), "start", True, True),
PropertyDescription(
"text-anchor",
_EnumValueConverter(["start", "middle", "end"]),
"start",
True,
True,
),
PropertyDescription(
"text-decoration-line", _StyleConverter(), "none", False, False
),
PropertyDescription(
"text-decoration-style",
_EnumValueConverter(["solid", "double", "dotted", "dashed", "wavy"]),
"solid",
False,
False,
),
PropertyDescription(
"text-decoration-color", _StyleConverter(), "currentcolor", False, False
),
PropertyDescription(
"text-overflow", _EnumValueConverter(["clip", "ellipsis"]), "clip", True, False
),
PropertyDescription(
"text-rendering",
_EnumValueConverter(
["auto", "optimizeSpeed", "optimizeLegibility", "geometricPrecision"]
),
"auto",
True,
True,
),
PropertyDescription(
"unicode-bidi",
_EnumValueConverter(
[
"normal",
"embed",
"isolate",
"bidi-override",
"isolate-override",
"plaintext",
]
),
"normal",
True,
False,
),
PropertyDescription("vector-effect", _StyleConverter(), "none", True, False),
PropertyDescription("vertical-align", _StyleConverter(), "baseline", False, False),
PropertyDescription(
"visibility",
_EnumValueConverter(["visible", "hidden", "collapse"]),
"visible",
True,
True,
),
PropertyDescription(
"white-space",
_EnumValueConverter(
["normal", "pre", "nowrap", "pre-wrap", "break-spaces", "pre-line"]
),
"normal",
True,
True,
),
PropertyDescription("word-spacing", _StyleConverter(), "normal", True, True),
PropertyDescription(
"writing-mode",
_EnumValueConverter(
[
"horizontal-tb",
"vertical-rl",
"vertical-lr",
"lr",
"lr-tb",
"rl",
"rl-tb",
"tb",
"tb-rl",
]
),
"horizontal-tb",
True,
True,
),
PropertyDescription(
"-inkscape-font-specification", _StyleConverter(), "sans-serif", False, True
),
]
all_properties = {v.name: v for v in properties_list}
properties_list += [
PropertyDescription("font", _FontValueShorthandConverter(), ""),
PropertyDescription("text-decoration", _TextDecorationValueConverter(), ""),
]
all_properties["font"] = properties_list[-2]
all_properties["text-decoration"] = properties_list[-1]
shorthand_from_value = {
item: prop.name
for prop in properties_list
if isinstance(prop.converter, _ShorthandValueConverter)
for item in prop.converter.keys
}
shorthand_properties = {
i.name: i
for i in properties_list
if isinstance(i.converter, _ShorthandValueConverter)
}

View File

View File

@@ -0,0 +1,756 @@
# 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
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Optional, Generator, TYPE_CHECKING, Tuple
from lxml import etree
import tinycss2
import tinycss2.ast
from .colors import Color
from .properties import (
_get_tokens_from_value,
_is_inherit,
all_properties,
shorthand_from_value,
shorthand_properties,
TokenList,
_strip_whitespace_nodes,
)
from .css import CSSCompiler, parser
from .utils import FragmentError, NotifyList, NotifyOrderedDict
from .elements._utils import NSS
from .elements import _base
if TYPE_CHECKING:
from .elements._base import BaseElement
class Classes(NotifyList):
"""A list of classes applied to an element (used in css and js)"""
def __init__(self, classes=None, callback=None, element=None):
if isinstance(classes, str):
classes = classes.split()
super().__init__(classes or (), callback=callback)
def __str__(self):
return " ".join(self)
@dataclass
class StyleValue:
"""Encapsulates a single parsed style value + its importance state"""
value: TokenList
important: bool = False
def __str__(self):
return tinycss2.serialize(self.value) + ("!important" if self.important else "")
def __eq__(self, other):
return (
tinycss2.serialize(self.value) == tinycss2.serialize(other.value)
and self.important == other.important
)
def is_inherit(self):
"""Checks if the value is "inherit" """
return _is_inherit(self.value)
class Style(NotifyOrderedDict):
"""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.callback = None
self.element = element
# if style is passed as kwargs, replace underscores by dashes
style = style or [(k.replace("_", "-"), v) for k, v in kw.items()]
self.update(style)
# Should accept dict, Style, parsed string, list etc.
super().__init__(callback=callback)
def _add(self, key: str, value: StyleValue):
# Works with both regular dictionaries and Styles
if key in shorthand_properties:
chg = shorthand_properties[key].converter.get_shorthand_changes(value.value) # type: ignore
for k, v in chg.items():
self._add(k, StyleValue(v, value.important))
else:
if key not in self or (
not self.get_store(key).important or value.important
):
# Only overwrite if importance of existing value is higher
super().__setitem__(key, value)
def _get_val(self, key: str, value):
if key in all_properties and not isinstance(value, str):
return StyleValue(
all_properties[key].converter.convert_back(value, self.element)
)
return StyleValue(_get_tokens_from_value(value))
def _attr_callback(self, key):
def inner(value):
self[key] = value
return inner
def _parse_str(self, style: str) -> Generator[Tuple[str, StyleValue], None, None]:
"""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, in a tokenized
form. Whitespace tokens from the start and end of the value are stripped.
Args:
style: the content of a CSS rule to parse. Can also be a List of
ComponentValues
Yields:
Tuple[str, class:`~inkex.style.StyleValue`]: the parsed attribute
"""
result = tinycss2.parse_declaration_list(
style, skip_comments=True, skip_whitespace=True
)
for declaration in result:
if isinstance(declaration, tinycss2.ast.Declaration):
yield (
declaration.name,
StyleValue(
_strip_whitespace_nodes(declaration.value),
declaration.important,
),
)
@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([f"{key}:{value}" for key, value in self.items()])
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, and simplifying
shorthands"""
if isinstance(other, Style):
for k, v in super(NotifyOrderedDict, other).items():
self._add(k, v)
# Order raw dictionaries so tests can be made reliable
elif isinstance(other, dict):
for k, v in sorted(other.items()):
self._add(k, self._get_val(k, v))
elif isinstance(other, list) and all(isinstance(i, tuple) for i in other):
for k, v in other:
self._add(k, self._get_val(k, v))
elif isinstance(other, str) or (isinstance(other, list)):
for k, v in self._parse_str(other):
self._add(k, v)
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()
if not (isinstance(parent, Style)):
return ret
for item in parent.keys():
apply = False
if item in all_properties and all_properties[item].inherited:
# only set parent value if value is not set or parent importance is
# higher
if item not in ret or (
not self.get_importance(item) and parent.get_importance(item)
):
apply = True
if item in ret and ret.get_store(item).is_inherit():
apply = True
if apply:
super(NotifyOrderedDict, ret).__setitem__(item, parent.get_store(item))
return ret
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:`StyleValue`
- a TokenList (tokenized CSS value),
- a string with the value
- any other object. The converter associated with the provided key will
attempt to create a string out of the passed value.
Raises:
ValueError: when passing something else than string, StyleValue or TokenList
and key is not a known style attribute
Error: Other exceptions may be raised when converting non-string objects."""
if isinstance(value, StyleValue):
super().__setitem__(key, value)
return
if isinstance(value, str):
value = value.strip()
tokenized = _get_tokens_from_value(value)
if key in all_properties:
all_properties[key].converter.raise_invalid_value(
tokenized, self.element
)
value = tokenized
elif (
isinstance(value, list)
and len(value) > 0
and all(isinstance(i, tinycss2.ast.Node) for i in value)
):
pass
elif key in all_properties:
value = all_properties[key].converter.convert_back(value, self.element)
else:
raise TypeError()
# Convert value to StyleValue
super().__setitem__(key, StyleValue(value, False))
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 tinycss2.serialize(super().__getitem__(key).value)
def get(self, key, default=None):
try:
return self[key]
except KeyError:
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: str, element: Optional[BaseElement] = 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"""
tmp = super().get(key, None)
v: None | TokenList = None if tmp is None else tmp.value
if (v is None and (key in all_properties or default is not None)) or (
v is not None and _is_inherit(v)
): # if the value is still inherit here, return the default
v = (
_get_tokens_from_value(default)
if default is not None
else (
all_properties[key].default_value if key in all_properties else None
)
)
if v is None:
return v
if v is not None:
if key in shorthand_properties:
return tinycss2.serialize(v)
if key in all_properties:
result = all_properties[key].converter.convert(
v, element or self.element
)
else:
result = tinycss2.serialize(v)
if isinstance(result, list) and not isinstance(result, Color):
result = NotifyList(result, callback=self._attr_callback(key))
return result
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 items as string
.. versionadded:: 1.2"""
for key, value in super().items():
yield key, tinycss2.serialize(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 self.get_store(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()
self._callback()
def get_color(self, name="fill"):
"""Get the color AND opacity as one Color object"""
color = Color(self.get(name, "none"))
color.alpha = float(self.get(name + "-opacity", 1.0))
return color
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.alpha is not None and name in Style.associated_props:
self[Style.associated_props[name]] = color.alpha
color.alpha = None
self[name] = color
def update_urls(self, old_id, new_id):
"""Find urls in this style and replace them with the new id"""
for _, elem in super().items():
for token in elem.value:
if (
isinstance(token, tinycss2.ast.URLToken)
and token.value == f"#{old_id}"
):
token.value = f"#{new_id}"
token.representation = f"url(#{new_id})"
self._callback()
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: BaseElement):
"""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))
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, _base.BaseElement):
cascaded = Style.add_inherited(cascaded, parent.specified_style())
cascaded.element = element
return cascaded # doesn't have a parent
@classmethod
def _get_cascade(cls, attribute: str, element: BaseElement) -> Optional[TokenList]:
if attribute in shorthand_from_value:
def relevant(style):
return attribute in style or shorthand_from_value[attribute] in style
else:
def relevant(style):
return attribute in style
try:
values = []
for sheet in element.root.stylesheets:
for style in sheet:
if relevant(style):
value = style.get_store(attribute)
values += [
(value, spec) for spec in style.get_specificities(element)
]
except FragmentError:
values = []
# presentation attributes have specificity 0,
# see https://www.w3.org/TR/SVG/styling.html#PresentationAttributes
# they also cannot be shorthands and are always important=False
if attribute in element.attrib:
values.append(
(
StyleValue(
_get_tokens_from_value(element.attrib[attribute]),
False,
),
(0, 0, 0),
)
)
if relevant(element.style):
values.append((element.style.get_store(attribute), (float("inf"), 0, 0)))
if len(values) == 0:
return None
# Sort according to importance, then specificity
values.sort(key=lambda item: (item[0].important, item[1]))
return values[-1][0].value
@classmethod
def _get_style(cls, attribute: str, element: BaseElement):
"""Specified style for :param:`attribute`"""
# The resolution order is:
# - cascade -> then resolve the value, except if the value is "inherit"
# - parent's computed value
# - initial (default) value -> then resolve
result = None
current = element
inherited = (
all_properties[attribute].inherited
if attribute in all_properties
else False
)
while True:
result = cls._get_cascade(attribute, current)
if result is not None and not _is_inherit(result):
break
current = current.getparent()
if current is None or (not inherited and not _is_inherit(result)):
break
# Compute value based on current
if result is None or _is_inherit(result): # Fallback to default value
if attribute in all_properties:
result = all_properties[attribute].default_value
else:
return None
return (
all_properties[attribute].converter.convert(result, current)
if attribute in all_properties
else tinycss2.serialize(result)
)
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 lookup(self, element):
"""
Find all styles for this element.
"""
for sheet in self:
for style in sheet.lookup(element):
yield style
def lookup_specificity(self, element):
"""
Find all styles for this element and return the specificity of the match.
.. versionadded:: 1.2
"""
for sheet in self:
for style in sheet.lookup_specificity(element):
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.
"""
def __init__(self, content=None, callback=None):
super().__init__()
self.callback = None
# Remove comments
if content is None:
parsed = []
else:
parsed = tinycss2.parse_stylesheet(
content, skip_comments=True, skip_whitespace=True
)
# Parse rules
for block in parsed:
if isinstance(block, tinycss2.ast.QualifiedRule):
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: str | tinycss2.ast.QualifiedRule):
"""Make sure callback is called when updating"""
if isinstance(other, str):
other = tinycss2.parse_one_rule(other)
if isinstance(other, tinycss2.ast.QualifiedRule):
other = ConditionalStyle(
other.prelude, other.content, callback=self._callback
)
super().append(other)
self._callback()
def lookup(self, element):
"""Lookup the element against all the styles in this sheet"""
for style in self:
if any(style.checks(element)):
yield style
def lookup_specificity(self, element):
"""Lookup the element_id against all the styles in this sheet
and return the specificity of the match
Args:
element: the element of the element that styles are being queried for
Yields:
Tuple[ConditionalStyle, Tuple[int, int, int]]: all matched styles and the
specificity of the match
"""
for style in self:
for specificity in style.get_specificities(element):
yield (style, specificity)
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: str | TokenList = "*", style=None, callback=None, **kwargs
):
super().__init__(style=style, callback=callback, **kwargs)
self._rules: str | TokenList = rules
self.rules = list(parser.parse(rules, namespaces=NSS))
self.checks = [
CSSCompiler.compile_node(selector.parsed_tree) for selector in self.rules
]
def matches(self, element: etree.Element):
"""Checks if an individual element matches this selector.
.. versionadded:: 1.4"""
if isinstance(element, etree._Comment):
return False
if any(check(element) for check in self.checks):
return True
return False
def all_matches(self, document: etree.Element):
"""Get all matches of this selector in document as iterator.
.. versionadded:: 1.4"""
for el in document.iter():
if self.matches(el):
yield el
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 get_specificities(self, element: Optional[BaseElement] = None):
"""Gets an iterator of the specificity of all rules in this ConditionalStyle
.. versionadded:: 1.2"""
if element is not None:
for rule, check in zip(self.rules, self.checks):
if check(element):
yield rule.specificity
else:
for rule in self.rules:
yield rule.specificity

View File

@@ -0,0 +1,547 @@
# 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 inkex.extensions import OutputExtension
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
def export_svg(self, document, *args) -> str:
"""Runs a svg through an export extension, with optional arguments
provided as "--arg=value" arguments"""
assert isinstance(self, OutputExtension)
output = StringIO()
writer = self.effect_class()
writer.parse_arguments([*args])
writer.svg = document.getroot()
writer.document = document
writer.effect()
writer.save(output)
output.seek(0)
return output.read()
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 ComparisonMeta(type):
"""Metaclass for ComparisonMixin which creates parametrized tests that can be run
independently. See :class:`~inkex.tester.ComparisonMixin` for details.
..versionadded :: 1.4"""
def __init__(cls, name, bases, attrs):
super().__init__(name, bases, attrs)
if name == "ComparisonMixin":
return # don't execute on the base class
_compare_file = cls.compare_file
_comparisons = cls.comparisons
if hasattr(cls, "comparisons_cmpfile_dict"):
_comparisons = cls.comparisons_cmpfile_dict.keys()
def get_compare_cmpfile(self, args, addout=None):
return self.data_file("refs", cls.comparisons_cmpfile_dict[args])
setattr(cls, "get_compare_cmpfile", get_compare_cmpfile)
test_method_name = f"test_all_comparisons"
if hasattr(cls, test_method_name):
return # Custom test logic, don't touch
append = isinstance(_compare_file, (list, tuple))
compare_file = _compare_file if append else [_compare_file]
try:
for file in compare_file:
for comparison in _comparisons:
test_method_name = f"test_comparison_{comparison}_{file}"
setattr(
cls,
test_method_name,
ComparisonMeta.create_test_method(
comparison,
file,
os.path.basename(file) if append else None,
),
)
except TypeError:
# If the compare_file or compare_
test_method_name = f"test_all_comparisons"
def test_method(self):
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)
)
setattr(cls, test_method_name, test_method)
@staticmethod
def create_test_method(comparison, file, addout):
def _test_method(self):
self._test_comparison(comparison, file, addout)
return _test_method
class ComparisonMixin(metaclass=ComparisonMeta):
"""
This mixin allows to easily specify a set of run-through unit tests for an
extension, which is specified in :attr:`inkex.tester.TestCase.effect_class`.
The commandline parameters are passed in :attr:`comparisons`, the input file
in :attr:`compare_file` (either a list of files, or a single file).
The :class:`ComparisonMeta` metaclass creates a set of independent unit tests
out of this data. Behavior notest:
- The unit tests created are the cross product of :attr:`comparisons` and
:attr:`compare_file`. If :attr:`compare_file` is a list, the comparison file name
is suffixed with the current ``compare_file`` name.
- Optionally, :attr:`comparisons_cmpfile_dict` may be specified as
``Dict[Tuple[str], str]`` where the keys are sets of command line parameters and
the values are the filenames of the output file. This takes precedence over
:attr:`comparisons`.
- If any of those values are properties, their values cannot be accessed at test
collection time and there will only be a single test, ``test_all_comparisons``
with otherwise identical behavior.
- If the class overrides ``test_all_comparisons``, no additional tests are
generated to allow for custom comparison logic.
To create the comparison files for the unit tests, use the ``EXPORT_COMPARE``
environment variable.
"""
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_comparisons(self, compare_file, addout=None):
for args in self.comparisons:
self._test_comparison(args, compare_file=compare_file, addout=addout)
def _test_comparison(self, args, compare_file, addout=None):
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")
self.write_compare_data(infile, write_output, data_a)
# 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 write_compare_data(self, infile, outfile, data):
"""Write output"""
with open(outfile, "wb") as fhl:
fhl.write(self._apply_compare_filters(data, True))
print(f"Written output: {outfile}")
def _base_compare(self, data_a, data_b, compare_mode):
data_a = self._apply_compare_filters(data_a)
if (
isinstance(data_a, bytes)
and isinstance(data_b, bytes)
and data_a.startswith(b"<")
and data_b.startswith(b"<")
):
# Late importing
diff_xml, delta = xmldiff(data_a, data_b)
if not delta and compare_mode == COMPARE_DELETE:
print(
"The XML is different, you can save the output using the "
"EXPORT_COMPARE envionment variable. Set it to 1 to save a file "
"you can check, set it to 3 to overwrite this comparison, setting "
"the new data as the correct one.\n"
)
diff = "SVG Differences\n\n"
if os.environ.get("XML_DIFF", False):
diff = "<- " + diff_xml
else:
for x, (value_a, value_b) in enumerate(delta):
try:
# Take advantage of better text diff in testcase's own asserts.
self.assertEqual(value_a, value_b)
except AssertionError as err:
diff += f" {x}. {str(err)}\n"
self.assertTrue(delta, diff)
else:
# compare any content (non svg)
self.assertEqual(data_a, data_b)
def _apply_compare_filters(self, data, is_saving=None):
data = to_bytes(data)
# Applying filters flips depending if we are saving the filtered content
# to disk, or filtering during the test run. This is because some filters
# are destructive others are useful for diagnostics.
if is_saving is self.compare_filter_save or is_saving is None:
for cfilter in self.compare_filters:
data = cfilter(data)
return data
def get_compare_cmpfile(self, args, addout=None):
"""Generate an output file for the arguments given"""
if addout is not None:
args = list(args) + [str(addout)]
opstr = (
"__".join(args)
.replace(self.tempdir, "TMP_DIR")
.replace(self.datadir(), "DAT_DIR")
)
opstr = re.sub(r"[^\w-]", "__", opstr)
if opstr:
if len(opstr) > 127:
# avoid filename-too-long error
opstr = hashlib.md5(opstr.encode("latin1")).hexdigest()
opstr = "__" + opstr
return self.data_file(
"refs", f"{self.effect_name}{opstr}.out", check_exists=False
)

View File

@@ -0,0 +1,10 @@
"""
Useful decorators for tests.
"""
import pytest
from inkex.command import is_inkscape_available
requires_inkscape = pytest.mark.skipif( # pylint: disable=invalid-name
not is_inkscape_available(), reason="Test requires inkscape, but it's not available"
)

View File

@@ -0,0 +1,181 @@
#
# Copyright (C) 2019 Thomas Holder
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# pylint: disable=too-few-public-methods
#
"""
Comparison filters for use with the ComparisonMixin.
Each filter should be initialised in the list of
filters that are being used.
.. code-block:: python
compare_filters = [
CompareNumericFuzzy(),
CompareOrderIndependentLines(option=yes),
]
"""
import re
from ..utils import to_bytes
class Compare:
"""
Comparison base class, this acts as a passthrough unless
the filter staticmethod is overwritten.
"""
def __init__(self, **options):
self.options = options
def __call__(self, content):
return self.filter(content)
@staticmethod
def filter(contents):
"""Replace this filter method with your own filtering"""
return contents
class CompareNumericFuzzy(Compare):
"""
Turn all numbers into shorter standard formats
1.2345678 -> 1.2346
1.2300 -> 1.23, 50.0000 -> 50.0
50.0 -> 50
"""
@staticmethod
def filter(contents):
func = lambda m: b"%.3f" % (float(m.group(0)) + 0)
contents = re.sub(rb"\d+\.\d+(e[+-]\d+)?", func, contents)
contents = re.sub(rb"(\d\.\d+?)0+\b", rb"\1", contents)
contents = re.sub(rb"(\d)\.0+(?=\D|\b)", rb"\1", contents)
contents = re.sub(rb"-0(?=\D|\b)", rb"0", contents) # Replace -0 with 0
return contents
class CompareWithoutIds(Compare):
"""Remove all ids from the svg"""
@staticmethod
def filter(contents):
return re.sub(rb' id="([^"]*)"', b"", contents)
class CompareWithPathSpace(Compare):
"""Make sure that path segment commands have spaces around them"""
@staticmethod
def filter(contents):
def func(match):
"""We've found a path command, process it"""
new = re.sub(rb"\s*([LZMHVCSQTAatqscvhmzl])\s*", rb" \1 ", match.group(1))
return b' d="' + new.replace(b",", b" ") + b'"'
return re.sub(rb' d="([^"]*)"', func, contents)
class CompareSize(Compare):
"""Compare the length of the contents instead of the contents"""
@staticmethod
def filter(contents):
return len(contents)
class CompareOrderIndependentBytes(Compare):
"""Take all the bytes and sort them"""
@staticmethod
def filter(contents):
return b"".join([bytes(i) for i in sorted(contents)])
class CompareOrderIndependentLines(Compare):
"""Take all the lines and sort them"""
@staticmethod
def filter(contents):
return b"\n".join(sorted(contents.splitlines()))
class CompareOrderIndependentStyle(Compare):
"""Take all styles and sort the results"""
@staticmethod
def filter(contents):
contents = CompareNumericFuzzy.filter(contents)
def func(match):
"""Search and replace function for sorting"""
sty = b";".join(sorted(match.group(1).split(b";")))
return b'style="%s"' % (sty,)
return re.sub(rb'style="([^"]*)"', func, contents)
class CompareOrderIndependentStyleAndPath(Compare):
"""Take all styles and paths and sort them both"""
@staticmethod
def filter(contents):
contents = CompareOrderIndependentStyle.filter(contents)
def func(match):
"""Search and replace function for sorting"""
path = b"X".join(sorted(re.split(rb"[A-Z]", match.group(1))))
return b'd="%s"' % (path,)
return re.sub(rb'\bd="([^"]*)"', func, contents)
class CompareOrderIndependentTags(Compare):
"""Sorts all the XML tags"""
@staticmethod
def filter(contents):
return b"\n".join(sorted(re.split(rb">\s*<", contents)))
class CompareReplacement(Compare):
"""Replace pieces to make output more comparable
.. versionadded:: 1.1"""
def __init__(self, *replacements):
self.deltas = replacements
super().__init__()
def filter(self, contents):
contents = to_bytes(contents)
for _from, _to in self.deltas:
contents = contents.replace(to_bytes(_from), to_bytes(_to))
return contents
class WindowsTextCompat(CompareReplacement):
"""Normalize newlines so tests comparing plain text work
.. versionadded:: 1.2"""
def __init__(self):
super().__init__(("\r\n", "\n"))

View File

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

View File

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

View File

@@ -0,0 +1,182 @@
#!/usr/bin/env python3
# coding=utf-8
"""
Test elements extra logic from svg xml lxml custom classes.
"""
import os
import sys
from importlib import resources
from lxml import etree, isoschematron
from ..utils import PY3
from ..inx import InxFile
INTERNAL_ARGS = ("help", "output", "id", "selected-nodes")
ARG_TYPES = {
"Boolean": "bool",
"Color": "color",
"str": "string",
"int": "int",
"float": "float",
}
class InxMixin:
"""Tools for Testing INX files, use as a mixin class:
class MyTests(InxMixin, TestCase):
def test_inx_file(self):
self.assertInxIsGood("some_inx_file.inx")
"""
def assertInxIsGood(self, inx_file): # pylint: disable=invalid-name
"""Test the inx file for consistancy and correctness"""
self.assertTrue(PY3, "INX files can only be tested in python3")
inx = InxFile(inx_file)
if "help" in inx.ident or inx.script.get("interpreter", None) != "python":
return
cls = inx.extension_class
# Check class can be matched in python file
self.assertTrue(cls, f"Can not find class for {inx.filename}")
# Check name is reasonable for the class
if not cls.multi_inx:
self.assertEqual(
cls.__name__,
inx.slug,
f"Name of extension class {cls.__module__}.{cls.__name__} "
f"is different from ident {inx.slug}",
)
self.assertParams(inx, cls)
def assertParams(self, inx, cls): # pylint: disable=invalid-name
"""Confirm the params in the inx match the python script
.. versionchanged:: 1.2
Also checks that the default values are identical"""
params = {param.name: self.parse_param(param) for param in inx.params}
args = dict(self.introspect_arg_parser(cls().arg_parser))
mismatch_a = list(set(params) ^ set(args) & set(params))
mismatch_b = list(set(args) ^ set(params) & set(args))
self.assertFalse(
mismatch_a, f"{inx.filename}: Inx params missing from arg parser"
)
self.assertFalse(
mismatch_b, f"{inx.filename}: Script args missing from inx xml"
)
for param in args:
if params[param]["type"] and args[param]["type"]:
self.assertEqual(
params[param]["type"],
args[param]["type"],
f"Type is not the same for {inx.filename}:param:{param}",
)
inxdefault = params[param]["default"]
argsdefault = args[param]["default"]
if inxdefault and argsdefault:
# for booleans, the inx is lowercase and the param is uppercase
if params[param]["type"] == "bool":
argsdefault = str(argsdefault).lower()
elif params[param]["type"] not in ["string", None, "color"] or args[
param
]["type"] in ["int", "float"]:
# try to parse the inx value to compare numbers to numbers
inxdefault = float(inxdefault)
if args[param]["type"] == "color" or callable(args[param]["default"]):
# skip color, method types
continue
self.assertEqual(
argsdefault,
inxdefault,
f"Default value is not the same for {inx.filename}:param:{param}",
)
inxchoices = params[param]["choices"]
argschoices = args[param]["choices"]
if argschoices is not None and len(argschoices) > 0:
assert set(inxchoices).issubset(argschoices), (
f"params don't match: inx={inxchoices}, py={argschoices}"
)
def introspect_arg_parser(self, arg_parser):
"""Pull apart the arg parser to find out what we have in it"""
for action in arg_parser._optionals._actions: # pylint: disable=protected-access
for opt in action.option_strings:
# Ignore params internal to inkscape (thus not in the inx)
if opt.startswith("--") and opt[2:] not in INTERNAL_ARGS:
yield (opt[2:], self.introspect_action(action))
@staticmethod
def introspect_action(action):
"""Pull apart a single action to get at the juicy insides"""
return {
"type": ARG_TYPES.get((action.type or str).__name__, "string"),
"default": action.default,
"choices": action.choices,
"help": action.help,
}
@staticmethod
def parse_param(param):
"""Pull apart the param element in the inx file"""
if param.param_type in ("optiongroup", "notebook"):
options = param.options
return {
"type": None,
"choices": options,
"default": options and options[0] or None,
}
param_type = param.param_type
if param.param_type in ("path",):
param_type = "string"
return {
"type": param_type,
"default": param.text,
"choices": None,
}
def assertInxSchemaValid(self, inx_file): # pylint: disable=invalid-name
"""Validate inx file schema."""
self.assertTrue(INX_SCHEMAS, "no schema files found")
with open(inx_file, "rb") as fp:
inx_doc = etree.parse(fp)
for schema_name, schema in INX_SCHEMAS.items():
with self.subTest(schema_file=schema_name):
schema.assert_(inx_doc)
def _load_inx_schemas():
_SCHEMA_CLASSES = {
".rng": etree.RelaxNG,
".schema": isoschematron.Schematron,
}
if sys.version_info > (3, 9):
def _contents(pkg):
return [path.name for path in resources.files(pkg).iterdir()]
else:
_contents = resources.contents
for name in _contents(__package__):
_, ext = os.path.splitext(name)
schema_class = _SCHEMA_CLASSES.get(ext)
if schema_class is None:
continue
if sys.version_info > (3, 9):
def _open_binary(pkg, res):
return resources.files(pkg).joinpath(res).open("rb")
else:
_open_binary = resources.open_binary
with _open_binary(__package__, name) as fp:
schema_doc = etree.parse(fp)
yield name, schema_class(schema_doc)
INX_SCHEMAS = dict(_load_inx_schemas())

View File

@@ -0,0 +1,459 @@
# coding=utf-8
#
# Copyright (C) 2018 Martin Owens
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA.
#
# pylint: disable=protected-access,too-few-public-methods
"""
Any mocking utilities required by testing. Mocking is when you need the test
to exercise a piece of code, but that code may or does call on something
outside of the target code that either takes too long to run, isn't available
during the test running process or simply shouldn't be running at all.
"""
import io
import os
import sys
import logging
import hashlib
import tempfile
from typing import List, Tuple, Any
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.parser import Parser as EmailParser
import inkex.command
FIXED_BOUNDARY = "--CALLDATA--//--CALLDATA--"
class Capture:
"""Capture stdout or stderr. Used as `with Capture('stdout') as stream:`"""
def __init__(self, io_name="stdout", swap=True):
self.io_name = io_name
self.original = getattr(sys, io_name)
self.stream = io.StringIO()
self.swap = swap
def __enter__(self):
if self.swap:
setattr(sys, self.io_name, self.stream)
return self.stream
def __exit__(self, exc, value, traceback):
if exc is not None and self.swap:
# Dump content back to original if there was an error.
self.original.write(self.stream.getvalue())
setattr(sys, self.io_name, self.original)
class ManualVerbosity:
"""Change the verbosity of the test suite manually"""
result = property(lambda self: self.test._current_result)
def __init__(self, test, okay=True, dots=False):
self.test = test
self.okay = okay
self.dots = dots
def flip(self, exc_type=None, exc_val=None, exc_tb=None): # pylint: disable=unused-argument
"""Swap the stored verbosity with the original"""
self.okay, self.result.showAll = self.result.showAll, self.okay
self.dots, self.result.dots = self.result.dots, self.okay
__enter__ = flip
__exit__ = flip
class MockMixin:
"""
Add mocking ability to any test base class, will set up mock on setUp
and remove it on tearDown.
Mocks are stored in an array attached to the test class (not instance!) which
ensures that mocks can only ever be setUp once and can never be reset over
themselves. (just in case this looks weird at first glance)
class SomeTest(MockingMixin, TestBase):
mocks = [(sys, 'exit', NoSystemExit("Nope!")]
"""
mocks = [] # type: List[Tuple[Any, str, Any]]
def setUpMock(self, owner, name, new): # pylint: disable=invalid-name
"""Setup the mock here, taking name and function and returning (name, old)"""
old = getattr(owner, name)
if isinstance(new, str):
if hasattr(self, new):
new = getattr(self, new)
if isinstance(new, Exception):
def _error_function(*args2, **kw2): # pylint: disable=unused-argument
raise type(new)(str(new))
setattr(owner, name, _error_function)
elif new is None or isinstance(new, (str, int, float, list, tuple)):
def _value_function(*args, **kw): # pylint: disable=unused-argument
return new
setattr(owner, name, _value_function)
else:
setattr(owner, name, new)
# When we start, mocks contains length 3 tuples, when we're finished, it
# contains length 4, this stops remocking and reunmocking from taking place.
return (owner, name, old, False)
def setUp(self): # pylint: disable=invalid-name
"""For each mock instruction, set it up and store the return"""
super().setUp()
for x, mock in enumerate(self.mocks):
if len(mock) == 4:
logging.error(
"Mock was already set up, so it wasn't cleared previously!"
)
continue
self.mocks[x] = self.setUpMock(*mock)
def tearDown(self): # pylint: disable=invalid-name
"""For each returned stored, tear it down and restore mock instruction"""
super().tearDown()
try:
for x, (owner, name, old, _) in enumerate(self.mocks):
self.mocks[x] = (owner, name, getattr(owner, name))
setattr(owner, name, old)
except ValueError:
logging.warning("Was never mocked, did something go wrong?")
def old_call(self, name):
"""Get the original caller"""
for arg in self.mocks:
if arg[1] == name:
return arg[2]
return lambda: None
class MockCommandMixin(MockMixin):
"""
Replace all the command functions with testable replacements.
This stops the pipeline and people without the programs, running into problems.
"""
mocks = [
(inkex.command, "_call", "mock_call"),
(tempfile, "mkdtemp", "record_tempdir"),
]
recorded_tempdirs = [] # type:List[str]
def setUp(self): # pylint: disable=invalid-name
super().setUp()
# This is a the daftest thing I've ever seen, when in the middle
# of a mock, the 'self' variable magically turns from a FooTest
# into a TestCase, this makes it impossible to find the datadir.
from . import TestCase
TestCase._mockdatadir = self.datadir()
@classmethod
def cmddir(cls):
"""Returns the location of all the mocked command results"""
from . import TestCase
return os.path.join(TestCase._mockdatadir, "cmd")
def record_tempdir(self, *args, **kwargs):
"""Record any attempts to make tempdirs"""
newdir = self.old_call("mkdtemp")(*args, **kwargs)
self.recorded_tempdirs.append(os.path.realpath(newdir))
return newdir
def clean_paths(self, data, files):
"""Clean a string of any files or tempdirs"""
def replace(indata, replaced, replacement):
if isinstance(indata, str):
indata = indata.replace(replaced, replacement)
else:
indata = [i.replace(replaced, replacement) for i in indata]
return indata
try:
for fdir in self.recorded_tempdirs:
data = replace(data, fdir + os.sep, "./")
data = replace(data, fdir, ".")
files = replace(files, fdir + os.sep, "./")
files = replace(files, fdir, ".")
for fname in files:
data = replace(data, fname, os.path.basename(fname))
except (UnicodeDecodeError, TypeError):
pass
return data
def get_all_tempfiles(self):
"""Returns a set() of all files currently in any of the tempdirs"""
ret = set([])
for fdir in self.recorded_tempdirs:
if not os.path.isdir(fdir):
continue
for fname in os.listdir(fdir):
if fname in (".", ".."):
continue
path = os.path.join(fdir, fname)
# We store the modified time so if a program modifies
# the input file in-place, it will look different.
ret.add(path + f";{os.path.getmtime(path)}")
return ret
def ignore_command_mock(self, program, arglst, path):
"""Return true if the mock is ignored"""
if self and program and arglst:
env = os.environ.get("NO_MOCK_COMMANDS", 0)
if (not os.path.exists(path) and int(env) == 1) or int(env) == 2:
return True
return False
def mock_call(self, program, *args, **kwargs):
"""
Replacement for the inkex.command.call() function, instead of calling
an external program, will compile all arguments into a hash and use the
hash to find a command result.
"""
# Remove stdin first because it needs to NOT be in the Arguments list.
stdin = kwargs.pop("stdin", None)
args = list(args)
# We use email
msg = MIMEMultipart(boundary=FIXED_BOUNDARY)
msg["Program"] = MockCommandMixin.get_program_name(program)
# Gather any output files and add any input files to msg, args and kwargs
# may be modified to strip out filename directories (which change)
inputs, outputs = self.add_call_files(msg, args, kwargs)
arglst = inkex.command.to_args_sorted(program, *args, **kwargs)[1:]
arglst = self.clean_paths(arglst, inputs + outputs)
argstr = " ".join(arglst)
msg["Arguments"] = argstr.strip()
if stdin is not None:
# The stdin is counted as the msg body
cleanin = (
self.clean_paths(stdin, inputs + outputs)
.replace("\r\n", "\n")
.replace(".\\", "./")
)
msg.attach(MIMEText(cleanin, "plain", "utf-8"))
keystr = msg.as_string()
# On Windows, output is separated by CRLF
keystr = keystr.replace("\r\n", "\n")
# There is a difference between python2 and python3 output
keystr = keystr.replace("\n\n", "\n")
keystr = keystr.replace("\n ", " ")
if "verb" in keystr:
# Verbs seperated by colons cause diff in py2/3
keystr = keystr.replace("; ", ";")
# Generate a unique key for this call based on _all_ it's inputs
key = hashlib.md5(keystr.encode("utf-8")).hexdigest()
if self.ignore_command_mock(
program, arglst, self.get_call_filename(program, key, create=True)
):
# Call original code. This is so programmers can run the test suite
# against the external programs too, to see how their fair.
if stdin is not None:
kwargs["stdin"] = stdin
before = self.get_all_tempfiles()
stdout = self.old_call("_call")(program, *args, **kwargs)
outputs += list(self.get_all_tempfiles() - before)
# Remove the modified time from the call
outputs = [out.rsplit(";", 1)[0] for out in outputs]
# After the program has run, we collect any file outputs and store
# them, then store any stdout or stderr created during the run.
# A developer can then use this to build new test cases.
reply = MIMEMultipart(boundary=FIXED_BOUNDARY)
reply["Program"] = MockCommandMixin.get_program_name(program)
reply["Arguments"] = argstr
self.save_call(program, key, stdout, outputs, reply)
self.save_key(program, key, keystr, "key")
return stdout
try:
return self.load_call(program, key, outputs)
except IOError as err:
self.save_key(program, key, keystr, "bad-key")
raise IOError(
f"Problem loading call: {program}/{key} use the environment variable "
"NO_MOCK_COMMANDS=1 to call out to the external program and generate "
f"the mock call file for call {program} {argstr}."
) from err
def add_call_files(self, msg, args, kwargs):
"""
Gather all files, adding input files to the msg (for hashing) and
output files to the returned files list (for outputting in debug)
"""
# Gather all possible string arguments together.
loargs = sorted(kwargs.items(), key=lambda i: i[0])
values = []
for arg in args:
if isinstance(arg, (tuple, list)):
loargs.append(arg)
else:
values.append(str(arg))
for _, value in loargs:
if isinstance(value, (tuple, list)):
for val in value:
if val is not True:
values.append(str(val))
elif value is not True:
values.append(str(value))
# See if any of the strings could be filenames, either going to be
# or are existing files on the disk.
files = [[], []]
for value in values:
if os.path.isfile(value): # Input file
files[0].append(value)
self.add_call_file(msg, value)
elif os.path.isdir(os.path.dirname(value)): # Output file
files[1].append(value)
return files
def add_call_file(self, msg, filename):
"""Add a single file to the given mime message"""
fname = os.path.basename(filename)
with open(filename, "rb") as fhl:
if filename.endswith(".svg"):
value = self.clean_paths(fhl.read().decode("utf8"), [])
else:
value = fhl.read()
try:
value = value.decode()
except UnicodeDecodeError:
pass # do not attempt to process binary files further
if isinstance(value, str):
value = value.replace("\r\n", "\n").replace(".\\", "./")
part = MIMEApplication(value, Name=fname)
# After the file is closed
part["Content-Disposition"] = "attachment"
part["Filename"] = fname
msg.attach(part)
def get_call_filename(self, program, key, create=False):
"""
Get the filename for the call testing information.
"""
path = self.get_call_path(program, create=create)
fname = os.path.join(path, key + ".msg")
if not create and not os.path.isfile(fname):
raise IOError(f"Attempted to find call test data {key}")
return fname
@staticmethod
def get_program_name(program):
"""Takes a program and returns a program name"""
if program == inkex.command.INKSCAPE_EXECUTABLE_NAME:
return "inkscape"
return program
def get_call_path(self, program, create=True):
"""Get where this program would store it's test data"""
command_dir = os.path.join(
self.cmddir(), MockCommandMixin.get_program_name(program)
)
if not os.path.isdir(command_dir):
if create:
os.makedirs(command_dir)
else:
raise IOError(
"A test is attempting to use an external program in a test:"
f" {program}; but there is not a command data directory which "
f"should contain the results of the command here: {command_dir}"
)
return command_dir
def load_call(self, program, key, files):
"""
Load the given call
"""
fname = self.get_call_filename(program, key, create=False)
with open(fname, "rb") as fhl:
msg = EmailParser().parsestr(fhl.read().decode("utf-8"))
stdout = None
for part in msg.walk():
if "attachment" in part.get("Content-Disposition", ""):
base_name = part["Filename"]
for out_file in files:
if out_file.endswith(base_name):
with open(out_file, "wb") as fhl:
fhl.write(part.get_payload(decode=True))
part = None
if part is not None:
# Was not caught by any normal outputs, so we will
# save the file to EVERY tempdir in the hopes of
# hitting on of them.
for fdir in self.recorded_tempdirs:
if os.path.isdir(fdir):
with open(os.path.join(fdir, base_name), "wb") as fhl:
fhl.write(part.get_payload(decode=True))
elif part.get_content_type() == "text/plain":
stdout = part.get_payload(decode=True)
return stdout
def save_call(self, program, key, stdout, files, msg, ext="output"): # pylint: disable=too-many-arguments
"""
Saves the results from the call into a debug output file, the resulting files
should be a Mime msg file format with each attachment being one of the input
files as well as any stdin and arguments used in the call.
"""
if stdout is not None and stdout.strip():
# The stdout is counted as the msg body here
msg.attach(MIMEText(stdout.decode("utf-8"), "plain", "utf-8"))
for fname in set(files):
if os.path.isfile(fname):
# print("SAVING FILE INTO MSG: {}".format(fname))
self.add_call_file(msg, fname)
else:
part = MIMEText("Missing File", "plain", "utf-8")
part.add_header("Filename", os.path.basename(fname))
msg.attach(part)
fname = self.get_call_filename(program, key, create=True) + "." + ext
with open(fname, "wb") as fhl:
fhl.write(msg.as_string().encode("utf-8"))
if int(os.environ.get("NO_MOCK_COMMANDS", 0)) == 1:
print(f"Saved mock call as {fname}, remove .{ext}")
def save_key(self, program, key, keystr, ext="key"):
"""Save the key file if we are debugging the key data"""
if os.environ.get("DEBUG_KEY"):
fname = self.get_call_filename(program, key, create=True) + "." + ext
with open(fname, "wb") as fhl:
fhl.write(keystr.encode("utf-8"))

View File

@@ -0,0 +1,55 @@
# coding=utf-8
#
# Copyright (C) 2018 Martin Owens
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA.
#
"""
SVG specific utilities for tests.
"""
from lxml import etree
from inkex import SVG_PARSER
def svg(svg_attrs=""):
"""Returns xml etree based on a simple SVG element.
svg_attrs: A string containing attributes to add to the
root <svg> element of a minimal SVG document.
"""
return etree.fromstring(
str.encode(
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>'
f"<svg {svg_attrs}></svg>"
),
parser=SVG_PARSER,
)
def svg_unit_scaled(width_unit):
"""Same as svg, but takes a width unit (top-level transform) for the new document.
The transform is the ratio between the SVG width and the viewBox width.
"""
return svg(f'width="1{width_unit}" viewBox="0 0 1 1"')
def svg_file(filename):
"""Parse an svg file and return it's document root"""
with open(filename, "r", encoding="utf-8") as fhl:
doc = etree.parse(fhl, parser=SVG_PARSER)
return doc.getroot()

View File

@@ -0,0 +1,42 @@
# coding=utf-8
#
# Unknown author
#
"""
Generate words for testing.
"""
import string
import random
def word_generator(text_length):
"""
Generate a word of text_length size
"""
word = ""
for _ in range(0, text_length):
word += random.choice(
string.ascii_lowercase
+ string.ascii_uppercase
+ string.digits
+ string.punctuation
)
return word
def sentencecase(word):
"""Make a word standace case"""
word_new = ""
lower_letters = list(string.ascii_lowercase)
first = True
for letter in word:
if letter in lower_letters and first is True:
word_new += letter.upper()
first = False
else:
word_new += letter
return word_new

View File

@@ -0,0 +1,125 @@
#
# Copyright 2011 (c) Ian Bicking <ianb@colorstudy.com>
# 2019 (c) Martin Owens <doctormo@gmail.com>
#
# Taken from http://formencode.org under the GPL compatible PSF License.
# Modified to produce more output as a diff.
#
"""
Allow two xml files/lxml etrees to be compared, returning their differences.
"""
import xml.etree.ElementTree as xml
from io import BytesIO
from inkex.paths import Path
def text_compare(test1, test2):
"""
Compare two text strings while allowing for '*' to match
anything on either lhs or rhs.
"""
if not test1 and not test2:
return True
if test1 == "*" or test2 == "*":
return True
return (test1 or "").strip() == (test2 or "").strip()
class DeltaLogger(list):
"""A record keeper of the delta between two svg files"""
def append_tag(self, tag_a, tag_b):
"""Record a tag difference"""
if tag_a:
tag_a = f"<{tag_a}.../>"
if tag_b:
tag_b = f"<{tag_b}.../>"
self.append((tag_a, tag_b))
def append_attr(self, attr, value_a, value_b):
"""Record an attribute difference"""
def _prep(val):
if val:
if attr == "d":
return [attr] + Path(val).to_arrays()
return (attr, val)
return val
# Only append a difference if the preprocessed values are different.
# This solves the issue that -0 != 0 in path data.
prep_a = _prep(value_a)
prep_b = _prep(value_b)
if prep_a != prep_b:
self.append((prep_a, prep_b))
def append_text(self, text_a, text_b):
"""Record a text difference"""
self.append((text_a, text_b))
def __bool__(self):
"""Returns True if there's no log, i.e. the delta is clean"""
return not self.__len__()
__nonzero__ = __bool__
def __repr__(self):
if self:
return "No differences detected"
return f"{len(self)} xml differences"
def to_xml(data):
"""Convert string or bytes to xml parsed root node"""
if isinstance(data, str):
data = data.encode("utf8")
if isinstance(data, bytes):
return xml.parse(BytesIO(data)).getroot()
return data
def xmldiff(data1, data2):
"""Create an xml difference, will modify the first xml structure with a diff"""
xml1, xml2 = to_xml(data1), to_xml(data2)
delta = DeltaLogger()
_xmldiff(xml1, xml2, delta)
return xml.tostring(xml1).decode("utf-8"), delta
def _xmldiff(xml1, xml2, delta):
if xml1.tag != xml2.tag:
xml1.tag = f"{xml1.tag}XXX{xml2.tag}"
delta.append_tag(xml1.tag, xml2.tag)
for name, value in xml1.attrib.items():
if name not in xml2.attrib:
delta.append_attr(name, xml1.attrib[name], None)
xml1.attrib[name] += "XXX"
elif xml2.attrib.get(name) != value:
delta.append_attr(name, xml1.attrib.get(name), xml2.attrib.get(name))
xml1.attrib[name] = f"{xml1.attrib.get(name)}XXX{xml2.attrib.get(name)}"
for name, value in xml2.attrib.items():
if name not in xml1.attrib:
delta.append_attr(name, None, value)
xml1.attrib[name] = "XXX" + value
if not text_compare(xml1.text, xml2.text):
delta.append_text(xml1.text, xml2.text)
xml1.text = f"{xml1.text}XXX{xml2.text}"
if not text_compare(xml1.tail, xml2.tail):
delta.append_text(xml1.tail, xml2.tail)
xml1.tail = f"{xml1.tail}XXX{xml2.tail}"
# Get children and pad with nulls
children_a = list(xml1)
children_b = list(xml2)
children_a += [None] * (len(children_b) - len(children_a))
children_b += [None] * (len(children_a) - len(children_b))
for child_a, child_b in zip(children_a, children_b):
if child_a is None: # child_b exists
delta.append_tag(child_b.tag, None)
elif child_b is None: # child_a exists
delta.append_tag(None, child_a.tag)
else:
_xmldiff(child_a, child_b, delta)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,258 @@
# coding=utf-8
#
# Copyright (C) 2005 Aaron Spike, aaron@ekips.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
"""A Python path turtle for Inkscape extensions"""
import math
import random
from typing import List, Union
from .paths import Line, Move, Path, PathCommand
from .elements import PathElement, Group, BaseElement
from .styles import Style
class PathTurtle:
"""A Python path turtle
.. versionchanged:: 1.2
pTurtle has been renamed to PathTurtle."""
def __init__(self, home=(0, 0)):
self.__home = [home[0], home[1]]
self.__pos = self.__home[:]
self.__heading = -90
self.__path = ""
self.__draw = True
self.__new = True
def forward(self, mag: float):
"""Move turtle forward by mag in the current direction."""
self.setpos(
(
self.__pos[0] + math.cos(math.radians(self.__heading)) * mag,
self.__pos[1] + math.sin(math.radians(self.__heading)) * mag,
)
)
def backward(self, mag):
"""Move turtle backward by mag in the current direction."""
self.setpos(
(
self.__pos[0] - math.cos(math.radians(self.__heading)) * mag,
self.__pos[1] - math.sin(math.radians(self.__heading)) * mag,
)
)
def right(self, deg):
"""Rotate turtle right by deg degrees.
Changed in inkex 1.2: The turtle now rotates right (previously left) when
calling this method."""
self.__heading += deg
def left(self, deg):
"""Rotate turtle left by deg degrees.
Changed in inkex 1.2: The turtle now rotates left (previously right) when
calling this method."""
self.__heading -= deg
def penup(self):
"""Enable non-drawing / moving mode"""
self.__draw = False
self.__new = False
def pendown(self):
"""Enable drawing mode"""
if not self.__draw:
self.__new = True
self.__draw = True
def pentoggle(self):
"""Switch between drawing and moving mode"""
if self.__draw:
self.penup()
else:
self.pendown()
def home(self):
"""Move to home position"""
self.setpos(self.__home)
def clean(self):
"""Delete current path"""
self.__path = ""
def clear(self):
"""Delete current path and move to home"""
self.clean()
self.home()
def setpos(self, arg):
"""Move/draw to position, depending on the current state"""
if self.__new:
self.__path += "M" + ",".join([str(i) for i in self.__pos])
self.__new = False
self.__pos = arg
if self.__draw:
self.__path += "L" + ",".join([str(i) for i in self.__pos])
def getpos(self):
"""Returns the current position"""
return self.__pos[:]
def setheading(self, deg):
"""Set the heading to deg degrees"""
self.__heading = deg
def getheading(self):
"""Returns the heading in degrees"""
return self.__heading
def sethome(self, arg):
"""Set home position"""
self.__home = list(arg)
def getPath(self):
"""Returns the current path"""
return self.__path
def rtree(self, size, minimum, pt=False):
"""Generates a random tree"""
if size < minimum:
return
self.fd(size)
turn = random.uniform(20, 40)
self.rt(turn)
self.rtree(size * random.uniform(0.5, 0.9), minimum, pt)
self.lt(turn)
turn = random.uniform(20, 40)
self.lt(turn)
self.rtree(size * random.uniform(0.5, 0.9), minimum, pt)
self.rt(turn)
if pt:
self.pu()
self.bk(size)
if pt:
self.pd()
# pylint: disable=invalid-name
fd = forward
bk = backward
rt = right
lt = left
pu = penup
pd = pendown
pTurtle = PathTurtle # should be deprecated
class PathBuilder:
"""This helper class can be used to construct a path and insert it into a
document.
.. versionadded:: 1.2"""
def __init__(self, style: Style):
"""Initializes a PathDrawHelper object
Args:
style (Style): Style of the path.
"""
self.current = Path()
self.style = style
def add(self, command: Union[PathCommand, List[PathCommand]]):
"""Add a Path command to the Helper
Args:
command (Union[PathCommand, List[PathCommand]]): A (list of) PathCommand(s)
to be appended.
"""
if isinstance(command, list):
self.current.extend(command)
else:
self.current.append(command)
def terminate(self):
"""Terminates current subpath. This method does nothing by default and is
supposed to be overridden in subclasses."""
def append_next(self, sibling_before: BaseElement):
"""Insert the resulting Path as :class:`inkex.elements._polygons.PathElement`
into the document tree.
Args:
sibling_before (BaseElement): The element the resulting path will be
appended after.
"""
pth = PathElement()
pth.path = self.current
pth.style = self.style
sibling_before.addnext(pth)
def Move_to(self, x, y): # pylint: disable=invalid-name
"""Shorthand to insert an absolute move command: `M x y`.
Args:
x (Float): x coordinate to move to
y (Float): y coordinate to move to
"""
self.add(Move(x, y))
def Line_to(self, x, y): # pylint: disable=invalid-name
"""Shorthand to insert an absolute lineto command: `L x y`.
Args:
x (Float): x coordinate to draw a line to
y (Float): y coordinate to draw a line to
"""
self.add(Line(x, y))
class PathGroupBuilder(PathBuilder):
"""This helper class can be used to construct a group of paths that all have the
same style.
.. versionadded:: 1.2"""
def __init__(self, style):
super().__init__(style)
self.result = Group()
def terminate(self):
"""Terminates the current Path, and appends it to the group if it is not
empty."""
if len(self.current) > 1:
pth = PathElement()
pth.path = self.current.to_absolute()
pth.style = self.style
self.result.append(pth)
self.current = Path()
def append_next(self, sibling_before: BaseElement):
"""Insert the resulting Path as :class:`inkex.elements._groups.Group` into the
document tree.
Args:
sibling_before (BaseElement): The element the resulting group will be
appended after.
"""
sibling_before.addnext(self.result)

View File

@@ -0,0 +1,862 @@
# coding=utf-8
#
# Copyright (C) 2005 Aaron Spike, aaron@ekips.org
# 2020 Jonathan Neuhauser, jonathan.neuhauser@outlook.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
"""Module for interpolating attributes and styles
.. versionchanged:: 1.2
Rewritten in inkex 1.2 in an object-oriented structure to support more attributes.
"""
from bisect import bisect_left
import abc
import copy
from .styles import Style
from .elements._filters import LinearGradient, RadialGradient, Stop
from .transforms import Transform
from .colors import Color
from .units import convert_unit, parse_unit, render_unit
from .bezier import bezlenapprx, cspbezsplit, cspbezsplitatlength, csplength
from .paths import Path, CubicSuperPath
from .elements import SvgDocumentElement
from .utils import FragmentError
try:
from typing import Tuple, TypeVar
Value = TypeVar("Value")
Number = TypeVar("Number", int, float)
except ImportError:
pass
def interpcoord(coord_a: Number, coord_b: Number, time: float):
"""Interpolate single coordinate by the amount of time"""
return ValueInterpolator(coord_a, coord_b).interpolate(time)
def interppoints(point1, point2, time):
# type: (Tuple[float, float], Tuple[float, float], float) -> Tuple[float, float]
"""Interpolate coordinate points by amount of time"""
return ArrayInterpolator(point1, point2).interpolate(time)
class AttributeInterpolator(abc.ABC):
"""Interpolate between attributes"""
def __init__(self, start_value, end_value):
self.start_value = start_value
self.end_value = end_value
@staticmethod
def best_style(node):
"""Gets the best possible approximation to a node's style. For nodes inside the
element tree of an SVG file, stylesheets defined in the defs of that file can be
taken into account. This should be the case for input elements, but is not
required - in that case, only the local inline style is used.
During the interpolation process, some nodes are created temporarily, such as
plain gradients of a single color to allow solid<->gradient interpolation. These
are not attached to the document tree and therefore have no root. Since the only
style relevant for them is the inline style, it is acceptable to fallback to it.
Args:
node (BaseElement): The node to get the best approximated style of
Returns:
Style: If the node is rooted, the CSS specified style. Else, the inline
style."""
try:
return node.specified_style()
except FragmentError:
return node.style
@staticmethod
def create_from_attribute(snode, enode, attribute, method=None):
"""Creates an interpolator for an attribute. Currently, only path, transform and
style attributes are supported
Args:
snode (BaseElement): start element
enode (BaseElement): end element
attribute (str): attribute name (for styles, starting with "style/")
method (AttributeInterpolator, optional): (currently only used for paths).
Specifies a method used to interpolate the attribute. Defaults to None.
Raises:
ValueError: if an attribute is passed that is not a style, path or transform
attribute
Returns:
AttributeInterpolator: an interpolator whose type depends on attribute.
"""
if attribute in Style.color_props:
return StyleInterpolator.create_from_fill_stroke(snode, enode, attribute)
if attribute == "d":
if method is None:
method = FirstNodesInterpolator
return method(snode.path, enode.path)
if attribute == "style":
return StyleInterpolator(snode, enode)
if attribute.startswith("style/"):
return StyleInterpolator.create(snode, enode, attribute[6:])
if attribute == "transform":
return TransformInterpolator(snode.transform, enode.transform)
if method is not None:
return method(snode.get(attribute), enode.get(attribute))
raise ValueError("only path and style attributes are supported")
@abc.abstractmethod
def interpolate(self, time=0):
"""Interpolation method, needs to be implemented by subclasses"""
return
class StyleInterpolator(AttributeInterpolator):
"""Class to interpolate styles"""
def __init__(self, start_value, end_value):
super().__init__(start_value, end_value)
self.interpolators = {}
# some keys are always processed in a certain order, these provide alternative
# interpolation routes if e.g. Color<->none is interpolated
all_keys = list(
dict.fromkeys(
["fill", "stroke", "fill-opacity", "stroke-opacity", "stroke-width"]
+ list(self.best_style(start_value).keys())
+ list(self.best_style(end_value).keys())
)
)
for attr in all_keys:
sstyle = self.best_style(start_value)
estyle = self.best_style(end_value)
if attr not in sstyle and attr not in estyle:
continue
try:
interp = StyleInterpolator.create(
self.start_value, self.end_value, attr
)
self.interpolators[attr] = interp
except ValueError:
# no interpolation method known for this attribute
pass
@staticmethod
def create(snode, enode, attribute):
"""Creates an Interpolator for a given style attribute, depending on its type:
- Color properties (such as fill, stroke) -> :class:`ColorInterpolator`,
:class:`GradientInterpolator` ect.
- Unit properties -> :class:`UnitValueInterpolator`
- other properties -> :class:`ValueInterpolator`
Args:
snode (BaseElement): start element
enode (BaseElement): end element
attribute (str): attribute to interpolate
Raises:
ValueError: if the attribute is not in any of the lists
Returns:
AttributeInterpolator: an interpolator object whose type depends on the
attribute.
"""
if attribute in Style.color_props:
return StyleInterpolator.create_from_fill_stroke(snode, enode, attribute)
if attribute in Style.unit_props:
return UnitValueInterpolator(
AttributeInterpolator.best_style(snode)(attribute),
AttributeInterpolator.best_style(enode)(attribute),
)
if attribute in Style.opacity_props:
return ValueInterpolator(
AttributeInterpolator.best_style(snode)(attribute),
AttributeInterpolator.best_style(enode)(attribute),
)
raise ValueError("Unknown attribute")
@staticmethod
def create_from_fill_stroke(snode, enode, attribute):
"""Creates an Interpolator for a given color-like attribute
Args:
snode (BaseElement): start element
enode (BaseElement): end element
attribute (str): attribute to interpolate
Raises:
ValueError: if the attribute is not color-like
ValueError: if the attribute is unset on both start and end style
Returns:
AttributeInterpolator: an interpolator object whose type depends on the
attribute.
"""
if attribute not in Style.color_props:
raise ValueError("attribute must be a color property")
sstyle = AttributeInterpolator.best_style(snode)
estyle = AttributeInterpolator.best_style(enode)
styles = [[snode, sstyle], [enode, estyle]]
for cur, curstyle in styles:
if curstyle(attribute) is None:
cur.style[attribute + "-opacity"] = 0.0
if attribute == "stroke":
cur.style["stroke-width"] = 0.0
# check if style is none, unset or a color
if isinstance(
sstyle(attribute), (LinearGradient, RadialGradient)
) or isinstance(estyle(attribute), (LinearGradient, RadialGradient)):
# if one of the two styles is a gradient, use gradient interpolation.
try:
return GradientInterpolator.create(snode, enode, attribute)
except ValueError:
# different gradient types, just duplicate the first
return TrivialInterpolator(sstyle(attribute))
if sstyle(attribute) is None and estyle(attribute) is None:
return TrivialInterpolator("none")
return ColorInterpolator.create(sstyle, estyle, attribute)
def interpolate(self, time=0):
"""Interpolates a style using the interpolators set in self.interpolators
Args:
time (int, optional): Interpolation position. If 0, start_value is returned,
if 1, end_value is returned. Defaults to 0.
Returns:
inkex.Style: interpolated style
"""
style = Style()
for prop, interp in self.interpolators.items():
style[prop] = interp.interpolate(time)
return style
class TrivialInterpolator(AttributeInterpolator):
"""Trivial interpolator, returns value for every time"""
def __init__(self, value):
super().__init__(value, value)
def interpolate(self, time=0):
return self.start_value
class ValueInterpolator(AttributeInterpolator):
"""Class for interpolation of a single value"""
def __init__(self, start_value=0, end_value=0):
super().__init__(float(start_value), float(end_value))
def interpolate(self, time=0):
"""(Linearly) interpolates a value
Args:
time (int, optional): Interpolation position. If 0, start_value is returned,
if 1, end_value is returned. Defaults to 0.
Returns:
int: interpolated value
"""
return self.start_value + ((self.end_value - self.start_value) * time)
class UnitValueInterpolator(ValueInterpolator):
"""Class for interpolation of a value with unit"""
def __init__(self, start_value=0, end_value=0):
start_val, start_unit = parse_unit(start_value)
end_val = convert_unit(end_value, start_unit)
super().__init__(start_val, end_val)
self.unit = start_unit
def interpolate(self, time=0):
return render_unit(super().interpolate(time), self.unit)
class ArrayInterpolator(AttributeInterpolator):
"""Interpolates array-like objects element-wise, e.g. color, transform,
coordinate"""
def __init__(self, start_value, end_value):
super().__init__(start_value, end_value)
self.interpolators = [
ValueInterpolator(cur, other)
for (cur, other) in zip(start_value, end_value)
]
def interpolate(self, time=0):
"""Interpolates an array element-wise
Args:
time (int, optional): [description]. Defaults to 0.
Returns:
List: interpolated array
"""
return [interp.interpolate(time) for interp in self.interpolators]
class TransformInterpolator(ArrayInterpolator):
"""Class for interpolation of transforms"""
def __init__(self, start_value=Transform(), end_value=Transform()):
"""Creates a transform interpolator.
Args:
start_value (inkex.Transform, optional): start transform. Defaults to
inkex.Transform().
end_value (inkex.Transform, optional): end transform. Defaults to
inkex.Transform().
"""
super().__init__(start_value.to_hexad(), end_value.to_hexad())
def interpolate(self, time=0):
"""Interpolates a transform by interpolating each item in the transform hexad
separately.
Args:
time (int, optional): Interpolation position. If 0, start_value is returned,
if 1, end_value is returned. Defaults to 0.
Returns:
Transform: interpolated transform
"""
return Transform(super().interpolate(time))
class ColorInterpolator(ArrayInterpolator):
"""Class for color interpolation"""
@staticmethod
def create(sst, est, attribute):
"""Creates a ColorInterpolator for either Fill or stroke, depending on the
attribute.
Args:
sst (Style): Start style
est (Style): End style
attribute (string): either fill or stroke
Raises:
ValueError: if none of the start or end style is a color.
Returns:
ColorInterpolator: A ColorInterpolator object
"""
styles = [sst, est]
for cur, other in zip(styles, reversed(styles)):
if not isinstance(cur(attribute), Color) or cur(attribute) is None:
cur[attribute] = other(attribute)
this = ColorInterpolator(
Color(styles[0](attribute)), Color(styles[1](attribute))
)
if this is None:
raise ValueError("One of the two attribute needs to be a plain color")
return this
def __init__(self, start_value=Color("#000000"), end_value=Color("#000000")):
# Remember what type the color was, handle none types as a special case
# so we can tween from "none" to some color effectively.
self.output_type = type(start_value)
if self.output_type.name == "none":
self.output_type = type(end_value)
# We tween alpha is there is any in either value
tween_alpha = (
start_value.effective_alpha != end_value.effective_alpha
or start_value.alpha is not None
or end_value.alpha is not None
)
super().__init__(
start_value.get_values(tween_alpha), end_value.get_values(tween_alpha)
)
def interpolate(self, time=0):
"""Interpolates a color by interpolating its channels separately.
Args:
time (int, optional): Interpolation position. If 0, start_value is returned,
if 1, end_value is returned. Defaults to 0.
Returns:
Color: interpolated color
"""
return self.output_type(list(map(float, super().interpolate(time))))
class GradientInterpolator(AttributeInterpolator):
"""Base class for Gradient Interpolation"""
def __init__(self, start_value, end_value, svg=None):
super().__init__(start_value, end_value)
self.svg = svg
# If one of the styles is empty, set it to the gradient of the other
if start_value is None:
self.start_value = end_value
if end_value is None:
self.end_value = start_value
self.transform_interpolator = TransformInterpolator(
self.start_value.gradientTransform, self.end_value.gradientTransform
)
self.orientation_interpolator = {
attr: UnitValueInterpolator(
self.start_value.get(attr), self.end_value.get(attr)
)
for attr in self.start_value.orientation_attributes
if self.start_value.get(attr) is not None
and self.end_value.get(attr) is not None
}
if not (
self.start_value.href is not None
and self.start_value.href is self.end_value.href
):
# the gradient link to different stops, interpolate between them
# add both start and end offsets, then take distict
newoffsets = sorted(
list(set(self.start_value.stop_offsets + self.end_value.stop_offsets))
)
def func(start, end, time):
return StopInterpolator(start, end).interpolate(time)
sstops = GradientInterpolator.interpolate_linear_list(
self.start_value.stop_offsets,
list(self.start_value.stops),
newoffsets,
func,
)
ostops = GradientInterpolator.interpolate_linear_list(
self.end_value.stop_offsets,
list(self.end_value.stops),
newoffsets,
func,
)
self.newstop_interpolator = [
StopInterpolator(s1, s2) for s1, s2 in zip(sstops, ostops)
]
else:
self.newstop_interpolator = None
@staticmethod
def create(snode, enode, attribute):
"""Creates a `GradientInterpolator` for either fill or stroke, depending on
attribute.
Cases: (A, B) -> Interpolator
- Linear Gradient, Linear Gradient -> LinearGradientInterpolator
- Color or None, Linear Gradient -> LinearGradientInterpolator
- Radial Gradient, Radial Gradient -> RadialGradientInterpolator
- Color or None, Radial Gradient -> RadialGradientInterpolator
- Radial Gradient, Linear Gradient -> ValueError
- Color or None, Color or None -> ValueError
Args:
snode (BaseElement): start element
enode (BaseElement): end element
attribute (string): either fill or stroke
Raises:
ValueError: if none of the styles are a gradient or if they are gradients
of different types
Returns:
GradientInterpolator: an Interpolator object
"""
interpolator = None
gradienttype = None
# first find out which type of interpolator we need
sstyle = AttributeInterpolator.best_style(snode)
estyle = AttributeInterpolator.best_style(enode)
for cur in [sstyle, estyle]:
curgrad = None
if isinstance(cur(attribute), (LinearGradient, RadialGradient)):
curgrad = cur(attribute)
for gradtype, interp in [
[LinearGradient, LinearGradientInterpolator],
[RadialGradient, RadialGradientInterpolator],
]:
if curgrad is not None and isinstance(curgrad, gradtype):
if interpolator is None:
interpolator = interp
gradienttype = gradtype
if not (interp == interpolator):
raise ValueError("Gradient types don't match")
# If one of the styles is empty, set it to the gradient of the other, but with
# zero opacity (and stroke-width for strokes)
# If one of the styles is a plain color, replace it by a gradient with a single
# stop
iterator = [[snode, gradienttype(), enode], [enode, gradienttype(), snode]]
for index in [0, 1]:
curstyle = AttributeInterpolator.best_style(iterator[index][0])
value = curstyle(attribute)
if value is None:
# if the attribute of one of the two ends is unset, set the opacity to
# zero.
iterator[index][0].style[attribute + "-opacity"] = 0.0
if attribute == "stroke":
iterator[index][0].style["stroke-width"] = 0.0
if isinstance(value, Color):
# if the attribute of one of the two ends is a color, convert it to a
# one-stop gradient. Type depends on the type of the other gradient.
interpolator.initialize_position(
iterator[index][1], iterator[index][0].bounding_box()
)
stop = Stop()
stop.style = Style()
stop.style["stop-color"] = value
stop.offset = 0
iterator[index][1].add(stop)
stop = Stop()
stop.style = Style()
stop.style["stop-color"] = value
stop.offset = 1
iterator[index][1].add(stop)
else:
iterator[index][1] = value # is a gradient
if interpolator is None:
raise ValueError("None of the two styles is a gradient")
if interpolator in [LinearGradientInterpolator, RadialGradientInterpolator]:
return interpolator(iterator[0][1], iterator[1][1], snode)
return interpolator(iterator[0][1], iterator[1][1])
@staticmethod
def interpolate_linear_list(positions, values, newpositions, func):
"""Interpolates a list of values given at n positions to the best approximation
at m newpositions.
>>>
|
| x
| x
_________________
pq q p q
(x denotes function values, p: positions, q: newpositions)
A function may be given to interpolate between given values.
Args:
positions (list[number-like]): position of current function values
values (list[Type]): list of arbitrary type,
``len(values) == len(positions)``
newpositions (list[number-like]): position of interpolated values
func (Callable[[Type, Type, float], Type]): Function to interpolate between
values
Returns:
list[Type]: interpolated function values at positions
"""
newvalues = []
positions = list(map(float, positions))
newpositions = list(map(float, newpositions))
for pos in newpositions:
if len(positions) == 1:
newvalues.append(values[0])
else:
# current run:
# idxl pos idxr
# p p | p
# q q
idxl = max(0, bisect_left(positions, pos) - 1)
idxr = min(len(positions) - 1, idxl + 1)
fraction = (pos - positions[idxl]) / (positions[idxr] - positions[idxl])
vall = values[idxl]
valr = values[idxr]
newval = func(vall, valr, fraction)
newvalues.append(newval)
return newvalues
@staticmethod
def append_to_doc(element, gradient):
"""Splits a gradient into stops and orientation, appends it to the document's
defs and returns the href to the orientation gradient.
Args:
element (BaseElement): an element inside the SVG that the gradient should be
added to
gradient (Gradient): the gradient to append to the document
Returns:
Gradient: the orientation gradient, or the gradient object if
element has no root or is None
"""
stops, orientation = gradient.stops_and_orientation()
if element is None or (
element.getparent() is None and not isinstance(element, SvgDocumentElement)
):
return gradient
element.root.defs.add(orientation)
if len(stops) > 0:
element.root.defs.add(stops, orientation)
orientation.href = stops.get_id()
return orientation
def interpolate(self, time=0):
"""Interpolate with another gradient."""
newgrad = self.start_value.copy()
# interpolate transforms
newgrad.gradientTransform = self.transform_interpolator.interpolate(time)
# interpolate orientation
for attr in self.orientation_interpolator.keys():
newgrad.set(attr, self.orientation_interpolator[attr].interpolate(time))
# interpolate stops
if self.newstop_interpolator is not None:
newgrad.remove_all(Stop)
newgrad.add(
*[interp.interpolate(time) for interp in self.newstop_interpolator]
)
if self.svg is None:
return newgrad
return GradientInterpolator.append_to_doc(self.svg, newgrad)
class LinearGradientInterpolator(GradientInterpolator):
"""Class for interpolation of linear gradients"""
def __init__(
self, start_value=LinearGradient(), end_value=LinearGradient(), svg=None
):
super().__init__(start_value, end_value, svg)
@staticmethod
def initialize_position(grad, bbox):
"""Initializes a linear gradient's position"""
grad.set("x1", bbox.left)
grad.set("x2", bbox.right)
grad.set("y1", bbox.center.y)
grad.set("y2", bbox.center.y)
class RadialGradientInterpolator(GradientInterpolator):
"""Class to interpolate radial gradients"""
def __init__(
self, start_value=RadialGradient(), end_value=RadialGradient(), svg=None
):
super().__init__(start_value, end_value, svg)
@staticmethod
def initialize_position(grad, bbox):
"""Initializes a radial gradient's position"""
x, y = bbox.center
grad.set("cx", x)
grad.set("cy", y)
grad.set("fx", x)
grad.set("fy", y)
grad.set("r", bbox.right - bbox.center.x)
class StopInterpolator(AttributeInterpolator):
"""Class to interpolate gradient stops"""
def __init__(self, start_value, end_value):
super().__init__(start_value, end_value)
self.style_interpolator = StyleInterpolator(start_value, end_value)
self.position_interpolator = ValueInterpolator(
float(start_value.offset), float(end_value.offset)
)
def interpolate(self, time=0):
"""Interpolates a gradient stop by interpolating style and offset separately
Args:
time (int, optional): Interpolation position. If 0, start_value is returned,
if 1, end_value is returned. Defaults to 0.
Returns:
Stop: interpolated gradient stop
"""
newstop = Stop()
newstop.style = self.style_interpolator.interpolate(time)
newstop.offset = self.position_interpolator.interpolate(time)
return newstop
class PathInterpolator(AttributeInterpolator):
"""Base class for Path interpolation"""
def __init__(self, start_value=Path(), end_value=Path()):
super().__init__(start_value.to_superpath(), end_value.to_superpath())
self.processed_end_path = None
self.processed_start_path = None
def truncate_subpaths(self):
"""Truncates the longer path so that all subpaths in both paths have an equal
number of bezier commands"""
s = [[]]
e = [[]]
# loop through all subpaths as long as there are remaining ones
while self.start_value and self.end_value:
# if both subpaths contain a bezier command, append it to s and e
if self.start_value[0] and self.end_value[0]:
s[-1].append(self.start_value[0].pop(0))
e[-1].append(self.end_value[0].pop(0))
# if the subpath of start_value is empty, add the remaining empty list as
# new subpath of s and one more item of end_value as new subpath of e.
# Afterwards, the loop terminates
elif self.end_value[0]:
s.append(self.start_value.pop(0))
e[-1].append(self.end_value[0][0])
e.append([self.end_value[0].pop(0)])
elif self.start_value[0]:
e.append(self.end_value.pop(0))
s[-1].append(self.start_value[0][0])
s.append([self.start_value[0].pop(0)])
# if there are no commands left in both start_value or end_value, add empty
# list to both start_value and end_value
else:
s.append(self.start_value.pop(0))
e.append(self.end_value.pop(0))
self.processed_start_path = s
self.processed_end_path = e
def interpolate(self, time=0):
# create an interpolated path for each interval
interp = []
# process subpaths
for ssubpath, esubpath in zip(
self.processed_start_path, self.processed_end_path
):
if not (ssubpath or esubpath):
break
# add a new subpath to the interpolated path
interp.append([])
# process each bezier command in the subpaths (which now have equal length)
for sbezier, ebezier in zip(ssubpath, esubpath):
if not (sbezier or ebezier):
break
# add a new bezier command to the last subpath
interp[-1].append([])
# process points
for point1, point2 in zip(sbezier, ebezier):
if not (point1 or point2):
break
# add a new point to the last bezier command
interp[-1][-1].append(
ArrayInterpolator(point1, point2).interpolate(time)
)
# remove final subpath if empty.
if not interp[-1]:
del interp[-1]
return CubicSuperPath(interp)
class EqualSubsegmentsInterpolator(PathInterpolator):
"""Interpolates the path by rediscretizing the subpaths first."""
@staticmethod
def get_subpath_lenghts(path):
"""prepare lengths for interpolation"""
sp_lenghts, total = csplength(path)
t = 0
lenghts = []
for sp in sp_lenghts:
for l in sp:
t += l / total
lenghts.append(t)
lenghts.sort()
return sp_lenghts, total, lenghts
@staticmethod
def process_path(path, other):
"""Rediscretize path so that all subpaths have an equal number of segments,
so that there is a node at the path "times" where path or other have a node
Args:
path (Path): the first path
other (Path): the second path
Returns:
Array: the prepared path description for the intermediate path"""
sp_lenghts, total, _ = EqualSubsegmentsInterpolator.get_subpath_lenghts(path)
_, _, lenghts = EqualSubsegmentsInterpolator.get_subpath_lenghts(other)
t = 0
s = [[]]
for sp in sp_lenghts:
if not path[0]:
s.append(path.pop(0))
s[-1].append(path[0].pop(0))
for l in sp:
pt = t
t += l / total
if lenghts and t > lenghts[0]:
while lenghts and lenghts[0] < t:
nt = (lenghts[0] - pt) / (t - pt)
bezes = cspbezsplitatlength(s[-1][-1][:], path[0][0][:], nt)
s[-1][-1:] = bezes[:2]
path[0][0] = bezes[2]
pt = lenghts.pop(0)
s[-1].append(path[0].pop(0))
return s
def __init__(self, start_path=Path(), end_path=Path()):
super().__init__(start_path, end_path)
# rediscretisize both paths
start_copy = copy.deepcopy(self.start_value)
# TODO find out why self.start_value.copy() doesn't work
self.start_value = EqualSubsegmentsInterpolator.process_path(
self.start_value, self.end_value
)
self.end_value = EqualSubsegmentsInterpolator.process_path(
self.end_value, start_copy
)
self.truncate_subpaths()
class FirstNodesInterpolator(PathInterpolator):
"""Interpolates a path by discarding the trailing nodes of the longer subpath"""
def __init__(self, start_path=Path(), end_path=Path()):
super().__init__(start_path, end_path)
# which path has fewer segments?
lengthdiff = len(self.start_value) - len(self.end_value)
# swap shortest first
if lengthdiff > 0:
self.start_value, self.end_value = self.end_value, self.start_value
# subdivide the shorter path
for _ in range(abs(lengthdiff)):
maxlen = 0
subpath = 0
segment = 0
for y, _ in enumerate(self.start_value):
for z in range(1, len(self.start_value[y])):
leng = bezlenapprx(
self.start_value[y][z - 1], self.start_value[y][z]
)
if leng > maxlen:
maxlen = leng
subpath = y
segment = z
sp1, sp2 = self.start_value[subpath][segment - 1 : segment + 1]
self.start_value[subpath][segment - 1 : segment + 1] = cspbezsplit(sp1, sp2)
# if swapped, swap them back
if lengthdiff > 0:
self.start_value, self.end_value = self.end_value, self.start_value
self.truncate_subpaths()

View File

@@ -0,0 +1,150 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) Aaron Spike <aaron@ekips.org>
# Aurélio A. Heckert <aurium(a)gmail.com>
# Bulia Byak <buliabyak@users.sf.net>
# Nicolas Dufour, nicoduf@yahoo.fr
# Peter J. R. Moulder <pjrm@users.sourceforge.net>
# Martin Owens <doctormo@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
"""
Convert to and from various units and find the closest matching unit.
"""
import re
# a dictionary of unit to user unit conversion factors
CONVERSIONS = {
"in": 96.0,
"pt": 1.3333333333333333,
"px": 1.0,
"mm": 3.779527559055118,
"cm": 37.79527559055118,
"m": 3779.527559055118,
"km": 3779527.559055118,
"Q": 0.94488188976378,
"pc": 16.0,
"yd": 3456.0,
"ft": 1152.0,
"": 1.0, # Default px
}
# allowed unit types, including percentages, relative units, and others
# that are not suitable for direct conversion to a length.
# Note that this is _not_ an exhaustive list of allowed unit types.
UNITS = [
"in",
"pt",
"px",
"mm",
"cm",
"m",
"km",
"Q",
"pc",
"yd",
"ft",
"",
"%",
"em",
"ex",
"ch",
"rem",
"vw",
"vh",
"vmin",
"vmax",
"deg",
"grad",
"rad",
"turn",
"s",
"ms",
"Hz",
"kHz",
"dpi",
"dpcm",
"dppx",
]
UNIT_MATCH = re.compile(rf"({'|'.join(UNITS)})")
NUMBER_MATCH = re.compile(r"(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)")
BOTH_MATCH = re.compile(rf"^\s*{NUMBER_MATCH.pattern}\s*{UNIT_MATCH.pattern}\s*$")
def parse_unit(value, default_unit="px", default_value=None):
"""
Takes a value such as 55.32px and returns (55.32, 'px')
Returns default (None) if no match can be found
"""
ret = BOTH_MATCH.match(str(value))
if ret:
return float(ret.groups()[0]), ret.groups()[-1] or default_unit
return (default_value, default_unit) if default_value is not None else None
def are_near_relative(point_a, point_b, eps=0.01):
"""Return true if the points are near to eps"""
return (point_a - point_b <= point_a * eps) and (
point_a - point_b >= -point_a * eps
)
def discover_unit(value, viewbox, default="px"):
"""Attempt to detect the unit being used based on the viewbox"""
# Default 100px when width can't be parsed
(value, unit) = parse_unit(value, default_value=100.0)
if unit not in CONVERSIONS:
return default
this_factor = CONVERSIONS[unit] * value / viewbox
# try to find the svgunitfactor in the list of units known. If we don't find
# something, ...
for unit, unit_factor in CONVERSIONS.items():
if unit != "":
# allow 1% error in factor
if are_near_relative(this_factor, unit_factor, eps=0.01):
return unit
return default
def convert_unit(value, to_unit, default="px"):
"""Returns userunits given a string representation of units in another system
Args:
value: <length> string
to_unit: unit to convert to
default: if ``value`` contains no unit, what unit should be assumed.
.. versionadded:: 1.1
"""
value, from_unit = parse_unit(value, default_unit=default, default_value=0.0)
if from_unit in CONVERSIONS and to_unit in CONVERSIONS:
return (
value * CONVERSIONS[from_unit] / CONVERSIONS.get(to_unit, CONVERSIONS["px"])
)
return 0.0
def render_unit(value, unit):
"""Checks and then renders a number with its unit"""
try:
if isinstance(value, str):
(value, unit) = parse_unit(value, default_unit=unit)
return f"{value:.6g}{unit:s}"
except TypeError:
return ""

View File

@@ -0,0 +1,410 @@
# coding=utf-8
#
# Copyright (C) 2010 Nick Drobchenko, nick@cnc-club.ru
# Copyright (C) 2005 Aaron Spike, aaron@ekips.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
"""
Basic common utility functions for calculated things
"""
from collections import OrderedDict, defaultdict
import os
import sys
import random
import re
import math
from argparse import ArgumentTypeError
from itertools import tee, cycle
import numpy as np
ABORT_STATUS = -5
(X, Y) = range(2)
PY3 = sys.version_info[0] == 3
# pylint: disable=line-too-long
# Taken from https://www.w3.org/Graphics/SVG/1.1/paths.html#PathDataBNF
DIGIT_REX_PART = r"[0-9]"
DIGIT_SEQUENCE_REX_PART = rf"(?:{DIGIT_REX_PART}+)"
INTEGER_CONSTANT_REX_PART = DIGIT_SEQUENCE_REX_PART
SIGN_REX_PART = r"[+-]"
EXPONENT_REX_PART = rf"(?:[eE]{SIGN_REX_PART}?{DIGIT_SEQUENCE_REX_PART})"
FRACTIONAL_CONSTANT_REX_PART = rf"(?:{DIGIT_SEQUENCE_REX_PART}?\.{DIGIT_SEQUENCE_REX_PART}|{DIGIT_SEQUENCE_REX_PART}\.)"
FLOATING_POINT_CONSTANT_REX_PART = rf"(?:{FRACTIONAL_CONSTANT_REX_PART}{EXPONENT_REX_PART}?|{DIGIT_SEQUENCE_REX_PART}{EXPONENT_REX_PART})"
NUMBER_REX = re.compile(
rf"(?:{SIGN_REX_PART}?{FLOATING_POINT_CONSTANT_REX_PART}|{SIGN_REX_PART}?{INTEGER_CONSTANT_REX_PART})"
)
# pylint: enable=line-too-long
def _pythonpath():
for pth in os.environ.get("PYTHONPATH", "").split(":"):
if os.path.isdir(pth):
yield pth
def get_user_directory():
"""Return the user directory where extensions are stored.
.. versionadded:: 1.1"""
if "INKSCAPE_PROFILE_DIR" in os.environ:
return os.path.abspath(
os.path.expanduser(
os.path.join(os.environ["INKSCAPE_PROFILE_DIR"], "extensions")
)
)
home = os.path.expanduser("~")
for pth in _pythonpath():
if pth.startswith(home):
return pth
return None
def get_inkscape_directory():
"""Return the system directory where inkscape's core is.
.. versionadded:: 1.1"""
for pth in _pythonpath():
if os.path.isdir(os.path.join(pth, "inkex")):
return pth
raise ValueError("Unable to determine the location of Inkscape")
class KeyDict(dict):
"""
A normal dictionary, except asking for anything not in the dictionary
always returns the key itself. This is used for translation dictionaries.
"""
def __getitem__(self, key):
try:
return super().__getitem__(key)
except KeyError:
return key
def parse_percent(val: str):
"""Parse strings that are either values (i.e., '3.14159') or percentages
(i.e. '75%') to a float.
.. versionadded:: 1.2"""
val = val.strip()
if val.endswith("%"):
return float(val[:-1]) / 100
return float(val)
def Boolean(value):
"""ArgParser function to turn a boolean string into a python boolean"""
if value.upper() == "TRUE":
return True
if value.upper() == "FALSE":
return False
return None
def to_bytes(content):
"""Ensures the content is bytes
.. versionadded:: 1.1"""
if isinstance(content, bytes):
return content
return str(content).encode("utf8")
def debug(what):
"""Print debug message if debugging is switched on"""
errormsg(what)
return what
def do_nothing(*args, **kwargs): # pylint: disable=unused-argument
"""A blank function to do nothing
.. versionadded:: 1.1"""
def errormsg(msg):
"""Intended for end-user-visible error messages.
(Currently just writes to stderr with an appended newline, but could do
something better in future: e.g. could add markup to distinguish error
messages from status messages or debugging output.)
Note that this should always be combined with translation::
import inkex
...
inkex.errormsg(_("This extension requires two selected paths."))
"""
try:
sys.stderr.write(msg)
except TypeError:
sys.stderr.write(str(msg))
except UnicodeEncodeError:
# Python 2:
# Fallback for cases where sys.stderr.encoding is not Unicode.
# Python 3:
# This will not work as write() does not accept byte strings, but AFAIK
# we should never reach this point as the default error handler is
# 'backslashreplace'.
# This will be None by default if stderr is piped, so use ASCII as a
# last resort.
encoding = sys.stderr.encoding or "ascii"
sys.stderr.write(msg.encode(encoding, "backslashreplace"))
# Write '\n' separately to avoid dealing with different string types.
sys.stderr.write("\n")
class AbortExtension(Exception):
"""Raised to print a message to the user without backtrace"""
class DependencyError(NotImplementedError):
"""Raised when we need an external python module that isn't available"""
class FragmentError(Exception):
"""Raised when trying to do rooty things on an xml fragment"""
def to(kind): # pylint: disable=invalid-name
"""
Decorator which will turn a generator into a list, tuple or other object type.
"""
def _inner(call):
def _outer(*args, **kw):
return kind(call(*args, **kw))
return _outer
return _inner
def strargs(string, kind=float):
"""Returns a list of floats from a string
.. versionchanged:: 1.1
also splits at -(minus) signs by adding a space in front of the - sign
.. versionchanged:: 1.2
Full support for the `SVG Path data BNF
<https://www.w3.org/Graphics/SVG/1.1/paths.html#PathDataBNF>`_
"""
return [kind(val) for val in NUMBER_REX.findall(string)]
class classproperty: # pylint: disable=invalid-name, too-few-public-methods
"""Combine classmethod and property decorators"""
def __init__(self, func):
self.func = func
def __get__(self, obj, owner):
return self.func(owner)
def filename_arg(name):
"""Existing file to read or option used in script arguments"""
filename = os.path.abspath(os.path.expanduser(name))
if not os.path.isfile(filename):
raise ArgumentTypeError(f"File not found: {name}")
return filename
def pairwise(iterable, start=True):
"Iterate over a list with overlapping pairs (see itertools recipes)"
first, then = tee(iterable)
starter = [(None, next(then, None))]
if not start:
starter = []
return starter + list(zip(first, then))
def circular_pairwise(l):
"""Iterate over a list with overlapping pairs in a periodic way, i.e.
[1, 2, 3] -> [(1, 2), (2, 3), (3, 1)]
..versionadded:: 1.3.1"""
second = cycle(l)
next(second)
return zip(l, second)
EVAL_GLOBALS = {}
EVAL_GLOBALS.update(random.__dict__)
EVAL_GLOBALS.update(math.__dict__)
def math_eval(function, variable="x"):
"""Interpret a function string. All functions from math and random may be used.
.. versionadded:: 1.1
Returns:
a lambda expression if sucessful; otherwise None.
"""
try:
if function != "":
return eval(
f"lambda {variable}: " + (function.strip('"') or "t"), EVAL_GLOBALS, {}
)
# handle incomplete/invalid function gracefully
except SyntaxError:
pass
return None
def is_number(string):
"""Checks if a value is a number
.. versionadded:: 1.2"""
try:
float(string)
return True
except ValueError:
return False
def rational_limit(f: np.poly1d, g: np.poly1d, t0):
"""Computes the limit of the rational function (f/g)(t)
as t approaches t0.
.. versionadded:: 1.4"""
assert g != np.poly1d([0])
if g(t0) != 0:
return f(t0) / g(t0)
elif f(t0) == 0:
return rational_limit(f.deriv(), g.deriv(), t0)
else:
raise ValueError("Limit does not exist.")
def callback_method(func):
def notify(self, *args, **kwargs):
result = func(self, *args, **kwargs)
self._callback()
return result
return notify
class NotifyList(list):
"""A list that calls a callback after it is modified
(to notify a parent about the modification).
Modified from https://stackoverflow.com/a/13259435/3298143
.. versionadded:: 1.4"""
extend = callback_method(list.extend)
append = callback_method(list.append)
remove = callback_method(list.remove)
pop = callback_method(list.pop)
__delitem__ = callback_method(list.__delitem__)
__setitem__ = callback_method(list.__setitem__)
__iadd__ = callback_method(list.__iadd__)
__imul__ = callback_method(list.__imul__)
def __getitem__(self, item):
"""Ensure that slicing returns a list of the same datatype"""
if isinstance(item, slice):
return self.__class__(list.__getitem__(self, item))
return list.__getitem__(self, item)
def __init__(self, *args, callback=None):
self.callback = None
list.__init__(self, *args)
self.callback = callback
def _callback(self):
if self.callback is not None:
self.callback(self)
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 NotifyOrderedDict(OrderedDict):
"""An OrderedDict that notifies a callback after a value is changed
.. versionadded:: 1.4"""
clear = callback_method(OrderedDict.clear)
popitem = callback_method(OrderedDict.popitem)
update = callback_method(OrderedDict.update)
setdefault = callback_method(OrderedDict.setdefault)
__setitem__ = callback_method(OrderedDict.__setitem__)
__delitem__ = callback_method(OrderedDict.__delitem__)
def __init__(self, *args, callback=None, **kwargs):
self.callback = None
super().__init__(*args, **kwargs)
self.callback = callback
def _callback(self):
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)
class NotifyDefaultDict(defaultdict):
"""A defaultdict that notifies a callback after a value is changed
.. versionadded:: 1.4"""
clear = callback_method(defaultdict.clear)
popitem = callback_method(defaultdict.popitem)
update = callback_method(defaultdict.update)
setdefault = callback_method(defaultdict.setdefault)
__setitem__ = callback_method(defaultdict.__setitem__)
__delitem__ = callback_method(defaultdict.__delitem__)
def __init__(self, *args, callback=None, **kwargs):
self.callback = None
super().__init__(*args, **kwargs)
self.callback = callback
def _callback(self):
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)

View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<name>Hatch Fill</name>
<id>org.knoxmakers.hatch</id>
<param name="units" type="optiongroup" appearance="combo" gui-text="Units:">
<option value="2">mm</option>
<option value="1">px</option>
<option value="3">in</option>
</param>
<param name="tab" type="notebook">
<page name="hatch" gui-text="Hatch Settings">
<param name="hatchSpacing" type="float" min="0.1" max="1000" gui-text="Hatch spacing:">1</param>
<param name="hatchAngle" type="float" min="-360" max="360" gui-text="Hatch angle (degrees):">0</param>
<param name="crossHatch" type="bool" gui-text="Cross hatch">false</param>
</page>
<page name="options" gui-text="Options">
<param name="insetDistance" type="float" min="0" max="100" gui-text="Inset distance from edges:">0</param>
<param name="tolerance" type="float" min="0.1" max="100" gui-text="Curve tolerance:">1</param>
<param name="connectEnds" type="bool" gui-text="Connect nearby ends">false</param>
<param name="connectTolerance" type="float" min="0" max="100" gui-text="Connection tolerance (units):">1</param>
</page>
</param>
<effect>
<object-type>path</object-type>
<effects-menu>
<submenu name="Knox Makers">
<submenu name="Laser"/>
</submenu>
</effects-menu>
</effect>
<script>
<command location="inx" interpreter="python">km_hatch.py</command>
</script>
</inkscape-extension>

View File

@@ -0,0 +1,436 @@
#!/usr/bin/env python3
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'deps'))
import math
from lxml import etree
import inkex
from inkex import Transform, BoundingBox, Path, CubicSuperPath, PathElement, Group
from inkex.elements import ShapeElement, Rectangle, Circle, Ellipse, Polygon, Polyline, Line
TOLERANCE = 1e-10
MIN_HATCH_LENGTH_AS_FRACTION = 0.25
RECURSION_LIMIT = 500
BEZIER_OVERSHOOT = 0.75
def distance_squared(p1, p2):
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
return dx * dx + dy * dy
def distance(p1, p2):
return math.sqrt(distance_squared(p1, p2))
def intersect_lines(p1, p2, p3, p4):
d21x = p2[0] - p1[0]
d21y = p2[1] - p1[1]
d43x = p4[0] - p3[0]
d43y = p4[1] - p3[1]
denom = d21x * d43y - d21y * d43x
if abs(denom) < TOLERANCE:
return -1.0
num_a = (p1[1] - p3[1]) * d43x - (p1[0] - p3[0]) * d43y
num_b = (p1[1] - p3[1]) * d21x - (p1[0] - p3[0]) * d21y
sa = num_a / denom
sb = num_b / denom
if 0.0 <= sa <= 1.0 and 0.0 <= sb <= 1.0:
return sa
return -1.0
def subdivide_cubic_path(sp, flatness):
while True:
changed = False
i = 1
while i < len(sp):
p0 = sp[i - 1][1]
p1 = sp[i - 1][2]
p2 = sp[i][0]
p3 = sp[i][1]
b = (p0[0] + p3[0]) / 2.0, (p0[1] + p3[1]) / 2.0
c1 = (p0[0] + p1[0]) / 2.0, (p0[1] + p1[1]) / 2.0
c2 = (p2[0] + p3[0]) / 2.0, (p2[1] + p3[1]) / 2.0
dx1 = c1[0] - b[0]
dy1 = c1[1] - b[1]
dx2 = c2[0] - b[0]
dy2 = c2[1] - b[1]
err = max(abs(dx1), abs(dy1), abs(dx2), abs(dy2))
if err > flatness:
m01 = ((p0[0] + p1[0]) / 2.0, (p0[1] + p1[1]) / 2.0)
m12 = ((p1[0] + p2[0]) / 2.0, (p1[1] + p2[1]) / 2.0)
m23 = ((p2[0] + p3[0]) / 2.0, (p2[1] + p3[1]) / 2.0)
m012 = ((m01[0] + m12[0]) / 2.0, (m01[1] + m12[1]) / 2.0)
m123 = ((m12[0] + m23[0]) / 2.0, (m12[1] + m23[1]) / 2.0)
mid = ((m012[0] + m123[0]) / 2.0, (m012[1] + m123[1]) / 2.0)
sp[i - 1][2] = m01
new_node = [m012, mid, m123]
sp[i][0] = m23
sp.insert(i, new_node)
changed = True
i += 1
if not changed:
break
class HatchFill(inkex.EffectExtension):
def add_arguments(self, pars):
pars.add_argument('--tab', type=str, default='hatch')
pars.add_argument('--hatchSpacing', type=float, default=1.0,
help='Spacing between hatch lines')
pars.add_argument('--hatchAngle', type=float, default=0.0,
help='Angle of hatch lines in degrees')
pars.add_argument('--crossHatch', type=inkex.Boolean, default=False,
help='Generate cross-hatch pattern')
pars.add_argument('--units', type=int, default=2,
help='Units: 1=px, 2=mm, 3=in')
pars.add_argument('--insetDistance', type=float, default=0,
help='Inset distance from edges')
pars.add_argument('--tolerance', type=float, default=1.0,
help='Curve tolerance')
pars.add_argument('--connectEnds', type=inkex.Boolean, default=False,
help='Connect nearby hatch ends')
pars.add_argument('--connectTolerance', type=float, default=1.0,
help='Tolerance for connecting ends')
def effect(self):
unit_factors = {1: 1.0, 2: 96.0 / 25.4, 3: 96.0}
unit_factor = unit_factors.get(self.options.units, 1.0)
self.hatch_spacing = self.options.hatchSpacing * unit_factor
self.hatch_angle = math.radians(self.options.hatchAngle)
self.cross_hatch = self.options.crossHatch
self.inset_distance = self.options.insetDistance * unit_factor
self.tolerance = self.options.tolerance
self.connect_ends = self.options.connectEnds
self.connect_tolerance = self.options.connectTolerance * unit_factor
if self.hatch_spacing < 0.1:
self.hatch_spacing = 0.1
shape_types = (PathElement, Rectangle, Circle, Ellipse, Polygon, Polyline)
if self.svg.selection:
elements = list(self.svg.selection.filter(*shape_types))
else:
elements = list(self.svg.descendants().filter(*shape_types))
if not elements:
inkex.errormsg("No shapes selected. Please select one or more closed shapes.")
return
any_hatches = False
for elem in elements:
self.polygons = []
self.transforms = []
self.process_element(elem)
if not self.polygons:
continue
hatches = self.generate_hatches()
if self.cross_hatch:
original_angle = self.hatch_angle
self.hatch_angle += math.pi / 2
hatches.extend(self.generate_hatches())
self.hatch_angle = original_angle
if not hatches:
continue
if self.connect_ends and self.connect_tolerance > 0:
hatches = self.connect_hatches(hatches)
self.add_hatches_for_element(elem, hatches)
any_hatches = True
if not any_hatches:
inkex.errormsg("No hatch lines were generated. Check that paths are closed.")
def process_element(self, elem):
try:
if hasattr(elem, 'get_path'):
path = elem.get_path()
elif hasattr(elem, 'path'):
path = elem.path
else:
return
if not path:
return
transform = elem.composed_transform()
csp = path.to_superpath()
for subpath in csp:
if len(subpath) < 2:
continue
subdivide_cubic_path(subpath, self.tolerance)
vertices = [(pt[1][0], pt[1][1]) for pt in subpath]
is_closed = False
if len(vertices) >= 3:
d = distance(vertices[0], vertices[-1])
if d < 1.0:
is_closed = True
elif isinstance(elem, (Rectangle, Circle, Ellipse, Polygon)):
is_closed = True
if d >= 1.0:
vertices.append(vertices[0])
if is_closed:
transformed = []
for v in vertices:
pt = transform.apply_to_point(v)
transformed.append((pt.x, pt.y))
self.polygons.append(transformed)
self.transforms.append(transform)
except Exception as e:
pass
def get_bounding_box(self):
if not self.polygons:
return None
min_x = min_y = float('inf')
max_x = max_y = float('-inf')
for poly in self.polygons:
for x, y in poly:
min_x = min(min_x, x)
min_y = min(min_y, y)
max_x = max(max_x, x)
max_y = max(max_y, y)
return (min_x, min_y, max_x, max_y)
def generate_hatches(self):
bbox = self.get_bounding_box()
if not bbox:
return []
min_x, min_y, max_x, max_y = bbox
cx = (min_x + max_x) / 2
cy = (min_y + max_y) / 2
diagonal = math.sqrt((max_x - min_x) ** 2 + (max_y - min_y) ** 2) / 2
perp_angle = self.hatch_angle + math.pi / 2
cos_a = math.cos(perp_angle)
sin_a = math.sin(perp_angle)
line_cos = math.cos(self.hatch_angle)
line_sin = math.sin(self.hatch_angle)
hatch_lines = []
offset = -diagonal
while offset <= diagonal:
x1 = cx + offset * cos_a - diagonal * line_cos
y1 = cy + offset * sin_a - diagonal * line_sin
x2 = cx + offset * cos_a + diagonal * line_cos
y2 = cy + offset * sin_a + diagonal * line_sin
hatch_lines.append(((x1, y1), (x2, y2)))
offset += self.hatch_spacing
hatches = []
for h_line in hatch_lines:
segments = self.get_hatch_segments(h_line)
hatches.extend(segments)
return hatches
def get_hatch_segments(self, h_line):
p1, p2 = h_line
intersections = []
for poly in self.polygons:
n = len(poly)
for i in range(n):
p3 = poly[i]
p4 = poly[(i + 1) % n]
t = intersect_lines(p1, p2, p3, p4)
if t >= 0:
ix = p1[0] + t * (p2[0] - p1[0])
iy = p1[1] + t * (p2[1] - p1[1])
intersections.append((t, ix, iy))
intersections.sort(key=lambda x: x[0])
filtered = []
prev_t = -1
for item in intersections:
if item[0] - prev_t > TOLERANCE:
filtered.append(item)
prev_t = item[0]
segments = []
i = 0
while i < len(filtered) - 1:
start = filtered[i]
end = filtered[i + 1]
seg_len = distance((start[1], start[2]), (end[1], end[2]))
min_len = self.hatch_spacing * MIN_HATCH_LENGTH_AS_FRACTION
if seg_len >= min_len:
if self.inset_distance > 0 and seg_len > 2 * self.inset_distance:
dx = end[1] - start[1]
dy = end[2] - start[2]
factor = self.inset_distance / seg_len
sx = start[1] + dx * factor
sy = start[2] + dy * factor
ex = end[1] - dx * factor
ey = end[2] - dy * factor
segments.append(((sx, sy), (ex, ey)))
else:
segments.append(((start[1], start[2]), (end[1], end[2])))
i += 2
return segments
def connect_hatches(self, hatches):
if not hatches:
return hatches
result = []
used = [False] * len(hatches)
tol_sq = self.connect_tolerance * self.connect_tolerance
i = 0
while i < len(hatches):
if used[i]:
i += 1
continue
used[i] = True
current_path = [hatches[i][0], hatches[i][1]]
changed = True
iterations = 0
while changed and iterations < RECURSION_LIMIT:
changed = False
iterations += 1
end = current_path[-1]
best_j = -1
best_dist = tol_sq
best_reverse = False
for j, h in enumerate(hatches):
if used[j]:
continue
d1 = distance_squared(end, h[0])
d2 = distance_squared(end, h[1])
if d1 < best_dist:
best_dist = d1
best_j = j
best_reverse = False
if d2 < best_dist:
best_dist = d2
best_j = j
best_reverse = True
if best_j >= 0:
used[best_j] = True
if best_reverse:
current_path.append(hatches[best_j][1])
current_path.append(hatches[best_j][0])
else:
current_path.append(hatches[best_j][0])
current_path.append(hatches[best_j][1])
changed = True
for k in range(0, len(current_path) - 1, 2):
result.append((current_path[k], current_path[k + 1]))
i += 1
return result
def add_hatches_for_element(self, source_elem, hatches):
if not hatches:
return
path_data = []
for start, end in hatches:
path_data.append(f'M {start[0]:.4f},{start[1]:.4f}')
path_data.append(f'L {end[0]:.4f},{end[1]:.4f}')
path_str = ' '.join(path_data)
path_elem = PathElement()
path_elem.path = Path(path_str)
source_style = source_elem.style
hatch_style = {
'fill': 'none',
'stroke-linecap': 'round',
'stroke-linejoin': 'round'
}
if 'stroke' in source_style:
hatch_style['stroke'] = source_style['stroke']
else:
if 'fill' in source_style and source_style['fill'] != 'none':
hatch_style['stroke'] = source_style['fill']
else:
hatch_style['stroke'] = '#000000'
if 'stroke-width' in source_style:
hatch_style['stroke-width'] = source_style['stroke-width']
else:
hatch_style['stroke-width'] = '1'
if 'stroke-opacity' in source_style:
hatch_style['stroke-opacity'] = source_style['stroke-opacity']
if 'opacity' in source_style:
hatch_style['opacity'] = source_style['opacity']
path_elem.style = hatch_style
parent = source_elem.getparent()
if parent is not None:
index = list(parent).index(source_elem)
parent.insert(index + 1, path_elem)
else:
self.svg.get_current_layer().append(path_elem)
if __name__ == '__main__':
HatchFill().run()

View File

@@ -0,0 +1 @@
main

View File

@@ -0,0 +1 @@
b9b0c988e4078c87c7b78820f92fad58dcddaf00

View File

@@ -0,0 +1 @@
https://git.knoxmakers.org/KnoxMakers/km-hershey.git

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