Skip to content
Permalink
Browse files

Make use of new processing parameter infrastructure

  • Loading branch information
m-kuhn authored and nyalldawson committed Mar 3, 2018
1 parent 2145865 commit a337d2050be447978ed147e0af51208d265de6b5
@@ -33,8 +33,11 @@
QgsProcessing,
QgsProcessingException,
QgsProcessingParameterDefinition,
QgsProcessingParameterType,
NULL)

from PyQt5.QtCore import QCoreApplication

from processing.algs.qgis.QgisAlgorithm import QgisFeatureBasedAlgorithm


@@ -141,6 +144,26 @@ def processFeature(self, feature, context, feedback):
self._row_number += 1
return [feature]

class ParameterFieldsMappingType(QgsProcessingParameterType):

def __init__(self):
super().__init__()

def create(self, name):
return FieldsMapper.ParameterFieldsMapping(name)

def metadata(self):
return {'widget_wrapper': 'processing.algs.qgis.ui.FieldsMappingPanel.FieldsMappingWidgetWrapper'}

def name(self):
return QCoreApplication.translate('Processing', 'Fields Mapper')

def id(self):
return 'Fields Mapper'

def description(self):
return QCoreApplication.translate('Processing', 'A mapping of field names to field type definitions and expressions. Used for the refactor fields algorithm.')

class ParameterFieldsMapping(QgsProcessingParameterDefinition):

def __init__(self, name, description='', parentLayerParameterName='INPUT'):
@@ -321,26 +321,16 @@ def loadAlgorithms(self):
def load(self):
success = super().load()

from processing.core.Processing import Processing

if success:
Processing.registerParameter(
'Fields Mapper',
self.fieldMappingParameterName,
parameter=FieldsMapper.ParameterFieldsMapping,
metadata={'widget_wrapper': 'processing.algs.qgis.ui.FieldsMappingPanel.FieldsMappingWidgetWrapper'}
)
self.parameterTypeFieldsMapping = FieldsMapper.ParameterFieldsMappingType()
QgsApplication.instance().processingRegistry().addParameterType(self.parameterTypeFieldsMapping)

return success

def unload(self):
super().unload()
from processing.core.Processing import Processing
Processing.unregisterParameter(self.fieldMappingParameterName)

def createParameter(self, type, name):
if type == 'fields_mapping':
return FieldsMapper.ParameterFieldsMapping(name)
QgsApplication.instance().processingRegistry().removeParameterType(self.parameterTypeFieldsMapping)

def supportsNonFileBasedOutput(self):
return True
@@ -45,8 +45,6 @@
QgsProcessingOutputMapLayer,
QgsProcessingOutputMultipleLayers)

from .parameters import initializeParameters

import processing
from processing.core.ProcessingConfig import ProcessingConfig
from processing.gui.MessageBarProgress import MessageBarProgress
@@ -69,7 +67,6 @@

class Processing(object):
BASIC_PROVIDERS = []
REGISTERED_PARAMETERS = dict()

@staticmethod
def activateProvider(providerOrName, activate=True):
@@ -100,7 +97,6 @@ def initialize():
if QgsApplication.processingRegistry().addProvider(p):
Processing.BASIC_PROVIDERS.append(p)
# And initialize
initializeParameters()
ProcessingConfig.initialize()
ProcessingConfig.readSettings()
RenderingStyles.loadStyles()
@@ -111,40 +107,6 @@ def deinitialize():
QgsApplication.processingRegistry().removeProvider(p)

Processing.BASIC_PROVIDERS = []
Processing.REGISTERED_PARAMETERS = dict()

@staticmethod
def registerParameter(id, name, parameter, metadata=dict(), description=None, exposeToModeller=True):
"""Register a new parameter.
The ``name`` is a human readable translated string, the ``parameter`` is a class type with the base class ``qgis.core.QgsProcessingParameterDefinition``,
the ``metadata`` is a dictionary with additional metadata, mainly used for widget wrappers.
"""
Processing.REGISTERED_PARAMETERS[id] = {
'name': name,
'parameter': parameter,
'metadata': metadata,
'description': description,
'exposeToModeller': exposeToModeller
}

@staticmethod
def unregisterParameter(name):
"""Unregister a registered parameter with the given name.
"""
del Processing.REGISTERED_PARAMETERS[name]

@staticmethod
def registeredParameters():
"""Returns a dict of registered parameters. The key of the dict is the id of the parameter.
Each entry is itself a dict with the keys
- name: The human readable name of the parameter
- parameter: The class of the parameter
- metadata: Additional metadata for the parameter, mainly used for widget wrappers
- description: A longer description for the parameter, suitable for tooltips etc
- exposeToModeller: A boolean indicating if the parameter is available as model parameter input
"""
return Processing.REGISTERED_PARAMETERS

@staticmethod
def runAlgorithm(algOrName, parameters, onFinish=None, feedback=None, context=None):
@@ -237,34 +237,3 @@ def getParameterFromString(s):
param = QgsProcessingParameters.parameterFromScriptCode(s)
if param:
return param


def initializeParameters():
from processing.core.Processing import Processing

