-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathVisor_UI.py
755 lines (661 loc) · 31.9 KB
/
Visor_UI.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
# -*- coding:utf-8 -*-
"""
/***************************************************************************
VisorWMSDialog
A QGIS plugin
Visor de mapas disponibles en el servicio THREDDS del Instituto de Hidráulica Ambiental IH Cantabria
-------------------
begin : 2015-12-07
git sha : $Format:%H$
copyright : (C) 2015 by IH Cantabria
email : placeholder@ihcantabria.es
***************************************************************************/
/***************************************************************************
* *
* LICENSE *
* *
***************************************************************************/
"""
import os
import sys
import traceback
from threading import RLock
from PyQt5 import uic
from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtWidgets import QMessageBox, QStatusBar
from qgis.utils import iface
from qgis.core import QgsMessageLog
from qgis.core import QgsLayerTreeGroup, QgsProject, Qgis
from .libvisor import VisorController
from .libvisor.animation.AnimationFrame import AnimationFrame
from .libvisor.persistence import ServerDataPersistenceManager
from .libvisor.utilities.LayerLegendGroupifier import LayerGroupifier
from .libvisor.providersmanagers.BoundingBoxInfo import BoundingBox
FORM_CLASS, _ = uic.loadUiType(
os.path.join(os.path.dirname(__file__), "THREDDS_Explorer_dockwidget_base.ui")
)
class Visor(QtWidgets.QDockWidget, FORM_CLASS):
"""
UI manager for the visor.
This is the View component of the MVC pattern. Will manage
inputs from the user using a combobox to select which
dataset to use, provide a tree view of the elements
included in those datasets, and provide the basic configuration
options to download maps through WMS and WCS services using a
controller and show them in QGIS.
"""
groupAssignmentLock = RLock()
def __init__(self, showEmptyDatasetNodes=False, parent=None):
"""Constructor."""
super(Visor, self).__init__(parent)
self.setupUi(self)
self.controller = VisorController.VisorController()
self.controller.threddsServerMapObjectRetrieved.connect(
self.onNewDatasetsAvailable
)
self.controller.threddsDataSetUpdated.connect(self.onDataSetUpdated)
self.controller.mapImageRetrieved.connect(self.showNewImage)
self.controller.standardMessage.connect(self.postInformationMessageToUser)
self.controller.errorMessage.connect(self.postCriticalErrorToUser)
self.controller.mapInfoRetrieved.connect(self._onMapInfoReceivedFromController)
self.controller.batchDownloadFinished.connect(self.createLayerGroup)
self.showEmptyDatasetNodes = showEmptyDatasetNodes # TODO: self-explanatory...
self.combo_dataset_list.currentIndexChanged[str].connect(
self._onDataSetItemChanged
)
self.tree_widget.itemClicked.connect(self._onMapTreeWidgetItemClicked)
self.tree_widget.itemExpanded.connect(self._onMapTreeWidgetItemExpanded)
self.tabWidget.currentChanged.connect(self.runWhenTabChange)
# self.connect(self.combo_wcs_coverage, Signal("currentIndexChanged(const QString&)"),
# self._onCoverageSelectorItemChanged)
# self.connect(self.combo_wms_layer, Signal("currentIndexChanged(const QString&)"),
# self._onWMSLayerSelectorItemChanged)
# self.connect(self.combo_wms_style_type, Signal("currentIndexChanged(const QString&)"),
# self._onWMSStyleTypeSelectorItemChanged)
# self.connect(self.combo_wms_time, Signal("currentIndexChanged(int)"), self._onWMSFirstTimeChanged)
# self.connect(self.combo_wcs_time, Signal("currentIndexChanged(int)"), self._onWCSFirstTimeChanged)
self.combo_wcs_coverage.currentIndexChanged[str].connect(
self._onCoverageSelectorItemChanged
)
self.combo_wms_layer.currentIndexChanged[str].connect(
self._onWMSLayerSelectorItemChanged
)
self.combo_wms_style_type.currentIndexChanged[str].connect(
self._onWMSStyleTypeSelectorItemChanged
)
self.combo_wms_time.currentIndexChanged[int].connect(
self._onWMSFirstTimeChanged
)
self.combo_wcs_time.currentIndexChanged[int].connect(
self._onWCSFirstTimeChanged
)
self.button_req_map.clicked.connect(self._onbuttonReqMapClicked)
# self.actionToggleAlwaysOnTop.toggled.connect(self._onAlwaysOnTopPrefsChanged)
self.buttonManageServers.clicked.connect(self._onManageServersRequested)
self.button_req_animation.clicked.connect(self.toggleAnimationMenu)
# We add a status bar to this QDockWidget:
self.statusbar = QStatusBar()
self.gridLayout.addWidget(self.statusbar)
self.datasetInUse = None
self.uiAnimation = None
self.currentMap = None
self.wcsAvailableTimes = []
self.wmsAvailableTimes = []
self.firstRunThisSession = True
def show(self):
if iface and not iface.mainWindow().restoreDockWidget(self):
iface.mainWindow().addDockWidget(Qt.LeftDockWidgetArea, self)
super(Visor, self).show()
if self.firstRunThisSession:
self.firstRunChecks()
self.firstRunThisSession = False
# If no dataset is selected yet, we will assume the first
# thing the user will want to do is actually doing something
# related to the servers (pick one from a list, or add a new
# one) as there is little else that can be done at this point.
# So we present them the screen to do so...
if self.datasetInUse is None:
self._onManageServersRequested()
def firstRunChecks(self):
"""Convenience method to add any checks which should be performed
when the user opens the plug-in for first time (be advised this
is not the same as the first time the plug-in object is created,
which is on QGIS load)."""
pass
def runWhenTabChange(self):
"""Convenience method to add any actions to be performed at tab change."""
# Show warning for GDAL version, if needed.
self.checkGdalWindowWarning()
def checkGdalWindowWarning(self):
"""Method to show GDAL version warning if need be."""
# If OS is linux:
if sys.platform.startswith("linux"):
# Show warning only if WCS tab selected:
if self.tabWidget.currentIndex() == self.tabWidget.indexOf(self.tab_WCS):
self.createGDALWindowWarning()
def createGDALWindowWarning(self):
"""Check GDAL version. Versions < 2.0 had a bug regarding driver selection
for network resource retrieval (https://trac.osgeo.org/gdal/ticket/2696)."""
persistenceManager = ServerDataPersistenceManager.ServerStorageManager()
if persistenceManager.show_GDAL_error:
try:
from osgeo import gdal
if int(gdal.VersionInfo()) < 2000000:
# Show warning window, and allow for "don't show again":
message = "Your GDAL libraries version is outdated. Versions\n"
message += "under 2.0 are not guaranteed to work when\n"
message += "attempting to load WCS Layers.\nPlease update GDAL."
reply = QtWidgets.QMessageBox.question(
self,
"GDAL: Unsupported version found",
(message),
"Close",
"Don't show again",
)
# If requested to, record setting not to show warning again:
if reply == 1:
persistenceManager.show_GDAL_error = False
except ImportError:
# Show warning window, and allow for "don't show again":
message = "Your GDAL libraries version could not be read"
message += "Versions under 2.0 are not guaranteed to work when\n"
message += "attempting to load WCS Layers. If you have any issues,\n"
message += "please update GDAL."
reply = QtWidgets.QMessageBox.question(
self,
"GDAL: Unsupported version found",
(message),
"Close",
"Don't show again",
)
# If requested to, record setting not to show warning again:
if reply == 1:
persistenceManager.show_GDAL_error = False
def toggleAnimationMenu(self):
"""Shows (or hides) the animation menu elements,
and instantiate a controller.
It seems I can not directly hide elements,
but I can make another Widget in QDesigner and
create/add it to a layout here so... oh well..."""
if self.uiAnimation is None:
self.uiAnimation = AnimationFrame(parent=self)
self.uiAnimation.errorSignal.connect(self.postCriticalErrorToUser)
self.controller.mapInfoRetrieved.connect(
self.uiAnimation.setAnimationInformation
)
if None is not self.currentMap:
self.uiAnimation.setAnimationInformation(self.currentMap)
self.uiAnimation.show()
self.button_req_animation.setText("Hide animation menu <<")
else:
self.uiAnimation.hide()
self.uiAnimation = None
self.button_req_animation.setText("Show animation menu >>")
def clearData(self):
self.WMSBoundingBoxInfo.setText("No Bounding Box or CRS information available.")
self.WMS_northBound.setText("East: No info")
self.WMS_southBound.setText("West: No info")
self.WMS_eastBound.setText("North: No info")
self.WMS_westBound.setText("South: No info")
self.combo_wms_layer.clear()
self.combo_wms_style_type.clear()
self.combo_wms_style_palette.clear()
self.combo_wms_time.clear()
self.combo_wms_time_last.clear()
self.combo_wcs_coverage.clear()
self.combo_wcs_time.clear()
self.combo_wcs_time_last.clear()
self.WCSBoundingBoxInfo.setText("No Bounding Box or CRS information available.")
self.WCS_northBound.setText("East: No info")
self.WCS_southBound.setText("West: No info")
self.WCS_eastBound.setText("North: No info")
self.WCS_westBound.setText("South: No info")
# TODO: Unused (for now)
@pyqtSlot(bool)
def _onAlwaysOnTopPrefsChanged(self, newSettingBool):
"""Will change the alwaysontop window modifier to suit the user selection."""
self.setWindowFlags(self.windowFlags() ^ Qt.WindowStaysOnTopHint)
QtWidgets.QMainWindow.show(self)
@pyqtSlot(list, str)
def onNewDatasetsAvailable(self, inDataSets, serverName):
"""
A callback for when the dataSet displayed
needs to be updated.
:param inDataSets: list of DataSet objects which will be
available to the user.
:type inDataSets: list of threddsFetcherRecursos.DataSet objects.
:param serverName: An user-friendly representation of this server name.
:type serverName: str
"""
StringList = []
for dataSet in inDataSets:
StringList.append(dataSet.getName())
self.setWindowTitle("THREDDS Explorer - Connected: " + serverName)
self.combo_dataset_list.clear()
self.combo_dataset_list.addItems(StringList)
self.combo_dataset_list.setCurrentIndex(0)
self.postInformationMessageToUser(
"Dataset list updated: " + str(len(StringList)) + " elements."
)
self.clearData()
@pyqtSlot(str)
def postInformationMessageToUser(self, message):
"""
Will post information messages to the user through
the status bar.
:param message: String to use as message to
the user.
:type message: str
"""
self.statusbar.showMessage(message)
@pyqtSlot(str)
def postCriticalErrorToUser(self, errorString):
"""
To be used with non-recoverable error situations. Shows
a message box with the error message.
:param errorString: String to use as message to
the user.
:type errorString: str
"""
box = QMessageBox()
box.setText(errorString)
box.setIcon(QMessageBox.Critical)
box.exec_()
@pyqtSlot(str)
def _onDataSetItemChanged(self, stringItem):
"""Will receive notifications about this window dataSet
chosen combobox when the item selected changes."""
self.tree_widget.clear()
self.datasetInUse = self.controller.getSingleDataset(
self.combo_dataset_list.currentText()
)
if self.datasetInUse is None:
return # If no dataset is available to be shown, we will create no tree.
rootItem = self.tree_widget.invisibleRootItem()
newItem = QtWidgets.QTreeWidgetItem(rootItem, [self.datasetInUse.getName()])
rootItem.addChild(self._createHierarchy(self.datasetInUse, newItem))
def _createHierarchy(self, dataSet, treeItemParent):
"""Recursively creates a hierarchy of elements to populate
a treeWidgetItem from a given dataSet.
:param dataSet: DataSet object to create an hierarchy from.
:type dataset: threddsFetcherRecursos.DataSet
:param treeItemParent: Item which will be this
branch parent.
:type treeItemParent: QTreeWidgetItem"""
i = 0
itemsAlreadyAddedToElement = []
while i < treeItemParent.childCount():
child = treeItemParent.child(i)
if child.text(0) == "Loading..." or child.text(0) == "No subsets found":
treeItemParent.removeChild(child)
else:
itemsAlreadyAddedToElement.append(child)
i = i + 1
elementsAlreadyInTreeItemParent = [
x.text(0) for x in itemsAlreadyAddedToElement
]
if dataSet != None:
for mapElement in dataSet.getAvailableMapList():
if mapElement.getName() in elementsAlreadyInTreeItemParent:
continue
else:
newItem = QtWidgets.QTreeWidgetItem(
treeItemParent, [mapElement.getName()]
)
treeItemParent.addChild(newItem)
subSets = dataSet.getSubSets()
if len(subSets) == 0:
# We add a dummy element so the element open icon is created..
newItem = QtWidgets.QTreeWidgetItem(treeItemParent)
newItem.setText(0, "No subsets found")
treeItemParent.addChild(newItem)
else:
for dataset in subSets:
# If an item with the same name as this dataset is found as a subchild
# of the parent item, we will use it to build our tree. Otherwise, we
# create a new one and append it.
itemList = [
x
for x in itemsAlreadyAddedToElement
if x.text(0) == dataset.getName()
]
if itemList is None or len(itemList) == 0:
item = QtWidgets.QTreeWidgetItem(
treeItemParent, [dataset.getName()]
)
treeItemParent.addChild(self._createHierarchy(dataset, item))
else:
item = itemList[0]
self._createHierarchy(dataset, item)
else:
self.postCriticalErrorToUser(
"WARNING: Attempted to add a null dataset to view."
)
def _onMapTreeWidgetItemClicked(self, mQTreeWidgetItem, column):
"""
Will receive notifications about the MapTreeWidget
elements being clicked, so we can update the first
combobox of WMS/WCS tabs with the layer list.
"""
self.clearData()
self.postInformationMessageToUser("")
if None is mQTreeWidgetItem or None is mQTreeWidgetItem.parent():
return
self.controller.getMapObject(
str(mQTreeWidgetItem.text(0)),
str(mQTreeWidgetItem.parent().text(0)),
self.datasetInUse,
)
@pyqtSlot(object)
def _onMapInfoReceivedFromController(self, mapInfoObject):
# print("_onMapInfoReceivedFromController 1"+str(mapInfoObject))
self.currentMap = mapInfoObject
# print("_onMapInfoReceivedFromController 2"+str(self.currentMap))
if self.currentMap is not None:
# WCS Data update
self.currentCoverages = self.controller.getWCSCoverages(self.currentMap)
if self.currentCoverages is not None:
for c in self.currentCoverages:
self.combo_wcs_coverage.addItem(c.getName())
else:
self.combo_wcs_coverage.addItem("No data available.")
# WMS Data update
self.currentWMSMapInfo = self.controller.getWMSMapInfo(self.currentMap)
if self.currentWMSMapInfo is not None:
for l in self.currentWMSMapInfo.getLayers():
self.combo_wms_layer.addItem(l.getName())
else:
self.combo_wms_layer.addItem("No data available.")
def _onMapTreeWidgetItemExpanded(self, mQTreeWidgetItem):
"""
Once a set is expanded in the tree view we will attempt to
recover it's data and present it to the user.
"""
setToUpdate = self.datasetInUse.searchSubsetsByName(
str(mQTreeWidgetItem.text(0)), exactMatch=True
)
if setToUpdate is not None and len(setToUpdate) > 0:
self.controller.mapDataSet(setToUpdate[0], depth=1)
def onDataSetUpdated(self, dataSetObject):
"""
Will update the QTreeWidget to include the updated
dataset object and it's new data.
"""
if dataSetObject.getParent() is not None:
parent = self.tree_widget.findItems(
dataSetObject.getName(), Qt.MatchRecursive
)
self._createHierarchy(dataSetObject, parent[0])
@pyqtSlot(str)
def _onCoverageSelectorItemChanged(self, QStringItem):
"""
Will triger when the user selects a coverage name in
the combobox (or that list is updated) so the available
times to request to server are updated in the other
combobox for the WCS service.
"""
self.combo_wcs_time.clear()
if self.currentCoverages is not None:
coverageElement = [
x for x in self.currentCoverages if x.getName() == str(QStringItem)
]
if None is not coverageElement or len(coverageElement) > 0:
try:
self.wcsAvailableTimes = coverageElement[0].getTiempos()
self.combo_wcs_time.addItems(self.wcsAvailableTimes)
BBinfo = coverageElement[0].getBoundingBoxInfo()
self.WCSBoundingBoxInfo.setText(
"CRS = "
+ BBinfo.getCRS()
+ "\n\n Bounding Box information (decimal degrees):"
)
self.WCS_eastBound.setText(BBinfo.getEast())
self.WCS_westBound.setText(BBinfo.getWest())
self.WCS_northBound.setText(BBinfo.getNorth())
self.WCS_southBound.setText(BBinfo.getSouth())
except IndexError:
pass
@pyqtSlot(str)
def _onWMSLayerSelectorItemChanged(self, QStringItem):
self.combo_wms_style_type.clear()
self.combo_wms_style_palette.clear()
self.combo_wms_time.clear()
# Only one should be returned here.
if self.currentWMSMapInfo is not None:
layerSelectedObject = [
x
for x in self.currentWMSMapInfo.getLayers()
if x.getName() == str(QStringItem)
]
if layerSelectedObject is not None and len(layerSelectedObject) == 1:
self.wmsAvailableTimes = layerSelectedObject[0].getTimes()
self.combo_wms_time.addItems(self.wmsAvailableTimes)
self.wmsAvailableStyles = layerSelectedObject[0].getStyles()
self.combo_wms_style_type.addItems(
list(
{(x.getName().split(r"/"))[0] for x in self.wmsAvailableStyles}
)
)
BBinfo = layerSelectedObject[0].getBoundingBoxInfo()
self.WMSBoundingBoxInfo.setText(
"CRS = "
+ BBinfo.getCRS()
+ "\n\n Bounding Box information (decimal degrees):"
)
self.WMS_eastBound.setText(BBinfo.getEast())
self.WMS_westBound.setText(BBinfo.getWest())
self.WMS_northBound.setText(BBinfo.getNorth())
self.WMS_southBound.setText(BBinfo.getSouth())
@pyqtSlot(str)
def _onWMSStyleTypeSelectorItemChanged(self, qstringitem):
self.combo_wms_style_palette.clear()
self.combo_wms_style_palette.addItems(
list(
{
(x.getName().split(r"/"))[1]
for x in self.wmsAvailableStyles
if str(qstringitem) in x.getName()
}
)
)
@pyqtSlot(int)
def _onWCSFirstTimeChanged(self, position):
# print("self.wcsAvailableTimes"+str((sorted(self.wcsAvailableTimes))))
# print("WCS INDEX: "+str(position))
self.combo_wcs_time_last.clear()
# print self.wcsAvailableTimes[position:]
self.combo_wcs_time_last.addItems((sorted(self.wcsAvailableTimes))[position:])
@pyqtSlot(int)
def _onWMSFirstTimeChanged(self, position):
# print("self.wmsAvailableTimes"+str((sorted(self.wmsAvailableTimes))))
# print("WMS INDEX: "+str(position))
self.combo_wms_time_last.clear()
# print self.wmsAvailableTimes[position:]
self.combo_wms_time_last.addItems(self.wmsAvailableTimes[position:])
def _onbuttonReqMapClicked(self):
"""
Action to be performed when the user clicks the
button to request a new map to be displayed,
after selecting proper values in the rest of fields.
"""
self.postInformationMessageToUser("") # reset error display.
if self.tabWidget.currentIndex() == self.tabWidget.indexOf(self.tab_WCS):
try:
selectedBeginTimeIndex = self.wcsAvailableTimes.index(
self.combo_wcs_time.currentText()
)
selectedFinishTimeIndex = (
self.wcsAvailableTimes.index(self.combo_wcs_time_last.currentText())
+ 1
)
# We retrieve some information about the current selected map, useful
# to grab the actual CRS used by the map service. Should be changed if
# CRS is to be user-selectable later via dropdown menu or anything like
# that.
if self.currentCoverages is not None:
coverageElement = [
x
for x in self.currentCoverages
if x.getName() == str(self.combo_wcs_coverage.currentText())
]
if None is not coverageElement or len(coverageElement) > 0:
try:
try:
north = float(self.WCS_northBound.text())
south = float(self.WCS_southBound.text())
east = float(self.WCS_eastBound.text())
west = float(self.WCS_westBound.text())
except ValueError:
self.postCriticalErrorToUser(
"Bounding box values were not valid."
+ "\nCheck only decimal numbers are used\n(example: 12.44)"
)
return
# We retrieve the bounding box CRS information from the
# requested coverage, and get the actual box values
# from the UI.
BBinfo = coverageElement[0].getBoundingBoxInfo()
boundingBoxToDownload = BoundingBox()
boundingBoxToDownload.setCRS(BBinfo.getCRS())
boundingBoxToDownload.setEast(east)
boundingBoxToDownload.setWest(west)
boundingBoxToDownload.setNorth(north)
boundingBoxToDownload.setSouth(south)
self.controller.asyncFetchWCSImageFile(
self.currentMap,
self.combo_wcs_coverage.currentText(),
self.wcsAvailableTimes[
selectedBeginTimeIndex:selectedFinishTimeIndex
],
boundingBox=boundingBoxToDownload,
)
except IndexError:
pass
except Exception as exc:
# self.postInformationMessageToUser("There was an error retrieving the WCS data.")
# QgsMessageLog.logMessage(traceback.format_exc(), "THREDDS Explorer", QgsMessageLog.CRITICAL )
iface.messageBar().pushMessage(
"THREDDS Explorer",
"There was an error retrieving the WCS data.",
level=Qgis.Critical,
)
elif self.tabWidget.currentIndex() == self.tabWidget.indexOf(self.tab_WMS):
try:
selectedBeginTimeIndex = self.wmsAvailableTimes.index(
self.combo_wms_time.currentText()
)
selectedFinishTimeIndex = (
self.wmsAvailableTimes.index(self.combo_wms_time_last.currentText())
+ 1
)
style = (
self.combo_wms_style_type.currentText()
+ r"/"
+ self.combo_wms_style_palette.currentText()
)
# We retrieve some information about the current selected map, useful
# to grab the actual CRS used by the map service. Should be changed if
# CRS is to be user-selectable later via dropdown menu or anything like
# that.
# Only one should be returned here.
if self.currentWMSMapInfo is not None:
layerSelectedObject = [
x
for x in self.currentWMSMapInfo.getLayers()
if x.getName() == str(self.combo_wms_layer.currentText())
]
# We retrieve the bounding box CRS information from the
# requested coverage, and get the actual box values
# from the UI.
if None is not layerSelectedObject or len(layerSelectedObject) > 0:
try:
north = float(self.WMS_northBound.text())
south = float(self.WMS_southBound.text())
east = float(self.WMS_eastBound.text())
west = float(self.WMS_westBound.text())
except ValueError:
self.postCriticalErrorToUser(
"Bounding box values were not valid."
+ "\nCheck only decimal numbers are used\n(example: 12.44)"
)
return
BBinfo = layerSelectedObject[0].getBoundingBoxInfo()
boundingBoxToDownload = BoundingBox()
boundingBoxToDownload.setCRS(BBinfo.getCRS())
boundingBoxToDownload.setEast(east)
boundingBoxToDownload.setWest(west)
boundingBoxToDownload.setNorth(north)
boundingBoxToDownload.setSouth(south)
self.controller.asyncFetchWMSImageFile(
self.currentMap,
self.combo_wms_layer.currentText(),
style,
self.wmsAvailableTimes[
selectedBeginTimeIndex:selectedFinishTimeIndex
],
boundingBox=boundingBoxToDownload,
)
except Exception as exc:
print(exc)
# self.postInformationMessageToUser("There was an error retrieving the WMS data.")
# QgsMessageLog.logMessage(traceback.format_exc(), "THREDDS Explorer", QgsMessageLog.CRITICAL )
iface.messageBar().pushMessage(
"THREDDS Explorer",
"There was an error retrieving the WMS data.",
level=Qgis.Critical,
)
@pyqtSlot(list, str)
def createLayerGroup(self, layerList, groupName):
if layerList:
groupifier = LayerGroupifier(layerList, groupName)
groupifier.setSingleLayerSelectionModeInGroup(False)
groupifier.statusSignal.connect(
self.postInformationMessageToUser, Qt.DirectConnection
)
groupifier.groupifyComplete.connect(self._onNewLayerGroupGenerated)
groupifier.groupify()
else:
self.postInformationMessageToUser(
"There was a problem showing the time series."
)
@pyqtSlot(QgsLayerTreeGroup, list)
def _onNewLayerGroupGenerated(self, groupObject, layerList):
"""
Currently only used to show the first image of a newly created group
so the user knows when the operation finishes.
:param groupObject: The legend group object which was created.
:type groupObject: QgsLayerTreeGrupo
:param layerList: The layers which are held in the group object.
:type layerList: [QgsLayer]
"""
if (layerList[0]).isValid():
# iface.legendInterface().setLayerVisible(layerList[0], True)
QgsProject.instance().layerTreeRoot().findLayer(
layerList[0].id()
).setItemVisibilityChecked(True)
else:
self.postInformationMessageToUser("There was a problem showing a layer.")
@pyqtSlot(tuple)
def showNewImage(self, image):
"""
Will order this UI to post a new image to the user
through the qgis window.
:param image: a tuple consisting of (imageOrLayerObject, Name, Service)
:type image: (QgsRasterLayer, String, String)
"""
self.postInformationMessageToUser(
"Layer '" + image[1] + "' [" + image[2] + "]retrieved"
)
layer = image[0]
if layer and layer.isValid():
QgsProject.instance().addMapLayer(layer)
iface.zoomToActiveLayer()
# iface.legendInterface().refreshLayerSymbology(layer)
iface.layerTreeView().refreshLayerSymbology(layer.id())
else:
self.postInformationMessageToUser("There was a problem loading the layer.")
@pyqtSlot()
def _onManageServersRequested(self):
"""Delegates the action of showing the server manager window to the controller."""
self.controller.showServerManager()