Files
geodonkey-qgis-plugin/geodonkey/processing/base.py
T
2026-12-01 19:59:12 +01:00

184 lines
6.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import collections
from typing import Any, Dict, Optional, Sequence, Tuple
from qgis.core import (
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
QgsFeature,
QgsFeatureSink,
QgsFields,
QgsGeometry,
QgsPointXY,
QgsProcessingAlgorithm,
QgsProcessingException,
QgsProcessingLayerPostProcessorInterface,
)
from .. import auth, config, geojson, layers, settings
from ..client import ApiClient
from ..compat import field, icon
from ..errors import GeoDonkeyError
from ..i18n import tr
from ..net import QgisTransport
from ..results import Field, Row
WGS84 = "EPSG:4326"
def wgs84() -> QgsCoordinateReferenceSystem:
return QgsCoordinateReferenceSystem(WGS84)
def build_fields(spec: Sequence[Field]) -> QgsFields:
fields = QgsFields()
for name, kind in spec:
fields.append(field(name, kind))
return fields
_KEEP = collections.deque(maxlen=64)
class Styler(QgsProcessingLayerPostProcessorInterface):
def __init__(self, rule) -> None:
super().__init__()
self._rule = rule
def postProcessLayer(self, layer, context, feedback) -> None: # noqa: N802
layers.apply_style(layer, self._rule)
class GeoDonkeyAlgorithm(QgsProcessingAlgorithm):
ICON = "geodonkey.svg"
GROUP = "GeoDonkey"
GROUP_ID = "geodonkey"
COST_KEY = ""
def group(self) -> str:
return tr(self.GROUP)
def groupId(self) -> str: # noqa: N802
return self.GROUP_ID
def icon(self):
return icon(self.ICON)
def price(self) -> int:
return config.COIN_COSTS.get(self.COST_KEY, 0)
def cost_note(self) -> str:
return tr(
"<p><b>Every run costs {coins} DonkeyCoins</b> once the {free} free "
"calls of the current hour are used up. The API key is taken from "
"the plugin settings (Web ▸ GeoDonkey ▸ GeoDonkey settings); "
"without a key only the free calls are available.</p>"
).format(coins=self.price(), free=config.FREE_CALLS_PER_HOUR)
def client(self, feedback) -> ApiClient:
api = ApiClient(transport=QgisTransport(),
base_url=settings.api_url(),
token=auth.load_token(),
language=settings.language())
if not api.token:
feedback.pushWarning(tr(
"No API key stored – only the free calls of this hour are available. "
"Add a key under Web ▸ GeoDonkey ▸ GeoDonkey settings."))
return api
@staticmethod
def fail(exc: GeoDonkeyError, feedback) -> None:
if exc.detail:
feedback.pushDebugInfo(exc.detail)
raise QgsProcessingException(exc.message)
@staticmethod
def report(api: ApiClient, feedback) -> None:
charged = api.usage.charged
if charged:
feedback.pushInfo(tr("Charged: {coins} DC · balance {balance} DC").format(
coins=charged, balance=api.usage.balance))
elif api.usage.free_remaining is not None:
feedback.pushInfo(tr("Free call · {count} left this hour").format(
count=api.usage.free_remaining))
def wgs84_point(self, parameters, name: str, context) -> Tuple[float, float]:
point = self.parameterAsPoint(parameters, name, context, wgs84())
return (point.x(), point.y())
@staticmethod
def source_points(source, context, feedback) -> Tuple[list, list]:
transform = QgsCoordinateTransform(source.sourceCrs(), wgs84(),
context.transformContext())
coordinates = []
features = []
skipped = 0
for feature in source.getFeatures():
if feedback.isCanceled():
break
geometry = feature.geometry()
if geometry is None or geometry.isEmpty():
skipped += 1
continue
point = geometry.centroid().asPoint() if geometry.isMultipart() \
else geometry.asPoint()
moved = transform.transform(QgsPointXY(point))
coordinates.append((moved.x(), moved.y()))
features.append(feature)
if skipped:
feedback.pushWarning(tr(
"{count} features without geometry were skipped.").format(count=skipped))
return coordinates, features
def make_sink(self, parameters, context, name: str, spec: Sequence[Field],
wkb, crs: Optional[QgsCoordinateReferenceSystem] = None):
return self.parameterAsSink(parameters, name, context,
build_fields(spec), wkb,
crs if crs is not None else wgs84())
def style(self, context, dest_id: Any, rule) -> bool:
if not dest_id or rule is None:
return False
try:
if not context.willLoadLayerOnCompletion(dest_id):
return False
details = context.layerToLoadOnCompletionDetails(dest_id)
except (AttributeError, TypeError):
return False
if details is None:
return False
processor = Styler(rule)
_KEEP.append(processor)
details.setPostProcessor(processor)
return True
@staticmethod
def write(sink, spec: Sequence[Field], rows: Sequence[Row], feedback) -> int:
if sink is None:
return 0
fields = build_fields(spec)
written = 0
for row in rows:
if feedback.isCanceled():
break
out = QgsFeature(fields)
wkt = geojson.to_wkt(row.get("geometry"))
if wkt:
out.setGeometry(QgsGeometry.fromWkt(wkt))
attrs = row.get("attrs") or {}
out.setAttributes([attrs.get(name) for name, _kind in spec])
sink.addFeature(out, QgsFeatureSink.Flag.FastInsert)
written += 1
return written
def attribution(meta: Dict[str, Any], feedback) -> None:
text = geojson.attribution(meta)
if not text:
sources = meta.get("attributions")
if isinstance(sources, (list, tuple)) and sources:
text = ", ".join(str(entry) for entry in sources)
if text:
feedback.pushInfo(str(text))