diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ 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.
+
+
+ Copyright (C)
+
+ 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 .
+
+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:
+
+ Copyright (C)
+ 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
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/__init__.py b/__init__.py
new file mode 100644
index 0000000..993cc69
--- /dev/null
+++ b/__init__.py
@@ -0,0 +1,35 @@
+"""
+/***************************************************************************
+ SpatialFilter
+ A QGIS plugin
+ This plugin applies spatial filters to layers for performance and efficiency.
+
+ Base was generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+ -------------------
+ begin : 2022-10-16
+ copyright : (C) 2022 Wheregroup GmbH
+ email : info@wheregroup.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 script initializes the plugin, making it known to QGIS.
+"""
+
+
+# noinspection PyPep8Naming
+def classFactory(iface): # pylint: disable=invalid-name
+ """Load MapFilter class from file MapFilter.
+
+ :param iface: A QGIS interface instance.
+ :type iface: QgsInterface
+ """
+ #
+ from .spatial_filter import SpatialFilter
+ return SpatialFilter(iface)
diff --git a/controller.py b/controller.py
new file mode 100644
index 0000000..9e25ca1
--- /dev/null
+++ b/controller.py
@@ -0,0 +1,142 @@
+from typing import Iterable, Optional, List
+
+from qgis.PyQt.QtCore import pyqtSignal, QObject
+from qgis.core import QgsProject, QgsMapLayer, QgsMapLayerType, QgsWkbTypes, QgsGeometry
+from qgis.gui import QgsRubberBand
+from qgis.utils import iface
+
+from .maptool import PolygonTool
+from .filters import FilterDefinition, Predicate, RemoteFilterStrategy
+from .helpers import getSupportedLayers, removeFilterFromLayer, addFilterToLayer, refreshLayerTree, hasLayerException, \
+ warnAboutCurveGeoms
+from .settings import FILTER_COMMENT_START, LOCALIZED_PLUGIN_NAME
+
+
+class FilterController(QObject):
+ currentFilter: Optional[FilterDefinition]
+ rubberBands: Optional[List[QgsRubberBand]]
+
+ filterChanged = pyqtSignal(object)
+
+ def __init__(self, parent: Optional[QObject] = None) -> None:
+ super().__init__(parent=parent)
+ self.currentFilter = None
+ self.rubberBands = []
+ self.connectSignals()
+
+ def connectSignals(self):
+ # Many thanks to *Thomas B* for suggesting that the layersAdded signal fires so quickly that editing
+ # the layer filter will happen before the data is actually requested, at least for PostGIS
+ QgsProject.instance().layersAdded.connect(self.onLayersAdded)
+
+ # to clear the filter when the project is cleared (e.g. a new project is loaded or created)
+ QgsProject.instance().cleared.connect(self.onProjectCleared)
+
+ def disconnectSignals(self):
+ # We shouldn't have to explicitly disconnect slots that vanish with the plugin (e.g. self.foo)
+ # but it does not hurt either
+ QgsProject.instance().layersAdded.disconnect(self.onLayersAdded)
+ QgsProject.instance().cleared.disconnect(self.onProjectCleared)
+
+ def removeFilter(self):
+ self.currentFilter = None
+ self.refreshFilter()
+
+ def onLayersAdded(self, layers: Iterable[QgsMapLayer]):
+ warnAboutCurveGeoms(layers)
+ if self.hasValidFilter():
+ # Apply the filter to added layers or loaded project
+ for layer in getSupportedLayers(layers):
+ addFilterToLayer(layer, self.currentFilter)
+ else:
+ # Look for saved filters to use with the plugin (possible when project was loaded)
+ for layer in getSupportedLayers(layers):
+ if FILTER_COMMENT_START in layer.subsetString():
+ self.setFilterFromLayer(layer)
+ return
+
+ def onProjectCleared(self):
+ """Removes the filter if one is active.
+
+ This prevents filters from staying active when the user loads another project or creates a new one.
+ """
+ self.removeFilter()
+
+ def setFilterFromLayer(self, layer):
+ filterDefinition = FilterDefinition.fromFilterString(layer.subsetString())
+ if not filterDefinition.crs.isValid():
+ filterDefinition.crs = layer.crs()
+ self.currentFilter = filterDefinition
+ self.refreshFilter()
+
+ def updateLayerFilters(self):
+ for layer in getSupportedLayers(QgsProject.instance().mapLayers().values()):
+ if self.hasValidFilter() and not hasLayerException(layer):
+ addFilterToLayer(layer, self.currentFilter)
+ else:
+ removeFilterFromLayer(layer)
+ refreshLayerTree()
+
+ def updateProjectLayers(self):
+ self.updateLayerFilters()
+
+ def refreshFilter(self):
+ self.filterChanged.emit(self.currentFilter)
+ self.updateProjectLayers()
+
+ def setFilterFromSelection(self):
+ layer = iface.activeLayer()
+ if not layer or not layer.type() == QgsMapLayerType.VectorLayer:
+ iface.messageBar().pushInfo(LOCALIZED_PLUGIN_NAME, self.tr('Select a polygon layer'))
+ return
+ if not layer.geometryType() == QgsWkbTypes.GeometryType.PolygonGeometry:
+ iface.messageBar().pushInfo(LOCALIZED_PLUGIN_NAME, self.tr('Select a polygon layer'))
+ return
+ if not layer.selectedFeatureCount():
+ iface.messageBar().pushInfo(LOCALIZED_PLUGIN_NAME, self.tr('No features selected'))
+ return
+ crs = iface.activeLayer().crs()
+ geom = QgsGeometry().unaryUnion([feature.geometry() for feature in layer.selectedFeatures()])
+ self.initFilter()
+ self.currentFilter.name = self.tr('New filter from selection')
+ self.currentFilter.crs = crs
+ self.currentFilter.wkt = geom.asWkt()
+ self.refreshFilter()
+
+ def setFilterPredicate(self, predicate: Predicate):
+ self.currentFilter.predicate = predicate.value
+ self.refreshFilter()
+
+ def setFilterBbox(self, bbox: bool):
+ self.currentFilter.bbox = bbox
+ self.refreshFilter()
+
+ def setRemoteFilterStrategy(self, strategy: RemoteFilterStrategy):
+ self.currentFilter.remote_strategy = strategy.value
+ self.refreshFilter()
+
+ def initFilter(self):
+ self.currentFilter = FilterDefinition.defaultFilter()
+
+ def hasValidFilter(self):
+ return self.currentFilter and self.currentFilter.isValid
+
+ def startSketchingTool(self):
+ self.mapTool = PolygonTool()
+ self.mapTool.sketchFinished.connect(self.onSketchFinished)
+ iface.mapCanvas().setMapTool(self.mapTool)
+
+ def stopSketchingTool(self):
+ iface.mapCanvas().unsetMapTool(self.mapTool)
+ self.mapTool.deactivate()
+
+ def onSketchFinished(self, geometry: QgsGeometry):
+ self.stopSketchingTool()
+ if not geometry.isGeosValid():
+ iface.messageBar().pushWarning(LOCALIZED_PLUGIN_NAME, self.tr("Geometry is not valid"))
+ return
+ self.initFilter()
+ self.currentFilter.name = self.tr('New filter from sketch')
+ self.currentFilter.wkt = geometry.asWkt()
+ self.currentFilter.crs = QgsProject.instance().crs()
+ self.refreshFilter()
diff --git a/filters.py b/filters.py
new file mode 100644
index 0000000..e872ed8
--- /dev/null
+++ b/filters.py
@@ -0,0 +1,481 @@
+from dataclasses import dataclass, replace
+from enum import IntEnum
+from typing import List
+import re
+
+from qgis.PyQt.QtWidgets import QMessageBox
+from qgis.core import QgsVectorLayer, QgsGeometry, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsProject, QgsWkbTypes
+from qgis.utils import iface
+
+from .settings import FILTER_COMMENT_START, FILTER_COMMENT_STOP, LOCALIZED_PLUGIN_NAME
+from .helpers import tr, saveSettingsValue, readSettingsValue, allSettingsValues, removeSettingsValue, \
+ getLayerGeomName, matchFormatString
+
+
+FILTERSTRING_SQL_TEMPLATE = "{spatial_predicate}({geom_expr}, ST_TRANSFORM(ST_GeomFromText('{wkt}', {srid}), {layer_srid}))"
+# Backward-compatible parser for filters written by older plugin versions.
+FILTERSTRING_SQL_TEMPLATE_LEGACY = "{spatial_predicate}({geom_name}, ST_TRANSFORM(ST_GeomFromText('{wkt}', {srid}), {layer_srid}))"
+FILTERSTRING_EXPR_TEMPLATE = "{spatial_predicate}(@geometry, geomFromWKT('{wkt}'))"
+MAX_REMOTE_FILTER_EXPRESSION_LENGTH = 6000
+
+
+def crs_from_postgis_srid(srid) -> QgsCoordinateReferenceSystem:
+ """Create a CRS from an EPSG/PostGIS SRID without using the deprecated int constructor."""
+ crs = QgsCoordinateReferenceSystem(f"EPSG:{int(srid)}")
+ if not crs.isValid():
+ crs = QgsCoordinateReferenceSystem()
+ crs.createFromSrid(int(srid))
+ return crs
+
+
+def geometry2d(geometry: QgsGeometry) -> QgsGeometry:
+ """Return a defensive 2D copy of a geometry.
+
+ Spatial filters in this plugin are planimetric. QGIS 3D renderer settings
+ and Z/M-enabled layer geometries must not make an otherwise matching
+ feature disappear from the 2D spatial filter. Some providers/services also
+ react poorly to PolygonZ/MultiPolygonZ WKT in subset expressions.
+ """
+ geom = QgsGeometry(geometry)
+ try:
+ abstract_geometry = geom.constGet()
+ if abstract_geometry is None:
+ return geom
+ abstract_geometry = abstract_geometry.clone()
+ if QgsWkbTypes.hasZ(abstract_geometry.wkbType()):
+ abstract_geometry.dropZValue()
+ if QgsWkbTypes.hasM(abstract_geometry.wkbType()):
+ abstract_geometry.dropMValue()
+ return QgsGeometry(abstract_geometry)
+ except Exception:
+ return geom
+
+
+def layer_geometry_sql_expression(layer: QgsVectorLayer) -> str:
+ """Return a provider SQL expression for the layer geometry as 2D geometry.
+
+ The filter is intentionally planimetric. Z/M values and QGIS 3D renderer
+ settings must not influence whether a feature is inside the filter area.
+
+ GeoPackage/SQLite layers from ALKIS/NAS and similar sources may expose
+ OGC geometry collection families such as MultiSurfaceZ or MultiCurveZ. For
+ those curved/surface types, provider-side SQL needs an additional
+ linearisation step before the normal 2D cast.
+ """
+ geom_name = getLayerGeomName(layer)
+ provider_type = layer.providerType().lower()
+ storage_type = layer.storageType().upper()
+ is_curved_or_surface = QgsWkbTypes.isCurvedType(layer.wkbType())
+
+ # PostGIS handles explicit 2D forcing reliably and this avoids Z/M-related
+ # false negatives for true database layers.
+ if provider_type == "postgres" or "POSTGIS" in storage_type:
+ geom_expr = geom_name
+ if is_curved_or_surface:
+ geom_expr = f"ST_CurveToLine({geom_expr})"
+ return f"ST_Force2D({geom_expr})"
+
+ if storage_type in {"GPKG", "SQLITE"}:
+ # Important: do not wrap GeoPackage/OGR geometries here. In practice,
+ # expressions such as CastToXY(ST_CurveToLine(GEOMETRY)) can be accepted
+ # by the provider but evaluate to NULL/false for MultiSurfaceZ and
+ # MultiCurveZ layers, which makes QGIS hide every feature. The filter
+ # geometry itself is already forced to 2D before it is written as WKT;
+ # OGR/SQLite spatial predicates then evaluate the layer geometry
+ # planimetrically and handle Z-enabled MultiSurface/MultiCurve layers
+ # much more robustly.
+ return geom_name
+
+ return geom_name
+
+
+def _filter_geometry_sql(filter_def: 'FilterDefinition', layer: QgsVectorLayer) -> str:
+ wkt = filter_def.boxGeometry.asWkt() if filter_def.bbox else filter_def.geometry.asWkt()
+ return "ST_TRANSFORM(ST_GeomFromText('{wkt}', {srid}), {layer_srid})".format(
+ wkt=wkt.replace("'", "''"),
+ srid=filter_def.crs.postgisSrid(),
+ layer_srid=layer.crs().postgisSrid(),
+ )
+
+
+def _sqlite_exact_spatial_filter_sql(filter_def: 'FilterDefinition', layer: QgsVectorLayer) -> str:
+ """Build a stricter GeoPackage/SQLite spatial predicate.
+
+ ST_Intersects on some GPKG/OGR builds can behave like an envelope hit for
+ complex MultiSurface/MultiCurve geometries. NOT ST_Disjoint usually forces
+ the exact topological test and avoids visible false positives outside the
+ drawn filter geometry.
+ """
+ geom_expr = layer_geometry_sql_expression(layer)
+ filter_geom = _filter_geometry_sql(filter_def, layer)
+ if filter_def.predicate == Predicate.INTERSECTS:
+ return f"NOT ST_Disjoint({geom_expr}, {filter_geom})"
+ if filter_def.predicate == Predicate.DISJOINT:
+ return f"ST_Disjoint({geom_expr}, {filter_geom})"
+ if filter_def.predicate == Predicate.WITHIN:
+ return f"ST_Within({geom_expr}, {filter_geom})"
+ return f"NOT ST_Disjoint({geom_expr}, {filter_geom})"
+
+
+class Predicate(IntEnum):
+ INTERSECTS = 1
+ WITHIN = 2
+ DISJOINT = 3
+
+
+class RemoteFilterStrategy(IntEnum):
+ """Strategy for WFS/OAPIF layers where long geometry filters may overload URLs/servers."""
+ AUTO = 1
+ EXACT = 2
+ SIMPLIFIED = 3
+ BBOX = 4
+
+
+@dataclass
+class RemoteFilterCandidate:
+ expression: str
+ geometry: QgsGeometry
+ strategy: RemoteFilterStrategy
+ used_bbox: bool = False
+
+
+class RemoteFilterStrategyBuilder:
+ """Builds robust provider-expression filters for WFS and OGC API Features layers.
+
+ In AUTO mode the class tries to keep the filter exact. Only if the generated
+ expression becomes too long, it falls back to a simplified geometry and then
+ to the bounding box. This avoids Request-URI-too-long errors without
+ unnecessarily reducing spatial precision.
+ """
+
+ def __init__(self, filter_def: 'FilterDefinition', layer: QgsVectorLayer):
+ self.filter_def = filter_def
+ self.layer = layer
+
+ def build(self) -> RemoteFilterCandidate:
+ selected_strategy = RemoteFilterStrategy(self.filter_def.remote_strategy)
+
+ if self.filter_def.bbox or selected_strategy == RemoteFilterStrategy.BBOX:
+ return self._candidate(self.filter_def.boxGeometry, use_bbox=True, strategy=RemoteFilterStrategy.BBOX)
+
+ exact = self._candidate(self.filter_def.geometry, strategy=RemoteFilterStrategy.EXACT)
+ if selected_strategy == RemoteFilterStrategy.EXACT:
+ return exact
+ if selected_strategy == RemoteFilterStrategy.SIMPLIFIED:
+ return self._simplified_or_bbox()
+ if len(exact.expression) <= MAX_REMOTE_FILTER_EXPRESSION_LENGTH:
+ return exact
+
+ return self._simplified_or_bbox()
+
+ def _simplified_or_bbox(self) -> RemoteFilterCandidate:
+ simplified = self._candidate(self._simplified_geometry(), strategy=RemoteFilterStrategy.SIMPLIFIED)
+ if simplified.geometry and simplified.geometry.isGeosValid() and len(simplified.expression) <= MAX_REMOTE_FILTER_EXPRESSION_LENGTH:
+ return simplified
+ return self._candidate(self.filter_def.boxGeometry, use_bbox=True, strategy=RemoteFilterStrategy.BBOX)
+
+ def _simplified_geometry(self) -> QgsGeometry:
+ geometry = geometry2d(self.filter_def.geometry)
+ bbox = geometry.boundingBox()
+ diagonal = ((bbox.width() ** 2) + (bbox.height() ** 2)) ** 0.5
+ tolerance = max(diagonal / 2000.0, 0.001)
+ simplified = geometry.simplify(tolerance)
+ if simplified and not simplified.isEmpty() and simplified.isGeosValid():
+ return simplified
+ return geometry
+
+ def _candidate(self, geometry: QgsGeometry, use_bbox: bool = False,
+ strategy: RemoteFilterStrategy = RemoteFilterStrategy.EXACT) -> RemoteFilterCandidate:
+ transformed_geometry = geometry2d(geometry)
+ if self.filter_def.crs.isValid() and self.layer.crs().isValid() and self.filter_def.crs != self.layer.crs():
+ transform = QgsCoordinateTransform(self.filter_def.crs, self.layer.crs(), QgsProject.instance())
+ transformed_geometry.transform(transform)
+
+ spatial_predicate = Predicate(self.filter_def.predicate).name.lower()
+ if use_bbox:
+ spatial_predicate = "bbox"
+
+ expression = FILTERSTRING_EXPR_TEMPLATE.format(
+ spatial_predicate=spatial_predicate,
+ wkt=transformed_geometry.asWkt(),
+ )
+ return RemoteFilterCandidate(expression, transformed_geometry, strategy, use_bbox)
+
+
+@dataclass
+class FilterDefinition:
+ name: str
+ wkt: str
+ crs: QgsCoordinateReferenceSystem
+ predicate: int
+ bbox: bool
+ remote_strategy: int = RemoteFilterStrategy.AUTO
+
+ def __post_init__(self):
+ self.predicate = int(self.predicate)
+ self.remote_strategy = int(self.remote_strategy)
+
+ def __lt__(self, other):
+ return self.name.upper() < other.name.upper()
+
+ @property
+ def geometry(self) -> QgsGeometry:
+ return geometry2d(QgsGeometry.fromWkt(self.wkt))
+
+ @property
+ def boxGeometry(self) -> QgsGeometry:
+ return geometry2d(QgsGeometry.fromRect(self.geometry.boundingBox()))
+
+ def filterString(self, layer: QgsVectorLayer) -> str:
+ """Returns a layer filter string corresponding to the filter definition.
+
+ Args:
+ layer (QgsVectorLayer): The layer for which the filter should be applied
+
+ Returns:
+ str: A layer filter string
+ """
+ provider_type = layer.providerType().lower()
+
+ if provider_type in {"wfs", "oapif"}:
+ return self._expressionFilterString(layer)
+
+ return self._sqlFilterString(layer)
+
+ def _sqlFilterString(self, layer: QgsVectorLayer) -> str:
+ # ST_DISJOINT does not use spatial indexes, but we can use its opposite "NOT ST_INTERSECTS" which does
+ spatial_predicate = f"ST_{Predicate(self.predicate).name}"
+ if self.predicate == Predicate.DISJOINT:
+ spatial_predicate = "NOT ST_INTERSECTS"
+
+ wkt = self.geometry.asWkt()
+ if self.bbox:
+ wkt = self.boxGeometry.asWkt()
+
+ storage_type = layer.storageType().upper()
+ if storage_type in {"GPKG", "SQLITE"}:
+ return _sqlite_exact_spatial_filter_sql(self, layer)
+
+ geom_expr = layer_geometry_sql_expression(layer)
+
+ return FILTERSTRING_SQL_TEMPLATE.format(
+ spatial_predicate=spatial_predicate,
+ geom_expr=geom_expr,
+ wkt=wkt.replace("'", "''"),
+ srid=self.crs.postgisSrid(),
+ layer_srid=layer.crs().postgisSrid()
+ )
+
+ def _expressionFilterString(self, layer: QgsVectorLayer) -> str:
+ return RemoteFilterStrategyBuilder(self, layer).build().expression
+
+ @staticmethod
+ def fromFilterString(subsetString: str) -> 'FilterDefinition':
+ start_index = subsetString.find(FILTER_COMMENT_START) + len(FILTER_COMMENT_START)
+ stop_index = subsetString.find(FILTER_COMMENT_STOP)
+ filterString = subsetString[start_index: stop_index].strip()
+ if filterString.upper().startswith('AND '):
+ filterString = filterString[4:].strip()
+
+ for parser in (_filterDefinitionFromSqlStringRobust, _filterDefinitionFromExpressionStringRobust):
+ try:
+ return updateFilterNameFromStorage(parser(filterString))
+ except Exception:
+ continue
+
+ raise ValueError(f"Unsupported filter string format: {filterString}")
+
+ @property
+ def storageDict(self) -> dict:
+ """Returns a text serialisation of the FilterDefinition.
+
+ For the CRS just the Auth ID is stored, e.g. EPSG:1234 or PROJ:9876.
+ """
+ return {
+ 'name': self.name,
+ 'wkt': self.wkt,
+ 'srid': self.crs.authid(),
+ 'predicate': str(self.predicate),
+ 'bbox': self.bbox,
+ 'remote_strategy': str(self.remote_strategy)
+ }
+
+ @staticmethod
+ def fromStorageDict(value: dict) -> 'FilterDefinition':
+ assert len(value) in (5, 6), f"Malformed FilterDefinition loaded from settings: {value}"
+ name = value['name']
+ wkt = value['wkt']
+ predicate = value['predicate']
+ bbox = value['bbox']
+ remote_strategy = value.get('remote_strategy', RemoteFilterStrategy.AUTO)
+ crs = QgsCoordinateReferenceSystem(value['srid'])
+ return FilterDefinition(name, wkt, crs, predicate, bbox, remote_strategy)
+
+ @staticmethod
+ def defaultFilter():
+ return FilterDefinition(tr('New Filter'), '', QgsCoordinateReferenceSystem(), Predicate.INTERSECTS, False, RemoteFilterStrategy.AUTO)
+
+ @property
+ def isValid(self) -> bool:
+ return all([self.geometry.isGeosValid(), self.crs.isValid(), self.predicate])
+
+ @property
+ def isSaved(self) -> bool:
+ return self.storageDict == readSettingsValue(self.name)
+
+ def copy(self):
+ return replace(self)
+
+
+def loadFilterDefinition(name: str) -> FilterDefinition:
+ return FilterDefinition.fromStorageDict(readSettingsValue(name))
+
+
+def loadAllFilterDefinitions() -> List[FilterDefinition]:
+ return [FilterDefinition.fromStorageDict(value) for value in allSettingsValues()]
+
+
+def saveFilterDefinition(filterDef: FilterDefinition) -> None:
+ if not filterDef:
+ iface.messageBar().pushInfo(LOCALIZED_PLUGIN_NAME, tr("No current filter"))
+ return
+ if not filterDef.isValid:
+ iface.messageBar().pushInfo(LOCALIZED_PLUGIN_NAME, tr("Current filter definition is not valid"))
+ return
+ if not filterDef.name:
+ iface.messageBar().pushInfo(LOCALIZED_PLUGIN_NAME, tr("Please provide a name for the filter"))
+ return
+ if filterDef.isSaved:
+ return
+ if readSettingsValue(filterDef.name):
+ if not askOverwrite(filterDef.name):
+ return
+ saveSettingsValue(filterDef.name, filterDef.storageDict)
+
+
+def deleteFilterDefinition(filterDef: FilterDefinition) -> None:
+ if askDelete(filterDef.name):
+ removeSettingsValue(filterDef.name)
+
+
+def updateFilterNameFromStorage(filterDef: FilterDefinition) -> FilterDefinition:
+ for storageFilter in loadAllFilterDefinitions():
+ if filterDef.crs == storageFilter.crs and filterDef.wkt == storageFilter.wkt:
+ storageFilter.predicate = filterDef.predicate
+ return storageFilter
+ if filterDef.crs == storageFilter.crs and filterDef.wkt == storageFilter.boxGeometry.asWkt():
+ storageFilter.predicate = filterDef.predicate
+ storageFilter.bbox = True
+ return storageFilter
+ return filterDef
+
+
+def askApply() -> bool:
+ txt = tr('Current settings will be lost. Apply anyway?')
+ return QMessageBox.question(iface.mainWindow(), tr('Continue?'), txt,
+ QMessageBox.StandardButton.Yes, QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes
+
+
+def askOverwrite(name: str) -> bool:
+ txt = tr('Overwrite settings for filter')
+ return QMessageBox.question(iface.mainWindow(), tr('Overwrite?'), f'{txt} {name}?',
+ QMessageBox.StandardButton.Yes, QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes
+
+
+def askDelete(name: str) -> bool:
+ txt = tr('Delete filter')
+ return QMessageBox.question(iface.mainWindow(), tr('Delete?'), f'{txt} {name}?',
+ QMessageBox.StandardButton.Yes, QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes
+
+
+def _filterDefinitionFromSqlString(filterString: str, params: dict) -> FilterDefinition:
+ predicateName = params['spatial_predicate'][len('ST_'):]
+ if filterString.startswith('NOT ST_INTERSECTS'):
+ predicateName = 'DISJOINT'
+
+ predicate = Predicate[predicateName]
+ return FilterDefinition(
+ name=tr('Unknown filter'),
+ wkt=params['wkt'],
+ crs=crs_from_postgis_srid(params['srid']),
+ predicate=predicate.value,
+ bbox=False,
+ remote_strategy=RemoteFilterStrategy.AUTO
+ )
+
+
+def _filterDefinitionFromExpressionString(filterString: str, params: dict) -> FilterDefinition:
+ predicate_name = params['spatial_predicate'].upper()
+ bbox = predicate_name == 'BBOX'
+ if bbox:
+ predicate_name = 'INTERSECTS'
+
+ predicate = Predicate[predicate_name]
+ return FilterDefinition(
+ name=tr('Unknown filter'),
+ wkt=params['wkt'],
+ crs=QgsCoordinateReferenceSystem(),
+ predicate=predicate.value,
+ bbox=bbox,
+ remote_strategy=RemoteFilterStrategy.AUTO
+ )
+
+
+def _filterDefinitionFromSqlStringRobust(filterString: str) -> FilterDefinition:
+ """Parse SQL subset strings written by this plugin.
+
+ The older generic format-string parser does not cope reliably with nested
+ geometry expressions such as CastToXY(ST_CurveToLine(GEOMETRY)) and long
+ MultiPolygon WKT. A narrow regex is safer here: the plugin only needs to
+ recover the spatial predicate, filter WKT and source SRID.
+ """
+ pattern = re.compile(
+ r"^\s*(?PNOT\s+)?(?PST_(?:INTERSECTS|WITHIN|DISJOINT))\s*\("
+ r".*?ST_GeomFromText\s*\(\s*'(?P.*?)'\s*,\s*(?P\d+)\s*\)"
+ r"\s*,\s*(?P\d+)\s*\)\s*\)\s*$",
+ re.IGNORECASE | re.DOTALL,
+ )
+ match = pattern.match(filterString)
+ if not match:
+ raise ValueError("not a plugin SQL filter")
+
+ predicate_name = match.group('pred').upper()[len('ST_'):]
+ if match.group('neg') and predicate_name == 'INTERSECTS':
+ predicate_name = 'DISJOINT'
+ elif match.group('neg') and predicate_name == 'DISJOINT':
+ predicate_name = 'INTERSECTS'
+
+ predicate = Predicate[predicate_name]
+ return FilterDefinition(
+ name=tr('Unknown filter'),
+ wkt=match.group('wkt'),
+ crs=crs_from_postgis_srid(match.group('srid')),
+ predicate=predicate.value,
+ bbox=False,
+ remote_strategy=RemoteFilterStrategy.AUTO,
+ )
+
+
+def _filterDefinitionFromExpressionStringRobust(filterString: str) -> FilterDefinition:
+ pattern = re.compile(
+ r"^\s*(?Pintersects|within|disjoint|bbox)\s*\(\s*@geometry\s*,\s*geomFromWKT\s*\(\s*'(?P.*?)'\s*\)\s*\)\s*$",
+ re.IGNORECASE | re.DOTALL,
+ )
+ match = pattern.match(filterString)
+ if not match:
+ raise ValueError("not a plugin expression filter")
+
+ predicate_name = match.group('pred').upper()
+ bbox = predicate_name == 'BBOX'
+ if bbox:
+ predicate_name = 'INTERSECTS'
+
+ predicate = Predicate[predicate_name]
+ return FilterDefinition(
+ name=tr('Unknown filter'),
+ wkt=match.group('wkt'),
+ crs=QgsCoordinateReferenceSystem(),
+ predicate=predicate.value,
+ bbox=bbox,
+ remote_strategy=RemoteFilterStrategy.AUTO,
+ )
diff --git a/helpers.py b/helpers.py
new file mode 100644
index 0000000..76d9f9b
--- /dev/null
+++ b/helpers.py
@@ -0,0 +1,209 @@
+import os
+import re
+import importlib
+from typing import Any, List, Iterable
+
+from osgeo import ogr
+from qgis.PyQt.QtCore import QCoreApplication
+from qgis.core import (
+ Qgis,
+ QgsExpressionContextUtils,
+ QgsSettings,
+ QgsMapLayer,
+ QgsMapLayerType,
+ QgsVectorLayer,
+ QgsWkbTypes,
+)
+from qgis.utils import iface
+
+from .settings import SUPPORTED_STORAGE_TYPES, SUPPORTED_PROVIDER_TYPES, GROUP, FILTER_COMMENT_START, FILTER_COMMENT_STOP, \
+ LAYER_EXCEPTION_VARIABLE, LOCALIZED_PLUGIN_NAME
+
+
+def tr(message):
+ return QCoreApplication.translate('@default', message)
+
+
+def saveSettingsValue(key: str, value: Any):
+ settings = QgsSettings()
+ settings.beginGroup(GROUP)
+ settings.setValue(key, value)
+ settings.endGroup()
+
+
+def readSettingsValue(key: str, defaultValue: Any = None) -> Any:
+ settings = QgsSettings()
+ settings.beginGroup(GROUP)
+ value = settings.value(key, defaultValue)
+ settings.endGroup()
+ return value
+
+
+def allSettingsValues(defaultValue: Any = None) -> List[Any]:
+ settings = QgsSettings()
+ settings.beginGroup(GROUP)
+ values = [settings.value(key, defaultValue) for key in settings.allKeys()]
+ settings.endGroup()
+ return values
+
+
+def removeSettingsValue(key: str) -> None:
+ settings = QgsSettings()
+ settings.beginGroup(GROUP)
+ settings.remove(key)
+ settings.endGroup()
+
+
+def refreshLayerTree() -> None:
+ """Refreshes the layer tree to update the filter icons.
+ We use hide() and show() as there is no native refresh method
+ """
+ tree = iface.layerTreeView()
+ tree.hide()
+ tree.show()
+
+
+def getSupportedLayers(layers: Iterable[QgsMapLayer]):
+ for layer in layers:
+ if isLayerSupported(layer):
+ yield layer
+
+
+def isLayerSupported(layer: QgsMapLayer):
+ if layer.type() != QgsMapLayerType.VectorLayer:
+ return False
+ if not layer.isSpatial():
+ return False
+
+ provider_type = layer.providerType().lower()
+ storage_type = layer.storageType().upper()
+
+ if provider_type in SUPPORTED_PROVIDER_TYPES:
+ return True
+ if storage_type in SUPPORTED_STORAGE_TYPES:
+ return True
+ return False
+
+
+def removeFilterFromLayer(layer: QgsVectorLayer):
+ currentFilter = layer.subsetString()
+ if FILTER_COMMENT_START not in currentFilter:
+ return
+ start_index = currentFilter.find(FILTER_COMMENT_START)
+ stop_index = currentFilter.find(FILTER_COMMENT_STOP) + len(FILTER_COMMENT_STOP)
+ newFilter = currentFilter[:start_index] + currentFilter[stop_index:]
+ layer.setSubsetString(newFilter)
+
+
+def addFilterToLayer(layer: QgsVectorLayer, filterDef: 'FilterDefinition'): # noqa: F821
+ currentFilter = layer.subsetString()
+ if FILTER_COMMENT_START in currentFilter:
+ removeFilterFromLayer(layer)
+ currentFilter = layer.subsetString()
+ connect = " AND " if currentFilter else ""
+ newFilter = f'{currentFilter}{FILTER_COMMENT_START}{connect}{filterDef.filterString(layer)}{FILTER_COMMENT_STOP}'
+ layer.setSubsetString(newFilter)
+
+
+def getLayerGeomName(layer: QgsVectorLayer):
+ return layer.dataProvider().uri().geometryColumn() or getLayerGeomNameOgr(layer)
+
+
+def getLayerGeomNameOgr(layer: QgsVectorLayer):
+ source = layer.source()
+
+ # layer source *might* include pipe character and then the layername
+ # but when created from a processing algorithm, it might not
+ if "|" in source:
+ split_source = source.split('|')
+ filepath = split_source[0]
+ lname = split_source[1].split('=')[1]
+ else:
+ # assuming we simply got a full path to the file and nothing else
+ filepath = layer.source()
+ lname = os.path.splitext(os.path.basename(filepath))[0]
+
+ conn = ogr.Open(filepath)
+ ogrLayer = conn.GetLayerByName(lname)
+ columnName = ogrLayer.GetGeometryColumn()
+ ogrLayer = None
+ conn = None
+ return columnName
+
+
+def hasLayerException(layer: QgsVectorLayer) -> bool:
+ return QgsExpressionContextUtils.layerScope(layer).variable(LAYER_EXCEPTION_VARIABLE) == 'true'
+
+
+def setLayerException(layer: QgsVectorLayer, exception: bool) -> None:
+ QgsExpressionContextUtils.setLayerVariable(layer, LAYER_EXCEPTION_VARIABLE, exception)
+
+
+def matchFormatString(format_str: str, s: str) -> dict:
+ """Match s against the given format string, return dict of matches.
+
+ We assume all of the arguments in format string are named keyword arguments (i.e. no {} or
+ {:0.2f}). We also assume that all chars are allowed in each keyword argument, so separators
+ need to be present which aren't present in the keyword arguments (i.e. '{one}{two}' won't work
+ reliably as a format string but '{one}-{two}' will if the hyphen isn't used in {one} or {two}).
+
+ We raise if the format string does not match s.
+
+ Example:
+ fs = '{test}-{flight}-{go}'
+ s = fs.format('first', 'second', 'third')
+ match_format_string(fs, s) -> {'test': 'first', 'flight': 'second', 'go': 'third'}
+
+ source: https://stackoverflow.com/questions/10663093/use-python-format-string-in-reverse-for-parsing
+ """
+
+ # First split on any keyword arguments, note that the names of keyword arguments will be in the
+ # 1st, 3rd, ... positions in this list
+ tokens = re.split(r'\{(.*?)\}', format_str)
+ keywords = tokens[1::2]
+
+ # Now replace keyword arguments with named groups matching them. We also escape between keyword
+ # arguments so we support meta-characters there. Re-join tokens to form our regexp pattern
+ tokens[1::2] = map(u'(?P<{}>.*)'.format, keywords)
+ tokens[0::2] = map(re.escape, tokens[0::2])
+ pattern = ''.join(tokens)
+
+ # Use our pattern to match the given string, raise if it doesn't match
+ matches = re.match(pattern, s)
+ if not matches:
+ raise Exception("Format string did not match")
+
+ # Return a dict with all of our keywords and their values
+ return {x: matches.group(x) for x in keywords}
+
+
+def class_for_name(module_name: str, class_name: str):
+ """Loads a class via its name as string.
+
+ Source: https://stackoverflow.com/questions/1176136/convert-string-to-python-class-object
+ """
+ # load the module, will raise ImportError if module cannot be loaded
+ m = importlib.import_module(module_name)
+ # get the class, will raise AttributeError if class cannot be found
+ c = getattr(m, class_name)
+ return c
+
+
+def warnAboutCurveGeoms(layers: Iterable[QgsMapLayer]):
+ # Curved/surface GeoPackage geometries such as MultiSurfaceZ and
+ # MultiCurveZ are handled in filters.layer_geometry_sql_expression() by
+ # ST_CurveToLine(...) + CastToXY(...). Older plugin versions showed a
+ # warning and treated these layers as unsupported; this is no longer
+ # appropriate and caused needless confusion. Keep this hook as a no-op for
+ # backwards compatibility with the controller.
+ return
+
+
+def warnAboutQgisBugProjectSaving():
+ """Show a warning because of https://github.com/qgis/QGIS/issues/55975"""
+ if Qgis.QGIS_VERSION_INT < 33404:
+ txt = tr(
+ "QGIS < 3.34.4 has a bug breaking the saving of (active) filters to projects "
+ '(Info)'
+ ).format(pluginName=LOCALIZED_PLUGIN_NAME)
+ iface.messageBar().pushWarning(LOCALIZED_PLUGIN_NAME, txt)
diff --git a/i18n/spatial_filter.pro b/i18n/spatial_filter.pro
new file mode 100644
index 0000000..b0616ec
--- /dev/null
+++ b/i18n/spatial_filter.pro
@@ -0,0 +1,3 @@
+FORMS = ../ui/named_filters_dialog.ui
+SOURCES = ../spatial_filter.py ../filters.py ../widgets.py ../helpers.py ../models.py ../controller.py ../settings.py
+TRANSLATIONS = spatial_filter_de.ts
diff --git a/i18n/spatial_filter_de.qm b/i18n/spatial_filter_de.qm
new file mode 100644
index 0000000..aab6b98
Binary files /dev/null and b/i18n/spatial_filter_de.qm differ
diff --git a/i18n/spatial_filter_de.ts b/i18n/spatial_filter_de.ts
new file mode 100644
index 0000000..aa1120b
--- /dev/null
+++ b/i18n/spatial_filter_de.ts
@@ -0,0 +1,288 @@
+
+
+
+
+ @default
+
+
+ Current filter definition is not valid
+ Aktuelle Filterdefinition ist ungültig
+
+
+
+ Please provide a name for the filter
+ Bitte zuerst einen Filternamen vergeben
+
+
+
+ Overwrite settings for filter
+ Einstellungen überschreiben für Filter
+
+
+
+ Overwrite?
+ Überschreiben?
+
+
+
+ Delete filter
+ Filter löschen
+
+
+
+ Delete?
+ Löschen?
+
+
+
+ Current settings will be lost. Apply anyway?
+ Aktuelle Einstellungen gehen verloren. Trotzdem anwenden?
+
+
+
+ Continue?
+ Fortfahren?
+
+
+
+ New Filter
+ Neuer Filter
+
+
+
+ No current filter
+ Kein Filter aktiv
+
+
+
+ Unknown filter
+ Unbekannter Filter
+
+
+
+ Spatial Filter
+ Räumlicher Filter
+
+
+
+ The {layerType} layer {layerName!r} has a geometry type ({geometryType}) that is not supported by the {pluginName} plugin and will be ignored for filtering.
+ Der {layerType}-Layer {layerName!r} hat einen vom {pluginName!r}-Plugin nicht unterstützten Geometrietyp ({geometryType}) und kann daher nicht gefiltert werden.
+
+
+
+ QGIS < 3.34.4 has a bug breaking the saving of (active) filters to projects (<a href="https://github.com/WhereGroup/spatial_filter/issues/24">Info</a>)
+ QGIS < 3.34.4 hat einen Bug, welcher beim Speichern von Projekten mit aktivem Filter zu Fehlern führt (<a href="https://github.com/WhereGroup/spatial_filter/issues/24">Info</a>)
+
+
+
+ ExtentDialog
+
+
+ Set rectangular filter geometry
+ Rechteckige Filtergeometrie setzen
+
+
+
+ New filter from extent
+ Neuer Filter aus Ausdehnung
+
+
+
+ FilterController
+
+
+ Select a polygon layer
+ Polygonlayer auswählen
+
+
+
+ No features selected
+ Keine Features gewählt
+
+
+
+ Geometry is not valid
+ Geometrie ist ungültig
+
+
+
+ New filter from selection
+ Neuer Filter aus Auswahl
+
+
+
+ New filter from sketch
+ Neuer Filter aus Skizze
+
+
+
+ FilterToolbar
+
+
+ Rectangular filter
+ Rechteckiger Filter
+
+
+
+ Filter from selected features
+ Filter aus gewählten Features
+
+
+
+ Manage filters
+ Filter verwalten
+
+
+
+ Filter Toolbar
+ Filterwerkzeugleiste
+
+
+
+ Show filter geometry
+ Filtergeometrie anzeigen
+
+
+
+ No filter geometry set
+ Keine Filtergeometrie gesetzt
+
+
+
+ Exclude layers from filter
+ Ausnahmen festlegen
+
+
+
+ Hide filter geometry
+ Filtergeometrie verstecken
+
+
+
+ Draw a filter polygon on the canvas
+ Filter-Polygon in der Karte zeichnen
+
+
+
+ Remove current filter
+ Filter entfernen
+
+
+
+ Filter style
+ Filterstil
+
+
+
+ Style filter
+ Filterstil wählen
+
+
+
+ Zoom to filter
+ Auf Filter zoomen
+
+
+
+ LayerExceptionsDialog
+
+
+ Exclude layers from filter
+ Ausnahmen festlegen
+
+
+
+ LayerModel
+
+
+ Layer has no spatial index
+ Layer hat keinen räumlichen Index
+
+
+
+ Layer type is not supported
+ Layertyp wird nicht unterstützt
+
+
+
+ ManageFiltersDialog
+
+
+ Named spatial filters
+ Benannte räumliche Filter
+
+
+
+ Active Filter:
+ Aktiver Filter:
+
+
+
+ Named Filters:
+ Benannte Filter:
+
+
+
+ Apply
+ Anwenden
+
+
+
+ Delete
+ Löschen
+
+
+
+ Close
+ Schließen
+
+
+
+ Save
+ Speichern
+
+
+
+ PredicateButton
+
+
+ Geometric predicate
+ Räumlicher Operator
+
+
+
+ Geometric Predicate
+ Räumlicher Operator
+
+
+
+ Object of comparison
+ Vergleichsobjekt
+
+
+
+ BBOX
+ BBOX
+
+
+
+ GEOM
+ GEOM
+
+
+
+ intersects
+ schneidet
+
+
+
+ within
+ innerhalb
+
+
+
+ disjoint
+ schneidet nicht
+
+
+
diff --git a/icons/filter_off.png b/icons/filter_off.png
new file mode 100644
index 0000000..f8122a2
Binary files /dev/null and b/icons/filter_off.png differ
diff --git a/icons/filter_on.png b/icons/filter_on.png
new file mode 100644
index 0000000..85e9bc8
Binary files /dev/null and b/icons/filter_on.png differ
diff --git a/icons/icon.png b/icons/icon.png
new file mode 100644
index 0000000..d0951fb
Binary files /dev/null and b/icons/icon.png differ
diff --git a/maptool.py b/maptool.py
new file mode 100644
index 0000000..7a33bcb
--- /dev/null
+++ b/maptool.py
@@ -0,0 +1,64 @@
+from qgis.gui import QgsMapTool, QgsRubberBand
+from qgis.core import QgsGeometry, QgsWkbTypes
+from qgis.utils import iface
+
+from qgis.PyQt.QtCore import Qt, QPoint, pyqtSignal
+
+
+class PolygonTool(QgsMapTool):
+ sketchFinished = pyqtSignal(QgsGeometry)
+
+ def __init__(self):
+ self.rubberBand = None
+ self.canvas = iface.mapCanvas()
+ super().__init__(self.canvas)
+
+ def reset(self):
+ if self.rubberBand:
+ self.rubberBand.reset()
+ self.canvas.scene().removeItem(self.rubberBand)
+ self.rubberBand = None
+
+ def canvasPressEvent(self, event):
+ pass
+
+ def canvasReleaseEvent(self, event):
+ x = event.pos().x()
+ y = event.pos().y()
+ thisPoint = QPoint(x, y)
+
+ mapToPixel = self.canvas.getCoordinateTransform() # QgsMapToPixel instance
+
+ if event.button() == Qt.MouseButton.LeftButton:
+ if not self.rubberBand:
+ self.rubberBand = QgsRubberBand(self.canvas, geometryType=QgsWkbTypes.GeometryType.PolygonGeometry)
+ self.rubberBand.setLineStyle(Qt.PenStyle.DashLine)
+ self.rubberBand.setWidth(2)
+ self.rubberBand.addPoint(mapToPixel.toMapCoordinates(thisPoint))
+
+ elif event.button() == Qt.MouseButton.RightButton:
+ if self.rubberBand and self.rubberBand.numberOfVertices() > 3:
+ # Finish rubberband sketch
+ self.rubberBand.removeLastPoint()
+ geometry = self.rubberBand.asGeometry()
+ self.sketchFinished.emit(geometry)
+ self.reset()
+ self.canvas.refresh()
+
+ def canvasMoveEvent(self, event):
+ if not self.rubberBand:
+ return
+ x = event.pos().x()
+ y = event.pos().y()
+ thisPoint = QPoint(x, y)
+ mapToPixel = self.canvas.getCoordinateTransform()
+ self.rubberBand.movePoint(self.rubberBand.numberOfVertices() - 1, mapToPixel.toMapCoordinates(thisPoint))
+
+ def keyPressEvent(self, event):
+ """Resets the rubber band when Escape key is pressed."""
+ if event.key() == Qt.Key.Key_Escape:
+ self.reset()
+
+ def deactivate(self):
+ self.reset()
+ QgsMapTool.deactivate(self)
diff --git a/metadata.txt b/metadata.txt
new file mode 100644
index 0000000..defafa9
--- /dev/null
+++ b/metadata.txt
@@ -0,0 +1,71 @@
+[general]
+name=Erweiterter Räumlicher Filter
+qgisMinimumVersion=3.22
+qgisMaximumVersion=4.99
+description=Spatial filters for PostGIS, GeoPackage, Spatialite, WFS and OGC API Features layers
+description[de]=Räumliche Filter für PostGIS-, GeoPackage-, Spatialite-, WFS- und OGC-API-Features-Layer
+version=2.1.7
+author=WhereGroup GmbH (Peter Gipper, Mathias Gröbe, Johannes Kröger), KRZN (WFS/OGC API Features)
+email=info@wheregroup.com
+
+about[en]=Create and manage spatial filters that are applied to PostGIS, GeoPackage, Spatialite, WFS and OGC API Features vector layers in the current QGIS project. The plugin allows for filtered viewing and editing of the layer, with the filter being defined by a polygon geometry or a bounding box. It is possible to define exceptions for layers and display the filter geometry on the map canvas.
+
+about=Erstellt und verwaltet räumliche Filter für vektorbasierte PostGIS-, GeoPackage-, Spatialite-, WFS- und OGC-API-Features-Layer im aktuellen QGIS-Projekt. Damit lässt sich die Anzeige und Bearbeitung der Layer auf eine bestimmte Polygongeometrie oder deren minimal umfassendes Rechteck begrenzen. Es ist möglich Ausnahmen für einzelne Layer zu definieren und die Filtergeometrie anzuzeigen.
+
+tracker=https://github.com/WhereGroup/spatial_filter/issues
+repository=https://github.com/WhereGroup/spatial_filter
+
+hasProcessingProvider=no
+tags=python, filter, vector, postgis, performance
+
+changelog=
+ Version 2.1.7: GeoPackage/SQLite-Intersects für komplexe MultiSurface/MultiCurve-Geometrien auf NOT ST_Disjoint umgestellt, um bbox-artige False-Positives außerhalb der Filtergeometrie zu vermeiden.
+ Version 2.1.5: CRS-Rekonstruktion aus gespeicherten SQL-Filtern korrigiert; verhindert falsche Reprojektion und leere Ergebnisse bei MultiPolygon/MultiSurface-Filtern.
+ Version 2.1.4: MultiSurfaceZ/MultiCurveZ-Unterstützung verbessert und Parser für verschachtelte SQL-Geometrieausdrücke stabilisiert.
+ Version 2.1.3:
+ - Force provider-side SQL filters to compare 2D geometries for PostGIS, GeoPackage and SQLite/SpatiaLite layers
+ - Fix filtering of PolygonZ/MultiPolygonZ layers and layers with 3D view styling where the provider otherwise evaluated spatial predicates incorrectly
+ Version 2.1.2:
+ - Normalize filter geometries to 2D before creating SQL/provider expressions
+ Version 2.1.1:
+ - Translate WFS/OAPIF strategy menu entries to German
+ Version 2.1.0:
+ - Add intelligent WFS/OAPIF filter strategy: exact geometry, simplify, BBOX fallback
+ - Add WFS/OAPIF strategy selector to the predicate menu
+ - Prevent overlong remote filter expressions from creating Request-URI-too-long errors
+ Version 2.0.0:
+ - Add spatial filter support for WFS and OGC API Features layers
+ - Use provider-specific filter expressions for web feature services
+ Version 1.8.1:
+ - Fix linting issues, drop deprecated Qt6 flag
+ Version 1.8:
+ - Fix metadata for QGIS 4
+ Version 1.7:
+ - Support for Qt 6
+ Version 1.6:
+ - Add warning on QGIS < 3.34.4 due to bug in project saving
+ - Improved warning message on unsupported geometry types
+ Version 1.5:
+ - Clear filter when a new project is loaded or created
+ Version 1.4:
+ - Add padding when zooming to filter geometry (thanks pathmapper!)
+ - Add plugin name to messages in message bar
+ - Fix crash when user edited style without having an active filter
+ Version 1.3.1:
+ - Fix raster layer exception in curved geometry check
+ Version 1.3:
+ - Add warning message for layers with unsupported geometry type
+ Version 1.2:
+ - Keep existing filter on layers that are added pre-filtered
+ - Don't crash in exclusion dialog if raster layers exist
+ - Ensure valid geometries when using multiple input geometries
+ - Fix retrieval of file path and layer name for processing results
+ Version 1.1:
+ - First public release
+
+homepage=https://github.com/WhereGroup/spatial_filter
+category=Plugins
+icon=icons/icon.png
+experimental=False
+deprecated=False
+server=False
\ No newline at end of file
diff --git a/models.py b/models.py
new file mode 100644
index 0000000..cd4ef59
--- /dev/null
+++ b/models.py
@@ -0,0 +1,61 @@
+from qgis.PyQt.QtCore import QAbstractListModel, Qt, QModelIndex
+from qgis.PyQt.QtGui import QStandardItemModel, QStandardItem
+
+from qgis.core import QgsProject, QgsFeatureSource, QgsApplication, QgsMapLayer
+
+from .filters import loadAllFilterDefinitions
+from .helpers import hasLayerException, isLayerSupported
+
+
+DataRole = Qt.ItemDataRole.UserRole + 1
+
+
+class FilterModel(QAbstractListModel):
+
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self.filters = loadAllFilterDefinitions()
+ self.filters.sort()
+
+ def data(self, index, role=Qt.ItemDataRole.DisplayRole):
+ if role == Qt.ItemDataRole.DisplayRole:
+ return self.filters[index.row()].name
+ elif role == DataRole:
+ return self.filters[index.row()]
+
+ def rowCount(self, parent=QModelIndex()):
+ return len(self.filters)
+
+ def removeRows(self, row: int, count: int = 1, parent: QModelIndex = ...) -> bool:
+ self.beginRemoveRows(QModelIndex(), row, row + count - 1)
+ self.filters = self.filters[:row] + self.tableData[row + count:]
+ self.endRemoveRows()
+ return True
+
+
+class LayerModel(QStandardItemModel):
+ def __init__(self, parent=None):
+ super(LayerModel, self).__init__(parent)
+
+ for layer in [layerNode.layer() for layerNode in QgsProject.instance().layerTreeRoot().findLayers()]:
+
+ item = QStandardItem(layer.name())
+ item.setData(layer, role=DataRole)
+
+ if isLayerSupported(layer):
+ item.setEnabled(True)
+ if layer.dataProvider().hasSpatialIndex() == QgsFeatureSource.SpatialIndexPresence.SpatialIndexNotPresent:
+ item.setToolTip(self.tr('Layer has no spatial index'))
+ item.setIcon(QgsApplication.getThemeIcon('/mIconWarning.svg'))
+ else:
+ item.setEnabled(False)
+ item.setToolTip(self.tr('Layer type is not supported'))
+ self.initItemCheckState(layer, item)
+ self.appendRow(item)
+
+ def initItemCheckState(self, layer: QgsMapLayer, item: QStandardItem):
+ item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
+ if hasLayerException(layer):
+ item.setCheckState(Qt.CheckState.Checked)
+ else:
+ item.setCheckState(Qt.CheckState.Unchecked)
diff --git a/settings.py b/settings.py
new file mode 100644
index 0000000..2e8e59f
--- /dev/null
+++ b/settings.py
@@ -0,0 +1,23 @@
+from qgis.PyQt.QtCore import QCoreApplication
+
+
+def tr(message):
+ return QCoreApplication.translate('@default', message)
+
+
+LOCALIZED_PLUGIN_NAME = tr("Spatial Filter") # for use in messages etc.
+
+GROUP = 'SpatialFilter' # The section name for filter definitions stored in QSettings
+GROUP_SYMBOL = 'SpatialFilterSymbol' # Section to store symbol settings
+LAYER_EXCEPTION_VARIABLE = 'SpatialFilterException'
+
+FILTER_SYMBOL = {"color": "#0000ff", "outline_color": "#000000", "opacity": 0.5}
+
+# The filter string might contain user-specific parts so we surround *our* filter
+# string with text markers
+FILTER_COMMENT_START = '/* SpatialFilter Plugin Start */'
+FILTER_COMMENT_STOP = '/* SpatialFilter Plugin Stop */'
+
+# The QGIS Storage Types that can be filtered by the plugin
+SUPPORTED_STORAGE_TYPES = ['POSTGRESQL DATABASE WITH POSTGIS EXTENSION', 'GPKG', 'SQLITE']
+SUPPORTED_PROVIDER_TYPES = ['postgres', 'wfs', 'oapif']
diff --git a/spatial_filter.py b/spatial_filter.py
new file mode 100644
index 0000000..e15167c
--- /dev/null
+++ b/spatial_filter.py
@@ -0,0 +1,57 @@
+"""
+/***************************************************************************
+ SpatialFilter
+ A QGIS plugin
+ This plugin applies spatial filters to layers for performance and efficiency.
+
+ Base was generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
+ -------------------
+ begin : 2022-10-16
+ copyright : (C) 2022 Wheregroup GmbH
+ email : info@wheregroup.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. *
+ * *
+ ***************************************************************************/
+"""
+from qgis.PyQt.QtCore import QLocale, QSettings, QTranslator, QCoreApplication
+
+import os.path
+
+
+class SpatialFilter:
+
+ def __init__(self, iface):
+ self.iface = iface
+ self.plugin_dir = os.path.dirname(__file__)
+ locale = QSettings().value('locale/userLocale', QLocale().name())[0:2]
+ locale_path = os.path.join(self.plugin_dir, 'i18n', f'spatial_filter_{locale}.qm')
+
+ if os.path.exists(locale_path):
+ self.translator = QTranslator()
+ self.translator.load(locale_path)
+ QCoreApplication.installTranslator(self.translator)
+
+ def initGui(self):
+ # we import just now because we need the QCoreApplication translator
+ # to be installed already (e.g. for the LOCALIZED_PLUGIN_NAME)
+ from .controller import FilterController
+ from .helpers import warnAboutQgisBugProjectSaving
+ from .widgets import FilterToolbar
+
+ self.toolbar = FilterToolbar(FilterController(), self.iface.mainWindow())
+ self.iface.mainWindow().addToolBar(self.toolbar)
+
+ warnAboutQgisBugProjectSaving()
+
+ def unload(self):
+ self.toolbar.hideFilterGeom()
+ self.toolbar.controller.removeFilter()
+ self.toolbar.controller.disconnectSignals()
+ self.toolbar.deleteLater()
diff --git a/ui/named_filters_dialog.ui b/ui/named_filters_dialog.ui
new file mode 100644
index 0000000..f801067
--- /dev/null
+++ b/ui/named_filters_dialog.ui
@@ -0,0 +1,125 @@
+
+
+ ManageFiltersDialog
+
+
+
+ 0
+ 0
+ 571
+ 527
+
+
+
+ Named spatial filters
+
+
+
+
+
+
+ 0
+ 0
+
+
+
+ Active Filter:
+
+
+
+
+
+
+
+
+
+ Save
+
+
+
+
+
+
+
+ 0
+ 0
+
+
+
+ Named Filters:
+
+
+
+
+
+
+ QAbstractItemView::NoEditTriggers
+
+
+
+
+
+
+
+
+ false
+
+
+ Apply
+
+
+
+
+
+
+ false
+
+
+ Delete
+
+
+
+
+
+
+ Qt::Vertical
+
+
+
+ 20
+ 40
+
+
+
+
+
+
+
+ Close
+
+
+
+
+
+
+
+
+
+
+ buttonClose
+ clicked()
+ ManageFiltersDialog
+ close()
+
+
+ 520
+ 503
+
+
+ 285
+ 263
+
+
+
+
+
diff --git a/widgets.py b/widgets.py
new file mode 100644
index 0000000..eb927c0
--- /dev/null
+++ b/widgets.py
@@ -0,0 +1,519 @@
+import os
+
+from typing import Optional
+
+from qgis.PyQt import uic
+from qgis.PyQt.QtCore import Qt, pyqtSignal
+from qgis.PyQt.QtGui import QIcon
+from qgis.PyQt.QtWidgets import (
+ QToolBar,
+ QWidget,
+ QAction,
+ QPushButton,
+ QLineEdit,
+ QDialog,
+ QVBoxLayout,
+ QSizePolicy,
+ QDialogButtonBox, QListWidget, QMenu, QActionGroup, QLabel, QFrame, QTreeView
+)
+
+from qgis.gui import QgsExtentWidget, QgsRubberBand, QgsSymbolButton
+from qgis.core import QgsApplication, QgsGeometry, QgsProject, QgsCoordinateReferenceSystem, QgsCoordinateTransform, \
+ QgsWkbTypes, QgsSymbol, QgsFillSymbol, QgsSettings, QgsVectorLayer
+from qgis.utils import iface
+
+from .helpers import removeFilterFromLayer, setLayerException, hasLayerException, addFilterToLayer, class_for_name
+from .controller import FilterController
+from .models import FilterModel, LayerModel, DataRole
+from .filters import Predicate, RemoteFilterStrategy, FilterDefinition, askApply, deleteFilterDefinition, saveFilterDefinition
+from .settings import GROUP_SYMBOL, FILTER_SYMBOL
+
+
+class ExtentDialog(QDialog):
+ def __init__(self, controller: FilterController, parent: Optional[QWidget] = None) -> None:
+ super().__init__(parent=parent)
+ self.controller = controller
+ self.setObjectName("mExtentDialog")
+ self.setWindowTitle(self.tr("Set rectangular filter geometry"))
+ self.setupUi()
+ self.extentWidget.setOriginalExtent(iface.mapCanvas().extent(), QgsProject.instance().crs())
+ self.extentWidget.setMapCanvas(iface.mapCanvas())
+
+ def setupUi(self):
+ self.resize(700, 80)
+ sizePolicy = QSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Preferred)
+ sizePolicy.setHorizontalStretch(0)
+ sizePolicy.setVerticalStretch(0)
+ sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
+ self.setSizePolicy(sizePolicy)
+ self.verticalLayout = QVBoxLayout(self)
+ self.extentWidget = QgsExtentWidget(self)
+ self.verticalLayout.addWidget(self.extentWidget)
+ self.buttonBox = QDialogButtonBox(self)
+ self.buttonBox.setOrientation(Qt.Orientation.Horizontal)
+ self.buttonBox.setStandardButtons(QDialogButtonBox.StandardButton.Cancel | QDialogButtonBox.StandardButton.Ok)
+ self.verticalLayout.addWidget(self.buttonBox)
+ self.buttonBox.accepted.connect(self.accept)
+ self.buttonBox.rejected.connect(self.reject)
+
+ def reset(self):
+ self.extentWidget.clear()
+ self.extentWidget.setOriginalExtent(iface.mapCanvas().extent(), QgsProject.instance().crs())
+ self.extentWidget.setMapCanvas(iface.mapCanvas())
+
+ def accept(self) -> None:
+ if self.extentWidget.isValid() and QgsGeometry.fromRect(self.extentWidget.outputExtent()).isGeosValid():
+ self.controller.initFilter()
+ self.controller.currentFilter.name = self.tr('New filter from extent')
+ self.controller.currentFilter.wkt = QgsGeometry.fromRect(self.extentWidget.outputExtent()).asWkt()
+ self.controller.currentFilter.crs = self.extentWidget.outputCrs()
+ self.controller.refreshFilter()
+ super().accept()
+
+
+class LayerExceptionsDialog(QDialog):
+ def __init__(self, controller: FilterController, parent: Optional[QWidget] = None) -> None:
+ super().__init__(parent=parent)
+ self.controller = controller
+ self.setObjectName("mLayerExceptionsDialog")
+ self.setWindowTitle(self.tr("Exclude layers from filter"))
+ self.setupUi()
+ self.listView.setModel(LayerModel())
+ self.adjustSize()
+
+ def setupUi(self):
+ sizePolicy = QSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Preferred)
+ sizePolicy.setHorizontalStretch(0)
+ sizePolicy.setVerticalStretch(0)
+ sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
+ self.setSizePolicy(sizePolicy)
+ self.verticalLayout = QVBoxLayout(self)
+ self.listView = QTreeView(self)
+ self.listView.header().hide()
+ self.verticalLayout.addWidget(self.listView)
+ self.buttonBox = QDialogButtonBox(self)
+ self.buttonBox.setOrientation(Qt.Orientation.Horizontal)
+ self.buttonBox.setStandardButtons(QDialogButtonBox.StandardButton.Cancel | QDialogButtonBox.StandardButton.Ok)
+ self.verticalLayout.addWidget(self.buttonBox)
+ self.buttonBox.accepted.connect(self.accept)
+ self.buttonBox.rejected.connect(self.reject)
+
+ def accept(self) -> None:
+ model = self.listView.model()
+ for index in range(model.rowCount()):
+ item = model.item(index)
+ layer = item.data()
+ self.setExceptionForLayer(layer, bool(item.checkState() == Qt.CheckState.Checked))
+ super().accept()
+
+ def setExceptionForLayer(self, layer: QgsVectorLayer, exception: bool) -> None:
+ if exception:
+ removeFilterFromLayer(layer)
+ if not exception and hasLayerException(layer) and self.controller.hasValidFilter():
+ addFilterToLayer(layer, self.controller.currentFilter)
+ setLayerException(layer, exception)
+
+
+FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'ui', 'named_filters_dialog.ui'))
+
+
+class ManageFiltersDialog(QDialog, FORM_CLASS):
+ lineEditActiveFilter: QLineEdit
+ listViewNamedFilters: QListWidget
+ buttonSave: QPushButton
+ buttonApply: QPushButton
+ buttonDelete: QPushButton
+ buttonClose: QPushButton
+
+ def __init__(self, controller, parent: Optional[QWidget] = None) -> None:
+ super().__init__(parent=parent)
+ self.controller = controller
+ self.setupUi(self)
+ self.lineEditActiveFilter.setText(self.controller.currentFilter.name if self.controller.currentFilter else '')
+ self.setupConnections()
+ self.setModel()
+
+ def setupConnections(self):
+ self.buttonSave.clicked.connect(self.onSaveClicked)
+ self.buttonApply.clicked.connect(self.onApplyClicked)
+ self.buttonDelete.clicked.connect(self.onDeleteClicked)
+
+ def setModel(self):
+ self.filterModel = FilterModel()
+ self.listViewNamedFilters.setModel(self.filterModel)
+ self.listViewNamedFilters.selectionModel().selectionChanged.connect(self.onSelectionChanged)
+ self.onSelectionChanged()
+
+ def onSelectionChanged(self):
+ hasSelection = self.listViewNamedFilters.selectionModel().hasSelection()
+ self.buttonApply.setEnabled(hasSelection)
+ self.buttonDelete.setEnabled(hasSelection)
+
+ def onApplyClicked(self):
+ if self.controller.currentFilter and not self.controller.currentFilter.isSaved and not askApply():
+ return
+ selectedIndex = self.listViewNamedFilters.selectedIndexes()[0]
+ filterDefinition = self.filterModel.data(index=selectedIndex, role=DataRole)
+ filterDefinitionCopy = filterDefinition.copy()
+ self.lineEditActiveFilter.setText(filterDefinitionCopy.name)
+ self.controller.currentFilter = filterDefinitionCopy
+ self.controller.refreshFilter()
+
+ def onDeleteClicked(self):
+ selectedIndex = self.listViewNamedFilters.selectedIndexes()[0]
+ filterDefinition = self.filterModel.data(index=selectedIndex, role=DataRole)
+ deleteFilterDefinition(filterDefinition)
+ self.setModel()
+ self.controller.refreshFilter()
+
+ def onSaveClicked(self):
+ if not self.controller.hasValidFilter():
+ return
+ text = self.lineEditActiveFilter.text()
+ namedFilter = self.controller.currentFilter.copy()
+ namedFilter.name = text
+ saveFilterDefinition(namedFilter)
+ self.setModel()
+
+
+class PredicateButton(QPushButton):
+ MENU_WIDTH = 250
+
+ predicateChanged = pyqtSignal(Predicate)
+ bboxChanged = pyqtSignal(bool)
+ remoteStrategyChanged = pyqtSignal(object)
+
+ def __init__(self, parent: Optional[QWidget] = None) -> None:
+ super().__init__(parent=parent)
+ predicateActionNames = {
+ Predicate.INTERSECTS: self.tr('intersects'),
+ Predicate.WITHIN: self.tr('within'),
+ Predicate.DISJOINT: self.tr('disjoint'),
+ }
+ self.setObjectName('mPredicateSelectAction')
+ self.setToolTip(self.tr('Geometric predicate'))
+ self.setIcon(QgsApplication.getThemeIcon('/mActionOptions.svg'))
+ self.menu = QMenu(parent=parent)
+
+ self.menu.addSection(self.tr('Geometric Predicate'))
+ self.predicateActionGroup = QActionGroup(self)
+ self.predicateActionGroup.setExclusive(True)
+ for predicate in Predicate:
+ action = QAction(self.menu)
+ action.setCheckable(True)
+ if predicate == Predicate.INTERSECTS:
+ action.setChecked(True)
+ action.setText(predicateActionNames.get(predicate))
+ action.predicate = predicate
+ action.triggered.connect(self.onPredicateChanged)
+ self.predicateActionGroup.addAction(action)
+ self.menu.addActions(self.predicateActionGroup.actions())
+
+ self.menu.addSection(self.tr('Object of comparison'))
+ self.bboxActionGroup = QActionGroup(self)
+ self.bboxActionGroup.setExclusive(True)
+ self.bboxTrueAction = QAction(self.menu)
+ self.bboxTrueAction.setCheckable(True)
+ self.bboxTrueAction.setText(self.tr('BBOX'))
+ self.bboxTrueAction.bbox = True
+ self.bboxTrueAction.triggered.connect(self.onBboxChanged)
+ self.bboxFalseAction = QAction(self.menu)
+ self.bboxFalseAction.setCheckable(True)
+ self.bboxFalseAction.setChecked(True)
+ self.bboxFalseAction.setText(self.tr('GEOM'))
+ self.bboxFalseAction.bbox = False
+ self.bboxFalseAction.triggered.connect(self.onBboxChanged)
+
+ self.bboxActionGroup.addAction(self.bboxTrueAction)
+ self.bboxActionGroup.addAction(self.bboxFalseAction)
+ self.menu.addActions(self.bboxActionGroup.actions())
+
+
+
+ self.menu.addSection(self.tr('WFS / OGC API Features'))
+ self.remoteStrategyActionGroup = QActionGroup(self)
+ self.remoteStrategyActionGroup.setExclusive(True)
+ remote_strategy_names = {
+ RemoteFilterStrategy.AUTO: self.tr('Automatisch (exakt → vereinfacht → BBOX)'),
+ RemoteFilterStrategy.EXACT: self.tr('Immer exakte Geometrie verwenden'),
+ RemoteFilterStrategy.SIMPLIFIED: self.tr('Vereinfachte Geometrie bevorzugen'),
+ RemoteFilterStrategy.BBOX: self.tr('Immer BBOX verwenden'),
+ }
+ for strategy in RemoteFilterStrategy:
+ action = QAction(self.menu)
+ action.setCheckable(True)
+ if strategy == RemoteFilterStrategy.AUTO:
+ action.setChecked(True)
+ action.setText(remote_strategy_names.get(strategy))
+ action.remote_strategy = strategy
+ action.triggered.connect(self.onRemoteStrategyChanged)
+ self.remoteStrategyActionGroup.addAction(action)
+ self.menu.addActions(self.remoteStrategyActionGroup.actions())
+
+ self.menu.setMinimumWidth(self.MENU_WIDTH)
+ self.setMenu(self.menu)
+ self.setFlat(True)
+
+ def onPredicateChanged(self):
+ self.predicateChanged.emit(self.getPredicate())
+
+ def getPredicate(self) -> Predicate:
+ currentAction = self.predicateActionGroup.checkedAction()
+ if currentAction:
+ return currentAction.predicate
+
+ def setCurrentPredicateAction(self, predicate: int):
+ for action in self.predicateActionGroup.actions():
+ if action.predicate == Predicate(predicate):
+ action.triggered.disconnect()
+ action.setChecked(True)
+ action.triggered.connect(self.onPredicateChanged)
+
+ def setCurrentBboxAction(self, bbox: bool):
+ action = self.bboxTrueAction if bbox else self.bboxFalseAction
+ action.triggered.disconnect()
+ action.setChecked(True)
+ action.triggered.connect(self.onBboxChanged)
+
+ def onBboxChanged(self):
+ self.bboxChanged.emit(self.getBbox())
+
+ def getBbox(self):
+ currentAction = self.bboxActionGroup.checkedAction()
+ if currentAction:
+ return currentAction.bbox
+
+ def onRemoteStrategyChanged(self):
+ self.remoteStrategyChanged.emit(self.getRemoteStrategy())
+
+ def getRemoteStrategy(self) -> RemoteFilterStrategy:
+ currentAction = self.remoteStrategyActionGroup.checkedAction()
+ if currentAction:
+ return currentAction.remote_strategy
+
+ def setCurrentRemoteStrategyAction(self, strategy: int):
+ for action in self.remoteStrategyActionGroup.actions():
+ if action.remote_strategy == RemoteFilterStrategy(strategy):
+ action.triggered.disconnect()
+ action.setChecked(True)
+ action.triggered.connect(self.onRemoteStrategyChanged)
+
+
+class FilterToolbar(QToolBar):
+ LAYOUT_SPACING = 5
+ FILTER_LABEL_WIDTH = 150
+ BUTTON_MIN_WIDTH = 50
+
+ def __init__(self, controller: FilterController, parent: Optional[QWidget] = None) -> None:
+ super().__init__(parent=parent)
+ self.controller = controller
+ self.showGeomStatus = True
+ self.extentDialog = None
+ self.symbol = self.loadFilterSymbol()
+ self.setWindowTitle(self.tr('Filter Toolbar'))
+ self.setObjectName('mFilterToolbar')
+ self.setupUi()
+ self.setupConnections()
+ self.controller.refreshFilter()
+
+ def setupUi(self):
+ self.layout().setSpacing(self.LAYOUT_SPACING)
+
+ self.removeFilterAction = QAction(self)
+ self.removeFilterAction.setIcon(QgsApplication.getThemeIcon('/mActionDeleteModelComponent.svg'))
+ self.removeFilterAction.setToolTip(self.tr('Remove current filter'))
+ self.addAction(self.removeFilterAction)
+
+ self.labelFilterName = QLabel(self)
+ self.labelFilterName.setFrameShape(QFrame.Shape.Panel)
+ self.labelFilterName.setFrameShadow(QFrame.Shadow.Sunken)
+ self.labelFilterName.setMinimumWidth(self.FILTER_LABEL_WIDTH)
+ self.addWidget(self.labelFilterName)
+
+ self.toggleVisibilityAction = QAction(self)
+ visibilityIcon = QIcon()
+ pixmapOn = QgsApplication.getThemeIcon("/mActionShowAllLayers.svg").pixmap(self.iconSize())
+ pixmapOff = QgsApplication.getThemeIcon("/mActionHideAllLayers.svg").pixmap(self.iconSize())
+ visibilityIcon.addPixmap(pixmapOn, QIcon.Mode.Normal, QIcon.State.On)
+ visibilityIcon.addPixmap(pixmapOff, QIcon.Mode.Normal, QIcon.State.Off)
+ self.toggleVisibilityAction.setIcon(visibilityIcon)
+ self.toggleVisibilityAction.setCheckable(True)
+ self.toggleVisibilityAction.setChecked(True)
+ self.toggleVisibilityAction.setToolTip(self.tr('Show filter geometry'))
+ self.addAction(self.toggleVisibilityAction)
+
+ self.zoomToFilterAction = QAction(self)
+ self.zoomToFilterAction.setIcon(QgsApplication.getThemeIcon('/mActionZoomToArea.svg'))
+ self.zoomToFilterAction.setToolTip(self.tr('Zoom to filter'))
+ self.addAction(self.zoomToFilterAction)
+
+ self.styleFilterButton = QgsSymbolButton(self, self.tr('Filter style'))
+ self.styleFilterButton.setMinimumWidth(self.BUTTON_MIN_WIDTH)
+ self.styleFilterButton.setSymbolType(QgsSymbol.SymbolType.Fill)
+ self.styleFilterButton.setSymbol(self.symbol.clone())
+ self.styleFilterButton.setDialogTitle(self.tr('Style filter'))
+ self.addWidget(self.styleFilterButton)
+
+ self.addSeparator()
+
+ self.filterFromExtentAction = QAction(self)
+ self.filterFromExtentAction.setIcon(QgsApplication.getThemeIcon('/mActionAddBasicRectangle.svg'))
+ self.filterFromExtentAction.setToolTip(self.tr('Rectangular filter'))
+ self.addAction(self.filterFromExtentAction)
+
+ self.filterFromSelectionAction = QAction(self)
+ self.filterFromSelectionAction.setIcon(QgsApplication.getThemeIcon('/mActionAddPointCloudLayer.svg'))
+ self.filterFromSelectionAction.setToolTip(self.tr('Filter from selected features'))
+ self.addAction(self.filterFromSelectionAction)
+
+ self.sketchingToolAction = QAction(self)
+ self.sketchingToolAction.setIcon(QgsApplication.getThemeIcon('/mActionAddPolygon.svg'))
+ self.sketchingToolAction.setToolTip(self.tr('Draw a filter polygon on the canvas'))
+ self.addAction(self.sketchingToolAction)
+
+ self.addSeparator()
+
+ self.predicateButton = PredicateButton(self)
+ self.predicateButton.setIconSize(self.iconSize())
+ self.addWidget(self.predicateButton)
+
+ self.layerExceptionsAction = QAction(self)
+ self.layerExceptionsAction.setIcon(QgsApplication.getThemeIcon('/mLayoutItemLegend.svg'))
+ self.layerExceptionsAction.setToolTip(self.tr('Exclude layers from filter'))
+ self.addAction(self.layerExceptionsAction)
+
+ self.manageFiltersAction = QAction(self)
+ self.manageFiltersAction.setIcon(QgsApplication.getThemeIcon('/mIconListView.svg'))
+ self.manageFiltersAction.setToolTip(self.tr('Manage filters'))
+ self.addAction(self.manageFiltersAction)
+
+ def setupConnections(self):
+ self.removeFilterAction.triggered.connect(self.onRemoveFilterClicked)
+ self.filterFromExtentAction.triggered.connect(self.startFilterFromExtentDialog)
+ self.layerExceptionsAction.triggered.connect(self.startLayerExceptionsDialog)
+ self.manageFiltersAction.triggered.connect(self.startManageFiltersDialog)
+ self.predicateButton.predicateChanged.connect(self.controller.setFilterPredicate)
+ self.predicateButton.bboxChanged.connect(self.controller.setFilterBbox)
+ self.predicateButton.remoteStrategyChanged.connect(self.controller.setRemoteFilterStrategy)
+ self.filterFromSelectionAction.triggered.connect(self.controller.setFilterFromSelection)
+ self.controller.filterChanged.connect(self.onFilterChanged)
+ self.toggleVisibilityAction.toggled.connect(self.onShowGeom)
+ self.sketchingToolAction.triggered.connect(self.controller.startSketchingTool)
+ self.styleFilterButton.changed.connect(self.onFilterStyleChanged)
+ self.zoomToFilterAction.triggered.connect(self.zoomToFilter)
+
+ def onRemoveFilterClicked(self):
+ self.controller.removeFilter()
+
+ def onFilterChanged(self, filterDef: Optional[FilterDefinition]):
+ if filterDef:
+ self.predicateButton.setCurrentPredicateAction(filterDef.predicate)
+ self.predicateButton.setCurrentBboxAction(filterDef.bbox)
+ self.predicateButton.setCurrentRemoteStrategyAction(filterDef.remote_strategy)
+ self.removeFilterAction.setEnabled(True)
+ self.labelFilterName.setEnabled(True)
+ self.toggleVisibilityAction.setEnabled(True)
+ self.predicateButton.setEnabled(True)
+ self.layerExceptionsAction.setEnabled(True)
+ self.zoomToFilterAction.setEnabled(True)
+ if not self.showGeomStatus:
+ self.toggleVisibilityAction.trigger()
+ else:
+ self.predicateButton.setCurrentPredicateAction(Predicate.INTERSECTS)
+ self.predicateButton.setCurrentBboxAction(False)
+ self.predicateButton.setCurrentRemoteStrategyAction(RemoteFilterStrategy.AUTO)
+ self.removeFilterAction.setEnabled(False)
+ self.labelFilterName.setEnabled(False)
+ self.toggleVisibilityAction.setEnabled(False)
+ self.predicateButton.setEnabled(False)
+ self.layerExceptionsAction.setEnabled(False)
+ self.zoomToFilterAction.setEnabled(False)
+ self.changeDisplayedName(filterDef)
+ self.onShowGeom(self.showGeomStatus)
+
+ def changeDisplayedName(self, filterDef: FilterDefinition):
+ if filterDef and filterDef.isValid:
+ self.labelFilterName.setText(filterDef.name)
+ else:
+ self.labelFilterName.setText(self.tr("No filter geometry set"))
+
+ def startFilterFromExtentDialog(self):
+ if not self.extentDialog:
+ self.extentDialog = ExtentDialog(self.controller, parent=self)
+ self.extentDialog.reset()
+ self.extentDialog.show()
+
+ def startLayerExceptionsDialog(self):
+ dlg = LayerExceptionsDialog(self.controller, parent=self)
+ dlg.exec()
+
+ def startManageFiltersDialog(self):
+ dlg = ManageFiltersDialog(self.controller, parent=self)
+ dlg.exec()
+
+ def onFilterStyleChanged(self, *args, **kwargs):
+ # Always use clone to assign symbols, otherwise QGIS will crash
+ self.symbol = self.styleFilterButton.symbol().clone()
+ self.saveFilterSymbol()
+
+ if self.showGeomStatus and self.controller.currentFilter:
+ self.hideFilterGeom()
+ self.showFilterGeom()
+
+ def onShowGeom(self, checked: bool):
+ self.showGeomStatus = checked
+ if checked and self.controller.currentFilter:
+ tooltip = self.tr('Hide filter geometry')
+ self.hideFilterGeom()
+ self.showFilterGeom()
+ else:
+ tooltip = self.tr('Show filter geometry')
+ self.hideFilterGeom()
+ self.toggleVisibilityAction.setToolTip(tooltip)
+
+ def showFilterGeom(self):
+ """Get filterRubberBand geometry, transform it and show it on canvas"""
+ filterRubberBand = QgsRubberBand(iface.mapCanvas(), QgsWkbTypes.GeometryType.PolygonGeometry)
+ filterGeom = self.controller.currentFilter.geometry
+ if self.controller.currentFilter.bbox:
+ filterGeom = self.controller.currentFilter.boxGeometry
+ filterCrs = self.controller.currentFilter.crs
+ projectCrs = QgsCoordinateReferenceSystem(QgsProject.instance().crs())
+ filterProj = QgsCoordinateTransform(filterCrs, projectCrs, QgsProject.instance())
+ filterGeom.transform(filterProj)
+ filterRubberBand.setToGeometry(filterGeom, None)
+ filterRubberBand.setSymbol(self.symbol.clone())
+ # Append to global variable
+ self.controller.rubberBands.append(filterRubberBand)
+
+ def hideFilterGeom(self):
+ """Removes potentially existing rubber bands"""
+ while self.controller.rubberBands:
+ rubberBand = self.controller.rubberBands.pop()
+ iface.mapCanvas().scene().removeItem(rubberBand)
+
+ def saveFilterSymbol(self):
+ """Save the current symbol of the filter into the profile settings"""
+ symbol = self.symbol.clone()
+ # Note: This does not store sub-layers of e.g. a Marker Fill's marker symbols!
+ symbol_layers = [[type(sl).__name__, sl.properties()] for sl in symbol.symbolLayers()]
+ QgsSettings().setValue(GROUP_SYMBOL + "/Symbol", symbol_layers)
+
+ def loadFilterSymbol(self):
+ """Load setting for filter symbol from profile settings"""
+ stored_symbol_layers = QgsSettings().value(GROUP_SYMBOL + "/Symbol")
+ if stored_symbol_layers:
+ # awkward but non-crashing creation with proper object ownerships...
+ symbol = QgsFillSymbol()
+ symbol.deleteSymbolLayer(0)
+ for symbol_layer_type, properties in stored_symbol_layers:
+ symbol_layer = class_for_name("qgis.core", symbol_layer_type).create(properties)
+ symbol.appendSymbolLayer(symbol_layer.clone())
+ return symbol
+ else:
+ return QgsFillSymbol.createSimple(FILTER_SYMBOL)
+
+ def zoomToFilter(self):
+ if self.controller.hasValidFilter():
+ iface.mapCanvas().zoomToFeatureExtent(self.controller.currentFilter.geometry.boundingBox())
+ iface.mapCanvas().refresh()