indentation update

This commit is contained in:
Juergen E. Fischer 2015-11-10 20:21:10 +00:00
parent b57d5abe36
commit 9a89408b72
26 changed files with 217 additions and 199 deletions

View File

@ -64,5 +64,5 @@ class QgsActionMenu : QMenu
signals:
void reinit();
};

View File

@ -1,7 +1,7 @@
/**
* @brief The QgsAdvancedDigitizingCanvasItem class draws the graphical elements of the CAD tools (@see QgsAdvancedDigitizingDock) on the map canvas.
*/
class QgsAdvancedDigitizingCanvasItem : QgsMapCanvasItem
{
%TypeHeaderCode

View File

@ -39,7 +39,7 @@ import os
try:
import processing
except ImportError, e:
except ImportError as e:
raise Exception("Processing must be installed and available in PYTHONPATH")
from processing.core.ProcessingConfig import ProcessingConfig
@ -47,7 +47,6 @@ from processing.core.ProcessingConfig import ProcessingConfig
from OTBUtils import OTBUtils
def adaptBinaryMorphologicalOperation(commands_list):
val = commands_list[commands_list.index("-filter") + 1]
@ -105,7 +104,7 @@ def adaptSplitImage(commands_list):
item = item.replace(".file", ".tif")
if item == "-out":
index = commands_list.index(item)
if "." not in os.path.basename(commands_list[index + 1] ):
if "." not in os.path.basename(commands_list[index + 1]):
commands_list[index + 1] = commands_list[index + 1][:-1] + ".tif" + commands_list[index + 1][-1]
commands_list2.append(item)
return commands_list2
@ -122,12 +121,13 @@ def adaptLSMSVectorization(commands_list):
item = item.replace(".file", ".shp")
if item == "-out":
index = commands_list.index(item)
if "." not in os.path.basename(commands_list[index + 1] ):
if "." not in os.path.basename(commands_list[index + 1]):
commands_list[index + 1] = commands_list[index + 1][:-1] + ".shp" + commands_list[index + 1][-1]
commands_list2.append(item)
return commands_list2
def adaptComputeImagesStatistics(commands_list):
"""
Ran by default, the extension of output file is .file. Replace it with ".xml"
@ -140,7 +140,7 @@ def adaptComputeImagesStatistics(commands_list):
commands_list2.append(item)
if item == "-out":
index = commands_list.index(item)
if "." not in os.path.basename(commands_list[index + 1] ):
if "." not in os.path.basename(commands_list[index + 1]):
commands_list[index + 1] = commands_list[index + 1][:-1] + ".xml" + commands_list[index + 1][-1]
return commands_list2
@ -159,7 +159,7 @@ def adaptKmzExport(commands_list):
item = item.replace(".file", ".kmz")
if item == "-out":
index = commands_list.index(item)
if "." not in os.path.basename(commands_list[index + 1] ):
if "." not in os.path.basename(commands_list[index + 1]):
commands_list[index + 1] = commands_list[index + 1][:-1] + ".kmz" + commands_list[index + 1][-1]
commands_list2.append(item)
@ -171,11 +171,10 @@ def adaptColorMapping(commands_list):
The output of this algorithm must be in uint8.
"""
indexInput = commands_list.index("-out")
commands_list[indexInput+1] = commands_list[indexInput+1] + " uint8"
commands_list[indexInput + 1] = commands_list[indexInput + 1] + " uint8"
return commands_list
def adaptStereoFramework(commands_list):
"""
Remove parameter and user value instead of giving None.
@ -186,7 +185,7 @@ def adaptStereoFramework(commands_list):
for item in commands_list:
if "None" in item:
index = commands_list2.index(item)
argumentToRemove = commands_list2[index-1]
argumentToRemove = commands_list2[index - 1]
commands_list2.remove(item)
commands_list2.remove(argumentToRemove)
#commands_list2.append(item)
@ -204,7 +203,7 @@ def adaptComputeConfusionMatrix(commands_list):
item = item.replace(".file", ".csv")
if item == "-out":
index = commands_list.index(item)
if "." not in os.path.basename(commands_list[index + 1] ):
if "." not in os.path.basename(commands_list[index + 1]):
commands_list[index + 1] = commands_list[index + 1][:-1] + ".csv" + commands_list[index + 1][-1]
commands_list2.append(item)
@ -222,12 +221,12 @@ def adaptRadiometricIndices(commands_list):
"ri" : "Soil:RI", "ci" : "Soil:CI", "bi" : "Soil:BI", "bi2" : "Soil:BI2"}
"""
# "laindvilog" : , "lairefl" : , "laindviformo" : ,
indices = {"ndvi" : "Vegetation:NDVI", "tndvi" : "Vegetation:TNDVI", "rvi" : "Vegetation:RVI", "savi" : "Vegetation:SAVI",
"tsavi" : "Vegetation:TSAVI", "msavi" : "Vegetation:MSAVI", "msavi2" : "Vegetation:MSAVI2", "gemi" : "Vegetation:GEMI",
"ipvi" : "Vegetation:IPVI",
"ndwi" : "Water:NDWI", "ndwi2" : "Water:NDWI2", "mndwi" :"Water:MNDWI" , "ndpi" : "Water:NDPI",
"ndti" : "Water:NDTI",
"ri" : "Soil:RI", "ci" : "Soil:CI", "bi" : "Soil:BI", "bi2" : "Soil:BI2"}
indices = {"ndvi": "Vegetation:NDVI", "tndvi": "Vegetation:TNDVI", "rvi": "Vegetation:RVI", "savi": "Vegetation:SAVI",
"tsavi": "Vegetation:TSAVI", "msavi": "Vegetation:MSAVI", "msavi2": "Vegetation:MSAVI2", "gemi": "Vegetation:GEMI",
"ipvi": "Vegetation:IPVI",
"ndwi": "Water:NDWI", "ndwi2": "Water:NDWI2", "mndwi": "Water:MNDWI", "ndpi": "Water:NDPI",
"ndti": "Water:NDTI",
"ri": "Soil:RI", "ci": "Soil:CI", "bi": "Soil:BI", "bi2": "Soil:BI2"}
for item in commands_list:
if item in indices:
commands_list[commands_list.index(item)] = indices[item]
@ -251,7 +250,7 @@ def adaptConnectedComponentSegmentation(commands_list):
for item in commands_list:
if "None" in item:
index = commands_list2.index(item)
argumentToRemove = commands_list2[index-1]
argumentToRemove = commands_list2[index - 1]
commands_list2.remove(item)
commands_list2.remove(argumentToRemove)
#commands_list2.append(item)
@ -289,25 +288,25 @@ def adaptTrainImagesClassifier(commands_list):
adaptGeoidSrtm(commands_list)
return commands_list
def adaptGeoidSrtm(commands_list):
"""
Check geoid file, srtm folder and given elevation and manage arguments.
"""
srtm, geoid = ckeckGeoidSrtmSettings()
if srtm :
if commands_list[0].endswith("ExtractROI") :
if srtm:
if commands_list[0].endswith("ExtractROI"):
commands_list.append("-mode.fit.elev.dem")
commands_list.append(srtm)
else :
else:
commands_list.append("-elev.dem")
commands_list.append(srtm)
if geoid :
if commands_list[0].endswith("ExtractROI") :
if geoid:
if commands_list[0].endswith("ExtractROI"):
commands_list.append("-mode.fit.elev.geoid")
commands_list.append(geoid)
else :
else:
commands_list.append("-elev.geoid")
commands_list.append(geoid)
@ -349,10 +348,10 @@ def adaptComputeOGRLayersFeaturesStatistics(commands_list):
def ckeckGeoidSrtmSettings():
folder = ProcessingConfig.getSetting(OTBUtils.OTB_SRTM_FOLDER)
if folder is None:
folder =""
folder = ""
filepath = ProcessingConfig.getSetting(OTBUtils.OTB_GEOID_FILE)
if filepath is None:
filepath =""
filepath = ""
return folder, filepath

View File

@ -33,6 +33,7 @@ import traceback
from contextlib import contextmanager
import shutil
@contextmanager
def tag(name, c):
c.append("<%s>" % name)
@ -42,20 +43,23 @@ def tag(name, c):
else:
c.append("</%s>" % name)
@contextmanager
def opentag(name, c):
c.append("<%s>" % name)
yield
def get_group( appInstance ) :
def get_group(appInstance):
tags = appInstance.GetDocTags()
sectionTags = ["Image Manipulation","Vector Data Manipulation", "Calibration","Geometry", "Image Filtering","Feature Extraction","Stereo","Learning","Segmentation"]
sectionTags = ["Image Manipulation", "Vector Data Manipulation", "Calibration", "Geometry", "Image Filtering", "Feature Extraction", "Stereo", "Learning", "Segmentation"]
for sectionTag in sectionTags:
for tag in tags:
if tag == sectionTag:
return sectionTag
return "Miscellaneous"
def set_OTB_log():
import logging
logger = logging.getLogger('OTBGenerator')
@ -69,6 +73,7 @@ def set_OTB_log():
logger.addHandler(cons)
logger.setLevel(logging.DEBUG)
def get_OTB_log():
import logging
logger = logging.getLogger('OTBGenerator')
@ -77,8 +82,9 @@ def get_OTB_log():
logger = logging.getLogger('OTBGenerator')
return logger
def indent(elem, level=0):
i = "\n" + level*" "
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
@ -94,17 +100,19 @@ def indent(elem, level=0):
set_OTB_log()
def get_parameters():
parameters = { getattr(otbApplication, each): each for each in dir(otbApplication) if 'ParameterType_' in each}
parameters = {getattr(otbApplication, each): each for each in dir(otbApplication) if 'ParameterType_' in each}
return parameters
def get_inverted_parameters():
"""
This function allows mapping otb parameters with processing parameters.
"""
parameters = { getattr(otbApplication, each): each for each in dir(otbApplication) if 'ParameterType_' in each}
parameters = {getattr(otbApplication, each): each for each in dir(otbApplication) if 'ParameterType_' in each}
inverted_parameters = { key: value for value, key in parameters.items() }
inverted_parameters = {key: value for value, key in parameters.items()}
inverted_parameters['ParameterType_Radius'] = 1
inverted_parameters['ParameterType_RAM'] = 1
inverted_parameters['ParameterType_ComplexInputImage'] = 9
@ -134,10 +142,11 @@ def get_inverted_parameters():
inverted_parameters_clone['ParameterType_RAM'] = 'ParameterNumber'
inverted_parameters_clone['ParameterType_InputProcessXML'] = 'ParameterFile'
inverted_parameters_clone['ParameterType_OutputProcessXML'] = 'ParameterFile'
inverted_parameters_clone['ParameterType_InputFilenameList'] = 'ParameterMultipleInput' # 'ParameterString'
inverted_parameters_clone['ParameterType_InputFilenameList'] = 'ParameterMultipleInput' # 'ParameterString'
return inverted_parameters_clone
def retrieve_module_name(param):
"""
returns the file parameter of the given processing parameter
@ -152,18 +161,19 @@ def retrieve_module_name(param):
if 'Output' in param:
exec("from processing.core.outputs import %s" % param)
return os.path.join(dir_p, "outputs.py")
except ImportError, e:
except ImportError as e:
print "Error parsing ", param
return None
def get_constructor_parameters_from_filename(py_file, param = ""):
def get_constructor_parameters_from_filename(py_file, param=""):
"""
Get all parameters from the constructor of the class param in the given py_file
"""
import ast
asto = ast.parse(open(py_file).read())
# get all class definitions corresponding to param given len(e1) should be 1
e1 = [each for each in asto.body if type(each) is ast.ClassDef and each.name == param]
e1 = [each for each in asto.body if isinstance(each, ast.ClassDef) and each.name == param]
# e1[0].body lists all functions from the class e1[0]
# e2 is a list of __init__ functions of class e1[0]
@ -185,12 +195,11 @@ def get_customize_app_functions():
py_file = os.path.join(os.path.dirname(__file__), "OTBSpecific_XMLcreation.py")
asto = ast.parse(open(py_file).read())
# get all class definitions corresponding to param given len(e1) should be 1
e1 = [each.name for each in asto.body if type(each) is ast.FunctionDef and each.name.startswith("get")]
e1 = [each.name for each in asto.body if isinstance(each, ast.FunctionDef) and each.name.startswith("get")]
return e1
def get_xml_description_from_application_name(our_app, criteria=None):
"""
creates an xml containing information about the given our_app
@ -226,17 +235,19 @@ def get_xml_description_from_application_name(our_app, criteria=None):
param_keys = filter(real_criteria, param_keys)
for param_key in param_keys:
if not param_key == "inxml" and not param_key == "outxml" :
if not param_key == "inxml" and not param_key == "outxml":
get_param_descriptor(app.text, app_instance, param_key, root)
indent(root)
return root
def get_the_choices(app_instance, our_descriptor, root):
choices = ET.SubElement(root, 'choices')
for choice in app_instance.GetChoiceKeys(our_descriptor):
choice_node = ET.SubElement(choices, 'choice')
choice_node.text = choice
def get_param_descriptor(appkey, app_instance, our_descriptor, root):
"""
update the root xml with the data of the parameter given by "our_descriptor"
@ -262,40 +273,39 @@ def get_param_descriptor(appkey, app_instance, our_descriptor, root):
if "default" in the_params:
try:
app_instance.GetParameterAsString(our_descriptor)
except RuntimeError, e:
except RuntimeError as e:
return
param = ET.SubElement(root, 'parameter')
attrs = {'source_parameter_type' : parameters[app_instance.GetParameterType(our_descriptor)]}
if appkey == "Segmentation" :
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_OutputFilename" :
attrs = {'source_parameter_type' : 'ParameterType_OutputVectorData'}
if appkey == "LSMSVectorization" :
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_OutputFilename" :
attrs = {'source_parameter_type' : 'ParameterType_OutputVectorData'}
if appkey == "SplitImage" :
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_OutputImage" :
attrs = {'source_parameter_type' : 'ParameterType_OutputFilename'}
attrs = {'source_parameter_type': parameters[app_instance.GetParameterType(our_descriptor)]}
if appkey == "Segmentation":
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_OutputFilename":
attrs = {'source_parameter_type': 'ParameterType_OutputVectorData'}
if appkey == "LSMSVectorization":
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_OutputFilename":
attrs = {'source_parameter_type': 'ParameterType_OutputVectorData'}
if appkey == "SplitImage":
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_OutputImage":
attrs = {'source_parameter_type': 'ParameterType_OutputFilename'}
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_ListView" :
if not appkey == "RadiometricIndices" :
attrs = {'source_parameter_type' : 'ParameterType_StringList'}
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_ListView":
if not appkey == "RadiometricIndices":
attrs = {'source_parameter_type': 'ParameterType_StringList'}
param_type = ET.SubElement(param, 'parameter_type', attrib=attrs)
param_type.text = inverted_parameters[parameters[app_instance.GetParameterType(our_descriptor)]]
if appkey == "Segmentation" :
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_OutputFilename" :
if appkey == "Segmentation":
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_OutputFilename":
param_type.text = "OutputVector"
if appkey == "LSMSVectorization" :
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_OutputFilename" :
if appkey == "LSMSVectorization":
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_OutputFilename":
param_type.text = "OutputVector"
if appkey == "SplitImage" :
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_OutputImage" :
if appkey == "SplitImage":
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_OutputImage":
param_type.text = "OutputFile"
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_ListView" :
if not appkey == "RadiometricIndices" :
if parameters[app_instance.GetParameterType(our_descriptor)] == "ParameterType_ListView":
if not appkey == "RadiometricIndices":
param_type.text = "ParameterString"
# {the_params = get_constructor_parameters_from_filename(file_parameter, mapped_parameter)
@ -410,6 +420,7 @@ def get_default_parameter_value(app_instance, param):
default_value = "True"
return default_value
def escape_html(par):
if 'Int' in par:
return '&lt;int32&gt;'
@ -423,9 +434,10 @@ def escape_html(par):
return '&lt;int32&gt;'
return '&lt;string&gt;'
def is_a_parameter(app_instance, param):
if app_instance.GetName() == "HaralickTextureExtraction" :
if param.startswith( "parameters." ):
if app_instance.GetName() == "HaralickTextureExtraction":
if param.startswith("parameters."):
return True
if '.' in param:
return False
@ -466,8 +478,8 @@ dl { border: 3px double #ccc; padding: 0.5em; } dt { float: left; clear: left; t
for param in params:
if is_a_parameter(app_instance, param):
with tag('li', result):
result.append('<b>%s -%s</b> %s ' % ('[param]', param, escape_html(parameters[app_instance.GetParameterType(param)]) ))
result.append('%s. Mandatory: %s. Default Value: &quot;%s&quot;' %(app_instance.GetParameterDescription(param), str(app_instance.IsMandatory(param)), get_default_parameter_value(app_instance, param)))
result.append('<b>%s -%s</b> %s ' % ('[param]', param, escape_html(parameters[app_instance.GetParameterType(param)])))
result.append('%s. Mandatory: %s. Default Value: &quot;%s&quot;' % (app_instance.GetParameterDescription(param), str(app_instance.IsMandatory(param)), get_default_parameter_value(app_instance, param)))
choices_tags = [each for each in params if (not is_a_parameter(app_instance, each)) and '.' not in each]
for choice in choices_tags:
result.append('<b>%s -%s</b> %s %s. Mandatory: %s. Default Value: &quot;%s&quot;' % ('[choice]', choice, app_instance.GetParameterDescription(choice), ','.join(app_instance.GetChoiceKeys(choice)), str(app_instance.IsMandatory(choice)), get_default_parameter_value(app_instance, choice)))
@ -482,7 +494,7 @@ dl { border: 3px double #ccc; padding: 0.5em; } dt { float: left; clear: left; t
for param_tag in param_tags:
with tag('li', result):
result.append('<b>%s -%s</b> ' % ('[param]', param_tag))
result.append("%s %s. Mandatory: %s. Default Value: &quot;%s&quot;" % ( escape_html(parameters[app_instance.GetParameterType(param_tag)]) ,app_instance.GetParameterDescription(param_tag), str(app_instance.IsMandatory(param_tag)), get_default_parameter_value(app_instance, param_tag)))
result.append("%s %s. Mandatory: %s. Default Value: &quot;%s&quot;" % (escape_html(parameters[app_instance.GetParameterType(param_tag)]), app_instance.GetParameterDescription(param_tag), str(app_instance.IsMandatory(param_tag)), get_default_parameter_value(app_instance, param_tag)))
with tag('h2', result):
result.append('Limitations')
result.append(app_instance.GetDocLimitations())
@ -495,14 +507,15 @@ dl { border: 3px double #ccc; padding: 0.5em; } dt { float: left; clear: left; t
with tag('h2', result):
result.append('Example of use')
result.append(app_instance.GetHtmlExample())
if app_instance.GetName() == "HaralickTextureExtraction" :
if app_instance.GetName() == "HaralickTextureExtraction":
index = result.index("<b>[param] -parameters</b> &lt;string&gt; ")
del result[index +2]
del result[index +1]
del result[index + 2]
del result[index + 1]
del result[index]
del result[index -1]
del result[index - 1]
return "".join(result)
def get_list_from_node(myet, available_app):
all_params = []
for parameter in myet.iter('parameter'):
@ -530,6 +543,7 @@ def get_list_from_node(myet, available_app):
all_params.append(rebuild)
return all_params
def adapt_list_to_string(c_list):
a_list = c_list[1:]
if a_list[0] in ["ParameterVector", "ParameterMultipleInput"]:
@ -548,7 +562,7 @@ def adapt_list_to_string(c_list):
if a_list[0] in ["ParameterSelection"]:
pass
a_list[1]="-%s" % a_list[1]
a_list[1] = "-%s" % a_list[1]
def mystr(par):
if isinstance(par, list):
@ -575,32 +589,37 @@ def get_automatic_ut_from_xml_description(the_root):
raise Exception('Wrong client executable')
rebu = get_list_from_node(dom_model, appkey)
the_result = map(adapt_list_to_string,rebu)
the_result = map(adapt_list_to_string, rebu)
ut_command = cliName + " " + " ".join(the_result)
return ut_command
except Exception, e:
except Exception as e:
ET.dump(dom_model)
raise
def list_reader(file_name, version):
tree = ET.parse(file_name)
root = tree.getroot()
nodes = [each.text for each in root.findall("./version[@id='%s']/app_name" % version)]
return nodes
def get_otb_version():
#TODO Find a way to retrieve installed otb version, force exception and parse otb-X.XX.X ?
# return "3.18"
return "5.0"
def get_white_list():
nodes = list_reader("white_list.xml",get_otb_version())
nodes = list_reader("white_list.xml", get_otb_version())
return nodes
def get_black_list():
nodes = list_reader("black_list.xml",get_otb_version())
nodes = list_reader("black_list.xml", get_otb_version())
return nodes
def create_xml_descriptors():
import os
if not os.path.exists("description"):
@ -628,7 +647,7 @@ def create_xml_descriptors():
try:
ut_command = get_automatic_ut_from_xml_description(each_dom)
except:
logger.error("Unit test for command %s must be fixed: %s" % (available_app , traceback.format_exc()))
logger.error("Unit test for command %s must be fixed: %s" % (available_app, traceback.format_exc()))
else:
logger.warning("%s is not in white list." % available_app)
@ -643,11 +662,12 @@ def create_xml_descriptors():
try:
ut_command = get_automatic_ut_from_xml_description(the_root)
except:
logger.error("Unit test for command %s must be fixed: %s" % (available_app , traceback.format_exc()))
logger.error("Unit test for command %s must be fixed: %s" % (available_app, traceback.format_exc()))
# except Exception, e:
# logger.error(traceback.format_exc())
def create_html_description():
logger = get_OTB_log()
@ -662,16 +682,17 @@ def create_html_description():
ct = describe_app(app_instance)
fh.write(ct)
fh.close()
except Exception, e:
except Exception as e:
logger.error(traceback.format_exc())
sub_algo = [each for each in os.listdir("description") if "-" in each and ".xml" in each]
for key in sub_algo:
shutil.copy("description/doc/%s" % key.split("-")[0] + ".html","description/doc/%s" % key.split(".")[0] + ".html")
shutil.copy("description/doc/%s" % key.split("-")[0] + ".html", "description/doc/%s" % key.split(".")[0] + ".html")
if __name__ == "__main__":
# Prepare the environment
import sys, os
import sys
import os
from qgis.core import QgsApplication
from PyQt4.QtGui import QApplication
app = QApplication([])
@ -681,7 +702,6 @@ if __name__ == "__main__":
from processing.core.Processing import Processing
Processing.initialize()
import OTBSpecific_XMLcreation
# try:
# import processing
@ -690,7 +710,7 @@ if __name__ == "__main__":
try:
import otbApplication
except ImportError, e:
except ImportError as e:
raise Exception("OTB python plugins must be installed and available in PYTHONPATH")
create_xml_descriptors()
@ -699,4 +719,3 @@ if __name__ == "__main__":
# Exit applications
QgsApplication.exitQgis()
QApplication.exit()

View File

@ -33,14 +33,14 @@ __version__ = "3.8"
import copy
from processing.algs.otb.OTBUtils import (renameValueField,
remove_dependant_choices,
remove_other_choices,
remove_parameter_by_key,
defaultSplit,
split_by_choice,
defaultWrite,
remove_choice,
remove_independant_choices )
remove_dependant_choices,
remove_other_choices,
remove_parameter_by_key,
defaultSplit,
split_by_choice,
defaultWrite,
remove_choice,
remove_independant_choices)
def getBinaryMorphologicalOperation(available_app, original_dom_document):
@ -128,9 +128,6 @@ def getOrthoRectification(available_app, original_dom_document):
remove_independant_choices(the_root, 'outputs.mode', 'orthofit')
merged = copy.deepcopy(the_root)
split = split_by_choice(the_root, 'map')
the_list = []
@ -399,6 +396,7 @@ def getSmoothing(available_app, original_dom_document):
# the_list.append(split[key])
#return the_list
def getColorMapping(available_app, original_dom_document):
"""
Remove the option colortolabel
@ -454,7 +452,6 @@ def getColorMapping(available_app, original_dom_document):
return the_list
def getFusionOfClassifications(available_app, original_dom_document):
"""
Split by method of fusion of classification (dempstershafer, majorityvoting)
@ -484,7 +481,6 @@ def getTrainImagesClassifier(available_app, original_dom_document):
return the_list
def getLineSegmentDetection(available_app, original_dom_document):
"""
Delete GEOID and DEM parameter as they are not updated at the creation of the otb algorithms when you launch QGIS.
@ -498,7 +494,6 @@ def getLineSegmentDetection(available_app, original_dom_document):
return [the_root]
def getImageEnvelope(available_app, original_dom_document):
"""
Delete GEOID and DEM parameter as they are not updated at the creation of the otb algorithms when you launch QGIS.
@ -553,7 +548,6 @@ def getReadImageInfo(available_app, original_dom_document):
return [the_root]
def getComputeModulusAndPhase(available_app, original_dom_document):
"""
Split the application according the field nbinput.
@ -570,7 +564,7 @@ def getComputeModulusAndPhase(available_app, original_dom_document):
the_doc.find('longname').text = '%s (%s)' % (old_app_name, 'OneEntry')
defaultWrite('%s-%s' % (available_app, 'OneEntry'), the_doc)
the_list.append(the_doc)
else :
else:
the_doc = split[key]
old_app_name = the_doc.find('key').text
the_doc.find('key').text = '%s-%s' % (old_app_name, 'TwoEntries')
@ -610,7 +604,7 @@ def getConnectedComponentSegmentation(available_app, original_dom_document):
The values are picked from the settings.
"""
the_root = original_dom_document
deleteGeoidSrtm( the_root )
deleteGeoidSrtm(the_root)
defaultWrite(available_app, the_root)
return [the_root]
@ -621,7 +615,7 @@ def getKmzExport(available_app, original_dom_document):
The values are picked from the settings.
"""
the_root = original_dom_document
deleteGeoidSrtm( the_root )
deleteGeoidSrtm(the_root)
defaultWrite(available_app, the_root)
return [the_root]
@ -632,7 +626,7 @@ def getSuperimpose(available_app, original_dom_document):
The values are picked from the settings.
"""
the_root = original_dom_document
deleteGeoidSrtm( the_root )
deleteGeoidSrtm(the_root)
defaultWrite(available_app, the_root)
return [the_root]
@ -643,7 +637,7 @@ def getStereoFramework(available_app, original_dom_document):
The values are picked from the settings.
"""
the_root = original_dom_document
deleteGeoidSrtm( the_root )
deleteGeoidSrtm(the_root)
defaultWrite(available_app, the_root)
return [the_root]
@ -725,7 +719,7 @@ def getDespeckle(available_app, original_dom_document):
return the_list
def deleteGeoidSrtm(doc) :
def deleteGeoidSrtm(doc):
"""
Delete GEOID and DEM parameter as they are not updated at the creation of the otb algorithms when you launch QGIS.
The values are picked from the settings.

View File

@ -27,6 +27,7 @@ __revision__ = '$Format:%H$'
from pyspatialite import dbapi2 as sqlite
class DbError(Exception):
def __init__(self, message, query=None):
@ -36,19 +37,20 @@ class DbError(Exception):
def __str__(self):
return 'MESSAGE: %s\nQUERY: %s' % (self.message, self.query)
class GeoDB:
def __init__(self, uri=None):
self.uri = uri
self.dbname = uri.database()
try:
self.con = sqlite.connect(self.con_info())
except (sqlite.InterfaceError, sqlite.OperationalError) as e:
raise DbError(e.message)
self.has_spatialite = self.check_spatialite()
if not self.has_spatialite:
self.has_spatialite = self.init_spatialite()
@ -77,15 +79,15 @@ class GeoDB:
return False
finally:
self.con.close()
try:
self.con = sqlite.connect(self.con_info())
except (sqlite.InterfaceError, sqlite.OperationalError) as e:
raise DbError(e.message)
return self.check_spatialite()
def check_spatialite(self):
try:
c = self.con.cursor()
@ -99,13 +101,13 @@ class GeoDB:
self.has_geometry_columns_access = self.has_geometry_columns
return self.has_geometry_columns
def _exec_sql(self, cursor, sql):
try:
cursor.execute(sql)
except (sqlite.Error, sqlite.ProgrammingError, sqlite.Warning, sqlite.InterfaceError, sqlite.OperationalError) as e:
raise DbError(e.message, sql)
def _exec_sql_and_commit(self, sql):
"""Tries to execute and commit some action, on error it rolls
back the change.

View File

@ -357,10 +357,10 @@ class Processing:
progress = None
if kwargs is not None and "progress" in kwargs.keys():
progress = kwargs["progress"]
elif iface is not None :
progress = kwargs["progress"]
elif iface is not None:
progress = MessageBarProgress()
ret = runalg(alg, progress)
if ret:
if onFinish is not None:

View File

@ -160,6 +160,7 @@ class ParameterCrs(Parameter):
def getAsScriptCode(self):
return '##' + self.name + '=crs ' + str(self.default)
class ParameterDataObject(Parameter):
def getValueAsCommandLineParameter(self):
@ -206,6 +207,7 @@ class ParameterExtent(Parameter):
def getAsScriptCode(self):
return '##' + self.name + '=extent'
class ParameterFile(Parameter):
def __init__(self, name='', description='', isFolder=False, optional=True, ext=None):
@ -428,6 +430,7 @@ class ParameterMultipleInput(ParameterDataObject):
else:
return '##' + self.name + '=multiple vector'
class ParameterNumber(Parameter):
def __init__(self, name='', description='', minValue=None, maxValue=None,
@ -471,10 +474,10 @@ class ParameterNumber(Parameter):
except:
return False
def getAsScriptCode(self):
return '##' + self.name + '=number ' + str(self.default)
class ParameterRange(Parameter):
def __init__(self, name='', description='', default='0,1', optional=False):
@ -634,12 +637,13 @@ class ParameterString(Parameter):
def getValueAsCommandLineParameter(self):
return ('"' + unicode(self.value.replace(ParameterString.NEWLINE,
ParameterString.ESCAPED_NEWLINE)) + '"'
if self.value is not None else unicode(None))
ParameterString.ESCAPED_NEWLINE)) + '"'
if self.value is not None else unicode(None))
def getAsScriptCode(self):
return '##' + self.name + '=string ' + self.default
class ParameterTable(ParameterDataObject):
def __init__(self, name='', description='', optional=False):

