mirror of
https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer.git
synced 2026-06-17 11:22:53 +02:00
Compare commits
64 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 89e596802f | |||
| 4ea679ec9e | |||
| 830537f1a4 | |||
| 785b83c9c5 | |||
| 493696c67b | |||
| b313fc6db0 | |||
| 9a935261e6 | |||
| a4e30bf334 | |||
| 56389e27d7 | |||
| c8d42e2459 | |||
| a6ebbce4cf | |||
| 88149fbb30 | |||
| c0d054d22a | |||
| ba41039468 | |||
| 499b3b3f0a | |||
| 54f154b264 | |||
| c679e776df | |||
| a5604dfaa8 | |||
| 11f44d025b | |||
| 7f3b2b46fb | |||
| be53edefa5 | |||
| 3be7832b40 | |||
| 8c0c540fa4 | |||
| 8088b32661 | |||
| c17275ef66 | |||
| 9ec866f1d2 | |||
| 5a951edec7 | |||
| 8825ac3272 | |||
| 3957b87a2b | |||
| 158f623574 | |||
| d54b4e476e | |||
| 6b39a05207 | |||
| f9bfe02597 | |||
| 36835c825d | |||
| d6d520e612 | |||
| 78bad9aaa7 | |||
| 9559712af9 | |||
| 9ccb9319b4 | |||
| a696872b0c | |||
| bcde600433 | |||
| 8b71d75701 | |||
| 6131c7ff9d | |||
| 396f4fbb4e | |||
| 0f07a40bb0 | |||
| 0d3bd0a696 | |||
| 777b1900d5 | |||
| 27303fdf53 | |||
| fbe5c6a113 | |||
| 8693179fa9 | |||
| a314dd3758 | |||
| e61759064e | |||
| 3fb60a87f9 | |||
| 0945d9b6c0 | |||
| b22629404b | |||
| 4c390f20f3 | |||
| 53ec54cdf7 | |||
| b37f9184b5 | |||
| 9dc00a508b | |||
| 8066c61ca4 | |||
| dec29ca61c | |||
| 656a94a938 | |||
| d1f095df80 | |||
| 1cc1850fb5 | |||
| 69b6edce96 |
@@ -0,0 +1,30 @@
|
||||
name: Release QGIS Plugin
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
build-and-release:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
# 1. Stáhne kód z repozitáře
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
# 2. Vytvoří ZIP (předpokládá, že kód je ve složce 'amcr_viewer')
|
||||
- name: Zip Plugin
|
||||
run: |
|
||||
# Zabalíme složku amcr_viewer do souboru amcr_viewer.zip
|
||||
# -r = rekurzivně, -x = ignorovat skryté git soubory
|
||||
zip -r amcr_viewer.zip amcr_viewer -x "*.git*"
|
||||
|
||||
# 3. Nahraje ZIP k Releasu
|
||||
- name: Upload Release Asset
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
with:
|
||||
files: amcr_viewer.zip
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -205,3 +205,10 @@ cython_debug/
|
||||
marimo/_static/
|
||||
marimo/_lsp/
|
||||
__marimo__/
|
||||
|
||||
|
||||
|
||||
README_files/
|
||||
README.html
|
||||
amcr_viewer.zip
|
||||
pyrefly.toml
|
||||
|
||||
+4
-1
@@ -15,6 +15,9 @@ authors:
|
||||
affiliation: >-
|
||||
Czech Academy of Sciences, Institute of Archaeology,
|
||||
Brno
|
||||
identifiers:
|
||||
- type: doi
|
||||
value: 10.5281/zenodo.18609813
|
||||
repository-code: 'https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer'
|
||||
abstract: >-
|
||||
This QGIS plugin is intended for downloading the data
|
||||
@@ -23,5 +26,5 @@ abstract: >-
|
||||
Republic (AMCR). As of now, only publicly accessible data
|
||||
can be downloaded.
|
||||
license: GPL-3.0
|
||||
version: '1.0'
|
||||
version: '1.0.1'
|
||||
date-released: '2026-02-11'
|
||||
|
||||
@@ -1,244 +0,0 @@
|
||||
#/***************************************************************************
|
||||
# AmcrViewer
|
||||
#
|
||||
# Viewing and downloading the AMČR data.
|
||||
# -------------------
|
||||
# begin : 2026-02-03
|
||||
# git sha : $Format:%H$
|
||||
# copyright : (C) 2026 by David Spáčil
|
||||
# email : spacil@arub.cz
|
||||
# ***************************************************************************/
|
||||
#
|
||||
#/***************************************************************************
|
||||
# * *
|
||||
# * This program is free software; you can redistribute it and/or modify *
|
||||
# * it under the terms of the GNU General Public License as published by *
|
||||
# * the Free Software Foundation; either version 2 of the License, or *
|
||||
# * (at your option) any later version. *
|
||||
# * *
|
||||
# ***************************************************************************/
|
||||
|
||||
#################################################
|
||||
# Edit the following to match your sources lists
|
||||
#################################################
|
||||
|
||||
|
||||
#Add iso code for any locales you want to support here (space separated)
|
||||
# default is no locales
|
||||
# LOCALES = af
|
||||
LOCALES =
|
||||
|
||||
# If locales are enabled, set the name of the lrelease binary on your system. If
|
||||
# you have trouble compiling the translations, you may have to specify the full path to
|
||||
# lrelease
|
||||
#LRELEASE = lrelease
|
||||
#LRELEASE = lrelease-qt4
|
||||
|
||||
|
||||
# translation
|
||||
SOURCES = \
|
||||
__init__.py \
|
||||
amcr_viewer.py amcr_viewer_dialog.py
|
||||
|
||||
PLUGINNAME = amcr_viewer
|
||||
|
||||
PY_FILES = \
|
||||
__init__.py \
|
||||
amcr_viewer.py amcr_viewer_dialog.py
|
||||
|
||||
UI_FILES = amcr_viewer_dialog_base.ui
|
||||
|
||||
EXTRAS = metadata.txt icon.png
|
||||
|
||||
EXTRA_DIRS =
|
||||
|
||||
COMPILED_RESOURCE_FILES = resources.py
|
||||
|
||||
PEP8EXCLUDE=pydev,resources.py,conf.py,third_party,ui
|
||||
|
||||
# QGISDIR points to the location where your plugin should be installed.
|
||||
# This varies by platform, relative to your HOME directory:
|
||||
# * Linux:
|
||||
# .local/share/QGIS/QGIS3/profiles/default/python/plugins/
|
||||
# * Mac OS X:
|
||||
# Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins
|
||||
# * Windows:
|
||||
# AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins'
|
||||
|
||||
QGISDIR=C:\Users\Spacil\AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins
|
||||
|
||||
#################################################
|
||||
# Normally you would not need to edit below here
|
||||
#################################################
|
||||
|
||||
HELP = help/build/html
|
||||
|
||||
PLUGIN_UPLOAD = $(c)/plugin_upload.py
|
||||
|
||||
RESOURCE_SRC=$(shell grep '^ *<file' resources.qrc | sed 's@</file>@@g;s/.*>//g' | tr '\n' ' ')
|
||||
|
||||
.PHONY: default
|
||||
default:
|
||||
@echo While you can use make to build and deploy your plugin, pb_tool
|
||||
@echo is a much better solution.
|
||||
@echo A Python script, pb_tool provides platform independent management of
|
||||
@echo your plugins and runs anywhere.
|
||||
@echo You can install pb_tool using: pip install pb_tool
|
||||
@echo See https://g-sherman.github.io/plugin_build_tool/ for info.
|
||||
|
||||
compile: $(COMPILED_RESOURCE_FILES)
|
||||
|
||||
%.py : %.qrc $(RESOURCES_SRC)
|
||||
pyrcc5 -o $*.py $<
|
||||
|
||||
%.qm : %.ts
|
||||
$(LRELEASE) $<
|
||||
|
||||
test: compile transcompile
|
||||
@echo
|
||||
@echo "----------------------"
|
||||
@echo "Regression Test Suite"
|
||||
@echo "----------------------"
|
||||
|
||||
@# Preceding dash means that make will continue in case of errors
|
||||
@-export PYTHONPATH=`pwd`:$(PYTHONPATH); \
|
||||
export QGIS_DEBUG=0; \
|
||||
export QGIS_LOG_FILE=/dev/null; \
|
||||
nosetests -v --with-id --with-coverage --cover-package=. \
|
||||
3>&1 1>&2 2>&3 3>&- || true
|
||||
@echo "----------------------"
|
||||
@echo "If you get a 'no module named qgis.core error, try sourcing"
|
||||
@echo "the helper script we have provided first then run make test."
|
||||
@echo "e.g. source run-env-linux.sh <path to qgis install>; make test"
|
||||
@echo "----------------------"
|
||||
|
||||
deploy: compile doc transcompile
|
||||
@echo
|
||||
@echo "------------------------------------------"
|
||||
@echo "Deploying plugin to your .qgis2 directory."
|
||||
@echo "------------------------------------------"
|
||||
# The deploy target only works on unix like operating system where
|
||||
# the Python plugin directory is located at:
|
||||
# $HOME/$(QGISDIR)/python/plugins
|
||||
mkdir -p $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
|
||||
cp -vf $(PY_FILES) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
|
||||
cp -vf $(UI_FILES) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
|
||||
cp -vf $(COMPILED_RESOURCE_FILES) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
|
||||
cp -vf $(EXTRAS) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
|
||||
cp -vfr i18n $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
|
||||
cp -vfr $(HELP) $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)/help
|
||||
# Copy extra directories if any
|
||||
(foreach EXTRA_DIR,(EXTRA_DIRS), cp -R (EXTRA_DIR) (HOME)/(QGISDIR)/python/plugins/(PLUGINNAME)/;)
|
||||
|
||||
|
||||
# The dclean target removes compiled python files from plugin directory
|
||||
# also deletes any .git entry
|
||||
dclean:
|
||||
@echo
|
||||
@echo "-----------------------------------"
|
||||
@echo "Removing any compiled python files."
|
||||
@echo "-----------------------------------"
|
||||
find $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) -iname "*.pyc" -delete
|
||||
find $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME) -iname ".git" -prune -exec rm -Rf {} \;
|
||||
|
||||
|
||||
derase:
|
||||
@echo
|
||||
@echo "-------------------------"
|
||||
@echo "Removing deployed plugin."
|
||||
@echo "-------------------------"
|
||||
rm -Rf $(HOME)/$(QGISDIR)/python/plugins/$(PLUGINNAME)
|
||||
|
||||
zip: deploy dclean
|
||||
@echo
|
||||
@echo "---------------------------"
|
||||
@echo "Creating plugin zip bundle."
|
||||
@echo "---------------------------"
|
||||
# The zip target deploys the plugin and creates a zip file with the deployed
|
||||
# content. You can then upload the zip file on http://plugins.qgis.org
|
||||
rm -f $(PLUGINNAME).zip
|
||||
cd $(HOME)/$(QGISDIR)/python/plugins; zip -9r $(CURDIR)/$(PLUGINNAME).zip $(PLUGINNAME)
|
||||
|
||||
package: compile
|
||||
# Create a zip package of the plugin named $(PLUGINNAME).zip.
|
||||
# This requires use of git (your plugin development directory must be a
|
||||
# git repository).
|
||||
# To use, pass a valid commit or tag as follows:
|
||||
# make package VERSION=Version_0.3.2
|
||||
@echo
|
||||
@echo "------------------------------------"
|
||||
@echo "Exporting plugin to zip package. "
|
||||
@echo "------------------------------------"
|
||||
rm -f $(PLUGINNAME).zip
|
||||
git archive --prefix=$(PLUGINNAME)/ -o $(PLUGINNAME).zip $(VERSION)
|
||||
echo "Created package: $(PLUGINNAME).zip"
|
||||
|
||||
upload: zip
|
||||
@echo
|
||||
@echo "-------------------------------------"
|
||||
@echo "Uploading plugin to QGIS Plugin repo."
|
||||
@echo "-------------------------------------"
|
||||
$(PLUGIN_UPLOAD) $(PLUGINNAME).zip
|
||||
|
||||
transup:
|
||||
@echo
|
||||
@echo "------------------------------------------------"
|
||||
@echo "Updating translation files with any new strings."
|
||||
@echo "------------------------------------------------"
|
||||
@chmod +x scripts/update-strings.sh
|
||||
@scripts/update-strings.sh $(LOCALES)
|
||||
|
||||
transcompile:
|
||||
@echo
|
||||
@echo "----------------------------------------"
|
||||
@echo "Compiled translation files to .qm files."
|
||||
@echo "----------------------------------------"
|
||||
@chmod +x scripts/compile-strings.sh
|
||||
@scripts/compile-strings.sh $(LRELEASE) $(LOCALES)
|
||||
|
||||
transclean:
|
||||
@echo
|
||||
@echo "------------------------------------"
|
||||
@echo "Removing compiled translation files."
|
||||
@echo "------------------------------------"
|
||||
rm -f i18n/*.qm
|
||||
|
||||
clean:
|
||||
@echo
|
||||
@echo "------------------------------------"
|
||||
@echo "Removing uic and rcc generated files"
|
||||
@echo "------------------------------------"
|
||||
rm $(COMPILED_UI_FILES) $(COMPILED_RESOURCE_FILES)
|
||||
|
||||
doc:
|
||||
@echo
|
||||
@echo "------------------------------------"
|
||||
@echo "Building documentation using sphinx."
|
||||
@echo "------------------------------------"
|
||||
cd help; make html
|
||||
|
||||
pylint:
|
||||
@echo
|
||||
@echo "-----------------"
|
||||
@echo "Pylint violations"
|
||||
@echo "-----------------"
|
||||
@pylint --reports=n --rcfile=pylintrc . || true
|
||||
@echo
|
||||
@echo "----------------------"
|
||||
@echo "If you get a 'no module named qgis.core' error, try sourcing"
|
||||
@echo "the helper script we have provided first then run make pylint."
|
||||
@echo "e.g. source run-env-linux.sh <path to qgis install>; make pylint"
|
||||
@echo "----------------------"
|
||||
|
||||
|
||||
# Run pep8 style checking
|
||||
#http://pypi.python.org/pypi/pep8
|
||||
pep8:
|
||||
@echo
|
||||
@echo "-----------"
|
||||
@echo "PEP8 issues"
|
||||
@echo "-----------"
|
||||
@pep8 --repeat --ignore=E203,E121,E122,E123,E124,E125,E126,E127,E128 --exclude $(PEP8EXCLUDE) . || true
|
||||
@echo "-----------"
|
||||
@echo "Ignored in PEP8 check:"
|
||||
@echo $(PEP8EXCLUDE)
|
||||
@@ -2,9 +2,7 @@
|
||||
|
||||
[](https://www.gnu.org/licenses/gpl-3.0)
|
||||
|
||||
**Version:** 1
|
||||
|
||||
**Platform:** QGIS 3.4.x
|
||||
**Platform:** QGIS 3.4.0–4.99.0
|
||||
|
||||
**Module Type:** Data Acquisition & Visualization
|
||||
|
||||
@@ -14,112 +12,169 @@
|
||||
|
||||
## 1. Overview
|
||||
|
||||
**AMCR Viewer** is a QGIS plugin designed to facilitate direct access to the Digital Archive of the Archaeological Map of the Czech Republic (AMČR). It allows researchers to **query, retrieve, and visualize Fieldwork events[^1] data (metadata and geometry) directly within the GIS environment**, eliminating the need to manually export data from the web interface. **Only publicly accessible data are supported at the time** (accessibility = anonymous).
|
||||
|
||||
[^1]: Only Fieldwork events (Akce) are supported at the time.
|
||||
**AMCR Viewer** is a QGIS plugin designed to facilitate direct access to the Digital Archive of the Archaeological Map of the Czech Republic (AMČR). It allows researchers to **query, retrieve, and visualize *Fieldwork events* and *Sites* data (metadata and geometry) directly within the GIS environment**, eliminating the need to manually export data from the web interface. Both *Fieldwork events* and *Sites* layers may optionally include component-level data (period and activity area) embedded directly in the attribute table. The plugin supports both **anonymous (public) access** and **authenticated access** for users with an AMČR account.
|
||||
|
||||
### Key Features
|
||||
|
||||
* **Spatial Querying:** Option to filter records based on the current map canvas extent (Bounding Box).
|
||||
* **Advanced Attribute Filtering:** Supports multi-criteria filtering using controlled vocabularies (Cadastral Area, District, Period, Type of Fieldwork event, Organization, Fieldwork Manager).
|
||||
* **Advanced Attribute Filtering:** Supports multi-criteria filtering using controlled vocabularies.
|
||||
* **Dynamic Geometry Retrieval:** Automatically downloads and categorizes spatial data into Point, Line, and Polygon layers.
|
||||
* **Semantic Interoperability:** Automatically translates internal system codes into human-readable labels using the AIS CR API.
|
||||
|
||||
---
|
||||
* **Authenticated Access:** Users with an AMČR account can log in to access non-public records.
|
||||
|
||||
## 2. Installation Guide
|
||||
|
||||
1. Obtain the [plugin distribution package](https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer/archive/refs/heads/main.zip) (ZIP archive containing the `amcr_viewer` directory).
|
||||
2. Launch QGIS.
|
||||
3. Navigate to **Plugins** **Manage and Install Plugins...**
|
||||
4. Select the **Install from ZIP** tab.
|
||||
5. Locate the source ZIP file and click **Install Plugin**.
|
||||
6. Upon successful installation, the AMCR download button (load AMCR data) will appear in the interface.
|
||||
**Install the plugin from QGIS plugin repository.**
|
||||
|
||||
**OR**
|
||||
**OR**
|
||||
|
||||
Install the plugin from QGIS plugin repository.
|
||||
|
||||
---
|
||||
1. *Obtain the [plugin distribution package](https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer/releases) (ZIP archive containing the `amcr_viewer` directory).*
|
||||
2. *Launch QGIS.*
|
||||
3. *Navigate to Plugins → Manage and Install Plugins...*
|
||||
4. *Select the Install from ZIP tab.*
|
||||
5. *Locate the source ZIP file and click Install Plugin.*
|
||||
6. *Upon successful installation, the AMCR Viewer button will appear in the toolbar.*
|
||||
|
||||
## 3. User Manual
|
||||
|
||||
### 3.1 Data Retrieval
|
||||
### 3.1 Authentication (Optional)
|
||||
|
||||
To initiate a search query, click the **Load AMCR Data** icon. The filter dialog provides the following options:
|
||||
By default, the plugin accesses only publicly available records (accessibility = anonymous). To access non-public data, log in using your AMČR account:
|
||||
|
||||
* **Spatial Filter:** *Checkbox "Limit search to current map extent":* If checked, the query is restricted to the geographical area currently visible in the QGIS canvas. If unchecked, the query searches the entire database (use with caution regarding data volume).
|
||||
* It is possible to view only those Fieldwork events with positive outcome, if "Positive findings only" is checked. Only PIANs marked as (or rather PIANs belonging to Documentation units marked as) "Type of evidence" = "positive" are rendered.
|
||||
* Click the dropdown arrow on the AMCR Viewer toolbar button and select **Přihlásit se**.
|
||||
* Enter your e-mail and password. Credentials are encrypted and stored securely in the **QGIS Authentication Manager** (DPAPI on Windows, Keychain on macOS, encrypted SQLite on Linux).
|
||||
* Stored credentials are reused automatically across sessions. To update or remove them, open the login dialog again.
|
||||
|
||||
### 3.2 Data Retrieval
|
||||
|
||||
To initiate a search query, click either the **Stáhnout data akcí** or the **Stáhnout data lokalit** option from the dropdown menu. The filter dialog provides the following options. Shown options vary based on the chosen tool.
|
||||
|
||||
* **Spatial Filter:** *Checkbox "Omezit vyhledávání rozsahem okna":* If checked, the query is restricted to the geographical area currently visible in the QGIS canvas. If unchecked, the query searches the entire database (use with caution regarding data volume).
|
||||
* **Positive findings only:** If checked, only *PIANs* belonging to Documentation units marked as "Type of evidence" = "positive" are included. *(Fieldwork events only.)*
|
||||
|
||||
* **Attribute Filters:**
|
||||
* The dialog utilizes "Picker" widgets for controlled vocabularies (Region, District, Cadastral area, Organisation, Period, Activity Area).
|
||||
* Click **Select...** to open a searchable selection window. Multiple values can be selected simultaneously (Logic: OR).
|
||||
* The dialog uses "Picker" widgets for controlled vocabularies (common: Region, District, Cadastral area, Period, Activity Area, *PIAN* accuracy, Accessibility; *events* related: Organisation, Researcher, Event type; *sites* related: Site type and class, Level of confidence, State of preservation).
|
||||
* Click **Vybrat...** to open a searchable selection window. Multiple values can be selected simultaneously (Logic: OR).
|
||||
|
||||
* **Codelists (Hesláře):**
|
||||
* Controlled vocabularies are downloaded from the AMČR OAI-PMH API and cached locally in `codelists/heslar.csv`.
|
||||
* To refresh all codelists, click the **Aktualizovat hesláře 🔄** button in the filter dialog. This runs as a background task and may take a few minutes.
|
||||
|
||||
* **Fieldwork Manager (Dynamic List):**
|
||||
* Due to the dynamic nature of the persons database, the list of Fieldwork Managers is retrieved from the AIS CR servers and needs to be updated the first time (and subsequently, if there is need).
|
||||
* To refresh the list from the server, click the **Refresh (🔄)** button next to the selection field. This downloads the latest list of researchers from the API.
|
||||
* If no filter is used, all accessible Fieldwork events/PIANs are returned (although the number of Fieldwork events to be loaded is capped at 20000 records; it is advisable to set at least one filter).
|
||||
* **Components:** Check **Načíst komponenty** to include period and activity area data directly in the output layers.
|
||||
> ⚠ When components are loaded, spatial features are duplicated — each feature corresponds to one component. Spatial analyses (areas, counts) may be inaccurate.
|
||||
|
||||
* If no filter is used, all accessible Fieldwork events/PIANs are returned (the number of records is capped at 20 000; it is advisable to set at least one filter).
|
||||
|
||||
For a more in-depth tutorial refer to the [AMČR Documentation](https://amcr-help.aiscr.cz/digiarchiv/qgis-viewer.html) (only in Czech).
|
||||
|
||||
### 3.2 Layer Structure & Attributes
|
||||
### 3.3 Layer Structure & Attributes
|
||||
|
||||
Upon successful retrieval, the plugin generates three temporary memory layers:
|
||||
Upon successful retrieval, the plugin generates up to three temporary memory layers:
|
||||
|
||||
1. **AMCR Plochy (Polygons)**
|
||||
2. **AMČR Linie (Lines)**
|
||||
3. **AMČR Body (Points)**
|
||||
1. **AMCR\_[Akce|Lokalita]\_Polygony**
|
||||
2. **AMCR\_[Akce|Lokalita]\_Linie**
|
||||
3. **AMCR\_[Akce|Lokalita]\_Body**
|
||||
|
||||
The Attribute Table includes standardized fields such as:
|
||||
Layers are only created if the query returns features of the corresponding geometry type. All layers share the same attribute schema.
|
||||
|
||||
* **Identification:** `Identifikátor` (Fieldwork event ID), `PIAN` (PIAN ID).
|
||||
* **Classification:** `Hlavní typ` (Main Fieldwork event Type), `Vedlejší typ` (Secondary Fieldwork event Type), `PIAN – typ` (PIAN Type).
|
||||
* **Administration:** `Vedoucí akce` (Fieldwork Manager), `Organizace` (Organization), `Datum zahájeni`/`Datum ukončení` (Dates of start and end of the Fieldwork event).
|
||||
* **Location:** `Katastr` (Main Cadastral area), `Další katastry` (Other Cadastral areas), `Okres` (District), `Definiční bod(y)` (PIAN point localization).
|
||||
* **Links:** `Odkaz do Digiarchivu` (Direct URL to the DigiArchive record).
|
||||
#### 3.3.1 Common fields
|
||||
|
||||
---
|
||||
| Field | Description |
|
||||
| --- | --- |
|
||||
| pian | PIAN (spatial identifier) ID |
|
||||
| presnost | Spatial deviation \[units/tens/hundreds of meters/defined by cadastre\] |
|
||||
| pian\_typ | \[point/line/polygon\] |
|
||||
| dj | Documentation unit ID |
|
||||
| typ\_dj | \[trench/event part/whole event/cadastral territory\] |
|
||||
| definicni\_body | Feature centroid in WGS-84 coordinate system |
|
||||
| akce / lokalita | Fieldwork event / Site ID |
|
||||
| odkaz\_do\_digiarchivu | Link to the record in the Digital Archive |
|
||||
| okres | District |
|
||||
| katastr | Main cadastral area |
|
||||
| dalsi\_katastry | Other cadastral areas, if the event extends beyond the main cadastre |
|
||||
| Přístupnost | Record accessibility \[A/B/C/D\] |
|
||||
|
||||
#### 3.3.2 Fields related to *Fieldwork events*
|
||||
|
||||
| Field | Description |
|
||||
| --- | --- |
|
||||
| akce\_lokalizace | Verbal description of the event location |
|
||||
| vedouci | Main fieldwork manager |
|
||||
| organizace | Organisation conducting the research |
|
||||
| specifikace\_data | \[exact date/exact years/sometime in years\] |
|
||||
| zahajeni | Event start date |
|
||||
| ukonceni | Event end date |
|
||||
| hlavni\_typ | Primary research method |
|
||||
| vedlejsi\_typ | Secondary research method |
|
||||
| zjisteni | Did the research reveal archaeological contexts? \[positive/negative\] |
|
||||
| nahrazuje\_NZ | Replaces a fieldwork report? \[yes/no\] |
|
||||
|
||||
#### 3.3.3 Fields related to *Sites*
|
||||
|
||||
| Field | Description |
|
||||
| --- | --- |
|
||||
| nazev\_lokality | Site name |
|
||||
| popis\_lokality | Site description |
|
||||
| typ\_lokality | Site classification by definition method |
|
||||
| druh\_lokality | Site classification by the nature of identified field relics |
|
||||
| zachovalost | Site preservation state |
|
||||
|
||||
#### 3.3.4 Component fields (only when *Načíst komponenty* is checked)
|
||||
|
||||
| Field | Description |
|
||||
| --- | --- |
|
||||
| komponenta | Component ID |
|
||||
| komponenta\_areal | Activity area \[settlement/burial area/field/…\] |
|
||||
| komponenta\_obdobi | Period \[Neolithic/High Middle Ages–Modern Period/…\] |
|
||||
|
||||
## 4. Technical Architecture
|
||||
|
||||
The plugin is developed in **Python 3** using the **PyQt5** framework for the GUI and the **Requests** library for HTTP communication.
|
||||
The plugin is developed in **Python 3** using the **PyQt6** framework for the GUI and the **Requests** library for HTTP communication.
|
||||
|
||||
### 4.1 File Structure
|
||||
|
||||
* `amcr_viewer.py`: Entry point; handles GUI integration and initialization.
|
||||
* `amcr_dialog.py`: Manages the UI logic, including the custom `FilterableSelectionDialog` for handling large vocabularies.
|
||||
* `amcr_tools.py`: Core logic module. Handles API requests, pagination, data parsing, and vector layer generation.
|
||||
* `amcr_codelists.py`: Manages local caching of controlled vocabularies (`codelists/*.csv`).
|
||||
* `amcr_viewer.py`: Entry point; handles GUI integration, toolbar/menu setup, and login flow.
|
||||
* `amcr_dialog.py`: Manages the UI logic, including `AmcrFilterDialog`, `FilterableSelectionDialog`, and `LoginDialog`.
|
||||
* `amcr_tools.py`: Core logic module. Handles authentication, API requests, pagination, data parsing, and vector layer generation.
|
||||
* `amcr_codelists.py`: Manages local caching of controlled vocabularies (`codelists/heslar.csv`) downloaded via OAI-PMH.
|
||||
|
||||
### 4.2 Data Flow & API Integration
|
||||
|
||||
The plugin interacts with three primary endpoints of the AIS CR infrastructure:
|
||||
The plugin interacts with the following endpoints:
|
||||
|
||||
1. **Search API (Solr):**
|
||||
* Endpoint: `https://digiarchiv.aiscr.cz/api/search/query`
|
||||
* Method: `GET`
|
||||
* Parameters: `entity=akce`, `fl` (field list), `q` (query), `rows/page` (pagination).
|
||||
* Logic: The plugin implements a `while True` loop to handle pagination, processing data in batches of 500 records to ensure stability.
|
||||
1. **Login API:**
|
||||
* Endpoint: `https://digiarchiv.aiscr.cz/api/user/login`
|
||||
* Method: `POST`
|
||||
* Returns a session cookie used for subsequent authenticated requests.
|
||||
* Credentials are stored in the QGIS Authentication Manager; the session is restored automatically if it expires mid-download.
|
||||
|
||||
2. **Search API (Solr):**
|
||||
* Endpoint: `https://digiarchiv.aiscr.cz/api/search/query`
|
||||
* Method: `GET`
|
||||
* Parameters: `entity=akce|lokalita|pian`, `rows/page` (pagination), `mapa=true`.
|
||||
* Logic: Paginated in batches of 500 records (metadata) and 200 records (geometries). A safety cap of 20 000 records is enforced.
|
||||
|
||||
2. **Translation API:**
|
||||
* Endpoint: `https://digiarchiv.aiscr.cz/api/assets/i18n/cs.json`
|
||||
* Function: Retrieves the mapping between system codes (e.g., `HES-xxxx`) and Czech labels. This dictionary is cached in memory during the session.
|
||||
3. **Translation API:**
|
||||
* Endpoint: `https://digiarchiv.aiscr.cz/api/assets/i18n/cs.json`
|
||||
* Function: Retrieves the mapping between system codes (e.g. `HES-xxxx`) and Czech labels. Cached in memory for the session.
|
||||
|
||||
4. **Codelists API (OAI-PMH):**
|
||||
* Endpoint: `https://api.aiscr.cz/2.2/oai`
|
||||
* Used for downloading controlled vocabularies (periods, regions, organisations, etc.) on demand.
|
||||
|
||||
### 4.3 Data Persistence
|
||||
|
||||
* **Vocabularies:** Static vocabularies (e.g., Periods, Regions) are stored in `codelists/heslar.csv`.
|
||||
* **Dynamic Data:** The list of investigators is downloaded on-demand and cached in `codelists/vedouci.csv`.
|
||||
* **Vocabularies:** Stored in `codelists/heslar.csv`; updated on user request via the background task.
|
||||
* **Layers:** Output layers are created as `memory` layers. They are non-persistent and will be lost if QGIS is closed without saving.
|
||||
|
||||
### 4.4 Constraints
|
||||
|
||||
* **Record Limit:** A safety cap of 20,000 records is enforced to prevent memory overflow in QGIS.
|
||||
* **Batch Processing:** Geometry fetching is batched (50 IDs per request) to comply with URL length limitations and server load balancing.
|
||||
* **Record Limit:** A safety cap of 20 000 records is enforced.
|
||||
* **Batch Processing:** Geometry fetching is batched (200 IDs per request) to comply with URL length limitations and server load balancing.
|
||||
* **Component duplication:** When components are loaded, each output feature corresponds to one component rather than one documentation unit. A single PIAN may therefore appear multiple times in the layer.
|
||||
|
||||
## 6. Links and resources
|
||||
## 5. Links and resources
|
||||
|
||||
* [AMCR/Digiarchive Documentation](https://amcr-help.aiscr.cz/) (only in Czech).
|
||||
* [AMCR Viewer tutorial](https://amcr-help.aiscr.cz/digiarchiv/qgis-viewer.html) (only in Czech).
|
||||
* [Import/Export. Pluginy propojující QGIS s AMČR \[poster\]](https://zenodo.org/records/20504909) (only in Czech; valid for v1.3.2).
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
import csv
|
||||
import codecs
|
||||
import requests
|
||||
import json
|
||||
|
||||
# Cesta k adresáři pluginu
|
||||
PLUGIN_DIR = os.path.dirname(__file__)
|
||||
CODELISTS_DIR = os.path.join(PLUGIN_DIR, 'codelists')
|
||||
|
||||
def ensure_codelists_dir():
|
||||
if not os.path.exists(CODELISTS_DIR):
|
||||
os.makedirs(CODELISTS_DIR)
|
||||
|
||||
# --- 1. NAČÍTÁNÍ DAT ---
|
||||
|
||||
def load_csv_data(filename):
|
||||
"""Obecná funkce pro načtení CSV souboru do slovníku"""
|
||||
data = {}
|
||||
path = os.path.join(CODELISTS_DIR, filename)
|
||||
if not os.path.exists(path):
|
||||
return data
|
||||
|
||||
try:
|
||||
with codecs.open(path, 'r', 'utf-8') as f:
|
||||
reader = csv.reader(f, delimiter=';')
|
||||
# Zkusíme přeskočit hlavičku, pokud tam je
|
||||
first_row = next(reader, None)
|
||||
|
||||
# Pokud soubor není prázdný, zpracujeme ho
|
||||
if first_row:
|
||||
# Pokud první řádek vypadá jako data (neobsahuje slovo "Název"), vrátíme ho do hry
|
||||
# Ale my budeme generovat soubory s hlavičkou, takže OK.
|
||||
pass
|
||||
|
||||
for row in reader:
|
||||
if len(row) >= 3:
|
||||
label = row[0].strip()
|
||||
code = row[1].strip()
|
||||
category = row[2].strip()
|
||||
|
||||
# Tady můžeme filtrovat podle kategorie,
|
||||
# nebo prostě vrátit všechno jako {label: code}
|
||||
# Pro jednoduchost vracíme {label: code}
|
||||
clean_code = code if code else None
|
||||
data[label] = clean_code
|
||||
except Exception as e:
|
||||
print(f"AMČR Chyba čtení {filename}: {e}")
|
||||
|
||||
return data
|
||||
|
||||
def load_all_data():
|
||||
"""
|
||||
Načte statický heslář I dynamický heslář vedoucích.
|
||||
Vrací slovník slovníků.
|
||||
"""
|
||||
ensure_codelists_dir()
|
||||
|
||||
# 1. Načteme hlavní statický heslář
|
||||
# Musíme ho rozparsovat podle kategorií, tak jak to bylo předtím
|
||||
categorized_data = {
|
||||
'obdobi': {}, 'typ_akce': {}, 'areal': {},
|
||||
'kraj': {}, 'organizace': {}, 'okres': {}, 'katastr': {},
|
||||
'vedouci': {}
|
||||
}
|
||||
|
||||
# Funkce pro roztřídění načteného slovníku (tohle je trochu redundance, ale pro zachování logiky)
|
||||
def parse_file(filename):
|
||||
path = os.path.join(CODELISTS_DIR, filename)
|
||||
if not os.path.exists(path): return
|
||||
|
||||
try:
|
||||
with codecs.open(path, 'r', 'utf-8') as f:
|
||||
reader = csv.reader(f, delimiter=';')
|
||||
next(reader, None) # Skip header
|
||||
for row in reader:
|
||||
if len(row) >= 3:
|
||||
label = row[0].strip()
|
||||
code = row[1].strip()
|
||||
cat = row[2].strip()
|
||||
clean = code if code else None
|
||||
|
||||
if cat in categorized_data:
|
||||
categorized_data[cat][label] = clean
|
||||
except: pass
|
||||
|
||||
# Načteme soubory
|
||||
parse_file('heslar.csv') # Statické
|
||||
parse_file('vedouci.csv') # Dynamické (pokud existuje)
|
||||
|
||||
return categorized_data
|
||||
|
||||
# --- 2. AKTUALIZACE DAT (DOWNLOAD) ---
|
||||
|
||||
def download_vedouci():
|
||||
"""
|
||||
Stáhne seznam vedoucích z API (pomocí onlyFacets) a uloží do codelists/vedouci.csv.
|
||||
"""
|
||||
ensure_codelists_dir()
|
||||
|
||||
# Tvá URL + pojistka, abychom dostali všechny záznamy (limit -1)
|
||||
url = "https://digiarchiv.aiscr.cz/api/search/query?entity=akce&sort=datestamp%20desc&page=0&onlyFacets=True&rows=0"
|
||||
|
||||
try:
|
||||
r = requests.get(url, timeout=20) # Raději delší timeout pro velký seznam
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
|
||||
# Cesta k datům dle tvého JSONu:
|
||||
# {"facet_counts": { "f_vedouci": [ {"name": "Novák", ...}, ... ] }}
|
||||
vedouci_list = data.get('facet_counts', {}).get('f_vedouci', [])
|
||||
|
||||
if not vedouci_list:
|
||||
# Zkusíme ještě alternativní cestu, kdyby API vrátilo standardní Solr strukturu
|
||||
# (facet_counts -> facet_fields -> f_vedouci)
|
||||
vedouci_list = data.get('facet_counts', {}).get('facet_fields', {}).get('f_vedouci', [])
|
||||
|
||||
csv_path = os.path.join(CODELISTS_DIR, 'vedouci.csv')
|
||||
|
||||
count = 0
|
||||
with codecs.open(csv_path, 'w', 'utf-8') as f:
|
||||
writer = csv.writer(f, delimiter=';')
|
||||
writer.writerow(['Název', 'Kód', 'Kategorie'])
|
||||
|
||||
# NOVÁ LOGIKA PARSOVÁNÍ
|
||||
for item in vedouci_list:
|
||||
name = None
|
||||
|
||||
# Varianta A: Položka je slovník {"name": "Jan Novák", "value": 10}
|
||||
if isinstance(item, dict):
|
||||
name = item.get('name')
|
||||
|
||||
# Varianta B: Položka je jen string (kdyby se API vrátilo k plochému seznamu)
|
||||
elif isinstance(item, str):
|
||||
name = item
|
||||
|
||||
# Pokud máme jméno a není to číslo (count), zapíšeme
|
||||
if name and not str(name).isdigit():
|
||||
writer.writerow([name, name, 'vedouci'])
|
||||
count += 1
|
||||
|
||||
return True, f"Staženo {count} jmen."
|
||||
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
|
||||
# --- GLOBAL DATA ---
|
||||
# Toto se načte při startu QGISu
|
||||
_DATA = load_all_data()
|
||||
|
||||
OBDOBI = _DATA['obdobi']
|
||||
TYP_AKCE = _DATA['typ_akce']
|
||||
AREAL = _DATA['areal']
|
||||
KRAJE = _DATA['kraj']
|
||||
ORGANIZACE = _DATA['organizace']
|
||||
OKRESY = _DATA['okres']
|
||||
KATASTRY = _DATA['katastr']
|
||||
VEDOUCI = _DATA['vedouci'] # Tady to bude zpočátku prázdné, pokud soubor neexistuje
|
||||
|
||||
def refresh_vedouci_cache():
|
||||
"""
|
||||
Znovu načte soubor vedouci.csv a aktualizuje globální proměnnou VEDOUCI.
|
||||
Použijeme 'update', aby se zachovala reference na objekt (pokud ho dialog už používá).
|
||||
"""
|
||||
temp_data = load_all_data()
|
||||
new_vedouci = temp_data['vedouci']
|
||||
|
||||
# Vyčistíme a naplníme existující slovník (in-place update)
|
||||
VEDOUCI.clear()
|
||||
VEDOUCI.update(new_vedouci)
|
||||
return len(VEDOUCI)
|
||||
-190
@@ -1,190 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from qgis.PyQt.QtWidgets import (QDialog, QVBoxLayout, QFormLayout,
|
||||
QLineEdit, QDialogButtonBox,
|
||||
QCheckBox, QGroupBox, QPushButton,
|
||||
QListWidget, QListWidgetItem, QHBoxLayout,
|
||||
QLabel, QMessageBox, QApplication, QWidget)
|
||||
from qgis.PyQt.QtCore import Qt
|
||||
from .amcr_codelists import (OBDOBI, TYP_AKCE, KRAJE, AREAL, ORGANIZACE,
|
||||
OKRESY, KATASTRY, VEDOUCI,
|
||||
download_vedouci, refresh_vedouci_cache)
|
||||
|
||||
class FilterableSelectionDialog(QDialog):
|
||||
def __init__(self, title, data_dict, preselected_codes, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle(f"Výběr: {title}")
|
||||
self.resize(400, 500)
|
||||
self.data_dict = data_dict
|
||||
self.preselected = preselected_codes if preselected_codes else []
|
||||
layout = QVBoxLayout()
|
||||
self.search_bar = QLineEdit()
|
||||
self.search_bar.setPlaceholderText("Hledat v seznamu...")
|
||||
self.search_bar.textChanged.connect(self.filter_list)
|
||||
layout.addWidget(self.search_bar)
|
||||
self.list_widget = QListWidget()
|
||||
self.populate_list()
|
||||
layout.addWidget(self.list_widget)
|
||||
buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
|
||||
buttons.accepted.connect(self.accept)
|
||||
buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(buttons)
|
||||
self.setLayout(layout)
|
||||
|
||||
def populate_list(self):
|
||||
sorted_names = sorted(self.data_dict.keys())
|
||||
for name in sorted_names:
|
||||
code = self.data_dict[name]
|
||||
item = QListWidgetItem(name)
|
||||
item.setData(Qt.UserRole, code)
|
||||
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
|
||||
if code in self.preselected: item.setCheckState(Qt.Checked)
|
||||
else: item.setCheckState(Qt.Unchecked)
|
||||
self.list_widget.addItem(item)
|
||||
|
||||
def filter_list(self, text):
|
||||
search_text = text.lower()
|
||||
for i in range(self.list_widget.count()):
|
||||
item = self.list_widget.item(i)
|
||||
if search_text not in item.text().lower(): item.setHidden(True)
|
||||
else: item.setHidden(False)
|
||||
|
||||
def get_selected_codes(self):
|
||||
codes = []
|
||||
labels = []
|
||||
for i in range(self.list_widget.count()):
|
||||
item = self.list_widget.item(i)
|
||||
if item.checkState() == Qt.Checked:
|
||||
codes.append(item.data(Qt.UserRole))
|
||||
labels.append(item.text())
|
||||
return codes, labels
|
||||
|
||||
|
||||
# --- Main window ---
|
||||
class AmcrFilterDialog(QDialog):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Filtr AMČR")
|
||||
self.resize(500, 750)
|
||||
|
||||
# Cache for filtering
|
||||
self.selection_cache = {
|
||||
'organizace': [], 'kraj': [], 'obdobi': [], 'areal': [],
|
||||
'typ_akce': [], 'okres': [], 'katastr': [], 'vedouci': []
|
||||
}
|
||||
|
||||
layout = QVBoxLayout()
|
||||
|
||||
self.chk_bbox = QCheckBox("Omezit vyhledávání rozsahem okna")
|
||||
self.chk_bbox.setChecked(True)
|
||||
layout.addWidget(self.chk_bbox)
|
||||
|
||||
self.chk_posevidence = QCheckBox("Pouze pozitivní zjištění")
|
||||
layout.addWidget(self.chk_posevidence)
|
||||
|
||||
layout.addSpacing(10)
|
||||
|
||||
def setup_picker(label_text, cache_key, data_source, extra_btn=None):
|
||||
row_widget = QGroupBox(label_text)
|
||||
# row_widget.setFlat(True)
|
||||
|
||||
row_layout = QHBoxLayout()
|
||||
row_layout.setContentsMargins(5, 5, 5, 5)
|
||||
|
||||
display_field = QLineEdit()
|
||||
display_field.setReadOnly(True)
|
||||
display_field.setPlaceholderText("Nic nevybráno (vše)")
|
||||
display_field.setStyleSheet("background-color: #f0f0f0; color: #333;")
|
||||
|
||||
btn = QPushButton("Vybrat...")
|
||||
btn.setFixedWidth(80)
|
||||
|
||||
def open_dialog():
|
||||
dlg = FilterableSelectionDialog(label_text, data_source, self.selection_cache[cache_key], self)
|
||||
if dlg.exec_() == QDialog.Accepted:
|
||||
codes, labels = dlg.get_selected_codes()
|
||||
self.selection_cache[cache_key] = codes
|
||||
if labels: display_field.setText(", ".join(labels))
|
||||
else: display_field.clear()
|
||||
|
||||
btn.clicked.connect(open_dialog)
|
||||
|
||||
row_layout.addWidget(display_field)
|
||||
row_layout.addWidget(btn)
|
||||
|
||||
if extra_btn:
|
||||
row_layout.addWidget(extra_btn)
|
||||
|
||||
row_widget.setLayout(row_layout)
|
||||
return row_widget
|
||||
|
||||
self.picker_kraj = setup_picker("Kraj", 'kraj', KRAJE)
|
||||
layout.addWidget(self.picker_kraj)
|
||||
|
||||
self.picker_okres = setup_picker("Okres", 'okres', OKRESY)
|
||||
layout.addWidget(self.picker_okres)
|
||||
|
||||
self.picker_katastr = setup_picker("Katastr", 'katastr', KATASTRY)
|
||||
layout.addWidget(self.picker_katastr)
|
||||
|
||||
self.picker_org = setup_picker("Organizace", 'organizace', ORGANIZACE)
|
||||
layout.addWidget(self.picker_org)
|
||||
|
||||
self.btn_update_vedouci = QPushButton("🔄")
|
||||
self.btn_update_vedouci.setToolTip("Aktualizovat seznam vedoucích z API")
|
||||
self.btn_update_vedouci.setFixedWidth(30)
|
||||
self.btn_update_vedouci.clicked.connect(self.action_update_vedouci)
|
||||
|
||||
self.picker_vedouci = setup_picker("Vedoucí výzkumu", 'vedouci', VEDOUCI, extra_btn=self.btn_update_vedouci)
|
||||
layout.addWidget(self.picker_vedouci)
|
||||
|
||||
self.picker_obdobi = setup_picker("Období", 'obdobi', OBDOBI)
|
||||
layout.addWidget(self.picker_obdobi)
|
||||
|
||||
self.picker_areal = setup_picker("Areál / Druh", 'areal', AREAL)
|
||||
layout.addWidget(self.picker_areal)
|
||||
|
||||
self.picker_typ = setup_picker("Typ výzkumu", 'typ_akce', TYP_AKCE)
|
||||
layout.addWidget(self.picker_typ)
|
||||
|
||||
layout.addStretch(1)
|
||||
|
||||
buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
|
||||
buttons.accepted.connect(self.accept)
|
||||
buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
self.setLayout(layout)
|
||||
|
||||
def action_update_vedouci(self):
|
||||
QApplication.setOverrideCursor(Qt.WaitCursor)
|
||||
try:
|
||||
success, msg = download_vedouci()
|
||||
if success:
|
||||
count = refresh_vedouci_cache()
|
||||
QApplication.restoreOverrideCursor()
|
||||
QMessageBox.information(self, "Úspěch", f"{msg}\nNyní je v paměti {count} osob.")
|
||||
else:
|
||||
QApplication.restoreOverrideCursor()
|
||||
QMessageBox.warning(self, "Chyba", f"Nepodařilo se stáhnout data:\n{msg}")
|
||||
except Exception as e:
|
||||
QApplication.restoreOverrideCursor()
|
||||
QMessageBox.critical(self, "Chyba", str(e))
|
||||
|
||||
def get_bbox(self):
|
||||
return "true" if self.chk_bbox.isChecked() else "false"
|
||||
|
||||
def get_filters(self):
|
||||
filters = {}
|
||||
if self.chk_posevidence.isChecked(): filters['posevidence'] = 'true'
|
||||
|
||||
# Loading from cache
|
||||
if self.selection_cache['organizace']: filters['f_organizace'] = self.selection_cache['organizace']
|
||||
if self.selection_cache['kraj']: filters['f_kraj'] = self.selection_cache['kraj']
|
||||
if self.selection_cache['okres']: filters['f_okres'] = self.selection_cache['okres']
|
||||
if self.selection_cache['katastr']: filters['f_katastr'] = self.selection_cache['katastr']
|
||||
if self.selection_cache['obdobi']: filters['f_obdobi'] = self.selection_cache['obdobi']
|
||||
if self.selection_cache['areal']: filters['f_areal'] = self.selection_cache['areal']
|
||||
if self.selection_cache['typ_akce']: filters['f_typ_vyzkumu'] = self.selection_cache['typ_akce']
|
||||
if self.selection_cache['vedouci']: filters['f_vedouci'] = self.selection_cache['vedouci']
|
||||
|
||||
return filters
|
||||
-418
@@ -1,418 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from qgis.gui import QgsMapToolIdentifyFeature
|
||||
from qgis.core import (QgsProject, QgsVectorLayer, QgsFeature, QgsGeometry,
|
||||
QgsField, QgsCoordinateReferenceSystem, QgsCoordinateTransform,
|
||||
QgsWkbTypes)
|
||||
from qgis.utils import iface
|
||||
from qgis.PyQt.QtCore import QVariant, Qt
|
||||
from qgis.PyQt.QtWidgets import QMessageBox, QApplication
|
||||
import requests
|
||||
import json
|
||||
import xml.etree.ElementTree as ET
|
||||
import re
|
||||
|
||||
# Global translations cache
|
||||
TRANSLATIONS = {}
|
||||
|
||||
# Download Digiarchive's vocabulary
|
||||
def load_translations():
|
||||
global TRANSLATIONS
|
||||
if TRANSLATIONS: return
|
||||
|
||||
url = "https://digiarchiv.aiscr.cz/api/assets/i18n/cs.json"
|
||||
try:
|
||||
r = requests.get(url, timeout=10)
|
||||
if r.status_code == 200:
|
||||
TRANSLATIONS = r.json()
|
||||
except Exception as e:
|
||||
print(f"Chyba při stahování hesláře: {e}")
|
||||
|
||||
def tr_code(code):
|
||||
if not code: return ""
|
||||
return TRANSLATIONS.get(code, code)
|
||||
|
||||
def load_amcr_data(canvas, bb, filters=None):
|
||||
load_translations()
|
||||
|
||||
# 1. Bounding box
|
||||
extent = canvas.extent()
|
||||
crs_src = canvas.mapSettings().destinationCrs()
|
||||
crs_dest = QgsCoordinateReferenceSystem("EPSG:4326")
|
||||
xform = QgsCoordinateTransform(crs_src, crs_dest, QgsProject.instance())
|
||||
extent_wgs = xform.transformBoundingBox(extent)
|
||||
bbox_str = f"{extent_wgs.yMinimum()},{extent_wgs.xMinimum()},{extent_wgs.yMaximum()},{extent_wgs.xMaximum()}"
|
||||
|
||||
url = "https://digiarchiv.aiscr.cz/api/search/query"
|
||||
|
||||
iface.messageBar().pushMessage("AMCR", "Hledám akce...", level=1)
|
||||
QApplication.setOverrideCursor(Qt.WaitCursor)
|
||||
|
||||
try:
|
||||
# ===================
|
||||
# A) METADATA (Fieldwork event)
|
||||
# ===================
|
||||
|
||||
# Field list
|
||||
fl_akce = [
|
||||
"ident_cely", "akce_typ", "akce_hlavni_vedouci", "akce_datum_zahajeni", "az_dj_pian", "akce_datum_ukonceni", "loc", "az_okres",
|
||||
"katastr", "az_chranene_udaje", "akce_organizace", "akce_specifikace_data",
|
||||
"akce_hlavni_typ", "akce_vedlejsi_typ", "akce_chranene_udaje",
|
||||
"akce_je_nz", "pristupnost", "dj_negativni_jednotka"
|
||||
]
|
||||
|
||||
base_params = {
|
||||
"mapa": "true",
|
||||
#"isExport": "true",
|
||||
"entity": "akce",
|
||||
"sort": "ident_cely asc",
|
||||
"fl": ",".join(fl_akce)
|
||||
}
|
||||
|
||||
if bb == "true":
|
||||
base_params["loc_rpt"] = bbox_str
|
||||
|
||||
# Apply filters
|
||||
if filters:
|
||||
for key, value in filters.items():
|
||||
if not value: continue
|
||||
if isinstance(value, list):
|
||||
base_params[key] = [f"{v}:or" for v in value]
|
||||
else:
|
||||
base_params[key] = str(value).strip()
|
||||
|
||||
docs_akce = []
|
||||
current_page = 0
|
||||
BATCH_AKCE = 500
|
||||
MAX_LIMIT = 20000
|
||||
|
||||
seen_ids = set()
|
||||
|
||||
while True:
|
||||
base_params['rows'] = BATCH_AKCE
|
||||
if current_page > 0:
|
||||
base_params['page'] = current_page
|
||||
elif 'page' in base_params:
|
||||
del base_params['page']
|
||||
|
||||
try:
|
||||
resp_akce = requests.get(url, params=base_params, timeout=30)
|
||||
resp_json = resp_akce.json()
|
||||
data = resp_json.get('response', {})
|
||||
batch_docs = data.get('docs', [])
|
||||
num_found = data.get('numFound', 0)
|
||||
|
||||
if not batch_docs:
|
||||
break
|
||||
|
||||
new_docs = []
|
||||
for d in batch_docs:
|
||||
ident = d.get('ident_cely')
|
||||
if ident and ident not in seen_ids:
|
||||
seen_ids.add(ident)
|
||||
new_docs.append(d)
|
||||
|
||||
docs_akce.extend(new_docs)
|
||||
print(f"Strana {current_page} stažena. Celkem záznamů: {len(docs_akce)} / {num_found}")
|
||||
|
||||
if len(docs_akce) >= num_found:
|
||||
break
|
||||
if len(docs_akce) >= MAX_LIMIT:
|
||||
iface.messageBar().pushMessage("AMCR", f"Limit {MAX_LIMIT} záznamů dosažen.", level=1)
|
||||
break
|
||||
|
||||
current_page += 1
|
||||
QApplication.processEvents()
|
||||
|
||||
except Exception as e:
|
||||
print(f"Chyba při stránkování na straně {current_page}: {e}")
|
||||
break
|
||||
|
||||
if not docs_akce:
|
||||
iface.messageBar().pushMessage("AMCR", "Žádné akce nenalezeny.", level=1)
|
||||
return
|
||||
|
||||
# ==========================================
|
||||
# Attribute parsing
|
||||
# ==========================================
|
||||
pian_lookup = {}
|
||||
target_pian_ids = set()
|
||||
actions_with_geom = 0
|
||||
|
||||
for akce in docs_akce:
|
||||
piani = akce.get('az_dj_pian', [])
|
||||
if not piani: continue
|
||||
|
||||
negative_pians = set()
|
||||
# Pokud je aktivní filtr 'posevidence', projdeme dokumentační jednotky
|
||||
if filters and filters.get('posevidence') == 'true':
|
||||
djs = akce.get('az_dokumentacni_jednotka', [])
|
||||
for dj in djs:
|
||||
# Pokud je jednotka negativní
|
||||
if dj.get('dj_negativni_jednotka') is True:
|
||||
# Získáme ID pianu z objektu (např. {"id": "P-...", "value": "..."})
|
||||
pian_obj = dj.get('dj_pian')
|
||||
if pian_obj and isinstance(pian_obj, dict):
|
||||
negative_pians.add(pian_obj.get('id'))
|
||||
|
||||
actions_with_geom += 1
|
||||
|
||||
def g(key, default=""):
|
||||
val = akce.get(key)
|
||||
if isinstance(val, list): return str(val[0]) if val else default
|
||||
return str(val) if val is not None else default
|
||||
|
||||
def g_list(key, translate=False):
|
||||
val = akce.get(key, [])
|
||||
if not isinstance(val, list): val = [val] if val else []
|
||||
if translate:
|
||||
return ", ".join([tr_code(str(x)) for x in val if x])
|
||||
return ", ".join([str(x) for x in val if x])
|
||||
|
||||
az_chranene = akce.get('az_chranene_udaje', {})
|
||||
akce_chranene = akce.get('akce_chranene_udaje', {})
|
||||
|
||||
dalsi_kat = az_chranene.get('dalsi_katastr', [])
|
||||
dalsi_kat_str = ""
|
||||
if isinstance(dalsi_kat, list):
|
||||
items = [x.get('value', '') if isinstance(x, dict) else str(x) for x in dalsi_kat]
|
||||
dalsi_kat_str = ", ".join([i for i in items if i])
|
||||
|
||||
lokalizace = akce_chranene.get('lokalizace_okolnosti', "")
|
||||
|
||||
# Prepate metadata for fieldwork event
|
||||
meta = {
|
||||
"ident_cely": akce.get('ident_cely', ''),
|
||||
"az_okres": g('az_okres'),
|
||||
"katastr": g_list('katastr'),
|
||||
"dalsi_katastr": dalsi_kat_str,
|
||||
"akce_hlavni_vedouci": g('akce_hlavni_vedouci'),
|
||||
"akce_organizace": tr_code(g('akce_organizace')),
|
||||
"akce_specifikace_data": tr_code(g('akce_specifikace_data')),
|
||||
"akce_datum_zahajeni": g('akce_datum_zahajeni'),
|
||||
"akce_datum_ukonceni": g('akce_datum_ukonceni'),
|
||||
"akce_hlavni_typ": tr_code(g('akce_hlavni_typ')),
|
||||
"akce_vedlejsi_typ": g_list('akce_vedlejsi_typ', translate=True),
|
||||
"lokalizace_okolnosti": str(lokalizace) if lokalizace else "",
|
||||
"akce_je_nz": "Ano" if akce.get('akce_je_nz') is True else "Ne",
|
||||
"pristupnost": g('pristupnost'),
|
||||
"loc": g_list('loc')
|
||||
}
|
||||
|
||||
for pid in piani:
|
||||
if pid in negative_pians:
|
||||
continue
|
||||
pian_lookup[pid] = meta
|
||||
target_pian_ids.add(pid)
|
||||
|
||||
if not target_pian_ids:
|
||||
iface.messageBar().pushMessage("AMCR", f"Nalezeno {len(docs_akce)} akcí, ale žádná nemá geometrii.", level=1)
|
||||
return
|
||||
|
||||
# ==========================================
|
||||
# B) Geometry (PIAN)
|
||||
# ==========================================
|
||||
ids_list = list(target_pian_ids)
|
||||
total_pians = len(ids_list)
|
||||
docs_pian = []
|
||||
BATCH_PIAN = 50
|
||||
|
||||
iface.messageBar().pushMessage("AMCR", f"Akcí: {len(docs_akce)} (z toho {actions_with_geom} s mapou). Stahuji {total_pians} geometrií...", level=1)
|
||||
|
||||
# Seznam polí pro PIAN
|
||||
fl_pian = ["ident_cely", "pian_typ", "pian_chranene_udaje", "pian_presnost"]
|
||||
|
||||
for i in range(0, total_pians, BATCH_PIAN):
|
||||
batch = ids_list[i : i + BATCH_PIAN]
|
||||
or_query = " OR ".join(batch)
|
||||
fq_pian = f"ident_cely:({or_query})"
|
||||
|
||||
params_pian = {
|
||||
"mapa": "true",
|
||||
"entity": "pian",
|
||||
"q": fq_pian,
|
||||
"rows": len(batch),
|
||||
"fl": ",".join(fl_pian)
|
||||
}
|
||||
try:
|
||||
QApplication.processEvents()
|
||||
r_pian = requests.get(url, params=params_pian, timeout=15)
|
||||
batch_docs = r_pian.json().get('response', {}).get('docs', [])
|
||||
docs_pian.extend(batch_docs)
|
||||
except Exception as e:
|
||||
print(f"Chyba PIAN: {e}")
|
||||
|
||||
# ==========================================
|
||||
# C) TVORBA VRSTEV
|
||||
# ==========================================
|
||||
vl_poly = QgsVectorLayer("Polygon?crs=epsg:5514", "AMCR Plochy", "memory")
|
||||
vl_line = QgsVectorLayer("LineString?crs=epsg:5514", "AMCR Linie", "memory")
|
||||
vl_point = QgsVectorLayer("Point?crs=epsg:5514", "AMCR Body", "memory")
|
||||
layers = [vl_poly, vl_line, vl_point]
|
||||
|
||||
# Definice sloupců atributové tabulky
|
||||
cols = [
|
||||
QgsField("PIAN", QVariant.String),
|
||||
QgsField("Přesnost", QVariant.String),
|
||||
QgsField("PIAN – typ", QVariant.String),
|
||||
QgsField("Definiční bod(y) (WGS-84)", QVariant.String),
|
||||
QgsField("Identifikátor", QVariant.String),
|
||||
QgsField("Odkaz do Digiarchivu", QVariant.String),
|
||||
QgsField("Okres", QVariant.String),
|
||||
QgsField("Katastr", QVariant.String),
|
||||
QgsField("Další katastry", QVariant.String),
|
||||
QgsField("Vedoucí akce", QVariant.String),
|
||||
QgsField("Organizace", QVariant.String),
|
||||
QgsField("Specifikace data", QVariant.String),
|
||||
QgsField("Datum zahájeni", QVariant.String),
|
||||
QgsField("Datum ukončení", QVariant.String),
|
||||
QgsField("Hlavní typ", QVariant.String),
|
||||
QgsField("Vedlejší typ", QVariant.String),
|
||||
QgsField("Akce – lokalizace", QVariant.String),
|
||||
QgsField("Akce - nahrazuje NZ", QVariant.String),
|
||||
QgsField("Přístupnost", QVariant.String)
|
||||
]
|
||||
|
||||
for vl in layers:
|
||||
vl.dataProvider().addAttributes(cols)
|
||||
vl.updateFields()
|
||||
|
||||
feats_p, feats_l, feats_pt = [], [], []
|
||||
|
||||
for doc in docs_pian:
|
||||
try:
|
||||
pid = doc.get('ident_cely', '')
|
||||
if pid not in pian_lookup: continue
|
||||
|
||||
meta = pian_lookup[pid]
|
||||
|
||||
# Geometry processing
|
||||
raw = doc.get('pian_chranene_udaje')
|
||||
if isinstance(raw, list) and raw: raw = raw[0]
|
||||
jdata = json.loads(raw) if isinstance(raw, str) else (raw if isinstance(raw, dict) else {})
|
||||
|
||||
wkt = None
|
||||
if jdata.get('geom_sjtsk_wkt'): wkt = jdata['geom_sjtsk_wkt'].get('value')
|
||||
elif jdata.get('geom_wkt'): wkt = jdata['geom_wkt'].get('value')
|
||||
|
||||
# PIAN attributes
|
||||
pian_presnost = tr_code(str(doc.get('pian_presnost', '')))
|
||||
pian_typ = tr_code(str(doc.get('pian_typ', '')))
|
||||
|
||||
if wkt:
|
||||
geom = QgsGeometry.fromWkt(wkt)
|
||||
if geom.isGeosValid():
|
||||
feat = QgsFeature()
|
||||
feat.setGeometry(geom)
|
||||
feat.setAttributes([
|
||||
pid,
|
||||
pian_presnost,
|
||||
pian_typ,
|
||||
meta['loc'],
|
||||
meta['ident_cely'],
|
||||
"https://digiarchiv.aiscr.cz/id/" + meta['ident_cely'],
|
||||
meta['az_okres'],
|
||||
meta['katastr'],
|
||||
meta['dalsi_katastr'],
|
||||
meta['akce_hlavni_vedouci'],
|
||||
meta['akce_organizace'],
|
||||
meta['akce_specifikace_data'],
|
||||
meta['akce_datum_zahajeni'],
|
||||
meta['akce_datum_ukonceni'],
|
||||
meta['akce_hlavni_typ'],
|
||||
meta['akce_vedlejsi_typ'],
|
||||
meta['lokalizace_okolnosti'],
|
||||
meta['akce_je_nz'],
|
||||
meta['pristupnost']
|
||||
])
|
||||
t = geom.type()
|
||||
if t == QgsWkbTypes.PolygonGeometry: feats_p.append(feat)
|
||||
elif t == QgsWkbTypes.LineGeometry: feats_l.append(feat)
|
||||
elif t == QgsWkbTypes.PointGeometry: feats_pt.append(feat)
|
||||
except Exception as ex:
|
||||
print(f"Chyba při tvorbě feature: {ex}")
|
||||
pass
|
||||
|
||||
proj = QgsProject.instance()
|
||||
added = 0
|
||||
for f, l, n in [(feats_p, vl_poly, "Plochy"), (feats_l, vl_line, "Linie"), (feats_pt, vl_point, "Body")]:
|
||||
if f:
|
||||
l.dataProvider().addFeatures(f)
|
||||
l.updateExtents()
|
||||
l.setName(f"AMČR {n} (Filtrováno)")
|
||||
proj.addMapLayer(l)
|
||||
added += len(f)
|
||||
|
||||
if added > 0:
|
||||
iface.messageBar().pushMessage("AMCR", f"Hotovo. Akcí: {len(docs_akce)} (s geom: {actions_with_geom}). Vykresleno: {added} prvků.", level=0)
|
||||
else:
|
||||
iface.messageBar().pushMessage("AMCR", "Žádná data k zobrazení.", level=1)
|
||||
|
||||
except Exception as e:
|
||||
iface.messageBar().pushMessage("Chyba", str(e), level=2)
|
||||
finally:
|
||||
QApplication.restoreOverrideCursor()
|
||||
|
||||
# class AmcrIdentifyTool(QgsMapToolIdentifyFeature):
|
||||
# def __init__(self, canvas):
|
||||
# super().__init__(canvas)
|
||||
# self.canvas = canvas
|
||||
# self.setCursor(Qt.CrossCursor)
|
||||
|
||||
# def canvasReleaseEvent(self, event):
|
||||
# results = self.identify(event.x(), event.y(), self.IdentifyMode.TopDownStopAtFirst, self.VectorLayer)
|
||||
# if not results: return
|
||||
# feature = results[0].mFeature
|
||||
# akce_id = None
|
||||
# # Změna: hledáme 'ident_cely' (ID akce)
|
||||
# idx = feature.fieldNameIndex('ident_cely')
|
||||
# if idx != -1:
|
||||
# akce_id = feature.attributes()[idx]
|
||||
|
||||
# # Fallback na starší názvy polí, kdyby něco
|
||||
# if not akce_id:
|
||||
# for col in ['akce_id', 'ident_cely', 'pian_id']:
|
||||
# if col in feature.fields().names():
|
||||
# akce_id = feature[col]
|
||||
# break
|
||||
|
||||
# if not akce_id: return
|
||||
|
||||
# full_id = akce_id if "api.aiscr.cz" in str(akce_id) else f"https://api.aiscr.cz/id/{akce_id}"
|
||||
# url = f"https://api.aiscr.cz/2.2/oai?verb=GetRecord&metadataPrefix=oai_amcr&identifier={full_id}"
|
||||
|
||||
# iface.messageBar().pushMessage("AMCR", f"Detail: {akce_id}...", level=1)
|
||||
# QApplication.setOverrideCursor(Qt.WaitCursor)
|
||||
# try:
|
||||
# r = requests.get(url, timeout=5)
|
||||
# if r.status_code == 200: self.show_detail(akce_id, r.text)
|
||||
# except Exception as e:
|
||||
# iface.messageBar().pushMessage("Chyba", str(e), level=2)
|
||||
# finally:
|
||||
# QApplication.restoreOverrideCursor()
|
||||
|
||||
# def show_detail(self, title, raw_xml):
|
||||
# xml = re.sub(r'\sxmlns="[^"]+"', '', raw_xml, count=1)
|
||||
# xml = re.sub(r'<(/?)[a-zA-Z0-9]+:', r'<\1', xml)
|
||||
# info = ""
|
||||
# try:
|
||||
# root = ET.fromstring(xml)
|
||||
# rec = root.find('.//archeologicky_zaznam')
|
||||
# if not rec: info = "Zadna data."
|
||||
# else:
|
||||
# kat = rec.find('.//hlavni_katastr')
|
||||
# info += f"<h3>{kat.text if kat is not None else '?'}</h3>"
|
||||
# for dj in rec.findall('.//dokumentacni_jednotka'):
|
||||
# pn = dj.find('pian')
|
||||
# p_txt = pn.text if pn is not None else ""
|
||||
# info += f"<hr><b>PIAN: {p_txt}</b><ul>"
|
||||
# for k in dj.findall('komponenta'):
|
||||
# ob = k.find('obdobi').text or "?"
|
||||
# ar = k.find('areal').text or "?"
|
||||
# info += f"<li>{ob} ({ar})</li>"
|
||||
# info += "</ul>"
|
||||
# dlg = QMessageBox()
|
||||
# dlg.setWindowTitle(str(title))
|
||||
# dlg.setText(info)
|
||||
# dlg.setTextFormat(Qt.RichText)
|
||||
# dlg.exec_()
|
||||
# except: pass
|
||||
-119
@@ -1,119 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
|
||||
from qgis.PyQt.QtGui import QIcon
|
||||
from qgis.PyQt.QtWidgets import QAction
|
||||
|
||||
from .amcr_tools import load_amcr_data#, AmcrIdentifyTool
|
||||
from .amcr_dialog import AmcrFilterDialog
|
||||
from .resources import *
|
||||
import os.path
|
||||
|
||||
class AmcrViewer:
|
||||
|
||||
def __init__(self, iface):
|
||||
self.iface = iface
|
||||
self.plugin_dir = os.path.dirname(__file__)
|
||||
locale = QSettings().value('locale/userLocale')[0:2]
|
||||
locale_path = os.path.join(
|
||||
self.plugin_dir,
|
||||
'i18n',
|
||||
'AmcrViewer_{}.qm'.format(locale))
|
||||
|
||||
if os.path.exists(locale_path):
|
||||
self.translator = QTranslator()
|
||||
self.translator.load(locale_path)
|
||||
QCoreApplication.installTranslator(self.translator)
|
||||
|
||||
self.actions = []
|
||||
self.menu = self.tr(u'&AMČR Viewer')
|
||||
self.first_start = None
|
||||
|
||||
def tr(self, message):
|
||||
return QCoreApplication.translate('AmcrViewer', message)
|
||||
|
||||
def add_action(self, icon_path, text, callback, enabled_flag=True,
|
||||
add_to_menu=True, add_to_toolbar=True, status_tip=None,
|
||||
whats_this=None, parent=None):
|
||||
icon = QIcon(icon_path)
|
||||
action = QAction(icon, text, parent)
|
||||
action.triggered.connect(callback)
|
||||
action.setEnabled(enabled_flag)
|
||||
|
||||
if status_tip is not None:
|
||||
action.setStatusTip(status_tip)
|
||||
|
||||
if whats_this is not None:
|
||||
action.setWhatsThis(whats_this)
|
||||
|
||||
if add_to_toolbar:
|
||||
self.iface.addToolBarIcon(action)
|
||||
|
||||
if add_to_menu:
|
||||
self.iface.addPluginToMenu(self.menu, action)
|
||||
|
||||
self.actions.append(action)
|
||||
return action
|
||||
|
||||
def initGui(self):
|
||||
|
||||
import os
|
||||
plugin_dir = os.path.dirname(__file__)
|
||||
|
||||
icon = QIcon(os.path.join(plugin_dir, 'download.png'))
|
||||
|
||||
# icon_info = QIcon(os.path.join(plugin_dir, 'info.png'))
|
||||
|
||||
# Download data button
|
||||
self.action_download = self.add_action(
|
||||
icon,
|
||||
text=self.tr(u'Načíst data z AMČR'),
|
||||
callback=self.run_download,
|
||||
parent=self.iface.mainWindow())
|
||||
|
||||
# # Info button (Checkable / Toggle)
|
||||
# self.action_tool = self.add_action(
|
||||
# icon_info,
|
||||
# text=self.tr(u'Výpis údajů záznamu'),
|
||||
# callback=self.run_tool,
|
||||
# parent=self.iface.mainWindow())
|
||||
# self.action_tool.setCheckable(True) # Toto tlačítko se zamačkává
|
||||
|
||||
self.first_start = True
|
||||
|
||||
def unload(self):
|
||||
for action in self.actions:
|
||||
self.iface.removePluginMenu(self.tr(u'&AMČR Viewer'), action)
|
||||
self.iface.removeToolBarIcon(action)
|
||||
|
||||
if hasattr(self, 'tool'):
|
||||
self.iface.mapCanvas().unsetMapTool(self.tool)
|
||||
|
||||
# --- Data downloading ---
|
||||
def run_download(self):
|
||||
|
||||
dlg = AmcrFilterDialog()
|
||||
result = dlg.exec_()
|
||||
|
||||
if result == 1:
|
||||
filters = dlg.get_filters()
|
||||
bbox = dlg.get_bbox()
|
||||
|
||||
canvas = self.iface.mapCanvas()
|
||||
load_amcr_data(canvas, bbox, filters)
|
||||
|
||||
# --- Info button toggle ---
|
||||
# def run_tool(self):
|
||||
|
||||
# if self.action_tool.isChecked():
|
||||
# canvas = self.iface.mapCanvas()
|
||||
|
||||
# if not hasattr(self, 'tool'):
|
||||
# self.tool = AmcrIdentifyTool(canvas)
|
||||
# self.tool.deactivated.connect(lambda: self.action_tool.setChecked(False))
|
||||
|
||||
# canvas.setMapTool(self.tool)
|
||||
# self.iface.messageBar().pushMessage("AMČR", "Info nástroj aktivní.", level=0)
|
||||
|
||||
# else:
|
||||
# if self.iface.mapCanvas().mapTool() == getattr(self, 'tool', None):
|
||||
# self.iface.mapCanvas().unsetMapTool(self.tool)
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 869 B |
Binary file not shown.
|
After Width: | Height: | Size: 533 B |
@@ -0,0 +1,276 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
import csv
|
||||
import requests
|
||||
import xml.etree.ElementTree as ET # nosec
|
||||
import time
|
||||
from qgis.core import QgsMessageLog, Qgis
|
||||
|
||||
# Define paths for the plugin and its codelists directory
|
||||
PLUGIN_DIR = os.path.dirname(__file__)
|
||||
CODELISTS_DIR = os.path.join(PLUGIN_DIR, 'codelists')
|
||||
BASE_URL = "https://api.aiscr.cz/2.2/oai"
|
||||
OUTPUT_FILE = os.path.join(CODELISTS_DIR, 'heslar.csv')
|
||||
|
||||
slovnicek = {
|
||||
'obdobi': 'heslo:obdobi',
|
||||
'typ_akce': 'heslo:akce_typ',
|
||||
'areal': 'heslo:areal',
|
||||
'kraj': 'ruian_kraj',
|
||||
'organizace': 'organizace',
|
||||
'okres': 'ruian_okres',
|
||||
'katastr': 'ruian_katastr',
|
||||
'vedouci': 'osoba',
|
||||
'pian_presnost': 'heslo:pian_presnost',
|
||||
'typ_lokality': 'heslo:lokalita_typ',
|
||||
'druh_lokality': 'heslo:lokalita_druh',
|
||||
'jistota': 'heslo:jistota_urceni',
|
||||
'lokalita_zachovalost': 'heslo:stav_dochovani',
|
||||
'pristupnost': 'heslo:pristupnost'
|
||||
}
|
||||
|
||||
NS = {
|
||||
'oai': 'http://www.openarchives.org/OAI/2.0/',
|
||||
'dc': 'http://purl.org/dc/elements/1.1/',
|
||||
'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/'
|
||||
}
|
||||
|
||||
|
||||
def ensure_codelists_dir():
|
||||
"""Creates the codelists directory if it does not exist."""
|
||||
if not os.path.exists(CODELISTS_DIR):
|
||||
os.makedirs(CODELISTS_DIR)
|
||||
|
||||
|
||||
def parse_codelist_file(filename, target_dict=None):
|
||||
"""
|
||||
Reads a CSV codelist file and populates
|
||||
the target dictionary grouped by categories.
|
||||
"""
|
||||
if target_dict is None:
|
||||
target_dict = {}
|
||||
|
||||
path = os.path.join(CODELISTS_DIR, filename)
|
||||
|
||||
# Return early if the file doesn't exist to avoid missing file errors
|
||||
if not os.path.exists(path):
|
||||
return target_dict
|
||||
|
||||
try:
|
||||
# Open the file using standard UTF-8 encoding
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
reader = csv.reader(f, delimiter=';')
|
||||
|
||||
# Skip the CSV header row
|
||||
next(reader, None)
|
||||
|
||||
# Iterate through rows and extract label, code, and category
|
||||
for row in reader:
|
||||
if len(row) >= 3:
|
||||
label = row[0].strip()
|
||||
code = row[1].strip()
|
||||
cat = row[2].strip()
|
||||
clean = code if code else None
|
||||
|
||||
# Initialize a new dictionary for a category if encountered
|
||||
# for the first time
|
||||
if cat not in target_dict:
|
||||
target_dict[cat] = {}
|
||||
|
||||
# Assign the extracted code to the corresponding label
|
||||
# within the category
|
||||
target_dict[cat][label] = clean
|
||||
|
||||
except Exception as e:
|
||||
QgsMessageLog.logMessage(
|
||||
f"AMČR Codelist Read Error for {filename}: {e}",
|
||||
"AMČR", Qgis.Critical)
|
||||
|
||||
return target_dict
|
||||
|
||||
|
||||
def load_all_data():
|
||||
"""Loads the codelist during plugin startup."""
|
||||
ensure_codelists_dir()
|
||||
categorized_data = {k: {} for k in slovnicek.keys()}
|
||||
parse_codelist_file('heslar.csv', categorized_data)
|
||||
return categorized_data
|
||||
|
||||
|
||||
def fetch_set(internal_name, api_set, task=None):
|
||||
dataset = []
|
||||
params = {
|
||||
"verb": "ListRecords",
|
||||
"metadataPrefix": "oai_dc",
|
||||
"set": api_set
|
||||
}
|
||||
|
||||
while True:
|
||||
# Check for cancellation at each iteration
|
||||
if task and task.isCanceled():
|
||||
return None
|
||||
|
||||
try:
|
||||
response = requests.get(BASE_URL, params=params, timeout=30)
|
||||
response.raise_for_status()
|
||||
root = ET.fromstring(response.content) # nosec
|
||||
|
||||
records = root.findall('.//oai:record', NS)
|
||||
for rec in records:
|
||||
metadata = rec.find('.//oai_dc:dc', NS)
|
||||
if metadata is not None:
|
||||
# Code (identifier)
|
||||
identifier_el = metadata.find('dc:identifier', NS)
|
||||
kod = (
|
||||
identifier_el.text
|
||||
if identifier_el is not None
|
||||
else ""
|
||||
)
|
||||
|
||||
# Title – filter out system labels "AMČR - ..."
|
||||
titles = metadata.findall('dc:title', NS)
|
||||
nazev = ""
|
||||
for t in titles:
|
||||
if (
|
||||
t.text
|
||||
and not t.text.startswith("AMČR -")
|
||||
and not t.text.startswith(" AMČR -")
|
||||
):
|
||||
nazev = t.text
|
||||
break
|
||||
# If no title passed the filter, fall back
|
||||
# to the first available one
|
||||
if not nazev and titles:
|
||||
nazev = titles[0].text
|
||||
|
||||
specialni_pripady = ['okres', 'katastr']
|
||||
|
||||
if internal_name in specialni_pripady:
|
||||
kod = nazev
|
||||
|
||||
if internal_name == 'pristupnost':
|
||||
kod = next(
|
||||
(
|
||||
t.text for t in titles
|
||||
if t.text
|
||||
and len(t.text) == 1
|
||||
and t.text.isalpha()
|
||||
),
|
||||
None
|
||||
)
|
||||
|
||||
dataset.append({
|
||||
'Název': nazev,
|
||||
'Kód': kod,
|
||||
'Kategorie': internal_name
|
||||
})
|
||||
|
||||
# Pagination
|
||||
token = root.find('.//oai:resumptionToken', NS)
|
||||
if token is not None and token.text:
|
||||
params = {
|
||||
"verb": "ListRecords",
|
||||
"resumptionToken": token.text
|
||||
}
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
QgsMessageLog.logMessage(
|
||||
f"Chyba u setu {api_set}: {e}",
|
||||
"AMČR", Qgis.Warning)
|
||||
break
|
||||
|
||||
return dataset
|
||||
|
||||
|
||||
def download_heslare(task=None):
|
||||
"""Fetches the codelists from the AMČR API and saves it to a CSV file."""
|
||||
ensure_codelists_dir()
|
||||
all_data = []
|
||||
total_sets = len(slovnicek)
|
||||
|
||||
for index, (interni, api_nazev) in enumerate(slovnicek.items()):
|
||||
# Check if the user cancelled the task via the QGIS taskbar
|
||||
if task and task.isCanceled():
|
||||
return False
|
||||
|
||||
QgsMessageLog.logMessage(
|
||||
f"Zpracovávám kategorii: {interni}...",
|
||||
"AMČR", Qgis.Info)
|
||||
|
||||
# Pass the task correctly to the updated fetch function
|
||||
data = fetch_set(interni, api_nazev, task=task)
|
||||
|
||||
if data is None:
|
||||
return False # Cancelled mid-download
|
||||
|
||||
all_data.extend(data)
|
||||
|
||||
# Report progress (0-100)
|
||||
if task:
|
||||
progress = (index + 1) / total_sets * 100
|
||||
task.setProgress(progress)
|
||||
|
||||
# Save to CSV
|
||||
with open(OUTPUT_FILE, 'w', newline='', encoding='utf-8-sig') as f:
|
||||
fieldnames = ['Název', 'Kód', 'Kategorie']
|
||||
writer = csv.DictWriter(f, fieldnames=fieldnames, delimiter=';')
|
||||
writer.writeheader()
|
||||
writer.writerows(all_data)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def refresh_globals():
|
||||
"""Reloads data from files into the global variables."""
|
||||
data = load_all_data()
|
||||
|
||||
OBDOBI.clear()
|
||||
OBDOBI.update(data.get('obdobi', {}))
|
||||
TYP_AKCE.clear()
|
||||
TYP_AKCE.update(data.get('typ_akce', {}))
|
||||
AREAL.clear()
|
||||
AREAL.update(data.get('areal', {}))
|
||||
KRAJE.clear()
|
||||
KRAJE.update(data.get('kraj', {}))
|
||||
ORGANIZACE.clear()
|
||||
ORGANIZACE.update(data.get('organizace', {}))
|
||||
OKRESY.clear()
|
||||
OKRESY.update(data.get('okres', {}))
|
||||
KATASTRY.clear()
|
||||
KATASTRY.update(data.get('katastr', {}))
|
||||
VEDOUCI.clear()
|
||||
VEDOUCI.update(data.get('vedouci', {}))
|
||||
PIAN_PRESNOST.clear()
|
||||
PIAN_PRESNOST.update(data.get('pian_presnost', {}))
|
||||
TYP_LOKALITY.clear()
|
||||
TYP_LOKALITY.update(data.get('typ_lokality', {}))
|
||||
DRUH_LOKALITY.clear()
|
||||
DRUH_LOKALITY.update(data.get('druh_lokality', {}))
|
||||
JISTOTA.clear()
|
||||
JISTOTA.update(data.get('jistota', {}))
|
||||
LOKALITA_ZACHOVALOST.clear()
|
||||
LOKALITA_ZACHOVALOST.update(data.get('lokalita_zachovalost', {}))
|
||||
PRISTUPNOST.clear()
|
||||
PRISTUPNOST.update(data.get('pristupnost', {}))
|
||||
|
||||
|
||||
# Initialize empty dicts that will be populated immediately below
|
||||
OBDOBI = {}
|
||||
TYP_AKCE = {}
|
||||
AREAL = {}
|
||||
KRAJE = {}
|
||||
ORGANIZACE = {}
|
||||
OKRESY = {}
|
||||
KATASTRY = {}
|
||||
VEDOUCI = {}
|
||||
PIAN_PRESNOST = {}
|
||||
TYP_LOKALITY = {}
|
||||
DRUH_LOKALITY = {}
|
||||
JISTOTA = {}
|
||||
LOKALITA_ZACHOVALOST = {}
|
||||
PRISTUPNOST = {}
|
||||
|
||||
refresh_globals()
|
||||
@@ -0,0 +1,720 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from qgis.PyQt.QtWidgets import (QDialog, QVBoxLayout,
|
||||
QLineEdit, QDialogButtonBox,
|
||||
QCheckBox, QGroupBox, QPushButton,
|
||||
QListWidget, QListWidgetItem, QHBoxLayout,
|
||||
QMessageBox, QLabel, QFormLayout)
|
||||
from qgis.PyQt.QtCore import Qt, QSettings
|
||||
from qgis.core import (QgsTask, QgsApplication,
|
||||
QgsMessageLog, Qgis, QgsAuthMethodConfig)
|
||||
from .amcr_codelists import (OBDOBI, TYP_AKCE, KRAJE, AREAL, ORGANIZACE,
|
||||
OKRESY, KATASTRY, VEDOUCI, PIAN_PRESNOST,
|
||||
TYP_LOKALITY, DRUH_LOKALITY, JISTOTA,
|
||||
LOKALITA_ZACHOVALOST, PRISTUPNOST,
|
||||
download_heslare, refresh_globals)
|
||||
|
||||
|
||||
class UpdateCodelistsTask(QgsTask):
|
||||
def __init__(self, description):
|
||||
super().__init__(description, QgsTask.CanCancel)
|
||||
self.success = False
|
||||
self.exception = None
|
||||
|
||||
def run(self):
|
||||
"""Runs in a background thread."""
|
||||
try:
|
||||
# Call the download function with the task reference
|
||||
self.success = download_heslare(task=self)
|
||||
return self.success
|
||||
except Exception as e:
|
||||
self.exception = e
|
||||
return False
|
||||
|
||||
def finished(self, result):
|
||||
"""Runs in the main thread after run() completes."""
|
||||
if result:
|
||||
# Safely update the global variables in the main thread
|
||||
refresh_globals()
|
||||
QgsMessageLog.logMessage(
|
||||
"Hesláře AMČR byly úspěšně aktualizovány.",
|
||||
"AMČR", Qgis.Info)
|
||||
else:
|
||||
if self.isCanceled():
|
||||
QgsMessageLog.logMessage(
|
||||
"Aktualizace heslářů byla zrušena.",
|
||||
"AMČR", Qgis.Warning)
|
||||
else:
|
||||
QgsMessageLog.logMessage(
|
||||
f"Chyba aktualizace: {self.exception}",
|
||||
"AMČR", Qgis.Critical)
|
||||
|
||||
|
||||
class FilterableSelectionDialog(QDialog):
|
||||
"""
|
||||
A custom dialog for selecting multiple items from
|
||||
a list with a search filter.
|
||||
Updated for PyQt6/Qt6 compatibility.
|
||||
"""
|
||||
def __init__(self, title, data_dict, preselected_codes, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle(f"Výběr: {title}")
|
||||
self.resize(400, 500)
|
||||
|
||||
# Store the source data and previously selected items
|
||||
self.data_dict = data_dict
|
||||
self.preselected = preselected_codes if preselected_codes else []
|
||||
|
||||
layout = QVBoxLayout()
|
||||
|
||||
# Setup search input for filtering items
|
||||
self.search_bar = QLineEdit()
|
||||
self.search_bar.setPlaceholderText("Hledat v seznamu...")
|
||||
self.search_bar.textChanged.connect(self.filter_list)
|
||||
layout.addWidget(self.search_bar)
|
||||
|
||||
# Main list widget for displaying selectable items
|
||||
self.list_widget = QListWidget()
|
||||
self.populate_list()
|
||||
layout.addWidget(self.list_widget)
|
||||
|
||||
# Standard OK/Cancel dialog buttons
|
||||
buttons = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok
|
||||
| QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
buttons.accepted.connect(self.accept)
|
||||
buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
self.setLayout(layout)
|
||||
|
||||
def populate_list(self):
|
||||
# Sort items alphabetically by their display name
|
||||
sorted_names = sorted(self.data_dict.keys())
|
||||
for name in sorted_names:
|
||||
code = self.data_dict[name]
|
||||
item = QListWidgetItem(name)
|
||||
|
||||
# Store the actual code (ID) hidden in the UserRole
|
||||
item.setData(Qt.ItemDataRole.UserRole, code)
|
||||
|
||||
# Make the item checkable (adds a checkbox)
|
||||
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
|
||||
|
||||
# Restore previous selection state
|
||||
if code in self.preselected:
|
||||
item.setCheckState(Qt.CheckState.Checked)
|
||||
else:
|
||||
item.setCheckState(Qt.CheckState.Unchecked)
|
||||
|
||||
self.list_widget.addItem(item)
|
||||
|
||||
def filter_list(self, text):
|
||||
# Hide items that don't match the search text (case-insensitive)
|
||||
search_text = text.lower()
|
||||
for i in range(self.list_widget.count()):
|
||||
item = self.list_widget.item(i)
|
||||
item.setHidden(search_text not in item.text().lower())
|
||||
|
||||
def get_selected_codes(self):
|
||||
"""Returns the hidden codes and display labels of all checked items."""
|
||||
codes = []
|
||||
labels = []
|
||||
for i in range(self.list_widget.count()):
|
||||
item = self.list_widget.item(i)
|
||||
if item.checkState() == Qt.CheckState.Checked:
|
||||
codes.append(item.data(Qt.ItemDataRole.UserRole))
|
||||
labels.append(item.text())
|
||||
return codes, labels
|
||||
|
||||
|
||||
# --- Main window ---
|
||||
class AmcrFilterDialog(QDialog):
|
||||
"""
|
||||
The main filtering UI where users set criteria before downloading data.
|
||||
"""
|
||||
def __init__(self, typ_dat, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Filtr AMČR")
|
||||
self.resize(500, 750)
|
||||
|
||||
# Determines if we are fetching 'akce' (events)
|
||||
# or 'lokalita' (sites)
|
||||
self.typ_dat = typ_dat
|
||||
|
||||
# Cache dictionary to store selected codes for each category
|
||||
self.selection_cache = {
|
||||
'organizace': [], 'kraj': [], 'obdobi': [], 'areal': [],
|
||||
'typ_akce': [], 'okres': [], 'katastr': [], 'vedouci': [],
|
||||
'pian_presnost': [], 'pristupnost': [], 'typ_lokality': [],
|
||||
'druh_lokality': [], 'jistota': [], 'lokalita_zachovalost': []
|
||||
}
|
||||
|
||||
layout = QVBoxLayout()
|
||||
|
||||
# Filter by current map canvas extent
|
||||
self.chk_bbox = QCheckBox("Omezit vyhledávání rozsahem okna")
|
||||
self.chk_bbox.setChecked(True)
|
||||
layout.addWidget(self.chk_bbox)
|
||||
|
||||
# Positive/negative evidence – valid for Akce
|
||||
|
||||
if self.typ_dat == "akce":
|
||||
self.chk_posevidence = QCheckBox("Pouze pozitivní zjištění")
|
||||
layout.addWidget(self.chk_posevidence)
|
||||
|
||||
layout.addSpacing(10)
|
||||
|
||||
# Spatial information – valid for all
|
||||
|
||||
self.picker_kraj = self.setup_picker("Kraj", 'kraj', KRAJE)
|
||||
layout.addWidget(self.picker_kraj)
|
||||
|
||||
self.picker_okres = self.setup_picker("Okres", 'okres', OKRESY)
|
||||
layout.addWidget(self.picker_okres)
|
||||
|
||||
self.picker_katastr = self.setup_picker(
|
||||
"Katastr",
|
||||
'katastr',
|
||||
KATASTRY
|
||||
)
|
||||
layout.addWidget(self.picker_katastr)
|
||||
|
||||
self.picker_presnost = self.setup_picker(
|
||||
"PIAN – přesnost",
|
||||
'pian_presnost',
|
||||
PIAN_PRESNOST
|
||||
)
|
||||
layout.addWidget(self.picker_presnost)
|
||||
|
||||
self.picker_pristupnost = self.setup_picker(
|
||||
"Přístupnost",
|
||||
'pristupnost',
|
||||
PRISTUPNOST
|
||||
)
|
||||
layout.addWidget(self.picker_pristupnost)
|
||||
|
||||
# Filters valid for Akce
|
||||
|
||||
if self.typ_dat == "akce":
|
||||
self.picker_org = self.setup_picker(
|
||||
"Organizace",
|
||||
'organizace',
|
||||
ORGANIZACE
|
||||
)
|
||||
layout.addWidget(self.picker_org)
|
||||
|
||||
self.picker_vedouci = self.setup_picker(
|
||||
"Vedoucí výzkumu",
|
||||
'vedouci',
|
||||
VEDOUCI
|
||||
)
|
||||
layout.addWidget(self.picker_vedouci)
|
||||
|
||||
# Type of event
|
||||
|
||||
self.picker_typ = self.setup_picker(
|
||||
"Typ výzkumu",
|
||||
'typ_akce',
|
||||
TYP_AKCE
|
||||
)
|
||||
layout.addWidget(self.picker_typ)
|
||||
|
||||
# Filters valid for Lokality
|
||||
|
||||
if self.typ_dat == "lokalita":
|
||||
self.picker_typ_lokality = self.setup_picker(
|
||||
"Lokalita – typ",
|
||||
'typ_lokality',
|
||||
TYP_LOKALITY
|
||||
)
|
||||
layout.addWidget(self.picker_typ_lokality)
|
||||
|
||||
self.picker_druh_lokality = self.setup_picker(
|
||||
"Lokalita – druh",
|
||||
'druh_lokality',
|
||||
DRUH_LOKALITY
|
||||
)
|
||||
layout.addWidget(self.picker_druh_lokality)
|
||||
|
||||
self.picker_jistota = self.setup_picker(
|
||||
"Lokalita – jistota určení",
|
||||
'jistota',
|
||||
JISTOTA
|
||||
)
|
||||
layout.addWidget(self.picker_jistota)
|
||||
|
||||
self.picker_lokalita_zachovalost = self.setup_picker(
|
||||
"Lokalita - stav dochování",
|
||||
'lokalita_zachovalost',
|
||||
LOKALITA_ZACHOVALOST
|
||||
)
|
||||
layout.addWidget(self.picker_lokalita_zachovalost)
|
||||
|
||||
# Contextual information
|
||||
|
||||
self.picker_obdobi = self.setup_picker("Období", 'obdobi', OBDOBI)
|
||||
layout.addWidget(self.picker_obdobi)
|
||||
|
||||
self.picker_areal = self.setup_picker("Areál", 'areal', AREAL)
|
||||
layout.addWidget(self.picker_areal)
|
||||
|
||||
# Option to download related components table
|
||||
self.chk_komponenty = QCheckBox("Načíst komponenty")
|
||||
layout.addWidget(self.chk_komponenty)
|
||||
|
||||
# Warning label
|
||||
self.lbl_komponenty_warning = QLabel(
|
||||
"⚠ Při načtení komponent jsou prostorové prvky duplikovány — "
|
||||
"každý prvek odpovídá jedné komponentě. "
|
||||
"Prostorové analýzy (plochy, počty) mohou být zkreslené."
|
||||
)
|
||||
self.lbl_komponenty_warning.setWordWrap(True)
|
||||
self.lbl_komponenty_warning.setStyleSheet(
|
||||
"color: #8a6d00; background-color: #fff8e1; "
|
||||
"border: 1px solid #ffe082; border-radius: 4px; padding: 6px;"
|
||||
)
|
||||
self.lbl_komponenty_warning.setVisible(False)
|
||||
layout.addWidget(self.lbl_komponenty_warning)
|
||||
|
||||
self.chk_komponenty.toggled.connect(
|
||||
self.lbl_komponenty_warning.setVisible
|
||||
)
|
||||
|
||||
# Pushes everything above to the top
|
||||
layout.addStretch(1)
|
||||
|
||||
# Main dialog OK/Cancel/Update buttons
|
||||
|
||||
buttons = QDialogButtonBox()
|
||||
|
||||
self.btn_update = QPushButton("Aktualizovat hesláře 🔄")
|
||||
self.btn_update.setToolTip(
|
||||
"Provede kompletní aktualizaci heslářů AMČR. "
|
||||
"Toto bude trvat pár minut."
|
||||
)
|
||||
self.btn_update.clicked.connect(self.action_update_heslare)
|
||||
|
||||
buttons.addButton(
|
||||
self.btn_update,
|
||||
QDialogButtonBox.ButtonRole.ActionRole
|
||||
)
|
||||
buttons.addButton(QDialogButtonBox.StandardButton.Ok)
|
||||
buttons.addButton(QDialogButtonBox.StandardButton.Cancel)
|
||||
|
||||
buttons.accepted.connect(self.accept)
|
||||
buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
self.setLayout(layout)
|
||||
|
||||
def setup_picker(self, label_text, cache_key, data_source, extra_btn=None):
|
||||
"""
|
||||
Creates a reusable UI component consisting of a label, a read-only
|
||||
text field showing selected items, and a button to open
|
||||
the selection dialog.
|
||||
"""
|
||||
row_widget = QGroupBox(label_text)
|
||||
row_layout = QHBoxLayout()
|
||||
row_layout.setContentsMargins(5, 5, 5, 5)
|
||||
|
||||
# Read-only field displaying the names of selected items
|
||||
display_field = QLineEdit()
|
||||
display_field.setReadOnly(True)
|
||||
display_field.setPlaceholderText("Nic nevybráno (vše)")
|
||||
display_field.setStyleSheet("background-color: #f0f0f0; color: #333;")
|
||||
|
||||
btn = QPushButton("Vybrat...")
|
||||
btn.setFixedWidth(80)
|
||||
|
||||
# Nested handler: opens the selection dialog and saves the result
|
||||
def open_dialog():
|
||||
dlg = FilterableSelectionDialog(
|
||||
label_text,
|
||||
data_source,
|
||||
self.selection_cache[cache_key],
|
||||
self
|
||||
)
|
||||
if dlg.exec() == QDialog.DialogCode.Accepted:
|
||||
codes, labels = dlg.get_selected_codes()
|
||||
# Update the local cache with selected IDs
|
||||
self.selection_cache[cache_key] = codes
|
||||
# Update the display field with the selected item names
|
||||
if labels:
|
||||
display_field.setText(", ".join(labels))
|
||||
else:
|
||||
display_field.clear()
|
||||
|
||||
# Special case: pre-select default PIAN accuracy levels
|
||||
if cache_key == 'pian_presnost':
|
||||
display_field.setText(
|
||||
"odchylka jednotky metrů, odchylka desítky metrů, "
|
||||
"odchylka stovky metrů"
|
||||
)
|
||||
self.selection_cache[cache_key] = [
|
||||
'HES-000861',
|
||||
'HES-000862',
|
||||
'HES-000863'
|
||||
]
|
||||
|
||||
btn.clicked.connect(open_dialog)
|
||||
|
||||
row_layout.addWidget(display_field)
|
||||
row_layout.addWidget(btn)
|
||||
|
||||
# Optionally append an extra button (e.g. a refresh button)
|
||||
if extra_btn:
|
||||
row_layout.addWidget(extra_btn)
|
||||
|
||||
row_widget.setLayout(row_layout)
|
||||
return row_widget
|
||||
|
||||
def action_update_heslare(self):
|
||||
# Create the task instance
|
||||
task = UpdateCodelistsTask("Aktualizace heslářů AMČR")
|
||||
|
||||
# Re-enable the button regardless of the outcome
|
||||
task.taskCompleted.connect(lambda: self.btn_update.setEnabled(True))
|
||||
task.taskTerminated.connect(lambda: self.btn_update.setEnabled(True))
|
||||
|
||||
task.taskCompleted.connect(lambda: QMessageBox.information(
|
||||
self,
|
||||
"Hotovo",
|
||||
"Hesláře byly úspěšně aktualizovány."
|
||||
))
|
||||
|
||||
# Show the exact error if the task fails
|
||||
def on_error():
|
||||
if task.exception:
|
||||
# This will show exactly what went wrong (e.g. PermissionError)
|
||||
msg = (
|
||||
"Aktualizace selhala z důvodu chyby:\n"
|
||||
f"{str(task.exception)}"
|
||||
)
|
||||
else:
|
||||
msg = "Aktualizace byla zrušena uživatelem."
|
||||
QMessageBox.warning(self, "Chyba / Zrušeno", msg)
|
||||
|
||||
task.taskTerminated.connect(on_error)
|
||||
|
||||
QgsApplication.taskManager().addTask(task)
|
||||
|
||||
def get_bbox(self):
|
||||
return "true" if self.chk_bbox.isChecked() else "false"
|
||||
|
||||
def get_komponenty(self):
|
||||
return "true" if self.chk_komponenty.isChecked() else "false"
|
||||
|
||||
def get_filters(self):
|
||||
"""Compiles the user selections from the cache into
|
||||
API-ready filter parameters."""
|
||||
filters = {}
|
||||
|
||||
if self.selection_cache['kraj']:
|
||||
filters['f_kraj'] = self.selection_cache['kraj']
|
||||
if self.selection_cache['okres']:
|
||||
filters['f_okres'] = self.selection_cache['okres']
|
||||
if self.selection_cache['katastr']:
|
||||
filters['f_katastr'] = self.selection_cache['katastr']
|
||||
if self.selection_cache['obdobi']:
|
||||
filters['f_obdobi'] = self.selection_cache['obdobi']
|
||||
if self.selection_cache['areal']:
|
||||
filters['f_areal'] = self.selection_cache['areal']
|
||||
if self.selection_cache['pian_presnost']:
|
||||
filters['f_pian_presnost'] = self.selection_cache['pian_presnost']
|
||||
if self.selection_cache['pristupnost']:
|
||||
filters['pristupnost'] = self.selection_cache['pristupnost']
|
||||
|
||||
if self.typ_dat == "akce":
|
||||
if self.chk_posevidence.isChecked():
|
||||
filters['posevidence'] = 'true'
|
||||
if self.selection_cache['organizace']:
|
||||
filters['f_organizace'] = self.selection_cache['organizace']
|
||||
if self.selection_cache['typ_akce']:
|
||||
filters['f_typ_vyzkumu'] = self.selection_cache['typ_akce']
|
||||
if self.selection_cache['vedouci']:
|
||||
filters['f_vedouci'] = self.selection_cache['vedouci']
|
||||
|
||||
if self.typ_dat == "lokalita":
|
||||
if self.selection_cache['typ_lokality']:
|
||||
filters['f_typ_lokality'] = self.selection_cache['typ_lokality']
|
||||
if self.selection_cache['druh_lokality']:
|
||||
filters['f_druh_lokality'] = self.selection_cache['druh_lokality']
|
||||
if self.selection_cache['jistota']:
|
||||
filters['f_jistota'] = self.selection_cache['jistota']
|
||||
if self.selection_cache['lokalita_zachovalost']:
|
||||
filters['f_lokalita_zachovalost'] = self.selection_cache['lokalita_zachovalost']
|
||||
|
||||
return filters
|
||||
|
||||
|
||||
class LoginDialog(QDialog):
|
||||
"""
|
||||
Dialog for saving AMČR login credentials securely in the
|
||||
QGIS Authentication Manager.
|
||||
|
||||
Credentials are encrypted by the platform's native secret storage
|
||||
(DPAPI on Windows, Keychain on macOS, encrypted SQLite on Linux).
|
||||
The auth config ID is persisted in QSettings so the session can be
|
||||
restored automatically after a QGIS restart.
|
||||
|
||||
Note on QgsAuthManager quirks (QGIS 4 / Python bindings):
|
||||
- hasConfigId() is unreliable – it checks an in-memory cache that may not
|
||||
be populated yet. We never use it as a hard gate; we skip it and call
|
||||
loadAuthenticationConfig() directly instead.
|
||||
- storeAuthenticationConfig() and loadAuthenticationConfig() both have
|
||||
SIP_INOUT on their config parameter, so Python bindings return a tuple
|
||||
(bool, QgsAuthMethodConfig) rather than just bool. Always unpack both.
|
||||
- loadAuthenticationConfig() with full=False loads only metadata (name, method,
|
||||
id) but NOT the config() values like username/password. Use full=True to
|
||||
access those.
|
||||
"""
|
||||
|
||||
SETTINGS_KEY = "amcr_viewer/auth_config_id"
|
||||
CONFIG_NAME = "AMČR Viewer"
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Přihlášení do AMČR")
|
||||
self.setMinimumWidth(360)
|
||||
|
||||
layout = QVBoxLayout()
|
||||
|
||||
# Check whether a config ID is already stored from a previous session.
|
||||
# We attempt a lightweight load (full=False) to confirm it is readable,
|
||||
# since hasConfigId() may return False even for valid configs
|
||||
# (cache lag).
|
||||
# The Auth Manager must be unlocked before we attempt to read from it;
|
||||
# otherwise loadAuthenticationConfig() returns ok=False even for valid
|
||||
# configs, causing _has_saved to be incorrectly set to False.
|
||||
existing_id = QSettings().value(self.SETTINGS_KEY, "")
|
||||
if existing_id:
|
||||
QgsApplication.authManager().setMasterPassword(True)
|
||||
username = self._load_username_from_config(existing_id)
|
||||
self._has_saved = bool(existing_id) and bool(username)
|
||||
|
||||
if self._has_saved:
|
||||
info = QLabel(
|
||||
"✔ Přihlašovací údaje jsou bezpečně uloženy "
|
||||
"ve správci autentizace QGIS.\n"
|
||||
"Vyplňte pole níže pouze pokud je chcete změnit."
|
||||
)
|
||||
info.setStyleSheet("color: green; font-style: italic;")
|
||||
else:
|
||||
info = QLabel(
|
||||
"Zadejte přihlašovací údaje k Digitálnímu archivu AMČR.\n"
|
||||
"Budou zašifrovaně uloženy ve správci autentizace QGIS."
|
||||
)
|
||||
info.setWordWrap(True)
|
||||
layout.addWidget(info)
|
||||
layout.addSpacing(8)
|
||||
|
||||
form = QFormLayout()
|
||||
|
||||
self.txt_user = QLineEdit()
|
||||
self.txt_user.setPlaceholderText("např. jan.novak@email.cz")
|
||||
# Pre-fill the stored username (not sensitive) for convenience
|
||||
if self._has_saved:
|
||||
self.txt_user.setText(self._load_username_from_config(existing_id))
|
||||
form.addRow("E-mail:", self.txt_user)
|
||||
|
||||
self.txt_pass = QLineEdit()
|
||||
self.txt_pass.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
self.txt_pass.setPlaceholderText(
|
||||
"ponechte prázdné pro zachování stávajícího hesla"
|
||||
if self._has_saved
|
||||
else "heslo"
|
||||
)
|
||||
form.addRow("Heslo:", self.txt_pass)
|
||||
|
||||
layout.addLayout(form)
|
||||
layout.addSpacing(8)
|
||||
|
||||
if self._has_saved:
|
||||
btn_forget = QPushButton("Odebrat uložené přihlašovací údaje")
|
||||
btn_forget.setStyleSheet("color: #c0392b;")
|
||||
btn_forget.clicked.connect(self._forget_credentials)
|
||||
layout.addWidget(btn_forget)
|
||||
|
||||
layout.addStretch(1)
|
||||
|
||||
buttons = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok
|
||||
| QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
buttons.accepted.connect(self._save_and_accept)
|
||||
buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
self.setLayout(layout)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _load_config(config_id: str, full: bool = False):
|
||||
"""
|
||||
Attempt to load a QgsAuthMethodConfig by ID.
|
||||
Returns (ok, cfg). Never raises; returns (False, empty cfg)
|
||||
on any error.
|
||||
full=True decrypts and includes the password.
|
||||
"""
|
||||
try:
|
||||
auth_mgr = QgsApplication.authManager()
|
||||
cfg = QgsAuthMethodConfig()
|
||||
result = auth_mgr.loadAuthenticationConfig(config_id, cfg, full)
|
||||
# Python bindings return (bool, cfg) due to SIP_INOUT parameter
|
||||
if isinstance(result, tuple):
|
||||
return result
|
||||
return result, cfg
|
||||
except Exception:
|
||||
return False, QgsAuthMethodConfig()
|
||||
|
||||
def _load_username_from_config(self, config_id: str) -> str:
|
||||
"""Load the username from a stored config.
|
||||
Requires full=True since config() values are only populated
|
||||
when the config is fully decrypted."""
|
||||
ok, cfg = self._load_config(config_id, full=True)
|
||||
return cfg.config("username", "") if ok else ""
|
||||
|
||||
def _ensure_master_password(self) -> bool:
|
||||
"""
|
||||
Ensure the Auth Manager is unlocked before writing.
|
||||
Prompts the user to set or enter the master password if needed.
|
||||
Returns True if the manager is ready, False if the user cancelled.
|
||||
"""
|
||||
auth_mgr = QgsApplication.authManager()
|
||||
|
||||
if auth_mgr.isDisabled():
|
||||
QMessageBox.critical(
|
||||
self, "Správce autentizace nedostupný",
|
||||
"Správce autentizace QGIS je zakázán nebo poškozený.\n"
|
||||
"Zkuste obnovit databázi: "
|
||||
"Nastavení → Možnosti → Autentizace → Pomůcky."
|
||||
)
|
||||
return False
|
||||
|
||||
# setMasterPassword(True) shows the QGIS
|
||||
# master password dialog if needed
|
||||
if not auth_mgr.setMasterPassword(True):
|
||||
return False # User cancelled the master password dialog
|
||||
|
||||
return True
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Button actions
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _save_and_accept(self):
|
||||
username = self.txt_user.text().strip()
|
||||
password = self.txt_pass.text()
|
||||
|
||||
if not username:
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"Chybí údaje",
|
||||
"Vyplňte prosím e-mailovou adresu."
|
||||
)
|
||||
return
|
||||
|
||||
existing_id = QSettings().value(self.SETTINGS_KEY, "")
|
||||
auth_mgr = QgsApplication.authManager()
|
||||
|
||||
# If a config already exists and the password field is blank,
|
||||
# update only the username and keep the existing encrypted password.
|
||||
if not password and existing_id:
|
||||
ok, cfg = self._load_config(existing_id, full=True)
|
||||
if ok:
|
||||
if not self._ensure_master_password():
|
||||
return
|
||||
cfg.setConfig("username", username)
|
||||
auth_mgr.updateAuthenticationConfig(cfg)
|
||||
self.accept()
|
||||
return
|
||||
|
||||
if not password:
|
||||
QMessageBox.warning(self, "Chybí údaje", "Vyplňte prosím heslo.")
|
||||
return
|
||||
|
||||
if not self._ensure_master_password():
|
||||
return
|
||||
|
||||
cfg = QgsAuthMethodConfig()
|
||||
cfg.setName(self.CONFIG_NAME)
|
||||
cfg.setMethod("Basic")
|
||||
cfg.setConfig("username", username)
|
||||
cfg.setConfig("password", password) # nosec B106
|
||||
|
||||
settings = QSettings()
|
||||
|
||||
# Try to update an existing config first;
|
||||
# fall back to creating a new one.
|
||||
# We skip hasConfigId() as it may return False
|
||||
# despite the config existing
|
||||
# (in-memory cache may not be populated yet in QGIS 4).
|
||||
ok_load, existing_cfg = (
|
||||
self._load_config(existing_id, full=False)
|
||||
if existing_id
|
||||
else (False, None)
|
||||
)
|
||||
if ok_load:
|
||||
cfg.setId(existing_id)
|
||||
ok = auth_mgr.updateAuthenticationConfig(cfg)
|
||||
else:
|
||||
ok, cfg = auth_mgr.storeAuthenticationConfig(cfg)
|
||||
|
||||
config_id = cfg.id() if cfg else ""
|
||||
|
||||
if not ok or not config_id:
|
||||
QMessageBox.critical(
|
||||
self, "Chyba uložení",
|
||||
"Přihlašovací údaje se nepodařilo "
|
||||
"uložit do správce autentizace QGIS.\n"
|
||||
"Zkuste restartovat QGIS a přihlásit se znovu."
|
||||
)
|
||||
return
|
||||
|
||||
settings.setValue(self.SETTINGS_KEY, config_id)
|
||||
self.accept()
|
||||
|
||||
def _forget_credentials(self):
|
||||
settings = QSettings()
|
||||
existing_id = settings.value(self.SETTINGS_KEY, "")
|
||||
if existing_id:
|
||||
QgsApplication.authManager().removeAuthenticationConfig(existing_id)
|
||||
settings.remove(self.SETTINGS_KEY)
|
||||
QMessageBox.information(
|
||||
self,
|
||||
"Hotovo",
|
||||
"Uložené přihlašovací údaje byly odebrány."
|
||||
)
|
||||
self.reject()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public static API – call this anywhere in the plugin to get credentials
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def get_credentials() -> tuple[str, str]:
|
||||
"""
|
||||
Retrieve (username, password) from the QGIS Authentication Manager.
|
||||
Returns ('', '') if no credentials are stored or the manager is locked.
|
||||
|
||||
Note: hasConfigId() is intentionally skipped here – it checks an
|
||||
in-memory cache that may lag behind the actual database contents,
|
||||
causing false negatives (see class docstring).
|
||||
loadAuthenticationConfig() is called directly and its return value is
|
||||
used as the authoritative result.
|
||||
"""
|
||||
settings = QSettings()
|
||||
config_id = settings.value(LoginDialog.SETTINGS_KEY, "")
|
||||
|
||||
if not config_id:
|
||||
return "", ""
|
||||
|
||||
ok, cfg = LoginDialog._load_config(config_id, full=True)
|
||||
if not ok:
|
||||
return "", ""
|
||||
|
||||
return cfg.config("username", ""), cfg.config("password", "") # nosec B106
|
||||
@@ -0,0 +1,866 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from qgis.core import (QgsProject, QgsVectorLayer, QgsFeature, QgsGeometry,
|
||||
QgsField, QgsCoordinateReferenceSystem,
|
||||
QgsCoordinateTransform, QgsWkbTypes, Qgis,
|
||||
QgsMessageLog)
|
||||
from qgis.utils import iface
|
||||
from qgis.PyQt.QtCore import Qt, QMetaType
|
||||
from qgis.PyQt.QtWidgets import QApplication
|
||||
from qgis.PyQt.QtGui import QCursor
|
||||
import requests
|
||||
import json
|
||||
|
||||
# Global cache to store translated terms from the Digital Archive
|
||||
TRANSLATIONS = {}
|
||||
|
||||
# Session with authentication cookie after login;
|
||||
# None = not logged in (anonymous access)
|
||||
AMCR_SESSION: requests.Session | None = None
|
||||
|
||||
|
||||
def _log(msg: str, level=Qgis.MessageLevel.Info):
|
||||
"""
|
||||
Shortcut: writes a message to the QGIS log
|
||||
(Messages panel → AMČR tab).
|
||||
"""
|
||||
QgsMessageLog.logMessage(msg, "AMČR login", level)
|
||||
|
||||
|
||||
def login_to_api(username: str, password: str):
|
||||
"""
|
||||
Logs in to the Digiarchiv API using a username and password.
|
||||
Returns a requests.Session with the session cookie set, or None on error.
|
||||
"""
|
||||
login_url = "https://digiarchiv.aiscr.cz/api/user/login"
|
||||
|
||||
_log(f"Přihlašuji uživatele: '{username}'")
|
||||
|
||||
if not username or not password:
|
||||
_log(
|
||||
"CHYBA: username nebo heslo je prázdné.",
|
||||
Qgis.MessageLevel.Critical
|
||||
)
|
||||
return None
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": "QGIS-Plugin/1.0 (AISCR Data Fetcher)"
|
||||
})
|
||||
|
||||
try:
|
||||
_log(f"Odesílám POST na {login_url} ...")
|
||||
response = session.post(
|
||||
login_url,
|
||||
json={"user": username, "pwd": password},
|
||||
timeout=10
|
||||
)
|
||||
_log(f"HTTP status: {response.status_code}")
|
||||
response.raise_for_status()
|
||||
|
||||
# The API returns errors with status code 200 –
|
||||
# the response body must be checked
|
||||
body = response.json()
|
||||
if "error" in body:
|
||||
_log(
|
||||
f"CHYBA přihlášení (API): {body['error']}",
|
||||
Qgis.MessageLevel.Critical
|
||||
)
|
||||
return None
|
||||
|
||||
_log("Přihlášení proběhlo úspěšně.")
|
||||
global AMCR_SESSION
|
||||
AMCR_SESSION = session
|
||||
return session
|
||||
|
||||
except requests.exceptions.HTTPError as e:
|
||||
_log(f"CHYBA HTTP {e.response.status_code if e.response else '?'}: "
|
||||
f"{e.response.text[:300] if e.response else 'žádná odpověď'}",
|
||||
Qgis.MessageLevel.Critical)
|
||||
return None
|
||||
except requests.exceptions.RequestException as e:
|
||||
_log(f"CHYBA sítě: {e}", Qgis.MessageLevel.Critical)
|
||||
return None
|
||||
|
||||
|
||||
def _get_session() -> requests.Session | None:
|
||||
"""
|
||||
Returns the active session. If none exists (e.g. after a QGIS restart),
|
||||
attempts automatic login using stored credentials.
|
||||
Returns None if no credentials are stored.
|
||||
"""
|
||||
global AMCR_SESSION
|
||||
if AMCR_SESSION is not None:
|
||||
return AMCR_SESSION
|
||||
|
||||
# Attempt auto-login using stored credentials
|
||||
from .amcr_dialog import LoginDialog
|
||||
username, password = LoginDialog.get_credentials()
|
||||
if username and password:
|
||||
_log("Session vypršela nebo chybí – automatické přihlášení...")
|
||||
AMCR_SESSION = login_to_api(username, password)
|
||||
|
||||
return AMCR_SESSION
|
||||
|
||||
|
||||
def _api_get(url, params, timeout=30) -> requests.Response:
|
||||
"""
|
||||
Performs a GET request. If the API signals an expired login,
|
||||
re-authenticates once and retries.
|
||||
"""
|
||||
global AMCR_SESSION
|
||||
|
||||
def _is_auth_error(resp: requests.Response) -> bool:
|
||||
"""The API returns auth errors with status 200 –
|
||||
the body must be checked."""
|
||||
if resp.status_code == 401:
|
||||
return True
|
||||
try:
|
||||
body = resp.json()
|
||||
err = str(body.get("error", "")).lower()
|
||||
return (
|
||||
"unauthorized" in err
|
||||
or "not logged" in err
|
||||
or "session" in err
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
session = _get_session()
|
||||
resp = (session or requests).get(url, params=params, timeout=timeout)
|
||||
|
||||
if _is_auth_error(resp):
|
||||
_log("Session vypršela během stahování – obnovuji přihlášení...",
|
||||
Qgis.MessageLevel.Warning)
|
||||
AMCR_SESSION = None # Invalidate the old session
|
||||
from .amcr_dialog import LoginDialog
|
||||
username, password = LoginDialog.get_credentials()
|
||||
if username and password:
|
||||
AMCR_SESSION = login_to_api(username, password)
|
||||
if AMCR_SESSION:
|
||||
resp = AMCR_SESSION.get(url, params=params, timeout=timeout)
|
||||
else:
|
||||
_log("Opakované přihlášení selhalo.",
|
||||
Qgis.MessageLevel.Critical)
|
||||
else:
|
||||
_log("Přihlašovací údaje nejsou uloženy – pokračuji anonymně.",
|
||||
Qgis.MessageLevel.Warning)
|
||||
|
||||
return resp
|
||||
|
||||
|
||||
def load_translations():
|
||||
"""
|
||||
Fetches the official Czech translation dictionary
|
||||
from the Digiarchive API.
|
||||
"""
|
||||
global TRANSLATIONS
|
||||
if TRANSLATIONS:
|
||||
return
|
||||
|
||||
url = "https://digiarchiv.aiscr.cz/api/assets/i18n/cs.json"
|
||||
try:
|
||||
r = requests.get(url, timeout=10)
|
||||
if r.status_code == 200:
|
||||
TRANSLATIONS = r.json()
|
||||
except Exception as e:
|
||||
print(f"Error downloading vocabulary: {e}")
|
||||
|
||||
|
||||
def tr_code(code):
|
||||
"""
|
||||
Translates a technical code into a human-readable string
|
||||
using the global cache.
|
||||
"""
|
||||
if not code:
|
||||
return ""
|
||||
return TRANSLATIONS.get(code, code)
|
||||
|
||||
|
||||
def komp_projde_filtrem(komp, filter_areal, filter_datace, filters):
|
||||
areal_id = komp.get('komponenta_areal', {}).get('id', "")
|
||||
if filter_areal and areal_id not in filters.get('f_areal', []):
|
||||
return False
|
||||
|
||||
obdobi_id = komp.get('komponenta_obdobi', {}).get('id', "")
|
||||
if filter_datace and obdobi_id not in filters.get('f_obdobi', []):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def load_amcr_data(canvas, bb, filters=None,
|
||||
typ_dat="akce", komponenty="false"):
|
||||
"""
|
||||
Main processing function:
|
||||
1. Determines search area (Bounding Box)
|
||||
2. Fetches metadata and geometries from API
|
||||
3. Creates QGIS memory layers and populates them with features
|
||||
"""
|
||||
load_translations()
|
||||
|
||||
# --- 1. COORDINATE TRANSFORMATION ---
|
||||
# Get current map extent and transform it
|
||||
# from project CRS (usually S-JTSK) to WGS-84 for the API
|
||||
extent = canvas.extent()
|
||||
crs_src = canvas.mapSettings().destinationCrs()
|
||||
crs_dest = QgsCoordinateReferenceSystem("EPSG:4326")
|
||||
xform = QgsCoordinateTransform(crs_src, crs_dest, QgsProject.instance())
|
||||
extent_wgs = xform.transformBoundingBox(extent)
|
||||
|
||||
# Format the bounding box string as required by the API:
|
||||
# minLat,minLon,maxLat,maxLon
|
||||
bbox_str = (
|
||||
f"{extent_wgs.yMinimum()},{extent_wgs.xMinimum()},"
|
||||
f"{extent_wgs.yMaximum()},{extent_wgs.xMaximum()}"
|
||||
)
|
||||
|
||||
url = "https://digiarchiv.aiscr.cz/api/search/query"
|
||||
|
||||
iface.messageBar().pushMessage(
|
||||
"AMCR",
|
||||
"Hledám záznamy...",
|
||||
level=Qgis.MessageLevel.Info
|
||||
)
|
||||
QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor))
|
||||
|
||||
try:
|
||||
# ==========================================
|
||||
# A) METADATA FETCHING (Fieldwork/Site)
|
||||
# ==========================================
|
||||
|
||||
base_params = {
|
||||
"mapa": "true",
|
||||
"sort": "ident_cely asc",
|
||||
"entity": typ_dat
|
||||
}
|
||||
|
||||
# Restrict search to map window if requested
|
||||
if bb == "true":
|
||||
base_params["loc_rpt"] = bbox_str
|
||||
|
||||
# Apply multi-select filters from the dialog using
|
||||
# the ':or' syntax required by the API
|
||||
if filters:
|
||||
for key, value in filters.items():
|
||||
if not value:
|
||||
continue
|
||||
if isinstance(value, list):
|
||||
base_params[key] = [f"{v}:or" for v in value]
|
||||
else:
|
||||
base_params[key] = str(value).strip()
|
||||
|
||||
docs = []
|
||||
current_page = 0
|
||||
BATCH_DOCS = 500 # Records per API request
|
||||
MAX_LIMIT = 20000 # Safety limit to prevent QGIS from freezing
|
||||
|
||||
seen_ids = set()
|
||||
target_pian_ids_count = 0
|
||||
|
||||
# Check if we should skip negative results based on filter
|
||||
skip_negativni = (
|
||||
filters.get('posevidence') == 'true'
|
||||
if filters
|
||||
else False
|
||||
)
|
||||
|
||||
# Check whether we should filter results based on component filters
|
||||
filter_areal = "f_areal" in filters if filters else False
|
||||
filter_datace = "f_obdobi" in filters if filters else False
|
||||
|
||||
# --- API PAGINATION LOOP ---
|
||||
while True:
|
||||
base_params['rows'] = BATCH_DOCS
|
||||
if current_page > 0:
|
||||
base_params['page'] = current_page
|
||||
elif 'page' in base_params:
|
||||
del base_params['page']
|
||||
|
||||
try:
|
||||
resp_docs = _api_get(url, params=base_params, timeout=30)
|
||||
resp_json = resp_docs.json()
|
||||
data = resp_json.get('response', {})
|
||||
batch_docs = data.get('docs', [])
|
||||
num_found = data.get('numFound', 0)
|
||||
|
||||
if not batch_docs:
|
||||
break
|
||||
|
||||
# Filter out duplicates and append to main list
|
||||
new_docs = []
|
||||
for d in batch_docs:
|
||||
ident = d.get('ident_cely')
|
||||
if ident and ident not in seen_ids:
|
||||
seen_ids.add(ident)
|
||||
new_docs.append(d)
|
||||
|
||||
docs.extend(new_docs)
|
||||
print(
|
||||
f"Strana {current_page} stažena. "
|
||||
f"Celkem záznamů: {len(docs)} / {num_found}"
|
||||
)
|
||||
|
||||
if len(docs) >= num_found:
|
||||
break
|
||||
if len(docs) >= MAX_LIMIT:
|
||||
iface.messageBar().pushMessage(
|
||||
"AMCR",
|
||||
f"Limit {MAX_LIMIT} záznamů dosažen.",
|
||||
level=Qgis.MessageLevel.Warning
|
||||
)
|
||||
break
|
||||
|
||||
current_page += 1
|
||||
QApplication.processEvents() # Keep UI responsive
|
||||
|
||||
except Exception as e:
|
||||
print(f"Chyba při stránkování na straně {current_page}: {e}")
|
||||
break
|
||||
|
||||
if not docs:
|
||||
iface.messageBar().pushMessage(
|
||||
"AMCR",
|
||||
"Žádné záznamy nenalezeny.",
|
||||
level=Qgis.MessageLevel.Warning
|
||||
)
|
||||
return
|
||||
|
||||
# ==========================================
|
||||
# B) ATTRIBUTE PARSING
|
||||
# ==========================================
|
||||
|
||||
# pian_lookup maps a Geometry ID (PIAN)
|
||||
# to a list of its associated metadata
|
||||
pian_lookup = {}
|
||||
target_pian_ids = set()
|
||||
actions_with_geom = 0
|
||||
|
||||
# Helper: safely extract a single value
|
||||
def g(doc, key, default=""):
|
||||
val = doc.get(key)
|
||||
if isinstance(val, list):
|
||||
return str(val[0]) if val else default
|
||||
return str(val) if val is not None else default
|
||||
|
||||
# Helper: safely extract and join a list of values
|
||||
def g_list(doc, key, translate=False):
|
||||
val = doc.get(key, [])
|
||||
if not isinstance(val, list):
|
||||
val = [val] if val else []
|
||||
if translate:
|
||||
return ", ".join([tr_code(str(x)) for x in val if x])
|
||||
return ", ".join([str(x) for x in val if x])
|
||||
|
||||
# Process each downloaded metadata record
|
||||
for doc in docs:
|
||||
piani = doc.get('az_dj_pian', [])
|
||||
if not piani:
|
||||
continue
|
||||
|
||||
actions_with_geom += 1
|
||||
|
||||
# Extract protected fields
|
||||
az_chranene = doc.get('az_chranene_udaje', {})
|
||||
chranene = (
|
||||
doc.get('akce_chranene_udaje')
|
||||
or doc.get('lokalita_chranene_udaje')
|
||||
or {}
|
||||
)
|
||||
|
||||
# Format additional cadastral areas from nested dicts
|
||||
dalsi_kat = az_chranene.get('dalsi_katastr', [])
|
||||
dalsi_kat_str = ""
|
||||
if isinstance(dalsi_kat, list):
|
||||
items = [
|
||||
x.get('value', '') if isinstance(x, dict) else str(x)
|
||||
for x in dalsi_kat
|
||||
]
|
||||
dalsi_kat_str = ", ".join([i for i in items if i])
|
||||
|
||||
lokalizace = chranene.get('lokalizace_okolnosti', "")
|
||||
lokalita_nazev = chranene.get('nazev', "")
|
||||
lokalita_popis = chranene.get('popis', "")
|
||||
|
||||
# Core metadata structure
|
||||
meta = {
|
||||
"ident_cely": doc.get('ident_cely', ''),
|
||||
"az_okres": g(doc, 'az_okres'),
|
||||
"katastr": g_list(doc, 'katastr'),
|
||||
"dalsi_katastr": dalsi_kat_str,
|
||||
"pristupnost": g(doc, 'pristupnost'),
|
||||
"loc": g_list(doc, 'loc')
|
||||
}
|
||||
|
||||
# Add entity-specific metadata
|
||||
if typ_dat == "akce":
|
||||
meta.update({
|
||||
"akce_hlavni_vedouci": g(
|
||||
doc,
|
||||
'akce_hlavni_vedouci'
|
||||
),
|
||||
"akce_organizace": tr_code(g(
|
||||
doc,
|
||||
'akce_organizace'
|
||||
)),
|
||||
"akce_specifikace_data": tr_code(g(
|
||||
doc,
|
||||
'akce_specifikace_data'
|
||||
)),
|
||||
"akce_datum_zahajeni": g(
|
||||
doc,
|
||||
'akce_datum_zahajeni'
|
||||
),
|
||||
"akce_datum_ukonceni": g(
|
||||
doc,
|
||||
'akce_datum_ukonceni'
|
||||
),
|
||||
"akce_hlavni_typ": tr_code(g(
|
||||
doc,
|
||||
'akce_hlavni_typ'
|
||||
)),
|
||||
"akce_vedlejsi_typ": g_list(
|
||||
doc,
|
||||
'akce_vedlejsi_typ',
|
||||
translate=True
|
||||
),
|
||||
"lokalizace_okolnosti": (
|
||||
str(lokalizace)
|
||||
if lokalizace
|
||||
else ""
|
||||
),
|
||||
"akce_je_nz": (
|
||||
"Ano"
|
||||
if doc.get('akce_je_nz') is True
|
||||
else "Ne"
|
||||
),
|
||||
})
|
||||
|
||||
elif typ_dat == "lokalita":
|
||||
meta.update({
|
||||
"lokalita_nazev": lokalita_nazev,
|
||||
"lokalita_popis": lokalita_popis,
|
||||
"lokalita_zachovalost": tr_code(g(
|
||||
doc,
|
||||
'lokalita_zachovalost'
|
||||
)),
|
||||
"lokalita_druh": tr_code(g(
|
||||
doc,
|
||||
'lokalita_druh'
|
||||
)),
|
||||
"lokalita_typ": tr_code(g(
|
||||
doc,
|
||||
'lokalita_typ_lokality'
|
||||
)),
|
||||
})
|
||||
|
||||
# Documentation units (DJ) within the record
|
||||
djs = doc.get('az_dokumentacni_jednotka', [])
|
||||
|
||||
for dj in djs:
|
||||
# Skip negative evidence units if requested
|
||||
if skip_negativni and dj.get('dj_negativni_jednotka') is True:
|
||||
continue
|
||||
|
||||
komps = dj.get('dj_komponenta', [])
|
||||
|
||||
if filter_areal or filter_datace:
|
||||
if not komps:
|
||||
continue
|
||||
if not any(
|
||||
komp_projde_filtrem(
|
||||
komp, filter_areal,
|
||||
filter_datace, filters
|
||||
)
|
||||
for komp in komps
|
||||
):
|
||||
continue
|
||||
|
||||
dj_id = dj.get('ident_cely')
|
||||
dj_typ = dj.get('dj_typ')
|
||||
|
||||
# Merge shared metadata with documentation unit-specific fields
|
||||
dj_meta = {
|
||||
**meta,
|
||||
'dj_id': dj_id,
|
||||
'dj_typ_value': dj_typ.get('value') if dj_typ else "",
|
||||
'dj_negativni': (
|
||||
"Negativní"
|
||||
if dj.get('dj_negativni_jednotka') is True
|
||||
else "Pozitivní"
|
||||
)
|
||||
}
|
||||
|
||||
# Link Documentation Unit to Geometry (PIAN)
|
||||
dj_pian = dj.get('dj_pian')
|
||||
if dj_pian:
|
||||
dj_pian_value = dj_pian.get('id')
|
||||
if dj_pian_value:
|
||||
target_pian_ids.add(dj_pian_value)
|
||||
if dj_pian_value not in pian_lookup:
|
||||
pian_lookup[dj_pian_value] = []
|
||||
|
||||
if komponenty == "true":
|
||||
# One feature per component –
|
||||
# all data on a single row, no relations needed
|
||||
if komps:
|
||||
for komp in komps:
|
||||
if not komp_projde_filtrem(
|
||||
komp, filter_areal,
|
||||
filter_datace, filters
|
||||
):
|
||||
continue
|
||||
|
||||
komp_meta = {
|
||||
**dj_meta,
|
||||
'komponenta_id': komp.get(
|
||||
'ident_cely',
|
||||
""
|
||||
),
|
||||
'komponenta_areal': komp.get(
|
||||
'komponenta_areal',
|
||||
{}
|
||||
).get('value', ""),
|
||||
'komponenta_obdobi': komp.get(
|
||||
'komponenta_obdobi',
|
||||
{}
|
||||
).get('value', ""),
|
||||
}
|
||||
pian_lookup[dj_pian_value].append(komp_meta)
|
||||
target_pian_ids_count += 1
|
||||
else:
|
||||
# DJ without components — still include
|
||||
# with empty component fields
|
||||
if filter_areal or filter_datace:
|
||||
continue
|
||||
|
||||
empty_meta = {
|
||||
**dj_meta,
|
||||
'komponenta_id': "",
|
||||
'komponenta_areal': "",
|
||||
'komponenta_obdobi': "",
|
||||
}
|
||||
pian_lookup[dj_pian_value].append(empty_meta)
|
||||
target_pian_ids_count += 1
|
||||
else:
|
||||
target_pian_ids_count += 1
|
||||
pian_lookup[dj_pian_value].append(dj_meta)
|
||||
|
||||
if not target_pian_ids:
|
||||
iface.messageBar().pushMessage(
|
||||
"AMCR",
|
||||
f"Nalezeno {len(docs)} záznamů, ale žádný nemá geometrii.",
|
||||
level=Qgis.MessageLevel.Warning
|
||||
)
|
||||
return
|
||||
|
||||
# ==========================================
|
||||
# C) GEOMETRY FETCHING (PIAN)
|
||||
# ==========================================
|
||||
ids_list = list(target_pian_ids)
|
||||
total_pians = len(ids_list)
|
||||
docs_pian = []
|
||||
# Geometry requests are batch-processed
|
||||
# to stay under URL length limits:
|
||||
BATCH_PIAN = 200
|
||||
|
||||
iface.messageBar().pushMessage(
|
||||
"AMCR",
|
||||
f"Záznamů: {len(docs)} (z toho {actions_with_geom} s mapou). "
|
||||
f"Stahuji {total_pians} unikátních geometrií, "
|
||||
f"vykresluji {target_pian_ids_count} geometrií...",
|
||||
level=Qgis.MessageLevel.Info
|
||||
)
|
||||
|
||||
fl_pian = [
|
||||
"ident_cely", "pian_typ",
|
||||
"pian_chranene_udaje", "pian_presnost"
|
||||
]
|
||||
|
||||
for i in range(0, total_pians, BATCH_PIAN):
|
||||
batch = ids_list[i: i + BATCH_PIAN]
|
||||
or_query = " OR ".join(batch)
|
||||
fq_pian = f"ident_cely:({or_query})"
|
||||
|
||||
params_pian = {
|
||||
"mapa": "true",
|
||||
"entity": "pian",
|
||||
"q": fq_pian,
|
||||
"rows": len(batch),
|
||||
"fl": ",".join(fl_pian)
|
||||
}
|
||||
try:
|
||||
QApplication.processEvents()
|
||||
r_pian = _api_get(url, params=params_pian, timeout=15)
|
||||
batch_docs = r_pian.json().get('response', {}).get('docs', [])
|
||||
docs_pian.extend(batch_docs)
|
||||
except Exception as e:
|
||||
print(f"Chyba PIAN: {e}")
|
||||
|
||||
# ==========================================
|
||||
# D) LAYER CREATION (QGIS Memory Layers)
|
||||
# ==========================================
|
||||
|
||||
archeologicky_zaznam = "Akce" if typ_dat == "akce" else "Lokalita"
|
||||
|
||||
# Initialize three layers for different geometry types (S-JTSK CRS)
|
||||
vl_poly = QgsVectorLayer(
|
||||
"Polygon?crs=epsg:5514",
|
||||
f"AMCR_{archeologicky_zaznam}_Polygony",
|
||||
"memory"
|
||||
)
|
||||
vl_line = QgsVectorLayer(
|
||||
"LineString?crs=epsg:5514",
|
||||
f"AMCR_{archeologicky_zaznam}_Linie",
|
||||
"memory"
|
||||
)
|
||||
vl_point = QgsVectorLayer(
|
||||
"Point?crs=epsg:5514",
|
||||
f"AMCR_{archeologicky_zaznam}_Body",
|
||||
"memory"
|
||||
)
|
||||
layers = [vl_poly, vl_line, vl_point]
|
||||
|
||||
# Define attribute table structure
|
||||
cols = [
|
||||
QgsField("pian", QMetaType.Type.QString),
|
||||
QgsField("presnost", QMetaType.Type.QString),
|
||||
QgsField("pian_typ", QMetaType.Type.QString),
|
||||
QgsField("dj", QMetaType.Type.QString),
|
||||
QgsField("typ_dj", QMetaType.Type.QString),
|
||||
QgsField("definicni_body", QMetaType.Type.QString),
|
||||
QgsField(typ_dat, QMetaType.Type.QString),
|
||||
QgsField("odkaz_do_digiarchivu", QMetaType.Type.QString),
|
||||
QgsField("okres", QMetaType.Type.QString),
|
||||
QgsField("katastr", QMetaType.Type.QString),
|
||||
QgsField("dalsi_katastry", QMetaType.Type.QString)
|
||||
]
|
||||
|
||||
# Extend table based on data type
|
||||
if typ_dat == "akce":
|
||||
cols += [
|
||||
QgsField("akce_lokalizace", QMetaType.Type.QString),
|
||||
QgsField("vedouci", QMetaType.Type.QString),
|
||||
QgsField("organizace", QMetaType.Type.QString),
|
||||
QgsField("specifikace_data", QMetaType.Type.QString),
|
||||
QgsField("zahajeni", QMetaType.Type.QString),
|
||||
QgsField("ukonceni", QMetaType.Type.QString),
|
||||
QgsField("hlavni_typ", QMetaType.Type.QString),
|
||||
QgsField("vedlejsi_typ", QMetaType.Type.QString),
|
||||
QgsField("zjisteni", QMetaType.Type.QString),
|
||||
QgsField("nahrazuje_NZ", QMetaType.Type.QString),
|
||||
]
|
||||
elif typ_dat == "lokalita":
|
||||
cols += [
|
||||
QgsField("nazev_lokality", QMetaType.Type.QString),
|
||||
QgsField("popis_lokality", QMetaType.Type.QString),
|
||||
QgsField("typ_lokality", QMetaType.Type.QString),
|
||||
QgsField("druh_lokality", QMetaType.Type.QString),
|
||||
QgsField("zachovalost", QMetaType.Type.QString)
|
||||
]
|
||||
|
||||
cols.append(QgsField("Přístupnost", QMetaType.Type.QString))
|
||||
|
||||
# Use aliases for technical field names
|
||||
alias_map = {
|
||||
"pian": "PIAN",
|
||||
"presnost": "Přesnost",
|
||||
"pian_typ": "PIAN – typ",
|
||||
"dj": "Dokumentační jednotka",
|
||||
"typ_dj": "Typ dokumentační jednotky",
|
||||
"definicni_body": "Definiční bod(y) (WGS-84)",
|
||||
typ_dat: archeologicky_zaznam,
|
||||
"odkaz_do_digiarchivu": "Odkaz do Digitálního archivu AMČR",
|
||||
"okres": "Okres",
|
||||
"katastr": "Katastr",
|
||||
"dalsi_katastry": "Další katastry",
|
||||
"akce_lokalizace": "Akce – lokalizace",
|
||||
"vedouci": "Vedoucí akce",
|
||||
"organizace": "Organizace",
|
||||
"specifikace_data": "Specifikace data",
|
||||
"zahajeni": "Datum zahájeni",
|
||||
"ukonceni": "Datum ukončení",
|
||||
"hlavni_typ": "Hlavní typ",
|
||||
"vedlejsi_typ": "Vedlejší typ",
|
||||
"zjisteni": "Zjištění",
|
||||
"nahrazuje_NZ": "Akce – nahrazuje NZ",
|
||||
"nazev_lokality": "Název lokality",
|
||||
"popis_lokality": "Popis lokality",
|
||||
"typ_lokality": "Typ lokality",
|
||||
"druh_lokality": "Druh lokality",
|
||||
"zachovalost": "Zachovalost",
|
||||
"komponenta": "Komponenta",
|
||||
"komponenta_areal": "Areál",
|
||||
"komponenta_obdobi": "Období",
|
||||
}
|
||||
|
||||
if komponenty == "true":
|
||||
cols += [
|
||||
QgsField("komponenta", QMetaType.Type.QString),
|
||||
QgsField("komponenta_areal", QMetaType.Type.QString),
|
||||
QgsField("komponenta_obdobi", QMetaType.Type.QString),
|
||||
]
|
||||
|
||||
for vl in layers:
|
||||
vl.dataProvider().addAttributes(cols)
|
||||
vl.updateFields()
|
||||
for tech_name, alias in alias_map.items():
|
||||
idx = vl.fields().lookupField(tech_name)
|
||||
if idx != -1:
|
||||
vl.setFieldAlias(idx, alias)
|
||||
|
||||
# Lists to hold features before batch-adding to layers
|
||||
feats_p, feats_l, feats_pt = [], [], []
|
||||
|
||||
# --- FEATURE POPULATION ---
|
||||
for doc in docs_pian:
|
||||
try:
|
||||
pid = doc.get('ident_cely', '')
|
||||
if pid not in pian_lookup:
|
||||
continue
|
||||
|
||||
metas = pian_lookup[pid]
|
||||
|
||||
# Extract WKT geometry from protected JSON data
|
||||
raw = doc.get('pian_chranene_udaje')
|
||||
if isinstance(raw, list) and raw:
|
||||
raw = raw[0]
|
||||
jdata = (
|
||||
json.loads(raw)
|
||||
if isinstance(raw, str)
|
||||
else (raw or {})
|
||||
)
|
||||
|
||||
wkt = None
|
||||
if jdata.get('geom_sjtsk_wkt'):
|
||||
wkt = jdata.get('geom_sjtsk_wkt', {}).get('value')
|
||||
elif jdata.get('geom_wkt'):
|
||||
wkt = jdata.get('geom_wkt', {}).get('value')
|
||||
|
||||
pian_presnost = tr_code(str(doc.get('pian_presnost', '')))
|
||||
pian_typ = tr_code(str(doc.get('pian_typ', '')))
|
||||
|
||||
# Final precision filter check
|
||||
if (
|
||||
filters
|
||||
and filters.get('f_pian_presnost')
|
||||
and doc.get('pian_presnost')
|
||||
not in filters.get('f_pian_presnost')
|
||||
):
|
||||
continue
|
||||
|
||||
if wkt:
|
||||
geom = QgsGeometry.fromWkt(wkt)
|
||||
if geom.isGeosValid():
|
||||
t = geom.type()
|
||||
target_list = None
|
||||
if t == QgsWkbTypes.PolygonGeometry:
|
||||
target_list = feats_p
|
||||
elif t == QgsWkbTypes.LineGeometry:
|
||||
target_list = feats_l
|
||||
elif t == QgsWkbTypes.PointGeometry:
|
||||
target_list = feats_pt
|
||||
|
||||
if target_list is None:
|
||||
continue
|
||||
|
||||
is_akce = (typ_dat == "akce")
|
||||
|
||||
# Create a QGIS feature for each documentation unit
|
||||
# associated with this geometry
|
||||
for meta in metas:
|
||||
feat = QgsFeature()
|
||||
feat.setGeometry(geom)
|
||||
atributy = [
|
||||
pid,
|
||||
pian_presnost,
|
||||
pian_typ,
|
||||
meta['dj_id'],
|
||||
meta['dj_typ_value'],
|
||||
meta['loc'],
|
||||
meta['ident_cely'],
|
||||
"https://digiarchiv.aiscr.cz/id/"
|
||||
+ meta['ident_cely'],
|
||||
meta['az_okres'],
|
||||
meta['katastr'],
|
||||
meta['dalsi_katastr']
|
||||
]
|
||||
if is_akce:
|
||||
atributy.extend([
|
||||
meta['lokalizace_okolnosti'],
|
||||
meta['akce_hlavni_vedouci'],
|
||||
meta['akce_organizace'],
|
||||
meta['akce_specifikace_data'],
|
||||
meta['akce_datum_zahajeni'],
|
||||
meta['akce_datum_ukonceni'],
|
||||
meta['akce_hlavni_typ'],
|
||||
meta['akce_vedlejsi_typ'],
|
||||
meta['dj_negativni'],
|
||||
meta['akce_je_nz']
|
||||
])
|
||||
else:
|
||||
atributy.extend([
|
||||
meta['lokalita_nazev'],
|
||||
meta['lokalita_popis'],
|
||||
meta['lokalita_typ'],
|
||||
meta['lokalita_druh'],
|
||||
meta['lokalita_zachovalost']
|
||||
])
|
||||
|
||||
atributy.append(meta['pristupnost'])
|
||||
|
||||
if komponenty == "true":
|
||||
atributy.extend([
|
||||
meta.get('komponenta_id', ""),
|
||||
meta.get('komponenta_areal', ""),
|
||||
meta.get('komponenta_obdobi', ""),
|
||||
])
|
||||
|
||||
feat.setAttributes(atributy)
|
||||
target_list.append(feat)
|
||||
|
||||
except Exception as ex:
|
||||
print(f"Chyba při tvorbě feature: {ex}")
|
||||
pass
|
||||
|
||||
# --- ADDING TO QGIS INTERFACE ---
|
||||
proj = QgsProject.instance()
|
||||
added = 0
|
||||
layers_to_process = [
|
||||
(feats_p, vl_poly, "Polygony"),
|
||||
(feats_l, vl_line, "Linie"),
|
||||
(feats_pt, vl_point, "Body"),
|
||||
]
|
||||
|
||||
for f, l, n in layers_to_process:
|
||||
if f:
|
||||
l.dataProvider().addFeatures(f)
|
||||
l.updateExtents()
|
||||
l.setName(f"AMCR_{archeologicky_zaznam}_{n}")
|
||||
proj.addMapLayer(l)
|
||||
added += len(f)
|
||||
|
||||
if added > 0:
|
||||
iface.messageBar().pushMessage(
|
||||
"AMCR",
|
||||
f"Hotovo. Záznamů: {len(docs)} (s geom: {actions_with_geom}). "
|
||||
f"Vykresleno: {added} prvků.",
|
||||
level=Qgis.MessageLevel.Success
|
||||
)
|
||||
else:
|
||||
iface.messageBar().pushMessage(
|
||||
"AMCR",
|
||||
"Žádná data k zobrazení.",
|
||||
level=Qgis.MessageLevel.Info
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
iface.messageBar().pushMessage(
|
||||
"Chyba",
|
||||
str(e),
|
||||
level=Qgis.MessageLevel.Critical
|
||||
)
|
||||
finally:
|
||||
# Always restore cursor, even after failure
|
||||
QApplication.restoreOverrideCursor()
|
||||
@@ -0,0 +1,234 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, QUrl
|
||||
from qgis.PyQt.QtGui import QIcon, QDesktopServices
|
||||
from qgis.PyQt.QtWidgets import QMenu, QAction, QToolButton, QDialog
|
||||
from qgis.core import Qgis
|
||||
|
||||
from .amcr_tools import load_amcr_data, login_to_api
|
||||
from .amcr_dialog import AmcrFilterDialog, LoginDialog
|
||||
from .resources import *
|
||||
import os.path
|
||||
|
||||
|
||||
class AmcrViewer:
|
||||
"""
|
||||
Main plugin class that manages the GUI elements, menu entries,
|
||||
and coordinates the flow between user input and data processing.
|
||||
"""
|
||||
|
||||
def __init__(self, iface):
|
||||
"""
|
||||
Constructor initializes the connection to QGIS interface and sets up
|
||||
internationalization (i18n).
|
||||
"""
|
||||
self.iface = iface
|
||||
self.plugin_dir = os.path.dirname(__file__)
|
||||
|
||||
# Determine the user's locale to load appropriate translation files
|
||||
locale = QSettings().value('locale/userLocale')[0:2]
|
||||
locale_path = os.path.join(
|
||||
self.plugin_dir,
|
||||
'i18n',
|
||||
'AmcrViewer_{}.qm'.format(locale)
|
||||
)
|
||||
|
||||
# Install the translator if a translation file
|
||||
# for the current locale exists
|
||||
if os.path.exists(locale_path):
|
||||
self.translator = QTranslator()
|
||||
self.translator.load(locale_path)
|
||||
QCoreApplication.installTranslator(self.translator)
|
||||
|
||||
# Initialize internal state
|
||||
self.actions = []
|
||||
self.menu = self.tr(u'&AMČR Viewer')
|
||||
self.first_start = None
|
||||
|
||||
def tr(self, message):
|
||||
"""
|
||||
Helper method for translating strings within
|
||||
the AmcrViewer context.
|
||||
"""
|
||||
return QCoreApplication.translate('AmcrViewer', message)
|
||||
|
||||
def add_action(self, icon_path, text, callback, enabled_flag=True,
|
||||
add_to_menu=True, add_to_toolbar=True, status_tip=None,
|
||||
whats_this=None, parent=None):
|
||||
"""
|
||||
Helper method to create QActions and automatically register them
|
||||
into the QGIS Menu and Toolbar.
|
||||
"""
|
||||
icon = QIcon(icon_path)
|
||||
action = QAction(icon, text, parent)
|
||||
action.triggered.connect(callback)
|
||||
action.setEnabled(enabled_flag)
|
||||
|
||||
if status_tip is not None:
|
||||
action.setStatusTip(status_tip)
|
||||
|
||||
if whats_this is not None:
|
||||
action.setWhatsThis(whats_this)
|
||||
|
||||
# Standard QGIS API for adding icons and menu items
|
||||
if add_to_toolbar:
|
||||
self.iface.addToolBarIcon(action)
|
||||
|
||||
if add_to_menu:
|
||||
self.iface.addPluginToMenu(self.menu, action)
|
||||
|
||||
# Store only actions that are directly attached
|
||||
# to the QGIS UI for later cleanup
|
||||
if add_to_toolbar or add_to_menu:
|
||||
self.actions.append(action)
|
||||
|
||||
return action
|
||||
|
||||
def initGui(self):
|
||||
"""
|
||||
Called when the plugin is loaded. Creates the menu structure,
|
||||
sub-actions, and the dropdown tool button in the toolbar.
|
||||
"""
|
||||
# Define paths for action-specific icons
|
||||
icon_akce_path = os.path.join(self.plugin_dir, 'akce.png')
|
||||
icon_lokality_path = os.path.join(self.plugin_dir, 'lokality.png')
|
||||
icon_amcr_help_path = os.path.join(self.plugin_dir, 'amcr-help.png')
|
||||
|
||||
# 1. Create a container menu for the plugin
|
||||
self.plugin_menu = QMenu()
|
||||
|
||||
# 2. Create sub-actions (Download Projects / Download Sites)
|
||||
# add_to_menu/toolbar is False because these go into our
|
||||
# custom dropdown menu
|
||||
self.action_download_akce = self.add_action(
|
||||
icon_path=icon_akce_path,
|
||||
text=self.tr(u'Stáhnout data akcí | AMČR Viewer'),
|
||||
callback=lambda checked=False: self.run_download('akce'),
|
||||
parent=self.iface.mainWindow(),
|
||||
add_to_menu=False,
|
||||
add_to_toolbar=False
|
||||
)
|
||||
self.plugin_menu.addAction(self.action_download_akce)
|
||||
|
||||
self.action_download_lokality = self.add_action(
|
||||
icon_path=icon_lokality_path,
|
||||
text=self.tr(u'Stáhnout data lokalit | AMČR Viewer'),
|
||||
callback=lambda checked=False: self.run_download('lokalita'),
|
||||
parent=self.iface.mainWindow(),
|
||||
add_to_menu=False,
|
||||
add_to_toolbar=False
|
||||
)
|
||||
self.plugin_menu.addAction(self.action_download_lokality)
|
||||
|
||||
self.action_login_dialog = self.add_action(
|
||||
icon_path=icon_akce_path,
|
||||
text=self.tr(u'Přihlásit se | AMČR Viewer'),
|
||||
callback=lambda checked=False: self.login(),
|
||||
parent=self.iface.mainWindow(),
|
||||
add_to_menu=False,
|
||||
add_to_toolbar=False
|
||||
)
|
||||
self.plugin_menu.addAction(self.action_login_dialog)
|
||||
|
||||
self.action_amcr_help = self.add_action(
|
||||
icon_path=icon_amcr_help_path,
|
||||
text=self.tr(u'Nápověda AMČR Help | AMČR Viewer'),
|
||||
callback=lambda checked=False: self.open_help(),
|
||||
parent=self.iface.mainWindow(),
|
||||
add_to_menu=False,
|
||||
add_to_toolbar=False
|
||||
)
|
||||
self.plugin_menu.addAction(self.action_amcr_help)
|
||||
|
||||
# 3. Create the main project action and attach the menu to it
|
||||
main_icon = QIcon(icon_akce_path)
|
||||
self.main_action = QAction(
|
||||
main_icon,
|
||||
'AMČR Viewer',
|
||||
self.iface.mainWindow()
|
||||
)
|
||||
self.main_action.setMenu(self.plugin_menu)
|
||||
self.iface.addPluginToMenu(self.menu, self.main_action)
|
||||
|
||||
# 4. Create and configure a QToolButton for the QGIS Toolbar
|
||||
# This button acts as a dropdown menu button (MenuButtonPopup)
|
||||
self.tool_button = QToolButton()
|
||||
self.tool_button.setMenu(self.plugin_menu)
|
||||
self.tool_button.setDefaultAction(self.action_download_akce)
|
||||
self.tool_button.setPopupMode(
|
||||
QToolButton.ToolButtonPopupMode.MenuButtonPopup
|
||||
)
|
||||
|
||||
# Add the widget directly to the toolbar
|
||||
# and store the reference for cleanup
|
||||
self.toolbar_action = self.iface.addToolBarWidget(self.tool_button)
|
||||
|
||||
self.first_start = True
|
||||
|
||||
def unload(self):
|
||||
"""
|
||||
Called when the plugin is disabled or removed.
|
||||
Ensures all GUI elements are removed from QGIS to avoid ghost icons.
|
||||
"""
|
||||
# 1. Remove the custom entry from the main 'Plugins' menu
|
||||
if hasattr(self, 'main_action'):
|
||||
self.iface.removePluginMenu(self.menu, self.main_action)
|
||||
|
||||
# 2. Remove the custom QToolButton from the toolbar
|
||||
if hasattr(self, 'toolbar_action'):
|
||||
self.iface.removeToolBarIcon(self.toolbar_action)
|
||||
|
||||
# 3. Clean up any remaining actions registered in self.actions
|
||||
for action in self.actions:
|
||||
self.iface.removePluginMenu(self.menu, action)
|
||||
self.iface.removeToolBarIcon(action)
|
||||
self.actions.clear()
|
||||
|
||||
# 4. Reset map tools if currently active
|
||||
if hasattr(self, 'tool'):
|
||||
self.iface.mapCanvas().unsetMapTool(self.tool)
|
||||
|
||||
# --- Data downloading ---
|
||||
def run_download(self, typ_dat):
|
||||
"""
|
||||
Triggered by menu/toolbar actions. Opens the filter dialog and
|
||||
hands off the parameters to the data loader.
|
||||
"""
|
||||
# Open the specific filter dialog (Projects vs Sites)
|
||||
dlg = AmcrFilterDialog(typ_dat)
|
||||
result = dlg.exec()
|
||||
|
||||
# If user confirmed the dialog (OK button),
|
||||
# gather filters and load data
|
||||
if result == QDialog.DialogCode.Accepted:
|
||||
filters = dlg.get_filters()
|
||||
bbox = dlg.get_bbox()
|
||||
komponenty = dlg.get_komponenty()
|
||||
|
||||
# Access the map canvas and start
|
||||
# the fetch/render process from amcr_tools
|
||||
canvas = self.iface.mapCanvas()
|
||||
load_amcr_data(canvas, bbox, filters, typ_dat, komponenty)
|
||||
|
||||
def login(self):
|
||||
dlg = LoginDialog(parent=self.iface.mainWindow())
|
||||
result = dlg.exec()
|
||||
if result == QDialog.DialogCode.Accepted:
|
||||
username, password = LoginDialog.get_credentials()
|
||||
session = login_to_api(username, password)
|
||||
if session:
|
||||
self.iface.messageBar().pushMessage(
|
||||
"AMČR",
|
||||
"Přihlášení proběhlo úspěšně.",
|
||||
level=Qgis.MessageLevel.Success
|
||||
)
|
||||
else:
|
||||
self.iface.messageBar().pushMessage(
|
||||
"AMČR",
|
||||
"Přihlášení se nezdařilo – viz záložka AMČR login "
|
||||
"v panelu Zprávy.",
|
||||
level=Qgis.MessageLevel.Critical
|
||||
)
|
||||
|
||||
def open_help(self):
|
||||
help_url = "https://amcr-help.aiscr.cz/digiarchiv/qgis-viewer.html"
|
||||
QDesktopServices.openUrl(QUrl(help_url))
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 877 B |
@@ -0,0 +1,62 @@
|
||||
# This file contains metadata for your plugin.
|
||||
|
||||
# This file should be included when you package your plugin.
|
||||
# Mandatory items:
|
||||
|
||||
[general]
|
||||
name=AMČR Viewer
|
||||
qgisMinimumVersion=3.4.0
|
||||
qgisMaximumVersion=4.99.0
|
||||
description=Viewing and downloading the AMČR data.
|
||||
version=2.0.0
|
||||
author=David Spáčil
|
||||
email=spacil@arub.cz
|
||||
|
||||
about=This plugin is intended for downloading the data (Fieldwork events, Sites, and their Components) from the Digital archive of the Archaeological Map of the Czech Republic (https://digiarchiv.aiscr.cz/).
|
||||
|
||||
tracker=https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer/issues
|
||||
repository=https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer
|
||||
# End of mandatory metadata
|
||||
|
||||
# Recommended items:
|
||||
|
||||
hasProcessingProvider=no
|
||||
# Uncomment the following line and add your changelog:
|
||||
changelog=
|
||||
Aktualizace na verzi 2.0.0 výrazně mění chování pluginu. Před updatem je doporučeno přečíst si seznam změn níže.
|
||||
Version 2.0.0 changes the plugin behavior dramatically. It is advised to check the changelog below.
|
||||
Plný seznam změn v češtině je dostupný zde: https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer/releases/tag/v2.0.0
|
||||
v2.0.0 (2026-06-05)
|
||||
* Added warning regarding the feature duplication when loading components to the dialog
|
||||
* Added Help button to the plugin menu
|
||||
* Code clean-up
|
||||
v2.0.0-alpha.4 (2026-06-03)
|
||||
* Backend filtering of the results based on the component-related filters improvement (plugin not only loads the results from API, it filters them further)
|
||||
v2.0.0-alpha.2–3 (2026-05-19)
|
||||
* Security vulnerabilities fix
|
||||
v2.0.0-alpha.1 (2026-05-19):
|
||||
* Attribute fields renamed to be ASCII compliant
|
||||
* Codelist update; codelist can be recompiled from AMČR API
|
||||
* Base element changed from Documentation Unit to Component if user asks for components to simplify result filtering
|
||||
* Plugin now supports logging with an AMČR account and enables the downloading of Events and Sites available to the roles Researcher and higher
|
||||
|
||||
# Tags are comma separated with spaces allowed
|
||||
tags=python,AMCR,AIS CR,archaeology,PIAN,AMČR,archeologie
|
||||
|
||||
homepage=https://amcr-help.aiscr.cz/digiarchiv/qgis-viewer.html
|
||||
category=Vector
|
||||
icon=download.png
|
||||
# experimental flag
|
||||
experimental=False
|
||||
|
||||
# deprecated flag (applies to the whole plugin, not just a single version)
|
||||
deprecated=False
|
||||
|
||||
# Since QGIS 3.8, a comma separated list of plugins to be installed
|
||||
# (or upgraded) can be specified.
|
||||
# Check the documentation for more information.
|
||||
# plugin_dependencies=
|
||||
|
||||
# If the plugin can run on QGIS Server.
|
||||
server=False
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
#
|
||||
# WARNING! All changes made in this file will be lost!
|
||||
|
||||
from PyQt5 import QtCore
|
||||
from qgis.PyQt import QtCore
|
||||
|
||||
qt_resource_data = b"\
|
||||
\x00\x00\x04\x0a\
|
||||
@@ -1,44 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
/***************************************************************************
|
||||
AmcrViewerDialog
|
||||
A QGIS plugin
|
||||
Viewing and downloading the AMČR data.
|
||||
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
|
||||
-------------------
|
||||
begin : 2026-02-03
|
||||
git sha : $Format:%H$
|
||||
copyright : (C) 2026 by David Spáčil
|
||||
email : spacil@arub.cz
|
||||
***************************************************************************/
|
||||
|
||||
/***************************************************************************
|
||||
* *
|
||||
* This program is free software; you can redistribute it and/or modify *
|
||||
* it under the terms of the GNU General Public License as published by *
|
||||
* the Free Software Foundation; either version 2 of the License, or *
|
||||
* (at your option) any later version. *
|
||||
* *
|
||||
***************************************************************************/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from qgis.PyQt import uic
|
||||
from qgis.PyQt import QtWidgets
|
||||
|
||||
# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
|
||||
FORM_CLASS, _ = uic.loadUiType(os.path.join(
|
||||
os.path.dirname(__file__), 'amcr_viewer_dialog_base.ui'))
|
||||
|
||||
|
||||
class AmcrViewerDialog(QtWidgets.QDialog, FORM_CLASS):
|
||||
def __init__(self, parent=None):
|
||||
"""Constructor."""
|
||||
super(AmcrViewerDialog, self).__init__(parent)
|
||||
# Set up the user interface from Designer through FORM_CLASS.
|
||||
# After self.setupUi() you can access any designer object by doing
|
||||
# self.<objectname>, and you can use autoconnect slots - see
|
||||
# http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
|
||||
# #widgets-and-dialogs-with-auto-connect
|
||||
self.setupUi(self)
|
||||
@@ -1,67 +0,0 @@
|
||||
<ui version="4.0" >
|
||||
<class>AmcrViewerDialogBase</class>
|
||||
<widget class="QDialog" name="AmcrViewerDialogBase" >
|
||||
<property name="geometry" >
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>400</width>
|
||||
<height>300</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle" >
|
||||
<string>AMČR Viewer</string>
|
||||
</property>
|
||||
<widget class="QDialogButtonBox" name="button_box" >
|
||||
<property name="geometry" >
|
||||
<rect>
|
||||
<x>30</x>
|
||||
<y>240</y>
|
||||
<width>341</width>
|
||||
<height>32</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="orientation" >
|
||||
<enum>Qt::Horizontal</enum>
|
||||
</property>
|
||||
<property name="standardButtons" >
|
||||
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
|
||||
</property>
|
||||
</widget>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections>
|
||||
<connection>
|
||||
<sender>button_box</sender>
|
||||
<signal>accepted()</signal>
|
||||
<receiver>AmcrViewerDialogBase</receiver>
|
||||
<slot>accept()</slot>
|
||||
<hints>
|
||||
<hint type="source_label" >
|
||||
<x>248</x>
|
||||
<y>254</y>
|
||||
</hint>
|
||||
<hint type="destination_label" >
|
||||
<x>157</x>
|
||||
<y>274</y>
|
||||
</hint>
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>button_box</sender>
|
||||
<signal>rejected()</signal>
|
||||
<receiver>AmcrViewerDialogBase</receiver>
|
||||
<slot>reject()</slot>
|
||||
<hints>
|
||||
<hint type="source_label" >
|
||||
<x>316</x>
|
||||
<y>260</y>
|
||||
</hint>
|
||||
<hint type="destination_label" >
|
||||
<x>286</x>
|
||||
<y>274</y>
|
||||
</hint>
|
||||
</hints>
|
||||
</connection>
|
||||
</connections>
|
||||
</ui>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 993 B |
@@ -1,47 +0,0 @@
|
||||
# This file contains metadata for your plugin.
|
||||
|
||||
# This file should be included when you package your plugin.# Mandatory items:
|
||||
|
||||
[general]
|
||||
name=AMČR Viewer
|
||||
qgisMinimumVersion=3.4
|
||||
description=Viewing and downloading the AMČR data.
|
||||
version=1
|
||||
author=David Spáčil
|
||||
email=spacil@arub.cz
|
||||
|
||||
about=This plugin is intended for downloading the data (Fieldwork events data only, at the time) from the Digiarchive of the Archaeological Map of the Czech Republic (AMCR). As of now, only publicly accessible data can be downloaded.
|
||||
|
||||
tracker=https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer/issues
|
||||
repository=https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer
|
||||
# End of mandatory metadata
|
||||
|
||||
# Recommended items:
|
||||
|
||||
hasProcessingProvider=no
|
||||
# Uncomment the following line and add your changelog:
|
||||
# changelog=
|
||||
|
||||
# Tags are comma separated with spaces allowed
|
||||
tags=python,AMCR,AIS CR,archaeology,PIAN,AMČR
|
||||
|
||||
homepage=https://github.com/ARUP-CAS/aiscr-qgis-amcr-viewer
|
||||
category=Vector
|
||||
icon=download.png
|
||||
# experimental flag
|
||||
experimental=True
|
||||
|
||||
# deprecated flag (applies to the whole plugin, not just a single version)
|
||||
deprecated=False
|
||||
|
||||
# Since QGIS 3.8, a comma separated list of plugins to be installed
|
||||
# (or upgraded) can be specified.
|
||||
# Check the documentation for more information.
|
||||
# plugin_dependencies=
|
||||
|
||||
# Category of the plugin: Raster, Vector, Database or Web
|
||||
# category=
|
||||
|
||||
# If the plugin can run on QGIS Server.
|
||||
server=False
|
||||
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
#/***************************************************************************
|
||||
# AmcrViewer
|
||||
#
|
||||
# Configuration file for plugin builder tool (pb_tool)
|
||||
# Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
|
||||
# -------------------
|
||||
# begin : 2026-02-03
|
||||
# copyright : (C) 2026 by David Spáčil
|
||||
# email : spacil@arub.cz
|
||||
# ***************************************************************************/
|
||||
#
|
||||
#/***************************************************************************
|
||||
# * *
|
||||
# * This program is free software; you can redistribute it and/or modify *
|
||||
# * it under the terms of the GNU General Public License as published by *
|
||||
# * the Free Software Foundation; either version 2 of the License, or *
|
||||
# * (at your option) any later version. *
|
||||
# * *
|
||||
# ***************************************************************************/
|
||||
#
|
||||
#
|
||||
# You can install pb_tool using:
|
||||
# pip install http://geoapt.net/files/pb_tool.zip
|
||||
#
|
||||
# Consider doing your development (and install of pb_tool) in a virtualenv.
|
||||
#
|
||||
# For details on setting up and using pb_tool, see:
|
||||
# http://g-sherman.github.io/plugin_build_tool/
|
||||
#
|
||||
# Issues and pull requests here:
|
||||
# https://github.com/g-sherman/plugin_build_tool:
|
||||
#
|
||||
# Sane defaults for your plugin generated by the Plugin Builder are
|
||||
# already set below.
|
||||
#
|
||||
# As you add Python source files and UI files to your plugin, add
|
||||
# them to the appropriate [files] section below.
|
||||
|
||||
[plugin]
|
||||
# Name of the plugin. This is the name of the directory that will
|
||||
# be created in .qgis2/python/plugins
|
||||
name: amcr_viewer
|
||||
|
||||
# Full path to where you want your plugin directory copied. If empty,
|
||||
# the QGIS default path will be used. Don't include the plugin name in
|
||||
# the path.
|
||||
plugin_path:
|
||||
|
||||
[files]
|
||||
# Python files that should be deployed with the plugin
|
||||
python_files: __init__.py amcr_viewer.py amcr_viewer_dialog.py
|
||||
|
||||
# The main dialog file that is loaded (not compiled)
|
||||
main_dialog: amcr_viewer_dialog_base.ui
|
||||
|
||||
# Other ui files for dialogs you create (these will be compiled)
|
||||
compiled_ui_files:
|
||||
|
||||
# Resource file(s) that will be compiled
|
||||
resource_files: resources.qrc
|
||||
|
||||
# Other files required for the plugin
|
||||
extras: metadata.txt icon.png
|
||||
|
||||
# Other directories to be deployed with the plugin.
|
||||
# These must be subdirectories under the plugin directory
|
||||
extra_dirs:
|
||||
|
||||
# ISO code(s) for any locales (translations), separated by spaces.
|
||||
# Corresponding .ts files must exist in the i18n directory
|
||||
locales:
|
||||
|
||||
[help]
|
||||
# the built help directory that should be deployed with the plugin
|
||||
dir: help/build/html
|
||||
# the name of the directory to target in the deployed plugin
|
||||
target: help
|
||||
|
||||
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
"""This script uploads a plugin package to the plugin repository.
|
||||
Authors: A. Pasotti, V. Picavet
|
||||
git sha : $TemplateVCSFormat
|
||||
"""
|
||||
|
||||
import sys
|
||||
import getpass
|
||||
import xmlrpc.client
|
||||
from optparse import OptionParser
|
||||
|
||||
standard_library.install_aliases()
|
||||
|
||||
# Configuration
|
||||
PROTOCOL = 'https'
|
||||
SERVER = 'plugins.qgis.org'
|
||||
PORT = '443'
|
||||
ENDPOINT = '/plugins/RPC2/'
|
||||
VERBOSE = False
|
||||
|
||||
|
||||
def main(parameters, arguments):
|
||||
"""Main entry point.
|
||||
|
||||
:param parameters: Command line parameters.
|
||||
:param arguments: Command line arguments.
|
||||
"""
|
||||
address = "{protocol}://{username}:{password}@{server}:{port}{endpoint}".format(
|
||||
protocol=PROTOCOL,
|
||||
username=parameters.username,
|
||||
password=parameters.password,
|
||||
server=parameters.server,
|
||||
port=parameters.port,
|
||||
endpoint=ENDPOINT)
|
||||
print("Connecting to: %s" % hide_password(address))
|
||||
|
||||
server = xmlrpc.client.ServerProxy(address, verbose=VERBOSE)
|
||||
|
||||
try:
|
||||
with open(arguments[0], 'rb') as handle:
|
||||
plugin_id, version_id = server.plugin.upload(
|
||||
xmlrpc.client.Binary(handle.read()))
|
||||
print("Plugin ID: %s" % plugin_id)
|
||||
print("Version ID: %s" % version_id)
|
||||
except xmlrpc.client.ProtocolError as err:
|
||||
print("A protocol error occurred")
|
||||
print("URL: %s" % hide_password(err.url, 0))
|
||||
print("HTTP/HTTPS headers: %s" % err.headers)
|
||||
print("Error code: %d" % err.errcode)
|
||||
print("Error message: %s" % err.errmsg)
|
||||
except xmlrpc.client.Fault as err:
|
||||
print("A fault occurred")
|
||||
print("Fault code: %d" % err.faultCode)
|
||||
print("Fault string: %s" % err.faultString)
|
||||
|
||||
|
||||
def hide_password(url, start=6):
|
||||
"""Returns the http url with password part replaced with '*'.
|
||||
|
||||
:param url: URL to upload the plugin to.
|
||||
:type url: str
|
||||
|
||||
:param start: Position of start of password.
|
||||
:type start: int
|
||||
"""
|
||||
start_position = url.find(':', start) + 1
|
||||
end_position = url.find('@')
|
||||
return "%s%s%s" % (
|
||||
url[:start_position],
|
||||
'*' * (end_position - start_position),
|
||||
url[end_position:])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = OptionParser(usage="%prog [options] plugin.zip")
|
||||
parser.add_option(
|
||||
"-w", "--password", dest="password",
|
||||
help="Password for plugin site", metavar="******")
|
||||
parser.add_option(
|
||||
"-u", "--username", dest="username",
|
||||
help="Username of plugin site", metavar="user")
|
||||
parser.add_option(
|
||||
"-p", "--port", dest="port",
|
||||
help="Server port to connect to", metavar="80")
|
||||
parser.add_option(
|
||||
"-s", "--server", dest="server",
|
||||
help="Specify server name", metavar="plugins.qgis.org")
|
||||
options, args = parser.parse_args()
|
||||
if len(args) != 1:
|
||||
print("Please specify zip file.\n")
|
||||
parser.print_help()
|
||||
sys.exit(1)
|
||||
if not options.server:
|
||||
options.server = SERVER
|
||||
if not options.port:
|
||||
options.port = PORT
|
||||
if not options.username:
|
||||
# interactive mode
|
||||
username = getpass.getuser()
|
||||
print("Please enter user name [%s] :" % username, end=' ')
|
||||
|
||||
res = input()
|
||||
if res != "":
|
||||
options.username = res
|
||||
else:
|
||||
options.username = username
|
||||
if not options.password:
|
||||
# interactive mode
|
||||
options.password = getpass.getpass()
|
||||
main(options, args)
|
||||
@@ -1,281 +0,0 @@
|
||||
[MASTER]
|
||||
|
||||
# Specify a configuration file.
|
||||
#rcfile=
|
||||
|
||||
# Python code to execute, usually for sys.path manipulation such as
|
||||
# pygtk.require().
|
||||
#init-hook=
|
||||
|
||||
# Profiled execution.
|
||||
profile=no
|
||||
|
||||
# Add files or directories to the blacklist. They should be base names, not
|
||||
# paths.
|
||||
ignore=CVS
|
||||
|
||||
# Pickle collected data for later comparisons.
|
||||
persistent=yes
|
||||
|
||||
# List of plugins (as comma separated values of python modules names) to load,
|
||||
# usually to register additional checkers.
|
||||
load-plugins=
|
||||
|
||||
|
||||
[MESSAGES CONTROL]
|
||||
|
||||
# Enable the message, report, category or checker with the given id(s). You can
|
||||
# either give multiple identifier separated by comma (,) or put this option
|
||||
# multiple time. See also the "--disable" option for examples.
|
||||
#enable=
|
||||
|
||||
# Disable the message, report, category or checker with the given id(s). You
|
||||
# can either give multiple identifiers separated by comma (,) or put this
|
||||
# option multiple times (only on the command line, not in the configuration
|
||||
# file where it should appear only once).You can also use "--disable=all" to
|
||||
# disable everything first and then reenable specific checks. For example, if
|
||||
# you want to run only the similarities checker, you can use "--disable=all
|
||||
# --enable=similarities". If you want to run only the classes checker, but have
|
||||
# no Warning level messages displayed, use"--disable=all --enable=classes
|
||||
# --disable=W"
|
||||
# see http://stackoverflow.com/questions/21487025/pylint-locally-defined-disables-still-give-warnings-how-to-suppress-them
|
||||
disable=locally-disabled,C0103
|
||||
|
||||
|
||||
[REPORTS]
|
||||
|
||||
# Set the output format. Available formats are text, parseable, colorized, msvs
|
||||
# (visual studio) and html. You can also give a reporter class, eg
|
||||
# mypackage.mymodule.MyReporterClass.
|
||||
output-format=text
|
||||
|
||||
# Put messages in a separate file for each module / package specified on the
|
||||
# command line instead of printing them on stdout. Reports (if any) will be
|
||||
# written in a file name "pylint_global.[txt|html]".
|
||||
files-output=no
|
||||
|
||||
# Tells whether to display a full report or only the messages
|
||||
reports=yes
|
||||
|
||||
# Python expression which should return a note less than 10 (10 is the highest
|
||||
# note). You have access to the variables errors warning, statement which
|
||||
# respectively contain the number of errors / warnings messages and the total
|
||||
# number of statements analyzed. This is used by the global evaluation report
|
||||
# (RP0004).
|
||||
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
|
||||
|
||||
# Add a comment according to your evaluation note. This is used by the global
|
||||
# evaluation report (RP0004).
|
||||
comment=no
|
||||
|
||||
# Template used to display messages. This is a python new-style format string
|
||||
# used to format the message information. See doc for all details
|
||||
#msg-template=
|
||||
|
||||
|
||||
[BASIC]
|
||||
|
||||
# Required attributes for module, separated by a comma
|
||||
required-attributes=
|
||||
|
||||
# List of builtins function names that should not be used, separated by a comma
|
||||
bad-functions=map,filter,apply,input
|
||||
|
||||
# Regular expression which should only match correct module names
|
||||
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
|
||||
|
||||
# Regular expression which should only match correct module level names
|
||||
const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
|
||||
|
||||
# Regular expression which should only match correct class names
|
||||
class-rgx=[A-Z_][a-zA-Z0-9]+$
|
||||
|
||||
# Regular expression which should only match correct function names
|
||||
function-rgx=[a-z_][a-z0-9_]{2,30}$
|
||||
|
||||
# Regular expression which should only match correct method names
|
||||
method-rgx=[a-z_][a-z0-9_]{2,30}$
|
||||
|
||||
# Regular expression which should only match correct instance attribute names
|
||||
attr-rgx=[a-z_][a-z0-9_]{2,30}$
|
||||
|
||||
# Regular expression which should only match correct argument names
|
||||
argument-rgx=[a-z_][a-z0-9_]{2,30}$
|
||||
|
||||
# Regular expression which should only match correct variable names
|
||||
variable-rgx=[a-z_][a-z0-9_]{2,30}$
|
||||
|
||||
# Regular expression which should only match correct attribute names in class
|
||||
# bodies
|
||||
class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
|
||||
|
||||
# Regular expression which should only match correct list comprehension /
|
||||
# generator expression variable names
|
||||
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
|
||||
|
||||
# Good variable names which should always be accepted, separated by a comma
|
||||
good-names=i,j,k,ex,Run,_
|
||||
|
||||
# Bad variable names which should always be refused, separated by a comma
|
||||
bad-names=foo,bar,baz,toto,tutu,tata
|
||||
|
||||
# Regular expression which should only match function or class names that do
|
||||
# not require a docstring.
|
||||
no-docstring-rgx=__.*__
|
||||
|
||||
# Minimum line length for functions/classes that require docstrings, shorter
|
||||
# ones are exempt.
|
||||
docstring-min-length=-1
|
||||
|
||||
|
||||
[MISCELLANEOUS]
|
||||
|
||||
# List of note tags to take in consideration, separated by a comma.
|
||||
notes=FIXME,XXX,TODO
|
||||
|
||||
|
||||
[TYPECHECK]
|
||||
|
||||
# Tells whether missing members accessed in mixin class should be ignored. A
|
||||
# mixin class is detected if its name ends with "mixin" (case insensitive).
|
||||
ignore-mixin-members=yes
|
||||
|
||||
# List of classes names for which member attributes should not be checked
|
||||
# (useful for classes with attributes dynamically set).
|
||||
ignored-classes=SQLObject
|
||||
|
||||
# When zope mode is activated, add a predefined set of Zope acquired attributes
|
||||
# to generated-members.
|
||||
zope=no
|
||||
|
||||
# List of members which are set dynamically and missed by pylint inference
|
||||
# system, and so shouldn't trigger E0201 when accessed. Python regular
|
||||
# expressions are accepted.
|
||||
generated-members=REQUEST,acl_users,aq_parent
|
||||
|
||||
|
||||
[VARIABLES]
|
||||
|
||||
# Tells whether we should check for unused import in __init__ files.
|
||||
init-import=no
|
||||
|
||||
# A regular expression matching the beginning of the name of dummy variables
|
||||
# (i.e. not used).
|
||||
dummy-variables-rgx=_$|dummy
|
||||
|
||||
# List of additional names supposed to be defined in builtins. Remember that
|
||||
# you should avoid to define new builtins when possible.
|
||||
additional-builtins=
|
||||
|
||||
|
||||
[FORMAT]
|
||||
|
||||
# Maximum number of characters on a single line.
|
||||
max-line-length=80
|
||||
|
||||
# Regexp for a line that is allowed to be longer than the limit.
|
||||
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
|
||||
|
||||
# Allow the body of an if to be on the same line as the test if there is no
|
||||
# else.
|
||||
single-line-if-stmt=no
|
||||
|
||||
# List of optional constructs for which whitespace checking is disabled
|
||||
no-space-check=trailing-comma,dict-separator
|
||||
|
||||
# Maximum number of lines in a module
|
||||
max-module-lines=1000
|
||||
|
||||
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
|
||||
# tab).
|
||||
indent-string=' '
|
||||
|
||||
|
||||
[SIMILARITIES]
|
||||
|
||||
# Minimum lines number of a similarity.
|
||||
min-similarity-lines=4
|
||||
|
||||
# Ignore comments when computing similarities.
|
||||
ignore-comments=yes
|
||||
|
||||
# Ignore docstrings when computing similarities.
|
||||
ignore-docstrings=yes
|
||||
|
||||
# Ignore imports when computing similarities.
|
||||
ignore-imports=no
|
||||
|
||||
|
||||
[IMPORTS]
|
||||
|
||||
# Deprecated modules which should not be used, separated by a comma
|
||||
deprecated-modules=regsub,TERMIOS,Bastion,rexec
|
||||
|
||||
# Create a graph of every (i.e. internal and external) dependencies in the
|
||||
# given file (report RP0402 must not be disabled)
|
||||
import-graph=
|
||||
|
||||
# Create a graph of external dependencies in the given file (report RP0402 must
|
||||
# not be disabled)
|
||||
ext-import-graph=
|
||||
|
||||
# Create a graph of internal dependencies in the given file (report RP0402 must
|
||||
# not be disabled)
|
||||
int-import-graph=
|
||||
|
||||
|
||||
[DESIGN]
|
||||
|
||||
# Maximum number of arguments for function / method
|
||||
max-args=5
|
||||
|
||||
# Argument names that match this expression will be ignored. Default to name
|
||||
# with leading underscore
|
||||
ignored-argument-names=_.*
|
||||
|
||||
# Maximum number of locals for function / method body
|
||||
max-locals=15
|
||||
|
||||
# Maximum number of return / yield for function / method body
|
||||
max-returns=6
|
||||
|
||||
# Maximum number of branch for function / method body
|
||||
max-branches=12
|
||||
|
||||
# Maximum number of statements in function / method body
|
||||
max-statements=50
|
||||
|
||||
# Maximum number of parents for a class (see R0901).
|
||||
max-parents=7
|
||||
|
||||
# Maximum number of attributes for a class (see R0902).
|
||||
max-attributes=7
|
||||
|
||||
# Minimum number of public methods for a class (see R0903).
|
||||
min-public-methods=2
|
||||
|
||||
# Maximum number of public methods for a class (see R0904).
|
||||
max-public-methods=20
|
||||
|
||||
|
||||
[CLASSES]
|
||||
|
||||
# List of interface methods to ignore, separated by a comma. This is used for
|
||||
# instance to not check methods defines in Zope's Interface base class.
|
||||
ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by
|
||||
|
||||
# List of method names used to declare (i.e. assign) instance attributes.
|
||||
defining-attr-methods=__init__,__new__,setUp
|
||||
|
||||
# List of valid names for the first argument in a class method.
|
||||
valid-classmethod-first-arg=cls
|
||||
|
||||
# List of valid names for the first argument in a metaclass class method.
|
||||
valid-metaclass-classmethod-first-arg=mcs
|
||||
|
||||
|
||||
[EXCEPTIONS]
|
||||
|
||||
# Exceptions that will emit a warning when being caught. Defaults to
|
||||
# "Exception"
|
||||
overgeneral-exceptions=Exception
|
||||
@@ -1,5 +0,0 @@
|
||||
<RCC>
|
||||
<qresource prefix="/plugins/amcr_viewer" >
|
||||
<file>icon.png</file>
|
||||
</qresource>
|
||||
</RCC>
|
||||
@@ -1,12 +0,0 @@
|
||||
#!/bin/bash
|
||||
LRELEASE=$1
|
||||
LOCALES=$2
|
||||
|
||||
|
||||
for LOCALE in ${LOCALES}
|
||||
do
|
||||
echo "Processing: ${LOCALE}.ts"
|
||||
# Note we don't use pylupdate with qt .pro file approach as it is flakey
|
||||
# about what is made available.
|
||||
$LRELEASE i18n/${LOCALE}.ts
|
||||
done
|
||||
@@ -1,28 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
QGIS_PREFIX_PATH=/usr/local/qgis-2.0
|
||||
if [ -n "$1" ]; then
|
||||
QGIS_PREFIX_PATH=$1
|
||||
fi
|
||||
|
||||
echo ${QGIS_PREFIX_PATH}
|
||||
|
||||
|
||||
export QGIS_PREFIX_PATH=${QGIS_PREFIX_PATH}
|
||||
export QGIS_PATH=${QGIS_PREFIX_PATH}
|
||||
export LD_LIBRARY_PATH=${QGIS_PREFIX_PATH}/lib
|
||||
export PYTHONPATH=${QGIS_PREFIX_PATH}/share/qgis/python:${QGIS_PREFIX_PATH}/share/qgis/python/plugins:${PYTHONPATH}
|
||||
|
||||
echo "QGIS PATH: $QGIS_PREFIX_PATH"
|
||||
export QGIS_DEBUG=0
|
||||
export QGIS_LOG_FILE=/tmp/inasafe/realtime/logs/qgis.log
|
||||
|
||||
export PATH=${QGIS_PREFIX_PATH}/bin:$PATH
|
||||
|
||||
echo "This script is intended to be sourced to set up your shell to"
|
||||
echo "use a QGIS 2.0 built in $QGIS_PREFIX_PATH"
|
||||
echo
|
||||
echo "To use it do:"
|
||||
echo "source $BASH_SOURCE /your/optional/install/path"
|
||||
echo
|
||||
echo "Then use the make file supplied here e.g. make guitest"
|
||||
@@ -1,56 +0,0 @@
|
||||
#!/bin/bash
|
||||
LOCALES=$*
|
||||
|
||||
# Get newest .py files so we don't update strings unnecessarily
|
||||
|
||||
CHANGED_FILES=0
|
||||
PYTHON_FILES=`find . -regex ".*\(ui\|py\)$" -type f`
|
||||
for PYTHON_FILE in $PYTHON_FILES
|
||||
do
|
||||
CHANGED=$(stat -c %Y $PYTHON_FILE)
|
||||
if [ ${CHANGED} -gt ${CHANGED_FILES} ]
|
||||
then
|
||||
CHANGED_FILES=${CHANGED}
|
||||
fi
|
||||
done
|
||||
|
||||
# Qt translation stuff
|
||||
# for .ts file
|
||||
UPDATE=false
|
||||
for LOCALE in ${LOCALES}
|
||||
do
|
||||
TRANSLATION_FILE="i18n/$LOCALE.ts"
|
||||
if [ ! -f ${TRANSLATION_FILE} ]
|
||||
then
|
||||
# Force translation string collection as we have a new language file
|
||||
touch ${TRANSLATION_FILE}
|
||||
UPDATE=true
|
||||
break
|
||||
fi
|
||||
|
||||
MODIFICATION_TIME=$(stat -c %Y ${TRANSLATION_FILE})
|
||||
if [ ${CHANGED_FILES} -gt ${MODIFICATION_TIME} ]
|
||||
then
|
||||
# Force translation string collection as a .py file has been updated
|
||||
UPDATE=true
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ ${UPDATE} == true ]
|
||||
# retrieve all python files
|
||||
then
|
||||
echo ${PYTHON_FILES}
|
||||
# update .ts
|
||||
echo "Please provide translations by editing the translation files below:"
|
||||
for LOCALE in ${LOCALES}
|
||||
do
|
||||
echo "i18n/"${LOCALE}".ts"
|
||||
# Note we don't use pylupdate with qt .pro file approach as it is flakey
|
||||
# about what is made available.
|
||||
pylupdate4 -noobsolete ${PYTHON_FILES} -ts i18n/${LOCALE}.ts
|
||||
done
|
||||
else
|
||||
echo "No need to edit any translation files (.ts) because no python files"
|
||||
echo "has been updated since the last update translation. "
|
||||
fi
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 6.3499998 6.35"
|
||||
version="1.1"
|
||||
id="svg1"
|
||||
xml:space="preserve"
|
||||
sodipodi:docname="icon.svg"
|
||||
inkscape:version="1.4.3 (0d15f75, 2025-12-25)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"><sodipodi:namedview
|
||||
id="namedview1"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#000000"
|
||||
borderopacity="0.25"
|
||||
inkscape:showpageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#d1d1d1"
|
||||
inkscape:document-units="mm"
|
||||
inkscape:zoom="22.627417"
|
||||
inkscape:cx="6.8059028"
|
||||
inkscape:cy="14.606174"
|
||||
inkscape:window-width="1920"
|
||||
inkscape:window-height="1009"
|
||||
inkscape:window-x="1912"
|
||||
inkscape:window-y="-8"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="layer1" /><defs
|
||||
id="defs1"><clipPath
|
||||
id="clip-0"><path
|
||||
clip-rule="nonzero"
|
||||
d="M 56 202 L 64 202 L 64 212.582031 L 56 212.582031 Z M 56 202 "
|
||||
id="path1" /></clipPath><clipPath
|
||||
id="clip-1"><path
|
||||
clip-rule="nonzero"
|
||||
d="M 111 202 L 120 202 L 120 212.582031 L 111 212.582031 Z M 111 202 "
|
||||
id="path2" /></clipPath><clipPath
|
||||
id="clip-2"><path
|
||||
clip-rule="nonzero"
|
||||
d="M 183 202 L 191 202 L 191 212.582031 L 183 212.582031 Z M 183 202 "
|
||||
id="path3" /></clipPath><clipPath
|
||||
id="clip-3"><path
|
||||
clip-rule="nonzero"
|
||||
d="M 220 202 L 227.445312 202 L 227.445312 212.582031 L 220 212.582031 Z M 220 202 "
|
||||
id="path4" /></clipPath></defs><g
|
||||
inkscape:label="Layer 1"
|
||||
inkscape:groupmode="layer"
|
||||
id="layer1"><path
|
||||
id="path39"
|
||||
style="display:inline"
|
||||
d="M 81.817206 0.011405799 C 62.571113 1.6910933 45.354524 13.210298 36.479524 30.538423 C 32.381867 38.534516 30.312854 47.189295 30.312854 56.243982 C 30.312854 69.122889 34.534136 81.246352 42.526324 91.312758 L 43.405375 92.378274 C 46.932719 96.698587 50.2156 100.55118 53.367944 104.05899 C 53.414814 104.10979 53.454254 104.16803 53.501133 104.21881 L 66.540378 73.385461 C 62.46616 68.596398 60.240518 62.587732 60.240518 56.243982 C 60.240518 52.493982 61.017351 48.846969 62.544695 45.429001 C 66.806414 35.882126 76.317127 29.725967 86.758533 29.725967 C 89.688221 29.725967 92.538869 30.194768 95.269338 31.124456 L 99.957606 21.201844 L 84.214615 14.209399 L 81.817206 0.011405799 z M 90.381286 0.35769831 L 92.152705 10.813068 L 110.39966 18.924304 L 103.31398 34.107899 C 107.88529 36.880579 111.46702 40.963271 113.6628 45.722017 C 116.28908 45.714971 119.29963 45.708698 122.71968 45.708698 C 133.11322 45.708698 139.70768 45.745211 143.25749 45.81525 C 143.26209 45.815341 143.27953 45.815159 143.28413 45.81525 L 144.8824 45.349087 C 144.8707 45.298307 144.85424 45.240042 144.84244 45.18926 C 139.4715 19.302542 117.04145 0.71707431 90.381286 0.35769831 z M 70.962267 79.791873 L 57.590049 110.8916 C 62.425987 115.99706 66.178471 119.43931 69.510502 122.50572 C 75.319096 127.84947 80.037477 132.17422 86.771852 142.01797 C 92.93488 133.01459 97.405493 128.62293 102.56812 123.85094 C 91.347418 109.36236 78.096901 91.972441 77.661695 90.939828 C 76.892417 89.114561 76.908479 86.67687 77.701652 84.946304 C 77.897699 84.518565 78.148245 84.087284 78.434194 83.681004 C 75.760133 82.798967 73.242325 81.491624 70.962267 79.791873 z "
|
||||
transform="matrix(0.0387992,0,0,0.0387992,-0.55393024,0.41865333)" /><path
|
||||
id="rect30"
|
||||
style="display:none;opacity:1;fill:#00b200;stroke:#ffffff;stroke-width:0.615;stroke-linecap:butt;stroke-linejoin:round;stroke-dasharray:none;paint-order:stroke fill markers"
|
||||
d="m 3.3486328,2.4970052 v 1.335319 H 2.7424683 L 4.2085286,5.738151 5.674589,3.8323242 H 5.0684245 v -1.335319 z" /><rect
|
||||
style="opacity:1;fill:#247e4b;fill-opacity:1;stroke:none;stroke-width:0.414999;stroke-linecap:butt;stroke-linejoin:round;stroke-dasharray:none;paint-order:stroke fill markers"
|
||||
id="rect31"
|
||||
width="1.672105"
|
||||
height="1.2511554"
|
||||
x="-4.501821"
|
||||
y="0.84189904" /><text
|
||||
xml:space="preserve"
|
||||
style="font-size:0.705556px;font-family:'Open Sans';-inkscape-font-specification:'Open Sans';text-align:start;writing-mode:lr-tb;direction:ltr;text-anchor:start;opacity:1;fill:#247e4b;fill-opacity:1;stroke:none;stroke-width:0.414999;stroke-linecap:butt;stroke-linejoin:round;stroke-dasharray:none;paint-order:stroke fill markers"
|
||||
x="-2.6080971"
|
||||
y="1.7071842"
|
||||
id="text31"><tspan
|
||||
sodipodi:role="line"
|
||||
id="tspan31"
|
||||
style="font-size:0.705556px;stroke-width:0.415"
|
||||
x="-1.8942729"
|
||||
y="1.7071842">akce</tspan></text><rect
|
||||
style="opacity:1;fill:#951e7a;fill-opacity:1;stroke:none;stroke-width:0.414999;stroke-linecap:butt;stroke-linejoin:round;stroke-dasharray:none;paint-order:stroke fill markers"
|
||||
id="rect32"
|
||||
width="1.672105"
|
||||
height="1.2511554"
|
||||
x="-4.501821"
|
||||
y="2.6939824" /><text
|
||||
xml:space="preserve"
|
||||
style="font-size:0.705556px;font-family:'Open Sans';-inkscape-font-specification:'Open Sans';text-align:start;writing-mode:lr-tb;direction:ltr;text-anchor:start;opacity:1;fill:#951e7a;fill-opacity:1;stroke:none;stroke-width:0.414999;stroke-linecap:butt;stroke-linejoin:round;stroke-dasharray:none;paint-order:stroke fill markers"
|
||||
x="-2.6360023"
|
||||
y="3.5261946"
|
||||
id="text32"><tspan
|
||||
sodipodi:role="line"
|
||||
id="tspan32"
|
||||
style="font-size:0.705556px;fill:#951e7a;fill-opacity:1;stroke-width:0.415"
|
||||
x="-2.6360023"
|
||||
y="3.5261946">lokality</tspan></text><path
|
||||
id="path32"
|
||||
style="opacity:1;fill:#00b200;stroke-width:0.615;paint-order:stroke fill markers;stroke:none;stroke-linecap:butt;stroke-linejoin:round;stroke-dasharray:none"
|
||||
d="M 3.3486328 2.4970052 L 3.3486328 3.8323242 L 2.7424683 3.8323242 L 4.2085286 5.738151 L 5.674589 3.8323242 L 5.0684245 3.8323242 L 5.0684245 2.4970052 L 3.3486328 2.4970052 z "
|
||||
inkscape:export-filename="path32.png"
|
||||
inkscape:export-xdpi="3000"
|
||||
inkscape:export-ydpi="3000" /></g></svg>
|
||||
|
After Width: | Height: | Size: 6.3 KiB |
@@ -1,2 +0,0 @@
|
||||
# import qgis libs so that ve set the correct sip api version
|
||||
import qgis # pylint: disable=W0611 # NOQA
|
||||
@@ -1,205 +0,0 @@
|
||||
# coding=utf-8
|
||||
"""QGIS plugin implementation.
|
||||
|
||||
.. note:: This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
.. note:: This source code was copied from the 'postgis viewer' application
|
||||
with original authors:
|
||||
Copyright (c) 2010 by Ivan Mincik, ivan.mincik@gista.sk
|
||||
Copyright (c) 2011 German Carrillo, geotux_tuxman@linuxmail.org
|
||||
Copyright (c) 2014 Tim Sutton, tim@linfiniti.com
|
||||
|
||||
"""
|
||||
|
||||
__author__ = 'tim@linfiniti.com'
|
||||
__revision__ = '$Format:%H$'
|
||||
__date__ = '10/01/2011'
|
||||
__copyright__ = (
|
||||
'Copyright (c) 2010 by Ivan Mincik, ivan.mincik@gista.sk and '
|
||||
'Copyright (c) 2011 German Carrillo, geotux_tuxman@linuxmail.org'
|
||||
'Copyright (c) 2014 Tim Sutton, tim@linfiniti.com'
|
||||
)
|
||||
|
||||
import logging
|
||||
from qgis.PyQt.QtCore import QObject, pyqtSlot, pyqtSignal
|
||||
from qgis.core import QgsMapLayerRegistry
|
||||
from qgis.gui import QgsMapCanvasLayer
|
||||
LOGGER = logging.getLogger('QGIS')
|
||||
|
||||
|
||||
#noinspection PyMethodMayBeStatic,PyPep8Naming
|
||||
class QgisInterface(QObject):
|
||||
"""Class to expose QGIS objects and functions to plugins.
|
||||
|
||||
This class is here for enabling us to run unit tests only,
|
||||
so most methods are simply stubs.
|
||||
"""
|
||||
currentLayerChanged = pyqtSignal(QgsMapCanvasLayer)
|
||||
|
||||
def __init__(self, canvas):
|
||||
"""Constructor
|
||||
:param canvas:
|
||||
"""
|
||||
QObject.__init__(self)
|
||||
self.canvas = canvas
|
||||
# Set up slots so we can mimic the behaviour of QGIS when layers
|
||||
# are added.
|
||||
LOGGER.debug('Initialising canvas...')
|
||||
# noinspection PyArgumentList
|
||||
QgsMapLayerRegistry.instance().layersAdded.connect(self.addLayers)
|
||||
# noinspection PyArgumentList
|
||||
QgsMapLayerRegistry.instance().layerWasAdded.connect(self.addLayer)
|
||||
# noinspection PyArgumentList
|
||||
QgsMapLayerRegistry.instance().removeAll.connect(self.removeAllLayers)
|
||||
|
||||
# For processing module
|
||||
self.destCrs = None
|
||||
|
||||
@pyqtSlot('QStringList')
|
||||
def addLayers(self, layers):
|
||||
"""Handle layers being added to the registry so they show up in canvas.
|
||||
|
||||
:param layers: list<QgsMapLayer> list of map layers that were added
|
||||
|
||||
.. note:: The QgsInterface api does not include this method,
|
||||
it is added here as a helper to facilitate testing.
|
||||
"""
|
||||
#LOGGER.debug('addLayers called on qgis_interface')
|
||||
#LOGGER.debug('Number of layers being added: %s' % len(layers))
|
||||
#LOGGER.debug('Layer Count Before: %s' % len(self.canvas.layers()))
|
||||
current_layers = self.canvas.layers()
|
||||
final_layers = []
|
||||
for layer in current_layers:
|
||||
final_layers.append(QgsMapCanvasLayer(layer))
|
||||
for layer in layers:
|
||||
final_layers.append(QgsMapCanvasLayer(layer))
|
||||
|
||||
self.canvas.setLayerSet(final_layers)
|
||||
#LOGGER.debug('Layer Count After: %s' % len(self.canvas.layers()))
|
||||
|
||||
@pyqtSlot('QgsMapLayer')
|
||||
def addLayer(self, layer):
|
||||
"""Handle a layer being added to the registry so it shows up in canvas.
|
||||
|
||||
:param layer: list<QgsMapLayer> list of map layers that were added
|
||||
|
||||
.. note: The QgsInterface api does not include this method, it is added
|
||||
here as a helper to facilitate testing.
|
||||
|
||||
.. note: The addLayer method was deprecated in QGIS 1.8 so you should
|
||||
not need this method much.
|
||||
"""
|
||||
pass
|
||||
|
||||
@pyqtSlot()
|
||||
def removeAllLayers(self):
|
||||
"""Remove layers from the canvas before they get deleted."""
|
||||
self.canvas.setLayerSet([])
|
||||
|
||||
def newProject(self):
|
||||
"""Create new project."""
|
||||
# noinspection PyArgumentList
|
||||
QgsMapLayerRegistry.instance().removeAllMapLayers()
|
||||
|
||||
# ---------------- API Mock for QgsInterface follows -------------------
|
||||
|
||||
def zoomFull(self):
|
||||
"""Zoom to the map full extent."""
|
||||
pass
|
||||
|
||||
def zoomToPrevious(self):
|
||||
"""Zoom to previous view extent."""
|
||||
pass
|
||||
|
||||
def zoomToNext(self):
|
||||
"""Zoom to next view extent."""
|
||||
pass
|
||||
|
||||
def zoomToActiveLayer(self):
|
||||
"""Zoom to extent of active layer."""
|
||||
pass
|
||||
|
||||
def addVectorLayer(self, path, base_name, provider_key):
|
||||
"""Add a vector layer.
|
||||
|
||||
:param path: Path to layer.
|
||||
:type path: str
|
||||
|
||||
:param base_name: Base name for layer.
|
||||
:type base_name: str
|
||||
|
||||
:param provider_key: Provider key e.g. 'ogr'
|
||||
:type provider_key: str
|
||||
"""
|
||||
pass
|
||||
|
||||
def addRasterLayer(self, path, base_name):
|
||||
"""Add a raster layer given a raster layer file name
|
||||
|
||||
:param path: Path to layer.
|
||||
:type path: str
|
||||
|
||||
:param base_name: Base name for layer.
|
||||
:type base_name: str
|
||||
"""
|
||||
pass
|
||||
|
||||
def activeLayer(self):
|
||||
"""Get pointer to the active layer (layer selected in the legend)."""
|
||||
# noinspection PyArgumentList
|
||||
layers = QgsMapLayerRegistry.instance().mapLayers()
|
||||
for item in layers:
|
||||
return layers[item]
|
||||
|
||||
def addToolBarIcon(self, action):
|
||||
"""Add an icon to the plugins toolbar.
|
||||
|
||||
:param action: Action to add to the toolbar.
|
||||
:type action: QAction
|
||||
"""
|
||||
pass
|
||||
|
||||
def removeToolBarIcon(self, action):
|
||||
"""Remove an action (icon) from the plugin toolbar.
|
||||
|
||||
:param action: Action to add to the toolbar.
|
||||
:type action: QAction
|
||||
"""
|
||||
pass
|
||||
|
||||
def addToolBar(self, name):
|
||||
"""Add toolbar with specified name.
|
||||
|
||||
:param name: Name for the toolbar.
|
||||
:type name: str
|
||||
"""
|
||||
pass
|
||||
|
||||
def mapCanvas(self):
|
||||
"""Return a pointer to the map canvas."""
|
||||
return self.canvas
|
||||
|
||||
def mainWindow(self):
|
||||
"""Return a pointer to the main window.
|
||||
|
||||
In case of QGIS it returns an instance of QgisApp.
|
||||
"""
|
||||
pass
|
||||
|
||||
def addDockWidget(self, area, dock_widget):
|
||||
"""Add a dock widget to the main window.
|
||||
|
||||
:param area: Where in the ui the dock should be placed.
|
||||
:type area:
|
||||
|
||||
:param dock_widget: A dock widget to add to the UI.
|
||||
:type dock_widget: QDockWidget
|
||||
"""
|
||||
pass
|
||||
|
||||
def legendInterface(self):
|
||||
"""Get the legend."""
|
||||
return self.canvas
|
||||
@@ -1,19 +0,0 @@
|
||||
NCOLS 10
|
||||
NROWS 10
|
||||
XLLCENTER 1535380.000000
|
||||
YLLCENTER 5083260.000000
|
||||
DX 10
|
||||
DY 10
|
||||
NODATA_VALUE -9999
|
||||
0 1 2 3 4 5 6 7 8 9
|
||||
0 1 2 3 4 5 6 7 8 9
|
||||
0 1 2 3 4 5 6 7 8 9
|
||||
0 1 2 3 4 5 6 7 8 9
|
||||
0 1 2 3 4 5 6 7 8 9
|
||||
0 1 2 3 4 5 6 7 8 9
|
||||
0 1 2 3 4 5 6 7 8 9
|
||||
0 1 2 3 4 5 6 7 8 9
|
||||
0 1 2 3 4 5 6 7 8 9
|
||||
0 1 2 3 4 5 6 7 8 9
|
||||
CRS
|
||||
NOTES
|
||||
@@ -1,13 +0,0 @@
|
||||
<PAMDataset>
|
||||
<Metadata>
|
||||
<MDI key="AREA_OR_POINT">Point</MDI>
|
||||
</Metadata>
|
||||
<PAMRasterBand band="1">
|
||||
<Metadata>
|
||||
<MDI key="STATISTICS_MAXIMUM">9</MDI>
|
||||
<MDI key="STATISTICS_MEAN">4.5</MDI>
|
||||
<MDI key="STATISTICS_MINIMUM">0</MDI>
|
||||
<MDI key="STATISTICS_STDDEV">2.872281323269</MDI>
|
||||
</Metadata>
|
||||
</PAMRasterBand>
|
||||
</PAMDataset>
|
||||
@@ -1 +0,0 @@
|
||||
title: Tenbytenraster
|
||||
@@ -1,18 +0,0 @@
|
||||
<?xml version='1.0' encoding='iso-8859-1'?>
|
||||
<ga_license_file>
|
||||
<metadata>
|
||||
<author>Tim Sutton, Linfiniti Consulting CC</author>
|
||||
</metadata>
|
||||
|
||||
<datafile>
|
||||
<filename>tenbytenraster.asc</filename>
|
||||
<checksum>2700044251</checksum>
|
||||
<publishable>Yes</publishable>
|
||||
<accountable>Tim Sutton</accountable>
|
||||
<source>Tim Sutton (QGIS Source Tree)</source>
|
||||
<IP_owner>Tim Sutton</IP_owner>
|
||||
<IP_info>This data is publicly available from QGIS Source Tree. The original
|
||||
file was created and contributed to QGIS by Tim Sutton.</IP_info>
|
||||
</datafile>
|
||||
|
||||
</ga_license_file>
|
||||
@@ -1 +0,0 @@
|
||||
GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]
|
||||
@@ -1,26 +0,0 @@
|
||||
<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>
|
||||
<qgis version="1.9.0-Master" minimumScale="-4.65661e-10" maximumScale="1e+08" hasScaleBasedVisibilityFlag="0">
|
||||
<pipe>
|
||||
<rasterrenderer opacity="1" alphaBand="0" classificationMax="9" classificationMinMaxOrigin="MinMaxFullExtentExact" band="1" classificationMin="0" type="singlebandpseudocolor">
|
||||
<rasterTransparency/>
|
||||
<rastershader>
|
||||
<colorrampshader colorRampType="INTERPOLATED" clip="0">
|
||||
<item alpha="255" value="0" label="0.000000" color="#d7191c"/>
|
||||
<item alpha="255" value="1" label="1.000000" color="#e75b3a"/>
|
||||
<item alpha="255" value="2" label="2.000000" color="#f89d59"/>
|
||||
<item alpha="255" value="3" label="3.000000" color="#fdc980"/>
|
||||
<item alpha="255" value="4" label="4.000000" color="#feedaa"/>
|
||||
<item alpha="255" value="5" label="5.000000" color="#ecf7b9"/>
|
||||
<item alpha="255" value="6" label="6.000000" color="#c7e8ad"/>
|
||||
<item alpha="255" value="7" label="7.000000" color="#9cd3a6"/>
|
||||
<item alpha="255" value="8" label="8.000000" color="#63abb0"/>
|
||||
<item alpha="255" value="9" label="9.000000" color="#2b83ba"/>
|
||||
</colorrampshader>
|
||||
</rastershader>
|
||||
</rasterrenderer>
|
||||
<brightnesscontrast brightness="0" contrast="0"/>
|
||||
<huesaturation colorizeGreen="128" colorizeOn="0" colorizeRed="255" colorizeBlue="128" grayscaleMode="0" saturation="0" colorizeStrength="100"/>
|
||||
<rasterresampler maxOversampling="2"/>
|
||||
</pipe>
|
||||
<blendMode>0</blendMode>
|
||||
</qgis>
|
||||
@@ -1,55 +0,0 @@
|
||||
# coding=utf-8
|
||||
"""Dialog test.
|
||||
|
||||
.. note:: This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
"""
|
||||
|
||||
__author__ = 'spacil@arub.cz'
|
||||
__date__ = '2026-02-03'
|
||||
__copyright__ = 'Copyright 2026, David Spáčil'
|
||||
|
||||
import unittest
|
||||
|
||||
from qgis.PyQt.QtGui import QDialogButtonBox, QDialog
|
||||
|
||||
from amcr_viewer_dialog import AmcrViewerDialog
|
||||
|
||||
from utilities import get_qgis_app
|
||||
QGIS_APP = get_qgis_app()
|
||||
|
||||
|
||||
class AmcrViewerDialogTest(unittest.TestCase):
|
||||
"""Test dialog works."""
|
||||
|
||||
def setUp(self):
|
||||
"""Runs before each test."""
|
||||
self.dialog = AmcrViewerDialog(None)
|
||||
|
||||
def tearDown(self):
|
||||
"""Runs after each test."""
|
||||
self.dialog = None
|
||||
|
||||
def test_dialog_ok(self):
|
||||
"""Test we can click OK."""
|
||||
|
||||
button = self.dialog.button_box.button(QDialogButtonBox.Ok)
|
||||
button.click()
|
||||
result = self.dialog.result()
|
||||
self.assertEqual(result, QDialog.Accepted)
|
||||
|
||||
def test_dialog_cancel(self):
|
||||
"""Test we can click cancel."""
|
||||
button = self.dialog.button_box.button(QDialogButtonBox.Cancel)
|
||||
button.click()
|
||||
result = self.dialog.result()
|
||||
self.assertEqual(result, QDialog.Rejected)
|
||||
|
||||
if __name__ == "__main__":
|
||||
suite = unittest.makeSuite(AmcrViewerDialogTest)
|
||||
runner = unittest.TextTestRunner(verbosity=2)
|
||||
runner.run(suite)
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
# coding=utf-8
|
||||
"""Tests QGIS plugin init."""
|
||||
|
||||
__author__ = 'Tim Sutton <tim@linfiniti.com>'
|
||||
__revision__ = '$Format:%H$'
|
||||
__date__ = '17/10/2010'
|
||||
__license__ = "GPL"
|
||||
__copyright__ = 'Copyright 2012, Australia Indonesia Facility for '
|
||||
__copyright__ += 'Disaster Reduction'
|
||||
|
||||
import os
|
||||
import unittest
|
||||
import logging
|
||||
import configparser
|
||||
|
||||
LOGGER = logging.getLogger('QGIS')
|
||||
|
||||
|
||||
class TestInit(unittest.TestCase):
|
||||
"""Test that the plugin init is usable for QGIS.
|
||||
|
||||
Based heavily on the validator class by Alessandro
|
||||
Passoti available here:
|
||||
|
||||
http://github.com/qgis/qgis-django/blob/master/qgis-app/
|
||||
plugins/validator.py
|
||||
|
||||
"""
|
||||
|
||||
def test_read_init(self):
|
||||
"""Test that the plugin __init__ will validate on plugins.qgis.org."""
|
||||
|
||||
# You should update this list according to the latest in
|
||||
# https://github.com/qgis/qgis-django/blob/master/qgis-app/
|
||||
# plugins/validator.py
|
||||
|
||||
required_metadata = [
|
||||
'name',
|
||||
'description',
|
||||
'version',
|
||||
'qgisMinimumVersion',
|
||||
'email',
|
||||
'author']
|
||||
|
||||
file_path = os.path.abspath(os.path.join(
|
||||
os.path.dirname(__file__), os.pardir,
|
||||
'metadata.txt'))
|
||||
LOGGER.info(file_path)
|
||||
metadata = []
|
||||
parser = configparser.ConfigParser()
|
||||
parser.optionxform = str
|
||||
parser.read(file_path)
|
||||
message = 'Cannot find a section named "general" in %s' % file_path
|
||||
assert parser.has_section('general'), message
|
||||
metadata.extend(parser.items('general'))
|
||||
|
||||
for expectation in required_metadata:
|
||||
message = ('Cannot find metadata "%s" in metadata source (%s).' % (
|
||||
expectation, file_path))
|
||||
|
||||
self.assertIn(expectation, dict(metadata), message)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,60 +0,0 @@
|
||||
# coding=utf-8
|
||||
"""Tests for QGIS functionality.
|
||||
|
||||
|
||||
.. note:: This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
"""
|
||||
__author__ = 'tim@linfiniti.com'
|
||||
__date__ = '20/01/2011'
|
||||
__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
|
||||
'Disaster Reduction')
|
||||
|
||||
import os
|
||||
import unittest
|
||||
from qgis.core import (
|
||||
QgsProviderRegistry,
|
||||
QgsCoordinateReferenceSystem,
|
||||
QgsRasterLayer)
|
||||
|
||||
from .utilities import get_qgis_app
|
||||
QGIS_APP = get_qgis_app()
|
||||
|
||||
|
||||
class QGISTest(unittest.TestCase):
|
||||
"""Test the QGIS Environment"""
|
||||
|
||||
def test_qgis_environment(self):
|
||||
"""QGIS environment has the expected providers"""
|
||||
|
||||
r = QgsProviderRegistry.instance()
|
||||
self.assertIn('gdal', r.providerList())
|
||||
self.assertIn('ogr', r.providerList())
|
||||
self.assertIn('postgres', r.providerList())
|
||||
|
||||
def test_projection(self):
|
||||
"""Test that QGIS properly parses a wkt string.
|
||||
"""
|
||||
crs = QgsCoordinateReferenceSystem()
|
||||
wkt = (
|
||||
'GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",'
|
||||
'SPHEROID["WGS_1984",6378137.0,298.257223563]],'
|
||||
'PRIMEM["Greenwich",0.0],UNIT["Degree",'
|
||||
'0.0174532925199433]]')
|
||||
crs.createFromWkt(wkt)
|
||||
auth_id = crs.authid()
|
||||
expected_auth_id = 'EPSG:4326'
|
||||
self.assertEqual(auth_id, expected_auth_id)
|
||||
|
||||
# now test for a loaded layer
|
||||
path = os.path.join(os.path.dirname(__file__), 'tenbytenraster.asc')
|
||||
title = 'TestRaster'
|
||||
layer = QgsRasterLayer(path, title)
|
||||
auth_id = layer.crs().authid()
|
||||
self.assertEqual(auth_id, expected_auth_id)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,44 +0,0 @@
|
||||
# coding=utf-8
|
||||
"""Resources test.
|
||||
|
||||
.. note:: This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
"""
|
||||
|
||||
__author__ = 'spacil@arub.cz'
|
||||
__date__ = '2026-02-03'
|
||||
__copyright__ = 'Copyright 2026, David Spáčil'
|
||||
|
||||
import unittest
|
||||
|
||||
from qgis.PyQt.QtGui import QIcon
|
||||
|
||||
|
||||
|
||||
class AmcrViewerDialogTest(unittest.TestCase):
|
||||
"""Test rerources work."""
|
||||
|
||||
def setUp(self):
|
||||
"""Runs before each test."""
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
"""Runs after each test."""
|
||||
pass
|
||||
|
||||
def test_icon_png(self):
|
||||
"""Test we can click OK."""
|
||||
path = ':/plugins/AmcrViewer/icon.png'
|
||||
icon = QIcon(path)
|
||||
self.assertFalse(icon.isNull())
|
||||
|
||||
if __name__ == "__main__":
|
||||
suite = unittest.makeSuite(AmcrViewerResourcesTest)
|
||||
runner = unittest.TextTestRunner(verbosity=2)
|
||||
runner.run(suite)
|
||||
|
||||
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
# coding=utf-8
|
||||
"""Safe Translations Test.
|
||||
|
||||
.. note:: This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
"""
|
||||
from .utilities import get_qgis_app
|
||||
|
||||
__author__ = 'ismailsunni@yahoo.co.id'
|
||||
__date__ = '12/10/2011'
|
||||
__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
|
||||
'Disaster Reduction')
|
||||
import unittest
|
||||
import os
|
||||
|
||||
from qgis.PyQt.QtCore import QCoreApplication, QTranslator
|
||||
|
||||
QGIS_APP = get_qgis_app()
|
||||
|
||||
|
||||
class SafeTranslationsTest(unittest.TestCase):
|
||||
"""Test translations work."""
|
||||
|
||||
def setUp(self):
|
||||
"""Runs before each test."""
|
||||
if 'LANG' in iter(os.environ.keys()):
|
||||
os.environ.__delitem__('LANG')
|
||||
|
||||
def tearDown(self):
|
||||
"""Runs after each test."""
|
||||
if 'LANG' in iter(os.environ.keys()):
|
||||
os.environ.__delitem__('LANG')
|
||||
|
||||
def test_qgis_translations(self):
|
||||
"""Test that translations work."""
|
||||
parent_path = os.path.join(__file__, os.path.pardir, os.path.pardir)
|
||||
dir_path = os.path.abspath(parent_path)
|
||||
file_path = os.path.join(
|
||||
dir_path, 'i18n', 'af.qm')
|
||||
translator = QTranslator()
|
||||
translator.load(file_path)
|
||||
QCoreApplication.installTranslator(translator)
|
||||
|
||||
expected_message = 'Goeie more'
|
||||
real_message = QCoreApplication.translate("@default", 'Good morning')
|
||||
self.assertEqual(real_message, expected_message)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
suite = unittest.makeSuite(SafeTranslationsTest)
|
||||
runner = unittest.TextTestRunner(verbosity=2)
|
||||
runner.run(suite)
|
||||
@@ -1,61 +0,0 @@
|
||||
# coding=utf-8
|
||||
"""Common functionality used by regression tests."""
|
||||
|
||||
import sys
|
||||
import logging
|
||||
|
||||
|
||||
LOGGER = logging.getLogger('QGIS')
|
||||
QGIS_APP = None # Static variable used to hold hand to running QGIS app
|
||||
CANVAS = None
|
||||
PARENT = None
|
||||
IFACE = None
|
||||
|
||||
|
||||
def get_qgis_app():
|
||||
""" Start one QGIS application to test against.
|
||||
|
||||
:returns: Handle to QGIS app, canvas, iface and parent. If there are any
|
||||
errors the tuple members will be returned as None.
|
||||
:rtype: (QgsApplication, CANVAS, IFACE, PARENT)
|
||||
|
||||
If QGIS is already running the handle to that app will be returned.
|
||||
"""
|
||||
|
||||
try:
|
||||
from qgis.PyQt import QtGui, QtCore
|
||||
from qgis.core import QgsApplication
|
||||
from qgis.gui import QgsMapCanvas
|
||||
from .qgis_interface import QgisInterface
|
||||
except ImportError:
|
||||
return None, None, None, None
|
||||
|
||||
global QGIS_APP # pylint: disable=W0603
|
||||
|
||||
if QGIS_APP is None:
|
||||
gui_flag = True # All test will run qgis in gui mode
|
||||
#noinspection PyPep8Naming
|
||||
QGIS_APP = QgsApplication(sys.argv, gui_flag)
|
||||
# Make sure QGIS_PREFIX_PATH is set in your env if needed!
|
||||
QGIS_APP.initQgis()
|
||||
s = QGIS_APP.showSettings()
|
||||
LOGGER.debug(s)
|
||||
|
||||
global PARENT # pylint: disable=W0603
|
||||
if PARENT is None:
|
||||
#noinspection PyPep8Naming
|
||||
PARENT = QtGui.QWidget()
|
||||
|
||||
global CANVAS # pylint: disable=W0603
|
||||
if CANVAS is None:
|
||||
#noinspection PyPep8Naming
|
||||
CANVAS = QgsMapCanvas(PARENT)
|
||||
CANVAS.resize(QtCore.QSize(400, 400))
|
||||
|
||||
global IFACE # pylint: disable=W0603
|
||||
if IFACE is None:
|
||||
# QgisInterface is a stub implementation of the QGIS plugin interface
|
||||
#noinspection PyPep8Naming
|
||||
IFACE = QgisInterface(CANVAS)
|
||||
|
||||
return QGIS_APP, CANVAS, IFACE, PARENT
|
||||
Reference in New Issue
Block a user