Files
geodonkey-qgis-plugin/geodonkey/gui/tools/elevation.py
T
2026-12-01 19:59:12 +01:00

302 lines
11 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
from typing import Any, Dict, List, Optional, Tuple
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtGui import QKeySequence
from qgis.PyQt.QtWidgets import (
QAbstractItemView,
QComboBox,
QHBoxLayout,
QHeaderView,
QPushButton,
QTableWidget,
QTableWidgetItem,
QVBoxLayout,
QWidget,
)
from qgis.core import Qgis, QgsProject
from ... import config, mapcontext, points as points_mod, results
from ...compat import QAction
from ...i18n import later, tr
from .. import theme
from ..maptab import MapTab
COL_X, COL_Y, COL_Z = 0, 1, 2
MAX_POINTS = 20
class ElevationPage(MapTab):
ALGORITHM = "geodonkey:elevationpoints"
NAME = later("Point elevation")
ICON = "elevation.svg"
WANTED = MAX_POINTS
FREE = True
LEAST = 1
CONNECT = False
AUTO_RUN = False
PROMPTS = (later("Click a point on the map."),
later("Another point, or right-click to finish."))
PICK_TEXT = later("Pick points on the map")
TASK_TITLE = later("GeoDonkey: point elevation")
LAYER_TITLE = later("Point elevation")
STYLE_KEY = "elevation"
def setup(self) -> None:
self._coordinates: List[Tuple[float, float]] = []
def body(self) -> Optional[QWidget]:
holder = QWidget()
box = QVBoxLayout(holder)
box.setContentsMargins(0, 0, 0, 0)
box.setSpacing(theme.TIGHT)
self.crs_box = QComboBox()
self.crs_box.addItem(tr("X/Y in WGS 84 · degrees"))
self.crs_box.addItem(tr("X/Y in the map CRS"))
self.crs_box.currentIndexChanged.connect(lambda _index: self.fill_places())
box.addWidget(self.crs_box)
self.table = QTableWidget(0, 3)
self.table.setHorizontalHeaderLabels([tr("X"), tr("Y"), tr("Z (m)")])
self.table.setAlternatingRowColors(True)
self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.table.setSelectionBehavior(
QAbstractItemView.SelectionBehavior.SelectRows)
self.table.setSelectionMode(
QAbstractItemView.SelectionMode.SingleSelection)
self.table.horizontalHeader().setSectionResizeMode(
QHeaderView.ResizeMode.Stretch)
self.table.verticalHeader().setDefaultSectionSize(20)
self.table.currentCellChanged.connect(
lambda row, _c, _pr, _pc: self._cell_changed(row))
self._remove_action = QAction(tr("Remove point"), self.table)
self._remove_action.setShortcut(QKeySequence.StandardKey.Delete)
self._remove_action.setShortcutContext(
Qt.ShortcutContext.WidgetShortcut)
self._remove_action.triggered.connect(self.remove_point)
self.table.addAction(self._remove_action)
self.table.setContextMenuPolicy(
Qt.ContextMenuPolicy.ActionsContextMenu)
box.addWidget(self.table, 1)
row = QHBoxLayout()
row.setSpacing(theme.TIGHT)
self.remove_button = QPushButton(tr("Remove point"))
self.remove_button.setToolTip(tr(
"Remove the selected point from the list. "
"A right-click on the row or the Delete key does the same."))
self.remove_button.setEnabled(False)
self.remove_button.clicked.connect(self.remove_point)
row.addWidget(self.remove_button)
self.lookup_button = QPushButton(tr("Look up elevations"))
self.lookup_button.setStyleSheet(theme.primary_button_style())
self.lookup_button.setEnabled(False)
self.lookup_button.clicked.connect(self.run)
row.addWidget(self.lookup_button, 1)
box.addLayout(row)
return holder
def controls(self):
return (self.crs_box,)
def busy(self, running: bool) -> None:
super().busy(running)
self.lookup_button.setEnabled(not running and bool(self.points))
def show_points(self) -> None:
if len(self.points) < 2:
super().show_points()
return
self.points_label.setText(tr("{count} points picked.").format(
count=len(self.points)))
def price(self) -> str:
return tr("{coins} DC per run · up to {limit} points").format(
coins=config.elevation_coins(MAX_POINTS, "elevation_points"),
limit=MAX_POINTS)
def run(self) -> None:
if not self.points:
self.panel.say(tr("Pick at least one point on the map."),
Qgis.MessageLevel.Warning)
return
coordinates = list(self.points)
client = self.panel.api()
def work(feedback):
return client.elevation_points(coordinates, feedback=feedback)
self.start(work, tr("Looking up the elevations…"))
def clear_result(self) -> None:
for row in range(self.table.rowCount()):
self._cell(row, COL_Z, "")
marker = self.marker()
if marker is not None:
marker.hide()
def accept(self, payload: Dict[str, Any]) -> None:
self.payload = payload
rows = results.elevation_point_rows(self.payload, self.points)
self._coordinates = list(self.points)
self.fill_places()
if not rows:
self.keep_button.setEnabled(False)
self.panel.say(tr("The service returned no elevations."),
Qgis.MessageLevel.Warning)
return
missing = 0
for index, row in enumerate(rows):
attrs = row["attrs"]
height = attrs.get("elevation")
if height is None:
missing += 1
self._cell(index, COL_Z, "–", tr("No elevation data here."))
else:
self._cell(index, COL_Z,
points_mod.fmt(round(float(height), 1)),
attrs.get("ele_source") or "")
self.keep_button.setEnabled(True)
self.summary.setText(self._span(rows))
if missing:
self.panel.say(tr("{missing} of {count} points have no elevation "
"data.").format(missing=missing, count=len(rows)),
Qgis.MessageLevel.Warning)
else:
self.panel.say(tr("{count} elevation(s) found.").format(
count=len(rows)), Qgis.MessageLevel.Success)
@staticmethod
def _span(rows) -> str:
heights = [row["attrs"]["elevation"] for row in rows
if row["attrs"].get("elevation") is not None]
if not heights:
return ""
if len(heights) == 1:
return tr("{height} m above sea level").format(
height=points_mod.fmt(round(float(heights[0]), 1)))
low, high = min(heights), max(heights)
return tr("{low} m to {high} m · {span} m difference").format(
low=points_mod.fmt(round(float(low), 1)),
high=points_mod.fmt(round(float(high), 1)),
span=points_mod.fmt(round(float(high) - float(low), 1)))
def points_changed(self) -> None:
self.payload = {}
self._coordinates = list(self.points)
self.fill_places()
self.summary.setText("")
self.keep_button.setEnabled(False)
self.lookup_button.setEnabled(bool(self.points))
dots = self.dots()
if dots is not None:
dots.show(self._coordinates)
self._selection_changed()
def remove_point(self) -> None:
row = self.table.currentRow()
if row < 0 or row >= len(self.points):
return
self._drop_from_payload(row)
self.points = [point for index, point in enumerate(self.points)
if index != row]
self._coordinates = list(self.points)
self.table.removeRow(row)
self.fill_places()
self.show_points()
dots = self.dots()
if dots is not None:
dots.show(self._coordinates)
rows = self.rows() if self.payload else []
self.summary.setText(self._span(rows) if rows else "")
self.keep_button.setEnabled(bool(rows))
self.lookup_button.setEnabled(bool(self.points))
self._row_changed(self.table.currentRow())
self._selection_changed()
self.panel.say(tr("Point removed."))
def _drop_from_payload(self, row: int) -> None:
if not isinstance(self.payload, dict):
return
places = self.payload.get("points")
if isinstance(places, list) and len(places) == len(self.points):
places.pop(row)
return
self.payload = {}
def _selection_changed(self) -> None:
row = self.table.currentRow()
self.remove_button.setEnabled(0 <= row < len(self._coordinates))
self._remove_action.setEnabled(self.remove_button.isEnabled())
def fill_places(self) -> None:
self._name_map_crs()
self.table.setRowCount(len(self._coordinates))
for row, (lon, lat) in enumerate(self._coordinates):
x, y = self._place(lon, lat)
self._cell(row, COL_X, x)
self._cell(row, COL_Y, y)
if self.table.item(row, COL_Z) is None:
self._cell(row, COL_Z, "")
def map_crs(self):
canvas = self.canvas()
if canvas is not None:
return canvas.mapSettings().destinationCrs()
return QgsProject.instance().crs()
def _name_map_crs(self) -> None:
crs = self.map_crs()
code = crs.authid() if crs is not None and crs.isValid() else ""
self.crs_box.setItemText(1, tr("X/Y in {crs}").format(crs=code)
if code else tr("X/Y in the map CRS"))
def _place(self, lon: float, lat: float) -> Tuple[str, str]:
if self.crs_box.currentIndex() == 0:
return ("%.5f" % lon, "%.5f" % lat)
crs = self.map_crs()
point = mapcontext.point_from_wgs84(lon, lat, crs)
if point is None:
return ("", "")
places = 5 if crs is not None and crs.isGeographic() else 2
return ("%.*f" % (places, point.x()), "%.*f" % (places, point.y()))
def _cell(self, row: int, column: int, text: str, tip: str = "") -> None:
item = self.table.item(row, column)
if item is None:
item = QTableWidgetItem()
item.setTextAlignment(Qt.AlignmentFlag.AlignRight
| Qt.AlignmentFlag.AlignVCenter)
self.table.setItem(row, column, item)
item.setText(text)
item.setToolTip(tip)
def rows(self):
return results.elevation_point_rows(self.payload, self._coordinates)
def _cell_changed(self, index: int) -> None:
self._row_changed(index)
self._selection_changed()
def _row_changed(self, index: int) -> None:
marker = self.marker()
if marker is None:
return
if index < 0 or index >= len(self._coordinates):
marker.hide()
return
lon, lat = self._coordinates[index]
marker.show(lon, lat)