View File

@ -144,9 +144,9 @@ class ConfigDialog(BASE, WIDGET):
else:
try:
setting.setValue(unicode(self.items[setting].text()))
except ValueError, e:
except ValueError as e:
QMessageBox.warning(self, self.tr('Wrong value'),
self.tr('Wrong value for parameter "%s":\n\n%s' %(setting.description, unicode(e))))
self.tr('Wrong value for parameter "%s":\n\n%s' % (setting.description, unicode(e))))
return
setting.save()
Processing.updateAlgsList()
@ -228,7 +228,6 @@ class SettingDelegate(QStyledItemDelegate):
else:
model.setData(index, editor.value(), Qt.EditRole)
def sizeHint(self, option, index):
return QSpinBox().sizeHint()

View File

@ -50,6 +50,7 @@ pluginPath = os.path.split(os.path.dirname(__file__))[0]
WIDGET, BASE = uic.loadUiType(
os.path.join(pluginPath, 'ui', 'DlgGetScriptsAndModels.ui'))
class GetScriptsAction(ToolboxAction):
def __init__(self):
@ -115,9 +116,9 @@ class GetScriptsAndModelsDialog(BASE, WIDGET):
SCRIPTS = 1
RSCRIPTS = 2
tr_disambiguation = { 0: 'GetModelsAction',
1: 'GetScriptsAction',
2: 'GetRScriptsAction' }
tr_disambiguation = {0: 'GetModelsAction',
1: 'GetScriptsAction',
2: 'GetRScriptsAction'}
def __init__(self, resourceType):
super(GetScriptsAndModelsDialog, self).__init__(iface.mainWindow())
@ -144,7 +145,7 @@ class GetScriptsAndModelsDialog(BASE, WIDGET):
self.buttonBox.accepted.connect(self.okPressed)
self.buttonBox.rejected.connect(self.cancelPressed)
self.tree.currentItemChanged.connect(self.currentItemChanged)
def popupError(self, error=None, url=None):
"""Popups an Error message bar for network errors."""
disambiguation = self.tr_disambiguation[self.resourceType]
@ -156,7 +157,7 @@ class GetScriptsAndModelsDialog(BASE, WIDGET):
widget.layout().addWidget(button)
iface.messageBar().pushWidget(widget, level=QgsMessageBar.CRITICAL, duration=5)
def grabHTTP(self, url, loadFunction, arguments=None):
"""Grab distant content via QGIS internal classes and QtNetwork."""
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
@ -166,7 +167,7 @@ class GetScriptsAndModelsDialog(BASE, WIDGET):
reply.finished.connect(partial(loadFunction, reply, arguments))
else:
reply.finished.connect(partial(loadFunction, reply))
def populateTree(self):
self.uptodateItem = QTreeWidgetItem()
self.uptodateItem.setText(0, self.tr('Installed'))
@ -181,7 +182,7 @@ class GetScriptsAndModelsDialog(BASE, WIDGET):
def treeLoaded(self, reply):
"""
update the tree of scripts/models whenever
update the tree of scripts/models whenever
HTTP request is finished
"""
QApplication.restoreOverrideCursor()
@ -219,7 +220,7 @@ class GetScriptsAndModelsDialog(BASE, WIDGET):
html += self.tr('<p><b>Version:</b> %s') % getDescription(ALG_VERSION, descriptions)
reply.deleteLater()
self.webView.setHtml(html)
def currentItemChanged(self, item, prev):
if isinstance(item, TreeItem):
url = self.urlBase + item.filename.replace(' ', '%20') + '.help'
@ -283,7 +284,7 @@ class GetScriptsAndModelsDialog(BASE, WIDGET):
QCoreApplication.processEvents()
url = self.urlBase + filename.replace(' ', '%20')
self.grabHTTP(url, self.storeFile, filename)
url += '.help'
self.grabHTTP(url, self.storeFile, filename + '.help')

