init plugin

This commit is contained in:
Colas Geier 2026-03-19 14:06:08 +01:00
commit 5974778b0a
65 changed files with 6606 additions and 0 deletions

131
.gitignore vendored Normal file
View File

@ -0,0 +1,131 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
junit/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
docs/_apidoc/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# -- CUSTOM ----
qgis_plugin_templater_debug.json
*.zip
*.qm

78
.pre-commit-config.yaml Normal file
View File

@ -0,0 +1,78 @@
exclude: ".venv|__pycache__|tests/dev/|tests/fixtures/"
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
- id: check-added-large-files
args:
- --maxkb=500
- id: check-case-conflict
- id: check-illegal-windows-names
- id: check-toml
- id: check-xml
- id: check-yaml
- id: detect-private-key
- id: end-of-file-fixer
- id: fix-byte-order-marker
- id: trailing-whitespace
args:
- --markdown-linebreak-ext=md
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: "v0.13.3"
hooks:
- id: ruff
args:
- --fix
- --target-version=py39
types_or:
- python
- pyi
- id: ruff-format
args:
- --line-length=88
- --target-version=py39
types_or:
- python
- pyi
# take care, it could conflicts with ruff-format
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 25.9.0
hooks:
- id: black
args:
- --target-version=py39
# Disabled until PyQt translation support f-strings
# - repo: https://github.com/asottile/pyupgrade
# rev: v3.15.0
# hooks:
# - id: pyupgrade
# args:
# - "--py39-plus"
- repo: https://github.com/pycqa/isort
rev: 6.1.0
hooks:
- id: isort
args:
- --profile
- black
- --filter-files
- repo: https://github.com/pycqa/flake8
rev: 7.3.0
hooks:
- id: flake8
files: ^gn_tools/.*\.py$
additional_dependencies:
- flake8-qgis
args:
[
"--config=setup.cfg",
"--select=E9,F63,F7,F82,QGS101,QGS102,QGS103,QGS104,QGS106",
]

13
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,13 @@
{
"recommendations": [
"davidanson.vscode-markdownlint",
"ms-python.black-formatter",
"ms-python.isort",
"ms-python.python",
"njpwerner.autodocstring",
"redhat.vscode-yaml",
"zhoufeng.pyqt-integration"
]
}

45
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,45 @@
{
// Editor
"editor.bracketPairColorization.enabled": true,
"editor.guides.bracketPairs": "active",
"files.associations": {
"./requirements/*.txt": "pip-requirements",
"metadata.txt": "ini",
"**/*.model3": "xml",
"**/*.ts": "xml",
"**/*.ui": "xml"
},
// Markdown
"markdown.updateLinksOnFileMove.enabled": "prompt",
"markdown.updateLinksOnFileMove.enableForDirectories": true,
"markdown.validate.enabled": true,
"markdown.validate.fileLinks.markdownFragmentLinks": "warning",
"markdown.validate.fragmentLinks.enabled": "warning",
"[markdown]": {
"editor.defaultFormatter": "DavidAnson.vscode-markdownlint",
"files.trimTrailingWhitespace": false,
},
// Python
"python.analysis.autoFormatStrings": false, // breaking PyQt translation
"python.analysis.typeCheckingMode": "basic",
// "python.defaultInterpreterPath": ".venv/bin/python",
"python.terminal.activateEnvInCurrentTerminal": true,
"python.terminal.activateEnvironment": true,
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports":"explicit"
},
"editor.rulers": [
88
],
"editor.wordWrapColumn": 88,
},
"python.testing.unittestEnabled": true,
"python.testing.pytestEnabled": true,
// Linter
// Extensions
"autoDocstring.docstringFormat": "sphinx"
}

37
.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,37 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Upgrade dependencies - Development",
"type": "shell",
"osx": {
"command": "${config:python.defaultInterpreterPath} -m pip install -U -r requirements/development.txt"
},
"windows": {
"command": "${config:python.defaultInterpreterPath} -m pip install -U -r requirements/development.txt"
},
"linux": {
"command": "${config:python.defaultInterpreterPath} -m pip install -U -r requirements/development.txt"
},
"problemMatcher": []
},
{
"label": "Translation Update",
"type": "shell",
"linux": {
"command": "pylupdate5 -verbose gn_tools/resources/i18n/plugin_translation.pro"
},
"problemMatcher": []
},
{
"label": "Translation Compile",
"type": "shell",
"linux": {
"command": "lrelease gn_tools/resources/i18n/*.ts "
},
"problemMatcher": []
}
]
}

22
CHANGELOG.md Normal file
View File

