Skip to content

Commit

Permalink
Merge pull request #11 from firstdayofjune/hausumringe
Browse files Browse the repository at this point in the history
Unique Layer-names and some refactoring
  • Loading branch information
firstdayofjune committed Jan 27, 2015
2 parents 79ea5a5 + 8523c69 commit 9e19dc4
Show file tree
Hide file tree
Showing 5 changed files with 161 additions and 66 deletions.
2 changes: 1 addition & 1 deletion ExportWMSasTif.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def export(self, clipped_raster_name = 'Investigation Area'):
"""
Put the steps necessary for the export together in one procedure
:return:
:rtype: None
:rtype:
"""

if not clipped_raster_name.isspace() and clipped_raster_name != self.export_name:
Expand Down
70 changes: 64 additions & 6 deletions LayerInteraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,21 @@ def hide_or_remove_layer(layer_name, mode='hide', iface = None):


def write_vector_layer_to_disk(vlayer, full_path):

"""
Write the given vector layer to disk.
:param vlayer: The vector layer that shall be written to disk
:type vlayer: QgsVectorLayer
:param full_path: The path and filename the layer shall be written to
:type full_path: str
:return:
:rtype:
"""
out_path, out_name = path.split(full_path)

if out_name.upper().endswith('.SHP'):
out_name = out_name[:-4]

if vlayer is not None and path.exists(out_path):
if vlayer is not None and vlayer.isValid() and path.exists(out_path):

if path.exists(path.join(out_path, out_name + '.shp')):
new_name = out_name
Expand Down Expand Up @@ -155,14 +163,13 @@ def trigger_edit_mode(iface, layer_name, trigger='on'):

# if the layer was found, it is activated and the editing and the adding of features will be triggered
if edit_layer is not None:
iface.setActiveLayer(edit_layer)

if trigger == 'on':
iface.actionToggleEditing().trigger()
edit_layer.startEditing()
iface.actionAddFeature().trigger()
elif trigger == 'off':
iface.actionAddFeature().trigger()
iface.actionToggleEditing().trigger()
edit_layer.commitChanges()

def get_wms_layer_list(iface, visibility='all'):
"""
Expand Down Expand Up @@ -198,4 +205,55 @@ def get_wms_layer_list(iface, visibility='all'):
if layer.type() == QgsMapLayer.RasterLayer:
active_wms_layers.append(layer)

return active_wms_layers
return active_wms_layers

def open_wms_as_raster(iface, wms_url_with_parameters, layer_name):
"""
Connect to a given wms-server and create a new wms-layer from the url.
:param iface:
:type iface:
:param wms_url_with_parameters: The url to the raster-layer in the form '{parameter=value&}*{url=http://url_to.wms/}'
:type wms_url_with_parameters: str
:param layer_name: Name of the new wms raster-layer
:type layer_name: str
:return:
:rtype:
"""
if iface is not None and wms_url_with_parameters and layer_name and not wms_url_with_parameters.isspace() and not layer_name.isspace():

rlayer = QgsRasterLayer(wms_url_with_parameters, layer_name, 'wms')

if not rlayer.isValid():
return None
else:
return rlayer

def zoom_to_layer(iface, layer_name):

if layer_name and not layer_name.isspace():

zoom_layer = find_layer_by_name(layer_name)

# if the shapefile was found set the layer active
if zoom_layer is not None:
iface.setActiveLayer(zoom_layer)
iface.actionZoomToLayer().trigger()

def biuniquify_layer_name(layer_name):

biunique_name = ''
if layer_name and not layer_name.isspace():

biunique_name = layer_name
suffix = 0

while(find_layer_by_name(biunique_name) is not None):
biunique_name = layer_name + str(suffix)
suffix += 1

return biunique_name





44 changes: 10 additions & 34 deletions OpenEQuarterMain.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def __init__(self, iface):
self.mainstay_process_dlg = MainstayProcess_dialog()
self.project_does_not_exist_dlg = ProjectDoesNotExist_dialog()
self.request_wms_url_dlg = RequestWmsUrl_dialog()
self.wms_url = ""
self.wms_url = 'crs=EPSG:3068&dpiMode=7&format=image/png&layers=0&styles=&url=http://fbinter.stadt-berlin.de/fb/wms/senstadt/k5'
self.confirm_selection_of_investigation_area_dlg = InvestigationAreaSelected_dialog()


Expand Down Expand Up @@ -169,13 +169,6 @@ def create_project_ifNotExists(self):
# trigger qgis "Save As"-function
iface.actionSaveProjectAs().trigger()

def enable_on_the_fly_projection(self):
"""
Enable on the fly projection in the current project.
:return:
:rtype:
"""
self.iface.mapCanvas().mapRenderer().setProjectionsEnabled(True)

def get_plugin_ifexists(self, plugin_name):
"""
Expand Down Expand Up @@ -285,30 +278,6 @@ def request_wms_layer_url(self):