View File

@ -117,14 +117,14 @@ class OutputSelectionPanel(BASE, WIDGET):
uri.setConnection(host, str(port), dbname, user, password)
uri.setDataSource(dlg.schema, dlg.table, "the_geom")
connInfo = uri.connectionInfo()
(success, user, passwd ) = QgsCredentials.instance().get(connInfo, None, None)
(success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
if success:
QgsCredentials.instance().put(connInfo, user, passwd)
self.leText.setText("postgis:" + uri.uri())
def saveToSpatialite(self):
fileFilter = self.output.tr('Spatialite files(*.sqlite)', 'OutputFile')
settings = QSettings()
if settings.contains('/Processing/LastOutputPath'):
path = settings.value('/Processing/LastOutputPath')
@ -152,7 +152,7 @@ class OutputSelectionPanel(BASE, WIDGET):
settings.setValue('/Processing/LastOutputPath',
os.path.dirname(fileName))
settings.setValue('/Processing/encoding', encoding)
uri = QgsDataSourceURI()
uri.setDatabase(fileName)
uri.setDataSource('', self.output.name.lower(), 'the_geom')
@ -195,7 +195,7 @@ class OutputSelectionPanel(BASE, WIDGET):
def selectDirectory(self):
lastDir = ''
dirName = QFileDialog.getExistingDirectory(self,self.tr('Select directory'),
dirName = QFileDialog.getExistingDirectory(self, self.tr('Select directory'),
lastDir, QFileDialog.ShowDirsOnly)
self.leText.setText(dirName)
@ -215,6 +215,4 @@ class OutputSelectionPanel(BASE, WIDGET):
else:
value = fileName
return value

View File

@ -54,6 +54,7 @@ class PostgisTableSelector(BASE, WIDGET):
self.connection = item.parent().text(0)
self.close()
class ConnectionItem(QtGui.QTreeWidgetItem):
connIcon = QtGui.QIcon(os.path.dirname(__file__) + '/../images/postgis.png')
@ -79,7 +80,7 @@ class ConnectionItem(QtGui.QTreeWidgetItem):
uri = QgsDataSourceURI()
uri.setConnection(host, str(port), database, user, passwd)
connInfo = uri.connectionInfo()
(success, user, passwd ) = QgsCredentials.instance().get(connInfo, None, None)
(success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
if success:
QgsCredentials.instance().put(connInfo, user, passwd)
geodb = GeoDB(host, int(port), database, user, passwd)
@ -89,4 +90,3 @@ class ConnectionItem(QtGui.QTreeWidgetItem):
item.setText(0, name)
item.setIcon(0, self.schemaIcon)
self.addChild(item)

View File

@ -128,6 +128,7 @@ class Algorithm():
params = []
for param in self.algorithm.parameters:
value = self.params[param.name]
def _toString(v):
if isinstance(v, (ValueFromInput, ValueFromOutput)):
return v.asPythonParameter()
@ -167,6 +168,7 @@ class ValueFromInput():
def asPythonParameter(self):
return self.name
class ValueFromOutput():
def __init__(self, alg="", output=""):
@ -687,7 +689,6 @@ class ModelerAlgorithm(GeoAlgorithm):
else:
raise WrongModelException(_tr('Error in model definition line: ') + '%s\n%s' % (line.strip(), traceback.format_exc()))
def toPython(self):
s = ['##%s=name' % self.name]
for param in self.inputs.values():
@ -713,6 +714,7 @@ class ModelerAlgorithm(GeoAlgorithm):
return '\n'.join(s)
def safeName(name):
validChars = 'abcdefghijklmnopqrstuvwxyz'
return ''.join(c for c in name.lower() if c in validChars)
return ''.join(c for c in name.lower() if c in validChars)

View File

@ -296,8 +296,7 @@ class ModelerDialog(BASE, WIDGET):
with codecs.open(filename, 'w', encoding='utf-8') as fout:
fout.write(text)
QMessageBox.information(self, self.tr('Model exported'),
self.tr('Model was correctly exported.'))
self.tr('Model was correctly exported.'))
def saveModel(self, saveAs):
if unicode(self.textGroup.text()).strip() == '' \

View File

@ -159,7 +159,6 @@ class ScriptAlgorithm(GeoAlgorithm):
else:
param = self.processInputParameterToken(tokens[1], tokens[0])
if param is not None:
self.addParameter(param)
elif out is not None:

View File

@ -45,6 +45,7 @@ def userFolder():
return unicode(QDir.toNativeSeparators(userDir))
def defaultOutputFolder():
folder = os.path.join(os.path.dirname(QgsApplication.qgisUserDbFilePath()),
"processing", "outputs")
@ -53,6 +54,7 @@ def defaultOutputFolder():
return unicode(QDir.toNativeSeparators(folder))
def isWindows():
return os.name == 'nt'

View File

@ -464,7 +464,7 @@ class VectorWriter:
self.isNotFileBased = True
uri = QgsDataSourceURI(self.destination[len(self.POSTGIS_LAYER_PREFIX):])
connInfo = uri.connectionInfo()
(success, user, passwd ) = QgsCredentials.instance().get(connInfo, None, None)
(success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
if success:
QgsCredentials.instance().put(connInfo, user, passwd)
else:
@ -472,7 +472,7 @@ class VectorWriter:
print uri.uri()
try:
db = postgis_utils.GeoDB(host=uri.host(), port=int(uri.port()),
dbname=uri.database(), user=user, passwd=passwd)
dbname=uri.database(), user=user, passwd=passwd)
except postgis_utils.DbError as e:
raise GeoAlgorithmExecutionException(
"Couldn't connect to database:\n%s" % e.message)
@ -486,12 +486,12 @@ class VectorWriter:
fields = [_toQgsField(f) for f in fields]
fieldsdesc = ",".join('%s %s' % (f.name(),
TYPE_MAP_POSTGIS_LAYER.get(f.type(), "VARCHAR"))
TYPE_MAP_POSTGIS_LAYER.get(f.type(), "VARCHAR"))
for f in fields)
_runSQL("CREATE TABLE %s.%s (%s)" % (uri.schema(), uri.table().lower(), fieldsdesc))
_runSQL("SELECT AddGeometryColumn('{schema}', '{table}', 'the_geom', {srid}, '{typmod}', 2)".format(
table=uri.table().lower(), schema=uri.schema(), srid=crs.authid().split(":")[-1],
table=uri.table().lower(), schema=uri.schema(), srid=crs.authid().split(":")[-1],
typmod=GEOM_TYPE_MAP[geometryType].upper()))
self.layer = QgsVectorLayer(uri.uri(), uri.table(), "postgres")
@ -515,13 +515,13 @@ class VectorWriter:
fields = [_toQgsField(f) for f in fields]
fieldsdesc = ",".join('%s %s' % (f.name(),
TYPE_MAP_SPATIALITE_LAYER.get(f.type(), "VARCHAR"))
TYPE_MAP_SPATIALITE_LAYER.get(f.type(), "VARCHAR"))
for f in fields)
_runSQL("DROP TABLE IF EXISTS %s" % uri.table().lower())
_runSQL("CREATE TABLE %s (%s)" % (uri.table().lower(), fieldsdesc))
_runSQL("SELECT AddGeometryColumn('{table}', 'the_geom', {srid}, '{typmod}', 2)".format(
table=uri.table().lower(), srid=crs.authid().split(":")[-1],
table=uri.table().lower(), srid=crs.authid().split(":")[-1],
typmod=GEOM_TYPE_MAP[geometryType].upper()))
self.layer = QgsVectorLayer(uri.uri(), uri.table(), "spatialite")
@ -545,7 +545,7 @@ class VectorWriter:
qgsfields.append(_toQgsField(field))
self.writer = QgsVectorFileWriter(self.destination, encoding,
qgsfields, geometryType, crs, OGRCodes[extension])
qgsfields, geometryType, crs, OGRCodes[extension])
def addFeature(self, feature):
if self.isNotFileBased:

