NumberInputPanel.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. """
  2. ***************************************************************************
  3. NumberInputPanel.py
  4. ---------------------
  5. Date : August 2012
  6. Copyright : (C) 2012 by Victor Olaya
  7. Email : volayaf at gmail dot com
  8. ***************************************************************************
  9. * *
  10. * This program is free software; you can redistribute it and/or modify *
  11. * it under the terms of the GNU General Public License as published by *
  12. * the Free Software Foundation; either version 2 of the License, or *
  13. * (at your option) any later version. *
  14. * *
  15. ***************************************************************************
  16. """
  17. __author__ = 'Victor Olaya'
  18. __date__ = 'August 2012'
  19. __copyright__ = '(C) 2012, Victor Olaya'
  20. import os
  21. import math
  22. import warnings
  23. from qgis.PyQt import uic
  24. from qgis.PyQt import sip
  25. from qgis.PyQt.QtCore import pyqtSignal, QSize
  26. from qgis.PyQt.QtWidgets import QDialog, QLabel, QComboBox
  27. from qgis.core import (
  28. Qgis,
  29. QgsApplication,
  30. QgsExpression,
  31. QgsProperty,
  32. QgsUnitTypes,
  33. QgsMapLayer,
  34. QgsCoordinateReferenceSystem,
  35. QgsProcessingParameterNumber,
  36. QgsProcessingOutputNumber,
  37. QgsProcessingParameterDefinition,
  38. QgsProcessingModelChildParameterSource,
  39. QgsProcessingFeatureSourceDefinition,
  40. QgsProcessingUtils
  41. )
  42. from qgis.gui import QgsExpressionBuilderDialog
  43. from processing.tools.dataobjects import createExpressionContext, createContext
  44. pluginPath = os.path.split(os.path.dirname(__file__))[0]
  45. with warnings.catch_warnings():
  46. warnings.filterwarnings("ignore", category=DeprecationWarning)
  47. NUMBER_WIDGET, NUMBER_BASE = uic.loadUiType(
  48. os.path.join(pluginPath, 'ui', 'widgetNumberSelector.ui'))
  49. WIDGET, BASE = uic.loadUiType(
  50. os.path.join(pluginPath, 'ui', 'widgetBaseSelector.ui'))
  51. class ModelerNumberInputPanel(BASE, WIDGET):
  52. """
  53. Number input panel for use inside the modeler - this input panel
  54. is based off the base input panel and includes a text based line input
  55. for entering values. This allows expressions and other non-numeric
  56. values to be set, which are later evalauted to numbers when the model
  57. is run.
  58. """
  59. hasChanged = pyqtSignal()
  60. def __init__(self, param, modelParametersDialog):
  61. super().__init__(None)
  62. self.setupUi(self)
  63. self.param = param
  64. self.modelParametersDialog = modelParametersDialog
  65. if param.defaultValue():
  66. self.setValue(param.defaultValue())
  67. self.btnSelect.clicked.connect(self.showExpressionsBuilder)
  68. self.leText.textChanged.connect(lambda: self.hasChanged.emit())
  69. def showExpressionsBuilder(self):
  70. context = createExpressionContext()
  71. processing_context = createContext()
  72. scope = self.modelParametersDialog.model.createExpressionContextScopeForChildAlgorithm(self.modelParametersDialog.childId, processing_context)
  73. context.appendScope(scope)
  74. highlighted = scope.variableNames()
  75. context.setHighlightedVariables(highlighted)
  76. dlg = QgsExpressionBuilderDialog(None, str(self.leText.text()), self, 'generic', context)
  77. dlg.setWindowTitle(self.tr('Expression Based Input'))
  78. if dlg.exec_() == QDialog.Accepted:
  79. exp = QgsExpression(dlg.expressionText())
  80. if not exp.hasParserError():
  81. self.setValue(dlg.expressionText())
  82. def getValue(self):
  83. value = self.leText.text()
  84. for param in self.modelParametersDialog.model.parameterDefinitions():
  85. if isinstance(param, QgsProcessingParameterNumber):
  86. if "@" + param.name() == value.strip():
  87. return QgsProcessingModelChildParameterSource.fromModelParameter(param.name())
  88. for alg in list(self.modelParametersDialog.model.childAlgorithms().values()):
  89. for out in alg.algorithm().outputDefinitions():
  90. if isinstance(out, QgsProcessingOutputNumber) and f"@{alg.childId()}_{out.name()}" == value.strip():
  91. return QgsProcessingModelChildParameterSource.fromChildOutput(alg.childId(), out.outputName())
  92. try:
  93. return float(value.strip())
  94. except:
  95. return QgsProcessingModelChildParameterSource.fromExpression(self.leText.text())
  96. def setValue(self, value):
  97. if isinstance(value, QgsProcessingModelChildParameterSource):
  98. if value.source() == Qgis.ProcessingModelChildParameterSource.ModelParameter:
  99. self.leText.setText('@' + value.parameterName())
  100. elif value.source() == Qgis.ProcessingModelChildParameterSource.ChildOutput:
  101. name = f"{value.outputChildId()}_{value.outputName()}"
  102. self.leText.setText(name)
  103. elif value.source() == Qgis.ProcessingModelChildParameterSource.Expression:
  104. self.leText.setText(value.expression())
  105. else:
  106. self.leText.setText(str(value.staticValue()))
  107. else:
  108. self.leText.setText(str(value))
  109. class NumberInputPanel(NUMBER_BASE, NUMBER_WIDGET):
  110. """
  111. Number input panel for use outside the modeler - this input panel
  112. contains a user friendly spin box for entering values.
  113. """
  114. hasChanged = pyqtSignal()
  115. def __init__(self, param):
  116. super().__init__(None)
  117. self.setupUi(self)
  118. self.layer = None
  119. self.spnValue.setExpressionsEnabled(True)
  120. self.param = param
  121. if self.param.dataType() == QgsProcessingParameterNumber.Integer:
  122. self.spnValue.setDecimals(0)
  123. else:
  124. # Guess reasonable step value
  125. if self.param.maximum() is not None and self.param.minimum() is not None:
  126. try:
  127. self.spnValue.setSingleStep(self.calculateStep(float(self.param.minimum()), float(self.param.maximum())))
  128. except:
  129. pass
  130. if self.param.maximum() is not None:
  131. self.spnValue.setMaximum(self.param.maximum())
  132. else:
  133. self.spnValue.setMaximum(999999999)
  134. if self.param.minimum() is not None:
  135. self.spnValue.setMinimum(self.param.minimum())
  136. else:
  137. self.spnValue.setMinimum(-999999999)
  138. self.allowing_null = False
  139. # set default value
  140. if param.flags() & QgsProcessingParameterDefinition.FlagOptional:
  141. self.spnValue.setShowClearButton(True)
  142. min = self.spnValue.minimum() - 1
  143. self.spnValue.setMinimum(min)
  144. self.spnValue.setValue(min)
  145. self.spnValue.setSpecialValueText(self.tr('Not set'))
  146. self.allowing_null = True
  147. if param.defaultValue() is not None:
  148. self.setValue(param.defaultValue())
  149. if not self.allowing_null:
  150. try:
  151. self.spnValue.setClearValue(float(param.defaultValue()))
  152. except:
  153. pass
  154. elif self.param.minimum() is not None and not self.allowing_null:
  155. try:
  156. self.setValue(float(self.param.minimum()))
  157. if not self.allowing_null:
  158. self.spnValue.setClearValue(float(self.param.minimum()))
  159. except:
  160. pass
  161. elif not self.allowing_null:
  162. self.setValue(0)
  163. self.spnValue.setClearValue(0)
  164. # we don't show the expression button outside of modeler
  165. self.layout().removeWidget(self.btnSelect)
  166. sip.delete(self.btnSelect)
  167. self.btnSelect = None
  168. if not self.param.isDynamic():
  169. # only show data defined button for dynamic properties
  170. self.layout().removeWidget(self.btnDataDefined)
  171. sip.delete(self.btnDataDefined)
  172. self.btnDataDefined = None
  173. else:
  174. self.btnDataDefined.init(0, QgsProperty(), self.param.dynamicPropertyDefinition())
  175. self.btnDataDefined.registerEnabledWidget(self.spnValue, False)
  176. self.spnValue.valueChanged.connect(lambda: self.hasChanged.emit())
  177. def setDynamicLayer(self, layer):
  178. try:
  179. self.layer = self.getLayerFromValue(layer)
  180. self.btnDataDefined.setVectorLayer(self.layer)
  181. except:
  182. pass
  183. def getLayerFromValue(self, value):
  184. context = createContext()
  185. if isinstance(value, QgsProcessingFeatureSourceDefinition):
  186. value, ok = value.source.valueAsString(context.expressionContext())
  187. if isinstance(value, str):
  188. value = QgsProcessingUtils.mapLayerFromString(value, context)
  189. if value is None or not isinstance(value, QgsMapLayer):
  190. return None
  191. # need to return layer with ownership - otherwise layer may be deleted when context
  192. # goes out of scope
  193. new_layer = context.takeResultLayer(value.id())
  194. # if we got ownership, return that - otherwise just return the layer (which may be owned by the project)
  195. return new_layer if new_layer is not None else value
  196. def getValue(self):
  197. if self.btnDataDefined is not None and self.btnDataDefined.isActive():
  198. return self.btnDataDefined.toProperty()
  199. elif self.allowing_null and self.spnValue.value() == self.spnValue.minimum():
  200. return None
  201. else:
  202. return self.spnValue.value()
  203. def setValue(self, value):
  204. try:
  205. self.spnValue.setValue(float(value))
  206. except:
  207. return
  208. def calculateStep(self, minimum, maximum):
  209. value_range = maximum - minimum
  210. if value_range <= 1.0:
  211. step = value_range / 10.0
  212. # round to 1 significant figrue
  213. return round(step, -int(math.floor(math.log10(step))))
  214. else:
  215. return 1.0
  216. class DistanceInputPanel(NumberInputPanel):
  217. """
  218. Distance input panel for use outside the modeler - this input panel
  219. contains a label showing the distance unit.
  220. """
  221. def __init__(self, param):
  222. super().__init__(param)
  223. self.label = QLabel('')
  224. self.units_combo = QComboBox()
  225. self.base_units = QgsUnitTypes.DistanceUnknownUnit
  226. for u in (QgsUnitTypes.DistanceMeters,
  227. QgsUnitTypes.DistanceKilometers,
  228. QgsUnitTypes.DistanceFeet,
  229. QgsUnitTypes.DistanceMiles,
  230. QgsUnitTypes.DistanceYards):
  231. self.units_combo.addItem(QgsUnitTypes.toString(u), u)
  232. label_margin = self.fontMetrics().width('X')
  233. self.layout().insertSpacing(1, int(label_margin / 2))
  234. self.layout().insertWidget(2, self.label)
  235. self.layout().insertWidget(3, self.units_combo)
  236. self.layout().insertSpacing(4, int(label_margin / 2))
  237. self.warning_label = QLabel()
  238. icon = QgsApplication.getThemeIcon('mIconWarning.svg')
  239. size = max(24, self.spnValue.height() * 0.5)
  240. self.warning_label.setPixmap(icon.pixmap(icon.actualSize(QSize(size, size))))
  241. self.warning_label.setToolTip(self.tr('Distance is in geographic degrees. Consider reprojecting to a projected local coordinate system for accurate results.'))
  242. self.layout().insertWidget(4, self.warning_label)
  243. self.layout().insertSpacing(5, label_margin)
  244. self.setUnits(QgsUnitTypes.DistanceUnknownUnit)
  245. def setUnits(self, units):
  246. self.label.setText(QgsUnitTypes.toString(units))
  247. if QgsUnitTypes.unitType(units) != QgsUnitTypes.Standard:
  248. self.units_combo.hide()
  249. self.label.show()
  250. else:
  251. self.units_combo.setCurrentIndex(self.units_combo.findData(units))
  252. self.units_combo.show()
  253. self.label.hide()
  254. self.warning_label.setVisible(units == QgsUnitTypes.DistanceDegrees)
  255. self.base_units = units
  256. def setUnitParameterValue(self, value):
  257. units = QgsUnitTypes.DistanceUnknownUnit
  258. layer = self.getLayerFromValue(value)
  259. if isinstance(layer, QgsMapLayer):
  260. units = layer.crs().mapUnits()
  261. elif isinstance(value, QgsCoordinateReferenceSystem):
  262. units = value.mapUnits()
  263. elif isinstance(value, str):
  264. crs = QgsCoordinateReferenceSystem(value)
  265. if crs.isValid():
  266. units = crs.mapUnits()
  267. self.setUnits(units)
  268. def getValue(self):
  269. val = super().getValue()
  270. if isinstance(val, float) and self.units_combo.isVisible():
  271. display_unit = self.units_combo.currentData()
  272. return val * QgsUnitTypes.fromUnitToUnitFactor(display_unit, self.base_units)
  273. return val
  274. def setValue(self, value):
  275. try:
  276. self.spnValue.setValue(float(value))
  277. except:
  278. return