From 20ab32da3016042fc27db338ee1982b11bca2cc7 Mon Sep 17 00:00:00 2001 From: GeoDonkey Date: Tue, 1 Dec 2026 19:59:12 +0100 Subject: [PATCH] GeoDonkey for QGIS 1.12 --- .gitignore | 3 + LICENSE | 674 ++++++ README.md | 132 ++ geodonkey/__init__.py | 7 + geodonkey/area.py | 90 + geodonkey/auth.py | 138 ++ geodonkey/basemaps.py | 98 + geodonkey/client.py | 383 +++ geodonkey/compat.py | 65 + geodonkey/config.py | 199 ++ geodonkey/errors.py | 148 ++ geodonkey/export.py | 86 + geodonkey/geojson.py | 212 ++ geodonkey/gui/__init__.py | 0 geodonkey/gui/chart.py | 262 +++ geodonkey/gui/maptab.py | 391 +++ geodonkey/gui/panel.py | 617 +++++ geodonkey/gui/pick.py | 259 ++ geodonkey/gui/settings_dialog.py | 190 ++ geodonkey/gui/theme.py | 274 +++ geodonkey/gui/tools/__init__.py | 18 + geodonkey/gui/tools/elevation.py | 301 +++ geodonkey/gui/tools/isochrone.py | 130 + geodonkey/gui/tools/profile.py | 146 ++ geodonkey/gui/tools/route.py | 113 + geodonkey/gui/tools/sight.py | 174 ++ geodonkey/gui/tools_tab.py | 60 + geodonkey/gui/upload_tab.py | 447 ++++ geodonkey/i18n.py | 15 + geodonkey/i18n/geodonkey_de.qm | Bin 0 -> 73158 bytes geodonkey/i18n/geodonkey_de.ts | 2093 +++++++++++++++++ geodonkey/icons/account.svg | 6 + geodonkey/icons/basemap.svg | 6 + geodonkey/icons/elevation.svg | 8 + geodonkey/icons/geodonkey.svg | 6 + geodonkey/icons/isochrone.svg | 11 + geodonkey/icons/lineofsight.svg | 9 + geodonkey/icons/osm.svg | 8 + geodonkey/icons/profile.svg | 12 + geodonkey/icons/route.svg | 10 + geodonkey/icons/tools.svg | 7 + geodonkey/icons/upload.svg | 6 + geodonkey/layers.py | 175 ++ geodonkey/mapcontext.py | 162 ++ geodonkey/metadata.txt | 36 + geodonkey/net.py | 71 + geodonkey/plot.py | 124 + geodonkey/plugin.py | 256 ++ geodonkey/points.py | 140 ++ geodonkey/processing/__init__.py | 0 geodonkey/processing/base.py | 183 ++ .../processing/elevation_points_algorithm.py | 170 ++ .../processing/elevation_profile_algorithm.py | 149 ++ geodonkey/processing/isochrone_algorithm.py | 129 + .../processing/line_of_sight_algorithm.py | 209 ++ geodonkey/processing/osm_algorithm.py | 215 ++ geodonkey/processing/provider.py | 42 + geodonkey/processing/route_algorithm.py | 181 ++ geodonkey/results.py | 584 +++++ geodonkey/settings.py | 39 + geodonkey/style.py | 228 ++ geodonkey/task.py | 52 + geodonkey/upload.py | 198 ++ 63 files changed, 11157 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 geodonkey/__init__.py create mode 100644 geodonkey/area.py create mode 100644 geodonkey/auth.py create mode 100644 geodonkey/basemaps.py create mode 100644 geodonkey/client.py create mode 100644 geodonkey/compat.py create mode 100644 geodonkey/config.py create mode 100644 geodonkey/errors.py create mode 100644 geodonkey/export.py create mode 100644 geodonkey/geojson.py create mode 100644 geodonkey/gui/__init__.py create mode 100644 geodonkey/gui/chart.py create mode 100644 geodonkey/gui/maptab.py create mode 100644 geodonkey/gui/panel.py create mode 100644 geodonkey/gui/pick.py create mode 100644 geodonkey/gui/settings_dialog.py create mode 100644 geodonkey/gui/theme.py create mode 100644 geodonkey/gui/tools/__init__.py create mode 100644 geodonkey/gui/tools/elevation.py create mode 100644 geodonkey/gui/tools/isochrone.py create mode 100644 geodonkey/gui/tools/profile.py create mode 100644 geodonkey/gui/tools/route.py create mode 100644 geodonkey/gui/tools/sight.py create mode 100644 geodonkey/gui/tools_tab.py create mode 100644 geodonkey/gui/upload_tab.py create mode 100644 geodonkey/i18n.py create mode 100644 geodonkey/i18n/geodonkey_de.qm create mode 100644 geodonkey/i18n/geodonkey_de.ts create mode 100644 geodonkey/icons/account.svg create mode 100644 geodonkey/icons/basemap.svg create mode 100644 geodonkey/icons/elevation.svg create mode 100644 geodonkey/icons/geodonkey.svg create mode 100644 geodonkey/icons/isochrone.svg create mode 100644 geodonkey/icons/lineofsight.svg create mode 100644 geodonkey/icons/osm.svg create mode 100644 geodonkey/icons/profile.svg create mode 100644 geodonkey/icons/route.svg create mode 100644 geodonkey/icons/tools.svg create mode 100644 geodonkey/icons/upload.svg create mode 100644 geodonkey/layers.py create mode 100644 geodonkey/mapcontext.py create mode 100644 geodonkey/metadata.txt create mode 100644 geodonkey/net.py create mode 100644 geodonkey/plot.py create mode 100644 geodonkey/plugin.py create mode 100644 geodonkey/points.py create mode 100644 geodonkey/processing/__init__.py create mode 100644 geodonkey/processing/base.py create mode 100644 geodonkey/processing/elevation_points_algorithm.py create mode 100644 geodonkey/processing/elevation_profile_algorithm.py create mode 100644 geodonkey/processing/isochrone_algorithm.py create mode 100644 geodonkey/processing/line_of_sight_algorithm.py create mode 100644 geodonkey/processing/osm_algorithm.py create mode 100644 geodonkey/processing/provider.py create mode 100644 geodonkey/processing/route_algorithm.py create mode 100644 geodonkey/results.py create mode 100644 geodonkey/settings.py create mode 100644 geodonkey/style.py create mode 100644 geodonkey/task.py create mode 100644 geodonkey/upload.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3bbe7b6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.pyc +*.pyo diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..175abbb --- /dev/null +++ b/README.md @@ -0,0 +1,132 @@ +# GeoDonkey for QGIS + +OpenStreetMap data, map styles, routing and elevation from +[geodonkey.com](https://geodonkey.com) directly in QGIS – without the detour +through browser, download and import. + +This repository contains the plugin and nothing else. It is client code: it +knows the public API, not what runs behind it. + +--- + +## What it does + +**DonkeyOSM queries.** Three ways to ask: plain language ("bakery", +"playground", "drinking water"), OSM tags (`shop=bakery,amenity=cafe`), or a +custom line query with OR between lines and AND within a line. Four ways to +define the area: current map extent, extent of a layer, extent of the +selection, outline of the selected polygons. + +**Basemaps.** The GeoDonkey map styles as vector tile layers – free and +without an API key. + +**Ways.** Two tools on the road network, not on the straight line: + +* **Isochrone** – the area reachable from a point, up to four rings in a + single call (`5,10,15` minutes or kilometres), on foot, by bike or by car. +* **Route** – a trip through up to ten points, optionally with optimised stop + order and with turn-by-turn instructions. The result is the legs as lines + and the stops as points. + +**Elevation.** Three tools on the official terrain model – **Germany only**: + +* **Elevation profile** – the cut through the terrain between two points, as a + series of points with distance and height, drawn as a chart. +* **Point elevations** – height above sea level, for clicked points or for + every point of a layer; large layers are split automatically without costing + more. +* **Line of sight** – clear view between two points, including earth curvature + and refraction. With obstacles as points and with the height a mast would + need. + +**Dataset upload.** The *Upload* tab sends a vector layer from the project to +GeoDonkey – no *Save as*, no file manager, no browser. GeoJSON in WGS 84 is +written, reprojected from the layer's CRS, with attributes and with curves, Z +and M values; the temporary file is deleted immediately, because this is your +data. The layer list fills itself the moment you open it, so a layer added +while the panel is open is there right away – vector layers only, as before. +Every dataset gets a link of the form `https://geodonkey.com/view/` +that shows the data on a map without an account and without an API key. + +**Processing toolbox.** All six tools are Processing algorithms and therefore +work in models, in batch runs and in `qgis_process`. They appear in the toolbox +under *GeoDonkey* and in the Web menu as *… (dialog) …*. + +**A panel for the quick case.** Every button in the toolbar leads to the +*Tools* tab, where points are placed on the map instead of typed into a text +field. The price is shown **before** the call, results that are geometry +themselves first appear as a preview, and *Keep as layer* turns that preview +into layers without calling the service – and paying – a second time. The +preview already uses the colours of the final layer: every isochrone ring and +every route leg in its own, with the outline in the colour of the area. +Where the number of points is open – route, point elevation – the button that +ends picking is called *Use these points* and does the same as a right-click +on the map. *Reset* clears the picked points and the result; the settings +above stay as they are, and a single row of the elevation table goes with +*Remove point*, a right-click on the row or the Delete key. + +**Results look like they do on geodonkey.com.** Every layer brings its style +along instead of getting the random colour QGIS hands out. The colour is also +written into a `color` column, so it travels with an export. + +--- + +## Installation + +Through the QGIS plugin manager. Alternatively from the ZIP of a release: +**Plugins ▸ Manage and Install Plugins ▸ Install from ZIP**, pick the file, +**Install Plugin**. + +There is no ZIP in this repository, and that is on purpose: the official QGIS +repository asks for a source repository without zipped files. + +Restart QGIS afterwards. The plugin then lives under **Web ▸ GeoDonkey** and in +its own toolbar. + +**QGIS 3.40 or newer** is required. There are no further dependencies – no +`requests`, no `pip install`. The plugin uses the network stack of QGIS itself, +so it inherits the proxy settings, the certificate store and the timeouts that +are already configured there. + +--- + +## The API key + +The map styles do not need one. For everything else you get a key at +[geodonkey.com/dashboard](https://geodonkey.com/dashboard) and enter it under +**Web ▸ GeoDonkey ▸ GeoDonkey settings**. + +**The key is never stored in clear text.** It lives in the QGIS authentication +database – the same one that guards database and WMS credentials – and +`QgsSettings` only holds its identifier. An API key is a means of payment: +whoever has it spends someone else's DonkeyCoins. + +If there is no master password, or the database cannot be opened, the key is +**not** written to a file as a fallback. It then only applies to this QGIS +session, and the plugin says so. The inconvenience hits the owner; a clear-text +key would hit everyone who can read the file. + +--- + +## What it costs + +Most tools are charged in DonkeyCoins once the free calls of the current hour +are used up. Only successful calls are charged – a rejected area costs nothing. + +The plugin shows the price **above the main button before you click**, together +with the remaining free calls and your balance. The current prices, quotas and +plans are on [geodonkey.com](https://geodonkey.com) – that is the one place +where they are always up to date. + +--- + +## Data and licences + +The data comes from OpenStreetMap and is licensed under the +[ODbL](https://www.openstreetmap.org/copyright). The plugin writes the +attribution into the layer metadata under `rights` – where QGIS finds it again +when building a layout and when exporting. It is not decoration, it is the +condition of the licence. + +The plugin itself is licensed under the **GNU General Public License v3 or +later**, see [LICENSE](LICENSE). diff --git a/geodonkey/__init__.py b/geodonkey/__init__.py new file mode 100644 index 0000000..69eed32 --- /dev/null +++ b/geodonkey/__init__.py @@ -0,0 +1,7 @@ +from __future__ import annotations + + +def classFactory(iface): # noqa: N802 + from .plugin import GeoDonkeyPlugin + + return GeoDonkeyPlugin(iface) diff --git a/geodonkey/area.py b/geodonkey/area.py new file mode 100644 index 0000000..209de03 --- /dev/null +++ b/geodonkey/area.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +from typing import Dict, Iterable, List, Sequence, Tuple + +from . import config +from .errors import RequestError +from .i18n import tr +from .points import PRECISION, Point # noqa: F401 +from .points import fmt as _fmt + + +def normalise_bbox(minx: float, miny: float, maxx: float, + maxy: float) -> Tuple[float, float, float, float]: + return (min(minx, maxx), min(miny, maxy), max(minx, maxx), max(miny, maxy)) + + +def bbox_area(minx: float, miny: float, maxx: float, maxy: float) -> float: + minx, miny, maxx, maxy = normalise_bbox(minx, miny, maxx, maxy) + return abs(maxx - minx) * abs(maxy - miny) + + +def check_bbox(minx: float, miny: float, maxx: float, maxy: float) -> None: + minx, miny, maxx, maxy = normalise_bbox(minx, miny, maxx, maxy) + if maxx <= minx or maxy <= miny: + raise RequestError(tr("The selected area is empty. Zoom to the region you want to query.")) + area = bbox_area(minx, miny, maxx, maxy) + if area > config.MAX_BBOX_AREA_DEGREES: + raise RequestError( + tr("The area is too large: {area} square degrees, the limit is {limit}. " + "Zoom in or draw a smaller rectangle.").format( + area="%.1f" % area, limit="%.0f" % config.MAX_BBOX_AREA_DEGREES)) + + +def bbox_param(minx: float, miny: float, maxx: float, maxy: float) -> Dict[str, str]: + check_bbox(minx, miny, maxx, maxy) + minx, miny, maxx, maxy = normalise_bbox(minx, miny, maxx, maxy) + return {"bbox": ",".join(_fmt(v) for v in (minx, miny, maxx, maxy))} + + +def around_param(lon: float, lat: float, metres: float) -> Dict[str, str]: + radius = float(metres) + if radius <= 0: + raise RequestError(tr("The radius must be greater than zero.")) + if radius > config.MAX_RADIUS_METRES: + raise RequestError( + tr("The radius is too large: {radius} m, the limit is {limit} m.").format( + radius="%.0f" % radius, limit="%.0f" % config.MAX_RADIUS_METRES)) + return {"around": "%s,%s,%s" % (_fmt(lon), _fmt(lat), _fmt(radius))} + + +def thin(points: Sequence[Point], limit: int = config.MAX_POLYGON_POINTS) -> List[Point]: + pts = list(points) + if limit < 4: + raise ValueError("limit must be at least 4") + if len(pts) <= limit: + return pts + closed = len(pts) > 2 and pts[0] == pts[-1] + body = pts[:-1] if closed else pts + keep = limit - 1 if closed else limit + step = len(body) / float(keep) + out = [body[min(len(body) - 1, int(i * step))] for i in range(keep)] + if closed: + out.append(out[0]) + return out + + +def polygon_param(points: Iterable[Point]) -> Dict[str, str]: + pts = [(float(x), float(y)) for x, y in points] + if len(pts) < 3: + raise RequestError(tr("A polygon needs at least three points.")) + pts = thin(pts, config.MAX_POLYGON_POINTS) + flat = [] + for x, y in pts: + flat.append(_fmt(x)) + flat.append(_fmt(y)) + return {"polygon": ",".join(flat)} + + +def describe(area: Dict[str, str]) -> str: + if "bbox" in area: + return tr("Rectangle {bbox}").format(bbox=area["bbox"]) + if "around" in area: + parts = area["around"].split(",") + if len(parts) == 3: + return tr("{radius} m around {lon}, {lat}").format( + radius=parts[2], lon=parts[0], lat=parts[1]) + if "polygon" in area: + count = len(area["polygon"].split(",")) // 2 + return tr("Polygon with {count} vertices").format(count=count) + return tr("No area selected") diff --git a/geodonkey/auth.py b/geodonkey/auth.py new file mode 100644 index 0000000..e308fae --- /dev/null +++ b/geodonkey/auth.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +from typing import Optional + +from qgis.core import QgsApplication, QgsAuthMethodConfig, QgsSettings + +from . import config +from .i18n import tr + +CONFIG_NAME = "GeoDonkey API" + +CONFIG_METHOD = "APIHeader" + +SETTINGS_KEY = config.SETTINGS_GROUP + "/authcfg" + +_session_token = {"value": ""} + + +class AuthUnavailable(Exception): + pass + + +def _manager(): + return QgsApplication.authManager() + + +def available() -> bool: + manager = _manager() + if manager is None: + return False + try: + if manager.isDisabled(): + return False + except AttributeError: + return False + return True + + +def unlock() -> bool: + if not available(): + return False + manager = _manager() + if manager.masterPasswordIsSet(): + return True + return bool(manager.setMasterPassword(True)) + + +def stored_id() -> str: + return str(QgsSettings().value(SETTINGS_KEY, "") or "") + + +def save_token(token: str) -> str: + token = (token or "").strip() + if not token: + raise ValueError("empty token") + if not unlock(): + raise AuthUnavailable( + tr("The QGIS authentication database is not available. " + "The key will only be kept for this session.")) + + manager = _manager() + cfg = QgsAuthMethodConfig() + existing = stored_id() + if existing and existing in manager.configIds(): + manager.loadAuthenticationConfig(existing, cfg, True) + cfg.setName(CONFIG_NAME) + cfg.setMethod(CONFIG_METHOD) + cfg.setConfig("Authorization", "Bearer " + token) + cfg.setConfig("token", token) + + if existing and existing in manager.configIds(): + cfg.setId(existing) + if not manager.updateAuthenticationConfig(cfg): + raise AuthUnavailable(tr("The key could not be stored.")) + config_id = existing + else: + if not manager.storeAuthenticationConfig(cfg): + raise AuthUnavailable(tr("The key could not be stored.")) + config_id = cfg.id() + + QgsSettings().setValue(SETTINGS_KEY, config_id) + _session_token["value"] = token + return config_id + + +def load_token() -> str: + if _session_token["value"]: + return _session_token["value"] + config_id = stored_id() + if not config_id or not available(): + return "" + manager = _manager() + if config_id not in manager.configIds(): + return "" + if not unlock(): + return "" + cfg = QgsAuthMethodConfig() + if not manager.loadAuthenticationConfig(config_id, cfg, True): + return "" + token = cfg.config("token") or "" + if not token: + header = cfg.config("Authorization") or "" + token = header[7:] if header.startswith("Bearer ") else header + _session_token["value"] = token + return token + + +def remember_for_session(token: str) -> None: + _session_token["value"] = (token or "").strip() + + +def forget() -> None: + _session_token["value"] = "" + config_id = stored_id() + QgsSettings().remove(SETTINGS_KEY) + if config_id and available(): + manager = _manager() + if config_id in manager.configIds() and unlock(): + manager.removeAuthenticationConfig(config_id) + + +def looks_like_token(token: str) -> bool: + token = (token or "").strip() + return token.startswith(config.TOKEN_PREFIXES) and len(token) > 16 + + +def masked(token: str) -> str: + token = (token or "").strip() + if not token: + return "" + if len(token) <= 14: + return "…" + return token[:11] + "…" + token[-4:] + + +def optional_token(token: str) -> Optional[str]: + token = (token or "").strip() + return token or None diff --git a/geodonkey/basemaps.py b/geodonkey/basemaps.py new file mode 100644 index 0000000..654ae40 --- /dev/null +++ b/geodonkey/basemaps.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Mapping, Optional + +from qgis.core import ( + QgsDataSourceUri, + QgsLayerMetadata, + QgsProject, + QgsVectorTileLayer, +) + +from . import config +from .errors import GeoDonkeyError +from .i18n import tr + + +def style_url(api_url: str, style_id: str) -> str: + return config.api_endpoint(api_url, "/map-styles/%s.json" % style_id) + + +def tile_url(api_url: str) -> str: + return config.api_endpoint(api_url, "/tiles/{z}/{x}/{y}.pbf") + + +def build_uri(api_url: str, style_id: str, + zmin: int = config.TILE_MIN_ZOOM, + zmax: int = config.TILE_MAX_ZOOM) -> str: + uri = QgsDataSourceUri() + uri.setParam("type", "xyz") + uri.setParam("url", tile_url(api_url)) + uri.setParam("zmin", str(int(zmin))) + uri.setParam("zmax", str(int(zmax))) + uri.setParam("styleUrl", style_url(api_url, style_id)) + return bytes(uri.encodedUri()).decode("utf-8") + + +def catalogue(payload: Optional[Mapping[str, Any]] = None) -> List[Dict[str, Any]]: + styles = (payload or {}).get("styles") + if not styles: + return [dict(item) for item in config.FALLBACK_STYLES] + out = [] + for item in styles: + if not isinstance(item, Mapping) or not item.get("id"): + continue + out.append({ + "id": str(item["id"]), + "name": str(item.get("name") or item["id"]), + "dark": bool(item.get("dark")), + "swatch": list(item.get("swatch") or [])[:3], + "temporary": bool(item.get("temporary")), + }) + return out or [dict(item) for item in config.FALLBACK_STYLES] + + +def zoom_range(tilejson: Optional[Mapping[str, Any]] = None) -> "tuple": + data = tilejson or {} + try: + zmin = int(data.get("minzoom", config.TILE_MIN_ZOOM)) + zmax = int(data.get("maxzoom", config.TILE_MAX_ZOOM)) + except (TypeError, ValueError): + return config.TILE_MIN_ZOOM, config.TILE_MAX_ZOOM + if zmax <= zmin: + return config.TILE_MIN_ZOOM, config.TILE_MAX_ZOOM + return zmin, zmax + + +def add_basemap(api_url: str, style: Mapping[str, Any], + zmin: int = config.TILE_MIN_ZOOM, + zmax: int = config.TILE_MAX_ZOOM, + attribution: str = "", + project: Optional[QgsProject] = None) -> QgsVectorTileLayer: + project = project or QgsProject.instance() + style_id = str(style.get("id") or "") + if not style_id: + raise GeoDonkeyError(tr("No map style selected.")) + + layer = QgsVectorTileLayer(build_uri(api_url, style_id, zmin, zmax), + "GeoDonkey %s" % (style.get("name") or style_id)) + if not layer.isValid(): + raise GeoDonkeyError( + tr("The basemap could not be loaded. Check the API address and your connection.")) + + name = layer.name() + layer.loadDefaultStyle() + layer.setName(name) + + md = QgsLayerMetadata() + md.setTitle(name) + md.setRights([attribution or config.DEFAULT_ATTRIBUTION]) + md.setLicenses([config.OSM_LICENSE]) + md.setAbstract(tr("GeoDonkey vector tiles, style “{style}”. {license}").format( + style=style.get("name") or style_id, license=config.OSM_LICENSE_URL)) + layer.setMetadata(md) + + project.addMapLayer(layer, False) + root = project.layerTreeRoot() + root.insertLayer(len(root.children()), layer) + return layer diff --git a/geodonkey/client.py b/geodonkey/client.py new file mode 100644 index 0000000..6b2fb30 --- /dev/null +++ b/geodonkey/client.py @@ -0,0 +1,383 @@ +from __future__ import annotations + +import json +from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple + +from . import config, points +from . import upload as upload_mod +from .errors import GeoDonkeyError, NetworkError, describe +from .i18n import tr + + +class Response(object): + def __init__(self, status: Optional[int], headers: Mapping[str, str], + body: bytes, url: str = "", error: str = "") -> None: + self.status = status + self.headers = {str(k).lower(): v for k, v in dict(headers or {}).items()} + self.body = body or b"" + self.url = url + self.error = error + + def json(self) -> Any: + if not self.body: + return None + try: + return json.loads(self.body.decode("utf-8", "replace")) + except ValueError: + return None + + +class Usage(object): + FIELDS = ( + ("balance", "x-coins-balance"), + ("charged", "x-coins-charged"), + ("limit", "x-ratelimit-limit"), + ("remaining", "x-ratelimit-remaining"), + ("reset", "x-ratelimit-reset"), + ("free_limit", "x-freecalls-limit"), + ("free_remaining", "x-freecalls-remaining"), + ("free_reset", "x-freecalls-reset"), + ("month_limit", "x-ratelimit-month-limit"), + ("month_remaining", "x-ratelimit-month-remaining"), + ) + + def __init__(self, headers: Optional[Mapping[str, str]] = None) -> None: + for name, _header in self.FIELDS: + setattr(self, name, None) + self.update(headers or {}) + + def update(self, headers: Mapping[str, str]) -> "Usage": + lower = {str(k).lower(): v for k, v in dict(headers or {}).items()} + for name, header in self.FIELDS: + raw = lower.get(header) + if raw is None or raw == "": + continue + try: + setattr(self, name, int(float(raw))) + except (TypeError, ValueError): + continue + return self + + def known(self) -> bool: + return self.balance is not None or self.limit is not None + + +def _clean(params: Mapping[str, Any]) -> Dict[str, str]: + out = {} + for key, value in params.items(): + if value is None: + continue + text = str(value) + if not text.strip(): + continue + out[key] = text + return out + + +def flag(value: Any) -> str: + return "true" if value else "false" + + +def parse_values(text: str, minimum: float, maximum: float, limit: int, + label: str) -> List[float]: + raw = [piece.strip() for piece in str(text or "").replace(";", ",").split(",")] + raw = [piece for piece in raw if piece] + if not raw: + raise GeoDonkeyError( + tr("Enter at least one value for {label}.").format(label=label)) + if len(raw) > limit: + raise GeoDonkeyError( + tr("At most {limit} rings can be calculated, {count} were given.").format( + limit=limit, count=len(raw))) + values: List[float] = [] + for piece in raw: + try: + value = float(piece.replace(",", ".")) + except ValueError: + raise GeoDonkeyError( + tr("“{value}” is not a number.").format(value=piece)) + if not minimum <= value <= maximum: + raise GeoDonkeyError( + tr("{value} is outside the allowed range for {label} " + "({min} to {max}).").format( + value=points.fmt(value), label=label, + min=points.fmt(minimum), max=points.fmt(maximum))) + values.append(value) + unique = sorted(set(values)) + return unique + + +def check_mode(mode: str, default: str) -> str: + key = (mode or default or "").strip().lower() + if key not in config.TRAVEL_MODES: + raise GeoDonkeyError( + tr("Unknown travel mode “{mode}”. Available: {list}.").format( + mode=mode, list=", ".join(config.TRAVEL_MODES))) + return key + + +def build_url(base_url: str, path: str, params: Optional[Mapping[str, Any]] = None) -> str: + from urllib.parse import urlencode + + url = config.api_endpoint(base_url, path) + clean = _clean(params or {}) + if clean: + url += "?" + urlencode(sorted(clean.items())) + return url + + +class ApiClient(object): + def __init__(self, transport: Callable[..., Response], + base_url: str = config.DEFAULT_API_URL, + token: Optional[str] = None, + language: str = "en") -> None: + self.transport = transport + self.base_url = (base_url or config.DEFAULT_API_URL).rstrip("/") + self.token = (token or "").strip() + self.language = language or "en" + self.usage = Usage() + + def headers(self, extra: Optional[Mapping[str, str]] = None) -> Dict[str, str]: + head = { + "Accept": "application/json", + "Accept-Language": self.language, + "User-Agent": config.USER_AGENT, + } + if self.token: + head["Authorization"] = "Bearer " + self.token + head.update(dict(extra or {})) + return head + + def request(self, method: str, path: str, + params: Optional[Mapping[str, Any]] = None, + body: Optional[bytes] = None, + content_type: str = "", + feedback: Any = None) -> Any: + url = build_url(self.base_url, path, params) + extra = {"Content-Type": content_type} if content_type else None + try: + response = self.transport(method=method, url=url, + headers=self.headers(extra), body=body, + feedback=feedback) + except GeoDonkeyError: + raise + except Exception as exc: + raise NetworkError(tr("No connection to the GeoDonkey service."), + detail="%s: %s" % (url, exc)) + + self.usage.update(response.headers) + + if response.status is None: + raise describe(None, response.error or None, response.headers, url) + if response.status >= 400: + raise describe(response.status, response.json() or response.error, + response.headers, url) + + data = response.json() + if data is None and response.body: + raise GeoDonkeyError( + tr("The GeoDonkey service returned a response that could not be read."), + status=response.status, detail=url) + return data + + def account(self, feedback: Any = None) -> Dict[str, Any]: + data = self.request("GET", "/user/dashboard", feedback=feedback) or {} + user = data.get("user") or {} + return { + "email": user.get("email") or "", + "plan": user.get("plan") or "", + "tier": user.get("tier") or "", + "coins": user.get("coin_balance"), + "monthly_coins": user.get("monthly_coins"), + "rate_limit_per_hour": user.get("rate_limit_per_hour"), + "rate_limit_per_month": user.get("rate_limit_per_month"), + "pro": str(user.get("tier") or "").lower() in ("professional", "enterprise", "admin"), + } + + def osm_search(self, area: Mapping[str, str], words: str = "", tags: str = "", + types: str = "", limit: Optional[int] = None, + feedback: Any = None) -> Dict[str, Any]: + words = (words or "").strip() + tags = (tags or "").strip() + if words and tags: + raise GeoDonkeyError( + tr("Use either a plain-language search or tag filters, not both.")) + if not words and not tags: + raise GeoDonkeyError(tr("Enter a search term or a tag filter.")) + params = dict(area) + params.update({"q": words, "tags": tags, "types": types, "limit": limit}) + return self.request("GET", "/osm", params=params, feedback=feedback) or {} + + def osm_query(self, query: str, area: Mapping[str, str], + limit: Optional[int] = None, feedback: Any = None) -> Dict[str, Any]: + text = (query or "").strip() + if not text: + raise GeoDonkeyError(tr("The query is empty.")) + params = dict(area) + if limit: + params["limit"] = limit + return self.request("POST", "/osm", params=params, + body=text.encode("utf-8"), + content_type="text/plain; charset=utf-8", + feedback=feedback) or {} + + def osm_status(self, feedback: Any = None) -> Dict[str, Any]: + return self.request("GET", "/osm/status", feedback=feedback) or {} + + def isochrone(self, lon: float, lat: float, + mode: str = config.ISOCHRONE_DEFAULT_MODE, + minutes: str = "", kilometres: str = "", + feedback: Any = None) -> Dict[str, Any]: + x, y = points.check(lon, lat) + key = check_mode(mode, config.ISOCHRONE_DEFAULT_MODE) + minutes = (minutes or "").strip() + kilometres = (kilometres or "").strip() + if minutes and kilometres: + raise GeoDonkeyError( + tr("Use either travel time or distance, not both.")) + if kilometres: + values = parse_values(kilometres, config.ISOCHRONE_MIN_KILOMETRES, + config.ISOCHRONE_MAX_KILOMETRES, + config.ISOCHRONE_MAX_RINGS, tr("kilometres")) + extra = {"kilometers": ",".join(points.fmt(v) for v in values)} + else: + values = parse_values(minutes or config.ISOCHRONE_DEFAULT_MINUTES, + config.ISOCHRONE_MIN_MINUTES, + config.ISOCHRONE_MAX_MINUTES, + config.ISOCHRONE_MAX_RINGS, tr("minutes")) + extra = {"minutes": ",".join(points.fmt(v) for v in values)} + params = {"lat": points.fmt(y), "lon": points.fmt(x), "mode": key} + params.update(extra) + return self.request("GET", "/isochrone", params=params, + feedback=feedback) or {} + + def route(self, stops: Sequence[Tuple[float, float]], + mode: str = config.ROUTE_DEFAULT_MODE, optimize: bool = False, + steps: bool = False, language: str = "", + feedback: Any = None) -> Dict[str, Any]: + pairs = [tuple(pair) for pair in stops] + if len(pairs) < config.ROUTE_MIN_POINTS: + raise GeoDonkeyError( + tr("A route needs at least {count} points.").format( + count=config.ROUTE_MIN_POINTS)) + key = check_mode(mode, config.ROUTE_DEFAULT_MODE) + params = { + "points": points.series(pairs, config.ROUTE_MAX_POINTS), + "mode": key, + "optimize": flag(optimize), + "steps": flag(steps), + } + language = (language or "").strip().lower()[:2] + if language in config.ROUTE_LANGUAGES: + params["language"] = language + return self.request("GET", "/route", params=params, + feedback=feedback) or {} + + def elevation_profile(self, start: Tuple[float, float], + end: Tuple[float, float], + max_points: int = config.ELEVATION_MAX_POINTS, + step: float = config.ELEVATION_DEFAULT_STEP_METRES, + feedback: Any = None) -> Dict[str, Any]: + a = points.check_germany(*start) + b = points.check_germany(*end) + limit = max(2, min(int(max_points), config.ELEVATION_MAX_POINTS)) + body = { + "start": points.lonlat(*a), + "end": points.lonlat(*b), + "max_points": limit, + "step": max(config.ELEVATION_MIN_STEP_METRES, float(step)), + } + return self.request("POST", "/elevation/profile", + body=json.dumps(body).encode("utf-8"), + content_type="application/json", + feedback=feedback) or {} + + def elevation_points(self, coordinates: Sequence[Tuple[float, float]], + feedback: Any = None) -> Dict[str, Any]: + pairs = [points.check_germany(x, y) for x, y in coordinates] + if not pairs: + raise GeoDonkeyError(tr("No points given.")) + if len(pairs) > config.ELEVATION_MAX_POINTS: + raise GeoDonkeyError( + tr("{count} points given, at most {limit} are allowed.").format( + count=len(pairs), limit=config.ELEVATION_MAX_POINTS)) + body = {"coordinates": [points.lonlat(x, y) for x, y in pairs]} + return self.request("POST", "/elevation/points", + body=json.dumps(body).encode("utf-8"), + content_type="application/json", + feedback=feedback) or {} + + def line_of_sight(self, start: Tuple[float, float], + end: Tuple[float, float], + height_a: float = config.LOS_DEFAULT_HEIGHT_METRES, + height_b: float = config.LOS_DEFAULT_HEIGHT_METRES, + curvature: bool = True, + k: float = config.LOS_REFRACTION_K, + step: float = config.ELEVATION_DEFAULT_STEP_METRES, + max_points: int = config.ELEVATION_MAX_POINTS, + samples: bool = False, + feedback: Any = None) -> Dict[str, Any]: + a = points.check_germany(*start) + b = points.check_germany(*end) + for height in (height_a, height_b): + if not 0.0 <= float(height) <= config.LOS_MAX_HEIGHT_METRES: + raise GeoDonkeyError( + tr("Heights above ground must be between 0 and {max} m.").format( + max=int(config.LOS_MAX_HEIGHT_METRES))) + if float(k) <= 0: + raise GeoDonkeyError(tr("The refraction factor must be greater than zero.")) + params = { + "from": points.latlon(*a), + "to": points.latlon(*b), + "height_a": points.fmt(height_a), + "height_b": points.fmt(height_b), + "curvature": flag(curvature), + "k": points.fmt(k), + "step": points.fmt(max(config.ELEVATION_MIN_STEP_METRES, float(step))), + "max_points": max(2, min(int(max_points), config.ELEVATION_MAX_POINTS)), + "samples": flag(samples), + } + return self.request("GET", "/line-of-sight", params=params, + feedback=feedback) or {} + + def upload_dataset(self, filename: str, data: bytes, ttl_days: int = 1, + feedback: Any = None) -> Dict[str, Any]: + body, content_type = upload_mod.multipart( + {"ttl_days": str(int(ttl_days))}, filename, data) + return self.request("POST", "/uploads", body=body, + content_type=content_type, feedback=feedback) or {} + + def uploads(self, feedback: Any = None) -> Dict[str, Any]: + return self.request("GET", "/uploads", feedback=feedback) or {} + + def upload_geojson(self, upload_id: str, feedback: Any = None) -> Dict[str, Any]: + ident = (upload_id or "").strip() + if not ident: + raise GeoDonkeyError(tr("Choose a dataset first.")) + return self.request("GET", upload_mod.dataset_path(ident), + feedback=feedback) or {} + + def delete_upload(self, upload_id: str, feedback: Any = None) -> Dict[str, Any]: + ident = (upload_id or "").strip() + if not ident: + raise GeoDonkeyError(tr("Choose a dataset to discard.")) + return self.request("DELETE", "/uploads/" + ident, + feedback=feedback) or {} + + def map_styles(self, feedback: Any = None) -> Dict[str, Any]: + return self.request("GET", "/map-styles", feedback=feedback) or {} + + def tilejson(self, feedback: Any = None) -> Dict[str, Any]: + return self.request("GET", "/tiles.json", feedback=feedback) or {} + + +def split_collection(data: Mapping[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]: + if not isinstance(data, Mapping): + return {"type": "FeatureCollection", "features": []}, {} + meta = data.get("metadata") + meta = dict(meta) if isinstance(meta, Mapping) else {} + collection = { + "type": "FeatureCollection", + "features": list(data.get("features") or []), + } + return collection, meta diff --git a/geodonkey/compat.py b/geodonkey/compat.py new file mode 100644 index 0000000..902085d --- /dev/null +++ b/geodonkey/compat.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import os + +try: + from qgis.PyQt.QtWidgets import QAction +except ImportError: + from qgis.PyQt.QtGui import QAction # noqa: F401 + +try: + from qgis.PyQt.QtWidgets import QShortcut # noqa: F401 +except ImportError: + try: + from qgis.PyQt.QtGui import QShortcut # noqa: F401 + except ImportError: + QShortcut = None # noqa: N816 + +PLUGIN_DIR = os.path.dirname(os.path.abspath(__file__)) + + +def icon_path(name: str) -> str: + return os.path.join(PLUGIN_DIR, "icons", name) + + +def icon(name: str): + from qgis.PyQt.QtGui import QIcon + + return QIcon(icon_path(name)) + + +FIELD_TYPES = { + "string": ("QString", "String"), + "double": ("Double", "Double"), + "integer": ("Int", "Int"), + "boolean": ("Bool", "Bool"), +} + + +def field(name: str, kind: str = "string"): + from qgis.core import QgsField + + modern, legacy = FIELD_TYPES.get(kind, FIELD_TYPES["string"]) + try: + from qgis.PyQt.QtCore import QMetaType + + return QgsField(name, getattr(QMetaType.Type, modern)) + except (ImportError, AttributeError, TypeError): + from qgis.PyQt.QtCore import QVariant + + return QgsField(name, getattr(QVariant, legacy)) + + +def string_field(name: str): + return field(name, "string") + + +def pixels(): + try: + from qgis.core import Qgis + + return Qgis.RenderUnit.Pixels + except (ImportError, AttributeError): + from qgis.core import QgsUnitTypes + + return QgsUnitTypes.RenderUnit.RenderPixels diff --git a/geodonkey/config.py b/geodonkey/config.py new file mode 100644 index 0000000..ec1eb38 --- /dev/null +++ b/geodonkey/config.py @@ -0,0 +1,199 @@ +from __future__ import annotations + +DEFAULT_API_URL = "https://api.geodonkey.com" + +API_PREFIX = "/api/v1" + +WEBSITE_URL = "https://geodonkey.com" + +TOKEN_URL = WEBSITE_URL + "/dashboard" + +TOKEN_PREFIXES = ("gd_live_", "gd_test_") + +COIN_COSTS = { + "osm": 3, + "staticmap": 3, + "geocode": 1, + "elevation": 2, + "elevation_points": 2, + "elevation_profile": 2, + "line_of_sight": 2, + "isochrone": 2, + "route": 2, + "route_optimized": 3, + "matrix": 3, + "upload": 50, + "upload_pro": 100, + "upload_extra_day": 10, +} + +FREE_CALLS_PER_HOUR = 60 + +ENDPOINT_FREE_CALLS = { + "line_of_sight": 5, +} + +OSM_LIMIT_DEFAULT = 100 +OSM_LIMIT_PRO = 2000 + +MAX_BBOX_AREA_DEGREES = 100.0 +MAX_RADIUS_METRES = 50000 +MAX_POLYGON_POINTS = 500 +MAX_TAGS = 10 + +TRAVEL_MODES = ("walking", "driving", "cycling") + +ISOCHRONE_DEFAULT_MODE = "walking" +ROUTE_DEFAULT_MODE = "driving" + +ISOCHRONE_MAX_RINGS = 4 +ISOCHRONE_MIN_MINUTES = 1.0 +ISOCHRONE_MAX_MINUTES = 60.0 +ISOCHRONE_MIN_KILOMETRES = 0.1 +ISOCHRONE_MAX_KILOMETRES = 100.0 +ISOCHRONE_DEFAULT_MINUTES = "5,10,15" + +ROUTE_MIN_POINTS = 2 +ROUTE_MAX_POINTS = 10 + +ROUTE_MAX_KILOMETRES = { + "walking": 100.0, + "cycling": 150.0, + "driving": 1500.0, +} + +ROUTE_LANGUAGES = ("de", "en", "fr", "es") + +ELEVATION_MAX_POINTS = 500 + +ELEVATION_BILLING_BATCH = 100 + +ELEVATION_MIN_STEP_METRES = 1.0 +ELEVATION_DEFAULT_STEP_METRES = 10.0 + +ELEVATION_BBOX = (5.0, 47.0, 15.0, 55.0) + +LOS_DEFAULT_HEIGHT_METRES = 1.7 +LOS_MAX_HEIGHT_METRES = 1000.0 + +LOS_REFRACTION_K = 4.0 / 3.0 + +LOS_FREE_METRES = 1000.0 + + +UPLOAD_FREE_OBJECTS = 10 + +UPLOAD_STANDARD_MAX_OBJECTS = 5000 +UPLOAD_PRO_MAX_OBJECTS = 20000 + +UPLOAD_DEFAULT_TTL_DAYS = 14 +UPLOAD_MAX_TTL_DAYS = 14 +UPLOAD_PRO_MAX_TTL_DAYS = 30 + +UPLOAD_MAX_DATASETS = 20 + +UPLOAD_MAX_BYTES = 10 * 1024 * 1024 + +TILE_MIN_ZOOM = 0 +TILE_MAX_ZOOM = 14 + +FALLBACK_STYLES = ( + {"id": "geodonkey-bright", "name": "GeoDonkey Bright", "dark": False, + "swatch": ["#f6f7fa", "#d2deef", "#ffffff"]}, + {"id": "geodonkey-day", "name": "GeoDonkey Day", "dark": False, + "swatch": ["#f2f5fa", "#8fb4e0", "#002060"]}, + {"id": "geodonkey-night", "name": "GeoDonkey Night", "dark": True, + "swatch": ["#0d1117", "#10243e", "#c8a24a"]}, + {"id": "classic", "name": "Classic", "dark": False, + "swatch": ["#f3efe8", "#a9c9ee", "#e9929f"]}, + {"id": "blueprint", "name": "Blueprint", "dark": True, + "swatch": ["#08203c", "#0c2b50", "#b9d9f5"]}, + {"id": "neon-coast", "name": "Neon Coast", "dark": True, + "swatch": ["#140b26", "#0f2a4d", "#ff2e88"]}, + {"id": "open-world", "name": "Open World", "dark": True, + "swatch": ["#10212b", "#0a3b4f", "#ffc93c"]}, +) + +DEFAULT_ATTRIBUTION = ( + "OpenFreeMap © OpenMapTiles © OpenStreetMap-Mitwirkende" +) +OSM_LICENSE = "ODbL-1.0" +OSM_LICENSE_URL = "https://www.openstreetmap.org/copyright" + +BRAND = { + "navy": "#002060", + "navy_dark": "#001a4d", + "green": "#40e060", + "green_dark": "#2bb848", + "green_deep": "#1fb23c", + "tint": "#eef2f7", + "tint_line": "#dbe3ec", + "paper": "#f8fafc", + "line": "#d5dae3", + "ink": "#1b2433", + "muted": "#5f7196", + "tint_night": "#16223a", + "tint_line_night": "#2a3a57", + "muted_night": "#9fb3d1", + "warn": "#b4660f", + "warn_night": "#e0a155", + "error": "#c0392b", + "error_night": "#f08a7f", + "good": "#1a8c38", + "good_night": "#5ddb7a", +} + +SETTINGS_GROUP = "geodonkey" + +USER_AGENT = "geodonkey-qgis-plugin" + + +def api_endpoint(base_url: str, path: str) -> str: + base = (base_url or DEFAULT_API_URL).rstrip("/") + tail = path if path.startswith("/") else "/" + path + if tail.startswith(API_PREFIX): + return base + tail + return base + API_PREFIX + tail + + +def elevation_coins(points: int, key: str = "elevation_profile") -> int: + batch = max(1, int(ELEVATION_BILLING_BATCH)) + count = max(1, int(points)) + units = (count + batch - 1) // batch + return units * COIN_COSTS.get(key, 2) + + +def line_of_sight_coins(metres: float) -> int: + try: + distance = float(metres) + except (TypeError, ValueError): + return COIN_COSTS.get("line_of_sight", 2) + if distance <= LOS_FREE_METRES: + return 0 + return COIN_COSTS.get("line_of_sight", 2) + + +def upload_ttl_limit(pro: bool = False) -> int: + return UPLOAD_PRO_MAX_TTL_DAYS if pro else UPLOAD_MAX_TTL_DAYS + + +def upload_object_limit(pro: bool = False) -> int: + return UPLOAD_PRO_MAX_OBJECTS if pro else UPLOAD_STANDARD_MAX_OBJECTS + + +def upload_coins(objects: int, ttl_days: int = 1, pro: bool = False) -> int: + try: + count = int(objects) + except (TypeError, ValueError): + return 0 + if count <= UPLOAD_FREE_OBJECTS: + return 0 + base = (COIN_COSTS.get("upload_pro", 100) + if count > UPLOAD_STANDARD_MAX_OBJECTS + else COIN_COSTS.get("upload", 50)) + try: + days = int(ttl_days) + except (TypeError, ValueError): + days = 1 + extra = max(0, min(days, upload_ttl_limit(pro)) - 1) + return base + extra * COIN_COSTS.get("upload_extra_day", 10) diff --git a/geodonkey/errors.py b/geodonkey/errors.py new file mode 100644 index 0000000..fa7b88d --- /dev/null +++ b/geodonkey/errors.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +from typing import Any, Mapping, Optional + +from .config import TOKEN_URL, WEBSITE_URL +from .i18n import tr + + +class GeoDonkeyError(Exception): + def __init__(self, message: str, *, status: Optional[int] = None, + code: str = "", detail: str = "", + retry_after: Optional[int] = None) -> None: + super().__init__(message) + self.message = message + self.status = status + self.code = code + self.detail = detail + self.retry_after = retry_after + + def __str__(self) -> str: + return self.message + + +class NetworkError(GeoDonkeyError): + pass + + +class AuthError(GeoDonkeyError): + pass + + +class CoinsError(GeoDonkeyError): + pass + + +class RateLimitError(GeoDonkeyError): + pass + + +class RequestError(GeoDonkeyError): + pass + + +def _server_text(payload: Any) -> str: + if isinstance(payload, Mapping): + error = payload.get("error") + if isinstance(error, Mapping): + for key in ("message", "detail"): + value = error.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + detail = payload.get("detail") + if isinstance(detail, str) and detail.strip(): + return detail.strip() + if isinstance(detail, list) and detail: + first = detail[0] + if isinstance(first, Mapping) and isinstance(first.get("msg"), str): + return first["msg"] + if isinstance(payload, str) and payload.strip(): + return payload.strip()[:400] + return "" + + +def _hint(payload: Any) -> str: + if isinstance(payload, Mapping): + error = payload.get("error") + if isinstance(error, Mapping) and isinstance(error.get("hint"), str): + return error["hint"].strip() + return "" + + +def _code(payload: Any) -> str: + if isinstance(payload, Mapping): + error = payload.get("error") + if isinstance(error, Mapping) and isinstance(error.get("code"), str): + return error["code"] + return "" + + +def _retry_after(payload: Any, headers: Optional[Mapping[str, str]]) -> Optional[int]: + if headers: + raw = headers.get("retry-after") or headers.get("Retry-After") + if raw: + try: + return max(0, int(float(raw))) + except (TypeError, ValueError): + pass + if isinstance(payload, Mapping): + error = payload.get("error") + if isinstance(error, Mapping): + raw = error.get("retry_after_seconds") + if isinstance(raw, (int, float)): + return max(0, int(raw)) + return None + + +def describe(status: Optional[int], payload: Any = None, + headers: Optional[Mapping[str, str]] = None, + url: str = "") -> GeoDonkeyError: + server = _server_text(payload) + hint = _hint(payload) + code = _code(payload) + wait = _retry_after(payload, headers) + detail = " · ".join(part for part in (url, server, hint) if part) + + if status == 401: + return AuthError( + tr("The GeoDonkey API key is missing or no longer valid. " + "Open the plugin settings and paste a key from {url}.").format(url=TOKEN_URL), + status=status, code=code, detail=detail) + + if status == 402: + return CoinsError( + tr("Not enough DonkeyCoins for this request. " + "Top up your balance at {url}.").format(url=WEBSITE_URL + "/preise"), + status=status, code=code, detail=detail) + + if status == 403: + return AuthError( + server or tr("This API key is not allowed to use that endpoint."), + status=status, code=code, detail=detail) + + if status == 429: + if wait: + message = tr("Rate limit reached. Try again in {seconds} seconds.").format(seconds=wait) + else: + message = tr("Rate limit reached. Please wait a moment and try again.") + return RateLimitError(message, status=status, code=code, detail=detail, + retry_after=wait) + + if status in (400, 404, 409, 413, 422): + return RequestError( + server or tr("The request was rejected. Please check the query and the area."), + status=status, code=code, detail=detail) + + if status is not None and status >= 500: + return GeoDonkeyError( + tr("The GeoDonkey service reported a problem. Please try again later."), + status=status, code=code, detail=detail) + + if status is None: + return NetworkError( + server or tr("No connection to the GeoDonkey service. " + "Check your internet connection and proxy settings."), + status=None, code=code, detail=detail) + + return GeoDonkeyError(server or tr("Unexpected response from the GeoDonkey service."), + status=status, code=code, detail=detail) diff --git a/geodonkey/export.py b/geodonkey/export.py new file mode 100644 index 0000000..1e71082 --- /dev/null +++ b/geodonkey/export.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +import os +import time +from typing import Optional, Tuple + +from qgis.core import ( + QgsCoordinateReferenceSystem, + QgsCoordinateTransform, + QgsProject, + QgsVectorFileWriter, + QgsVectorLayer, +) + +from . import layers, upload +from .errors import GeoDonkeyError +from .i18n import tr +from .mapcontext import WGS84 + + +def feature_count(layer: QgsVectorLayer, selected_only: bool = False) -> int: + if layer is None: + return 0 + if selected_only: + return int(layer.selectedFeatureCount()) + count = layer.featureCount() + return int(count) if count and count > 0 else 0 + + +def _target_path(layer: QgsVectorLayer) -> str: + name = upload.filename_for(layer.name() if layer is not None else "") + return os.path.join(layers.result_folder(), + "upload-%d-%s" % (int(time.time()), name)) + + +def layer_to_geojson(layer: QgsVectorLayer, + selected_only: bool = False, + feedback=None) -> Tuple[bytes, str]: + if layer is None: + raise GeoDonkeyError(tr("Choose a vector layer first.")) + if selected_only and layer.selectedFeatureCount() <= 0: + raise GeoDonkeyError(tr("Nothing is selected in this layer.")) + + options = QgsVectorFileWriter.SaveVectorOptions() + options.driverName = "GeoJSON" + options.fileEncoding = "UTF-8" + options.onlySelectedFeatures = bool(selected_only) + options.ct = QgsCoordinateTransform(layer.crs(), + QgsCoordinateReferenceSystem(WGS84), + QgsProject.instance()) + options.layerOptions = ["RFC7946=YES", "WRITE_NAME=NO", "COORDINATE_PRECISION=7"] + if feedback is not None: + options.feedback = feedback + + path = _target_path(layer) + result = QgsVectorFileWriter.writeAsVectorFormatV3( + layer, path, QgsProject.instance().transformContext(), options) + code = result[0] + message = result[1] if len(result) > 1 else "" + if code != QgsVectorFileWriter.WriterError.NoError: + raise GeoDonkeyError( + tr("The layer could not be written as GeoJSON."), + detail="%s (%s)" % (message or code, path)) + + written = result[2] if len(result) > 2 and result[2] else path + try: + with open(written, "rb") as handle: + data = handle.read() + except OSError as exc: + raise GeoDonkeyError(tr("The layer could not be written as GeoJSON."), + detail="%s: %s" % (written, exc)) + finally: + _remove(written) + + if not data.strip(): + raise GeoDonkeyError(tr("The layer has no features to upload.")) + return data, upload.filename_for(layer.name()) + + +def _remove(path: Optional[str]) -> None: + if not path: + return + try: + os.remove(path) + except OSError: + pass diff --git a/geodonkey/geojson.py b/geodonkey/geojson.py new file mode 100644 index 0000000..f4358e0 --- /dev/null +++ b/geodonkey/geojson.py @@ -0,0 +1,212 @@ +from __future__ import annotations + +import json +import os +import re +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple + +from .i18n import tr + +GEOMETRY_GROUPS = { + "Point": "Point", + "MultiPoint": "Point", + "LineString": "Line", + "MultiLineString": "Line", + "Polygon": "Polygon", + "MultiPolygon": "Polygon", +} + +GROUP_ORDER = ("Point", "Line", "Polygon") + +OGR_GEOMETRY_TYPE = { + "Point": "Point", + "Line": "LineString", + "Polygon": "Polygon", +} + + +def geometry_group(feature: Mapping[str, Any]) -> Optional[str]: + if not isinstance(feature, Mapping): + return None + geometry = feature.get("geometry") + if not isinstance(geometry, Mapping): + return None + return GEOMETRY_GROUPS.get(geometry.get("type")) + + +def split_by_geometry(collection: Mapping[str, Any]) -> "Tuple[Dict[str, Dict[str, Any]], int]": + buckets: Dict[str, List[Any]] = {name: [] for name in GROUP_ORDER} + without = 0 + for feature in (collection or {}).get("features") or []: + group = geometry_group(feature) + if group is None: + without += 1 + continue + buckets[group].append(feature) + out: Dict[str, Dict[str, Any]] = {} + for name in GROUP_ORDER: + if buckets[name]: + out[name] = {"type": "FeatureCollection", "features": buckets[name]} + return out, without + + +def tag_keys(collection: Mapping[str, Any], limit: int = 0) -> List[str]: + keys = set() + for feature in (collection or {}).get("features") or []: + props = feature.get("properties") if isinstance(feature, Mapping) else None + tags = props.get("tags") if isinstance(props, Mapping) else None + if isinstance(tags, Mapping): + keys.update(str(k) for k in tags.keys()) + names = sorted(keys) + return names[:limit] if limit else names + + +_UNSAFE = re.compile(r"[^0-9A-Za-zÄÖÜäöüß _.\-]+") + + +def safe_name(text: str, fallback: str = "donkeyosm", limit: int = 48) -> str: + cleaned = _UNSAFE.sub(" ", str(text or "")).strip() + cleaned = re.sub(r"\s+", " ", cleaned) + if not cleaned: + cleaned = fallback + if len(cleaned) > limit: + cleaned = cleaned[:limit].rstrip() + "…" + return cleaned + + +def write_collection(folder: str, basename: str, collection: Mapping[str, Any]) -> str: + path = os.path.join(folder, basename + ".geojson") + with open(path, "w", encoding="utf-8") as handle: + json.dump(collection, handle, ensure_ascii=False) + return path + + +def result_summary(meta: Mapping[str, Any], counts: Mapping[str, int], + without_geometry: int = 0) -> str: + total = sum(counts.values()) + parts = [tr("{count} objects").format(count=total)] + detail = ", ".join( + "%s %s" % (counts[name], name.lower()) + for name in GROUP_ORDER if counts.get(name)) + if detail and len(counts) > 1: + parts.append("(%s)" % detail) + if without_geometry: + parts.append(tr("{count} without geometry").format(count=without_geometry)) + if meta.get("truncated"): + parts.append(tr("limit of {limit} reached – the result is incomplete").format( + limit=meta.get("limit") or "?")) + return " · ".join(parts) + + +def attribution(meta: Mapping[str, Any], fallback: str = "") -> str: + for key in ("attribution", "provider"): + value = (meta or {}).get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return fallback + + +def ogr_uri(path: str, group: str = "", flatten: bool = True) -> str: + uri = path + if flatten: + uri += "|option:FLATTEN_NESTED_ATTRIBUTES=YES" + wanted = OGR_GEOMETRY_TYPE.get(group) + if wanted: + uri += "|geometrytype=" + wanted + return uri + + +WKT_PRECISION = 8 + + +def _wkt_number(value: Any) -> str: + text = "%.*f" % (WKT_PRECISION, float(value)) + if "." in text: + text = text.rstrip("0").rstrip(".") + return text or "0" + + +def _wkt_point(pair: Sequence[Any]) -> str: + return "%s %s" % (_wkt_number(pair[0]), _wkt_number(pair[1])) + + +def _wkt_list(items: Sequence[Any]) -> str: + return "(" + ", ".join(_wkt_point(pair) for pair in items) + ")" + + +def _wkt_rings(rings: Sequence[Any]) -> str: + return "(" + ", ".join(_wkt_list(ring) for ring in rings) + ")" + + +def to_wkt(geometry: Optional[Mapping[str, Any]]) -> Optional[str]: + if not isinstance(geometry, Mapping): + return None + kind = geometry.get("type") + coords = geometry.get("coordinates") + if not kind or coords is None: + return None + try: + if kind == "Point": + if not coords: + return None + return "POINT (%s)" % _wkt_point(coords) + if kind == "MultiPoint": + if not coords: + return None + return "MULTIPOINT (%s)" % ", ".join( + "(%s)" % _wkt_point(pair) for pair in coords) + if kind == "LineString": + if len(coords) < 2: + return None + return "LINESTRING %s" % _wkt_list(coords) + if kind == "MultiLineString": + parts = [part for part in coords if len(part) >= 2] + if not parts: + return None + return "MULTILINESTRING (%s)" % ", ".join(_wkt_list(p) for p in parts) + if kind == "Polygon": + rings = [ring for ring in coords if len(ring) >= 4] + if not rings: + return None + return "POLYGON %s" % _wkt_rings(rings) + if kind == "MultiPolygon": + parts = [] + for polygon in coords: + rings = [ring for ring in polygon if len(ring) >= 4] + if rings: + parts.append(_wkt_rings(rings)) + if not parts: + return None + return "MULTIPOLYGON (%s)" % ", ".join(parts) + except (TypeError, ValueError, IndexError): + return None + return None + + +PROCESSING_FIELDS: Sequence[Tuple[str, str]] = ( + ("osm_type", "string"), + ("osm_id", "string"), + ("osm_url", "string"), + ("name", "string"), + ("tags", "string"), +) + + +def processing_row(feature: Mapping[str, Any]) -> Dict[str, str]: + props = feature.get("properties") if isinstance(feature, Mapping) else None + props = props if isinstance(props, Mapping) else {} + tags = props.get("tags") + if isinstance(tags, str) and tags.strip(): + try: + parsed = json.loads(tags) + except ValueError: + parsed = None + tags = parsed if isinstance(parsed, dict) else {} + tags = tags if isinstance(tags, Mapping) else {} + return { + "osm_type": str(props.get("osm_type") or ""), + "osm_id": str(props.get("osm_id") or ""), + "osm_url": str(props.get("osm_url") or ""), + "name": str(tags.get("name") or ""), + "tags": json.dumps(tags, ensure_ascii=False, sort_keys=True) if tags else "", + } diff --git a/geodonkey/gui/__init__.py b/geodonkey/gui/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/geodonkey/gui/chart.py b/geodonkey/gui/chart.py new file mode 100644 index 0000000..fde73a2 --- /dev/null +++ b/geodonkey/gui/chart.py @@ -0,0 +1,262 @@ +from __future__ import annotations + +from typing import List, Sequence, Tuple + +from qgis.PyQt.QtCore import QPointF, QRectF, QSize, Qt, pyqtSignal +from qgis.PyQt.QtGui import ( + QBrush, + QColor, + QFont, + QLinearGradient, + QPainter, + QPainterPath, + QPen, +) +from qgis.PyQt.QtWidgets import QSizePolicy, QWidget + +from .. import plot +from ..i18n import tr +from . import theme + +PAD_LEFT = 52 +PAD_RIGHT = 12 +PAD_TOP = 12 +PAD_BOTTOM = 28 + + +def _metres(value: float) -> str: + if abs(value) >= 1000.0: + return "%.1f km" % (value / 1000.0) + if abs(value) >= 10.0: + return "%.0f m" % value + return "%.1f m" % value + + +def _distance_axis(span: float): + if span >= 2000.0: + return lambda value: "%g km" % round(value / 1000.0, 2) + return lambda value: "%g m" % round(value, 1) + + +class ProfileChart(QWidget): + hovered = pyqtSignal(int) + + def __init__(self, parent=None) -> None: + super().__init__(parent) + self.setMinimumHeight(190) + self.setSizePolicy(QSizePolicy.Policy.Expanding, + QSizePolicy.Policy.Expanding) + self.setMouseTracking(True) + self.setCursor(Qt.CursorShape.CrossCursor) + + self._samples: List[plot.Sample] = [] + self._line: List[plot.Sample] = [] + self._marks: List[Tuple[float, float]] = [] + self._hover = -1 + self._empty = tr("Pick two points on the map.") + + def sizeHint(self): # noqa: N802 + return QSize(360, 220) + + def minimumSizeHint(self): # noqa: N802 + return QSize(220, 190) + + def set_samples(self, samples: Sequence[plot.Sample]) -> None: + self._samples = [(float(x), None if y is None else float(y)) + for x, y in samples] + self._hover = -1 + self.update() + + def set_line(self, line: Sequence[plot.Sample]) -> None: + self._line = [(float(x), None if y is None else float(y)) + for x, y in line] + self.update() + + def set_marks(self, marks: Sequence[Tuple[float, float]]) -> None: + self._marks = [(float(x), float(y)) for x, y in marks] + self.update() + + def set_placeholder(self, text: str) -> None: + self._empty = text + self.update() + + def clear(self) -> None: + self._samples = [] + self._line = [] + self._marks = [] + self._hover = -1 + self.update() + + def has_data(self) -> bool: + return bool(self._samples) + + def mouseMoveEvent(self, event): # noqa: N802 + if not self._samples: + return + scale_x, _ = self._scales() + index = plot.nearest(self._samples, scale_x.to_value(event.position().x() + if hasattr(event, "position") + else event.x())) + if index != self._hover: + self._hover = index + self.hovered.emit(index) + self.update() + + def leaveEvent(self, event): # noqa: N802 + if self._hover != -1: + self._hover = -1 + self.hovered.emit(-1) + self.update() + + def highlight(self, index: int) -> None: + if index != self._hover: + self._hover = index + self.update() + + def _area(self) -> QRectF: + return QRectF(PAD_LEFT, PAD_TOP, + max(1.0, self.width() - PAD_LEFT - PAD_RIGHT), + max(1.0, self.height() - PAD_TOP - PAD_BOTTOM)) + + def _scales(self) -> Tuple[plot.Scale, plot.Scale]: + area = self._area() + x0, x1, y0, y1 = plot.bounds(self._samples) + for x, y in self._line: + if y is None: + continue + y0, y1 = min(y0, y), max(y1, y) + low, high = plot.padded(y0, y1) + return (plot.Scale(x0, x1, area.left(), area.right()), + plot.Scale(low, high, area.bottom(), area.top())) + + def paintEvent(self, event): # noqa: N802 + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + colours = theme.colours() + area = self._area() + + painter.fillRect(self.rect(), QColor(colours["chart_bg"])) + + if not self._samples: + painter.setPen(QPen(QColor(colours["chart_muted"]))) + painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, self._empty) + painter.end() + return + + scale_x, scale_y = self._scales() + self._grid(painter, colours, area, scale_x, scale_y) + self._terrain(painter, colours, area, scale_x, scale_y) + if self._line: + self._sight(painter, colours, scale_x, scale_y) + self._points_of_interest(painter, colours, scale_x, scale_y) + self._cursor(painter, colours, area, scale_x, scale_y) + painter.end() + + def _grid(self, painter, colours, area, scale_x, scale_y) -> None: + font = QFont(self.font()) + font.setPointSizeF(max(7.0, font.pointSizeF() - 1.5)) + painter.setFont(font) + + grid = QPen(QColor(colours["chart_grid"])) + grid.setWidthF(1.0) + label = QPen(QColor(colours["chart_muted"])) + + for value in plot.ticks(scale_y.low, scale_y.high, 5): + y = scale_y.to_pixel(value) + painter.setPen(grid) + painter.drawLine(QPointF(area.left(), y), QPointF(area.right(), y)) + painter.setPen(label) + painter.drawText(QRectF(0, y - 8, PAD_LEFT - 6, 16), + int(Qt.AlignmentFlag.AlignRight + | Qt.AlignmentFlag.AlignVCenter), + "%g" % round(value, 1)) + + as_distance = _distance_axis(scale_x.high - scale_x.low) + for value in plot.ticks(scale_x.low, scale_x.high, 4): + x = scale_x.to_pixel(value) + painter.setPen(grid) + painter.drawLine(QPointF(x, area.top()), QPointF(x, area.bottom())) + painter.setPen(label) + painter.drawText(QRectF(x - 40, area.bottom() + 4, 80, 16), + int(Qt.AlignmentFlag.AlignCenter), as_distance(value)) + + def _terrain(self, painter, colours, area, scale_x, scale_y) -> None: + fill = QLinearGradient(0, area.top(), 0, area.bottom()) + top = QColor(colours["chart_terrain"]) + top.setAlpha(150) + bottom = QColor(colours["chart_terrain"]) + bottom.setAlpha(25) + fill.setColorAt(0.0, top) + fill.setColorAt(1.0, bottom) + + outline = QPen(QColor(colours["chart_terrain"])) + outline.setWidthF(2.0) + outline.setJoinStyle(Qt.PenJoinStyle.RoundJoin) + + for piece in plot.segments(self._samples): + path = QPainterPath() + path.moveTo(scale_x.to_pixel(piece[0][0]), scale_y.to_pixel(piece[0][1])) + for x, y in piece[1:]: + path.lineTo(scale_x.to_pixel(x), scale_y.to_pixel(y)) + + body = QPainterPath(path) + body.lineTo(scale_x.to_pixel(piece[-1][0]), area.bottom()) + body.lineTo(scale_x.to_pixel(piece[0][0]), area.bottom()) + body.closeSubpath() + painter.fillPath(body, QBrush(fill)) + + painter.strokePath(path, outline) + + def _sight(self, painter, colours, scale_x, scale_y) -> None: + pen = QPen(QColor(colours["warn"])) + pen.setWidthF(1.6) + pen.setStyle(Qt.PenStyle.DashLine) + painter.setPen(pen) + for piece in plot.segments(self._line): + path = QPainterPath() + path.moveTo(scale_x.to_pixel(piece[0][0]), scale_y.to_pixel(piece[0][1])) + for x, y in piece[1:]: + path.lineTo(scale_x.to_pixel(x), scale_y.to_pixel(y)) + painter.drawPath(path) + + def _points_of_interest(self, painter, colours, scale_x, scale_y) -> None: + painter.setPen(QPen(QColor(colours["error"]), 2.0)) + painter.setBrush(QBrush(QColor(colours["chart_bg"]))) + for x, y in self._marks: + painter.drawEllipse(QPointF(scale_x.to_pixel(x), scale_y.to_pixel(y)), + 4.5, 4.5) + + def _cursor(self, painter, colours, area, scale_x, scale_y) -> None: + if not (0 <= self._hover < len(self._samples)): + return + distance, height = self._samples[self._hover] + x = scale_x.to_pixel(distance) + + pen = QPen(QColor(colours["chart_text"])) + pen.setWidthF(1.0) + painter.setPen(pen) + painter.drawLine(QPointF(x, area.top()), QPointF(x, area.bottom())) + + if height is None: + text = tr("no elevation data") + else: + text = "%s · %g m" % (_metres(distance), round(height, 1)) + painter.setBrush(QBrush(QColor(colours["chart_text"]))) + painter.drawEllipse(QPointF(x, scale_y.to_pixel(height)), 3.5, 3.5) + + self._bubble(painter, colours, area, x, text) + + def _bubble(self, painter, colours, area, x: float, text: str) -> None: + metrics = painter.fontMetrics() + width = metrics.horizontalAdvance(text) + 12 + height = metrics.height() + 6 + left = min(max(area.left(), x - width / 2.0), area.right() - width) + box = QRectF(left, area.top(), width, height) + + back = QColor(colours["surface"]) + back.setAlpha(235) + painter.setBrush(QBrush(back)) + painter.setPen(QPen(QColor(colours["chart_grid"]))) + painter.drawRoundedRect(box, 4, 4) + painter.setPen(QPen(QColor(colours["chart_text"]))) + painter.drawText(box, int(Qt.AlignmentFlag.AlignCenter), text) diff --git a/geodonkey/gui/maptab.py b/geodonkey/gui/maptab.py new file mode 100644 index 0000000..9ceb2ff --- /dev/null +++ b/geodonkey/gui/maptab.py @@ -0,0 +1,391 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Sequence, Tuple + +from qgis.PyQt.QtCore import Qt +from qgis.PyQt.QtWidgets import ( + QHBoxLayout, + QLabel, + QPushButton, + QSizePolicy, + QVBoxLayout, + QWidget, +) +from qgis.core import Qgis + +from .. import layers, points as points_mod, results, task +from ..errors import GeoDonkeyError +from ..i18n import later, tr +from . import theme +from .pick import Dots, Marker, PointPicker, Shapes, Track + +Point = Tuple[float, float] + + +class MapTab(QWidget): + WANTED = 2 + FREE = False + LEAST = 2 + CONNECT = True + AUTO_RUN = True + PROMPTS: Sequence[str] = (later("Click a point on the map."),) + PICK_TEXT = later("Pick points on the map") + STOP_TEXT = later("Cancel picking") + FREE_STOP_TEXT = later("Use these points") + TASK_TITLE = later("GeoDonkey") + LAYER_TITLE = later("GeoDonkey result") + STYLE_KEY = "" + PLACEHOLDER = later("Pick points on the map.") + + def __init__(self, panel, iface, parent=None) -> None: + super().__init__(parent) + self.panel = panel + self.iface = iface + + self._picker: Optional[PointPicker] = None + self._previous_tool = None + self._collecting = False + self._task = None + + self.payload: Dict[str, Any] = {} + self.points: List[Point] = [] + + self._marker: Optional[Marker] = None + self._track: Optional[Track] = None + self._dots: Optional[Dots] = None + self._shapes: Optional[Shapes] = None + + self.setup() + self._build() + self.update_cost() + + def canvas(self): + return self.iface.mapCanvas() if self.iface is not None else None + + def marker(self) -> Optional[Marker]: + canvas = self.canvas() + if canvas is None: + return None + if self._marker is None: + self._marker = Marker(canvas) + return self._marker + + def track(self) -> Optional[Track]: + canvas = self.canvas() + if canvas is None: + return None + if self._track is None: + self._track = Track(canvas) + return self._track + + def dots(self) -> Optional[Dots]: + canvas = self.canvas() + if canvas is None: + return None + if self._dots is None: + self._dots = Dots(canvas) + return self._dots + + def shapes(self) -> Optional[Shapes]: + canvas = self.canvas() + if canvas is None: + return None + if self._shapes is None: + self._shapes = Shapes(canvas) + return self._shapes + + def setup(self) -> None: + pass + + def options(self) -> Optional[QWidget]: + return None + + def body(self) -> Optional[QWidget]: + return None + + def _build(self) -> None: + box = QVBoxLayout(self) + box.setContentsMargins(0, 0, 0, 0) + box.setSpacing(theme.GAP) + + pick = QVBoxLayout() + pick.setSpacing(theme.TIGHT) + self.pick_button = QPushButton(tr(self.PICK_TEXT)) + self.pick_button.setStyleSheet(theme.primary_button_style()) + self.pick_button.clicked.connect(self.toggle_picking) + pick.addWidget(self.pick_button) + + self.points_label = QLabel(tr("No points picked yet.")) + self.points_label.setWordWrap(True) + self.points_label.setTextFormat(Qt.TextFormat.RichText) + self.points_label.setStyleSheet(theme.note_style()) + pick.addWidget(self.points_label) + box.addLayout(pick) + + extra = self.options() + if extra is not None: + box.addWidget(extra) + + self.cost_label = QLabel("") + self.cost_label.setWordWrap(True) + self.cost_label.setStyleSheet(theme.note_style()) + theme.small(self.cost_label) + box.addWidget(self.cost_label) + + middle = self.body() + if middle is not None: + box.addWidget(middle, 1) + else: + box.addStretch(1) + + self.summary = QLabel("") + self.summary.setWordWrap(True) + self.summary.setTextFormat(Qt.TextFormat.RichText) + box.addWidget(self.summary) + + buttons = QHBoxLayout() + buttons.setSpacing(6) + self.keep_button = QPushButton(tr("Keep as layer")) + self.keep_button.setEnabled(False) + self.keep_button.clicked.connect(self.keep_as_layer) + buttons.addWidget(self.keep_button, 1) + + self.reset_button = QPushButton(tr("Reset")) + self.reset_button.setToolTip(tr( + "Clear the picked points and the result. " + "The settings above stay as they are.")) + self.reset_button.clicked.connect(self.reset) + buttons.addWidget(self.reset_button) + + self.cancel_button = QPushButton(tr("Cancel")) + self.cancel_button.setEnabled(False) + self.cancel_button.clicked.connect(self.cancel_task) + buttons.addWidget(self.cancel_button) + box.addLayout(buttons) + + self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Preferred) + + def price(self) -> str: + return "" + + def update_cost(self) -> None: + self.cost_label.setText(self.price()) + + def toggle_picking(self) -> None: + if self._collecting: + self.stop_picking() + return + self.start_picking() + + def prompt(self, index: int) -> str: + if not self.PROMPTS: + return "" + return tr(self.PROMPTS[min(index, len(self.PROMPTS) - 1)]) + + def start_picking(self) -> None: + canvas = self.canvas() + if canvas is None: + return + self._picker = PointPicker(canvas, wanted=self.WANTED, free=self.FREE, + least=self.LEAST, line=self.CONNECT) + self._picker.picked.connect(self._picked) + self._picker.progress.connect(self._progress) + self._picker.cancelled.connect(self._cancelled) + + self._previous_tool = canvas.mapTool() + self._collecting = True + canvas.setMapTool(self._picker) + + self.pick_button.setText( + tr(self.FREE_STOP_TEXT if self.FREE else self.STOP_TEXT)) + self.points_label.setText(self.prompt(0)) + track = self.track() + if track is not None: + track.clear() + dots = self.dots() + if dots is not None: + dots.clear() + self.panel.say(self.prompt(0)) + + def stop_picking(self) -> None: + picked = self._picker.wgs84_points() if self._picker is not None else [] + if self.enough(picked): + self._picked(picked) + return + self._collecting = False + self._restore_tool() + self.pick_button.setText(tr(self.PICK_TEXT)) + self.show_points() + + def _restore_tool(self) -> None: + canvas = self.canvas() + if canvas is not None and self._picker is not None \ + and canvas.mapTool() is self._picker: + canvas.unsetMapTool(self._picker) + if self._previous_tool is not None: + canvas.setMapTool(self._previous_tool) + self._picker = None + self._previous_tool = None + + def _progress(self, count: int, left: int) -> None: + self.points_label.setText(self.prompt(count)) + + def _cancelled(self) -> None: + if not self._collecting: + return + self._collecting = False + self._picker = None + self._previous_tool = None + self.pick_button.setText(tr(self.PICK_TEXT)) + self.points_label.setText(tr("No points picked yet.")) + + def enough(self, picked: Sequence[Point]) -> bool: + return len(picked) >= (self.LEAST if self.FREE else self.WANTED) + + def _picked(self, picked: list) -> None: + if not self.enough(picked): + return + self._collecting = False + self.points = [(float(lon), float(lat)) for lon, lat in picked] + self._restore_tool() + self.pick_button.setText(tr(self.PICK_TEXT)) + self.show_points() + self.points_changed() + if self.AUTO_RUN: + self.run() + + def points_changed(self) -> None: + pass + + def show_points(self) -> None: + if not self.points: + self.points_label.setText(tr("No points picked yet.")) + elif len(self.points) == 1: + self.points_label.setText(points_mod.pretty(*self.points[0])) + elif len(self.points) == 2: + self.points_label.setText("%s
%s" % ( + tr("Start: {point}").format(point=points_mod.pretty(*self.points[0])), + tr("End: {point}").format(point=points_mod.pretty(*self.points[1])))) + else: + self.points_label.setText(tr( + "{count} points · start {start}").format( + count=len(self.points), + start=points_mod.pretty(*self.points[0]))) + + def run(self) -> None: + pass + + def start(self, work, note: str = "") -> None: + def done(payload): + self._task = None + self.busy(False) + self.panel.update_cost_label() + self.accept(payload or {}) + + def failed(error): + self._task = None + self.busy(False) + self.panel.update_cost_label() + self.panel.complain(error) + + self.busy(True) + self.summary.setText("") + self.clear_result() + if note: + self.panel.say(note) + self._task = task.run(tr(self.TASK_TITLE), work, done, failed) + + def accept(self, payload: Dict[str, Any]) -> None: + pass + + def clear_result(self) -> None: + pass + + def busy(self, running: bool) -> None: + self.pick_button.setEnabled(not running) + self.cancel_button.setEnabled(running) + self.reset_button.setEnabled(not running) + for widget in self.controls(): + widget.setEnabled(not running) + if running: + self.keep_button.setEnabled(False) + + def controls(self) -> Sequence[QWidget]: + return () + + def cancel_task(self) -> None: + if self._task is not None: + self._task.cancel() + self._task = None + self.busy(False) + self.panel.say(tr("Cancelled.")) + + def reset(self) -> None: + self.stop_picking() + self.points = [] + self.payload = {} + self.summary.setText("") + self.keep_button.setEnabled(False) + self.clear_map() + self.forget() + self.show_points() + self.points_changed() + self.update_cost() + self.panel.say(tr("Points and result cleared.")) + + def forget(self) -> None: + pass + + def clear_map(self) -> None: + if self._marker is not None: + self._marker.hide() + if self._track is not None: + self._track.clear() + if self._dots is not None: + self._dots.clear() + if self._shapes is not None: + self._shapes.clear() + + def rows(self) -> List[results.Row]: + return [] + + def where(self) -> str: + if not self.points: + return "" + if len(self.points) == 1: + return points_mod.pretty(*self.points[0]) + return "%s → %s" % (points_mod.pretty(*self.points[0]), + points_mod.pretty(*self.points[-1])) + + def keep_as_layer(self) -> None: + rows = self.rows() + if not rows: + self.panel.say(tr("Nothing to keep yet."), Qgis.MessageLevel.Warning) + return + try: + created, counts, _without = layers.load_result( + results.collection(rows), results.metadata(self.payload), + tr(self.LAYER_TITLE), self.where(), + style_key=self.STYLE_KEY) + except GeoDonkeyError as exc: + self.panel.complain(exc) + return + if created and self.iface is not None: + self.iface.setActiveLayer(created[0]) + self.panel.say(tr("{count} features added as a layer.").format( + count=sum(counts.values()) if counts else len(rows)), + Qgis.MessageLevel.Success) + + def shutdown(self) -> None: + self.stop_picking() + if self._marker is not None: + self._marker.remove() + self._marker = None + if self._track is not None: + self._track.clear() + if self._dots is not None: + self._dots.remove() + self._dots = None + if self._shapes is not None: + self._shapes.remove() + self._shapes = None diff --git a/geodonkey/gui/panel.py b/geodonkey/gui/panel.py new file mode 100644 index 0000000..abdbe33 --- /dev/null +++ b/geodonkey/gui/panel.py @@ -0,0 +1,617 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Optional + +from qgis.PyQt.QtCore import QSize, Qt +from qgis.PyQt.QtWidgets import ( + QComboBox, + QFrame, + QHBoxLayout, + QLabel, + QLineEdit, + QListWidget, + QListWidgetItem, + QPlainTextEdit, + QPushButton, + QSpinBox, + QTabWidget, + QVBoxLayout, + QWidget, +) +from qgis.core import Qgis, QgsMessageLog, QgsProject, QgsVectorLayer, QgsWkbTypes +from qgis.gui import QgsDockWidget + +from .. import area as area_mod +from .. import auth, basemaps, config, geojson, layers, mapcontext, settings, task +from ..client import ApiClient, split_collection +from ..compat import icon, icon_path +from ..errors import GeoDonkeyError +from ..i18n import tr +from ..net import QgisTransport +from . import theme +from .settings_dialog import SettingsDialog +from .tools_tab import ToolsTab +from .upload_tab import UploadTab + +LOG_TAG = "GeoDonkey" + +AREA_CANVAS = 0 +AREA_LAYER_EXTENT = 1 +AREA_SELECTION_EXTENT = 2 +AREA_SELECTION_OUTLINE = 3 + +MODE_WORDS = 0 +MODE_TAGS = 1 +MODE_QUERY = 2 + + +class GeoDonkeyPanel(QgsDockWidget): + def __init__(self, iface, parent=None) -> None: + super().__init__(tr("GeoDonkey"), parent) + self.setObjectName("GeoDonkeyPanel") + self.setWindowIcon(icon("geodonkey.svg")) + self.iface = iface + self._task = None + self._styles: List[Dict[str, Any]] = basemaps.catalogue() + self._zoom = (config.TILE_MIN_ZOOM, config.TILE_MAX_ZOOM) + self._attribution = config.DEFAULT_ATTRIBUTION + self._pro = False + self._client = self.build_client() + + self.setWidget(self._build()) + self.refresh_styles_list() + self.update_account_labels() + self.update_cost_label() + + def build_client(self) -> ApiClient: + return ApiClient(transport=QgisTransport(), + base_url=settings.api_url(), + token=auth.load_token(), + language=self._language()) + + def api(self) -> ApiClient: + return self._client + + @staticmethod + def _language() -> str: + return settings.language() + + def _build(self) -> QWidget: + root = QWidget() + box = QVBoxLayout(root) + box.setContentsMargins(8, 8, 8, 8) + box.setSpacing(8) + box.addWidget(self._header()) + + self.tabs = QTabWidget() + self.tabs.setIconSize(QSize(22, 22)) + self.tabs.addTab(self._osm_tab(), icon("osm.svg"), tr("DonkeyOSM")) + self.tabs.addTab(self._basemap_tab(), icon("basemap.svg"), tr("Basemaps")) + self.tools = ToolsTab(self, self.iface) + self.tabs.addTab(self.tools, icon("tools.svg"), tr("Tools")) + self.upload = UploadTab(self, self.iface) + self.tabs.addTab(self.upload, icon("upload.svg"), tr("Upload")) + self.tabs.addTab(self._account_tab(), icon("account.svg"), tr("Account")) + for index in range(self.tabs.count()): + self.tabs.setTabToolTip(index, self.tabs.tabText(index)) + self.tabs.setTabText(index, "") + self.tabs.setDocumentMode(True) + box.addWidget(self.tabs, 1) + + self.status = QLabel("") + self.status.setWordWrap(True) + self.status.setStyleSheet(theme.note_style()) + box.addWidget(self.status) + return root + + def _header(self) -> QWidget: + frame = QFrame() + frame.setObjectName("gdHeader") + frame.setStyleSheet(theme.header_style()) + row = QHBoxLayout(frame) + row.setContentsMargins(10, 6, 10, 6) + row.setSpacing(9) + + mark = QLabel() + mark.setPixmap(icon("geodonkey.svg").pixmap(30, 30)) + row.addWidget(mark) + + column = QVBoxLayout() + column.setSpacing(0) + title = QLabel("GeoDonkey") + title.setObjectName("gdHeaderTitle") + claim = theme.ElidedLabel( + tr("OpenStreetMap data and map styles, straight into QGIS")) + claim.setObjectName("gdHeaderClaim") + column.addWidget(title) + column.addWidget(claim) + row.addLayout(column, 1) + return frame + + def _osm_tab(self) -> QWidget: + page = QWidget() + box = theme.page_box(page) + box.addWidget(theme.page_title(tr("DonkeyOSM"))) + + self.mode = QComboBox() + self.mode.addItem(tr("Search in plain language")) + self.mode.addItem(tr("Filter by OSM tags")) + self.mode.addItem(tr("Custom query")) + self.mode.currentIndexChanged.connect(self._mode_changed) + box.addWidget(theme.section(tr("What are you looking for?"))) + box.addWidget(self.mode) + + self.input_stack = theme.FittedStack() + + self.words = QLineEdit() + self.words.setPlaceholderText(tr("bakery, playground, drinking water…")) + self.words.returnPressed.connect(self.run_query) + self.input_stack.addWidget(self.words) + + self.tags = QLineEdit() + self.tags.setPlaceholderText("shop=bakery,amenity=cafe") + self.tags.returnPressed.connect(self.run_query) + self.input_stack.addWidget(self.tags) + + self.query = QPlainTextEdit() + self.query.setPlaceholderText( + "node way amenity=drinking_water\nnode amenity=fountain drinking_water=yes") + self.query.setMinimumHeight(90) + self.input_stack.addWidget(self.query) + + self._mode_hints = ( + tr("One or more everyday words. GeoDonkey translates them into OSM tags."), + tr("Up to {count} tags, separated by commas. All of them must match.").format( + count=config.MAX_TAGS), + tr("One line per selection: OR between lines, AND inside a line."), + ) + self.mode_hint = QLabel("") + self.mode_hint.setWordWrap(True) + self.mode_hint.setStyleSheet(theme.note_style()) + theme.small(self.mode_hint) + + entry = QVBoxLayout() + entry.setSpacing(theme.TIGHT) + entry.addWidget(self.input_stack) + entry.addWidget(self.mode_hint) + box.addLayout(entry) + + box.addWidget(self._separator()) + box.addWidget(theme.section(tr("Where?"))) + + self.area_source = QComboBox() + self.area_source.addItem(tr("Current map view")) + self.area_source.addItem(tr("Extent of a layer")) + self.area_source.addItem(tr("Extent of the selected features")) + self.area_source.addItem(tr("Outline of the selected polygons")) + self.area_source.currentIndexChanged.connect(self._area_changed) + box.addWidget(self.area_source) + + self.area_layer = theme.LayerBox(refill=self.reload_layers) + self.area_layer.setVisible(False) + box.addWidget(self.area_layer) + + self.area_note = QLabel("") + self.area_note.setWordWrap(True) + theme.small(self.area_note) + self.area_note.setStyleSheet(theme.note_style()) + box.addWidget(self.area_note) + + row = QHBoxLayout() + row.addWidget(QLabel(tr("Maximum objects"))) + self.limit = QSpinBox() + self.limit.setRange(1, config.OSM_LIMIT_PRO) + self.limit.setValue(int(settings.get("limit"))) + self.limit.setSingleStep(10) + row.addWidget(self.limit) + row.addStretch(1) + box.addLayout(row) + + box.addWidget(self._separator()) + + self.cost = QLabel("") + self.cost.setWordWrap(True) + self.cost.setStyleSheet(theme.note_style()) + box.addWidget(self.cost) + + buttons = QHBoxLayout() + self.run_button = QPushButton(tr("Run query")) + self.run_button.setStyleSheet(theme.primary_button_style()) + self.run_button.clicked.connect(self.run_query) + self.cancel_button = QPushButton(tr("Cancel")) + self.cancel_button.setEnabled(False) + self.cancel_button.clicked.connect(self.cancel_task) + buttons.addWidget(self.run_button, 1) + buttons.addWidget(self.cancel_button) + box.addLayout(buttons) + + box.addStretch(1) + self._mode_changed(MODE_WORDS) + self._area_changed(AREA_CANVAS) + return page + + def _basemap_tab(self) -> QWidget: + page = QWidget() + box = theme.page_box(page) + box.addWidget(theme.page_title(tr("Basemaps"))) + self.style_list = QListWidget() + self.style_list.setAlternatingRowColors(True) + self.style_list.itemDoubleClicked.connect(lambda _item: self.add_basemap()) + box.addWidget(self.style_list, 1) + + self.style_note = QLabel(tr("Free of charge and without an API key.")) + self.style_note.setWordWrap(True) + self.style_note.setStyleSheet(theme.note_style()) + theme.small(self.style_note) + box.addWidget(self.style_note) + + self.basemap_button = QPushButton(tr("Add as basemap")) + self.basemap_button.setStyleSheet(theme.primary_button_style()) + self.basemap_button.clicked.connect(self.add_basemap) + box.addWidget(self.basemap_button) + + refresh = QPushButton(tr("Reload style list")) + refresh.clicked.connect(self.fetch_styles) + box.addWidget(refresh) + return page + + def _account_tab(self) -> QWidget: + page = QWidget() + box = theme.page_box(page) + box.addWidget(theme.page_title(tr("Account"))) + + box.addWidget(theme.section(tr("API key"))) + self.token_label = QLabel("") + self.token_label.setWordWrap(True) + box.addWidget(self.token_label) + + key_button = QPushButton(tr("API key and settings…")) + key_button.clicked.connect(self.open_settings) + box.addWidget(key_button) + + link = QLabel('%s' % ( + config.TOKEN_URL, theme.link_style(), + tr("Manage keys on geodonkey.com"))) + link.setOpenExternalLinks(True) + link.setWordWrap(True) + theme.small(link) + box.addWidget(link) + + box.addWidget(self._separator()) + + box.addWidget(theme.section(tr("Plan and balance"))) + self.account_label = QLabel(tr("Not checked yet.")) + self.account_label.setWordWrap(True) + self.account_label.setTextFormat(Qt.TextFormat.RichText) + box.addWidget(self.account_label) + + check = QPushButton(tr("Check account")) + check.setStyleSheet(theme.primary_button_style()) + check.clicked.connect(self.check_account) + box.addWidget(check) + + box.addStretch(1) + return page + + @staticmethod + def _separator() -> QFrame: + return theme.rule() + + def _mode_changed(self, index: int) -> None: + self.input_stack.setCurrentIndex(index) + if 0 <= index < len(self._mode_hints): + self.mode_hint.setText(self._mode_hints[index]) + self.update_cost_label() + + def _area_changed(self, index: int) -> None: + needs_layer = index != AREA_CANVAS + self.area_layer.setVisible(needs_layer) + if needs_layer: + self.reload_layers() + self.update_area_note() + + def reload_layers(self) -> None: + wanted_outline = self.area_source.currentIndex() == AREA_SELECTION_OUTLINE + current = self.area_layer.currentData() + self.area_layer.clear() + pool = (mapcontext.polygon_layers() if wanted_outline + else mapcontext.vector_layers()) + for layer in pool: + self.area_layer.addItem(layer.name(), layer.id()) + if current: + index = self.area_layer.findData(current) + if index >= 0: + self.area_layer.setCurrentIndex(index) + if not pool: + self.area_layer.addItem( + tr("No polygon layer in the project") if wanted_outline + else tr("No vector layer in the project"), None) + + def selected_layer(self) -> Optional[QgsVectorLayer]: + layer_id = self.area_layer.currentData() + if not layer_id: + return None + layer = QgsProject.instance().mapLayer(layer_id) + return layer if isinstance(layer, QgsVectorLayer) else None + + def current_area(self) -> Dict[str, str]: + choice = self.area_source.currentIndex() + if choice == AREA_CANVAS: + return mapcontext.canvas_bbox(self.iface.mapCanvas()) + layer = self.selected_layer() + if layer is None: + raise GeoDonkeyError(tr("Pick a layer for the area first.")) + if choice == AREA_LAYER_EXTENT: + return mapcontext.layer_bbox(layer) + if choice == AREA_SELECTION_EXTENT: + return mapcontext.layer_bbox(layer, selected_only=True) + return mapcontext.selection_polygon(layer) + + def update_area_note(self) -> None: + try: + self.area_note.setText(area_mod.describe(self.current_area())) + self.area_note.setStyleSheet(theme.note_style()) + except GeoDonkeyError as exc: + self.area_note.setText(exc.message) + self.area_note.setStyleSheet(theme.warn_style()) + except Exception as exc: + self.area_note.setText(str(exc)) + self.area_note.setStyleSheet(theme.warn_style()) + + def update_cost_label(self) -> None: + price = config.COIN_COSTS.get("osm", 0) + parts = [tr("This query costs {coins} DC.").format(coins=price)] + usage = self._client.usage + if usage.free_remaining is not None: + parts.append(tr("{left} of {total} free calls left this hour.").format( + left=usage.free_remaining, + total=usage.free_limit or config.FREE_CALLS_PER_HOUR)) + if usage.balance is not None: + parts.append(tr("Balance: {coins} DC.").format(coins=usage.balance)) + elif not self._client.token: + parts.append(tr("Without an API key only the hourly free calls are available.")) + self.cost.setText(" ".join(parts)) + + def update_account_labels(self) -> None: + token = self._client.token + if token: + self.token_label.setText(tr("API key: {key}").format(key=auth.masked(token))) + else: + self.token_label.setText(tr("No API key stored.")) + self.token_label.setStyleSheet(theme.note_style() if token else theme.warn_style()) + + def refresh_styles_list(self) -> None: + self.style_list.clear() + current = settings.get("style") + for style in self._styles: + label = style["name"] + if style.get("temporary"): + label += " " + tr("(temporary)") + item = QListWidgetItem(label) + item.setIcon(self._swatch_icon(style.get("swatch"))) + item.setData(Qt.ItemDataRole.UserRole, style["id"]) + self.style_list.addItem(item) + if style["id"] == current: + self.style_list.setCurrentItem(item) + if self.style_list.currentRow() < 0 and self.style_list.count(): + self.style_list.setCurrentRow(0) + self.style_note.setText("%s · %s" % ( + tr("Free of charge and without an API key."), self._attribution)) + + @staticmethod + def _swatch_icon(colors): + from qgis.PyQt.QtGui import QIcon + + return QIcon(theme.swatch(colors)) + + def say(self, text: str, level=Qgis.MessageLevel.Info, duration: int = 6) -> None: + self.status.setText(text) + self.status.setStyleSheet( + theme.error_style() if level == Qgis.MessageLevel.Critical + else theme.warn_style() if level == Qgis.MessageLevel.Warning + else theme.good_style() if level == Qgis.MessageLevel.Success + else theme.note_style()) + if self.iface is not None: + self.iface.messageBar().pushMessage( + "GeoDonkey", text, level=level, duration=duration) + + def complain(self, error: GeoDonkeyError) -> None: + self.say(error.message, Qgis.MessageLevel.Critical, duration=10) + if error.detail: + QgsMessageLog.logMessage(error.detail, LOG_TAG, Qgis.MessageLevel.Warning) + + def busy(self, running: bool) -> None: + self.run_button.setEnabled(not running) + self.cancel_button.setEnabled(running) + + def cancel_task(self) -> None: + if self._task is not None: + self._task.cancel() + self._task = None + self.busy(False) + self.say(tr("Cancelled.")) + + def reload_client(self) -> None: + usage = self._client.usage + self._client = self.build_client() + self._client.usage = usage + self.update_account_labels() + self.update_cost_label() + self.upload.update_link() + + def open_settings(self) -> None: + dialog = SettingsDialog(self) + if dialog.exec() if hasattr(dialog, "exec") else dialog.exec_(): + self.reload_client() + self.say(tr("Settings saved."), Qgis.MessageLevel.Success) + + def check_account(self) -> None: + if not self._client.token: + self.say(tr("Store an API key first."), Qgis.MessageLevel.Warning) + return + client = self._client + self.busy(True) + self.account_label.setText(tr("Checking…")) + + def work(feedback): + return client.account(feedback=feedback) + + def done(data): + self.busy(False) + self._task = None + self.account_label.setText( + "%s
%s
%s
%s" % ( + data.get("email") or tr("unknown account"), + tr("Plan: {plan}").format(plan=data.get("tier") or data.get("plan") or "–"), + tr("Balance: {coins} DC").format(coins=data.get("coins")), + tr("Rate limit: {hour} per hour").format( + hour=data.get("rate_limit_per_hour") or "–"))) + self._pro = bool(data.get("pro")) + if self._pro: + self.limit.setMaximum(config.OSM_LIMIT_PRO) + else: + self.limit.setMaximum(config.OSM_LIMIT_DEFAULT) + self.upload.refresh_limits() + self.update_cost_label() + self.say(tr("API key is valid."), Qgis.MessageLevel.Success) + + def failed(error): + self.busy(False) + self._task = None + self.account_label.setText(error.message) + self.complain(error) + + self._task = task.run(tr("GeoDonkey: checking account"), work, done, failed) + + def fetch_styles(self) -> None: + client = self._client + + def work(feedback): + return {"styles": client.map_styles(feedback=feedback), + "tiles": client.tilejson(feedback=feedback)} + + def done(data): + self._task = None + self._styles = basemaps.catalogue(data["styles"]) + self._zoom = basemaps.zoom_range(data["tiles"]) + self._attribution = (data["styles"].get("attribution_text") + or data["tiles"].get("attribution") + or config.DEFAULT_ATTRIBUTION) + self.refresh_styles_list() + self.say(tr("{count} map styles available.").format(count=len(self._styles)), + Qgis.MessageLevel.Success) + + def failed(error): + self._task = None + self.complain(error) + + self._task = task.run(tr("GeoDonkey: loading map styles"), work, done, failed) + + def add_basemap(self) -> None: + item = self.style_list.currentItem() + if item is None: + self.say(tr("Pick a map style first."), Qgis.MessageLevel.Warning) + return + style_id = item.data(Qt.ItemDataRole.UserRole) + style = next((s for s in self._styles if s["id"] == style_id), None) + if style is None: + return + try: + basemaps.add_basemap(settings.api_url(), style, + zmin=self._zoom[0], zmax=self._zoom[1], + attribution=self._attribution) + except GeoDonkeyError as exc: + self.complain(exc) + return + settings.set("style", style_id) + self.say(tr("Basemap “{name}” added.").format(name=style["name"]), + Qgis.MessageLevel.Success) + + def run_query(self) -> None: + try: + area = self.current_area() + except GeoDonkeyError as exc: + self.complain(exc) + return + + mode = self.mode.currentIndex() + limit = int(self.limit.value()) + client = self._client + if mode == MODE_WORDS: + text = self.words.text().strip() + title = text + elif mode == MODE_TAGS: + text = self.tags.text().strip() + title = text + else: + text = self.query.toPlainText().strip() + title = tr("Custom query") + if not text: + self.say(tr("Enter a search term first."), Qgis.MessageLevel.Warning) + return + + settings.set("limit", limit) + settings.set("mode", ("words", "tags", "query")[mode]) + area_text = area_mod.describe(area) + + def work(feedback): + if mode == MODE_WORDS: + return client.osm_search(area, words=text, limit=limit, feedback=feedback) + if mode == MODE_TAGS: + return client.osm_search(area, tags=text, limit=limit, feedback=feedback) + return client.osm_query(text, area, limit=limit, feedback=feedback) + + def done(payload): + self.busy(False) + self._task = None + self.update_cost_label() + collection, meta = split_collection(payload) + if not collection["features"]: + self.say(tr("No objects found in that area."), Qgis.MessageLevel.Warning) + return + try: + created, counts, without = layers.load_result( + collection, meta, title, area_text) + except GeoDonkeyError as exc: + self.complain(exc) + return + summary = geojson.result_summary(meta, counts, without) + level = (Qgis.MessageLevel.Warning if meta.get("truncated") + else Qgis.MessageLevel.Success) + self.say(summary, level) + if created: + self.iface.setActiveLayer(created[0]) + + def failed(error): + self.busy(False) + self._task = None + self.update_cost_label() + self.complain(error) + + self.busy(True) + self.say(tr("Querying DonkeyOSM…")) + self._task = task.run(tr("GeoDonkey: DonkeyOSM query"), work, done, failed) + + def showEvent(self, event): # noqa: N802 + super().showEvent(event) + if self.area_layer.isVisible(): + self.reload_layers() + self.update_area_note() + + def hideEvent(self, event): # noqa: N802 + super().hideEvent(event) + tools = getattr(self, "tools", None) + if tools is not None: + tools.shutdown() + + +def geometry_label(layer: QgsVectorLayer) -> str: + kinds = { + QgsWkbTypes.GeometryType.PointGeometry: tr("points"), + QgsWkbTypes.GeometryType.LineGeometry: tr("lines"), + QgsWkbTypes.GeometryType.PolygonGeometry: tr("areas"), + } + return kinds.get(QgsWkbTypes.geometryType(layer.wkbType()), tr("objects")) + + +__all__ = ["GeoDonkeyPanel", "icon_path"] diff --git a/geodonkey/gui/pick.py b/geodonkey/gui/pick.py new file mode 100644 index 0000000..da220df --- /dev/null +++ b/geodonkey/gui/pick.py @@ -0,0 +1,259 @@ +from __future__ import annotations + +from typing import List, Optional, Sequence, Tuple + +from qgis.PyQt.QtCore import Qt, pyqtSignal +from qgis.PyQt.QtGui import QColor +from qgis.core import QgsPointXY, QgsWkbTypes +from qgis.gui import QgsMapTool, QgsRubberBand, QgsVertexMarker + +from .. import mapcontext, style +from ..config import BRAND + + +def _colour(value: Optional[str]) -> QColor: + colour = QColor(value or "") + return colour if colour.isValid() else QColor(style.HOUSE) + + +class PointPicker(QgsMapTool): + picked = pyqtSignal(list) + progress = pyqtSignal(int, int) + cancelled = pyqtSignal() + + def __init__(self, canvas, wanted: int = 2, free: bool = False, + least: int = 2, line: bool = True) -> None: + super().__init__(canvas) + self.canvas = canvas + self.wanted = max(1, int(wanted)) + self.free = bool(free) + self.least = max(1, int(least)) + self.line = bool(line) + + self._points: List[QgsPointXY] = [] + self._markers: List[QgsVertexMarker] = [] + + self._band: Optional[QgsRubberBand] = None + self._ghost: Optional[QgsRubberBand] = None + if self.line: + self._band = QgsRubberBand(canvas, QgsWkbTypes.GeometryType.LineGeometry) + self._band.setColor(QColor(BRAND["green_deep"])) + self._band.setWidth(3) + self._ghost = QgsRubberBand(canvas, QgsWkbTypes.GeometryType.LineGeometry) + self._ghost.setColor(QColor(BRAND["green_deep"])) + self._ghost.setWidth(1) + self._ghost.setLineStyle(Qt.PenStyle.DashLine) + + self.setCursor(Qt.CursorShape.CrossCursor) + + def reset(self) -> None: + self._points = [] + markers, self._markers = self._markers, [] + try: + for band in (self._band, self._ghost): + if band is not None: + band.reset(QgsWkbTypes.GeometryType.LineGeometry) + scene = self.canvas.scene() + for marker in markers: + scene.removeItem(marker) + except RuntimeError: + pass + + def points(self) -> List[QgsPointXY]: + return list(self._points) + + def wgs84_points(self) -> List[Tuple[float, float]]: + crs = self.canvas.mapSettings().destinationCrs() + return [mapcontext.point_to_wgs84(point, crs) for point in self._points] + + def canvasReleaseEvent(self, event): # noqa: N802 + if event.button() == Qt.MouseButton.RightButton: + if self.free and len(self._points) >= self.least: + self._finish() + else: + self._abort() + return + + point = self.toMapCoordinates(event.pos()) + self._points.append(point) + self._mark(point) + if self._band is not None: + self._band.addPoint(point, True) + + left = 0 if self.free else self.wanted - len(self._points) + self.progress.emit(len(self._points), max(0, left)) + + if len(self._points) >= self.wanted: + self._finish() + + def canvasMoveEvent(self, event): # noqa: N802 + if self._ghost is None or not self._points: + return + self._ghost.reset(QgsWkbTypes.GeometryType.LineGeometry) + self._ghost.addPoint(self._points[-1], False) + self._ghost.addPoint(self.toMapCoordinates(event.pos()), True) + + def keyPressEvent(self, event): # noqa: N802 + if event.key() == Qt.Key.Key_Escape: + self._abort() + elif event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter): + if self.free and len(self._points) >= self.least: + self._finish() + + def deactivate(self): # noqa: N802 + self.reset() + super().deactivate() + self.cancelled.emit() + + def _mark(self, point: QgsPointXY) -> None: + marker = QgsVertexMarker(self.canvas) + marker.setCenter(point) + marker.setIconType(QgsVertexMarker.IconType.ICON_CIRCLE) + marker.setIconSize(11) + marker.setPenWidth(3) + marker.setColor(QColor(BRAND["green_deep"])) + marker.setFillColor(QColor(BRAND["navy"])) + self._markers.append(marker) + + def _finish(self) -> None: + out = self.wgs84_points() + if self._ghost is not None: + self._ghost.reset(QgsWkbTypes.GeometryType.LineGeometry) + self.picked.emit(out) + + def _abort(self) -> None: + self.reset() + self.cancelled.emit() + + +class Marker(object): + def __init__(self, canvas) -> None: + self.canvas = canvas + self._marker = None + + def show(self, lon: float, lat: float) -> None: + crs = self.canvas.mapSettings().destinationCrs() + point = mapcontext.point_from_wgs84(lon, lat, crs) + if point is None: + return self.hide() + if self._marker is None: + self._marker = QgsVertexMarker(self.canvas) + self._marker.setIconType(QgsVertexMarker.IconType.ICON_CROSS) + self._marker.setIconSize(16) + self._marker.setPenWidth(3) + self._marker.setColor(QColor(BRAND["error"])) + self._marker.setCenter(point) + self._marker.show() + + def hide(self) -> None: + if self._marker is not None: + self._marker.hide() + + def remove(self) -> None: + if self._marker is not None: + self.canvas.scene().removeItem(self._marker) + self._marker = None + + +class Dots(object): + def __init__(self, canvas) -> None: + self.canvas = canvas + self._markers: List[QgsVertexMarker] = [] + + def show(self, coordinates: Sequence[Tuple[float, float]]) -> None: + crs = self.canvas.mapSettings().destinationCrs() + self.clear() + for lon, lat in coordinates: + point = mapcontext.point_from_wgs84(lon, lat, crs) + if point is None: + continue + marker = QgsVertexMarker(self.canvas) + marker.setCenter(point) + marker.setIconType(QgsVertexMarker.IconType.ICON_CIRCLE) + marker.setIconSize(11) + marker.setPenWidth(3) + marker.setColor(QColor(BRAND["green_deep"])) + marker.setFillColor(QColor(BRAND["navy"])) + self._markers.append(marker) + + def clear(self) -> None: + markers, self._markers = self._markers, [] + try: + scene = self.canvas.scene() + for marker in markers: + scene.removeItem(marker) + except RuntimeError: + pass + + def remove(self) -> None: + self.clear() + + +class Shapes(object): + def __init__(self, canvas) -> None: + self.canvas = canvas + self._bands = {} + + def _band(self, kind, colour: QColor): + key = (kind, colour.name()) + band = self._bands.get(key) + if band is not None: + return band + + band = QgsRubberBand(self.canvas, kind) + band.setColor(colour) + if kind == QgsWkbTypes.GeometryType.PolygonGeometry: + fill = QColor(colour) + fill.setAlphaF(style.AREA_OPACITY) + band.setFillColor(fill) + band.setStrokeColor(colour) + band.setWidth(int(round(style.AREA_OUTLINE))) + else: + band.setWidth(int(round(style.LINE_WIDTH))) + self._bands[key] = band + return band + + def show(self, shapes: Sequence[Tuple[object, Optional[str]]]) -> None: + crs = self.canvas.mapSettings().destinationCrs() + self.clear() + for shape, color in shapes: + geometry = mapcontext.geometry_from_wgs84(shape, crs) + if geometry is None: + continue + kind = geometry.type() + if kind == QgsWkbTypes.GeometryType.PointGeometry: + continue + self._band(kind, _colour(color)).addGeometry(geometry, None) + + def clear(self) -> None: + bands, self._bands = self._bands, {} + try: + scene = self.canvas.scene() + for band in bands.values(): + scene.removeItem(band) + except RuntimeError: + pass + + def remove(self) -> None: + self.clear() + + +class Track(object): + def __init__(self, canvas) -> None: + self.canvas = canvas + self._band = QgsRubberBand(canvas, QgsWkbTypes.GeometryType.LineGeometry) + self._band.setColor(QColor(BRAND["navy"])) + self._band.setWidth(2) + + def show(self, coordinates: Sequence[Tuple[float, float]]) -> None: + crs = self.canvas.mapSettings().destinationCrs() + self._band.reset(QgsWkbTypes.GeometryType.LineGeometry) + for lon, lat in coordinates: + point = mapcontext.point_from_wgs84(lon, lat, crs) + if point is not None: + self._band.addPoint(point, False) + self._band.updatePosition() + self._band.show() + + def clear(self) -> None: + self._band.reset(QgsWkbTypes.GeometryType.LineGeometry) diff --git a/geodonkey/gui/settings_dialog.py b/geodonkey/gui/settings_dialog.py new file mode 100644 index 0000000..7fadd65 --- /dev/null +++ b/geodonkey/gui/settings_dialog.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +from qgis.PyQt.QtCore import Qt +from qgis.PyQt.QtGui import QCursor +from qgis.PyQt.QtWidgets import ( + QApplication, + QCheckBox, + QDialog, + QDialogButtonBox, + QFormLayout, + QHBoxLayout, + QLabel, + QLineEdit, + QMessageBox, + QPushButton, + QSpinBox, + QVBoxLayout, +) + +from .. import auth, config, settings +from ..client import ApiClient +from ..compat import icon +from ..errors import GeoDonkeyError +from ..i18n import tr +from ..net import QgisTransport +from . import theme + + +class SettingsDialog(QDialog): + def __init__(self, parent=None) -> None: + super().__init__(parent) + self.setWindowTitle(tr("GeoDonkey settings")) + self.setWindowIcon(icon("geodonkey.svg")) + self.setMinimumWidth(460) + self._build() + self._load() + + def _build(self) -> None: + box = QVBoxLayout(self) + box.setSpacing(8) + + intro = QLabel( + tr("An API key unlocks DonkeyOSM queries. The map styles work without one.") + + ' %s' % (config.TOKEN_URL, tr("Get a key"))) + intro.setOpenExternalLinks(True) + intro.setWordWrap(True) + box.addWidget(intro) + + form = QFormLayout() + form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) + + self.token = QLineEdit() + self.token.setEchoMode(QLineEdit.EchoMode.Password) + self.token.setPlaceholderText("gd_live_…") + self.token.textChanged.connect(self._token_changed) + + show = QCheckBox(tr("Show")) + show.toggled.connect( + lambda on: self.token.setEchoMode( + QLineEdit.EchoMode.Normal if on else QLineEdit.EchoMode.Password)) + + key_row = QHBoxLayout() + key_row.addWidget(self.token, 1) + key_row.addWidget(show) + form.addRow(tr("API key"), key_row) + + self.api_url = QLineEdit() + self.api_url.setPlaceholderText(config.DEFAULT_API_URL) + form.addRow(tr("API address"), self.api_url) + + self.limit = QSpinBox() + self.limit.setRange(1, config.OSM_LIMIT_PRO) + self.limit.setSingleStep(10) + form.addRow(tr("Default maximum objects"), self.limit) + + box.addLayout(form) + + buttons = QHBoxLayout() + self.test_button = QPushButton(tr("Test key")) + self.test_button.setStyleSheet(theme.primary_button_style()) + self.test_button.clicked.connect(self.test_token) + self.forget_button = QPushButton(tr("Remove key")) + self.forget_button.clicked.connect(self.forget_token) + buttons.addWidget(self.test_button) + buttons.addWidget(self.forget_button) + buttons.addStretch(1) + box.addLayout(buttons) + + self.note = QLabel("") + self.note.setWordWrap(True) + self.note.setStyleSheet(theme.note_style()) + box.addWidget(self.note) + + self.storage_note = QLabel("") + self.storage_note.setWordWrap(True) + self.storage_note.setStyleSheet(theme.note_style()) + theme.small(self.storage_note) + box.addWidget(self.storage_note) + + standard = QDialogButtonBox( + QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) + standard.accepted.connect(self.accept) + standard.rejected.connect(self.reject) + box.addWidget(standard) + + def _load(self) -> None: + self.token.setText(auth.load_token()) + self.api_url.setText(settings.api_url()) + self.limit.setValue(int(settings.get("limit"))) + if auth.available(): + self.storage_note.setText( + tr("The key is stored encrypted in the QGIS authentication database.")) + else: + self.storage_note.setText( + tr("The QGIS authentication database is locked or unavailable. " + "The key will only be kept until QGIS is closed – it is never " + "written in plain text.")) + self.storage_note.setStyleSheet(theme.warn_style()) + + def _token_changed(self, text: str) -> None: + text = (text or "").strip() + if not text: + self.note.setText("") + return + if not auth.looks_like_token(text): + self.note.setText( + tr("That does not look like a GeoDonkey key. Keys start with {prefixes}.") + .format(prefixes=" or ".join(config.TOKEN_PREFIXES))) + self.note.setStyleSheet(theme.warn_style()) + return + self.note.setText("") + self.note.setStyleSheet(theme.note_style()) + + def test_token(self) -> None: + token = self.token.text().strip() + if not token: + self.note.setText(tr("Enter a key first.")) + self.note.setStyleSheet(theme.warn_style()) + return + client = ApiClient(transport=QgisTransport(), + base_url=str(self.api_url.text() or config.DEFAULT_API_URL), + token=token) + QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) + self.test_button.setEnabled(False) + try: + data = client.account() + except GeoDonkeyError as exc: + self.note.setText(exc.message) + self.note.setStyleSheet(theme.error_style()) + return + finally: + self.test_button.setEnabled(True) + QApplication.restoreOverrideCursor() + + self.note.setText(tr("Key works · {email} · {tier} · {coins} DC").format( + email=data.get("email") or "–", + tier=data.get("tier") or data.get("plan") or "–", + coins=data.get("coins"))) + self.note.setStyleSheet(theme.good_style()) + if data.get("pro"): + self.limit.setMaximum(config.OSM_LIMIT_PRO) + + def forget_token(self) -> None: + auth.forget() + self.token.clear() + self.note.setText(tr("Key removed.")) + self.note.setStyleSheet(theme.note_style()) + + def accept(self) -> None: + settings.set("api_url", str(self.api_url.text() or config.DEFAULT_API_URL).rstrip("/")) + settings.set("limit", int(self.limit.value())) + + token = self.token.text().strip() + if not token: + auth.forget() + super().accept() + return + + try: + auth.save_token(token) + except auth.AuthUnavailable: + auth.remember_for_session(token) + QMessageBox.warning( + self, tr("GeoDonkey"), + tr("The key could not be stored in the QGIS authentication database.\n\n" + "It will be used for this session and is forgotten when QGIS closes. " + "GeoDonkey never writes the key to disk in plain text.\n\n" + "To keep it permanently, set a master password under " + "Settings ▸ Options ▸ Authentication.")) + super().accept() diff --git a/geodonkey/gui/theme.py b/geodonkey/gui/theme.py new file mode 100644 index 0000000..e4d5649 --- /dev/null +++ b/geodonkey/gui/theme.py @@ -0,0 +1,274 @@ +from __future__ import annotations + +from typing import Optional + +from qgis.PyQt.QtCore import QSize, Qt +from qgis.PyQt.QtGui import QColor, QFont, QFontMetrics, QPainter, QPixmap +from qgis.PyQt.QtWidgets import ( + QComboBox, + QFrame, + QLabel, + QSizePolicy, + QStackedWidget, + QVBoxLayout, +) + +from ..config import BRAND + + +PAGE_TOP = 10 + +GAP = 7 + +TIGHT = 3 + + +DARK_THEMES = {"night mapping", "nightmapping"} + + +def night() -> bool: + themed: Optional[bool] = None + try: + from qgis.core import QgsApplication + + themed = str(QgsApplication.themeName() or "").strip().lower() in DARK_THEMES + except Exception: + themed = None + if themed: + return True + try: + from qgis.PyQt.QtWidgets import QApplication + + palette = QApplication.palette() + if palette is None: + return False + return palette.window().color().lightness() < 128 + except Exception: + return False + + +def colours() -> dict: + if night(): + return { + "surface": BRAND["tint_night"], + "surface_line": BRAND["tint_line_night"], + "title": "#ffffff", + "claim": BRAND["muted_night"], + "note": BRAND["muted_night"], + "warn": BRAND["warn_night"], + "error": BRAND["error_night"], + "good": BRAND["good_night"], + "line": BRAND["tint_line_night"], + "off_bg": BRAND["tint_line_night"], + "off_fg": "#8d9cb5", + "chart_bg": "#101a2e", + "chart_grid": BRAND["tint_line_night"], + "chart_text": "#e8eefb", + "chart_muted": BRAND["muted_night"], + "chart_terrain": BRAND["green"], + "link": BRAND["green"], + } + return { + "surface": BRAND["tint"], + "surface_line": BRAND["tint_line"], + "title": BRAND["navy"], + "claim": BRAND["muted"], + "note": BRAND["muted"], + "warn": BRAND["warn"], + "error": BRAND["error"], + "good": BRAND["good"], + "line": BRAND["line"], + "off_bg": BRAND["tint_line"], + "off_fg": "#8a99b3", + "chart_bg": BRAND["paper"], + "chart_grid": BRAND["line"], + "chart_text": BRAND["ink"], + "chart_muted": BRAND["muted"], + "chart_terrain": BRAND["green_deep"], + "link": BRAND["navy"], + } + + +def header_style() -> str: + values = dict(BRAND, **colours()) + return """ +QFrame#gdHeader { + background-color: %(surface)s; + border: 1px solid %(surface_line)s; + border-left: 4px solid %(green)s; + border-radius: 8px; +} +QLabel#gdHeaderTitle { + color: %(title)s; + font-weight: 700; + font-size: 13pt; +} +QLabel#gdHeaderClaim { + color: %(claim)s; + font-size: 9pt; +} +""" % values + + +def primary_button_style() -> str: + values = dict(BRAND, **colours()) + return """ +QPushButton { + background-color: %(green)s; + color: %(navy)s; + border: 1px solid %(green_dark)s; + border-radius: 4px; + padding: 6px 14px; + font-weight: 600; +} +QPushButton:hover { background-color: %(green_dark)s; border-color: %(green_dark)s; } +QPushButton:pressed { background-color: %(green_deep)s; border-color: %(green_deep)s; } +QPushButton:disabled { background-color: %(off_bg)s; border-color: %(off_bg)s; color: %(off_fg)s; } +""" % values + + +def note_style() -> str: + return "color: %(note)s;" % colours() + + +def link_style() -> str: + return "color: %(link)s;" % colours() + + +def page_title_style() -> str: + return "color: %(title)s; font-weight: 700; font-size: 11pt;" % colours() + + +def section_style() -> str: + return "color: %(title)s; font-weight: 600;" % colours() + + +def page_title(text: str) -> QLabel: + label = QLabel(text) + label.setStyleSheet(page_title_style()) + return label + + +def section(text: str) -> QLabel: + label = QLabel(text) + label.setWordWrap(True) + label.setStyleSheet(section_style()) + return label + + +def rule() -> QFrame: + line = QFrame() + line.setFrameShape(QFrame.Shape.HLine) + line.setFrameShadow(QFrame.Shadow.Plain) + line.setFixedHeight(1) + line.setStyleSheet("background-color: %(line)s; border: none;" % colours()) + return line + + +class LayerBox(QComboBox): + def __init__(self, refill=None, parent=None) -> None: + super().__init__(parent) + self.refill = refill + + def showPopup(self): # noqa: N802 + if self.refill is not None: + self.refill() + super().showPopup() + + +class ElidedLabel(QLabel): + def __init__(self, text: str = "", parent=None) -> None: + super().__init__(text, parent) + self._full = text + self.setToolTip(text) + self.setMinimumWidth(1) + self.setSizePolicy(QSizePolicy.Policy.Ignored, + QSizePolicy.Policy.Preferred) + + def full_text(self) -> str: + return self._full + + def setText(self, text: str) -> None: # noqa: N802 + self._full = text or "" + self.setToolTip(self._full) + self._shorten() + + def resizeEvent(self, event): # noqa: N802 + super().resizeEvent(event) + self._shorten() + + def _shorten(self) -> None: + metrics = QFontMetrics(self.font()) + QLabel.setText(self, metrics.elidedText( + self._full, Qt.TextElideMode.ElideRight, max(1, self.width()))) + + +class FittedStack(QStackedWidget): + def __init__(self, parent=None) -> None: + super().__init__(parent) + self.currentChanged.connect(lambda _index: self.updateGeometry()) + + def sizeHint(self) -> QSize: # noqa: N802 + page = self.currentWidget() + return page.sizeHint() if page is not None else super().sizeHint() + + def minimumSizeHint(self) -> QSize: # noqa: N802 + page = self.currentWidget() + if page is None: + return super().minimumSizeHint() + return page.minimumSizeHint().expandedTo(page.minimumSize()) + + def hasHeightForWidth(self) -> bool: # noqa: N802 + page = self.currentWidget() + return (page.hasHeightForWidth() if page is not None + else super().hasHeightForWidth()) + + def heightForWidth(self, width: int) -> int: # noqa: N802 + page = self.currentWidget() + return (page.heightForWidth(width) if page is not None + else super().heightForWidth(width)) + + +def page_box(widget) -> QVBoxLayout: + box = QVBoxLayout(widget) + box.setContentsMargins(0, PAGE_TOP, 0, 0) + box.setSpacing(GAP) + return box + + +def warn_style() -> str: + return "color: %(warn)s; font-weight: 600;" % colours() + + +def error_style() -> str: + return "color: %(error)s; font-weight: 600;" % colours() + + +def good_style() -> str: + return "color: %(good)s; font-weight: 600;" % colours() + + +def swatch(colors, size: int = 16) -> QPixmap: + values = [c for c in (colors or []) if isinstance(c, str) and c.startswith("#")] + if not values: + values = ["#cccccc"] + pixmap = QPixmap(QSize(size, size)) + pixmap.fill(Qt.GlobalColor.transparent) + painter = QPainter(pixmap) + try: + width = size / float(len(values)) + for index, value in enumerate(values): + painter.fillRect(int(index * width), 0, + int(width + 1), size, QColor(value)) + painter.setPen(QColor(colours()["line"])) + painter.drawRect(0, 0, size - 1, size - 1) + finally: + painter.end() + return pixmap + + +def small(widget, points: int = 8): + font = QFont(widget.font()) + font.setPointSize(max(6, widget.font().pointSize() - 1 if points is None else points)) + widget.setFont(font) + return widget diff --git a/geodonkey/gui/tools/__init__.py b/geodonkey/gui/tools/__init__.py new file mode 100644 index 0000000..b460601 --- /dev/null +++ b/geodonkey/gui/tools/__init__.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from .elevation import ElevationPage +from .isochrone import IsochronePage +from .profile import ProfilePage +from .route import RoutePage +from .sight import SightPage + +PAGES = ( + IsochronePage, + RoutePage, + ProfilePage, + ElevationPage, + SightPage, +) + +__all__ = ["PAGES", "ElevationPage", "IsochronePage", "ProfilePage", + "RoutePage", "SightPage"] diff --git a/geodonkey/gui/tools/elevation.py b/geodonkey/gui/tools/elevation.py new file mode 100644 index 0000000..033a172 --- /dev/null +++ b/geodonkey/gui/tools/elevation.py @@ -0,0 +1,301 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Tuple + +from qgis.PyQt.QtCore import Qt +from qgis.PyQt.QtGui import QKeySequence +from qgis.PyQt.QtWidgets import ( + QAbstractItemView, + QComboBox, + QHBoxLayout, + QHeaderView, + QPushButton, + QTableWidget, + QTableWidgetItem, + QVBoxLayout, + QWidget, +) +from qgis.core import Qgis, QgsProject + +from ... import config, mapcontext, points as points_mod, results +from ...compat import QAction +from ...i18n import later, tr +from .. import theme +from ..maptab import MapTab + +COL_X, COL_Y, COL_Z = 0, 1, 2 + +MAX_POINTS = 20 + + +class ElevationPage(MapTab): + ALGORITHM = "geodonkey:elevationpoints" + NAME = later("Point elevation") + ICON = "elevation.svg" + + WANTED = MAX_POINTS + FREE = True + LEAST = 1 + CONNECT = False + AUTO_RUN = False + PROMPTS = (later("Click a point on the map."), + later("Another point, or right-click to finish.")) + PICK_TEXT = later("Pick points on the map") + TASK_TITLE = later("GeoDonkey: point elevation") + LAYER_TITLE = later("Point elevation") + STYLE_KEY = "elevation" + + def setup(self) -> None: + self._coordinates: List[Tuple[float, float]] = [] + + def body(self) -> Optional[QWidget]: + holder = QWidget() + box = QVBoxLayout(holder) + box.setContentsMargins(0, 0, 0, 0) + box.setSpacing(theme.TIGHT) + + self.crs_box = QComboBox() + self.crs_box.addItem(tr("X/Y in WGS 84 · degrees")) + self.crs_box.addItem(tr("X/Y in the map CRS")) + self.crs_box.currentIndexChanged.connect(lambda _index: self.fill_places()) + box.addWidget(self.crs_box) + + self.table = QTableWidget(0, 3) + self.table.setHorizontalHeaderLabels([tr("X"), tr("Y"), tr("Z (m)")]) + self.table.setAlternatingRowColors(True) + self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) + self.table.setSelectionBehavior( + QAbstractItemView.SelectionBehavior.SelectRows) + self.table.setSelectionMode( + QAbstractItemView.SelectionMode.SingleSelection) + self.table.horizontalHeader().setSectionResizeMode( + QHeaderView.ResizeMode.Stretch) + self.table.verticalHeader().setDefaultSectionSize(20) + self.table.currentCellChanged.connect( + lambda row, _c, _pr, _pc: self._cell_changed(row)) + + self._remove_action = QAction(tr("Remove point"), self.table) + self._remove_action.setShortcut(QKeySequence.StandardKey.Delete) + self._remove_action.setShortcutContext( + Qt.ShortcutContext.WidgetShortcut) + self._remove_action.triggered.connect(self.remove_point) + self.table.addAction(self._remove_action) + self.table.setContextMenuPolicy( + Qt.ContextMenuPolicy.ActionsContextMenu) + box.addWidget(self.table, 1) + + row = QHBoxLayout() + row.setSpacing(theme.TIGHT) + + self.remove_button = QPushButton(tr("Remove point")) + self.remove_button.setToolTip(tr( + "Remove the selected point from the list. " + "A right-click on the row or the Delete key does the same.")) + self.remove_button.setEnabled(False) + self.remove_button.clicked.connect(self.remove_point) + row.addWidget(self.remove_button) + + self.lookup_button = QPushButton(tr("Look up elevations")) + self.lookup_button.setStyleSheet(theme.primary_button_style()) + self.lookup_button.setEnabled(False) + self.lookup_button.clicked.connect(self.run) + row.addWidget(self.lookup_button, 1) + box.addLayout(row) + return holder + + def controls(self): + return (self.crs_box,) + + def busy(self, running: bool) -> None: + super().busy(running) + self.lookup_button.setEnabled(not running and bool(self.points)) + + def show_points(self) -> None: + if len(self.points) < 2: + super().show_points() + return + self.points_label.setText(tr("{count} points picked.").format( + count=len(self.points))) + + def price(self) -> str: + return tr("{coins} DC per run · up to {limit} points").format( + coins=config.elevation_coins(MAX_POINTS, "elevation_points"), + limit=MAX_POINTS) + + def run(self) -> None: + if not self.points: + self.panel.say(tr("Pick at least one point on the map."), + Qgis.MessageLevel.Warning) + return + coordinates = list(self.points) + client = self.panel.api() + + def work(feedback): + return client.elevation_points(coordinates, feedback=feedback) + + self.start(work, tr("Looking up the elevations…")) + + def clear_result(self) -> None: + for row in range(self.table.rowCount()): + self._cell(row, COL_Z, "") + marker = self.marker() + if marker is not None: + marker.hide() + + def accept(self, payload: Dict[str, Any]) -> None: + self.payload = payload + rows = results.elevation_point_rows(self.payload, self.points) + self._coordinates = list(self.points) + self.fill_places() + if not rows: + self.keep_button.setEnabled(False) + self.panel.say(tr("The service returned no elevations."), + Qgis.MessageLevel.Warning) + return + + missing = 0 + for index, row in enumerate(rows): + attrs = row["attrs"] + height = attrs.get("elevation") + if height is None: + missing += 1 + self._cell(index, COL_Z, "–", tr("No elevation data here.")) + else: + self._cell(index, COL_Z, + points_mod.fmt(round(float(height), 1)), + attrs.get("ele_source") or "") + + self.keep_button.setEnabled(True) + self.summary.setText(self._span(rows)) + if missing: + self.panel.say(tr("{missing} of {count} points have no elevation " + "data.").format(missing=missing, count=len(rows)), + Qgis.MessageLevel.Warning) + else: + self.panel.say(tr("{count} elevation(s) found.").format( + count=len(rows)), Qgis.MessageLevel.Success) + + @staticmethod + def _span(rows) -> str: + heights = [row["attrs"]["elevation"] for row in rows + if row["attrs"].get("elevation") is not None] + if not heights: + return "" + if len(heights) == 1: + return tr("{height} m above sea level").format( + height=points_mod.fmt(round(float(heights[0]), 1))) + low, high = min(heights), max(heights) + return tr("{low} m to {high} m · {span} m difference").format( + low=points_mod.fmt(round(float(low), 1)), + high=points_mod.fmt(round(float(high), 1)), + span=points_mod.fmt(round(float(high) - float(low), 1))) + + def points_changed(self) -> None: + self.payload = {} + self._coordinates = list(self.points) + self.fill_places() + self.summary.setText("") + self.keep_button.setEnabled(False) + self.lookup_button.setEnabled(bool(self.points)) + dots = self.dots() + if dots is not None: + dots.show(self._coordinates) + self._selection_changed() + + def remove_point(self) -> None: + row = self.table.currentRow() + if row < 0 or row >= len(self.points): + return + + self._drop_from_payload(row) + self.points = [point for index, point in enumerate(self.points) + if index != row] + self._coordinates = list(self.points) + self.table.removeRow(row) + self.fill_places() + self.show_points() + + dots = self.dots() + if dots is not None: + dots.show(self._coordinates) + + rows = self.rows() if self.payload else [] + self.summary.setText(self._span(rows) if rows else "") + self.keep_button.setEnabled(bool(rows)) + self.lookup_button.setEnabled(bool(self.points)) + self._row_changed(self.table.currentRow()) + self._selection_changed() + self.panel.say(tr("Point removed.")) + + def _drop_from_payload(self, row: int) -> None: + if not isinstance(self.payload, dict): + return + places = self.payload.get("points") + if isinstance(places, list) and len(places) == len(self.points): + places.pop(row) + return + self.payload = {} + + def _selection_changed(self) -> None: + row = self.table.currentRow() + self.remove_button.setEnabled(0 <= row < len(self._coordinates)) + self._remove_action.setEnabled(self.remove_button.isEnabled()) + + def fill_places(self) -> None: + self._name_map_crs() + self.table.setRowCount(len(self._coordinates)) + for row, (lon, lat) in enumerate(self._coordinates): + x, y = self._place(lon, lat) + self._cell(row, COL_X, x) + self._cell(row, COL_Y, y) + if self.table.item(row, COL_Z) is None: + self._cell(row, COL_Z, "") + + def map_crs(self): + canvas = self.canvas() + if canvas is not None: + return canvas.mapSettings().destinationCrs() + return QgsProject.instance().crs() + + def _name_map_crs(self) -> None: + crs = self.map_crs() + code = crs.authid() if crs is not None and crs.isValid() else "" + self.crs_box.setItemText(1, tr("X/Y in {crs}").format(crs=code) + if code else tr("X/Y in the map CRS")) + + def _place(self, lon: float, lat: float) -> Tuple[str, str]: + if self.crs_box.currentIndex() == 0: + return ("%.5f" % lon, "%.5f" % lat) + crs = self.map_crs() + point = mapcontext.point_from_wgs84(lon, lat, crs) + if point is None: + return ("", "") + places = 5 if crs is not None and crs.isGeographic() else 2 + return ("%.*f" % (places, point.x()), "%.*f" % (places, point.y())) + + def _cell(self, row: int, column: int, text: str, tip: str = "") -> None: + item = self.table.item(row, column) + if item is None: + item = QTableWidgetItem() + item.setTextAlignment(Qt.AlignmentFlag.AlignRight + | Qt.AlignmentFlag.AlignVCenter) + self.table.setItem(row, column, item) + item.setText(text) + item.setToolTip(tip) + + def rows(self): + return results.elevation_point_rows(self.payload, self._coordinates) + + def _cell_changed(self, index: int) -> None: + self._row_changed(index) + self._selection_changed() + + def _row_changed(self, index: int) -> None: + marker = self.marker() + if marker is None: + return + if index < 0 or index >= len(self._coordinates): + marker.hide() + return + lon, lat = self._coordinates[index] + marker.show(lon, lat) diff --git a/geodonkey/gui/tools/isochrone.py b/geodonkey/gui/tools/isochrone.py new file mode 100644 index 0000000..f297061 --- /dev/null +++ b/geodonkey/gui/tools/isochrone.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +from typing import Any, Dict, Optional + +from qgis.PyQt.QtWidgets import ( + QComboBox, + QFormLayout, + QWidget, +) +from qgis.core import Qgis + +from ... import config, results +from ...i18n import later, tr +from ..maptab import MapTab + +MODES = ( + ("walking", later("on foot")), + ("cycling", later("by bike")), + ("driving", later("by car")), +) + +METRICS = ( + ("minutes", later("minutes"), ("5,10,15", "10,20,30", "15,30,45,60")), + ("kilometres", later("kilometres"), ("1,2,5", "2,5,10", "5,10,25,50")), +) + + +class IsochronePage(MapTab): + ALGORITHM = "geodonkey:isochrone" + NAME = later("Isochrone") + ICON = "isochrone.svg" + + WANTED = 1 + PROMPTS = (later("Click the centre point on the map."),) + PICK_TEXT = later("Pick the centre on the map") + TASK_TITLE = later("GeoDonkey: isochrone") + LAYER_TITLE = later("Isochrone") + STYLE_KEY = "isochrone" + + def options(self) -> Optional[QWidget]: + box = QWidget() + form = QFormLayout(box) + form.setContentsMargins(0, 0, 0, 0) + form.setSpacing(6) + + self.mode = QComboBox() + for key, label in MODES: + self.mode.addItem(tr(label), key) + self.mode.setCurrentIndex( + [key for key, _ in MODES].index(config.ISOCHRONE_DEFAULT_MODE)) + form.addRow(tr("Travel:"), self.mode) + + self.metric = QComboBox() + for key, label, _presets in METRICS: + self.metric.addItem(tr(label), key) + self.metric.currentIndexChanged.connect(self._metric_changed) + form.addRow(tr("Measured in:"), self.metric) + + self.rings = QComboBox() + self.rings.setEditable(True) + form.addRow(tr("Rings:"), self.rings) + self._metric_changed() + return box + + def _metric_changed(self) -> None: + index = max(0, self.metric.currentIndex()) + _key, _label, presets = METRICS[index] + self.rings.clear() + self.rings.addItems(list(presets)) + self.rings.setCurrentIndex(0) + + def controls(self): + return (self.mode, self.metric, self.rings) + + def price(self) -> str: + return tr("{coins} DC per run, regardless of the number of rings").format( + coins=config.COIN_COSTS.get("isochrone", 0)) + + def run(self) -> None: + if not self.points: + self.panel.say(tr("Pick the centre on the map first."), + Qgis.MessageLevel.Warning) + return + lon, lat = self.points[0] + mode = self.mode.currentData() + metric = self.metric.currentData() + values = self.rings.currentText().strip() + if not values: + self.panel.say(tr("Enter at least one ring, for example 5,10,15."), + Qgis.MessageLevel.Warning) + return + client = self.panel.api() + + def work(feedback): + if metric == "kilometres": + return client.isochrone(lon, lat, mode=mode, kilometres=values, + feedback=feedback) + return client.isochrone(lon, lat, mode=mode, minutes=values, + feedback=feedback) + + self.start(work, tr("Calculating the isochrone…")) + + def clear_result(self) -> None: + shapes = self.shapes() + if shapes is not None: + shapes.clear() + + def accept(self, payload: Dict[str, Any]) -> None: + self.payload = payload + rows = results.isochrone_rows(self.payload) + if not rows: + self.keep_button.setEnabled(False) + self.panel.say(tr("The service returned no area."), + Qgis.MessageLevel.Warning) + return + + shapes = self.shapes() + if shapes is not None: + shapes.show([(row.get("geometry"), row["attrs"].get("color")) + for row in rows]) + self.keep_button.setEnabled(True) + + labels = [row["attrs"].get("label") or "" for row in rows] + self.summary.setText(tr("{count} ring(s): {list}").format( + count=len(rows), list=" · ".join(reversed(labels)))) + self.panel.say(tr("{count} ring(s) calculated.").format(count=len(rows)), + Qgis.MessageLevel.Success) + + def rows(self): + return results.isochrone_rows(self.payload) diff --git a/geodonkey/gui/tools/profile.py b/geodonkey/gui/tools/profile.py new file mode 100644 index 0000000..09f8bce --- /dev/null +++ b/geodonkey/gui/tools/profile.py @@ -0,0 +1,146 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Tuple + +from qgis.PyQt.QtWidgets import QComboBox, QHBoxLayout, QLabel, QWidget +from qgis.core import Qgis + +from ... import config, plot, points as points_mod, results +from ...i18n import later, tr +from ..chart import ProfileChart +from ..maptab import MapTab + +RESOLUTIONS = ( + (100, later("Rough")), + (250, later("Normal")), + (config.ELEVATION_MAX_POINTS, later("Fine")), +) + +DEFAULT_RESOLUTION = 1 + + +class ProfilePage(MapTab): + ALGORITHM = "geodonkey:elevationprofile" + NAME = later("Elevation profile") + ICON = "profile.svg" + + WANTED = 2 + PROMPTS = (later("Click the start point on the map."), + later("Click the end point on the map.")) + PICK_TEXT = later("Pick two points on the map") + TASK_TITLE = later("GeoDonkey: elevation profile") + LAYER_TITLE = later("Elevation profile") + STYLE_KEY = "profile" + PLACEHOLDER = later("Pick two points on the map.") + + def setup(self) -> None: + self._coordinates: List[Tuple[float, float]] = [] + + def options(self) -> Optional[QWidget]: + box = QWidget() + row = QHBoxLayout(box) + row.setContentsMargins(0, 0, 0, 0) + row.setSpacing(6) + row.addWidget(QLabel(tr("Detail:"))) + self.resolution = QComboBox() + for count, label in RESOLUTIONS: + self.resolution.addItem(tr(label), count) + self.resolution.setCurrentIndex(DEFAULT_RESOLUTION) + self.resolution.currentIndexChanged.connect(self.update_cost) + row.addWidget(self.resolution, 1) + return box + + def body(self) -> Optional[QWidget]: + self.chart = ProfileChart() + self.chart.set_placeholder(tr(self.PLACEHOLDER)) + self.chart.hovered.connect(self._hovered) + return self.chart + + def controls(self): + return (self.resolution,) + + def max_points(self) -> int: + value = self.resolution.currentData() + return int(value or config.ELEVATION_MAX_POINTS) + + def price(self) -> str: + return tr("Up to {count} points · {coins} DC per run").format( + count=self.max_points(), + coins=config.elevation_coins(self.max_points(), "elevation_profile")) + + def run(self) -> None: + if len(self.points) < 2: + self.panel.say(tr("Pick two points on the map first."), + Qgis.MessageLevel.Warning) + return + start, end = self.points[0], self.points[1] + limit = self.max_points() + client = self.panel.api() + + def work(feedback): + return client.elevation_profile( + start, end, max_points=limit, + step=config.ELEVATION_DEFAULT_STEP_METRES, feedback=feedback) + + self.start(work, tr("Calculating the elevation profile…")) + + def clear_result(self) -> None: + self.chart.set_placeholder(tr("Calculating…")) + self.chart.clear() + + def forget(self) -> None: + self._coordinates = [] + self.chart.set_placeholder(tr(self.PLACEHOLDER)) + self.chart.clear() + + def accept(self, payload: Dict[str, Any]) -> None: + self.payload = payload + series = results.profile_series(self.payload) + self._coordinates = results.profile_coordinates(self.payload) + + if not series: + self.chart.set_placeholder(tr("The service returned no points.")) + self.chart.clear() + self.keep_button.setEnabled(False) + self.panel.say(tr("The service returned no points."), + Qgis.MessageLevel.Warning) + return + + self.chart.set_samples(series) + track = self.track() + if track is not None: + track.show(self._coordinates) + self.keep_button.setEnabled(True) + + up, down = plot.gain_and_loss(series) + self.summary.setText("%s
%s" % ( + results.profile_summary(self.payload), + tr("Ascent {up} m · descent {down} m").format( + up=points_mod.fmt(round(up)), down=points_mod.fmt(round(down))))) + + missing = sum(1 for _x, y in series if y is None) + if missing: + self.panel.say(tr("{missing} of {count} points have no elevation " + "data.").format(missing=missing, count=len(series)), + Qgis.MessageLevel.Warning) + else: + self.panel.say(results.profile_summary(self.payload), + Qgis.MessageLevel.Success) + + def cancel_task(self) -> None: + super().cancel_task() + self.chart.set_placeholder(tr(self.PLACEHOLDER)) + + def rows(self): + return list(results.profile_rows(self.payload)) + \ + list(results.profile_segment_rows(self.payload)) + + def _hovered(self, index: int) -> None: + marker = self.marker() + if marker is None: + return + if index < 0 or index >= len(self._coordinates): + marker.hide() + return + lon, lat = self._coordinates[index] + marker.show(lon, lat) diff --git a/geodonkey/gui/tools/route.py b/geodonkey/gui/tools/route.py new file mode 100644 index 0000000..586aa97 --- /dev/null +++ b/geodonkey/gui/tools/route.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +from typing import Any, Dict, Optional + +from qgis.PyQt.QtWidgets import ( + QCheckBox, + QComboBox, + QFormLayout, + QWidget, +) +from qgis.core import Qgis + +from ... import config, results +from ...i18n import later, tr +from ..maptab import MapTab + +MODES = ( + ("driving", later("by car")), + ("cycling", later("by bike")), + ("walking", later("on foot")), +) + + +class RoutePage(MapTab): + ALGORITHM = "geodonkey:route" + NAME = later("Route") + ICON = "route.svg" + + WANTED = config.ROUTE_MAX_POINTS + FREE = True + PROMPTS = (later("Click the start point on the map."), + later("Click the destination – or further stopovers."), + later("Another stopover, or right-click to finish.")) + PICK_TEXT = later("Pick the route on the map") + TASK_TITLE = later("GeoDonkey: route") + LAYER_TITLE = later("Route") + STYLE_KEY = "route" + + def options(self) -> Optional[QWidget]: + box = QWidget() + form = QFormLayout(box) + form.setContentsMargins(0, 0, 0, 0) + form.setSpacing(6) + + self.mode = QComboBox() + for key, label in MODES: + self.mode.addItem(tr(label), key) + form.addRow(tr("Travel:"), self.mode) + + self.optimize = QCheckBox(tr("Find the shortest order")) + self.optimize.toggled.connect(self.update_cost) + form.addRow("", self.optimize) + + self.steps = QCheckBox(tr("Include turn-by-turn directions")) + form.addRow("", self.steps) + return box + + def controls(self): + return (self.mode, self.optimize, self.steps) + + def price(self) -> str: + key = "route_optimized" if self.optimize.isChecked() else "route" + return tr("{coins} DC per run · 2 to {limit} points").format( + coins=config.COIN_COSTS.get(key, 0), + limit=config.ROUTE_MAX_POINTS) + + def run(self) -> None: + if len(self.points) < config.ROUTE_MIN_POINTS: + self.panel.say(tr("A route needs at least {count} points.").format( + count=config.ROUTE_MIN_POINTS), Qgis.MessageLevel.Warning) + return + stops = list(self.points) + mode = self.mode.currentData() + optimize = self.optimize.isChecked() + steps = self.steps.isChecked() + client = self.panel.api() + + def work(feedback): + return client.route(stops, mode=mode, optimize=optimize, + steps=steps, feedback=feedback) + + self.start(work, tr("Calculating the route…")) + + def clear_result(self) -> None: + shapes = self.shapes() + if shapes is not None: + shapes.clear() + + def accept(self, payload: Dict[str, Any]) -> None: + self.payload = payload + legs, stops = results.route_rows(self.payload) + if not legs: + self.keep_button.setEnabled(False) + self.panel.say(tr("The service returned no route."), + Qgis.MessageLevel.Warning) + return + + shapes = self.shapes() + if shapes is not None: + shapes.show([(row.get("geometry"), row["attrs"].get("color")) + for row in legs]) + self.keep_button.setEnabled(True) + + summary = results.route_summary(self.payload) + self.summary.setText("%s
%s" % ( + summary, + tr("{legs} leg(s) · {stops} stop(s)").format( + legs=len(legs), stops=len(stops)))) + self.panel.say(summary, Qgis.MessageLevel.Success) + + def rows(self): + legs, stops = results.route_rows(self.payload) + return list(legs) + list(stops) diff --git a/geodonkey/gui/tools/sight.py b/geodonkey/gui/tools/sight.py new file mode 100644 index 0000000..979cc01 --- /dev/null +++ b/geodonkey/gui/tools/sight.py @@ -0,0 +1,174 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Tuple + +from qgis.PyQt.QtWidgets import ( + QCheckBox, + QDoubleSpinBox, + QFormLayout, + QWidget, +) +from qgis.core import Qgis + +from ... import config, points as points_mod, results +from ...i18n import later, tr +from ..chart import ProfileChart +from ..maptab import MapTab + + +class SightPage(MapTab): + ALGORITHM = "geodonkey:lineofsight" + NAME = later("Line of sight") + ICON = "lineofsight.svg" + + WANTED = 2 + PROMPTS = (later("Click the first point on the map."), + later("Click the second point on the map.")) + PICK_TEXT = later("Pick two points on the map") + TASK_TITLE = later("GeoDonkey: line of sight") + LAYER_TITLE = later("Line of sight") + STYLE_KEY = "sight" + PLACEHOLDER = later("Pick two points on the map.") + + def setup(self) -> None: + self._coordinates: List[Tuple[float, float]] = [] + + def options(self) -> Optional[QWidget]: + box = QWidget() + form = QFormLayout(box) + form.setContentsMargins(0, 0, 0, 0) + form.setSpacing(6) + + self.height_a = self._height() + form.addRow(tr("Height at A:"), self.height_a) + self.height_b = self._height() + form.addRow(tr("Height at B:"), self.height_b) + + self.curvature = QCheckBox(tr("Account for earth curvature")) + self.curvature.setChecked(True) + form.addRow("", self.curvature) + return box + + @staticmethod + def _height() -> QDoubleSpinBox: + spin = QDoubleSpinBox() + spin.setRange(0.0, config.LOS_MAX_HEIGHT_METRES) + spin.setDecimals(1) + spin.setSingleStep(0.5) + spin.setSuffix(" m") + spin.setValue(config.LOS_DEFAULT_HEIGHT_METRES) + return spin + + def body(self) -> Optional[QWidget]: + self.chart = ProfileChart() + self.chart.set_placeholder(tr(self.PLACEHOLDER)) + self.chart.hovered.connect(self._hovered) + return self.chart + + def controls(self): + return (self.height_a, self.height_b, self.curvature) + + def price(self) -> str: + if len(self.points) < 2: + return tr("Free up to {limit} m air line, {coins} DC above").format( + limit=points_mod.fmt(round(config.LOS_FREE_METRES)), + coins=config.COIN_COSTS.get("line_of_sight", 0)) + metres = points_mod.distance(self.points[0], self.points[1]) + coins = config.line_of_sight_coins(metres) + if not coins: + return tr("{distance} m air line · free").format( + distance=points_mod.fmt(round(metres))) + return tr("{distance} m air line · {coins} DC").format( + distance=points_mod.fmt(round(metres)), coins=coins) + + def show_points(self) -> None: + super().show_points() + self.update_cost() + + def run(self) -> None: + if len(self.points) < 2: + self.panel.say(tr("Pick two points on the map first."), + Qgis.MessageLevel.Warning) + return + start, end = self.points[0], self.points[1] + height_a = self.height_a.value() + height_b = self.height_b.value() + curvature = self.curvature.isChecked() + client = self.panel.api() + + def work(feedback): + return client.line_of_sight( + start, end, height_a=height_a, height_b=height_b, + curvature=curvature, samples=True, feedback=feedback) + + self.start(work, tr("Checking the line of sight…")) + + def clear_result(self) -> None: + self.chart.set_placeholder(tr("Calculating…")) + self.chart.clear() + + def forget(self) -> None: + self._coordinates = [] + self.chart.set_placeholder(tr(self.PLACEHOLDER)) + self.chart.clear() + + def accept(self, payload: Dict[str, Any]) -> None: + self.payload = payload + start = self.points[0] if self.points else (0.0, 0.0) + end = self.points[1] if len(self.points) > 1 else start + lines, obstacles, samples = results.sight_rows(self.payload, start, end) + + if not samples: + self.chart.set_placeholder(tr("No terrain samples returned.")) + self.chart.clear() + else: + terrain = [(row["attrs"]["distance"], row["attrs"]["terrain"]) + for row in samples] + sight = [(row["attrs"]["distance"], row["attrs"]["sight"]) + for row in samples] + self.chart.set_samples(terrain) + self.chart.set_line(sight) + self.chart.set_marks([ + (row["attrs"]["distance"], row["attrs"]["terrain"]) + for row in obstacles + if row["attrs"].get("distance") is not None + and row["attrs"].get("terrain") is not None]) + self._coordinates = [ + tuple((row.get("geometry") or {}).get("coordinates") or ()) + for row in samples] + + track = self.track() + if track is not None: + track.show([start, end]) + + self.keep_button.setEnabled(bool(lines)) + self.summary.setText(results.sight_summary(self.payload)) + visible = bool((self.payload or {}).get("visible")) + self.panel.say(results.sight_summary(self.payload), + Qgis.MessageLevel.Success if visible + else Qgis.MessageLevel.Warning) + + def cancel_task(self) -> None: + super().cancel_task() + self.chart.set_placeholder(tr(self.PLACEHOLDER)) + + def rows(self): + if not self.payload: + return [] + start = self.points[0] if self.points else (0.0, 0.0) + end = self.points[1] if len(self.points) > 1 else start + _lines, obstacles, _samples = results.sight_rows(self.payload, start, end) + return list(results.sight_segment_rows(self.payload, start, end)) + list(obstacles) + + def _hovered(self, index: int) -> None: + marker = self.marker() + if marker is None: + return + if index < 0 or index >= len(self._coordinates): + marker.hide() + return + pair = self._coordinates[index] + if len(pair) != 2: + marker.hide() + return + marker.show(pair[0], pair[1]) diff --git a/geodonkey/gui/tools_tab.py b/geodonkey/gui/tools_tab.py new file mode 100644 index 0000000..d55e750 --- /dev/null +++ b/geodonkey/gui/tools_tab.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from typing import List, Optional + +from qgis.PyQt.QtWidgets import ( + QComboBox, + QStackedWidget, + QWidget, +) + +from ..compat import icon +from ..i18n import tr +from . import theme +from .tools import PAGES + + +class ToolsTab(QWidget): + def __init__(self, panel, iface, parent=None) -> None: + super().__init__(parent) + self.panel = panel + self.iface = iface + self.pages: List[QWidget] = [] + self._build() + + def _build(self) -> None: + box = theme.page_box(self) + box.addWidget(theme.page_title(tr("Tools"))) + + self.chooser = QComboBox() + box.addWidget(self.chooser) + + self.stack = QStackedWidget() + for page_class in PAGES: + page = page_class(self.panel, self.iface) + self.pages.append(page) + self.stack.addWidget(page) + self.chooser.addItem(icon(page_class.ICON), tr(page_class.NAME), + page_class.ALGORITHM) + box.addWidget(self.stack, 1) + + self.chooser.currentIndexChanged.connect(self.show_page) + + def show_page(self, index: int) -> None: + if index < 0 or index >= len(self.pages): + return + current = self.stack.currentIndex() + if current != index and 0 <= current < len(self.pages): + self.pages[current].stop_picking() + self.chooser.setCurrentIndex(index) + self.stack.setCurrentIndex(index) + + def page_for(self, algorithm: str) -> Optional[int]: + for index, page_class in enumerate(PAGES): + if page_class.ALGORITHM == algorithm: + return index + return None + + def shutdown(self) -> None: + for page in self.pages: + page.shutdown() diff --git a/geodonkey/gui/upload_tab.py b/geodonkey/gui/upload_tab.py new file mode 100644 index 0000000..c328b0a --- /dev/null +++ b/geodonkey/gui/upload_tab.py @@ -0,0 +1,447 @@ +from __future__ import annotations + +from typing import Any, List, Optional + +from qgis.PyQt.QtCore import QUrl, Qt +from qgis.PyQt.QtGui import QDesktopServices +from qgis.PyQt.QtWidgets import ( + QApplication, + QCheckBox, + QHBoxLayout, + QLabel, + QLineEdit, + QListWidget, + QListWidgetItem, + QPushButton, + QSizePolicy, + QSpinBox, + QWidget, +) +from qgis.core import Qgis, QgsProject, QgsVectorLayer + +from .. import config, export, layers, mapcontext, task +from .. import upload as upload_mod +from ..errors import GeoDonkeyError +from ..i18n import tr +from . import theme + + +class UploadTab(QWidget): + def __init__(self, panel, iface, parent=None) -> None: + super().__init__(parent) + self.panel = panel + self.iface = iface + self._task = None + self._layers: List[QgsVectorLayer] = [] + self._fresh = "" + self._link_id = "" + self._data_url = "" + self._build() + self.reload_layers() + + def _build(self) -> None: + box = theme.page_box(self) + box.addWidget(theme.page_title(tr("Upload"))) + + box.addWidget(theme.section(tr("New dataset"))) + + row = QHBoxLayout() + row.setSpacing(6) + row.addWidget(QLabel(tr("Layer:"))) + self.layer_box = theme.LayerBox(refill=self.reload_layers) + self.layer_box.currentIndexChanged.connect(self.layer_changed) + row.addWidget(self.layer_box, 1) + box.addLayout(row) + + self.only_selected = QCheckBox(tr("Only the selected features")) + self.only_selected.stateChanged.connect(self.update_note) + box.addWidget(self.only_selected) + + days = QHBoxLayout() + days.setSpacing(6) + days.addWidget(QLabel(tr("Keep for:"))) + self.ttl = QSpinBox() + self.ttl.setRange(1, config.upload_ttl_limit(False)) + self.ttl.setValue(config.UPLOAD_DEFAULT_TTL_DAYS) + self.ttl.setSuffix(" " + tr("days")) + self.ttl.valueChanged.connect(self.update_note) + days.addWidget(self.ttl) + days.addStretch(1) + box.addLayout(days) + + self.note = QLabel("") + self.note.setWordWrap(True) + self.note.setStyleSheet(theme.note_style()) + theme.small(self.note) + box.addWidget(self.note) + + buttons = QHBoxLayout() + buttons.setSpacing(6) + self.send_button = QPushButton(tr("Upload layer")) + self.send_button.setStyleSheet(theme.primary_button_style()) + self.send_button.clicked.connect(self.send) + buttons.addWidget(self.send_button, 1) + self.cancel_button = QPushButton(tr("Cancel")) + self.cancel_button.setEnabled(False) + self.cancel_button.clicked.connect(self.cancel_task) + buttons.addWidget(self.cancel_button) + box.addLayout(buttons) + + box.addWidget(self.panel._separator()) + + box.addWidget(theme.section(tr("My datasets"))) + self.list = QListWidget() + self.list.setSizePolicy(QSizePolicy.Policy.Preferred, + QSizePolicy.Policy.Expanding) + box.addWidget(self.list, 1) + + self.list_note = QLabel(tr("Not loaded yet.")) + self.list_note.setWordWrap(True) + self.list_note.setStyleSheet(theme.note_style()) + theme.small(self.list_note) + box.addWidget(self.list_note) + + lower = QHBoxLayout() + lower.setSpacing(6) + refresh = QPushButton(tr("Refresh")) + refresh.clicked.connect(self.reload_datasets) + lower.addWidget(refresh, 1) + self.discard_button = QPushButton(tr("Discard")) + self.discard_button.clicked.connect(self.discard) + lower.addWidget(self.discard_button) + box.addLayout(lower) + + box.addWidget(self.panel._separator()) + + box.addWidget(theme.section(tr("Pass it on"))) + self.link = QLineEdit() + self.link.setReadOnly(True) + self.link.setPlaceholderText(tr("Select a dataset to see its link.")) + box.addWidget(self.link) + + share = QHBoxLayout() + share.setSpacing(6) + self.copy_button = QPushButton(tr("Copy link")) + self.copy_button.clicked.connect(self.copy_link) + share.addWidget(self.copy_button, 1) + self.open_button = QPushButton(tr("Open in browser")) + self.open_button.clicked.connect(self.open_link) + share.addWidget(self.open_button, 1) + box.addLayout(share) + + direct = QHBoxLayout() + direct.setSpacing(6) + self.data_button = QPushButton(tr("Copy data address")) + self.data_button.clicked.connect(self.copy_data_link) + direct.addWidget(self.data_button, 1) + self.fetch_button = QPushButton(tr("Load as layer")) + self.fetch_button.clicked.connect(self.load_dataset) + direct.addWidget(self.fetch_button, 1) + box.addLayout(direct) + + self.link_note = QLabel(upload_mod.share_warning()) + self.link_note.setWordWrap(True) + self.link_note.setStyleSheet(theme.note_style()) + theme.small(self.link_note) + box.addWidget(self.link_note) + + self.list.currentItemChanged.connect(self.update_link) + self.update_link() + self.update_note() + + def pro(self) -> bool: + return bool(getattr(self.panel, "_pro", False)) + + def reload_layers(self) -> None: + before = self.current_layer() + self.layer_box.blockSignals(True) + self.layer_box.clear() + self._layers = mapcontext.vector_layers(QgsProject.instance()) + for layer in self._layers: + self.layer_box.addItem(layer.name()) + if before is not None and before in self._layers: + self.layer_box.setCurrentIndex(self._layers.index(before)) + self.layer_box.blockSignals(False) + self.layer_changed() + + def current_layer(self) -> Optional[QgsVectorLayer]: + index = self.layer_box.currentIndex() + if 0 <= index < len(self._layers): + return self._layers[index] + return None + + def layer_changed(self, *_args) -> None: + layer = self.current_layer() + picked = layer.selectedFeatureCount() if layer is not None else 0 + self.only_selected.blockSignals(True) + self.only_selected.setEnabled(picked > 0) + self.only_selected.setChecked(picked > 0) + self.only_selected.setText( + tr("Only the selected features ({count})").format(count=picked) + if picked > 0 else tr("Only the selected features")) + self.only_selected.blockSignals(False) + self.update_note() + + def refresh_limits(self) -> None: + self.ttl.setMaximum(config.upload_ttl_limit(self.pro())) + self.update_note() + + def count(self) -> int: + return export.feature_count(self.current_layer(), + self.only_selected.isChecked()) + + def update_note(self, *_args) -> None: + layer = self.current_layer() + if layer is None: + self.note.setText(tr("No vector layer in this project.")) + self.note.setStyleSheet(theme.warn_style()) + self.send_button.setEnabled(False) + return + + objects = self.count() + trouble = upload_mod.complaint(objects, pro=self.pro()) + if trouble: + self.note.setText(trouble) + self.note.setStyleSheet(theme.warn_style()) + self.send_button.setEnabled(False) + return + + coins = config.upload_coins(objects, self.ttl.value(), self.pro()) + parts = [tr("{count} feature(s)").format(count=objects)] + if coins > 0: + parts.append(tr("This upload costs {coins} DC.").format(coins=coins)) + else: + parts.append(tr("Up to {count} features are free of charge.").format( + count=config.UPLOAD_FREE_OBJECTS)) + self.note.setText(" · ".join(parts)) + self.note.setStyleSheet(theme.note_style()) + self.send_button.setEnabled(True) + + def busy(self, running: bool) -> None: + self.send_button.setEnabled(not running) + self.cancel_button.setEnabled(running) + + def cancel_task(self) -> None: + if self._task is not None: + self._task.cancel() + self._task = None + self.busy(False) + self.update_note() + self.panel.say(tr("Cancelled.")) + + def send(self) -> None: + layer = self.current_layer() + if layer is None: + self.panel.say(tr("Choose a vector layer first."), + Qgis.MessageLevel.Warning) + return + try: + data, filename = export.layer_to_geojson( + layer, self.only_selected.isChecked()) + except GeoDonkeyError as error: + self.panel.complain(error) + return + + trouble = upload_mod.complaint(self.count(), len(data), self.pro()) + if trouble: + self.panel.say(trouble, Qgis.MessageLevel.Warning) + return + + client = self.panel.api() + days = upload_mod.clamp_ttl(self.ttl.value(), self.pro()) + + def work(feedback): + return client.upload_dataset(filename, data, days, feedback=feedback) + + def done(meta): + self._task = None + self.busy(False) + self.update_note() + self.panel.update_cost_label() + self._fresh = str((meta or {}).get("upload_id") or "") + self.panel.say(upload_mod.receipt(meta or {}), + Qgis.MessageLevel.Success) + self.reload_datasets() + if self._fresh and not self.link.text(): + self.show_link(self._fresh) + + def failed(error): + self._task = None + self.busy(False) + self.update_note() + self.panel.complain(error) + + self.busy(True) + self.panel.say(tr("Uploading {name} ({size})…").format( + name=filename, size=upload_mod.pretty_size(len(data)))) + self._task = task.run(tr("GeoDonkey: upload"), work, done, failed) + + def reload_datasets(self) -> None: + client = self.panel.api() + if not client.token: + self.list.clear() + self.list_note.setText( + tr("Datasets can only be listed with an API key.")) + self.list_note.setStyleSheet(theme.warn_style()) + return + + def work(feedback): + return client.uploads(feedback=feedback) + + def done(payload): + self._task = None + self.show_datasets(payload or {}) + + def failed(error): + self._task = None + self.list_note.setText(error.message) + self.list_note.setStyleSheet(theme.warn_style()) + self.panel.complain(error) + + self.list_note.setText(tr("Loading…")) + self.list_note.setStyleSheet(theme.note_style()) + self._task = task.run(tr("GeoDonkey: datasets"), work, done, failed) + + def show_datasets(self, payload: Any) -> None: + rows = upload_mod.datasets(payload) + self.list.clear() + for meta in rows: + item = QListWidgetItem(upload_mod.describe(meta)) + item.setData(Qt.ItemDataRole.UserRole, meta.get("upload_id") or "") + self.list.addItem(item) + if self.list.count(): + self.list.setCurrentRow(self._row_of(self._fresh)) + limit = (payload.get("limit") if isinstance(payload, dict) else None) \ + or config.UPLOAD_MAX_DATASETS + self.list_note.setText(tr("{count} of {limit} datasets in use.").format( + count=len(rows), limit=limit)) + self.list_note.setStyleSheet(theme.note_style()) + + def _row_of(self, upload_id: str) -> int: + ident = (upload_id or "").strip() + if ident: + for row in range(self.list.count()): + item = self.list.item(row) + if str(item.data(Qt.ItemDataRole.UserRole) or "") == ident: + return row + return 0 + + def selected_dataset(self) -> str: + item = self.list.currentItem() + if item is None: + return "" + return str(item.data(Qt.ItemDataRole.UserRole) or "") + + def update_link(self, *_args) -> None: + self.show_link(self.selected_dataset()) + + def show_link(self, upload_id: str) -> None: + self._link_id = (upload_id or "").strip() + base = self.panel.api().base_url + self._data_url = upload_mod.share_url(base, self._link_id) + view = upload_mod.viewer_url(base, self._link_id) + url = view or self._data_url + self.link.setText(url) + self.link.setCursorPosition(0) + for button in (self.copy_button, self.open_button, self.fetch_button): + button.setEnabled(bool(url)) + self.data_button.setEnabled(bool(view)) + self.link_note.setText( + upload_mod.share_warning(bool(view) or not self._link_id)) + + def copy_link(self) -> None: + url = self.link.text().strip() + if not url: + self.panel.say(tr("Choose a dataset first."), + Qgis.MessageLevel.Warning) + return + QApplication.clipboard().setText(url) + self.panel.say(tr("Link copied to the clipboard."), + Qgis.MessageLevel.Success) + + def copy_data_link(self) -> None: + url = (self._data_url or "").strip() + if not url: + self.panel.say(tr("Choose a dataset first."), + Qgis.MessageLevel.Warning) + return + QApplication.clipboard().setText(url) + self.panel.say(tr("Data address copied to the clipboard."), + Qgis.MessageLevel.Success) + + def open_link(self) -> None: + url = self.link.text().strip() + if not url: + self.panel.say(tr("Choose a dataset first."), + Qgis.MessageLevel.Warning) + return + QDesktopServices.openUrl(QUrl(url)) + + def load_dataset(self) -> None: + ident = self._link_id + if not ident: + self.panel.say(tr("Choose a dataset first."), + Qgis.MessageLevel.Warning) + return + client = self.panel.api() + item = self.list.currentItem() + title = (item.text().split(" · ")[0] + if item is not None and self.selected_dataset() == ident + else ident) + + def work(feedback): + return client.upload_geojson(ident, feedback=feedback) + + def done(payload): + self._task = None + collection = dict(payload or {}) + if not collection.get("features"): + self.panel.say(tr("That dataset has no features."), + Qgis.MessageLevel.Warning) + return + try: + created, counts, _without = layers.load_result( + collection, {}, title, style_key="osm") + except GeoDonkeyError as error: + self.panel.complain(error) + return + self.panel.say(tr("{count} feature(s) loaded.").format( + count=sum(counts.values())), Qgis.MessageLevel.Success) + if created and self.iface is not None: + self.iface.setActiveLayer(created[0]) + + def failed(error): + self._task = None + self.panel.complain(error) + + self.panel.say(tr("Loading dataset…")) + self._task = task.run(tr("GeoDonkey: load dataset"), work, done, failed) + + def discard(self) -> None: + ident = self.selected_dataset() + if not ident: + self.panel.say(tr("Choose a dataset to discard."), + Qgis.MessageLevel.Warning) + return + client = self.panel.api() + + def work(feedback): + return client.delete_upload(ident, feedback=feedback) + + def done(_payload): + self._task = None + if self._fresh == ident: + self._fresh = "" + self.show_link("") + self.panel.say(tr("Dataset discarded."), Qgis.MessageLevel.Success) + self.reload_datasets() + + def failed(error): + self._task = None + self.panel.complain(error) + + self._task = task.run(tr("GeoDonkey: discard dataset"), work, done, failed) + + def showEvent(self, event): # noqa: N802 + super().showEvent(event) + self.reload_layers() diff --git a/geodonkey/i18n.py b/geodonkey/i18n.py new file mode 100644 index 0000000..521c826 --- /dev/null +++ b/geodonkey/i18n.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +try: + from qgis.PyQt.QtCore import QCoreApplication + + def tr(text: str, context: str = "GeoDonkey") -> str: + return QCoreApplication.translate(context, text) + +except ImportError: + def tr(text: str, context: str = "GeoDonkey") -> str: + return text + + +def later(text: str) -> str: + return text diff --git a/geodonkey/i18n/geodonkey_de.qm b/geodonkey/i18n/geodonkey_de.qm new file mode 100644 index 0000000000000000000000000000000000000000..9a1c13c68d21038bef2074ef6473c38da121a839 GIT binary patch literal 73158 zcmeHw37lO;m40>7dv`hz!eR*FvIp!mJ7NftB%OqimF|Qk1H{+;UUxtG^?Q%Eq|<3z zaT^&$WLyvw5m#IoHxxku7gPpDnQ=!&R7A%Wb#!phi2v`abL&>!_v&^x$jpEF{eS#O zcfWUU)v0q%o%5Yjr>a)mkv`;s-`x17uN<-XGcSC{-QT}ODK#gZS*=v(wfOZSrT*}J z{JdDH|9nEJzE3Lk4-cz3Lys#pcC~7}>Z3|+zg;!{+ghb|U#6PgKCINIZ&%IlpR3d# zf1ws%egIy*Pc6BBiBiL#Q%CZ>|5~V4o$-iLnOCdxfAY9$nDah$(Oowv^-n|UqWiy~ z)F*CM7mq%q)a}=)i*xV6&(Eoy?|Y+CckNI+Z!ar#_dlwg-+qBozrS4l-O#B@{rnnr zNzao?J#nx~_jW1u%@?botI+Oq%^@FC{l=_dKtDiQ4AK8c1FW&JA zrKS#5kH4!&sq1#CCy#py-yhk~cn^NQ=hBA8?|)M@%zL2WxPACL)6sC&0G|8#0S)VJ z%PW;@Y1nWs#+_Z=u<`d9)zCK3uo^$)MN0fT-)Hz?=nN{lYm2-Zx8alM)vvYoP+6@zH+!*h4s@;0SDaK+q#GTM2^yt(iH z)l*6x_p`a5_|(Ug`t6pvw=Zr3pBBx%IduQK7Rj$O1=BMxqm$x&;Rww#-;~ugC2dXvH3-y=Uvw} zc8ooOIq^W_0dE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n zQmCYISjD$@Nb@@^u%I}GS$!YX7l5yV)*LJv6G@7u2Gw~f)fbTpBh`M>NEIM2b!Nc86Mx2sQPto)~8AIOL`3lL$F&( zm?)t{sAZo0Hj$nznT+;_U^R|O2WXDnRpXJvk!X{;$SOa|orlTT10~?sorQ}9m>UI5 zjiquhM8b;njc9SV)@W|aXPX9`a}C%B%?U)!+OgRJW@-+2)tlf7SwG-&wgQ&n34ODn zT@*kpo7E{+eBhXNpcFgfS5M+#wQ6RHwVVj;^yPzG$HFley6_K|@u3`nJLj<fl&v&y@Fo$5V8*t26poy{oHCCZ%O5TEhAzA?nd9-)3q|Q(?xcR#&c4O3i6# F_+KK;m5l%Z literal 0 HcmV?d00001 diff --git a/geodonkey/i18n/geodonkey_de.ts b/geodonkey/i18n/geodonkey_de.ts new file mode 100644 index 0000000..bea49f6 --- /dev/null +++ b/geodonkey/i18n/geodonkey_de.ts @@ -0,0 +1,2093 @@ + + + + + GeoDonkey + + + No area selected + Kein Gebiet gewählt + + + + The selected area is empty. Zoom to the region you want to query. + Das gewählte Gebiet ist leer. Zoomen Sie auf die Gegend, die Sie abfragen wollen. + + + + The radius must be greater than zero. + Der Umkreis muss größer als null sein. + + + + A polygon needs at least three points. + Ein Vieleck braucht mindestens drei Punkte. + + + + Rectangle {bbox} + Rechteck {bbox} + + + + Polygon with {count} vertices + Vieleck mit {count} Stützpunkten + + + + The area is too large: {area} square degrees, the limit is {limit}. Zoom in or draw a smaller rectangle. + Das Gebiet ist zu groß: {area} Quadratgrad, erlaubt sind {limit}. Zoomen Sie näher heran oder ziehen Sie ein kleineres Rechteck auf. + + + + The radius is too large: {radius} m, the limit is {limit} m. + Der Umkreis ist zu groß: {radius} m, erlaubt sind {limit} m. + + + + {radius} m around {lon}, {lat} + {radius} m um {lon}, {lat} + + + + The QGIS authentication database is not available. The key will only be kept for this session. + Die Authentifizierungsdatenbank von QGIS steht nicht zur Verfügung. Der Schlüssel gilt nur für diese Sitzung. + + + + The key could not be stored. + Der Schlüssel konnte nicht gespeichert werden. + + + + No map style selected. + Kein Kartenstil gewählt. + + + + The basemap could not be loaded. Check the API address and your connection. + Die Hintergrundkarte konnte nicht geladen werden. Prüfen Sie die API-Adresse und Ihre Verbindung. + + + + GeoDonkey vector tiles, style “{style}”. {license} + GeoDonkey-Vektorkacheln, Stil „{style}“. {license} + + + + The GeoDonkey service returned a response that could not be read. + Der GeoDonkey-Dienst hat eine Antwort geschickt, die nicht lesbar war. + + + + Use either a plain-language search or tag filters, not both. + Entweder in Alltagssprache suchen oder nach Merkmalen filtern – beides zugleich geht nicht. + + + + Enter a search term or a tag filter. + Geben Sie einen Suchbegriff oder einen Merkmalsfilter ein. + + + + The query is empty. + Die Abfrage ist leer. + + + + Use either travel time or distance, not both. + Bitte entweder Fahrzeit oder Entfernung angeben, nicht beides. + + + + kilometres + Kilometer + + + + minutes + Minuten + + + + No points given. + Es wurden keine Punkte angegeben. + + + + The refraction factor must be greater than zero. + Der Refraktionsfaktor muss größer als null sein. + + + + Choose a dataset first. + Wählen Sie zuerst einen Datensatz. + + + + Choose a dataset to discard. + Wählen Sie einen Datensatz zum Verwerfen. + + + + Enter at least one value for {label}. + Bitte mindestens einen Wert für {label} angeben. + + + + At most {limit} rings can be calculated, {count} were given. + Es lassen sich höchstens {limit} Ringe berechnen, angegeben wurden {count}. + + + + Unknown travel mode “{mode}”. Available: {list}. + Unbekanntes Verkehrsmittel „{mode}“. Möglich sind: {list}. + + + + No connection to the GeoDonkey service. + Keine Verbindung zum GeoDonkey-Dienst. + + + + {value} is outside the allowed range for {label} ({min} to {max}). + {value} liegt außerhalb des zulässigen Bereichs für {label} ({min} bis {max}). + + + + A route needs at least {count} points. + Eine Route braucht mindestens {count} Punkte. + + + + {count} points given, at most {limit} are allowed. + {count} Punkte angegeben, erlaubt sind höchstens {limit}. + + + + “{value}” is not a number. + „{value}“ ist keine Zahl. + + + + Heights above ground must be between 0 and {max} m. + Höhen über Grund müssen zwischen 0 und {max} m liegen. + + + + Rate limit reached. Please wait a moment and try again. + Das Aufruflimit ist erreicht. Warten Sie einen Moment und versuchen Sie es erneut. + + + + The GeoDonkey service reported a problem. Please try again later. + Der GeoDonkey-Dienst meldet eine Störung. Bitte später noch einmal versuchen. + + + + Unexpected response from the GeoDonkey service. + Unerwartete Antwort vom GeoDonkey-Dienst. + + + + This API key is not allowed to use that endpoint. + Dieser API-Schlüssel darf diesen Endpunkt nicht benutzen. + + + + The request was rejected. Please check the query and the area. + Die Anfrage wurde abgelehnt. Prüfen Sie Abfrage und Gebiet. + + + + No connection to the GeoDonkey service. Check your internet connection and proxy settings. + Keine Verbindung zum GeoDonkey-Dienst. Prüfen Sie Ihre Internetverbindung und die Proxy-Einstellungen. + + + + The GeoDonkey API key is missing or no longer valid. Open the plugin settings and paste a key from {url}. + Der GeoDonkey-API-Schlüssel fehlt oder gilt nicht mehr. Öffnen Sie die Einstellungen des Plugins und fügen Sie einen Schlüssel von {url} ein. + + + + Not enough DonkeyCoins for this request. Top up your balance at {url}. + Zu wenig DonkeyCoins für diese Anfrage. Guthaben aufladen unter {url}. + + + + Rate limit reached. Try again in {seconds} seconds. + Das Aufruflimit ist erreicht. In {seconds} Sekunden geht es weiter. + + + + Choose a vector layer first. + Wählen Sie zuerst einen Vektorlayer. + + + + Nothing is selected in this layer. + In diesem Layer ist nichts ausgewählt. + + + + The layer could not be written as GeoJSON. + Der Layer ließ sich nicht als GeoJSON schreiben. + + + + The layer has no features to upload. + Der Layer enthält keine Objekte zum Hochladen. + + + + {count} objects + {count} Objekte + + + + {count} without geometry + {count} ohne Geometrie + + + + limit of {limit} reached – the result is incomplete + Grenze von {limit} erreicht – das Ergebnis ist unvollständig + + + + points + Punkte + + + + lines + Linien + + + + areas + Flächen + + + + Retrieved from GeoDonkey (DonkeyOSM). + Abgerufen von GeoDonkey (DonkeyOSM). + + + + Query: {query} + Abfrage: {query} + + + + Area: {area} + Gebiet: {area} + + + + Data status: {stamp} + Datenstand: {stamp} + + + + Incomplete: the limit of {limit} was reached. + Unvollständig: Die Grenze von {limit} wurde erreicht. + + + + QGIS could not read the result file: {path} + QGIS konnte die Ergebnisdatei nicht lesen: {path} + + + + The selected area is empty. + Das gewählte Gebiet ist leer. + + + + No layer selected. + Kein Layer gewählt. + + + + Select one or more polygons first. + Wählen Sie zuerst eine oder mehrere Flächen aus. + + + + Area selection needs a polygon layer. + Für einen Umriss wird ein Flächenlayer gebraucht. + + + + The selected features have no geometry. + Die gewählten Objekte haben keine Geometrie. + + + + The selected features could not be combined. + Die gewählten Objekte ließen sich nicht zusammenfassen. + + + + The selection has no usable outline. + Die Auswahl ergibt keinen brauchbaren Umriss. + + + + An extent needs four numbers. + Ein Ausschnitt braucht vier Zahlen. + + + + Nothing is selected in that layer. + In diesem Layer ist nichts ausgewählt. + + + + Isochrone + Isochrone + + + + Reachable area from a point, by foot, bike or car + Erreichbares Gebiet um einen Punkt, zu Fuß, mit dem Rad oder dem Auto + + + + Route + Route + + + + Route through several points, with distance, time and directions + Route über mehrere Punkte, mit Strecke, Dauer und Wegbeschreibung + + + + Elevation profile + Höhenprofil + + + + Terrain profile along the straight line between two points + Geländeschnitt entlang der Geraden zwischen zwei Punkten + + + + Point elevation + Punkthöhen + + + + Add the elevation above sea level to every point of a layer + Ergänzt jeden Punkt einer Ebene um seine Höhe über dem Meer + + + + Line of sight + Sichtverbindung + + + + Is there a clear line of sight between two points? + Besteht zwischen zwei Punkten freie Sicht? + + + + DonkeyOSM query + DonkeyOSM-Abfrage + + + + Query OpenStreetMap data and load it as vector layers + OpenStreetMap-Daten abfragen und als Vektorlayer laden + + + + GeoDonkey basemaps + GeoDonkey-Hintergrundkarten + + + + Add a GeoDonkey vector tile basemap + Eine GeoDonkey-Vektorkachelkarte als Hintergrund hinzufügen + + + + Upload data + Geodaten hochladen + + + + Upload a vector layer to GeoDonkey and manage your datasets + Einen Vektorlayer zu GeoDonkey hochladen und eigene Datensätze verwalten + + + + GeoDonkey settings… + GeoDonkey-Einstellungen … + + + + API key, API address, account and defaults + API-Schlüssel, API-Adresse, Konto und Voreinstellungen + + + + Add last basemap + Letzte Hintergrundkarte hinzufügen + + + + Add the last used GeoDonkey map style as a basemap + Den zuletzt benutzten GeoDonkey-Kartenstil als Hintergrundkarte hinzufügen + + + + GeoDonkey account + GeoDonkey-Konto + + + + Balance, plan and hourly limit of the stored API key + Guthaben, Tarif und Stundenlimit des hinterlegten API-Schlüssels + + + + The full Processing dialog, with all options + Der vollständige Verarbeitungsdialog, mit allen Einstellungen + + + + Basemap “{name}” added. + Hintergrundkarte „{name}“ hinzugefügt. + + + + {tool} (dialog)… + {tool} (Dialog) … + + + + The Processing plugin is not active. + Die Verarbeitungs-Erweiterung ist nicht aktiv. + + + + The tool could not be opened. See the GeoDonkey log for details. + Das Werkzeug ließ sich nicht öffnen. Einzelheiten stehen im GeoDonkey-Protokoll. + + + + The tool '{name}' is not registered. Reload the GeoDonkey plugin, or restart QGIS. + Das Werkzeug „{name}“ ist nicht angemeldet. Laden Sie das GeoDonkey-Plugin neu oder starten Sie QGIS neu. + + + + Elevation data is available for Germany only (longitude {west} to {east}, latitude {south} to {north}). + Höhendaten gibt es nur für Deutschland (Längengrad {west} bis {east}, Breitengrad {south} bis {north}). + + + + Longitude {value} is outside the valid range of −180 to 180. + Der Längengrad {value} liegt außerhalb des gültigen Bereichs von −180 bis 180. + + + + Latitude {value} is outside the valid range of −90 to 90. + Der Breitengrad {value} liegt außerhalb des gültigen Bereichs von −90 bis 90. + + + + The point {lon}, {lat} lies outside. + Der Punkt {lon}, {lat} liegt außerhalb. + + + + start + Start + + + + {km} km · {minutes} minutes + {km} km · {minutes} Minuten + + + + {count} points over {length} m · {low} to {high} m above sea level + {count} Punkte über {length} m · {low} bis {high} m über dem Meer + + + + Blocked by {count} obstacle(s) · {raise_a} m more height at the first point would clear it. + Durch {count} Hindernis(se) versperrt · {raise_a} m mehr Höhe am ersten Punkt würden genügen. + + + + destination + Ziel + + + + stopover + Zwischenstopp + + + + {count} points, no elevation data + {count} Punkte, keine Höhendaten + + + + Clear line of sight over {length} m · {clearance} m to spare. + Freie Sicht über {length} m · {clearance} m Abstand zum Gelände. + + + + Clear line of sight over {length} m. + Freie Sicht über {length} m. + + + + under {limit} % + unter {limit} % + + + + {low} to {high} % + {low} bis {high} % + + + + over {limit} % + über {limit} % + + + + no elevation data + keine Höhendaten + + + + Leg + Abschnitt + + + + Leg {number} + Abschnitt {number} + + + + clear view + freie Sicht + + + + blocked + versperrt + + + + The link returns the data as a GeoJSON file and needs no API key: anyone who has it can download them, and in QGIS it opens directly as a vector layer. + Der Link liefert die Daten als GeoJSON-Datei und braucht keinen API-Schlüssel: Wer ihn hat, kann sie herunterladen – in QGIS lässt er sich direkt als Vektorlayer öffnen. + + + + The link opens the dataset on a map at geodonkey.com - no account and no API key needed. For colleagues working in QGIS, 'Copy data address' gives the direct link to the features instead. + Der Link zeigt den Datensatz auf einer Karte auf geodonkey.com – ohne Konto und ohne API-Schlüssel. Für Kollegen, die in QGIS arbeiten, gibt „Datenadresse kopieren“ stattdessen die direkte Adresse der Objekte. + + + + Free of charge. + Kostenlos. + + + + At most {limit} features per dataset. Larger datasets need an active Pro subscription. + Höchstens {limit} Objekte je Datensatz. Größere Datensätze brauchen ein aktives Pro-Abo. + + + + The file would be {size}; the limit is {limit}. + Die Datei wäre {size} groß; erlaubt sind {limit}. + + + + expired + abgelaufen + + + + {count} feature(s) uploaded. + {count} Objekte hochgeladen. + + + + At most {limit} features per dataset. + Höchstens {limit} Objekte je Datensatz. + + + + {count} feature(s) + {count} Objekte + + + + 1 more day + noch 1 Tag + + + + {coins} DC charged. + {coins} DC abgebucht. + + + + Stored for {days} more day(s). + Liegt noch {days} Tage. + + + + {days} more days + noch {days} Tage + + + + Pick two points on the map. + Zwei Punkte auf der Karte wählen. + + + + Pick points on the map + Punkte auf der Karte wählen + + + + Cancel picking + Auswahl abbrechen + + + + Use these points + Punkte übernehmen + + + + GeoDonkey + GeoDonkey + + + + GeoDonkey result + GeoDonkey-Ergebnis + + + + Pick points on the map. + Punkte auf der Karte wählen. + + + + Click a point on the map. + Einen Punkt auf der Karte anklicken. + + + + No points picked yet. + Noch keine Punkte gewählt. + + + + Keep as layer + Als Layer behalten + + + + Reset + Zurücksetzen + + + + Clear the picked points and the result. The settings above stay as they are. + Entfernt die gesetzten Punkte und das Ergebnis. Die Einstellungen darüber bleiben stehen. + + + + Cancel + Abbrechen + + + + Cancelled. + Abgebrochen. + + + + Points and result cleared. + Punkte und Ergebnis entfernt. + + + + Nothing to keep yet. + Es gibt noch nichts zu behalten. + + + + {count} features added as a layer. + {count} Objekte als Layer hinzugefügt. + + + + {count} points · start {start} + {count} Punkte · Start {start} + + + + Start: {point} + Start: {point} + + + + End: {point} + Ziel: {point} + + + + objects + Objekte + + + + DonkeyOSM + DonkeyOSM + + + + Basemaps + Hintergrundkarten + + + + Tools + Werkzeuge + + + + Upload + Upload + + + + Account + Konto + + + + OpenStreetMap data and map styles, straight into QGIS + OpenStreetMap-Daten und Kartenstile, direkt in QGIS + + + + Search in plain language + In Alltagssprache suchen + + + + Filter by OSM tags + Nach OSM-Merkmalen filtern + + + + Custom query + Eigene Abfrage + + + + bakery, playground, drinking water… + Bäckerei, Spielplatz, Trinkwasser … + + + + One or more everyday words. GeoDonkey translates them into OSM tags. + Ein oder mehrere Wörter aus der Alltagssprache. GeoDonkey übersetzt sie in OSM-Merkmale. + + + + One line per selection: OR between lines, AND inside a line. + Eine Zeile je Auswahl: ODER zwischen den Zeilen, UND innerhalb einer Zeile. + + + + Current map view + Aktueller Kartenausschnitt + + + + Extent of a layer + Ausdehnung eines Layers + + + + Extent of the selected features + Ausdehnung der ausgewählten Objekte + + + + Outline of the selected polygons + Umriss der ausgewählten Flächen + + + + Run query + Abfrage starten + + + + Free of charge and without an API key. + Kostenlos und ohne API-Schlüssel. + + + + Add as basemap + Als Hintergrundkarte hinzufügen + + + + Reload style list + Stilliste neu laden + + + + API key and settings… + API-Schlüssel und Einstellungen … + + + + Not checked yet. + Noch nicht geprüft. + + + + Check account + Konto prüfen + + + + Checking… + Wird geprüft … + + + + GeoDonkey: checking account + GeoDonkey: Konto wird geprüft + + + + GeoDonkey: loading map styles + GeoDonkey: Kartenstile werden geladen + + + + Querying DonkeyOSM… + DonkeyOSM wird abgefragt … + + + + GeoDonkey: DonkeyOSM query + GeoDonkey: DonkeyOSM-Abfrage + + + + What are you looking for? + Wonach suchen Sie? + + + + Where? + Wo? + + + + Maximum objects + Höchstzahl der Objekte + + + + API key + API-Schlüssel + + + + Plan and balance + Tarif und Guthaben + + + + Pick a layer for the area first. + Wählen Sie zuerst einen Layer für das Gebiet. + + + + No API key stored. + Kein API-Schlüssel hinterlegt. + + + + Settings saved. + Einstellungen gespeichert. + + + + Store an API key first. + Hinterlegen Sie zuerst einen API-Schlüssel. + + + + API key is valid. + Der API-Schlüssel gilt. + + + + Pick a map style first. + Wählen Sie zuerst einen Kartenstil. + + + + Enter a search term first. + Geben Sie zuerst einen Suchbegriff ein. + + + + Up to {count} tags, separated by commas. All of them must match. + Bis zu {count} Merkmale, durch Kommas getrennt. Alle müssen zutreffen. + + + + Manage keys on geodonkey.com + Schlüssel auf geodonkey.com verwalten + + + + No polygon layer in the project + Kein Flächenlayer im Projekt + + + + No vector layer in the project + Kein Vektorlayer im Projekt + + + + This query costs {coins} DC. + Diese Abfrage kostet {coins} DC. + + + + Without an API key only the hourly free calls are available. + Ohne API-Schlüssel stehen nur die Freiaufrufe dieser Stunde zur Verfügung. + + + + (temporary) + (zeitlich begrenzt) + + + + No objects found in that area. + In diesem Gebiet wurde nichts gefunden. + + + + {left} of {total} free calls left this hour. + Noch {left} von {total} Freiaufrufen in dieser Stunde. + + + + Balance: {coins} DC. + Guthaben: {coins} DC. + + + + API key: {key} + API-Schlüssel: {key} + + + + {count} map styles available. + {count} Kartenstile verfügbar. + + + + unknown account + unbekanntes Konto + + + + Plan: {plan} + Tarif: {plan} + + + + Balance: {coins} DC + Guthaben: {coins} DC + + + + Rate limit: {hour} per hour + Aufruflimit: {hour} je Stunde + + + + GeoDonkey settings + GeoDonkey-Einstellungen + + + + Show + Zeigen + + + + API address + API-Adresse + + + + Default maximum objects + Vorgabe für die Höchstzahl + + + + Test key + Schlüssel testen + + + + Remove key + Schlüssel entfernen + + + + Key removed. + Schlüssel entfernt. + + + + An API key unlocks DonkeyOSM queries. The map styles work without one. + Ein API-Schlüssel schaltet die DonkeyOSM-Abfragen frei. Die Kartenstile gehen auch ohne. + + + + The key is stored encrypted in the QGIS authentication database. + Der Schlüssel liegt verschlüsselt in der Authentifizierungsdatenbank von QGIS. + + + + The QGIS authentication database is locked or unavailable. The key will only be kept until QGIS is closed – it is never written in plain text. + Die Authentifizierungsdatenbank von QGIS ist gesperrt oder nicht verfügbar. Der Schlüssel gilt dann nur bis zum Beenden von QGIS – im Klartext wird er nie gespeichert. + + + + Enter a key first. + Geben Sie zuerst einen Schlüssel ein. + + + + Key works · {email} · {tier} · {coins} DC + Schlüssel gilt · {email} · {tier} · {coins} DC + + + + The key could not be stored in the QGIS authentication database. + +It will be used for this session and is forgotten when QGIS closes. GeoDonkey never writes the key to disk in plain text. + +To keep it permanently, set a master password under Settings ▸ Options ▸ Authentication. + Der Schlüssel konnte nicht in der Authentifizierungsdatenbank von QGIS abgelegt werden. + +Er gilt für diese Sitzung und ist vergessen, sobald QGIS beendet wird. GeoDonkey schreibt den Schlüssel nie im Klartext auf die Festplatte. + +Damit er dauerhaft bleibt, vergeben Sie ein Hauptpasswort unter Einstellungen ▸ Optionen ▸ Authentifizierung. + + + + Get a key + Schlüssel holen + + + + That does not look like a GeoDonkey key. Keys start with {prefixes}. + Das sieht nicht nach einem GeoDonkey-Schlüssel aus. Schlüssel beginnen mit {prefixes}. + + + + Only the selected features + Nur die ausgewählten Objekte + + + + Upload layer + Layer hochladen + + + + Not loaded yet. + Noch nicht geladen. + + + + Refresh + Aktualisieren + + + + Discard + Verwerfen + + + + Select a dataset to see its link. + Wählen Sie einen Datensatz, um seinen Link zu sehen. + + + + Copy link + Link kopieren + + + + Open in browser + Im Browser öffnen + + + + Copy data address + Datenadresse kopieren + + + + Load as layer + Als Layer laden + + + + GeoDonkey: upload + GeoDonkey: Upload + + + + Loading… + Wird geladen… + + + + GeoDonkey: datasets + GeoDonkey: Datensätze + + + + Link copied to the clipboard. + Link in die Zwischenablage kopiert. + + + + Data address copied to the clipboard. + Datenadresse in die Zwischenablage kopiert. + + + + Loading dataset… + Datensatz wird geladen… + + + + GeoDonkey: load dataset + GeoDonkey: Datensatz laden + + + + GeoDonkey: discard dataset + GeoDonkey: Datensatz verwerfen + + + + New dataset + Neuer Datensatz + + + + Layer: + Layer: + + + + Keep for: + Speichern für: + + + + days + Tage + + + + My datasets + Meine Datensätze + + + + Pass it on + Weitergeben + + + + No vector layer in this project. + In diesem Projekt gibt es keinen Vektorlayer. + + + + Datasets can only be listed with an API key. + Datensätze lassen sich nur mit einem API-Schlüssel auflisten. + + + + Dataset discarded. + Datensatz verworfen. + + + + Uploading {name} ({size})… + {name} ({size}) wird hochgeladen… + + + + {count} of {limit} datasets in use. + {count} von {limit} Datensätzen belegt. + + + + That dataset has no features. + Dieser Datensatz enthält keine Objekte. + + + + Only the selected features ({count}) + Nur die Auswahl ({count} Objekte) + + + + This upload costs {coins} DC. + Dieser Upload kostet {coins} DC. + + + + Up to {count} features are free of charge. + Bis {count} Objekte kostenlos. + + + + {count} feature(s) loaded. + {count} Objekte geladen. + + + + GeoDonkey: point elevation + GeoDonkey: Punkthöhen + + + + Another point, or right-click to finish. + Noch ein Punkt, oder mit einem Rechtsklick beenden. + + + + X/Y in WGS 84 · degrees + X/Y in WGS 84 · Grad + + + + X/Y in the map CRS + X/Y im KBS der Karte + + + + Remove point + Punkt entfernen + + + + Remove the selected point from the list. A right-click on the row or the Delete key does the same. + Entfernt den ausgewählten Punkt aus der Liste. Ein Rechtsklick auf die Zeile oder die Entf-Taste tun dasselbe. + + + + Look up elevations + Höhen abrufen + + + + Looking up the elevations… + Höhen werden ermittelt … + + + + Point removed. + Punkt entfernt. + + + + X + X + + + + Y + Y + + + + Z (m) + Z (m) + + + + {coins} DC per run · up to {limit} points + {coins} DC je Lauf · bis zu {limit} Punkte + + + + Pick at least one point on the map. + Wählen Sie mindestens einen Punkt auf der Karte. + + + + The service returned no elevations. + Der Dienst hat keine Höhen geliefert. + + + + {low} m to {high} m · {span} m difference + {low} m bis {high} m · {span} m Unterschied + + + + {count} points picked. + {count} Punkte gewählt. + + + + No elevation data here. + Hier gibt es keine Höhendaten. + + + + {height} m above sea level + {height} m über dem Meer + + + + {missing} of {count} points have no elevation data. + {missing} von {count} Stützpunkten haben keine Höhendaten. + + + + {count} elevation(s) found. + {count} Höhe(n) ermittelt. + + + + X/Y in {crs} + X/Y in {crs} + + + + Pick the centre on the map + Mittelpunkt auf der Karte wählen + + + + GeoDonkey: isochrone + GeoDonkey: Isochrone + + + + on foot + zu Fuß + + + + by bike + mit dem Rad + + + + by car + mit dem Auto + + + + Click the centre point on the map. + Mittelpunkt auf der Karte anklicken. + + + + Travel: + Unterwegs: + + + + Measured in: + Gemessen in: + + + + Rings: + Ringe: + + + + Calculating the isochrone… + Isochrone wird berechnet … + + + + {coins} DC per run, regardless of the number of rings + {coins} DC je Lauf, unabhängig von der Zahl der Ringe + + + + Pick the centre on the map first. + Wählen Sie zuerst den Mittelpunkt auf der Karte. + + + + Enter at least one ring, for example 5,10,15. + Geben Sie mindestens einen Ring an, zum Beispiel 5,10,15. + + + + The service returned no area. + Der Dienst hat keine Fläche geliefert. + + + + {count} ring(s): {list} + {count} Ring(e): {list} + + + + {count} ring(s) calculated. + {count} Ring(e) berechnet. + + + + Pick two points on the map + Zwei Punkte auf der Karte wählen + + + + GeoDonkey: elevation profile + GeoDonkey: Höhenprofil + + + + Rough + Grob + + + + Normal + Mittel + + + + Fine + Fein + + + + Click the start point on the map. + Startpunkt auf der Karte anklicken. + + + + Click the end point on the map. + Endpunkt auf der Karte anklicken. + + + + Calculating the elevation profile… + Höhenprofil wird berechnet… + + + + Calculating… + Wird berechnet… + + + + Detail: + Auflösung: + + + + Up to {count} points · {coins} DC per run + Bis zu {count} Punkte · {coins} DC je Lauf + + + + Pick two points on the map first. + Erst zwei Punkte auf der Karte wählen. + + + + The service returned no points. + Der Dienst hat keine Punkte geliefert. + + + + Ascent {up} m · descent {down} m + Anstieg {up} m · Abstieg {down} m + + + + Pick the route on the map + Route auf der Karte klicken + + + + GeoDonkey: route + GeoDonkey: Route + + + + Click the destination – or further stopovers. + Ziel anklicken – oder weitere Zwischenstopps. + + + + Another stopover, or right-click to finish. + Noch ein Zwischenstopp, oder mit einem Rechtsklick beenden. + + + + Find the shortest order + Kürzeste Reihenfolge suchen + + + + Include turn-by-turn directions + Wegbeschreibung mitliefern + + + + Calculating the route… + Route wird berechnet … + + + + {coins} DC per run · 2 to {limit} points + {coins} DC je Lauf · 2 bis {limit} Punkte + + + + The service returned no route. + Der Dienst hat keine Route geliefert. + + + + {legs} leg(s) · {stops} stop(s) + {legs} Abschnitt(e) · {stops} Haltepunkt(e) + + + + GeoDonkey: line of sight + GeoDonkey: Sichtverbindung + + + + Click the first point on the map. + Ersten Punkt auf der Karte anklicken. + + + + Click the second point on the map. + Zweiten Punkt auf der Karte anklicken. + + + + Height at A: + Höhe an A: + + + + Height at B: + Höhe an B: + + + + Account for earth curvature + Erdkrümmung berücksichtigen + + + + Checking the line of sight… + Sichtverbindung wird geprüft … + + + + {distance} m air line · {coins} DC + {distance} m Luftlinie · {coins} DC + + + + No terrain samples returned. + Es kamen keine Stützpunkte zurück. + + + + Free up to {limit} m air line, {coins} DC above + Bis {limit} m Luftlinie kostenlos, darüber {coins} DC + + + + {distance} m air line · free + {distance} m Luftlinie · kostenlos + + + + <p><b>Every run costs {coins} DonkeyCoins</b> once the {free} free calls of the current hour are used up. The API key is taken from the plugin settings (Web ▸ GeoDonkey ▸ GeoDonkey settings); without a key only the free calls are available.</p> + <p><b>Jeder Lauf kostet {coins} DonkeyCoins</b>, sobald die {free} Freiaufrufe der laufenden Stunde verbraucht sind. Der API-Schlüssel kommt aus den Einstellungen des Plugins (Web ▸ GeoDonkey ▸ GeoDonkey-Einstellungen); ohne Schlüssel stehen nur die Freiaufrufe zur Verfügung.</p> + + + + No API key stored – only the free calls of this hour are available. Add a key under Web ▸ GeoDonkey ▸ GeoDonkey settings. + Kein API-Schlüssel hinterlegt – es stehen nur die Freiaufrufe dieser Stunde zur Verfügung. Schlüssel eintragen unter Web ▸ GeoDonkey ▸ GeoDonkey-Einstellungen. + + + + Charged: {coins} DC · balance {balance} DC + Abgebucht: {coins} DC · Guthaben {balance} DC + + + + {count} features without geometry were skipped. + {count} Objekte ohne Geometrie wurden übersprungen. + + + + Free call · {count} left this hour + Freiaufruf · {count} verbleiben in dieser Stunde + + + + Add elevation to points + Höhen für Punkte ergänzen + + + + <p>Looks up the elevation above sea level for every point of a layer and writes it into three new fields: <code>elevation</code>, <code>ele_source</code> and <code>ele_state</code>. Geometry and existing fields are kept unchanged.</p><p>Layers with more than {max_points} points are split into several calls automatically. That does not cost extra: the price follows the number of points, not the number of calls.</p><p><b>Elevation data is available for Germany only.</b> Points outside keep their place in the layer, get an empty elevation and <code>{outside}</code> in <code>ele_state</code> – a single point abroad does not abort the run.</p><p><b>The price follows the quantity:</b> {coins} DonkeyCoins per started {batch} points, once the {free} free calls of the current hour are used up.</p><p>Elevation data by the surveying authorities of the German federal states; the exact source of every point is in <code>ele_source</code>.</p> + <p>Schlägt für jeden Punkt eines Layers die Höhe über dem Meer nach und schreibt sie in drei neue Felder: <code>elevation</code>, <code>ele_source</code> und <code>ele_state</code>. Geometrie und vorhandene Felder bleiben unverändert.</p><p>Layer mit mehr als {max_points} Punkten werden selbsttätig auf mehrere Aufrufe verteilt. Das kostet nichts zusätzlich: Der Preis folgt der Zahl der Punkte, nicht der Zahl der Aufrufe.</p><p><b>Höhendaten gibt es nur für Deutschland.</b> Punkte außerhalb behalten ihren Platz im Layer, bekommen eine leere Höhe und <code>{outside}</code> in <code>ele_state</code> – ein einzelner Punkt im Ausland bricht den Lauf nicht ab.</p><p><b>Der Preis folgt der Menge:</b> {coins} DonkeyCoins je angefangene {batch} Punkte, sobald die {free} Freiaufrufe der laufenden Stunde verbraucht sind.</p><p>Höhendaten der Landesvermessungsämter; die genaue Quelle jedes Punkts steht in <code>ele_source</code>.</p> + + + + Point layer + Punktlayer + + + + Points with elevation + Punkte mit Höhe + + + + The input layer could not be read. + Der Eingabelayer konnte nicht gelesen werden. + + + + The layer contains no usable points. + Der Layer enthält keine brauchbaren Punkte. + + + + The output could not be created. + Die Ausgabe konnte nicht angelegt werden. + + + + {known} of {count} points have an elevation. + {known} von {count} Punkten haben eine Höhe. + + + + {count} points lie outside Germany and get no elevation. + {count} Punkte liegen außerhalb Deutschlands und bekommen keine Höhe. + + + + Batch {number} of {total} · {count} points + Teil {number} von {total} · {count} Punkte + + + + The service returned {got} elevations for {sent} points. + Der Dienst hat {got} Höhen für {sent} Punkte zurückgegeben. + + + + <p>Samples the terrain along the straight line between two points and returns one point per sample, carrying the distance from the start and the elevation above sea level.</p><p>The service places the samples on the centres of its elevation tiles. <b>Maximum points</b> is the upper limit (at most {max_points}), <b>Minimum spacing</b> the smallest distance between two samples (at least {min_step} m).</p><p>Samples without elevation data keep their place in the list and have an empty <code>elevation</code>. Dropping them would tear the distance axis apart.</p><p><b>Elevation data is available for Germany only.</b> Points outside are rejected before the call is sent.</p><p><b>The price follows the quantity:</b> {coins} DonkeyCoins per started {batch} points of <i>Maximum points</i> – {max_points} points therefore cost {full} DC, once the {free} free calls of the current hour are used up.</p><p>Elevation data by the surveying authorities of the German federal states; the exact source of every sample is in the field <code>source</code>.</p> + <p>Tastet das Gelände entlang der Geraden zwischen zwei Punkten ab und gibt je Stützpunkt einen Punkt zurück, mit der Entfernung vom Start und der Höhe über dem Meer.</p><p>Die Stützpunkte setzt der Dienst auf die Mittelpunkte seiner Höhenkacheln. <b>Höchstzahl der Stützpunkte</b> ist die Obergrenze (höchstens {max_points}), <b>Kleinster Abstand</b> der geringste Abstand zweier Stützpunkte (mindestens {min_step} m).</p><p>Stützpunkte ohne Höhendaten behalten ihren Platz in der Liste und haben eine leere <code>elevation</code>. Sie wegzulassen würde die Entfernungsachse zerreißen.</p><p><b>Höhendaten gibt es nur für Deutschland.</b> Punkte außerhalb werden abgewiesen, bevor der Aufruf abgeht.</p><p><b>Der Preis folgt der Menge:</b> {coins} DonkeyCoins je angefangene {batch} Stützpunkte der <i>Höchstzahl</i> – {max_points} Stützpunkte kosten also {full} DC, sobald die {free} Freiaufrufe der laufenden Stunde verbraucht sind.</p><p>Höhendaten der Landesvermessungsämter; die genaue Quelle jedes Stützpunkts steht im Feld <code>source</code>.</p> + + + + Start point + Startpunkt + + + + End point + Endpunkt + + + + Maximum points + Höchstzahl der Stützpunkte + + + + Minimum spacing (metres) + Kleinster Abstand (Meter) + + + + Sections by gradient (optional) + Abschnitte nach Steigung (optional) + + + + Up to {count} points · {coins} DC + Bis zu {count} Stützpunkte · {coins} DC + + + + Isochrone (reachable area) + Isochrone (erreichbares Gebiet) + + + + Travel mode + Verkehrsmittel + + + + Measure + Maß + + + + Contours (comma separated) + Ringe (durch Komma getrennt) + + + + Reachable area + Erreichbares Gebiet + + + + No reachable area was returned for this point. + Für diesen Punkt kam kein erreichbares Gebiet zurück. + + + + <p>Calculates the area that can be reached from a point within a given travel time or distance, using the road network – not a circle around the point.</p><p><b>Contours</b> is a comma separated list, for example <code>5,10,15</code>. Up to {rings} rings are calculated in a single call and cost the same as one: travel time from {min_min} to {max_min} minutes, distance from {min_km} to {max_km} kilometres.</p><p>The rings are returned from the largest to the smallest, so that drawing them in that order keeps all of them visible. The field <code>label</code> holds the ring as readable text, for example <code>10 min</code>.</p><p>Data © OpenStreetMap contributors, ODbL.</p> + <p>Berechnet das Gebiet, das von einem Punkt aus in einer bestimmten Fahrzeit oder Entfernung erreichbar ist – im Straßennetz und nicht als Kreis um den Punkt.</p><p><b>Ringe</b> ist eine durch Komma getrennte Liste, etwa <code>5,10,15</code>. Bis zu {rings} Ringe werden in einem einzigen Aufruf berechnet und kosten so viel wie einer: Fahrzeit von {min_min} bis {max_min} Minuten, Entfernung von {min_km} bis {max_km} Kilometern.</p><p>Die Ringe kommen vom größten zum kleinsten zurück; in dieser Reihenfolge gezeichnet bleiben alle sichtbar. Das Feld <code>label</code> nennt den Ring als lesbaren Text, etwa <code>10 min</code>.</p><p>Daten © OpenStreetMap-Mitwirkende, ODbL.</p> + + + + {count} rings written. + {count} Ringe geschrieben. + + + + Walking + Zu Fuß + + + + Driving + Mit dem Auto + + + + Cycling + Mit dem Rad + + + + Travel time (minutes) + Fahrzeit (Minuten) + + + + Distance (kilometres) + Entfernung (Kilometer) + + + + <p>Checks whether there is a clear line of sight between two points, using the terrain model including earth curvature and atmospheric refraction.</p><p><b>Height above ground</b> is the height of the eye, the mast or the roof edge at each end, from 0 to {max_height} m. If the sight is blocked, the fields <code>raise_a</code> and <code>raise_b</code> say how much higher one end would have to be.</p><p>Three outputs: the <b>sight line</b> with the result in its attributes, the <b>obstacles</b> as points at the spot where the terrain rises highest above the ray, and optionally <b>every sample</b> with terrain, ray and clearance – the basis for a profile chart of your own.</p><p><b>Refraction factor k</b> is {k_default} for the standard atmosphere. <code>k = 1</code> applies earth curvature without refraction; switching curvature off applies neither.</p><p><b>Elevation data is available for Germany only.</b></p><p><b>Up to {free_metres} m of straight-line distance a run is free</b>, above that it costs {coins} DonkeyCoins. This endpoint has its own allowance of {free_calls} calls per hour, replacing the shared one – after that it requires an API key, as the only tool in this plugin.</p><p>Elevation data by the surveying authorities of the German federal states.</p> + <p>Prüft am Geländemodell, ob zwischen zwei Punkten freie Sicht besteht – mit Erdkrümmung und atmosphärischer Brechung.</p><p><b>Höhe über Grund</b> ist die Höhe des Auges, des Masts oder der Dachkante an jedem Ende, von 0 bis {max_height} m. Ist die Sicht versperrt, nennen die Felder <code>raise_a</code> und <code>raise_b</code>, um wie viel höher ein Ende stehen müsste.</p><p>Drei Ausgaben: die <b>Sichtlinie</b> mit dem Ergebnis in ihren Attributen, die <b>Hindernisse</b> als Punkte an der Stelle, an der das Gelände am weitesten über den Strahl ragt, und auf Wunsch <b>jeder Stützpunkt</b> mit Gelände, Strahl und Abstand – die Grundlage für ein eigenes Profildiagramm.</p><p><b>Der Refraktionsfaktor k</b> ist {k_default} für die Standardatmosphäre. <code>k = 1</code> rechnet die Erdkrümmung ohne Brechung; ohne Erdkrümmung entfällt beides.</p><p><b>Höhendaten gibt es nur für Deutschland.</b></p><p><b>Bis {free_metres} m Luftlinie ist ein Lauf kostenlos</b>, darüber kostet er {coins} DonkeyCoins. Dieser Endpunkt hat ein eigenes Kontingent von {free_calls} Aufrufen je Stunde an Stelle des gemeinsamen – danach verlangt er einen API-Schlüssel, als einziges Werkzeug dieses Plugins.</p><p>Höhendaten der Landesvermessungsämter.</p> + + + + Observer point + Standpunkt + + + + Target point + Zielpunkt + + + + Height above ground at the observer (metres) + Höhe über Grund am Standpunkt (Meter) + + + + Height above ground at the target (metres) + Höhe über Grund am Zielpunkt (Meter) + + + + Refraction factor k + Refraktionsfaktor k + + + + Maximum samples + Höchstzahl der Stützpunkte + + + + Sight line + Sichtlinie + + + + Obstacles + Hindernisse + + + + Sections by visibility (optional) + Abschnitte nach Sicht (optional) + + + + Samples (optional) + Stützpunkte (optional) + + + + <p>Queries OpenStreetMap data through the DonkeyOSM service of geodonkey.com and returns it as three layers: points, lines and areas.</p><p><b>Search mode</b> decides how the query text is read: as everyday words, as a comma separated list of OSM tags (<code>shop=bakery,amenity=cafe</code>), or as a DonkeyOSM line query (one selection per line).</p><p><b>Every run costs {coins} DonkeyCoins</b> once the free calls of the current hour are used up. The API key is taken from the plugin settings.</p><p>All outputs share the same five fields: <code>osm_type</code>, <code>osm_id</code>, <code>osm_url</code>, <code>name</code> and <code>tags</code>. <code>tags</code> holds the complete OSM tags as JSON text, so the schema stays the same no matter what the query finds.</p><p>Data © OpenStreetMap contributors, ODbL.</p> + <p>Fragt OpenStreetMap-Daten über den DonkeyOSM-Dienst von geodonkey.com ab und gibt sie als drei Layer zurück: Punkte, Linien und Flächen.</p><p><b>Die Suchart</b> bestimmt, wie der Abfragetext gelesen wird: als Wörter der Alltagssprache, als durch Kommas getrennte Liste von OSM-Merkmalen (<code>shop=bakery,amenity=cafe</code>) oder als DonkeyOSM-Zeilenabfrage (eine Auswahl je Zeile).</p><p><b>Jeder Lauf kostet {coins} DonkeyCoins</b>, sobald die Freiaufrufe der laufenden Stunde verbraucht sind. Der API-Schlüssel kommt aus den Einstellungen des Plugins.</p><p>Alle Ausgaben haben dieselben fünf Felder: <code>osm_type</code>, <code>osm_id</code>, <code>osm_url</code>, <code>name</code> und <code>tags</code>. In <code>tags</code> stehen die vollständigen OSM-Merkmale als JSON-Text – so bleibt das Schema gleich, egal was die Abfrage findet.</p><p>Daten © OpenStreetMap-Mitwirkende, ODbL.</p> + + + + Search mode + Suchart + + + + Query + Abfrage + + + + Area + Gebiet + + + + OSM element types (node, way, relation) + OSM-Elementarten (node, way, relation) + + + + The area is empty. + Das Gebiet ist leer. + + + + Plain language + Alltagssprache + + + + OSM tags + OSM-Merkmale + + + + Custom line query + Eigene Zeilenabfrage + + + + The limit of {limit} was reached – the result is incomplete. + Die Grenze von {limit} wurde erreicht – das Ergebnis ist unvollständig. + + + + {count} objects without geometry were skipped. + {count} Objekte ohne Geometrie wurden übergangen. + + + + GeoDonkey – OpenStreetMap, routing, elevation and map styles + GeoDonkey – OpenStreetMap, Routing, Höhendaten und Kartenstile + + + + <p>Calculates a route from the start through any stopovers to the destination and returns two layers: the driven legs as lines and the stops as points.</p><p><b>Stopovers</b> is an optional point layer. Its features are visited in the order of the layer. Start, stopovers and destination together may be at most {max_points} points.</p><p><b>Optimise stopover order</b> searches for the shortest order of the stopovers; start and destination stay where they are. The field <code>stop</code> then holds the driven order and <code>input</code> the order as entered.</p><p><b>Turn-by-turn directions</b> adds the instructions of each leg to the field <code>directions</code>.</p><p>Maximum total length: {walking} km walking, {cycling} km cycling, {driving} km driving.</p><p>Data © OpenStreetMap contributors, ODbL.</p><p><b>A run costs {plain} DonkeyCoins, {optimized} with optimised stopover order</b>, once the {free} free calls of the current hour are used up. The API key is taken from the plugin settings (Web ▸ GeoDonkey ▸ GeoDonkey settings).</p> + <p>Berechnet eine Route vom Start über beliebige Zwischenstopps zum Ziel und gibt zwei Layer zurück: die gefahrenen Abschnitte als Linien und die Haltepunkte als Punkte.</p><p><b>Zwischenstopps</b> ist ein optionaler Punktlayer. Seine Objekte werden in der Reihenfolge des Layers angefahren. Start, Zwischenstopps und Ziel zusammen dürfen höchstens {max_points} Punkte sein.</p><p><b>Reihenfolge der Zwischenstopps optimieren</b> sucht die kürzeste Reihenfolge der Zwischenstopps; Start und Ziel bleiben stehen. Das Feld <code>stop</code> nennt danach die gefahrene Reihenfolge und <code>input</code> die eingegebene.</p><p><b>Abbiegehinweise</b> legt die Anweisungen jedes Abschnitts in das Feld <code>directions</code>.</p><p>Größte Gesamtstrecke: {walking} km zu Fuß, {cycling} km mit dem Rad, {driving} km mit dem Auto.</p><p>Daten © OpenStreetMap-Mitwirkende, ODbL.</p><p><b>Ein Lauf kostet {plain} DonkeyCoins, mit optimierter Reihenfolge {optimized}</b>, sobald die {free} Freiaufrufe der laufenden Stunde verbraucht sind. Der API-Schlüssel kommt aus den Einstellungen des Plugins (Web ▸ GeoDonkey ▸ GeoDonkey-Einstellungen).</p> + + + + Start + Start + + + + Destination + Ziel + + + + Stopovers (optional point layer) + Zwischenstopps (optionaler Punktlayer) + + + + Optimise stopover order + Reihenfolge der Zwischenstopps optimieren + + + + Turn-by-turn directions + Abbiegehinweise + + + + Language of the directions + Sprache der Abbiegehinweise + + + + Stops + Haltepunkte + + + + {count} points · {mode} + {count} Punkte · {mode} + + + + Follow QGIS + Wie QGIS + + + + German + Deutsch + + + + English + Englisch + + + + French + Französisch + + + + Spanish + Spanisch + + + API key, API address and defaults + API-Schlüssel, API-Adresse und Vorgaben + + + Add GeoDonkey basemap + GeoDonkey-Hintergrundkarte hinzufügen + + + Anyone with this link can download the data — no API key needed. + Wer diesen Link hat, kann die Daten herunterladen – ohne API-Schlüssel. + + + Click the start point, then the end point. Esc cancels. + Erst den Startpunkt anklicken, dann den Endpunkt. Esc bricht ab. + + + Elevation profile (dialog)… + Höhenprofil (Dialog)… + + + GeoDonkey panel + GeoDonkey-Bedienfeld + + + GeoDonkey – OpenStreetMap data and map styles + GeoDonkey – OpenStreetMap-Daten und Kartenstile + + + Map styles + Kartenstile + + + Open the GeoDonkey panel: DonkeyOSM queries, basemaps, account + Das GeoDonkey-Bedienfeld öffnen: DonkeyOSM-Abfragen, Hintergrundkarten, Konto + + + OpenStreetMap + OpenStreetMap + + + Profile + Profil + + + Stop picking + Auswahl beenden + + + The full Processing dialog, with spacing and output options + Der vollständige Processing-Dialog, mit Mindestabstand und Ausgabeoptionen + + + Tool: + Werkzeug: + + + {count} profile points added as a layer. + {count} Profilpunkte als Layer hinzugefügt. + + + {point} · no elevation data + {point} · keine Höhendaten + + + {point} · {height} m + {point} · {height} m + + + diff --git a/geodonkey/icons/account.svg b/geodonkey/icons/account.svg new file mode 100644 index 0000000..a3302d9 --- /dev/null +++ b/geodonkey/icons/account.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/geodonkey/icons/basemap.svg b/geodonkey/icons/basemap.svg new file mode 100644 index 0000000..4c2aa96 --- /dev/null +++ b/geodonkey/icons/basemap.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/geodonkey/icons/elevation.svg b/geodonkey/icons/elevation.svg new file mode 100644 index 0000000..7c99251 --- /dev/null +++ b/geodonkey/icons/elevation.svg @@ -0,0 +1,8 @@ + + + + + + + diff --git a/geodonkey/icons/geodonkey.svg b/geodonkey/icons/geodonkey.svg new file mode 100644 index 0000000..40f5ef5 --- /dev/null +++ b/geodonkey/icons/geodonkey.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/geodonkey/icons/isochrone.svg b/geodonkey/icons/isochrone.svg new file mode 100644 index 0000000..534f356 --- /dev/null +++ b/geodonkey/icons/isochrone.svg @@ -0,0 +1,11 @@ + + + + + + + + + + diff --git a/geodonkey/icons/lineofsight.svg b/geodonkey/icons/lineofsight.svg new file mode 100644 index 0000000..9d0a524 --- /dev/null +++ b/geodonkey/icons/lineofsight.svg @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/geodonkey/icons/osm.svg b/geodonkey/icons/osm.svg new file mode 100644 index 0000000..e2af34c --- /dev/null +++ b/geodonkey/icons/osm.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/geodonkey/icons/profile.svg b/geodonkey/icons/profile.svg new file mode 100644 index 0000000..07980c5 --- /dev/null +++ b/geodonkey/icons/profile.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + diff --git a/geodonkey/icons/route.svg b/geodonkey/icons/route.svg new file mode 100644 index 0000000..1d86c7f --- /dev/null +++ b/geodonkey/icons/route.svg @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/geodonkey/icons/tools.svg b/geodonkey/icons/tools.svg new file mode 100644 index 0000000..2c6ddbb --- /dev/null +++ b/geodonkey/icons/tools.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/geodonkey/icons/upload.svg b/geodonkey/icons/upload.svg new file mode 100644 index 0000000..ae23498 --- /dev/null +++ b/geodonkey/icons/upload.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/geodonkey/layers.py b/geodonkey/layers.py new file mode 100644 index 0000000..a2377da --- /dev/null +++ b/geodonkey/layers.py @@ -0,0 +1,175 @@ +from __future__ import annotations + +import os +import tempfile +from typing import Any, Dict, List, Mapping, Optional, Tuple + +from qgis.core import ( + QgsCategorizedSymbolRenderer, + QgsFillSymbol, + QgsLayerMetadata, + QgsLineSymbol, + QgsMarkerSymbol, + QgsProject, + QgsRendererCategory, + QgsSingleSymbolRenderer, + QgsVectorLayer, +) +from qgis.PyQt.QtGui import QColor + +from . import config, geojson, style +from .compat import pixels +from .errors import GeoDonkeyError +from .i18n import tr + +GROUP_LABEL = { + "Point": tr("points"), + "Line": tr("lines"), + "Polygon": tr("areas"), +} + + +def result_folder() -> str: + folder = os.path.join(tempfile.gettempdir(), "geodonkey-qgis") + if not os.path.isdir(folder): + os.makedirs(folder) + return folder + + +def _colour(value: str, opacity: float = 1.0) -> QColor: + colour = QColor(value) + if not colour.isValid(): + colour = QColor(style.HOUSE) + colour.setAlphaF(max(0.0, min(1.0, float(opacity)))) + return colour + + +def _symbol(geometry: str, value: str): + if geometry == "Point": + symbol = QgsMarkerSymbol.createSimple({"name": "circle"}) + symbol.setColor(_colour(value, style.POINT_OPACITY)) + symbol.setSize(style.POINT_SIZE) + symbol.setSizeUnit(pixels()) + layer_zero = symbol.symbolLayer(0) + if layer_zero is not None: + layer_zero.setStrokeColor(_colour(value)) + layer_zero.setStrokeWidth(style.POINT_OUTLINE) + layer_zero.setStrokeWidthUnit(pixels()) + return symbol + + if geometry == "Line": + symbol = QgsLineSymbol.createSimple({}) + symbol.setColor(_colour(value)) + symbol.setWidth(style.LINE_WIDTH) + symbol.setWidthUnit(pixels()) + return symbol + + symbol = QgsFillSymbol.createSimple({}) + symbol.setColor(_colour(value, style.AREA_OPACITY)) + layer_zero = symbol.symbolLayer(0) + if layer_zero is not None: + layer_zero.setStrokeColor(_colour(value)) + layer_zero.setStrokeWidth(style.AREA_OUTLINE) + layer_zero.setStrokeWidthUnit(pixels()) + return symbol + + +def apply_style(layer: QgsVectorLayer, rule: Optional[Mapping[str, Any]]) -> bool: + if layer is None or not rule: + return False + geometry = str(rule.get("geometry") or "") + try: + if rule.get("kind") == "categories": + categories = [] + for entry in rule.get("entries") or []: + categories.append(QgsRendererCategory( + entry.get("value"), _symbol(geometry, str(entry.get("color") or "")), + str(entry.get("label") or ""))) + if not categories: + return False + renderer = QgsCategorizedSymbolRenderer(str(rule.get("field") or ""), + categories) + else: + renderer = QgsSingleSymbolRenderer( + _symbol(geometry, str(rule.get("color") or style.HOUSE))) + layer.setRenderer(renderer) + layer.triggerRepaint() + return True + except Exception: + return False + + +def _properties(part: Mapping[str, Any]) -> List[Mapping[str, Any]]: + out: List[Mapping[str, Any]] = [] + for feature in (part or {}).get("features") or []: + props = (feature or {}).get("properties") + if isinstance(props, Mapping): + out.append(props) + return out + + +def _apply_metadata(layer: QgsVectorLayer, meta: Mapping[str, Any], + query: str, area_text: str) -> None: + md = QgsLayerMetadata() + md.setTitle(layer.name()) + rights = [] + credit = geojson.attribution(meta, config.DEFAULT_ATTRIBUTION) + if credit: + rights.append(credit) + licence = meta.get("license") or config.OSM_LICENSE + if licence: + rights.append(str(licence)) + md.setRights(rights) + md.setLicenses([str(meta.get("license") or config.OSM_LICENSE)]) + + lines = [tr("Retrieved from GeoDonkey (DonkeyOSM).")] + if query: + lines.append(tr("Query: {query}").format(query=query)) + if area_text: + lines.append(tr("Area: {area}").format(area=area_text)) + if meta.get("data_updated_at"): + lines.append(tr("Data status: {stamp}").format(stamp=meta["data_updated_at"])) + if meta.get("truncated"): + lines.append(tr("Incomplete: the limit of {limit} was reached.").format( + limit=meta.get("limit") or "?")) + md.setAbstract("\n".join(lines)) + layer.setMetadata(md) + + +def load_result(collection: Mapping[str, Any], meta: Mapping[str, Any], + title: str, area_text: str = "", + project: Optional[QgsProject] = None, + style_key: str = "osm") -> Tuple[List[QgsVectorLayer], Dict[str, int], int]: + project = project or QgsProject.instance() + buckets, without = geojson.split_by_geometry(collection) + if not buckets: + return [], {}, without + + base = geojson.safe_name(title) + folder = result_folder() + root = project.layerTreeRoot() + group = root.insertGroup(0, base) + + layers: List[QgsVectorLayer] = [] + counts: Dict[str, int] = {} + for name in geojson.GROUP_ORDER: + part = buckets.get(name) + if not part: + continue + counts[name] = len(part["features"]) + stem = "%s-%s-%d" % (geojson.safe_name(base, limit=32), name.lower(), + abs(hash((base, name))) % 100000) + path = geojson.write_collection(folder, stem, part) + layer = QgsVectorLayer(geojson.ogr_uri(path, name), + "%s – %s" % (base, GROUP_LABEL.get(name, name)), + "ogr") + if not layer.isValid(): + raise GeoDonkeyError( + tr("QGIS could not read the result file: {path}").format(path=path)) + _apply_metadata(layer, meta, title, area_text) + apply_style(layer, style.plan(style_key, name, _properties(part))) + project.addMapLayer(layer, False) + group.addLayer(layer) + layers.append(layer) + + return layers, counts, without diff --git a/geodonkey/mapcontext.py b/geodonkey/mapcontext.py new file mode 100644 index 0000000..eaa66c4 --- /dev/null +++ b/geodonkey/mapcontext.py @@ -0,0 +1,162 @@ +from __future__ import annotations + +from typing import List, Optional, Sequence, Tuple + +from qgis.core import ( + QgsCoordinateReferenceSystem, + QgsCoordinateTransform, + QgsGeometry, + QgsPointXY, + QgsProject, + QgsRectangle, + QgsVectorLayer, + QgsWkbTypes, +) + +from . import area +from .errors import RequestError +from .i18n import tr + +WGS84 = "EPSG:4326" + + +def _to_wgs84(source_crs: QgsCoordinateReferenceSystem) -> QgsCoordinateTransform: + target = QgsCoordinateReferenceSystem(WGS84) + return QgsCoordinateTransform(source_crs, target, QgsProject.instance()) + + +def point_to_wgs84(point, crs: QgsCoordinateReferenceSystem) -> Tuple[float, float]: + if crs is not None and crs.isValid() and crs.authid() != WGS84: + point = _to_wgs84(crs).transform(point) + return (point.x(), point.y()) + + +def point_from_wgs84(lon: float, lat: float, + crs: QgsCoordinateReferenceSystem): + if lon is None or lat is None or lon != lon or lat != lat: + return None + point = QgsPointXY(float(lon), float(lat)) + if crs is None or not crs.isValid() or crs.authid() == WGS84: + return point + try: + target = QgsCoordinateReferenceSystem(WGS84) + return QgsCoordinateTransform(target, crs, QgsProject.instance()).transform(point) + except Exception: # noqa: BLE001 + return None + + +def geometry_from_wgs84(shape, crs: QgsCoordinateReferenceSystem): + from . import geojson + + try: + wkt = geojson.to_wkt(shape) + except Exception: # noqa: BLE001 + return None + if not wkt: + return None + geometry = QgsGeometry.fromWkt(wkt) + if geometry is None or geometry.isEmpty(): + return None + if crs is not None and crs.isValid() and crs.authid() != WGS84: + try: + source = QgsCoordinateReferenceSystem(WGS84) + geometry.transform(QgsCoordinateTransform(source, crs, + QgsProject.instance())) + except Exception: # noqa: BLE001 + return None + return geometry + + +def rectangle_to_bbox(rect: QgsRectangle, crs: QgsCoordinateReferenceSystem) -> dict: + if rect is None or rect.isEmpty(): + raise RequestError(tr("The selected area is empty.")) + if crs is not None and crs.isValid() and crs.authid() != WGS84: + rect = _to_wgs84(crs).transformBoundingBox(rect) + return area.bbox_param(rect.xMinimum(), rect.yMinimum(), + rect.xMaximum(), rect.yMaximum()) + + +def canvas_bbox(canvas) -> dict: + settings = canvas.mapSettings() + return rectangle_to_bbox(canvas.extent(), settings.destinationCrs()) + + +def layer_bbox(layer: QgsVectorLayer, selected_only: bool = False) -> dict: + if layer is None: + raise RequestError(tr("No layer selected.")) + if selected_only: + if layer.selectedFeatureCount() == 0: + raise RequestError(tr("Nothing is selected in that layer.")) + rect = layer.boundingBoxOfSelected() + else: + rect = layer.extent() + return rectangle_to_bbox(rect, layer.crs()) + + +def _rings_of(geometry: QgsGeometry) -> List[List[Tuple[float, float]]]: + rings: List[List[Tuple[float, float]]] = [] + if geometry is None or geometry.isEmpty(): + return rings + if geometry.isMultipart(): + parts = geometry.asMultiPolygon() + else: + parts = [geometry.asPolygon()] + for part in parts or []: + if not part: + continue + outer = part[0] + if len(outer) >= 3: + rings.append([(point.x(), point.y()) for point in outer]) + return rings + + +def selection_polygon(layer: QgsVectorLayer) -> dict: + if layer is None or layer.selectedFeatureCount() == 0: + raise RequestError(tr("Select one or more polygons first.")) + if QgsWkbTypes.geometryType(layer.wkbType()) != QgsWkbTypes.GeometryType.PolygonGeometry: + raise RequestError(tr("Area selection needs a polygon layer.")) + + geometries = [f.geometry() for f in layer.selectedFeatures() if f.hasGeometry()] + if not geometries: + raise RequestError(tr("The selected features have no geometry.")) + + combined = QgsGeometry.unaryUnion(geometries) + if combined is None or combined.isEmpty(): + raise RequestError(tr("The selected features could not be combined.")) + + if layer.crs().isValid() and layer.crs().authid() != WGS84: + combined.transform(_to_wgs84(layer.crs())) + + rings = _rings_of(combined) + if not rings: + raise RequestError(tr("The selection has no usable outline.")) + if len(rings) > 1: + hull = combined.convexHull() + rings = _rings_of(hull) + if not rings: + raise RequestError(tr("The selection has no usable outline.")) + return area.polygon_param(rings[0]) + + +def polygon_layers(project: Optional[QgsProject] = None) -> List[QgsVectorLayer]: + project = project or QgsProject.instance() + out = [] + for layer in project.mapLayers().values(): + if not isinstance(layer, QgsVectorLayer): + continue + if QgsWkbTypes.geometryType(layer.wkbType()) == QgsWkbTypes.GeometryType.PolygonGeometry: + out.append(layer) + return sorted(out, key=lambda item: item.name().lower()) + + +def vector_layers(project: Optional[QgsProject] = None) -> List[QgsVectorLayer]: + project = project or QgsProject.instance() + out = [layer for layer in project.mapLayers().values() + if isinstance(layer, QgsVectorLayer)] + return sorted(out, key=lambda item: item.name().lower()) + + +def extent_from_sequence(values: Sequence[float]) -> dict: + if len(values) != 4: + raise RequestError(tr("An extent needs four numbers.")) + return area.bbox_param(*[float(v) for v in values]) diff --git a/geodonkey/metadata.txt b/geodonkey/metadata.txt new file mode 100644 index 0000000..ca63c23 --- /dev/null +++ b/geodonkey/metadata.txt @@ -0,0 +1,36 @@ +[general] +name=GeoDonkey +qgisMinimumVersion=3.40 +qgisMaximumVersion=4.99 +description=OpenStreetMap data, routing, elevation and vector map styles from geodonkey.com, straight into QGIS. +about=GeoDonkey brings the services of geodonkey.com into QGIS: OpenStreetMap data, basemaps, routing, elevation and your own datasets - every result a ready-to-use layer, styled and in the right place. + What it does + - DonkeyOSM: ask for OpenStreetMap data in plain language ("bakery"), by OSM tags, or with a custom query. The answer arrives as vector layers, split by geometry type. + - Basemaps: seven GeoDonkey vector tile styles, free of charge and without an API key. + - Ways: isochrones with up to four rings in a single call, and routes through up to ten points - on foot, by bike or by car, on the road network rather than the straight line. + - Elevation: a profile along a line, the elevation above sea level for a whole point layer, and the line of sight between two points including earth curvature. + - Datasets: upload a vector layer, manage your datasets without leaving QGIS, and copy a link that shows any of them on a map in the browser. + Every result is styled the way it looks on geodonkey.com, so the map in QGIS and the map in the browser show the same picture. Every tool is a Processing algorithm, so it is available in models, in batch runs and with qgis_process. + What you need + The basemaps and the shareable dataset links work without an account. Everything else - OpenStreetMap, routing, isochrones, elevation, line of sight and dataset management - needs a geodonkey.com account with an API key and DonkeyCoins, the prepaid credits of the service. The key is kept in the QGIS password manager and is never written to disk in clear text. No additional Python packages are required. + Elevation data covers Germany only. + Data © OpenStreetMap contributors, ODbL. +version=1.12 +author=GeoDonkey +email=support@geodonkey.com + +tracker=https://git.geodonkey.com/geodonkey/geodonkey-qgis-plugin/issues +repository=https://git.geodonkey.com/geodonkey/geodonkey-qgis-plugin +homepage=https://geodonkey.com + +tags=openstreetmap,osm,overpass,vector tiles,basemap,poi,download,web services,processing,routing,isochrone,route,elevation,dem,line of sight,viewshed,upload + +category=Web +icon=icons/geodonkey.svg +experimental=False +deprecated=False +hasProcessingProvider=yes +server=False + +changelog=1.12 + First public release. diff --git a/geodonkey/net.py b/geodonkey/net.py new file mode 100644 index 0000000..41001a1 --- /dev/null +++ b/geodonkey/net.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from typing import Any, Mapping, Optional, Tuple + +from qgis.PyQt.QtCore import QByteArray, QUrl +from qgis.PyQt.QtNetwork import QNetworkRequest +from qgis.core import QgsBlockingNetworkRequest + +from .client import Response + + +def _no_error(): + scoped = getattr(QgsBlockingNetworkRequest, "ErrorCode", None) + if scoped is not None and hasattr(scoped, "NoError"): + return scoped.NoError + return QgsBlockingNetworkRequest.NoError + + +def _status_of(reply) -> Optional[int]: + code = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute) + try: + return int(code) + except (TypeError, ValueError): + return None + + +def _headers_of(reply) -> dict: + out = {} + for name in reply.rawHeaderList(): + pair = _header_pair(reply, name) + if pair is not None: + out[pair[0]] = pair[1] + return out + + +def _header_pair(reply, name) -> Optional[Tuple[str, str]]: + try: + return (bytes(name).decode("latin-1"), + bytes(reply.rawHeader(name)).decode("latin-1")) + except Exception: + return None + + +class QgisTransport(object): + def __call__(self, method: str, url: str, headers: Mapping[str, str], + body: Optional[bytes] = None, feedback: Any = None) -> Response: + request = QNetworkRequest(QUrl(url)) + for name, value in (headers or {}).items(): + request.setRawHeader(str(name).encode("latin-1"), + str(value).encode("latin-1")) + + blocking = QgsBlockingNetworkRequest() + + verb = (method or "GET").upper() + if verb == "POST": + payload = QByteArray(body or b"") + code = blocking.post(request, payload, forceRefresh=True, feedback=feedback) + else: + code = blocking.get(request, forceRefresh=True, feedback=feedback) + + reply = blocking.reply() + status = _status_of(reply) if reply is not None else None + content = bytes(reply.content()) if reply is not None else b"" + head = _headers_of(reply) if reply is not None else {} + + error_text = "" + if code != _no_error(): + error_text = blocking.errorMessage() or "" + + return Response(status=status, headers=head, body=content, + url=url, error=error_text) diff --git a/geodonkey/plot.py b/geodonkey/plot.py new file mode 100644 index 0000000..bd25e85 --- /dev/null +++ b/geodonkey/plot.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import math +from typing import List, Optional, Sequence, Tuple + +Sample = Tuple[float, Optional[float]] + + +def nice_step(rough: float, snap: bool = False) -> float: + if not rough or rough <= 0 or not math.isfinite(rough): + return 1.0 + power = math.floor(math.log10(rough)) + base = 10.0 ** power + share = rough / base + if snap: + for limit, factor in ((1.5, 1.0), (3.0, 2.0), (7.0, 5.0)): + if share < limit: + return factor * base + return 10.0 * base + for factor in (1.0, 2.0, 5.0, 10.0): + if share <= factor * 1.0000001: + return factor * base + return 10.0 * base + + +def ticks(low: float, high: float, target: int = 5) -> List[float]: + if not math.isfinite(low) or not math.isfinite(high): + return [] + if high < low: + low, high = high, low + if high == low: + return [low] + step = nice_step((high - low) / max(1, target), snap=True) + first = math.ceil(low / step) * step + out: List[float] = [] + value = first + while value <= high + step * 1e-9 and len(out) < 1000: + out.append(value + 0.0 if value else 0.0) + value += step + return out + + +def padded(low: float, high: float, fraction: float = 0.08, + minimum: float = 1.0) -> Tuple[float, float]: + if not math.isfinite(low) or not math.isfinite(high): + return (0.0, max(minimum, 1.0)) + if high < low: + low, high = high, low + span = high - low + if span < minimum: + middle = (high + low) / 2.0 + low, high = middle - minimum / 2.0, middle + minimum / 2.0 + span = high - low + room = span * fraction + return (low - room, high + room) + + +class Scale(object): + def __init__(self, low: float, high: float, + start: float, end: float) -> None: + self.low = float(low) + self.high = float(high) + self.start = float(start) + self.end = float(end) + span = self.high - self.low + self._span = span if span else 1.0 + + def to_pixel(self, value: float) -> float: + share = (float(value) - self.low) / self._span + return self.start + share * (self.end - self.start) + + def to_value(self, pixel: float) -> float: + width = self.end - self.start + if not width: + return self.low + share = (float(pixel) - self.start) / width + return self.low + share * self._span + + +def bounds(samples: Sequence[Sample]) -> Tuple[float, float, float, float]: + xs = [float(x) for x, _ in samples if math.isfinite(x)] + ys = [float(y) for _, y in samples + if y is not None and math.isfinite(float(y))] + if not xs: + return (0.0, 1.0, 0.0, 1.0) + if not ys: + return (min(xs), max(xs), 0.0, 1.0) + return (min(xs), max(xs), min(ys), max(ys)) + + +def segments(samples: Sequence[Sample]) -> List[List[Sample]]: + out: List[List[Sample]] = [] + current: List[Sample] = [] + for x, y in samples: + if y is None: + if len(current) > 0: + out.append(current) + current = [] + continue + current.append((float(x), float(y))) + if current: + out.append(current) + return [piece for piece in out if piece] + + +def nearest(samples: Sequence[Sample], x: float) -> int: + best, distance = -1, None + for index, (value, _) in enumerate(samples): + gap = abs(float(value) - float(x)) + if distance is None or gap < distance: + best, distance = index, gap + return best + + +def gain_and_loss(samples: Sequence[Sample]) -> Tuple[float, float]: + up = down = 0.0 + for piece in segments(samples): + for (_, a), (_, b) in zip(piece, piece[1:]): + change = float(b) - float(a) + if change > 0: + up += change + else: + down -= change + return (up, down) diff --git a/geodonkey/plugin.py b/geodonkey/plugin.py new file mode 100644 index 0000000..3b6de9b --- /dev/null +++ b/geodonkey/plugin.py @@ -0,0 +1,256 @@ +from __future__ import annotations + +import os + +from qgis.PyQt.QtCore import QCoreApplication, QLocale, QSettings, Qt, QTranslator + +from .compat import PLUGIN_DIR, QAction, icon +from .i18n import later, tr + +MENU_NAME = "GeoDonkey" + +TAB_OSM = 0 +TAB_BASEMAPS = 1 +TAB_TOOLS = 2 +TAB_UPLOAD = 3 +TAB_ACCOUNT = 4 + +TOOLS = ( + ("isochrone.svg", "geodonkey:isochrone", later("Isochrone"), + later("Reachable area from a point, by foot, bike or car")), + ("route.svg", "geodonkey:route", later("Route"), + later("Route through several points, with distance, time and directions")), + ("profile.svg", "geodonkey:elevationprofile", later("Elevation profile"), + later("Terrain profile along the straight line between two points")), + ("elevation.svg", "geodonkey:elevationpoints", later("Point elevation"), + later("Add the elevation above sea level to every point of a layer")), + ("lineofsight.svg", "geodonkey:lineofsight", later("Line of sight"), + later("Is there a clear line of sight between two points?")), +) + +PANEL_TOOLS = ( + "geodonkey:isochrone", + "geodonkey:route", + "geodonkey:elevationprofile", + "geodonkey:elevationpoints", + "geodonkey:lineofsight", +) + + +class GeoDonkeyPlugin(object): + def __init__(self, iface) -> None: + self.iface = iface + self.actions = [] + self.panel = None + self.provider = None + self.translator = None + self.toolbar = None + self._install_translator() + + def _install_translator(self) -> None: + locale = QSettings().value("locale/userLocale") + if not locale: + locale = QLocale.system().name() + code = str(locale)[:2] + path = os.path.join(PLUGIN_DIR, "i18n", "geodonkey_%s.qm" % code) + if not os.path.exists(path): + return + translator = QTranslator() + if translator.load(path): + QCoreApplication.installTranslator(translator) + self.translator = translator + + def initGui(self) -> None: # noqa: N802 + self.initProcessing() + + self.toolbar = self.iface.addToolBar(MENU_NAME) + self.toolbar.setObjectName("GeoDonkeyToolbar") + + self._add_action( + "osm.svg", tr("DonkeyOSM query"), + lambda: self.show_panel(TAB_OSM), + tr("Query OpenStreetMap data and load it as vector layers")) + self._add_action( + "basemap.svg", tr("GeoDonkey basemaps"), + lambda: self.show_panel(TAB_BASEMAPS), + tr("Add a GeoDonkey vector tile basemap")) + + self.toolbar.addSeparator() + for icon_name, algorithm, label, tip in TOOLS: + action = (self._panel_tool(algorithm) + if algorithm in PANEL_TOOLS else self._tool(algorithm)) + self._add_action(icon_name, tr(label), action, tr(tip)) + + for icon_name, algorithm, label, _tip in TOOLS: + if algorithm not in PANEL_TOOLS: + continue + self._add_action( + icon_name, tr("{tool} (dialog)…").format(tool=tr(label)), + self._tool(algorithm), + tr("The full Processing dialog, with all options"), + toolbar=False) + + self.toolbar.addSeparator() + self._add_action( + "upload.svg", tr("Upload data"), + lambda: self.show_panel(TAB_UPLOAD), + tr("Upload a vector layer to GeoDonkey and manage your datasets")) + + self.toolbar.addSeparator() + self._add_action( + "geodonkey.svg", tr("GeoDonkey settings…"), + self.open_settings, + tr("API key, API address, account and defaults")) + + self._add_action( + "basemap.svg", tr("Add last basemap"), + self.add_last_basemap, + tr("Add the last used GeoDonkey map style as a basemap"), + toolbar=False) + self._add_action( + "account.svg", tr("GeoDonkey account"), + lambda: self.show_panel(TAB_ACCOUNT), + tr("Balance, plan and hourly limit of the stored API key"), + toolbar=False) + + def initProcessing(self) -> None: # noqa: N802 + if self.provider is not None: + return + + from qgis.core import QgsApplication + + from .processing.provider import GeoDonkeyProvider + + self.provider = GeoDonkeyProvider() + QgsApplication.processingRegistry().addProvider(self.provider) + + def _add_action(self, icon_name: str, text: str, slot, tip: str = "", + checkable: bool = False, toolbar: bool = True) -> QAction: + action = QAction(icon(icon_name), text, self.iface.mainWindow()) + action.triggered.connect(slot) + action.setCheckable(checkable) + if tip: + action.setStatusTip(tip) + action.setToolTip(tip) + if toolbar: + self.toolbar.addAction(action) + self.iface.addPluginToWebMenu(MENU_NAME, action) + self.actions.append(action) + return action + + def unload(self) -> None: + for action in self.actions: + self.iface.removePluginWebMenu(MENU_NAME, action) + self.actions = [] + + if self.toolbar is not None: + self.iface.mainWindow().removeToolBar(self.toolbar) + self.toolbar.deleteLater() + self.toolbar = None + + if self.panel is not None: + self.iface.removeDockWidget(self.panel) + self.panel.deleteLater() + self.panel = None + + if self.provider is not None: + from qgis.core import QgsApplication + + QgsApplication.processingRegistry().removeProvider(self.provider) + self.provider = None + + def ensure_panel(self): + if self.panel is None: + from .gui.panel import GeoDonkeyPanel + + self.panel = GeoDonkeyPanel(self.iface, self.iface.mainWindow()) + self.iface.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.panel) + return self.panel + + def show_panel(self, tab: int = TAB_OSM, algorithm: str = "") -> None: + panel = self.ensure_panel() + panel.setVisible(True) + panel.raise_() + tabs = getattr(panel, "tabs", None) + if tabs is not None: + tabs.setCurrentIndex(tab) + if not algorithm: + return + tools = getattr(panel, "tools", None) + if tools is None: + return + page = tools.page_for(algorithm) + if page is not None: + tools.show_page(page) + + def _panel_tool(self, algorithm: str): + return lambda: self.show_panel(TAB_TOOLS, algorithm) + + def _tool(self, algorithm: str): + def open_dialog() -> None: + from qgis.core import Qgis, QgsApplication + + try: + import processing + except ImportError: + self._complain(tr("The Processing plugin is not active.")) + return + + self.initProcessing() + if QgsApplication.processingRegistry().algorithmById(algorithm) is None: + self._complain(tr( + "The tool '{name}' is not registered. Reload the GeoDonkey " + "plugin, or restart QGIS.").format(name=algorithm), + level=Qgis.MessageLevel.Critical) + return + + try: + processing.execAlgorithmDialog(algorithm, {}) + except Exception as exc: # noqa: BLE001 + from qgis.core import QgsMessageLog + + QgsMessageLog.logMessage( + "%s: %s" % (algorithm, exc), "GeoDonkey", + Qgis.MessageLevel.Critical) + self._complain(tr("The tool could not be opened. See the " + "GeoDonkey log for details."), + level=Qgis.MessageLevel.Critical) + + return open_dialog + + def _complain(self, text: str, level=None) -> None: + from qgis.core import Qgis + + if level is None: + level = Qgis.MessageLevel.Warning + self.iface.messageBar().pushMessage( + "GeoDonkey", text, level=level, duration=10) + + def open_settings(self) -> None: + from .gui.settings_dialog import SettingsDialog + + dialog = SettingsDialog(self.iface.mainWindow()) + accepted = dialog.exec() if hasattr(dialog, "exec") else dialog.exec_() + if accepted and self.panel is not None: + self.panel.reload_client() + + def add_last_basemap(self) -> None: + from qgis.core import Qgis + + from . import basemaps, config, settings + from .errors import GeoDonkeyError + + style_id = str(settings.get("style")) + style = next((dict(s) for s in config.FALLBACK_STYLES if s["id"] == style_id), None) + if style is None: + style = dict(config.FALLBACK_STYLES[0]) + try: + basemaps.add_basemap(settings.api_url(), style) + except GeoDonkeyError as exc: + self.iface.messageBar().pushMessage( + "GeoDonkey", exc.message, level=Qgis.MessageLevel.Critical, duration=10) + return + self.iface.messageBar().pushMessage( + "GeoDonkey", + tr("Basemap “{name}” added.").format(name=style["name"]), + level=Qgis.MessageLevel.Success, duration=5) diff --git a/geodonkey/points.py b/geodonkey/points.py new file mode 100644 index 0000000..8d3dee7 --- /dev/null +++ b/geodonkey/points.py @@ -0,0 +1,140 @@ +from __future__ import annotations + +import math +from typing import Any, Iterable, Iterator, List, Sequence, Tuple + +from . import config +from .errors import RequestError +from .i18n import tr + +Point = Tuple[float, float] + +PRECISION = 6 + + +def fmt(value: float) -> str: + text = "%.*f" % (PRECISION, float(value)) + if "." in text: + text = text.rstrip("0").rstrip(".") + return text or "0" + + +def _number(value: Any, label: str) -> float: + try: + number = float(value) + except (TypeError, ValueError): + raise RequestError(tr("“{value}” is not a number.").format(value=value)) + if math.isnan(number) or math.isinf(number): + raise RequestError(tr("“{value}” is not a number.").format(value=label)) + return number + + +def check(lon: float, lat: float) -> Point: + x = _number(lon, "lon") + y = _number(lat, "lat") + if not -180.0 <= x <= 180.0: + raise RequestError( + tr("Longitude {value} is outside the valid range of −180 to 180.").format( + value=fmt(x))) + if not -90.0 <= y <= 90.0: + raise RequestError( + tr("Latitude {value} is outside the valid range of −90 to 90.").format( + value=fmt(y))) + return (x, y) + + +def latlon(lon: float, lat: float) -> str: + x, y = check(lon, lat) + return "%s,%s" % (fmt(y), fmt(x)) + + +def pretty(lon: float, lat: float, places: int = 5) -> str: + x, y = check(lon, lat) + return "%.*f° %s, %.*f° %s" % ( + places, abs(y), "N" if y >= 0 else "S", + places, abs(x), "E" if x >= 0 else "W") + + +def series(points: Sequence[Point], limit: int = 0, label: str = "") -> str: + pairs = list(points) + if not pairs: + raise RequestError(tr("No points given.")) + if limit and len(pairs) > limit: + raise RequestError( + tr("{count} points given, at most {limit} are allowed.").format( + count=len(pairs), limit=limit)) + return ";".join(latlon(x, y) for x, y in pairs) + + +def lonlat(lon: float, lat: float) -> List[float]: + x, y = check(lon, lat) + return [round(x, PRECISION), round(y, PRECISION)] + + +GERMANY = config.ELEVATION_BBOX + + +def in_germany(lon: float, lat: float) -> bool: + west, south, east, north = GERMANY + try: + x, y = float(lon), float(lat) + except (TypeError, ValueError): + return False + if math.isnan(x) or math.isnan(y): + return False + return west <= x <= east and south <= y <= north + + +def germany_message() -> str: + west, south, east, north = GERMANY + return tr( + "Elevation data is available for Germany only " + "(longitude {west} to {east}, latitude {south} to {north})." + ).format(west=fmt(west), east=fmt(east), south=fmt(south), north=fmt(north)) + + +def check_germany(lon: float, lat: float) -> Point: + x, y = check(lon, lat) + if not in_germany(x, y): + raise RequestError( + "%s %s" % (germany_message(), + tr("The point {lon}, {lat} lies outside.").format( + lon=fmt(x), lat=fmt(y)))) + return (x, y) + + +def split_germany(points: Iterable[Point]) -> Tuple[List[int], List[int]]: + inside: List[int] = [] + outside: List[int] = [] + for index, pair in enumerate(points): + try: + x, y = pair + except (TypeError, ValueError): + outside.append(index) + continue + (inside if in_germany(x, y) else outside).append(index) + return inside, outside + + +def along(start: Point, end: Point, fraction: float) -> Point: + x1, y1 = float(start[0]), float(start[1]) + x2, y2 = float(end[0]), float(end[1]) + t = max(0.0, min(1.0, float(fraction))) + return (x1 + (x2 - x1) * t, y1 + (y2 - y1) * t) + + +EARTH_RADIUS_METRES = 6371008.8 + + +def distance(start: Point, end: Point) -> float: + lon1, lat1 = math.radians(float(start[0])), math.radians(float(start[1])) + lon2, lat2 = math.radians(float(end[0])), math.radians(float(end[1])) + a = (math.sin((lat2 - lat1) / 2.0) ** 2 + + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2.0) ** 2) + return 2.0 * EARTH_RADIUS_METRES * math.asin(min(1.0, math.sqrt(a))) + + +def chunks(items: Sequence[Any], size: int) -> Iterator[List[Any]]: + step = max(1, int(size)) + for start in range(0, len(items), step): + yield list(items[start:start + step]) diff --git a/geodonkey/processing/__init__.py b/geodonkey/processing/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/geodonkey/processing/base.py b/geodonkey/processing/base.py new file mode 100644 index 0000000..2f34925 --- /dev/null +++ b/geodonkey/processing/base.py @@ -0,0 +1,183 @@ +from __future__ import annotations + +import collections +from typing import Any, Dict, Optional, Sequence, Tuple + +from qgis.core import ( + QgsCoordinateReferenceSystem, + QgsCoordinateTransform, + QgsFeature, + QgsFeatureSink, + QgsFields, + QgsGeometry, + QgsPointXY, + QgsProcessingAlgorithm, + QgsProcessingException, + QgsProcessingLayerPostProcessorInterface, +) + +from .. import auth, config, geojson, layers, settings +from ..client import ApiClient +from ..compat import field, icon +from ..errors import GeoDonkeyError +from ..i18n import tr +from ..net import QgisTransport +from ..results import Field, Row + +WGS84 = "EPSG:4326" + + +def wgs84() -> QgsCoordinateReferenceSystem: + return QgsCoordinateReferenceSystem(WGS84) + + +def build_fields(spec: Sequence[Field]) -> QgsFields: + fields = QgsFields() + for name, kind in spec: + fields.append(field(name, kind)) + return fields + + +_KEEP = collections.deque(maxlen=64) + + +class Styler(QgsProcessingLayerPostProcessorInterface): + def __init__(self, rule) -> None: + super().__init__() + self._rule = rule + + def postProcessLayer(self, layer, context, feedback) -> None: # noqa: N802 + layers.apply_style(layer, self._rule) + + +class GeoDonkeyAlgorithm(QgsProcessingAlgorithm): + ICON = "geodonkey.svg" + GROUP = "GeoDonkey" + GROUP_ID = "geodonkey" + COST_KEY = "" + + def group(self) -> str: + return tr(self.GROUP) + + def groupId(self) -> str: # noqa: N802 + return self.GROUP_ID + + def icon(self): + return icon(self.ICON) + + def price(self) -> int: + return config.COIN_COSTS.get(self.COST_KEY, 0) + + def cost_note(self) -> str: + return tr( + "

Every run costs {coins} DonkeyCoins once the {free} free " + "calls of the current hour are used up. The API key is taken from " + "the plugin settings (Web ▸ GeoDonkey ▸ GeoDonkey settings); " + "without a key only the free calls are available.

" + ).format(coins=self.price(), free=config.FREE_CALLS_PER_HOUR) + + def client(self, feedback) -> ApiClient: + api = ApiClient(transport=QgisTransport(), + base_url=settings.api_url(), + token=auth.load_token(), + language=settings.language()) + if not api.token: + feedback.pushWarning(tr( + "No API key stored – only the free calls of this hour are available. " + "Add a key under Web ▸ GeoDonkey ▸ GeoDonkey settings.")) + return api + + @staticmethod + def fail(exc: GeoDonkeyError, feedback) -> None: + if exc.detail: + feedback.pushDebugInfo(exc.detail) + raise QgsProcessingException(exc.message) + + @staticmethod + def report(api: ApiClient, feedback) -> None: + charged = api.usage.charged + if charged: + feedback.pushInfo(tr("Charged: {coins} DC · balance {balance} DC").format( + coins=charged, balance=api.usage.balance)) + elif api.usage.free_remaining is not None: + feedback.pushInfo(tr("Free call · {count} left this hour").format( + count=api.usage.free_remaining)) + + def wgs84_point(self, parameters, name: str, context) -> Tuple[float, float]: + point = self.parameterAsPoint(parameters, name, context, wgs84()) + return (point.x(), point.y()) + + @staticmethod + def source_points(source, context, feedback) -> Tuple[list, list]: + transform = QgsCoordinateTransform(source.sourceCrs(), wgs84(), + context.transformContext()) + coordinates = [] + features = [] + skipped = 0 + for feature in source.getFeatures(): + if feedback.isCanceled(): + break + geometry = feature.geometry() + if geometry is None or geometry.isEmpty(): + skipped += 1 + continue + point = geometry.centroid().asPoint() if geometry.isMultipart() \ + else geometry.asPoint() + moved = transform.transform(QgsPointXY(point)) + coordinates.append((moved.x(), moved.y())) + features.append(feature) + if skipped: + feedback.pushWarning(tr( + "{count} features without geometry were skipped.").format(count=skipped)) + return coordinates, features + + def make_sink(self, parameters, context, name: str, spec: Sequence[Field], + wkb, crs: Optional[QgsCoordinateReferenceSystem] = None): + return self.parameterAsSink(parameters, name, context, + build_fields(spec), wkb, + crs if crs is not None else wgs84()) + + def style(self, context, dest_id: Any, rule) -> bool: + if not dest_id or rule is None: + return False + try: + if not context.willLoadLayerOnCompletion(dest_id): + return False + details = context.layerToLoadOnCompletionDetails(dest_id) + except (AttributeError, TypeError): + return False + if details is None: + return False + processor = Styler(rule) + _KEEP.append(processor) + details.setPostProcessor(processor) + return True + + @staticmethod + def write(sink, spec: Sequence[Field], rows: Sequence[Row], feedback) -> int: + if sink is None: + return 0 + fields = build_fields(spec) + written = 0 + for row in rows: + if feedback.isCanceled(): + break + out = QgsFeature(fields) + wkt = geojson.to_wkt(row.get("geometry")) + if wkt: + out.setGeometry(QgsGeometry.fromWkt(wkt)) + attrs = row.get("attrs") or {} + out.setAttributes([attrs.get(name) for name, _kind in spec]) + sink.addFeature(out, QgsFeatureSink.Flag.FastInsert) + written += 1 + return written + + +def attribution(meta: Dict[str, Any], feedback) -> None: + text = geojson.attribution(meta) + if not text: + sources = meta.get("attributions") + if isinstance(sources, (list, tuple)) and sources: + text = ", ".join(str(entry) for entry in sources) + if text: + feedback.pushInfo(str(text)) diff --git a/geodonkey/processing/elevation_points_algorithm.py b/geodonkey/processing/elevation_points_algorithm.py new file mode 100644 index 0000000..74289ad --- /dev/null +++ b/geodonkey/processing/elevation_points_algorithm.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +from typing import Any, Dict, List + +from qgis.core import ( + QgsFeature, + QgsFeatureSink, + QgsFields, + QgsProcessing, + QgsProcessingException, + QgsProcessingParameterFeatureSink, + QgsProcessingParameterFeatureSource, +) + +from .. import config, points, results, style +from ..compat import field +from ..errors import GeoDonkeyError +from ..i18n import tr +from .base import GeoDonkeyAlgorithm + +OUTSIDE = "outside" + + +class ElevationPointsAlgorithm(GeoDonkeyAlgorithm): + ICON = "elevation.svg" + GROUP = "Elevation" + GROUP_ID = "elevation" + COST_KEY = "elevation_points" + + INPUT = "INPUT" + OUTPUT = "OUTPUT" + + def createInstance(self): # noqa: N802 + return ElevationPointsAlgorithm() + + def name(self) -> str: + return "elevationpoints" + + def displayName(self) -> str: # noqa: N802 + return tr("Add elevation to points") + + def shortHelpString(self) -> str: # noqa: N802 + return tr( + "

Looks up the elevation above sea level for every point of a " + "layer and writes it into three new fields: elevation, " + "ele_source and ele_state. Geometry and " + "existing fields are kept unchanged.

" + "

Layers with more than {max_points} points are split into " + "several calls automatically. That does not cost extra: the price " + "follows the number of points, not the number of calls.

" + "

Elevation data is available for Germany only. Points " + "outside keep their place in the layer, get an empty elevation and " + "{outside} in ele_state – a single point " + "abroad does not abort the run.

" + "

The price follows the quantity: {coins} DonkeyCoins per " + "started {batch} points, once the {free} free calls of the current " + "hour are used up.

" + "

Elevation data by the surveying authorities of the German " + "federal states; the exact source of every point is in " + "ele_source.

" + ).format(max_points=config.ELEVATION_MAX_POINTS, + batch=config.ELEVATION_BILLING_BATCH, + coins=config.COIN_COSTS.get("elevation_points", 2), + free=config.FREE_CALLS_PER_HOUR, outside=OUTSIDE) + + def initAlgorithm(self, configuration=None): # noqa: N802 + self.addParameter(QgsProcessingParameterFeatureSource( + self.INPUT, tr("Point layer"), + types=[QgsProcessing.SourceType.TypeVectorPoint])) + + self.addParameter(QgsProcessingParameterFeatureSink( + self.OUTPUT, tr("Points with elevation"), + type=QgsProcessing.SourceType.TypeVectorPoint)) + + def processAlgorithm(self, parameters, context, feedback): # noqa: N802 + source = self.parameterAsSource(parameters, self.INPUT, context) + if source is None: + raise QgsProcessingException(tr("The input layer could not be read.")) + + coordinates, features = self.source_points(source, context, feedback) + if not coordinates: + raise QgsProcessingException(tr("The layer contains no usable points.")) + + inside, outside = points.split_germany(coordinates) + if outside: + feedback.pushWarning(tr( + "{count} points lie outside Germany and get no elevation.").format( + count=len(outside))) + if not inside: + raise QgsProcessingException(points.germany_message()) + + values = self._lookup(coordinates, inside, feedback) + if feedback.isCanceled(): + return {} + + out_fields = self._fields(source.fields()) + sink, dest = self.parameterAsSink( + parameters, self.OUTPUT, context, out_fields, + source.wkbType(), source.sourceCrs()) + if sink is None: + raise QgsProcessingException(tr("The output could not be created.")) + + known = 0 + for feature, extra in zip(features, values): + if feedback.isCanceled(): + return {} + out = QgsFeature(out_fields) + out.setGeometry(feature.geometry()) + out.setAttributes(list(feature.attributes()) + [ + extra.get("elevation"), extra.get("ele_source"), + extra.get("ele_state")]) + sink.addFeature(out, QgsFeatureSink.Flag.FastInsert) + if extra.get("elevation") is not None: + known += 1 + + feedback.pushInfo(tr("{known} of {count} points have an elevation.").format( + known=known, count=len(features))) + self.style(context, dest, style.elevation_plan()) + feedback.setProgress(100) + + result: Dict[str, Any] = {self.OUTPUT: dest} + return result + + def _lookup(self, coordinates, inside: List[int], feedback) -> List[Dict[str, Any]]: + wanted = set(inside) + values: List[Dict[str, Any]] = [ + {"elevation": None, "ele_source": None, + "ele_state": None if index in wanted else OUTSIDE} + for index in range(len(coordinates)) + ] + + api = self.client(feedback) + batches = list(points.chunks(inside, config.ELEVATION_MAX_POINTS)) + for number, batch in enumerate(batches): + if feedback.isCanceled(): + return values + feedback.pushInfo(tr("Batch {number} of {total} · {count} points").format( + number=number + 1, total=len(batches), count=len(batch))) + try: + payload = api.elevation_points([coordinates[i] for i in batch], + feedback=feedback) + except GeoDonkeyError as exc: + self.fail(exc, feedback) + self.report(api, feedback) + answers = results.elevation_values(payload) + if len(answers) != len(batch): + raise QgsProcessingException(tr( + "The service returned {got} elevations for {sent} points." + ).format(got=len(answers), sent=len(batch))) + for position, index in enumerate(batch): + values[index] = answers[position] + feedback.setProgress(10 + 80.0 * (number + 1) / len(batches)) + return values + + @staticmethod + def _fields(source_fields: QgsFields) -> QgsFields: + out = QgsFields() + taken = set() + for existing in source_fields: + out.append(existing) + taken.add(existing.name()) + for name, kind in results.ELEVATION_FIELDS: + unique = name + suffix = 2 + while unique in taken: + unique = "%s_%d" % (name, suffix) + suffix += 1 + taken.add(unique) + out.append(field(unique, kind)) + return out diff --git a/geodonkey/processing/elevation_profile_algorithm.py b/geodonkey/processing/elevation_profile_algorithm.py new file mode 100644 index 0000000..ebf2568 --- /dev/null +++ b/geodonkey/processing/elevation_profile_algorithm.py @@ -0,0 +1,149 @@ +from __future__ import annotations + +from typing import Any, Dict + +from qgis.core import ( + QgsProcessing, + QgsProcessingException, + QgsProcessingParameterFeatureSink, + QgsProcessingParameterNumber, + QgsProcessingParameterPoint, + QgsWkbTypes, +) + +from .. import config, results, style +from ..errors import GeoDonkeyError +from ..i18n import tr +from .base import GeoDonkeyAlgorithm, attribution + + +class ElevationProfileAlgorithm(GeoDonkeyAlgorithm): + ICON = "profile.svg" + GROUP = "Elevation" + GROUP_ID = "elevation" + COST_KEY = "elevation_profile" + + START = "START" + END = "END" + MAX_POINTS = "MAX_POINTS" + STEP = "STEP" + OUTPUT = "OUTPUT" + OUTPUT_SEGMENTS = "OUTPUT_SEGMENTS" + + def createInstance(self): # noqa: N802 + return ElevationProfileAlgorithm() + + def name(self) -> str: + return "elevationprofile" + + def displayName(self) -> str: # noqa: N802 + return tr("Elevation profile") + + def shortHelpString(self) -> str: # noqa: N802 + return tr( + "

Samples the terrain along the straight line between two points " + "and returns one point per sample, carrying the distance from the " + "start and the elevation above sea level.

" + "

The service places the samples on the centres of its elevation " + "tiles. Maximum points is the upper limit (at most " + "{max_points}), Minimum spacing the smallest distance " + "between two samples (at least {min_step} m).

" + "

Samples without elevation data keep their place in the list " + "and have an empty elevation. Dropping them would " + "tear the distance axis apart.

" + "

Elevation data is available for Germany only. Points " + "outside are rejected before the call is sent.

" + "

The price follows the quantity: {coins} DonkeyCoins per " + "started {batch} points of Maximum points – {max_points} " + "points therefore cost {full} DC, once the {free} free calls of " + "the current hour are used up.

" + "

Elevation data by the surveying authorities of the German " + "federal states; the exact source of every sample is in the field " + "source.

" + ).format(max_points=config.ELEVATION_MAX_POINTS, + min_step=config.ELEVATION_MIN_STEP_METRES, + batch=config.ELEVATION_BILLING_BATCH, + coins=config.COIN_COSTS.get("elevation_profile", 2), + full=config.elevation_coins(config.ELEVATION_MAX_POINTS), + free=config.FREE_CALLS_PER_HOUR) + + def initAlgorithm(self, configuration=None): # noqa: N802 + self.addParameter(QgsProcessingParameterPoint( + self.START, tr("Start point"))) + + self.addParameter(QgsProcessingParameterPoint( + self.END, tr("End point"))) + + self.addParameter(QgsProcessingParameterNumber( + self.MAX_POINTS, tr("Maximum points"), + type=QgsProcessingParameterNumber.Type.Integer, + minValue=2, maxValue=config.ELEVATION_MAX_POINTS, + defaultValue=config.ELEVATION_MAX_POINTS)) + + self.addParameter(QgsProcessingParameterNumber( + self.STEP, tr("Minimum spacing (metres)"), + type=QgsProcessingParameterNumber.Type.Double, + minValue=config.ELEVATION_MIN_STEP_METRES, + defaultValue=config.ELEVATION_DEFAULT_STEP_METRES)) + + self.addParameter(QgsProcessingParameterFeatureSink( + self.OUTPUT, tr("Elevation profile"), + type=QgsProcessing.SourceType.TypeVectorPoint)) + + self.addParameter(QgsProcessingParameterFeatureSink( + self.OUTPUT_SEGMENTS, tr("Sections by gradient (optional)"), + type=QgsProcessing.SourceType.TypeVectorLine, + optional=True, createByDefault=False)) + + def processAlgorithm(self, parameters, context, feedback): # noqa: N802 + start = self.wgs84_point(parameters, self.START, context) + end = self.wgs84_point(parameters, self.END, context) + max_points = self.parameterAsInt(parameters, self.MAX_POINTS, context) + step = self.parameterAsDouble(parameters, self.STEP, context) + + api = self.client(feedback) + feedback.pushInfo(tr("Up to {count} points · {coins} DC").format( + count=max_points, + coins=config.elevation_coins(max_points, "elevation_profile"))) + feedback.setProgress(5) + try: + payload = api.elevation_profile(start, end, max_points=max_points, + step=step, feedback=feedback) + except GeoDonkeyError as exc: + self.fail(exc, feedback) + + if feedback.isCanceled(): + return {} + + feedback.setProgress(60) + self.report(api, feedback) + rows = results.profile_rows(payload) + feedback.pushInfo(results.profile_summary(payload)) + attribution(results.metadata(payload), feedback) + + covered = results.metadata(payload).get("covered") + if covered is not None and rows and covered < len(rows): + feedback.pushWarning(tr( + "{missing} of {count} points have no elevation data.").format( + missing=len(rows) - int(covered), count=len(rows))) + + sink, dest = self.make_sink(parameters, context, self.OUTPUT, + results.PROFILE_FIELDS, QgsWkbTypes.Type.Point) + if sink is None: + raise QgsProcessingException(tr("The output could not be created.")) + self.write(sink, results.PROFILE_FIELDS, rows, feedback) + self.style(context, dest, style.profile_point_plan()) + out: Dict[str, Any] = {self.OUTPUT: dest} + feedback.setProgress(85) + + if parameters.get(self.OUTPUT_SEGMENTS): + sink, dest = self.make_sink(parameters, context, self.OUTPUT_SEGMENTS, + results.PROFILE_SEGMENT_FIELDS, + QgsWkbTypes.Type.LineString) + if sink is not None: + self.write(sink, results.PROFILE_SEGMENT_FIELDS, + results.profile_segment_rows(payload), feedback) + self.style(context, dest, style.profile_segment_plan()) + out[self.OUTPUT_SEGMENTS] = dest + feedback.setProgress(100) + return out diff --git a/geodonkey/processing/isochrone_algorithm.py b/geodonkey/processing/isochrone_algorithm.py new file mode 100644 index 0000000..94e8fcb --- /dev/null +++ b/geodonkey/processing/isochrone_algorithm.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +from typing import Any, Dict + +from qgis.core import ( + QgsProcessing, + QgsProcessingException, + QgsProcessingParameterEnum, + QgsProcessingParameterFeatureSink, + QgsProcessingParameterPoint, + QgsProcessingParameterString, + QgsWkbTypes, +) + +from .. import config, results, style +from ..errors import GeoDonkeyError +from ..i18n import tr +from .base import GeoDonkeyAlgorithm, attribution + +MEASURE_MINUTES = 0 +MEASURE_KILOMETRES = 1 + + +class IsochroneAlgorithm(GeoDonkeyAlgorithm): + ICON = "isochrone.svg" + GROUP = "Routing" + GROUP_ID = "routing" + COST_KEY = "isochrone" + + POINT = "POINT" + MODE = "MODE" + MEASURE = "MEASURE" + VALUES = "VALUES" + OUTPUT = "OUTPUT" + + def createInstance(self): # noqa: N802 + return IsochroneAlgorithm() + + def name(self) -> str: + return "isochrone" + + def displayName(self) -> str: # noqa: N802 + return tr("Isochrone (reachable area)") + + def shortHelpString(self) -> str: # noqa: N802 + return tr( + "

Calculates the area that can be reached from a point within a " + "given travel time or distance, using the road network – not a " + "circle around the point.

" + "

Contours is a comma separated list, for example " + "5,10,15. Up to {rings} rings are calculated in a " + "single call and cost the same as one: travel time from {min_min} " + "to {max_min} minutes, distance from {min_km} to {max_km} " + "kilometres.

" + "

The rings are returned from the largest to the smallest, so " + "that drawing them in that order keeps all of them visible. The " + "field label holds the ring as readable text, for " + "example 10 min.

" + "

Data © OpenStreetMap contributors, ODbL.

" + ).format(rings=config.ISOCHRONE_MAX_RINGS, + min_min=int(config.ISOCHRONE_MIN_MINUTES), + max_min=int(config.ISOCHRONE_MAX_MINUTES), + min_km=config.ISOCHRONE_MIN_KILOMETRES, + max_km=int(config.ISOCHRONE_MAX_KILOMETRES)) + self.cost_note() + + def initAlgorithm(self, configuration=None): # noqa: N802 + self.addParameter(QgsProcessingParameterPoint( + self.POINT, tr("Start point"))) + + self.addParameter(QgsProcessingParameterEnum( + self.MODE, tr("Travel mode"), + options=[tr("Walking"), tr("Driving"), tr("Cycling")], + defaultValue=0)) + + self.addParameter(QgsProcessingParameterEnum( + self.MEASURE, tr("Measure"), + options=[tr("Travel time (minutes)"), tr("Distance (kilometres)")], + defaultValue=MEASURE_MINUTES)) + + self.addParameter(QgsProcessingParameterString( + self.VALUES, tr("Contours (comma separated)"), + defaultValue=config.ISOCHRONE_DEFAULT_MINUTES)) + + self.addParameter(QgsProcessingParameterFeatureSink( + self.OUTPUT, tr("Reachable area"), + type=QgsProcessing.SourceType.TypeVectorPolygon)) + + def processAlgorithm(self, parameters, context, feedback): # noqa: N802 + lon, lat = self.wgs84_point(parameters, self.POINT, context) + mode = config.TRAVEL_MODES[self.parameterAsEnum(parameters, self.MODE, context)] + measure = self.parameterAsEnum(parameters, self.MEASURE, context) + values = (self.parameterAsString(parameters, self.VALUES, context) or "").strip() + + api = self.client(feedback) + feedback.setProgress(5) + try: + if measure == MEASURE_KILOMETRES: + payload = api.isochrone(lon, lat, mode=mode, kilometres=values, + feedback=feedback) + else: + payload = api.isochrone(lon, lat, mode=mode, minutes=values, + feedback=feedback) + except GeoDonkeyError as exc: + self.fail(exc, feedback) + + if feedback.isCanceled(): + return {} + + feedback.setProgress(60) + self.report(api, feedback) + rows = results.isochrone_rows(payload) + if not rows: + feedback.pushWarning(tr("No reachable area was returned for this point.")) + + attribution(results.metadata(payload), feedback) + + sink, dest = self.make_sink(parameters, context, self.OUTPUT, + results.ISOCHRONE_FIELDS, + QgsWkbTypes.Type.MultiPolygon) + if sink is None: + raise QgsProcessingException(tr("The output could not be created.")) + written = self.write(sink, results.ISOCHRONE_FIELDS, rows, feedback) + self.style(context, dest, style.isochrone_plan( + [row.get("attrs") or {} for row in rows])) + feedback.pushInfo(tr("{count} rings written.").format(count=written)) + feedback.setProgress(100) + + out: Dict[str, Any] = {self.OUTPUT: dest} + return out diff --git a/geodonkey/processing/line_of_sight_algorithm.py b/geodonkey/processing/line_of_sight_algorithm.py new file mode 100644 index 0000000..38bdec8 --- /dev/null +++ b/geodonkey/processing/line_of_sight_algorithm.py @@ -0,0 +1,209 @@ +from __future__ import annotations + +from typing import Any, Dict + +from qgis.core import ( + QgsProcessing, + QgsProcessingException, + QgsProcessingParameterBoolean, + QgsProcessingParameterFeatureSink, + QgsProcessingParameterNumber, + QgsProcessingParameterPoint, + QgsWkbTypes, +) + +from .. import config, results, style +from ..errors import GeoDonkeyError +from ..i18n import tr +from .base import GeoDonkeyAlgorithm, attribution + + +class LineOfSightAlgorithm(GeoDonkeyAlgorithm): + ICON = "lineofsight.svg" + GROUP = "Elevation" + GROUP_ID = "elevation" + COST_KEY = "line_of_sight" + + FROM = "FROM" + TO = "TO" + HEIGHT_A = "HEIGHT_A" + HEIGHT_B = "HEIGHT_B" + CURVATURE = "CURVATURE" + K = "K" + STEP = "STEP" + MAX_POINTS = "MAX_POINTS" + OUTPUT_LINE = "OUTPUT_LINE" + OUTPUT_OBSTACLES = "OUTPUT_OBSTACLES" + OUTPUT_SAMPLES = "OUTPUT_SAMPLES" + OUTPUT_SEGMENTS = "OUTPUT_SEGMENTS" + + def createInstance(self): # noqa: N802 + return LineOfSightAlgorithm() + + def name(self) -> str: + return "lineofsight" + + def displayName(self) -> str: # noqa: N802 + return tr("Line of sight") + + def shortHelpString(self) -> str: # noqa: N802 + return tr( + "

Checks whether there is a clear line of sight between two " + "points, using the terrain model including earth curvature and " + "atmospheric refraction.

" + "

Height above ground is the height of the eye, the mast " + "or the roof edge at each end, from 0 to {max_height} m. If the " + "sight is blocked, the fields raise_a and " + "raise_b say how much higher one end would have to " + "be.

" + "

Three outputs: the sight line with the result in its " + "attributes, the obstacles as points at the spot where the " + "terrain rises highest above the ray, and optionally every " + "sample with terrain, ray and clearance – the basis for a " + "profile chart of your own.

" + "

Refraction factor k is {k_default} for the standard " + "atmosphere. k = 1 applies earth curvature without " + "refraction; switching curvature off applies neither.

" + "

Elevation data is available for Germany only.

" + "

Up to {free_metres} m of straight-line distance a run is " + "free, above that it costs {coins} DonkeyCoins. This endpoint " + "has its own allowance of {free_calls} calls per hour, replacing " + "the shared one – after that it requires an API key, as the only " + "tool in this plugin.

" + "

Elevation data by the surveying authorities of the German " + "federal states.

" + ).format(max_height=int(config.LOS_MAX_HEIGHT_METRES), + k_default=round(config.LOS_REFRACTION_K, 3), + free_metres=int(config.LOS_FREE_METRES), + coins=config.COIN_COSTS.get("line_of_sight", 2), + free_calls=config.ENDPOINT_FREE_CALLS.get("line_of_sight", 5)) + + def initAlgorithm(self, configuration=None): # noqa: N802 + self.addParameter(QgsProcessingParameterPoint( + self.FROM, tr("Observer point"))) + + self.addParameter(QgsProcessingParameterPoint( + self.TO, tr("Target point"))) + + self.addParameter(QgsProcessingParameterNumber( + self.HEIGHT_A, tr("Height above ground at the observer (metres)"), + type=QgsProcessingParameterNumber.Type.Double, + minValue=0.0, maxValue=config.LOS_MAX_HEIGHT_METRES, + defaultValue=config.LOS_DEFAULT_HEIGHT_METRES)) + + self.addParameter(QgsProcessingParameterNumber( + self.HEIGHT_B, tr("Height above ground at the target (metres)"), + type=QgsProcessingParameterNumber.Type.Double, + minValue=0.0, maxValue=config.LOS_MAX_HEIGHT_METRES, + defaultValue=config.LOS_DEFAULT_HEIGHT_METRES)) + + self.addParameter(QgsProcessingParameterBoolean( + self.CURVATURE, tr("Account for earth curvature"), defaultValue=True)) + + self.addParameter(QgsProcessingParameterNumber( + self.K, tr("Refraction factor k"), + type=QgsProcessingParameterNumber.Type.Double, + minValue=0.1, maxValue=10.0, + defaultValue=config.LOS_REFRACTION_K)) + + self.addParameter(QgsProcessingParameterNumber( + self.STEP, tr("Minimum spacing (metres)"), + type=QgsProcessingParameterNumber.Type.Double, + minValue=config.ELEVATION_MIN_STEP_METRES, + defaultValue=config.ELEVATION_DEFAULT_STEP_METRES)) + + self.addParameter(QgsProcessingParameterNumber( + self.MAX_POINTS, tr("Maximum samples"), + type=QgsProcessingParameterNumber.Type.Integer, + minValue=2, maxValue=config.ELEVATION_MAX_POINTS, + defaultValue=config.ELEVATION_MAX_POINTS)) + + self.addParameter(QgsProcessingParameterFeatureSink( + self.OUTPUT_LINE, tr("Sight line"), + type=QgsProcessing.SourceType.TypeVectorLine)) + + self.addParameter(QgsProcessingParameterFeatureSink( + self.OUTPUT_OBSTACLES, tr("Obstacles"), + type=QgsProcessing.SourceType.TypeVectorPoint)) + + self.addParameter(QgsProcessingParameterFeatureSink( + self.OUTPUT_SEGMENTS, tr("Sections by visibility (optional)"), + type=QgsProcessing.SourceType.TypeVectorLine, + optional=True, createByDefault=False)) + + self.addParameter(QgsProcessingParameterFeatureSink( + self.OUTPUT_SAMPLES, tr("Samples (optional)"), + type=QgsProcessing.SourceType.TypeVectorPoint, + optional=True, createByDefault=False)) + + def processAlgorithm(self, parameters, context, feedback): # noqa: N802 + start = self.wgs84_point(parameters, self.FROM, context) + end = self.wgs84_point(parameters, self.TO, context) + height_a = self.parameterAsDouble(parameters, self.HEIGHT_A, context) + height_b = self.parameterAsDouble(parameters, self.HEIGHT_B, context) + curvature = self.parameterAsBool(parameters, self.CURVATURE, context) + k = self.parameterAsDouble(parameters, self.K, context) + step = self.parameterAsDouble(parameters, self.STEP, context) + max_points = self.parameterAsInt(parameters, self.MAX_POINTS, context) + + wants_segments = bool(parameters.get(self.OUTPUT_SEGMENTS)) + wants_samples = bool(parameters.get(self.OUTPUT_SAMPLES)) or wants_segments + + api = self.client(feedback) + feedback.setProgress(5) + try: + payload = api.line_of_sight(start, end, height_a=height_a, + height_b=height_b, curvature=curvature, + k=k, step=step, max_points=max_points, + samples=wants_samples, feedback=feedback) + except GeoDonkeyError as exc: + self.fail(exc, feedback) + + if feedback.isCanceled(): + return {} + + feedback.setProgress(60) + self.report(api, feedback) + line_rows, obstacle_rows, sample_rows = results.sight_rows(payload, start, end) + feedback.pushInfo(results.sight_summary(payload)) + attribution(results.metadata(payload), feedback) + + out: Dict[str, Any] = {} + + sink, dest = self.make_sink(parameters, context, self.OUTPUT_LINE, + results.SIGHT_FIELDS, + QgsWkbTypes.Type.LineString) + if sink is None: + raise QgsProcessingException(tr("The output could not be created.")) + self.write(sink, results.SIGHT_FIELDS, line_rows, feedback) + self.style(context, dest, style.sight_segment_plan()) + out[self.OUTPUT_LINE] = dest + feedback.setProgress(70) + + sink, dest = self.make_sink(parameters, context, self.OUTPUT_OBSTACLES, + results.OBSTACLE_FIELDS, QgsWkbTypes.Type.Point) + if sink is not None: + self.write(sink, results.OBSTACLE_FIELDS, obstacle_rows, feedback) + self.style(context, dest, style.sight_obstacle_plan()) + out[self.OUTPUT_OBSTACLES] = dest + feedback.setProgress(80) + + if wants_segments: + sink, dest = self.make_sink(parameters, context, self.OUTPUT_SEGMENTS, + results.SIGHT_SEGMENT_FIELDS, + QgsWkbTypes.Type.LineString) + if sink is not None: + self.write(sink, results.SIGHT_SEGMENT_FIELDS, + results.sight_segment_rows(payload, start, end), feedback) + self.style(context, dest, style.sight_segment_plan()) + out[self.OUTPUT_SEGMENTS] = dest + feedback.setProgress(90) + + if parameters.get(self.OUTPUT_SAMPLES): + sink, dest = self.make_sink(parameters, context, self.OUTPUT_SAMPLES, + results.SAMPLE_FIELDS, QgsWkbTypes.Type.Point) + if sink is not None: + self.write(sink, results.SAMPLE_FIELDS, sample_rows, feedback) + out[self.OUTPUT_SAMPLES] = dest + feedback.setProgress(100) + return out diff --git a/geodonkey/processing/osm_algorithm.py b/geodonkey/processing/osm_algorithm.py new file mode 100644 index 0000000..4a94c0a --- /dev/null +++ b/geodonkey/processing/osm_algorithm.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +from typing import Any, Dict, Mapping + +from qgis.core import ( + QgsCoordinateReferenceSystem, + QgsFeature, + QgsFeatureSink, + QgsFields, + QgsProcessing, + QgsProcessingException, + QgsProcessingParameterEnum, + QgsProcessingParameterExtent, + QgsProcessingParameterFeatureSink, + QgsProcessingParameterNumber, + QgsProcessingParameterString, + QgsVectorLayer, + QgsWkbTypes, +) +from qgis.PyQt.QtCore import QVariant + +from .. import area as area_mod +from .. import config, geojson, layers, style +from ..client import split_collection +from ..compat import string_field +from ..errors import GeoDonkeyError +from ..i18n import tr +from .base import GeoDonkeyAlgorithm + +MODE_WORDS = 0 +MODE_TAGS = 1 +MODE_QUERY = 2 + +SINKS = ( + ("OUTPUT_POINTS", "Point", QgsWkbTypes.Type.Point, "Points"), + ("OUTPUT_LINES", "Line", QgsWkbTypes.Type.MultiLineString, "Lines"), + ("OUTPUT_POLYGONS", "Polygon", QgsWkbTypes.Type.MultiPolygon, "Areas"), +) + + +def output_fields() -> QgsFields: + fields = QgsFields() + for name, _kind in geojson.PROCESSING_FIELDS: + fields.append(string_field(name)) + return fields + + +class DonkeyOsmAlgorithm(GeoDonkeyAlgorithm): + ICON = "osm.svg" + GROUP = "OpenStreetMap" + GROUP_ID = "openstreetmap" + COST_KEY = "osm" + + MODE = "MODE" + QUERY = "QUERY" + EXTENT = "EXTENT" + TYPES = "TYPES" + LIMIT = "LIMIT" + + def createInstance(self): # noqa: N802 + return DonkeyOsmAlgorithm() + + def name(self) -> str: + return "donkeyosm" + + def displayName(self) -> str: # noqa: N802 + return tr("DonkeyOSM query") + + def shortHelpString(self) -> str: # noqa: N802 + return tr( + "

Queries OpenStreetMap data through the DonkeyOSM service of " + "geodonkey.com and returns it as three layers: points, lines and " + "areas.

" + "

Search mode decides how the query text is read: as " + "everyday words, as a comma separated list of OSM tags " + "(shop=bakery,amenity=cafe), or as a DonkeyOSM line " + "query (one selection per line).

" + "

Every run costs {coins} DonkeyCoins once the free calls " + "of the current hour are used up. The API key is taken from the " + "plugin settings.

" + "

All outputs share the same five fields: osm_type, " + "osm_id, osm_url, name and " + "tags. tags holds the complete OSM tags " + "as JSON text, so the schema stays the same no matter what the " + "query finds.

" + "

Data © OpenStreetMap contributors, ODbL.

" + ).format(coins=config.COIN_COSTS.get("osm", 3)) + + def initAlgorithm(self, configuration=None): # noqa: N802 + self.addParameter(QgsProcessingParameterEnum( + self.MODE, tr("Search mode"), + options=[tr("Plain language"), tr("OSM tags"), tr("Custom line query")], + defaultValue=MODE_WORDS)) + + self.addParameter(QgsProcessingParameterString( + self.QUERY, tr("Query"), multiLine=True)) + + self.addParameter(QgsProcessingParameterExtent( + self.EXTENT, tr("Area"))) + + self.addParameter(QgsProcessingParameterString( + self.TYPES, tr("OSM element types (node, way, relation)"), + defaultValue="", optional=True)) + + self.addParameter(QgsProcessingParameterNumber( + self.LIMIT, tr("Maximum objects"), + type=QgsProcessingParameterNumber.Type.Integer, + minValue=1, maxValue=config.OSM_LIMIT_PRO, + defaultValue=config.OSM_LIMIT_DEFAULT)) + + for key, _group, _wkb, label in SINKS: + self.addParameter(QgsProcessingParameterFeatureSink( + key, tr(label), type=QgsProcessing.SourceType.TypeVectorAnyGeometry, + optional=True, createByDefault=True)) + + def processAlgorithm(self, parameters, context, feedback): # noqa: N802 + mode = self.parameterAsEnum(parameters, self.MODE, context) + text = (self.parameterAsString(parameters, self.QUERY, context) or "").strip() + types = (self.parameterAsString(parameters, self.TYPES, context) or "").strip() + limit = self.parameterAsInt(parameters, self.LIMIT, context) + + if not text: + raise QgsProcessingException(tr("The query is empty.")) + + rect = self.parameterAsExtent(parameters, self.EXTENT, context, + QgsCoordinateReferenceSystem("EPSG:4326")) + if rect.isEmpty(): + raise QgsProcessingException(tr("The area is empty.")) + try: + area = area_mod.bbox_param(rect.xMinimum(), rect.yMinimum(), + rect.xMaximum(), rect.yMaximum()) + except GeoDonkeyError as exc: + raise QgsProcessingException(exc.message) + + client = self.client(feedback) + + feedback.pushInfo(tr("Area: {area}").format(area=area_mod.describe(area))) + feedback.setProgress(5) + + try: + if mode == MODE_QUERY: + payload = client.osm_query(text, area, limit=limit, feedback=feedback) + elif mode == MODE_TAGS: + payload = client.osm_search(area, tags=text, types=types, + limit=limit, feedback=feedback) + else: + payload = client.osm_search(area, words=text, types=types, + limit=limit, feedback=feedback) + except GeoDonkeyError as exc: + self.fail(exc, feedback) + + if feedback.isCanceled(): + return {} + + feedback.setProgress(50) + collection, meta = split_collection(payload) + self.report(client, feedback) + if meta.get("truncated"): + feedback.pushWarning(tr( + "The limit of {limit} was reached – the result is incomplete.").format( + limit=meta.get("limit") or limit)) + feedback.pushInfo(geojson.attribution(meta, config.DEFAULT_ATTRIBUTION)) + + buckets, without = geojson.split_by_geometry(collection) + if without: + feedback.pushInfo(tr("{count} objects without geometry were skipped.").format( + count=without)) + + results: Dict[str, Any] = {} + for index, (key, group, wkb, _label) in enumerate(SINKS): + if feedback.isCanceled(): + return results + sink, dest = self.parameterAsSink( + parameters, key, context, output_fields(), wkb, + QgsCoordinateReferenceSystem("EPSG:4326")) + if sink is None: + continue + part = buckets.get(group) + if part: + self._fill(sink, part, group, feedback) + self.style(context, dest, style.osm_plan(group)) + results[key] = dest + feedback.setProgress(50 + (index + 1) * 15) + + return results + + @staticmethod + def _fill(sink: QgsFeatureSink, part: Mapping[str, Any], group: str, + feedback) -> None: + folder = layers.result_folder() + path = geojson.write_collection(folder, "processing-%s" % group.lower(), part) + layer = QgsVectorLayer(geojson.ogr_uri(path, group, flatten=False), + "donkeyosm", "ogr") + if not layer.isValid(): + raise QgsProcessingException( + tr("QGIS could not read the result file: {path}").format(path=path)) + + names = [field.name() for field in layer.fields()] + for feature in layer.getFeatures(): + if feedback.isCanceled(): + return + raw = {name: _plain(feature[name]) for name in names} + row = geojson.processing_row({"properties": raw}) + out = QgsFeature(output_fields()) + out.setGeometry(feature.geometry()) + out.setAttributes([row[name] for name, _kind in geojson.PROCESSING_FIELDS]) + sink.addFeature(out, QgsFeatureSink.Flag.FastInsert) + + +def _plain(value): + if value is None: + return None + if isinstance(value, QVariant): + return None if value.isNull() else value.value() + return value diff --git a/geodonkey/processing/provider.py b/geodonkey/processing/provider.py new file mode 100644 index 0000000..41b481b --- /dev/null +++ b/geodonkey/processing/provider.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +from qgis.core import QgsProcessingProvider + +from ..compat import icon +from ..i18n import tr +from .elevation_points_algorithm import ElevationPointsAlgorithm +from .elevation_profile_algorithm import ElevationProfileAlgorithm +from .isochrone_algorithm import IsochroneAlgorithm +from .line_of_sight_algorithm import LineOfSightAlgorithm +from .osm_algorithm import DonkeyOsmAlgorithm +from .route_algorithm import RouteAlgorithm + +ALGORITHMS = ( + DonkeyOsmAlgorithm, + IsochroneAlgorithm, + RouteAlgorithm, + ElevationProfileAlgorithm, + ElevationPointsAlgorithm, + LineOfSightAlgorithm, +) + + +class GeoDonkeyProvider(QgsProcessingProvider): + def loadAlgorithms(self) -> None: # noqa: N802 + for algorithm in ALGORITHMS: + self.addAlgorithm(algorithm()) + + def id(self) -> str: # noqa: A003 + return "geodonkey" + + def name(self) -> str: + return "GeoDonkey" + + def longName(self) -> str: # noqa: N802 + return tr("GeoDonkey – OpenStreetMap, routing, elevation and map styles") + + def icon(self): + return icon("geodonkey.svg") + + def versionInfo(self) -> str: # noqa: N802 + return "1.12" diff --git a/geodonkey/processing/route_algorithm.py b/geodonkey/processing/route_algorithm.py new file mode 100644 index 0000000..e48aa5f --- /dev/null +++ b/geodonkey/processing/route_algorithm.py @@ -0,0 +1,181 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Tuple + +from qgis.core import ( + QgsProcessing, + QgsProcessingException, + QgsProcessingParameterBoolean, + QgsProcessingParameterEnum, + QgsProcessingParameterFeatureSink, + QgsProcessingParameterFeatureSource, + QgsProcessingParameterPoint, + QgsWkbTypes, +) + +from .. import config, results, settings, style +from ..errors import GeoDonkeyError +from ..i18n import tr +from .base import GeoDonkeyAlgorithm, attribution + +LANGUAGE_OPTIONS = ("", ) + tuple(config.ROUTE_LANGUAGES) + + +class RouteAlgorithm(GeoDonkeyAlgorithm): + ICON = "route.svg" + GROUP = "Routing" + GROUP_ID = "routing" + COST_KEY = "route" + + START = "START" + END = "END" + VIA = "VIA" + MODE = "MODE" + OPTIMIZE = "OPTIMIZE" + STEPS = "STEPS" + LANGUAGE = "LANGUAGE" + OUTPUT_ROUTE = "OUTPUT_ROUTE" + OUTPUT_POINTS = "OUTPUT_POINTS" + + def createInstance(self): # noqa: N802 + return RouteAlgorithm() + + def name(self) -> str: + return "route" + + def displayName(self) -> str: # noqa: N802 + return tr("Route") + + def shortHelpString(self) -> str: # noqa: N802 + return tr( + "

Calculates a route from the start through any stopovers to the " + "destination and returns two layers: the driven legs as lines and " + "the stops as points.

" + "

Stopovers is an optional point layer. Its features are " + "visited in the order of the layer. Start, stopovers and " + "destination together may be at most {max_points} points.

" + "

Optimise stopover order searches for the shortest " + "order of the stopovers; start and destination stay where they " + "are. The field stop then holds the driven order and " + "input the order as entered.

" + "

Turn-by-turn directions adds the instructions of each " + "leg to the field directions.

" + "

Maximum total length: {walking} km walking, {cycling} km " + "cycling, {driving} km driving.

" + "

Data © OpenStreetMap contributors, ODbL.

" + "

A run costs {plain} DonkeyCoins, {optimized} with optimised " + "stopover order, once the {free} free calls of the current " + "hour are used up. The API key is taken from the plugin settings " + "(Web ▸ GeoDonkey ▸ GeoDonkey settings).

" + ).format(max_points=config.ROUTE_MAX_POINTS, + walking=int(config.ROUTE_MAX_KILOMETRES["walking"]), + cycling=int(config.ROUTE_MAX_KILOMETRES["cycling"]), + driving=int(config.ROUTE_MAX_KILOMETRES["driving"]), + plain=config.COIN_COSTS.get("route", 2), + optimized=config.COIN_COSTS.get("route_optimized", 3), + free=config.FREE_CALLS_PER_HOUR) + + def initAlgorithm(self, configuration=None): # noqa: N802 + self.addParameter(QgsProcessingParameterPoint( + self.START, tr("Start"))) + + self.addParameter(QgsProcessingParameterPoint( + self.END, tr("Destination"))) + + self.addParameter(QgsProcessingParameterFeatureSource( + self.VIA, tr("Stopovers (optional point layer)"), + types=[QgsProcessing.SourceType.TypeVectorPoint], optional=True)) + + self.addParameter(QgsProcessingParameterEnum( + self.MODE, tr("Travel mode"), + options=[tr("Walking"), tr("Driving"), tr("Cycling")], + defaultValue=1)) + + self.addParameter(QgsProcessingParameterBoolean( + self.OPTIMIZE, tr("Optimise stopover order"), defaultValue=False)) + + self.addParameter(QgsProcessingParameterBoolean( + self.STEPS, tr("Turn-by-turn directions"), defaultValue=False)) + + self.addParameter(QgsProcessingParameterEnum( + self.LANGUAGE, tr("Language of the directions"), + options=[tr("Follow QGIS"), tr("German"), tr("English"), + tr("French"), tr("Spanish")], + defaultValue=0)) + + self.addParameter(QgsProcessingParameterFeatureSink( + self.OUTPUT_ROUTE, tr("Route"), + type=QgsProcessing.SourceType.TypeVectorLine)) + + self.addParameter(QgsProcessingParameterFeatureSink( + self.OUTPUT_POINTS, tr("Stops"), + type=QgsProcessing.SourceType.TypeVectorPoint)) + + def processAlgorithm(self, parameters, context, feedback): # noqa: N802 + stops = self._stops(parameters, context, feedback) + mode = config.TRAVEL_MODES[self.parameterAsEnum(parameters, self.MODE, context)] + optimize = self.parameterAsBool(parameters, self.OPTIMIZE, context) + steps = self.parameterAsBool(parameters, self.STEPS, context) + language = LANGUAGE_OPTIONS[ + self.parameterAsEnum(parameters, self.LANGUAGE, context)] + if not language: + language = settings.language() + + api = self.client(feedback) + feedback.pushInfo(tr("{count} points · {mode}").format( + count=len(stops), mode=mode)) + feedback.setProgress(5) + try: + payload = api.route(stops, mode=mode, optimize=optimize, steps=steps, + language=language, feedback=feedback) + except GeoDonkeyError as exc: + self.fail(exc, feedback) + + if feedback.isCanceled(): + return {} + + feedback.setProgress(60) + self.report(api, feedback) + legs, points_rows = results.route_rows(payload) + feedback.pushInfo(results.route_summary(payload)) + attribution(results.metadata(payload), feedback) + + out: Dict[str, Any] = {} + + sink, dest = self.make_sink(parameters, context, self.OUTPUT_ROUTE, + results.ROUTE_LEG_FIELDS, + QgsWkbTypes.Type.MultiLineString) + if sink is None: + raise QgsProcessingException(tr("The output could not be created.")) + self.write(sink, results.ROUTE_LEG_FIELDS, legs, feedback) + self.style(context, dest, style.route_leg_plan( + [row.get("attrs") or {} for row in legs])) + out[self.OUTPUT_ROUTE] = dest + feedback.setProgress(80) + + sink, dest = self.make_sink(parameters, context, self.OUTPUT_POINTS, + results.ROUTE_STOP_FIELDS, + QgsWkbTypes.Type.Point) + if sink is not None: + self.write(sink, results.ROUTE_STOP_FIELDS, points_rows, feedback) + self.style(context, dest, style.route_stop_plan( + [row.get("attrs") or {} for row in points_rows])) + out[self.OUTPUT_POINTS] = dest + feedback.setProgress(100) + return out + + def _stops(self, parameters, context, feedback) -> List[Tuple[float, float]]: + start = self.wgs84_point(parameters, self.START, context) + end = self.wgs84_point(parameters, self.END, context) + + via: List[Tuple[float, float]] = [] + source = self.parameterAsSource(parameters, self.VIA, context) + if source is not None: + via, _features = self.source_points(source, context, feedback) + + stops = [start] + via + [end] + if len(stops) > config.ROUTE_MAX_POINTS: + raise QgsProcessingException(tr( + "{count} points given, at most {limit} are allowed.").format( + count=len(stops), limit=config.ROUTE_MAX_POINTS)) + return stops diff --git a/geodonkey/results.py b/geodonkey/results.py new file mode 100644 index 0000000..bc17853 --- /dev/null +++ b/geodonkey/results.py @@ -0,0 +1,584 @@ +from __future__ import annotations + +import json +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple + +from . import points, style +from .i18n import tr + +Field = Tuple[str, str] +Row = Dict[str, Any] + + +def _row(geometry: Optional[Mapping[str, Any]], spec: Sequence[Field], + values: Mapping[str, Any]) -> Row: + return { + "geometry": geometry, + "attrs": {name: values.get(name) for name, _kind in spec}, + } + + +def _point(lon: Any, lat: Any) -> Optional[Dict[str, Any]]: + try: + x, y = float(lon), float(lat) + except (TypeError, ValueError): + return None + return {"type": "Point", "coordinates": [x, y]} + + +def _line(a: Sequence[float], b: Sequence[float]) -> Dict[str, Any]: + return {"type": "LineString", + "coordinates": [[float(a[0]), float(a[1])], + [float(b[0]), float(b[1])]]} + + +def _number(value: Any) -> Optional[float]: + if value is None or isinstance(value, bool): + return None + try: + return float(value) + except (TypeError, ValueError): + return None + + +def _text(value: Any) -> Optional[str]: + if value is None: + return None + if isinstance(value, (list, tuple)): + return ", ".join(str(item) for item in value if item is not None) or None + if isinstance(value, Mapping): + return json.dumps(value, ensure_ascii=False, sort_keys=True) + text = str(value) + return text or None + + +def _integer(value: Any) -> Optional[int]: + number = _number(value) + return None if number is None else int(number) + + +def metadata(payload: Mapping[str, Any]) -> Dict[str, Any]: + meta = payload.get("metadata") if isinstance(payload, Mapping) else None + return dict(meta) if isinstance(meta, Mapping) else {} + + +ISOCHRONE_FIELDS: Sequence[Field] = ( + ("contour", "double"), + ("unit", "string"), + ("label", "string"), + ("metric", "string"), + ("mode", "string"), + ("color", "string"), +) + + +def isochrone_rows(payload: Mapping[str, Any]) -> List[Row]: + rows: List[Row] = [] + for feature in (payload or {}).get("features") or []: + if not isinstance(feature, Mapping): + continue + props = feature.get("properties") + props = props if isinstance(props, Mapping) else {} + contour = _number(props.get("contour")) + unit = _text(props.get("unit")) or "" + label = "%s %s" % (points.fmt(contour), unit) if contour is not None else "" + rows.append(_row(feature.get("geometry"), ISOCHRONE_FIELDS, { + "contour": contour, + "unit": unit, + "label": label.strip(), + "metric": _text(props.get("metric")), + "mode": _text(props.get("mode")), + "color": _text(props.get("color")), + })) + return rows + + +ROUTE_LEG_FIELDS: Sequence[Field] = ( + ("leg", "integer"), + ("from_point", "integer"), + ("to_point", "integer"), + ("km", "double"), + ("minutes", "double"), + ("directions", "string"), + ("color", "string"), +) + +ROUTE_STOP_FIELDS: Sequence[Field] = ( + ("stop", "integer"), + ("input", "integer"), + ("role", "string"), + ("lon", "double"), + ("lat", "double"), + ("snapped_lon", "double"), + ("snapped_lat", "double"), + ("color", "string"), +) + + +def _directions(steps: Any) -> Optional[str]: + if not isinstance(steps, (list, tuple)): + return None + parts = [] + for entry in steps: + if not isinstance(entry, Mapping): + continue + text = _text(entry.get("instruction")) + if text: + parts.append(text) + return " · ".join(parts) or None + + +def route_rows(payload: Mapping[str, Any]) -> Tuple[List[Row], List[Row]]: + legs = [leg for leg in (payload or {}).get("legs") or [] if isinstance(leg, Mapping)] + by_leg = {_integer(leg.get("leg")): leg for leg in legs} + + collection = (payload or {}).get("routes") + features = (collection or {}).get("features") or [] if isinstance(collection, Mapping) else [] + + leg_rows: List[Row] = [] + for index, feature in enumerate(features): + if not isinstance(feature, Mapping): + continue + props = feature.get("properties") + props = props if isinstance(props, Mapping) else {} + number = _integer(props.get("leg")) + number = index if number is None else number + leg = by_leg.get(number) or {} + leg_rows.append(_row(feature.get("geometry"), ROUTE_LEG_FIELDS, { + "leg": number, + "from_point": _integer(props.get("from")), + "to_point": _integer(props.get("to")), + "km": _number(props.get("km")), + "minutes": _number(props.get("min")), + "directions": _directions(leg.get("steps")), + "color": style.leg_color(number), + })) + + stops = [stop for stop in (payload or {}).get("points") or [] + if isinstance(stop, Mapping)] + stop_rows: List[Row] = [] + for position, stop in enumerate(stops): + snapped = stop.get("snapped") + snapped = snapped if isinstance(snapped, (list, tuple)) and len(snapped) == 2 else None + if position == 0: + role = tr("start") + elif position == len(stops) - 1: + role = tr("destination") + else: + role = tr("stopover") + order = _integer(stop.get("order")) if stop.get("order") is not None else position + stop_rows.append(_row(_point(stop.get("lon"), stop.get("lat")), + ROUTE_STOP_FIELDS, { + "stop": order, + "input": _integer(stop.get("index")), + "role": role, + "lon": _number(stop.get("lon")), + "lat": _number(stop.get("lat")), + "snapped_lon": _number(snapped[0]) if snapped else None, + "snapped_lat": _number(snapped[1]) if snapped else None, + "color": style.leg_color(min(order if order is not None else position, + max(len(leg_rows) - 1, 0))), + })) + return leg_rows, stop_rows + + +def route_summary(payload: Mapping[str, Any]) -> str: + total = (payload or {}).get("total") + total = total if isinstance(total, Mapping) else {} + km = _number(total.get("km")) or 0.0 + minutes = _number(total.get("min")) or 0.0 + return tr("{km} km · {minutes} minutes").format( + km=points.fmt(round(km, 1)), minutes=points.fmt(round(minutes, 1))) + + +PROFILE_FIELDS: Sequence[Field] = ( + ("point", "integer"), + ("distance", "double"), + ("elevation", "double"), + ("source", "string"), + ("state", "string"), +) + + +def profile_rows(payload: Mapping[str, Any]) -> List[Row]: + rows: List[Row] = [] + for index, point in enumerate((payload or {}).get("points") or []): + if not isinstance(point, Mapping): + continue + rows.append(_row(_point(point.get("lon"), point.get("lat")), + PROFILE_FIELDS, { + "point": index, + "distance": _number(point.get("distance")), + "elevation": _number(point.get("elevation")), + "source": _text(point.get("attribution")), + "state": _text(point.get("state")), + })) + return rows + + +PROFILE_SEGMENT_FIELDS: Sequence[Field] = ( + ("segment", "integer"), + ("from_distance", "double"), + ("to_distance", "double"), + ("length", "double"), + ("rise", "double"), + ("slope", "double"), + ("slope_class", "string"), + ("color", "string"), +) + + +def _slope(run: Optional[float], low: Optional[float], + high: Optional[float]) -> Optional[float]: + if run is None or run <= 0 or low is None or high is None: + return None + return round((high - low) / run * 100.0, 2) + + +def _direction(rise: Optional[float]) -> str: + if rise is None: + return "none" + if rise > 0: + return "up" + if rise < 0: + return "down" + return "level" + + +def profile_segment_rows(payload: Mapping[str, Any]) -> List[Row]: + samples = [] + for point in (payload or {}).get("points") or []: + if not isinstance(point, Mapping): + continue + distance = _number(point.get("distance")) + lon, lat = _number(point.get("lon")), _number(point.get("lat")) + if distance is None or lon is None or lat is None: + continue + samples.append((distance, lon, lat, _number(point.get("elevation")))) + + runs: List[Dict[str, Any]] = [] + for index in range(1, len(samples)): + start, finish = samples[index - 1], samples[index] + slope = _slope(finish[0] - start[0], start[3], finish[3]) + name = style.slope_class(slope) + key = (name, _direction(None if slope is None else finish[3] - start[3])) + if runs and runs[-1]["key"] == key: + runs[-1]["points"].append(finish) + else: + runs.append({"key": key, "class": name, + "points": [start, finish]}) + + rows: List[Row] = [] + for number, run in enumerate(runs): + chain = run["points"] + first, last = chain[0], chain[-1] + length = last[0] - first[0] + rise = None if first[3] is None or last[3] is None else round(last[3] - first[3], 2) + rows.append(_row({"type": "LineString", + "coordinates": [[p[1], p[2]] for p in chain]}, + PROFILE_SEGMENT_FIELDS, { + "segment": number, + "from_distance": round(first[0], 2), + "to_distance": round(last[0], 2), + "length": round(length, 2), + "rise": rise, + "slope": _slope(length, first[3], last[3]), + "slope_class": run["class"], + "color": style.SLOPE_COLORS[run["class"]], + })) + return rows + + +def collection(rows: Sequence[Row]) -> Dict[str, Any]: + return { + "type": "FeatureCollection", + "features": [{"type": "Feature", + "geometry": row.get("geometry"), + "properties": dict(row.get("attrs") or {})} + for row in rows], + } + + +def profile_series(payload: Mapping[str, Any]) -> List[Tuple[float, Optional[float]]]: + out: List[Tuple[float, Optional[float]]] = [] + for point in (payload or {}).get("points") or []: + if not isinstance(point, Mapping): + continue + distance = _number(point.get("distance")) + if distance is None: + continue + out.append((distance, _number(point.get("elevation")))) + return out + + +def profile_coordinates(payload: Mapping[str, Any]) -> List[Tuple[float, float]]: + out: List[Tuple[float, float]] = [] + for point in (payload or {}).get("points") or []: + if not isinstance(point, Mapping): + continue + if _number(point.get("distance")) is None: + continue + lon = _number(point.get("lon")) + lat = _number(point.get("lat")) + out.append((float("nan") if lon is None else lon, + float("nan") if lat is None else lat)) + return out + + +def profile_summary(payload: Mapping[str, Any]) -> str: + rows = [_number(p.get("elevation")) for p in (payload or {}).get("points") or [] + if isinstance(p, Mapping)] + known = [value for value in rows if value is not None] + meta = metadata(payload) + length = _number(meta.get("length")) or 0.0 + if not known: + return tr("{count} points, no elevation data").format(count=len(rows)) + return tr("{count} points over {length} m · {low} to {high} m above sea level").format( + count=len(rows), length=points.fmt(round(length, 1)), + low=points.fmt(round(min(known), 1)), high=points.fmt(round(max(known), 1))) + + +ELEVATION_FIELDS: Sequence[Field] = ( + ("elevation", "double"), + ("ele_source", "string"), + ("ele_state", "string"), +) + + +def elevation_values(payload: Mapping[str, Any]) -> List[Dict[str, Any]]: + out: List[Dict[str, Any]] = [] + for point in (payload or {}).get("points") or []: + if not isinstance(point, Mapping): + out.append({"elevation": None, "ele_source": None, "ele_state": None}) + continue + out.append({ + "elevation": _number(point.get("elevation")), + "ele_source": _text(point.get("attribution")), + "ele_state": _text(point.get("state")), + }) + return out + + +ELEVATION_POINT_FIELDS: Sequence[Field] = ( + ("point", "integer"), + ("lon", "double"), + ("lat", "double"), + ("elevation", "double"), + ("ele_source", "string"), + ("ele_state", "string"), +) + + +def elevation_point_rows(payload: Mapping[str, Any], + coordinates: Sequence[Sequence[float]]) -> List[Row]: + values = elevation_values(payload) + rows: List[Row] = [] + for index, pair in enumerate(coordinates or []): + try: + lon, lat = float(pair[0]), float(pair[1]) + except (TypeError, ValueError, IndexError): + continue + found = values[index] if index < len(values) else {} + rows.append(_row(_point(lon, lat), ELEVATION_POINT_FIELDS, { + "point": index, + "lon": lon, + "lat": lat, + "elevation": found.get("elevation"), + "ele_source": found.get("ele_source"), + "ele_state": found.get("ele_state"), + })) + return rows + + +SIGHT_FIELDS: Sequence[Field] = ( + ("visible", "boolean"), + ("length", "double"), + ("air_line", "double"), + ("height_a", "double"), + ("height_b", "double"), + ("terrain_a", "double"), + ("terrain_b", "double"), + ("min_clearance", "double"), + ("min_clearance_at", "double"), + ("raise_a", "double"), + ("raise_b", "double"), + ("obstacles", "integer"), +) + +OBSTACLE_FIELDS: Sequence[Field] = ( + ("obstacle", "integer"), + ("distance", "double"), + ("from_distance", "double"), + ("to_distance", "double"), + ("height", "double"), + ("terrain", "double"), +) + +SAMPLE_FIELDS: Sequence[Field] = ( + ("point", "integer"), + ("distance", "double"), + ("terrain", "double"), + ("sight", "double"), + ("clearance", "double"), + ("drop", "double"), + ("blocked", "boolean"), +) + +SIGHT_SEGMENT_FIELDS: Sequence[Field] = ( + ("segment", "integer"), + ("visible", "boolean"), + ("from_distance", "double"), + ("to_distance", "double"), + ("length", "double"), + ("min_clearance", "double"), + ("color", "string"), +) + + +def _ends(payload: Mapping[str, Any], + fallback_start: Sequence[float], + fallback_end: Sequence[float]) -> Tuple[points.Point, points.Point]: + out = [] + for key, fallback in (("from", fallback_start), ("to", fallback_end)): + entry = (payload or {}).get(key) + entry = entry if isinstance(entry, Mapping) else {} + lon = _number(entry.get("lon")) + lat = _number(entry.get("lat")) + if lon is None or lat is None: + out.append((float(fallback[0]), float(fallback[1]))) + else: + out.append((lon, lat)) + return out[0], out[1] + + +def _placer(payload: Mapping[str, Any], start: Sequence[float], + end: Sequence[float]): + a, b = _ends(payload, start, end) + length = _number((payload or {}).get("length")) or 0.0 + + def place(distance: Any) -> Optional[Tuple[float, float]]: + metres = _number(distance) + if metres is None: + return None + fraction = metres / length if length > 0 else 0.0 + return points.along(a, b, fraction) + + return a, b, length, place + + +def sight_segment_rows(payload: Mapping[str, Any], start: Sequence[float], + end: Sequence[float]) -> List[Row]: + _a, _b, _length, place = _placer(payload, start, end) + + samples = [] + for entry in (payload or {}).get("samples") or []: + if not isinstance(entry, Mapping): + continue + distance = _number(entry.get("distance")) + spot = place(distance) + if distance is None or spot is None: + continue + samples.append((distance, spot, _number(entry.get("clearance")))) + + runs: List[Dict[str, Any]] = [] + for index in range(1, len(samples)): + before, now = samples[index - 1], samples[index] + blocked = now[2] is not None and now[2] < 0 + if runs and runs[-1]["blocked"] == blocked: + runs[-1]["points"].append(now) + else: + runs.append({"blocked": blocked, "points": [before, now]}) + + rows: List[Row] = [] + for number, run in enumerate(runs): + chain = run["points"] + clearances = [entry[2] for entry in chain if entry[2] is not None] + visible = not run["blocked"] + rows.append(_row({"type": "LineString", + "coordinates": [[spot[0], spot[1]] for _d, spot, _c in chain]}, + SIGHT_SEGMENT_FIELDS, { + "segment": number, + "visible": visible, + "from_distance": round(chain[0][0], 2), + "to_distance": round(chain[-1][0], 2), + "length": round(chain[-1][0] - chain[0][0], 2), + "min_clearance": round(min(clearances), 2) if clearances else None, + "color": style.sight_color(run["blocked"]), + })) + return rows + + +def sight_rows(payload: Mapping[str, Any], start: Sequence[float], + end: Sequence[float]) -> Tuple[List[Row], List[Row], List[Row]]: + a, b, length, spot = _placer(payload, start, end) + + def place(distance: Any) -> Optional[Dict[str, Any]]: + found = spot(distance) + return None if found is None else _point(found[0], found[1]) + + first = (payload or {}).get("from") + first = first if isinstance(first, Mapping) else {} + last = (payload or {}).get("to") + last = last if isinstance(last, Mapping) else {} + obstacles = [o for o in (payload or {}).get("obstacles") or [] if isinstance(o, Mapping)] + + line = _row(_line(a, b), SIGHT_FIELDS, { + "visible": bool((payload or {}).get("visible")), + "length": length, + "air_line": _number((payload or {}).get("air_line")), + "height_a": _number(first.get("height")), + "height_b": _number(last.get("height")), + "terrain_a": _number(first.get("terrain")), + "terrain_b": _number(last.get("terrain")), + "min_clearance": _number((payload or {}).get("min_clearance")), + "min_clearance_at": _number((payload or {}).get("min_clearance_distance")), + "raise_a": _number((payload or {}).get("required_extra_a")), + "raise_b": _number((payload or {}).get("required_extra_b")), + "obstacles": len(obstacles), + }) + + obstacle_rows = [ + _row(place(entry.get("distance")), OBSTACLE_FIELDS, { + "obstacle": index, + "distance": _number(entry.get("distance")), + "from_distance": _number(entry.get("from")), + "to_distance": _number(entry.get("to")), + "height": _number(entry.get("height")), + "terrain": _number(entry.get("terrain")), + }) + for index, entry in enumerate(obstacles) + ] + + sample_rows = [] + for index, entry in enumerate((payload or {}).get("samples") or []): + if not isinstance(entry, Mapping): + continue + clearance = _number(entry.get("clearance")) + sample_rows.append(_row(place(entry.get("distance")), SAMPLE_FIELDS, { + "point": index, + "distance": _number(entry.get("distance")), + "terrain": _number(entry.get("terrain")), + "sight": _number(entry.get("sight")), + "clearance": clearance, + "drop": _number(entry.get("drop")), + "blocked": None if clearance is None else clearance < 0, + })) + + return [line], obstacle_rows, sample_rows + + +def sight_summary(payload: Mapping[str, Any]) -> str: + length = _number((payload or {}).get("length")) or 0.0 + if (payload or {}).get("visible"): + clearance = _number((payload or {}).get("min_clearance")) + if clearance is None: + return tr("Clear line of sight over {length} m.").format( + length=points.fmt(round(length, 1))) + return tr("Clear line of sight over {length} m · {clearance} m to spare.").format( + length=points.fmt(round(length, 1)), + clearance=points.fmt(round(clearance, 1))) + obstacles = [o for o in (payload or {}).get("obstacles") or [] if isinstance(o, Mapping)] + raise_a = _number((payload or {}).get("required_extra_a")) or 0.0 + return tr("Blocked by {count} obstacle(s) · {raise_a} m more height at the " + "first point would clear it.").format( + count=len(obstacles), raise_a=points.fmt(round(raise_a, 1))) diff --git a/geodonkey/settings.py b/geodonkey/settings.py new file mode 100644 index 0000000..101f188 --- /dev/null +++ b/geodonkey/settings.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from qgis.core import QgsSettings + +from . import config + +_PREFIX = config.SETTINGS_GROUP + "/" + +DEFAULTS = { + "api_url": config.DEFAULT_API_URL, + "limit": config.OSM_LIMIT_DEFAULT, + "style": config.FALLBACK_STYLES[0]["id"], + "last_query": "", + "mode": "words", +} + + +def get(name: str, default=None): + fallback = DEFAULTS.get(name) if default is None else default + value = QgsSettings().value(_PREFIX + name, fallback) + if isinstance(fallback, int) and not isinstance(fallback, bool): + try: + return int(value) + except (TypeError, ValueError): + return fallback + return value + + +def set(name: str, value) -> None: # noqa: A001 + QgsSettings().setValue(_PREFIX + name, value) + + +def language() -> str: + locale = str(QgsSettings().value("locale/userLocale", "en") or "en") + return "de" if locale.lower().startswith("de") else "en" + + +def api_url() -> str: + return str(get("api_url") or config.DEFAULT_API_URL).rstrip("/") diff --git a/geodonkey/style.py b/geodonkey/style.py new file mode 100644 index 0000000..1ad23cd --- /dev/null +++ b/geodonkey/style.py @@ -0,0 +1,228 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Mapping, Optional, Sequence + +from .i18n import later, tr + + +HOUSE = "#002060" + +GREY = "#94a3b8" + +LEG_COLORS: Sequence[str] = ( + "#1d4ed8", + "#0891b2", + "#15803d", + "#ca8a04", + "#ea580c", + "#b91c1c", + "#9333ea", + "#be185d", + "#0f766e", +) + +SIGHT_COLORS: Mapping[str, str] = { + "clear": "#16a34a", + "blocked": "#dc2626", +} + +SLOPE_COLORS: Mapping[str, str] = { + "gentle": "#16a34a", + "moderate": "#eab308", + "steep": "#dc2626", + "unknown": GREY, +} + +SLOPE_GENTLE = 3.0 +SLOPE_MODERATE = 8.0 + +SLOPE_ORDER: Sequence[str] = ("gentle", "moderate", "steep", "unknown") + +SLOPE_LABELS: Mapping[str, str] = { + "gentle": later("under {limit} %"), + "moderate": later("{low} to {high} %"), + "steep": later("over {limit} %"), + "unknown": later("no elevation data"), +} + + +POINT_SIZE = 12.0 +POINT_OUTLINE = 1.0 +POINT_OPACITY = 0.7 + +LINE_WIDTH = 4.0 + +AREA_OUTLINE = 2.0 +AREA_OPACITY = 0.5 + + +def leg_color(index: Any) -> str: + try: + number = int(index) + except (TypeError, ValueError): + return HOUSE + return LEG_COLORS[number % len(LEG_COLORS)] + + +def slope_class(slope: Any) -> str: + if slope is None or isinstance(slope, bool): + return "unknown" + try: + value = abs(float(slope)) + except (TypeError, ValueError): + return "unknown" + if value != value: + return "unknown" + if value < SLOPE_GENTLE: + return "gentle" + if value <= SLOPE_MODERATE: + return "moderate" + return "steep" + + +def slope_color(slope: Any) -> str: + return SLOPE_COLORS[slope_class(slope)] + + +def sight_color(blocked: Any) -> str: + return SIGHT_COLORS["blocked" if blocked else "clear"] + + +def slope_label(name: str) -> str: + pattern = tr(SLOPE_LABELS.get(name, "")) + return pattern.format(limit=SLOPE_GENTLE if name == "gentle" else SLOPE_MODERATE, + low=SLOPE_GENTLE, high=SLOPE_MODERATE) + + +def _single(geometry: str, color: str) -> Dict[str, Any]: + return {"kind": "single", "geometry": geometry, "color": color} + + +def _categories(geometry: str, field: str, + entries: Sequence[Mapping[str, Any]]) -> Optional[Dict[str, Any]]: + if not entries: + return None + return {"kind": "categories", "geometry": geometry, "field": field, + "entries": [dict(entry) for entry in entries]} + + +def _distinct(properties: Sequence[Mapping[str, Any]], field: str, + label_of, color_of) -> List[Dict[str, Any]]: + out: List[Dict[str, Any]] = [] + seen = set() + for props in properties or []: + if not isinstance(props, Mapping): + continue + value = props.get(field) + if value is None: + continue + try: + key = (type(value).__name__, value) + if key in seen: + continue + seen.add(key) + except TypeError: + continue + out.append({"value": value, "color": color_of(props) or HOUSE, + "label": label_of(props)}) + return out + + +def _own_color(props: Mapping[str, Any]) -> Optional[str]: + color = props.get("color") + if isinstance(color, str) and color.strip(): + return color.strip() + return None + + +def isochrone_plan(properties: Sequence[Mapping[str, Any]]) -> Optional[Dict[str, Any]]: + return _categories("Polygon", "label", + _distinct(properties, "label", + lambda props: str(props.get("label") or ""), + _own_color)) + + +def route_leg_plan(properties: Sequence[Mapping[str, Any]]) -> Optional[Dict[str, Any]]: + def label(props: Mapping[str, Any]) -> str: + try: + number = int(props.get("leg")) + 1 + except (TypeError, ValueError): + return tr("Leg") + return tr("Leg {number}").format(number=number) + + return _categories("Line", "leg", _distinct(properties, "leg", label, _own_color)) + + +def route_stop_plan(properties: Sequence[Mapping[str, Any]]) -> Optional[Dict[str, Any]]: + def label(props: Mapping[str, Any]) -> str: + role = props.get("role") + try: + number = int(props.get("stop")) + 1 + except (TypeError, ValueError): + return str(role or "") + return "%d · %s" % (number, role) if role else str(number) + + return _categories("Point", "stop", _distinct(properties, "stop", label, _own_color)) + + +def profile_segment_plan() -> Dict[str, Any]: + return { + "kind": "categories", "geometry": "Line", "field": "slope_class", + "entries": [{"value": name, "color": SLOPE_COLORS[name], + "label": slope_label(name)} for name in SLOPE_ORDER], + } + + +def profile_point_plan() -> Dict[str, Any]: + return _single("Point", HOUSE) + + +def sight_segment_plan() -> Dict[str, Any]: + return { + "kind": "categories", "geometry": "Line", "field": "visible", + "entries": [ + {"value": True, "color": SIGHT_COLORS["clear"], "label": tr("clear view")}, + {"value": False, "color": SIGHT_COLORS["blocked"], "label": tr("blocked")}, + ], + } + + +def sight_obstacle_plan() -> Dict[str, Any]: + return _single("Point", SIGHT_COLORS["blocked"]) + + +def elevation_plan() -> Dict[str, Any]: + return _single("Point", HOUSE) + + +def osm_plan(geometry: str) -> Dict[str, Any]: + return _single(geometry, HOUSE) + + +KEYS = ("isochrone", "route", "profile", "sight", "elevation", "osm") + + +def plan(key: str, geometry: str, + properties: Sequence[Mapping[str, Any]] = ()) -> Optional[Dict[str, Any]]: + if key == "isochrone" and geometry == "Polygon": + return isochrone_plan(properties) + if key == "route": + if geometry == "Line": + return route_leg_plan(properties) + if geometry == "Point": + return route_stop_plan(properties) + if key == "profile": + if geometry == "Line": + return profile_segment_plan() + if geometry == "Point": + return profile_point_plan() + if key == "sight": + if geometry == "Line": + return sight_segment_plan() + if geometry == "Point": + return sight_obstacle_plan() + if key == "elevation" and geometry == "Point": + return elevation_plan() + if key == "osm": + return osm_plan(geometry) + return None diff --git a/geodonkey/task.py b/geodonkey/task.py new file mode 100644 index 0000000..e7154c1 --- /dev/null +++ b/geodonkey/task.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +from typing import Any, Callable, Optional + +from qgis.core import QgsApplication, QgsFeedback, QgsTask + +from .errors import GeoDonkeyError + + +class ApiTask(QgsTask): + def __init__(self, description: str, work: Callable[[QgsFeedback], Any], + on_done: Callable[[Any], None], + on_error: Callable[[GeoDonkeyError], None]) -> None: + super().__init__(description, QgsTask.Flag.CanCancel) + self._work = work + self._on_done = on_done + self._on_error = on_error + self._feedback = QgsFeedback() + self._result: Any = None + self._error: Optional[BaseException] = None + + def run(self) -> bool: + try: + self._result = self._work(self._feedback) + except BaseException as exc: # noqa: BLE001 + self._error = exc + return False + return not self._feedback.isCanceled() + + def cancel(self) -> None: + self._feedback.cancel() + super().cancel() + + def finished(self, ok: bool) -> None: + if self.isCanceled(): + return + if not ok or self._error is not None: + error = self._error + if not isinstance(error, GeoDonkeyError): + error = GeoDonkeyError(str(error) if error else "unknown error", + detail=repr(error)) + self._on_error(error) + return + self._on_done(self._result) + + +def run(description: str, work: Callable[[QgsFeedback], Any], + on_done: Callable[[Any], None], + on_error: Callable[[GeoDonkeyError], None]) -> ApiTask: + task = ApiTask(description, work, on_done, on_error) + QgsApplication.taskManager().addTask(task) + return task diff --git a/geodonkey/upload.py b/geodonkey/upload.py new file mode 100644 index 0000000..f3f9c10 --- /dev/null +++ b/geodonkey/upload.py @@ -0,0 +1,198 @@ +from __future__ import annotations + +import re +import secrets +from datetime import datetime +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple + +from . import config +from .i18n import tr + +ACCEPTED_SUFFIXES = (".geojson", ".json", ".csv", ".kml", ".zip") + +SUFFIX = ".geojson" + + +def boundary() -> str: + return "----GeoDonkeyQGIS" + secrets.token_hex(16) + + +def multipart(fields: Mapping[str, str], filename: str, data: bytes, + field: str = "file", + content_type: str = "application/geo+json", + mark: str = "") -> Tuple[bytes, str]: + line = mark or boundary() + out: List[bytes] = [] + for name, value in fields.items(): + out.append(b"--" + line.encode("ascii") + b"\r\n") + out.append(('Content-Disposition: form-data; name="%s"\r\n\r\n' + % name).encode("utf-8")) + out.append(("%s\r\n" % value).encode("utf-8")) + out.append(b"--" + line.encode("ascii") + b"\r\n") + out.append(('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' + % (field, filename)).encode("utf-8")) + out.append(("Content-Type: %s\r\n\r\n" % content_type).encode("ascii")) + out.append(data) + out.append(b"\r\n--" + line.encode("ascii") + b"--\r\n") + return b"".join(out), "multipart/form-data; boundary=" + line + + +def filename_for(name: str) -> str: + clean = re.sub(r"[^0-9A-Za-zÄÖÜäöüß._ -]+", "", (name or "").strip()) + clean = re.sub(r"[\s_]+", "_", clean).strip("._-") + if not clean: + clean = "qgis-layer" + if len(clean) > 60: + clean = clean[:60].rstrip("._-") + lower = clean.lower() + for suffix in ACCEPTED_SUFFIXES: + if lower.endswith(suffix): + return clean[:-len(suffix)] + SUFFIX + return clean + SUFFIX + + +def complaint(objects: int, size: int = 0, pro: bool = False) -> str: + count = int(objects or 0) + if count <= 0: + return tr("The layer has no features to upload.") + limit = config.upload_object_limit(pro) + if count > limit: + if pro: + return tr("At most {limit} features per dataset.").format(limit=limit) + return tr("At most {limit} features per dataset. Larger datasets need " + "an active Pro subscription.").format(limit=limit) + if size and size > config.UPLOAD_MAX_BYTES: + return tr("The file would be {size}; the limit is {limit}.").format( + size=pretty_size(size), limit=pretty_size(config.UPLOAD_MAX_BYTES)) + return "" + + +def clamp_ttl(days: int, pro: bool = False) -> int: + try: + value = int(days) + except (TypeError, ValueError): + value = config.UPLOAD_DEFAULT_TTL_DAYS + return max(1, min(value, config.upload_ttl_limit(pro))) + + +def pretty_size(size: int) -> str: + value = float(size or 0) + for unit in ("B", "kB", "MB"): + if value < 1024.0 or unit == "MB": + if unit == "B": + return "%d %s" % (int(value), unit) + return ("%.1f %s" % (value, unit)).replace(".0 ", " ") + value /= 1024.0 + return "%d B" % int(size or 0) + + +def parse_time(text: str) -> Optional[datetime]: + raw = (text or "").strip() + if not raw: + return None + if raw.endswith("Z"): + raw = raw[:-1] + try: + stamp = datetime.fromisoformat(raw) + except ValueError: + return None + return stamp.replace(tzinfo=None) + + +def days_left(expires_at: str, now: Optional[datetime] = None) -> Optional[int]: + stamp = parse_time(expires_at) + if stamp is None: + return None + moment = now or datetime.utcnow() + seconds = (stamp - moment).total_seconds() + if seconds <= 0: + return 0 + return int((seconds + 86399) // 86400) + + +def describe(meta: Mapping[str, Any], now: Optional[datetime] = None) -> str: + name = str(meta.get("filename") or meta.get("upload_id") or "?") + parts = [name] + count = meta.get("object_count") + if isinstance(count, int): + parts.append(tr("{count} feature(s)").format(count=count)) + left = days_left(str(meta.get("expires_at") or ""), now) + if left is None: + pass + elif left <= 0: + parts.append(tr("expired")) + elif left == 1: + parts.append(tr("1 more day")) + else: + parts.append(tr("{days} more days").format(days=left)) + return " · ".join(parts) + + +def datasets(payload: Any) -> List[Dict[str, Any]]: + if isinstance(payload, Mapping): + rows = payload.get("datasets") + elif isinstance(payload, Sequence) and not isinstance(payload, (str, bytes)): + rows = payload + else: + rows = None + if not isinstance(rows, (list, tuple)): + return [] + return [dict(row) for row in rows if isinstance(row, Mapping)] + + +GEOJSON_PATH = "/uploads/{id}/geojson" + + +def dataset_path(upload_id: str) -> str: + from urllib.parse import quote + + return GEOJSON_PATH.format(id=quote((upload_id or "").strip(), safe="")) + + +def share_url(base_url: str, upload_id: str) -> str: + ident = (upload_id or "").strip() + if not ident: + return "" + return config.api_endpoint(base_url, dataset_path(ident)) + + +VIEW_PATH = "/view/{id}" + + +def viewer_url(base_url: str, upload_id: str) -> str: + from urllib.parse import quote + + ident = (upload_id or "").strip() + if not ident: + return "" + base = (base_url or config.DEFAULT_API_URL).strip().rstrip("/") + if base.lower() != config.DEFAULT_API_URL.rstrip("/").lower(): + return "" + return (config.WEBSITE_URL.rstrip("/") + + VIEW_PATH.format(id=quote(ident, safe=""))) + + +def share_warning(viewer: bool = True) -> str: + if viewer: + return tr("The link opens the dataset on a map at geodonkey.com - no " + "account and no API key needed. For colleagues working in " + "QGIS, 'Copy data address' gives the direct link to the " + "features instead.") + return tr("The link returns the data as a GeoJSON file and needs no API key: " + "anyone who has it can download them, and in QGIS it opens " + "directly as a vector layer.") + + +def receipt(meta: Mapping[str, Any]) -> str: + count = meta.get("object_count") + coins = meta.get("cost") + parts = [tr("{count} feature(s) uploaded.").format( + count=count if isinstance(count, int) else 0)] + if isinstance(coins, int) and coins > 0: + parts.append(tr("{coins} DC charged.").format(coins=coins)) + else: + parts.append(tr("Free of charge.")) + left = days_left(str(meta.get("expires_at") or "")) + if left: + parts.append(tr("Stored for {days} more day(s).").format(days=left)) + return " ".join(parts)