View File

@ -99,7 +99,7 @@ class QgsComposerLegendWidget: public QgsComposerItemBaseWidget, private Ui::Qgs
/** Sets GUI according to state of mLegend*/
void setGuiElements();
/** update the enabling state of the filter by atlas button */
/** Update the enabling state of the filter by atlas button */
void updateFilterLegendByAtlasButton();
private:

View File

@ -238,13 +238,13 @@ bool QgsVectorLayerFeatureIterator::fetchFeature( QgsFeature& f )
if ( mRequest.filterType() == QgsFeatureRequest::FilterExpression && mProviderRequest.filterType() != QgsFeatureRequest::FilterExpression )
{
//filtering by expression, and couldn't do it on the provider side
mRequest.expressionContext()->setFeature( f );
if ( !mRequest.filterExpression()->evaluate( mRequest.expressionContext() ).toBool() )
{
//feature did not match filter
continue;
}
//filtering by expression, and couldn't do it on the provider side
mRequest.expressionContext()->setFeature( f );
if ( !mRequest.filterExpression()->evaluate( mRequest.expressionContext() ).toBool() )
{
//feature did not match filter
continue;
}
}
// update geometry

View File

@ -101,7 +101,7 @@ QgsExpressionBuilderWidget::QgsExpressionBuilderWidget( QWidget *parent )
QModelIndex firstItem = mProxyModel->index( 0, 0, QModelIndex() );
expressionTree->setCurrentIndex( firstItem );
lblAutoSave->setText("");
lblAutoSave->setText( "" );
}
@ -208,7 +208,7 @@ void QgsExpressionBuilderWidget::updateFunctionFileList( const QString& path )
{
QFileInfo info( mFunctionsPath + QDir::separator() + name );
if ( info.baseName() == "__init__" ) continue;
QListWidgetItem* item = new QListWidgetItem( QgsApplication::getThemeIcon("console/iconTabEditorConsole.png"), info.baseName() );
QListWidgetItem* item = new QListWidgetItem( QgsApplication::getThemeIcon( "console/iconTabEditorConsole.png" ), info.baseName() );
cmbFileNames->addItem( item );
}
if ( !cmbFileNames->currentItem() )