Processing.registerParameter(PARAMETER_MAP_LAYER, QCoreApplication.translate('Processing', 'Map Layer'),
QgsProcessingParameterMapLayer,
description=QCoreApplication.translate('Processing', 'A generic map layer parameter, which accepts either vector or raster layers.'))
Processing.registerParameter(PARAMETER_BAND, QCoreApplication.translate('Processing', 'Raster Band'),
QgsProcessingParameterBand,
description=QCoreApplication.translate('Processing', 'A raster band parameter, for selecting an existing band from a raster source.'))
Processing.registerParameter(PARAMETER_EXPRESSION, QCoreApplication.translate('Processing', 'Expression'),
QgsProcessingParameterExpression,
description=QCoreApplication.translate('Processing', 'A QGIS expression parameter, which presents an expression builder widget to users.'))
Processing.registerParameter(PARAMETER_RASTER, QCoreApplication.translate('Processing', 'Raster Layer'), QgsProcessingParameterRasterLayer,
description=QCoreApplication.translate('Processing', 'A raster layer parameter.'))
Processing.registerParameter(PARAMETER_TABLE, QCoreApplication.translate('Processing', 'Vector Layer'), QgsProcessingParameterVectorLayer,
description=QCoreApplication.translate('Processing', 'A vector feature parameter, e.g. for algorithms which operate on the features within a layer.'))

Processing.registerParameter(PARAMETER_VECTOR_DESTINATION, QCoreApplication.translate('Processing', 'Vector Destination'), QgsProcessingParameterVectorDestination, exposeToModeller=False)
Processing.registerParameter(PARAMETER_FILE_DESTINATION, QCoreApplication.translate('Processing', 'File Destination'), QgsProcessingParameterFileDestination, exposeToModeller=False)
Processing.registerParameter(PARAMETER_FOLDER_DESTINATION, QCoreApplication.translate('Processing', 'Folder Destination'), QgsProcessingParameterFolderDestination, exposeToModeller=False)
Processing.registerParameter(PARAMETER_RASTER_DESTINATION, QCoreApplication.translate('Processing', 'Raster Destination'), QgsProcessingParameterRasterDestination, exposeToModeller=False)
Processing.registerParameter(PARAMETER_STRING, QCoreApplication.translate('Processing', 'String'), QgsProcessingParameterString,
description=QCoreApplication.translate('Processing', 'A freeform string parameter.'))
Processing.registerParameter(PARAMETER_MULTIPLE, QCoreApplication.translate('Processing', 'Multiple Layers'), QgsProcessingParameterMultipleLayers,
description=QCoreApplication.translate('Processing', 'An input allowing selection of multiple sources, including multiple map layers or file sources.'))
Processing.registerParameter(PARAMETER_VECTOR, QCoreApplication.translate('Processing', 'Feature Source'), QgsProcessingParameterFeatureSource)
Processing.registerParameter(PARAMETER_NUMBER, QCoreApplication.translate('Processing', 'Number'), QgsProcessingParameterNumber,
description=QCoreApplication.translate('Processing', 'A numeric parameter, including float or integer values.'))
Processing.registeredParameters()
@@ -52,6 +52,7 @@
QgsProcessingUtils,
QgsProcessingModelAlgorithm,
QgsProcessingModelParameter,
QgsProcessingParameterType
)
from qgis.gui import QgsMessageBar
from processing.gui.HelpEditionDialog import HelpEditionDialog
@@ -154,11 +155,9 @@ def _dragEnterEvent(event):
event.ignore()

def _dropEvent(event):
from processing.core.Processing import Processing

if event.mimeData().hasText():
itemId = event.mimeData().text()
if itemId in Processing.registeredParameters():
if itemId in [param.id() for param in QgsApplication.instance().processingRegistry().parameterTypes()]:
self.addInputOfType(itemId, event.pos())
else:
alg = QgsApplication.processingRegistry().createAlgorithmById(itemId)
@@ -626,15 +625,15 @@ def fillInputsTree(self):
icon = QIcon(os.path.join(pluginPath, 'images', 'input.svg'))
parametersItem = QTreeWidgetItem()
parametersItem.setText(0, self.tr('Parameters'))
sortedParams = sorted(Processing.registeredParameters().items())
sortedParams = sorted(QgsApplication.instance().processingRegistry().parameterTypes(), key=lambda pt: pt.id())
for param in sortedParams:
if param[1]['exposeToModeller']:
if param.exposeToModeller():
paramItem = QTreeWidgetItem()
paramItem.setText(0, param[1]['name'])
paramItem.setData(0, Qt.UserRole, param[0])
paramItem.setText(0, param.name())
paramItem.setData(0, Qt.UserRole, param.id())
paramItem.setIcon(0, icon)
paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)
paramItem.setToolTip(0, param[1]['description'])
paramItem.setToolTip(0, param.description())
parametersItem.addChild(paramItem)
self.inputsTree.addTopLevelItem(parametersItem)
parametersItem.setExpanded(True)
@@ -28,7 +28,8 @@
import math

from qgis.gui import QgsExpressionLineEdit, QgsProjectionSelectionWidget
from qgis.core import (QgsSettings,
from qgis.core import (QgsApplication,
QgsSettings,
QgsProcessing,
QgsCoordinateReferenceSystem,
QgsProcessingParameterDefinition,
@@ -49,7 +50,8 @@
QgsProcessingParameterVectorLayer,
QgsProcessingParameterField,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterBand)
QgsProcessingParameterBand
)
from qgis.PyQt.QtCore import (Qt,
QByteArray,
QCoreApplication)
@@ -397,12 +399,9 @@ def accept(self):
isinstance(self.param, QgsProcessingParameterCrs)):
self.param = QgsProcessingParameterCrs(name, description, self.selector.crs().authid())
else:
from processing.core.Processing import Processing

param = Processing.registeredParameters()[self.paramType]

self.param = param['parameter'](name, description, None)
self.param.setMetadata(param['metadata'])
paramType = QgsApplication.instance().processingRegistry().parameterType(self.paramType)
self.param = paramType.create(name)
self.param.setMetadata(paramType.metadata())

if not self.requiredCheck.isChecked():
self.param.setFlags(self.param.flags() | QgsProcessingParameterDefinition.FlagOptional)

0 comments on commit a337d20

Please sign in to comment.
You can’t perform that action at this time.