Exemplo n.º 1
0
def parse_file_input(param: QgsProcessingParameterDefinition,
                     kwargs) -> Union[LiteralInput, ComplexInput]:
    """ Input is file
    """
    typ = param.type()
    if typ == 'file':
        if param.behavior() == QgsProcessingParameterFile.Folder:
            kwargs['data_type'] = 'string'
            return LiteralInput(**kwargs)
        ext = param.extension()
        if ext:
            mime = mimetypes.types_map.get(param.extension())
            if mime is not None:
                kwargs['supported_formats'] = [Format(mime)]
            kwargs['metadata'].append(
                Metadata('processing:extension', param.extension()))
        return ComplexInput(**kwargs)
    elif typ == 'fileDestination':
        extension = '.' + param.defaultFileExtension()
        kwargs['data_type'] = 'string'
        kwargs['metadata'].append(
            Metadata('processing:format',
                     mimetypes.types_map.get(extension, '')))
        return LiteralInput(**kwargs)
    elif typ == 'folderDestination':
        kwargs['data_type'] = 'string'
        return LiteralInput(**kwargs)
Exemplo n.º 2
0
def parse_layer_input(param: QgsProcessingParameterDefinition,
                      kwargs,
                      context: MapContext = None) -> LiteralInput:
    """ Layers input are passed as layer name

        We treat layer destination the same as input since they refer to
        layers ids in qgisProject
    """
    if isinstance(param, INPUT_LAYER_TYPES):
        kwargs['data_type'] = 'string'
        parse_allowed_layers(param, kwargs, context)
    elif isinstance(param, QgsProcessingParameterRasterDestination):
        kwargs['data_type'] = 'string'
        kwargs['metadata'].append(
            Metadata('processing:extension', param.defaultFileExtension()))
    elif isinstance(param, (QgsProcessingParameterVectorDestination,
                            QgsProcessingParameterFeatureSink)):
        kwargs['data_type'] = 'string'
        kwargs['metadata'].append(
            Metadata('processing:dataType', str(param.dataType())))
        kwargs['metadata'].append(
            Metadata('processing:extension', param.defaultFileExtension()))
    else:
        return None

    return LiteralInput(**kwargs)
Exemplo n.º 3
0
    def get_processes(self):
        def hello(request):
            pass

        hello_string = WPSProcess(
            hello,
            'hello_string',
            'Process Hello',
            inputs=[LiteralInput('the_name', 'Input name')],
            metadata=[
                Metadata('process metadata 1', 'http://example.org/1'),
                Metadata('process metadata 2', 'http://example.org/2')
            ])

        def hello(request):
            pass

        hello_integer = WPSProcess(hello,
                                   'hello_integer',
                                   'Process Hello',
                                   inputs=[
                                       LiteralInput(
                                           'the_number',
                                           'Input number',
                                           data_type='positiveInteger')
                                   ])
        return [hello_string, hello_integer]
Exemplo n.º 4
0
def parse_literal_input(param: QgsProcessingParameterDefinition,
                        kwargs) -> LiteralInput:
    """
    """
    typ = param.type()

    if typ == 'string':
        kwargs['data_type'] = 'string'
    elif typ == 'boolean':
        kwargs['data_type'] = 'boolean'
    elif typ == 'enum':
        options = param.options()
        kwargs['data_type'] = 'string'
        kwargs['allowed_values'] = options
        kwargs['max_occurs'] = len(options) if param.allowMultiple() else 1
        default_value = param.defaultValue()
        if default_value is not None:
            # XXX Values for processing enum are indices
            if isinstance(default_value, int):
                kwargs['default'] = options[default_value]
            elif isinstance(default_value, list):
                kwargs['default'] = options[default_value[0]]
            else:
                raise InvalidParameterValue('Unsupported default value: %s' %
                                            default_value)
    elif typ == 'number':
        kwargs['data_type'] = {
            QgsProcessingParameterNumber.Double: 'float',
            QgsProcessingParameterNumber.Integer: 'integer'
        }[param.dataType()]
        kwargs['allowed_values'] = [(param.minimum(), param.maximum())]
    elif typ == 'field':
        kwargs['data_type'] = 'string'
        kwargs['metadata'].append(
            Metadata('processing:parentLayerParameterName',
                     param.parentLayerParameterName()))
        kwargs['metadata'].append(
            Metadata(
                'processing:dataType', {
                    QgsProcessingParameterField.Any: 'Any',
                    QgsProcessingParameterField.Numeric: 'Numeric',
                    QgsProcessingParameterField.String: 'String',
                    QgsProcessingParameterField.DateTime: 'DateTime'
                }[param.dataType()]))
    elif typ == 'crs':
        kwargs['data_type'] = 'string'
    elif typ == 'band':
        kwargs['data_type'] = 'nonNegativeInteger'
    else:
        return None

    return LiteralInput(**kwargs)