View File

@ -74,7 +74,7 @@ int QgsMapCanvasSnapper::snapToCurrentLayer( const QPoint& p, QList<QgsSnappingR
int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 );
if ( allResutInTolerance )
{
mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances);
mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances );
}
else if ( topologicalEditing == 0 )
{

View File

@ -73,7 +73,7 @@ QgsSymbolsListWidget::QgsSymbolsListWidget( QgsSymbolV2* symbol, QgsStyleV2* sty
groupsCombo->addItem( "" );
populateGroups();
QStringList groups = style->smartgroupNames();
Q_FOREACH( const QString& group, groups )
Q_FOREACH ( const QString& group, groups )
{
groupsCombo->addItem( group, QVariant( "smart" ) );
}
@ -130,11 +130,11 @@ QgsSymbolsListWidget::~QgsSymbolsListWidget()
void QgsSymbolsListWidget::setMapCanvas( QgsMapCanvas* canvas )
{
mMapCanvas = canvas;
Q_FOREACH( QgsUnitSelectionWidget* unitWidget, findChildren<QgsUnitSelectionWidget*>() )
Q_FOREACH ( QgsUnitSelectionWidget* unitWidget, findChildren<QgsUnitSelectionWidget*>() )
{
unitWidget->setMapCanvas( canvas );
}
Q_FOREACH( QgsDataDefinedButton* ddButton, findChildren<QgsDataDefinedButton*>() )
Q_FOREACH ( QgsDataDefinedButton* ddButton, findChildren<QgsDataDefinedButton*>() )
{
if ( ddButton->assistant() )
ddButton->assistant()->setMapCanvas( mMapCanvas );
@ -429,7 +429,7 @@ void QgsSymbolsListWidget::updateSymbolInfo()
{
updateSymbolColor();
Q_FOREACH( QgsDataDefinedButton* button, findChildren< QgsDataDefinedButton* >() )
Q_FOREACH ( QgsDataDefinedButton* button, findChildren< QgsDataDefinedButton* >() )
{
button->registerGetExpressionContextCallback( &_getExpressionContext, this );
}

View File

@ -19,20 +19,20 @@
#include "qgslogger.h"
QgsGrassUndoCommandChangeAttribute::QgsGrassUndoCommandChangeAttribute( QgsGrassProvider * provider, int fid, int lid, int field, int cat, bool deleteCat, bool deleteRecord )
: mProvider( provider )
, mFid(fid)
, mLid(lid)
, mField(field)
, mCat(cat)
, mDeleteCat(deleteCat)
, mDeleteRecord( deleteRecord )
: mProvider( provider )
, mFid( fid )
, mLid( lid )
, mField( field )
, mCat( cat )
, mDeleteCat( deleteCat )
, mDeleteRecord( deleteRecord )
{
Q_UNUSED(mField);
Q_UNUSED( mField );
}
void QgsGrassUndoCommandChangeAttribute::undo()
{
QgsDebugMsg( QString("mLid = %1 mField = %2, mCat = %3").arg(mLid).arg(mField).arg(mCat) );
QgsDebugMsg( QString( "mLid = %1 mField = %2, mCat = %3" ).arg( mLid ).arg( mField ).arg( mCat ) );
if ( mDeleteCat )
{
int realLine = mLid;
@ -40,7 +40,7 @@ void QgsGrassUndoCommandChangeAttribute::undo()
{
realLine = mProvider->mLayer->map()->newLids().value( mLid );
}
QgsDebugMsg( QString("realLine = %1").arg(realLine) );
QgsDebugMsg( QString( "realLine = %1" ).arg( realLine ) );
int type = mProvider->readLine( mProvider->mPoints, mProvider->mCats, realLine );
if ( type <= 0 )
@ -59,7 +59,7 @@ void QgsGrassUndoCommandChangeAttribute::undo()
mProvider->mLayer->map()->lockReadWrite();
int newLid = mProvider->rewriteLine( realLine, type, mProvider->mPoints, mProvider->mCats );
Q_UNUSED( newLid );
mProvider->mLayer->map()->newCats().remove(mFid);
mProvider->mLayer->map()->newCats().remove( mFid );
mProvider->mLayer->map()->unlockReadWrite();
}
}

View File

@ -154,7 +154,7 @@ void QgsConfigParserUtils::appendLayerBoundingBoxes( QDomElement& layerElem, QDo
layerElem.appendChild( ExGeoBBoxElement );
//layerElem.appendChild( bBoxElement );
}
//In case the number of advertised CRS is constrained
if ( constrainedCrsList.size() > 0 )
{
@ -179,15 +179,15 @@ void QgsConfigParserUtils::appendLayerBoundingBox( QDomElement& layerElem, QDomD
{
return;
}
QString version = doc.documentElement().attribute( "version" );
const QgsCoordinateReferenceSystem& crs = QgsCRSCache::instance()->crsByAuthId( crsText );
//transform the layers native CRS into CRS
QgsCoordinateTransform crsTransform( layerCRS, crs );
QgsRectangle crsExtent = crsTransform.transformBoundingBox( layerExtent );
//BoundingBox element
QDomElement bBoxElement = doc.createElement( "BoundingBox" );
if ( crs.isValid() )

View File

@ -38,7 +38,7 @@ class QgsConfigParserUtils
const QgsCoordinateReferenceSystem& layerCRS, const QStringList &crsList,
const QStringList& constrainedCrsList );
static void appendLayerBoundingBox( QDomElement& layerElem, QDomDocument& doc, const QgsRectangle& layerExtent,
const QgsCoordinateReferenceSystem& layerCRS, const QString& crsText );
const QgsCoordinateReferenceSystem& layerCRS, const QString& crsText );
/** Returns a list of supported EPSG coordinate system numbers from a layer*/
static QStringList createCRSListForLayer( QgsMapLayer* theMapLayer );

View File

@ -293,32 +293,32 @@ class TestQgsAtlasComposition(unittest.TestCase):
f1.initAttributes(2)
f1.setAttribute(0, 1)
f1.setAttribute(1, "Test label 1")
f1.setGeometry( QgsGeometry.fromPoint(QgsPoint(-0.638,48.954)) )
f1.setGeometry(QgsGeometry.fromPoint(QgsPoint(-0.638, 48.954)))
f2 = QgsFeature(2)
f2.initAttributes(2)
f2.setAttribute(0, 2)
f2.setAttribute(1, "Test label 2")
f2.setGeometry( QgsGeometry.fromPoint(QgsPoint(-1.682,48.550)) )
pr.addFeatures([f1,f2])
f2.setGeometry(QgsGeometry.fromPoint(QgsPoint(-1.682, 48.550)))
pr.addFeatures([f1, f2])
# categorized symbology
r = QgsCategorizedSymbolRendererV2( "attr", [ QgsRendererCategoryV2( 1, QgsMarkerSymbolV2.createSimple( {"color": "255,0,0"} ), "red" ),
QgsRendererCategoryV2( 2, QgsMarkerSymbolV2.createSimple( {"color": "0,0,255"} ), "blue" ) ] )
ptLayer.setRendererV2( r )
r = QgsCategorizedSymbolRendererV2("attr", [QgsRendererCategoryV2(1, QgsMarkerSymbolV2.createSimple({"color": "255,0,0"}), "red"),
QgsRendererCategoryV2(2, QgsMarkerSymbolV2.createSimple({"color": "0,0,255"}), "blue")])
ptLayer.setRendererV2(r)
QgsMapLayerRegistry.instance().addMapLayer(ptLayer)
# add the point layer to the map settings
layers = self.mapSettings.layers()
layers = [ ptLayer.id() ] + layers
self.mapSettings.setLayers( layers )
layers = [ptLayer.id()] + layers
self.mapSettings.setLayers(layers)
# add a legend
legend = QgsComposerLegend( self.mComposition )
legend.moveBy( 200, 100 )
legend = QgsComposerLegend(self.mComposition)
legend.moveBy(200, 100)
# sets the legend filter parameter
legend.setComposerMap( self.mAtlasMap )
legend.setLegendFilterOutAtlas( True )
legend.setComposerMap(self.mAtlasMap)
legend.setLegendFilterOutAtlas(True)
self.mComposition.addComposerLegend(legend)
self.mAtlas.beginRender()
@ -333,8 +333,8 @@ class TestQgsAtlasComposition(unittest.TestCase):
self.mAtlas.endRender()
# restore state
self.mapSettings.setLayers( [layers[1]] )
self.mComposition.removeComposerItem( legend )
self.mapSettings.setLayers([layers[1]])
self.mComposition.removeComposerItem(legend)
QgsMapLayerRegistry.instance().removeMapLayer(ptLayer.id())