self.wms_url = wms_url

def open_wms_as_raster(self):
"""
Use the url in self.wms_url to open and add a raster layer
:return:
:rtype:
"""
urlWithParams = 'crs=EPSG:3068&dpiMode=7&format=image/png&layers=0&styles=&url=http://fbinter.stadt-berlin.de/fb/wms/senstadt/k5'
rlayer = QgsRasterLayer(urlWithParams, self.clipping_raster_layer_name, 'wms')
#rlayer = QgsRasterLaayer(self.wms_url, 'Raster layer basis', 'wms')
if not rlayer.isValid():
print "Layer failed to load!"
else:
QgsMapLayerRegistry.instance().addMapLayer(rlayer)
self.iface.setActiveLayer(rlayer)

def open_add_wms_dialog(self):
"""
Open the common QGIS "Add WMS/WMTS Layer..."-dialog
:return:
:rtype:
"""
#ToDo use this or the open_wms_as_raster function
self.iface.actionAddWmsLayer().trigger()

def set_project_crs(self, crs):
"""
Set the project crs to the given crs and do a re-projection to keep the currently viewed extent focused
Expand Down Expand Up @@ -545,8 +514,15 @@ def start_or_continue_process(self):
if self.process_monitor.is_in_progress('building_shapes', 'raster_loaded'):
self.mainstay_process_dlg.go_to_page('building_shapes')
#self.request_wms_layer_url()
self.open_wms_as_raster()
self.process_monitor.update_progress('building_shapes', 'raster_loaded', True )
investigation_raster_layer = LayerInteraction.open_wms_as_raster(self.iface, self.wms_url, self.clipping_raster_layer_name)

if investigation_raster_layer is not None and investigation_raster_layer.isValid():
LayerInteraction.add_layer_to_registry(investigation_raster_layer)
self.iface.setActiveLayer(investigation_raster_layer)
self.process_monitor.update_progress('building_shapes', 'raster_loaded', True )

else:
self.iface.actionAddWmsLayer().trigger()

if self.step_queue[next_step] == 'extent_clipped' and not self.process_monitor.is_in_progress('investigation_area'):

Expand Down
109 changes: 85 additions & 24 deletions Tests/LayerInteraction_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ def __init__(self, testName, iface = QgisTestInterface()):
super(LayerInteraction_test, self).__init__(testName)
self.iface = iface
self.layer_list = []
self.valid_wms_url = 'crs=EPSG:3068&dpiMode=7&format=image/png&layers=0&styles=&url=http://fbinter.stadt-berlin.de/fb/wms/senstadt/k5'

def setUp(self):
QgsApplication.setPrefixPath('/Applications/QGIS.app/Contents/MacOS', True)
Expand Down Expand Up @@ -40,7 +41,7 @@ def test_create_temporary_layer(self):
layer_name = layer_type = None
self.assertIsNone(LayerInteraction.create_temporary_layer(layer_name,layer_type), 'An error occured when trying to create a layer with an invalid type')

layer_name = 'MyLayer'
layer_name = LayerInteraction.biuniquify_layer_name('MyLayer')
layer_type = 'Shapefile'
crs_name = ''
layer = LayerInteraction.create_temporary_layer(layer_name,layer_type, crs_name)
Expand All @@ -57,7 +58,7 @@ def test_create_temporary_layer(self):
self.assertEqual(layer.crs().toProj4(), '')

def test_add_layer_to_registry(self):
layer_name = 'this_layer_was_added_for_testing_purpose'
layer_name = LayerInteraction.biuniquify_layer_name('this_layer_was_added_for_testing_purpose')

layer = QgsVectorLayer('Polygon?crs=EPSG:3857', layer_name, 'memory', False)

Expand Down Expand Up @@ -88,9 +89,9 @@ def test_find_layer_by_name(self):

reg = QgsMapLayerRegistry.instance()

v1_name = 'layer1'
v2_name = 'layer2'
v3_name = 'layer3'
v1_name = LayerInteraction.biuniquify_layer_name('layer1')
v2_name = LayerInteraction.biuniquify_layer_name('layer2')
v3_name = LayerInteraction.biuniquify_layer_name('layer3')
reg.addMapLayer(QgsVectorLayer('Polygon?crs=EPSG:3857', v1_name, 'memory', False))
self.layer_list.append(v1_name)
reg.addMapLayer(QgsVectorLayer('Point?crs=EPSG:3857', v2_name, 'memory', False))
Expand Down Expand Up @@ -131,7 +132,7 @@ def test_hide_or_remove_layer(self):
iface = self.iface

reg = QgsMapLayerRegistry.instance()
v1_name = 'layer1'
v1_name = LayerInteraction.biuniquify_layer_name('layer1')

reg.addMapLayer(QgsVectorLayer('Polygon?crs=EPSG:3857', v1_name, 'memory', False))
self.layer_list.append(v1_name)
Expand All @@ -145,7 +146,7 @@ def test_hide_or_remove_layer(self):

def test_write_vector_layer_to_disk(self):

v_layer_name = 'MyWriteTestLayer'
v_layer_name = LayerInteraction.biuniquify_layer_name('MyWriteTestLayer')
v_layer = QgsVectorLayer('Polygon?crs=EPSG:3857', v_layer_name, 'memory', False)

test_path = path.join('/', 'Users', 'VPTtutor', 'Desktop', v_layer_name)
Expand Down Expand Up @@ -193,35 +194,31 @@ def test_trigger_edit_mode(self):
iface = self.iface

reg = QgsMapLayerRegistry.instance()
edit_layer = 'MylayerForEditing'
reg.addMapLayer(QgsVectorLayer('Polygon?crs=EPSG:3857', edit_layer, 'memory', False))
self.layer_list.append(edit_layer)
edit_layer_name = LayerInteraction.biuniquify_layer_name('MylayerForEditing')
edit_layer = QgsVectorLayer('Polygon?crs=EPSG:3857', edit_layer_name, 'memory', False)
reg.addMapLayer(edit_layer)
self.layer_list.append(edit_layer_name)

editing_triggered = [False]
iface.actionToggleEditing().triggered.connect(lambda who: self.checkSender(who, editing_triggered))
LayerInteraction.trigger_edit_mode(self.iface, edit_layer)
LayerInteraction.trigger_edit_mode(self.iface, edit_layer_name)

self.assertTrue(editing_triggered[1])
self.assertTrue(edit_layer.isEditable())

LayerInteraction.trigger_edit_mode(self.iface, edit_layer, 'off')
self.assertFalse(editing_triggered[2])


def checkSender(self, sender, edit_list):
edit_list.append(sender)
LayerInteraction.trigger_edit_mode(self.iface, edit_layer_name, 'off')
self.assertFalse(edit_layer.isEditable())

def test_get_wms_layer_list(self):
urlWithParams = 'crs=EPSG:3068&dpiMode=7&format=image/png&layers=0&styles=&url=http://fbinter.stadt-berlin.de/fb/wms/senstadt/k5'
wms_url_with_parameters = self.valid_wms_url
visibility = [True, False, True, True, True, False]

for i in range(0, len(visibility)):
layer_name = 'r{0}_visible:{1}'.format(i, visibility[i])
rlayer = QgsRasterLayer(urlWithParams, layer_name, 'wms')
layer_name = LayerInteraction.biuniquify_layer_name('r{0}_visible:{1}'.format(i, visibility[i]))
rlayer = QgsRasterLayer(wms_url_with_parameters, layer_name, 'wms')
self.assertTrue(rlayer.isValid(), layer_name + ' is not a valid raster layer')
QgsMapLayerRegistry.instance().addMapLayer(rlayer)
self.iface.legendInterface().setLayerVisible(rlayer, visibility[i])
self.layer_list.append(layer_name)

# get a list of all visible wms layers
expected_layers = {}
actual_layers = {}
visible_raster_layers = LayerInteraction.get_wms_layer_list(self.iface, 'visible')
Expand All @@ -236,7 +233,7 @@ def test_get_wms_layer_list(self):

self.assertDictEqual(expected_layers, actual_layers, 'The returned layers do not match the expected layers.\n\t Expected: {0}\n\t received: {1}.'.format(expected_layers, actual_layers))


# get a list of all invisible wms layers
expected_layers = {}
actual_layers = {}
invisible_raster_layers = LayerInteraction.get_wms_layer_list(self.iface, 'invisible')
Expand All @@ -251,6 +248,7 @@ def test_get_wms_layer_list(self):

self.assertDictEqual(expected_layers, actual_layers, 'The returned layers do not match the expected layers.\n\t Expected: {0}\n\t received: {1}.'.format(expected_layers, actual_layers))

# get a list of wms layers
expected_layers = {}
actual_layers = {}
invisible_raster_layers = LayerInteraction.get_wms_layer_list(self.iface, 'all')
Expand All @@ -264,7 +262,70 @@ def test_get_wms_layer_list(self):

self.assertDictEqual(expected_layers, actual_layers, 'The returned layers do not match the expected layers.\n\t Expected: {0}\n\t received: {1}.'.format(expected_layers, actual_layers))

def test_open_wms_as_raster(self):

valid_url = self.valid_wms_url
invalid_url = valid_url[7:46]
layer_name = 'Test_opening_a_raster_layer_from_wms_url'
returned_layer = None

returned_layer = LayerInteraction.open_wms_as_raster(self.iface, invalid_url, layer_name)
self.assertIsNone(returned_layer)

returned_layer = LayerInteraction.open_wms_as_raster(self.iface, valid_url, layer_name)
self.assertIsNotNone(returned_layer, 'Tried to open a layer with the url {} failed, but should have passed.'.format(valid_url))
self.assertTrue(returned_layer.isValid())
self.assertEqual(layer_name, returned_layer.name())

def test_zoom_to_layer(self):
zoom_layer_name = LayerInteraction.biuniquify_layer_name('Test_zoom_to_layer')
zoom_layer = QgsVectorLayer('Polygon?crs=EPSG:3857', zoom_layer_name, 'memory', False)
inactive_layer_name = LayerInteraction.biuniquify_layer_name('Layer_to_be_activated_and_deactivated_again')
inactive_layer = QgsVectorLayer('Polygon?crs=EPSG:3857', inactive_layer_name, 'memory', False)

self.layer_list.extend([zoom_layer_name, inactive_layer_name])

reg = QgsMapLayerRegistry.instance()
reg.addMapLayer(zoom_layer)
reg.addMapLayer(inactive_layer)

self.iface.setActiveLayer(inactive_layer)
self.assertEqual(inactive_layer, self.iface.activeLayer(), 'The layer \"{}\" has not been activated'.format(inactive_layer_name))
LayerInteraction.zoom_to_layer(self.iface, zoom_layer_name)

# if the passed zoom_layer was set active, it has been found and used as the basis for the zoom
# in that case, the formerly activated layer has to be inactive now!
self.assertEqual(zoom_layer, self.iface.activeLayer())
self.assertNotEqual(inactive_layer, self.iface.activeLayer())

def test_biuniquify_layer_name(self):
layer1_name = 'asdhhkhlu18927309hgdkaghdzuz7817982_unique'
layer2_name = 'asdhhkhlu18927309hgdkaghdzuz781712ziadgwz_unique'
layer3_name = ''

self.assertIsNone(LayerInteraction.find_layer_by_name(layer1_name), 'Default layer name (\"{}\") is not unique!'.format(layer1_name))
self.assertIsNone(LayerInteraction.find_layer_by_name(layer2_name), 'Default layer name (\"{}\") is not unique!'.format(layer2_name))

layer1 = QgsVectorLayer('Polygon?crs=EPSG:3857', layer1_name, 'memory', False)
layer2 = QgsVectorLayer('Polygon?crs=EPSG:3857', layer2_name, 'memory', False)

self.layer_list.extend([layer1_name, layer2_name])

reg = QgsMapLayerRegistry.instance()
reg.addMapLayer(layer1)
reg.addMapLayer(layer2)

self.assertEqual('', LayerInteraction.biuniquify_layer_name(''))
self.assertEqual('', LayerInteraction.biuniquify_layer_name(None))

# create a new unique name and add a layer with that name, to check the correctness of the functions while loop
layer3_name = LayerInteraction.biuniquify_layer_name(layer1_name)
self.assertEqual(layer1_name + '0', layer3_name)

layer3 = QgsVectorLayer('Polygon?crs=EPSG:3857', layer3_name, 'memory', False)
reg.addMapLayer(layer3)
self.layer_list.extend([layer3_name])

self.assertEqual(layer1_name +'1', LayerInteraction.biuniquify_layer_name(layer1_name))
self.assertEqual(layer1_name +'2', LayerInteraction.biuniquify_layer_name(layer1_name + str(2)))
self.assertEqual(layer2_name +'0', LayerInteraction.biuniquify_layer_name(layer2_name))
2 changes: 1 addition & 1 deletion ui_request_wms_url_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def setupUi(self, RequestWmsUrl_dialog):
self.wms_url.setCursor(QtGui.QCursor(QtCore.Qt.IBeamCursor))
self.wms_url.setInputMethodHints(QtCore.Qt.ImhUrlCharactersOnly)
self.wms_url.setText(_fromUtf8(""))
self.wms_url.setObjectName(_fromUtf8("wms_url"))
self.wms_url.setObjectName(_fromUtf8("valid_wms_url"))

self.retranslateUi(RequestWmsUrl_dialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), RequestWmsUrl_dialog.accept)
Expand Down

0 comments on commit 9e19dc4

Please sign in to comment.