Exemplo n.º 5
0
    def get_processes(self):
        def pr1():
            pass

        def pr2():
            pass

        return [
            WPSProcess(pr1,
                       'pr1',
                       'Process 1',
                       metadata=[Metadata('pr1 metadata')]),
            WPSProcess(pr2,
                       'pr2',
                       'Process 2',
                       metadata=[Metadata('pr2 metadata')])
        ]
Exemplo n.º 6
0
def parse_allowed_layers(param: QgsProcessingParameterDefinition, kwargs,
                         context: MapContext) -> None:
    """ Find candidate layers according to datatypes
    """
    typ = param.type()

    if typ == 'multilayer':
        num_inputs = param.minimumNumberInputs()
        kwargs['min_occurs'] = num_inputs if num_inputs >= 1 else 0
        kwargs['max_occurs'] = 20  # XXX arbitrary number

    datatypes = []
    if isinstance(param, QgsProcessingParameterLimitedDataTypes):
        datatypes = param.dataTypes()

    if not datatypes:
        if isinstance(param, INPUT_VECTOR_LAYER_TYPES):
            datatypes = [QgsProcessing.TypeVector]
        elif isinstance(param, INPUT_RASTER_LAYER_TYPES):
            datatypes = [QgsProcessing.TypeRaster]
        elif isinstance(param, QgsProcessingParameterMultipleLayers):
            datatypes = [param.layerType()]
        else:
            datatypes = [QgsProcessing.TypeMapLayer]

    kwargs['metadata'].append(
        Metadata('processing:dataTypes',
                 ','.join(SourceTypes[dtyp] for dtyp in datatypes)))

    # Nothing to do is there is no context
    if context is None:
        return

    project = context.project()

    def _is_allowed(lyr):
        if lyr.type() == QgsMapLayer.VectorLayer:
            geomtype = lyr.geometryType()
            return (geomtype == QgsWkbTypes.PointGeometry and QgsProcessing.TypeVectorPoint in datatypes) \
            or (geomtype == QgsWkbTypes.LineGeometry      and QgsProcessing.TypeVectorLine in datatypes)  \
            or (geomtype == QgsWkbTypes.PolygonGeometry   and QgsProcessing.TypeVectorPolygon in datatypes) \
            or QgsProcessing.TypeVectorAnyGeometry in datatypes \
            or QgsProcessing.TypeVector in datatypes \
            or QgsProcessing.TypeMapLayer in datatypes
        elif lyr.type() == QgsMapLayer.RasterLayer:
            return QgsProcessing.TypeRaster in datatypes \
                or QgsProcessing.TypeMapLayer in datatypes
        return False

    kwargs['allowed_values'] = [
        lyr.name() for lyr in project.mapLayers().values() if _is_allowed(lyr)
    ]

    # Set max occurs accordingly to
    if typ == 'multilayer':
        kwargs['max_occurs'] = len(kwargs['allowed_values'])
Exemplo n.º 7
0
def parse_input_definition(param: QgsProcessingParameterDefinition,
                           alg: QgsProcessingAlgorithm = None,
                           context: MapContext = None) -> WPSInput:
    """ Create WPS input from QgsProcessingParamDefinition

        see https://qgis.org/api/qgsprocessingparameters_8h_source.html#l01312
    """
    kwargs = {
        'identifier': param.name(),
        'title': param.name().replace('_', ' '),
        'abstract': param.description(),
        'metadata': [
            Metadata('processing:type', param.type()),
        ]
    }

    # Handle defaultValue
    # XXX In some case QVariant are
    # not converted to python object (SIP bug ?)
    # Problem stated in getting QgsProcessingParameterFeatureSource
    # from processing.core.parameters.getParameterFromString
    defaultValue = param.defaultValue()
    if isinstance(defaultValue, QVariant):
        defaultValue = None if defaultValue.isNull() else defaultValue.value()

    kwargs['default'] = defaultValue

    # Check for optional flags
    if _is_optional(param):
        kwargs['min_occurs'] = 0

    inp = parse_literal_input(param,kwargs) \
            or parse_layer_input(param,kwargs, context) \
            or parse_extent_input(param, kwargs) \
            or parse_file_input(param, kwargs)
    if inp is None:
        raise ProcessingInputTypeNotSupported("%s:'%s'" %
                                              (type(param), param.type()))

    parse_metadata(param, kwargs)

    return inp
Exemplo n.º 8
0
def parse_metadata(param: QgsProcessingParameterDefinition, kwargs) -> None:
    """ Parse freeform metadata
    """
    kwargs['metadata'].extend(
        Metadata('processing:meta:%s' % k, str(v))
        for k, v in param.metadata().items())