176 lines
5.9 KiB
Python
176 lines
5.9 KiB
Python
from __future__ import annotations
|
||
|
||
import os
|
||
import tempfile
|
||
from typing import Any, Dict, List, Mapping, Optional, Tuple
|
||
|
||
from qgis.core import (
|
||
QgsCategorizedSymbolRenderer,
|
||
QgsFillSymbol,
|
||
QgsLayerMetadata,
|
||
QgsLineSymbol,
|
||
QgsMarkerSymbol,
|
||
QgsProject,
|
||
QgsRendererCategory,
|
||
QgsSingleSymbolRenderer,
|
||
QgsVectorLayer,
|
||
)
|
||
from qgis.PyQt.QtGui import QColor
|
||
|
||
from . import config, geojson, style
|
||
from .compat import pixels
|
||
from .errors import GeoDonkeyError
|
||
from .i18n import tr
|
||
|
||
GROUP_LABEL = {
|
||
"Point": tr("points"),
|
||
"Line": tr("lines"),
|
||
"Polygon": tr("areas"),
|
||
}
|
||
|
||
|
||
def result_folder() -> str:
|
||
folder = os.path.join(tempfile.gettempdir(), "geodonkey-qgis")
|
||
if not os.path.isdir(folder):
|
||
os.makedirs(folder)
|
||
return folder
|
||
|
||
|
||
def _colour(value: str, opacity: float = 1.0) -> QColor:
|
||
colour = QColor(value)
|
||
if not colour.isValid():
|
||
colour = QColor(style.HOUSE)
|
||
colour.setAlphaF(max(0.0, min(1.0, float(opacity))))
|
||
return colour
|
||
|
||
|
||
def _symbol(geometry: str, value: str):
|
||
if geometry == "Point":
|
||
symbol = QgsMarkerSymbol.createSimple({"name": "circle"})
|
||
symbol.setColor(_colour(value, style.POINT_OPACITY))
|
||
symbol.setSize(style.POINT_SIZE)
|
||
symbol.setSizeUnit(pixels())
|
||
layer_zero = symbol.symbolLayer(0)
|
||
if layer_zero is not None:
|
||
layer_zero.setStrokeColor(_colour(value))
|
||
layer_zero.setStrokeWidth(style.POINT_OUTLINE)
|
||
layer_zero.setStrokeWidthUnit(pixels())
|
||
return symbol
|
||
|
||
if geometry == "Line":
|
||
symbol = QgsLineSymbol.createSimple({})
|
||
symbol.setColor(_colour(value))
|
||
symbol.setWidth(style.LINE_WIDTH)
|
||
symbol.setWidthUnit(pixels())
|
||
return symbol
|
||
|
||
symbol = QgsFillSymbol.createSimple({})
|
||
symbol.setColor(_colour(value, style.AREA_OPACITY))
|
||
layer_zero = symbol.symbolLayer(0)
|
||
if layer_zero is not None:
|
||
layer_zero.setStrokeColor(_colour(value))
|
||
layer_zero.setStrokeWidth(style.AREA_OUTLINE)
|
||
layer_zero.setStrokeWidthUnit(pixels())
|
||
return symbol
|
||
|
||
|
||
def apply_style(layer: QgsVectorLayer, rule: Optional[Mapping[str, Any]]) -> bool:
|
||
if layer is None or not rule:
|
||
return False
|
||
geometry = str(rule.get("geometry") or "")
|
||
try:
|
||
if rule.get("kind") == "categories":
|
||
categories = []
|
||
for entry in rule.get("entries") or []:
|
||
categories.append(QgsRendererCategory(
|
||
entry.get("value"), _symbol(geometry, str(entry.get("color") or "")),
|
||
str(entry.get("label") or "")))
|
||
if not categories:
|
||
return False
|
||
renderer = QgsCategorizedSymbolRenderer(str(rule.get("field") or ""),
|
||
categories)
|
||
else:
|
||
renderer = QgsSingleSymbolRenderer(
|
||
_symbol(geometry, str(rule.get("color") or style.HOUSE)))
|
||
layer.setRenderer(renderer)
|
||
layer.triggerRepaint()
|
||
return True
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def _properties(part: Mapping[str, Any]) -> List[Mapping[str, Any]]:
|
||
out: List[Mapping[str, Any]] = []
|
||
for feature in (part or {}).get("features") or []:
|
||
props = (feature or {}).get("properties")
|
||
if isinstance(props, Mapping):
|
||
out.append(props)
|
||
return out
|
||
|
||
|
||
def _apply_metadata(layer: QgsVectorLayer, meta: Mapping[str, Any],
|
||
query: str, area_text: str) -> None:
|
||
md = QgsLayerMetadata()
|
||
md.setTitle(layer.name())
|
||
rights = []
|
||
credit = geojson.attribution(meta, config.DEFAULT_ATTRIBUTION)
|
||
if credit:
|
||
rights.append(credit)
|
||
licence = meta.get("license") or config.OSM_LICENSE
|
||
if licence:
|
||
rights.append(str(licence))
|
||
md.setRights(rights)
|
||
md.setLicenses([str(meta.get("license") or config.OSM_LICENSE)])
|
||
|
||
lines = [tr("Retrieved from GeoDonkey (DonkeyOSM).")]
|
||
if query:
|
||
lines.append(tr("Query: {query}").format(query=query))
|
||
if area_text:
|
||
lines.append(tr("Area: {area}").format(area=area_text))
|
||
if meta.get("data_updated_at"):
|
||
lines.append(tr("Data status: {stamp}").format(stamp=meta["data_updated_at"]))
|
||
if meta.get("truncated"):
|
||
lines.append(tr("Incomplete: the limit of {limit} was reached.").format(
|
||
limit=meta.get("limit") or "?"))
|
||
md.setAbstract("\n".join(lines))
|
||
layer.setMetadata(md)
|
||
|
||
|
||
def load_result(collection: Mapping[str, Any], meta: Mapping[str, Any],
|
||
title: str, area_text: str = "",
|
||
project: Optional[QgsProject] = None,
|
||
style_key: str = "osm") -> Tuple[List[QgsVectorLayer], Dict[str, int], int]:
|
||
project = project or QgsProject.instance()
|
||
buckets, without = geojson.split_by_geometry(collection)
|
||
if not buckets:
|
||
return [], {}, without
|
||
|
||
base = geojson.safe_name(title)
|
||
folder = result_folder()
|
||
root = project.layerTreeRoot()
|
||
group = root.insertGroup(0, base)
|
||
|
||
layers: List[QgsVectorLayer] = []
|
||
counts: Dict[str, int] = {}
|
||
for name in geojson.GROUP_ORDER:
|
||
part = buckets.get(name)
|
||
if not part:
|
||
continue
|
||
counts[name] = len(part["features"])
|
||
stem = "%s-%s-%d" % (geojson.safe_name(base, limit=32), name.lower(),
|
||
abs(hash((base, name))) % 100000)
|
||
path = geojson.write_collection(folder, stem, part)
|
||
layer = QgsVectorLayer(geojson.ogr_uri(path, name),
|
||
"%s – %s" % (base, GROUP_LABEL.get(name, name)),
|
||
"ogr")
|
||
if not layer.isValid():
|
||
raise GeoDonkeyError(
|
||
tr("QGIS could not read the result file: {path}").format(path=path))
|
||
_apply_metadata(layer, meta, title, area_text)
|
||
apply_style(layer, style.plan(style_key, name, _properties(part)))
|
||
project.addMapLayer(layer, False)
|
||
group.addLayer(layer)
|
||
layers.append(layer)
|
||
|
||
return layers, counts, without
|