@ -0,0 +1,22 @@
# CHANGELOG
The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/).
<!--
Unreleased
## version_tag - YYYY-DD-mm
### Added
### Changed
### Removed
-->
## 0.1.0 - 2026-02-16
- First release
- Generated with the [QGIS Plugins templater](https://oslandia.gitlab.io/qgis/template-qgis-plugin/)

82
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,82 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement on `geomatique@cen-isere.org (Conservatoire d'espaces naturels Isère)` .
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at <https://www.contributor-covenant.org/version/2/0/code_of_conduct.html>.
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at <https://www.contributor-covenant.org/faq>. Translations are available at <https://www.contributor-covenant.org/translations>.

20
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,20 @@
# Contributing Guidelines
First off, thanks for considering to contribute to this project!
These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request.
## Git hooks
We use git hooks through [pre-commit](https://pre-commit.com/) to enforce and automatically check some "rules". Please install them (`pre-commit install`) before to push any commit.
See the relevant configuration file: `.pre-commit-config.yaml`.
## Code Style
Make sure your code *roughly* follows [PEP-8](https://www.python.org/dev/peps/pep-0008/) and keeps things consistent with the rest of the code:
- docstrings: [sphinx-style](https://sphinx-rtd-tutorial.readthedocs.io/en/latest/docstrings.html#the-sphinx-docstring-format) is used to write technical documentation.
- formatting: [black](https://black.readthedocs.io/) is used to automatically format the code without debate.
- sorted imports: [isort](https://pycqa.github.io/isort/) is used to sort imports

677
LICENSE Normal file
View File

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

126
README.md Normal file
View File

@ -0,0 +1,126 @@
# gn_tools - QGIS Plugin
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://pycqa.github.io/isort/)
[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)](https://github.com/pre-commit/pre-commit)
## Generated options
### Plugin
> Here is a list of the options you picked when creating the plugin with the cookiecutter template.
| Cookiecutter option | Picked value |
| :------------------ | :----------: |
| Plugin name | gn_tools |
| Plugin name slugified | gn_tools |
| Plugin name class (used in code) | GnTools |
| Plugin category | None |
| Plugin description short | Bienvenue dans le GéoNature du Conservatoire des Espaces Naturels de l'Isère |
| Plugin description long | Extension QGIS permettant de récupérer des données issue de Géonature |
| Plugin tags | GéoNature, api, tools |
| Plugin icon | default_icon.png |
| Plugin with processing provider | True |
| Author name | Colas GEIER |
| Author organization | Conservatoire d'espaces naturels Isère |
| Author email | geomatique@cen-isere.org |
| Minimum QGIS version | 3.30 |
| Maximum QGIS version | 3.99 |
| Support Qt6 | True |
| Git repository URL | https://gitea.cenra-outils.org/CEN38/gn_tools |
| Git default branch | main |
| License | GPLv3 |
| Python linter | None |
| CI/CD platform | None |
| Publish to <https://plugins.qgis.org> using CI/CD | False |
| IDE | VSCode |
### Tooling
This project is configured with the following tools:
- [Black](https://black.readthedocs.io/en/stable/) to format the code without any existential question
- [iSort](https://pycqa.github.io/isort/) to sort the Python imports
Code rules are enforced with [pre-commit](https://pre-commit.com/) hooks.
See also: [contribution guidelines](CONTRIBUTING.md).
### Documentation
The documentation is located in `docs` subfolder, written in Markdown using [myst-parser](https://myst-parser.readthedocs.io/), structured in two main parts, Usage and Contribution, generated using Sphinx (have a look to [the configuration file](./docs/conf.py)) and is automatically generated through the CI and published on Pages: <https://gitea.cenra-outils.org/CEN38/gn_tools/pages> (see [post generation steps](#2-build-the-documentation-locally) below).
----
## Next steps post generation
### 1. Set up development environment
> Typical commands on Linux (Ubuntu).
1. If you didn't pick the `git init` option, initialize your local repository:
```sh
git init
```
1. Follow the [embedded documentation to set up your development environment](./docs/development/environment.md) to create virtual environment and install development dependencies.
1. Add all files to git index to prepare initial commit:
```sh
git add -A
```
1. Run the git hooks to ensure that everything runs OK and to start developing on quality standards:
```sh
# run all pre-commit hooks on all files
pre-commit run -a
# don't be shy, run it again until it's all green
```
### 2. Adjust URL and build the documentation locally
> [!NOTE]
> Since it's very hard to determine which the final documentation URL will be, the templater does not set it up. You have to do it manually.
1. Have a look to the [plugin's metadata.txt file](gn_tools/metadata.txt): review it, complete it or fix it if needed (URLs, etc.)., especially the `homepage` URL which should be to your GitLab or GitHub Pages.
1. Update the base URL of custom repository in [installation doc page](./docs/usage/installation.md).
1. Change the plugin's icon stored in `gn_tools/resources/images`
1. Follow the [embedded documentation to build plugin documentation locally](./docs/development/documentation.md)
### 3. Prepare your remote repository
1. If you did not yet, create a remote repository on your Git hosting platform (GitHub, GitLab, etc.)
1. Add the remote repository to your local repository:
```sh
git remote add origin https://gitea.cenra-outils.org/CEN38/gn_tools
```
1. Commit changes:
```sh
git commit -m "init(plugin): adding first files of gn_tools" -m "generated with QGIS Plugin Templater (https://oslandia.gitlab.io/qgis/template-qgis-plugin)"
```
1. Push the initial commit to the remote repository:
```sh
git push -u origin main
```
1. Create a new release following the [packaging/release guide](./docs//development/packaging.md) with the tag `0.1.0-beta1` to trigger the CI/CD pipeline and publish the plugin on the [official QGIS plugins repository](https://plugins.qgis.org/) (if you picked up the option).
----
## License
Distributed under the terms of the [`GPLv3` license](LICENSE).

133
docs/conf.py Normal file
View File

@ -0,0 +1,133 @@
#!python3
"""Configuration for project documentation using Sphinx."""
# standard
import sys
from datetime import datetime
from os import environ, path
sys.path.insert(0, path.abspath("..")) # move into project package
# 3rd party
import sphinx_rtd_theme # noqa: F401 theme of Read the Docs
# Package
from gn_tools import __about__
# -- Build environment -----------------------------------------------------
on_rtd = environ.get("READTHEDOCS", None) == "True"
# -- Project information -----------------------------------------------------
author = __about__.__author__
copyright = __about__.__copyright__
description = __about__.__summary__
project = __about__.__title__
version = release = __about__.__version__
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
# Sphinx included
"sphinx.ext.autosectionlabel",
"sphinx.ext.extlinks",
"sphinx.ext.githubpages",
"sphinx.ext.intersphinx",
"sphinx.ext.viewcode",
# 3rd party
"myst_parser",
"sphinx_copybutton",
"sphinx_rtd_theme",
]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
source_suffix = {".md": "markdown", ".rst": "restructuredtext"}
autosectionlabel_prefix_document = True
# The master toctree document.
master_doc = "index"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = [
"_build",
".venv",
"Thumbs.db",
".DS_Store",
"_output",
"ext_libs",
"tests",
"demo",
]
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# -- Options for HTML output -------------------------------------------------
# -- Theme
html_favicon = str(__about__.__icon_path__)
html_logo = str(__about__.__icon_path__)
# uncomment next line if you store some statics which are not directly linked into the markdown/RST files
# html_static_path = ["static/include_additional"]
html_theme = "sphinx_rtd_theme"
html_theme_options = {
"display_version": True,
"logo_only": False,
"prev_next_buttons_location": "both",
"style_external_links": True,
"style_nav_header_background": "SteelBlue",
# Toc options
"collapse_navigation": True,
"includehidden": False,
"navigation_depth": 4,
"sticky_navigation": False,
"titles_only": False,
}
# -- EXTENSIONS --------------------------------------------------------
# Configuration for intersphinx (refer to others docs).
intersphinx_mapping = {
"PyQt5": ("https://www.riverbankcomputing.com/static/Docs/PyQt5", None),
"python": ("https://docs.python.org/3/", None),
"qgis": ("https://qgis.org/pyqgis/master/", None),
}
# MyST Parser
myst_enable_extensions = [
"amsmath",
"colon_fence",
"deflist",
"dollarmath",
"html_image",
"linkify",
"replacements",
"smartquotes",
"substitution",
]
myst_substitutions = {
"author": author,
"date_update": datetime.now().strftime("%d %B %Y"),
"description": description,
"qgis_version_max": __about__.__plugin_md__.get("general").get(
"qgismaximumversion"
),
"qgis_version_min": __about__.__plugin_md__.get("general").get(
"qgisminimumversion"
),
"repo_url": __about__.__uri__,
"title": project,
"version": version,
}
myst_url_schemes = ("http", "https", "mailto")

View File

@ -0,0 +1,2 @@
```{include} ../../CODE_OF_CONDUCT.md
```

View File

@ -0,0 +1,2 @@
```{include} ../../CONTRIBUTING.md
```

View File

@ -0,0 +1,24 @@
# Documentation
Project uses Sphinx to generate documentation from docstrings (documentation in-code) and custom pages written in Markdown (through the [MyST parser](https://myst-parser.readthedocs.io/en/latest/)).
## Build documentation website
To build it:
```bash
# install aditionnal dependencies
python -m pip install -U -r requirements/documentation.txt
# build it
sphinx-build -b html -d docs/_build/cache -j auto -q docs docs/_build/html
```
Open `docs/_build/index.html` in a web browser.
## Write documentation using live render
```bash
sphinx-autobuild -b html docs/ docs/_build
```
Open <http://localhost:8000> in a web browser to see the HTML render updated when a file is saved.

View File

@ -0,0 +1,63 @@
# Development
## Environment setup
> Typically on Ubuntu (but should also work on Windows with potential small adjustments).
### 1. Install virtual environment
Using [qgis-venv-creator](https://github.com/GispoCoding/qgis-venv-creator) (see [this article](https://blog.geotribu.net/2024/11/25/creating-a-python-virtual-environment-for-pyqgis-development-with-vs-code-on-windows/#with-the-qgis-venv-creator-utility)) through [pipx](https://pipx.pypa.io) (`sudo apt install pipx`):
```sh
pipx run qgis-venv-creator --venv-name ".venv"
```
Then enter into the virtual environment:
```sh
. .venv/bin/activate
# or
source .venv/bin/activate
```
Old school way:
```bash
# create virtual environment linking to system packages (for pyqgis)
python3 -m venv .venv --system-site-packages
source .venv/bin/activate
```
### 2. Install development dependencies
```sh
# bump dependencies inside venv
python -m pip install -U pip
python -m pip install -U -r requirements/development.txt
# install git hooks (pre-commit)
pre-commit install
```
### 3. Dedicated QGIS profile
It's recommended to create a dedicated QGIS profile for the development of the plugin to avoid conflicts with other plugins.
1. From the command-line (a terminal with qgis executable in `PATH` or OSGeo4W Shell):
```sh
# Linux
qgis --profile plg_gn_tools
# Windows - OSGeo4W Shell
qgis-ltr --profile plg_gn_tools
# Windows - PowerShell opened in the QGIS installation directory
PS C:\Program Files\QGIS 3.40.4\LTR\bin> .\qgis-ltr-bin.exe --profile plg_gn_tools
```
1. Then, set the `QGIS_PLUGINPATH` environment variable to the path of the plugin in profile preferences:
![QGIS - Add QGIS_PLUGINPATH environment variable in profile settings](../static/dev_qgis_set_pluginpath_envvar.png)
1. Finally, enable the plugin in the plugin manager (ignore invalid folders like documentation, tests, etc.):
![QGIS - Enable the plugin in the plugin manager](../static/dev_qgis_enable_plugin.png)

View File

@ -0,0 +1,2 @@
```{include} ../../CHANGELOG.md
```

View File

@ -0,0 +1,43 @@
# Packaging and deployment
## Packaging
This plugin is using the [qgis-plugin-ci](https://github.com/opengisch/qgis-plugin-ci/) tool to perform packaging operations.
Under the hood, the package command is performing a `git archive` run based on `CHANGELOG.md`.
Install additional dependencies:
```bash
python -m pip install -U -r requirements/packaging.txt
```
Then use it:
```bash
# package a specific version
qgis-plugin-ci package 1.3.1
# package latest version
qgis-plugin-ci package latest
```
## Release a version
Everything is done through the continuous deployment, sticking to a classic git workflow: 1 released version = 1 git tag.
Here comes the process for a tag `X.y.z` (which has to be SemVer compliant):
1. Add the new version to the `CHANGELOG.md`..
1. Optionally change the version number in `metadata.txt`. It's recommended to use the next version number with `-DEV` suffix (e.g. `1.4.0-DEV` when `X.y.z` is `1.3.0` ) to avoid confusion during the development phase.
1. Apply a git tag with the relevant version: `git tag -a X.y.z {git commit hash} -m "This version rocks!"`
1. Push tag to main branch: `git push origin X.y.z` or `git push --tags` if you want to push all tags at once.
1. The CI/CD pipeline will be triggered and will create a new release on your Git repository and publish it to the [official QGIS plugins repository](https://plugins.qgis.org/) (if you picked up the option).
If things go wrong (failed CI/CD pipeline, missed step...), here comes the fix process:
```sh
git tag -d old
git push origin :refs/tags/old
git push --tags
```
And try again!

View File

@ -0,0 +1,33 @@
# Testing the plugin
Tests are written in 2 separate folders:
- `tests/unit`: testing code which is independent of QGIS API
- `tests/qgis`: testing code which depends on QGIS API
## Requirements
- 3.30 < QGIS < 3.99
```bash
python -m pip install -U -r requirements/testing.txt
```
## Run unit tests
```bash
# run all tests with PyTest and Coverage report
python -m pytest
# run only unit tests with pytest launcher (disabling pytest-qgis)
python -m pytest -p no:qgis tests/unit
# run only QGIS tests with pytest launcher
python -m pytest tests/qgis
# run a specific test module using standard unittest
python -m unittest tests.unit.test_plg_metadata
# run a specific test function using standard unittest
python -m unittest tests.unit.test_plg_metadata.TestPluginMetadata.test_version_semver
```

View File

@ -0,0 +1,44 @@
# Manage translations
## Requirements
Qt Linguist tools are used to manage translations. Typically on Ubuntu:
```bash
sudo apt install qttools5-dev-tools
```
## Workflow
1. Generate the `plugin_translation.pro` file:
```bash
python scripts/generate_translation_profile.py
```
1. Update `.ts` files:
```bash
pylupdate5 -noobsolete -verbose gn_tools/resources/i18n/plugin_translation.pro
```
1. Translate your text using QLinguist or directly into `.ts` files. Launching it through command-line is possible:
```bash
linguist gn_tools/resources/i18n/*.ts
```
1. Compile it:
```bash
lrelease gn_tools/resources/i18n/*.ts
```
## Notes
- Remember that the resulting `*.qm` file should not be tracked in git history since it's autogenerated and a binary file. The CI/CD pipeline will take care of generating it and packaging it. However, you can add the `*.qm` file to `.gitignore` to avoid any accidental commits.
- The `pylupdate5` command is used to extract translatable strings from the source code and update the `.ts` files accordingly.
- The `-no-obsolete` flag is important to avoid removing obsolete translations, which can be useful for maintaining the history of translations and ensuring that no existing translations are lost during updates.
- The `-verbose` flag is used to provide detailed output during the translation update process, which can be helpful for debugging and ensuring that the process is working correctly.
- The `linguist` command is used to launch the Qt Linguist application, which provides a graphical interface for translating the `.ts` files. This can be more user-friendly than editing the files directly in a text editor.
- The `lrelease` command is used to compile the `.ts` files into `.qm` files, which are binary files used by Qt applications for translations.

34
docs/index.md Normal file
View File

@ -0,0 +1,34 @@
# {{ title }} - Documentation
> **Description:** {{ description }}
> **Author and contributors:** {{ author }}
> **Plugin version:** {{ version }}
> **QGIS minimum version:** {{ qgis_version_min }}
> **QGIS maximum version:** {{ qgis_version_max }}
> **Source code:** {{ repo_url }}
> **Last documentation update:** {{ date_update }}
----
```{toctree}
---
caption: Usage
maxdepth: 1
---
Installation <usage/installation>
```
```{toctree}
---
caption: Contribution guide
maxdepth: 1
---
development/code_of_conduct
development/contribute
development/environment
development/documentation
development/translation
development/packaging
development/testing
development/history
```

BIN
docs/static/dev_qgis_enable_plugin.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

View File

@ -0,0 +1,19 @@
# Installation
## Stable version (recomended)
This plugin is published on the official QGIS plugins repository: <https://plugins.qgis.org/plugins/gn_tools/>.
## Beta versions released
Enable experimental extensions in the QGIS plugins manager settings panel.
## Earlier development version
If you define yourself as early adopter or a tester and can't wait for the release, the plugin is automatically packaged for each commit to main, so you can use this address as repository URL in your QGIS extensions manager settings:
```url
https://gitea.cenra-outils.org/CEN38/gn_tools/pages/plugins.xml
```
Be careful, this version can be unstable.

134
gn_tools/__about__.py Normal file
View File

@ -0,0 +1,134 @@
#! python3 # noqa: E265
"""
Metadata about the package to easily retrieve informations about it.
See: https://packaging.python.org/guides/single-sourcing-package-version/
"""
# ############################################################################
# ########## Libraries #############
# ##################################
# standard library
from configparser import ConfigParser
from datetime import date
from pathlib import Path
import json
# ############################################################################
# ########## Globals ###############
# ##################################
__all__: list = [
"__author__",
"__copyright__",
"__email__",
"__license__",
"__summary__",
"__title__",
"__uri__",
"__version__",
]
DIR_PLUGIN_ROOT: Path = Path(__file__).parent
PLG_METADATA_FILE: Path = DIR_PLUGIN_ROOT.resolve() / "metadata.txt"
# ############################################################################
# ########## Functions #############
# ##################################
def plugin_metadata_as_dict() -> dict:
"""Read plugin metadata.txt and returns it as a Python dict.
Raises:
IOError: if metadata.txt is not found
Returns:
dict: dict of dicts.
"""
config = ConfigParser(interpolation=None)
if PLG_METADATA_FILE.is_file():
config.read(PLG_METADATA_FILE.resolve(), encoding="UTF-8")
return {s: dict(config.items(s)) for s in config.sections()}
else:
raise IOError("Plugin metadata.txt not found at: %s" % PLG_METADATA_FILE)
# ############################################################################
# ########## Variables #############
# ##################################
# store full metadata.txt as dict into a var
__plugin_md__: dict = plugin_metadata_as_dict()
__author__: str = __plugin_md__.get("general").get("author")
__copyright__: str = "2026 - {0}, {1}".format(
date.today().year, __author__
)
__email__: str = __plugin_md__.get("general").get("email")
__icon_path__: Path = DIR_PLUGIN_ROOT.resolve() / __plugin_md__.get("general").get(
"icon"
)
__keywords__: list = [
t.strip() for t in __plugin_md__.get("general").get("repository").split("tags")
]
__license__: str = "GPLv3"
__plugin_dependencies__ = [
dep.strip()
for dep in __plugin_md__.get("general").get("plugin_dependencies", "").split(",")
if dep.strip()
]
__summary__: str = "{}\n{}".format(
__plugin_md__.get("general").get("description"),
__plugin_md__.get("general").get("about"),
)
__title__: str = __plugin_md__.get("general").get("name")
__title_clean__: str = "".join(e for e in __title__ if e.isalnum())
__uri_homepage__: str = __plugin_md__.get("general").get("homepage")
__uri_repository__: str = __plugin_md__.get("general").get("repository")
__uri_tracker__: str = __plugin_md__.get("general").get("tracker")
__uri__: str = __uri_repository__
__version__: str = __plugin_md__.get("general").get("version")
__version_info__: tuple = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
__domain_url__: str = __plugin_md__.get("service").get("domain_name")
__biodiv_aura__: str = __plugin_md__.get("service").get("biodiv_aura")
__gbif__: str = __plugin_md__.get("service").get("gbif")
__api_sn_web__: str = __plugin_md__.get("export").get("synth_web")
__api_sn_exp__: str = __plugin_md__.get("export").get("synth_exp")
__api_lst_ex__: str = __plugin_md__.get("export").get("lstexport")
__api_cd_sta__: str = __plugin_md__.get("export").get("cd_status")
__login_url__: str = __plugin_md__.get("api").get("login_api")
__orb_tax_url__: str = __plugin_md__.get("ref_taxon").get("biodiv_aura")
__exept_export__: list = json.loads(__plugin_md__.get("export").get("except_export_term"))
# #############################################################################
# ##### Main #######################
# ##################################
if __name__ == "__main__":
plugin_md = plugin_metadata_as_dict()
assert isinstance(plugin_md, dict)
assert plugin_md.get("general").get("name") == __title__
print(f"Plugin: {__title__}")
print(f"By: {__author__}")
print(f"Version: {__version__}")
print(f"Description: {__summary__}")
print(f"Icon: {__icon_path__}")
print(
"For: %s > QGIS > %s"
% (
plugin_md.get("general").get("qgisminimumversion"),
plugin_md.get("general").get("qgismaximumversion"),
)
)
print(__title_clean__)
print(f"Depends on other plugins: {__plugin_dependencies__}")

23
gn_tools/__init__.py Normal file
View File

@ -0,0 +1,23 @@
#! python3 # noqa: E265
# ----------------------------------------------------------
# Copyright (C) 2015 Martin Dobias
# ----------------------------------------------------------
# Licensed under the terms of GNU GPL 2
#
# 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.
# --------------------------------------------------------------------
def classFactory(iface):
"""Load the plugin class.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
from .plugin_main import GnToolsPlugin
return GnToolsPlugin(iface)

0
gn_tools/gui/__init__.py Normal file
View File

View File

@ -0,0 +1,45 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
gnToolsSynthese
A QGIS plugin
dlg_gn_tools
Plugin settings form integrated into QGIS 'Options' menu.
-------------------
begin : 2022-08-22
git sha : $Format:%H$
copyright : (C) 2022 by colas
email : colas.geier@cen-isere.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import os
from qgis.PyQt import uic
from qgis.PyQt import QtWidgets
from datetime import datetime as dt
# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'dlg_gn_synthese.ui'))
class gnToolsSynthese(QtWidgets.QDialog, FORM_CLASS):
def __init__(self, parent=None):
"""Constructor."""
super(gnToolsSynthese, self).__init__(parent)
# Set up the user interface from Designer through FORM_CLASS.
# After self.setupUi() you can access any designer object by doing
# self.<objectname>, and you can use autoconnect slots - see
# http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
# #widgets-and-dialogs-with-auto-connect
self.setupUi(self)

View File

@ -0,0 +1,209 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>341</height>
</rect>
</property>
<property name="windowTitle">
<string>Paramètres de la Synthèse</string>
</property>
<property name="sizeGripEnabled">
<bool>true</bool>
</property>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="geometry">
<rect>
<x>50</x>
<y>290</y>
<width>341</width>
<height>32</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
<widget class="QgsCheckableComboBox" name="jdd_box">
<property name="geometry">
<rect>
<x>149</x>
<y>120</y>
<width>221</width>
<height>27</height>
</rect>
</property>
</widget>
<widget class="QLabel" name="lab_jdd">
<property name="geometry">
<rect>
<x>20</x>
<y>118</y>
<width>121</width>
<height>31</height>
</rect>
</property>
<property name="text">
<string>Jeu de données</string>
</property>
</widget>
<widget class="QgsCheckableComboBox" name="regne">
<property name="geometry">
<rect>
<x>150</x>
<y>160</y>
<width>221</width>
<height>27</height>
</rect>
</property>
</widget>
<widget class="QLabel" name="lab_regne">
<property name="geometry">
<rect>
<x>20</x>
<y>160</y>
<width>131</width>
<height>31</height>
</rect>
</property>
<property name="text">
<string>Règne de taxons</string>
</property>
</widget>
<widget class="QLabel" name="lab_dmin">
<property name="geometry">
<rect>
<x>20</x>
<y>200</y>
<width>121</width>
<height>31</height>
</rect>
</property>
<property name="text">
<string>Date min</string>
</property>
</widget>
<widget class="QLabel" name="lab_dmax">
<property name="geometry">
<rect>
<x>20</x>
<y>240</y>
<width>121</width>
<height>31</height>
</rect>
</property>
<property name="text">
<string>Date max</string>
</property>
</widget>
<widget class="QgsDateTimeEdit" name="date_min">
<property name="geometry">
<rect>
<x>150</x>
<y>200</y>
<width>221</width>
<height>28</height>
</rect>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
</widget>
<widget class="QgsDateTimeEdit" name="date_max">
<property name="geometry">
<rect>
<x>150</x>
<y>240</y>
<width>221</width>
<height>28</height>
</rect>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
</widget>
<widget class="QLabel" name="send_to_gn">
<property name="geometry">
<rect>
<x>20</x>
<y>10</y>
<width>351</width>
<height>91</height>
</rect>
</property>
<property name="text">
<string>Pour plus de paramètres, accèder à la plateforme en ligne : </string>
</property>
<property name="textFormat">
<enum>Qt::AutoText</enum>
</property>
<property name="scaledContents">
<bool>true</bool>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::TextBrowserInteraction</set>
</property>
</widget>
</widget>
<customwidgets>
<customwidget>
<class>QgsCheckableComboBox</class>
<extends>QComboBox</extends>
<header>qgscheckablecombobox.h</header>
</customwidget>
<customwidget>
<class>QgsDateTimeEdit</class>
<extends>QDateTimeEdit</extends>
<header>qgsdatetimeedit.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>Dialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>Dialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -0,0 +1,45 @@
# -*- coding: utf-8 -*-
"""
/***************************************************************************
gnToolsDialog
A QGIS plugin
dlg_gn_tools
Plugin settings form integrated into QGIS 'Options' menu.
-------------------
begin : 2022-08-22
git sha : $Format:%H$
copyright : (C) 2022 by colas
email : colas.geier@cen-isere.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import os
from qgis.PyQt import uic
from qgis.PyQt import QtWidgets
from datetime import datetime as dt
# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'dlg_gn_tools.ui'))
class gnToolsDialog(QtWidgets.QDialog, FORM_CLASS):
def __init__(self, parent=None):
"""Constructor."""
super(gnToolsDialog, self).__init__(parent)
# Set up the user interface from Designer through FORM_CLASS.
# After self.setupUi() you can access any designer object by doing
# self.<objectname>, and you can use autoconnect slots - see
# http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
# #widgets-and-dialogs-with-auto-connect
self.setupUi(self)

View File

@ -0,0 +1,443 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>771</width>
<height>453</height>
</rect>
</property>
<property name="windowTitle">
<string>GéoNature tools</string>
</property>
<property name="autoFillBackground">
<bool>true</bool>
</property>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="geometry">
<rect>
<x>410</x>
<y>410</y>
<width>341</width>
<height>32</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
<widget class="QTabWidget" name="tab">
<property name="geometry">
<rect>
<x>70</x>
<y>110</y>
<width>631</width>
<height>281</height>
</rect>
</property>
<property name="mouseTracking">
<bool>true</bool>
</property>
<property name="tabletTracking">
<bool>true</bool>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="accessibleName">
<string>auth_url</string>
</property>
<property name="autoFillBackground">
<bool>false</bool>
</property>
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="import_2">
<attribute name="title">
<string>Import</string>
</attribute>
<widget class="QLabel" name="lab_src_imp">
<property name="geometry">
<rect>
<x>40</x>
<y>30</y>
<width>66</width>
<height>31</height>
</rect>
</property>
<property name="text">
<string>Source : </string>
</property>
</widget>
<widget class="QComboBox" name="source_import">
<property name="geometry">
<rect>
<x>130</x>
<y>30</y>
<width>241</width>
<height>27</height>
</rect>
</property>
<property name="currentText">
<string/>
</property>
</widget>
<widget class="QPushButton" name="draw_bounds">
<property name="geometry">
<rect>
<x>350</x>
<y>90</y>
<width>251</width>
<height>27</height>
</rect>
</property>
<property name="text">
<string>Tracer une emprise</string>
</property>
</widget>
<widget class="QPushButton" name="active_filter_layer">
<property name="geometry">
<rect>
<x>40</x>
<y>90</y>
<width>231</width>
<height>27</height>
</rect>
</property>
<property name="text">
<string>Filtrer à partir d'une couche</string>
</property>
</widget>
<widget class="QgsMapLayerComboBox" name="filter_layer">
<property name="geometry">
<rect>
<x>40</x>
<y>150</y>
<width>251</width>
<height>27</height>
</rect>
</property>
<property name="accessibleName">
<string>Couche taxonomique</string>
</property>
<property name="allowEmptyLayer">
<bool>true</bool>
</property>
</widget>
<widget class="QCheckBox" name="use_entity">
<property name="geometry">
<rect>
<x>40</x>
<y>200</y>
<width>271</width>
<height>31</height>
</rect>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="toolTip">
<string>Utilisation de l'emprise</string>
</property>
<property name="text">
<string>Utiliser les entitées sélectionnées</string>
</property>
</widget>
<widget class="QTextEdit" name="bound_log">
<property name="geometry">
<rect>
<x>350</x>
<y>150</y>
<width>251</width>
<height>81</height>
</rect>
</property>
<property name="html">
<string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Ubuntu Sans'; font-size:11pt; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;br /&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
<widget class="QPushButton" name="clear_filter">
<property name="geometry">
<rect>
<x>467</x>
<y>30</y>
<width>131</width>
<height>27</height>
</rect>
</property>
<property name="text">
<string>Clear filter</string>
</property>
</widget>
<widget class="QToolButton" name="syn_tools">
<property name="geometry">
<rect>
<x>380</x>
<y>30</y>
<width>26</width>
<height>26</height>
</rect>
</property>
<property name="toolTip">
<string>Ajouter des filtres</string>
</property>
<property name="text">
<string>...</string>
</property>
<property name="popupMode">
<enum>QToolButton::InstantPopup</enum>
</property>
<property name="autoRaise">
<bool>false</bool>
</property>
</widget>
</widget>
<widget class="QWidget" name="status">
<attribute name="title">
<string>Statuts</string>
</attribute>
<widget class="QgsMapLayerComboBox" name="map_layers">
<property name="geometry">
<rect>
<x>238</x>
<y>40</y>
<width>271</width>
<height>27</height>
</rect>
</property>
<property name="accessibleName">
<string>Couche taxonomique</string>
</property>
<property name="allowEmptyLayer">
<bool>true</bool>
</property>
</widget>
<widget class="QLabel" name="lab_lay_tax">
<property name="geometry">
<rect>
<x>45</x>
<y>40</y>
<width>211</width>
<height>31</height>
</rect>
</property>
<property name="text">
<string>Couche taxonomique :</string>
</property>
</widget>
<widget class="QLabel" name="lab_cd_tax">
<property name="geometry">
<rect>
<x>110</x>
<y>100</y>
<width>151</width>
<height>31</height>
</rect>
</property>
<property name="text">
<string>Code taxon :</string>
</property>
</widget>
<widget class="QComboBox" name="cd_taxon">
<property name="geometry">
<rect>
<x>240</x>
<y>100</y>
<width>271</width>
<height>27</height>
</rect>
</property>
<property name="toolTip">
<string>Doit correspondre au cd_nom ou cd_ref</string>
</property>
</widget>
<widget class="QLineEdit" name="layer_out">
<property name="geometry">
<rect>
<x>240</x>
<y>160</y>
<width>341</width>
<height>27</height>
</rect>
</property>
<property name="toolTip">
<string>Nom de la couche à créer</string>
</property>
<property name="text">
<string>output</string>
</property>
<property name="clearButtonEnabled">
<bool>true</bool>
</property>
</widget>
<widget class="QLabel" name="lab_lay_out">
<property name="geometry">
<rect>
<x>80</x>
<y>160</y>
<width>191</width>
<height>31</height>
</rect>
</property>
<property name="text">
<string>Name layer out :</string>
</property>
</widget>
</widget>
</widget>
<widget class="QgsAuthConfigSelect" name="mAuthConfigSelect">
<property name="enabled">
<bool>true</bool>
</property>
<property name="geometry">
<rect>
<x>70</x>
<y>60</y>
<width>292</width>
<height>41</height>
</rect>
</property>
<property name="tabletTracking">
<bool>true</bool>
</property>
<property name="autoFillBackground">
<bool>true</bool>
</property>
</widget>
<widget class="QLineEdit" name="report_url">
<property name="enabled">
<bool>false</bool>
</property>
<property name="geometry">
<rect>
<x>360</x>
<y>20</y>
<width>341</width>
<height>27</height>
</rect>
</property>
<property name="text">
<string/>
</property>
<property name="alignment">
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
</property>
</widget>
<widget class="QPushButton" name="login_gn">
<property name="geometry">
<rect>
<x>400</x>
<y>60</y>
<width>88</width>
<height>27</height>
</rect>
</property>
<property name="text">
<string>Connect</string>
</property>
</widget>
<widget class="QLabel" name="is_connect">
<property name="geometry">
<rect>
<x>500</x>
<y>60</y>
<width>201</width>
<height>31</height>
</rect>
</property>
<property name="text">
<string>Non connecté..</string>
</property>
</widget>
<widget class="QComboBox" name="src_database">
<property name="geometry">
<rect>
<x>70</x>
<y>20</y>
<width>201</width>
<height>27</height>
</rect>
</property>
<property name="toolTip">
<string>Source de données</string>
</property>
<property name="currentText">
<string/>
</property>
</widget>
<widget class="QRadioButton" name="pub_access">
<property name="geometry">
<rect>
<x>280</x>
<y>20</y>
<width>111</width>
<height>31</height>
</rect>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
<property name="text">
<string>Public</string>
</property>
</widget>
</widget>
<customwidgets>
<customwidget>
<class>QgsAuthConfigSelect</class>
<extends>QWidget</extends>
<header>qgsauthconfigselect.h</header>
</customwidget>
<customwidget>
<class>QgsMapLayerComboBox</class>
<extends>QComboBox</extends>
<header>qgsmaplayercombobox.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>Dialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>Dialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

169
gn_tools/gui/dlg_settings.py Executable file
View File

@ -0,0 +1,169 @@
#! python3 # noqa: E265
"""
Plugin settings form integrated into QGIS 'Options' menu.
"""
# standard
import platform
from functools import partial
from pathlib import Path
from urllib.parse import quote
# PyQGIS
from qgis.core import Qgis, QgsApplication
from qgis.gui import QgsOptionsPageWidget, QgsOptionsWidgetFactory
from qgis.PyQt import uic
from qgis.PyQt.QtCore import QUrl
from qgis.PyQt.QtGui import QDesktopServices, QIcon
# project
from gn_tools.__about__ import (
__icon_path__,
__title__,
__uri_homepage__,
__uri_tracker__,
__version__,
)
from gn_tools.toolbelt import PlgLogger, PlgOptionsManager
from gn_tools.toolbelt.preferences import PlgSettingsStructure
# ############################################################################
# ########## Globals ###############
# ##################################
FORM_CLASS, _ = uic.loadUiType(
Path(__file__).parent / "{}.ui".format(Path(__file__).stem)
)
# ############################################################################
# ########## Classes ###############
# ##################################
class ConfigOptionsPage(FORM_CLASS, QgsOptionsPageWidget):
"""Settings form embedded into QGIS 'options' menu."""
def __init__(self, parent):
super().__init__(parent)
self.log = PlgLogger().log
self.plg_settings = PlgOptionsManager()
# load UI and set objectName
self.setupUi(self)
self.setObjectName("mOptionsPage{}".format(__title__))
report_context_message = quote(
"> Reported from plugin settings\n\n"
f"- operating system: {platform.system()} "
f"{platform.release()}_{platform.version()}\n"
f"- QGIS: {Qgis.QGIS_VERSION}\n"
f"- plugin version: {__version__}\n"
)
# header
self.lbl_title.setText(f"{__title__} - Version {__version__}")
# customization
self.btn_help.setIcon(QIcon(QgsApplication.iconPath("mActionHelpContents.svg")))
self.btn_help.pressed.connect(
partial(QDesktopServices.openUrl, QUrl(__uri_homepage__))
)
self.btn_report.setIcon(
QIcon(QgsApplication.iconPath("console/iconSyntaxErrorConsole.svg"))
)
self.btn_reset.setIcon(QIcon(QgsApplication.iconPath("mActionUndo.svg")))
self.btn_reset.pressed.connect(self.reset_settings)
# load previously saved settings
self.load_settings()
def apply(self):
"""Called to permanently apply the settings shown in the options page (e.g. \
save them to QgsSettings objects). This is usually called when the options \
dialog is accepted."""
settings = self.plg_settings.get_plg_settings()
# misc
settings.debug_mode = self.opt_debug.isChecked()
settings.version = __version__
# param
settings.domain_url = self.edit_url.text()
# dump new settings into QgsSettings
self.plg_settings.save_from_object(settings)
if __debug__:
self.log(
message="DEBUG - Settings successfully saved.",
log_level=Qgis.MessageLevel.NoLevel,
)
def load_settings(self):
"""Load options from QgsSettings into UI form."""
settings = self.plg_settings.get_plg_settings()
# global
self.opt_debug.setChecked(settings.debug_mode)
self.lbl_version_saved_value.setText(settings.version)
# param
self.edit_url.setText(settings.domain_url)
def reset_settings(self):
"""Reset settings to default values (set in preferences.py module)."""
default_settings = PlgSettingsStructure()
# dump default settings into QgsSettings
self.plg_settings.save_from_object(default_settings)
# update the form
self.load_settings()
class PlgOptionsFactory(QgsOptionsWidgetFactory):
"""Factory for options widget."""
def __init__(self):
"""Constructor."""
super().__init__()
def icon(self) -> QIcon:
"""Returns plugin icon, used to as tab icon in QGIS options tab widget.
:return: _description_
:rtype: QIcon
"""
return QIcon(str(__icon_path__))
def createWidget(self, parent) -> ConfigOptionsPage:
"""Create settings widget.
:param parent: Qt parent where to include the options page.
:type parent: QObject
:return: options page for tab widget
:rtype: ConfigOptionsPage
"""
return ConfigOptionsPage(parent)
def title(self) -> str:
"""Returns plugin title, used to name the tab in QGIS options tab widget.
:return: plugin title from about module
:rtype: str
"""
return __title__
def helpId(self) -> str:
"""Returns plugin help URL.
:return: plugin homepage url from about module
:rtype: str
"""
return __uri_homepage__

View File

@ -0,0 +1,255 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>wdg_gn_tools_settings</class>
<widget class="QWidget" name="wdg_gn_tools_settings">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>638</width>
<height>325</height>
</rect>
</property>
<property name="windowTitle">
<string>gn_tools - Settings</string>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="lbl_title">
<property name="minimumSize">
<size>
<width>0</width>
<height>25</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>30</height>
</size>
</property>
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;PluginTitle - Version X.X.X&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="scaledContents">
<bool>true</bool>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
<property name="openExternalLinks">
<bool>false</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item>
<widget class="QGroupBox" name="grp_misc">
<property name="minimumSize">
<size>
<width>0</width>
<height>100</height>
</size>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="title">
<string>Miscellaneous</string>
</property>
<property name="flat">
<bool>false</bool>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="2" column="0">
<widget class="QPushButton" name="btn_help">
<property name="minimumSize">
<size>
<width>200</width>
<height>25</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>500</width>
<height>30</height>
</size>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="text">
<string>Help</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QLabel" name="lbl_version_saved_value">
<property name="minimumSize">
<size>
<width>0</width>
<height>25</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>30</height>
</size>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="text">
<string notr="true">X.X.X</string>
</property>
<property name="textInteractionFlags">
<set>Qt::NoTextInteraction</set>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="lbl_version_saved">
<property name="minimumSize">
<size>
<width>0</width>
<height>25</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>30</height>
</size>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="text">
<string>Version used to save settings:</string>
</property>
</widget>
</item>
<item row="5" column="0" colspan="2">
<widget class="QPushButton" name="btn_reset">
<property name="minimumSize">
<size>
<width>200</width>
<height>25</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>30</height>
</size>
</property>
<property name="autoFillBackground">
<bool>true</bool>
</property>
<property name="text">
<string>Reset settings to factory defaults</string>
</property>
</widget>
</item>
<item row="3" column="0" colspan="2">
<widget class="QCheckBox" name="opt_debug">
<property name="minimumSize">
<size>
<width>0</width>
<height>25</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>30</height>
</size>
</property>
<property name="toolTip">
<string>Enable debug mode.</string>
</property>
<property name="autoFillBackground">
<bool>true</bool>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="text">
<string>Debug mode (degraded performances)</string>
</property>
<property name="tristate">
<bool>false</bool>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QPushButton" name="btn_report">
<property name="minimumSize">
<size>
<width>200</width>
<height>25</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>500</width>
<height>30</height>
</size>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="text">
<string>Report an issue</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="edit_url"/>
</item>
<item row="1" column="0">
<widget class="QLabel" name="lab_url_gn">
<property name="text">
<string>Url GéoNature :</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>56</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

45
gn_tools/metadata.txt Normal file
View File

@ -0,0 +1,45 @@
[general]
name=gn_tools
about=Bienvenue dans le GéoNature du Conservatoire des Espaces Naturels de l'Isère
category=None
hasProcessingProvider=True
description=Extension QGIS permettant de récupérer des données issue de Géonature
icon=resources/images/Taxon_icon_vert.svg
tags=GéoNature, api, tools
# credits and contact
author=Colas GEIER
email=geomatique@cen-isere.org
homepage=https://gitea.cenra-outils.org/CEN38/gn_tools/pages
repository=https://gitea.cenra-outils.org/CEN38/gn_tools
tracker=None
# QGIS context
deprecated=False
experimental=True
plugin_dependencies=
qgisMinimumVersion=3.30
qgisMaximumVersion=3.99
supportsQt6=True
# versioning
version=0.1.0
changelog=
[service]
domain_name=https://geonature.cen-isere.fr/geonature
biodiv_aura=https://donnees.biodiversite-auvergne-rhone-alpes.fr
[ref_taxon]
biodiv_aura=https://taxons.biodiversite-aura.fr
[api]
login_api=api/auth/login
[export]
except_export_term=["sinp","synthese_ens_departement"]
synth_web=api/synthese/for_web
synth_exp=api/synthese/export_observations
lstexport=api/exports/?search=&per_page=100&page=1
cd_status=api/taxhub/api/taxref/

566
gn_tools/plugin_main.py Executable file
View File

@ -0,0 +1,566 @@
#! python3 # noqa: E265
"""Main plugin module."""
# standard
from functools import partial
from pathlib import Path
from typing import Optional
# PyQGIS
from qgis.core import (
Qgis,
QgsApplication,
QgsSettings,
QgsProject,
QgsGeometry,
QgsMapLayerProxyModel,
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
)
from qgis.gui import QgisInterface
from qgis.PyQt.QtCore import QCoreApplication, QLocale, QTranslator, QUrl
from qgis.PyQt.QtGui import QDesktopServices, QIcon
from qgis.PyQt.QtWidgets import QAction, QMessageBox
from qgis.PyQt.QtNetwork import QNetworkAccessManager
from PyQt5.QtWidgets import QCheckBox, QApplication
# project
from gn_tools.__about__ import (
DIR_PLUGIN_ROOT,
__icon_path__,
__title__,
__uri_homepage__,
__domain_url__,
__biodiv_aura__,
__gbif__,
__api_sn_web__,
__api_sn_exp__,
__api_lst_ex__,
__api_cd_sta__,
)
from gn_tools.gui.dlg_settings import PlgOptionsFactory, PlgOptionsManager
from gn_tools.gui.dlg_gn_tools import gnToolsDialog
from gn_tools.gui.dlg_gn_synthese import gnToolsSynthese
from gn_tools.processing import (
GnToolsProvider,
GetLogin,
ParamWidget,
LoadingImport,
RectangleFeatureTool,
PivotStatus,
GetFilterFromAPI,
)
from gn_tools.toolbelt import PlgLogger
# ############################################################################
# ########## Classes ###############
# ##################################
class GnToolsPlugin:
def __init__(self, iface: QgisInterface):
"""Constructor.
:param iface: An interface instance that will be passed to this class which \
provides the hook by which you can manipulate the QGIS application at run time.
:type iface: QgsInterface
"""
self.iface = iface
self.canvas = iface.mapCanvas()
self.project = QgsProject.instance()
self.log = PlgLogger().log
self.provider: Optional[GnToolsProvider] = None
self.rectangle = None
self.src_bdd = {
'GéoNature':__domain_url__,
"Biodiv'AuRA":__biodiv_aura__
}
self.syn_params = {}
# translation
# initialize the locale
self.locale: str = QgsSettings().value("locale/userLocale", QLocale().name())[
0:2
]
locale_path: Path = (
DIR_PLUGIN_ROOT
/ "resources"
/ "i18n"
/ f"{__title__.lower()}_{self.locale}.qm"
)
self.log(message=f"Translation: {self.locale}, {locale_path}", log_level=Qgis.MessageLevel.NoLevel)
if locale_path.exists():
self.translator = QTranslator()
self.translator.load(str(locale_path.resolve()))
QCoreApplication.installTranslator(self.translator)
lst_src = []
for src,url in self.src_bdd.items():
if url != '':
self.src_bdd[src] = url + '/' if url[-1] != '/' else url
lst_src += [src]
# self.domain_url = self.src_bdd['GéoNature']
self.dlg = gnToolsDialog()
self.dlg_syn = gnToolsSynthese()
# Masquer les widgets
self.dlg.pub_access.setVisible(False)
# self.dlg.syn_tools.setVisible(False)
self.dlg_syn.date_min.clear()
self.dlg_syn.date_max.clear()
self.dlg.status.setDisabled(True)
self.dlg.src_database.addItems(['',*lst_src])
self.dlg.src_database.currentTextChanged.connect(
self.define_domain_url
)
# Biodiv'AuRA check box action
self.dlg.pub_access.toggled.connect(
self.dlg.mAuthConfigSelect.setEnabled
)
self.dlg.pub_access.toggled.connect(
self.dlg.mAuthConfigSelect.setDisabled
)
# Import the extent drawer tool and connect a signal to make the window appear once the extent is drawned
self.move_tool = RectangleFeatureTool(self.project, self.canvas)
self.move_tool.signal.connect(self.activate_window)
# Login to GN
self.dlg.login_gn.clicked.connect(self.connect_src)
# Filter Active Layer
self.dlg.draw_bounds.setDisabled(True)
self.dlg.bound_log.setReadOnly(True)
self.dlg.bound_log.setPlainText('')
self.dlg.draw_bounds.clicked.connect(self.pointer)
self.dlg.active_filter_layer.setDisabled(True)
self.dlg.active_filter_layer.clicked.connect(self.filter_layer_activate)
self.dlg.filter_layer.setDisabled(True)
self.dlg.use_entity.setDisabled(True)
self.dlg.use_entity.setChecked(False)
self.dlg.map_layers.setFilters(QgsMapLayerProxyModel.VectorLayer)
self.dlg.map_layers.setAllowEmptyLayer(True)
self.filter_layers()
self.canvas.layersChanged.connect(self.filter_layers)
self.dlg.filter_layer.setFilters(QgsMapLayerProxyModel.VectorLayer)
self.dlg.filter_layer.setAllowEmptyLayer(True)
self.dlg.filter_layer.layerChanged.connect(self.extend_layer)
self.dlg.map_layers.layerChanged.connect(self.param_cd_taxon)
# Filtre de la synthèse
self.dlg.syn_tools.clicked.connect(self.dlg_syn.show)
# Clear button
self.dlg.clear_filter.setDisabled(True)
self.dlg.clear_filter.clicked.connect(self.clear_filter)
# Finished Button
self.dlg.buttonBox.accepted.disconnect()
self.dlg.buttonBox.accepted.connect(self.accept)
self.dlg.buttonBox.rejected.connect(self.reject)
def initGui(self):
"""Set up plugin UI elements."""
self.manager = QNetworkAccessManager()
self.manager.accepted = False
# settings page within the QGIS preferences menu
self.options_factory = PlgOptionsFactory()
self.iface.registerOptionsWidgetFactory(self.options_factory)
# -- Actions
self.action_help = QAction(
QgsApplication.getThemeIcon("mActionHelpContents.svg"),
self.tr("Help"),
self.iface.mainWindow(),
)
self.action_help.triggered.connect(
partial(QDesktopServices.openUrl, QUrl(__uri_homepage__))
)
self.action_settings = QAction(
QgsApplication.getThemeIcon("console/iconSettingsConsole.svg"),
self.tr("Settings"),
self.iface.mainWindow(),
)
self.action_settings.triggered.connect(
lambda: self.iface.showOptionsDialog(
currentPage="mOptionsPage{}".format(__title__)
)
)
self.action_gn_tools = QAction(
QIcon(str(__icon_path__)),
f"{__title__} - Import project",
self.iface.mainWindow(),
)
self.iface.addToolBarIcon(self.action_gn_tools)
self.action_gn_tools.triggered.connect(
lambda: self.run_gn_tools()
)
# -- Menu
self.iface.addPluginToMenu(__title__, self.action_gn_tools)
self.iface.addPluginToMenu(__title__, self.action_settings)
self.iface.addPluginToMenu(__title__, self.action_help)
# -- Processing
self.initProcessing()
# -- Help menu
# documentation
self.iface.pluginHelpMenu().addSeparator()
self.action_help_plugin_menu_documentation = QAction(
QIcon(str(__icon_path__)),
f"{__title__} - Documentation",
self.iface.mainWindow(),
)
self.action_help_plugin_menu_documentation.triggered.connect(
partial(QDesktopServices.openUrl, QUrl(__uri_homepage__))
)
self.iface.pluginHelpMenu().addAction(
self.action_help_plugin_menu_documentation
)
self.dlg.is_connect.setText('Non connecté..')
def initProcessing(self):
"""Initialize the processing provider."""
self.provider = GnToolsProvider()
QgsApplication.processingRegistry().addProvider(self.provider)
def tr(self, message: str) -> str:
"""Get the translation for a string using Qt translation API.
:param message: string to be translated.
:type message: str
:returns: Translated version of message.
:rtype: str
"""
return QCoreApplication.translate(self.__class__.__name__, message)
def unload(self):
"""Cleans up when plugin is disabled/uninstalled."""
# -- Clean up toolbar
self.iface.removeToolBarIcon(self.action_gn_tools)
# -- Clean up menu
self.iface.removePluginMenu(__title__, self.action_gn_tools)
self.iface.removePluginMenu(__title__, self.action_help)
self.iface.removePluginMenu(__title__, self.action_settings)
# -- Clean up preferences panel in QGIS settings
self.iface.unregisterOptionsWidgetFactory(self.options_factory)
# -- Unregister processing
QgsApplication.processingRegistry().removeProvider(self.provider)
# remove from QGIS help/extensions menu
if self.action_help_plugin_menu_documentation:
self.iface.pluginHelpMenu().removeAction(
self.action_help_plugin_menu_documentation
)
# remove actions
del self.action_gn_tools
del self.action_settings
del self.action_help
def run(self):
"""Main process.
:raises Exception: if there is no item in the feed
"""
try:
self.log(
message=self.tr("Everything ran OK."),
log_level=Qgis.MessageLevel.Success,
push=False,
)
print("tom")
except Exception as err:
self.log(
message=self.tr("Houston, we've got a problem: {}".format(err)),
log_level=Qgis.MessageLevel.Critical,
push=True,
)
def define_domain_url(self):
self.src_name = self.dlg.src_database.currentText()
if self.src_name != '':
self.domain_url = self.src_bdd[self.src_name]
self.dlg.report_url.setText(self.domain_url[:42])
if self.src_name == 'GBIF':
self.dlg.mAuthConfigSelect.setDisabled(True)
self.dlg.login_gn.setDisabled(True)
self.dlg.is_connect.setText('No connection need')
self.print_change()
ParamWidget(
parent=self,network_manager=self.manager
)
else:
self.dlg.mAuthConfigSelect.setEnabled(True)
self.dlg.login_gn.setEnabled(True)
self.dlg.is_connect.setText('Non connecté..')
if self.src_name == "Biodiv'AuRA":
self.dlg.pub_access.setVisible(True)
self.dlg.status.setDisabled(True)
else :
self.dlg.pub_access.setVisible(False)
self.dlg.pub_access.setChecked(False)
self.dlg.status.setEnabled(True)
else:
self.dlg.clear_filter.setDisabled(True)
self.dlg.draw_bounds.setDisabled(True)
self.dlg.active_filter_layer.setDisabled(True)
self.dlg.pub_access.setVisible(False)
self.dlg.pub_access.setChecked(False)
self.dlg.mAuthConfigSelect.setDisabled(True)
self.dlg.login_gn.setDisabled(True)
self.dlg.status.setDisabled(True)
self.dlg.is_connect.setText('Non connecté..')
def filter_layers(self):
checked_layers = self.canvas.layers()
excluded_layers = [l for l in QgsProject.instance().mapLayers().values() if not l in checked_layers]
self.dlg.map_layers.setExceptedLayerList(excluded_layers)
self.dlg.filter_layer.setExceptedLayerList(excluded_layers)
self.param_cd_taxon()
return excluded_layers
def run_gn_tools(self):
"""Main process. Create a QGIS project with ZH data from GeoNature."""
print("****** CREATE PROJECT ******")
# Get base url for all the request from the dlg settings
self.plg_settings = PlgOptionsManager().get_plg_settings()
if self.plg_settings.domain_url:
self.domain_url = self.plg_settings.domain_url
else :
self.domain_url = __domain_url__
if self.domain_url[-1] != '/':
self.domain_url = self.domain_url + '/'
# self.study_area_list = self.plg_settings.study_area_list
# self.dl_zh_pot = self.plg_settings.dl_zh_pot
# self.export_number = self.plg_settings.export_number
if self.domain_url == "":
msg = QMessageBox()
msg.warning(
None,
self.tr("Warning"),
self.tr("You need to inform GeoNature's URL"), # noqa: E501
)
self.iface.showOptionsDialog(currentPage="mOptionsPage{}".format(__title__))
self.run_gn_tools()
else:
# Initiate class
print(self.domain_url)
print(self.dlg.src_database.currentText())
if self.dlg.src_database.currentText() != '':
api = self.src_bdd[self.dlg.src_database.currentText()]
self.dlg.report_url.setText(api[:42])
self.domain_url = api
self.src_name = self.dlg.src_database.currentText()
self.dlg.show()
# Run the dialog event loop
result = self.dlg.exec_()
if result:
# Do something useful here - delete the line containing pass and
# substitute with you
print('ok')
print(result)
pass
def connect_src(self):
print('connect_src : ',self.src_name)
if self.src_name == 'GéoNature':
self.getLogin = GetLogin(parent=self,network_manager=self.manager)
self.getLogin.finished_login.connect(self.param_widget)
elif self.src_name == "Biodiv'AuRA":
if self.dlg.pub_access.isChecked():
user = {
'usr': 'user-public',
'pwd': 'public'
}
self.getLogin = GetLogin(parent=self,network_manager=self.manager,params=user)
self.getLogin.finished_login.connect(self.param_widget)
else :
self.getLogin = GetLogin(parent=self,network_manager=self.manager)
self.getLogin.finished_login.connect(self.param_widget)
# if self.manager.cookieJar():
# self.dlg.is_connect.setText("Good Job !")
# else:
# self.dlg.is_connect.setText("Aie !")
def param_widget(self):
print(self.manager.cookieStatus)
if self.manager.cookieStatus==200:
self.paramWidget = ParamWidget(
parent=self,network_manager=self.manager
)
self.dlg.source_import.currentTextChanged.connect(
self.print_change
)
def param_cd_taxon(self):
layer = self.dlg.map_layers.currentLayer()
if layer:
cols_name = layer.fields().names()
self.dlg.cd_taxon.clear()
self.dlg.cd_taxon.addItems(cols_name)
def print_change(self):
self.dlg.clear_filter.setEnabled(True)
self.dlg.draw_bounds.setEnabled(True)
self.dlg.active_filter_layer.setEnabled(True)
txt = self.dlg.source_import.currentText()
self.dlg.syn_tools.setVisible(True
if txt == 'Synthèse taxons' else False
)
if txt == 'Synthèse taxons':
self.syn = GetFilterFromAPI(
parent=self, network_manager=self.manager
)
print(self.dlg.source_import.currentIndex())
def pointer(self):
self.dlg.filter_layer.setDisabled(True)
self.dlg.use_entity.setDisabled(True)
self.dlg.use_entity.setChecked(False)
self.dlg.bound_log.setPlainText('')
# Add the tool to draw a rectangle
self.iface.mainWindow().activateWindow()
self.canvas.setMapTool(self.move_tool)
def activate_window(self):
# Put the dialog on top once the rectangle is drawn
# self.activateWindow()
self.canvas.unsetMapTool(self.move_tool)
self.check_valid()
def check_valid(self):
self.rectangle = QgsGeometry.fromRect(self.move_tool.new_extent)
sourceCrs = QgsCoordinateReferenceSystem(self.project.crs())
destCrs = QgsCoordinateReferenceSystem(4326)
tr = QgsCoordinateTransform(sourceCrs, destCrs, self.project)
self.rectangle.transform(tr)
self.dlg.bound_log.setPlainText(
'Bound selected : '
+ str(self.rectangle.asWkt())
)
print('rectangle : ',self.rectangle.asJson())
def filter_layer_activate(self):
self.dlg.bound_log.setPlainText('')
self.extend_layer()
self.dlg.filter_layer.setEnabled(True)
self.dlg.use_entity.setEnabled(True)
self.canvas.unsetMapTool(self.move_tool)
def extend_layer(self):
if self.dlg_syn.jdd_box.checkedItemsData():
print('checked : ',self.dlg_syn.jdd_box.checkedItems())
print('checked : ',self.syn_params)
if self.dlg.filter_layer.currentText() != '':
layer = self.dlg.filter_layer.currentLayer()
destCrs = QgsCoordinateReferenceSystem(4326)
self.rectangle = QgsGeometry.fromRect(
layer.extent()
)
if self.dlg.use_entity.isChecked():
geoms = [f.geometry() for f in layer.getSelectedFeatures()]
if geoms:
union = QgsGeometry.unaryUnion(geoms)
self.rectangle = QgsGeometry.fromRect(
union.boundingBox()
)
if layer.crs() != destCrs:
tr = QgsCoordinateTransform(layer.crs(), destCrs, self.project)
self.rectangle.transform(tr)
print(layer.extent())
print(layer.crs())
def clear_filter(self):
self.dlg.bound_log.setPlainText('')
self.rectangle = None
def accept(self):
currentTab = self.dlg.tab.currentWidget().objectName()
if self.manager.accepted or self.src_name=='GBIF' :
self.dlg.buttonBox.blockSignals(False)
if currentTab == 'import_2':
load = LoadingImport(
parent=self,network_manager=self.manager
)
# load.finished_dl.connect()
elif currentTab == 'status':
PivotStatus(
parent=self,network_manager=self.manager,
layer=self.dlg.map_layers.currentLayer(),
cd_nom=self.dlg.cd_taxon.currentText(),
)
# print("Work in progress ..")
# msg = QMessageBox()
# msg.warning(
# None,
# self.tr("Warning"),
# self.tr("Work in progress .."), # noqa: E501
# )
print("Accepted")
else:
msg = QMessageBox()
msg.warning(
None,
self.tr("Warning"),
self.tr("Opération impossible ! \nVous n'êtes pas connectez à GéoNature"), # noqa: E501
)
self.dlg.show()
def reject(self):
QApplication.restoreOverrideCursor()
print("Rejected")

View File

@ -0,0 +1,8 @@
#! python3 # noqa: E265
from .provider import GnToolsProvider # noqa: F401
from .login import GetLogin
from .widget import ParamWidget, LoadingImport
from .draw import RectangleFeatureTool
from .gbif import ImportDataGbif
from .status import PivotStatus
from .filter_synthese import GetFilterFromAPI

104
gn_tools/processing/draw.py Normal file
View File

@ -0,0 +1,104 @@
# Import PyQt libs
from PyQt5.QtCore import (
pyqtSignal,
Qt,
)
from PyQt5.QtGui import QColor
# Import PyQgis libs
from qgis.core import (
QgsRectangle,
QgsPointXY,
QgsWkbTypes,
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
)
from qgis.gui import (
QgsMapTool,
QgsMapMouseEvent,
QgsRubberBand,
)
class RectangleFeatureTool(QgsMapTool):
signal = pyqtSignal()
def __init__(self, project, canvas):
super().__init__(canvas)
self.project = project
self.canvas = canvas
# initiate variable to calculate the extent
self.start_point = None
self.end_point = None
self.new_extent = None
# flag to check if the left mouse button was pressed
self.is_left_button_pressed = False
# create a rubber line object
# to display the geometry of the dragged object on the canvas
self.rubber_band = QgsRubberBand(self.canvas, QgsWkbTypes.PolygonGeometry)
self.rubber_band.setColor(QColor(255, 0, 0, 50))
self.rubber_band.setWidth(2)
# Mouse button pressed.
def canvasPressEvent(self, event: QgsMapMouseEvent):
if event.button() == Qt.LeftButton:
self.start_point = self.toMapCoordinates(event.pos())
self.end_point = self.start_point
self.is_left_button_pressed = True
# The cursor moves across the screen.
def canvasMoveEvent(self, event: QgsMapMouseEvent):
# if the left mouse button is pressed
if self.is_left_button_pressed:
self.end_point = self.toMapCoordinates(event.pos())
# draw a rectangle on the canvas
self.showRect(self.start_point, self.end_point)
# The mouse button is released.
def canvasReleaseEvent(self, event: QgsMapMouseEvent):
# if the left mouse button was released
if event.button() == Qt.LeftButton:
if event.type() == 3:
# get the rectangle created from the click point and
# left mouse button release points
self.new_extent = self.rectangle()
self.signal.emit()
# toggle the flag, the left mouse button is no longer held down
self.is_left_button_pressed = False
self.rubber_band.reset() # remove rubber band from canvas
sourceCrs = QgsCoordinateReferenceSystem(self.project.crs())
destCrs = QgsCoordinateReferenceSystem(4326)
tr = QgsCoordinateTransform(sourceCrs, destCrs, self.project)
# Draw the rectangle on the canvas
def showRect(self, startPoint, endPoint):
# Reset the last drawn rectangle
self.rubber_band.reset(QgsWkbTypes.PolygonGeometry)
# Make sure the mouse has moved
if startPoint.x() == endPoint.x() or startPoint.y() == endPoint.y():
return
# Create the rectangle
point1 = QgsPointXY(startPoint.x(), startPoint.y())
point2 = QgsPointXY(startPoint.x(), endPoint.y())
point3 = QgsPointXY(endPoint.x(), endPoint.y())
point4 = QgsPointXY(endPoint.x(), startPoint.y())
self.rubber_band.addPoint(point1, False)
self.rubber_band.addPoint(point2, False)
self.rubber_band.addPoint(point3, False)
self.rubber_band.addPoint(point4, True) # true to update canvas
self.rubber_band.show()
def rectangle(self):
if self.start_point is None or self.end_point is None:
return None
elif self.start_point.x() == self.end_point.x() or self.start_point.y() == self.end_point.y():
return None
return QgsRectangle(self.start_point, self.end_point)
def deactivate(self):
# unload the map tool on the mouse
QgsMapTool.deactivate(self)
self.deactivated.emit()

View File

@ -0,0 +1,227 @@
# Standard
import json
# PyQt
from qgis.core import QgsAuthMethodConfig, QgsDataSourceUri
from qgis.PyQt.QtCore import QByteArray, QJsonDocument, QObject, QUrl, pyqtSignal, Qt
from qgis.PyQt.QtNetwork import QNetworkReply, QNetworkRequest
from qgis.PyQt.QtWidgets import QAction, QMessageBox, QDialog, QApplication
# Project
from gn_tools.__about__ import (
__orb_tax_url__
)
class GetFilterFromAPI(QDialog):
finished_params = pyqtSignal()
"""
Create a filter, specific to GeoNature ZH API and fetch all the features corresponding.
"""
def __init__(
self,
parent=None,
network_manager=None
):
super().__init__()
print("enfin !")
self.domain_url = parent.domain_url
self.tax_url = self.domain_url if parent.src_name == 'GéoNature' else __orb_tax_url__
if self.tax_url[-1] != '/':
self.tax_url += '/'
self.network_manager = network_manager
self.auth = parent.dlg.mAuthConfigSelect
self.is_connect = parent.dlg.is_connect
self.dlg = parent.dlg_syn
self.parent = parent
self.cookie = (self.network_manager.cookieJar()
.cookiesForUrl(QUrl(self.domain_url))[0]
)
# PyQt5 - Version
# PyQt6 - Version
# QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor)
self._pending_downloads = 0
# self.dlg.send_to_gn.
self.dlg.send_to_gn.setText(
self.dlg.send_to_gn.text() + '<br><br><a href="{url}">{url}</a>'.format(url=self.domain_url)
)
self.dlg.send_to_gn.setStyleSheet(
"border: 1px solid; border-color:blue; font-weight:bold"
)
self.dlg.send_to_gn.setOpenExternalLinks(True)
self.params = {}
self.get_jdd()
if self.parent.src_name == 'GéoNature':
self.get_phylog()
else:
self.self.dlg.regne.deselectAllOptions()
self.self.dlg.regne.clear()
self.dlg.buttonBox.accepted.connect(self.accept)
self.dlg.buttonBox.rejected.connect(self.reject)
@property
def pending_downloads(self):
return self._pending_downloads
def handle_finished(self, reply):
self._pending_downloads -= 1
# If reply is an error or reply is a redirection, login is not accepted
print(reply.attribute(
QNetworkRequest.HttpStatusCodeAttribute
))
print(reply.error(),' : ',reply.dtype)
self.network_manager.cookieStatus = reply.attribute(
QNetworkRequest.HttpStatusCodeAttribute
)
QApplication.restoreOverrideCursor()
if (
reply.error() != QNetworkReply.NoError
or self.network_manager.cookieStatus != 200
):
# Error code 299 means the logins are invalid
# Redirection not equal to 200 means a redirection happened
if reply.dtype == 'JDD':
self.dlg.jdd_box.setDisabled(True)
self.dlg.jdd_box.clear()
elif reply.dtype in ['PHYLOG','TAX_TREE']:
self.dlg.regne.setDisabled(True)
self.dlg.regne.clear()
if reply.error() == 0:
msg = QMessageBox()
msg.warning(
None,
self.tr("Warning"),
self.tr(
"Houston, we've got a problem ... \n\n L'utilisateur ou le mot de passe est invalide !"
), # noqa: E501
)
else:
print(f"code: {reply.error()} message: {reply.errorString()}")
else:
data_request = reply.readAll().data().decode()
data = json.loads(data_request)
self.params[reply.dtype] = data
self.close()
if self.pending_downloads == 1 :
self.get_taxon_tree()
if self.pending_downloads == 0:
self.set_params_to_widget()
self.finished_params.emit()
QApplication.restoreOverrideCursor()
def get_jdd(self):
self._pending_downloads += 1
QApplication.setOverrideCursor(Qt.WaitCursor)
self.dlg.jdd_box.setEnabled(True)
url_api = self.domain_url + 'api/meta/datasets?'
if self.parent.src_name == 'GéoNature':
url_api += 'orderby=dataset_shortname'
request_type = 'POST'
elif self.parent.src_name == "Biodiv'AuRA":
url_api += 'orderby=dataset_name'
request_type = 'GET'
url = QUrl(url_api)
self.send_request(url,type_request=request_type,type_param='JDD')
def get_phylog(self):
self._pending_downloads += 2
QApplication.setOverrideCursor(Qt.WaitCursor)
self.dlg.regne.setEnabled(True)
if self.parent.src_name == 'GéoNature':
url_api = self.tax_url + 'api/taxhub/api/taxref/regnewithgroupe2'
if self.parent.src_name == "Biodiv'AuRA":
url_api = self.tax_url + 'api/taxref/regnewithgroupe2'
url = QUrl(url_api)
self.send_request(url,type_request='GET',type_param='PHYLOG')
def get_taxon_tree(self):
QApplication.setOverrideCursor(Qt.WaitCursor)
if self.parent.src_name == 'GéoNature':
url_api = self.tax_url + 'api/synthese/taxons_tree'
url = QUrl(url_api)
self.send_request(url,type_request='GET',type_param='TAX_TREE')
else:
self._pending_downloads -= 1
self.set_params_to_widget()
self.finished_params.emit()
QApplication.restoreOverrideCursor()
def send_request(self,url,type_request,type_param):
print(url)
request = QNetworkRequest(url)
request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
request.setHeader(QNetworkRequest.CookieHeader, self.cookie)
if type_request == 'GET':
reply = self.network_manager.get(request)
elif type_request == 'POST':
doc = QJsonDocument({})
reply = self.network_manager.post(request,doc.toJson())
reply.dtype = type_param
reply.finished.connect(lambda: self.handle_finished(reply))
def set_params_to_widget(self):
if 'JDD' in self.params.keys():
jdd_items = [i['dataset_shortname'] for i in self.params['JDD']]
self.dlg.jdd_box.addItems(jdd_items)
if 'PHYLOG' in self.params.keys():
rgn_items = [i for i in self.params['PHYLOG'].keys()]
self.dlg.regne.addItems(rgn_items)
# self.dlg.jdd_box.setCheckedItems(items)
print('END loading params ...')
def accept(self):
params = {
'id_dataset':[ i['id_dataset']
for i in self.params['JDD']
if i['dataset_shortname'] in self.dlg.jdd_box.checkedItems()
] if 'JDD' in self.params.keys() else [],
'cd_ref_parent': [ i['cd_ref']
for i in self.params['TAX_TREE']
if i['nom_regne'] in self.dlg.regne.checkedItems()
] if 'PHYLOG' in self.params.keys() else [],
'date_min' : None if self.dlg.date_min.isNull()
else self.dlg.date_min.date().toString('yyyy-MM-dd'),
'date_max' : None if self.dlg.date_max.isNull()
else self.dlg.date_max.date().toString('yyyy-MM-dd'),
}
self.parent.syn_params = {
i : params[i] for i in params if params[i]
}
def reject(self):
self.clear_widgets()
QApplication.restoreOverrideCursor()
print("Rejected")
def clear_widgets(self):
self.dlg.jdd_box.deselectAllOptions()
self.dlg.regne.deselectAllOptions()
self.dlg.date_min.clear()
self.dlg.date_max.clear()

205
gn_tools/processing/gbif.py Normal file
View File

@ -0,0 +1,205 @@
# Import basic libs
import json
import time
# Import PyQt libs
from PyQt5.QtCore import QObject, pyqtSignal, QUrl, Qt, QVariant
from PyQt5.QtGui import QColor
from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply
from PyQt5.QtWidgets import QDialog, QPushButton, QApplication, QVBoxLayout, QHBoxLayout, QButtonGroup, QCheckBox, QLabel
# Import PyQgis libs
from qgis.utils import iface
from qgis.core import QgsProject, QgsFeature, QgsDataSourceUri, QgsRectangle, QgsNetworkAccessManager, QgsVectorLayer, QgsPointXY, QgsWkbTypes, QgsMapLayerProxyModel, QgsGeometry, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsField
from qgis.gui import QgsMapTool, QgsMapMouseEvent, QgsRubberBand, QgsMapLayerComboBox
class GetTaxrefId(QObject):
finished_dl = pyqtSignal()
"""Get multiples informations from a getcapabilities request.
List all layers available, get the maximal extent of all the Wfs' data."""
def __init__(self, network_manager=None, project=None, layer=None, field_name=None, field_rank=None):
super().__init__()
self.network_manager = network_manager
self.project = project
self.layer = layer
self.field_name = field_name
self.field_rank = field_rank
self._pending_downloads = 0
self.ids = []
self.names = []
self.rank = []
for obs in self.layer.getFeatures():
self.ids.append(obs.id())
self.names.append(obs[self.field_name])
self.rank.append(obs[self.field_rank])
self._pending_downloads = len(self.names)
self._iterate_names = 0
self.download(self.ids[self._iterate_names], self.names[self._iterate_names], self.rank[self._iterate_names])
@property
def pending_downloads(self):
return self._pending_downloads
@property
def iterate_names(self):
return self._iterate_names
def download(self, feature_id, nom, rank):
if rank.lower() == 'stateofmatter':
self._iterate_names += 1
self.download(self.ids[self._iterate_names], self.names[self._iterate_names], self.rank[self._iterate_names])
else:
if rank.lower() == 'complex' or rank.lower() == 'hybrid':
rank = 'species'
elif rank.lower() == 'epifamily' or rank.lower() == 'section':
rank = 'genus'
elif rank.lower() == 'subtribe':
rank = 'subfamily'
url = "https://api.checklistbank.org/nameusage/search?content=SCIENTIFIC_NAME&datasetKey=2008&facet=datasetKey&facet=rank&facet=issue&facet=status&facet=nomStatus&facet=nameType&facet=field&facet=authorship&facet=authorshipYear&facet=extinct&facet=environment&facet=origin&limit=50&offset=0&q={nom}&rank={rank}&type=PREFIX".format(nom=nom.split("(")[0], rank=rank.lower())
print(url)
request = QNetworkRequest(QUrl(url))
request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
reply = self.network_manager.get(request)
reply.finished.connect(lambda: self.handle_finished(reply, feature_id))
self._iterate_names += 1
def handle_finished(self, reply, feature_id):
self._pending_downloads -= 1
if reply.error() != QNetworkReply.NoError:
print(f"code: {reply.error()} message: {reply.errorString()}")
if reply.error() == 403:
print("Service down")
else:
data_request = reply.readAll().data().decode()
if data_request != "":
res = json.loads(data_request)
if "result" in res:
taxref_id = res["result"][0]["id"]
taxref_name = res["result"][0]["usage"]["label"]
self.layer.startEditing()
self.layer.changeAttributeValue(feature_id, self.layer.fields().indexFromName("cd_nom"), taxref_id)
self.layer.changeAttributeValue(feature_id, self.layer.fields().indexFromName("nom_scien"), taxref_name)
self.layer.commitChanges()
self.layer.triggerRepaint()
if self.pending_downloads == 0:
self.project.addMapLayer(self.layer)
self.finished_dl.emit()
else:
self.download(self.ids[self._iterate_names], self.names[self._iterate_names], self.rank[self._iterate_names])
class ImportDataGbif(QObject):
finished_dl = pyqtSignal()
"""Get multiples informations from a getcapabilities request.
List all layers available, get the maximal extent of all the Wfs' data."""
def __init__(self, network_manager=None, project=None, geom=None, ):
super().__init__()
self._pending_downloads = 0
self._pending_pages = 1
self.network_manager = network_manager
self.project = project
self.layer = self.new_layer()
self.geom = geom
self.new_features = []
self.max_obs = 0
self.total_pages = 0
self.download()
@property
def pending_downloads(self):
return self._pending_downloads
@property
def pending_pages(self):
return self._pending_pages
def new_layer(self):
geom_type = "Point"
new_layer = QgsVectorLayer(geom_type + "?crs=epsg:4326", "GBIF", "memory")
new_layer.startEditing()
new_layer.addAttribute(QgsField("id", QVariant.String, "string", 254))
new_layer.addAttribute(QgsField("cd_nom", QVariant.Int, "integer", 10))
new_layer.addAttribute(QgsField("niveau", QVariant.String, "string", 254))
new_layer.addAttribute(QgsField("nom", QVariant.String, "string", 254))
new_layer.addAttribute(QgsField("nom_scien", QVariant.String, "string", 100000))
new_layer.addAttribute(QgsField("observat", QVariant.String, "string", 254))
new_layer.addAttribute(QgsField("date", QVariant.String, "string", 254))
new_layer.addAttribute(QgsField("projet", QVariant.String, "string", 254))
new_layer.addAttribute(QgsField("effectif", QVariant.Int, "integer", 10))
new_layer.addAttribute(QgsField("url", QVariant.String, "string", 254))
new_layer.commitChanges()
new_layer.triggerRepaint()
return new_layer
def download(self):
url = "https://api.gbif.org/v1/occurrence/search?advanced=false&geometry={polygon}&offset={offset}&limit=1000".format(
offset=self.pending_pages, polygon=self.geom.asWkt())
url = QUrl(url)
self.nb_request = 1
print(url)
request = QNetworkRequest(url)
request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
reply = self.network_manager.get(request)
reply.finished.connect(lambda: self.handle_finished(reply))
self._pending_downloads += 1
def handle_finished(self, reply):
self._pending_downloads -= 1
if reply.error() != QNetworkReply.NoError:
print(f"code: {reply.error()} message: {reply.errorString()}")
if reply.error() == 403:
print("Service down")
else:
data_request = reply.readAll().data().decode()
if self.pending_downloads == 0:
res = json.loads(data_request)
self.max_obs = res["count"]
self.total_pages = int(self.max_obs/20) + 1
for obs in res["results"]:
new_geom = QgsGeometry.fromPointXY(QgsPointXY(obs["decimalLongitude"], obs["decimalLatitude"]))
new_feature = QgsFeature(self.layer.fields())
new_feature.setGeometry(new_geom)
new_feature.setAttribute(0, str(obs["key"]))
new_feature.setAttribute(1, 0)
new_feature.setAttribute(2, obs["taxonRank"])
if obs["taxonRank"].lower() in ['kingdom', 'phylum', 'order', 'family', 'genus', 'species']:
new_feature.setAttribute(3, obs[obs["taxonRank"].lower()])
else:
new_feature.setAttribute(3, obs["scientificName"])
new_feature.setAttribute(4, "")
new_feature.setAttribute(5, "")
new_feature.setAttribute(6, str(obs["eventDate"]))
# new_feature.setAttribute(7, obs["_datasetKey"]["title"])
new_feature.setAttribute(7, obs["datasetName"] if "datasetName" in obs.keys() else None )
new_feature.setAttribute(8, 1)
new_feature.setAttribute(9, "https://www.gbif.org/fr/occurrence/" + str(obs["key"]))
self.new_features.append(new_feature)
if self.nb_request == 10:
time.sleep(10)
if self.pending_pages < self.total_pages:
self._pending_pages += 300
self.nb_request += 1
self.download()
else:
# Add the new feature to the temporary layer
self.layer.startEditing()
self.layer.dataProvider().addFeatures(self.new_features)
self.layer.updateExtents()
self.layer.commitChanges()
self.layer.triggerRepaint()
GetTaxrefId(self.network_manager, self.project, self.layer, "nom", "niveau")
self.finished_dl.emit()

View File

@ -0,0 +1,173 @@
# Standard
import json
# PyQt
from qgis.core import QgsAuthMethodConfig, QgsDataSourceUri
from qgis.PyQt.QtCore import QByteArray, QJsonDocument, QObject, QUrl, pyqtSignal
from qgis.PyQt.QtNetwork import QNetworkReply, QNetworkRequest
from qgis.PyQt.QtWidgets import QAction, QMessageBox, QDialog
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
# from PyQt6.QtCore import Qt
# from PyQt6.QtWidgets import QApplication
# Project
from gn_tools.__about__ import __login_url__
class GetLogin(QDialog):
finished_login = pyqtSignal()
"""
Create a filter, specific to GeoNature ZH API and fetch all the features corresponding.
"""
def __init__(
self,
parent=None,
network_manager=None,
params=None
):
super().__init__()
print("enfin !")
self.domain_url = parent.domain_url
self.network_manager = network_manager
self.auth = parent.dlg.mAuthConfigSelect
self.is_connect = parent.dlg.is_connect
self.params = params
print(self.auth.configId())
# self.zhs = None
# self.json_filter = {}
# self.total_zh = 0
# PyQt5 - Version
QApplication.setOverrideCursor(Qt.WaitCursor)
# PyQt6 - Version
# QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor)
self._pending_downloads = 0
self.check_password()
@property
def pending_downloads(self):
return self._pending_downloads
def handle_finished(self, reply):
self._pending_downloads -= 1
QApplication.restoreOverrideCursor()
# If reply is an error or reply is a redirection, login is not accepted
print(reply.attribute(
QNetworkRequest.HttpStatusCodeAttribute
))
print('Login : ',reply.error())
self.network_manager.cookieStatus = reply.attribute(
QNetworkRequest.HttpStatusCodeAttribute
)
if (
reply.error() != QNetworkReply.NoError
or self.network_manager.cookieStatus != 200
):
# Error code 299 means the logins are invalid
# Redirection not equal to 200 means a redirection happened
if reply.error() == 0:
self.is_connect.setText("Aie !")
msg = QMessageBox()
msg.warning(
None,
self.tr("Warning"),
self.tr(
"Houston, we've got a problem ... \n\n L'utilisateur ou le mot de passe est invalide !"
), # noqa: E501
)
elif reply.error() == 3:
msg = QMessageBox()
msg.warning(
None,
self.tr("Warning"),
self.tr(
"GéoNature's URL not found, add it to the plugin settings"
), # noqa: E501
)
self.close()
self.parent.iface.showOptionsDialog(
currentPage="mOptionsPage{}".format(__title__)
)
self.parent.create_project_from_gn()
else:
print(f"code: {reply.error()} message: {reply.errorString()}")
else:
self.cookies = self.network_manager.cookieJar()
self.is_connect.setText("Good Job !")
# If the authenfication configuration already exists,
# modify it with the new values
# self.manager_config.setConfigMap(
# {
# "password": self.usr,
# "username": self.pwd,
# }
# )
# self.manager.storeAuthenticationConfig(
# self.manager_config, True
# )
# delete sensitive informations... even if it's in the database now...
self.network_manager.accepted = True
# Add the cookie created with the login to the request
self.network_manager.setCookieJar(self.cookies)
# self.network_manager.setCookiesFromUrl(self.cookies,self.domain_url)
self.close()
if self.pending_downloads == 0:
self.finished_login.emit()
return self.network_manager
def get_param_connect(self):
if self.params:
self.usr = self.params["usr"]
self.pwd = self.params["pwd"]
return True
elif self.auth.configId():
authCfg = self.auth.configId()
quri = QgsDataSourceUri()
quri.setParam("authcfg", authCfg)
quri.setParam("url", self.domain_url)
self.usr = quri.uri().split("user='")[1].split("' ",1)[0]
self.pwd = quri.uri().split("password='")[1].split("' ",1)[0]
return True
else :
return False
def check_password(self):
# Test if the user wrote something
if self.auth.configId() or self.params:
is_connect = self.get_param_connect()
url = QUrl(self.domain_url + __login_url__)
print(self.usr)
data_json = {
"login": (
self.usr
),
"password": (
self.pwd
),
}
print(url)
request = QNetworkRequest(url)
request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
document = QJsonDocument(data_json)
print(document.toJson())
reply = self.network_manager.post(request, document.toJson())
reply.finished.connect(lambda: self.handle_finished(reply))
self._pending_downloads += 1
else:
msg = QMessageBox()
msg.warning(
None,
self.tr("Warning"),
self.tr(
"GéoNature's Auth not found, add it to the plugin settings"
), # noqa: E501
)

View File

@ -0,0 +1,88 @@
#! python3 # noqa: E265
"""
Processing provider module.
"""
# PyQGIS
from qgis.core import QgsProcessingProvider
from qgis.PyQt.QtCore import QCoreApplication
from qgis.PyQt.QtGui import QIcon
# project
from gn_tools.__about__ import (
__icon_path__,
__title__,
__version__,
)
# ############################################################################
# ########## Classes ###############
# ##################################
class GnToolsProvider(QgsProcessingProvider):
"""Processing provider class."""
def loadAlgorithms(self):
"""Loads all algorithms belonging to this provider."""
pass
def id(self) -> str:
"""Unique provider id, used for identifying it. This string should be unique, \
short, character only string, eg "qgis" or "gdal". \
This string should not be localised.
:return: provider ID
:rtype: str
"""
return "gn_tools"
def name(self) -> str:
"""Returns the provider name, which is used to describe the provider
within the GUI. This string should be short (e.g. "Lastools") and localised.
:return: provider name
:rtype: str
"""
return __title__
def longName(self) -> str:
"""Longer version of the provider name, which can include
extra details such as version numbers. E.g. "Lastools LIDAR tools". This string should be localised. The default
implementation returns the same string as name().
:return: provider long name
:rtype: str
"""
return self.tr("{} - Tools".format(__title__))
def icon(self) -> QIcon:
"""QIcon used for your provider inside the Processing toolbox menu.
:return: provider icon
:rtype: QIcon
"""
return QIcon(str(__icon_path__))
def tr(self, message: str) -> str:
"""Get the translation for a string using Qt translation API.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: str
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate(self.__class__.__name__, message)
def versionInfo(self) -> str:
"""Version information for the provider, or an empty string if this is not \
applicable (e.g. for inbuilt Processing providers). For plugin based providers, \
this should return the plugins version identifier.
:return: version
:rtype: str
"""
return __version__

View File

@ -0,0 +1,469 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# import requests
# import numpy as np
# import pandas as pd
# import os
# Standard
import json
from qgis.core import QgsGeometry, QgsProject, QgsJsonUtils, QgsVectorLayer
# PyQt
from qgis.PyQt.QtCore import (
QUrl,
pyqtSignal,
QJsonDocument,
Qt,
QTextCodec
)
from qgis.PyQt.QtNetwork import QNetworkReply, QNetworkRequest
from qgis.PyQt.QtWidgets import (
QAction,
QMessageBox,
QDialog,
QApplication
)
from gn_tools.__about__ import __api_cd_sta__
def get_status(lst,con):
sql = """
SELECT
t.cd_nom,
t.cd_ref,
t.regne,
t.phylum,
t.classe,
t.ordre,
t.famille,
t.group1_inpn,
t.group2_inpn,
t.group3_inpn,
t.nom_vern,
t.nom_complet,
t.nom_valide,
t.lb_nom,
--s.*
s.cd_sig,
s.rq_statut,
s.code_statut,
s.cd_type_statut,
s.label_statut,
s.niveau_admin,
s.full_citation,
s.doc_url
FROM taxonomie.taxref t
JOIN taxonomie.v_bdc_status s USING (cd_nom)
WHERE t.cd_nom IN {cd_nom}
;""".format(cd_nom = tuple(lst))
return pd.read_sql_query(sql,con)
def get_type_status(con):
sql = """
SELECT * FROM taxonomie.bdc_statut_type
;"""
return pd.read_sql_query(sql,con)
def get_api_status(api,cd_nom:int):
res = requests.api.get('%s/%i'%(api,cd_nom))
if res.status_code == 200:
return res.json()
else :
raise('Error : %i\tcd_nom : %i'%(res.status_code,cd_nom))
def get_taxon_status(lst,api):
from datetime import datetime as dt
init = dt.now()
st = [get_api_status(api,x) for x in lst] # TOO LONG
print(dt.now()-init)
phylo = {
'cd_ref':[x['cd_ref'] for x in st],
'nom_valide':[x['nom_valide'] if 'nom_valide' in x.keys() else None for x in st],
'nom_vernac':[x['nom_vern'] if 'nom_vern' in x.keys() else None for x in st],
'regne':[x['regne'] if 'regne' in x.keys() else None for x in st],
'group1_inp':[x['group1_inpn'] if 'group1_inpn' in x.keys() else None for x in st],
'group2_inp':[x['group2_inp'] if 'group2_inp' in x.keys() else None for x in st],
'group3_inpn':[x['group3_inpn'] for x in st],
'classe':[x['classe'] if 'classe' in x.keys() else None for x in st],
'ordre':[x['ordre'] if 'ordre' in x.keys() else None for x in st],
'famille':[x['famille'] if 'famille' in x.keys() else None for x in st]}
cd_status = {
'AL':[
[val['values'][v]['code_statut']
for val in x['status']['AL']['text'].values() for v in val['values'] ]
if 'AL' in x['status'].keys() else None
for x in st
],
'BERN':[
[val['values'][v]['code_statut']
for val in x['status']['BERN']['text'].values() for v in val['values'] ]
if 'BERN' in x['status'].keys() else None
for x in st
],
'BONN':[
[val['values'][v]['code_statut']
for val in x['status']['BONN']['text'].values() for v in val['values'] ]
if 'BONN' in x['status'].keys() else None
for x in st
],
'DH':[
[val['values'][v]['code_statut']
for val in x['status']['DH']['text'].values() for v in val['values'] ]
if 'DH' in x['status'].keys() else None
for x in st
],
'DO':[
[val['values'][v]['code_statut']
for val in x['status']['DO']['text'].values() for v in val['values'] ]
if 'DO' in x['status'].keys() else None
for x in st
],
'LRE':[
[val['values'][v]['code_statut']
for val in x['status']['LRE']['text'].values() for v in val['values'] ]
if 'LRE' in x['status'].keys() else None
for x in st
],
'LRM':[
[val['values'][v]['code_statut']
for val in x['status']['LRM']['text'].values() for v in val['values'] ]
if 'LRM' in x['status'].keys() else None
for x in st
],
'LRN':[
[val['values'][v]['code_statut']
for val in x['status']['LRN']['text'].values() for v in val['values'] ]
if 'LRN' in x['status'].keys() else None
for x in st
],
'LRR':[
[val['values'][v]['code_statut']
for val in x['status']['LRR']['text'].values() for v in val['values'] ]
if 'LRR' in x['status'].keys() else None
for x in st
],
'PAPNAT':[
[val['values'][v]['code_statut']
for val in x['status']['PAPNAT']['text'].values() for v in val['values'] ]
if 'PAPNAT' in x['status'].keys() else None
for x in st
],
'PD':[
[val['values'][v]['code_statut']
for val in x['status']['PD']['text'].values() for v in val['values'] ]
if 'PD' in x['status'].keys() else None
for x in st
],
'PNA':[
[val['values'][v]['code_statut']
for val in x['status']['PNA']['text'].values() for v in val['values'] ]
if 'PNA' in x['status'].keys() else None
for x in st
],
'PR':[
[val['values'][v]['code_statut']
for val in x['status']['PR']['text'].values() for v in val['values'] ]
if 'PR' in x['status'].keys() else None
for x in st
],
'REGL':[
[val['values'][v]['code_statut']
for val in x['status']['REGL']['text'].values() for v in val['values'] ]
if 'REGL' in x['status'].keys() else None
for x in st
],
'REGLII':[
[val['values'][v]['code_statut']
for val in x['status']['REGLII']['text'].values() for v in val['values'] ]
if 'REGLII' in x['status'].keys() else None
for x in st
],
'REGLLUTTE':[
[val['values'][v]['code_statut']
for val in x['status']['REGLLUTTE']['text'].values() for v in val['values'] ]
if 'REGLLUTTE' in x['status'].keys() else None
for x in st
],
'REGLSO':[
[val['values'][v]['code_statut']
for val in x['status']['REGLSO']['text'].values() for v in val['values'] ]
if 'REGLSO' in x['status'].keys() else None
for x in st
],
'SCAP NAT':[
[val['values'][v]['code_statut']
for val in x['status']['SCAP NAT']['text'].values() for v in val['values'] ]
if 'SCAP NAT' in x['status'].keys() else None
for x in st
],
'SCAP REG':[
[val['values'][v]['code_statut']
for val in x['status']['SCAP REG']['text'].values() for v in val['values'] ]
if 'SCAP REG' in x['status'].keys() else None
for x in st
],
'SENSNAT':[
[val['values'][v]['code_statut']
for val in x['status']['SENSNAT']['text'].values() for v in val['values'] ]
if 'SENSNAT' in x['status'].keys() else None
for x in st
],
'ZDET':[
[val['values'][v]['code_statut']
for val in x['status']['ZDET']['text'].values() for v in val['values'] ]
if 'ZDET' in x['status'].keys() else None
for x in st
],
'exPNA':[
[val['values'][v]['code_statut']
for val in x['status']['exPNA']['text'].values() for v in val['values'] ]
if 'exPNA' in x['status'].keys() else None
for x in st
]
}
return pd.DataFrame({**phylo,**cd_status})
def filter_bio_geo(df,zone_bio):
idNotBioGeo = []
# Filtre du dommaine biogeographique sur la plaine Rhodanienne et Alpine
test_rhod = df.rq_statut.str.contains('rhodanienne : Non déterminante')
test_alpi = df.rq_statut.str.contains('Alpine : Non déterminante')
if zone_bio == 'rhod':
idNotBioGeo = df[test_rhod].index
elif zone_bio == 'alpi':
idNotBioGeo = df[test_alpi].index
elif zone_bio == 'all':
idNotBioGeo = df[test_rhod&test_alpi].index
if not idNotBioGeo.empty:
df.drop(idNotBioGeo, inplace=True)
return df
def form_territoire(df,terr):
is_dep = df.cd_sig.str.contains('INSEED')
is_38 = df.cd_sig=='INSEED38'
if terr == 'isere':
filter_id = df[is_dep&(~is_38)].index
df.drop(filter_id,inplace=True)
elif terr == 'platiere':
lst_stat = df[is_dep&(~is_38)].cd_type_statut.unique()
# is_lst = df.cd_type_statut.isin(lst_stat)
df.loc[is_dep&(~is_38),'cd_type_statut'] = ( df[is_dep&(~is_38)]
.cd_type_statut + '_' + df[is_dep&(~is_38)].cd_sig.str.strip('INSEED')
)
df.loc[is_38,'cd_type_statut'] = ( df[is_38]
.cd_type_statut + '_38'
)
return df
dict_dep = {
'38':'Isère',
'42':'Loire',
'07':'Ardèche',
'26':'Drôme',
}
class PivotStatus(QDialog):
finished_dl = pyqtSignal()
"""
Create a filter, specific to GeoNature ZH API and fetch all the features corresponding.
"""
def __init__(
self,
parent=None,
network_manager=None,
layer=None,
cd_nom=None
):
super().__init__()
print(parent.dlg.tab)
self.dlg = parent.dlg
self.src_name = parent.src_name
self.domain_url = parent.domain_url
self.network_manager = network_manager
self.layer = layer
self.cd_nom = cd_nom
self.url_api = self.domain_url + __api_cd_sta__
# QApplication.setOverrideCursor(Qt.WaitCursor)
self.multi_dep = True
self.cookie = (self.network_manager.cookieJar()
.cookiesForUrl(QUrl(self.domain_url))[0]
)
self._pending_downloads = 0
self.import_status()
@property
def pending_downloads(self):
return self._pending_downloads
def import_status(self):
idx = self.layer.fields().indexOf(self.cd_nom)
unique_cd = self.layer.uniqueValues(idx)
print(len(unique_cd))
self.res = {}
self.get_status(unique_cd)
def get_status(self,cd_nom):
self._pending_downloads += 1
url = QUrl(
self.url_api
+ '?fields=status&cd_nom='
+ ','.join(map(str,cd_nom))
)
request = QNetworkRequest(url)
request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
request.setHeader(QNetworkRequest.CookieHeader, self.cookie)
reply = self.network_manager.get(request)
reply.finished.connect(lambda: self.import_finished(reply))
def import_finished(self, reply):
self._pending_downloads -= 1
print(reply.attribute(QNetworkRequest.HttpStatusCodeAttribute))
if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) != 200:
print(f"code: {reply.error()} message: {reply.errorString()}")
else:
data_request = reply.readAll().data().decode()
data = json.loads(data_request)
self.layer_type = self.layer.wkbType().name
self.layer_crs = self.layer.crs()
bdc = self.v_bdc_status(data)
bdc_cd = self._v_bdc_(data,'code')
bdc_lab = self._v_bdc_(data,'label')
self.add_new_layer(bdc)
self.add_new_layer(bdc_cd)
self.add_new_layer(bdc_lab)
# remak_data = {
# "features" :[
# {
# "geometry":
# json.loads(
# QgsGeometry.unaryUnion([
# g.geometry() for g in self.layer.getFeatures()
# if g.attribute(name_cd_nom) == i['cd_ref']
# ]).asJson()
# ),
# "properties" : i ,
# "type": "Feature"
# }
# for i in data['items']
# ],
# "type": "FeatureCollection",
# "geom_type": "Multi"+layer_type
# }
# fcString = json.dumps(remak_data)
# codec = QTextCodec.codecForName("UTF-8")
# fields = QgsJsonUtils.stringToFields(fcString, codec)
# feats = QgsJsonUtils.stringToFeatureList(fcString, fields, codec)
# vl = QgsVectorLayer(remak_data['geom_type'], lay_status_name, "memory")
# if vl.sourceCrs() != layer_crs:
# print('Changed crs !')
# # crs = vl.crs()
# # crs.createFromId(self.api['geometry_srid'])
# vl.setCrs(layer_crs)
# dp = vl.dataProvider()
# dp.addAttributes(fields)
# vl.updateFields()
# dp.addFeatures(feats)
# vl.updateExtents()
if self.pending_downloads == 0:
self.finished_dl.emit()
QApplication.restoreOverrideCursor()
def v_bdc_status(self,data):
return {
"features" :[
{
"properties" : {**{
ii:i[ii]
for ii in i if ii != 'status'
},
**ii
},
"type": "Feature"
}
for i in data['items']
for ii in i['status']
],
"type": "FeatureCollection",
"geom_type": "No geometry",
"layer_name": 'Status - ' + self.layer.name()
}
def _v_bdc_(self,data,type_status):
dtype = 'code_statut' if type_status=='code' else 'label_statut'
return {
"features" :[
{
"geometry": json.loads(
QgsGeometry.unaryUnion([
g.geometry() for g in self.layer.getFeatures()
if g.attribute(self.cd_nom) == i['cd_ref']
]).asJson()
),
"properties" : {
**{
ii:i[ii]
for ii in i if ii != 'status'
}, **{
ii['cd_type_statut'] + '_' + ii['cd_sig'].strip('INSEED')
if self.multi_dep and 'INSEED' in ii['cd_sig']
else ii['cd_type_statut'] : ii[dtype]
for ii in i['status']
}
},
"type": "Feature"
}
for i in data['items']
],
"type": "FeatureCollection",
"geom_type": self.layer_type if "Multi" in self.layer_type else "Multi" + self.layer_type,
"layer_name": 'Status %s - '%type_status + self.layer.name()
}
def add_new_layer(self,data):
geom_type = data['geom_type']
layername = data['layer_name']
fcString = json.dumps(data)
codec = QTextCodec.codecForName("UTF-8")
fields = QgsJsonUtils.stringToFields(fcString, codec)
feats = QgsJsonUtils.stringToFeatureList(fcString, fields, codec)
vl = QgsVectorLayer(geom_type, layername, "memory")
if vl.sourceCrs() != self.layer_crs:
print('Changed crs !')
# crs = vl.crs()
# crs.createFromId(self.api['geometry_srid'])
vl.setCrs(self.layer_crs)
dp = vl.dataProvider()
dp.addAttributes(fields)
vl.updateFields()
dp.addFeatures(feats)
vl.updateExtents()
QgsProject.instance().addMapLayer(vl)

View File

@ -0,0 +1,441 @@
# Standard
import json
# PyQt
from qgis.core import (
QgsAuthMethodConfig,
QgsDataSourceUri,QgsVectorLayer,
QgsJsonUtils,
QgsProject,
QgsCoordinateReferenceSystem,
QgsCoordinateTransform
)
from qgis.PyQt.QtCore import (
QByteArray,
QJsonDocument,
QObject,
QUrl,
pyqtSignal,
QTextCodec,
Qt
)
from qgis.PyQt.QtNetwork import QNetworkReply, QNetworkRequest
from qgis.PyQt.QtWidgets import QAction, QMessageBox, QDialog, QApplication
# from PyQt5.QtCore import Qt
# from PyQt5.QtWidgets import QApplication
# from PyQt6.QtCore import Qt
# from PyQt6.QtWidgets import QApplication
# Project
from gn_tools.__about__ import (
__api_sn_web__,
__api_sn_exp__,
__api_lst_ex__,
__exept_export__,
)
# from gn_tools.processing import ImportDataGbif
from .gbif import ImportDataGbif
dict_exp = []
class ParamWidget(QDialog):
finished_dl = pyqtSignal()
"""
Create a filter, specific to GeoNature ZH API and fetch all the features corresponding.
"""
def __init__(
self,
parent=None,
network_manager=None
):
super().__init__()
print(parent.dlg.tab)
self.dlg = parent.dlg
self.src_name = parent.src_name
self.domain_url = parent.domain_url
self.network_manager = network_manager
# self.zhs = None
# self.json_filter = {}
# self.total_zh = 0
self._pending_downloads = 0
if self.src_name == 'GBIF':
self.dlg.source_import.addItems(['Synthèse GBIF'])
self.dlg.source_import.currentTextChanged.connect(
self.print_change
)
else :
QApplication.setOverrideCursor(Qt.WaitCursor)
self.cookie = (network_manager.cookieJar()
.cookiesForUrl(QUrl(self.domain_url))[0]
)
self.send_tab_import()
@property
def pending_downloads(self):
return self._pending_downloads
def send_tab_import(self):
if self.src_name == 'GBIF':
self.dlg.source_import.addItems(['Synthèse GBIF'])
self.dlg.source_import.currentTextChanged.connect(
self.print_change
)
else :
self.dlg.source_import.clear()
request = self.get_api(api=__api_lst_ex__)
reply = self.network_manager.get(request)
reply.finished.connect(lambda: self.import_finished(reply))
# reply_exp
# dict_exp = {i for i in exp_all if exp_all[i].geometry_srid and 'sinp' not in exp_all[i].label.lower}
# lst_exp = [i.label for i in dict_exp]
# # self.dlg.source_import.setText(self.tr("Choose source data"))
# self.dlg.source_import.addItems(lst_exp)
# self.dlg.source_import.currentTextChanged.connect(
# self.print_change
# )
def import_finished(self, reply):
self._pending_downloads -= 1
QApplication.restoreOverrideCursor()
print(reply.attribute(QNetworkRequest.HttpStatusCodeAttribute))
if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) != 200:
print(f"code: {reply.error()} message: {reply.errorString()}")
else:
self.lst_exp = ['Synthèse taxons']
if self.src_name == 'GéoNature':
data_request = reply.readAll().data().decode()
data = json.loads(data_request)
items = data['items']
self.dlg.dict_exp = [i for i in items if i['geometry_srid'] ]
if len(__exept_export__) > 0:
for j in __exept_export__ :
self.dlg.dict_exp = [i for i in self.dlg.dict_exp if j not in i['label'].lower()]
self.lst_exp += [i['label'] for i in self.dlg.dict_exp]
self.dlg.source_import.addItems(self.lst_exp)
self.dlg.source_import.currentTextChanged.connect(
self.print_change
)
if self.pending_downloads == 0:
self.finished_dl.emit()
def print_change(self):
print(self.dlg.source_import.currentIndex())
def get_api(self,api=None,apiFilter=None):
self._pending_downloads += 1
# Function launched two times, one to check zh number the other to dl them
url_api = self.domain_url
if api:
url_api += str(api)
url = QUrl(url_api)
print(url)
# Define request properties (cookie, header)
request = QNetworkRequest(url)
request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
request.setHeader(QNetworkRequest.CookieHeader, self.cookie)
if apiFilter:
doc = QJsonDocument(self.json_filter)
else:
doc = QJsonDocument({})
return request
# data_request = reply.readAll().data().decode()
# print('tom')
# print(data_request)
# return json.loads(data_request)
# print(data)
class LoadingImport(QDialog):
finished_dl = pyqtSignal()
"""
Create a filter, specific to GeoNature ZH API and fetch all the features corresponding.
"""
def __init__(
self,
parent=None,
network_manager=None
):
super().__init__()
print(parent.dlg.tab)
self.dlg = parent.dlg
self.syn_params = parent.syn_params
self.source = self.dlg.source_import.currentText()
self.src_name = parent.src_name
self.domain_url = parent.domain_url
self.network_manager = network_manager
self.cookie = (network_manager.cookieJar()
.cookiesForUrl(QUrl(self.domain_url))[0]
) if self.src_name != 'GBIF' else None
self.rectangle = parent.rectangle
self.syn_params = parent.syn_params
self.project = parent.project
# self.zhs = None
# self.json_filter = {}
# self.total_zh = 0
QApplication.setOverrideCursor(Qt.WaitCursor)
self._pending_downloads = 0
self.run()
@property
def pending_downloads(self):
return self._pending_downloads
def run(self,items=None):
self._pending_downloads += 1
self.api = None
if self.source == 'Synthèse taxons':
url_api = self.domain_url + __api_sn_web__
self.transform_bouds(4326)
url_api += '?limit=800000'
if self.src_name == 'GéoNature':
geo_param = {
"geoIntersection": {
"type": "Feature",
"properties": {},
"geometry": json.loads(self.rectangle.asJson())
}
} if self.rectangle else {}
elif self.src_name == "Biodiv'AuRA":
geo_param = {
"geoIntersection": self.rectangle.asWkt(),
"with_areas":False
} if self.rectangle else {}
json_param = {
"modif_since_validation": False,
**geo_param,
**self.syn_params
}
doc = QJsonDocument(
json_param
)
print(doc.toJson())
elif self.source == 'Synthèse taxons export':
url_api = self.domain_url + __api_sn_exp__
url_api += '?export_format=geojson'
if self.src_name == 'GéoNature':
lst_id_synth = [
i['properties']['id_synthese']
for i in items['features']
]
elif self.src_name == "Biodiv'AuRA":
lst_id_synth = [
j['id']
for i in items['features']
for j in i['properties']['observations']
]
doc = QJsonDocument(lst_id_synth)
elif self.source == 'Synthèse GBIF':
ImportDataGbif(
self.network_manager, self.project, self.rectangle
)
# self.close()
return QApplication.restoreOverrideCursor()
# self.cookie = None
# url_api = self.domain_url
# url_api += '?advanced=false&geometry={polygon}&offset={offset}'.format(
# offset=1, polygon=self.rectangle.asWkt())
elif self.source in [i['label'] for i in self.dlg.dict_exp]:
self.api = [i for i in self.dlg.dict_exp if i['label'] == self.source][0]
url_api = self.domain_url + 'api/exports/api/%i'%self.api['id']
self.transform_bouds(self.api['geometry_srid'])
url_api += '?limit=0'
if self.rectangle :
url_api += "&geometry=" + str(self.rectangle.asWkt())
url = QUrl(url_api)
print(url)
# print('crs rect : ',self.rectangle.sourceCrs())
# Define request properties (cookie, header)
request = QNetworkRequest(url)
request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
if self.cookie:
request.setHeader(QNetworkRequest.CookieHeader, self.cookie)
if 'Synthèse taxons' in self.source :
reply = self.network_manager.post(request,doc.toJson())
else:
reply = self.network_manager.get(request)
reply.finished.connect(lambda: self.loading_finished(reply))
def loading_finished(self,reply):
self._pending_downloads -= 1
print(reply.attribute(QNetworkRequest.HttpStatusCodeAttribute))
if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) != 200:
print(f"code: {reply.error()} message: {reply.errorString()}")
else:
data_request = reply.readAll().data().decode()
data = json.loads(data_request)
items = data['items'] if 'items' in data.keys() else data
if self.source == 'Synthèse taxons':
self.source = 'Synthèse taxons export'
self.run(items)
return
items_point,items_poly,items_line = self.filter_gn_geom(items)
if items_point['features']:
self.addMapLayer(items_point,items_point['geom_type'])
if items_poly['features']:
self.addMapLayer(items_poly,items_poly['geom_type'])
if items_line['features']:
self.addMapLayer(items_line,items_line['geom_type'])
if self.pending_downloads == 0:
self.finished_dl.emit()
QApplication.restoreOverrideCursor()
print("END")
def filter_gn_geom(self,items):
nb_items = len(items['features'])
print('total_count : ',nb_items)
items_poly = {"features":[],"type": "FeatureCollection","geom_type": "MultiPolygon"}
items_line = {"features":[],"type": "FeatureCollection","geom_type": "MultiLine"}
items_point = {
"features":[i for i in items['features'] if 'point' in i['geometry']['type'].lower()],
"type": "FeatureCollection",
"geom_type": "Point"
}
len_data = len(items_point['features'])
if nb_items> len_data:
items_poly = {
"features":[i for i in items['features'] if 'polygon' in i['geometry']['type'].lower()],
"type": "FeatureCollection",
"geom_type": "MultiPolygon"
}
len_data += len(items_poly['features'])
if nb_items> len_data:
items_line = {
"features":[i for i in items['features'] if 'line' in i['geometry']['type'].lower()],
"type": "FeatureCollection",
"geom_type": "MultiLineString"
}
len_data += len(items_line['features'])
return items_point,items_poly,items_line
# def filter_biodiv_geom(self,items):
# items_point = {
# "features":[ {
# 'geometry' : i['geometry'],
# 'properties': j
# }
# for i in items['features'] if 'point' in i['geometry']['type'].lower()
# for j in i['properties']['observations']
# ],
# "type": "FeatureCollection",
# "geom_type": "Point"
# }
# items_poly = {
# "features":[ {
# 'geometry' : i['geometry'],
# 'properties': j
# }
# for i in items['features'] if 'polygon' in i['geometry']['type'].lower()
# for j in i['properties']['observations']
# ],
# "type": "FeatureCollection",
# "geom_type": "MultiPolygon"
# }
# items_line = {
# "features":[ {
# 'geometry' : i['geometry'],
# 'properties': j
# }
# for i in items['features'] if 'line' in i['geometry']['type'].lower()
# for j in i['properties']['observations']
# ],
# "type": "FeatureCollection",
# "geom_type": "MultiLineString"
# }
# return items_point,items_poly,items_line
def addMapLayer(self,data,geom_type):
mon_layer = ' - '.join([self.src_name[:6], self.source])
fcString = json.dumps(data)
codec = QTextCodec.codecForName("UTF-8")
fields = QgsJsonUtils.stringToFields(fcString, codec)
feats = QgsJsonUtils.stringToFeatureList(fcString, fields, codec)
if self.api:
crs_api = QgsCoordinateReferenceSystem(self.api['geometry_srid'])
else :
crs_api = QgsCoordinateReferenceSystem(4326)
vl = QgsVectorLayer(geom_type, mon_layer, "memory")
if vl.sourceCrs() != crs_api:
print('Changed crs !')
# crs = vl.crs()
# crs.createFromId(self.api['geometry_srid'])
vl.setCrs(crs_api)
dp = vl.dataProvider()
dp.addAttributes(fields)
vl.updateFields()
dp.addFeatures(feats)
vl.updateExtents()
if dp.errors():
msg = QMessageBox()
msg.warning(
None,
self.tr("Warning"),
self.tr(
"Houston, we've got a problem ... \n\n %s !"%str(dp.errors())
), # noqa: E501
)
QgsProject.instance().addMapLayer(vl)
def transform_bouds(self,crs):
sourceCrs = QgsCoordinateReferenceSystem(4326)
destCrs = QgsCoordinateReferenceSystem(crs)
if sourceCrs != destCrs:
tr = QgsCoordinateTransform(sourceCrs, destCrs, self.project)
self.rectangle.transform(tr)

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="fr" sourcelanguage="en">
</TS>

View File

@ -0,0 +1,13 @@
# This file is auto-generated by the script generate_translation_profile.py
# Do not edit this file manually
FORMS = ../../gui/dlg_settings.ui
SOURCES = ../../gui/dlg_settings.py \
../../plugin_main.py \
../../processing/provider.py \
../../toolbelt/env_var_parser.py \
../../toolbelt/log_handler.py \
../../toolbelt/preferences.py
TRANSLATIONS = gn_tools_en.ts

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

View File

@ -0,0 +1,3 @@
#! python3 # noqa: E265
from .log_handler import PlgLogger # noqa: F401
from .preferences import PlgOptionsManager # noqa: F401

View File

@ -0,0 +1,60 @@
import os
from typing import Type, TypeVar
T = TypeVar("T")
class EnvVarParser:
"""Utility class to retrieve and convert environment variables."""
@staticmethod
def get_env_var(name: str, default: T) -> T:
"""Retrieves an environment variable and converts it based on the default value type.
Args:
name (str): The environment variable name.
default (T): The default value, used to infer the expected type.
Returns:
T: The converted value, matching the type of `default`.
"""
value = os.getenv(name)
if value is None:
return (
default # Return the default value if the environment variable is not
)
# Otherwise, treat it as a single value
return EnvVarParser._convert_single(value, type(default), default)
@staticmethod
def _convert_single(value: str, expected_type: Type[T], default: T) -> T:
"""Converts a string into a single value of the expected type."""
try:
if expected_type is int:
return int(value)
elif expected_type is float:
return float(value)
elif expected_type is bool:
return EnvVarParser._convert_bool(value, default)
elif expected_type is str:
return value # String value
except ValueError:
return default # Return default value in case of conversion failure
raise TypeError(
f"Unsupported type: {expected_type}. Value definition from environment variable is not possible."
)
@staticmethod
def _convert_bool(value: str, default: bool) -> bool:
"""Converts a string into a boolean, handling explicit True/False values."""
true_values = {"1", "true", "yes", "on"}
false_values = {"0", "false", "no", "off"}
value_lower = value.lower()
if value_lower in true_values:
return True
elif value_lower in false_values:
return False
return default # Return default value if conversion fails

193
gn_tools/toolbelt/log_handler.py Executable file
View File

@ -0,0 +1,193 @@
#! python3 # noqa: E265
# standard library
import logging
from functools import partial
from typing import Callable, Literal, Optional, Union
# PyQGIS
from qgis.core import Qgis, QgsMessageLog, QgsMessageOutput
from qgis.gui import QgsMessageBar
from qgis.PyQt.QtWidgets import QPushButton, QWidget
from qgis.utils import iface
# project package
import gn_tools.toolbelt.preferences as plg_prefs_hdlr
from gn_tools.__about__ import __title__
# ############################################################################
# ########## Classes ###############
# ##################################
class PlgLogger(logging.Handler):
"""Python logging handler supercharged with QGIS useful methods."""
@staticmethod
def log(
message: str,
application: str = __title__,
log_level: Union[
Qgis.MessageLevel, Literal[0, 1, 2, 3, 4]
] = Qgis.MessageLevel.Info,
push: bool = False,
duration: Optional[int] = None,
# widget
button: bool = False,
button_text: Optional[str] = None,
button_more_text: Optional[str] = None,
button_connect: Optional[Callable] = None,
# parent
parent_location: Optional[QWidget] = None,
):
"""Send messages to QGIS messages windows and to the user as a message bar. \
Plugin name is used as title. If debug mode is disabled, only warnings (1) and \
errors (2) or with push are sent.
:param message: message to display
:type message: str
:param application: name of the application sending the message. \
Defaults to __about__.__title__
:type application: str, optional
:param log_level: message level. Possible values: any values of enum \
`Qgis.MessageLevel`. For legacy purposes, it's also possible to pass \
corresponding integers but it's not recommended anymore. Legacy values: \
0 (info), 1 (warning), 2 (critical), 3 (success), 4 (none - grey). Defaults \
to Qgis.MessageLevel(0) (info)
:type log_level: Union[Qgis.MessageLevel, Literal[0, 1, 2, 3, 4]], optional
:param push: also display the message in the QGIS message bar in addition to \
the log, defaults to False
:type push: bool, optional
:param duration: duration of the message in seconds. If not set, the \
duration is calculated from the log level: `(log_level + 1) * 3`. seconds. \
If set to 0, then the message must be manually dismissed by the user. \
Defaults to None.
:type duration: int, optional
:param button: display a button in the message bar. Defaults to False.
:type button: bool, optional
:param button_text: text label of the button. Defaults to None.
:type button_text: str, optional
:param button_more_text: text to display within the QgsMessageOutput
:type button_more_text: str, optional
:param button_connect: function to be called when the button is pressed. \
If not set, a simple dialog (QgsMessageOutput) is used to dislay the message. \
Defaults to None.
:type button_connect: Callable, optional
:param parent_location: parent location widget. \
If not set, QGIS canvas message bar is used to push message, \
otherwise if a QgsMessageBar is available in parent_location it is used instead. \
Defaults to None.
:type parent_location: Widget, optional
:Example:
.. code-block:: python
# using enums from Qgis:
# Qgis.Info, Qgis.MessageLevel.Warning, Qgis.MessageLevel.Critical, Qgis.MessageLevel.Success, Qgis.MessageLevel.NoLevel
from qgis.core import Qgis
log(message="Plugin loaded - INFO", log_level=Qgis.MessageLevel.Info, push=False)
log(
message="Something went wrong but it's not blocking",
log_level=Qgis.MessageLevel.Warning
)
log(
message="Plugin failed to load - CRITICAL",
log_level=Qgis.MessageLevel(2),
push=True
)
# LEGACY - using integers:
log(message="Plugin loaded - INFO", log_level=Qgis.MessageLevel.Info, push=False)
log(message="Plugin loaded - WARNING", log_level=Qgis.MessageLevel.Warning, push=1, duration=5)
log(message="Plugin loaded - ERROR", log_level=Qgis.MessageLevel.Critical, push=1, duration=0)
log(
message="Plugin loaded - SUCCESS",
log_level=Qgis.MessageLevel.Success,
push=1,
duration=10,
button=True
)
log(
message="Plugin loaded",
log_level=Qgis.MessageLevel.Critical,
push=1,
duration=0
button=True,
button_label=self.tr("See details"),
button_more_text=detailed_error_message
)
log(message="Plugin loaded - TEST", log_level=Qgis.MessageLevel.NoLevel, push=0)
"""
# if not debug mode and not push, let's ignore INFO, SUCCESS and TEST
debug_mode = plg_prefs_hdlr.PlgOptionsManager.get_plg_settings().debug_mode
if not debug_mode and not push and (log_level < 1 or log_level > 2):
return
# if log_level is an int, convert it to Qgis.MessageLevel
if isinstance(log_level, int):
log_level = Qgis.MessageLevel(log_level)
# ensure message is a string
if not isinstance(message, str):
try:
message = str(message)
except Exception as err:
err_msg = "Log message must be a string, not: {}. Trace: {}".format(
type(message), err
)
logging.error(err_msg)
message = err_msg
# send it to QGIS messages panel
QgsMessageLog.logMessage(
message=message, tag=application, notifyUser=push, level=log_level
)
# optionally, display message on QGIS Message bar (above the map canvas)
if push and iface is not None:
msg_bar = None
# QGIS or custom dialog
if parent_location and isinstance(parent_location, QWidget):
msg_bar = parent_location.findChild(QgsMessageBar)
if not msg_bar:
msg_bar = iface.messageBar()
# calc duration
if duration is None:
duration = (log_level + 1) * 3
# create message with/out a widget
if button:
# create output message
notification = iface.messageBar().createMessage(
title=application, text=message
)
widget_button = QPushButton(button_text or "More...")
if button_connect:
widget_button.clicked.connect(button_connect)
else:
mini_dlg: QgsMessageOutput = QgsMessageOutput.createMessageOutput()
mini_dlg.setTitle(application)
mini_dlg.setMessage(
f"{message}\n{button_more_text}",
QgsMessageOutput.MessageType.MessageText,
)
widget_button.clicked.connect(partial(mini_dlg.showMessage, False))
notification.layout().addWidget(widget_button)
msg_bar.pushWidget(
widget=notification, level=log_level, duration=duration
)
else:
# send simple message
msg_bar.pushMessage(
title=application,
text=message,
level=log_level,
duration=duration,
)

184
gn_tools/toolbelt/preferences.py Executable file
View File

@ -0,0 +1,184 @@
#! python3 # noqa: E265
"""
Plugin settings.
"""
# standard
from dataclasses import asdict, dataclass, fields
# PyQGIS
from qgis.core import Qgis, QgsSettings
# package
import gn_tools.toolbelt.log_handler as log_hdlr
from gn_tools.__about__ import (
__domain_url__,
__title__,
__version__
)
from gn_tools.toolbelt.env_var_parser import EnvVarParser
# ############################################################################
# ########## Classes ###############
# ##################################
PREFIX_ENV_VARIABLE = "QGIS_GN_TOOLS_"
@dataclass
class PlgEnvVariableSettings:
"""Plugin settings from environnement variable"""
def env_variable_used(self, attribute: str, default_from_name: bool = True) -> str:
"""Get environnement variable used for environnement variable settings
:param attribute: attribute to check
:type attribute: str
:param default_from_name: define default environnement value from attribute name PREFIX_ENV_VARIABLE_<upper case attribute>
:type default_from_name: bool
:return: environnement variable used
:rtype: str
"""
settings_env_variable = asdict(self)
env_variable = settings_env_variable.get(attribute, "")
if not env_variable and default_from_name:
env_variable = f"{PREFIX_ENV_VARIABLE}{attribute}".upper()
return env_variable
@dataclass
class PlgSettingsStructure:
"""Plugin settings structure and defaults values."""
# global
debug_mode: bool = False
version: str = __version__
# param
domain_url: str = __domain_url__
class PlgOptionsManager:
@staticmethod
def get_plg_settings() -> PlgSettingsStructure:
"""Load and return plugin settings as a dictionary. \
Useful to get user preferences across plugin logic.
:return: plugin settings
:rtype: PlgSettingsStructure
"""
# get dataclass fields definition
settings_fields = fields(PlgSettingsStructure)
env_variable_settings = PlgEnvVariableSettings()
# retrieve settings from QGIS/Qt
settings = QgsSettings()
settings.beginGroup(__title__)
# map settings values to preferences object
li_settings_values = []
for i in settings_fields:
try:
value = settings.value(key=i.name, defaultValue=i.default, type=i.type)
# If environnement variable used, get value from environnement variable
env_variable = env_variable_settings.env_variable_used(i.name)
if env_variable:
value = EnvVarParser.get_env_var(env_variable, value)
li_settings_values.append(value)
except TypeError:
li_settings_values.append(
settings.value(key=i.name, defaultValue=i.default)
)
# instanciate new settings object
options = PlgSettingsStructure(*li_settings_values)
settings.endGroup()
return options
@staticmethod
def get_value_from_key(key: str, default=None, exp_type=None):
"""Load and return plugin settings as a dictionary. \
Useful to get user preferences across plugin logic.
:return: plugin settings value matching key
"""
if not hasattr(PlgSettingsStructure, key):
log_hdlr.PlgLogger.log(
message="Bad settings key. Must be one of: {}".format(
",".join(PlgSettingsStructure._fields)
),
log_level=Qgis.MessageLevel.Warning,
)
return None
settings = QgsSettings()
settings.beginGroup(__title__)
try:
out_value = settings.value(key=key, defaultValue=default, type=exp_type)
except Exception as err:
log_hdlr.PlgLogger.log(
message="Error occurred trying to get settings: {}.Trace: {}".format(
key, err
)
)
out_value = None
settings.endGroup()
return out_value
@classmethod
def set_value_from_key(cls, key: str, value) -> bool:
"""Set plugin QSettings value using the key.
:param key: QSettings key
:type key: str
:param value: value to set
:type value: depending on the settings
:return: operation status
:rtype: bool
"""
if not hasattr(PlgSettingsStructure, key):
log_hdlr.PlgLogger.log(
message="Bad settings key. Must be one of: {}".format(
",".join(PlgSettingsStructure._fields)
),
log_level=Qgis.MessageLevel.Critical,
)
return False
settings = QgsSettings()
settings.beginGroup(__title__)
try:
settings.setValue(key, value)
out_value = True
except Exception as err:
log_hdlr.PlgLogger.log(
message="Error occurred trying to set settings: {}.Trace: {}".format(
key, err
)
)
out_value = False
settings.endGroup()
return out_value
@classmethod
def save_from_object(cls, plugin_settings_obj: PlgSettingsStructure):
"""Load and return plugin settings as a dictionary. \
Useful to get user preferences across plugin logic.
:return: plugin settings value matching key
"""
settings = QgsSettings()
settings.beginGroup(__title__)
for k, v in asdict(plugin_settings_obj).items():
cls.set_value_from_key(k, v)
settings.endGroup()

200
linters/pylintrc Normal file
View File

@ -0,0 +1,200 @@
[MAIN]
# Add files or directories to the blacklist. They should be base names, not
# paths.
ignore=CVS
# Pickle collected data for later comparisons.
persistent=yes
[MESSAGES CONTROL]
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time. See also the "--disable" option for examples.
#enable=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once).You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
# see http://stackoverflow.com/questions/21487025/pylint-locally-defined-disables-still-give-warnings-how-to-suppress-them
disable=locally-disabled,C0103,import-error,no-name-in-module
[REPORTS]
# Set the output format. Available formats are text, parseable, colorized, msvs
# (visual studio) and html. You can also give a reporter class, eg
# mypackage.mymodule.MyReporterClass.
output-format=text
# Tells whether to display a full report or only the messages
reports=yes
# Python expression which should return a note less than 10 (10 is the highest
# note). You have access to the variables errors warning, statement which
# respectively contain the number of errors / warnings messages and the total
# number of statements analyzed. This is used by the global evaluation report
# (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
[BASIC]
# Regular expression which should only match correct module names
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
# Regular expression which should only match correct module level names
const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
# Regular expression which should only match correct class names
class-rgx=[A-Z_][a-zA-Z0-9]+$
# Regular expression which should only match correct function names
function-rgx=[a-z_][a-z0-9_]{2,30}$
# Regular expression which should only match correct method names
method-rgx=[a-z_][a-z0-9_]{2,30}$
# Regular expression which should only match correct instance attribute names
attr-rgx=[a-z_][a-z0-9_]{2,30}$
# Regular expression which should only match correct argument names
argument-rgx=[a-z_][a-z0-9_]{2,30}$
# Regular expression which should only match correct variable names
variable-rgx=[a-z_][a-z0-9_]{2,30}$
# Regular expression which should only match correct attribute names in class
# bodies
class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
# Regular expression which should only match correct list comprehension /
# generator expression variable names
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
# Good variable names which should always be accepted, separated by a comma
good-names=i,j,k,ex,Run,_,x,y,z,w
# Bad variable names which should always be refused, separated by a comma
bad-names=foo,bar,baz,toto,tutu,tata,popo
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=__.*__
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,XXX,TODO
[TYPECHECK]
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E0201 when accessed. Python regular
# expressions are accepted.
generated-members=REQUEST,acl_users,aq_parent
[VARIABLES]
# Tells whether we should check for unused import in __init__ files.
init-import=no
# A regular expression matching the beginning of the name of dummy variables
# (i.e. not used).
dummy-variables-rgx=_$|dummy
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid to define new builtins when possible.
additional-builtins=
[FORMAT]
# Maximum number of characters on a single line.
max-line-length=88
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Allow the body of an if to be on the same line as the test if there is no else.
single-line-if-stmt=no
# Maximum number of lines in a module
max-module-lines=1000
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 tab).
indent-string=' '
[SIMILARITIES]
# Minimum lines number of a similarity.
min-similarity-lines=4
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
# Ignore imports when computing similarities.
ignore-imports=no
[DESIGN]
# Maximum number of arguments for function / method
max-args=5
# Maximum number of locals for function / method body
max-locals=15
# Maximum number of return / yield for function / method body
max-returns=6
# Maximum number of branch for function / method body
max-branches=12
# Maximum number of statements in function / method body
max-statements=50
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,__new__,setUp,initGui
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=mcs

View File

@ -0,0 +1,8 @@
# Develoment dependencies
# -----------------------
black
isort>=5.13
pre-commit>=4,<5

View File

@ -0,0 +1,7 @@
# Documentation (for devs)
# -----------------------
myst-parser[linkify]>=2
sphinx-autobuild>=2024
sphinx-copybutton>=0.5,<1
sphinx-rtd-theme>=2

View File

@ -0,0 +1,4 @@
# Packaging
# ---------
qgis-plugin-ci>=2.8,<3

5
requirements/testing.txt Normal file
View File

@ -0,0 +1,5 @@
# Testing dependencies
# --------------------
pytest-cov>=4
packaging>=23

0
scripts/__init__.py Normal file
View File

View File

@ -0,0 +1,86 @@
#! python3
"""Script to generate the translation profile for a PyQt project, listing Python,
forms (ui) and targetted translation files. This script is intended to be run from the
root of the project, and will create a file named `plugin_translation.pro` in the
`oslandia/resources/i18n` directory.
TODO: remove the get_relative_paths function if your stack is Python 3.12+, which added
the walk_up option in pathlib.Path.relative_to(). It would be a cleaner solution.
Listing files would become:
python_files = [
f.relative_to(i18n_path, walk_up=True)
for f in sorted(list(Path(src_path).rglob("*.py")))
if not f.name.startswith("__")
]
ui_files = [
f.relative_to(i18n_path, walk_up=True)
for f in sorted(list(Path(src_path).rglob("*.ui")))
]
ts_files = [
f.relative_to(i18n_path, walk_up=True)
for f in sorted(list(Path(src_path).rglob("*.ts")))
]
So update the script accordingly by removing the function and references.
"""
# -- Imports
from os import path
from pathlib import Path
# -- Variables
src_path = Path("gn_tools")
i18n_path = src_path.joinpath("resources/i18n")
output_file = i18n_path.joinpath("plugin_translation.pro")
# make sure the output directory exists
i18n_path.mkdir(parents=True, exist_ok=True)
# -- Functions
def get_relative_paths(filepaths_list: list[Path]) -> list[str]:
"""Parse a list of file paths and return a list of relative paths to the i18n
directory, escaping the backslashes to make them compatible with Qt Linguist.
:param filepaths_list: List of file paths to parse
:type filepaths_list: list[Path]
:return: List of relative paths to the i18n directory
:rtype: list[str]
"""
return [
path.relpath(filepath, i18n_path).replace("\\", "/")
for filepath in filepaths_list
]
# -- Run
# Get the list of all files in directory tree at given path
python_files = [
f for f in sorted(list(Path(src_path).rglob("*.py"))) if not f.name.startswith("__")
]
ui_files = [f for f in sorted(list(Path(src_path).rglob("*.ui")))]
ts_files = [f for f in sorted(list(Path(src_path).rglob("*.ts")))]
# Generate the translation profile
forms = "FORMS =" + " \\\n".join([f"\t{f}" for f in get_relative_paths(ui_files)])
sources = "SOURCES =" + " \\\n".join(
[f"\t{f}" for f in get_relative_paths(python_files)]
)
translations = "TRANSLATIONS =" + " \\\n".join(
[f"\t{f}" for f in get_relative_paths(ts_files)]
)
# write to output file
with output_file.open("w", encoding="UTF-8") as f:
f.write(
"# This file is auto-generated by the script generate_translation_profile.py\n"
"# Do not edit this file manually\n\n"
)
f.write(f"{forms}\n\n{sources}\n\n{translations}")

50
setup.cfg Normal file
View File

@ -0,0 +1,50 @@
# -- Packaging --------------------------------------
[metadata]
description-file = README.md
[qgis-plugin-ci]
plugin_path = gn_tools
project_slug = TO BE SET WITH THE GITLAB/GITHUB SLUGIFIED PROJECT NAME (IN PROJECT'S URL)
# -- Code quality ------------------------------------
[isort]
ensure_newline_before_comments = True
force_grid_wrap = 0
include_trailing_comma = True
line_length = 88
multi_line_output = 3
profile = black
use_parentheses = True
# -- Tests ----------------------------------------------
[tool:pytest]
addopts =
--junitxml=junit/test-results.xml
--cov-config=setup.cfg
--cov=gn_tools
--cov-report=html
--cov-report=term
--cov-report=xml
--ignore=tests/_wip/
norecursedirs = .* build dev development dist docs CVS fixtures _darcs {arch} *.egg venv _wip
python_files = test_*.py
testpaths = tests
[coverage:run]
branch = True
omit =
.venv/*
*tests*
[coverage:report]
exclude_lines =
if self.debug:
pragma: no cover
raise NotImplementedError
if __name__ == .__main__.:
ignore_errors = True
show_missing = True

0
tests/__init__.py Normal file
View File

0
tests/qgis/__init__.py Normal file
View File

View File

@ -0,0 +1,76 @@
import os
import unittest
from gn_tools.toolbelt.env_var_parser import EnvVarParser
class TestEnvVarParser(unittest.TestCase):
"""Unit tests for EnvVarParser."""
def setUp(self) -> None:
"""Prepare the test environment before each test."""
self.env_backup = dict(os.environ) # Backup environment variables
def tearDown(self) -> None:
"""Restore the original environment variables after each test."""
os.environ.clear()
os.environ.update(self.env_backup)
def test_int_conversion(self) -> None:
"""Test integer conversion from environment variable"""
os.environ["MY_INT"] = "42"
self.assertEqual(EnvVarParser.get_env_var("MY_INT", 0), 42)
def test_float_conversion(self) -> None:
"""Test float conversion from environment variable"""
os.environ["MY_FLOAT"] = "3.14"
self.assertEqual(EnvVarParser.get_env_var("MY_FLOAT", 0.0), 3.14)
def test_bool_conversion_true(self) -> None:
"""Test bool conversion from environment variable"""
for true_value in ["1", "true", "yes", "on"]:
os.environ["MY_BOOL"] = true_value
self.assertTrue(EnvVarParser.get_env_var("MY_BOOL", False))
def test_bool_conversion_false(self) -> None:
"""Test bool conversion from environment variable"""
for false_value in ["0", "false", "no", "off"]:
os.environ["MY_BOOL"] = false_value
self.assertFalse(EnvVarParser.get_env_var("MY_BOOL", True))
def test_bool_invalid_defaults_to_original(self) -> None:
"""Test invalid bool conversion from environment variable"""
os.environ["MY_BOOL"] = "maybe"
self.assertFalse(
EnvVarParser.get_env_var("MY_BOOL", False)
) # Default should remain
def test_string_conversion(self) -> None:
"""Test string conversion from environment variable"""
os.environ["MY_STRING"] = "Hello, World!"
self.assertEqual(
EnvVarParser.get_env_var("MY_STRING", "default"), "Hello, World!"
)
def test_default_value_when_env_missing(self) -> None:
"""Test default value is used when environment variable is missing"""
self.assertEqual(EnvVarParser.get_env_var("MISSING_INT", 99), 99)
def test_invalid_int_fallback_to_default(self) -> None:
"""Test default value used when the environment variable is not a valid int"""
os.environ["MY_INT"] = "not_an_int"
self.assertEqual(EnvVarParser.get_env_var("MY_INT", 10), 10)
def test_invalid_float_fallback_to_default(self) -> None:
"""Test default value used when the environment variable is not a valid float"""
os.environ["MY_FLOAT"] = "not_a_float"
self.assertEqual(EnvVarParser.get_env_var("MY_FLOAT", 1.23), 1.23)
def test_unsupported_type(self) -> None:
"""Test exception is raised when the type expected is not supported"""
os.environ["INT_LIST"] = "1,2,3,4"
self.assertRaises(TypeError, EnvVarParser.get_env_var, "INT_LIST", [1, 2, 3, 4])
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,99 @@
#! python3 # noqa E265
"""
Usage from the repo root folder:
.. code-block:: bash
# for whole tests
python -m unittest tests.qgis.test_plg_preferences
# for specific test
python -m unittest tests.qgis.test_plg_preferences.TestPlgPreferences.test_plg_preferences_structure
"""
# standard library
import os
from unittest.mock import patch
from qgis.testing import unittest
# project
from gn_tools.__about__ import __version__
from gn_tools.toolbelt.preferences import (
PREFIX_ENV_VARIABLE,
PlgOptionsManager,
PlgSettingsStructure,
)
# ############################################################################
# ########## Classes #############
# ################################
class TestPlgPreferences(unittest.TestCase):
def test_plg_preferences_structure(self):
"""Test settings types and default values."""
settings = PlgSettingsStructure()
# global
self.assertTrue(hasattr(settings, "debug_mode"))
self.assertIsInstance(settings.debug_mode, bool)
self.assertEqual(settings.debug_mode, False)
self.assertTrue(hasattr(settings, "version"))
self.assertIsInstance(settings.version, str)
self.assertEqual(settings.version, __version__)
def test_bool_env_variable(self):
"""Test settings with environment value."""
manager = PlgOptionsManager()
with patch.dict(
os.environ, {f"{PREFIX_ENV_VARIABLE}DEBUG_MODE": "true"}, clear=True
):
settings = manager.get_plg_settings()
self.assertEqual(settings.debug_mode, True)
with patch.dict(
os.environ, {f"{PREFIX_ENV_VARIABLE}DEBUG_MODE": "false"}, clear=True
):
settings = manager.get_plg_settings()
self.assertEqual(settings.debug_mode, False)
with patch.dict(
os.environ, {f"{PREFIX_ENV_VARIABLE}DEBUG_MODE": "on"}, clear=True
):
settings = manager.get_plg_settings()
self.assertEqual(settings.debug_mode, True)
with patch.dict(
os.environ, {f"{PREFIX_ENV_VARIABLE}DEBUG_MODE": "off"}, clear=True
):
settings = manager.get_plg_settings()
self.assertEqual(settings.debug_mode, False)
with patch.dict(
os.environ, {f"{PREFIX_ENV_VARIABLE}DEBUG_MODE": "1"}, clear=True
):
settings = manager.get_plg_settings()
self.assertEqual(settings.debug_mode, True)
with patch.dict(
os.environ, {f"{PREFIX_ENV_VARIABLE}DEBUG_MODE": "0"}, clear=True
):
settings = manager.get_plg_settings()
self.assertEqual(settings.debug_mode, False)
with patch.dict(
os.environ,
{f"{PREFIX_ENV_VARIABLE}DEBUG_MODE": "invalid_value"},
clear=True,
):
settings = manager.get_plg_settings()
self.assertEqual(settings.debug_mode, False)
# ############################################################################
# ####### Stand-alone run ########
# ################################
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,40 @@
#! python3 # noqa E265
"""
Usage from the repo root folder:
.. code-block:: bash
# for whole tests
python -m unittest tests.qgis.test_plg_processing
# for specific test
python -m unittest tests.qgis.test_plg_processing.TestPlgprocessing.test_plg_processing_structure
"""
# PyQGIS
from qgis.core import QgsApplication
from qgis.testing import unittest, start_app
from gn_tools.processing.provider import (
GnToolsProvider,
)
provider = None
class TestProcessing(unittest.TestCase):
"""Tests for processing algorithms."""
def setUp(self) -> None:
"""Set up the processing tests."""
if not QgsApplication.processingRegistry().providers():
self.provider = GnToolsProvider()
QgsApplication.processingRegistry().addProvider(self.provider)
self.maxDiff = None
# Start App needed to run processing on unittest
start_app()
def test_processing_provider(self):
"""Sample test."""
print(f"Processing provider name : {self.provider.name()}")

0
tests/unit/__init__.py Normal file
View File

87
tests/unit/test_plg_metadata.py Executable file
View File

@ -0,0 +1,87 @@
#! python3 # noqa E265
"""
Usage from the repo root folder:
.. code-block:: bash
# for whole tests
python -m unittest tests.unit.test_plg_metadata
# for specific test
python -m unittest tests.unit.test_plg_metadata.TestPluginMetadata.test_version_semver
"""
# standard library
import unittest
from pathlib import Path
# 3rd party
from packaging.version import parse
# project
from gn_tools import __about__
# ############################################################################
# ########## Classes #############
# ################################
class TestPluginMetadata(unittest.TestCase):
"""Test about module"""
def test_metadata_types(self):
"""Test types."""
# plugin metadata.txt file
self.assertIsInstance(__about__.PLG_METADATA_FILE, Path)
self.assertTrue(__about__.PLG_METADATA_FILE.is_file())
# plugin dir
self.assertIsInstance(__about__.DIR_PLUGIN_ROOT, Path)
self.assertTrue(__about__.DIR_PLUGIN_ROOT.is_dir())
# metadata as dict
self.assertIsInstance(__about__.__plugin_md__, dict)
# general
self.assertIsInstance(__about__.__author__, str)
self.assertIsInstance(__about__.__copyright__, str)
self.assertIsInstance(__about__.__email__, str)
self.assertIsInstance(__about__.__keywords__, list)
self.assertIsInstance(__about__.__license__, str)
self.assertIsInstance(__about__.__plugin_dependencies__, list)
self.assertIsInstance(__about__.__summary__, str)
self.assertIsInstance(__about__.__title__, str)
self.assertIsInstance(__about__.__title_clean__, str)
self.assertIsInstance(__about__.__version__, str)
self.assertIsInstance(__about__.__version_info__, tuple)
# misc
self.assertLessEqual(len(__about__.__title_clean__), len(__about__.__title__))
# QGIS versions
self.assertIsInstance(
__about__.__plugin_md__.get("general").get("qgisminimumversion"), str
)
self.assertIsInstance(
__about__.__plugin_md__.get("general").get("qgismaximumversion"), str
)
min_version_parsed = parse(
__about__.__plugin_md__.get("general").get("qgisminimumversion")
)
max_version_parsed = parse(
__about__.__plugin_md__.get("general").get("qgismaximumversion")
)
self.assertLessEqual(min_version_parsed, max_version_parsed)
def test_version_semver(self):
"""Test if version comply with semantic versioning."""
self.assertTrue(parse(__about__.__version__))
# ############################################################################
# ####### Stand-alone run ########
# ################################
if __name__ == "__main__":
unittest.main()