Newer
Older
# -*- coding: utf-8 -*-
"""
/***************************************************************************

Benjamin Jakimow
committed
EO Time Series Viewer
-------------------
begin : 2015-08-20
git sha : $Format:%H$
copyright : (C) 2017 by HU-Berlin
email : benjamin.jakimow@geo.hu-berlin.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import os, sys, re, fnmatch, collections, copy, traceback, bisect

benjamin.jakimow@geo.hu-berlin.de
committed
from qgis.core import *
from qgis.core import QgsContrastEnhancement, QgsRasterShader, QgsColorRampShader, QgsProject, QgsCoordinateReferenceSystem, \
QgsRasterLayer, QgsVectorLayer, QgsMapLayer, QgsMapLayerProxyModel, QgsColorRamp, QgsSingleBandPseudoColorRenderer
from qgis.gui import QgsDockWidget, QgsMapCanvas, QgsMapTool
from PyQt5.QtXml import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

benjamin.jakimow@geo.hu-berlin.de
committed
import numpy as np
from timeseriesviewer.utils import *
from timeseriesviewer.timeseries import SensorInstrument, TimeSeriesDatum, TimeSeries
from timeseriesviewer.main import TsvMimeDataUtils

benjamin.jakimow@geo.hu-berlin.de
committed
from timeseriesviewer.ui.mapviewscrollarea import MapViewScrollArea
from timeseriesviewer.mapcanvas import MapCanvas
#dummyPath = os.path.abspath(os.path.join(os.path.dirname(__file__), 'dummy_gdal.vrt'))
#assert os.path.isfile(dummyPath)
#lyr = QgsRasterLayer(dummyPath)
#assert lyr.isValid()
DUMMY_RASTERINTERFACE = QgsSingleBandGrayRenderer(None, 0)
class MapViewUI(QFrame, loadUI('mapviewdefinition.ui')):
def __init__(self, parent=None):
super(MapViewUI, self).__init__(parent)
self.setupUi(self)
self.mSensors = collections.OrderedDict()
m = QMenu(self.btnToggleCrosshair)
m.addAction(self.actionSetCrosshairStyle)
#a = m.addAction('Set Crosshair Style')
self.btnToggleCrosshair.setMenu(m)
#connect the QActions with the QgsCollapsibleGroupBoxes

Benjamin Jakimow
committed
self.gbVectorRendering.toggled.connect(self.actionToggleVectorVisibility.setChecked)
self.gbRasterRendering.toggled.connect(self.actionToggleRasterVisibility.setChecked)
#self.connectActionWithGroupBox(self.actionToggleVectorVisibility, self.gbVectorRendering)
#self.connectActionWithGroupBox(self.actionToggleRasterVisibility, self.gbRasterRendering)
#self.gbVectorRendering.toggled.connect(self.actionToggleVectorVisibility.toggle)
#self.gbRasterRendering.toggled.connect(self.actionToggleRasterVisibility.toggle)
#self.actionToggleVectorVisibility.toggled.connect(self.gbVectorRendering.setChecked)
#self.actionToggleRasterVisibility.toggled.connect(self.gbRasterRendering.setChecked)
self.btnToggleCrosshair.setDefaultAction(self.actionToggleCrosshairVisibility)
self.btnToggleMapViewVisibility.setDefaultAction(self.actionToggleMapViewHidden)

benjamin.jakimow@geo.hu-berlin.de
committed
self.btnSetVectorStyle.setDefaultAction(self.actionSetVectorStyle)
def addSensor(self, sensor):
assert isinstance(sensor, SensorInstrument)
#w = MapViewSensorSettings(sensor)
w = MapViewRenderSettingsV2(sensor)

benjamin.jakimow@geo.hu-berlin.de
committed
#sizePolicy = QSizePolicy(QSize)
#w.ui.
#l = self.renderSettingsLayout
l = self.gbRasterRendering.layout()
i = l.count()-1
while i > 0 and not isinstance(l.itemAt(i), QWidget):
i -= 1
l.insertWidget(i, w, stretch=0, alignment=Qt.AlignTop)
self.mSensors[sensor] = w
#self.resize(self.sizeHint())
return w
def removeSensor(self, sensor):
assert isinstance(sensor, SensorInstrument)
sensorSettings = self.mSensors.pop(sensor)
assert isinstance(sensorSettings, MapViewRenderSettingsV2)
#l = self.renderSettingsLayout
l = self.gbRasterRendering.layout()
l.removeWidget(sensorSettings.ui)
sensorSettings.ui.close()
#self.resize(self.sizeHint())
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
class RendererWidgetModifications(object):
def __init__(self):
self.mBandComboBoxes = []
def modifyGridLayout(self):
gridLayoutOld = self.layout().children()[0]
self.gridLayout = QGridLayout()
while gridLayoutOld.count() > 0:
w = gridLayoutOld.takeAt(0)
w = w.widget()
gridLayoutOld.removeWidget(w)
w.setVisible(False)
setattr(self, w.objectName(), w)
self.layout().removeItem(gridLayoutOld)
self.layout().insertItem(0, self.gridLayout)
self.gridLayout.setSpacing(2)
self.layout().addStretch()
def connectSliderWithBandComboBox(self, slider, combobox):
"""
Connects a band-selection slider with a band-selection combobox
:param widget: QgsRasterRendererWidget
:param slider: QSlider to show the band number
:param combobox: QComboBox to show the band name
:return:
"""
assert isinstance(self, QgsRasterRendererWidget)
assert isinstance(slider, QSlider)
assert isinstance(combobox, QComboBox)
# init the slider
nb = self.rasterLayer().dataProvider().bandCount()
slider.setTickPosition(QSlider.TicksAbove)
slider.valueChanged.connect(combobox.setCurrentIndex)
slider.setMinimum(1)
slider.setMaximum(nb)
intervals = [1, 2, 5, 10, 25, 50]
for interval in intervals:
if nb / interval < 10:
break
slider.setTickInterval(interval)
slider.setPageStep(interval)
def onBandValueChanged(self, idx, slider):
assert isinstance(self, QgsRasterRendererWidget)
assert isinstance(idx, int)
assert isinstance(slider, QSlider)
# i = slider.value()
slider.blockSignals(True)
slider.setValue(idx)
slider.blockSignals(False)
# self.minMaxWidget().setBands(myBands)
# self.widgetChanged.emit()
if self.comboBoxWithNotSetItem(combobox):
combobox.currentIndexChanged[int].connect(lambda idx: onBandValueChanged(self, idx, slider))
else:
combobox.currentIndexChanged[int].connect(lambda idx: onBandValueChanged(self, idx + 1, slider))
def comboBoxWithNotSetItem(self, cb):
assert isinstance(cb, QComboBox)
return cb.itemData(0, role=Qt.DisplayRole) == 'not set'
def setLayoutItemVisibility(self, grid, isVisible):
assert isinstance(self, QgsRasterRendererWidget)
for i in range(grid.count()):
item = grid.itemAt(i)
if isinstance(item, QLayout):
s = ""
elif isinstance(item, QWidgetItem):
item.widget().setVisible(isVisible)
item.widget().setParent(self)
else:
s = ""
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
def fixBandNames(self, comboBox):
"""
Changes the QGIS default bandnames ("Band 001") to more meaning ful information including gdal.Dataset.Descriptions.
:param widget:
:param comboBox:
"""
assert isinstance(self, QgsRasterRendererWidget)
if type(comboBox) is QComboBox:
bandNames = displayBandNames(self.rasterLayer())
for i in range(comboBox.count()):
# text = cb.itemText(i)
if i > 0:
comboBox.setItemText(i, bandNames[i - 1])
else:
raise NotImplementedError()
def displayBandNames(provider_or_dataset, bands=None):
results = None
if isinstance(provider_or_dataset, QgsRasterLayer):
return displayBandNames(provider_or_dataset.dataProvider())
elif isinstance(provider_or_dataset, QgsRasterDataProvider):
if provider_or_dataset.name() == 'gdal':
ds = gdal.Open(provider_or_dataset.dataSourceUri())
results = displayBandNames(ds, bands=bands)
else:
# same as in QgsRasterRendererWidget::displayBandName
results = []
if bands is None:
bands = range(1, provider_or_dataset.bandCount() + 1)
for band in bands:
result = provider_or_dataset.generateBandName(band)
colorInterp ='{}'.format(provider_or_dataset.colorInterpretationName(band))
if colorInterp != 'Undefined':
result += '({})'.format(colorInterp)
results.append(result)
elif isinstance(provider_or_dataset, gdal.Dataset):
results = []
if bands is None:
bands = range(1, provider_or_dataset.RasterCount+1)
for band in bands:
b = provider_or_dataset.GetRasterBand(band)
descr = b.GetDescription()
if len(descr) == 0:
descr = 'Band {}'.format(band)
results.append(descr)
return results
class SingleBandGrayRendererWidget(QgsSingleBandGrayRendererWidget, RendererWidgetModifications):
@staticmethod
def create(layer, extent):
return SingleBandGrayRendererWidget(layer, extent)
def __init__(self, layer, extent):
super(SingleBandGrayRendererWidget, self).__init__(layer, extent)
self.modifyGridLayout()
self.mGrayBandSlider = QSlider(Qt.Horizontal)
self.mBandComboBoxes.append(self.mGrayBandComboBox)
self.fixBandNames(self.mGrayBandComboBox)
self.connectSliderWithBandComboBox(self.mGrayBandSlider, self.mGrayBandComboBox)
self.mBtnBar = QFrame()
self.initActionButtons()
self.gridLayout.addWidget(self.mGrayBandLabel, 0, 0)
self.gridLayout.addWidget(self.mBtnBar, 0, 1, 1, 4, Qt.AlignLeft)
self.gridLayout.addWidget(self.mGrayBandSlider, 1, 1, 1, 2)
self.gridLayout.addWidget(self.mGrayBandComboBox, 1, 3,1,2)
self.gridLayout.addWidget(self.label, 2, 0)
self.gridLayout.addWidget(self.mGradientComboBox, 2, 1, 1, 4)
self.gridLayout.addWidget(self.mMinLabel, 3, 1)
self.gridLayout.addWidget(self.mMinLineEdit, 3, 2)
self.gridLayout.addWidget(self.mMaxLabel, 3, 3)
self.gridLayout.addWidget(self.mMaxLineEdit, 3, 4)
self.gridLayout.addWidget(self.mContrastEnhancementLabel, 4, 0)
self.gridLayout.addWidget(self.mContrastEnhancementComboBox, 4, 1, 1 ,4)
self.gridLayout.setSpacing(2)
self.setLayoutItemVisibility(self.gridLayout, True)
self.mDefaultRenderer = layer.renderer()
def initActionButtons(self):
wl, wlu = parseWavelength(self.rasterLayer())
self.wavelengths = wl
self.wavelengthUnit = wlu
self.mBtnBar.setLayout(QHBoxLayout())
self.mBtnBar.layout().addStretch()
self.mBtnBar.layout().setContentsMargins(0, 0, 0, 0)
self.mBtnBar.layout().setSpacing(2)
self.actionSetDefault = QAction('Default')
self.actionSetRed = QAction('R')
self.actionSetGreen = QAction('G')
self.actionSetBlue = QAction('B')
self.actionSetNIR = QAction('nIR')
self.actionSetSWIR = QAction('swIR')
self.actionSetDefault.triggered.connect(lambda: self.setBandSelection('default'))
self.actionSetRed.triggered.connect(lambda: self.setBandSelection('R'))
self.actionSetGreen.triggered.connect(lambda: self.setBandSelection('G'))
self.actionSetBlue.triggered.connect(lambda: self.setBandSelection('B'))
self.actionSetNIR.triggered.connect(lambda: self.setBandSelection('nIR'))
self.actionSetSWIR.triggered.connect(lambda: self.setBandSelection('swIR'))
def addBtnAction(action):
btn = QToolButton()
btn.setDefaultAction(action)
self.mBtnBar.layout().addWidget(btn)
self.insertAction(None, action)
return btn
self.btnDefault = addBtnAction(self.actionSetDefault)
self.btnRed = addBtnAction(self.actionSetRed)
self.btnGreen = addBtnAction(self.actionSetGreen)
self.btnBlue = addBtnAction(self.actionSetRed)
self.btnNIR = addBtnAction(self.actionSetNIR)
self.btnSWIR = addBtnAction(self.actionSetSWIR)
b = self.wavelengths is not None
for a in [self.actionSetRed, self.actionSetGreen, self.actionSetBlue, self.actionSetNIR, self.actionSetSWIR]:
a.setEnabled(b)
class SingleBandPseudoColorRendererWidget(QgsSingleBandPseudoColorRendererWidget, RendererWidgetModifications):
@staticmethod
def create(layer, extent):
return SingleBandPseudoColorRendererWidget(layer, extent)
def __init__(self, layer, extent):
super(SingleBandPseudoColorRendererWidget, self).__init__(layer, extent)
self.gridLayout = self.layout()
assert isinstance(self.gridLayout, QGridLayout)
for i in range(self.gridLayout.count()):
w = self.gridLayout.itemAt(i)
w = w.widget()
if isinstance(w, QWidget):
setattr(self, w.objectName(), w)
toReplace = [self.mBandComboBox,self.mMinLabel,self.mMaxLabel, self.mMinLineEdit, self.mMaxLineEdit ]
for w in toReplace:
self.gridLayout.removeWidget(w)
w.setVisible(False)
self.mBandSlider = QSlider(Qt.Horizontal)
self.mBandComboBoxes.append(self.mBandComboBox)
self.fixBandNames(self.mBandComboBox)
self.connectSliderWithBandComboBox(self.mBandSlider, self.mBandComboBox)
self.mBtnBar = QFrame()
self.initActionButtons()
grid = QGridLayout()
grid.addWidget(self.mBtnBar,0,0,1,4, Qt.AlignLeft)
grid.addWidget(self.mBandSlider, 1,0, 1,2)
grid.addWidget(self.mBandComboBox, 1,2, 1,2)
grid.addWidget(self.mMinLabel, 2, 0)
grid.addWidget(self.mMinLineEdit, 2, 1)
grid.addWidget(self.mMaxLabel, 2, 2)
grid.addWidget(self.mMaxLineEdit, 2, 3)
#grid.setContentsMargins(2, 2, 2, 2, )
grid.setColumnStretch(0, 0)
grid.setColumnStretch(1, 2)
grid.setColumnStretch(2, 0)
grid.setColumnStretch(3, 2)
grid.setSpacing(2)
self.gridLayout.addItem(grid, 0,1,2,4)
self.gridLayout.setSpacing(2)
self.setLayoutItemVisibility(grid, True)
def initActionButtons(self):
from enmapbox.gui.utils import parseWavelength
wl, wlu = parseWavelength(self.rasterLayer())
self.wavelengths = wl
self.wavelengthUnit = wlu
self.mBtnBar.setLayout(QHBoxLayout())
self.mBtnBar.layout().addStretch()
self.mBtnBar.layout().setContentsMargins(0, 0, 0, 0)
self.mBtnBar.layout().setSpacing(2)
self.actionSetDefault = QAction('Default')
self.actionSetRed = QAction('R')
self.actionSetGreen = QAction('G')
self.actionSetBlue = QAction('B')
self.actionSetNIR = QAction('nIR')
self.actionSetSWIR = QAction('swIR')
self.actionSetDefault.triggered.connect(lambda: self.setBandSelection('default'))
self.actionSetRed.triggered.connect(lambda: self.setBandSelection('R'))
self.actionSetGreen.triggered.connect(lambda: self.setBandSelection('G'))
self.actionSetBlue.triggered.connect(lambda: self.setBandSelection('B'))
self.actionSetNIR.triggered.connect(lambda: self.setBandSelection('nIR'))
self.actionSetSWIR.triggered.connect(lambda: self.setBandSelection('swIR'))
def addBtnAction(action):
btn = QToolButton()
btn.setDefaultAction(action)
self.mBtnBar.layout().addWidget(btn)
self.insertAction(None, action)
return btn
self.btnDefault = addBtnAction(self.actionSetDefault)
self.btnRed = addBtnAction(self.actionSetRed)
self.btnGreen = addBtnAction(self.actionSetGreen)
self.btnBlue = addBtnAction(self.actionSetRed)
self.btnNIR = addBtnAction(self.actionSetNIR)
self.btnSWIR = addBtnAction(self.actionSetSWIR)
b = self.wavelengths is not None
for a in [self.actionSetRed, self.actionSetGreen, self.actionSetBlue, self.actionSetNIR, self.actionSetSWIR]:
a.setEnabled(b)
class MultiBandColorRendererWidget(QgsMultiBandColorRendererWidget, RendererWidgetModifications):
@staticmethod
def create(layer, extent):
return MultiBandColorRendererWidget(layer, extent)
def __init__(self, layer, extent):
super(MultiBandColorRendererWidget, self).__init__(layer, extent)
self.modifyGridLayout()
self.mRedBandSlider = QSlider(Qt.Horizontal)
self.mGreenBandSlider = QSlider(Qt.Horizontal)
self.mBlueBandSlider = QSlider(Qt.Horizontal)
self.mBandComboBoxes.extend([self.mRedBandComboBox, self.mGreenBandComboBox, self.mBlueBandComboBox])
self.mSliders = [self.mRedBandSlider, self.mGreenBandSlider, self.mBlueBandSlider]
nb = self.rasterLayer().dataProvider().bandCount()
for cbox, slider in zip(self.mBandComboBoxes, self.mSliders):
self.connectSliderWithBandComboBox(slider, cbox)
self.fixBandNames(self.mRedBandComboBox)
self.fixBandNames(self.mGreenBandComboBox)
self.fixBandNames(self.mBlueBandComboBox)
self.mBtnBar = QFrame()
self.mBtnBar.setLayout(QHBoxLayout())
self.initActionButtons()
self.mBtnBar.layout().addStretch()
self.mBtnBar.layout().setContentsMargins(0, 0, 0, 0)
self.mBtnBar.layout().setSpacing(2)
#self.gridLayout.deleteLater()
# self.gridLayout = newGrid
self.gridLayout.addWidget(self.mBtnBar, 0, 1, 1, 3)
self.gridLayout.addWidget(self.mRedBandLabel, 1, 0)
self.gridLayout.addWidget(self.mRedBandSlider, 1, 1)
self.gridLayout.addWidget(self.mRedBandComboBox, 1, 2)
self.gridLayout.addWidget(self.mRedMinLineEdit, 1, 3)
self.gridLayout.addWidget(self.mRedMaxLineEdit, 1, 4)
self.gridLayout.addWidget(self.mGreenBandLabel, 2, 0)
self.gridLayout.addWidget(self.mGreenBandSlider, 2, 1)
self.gridLayout.addWidget(self.mGreenBandComboBox, 2, 2)
self.gridLayout.addWidget(self.mGreenMinLineEdit, 2, 3)
self.gridLayout.addWidget(self.mGreenMaxLineEdit, 2, 4)
self.gridLayout.addWidget(self.mBlueBandLabel, 3, 0)
self.gridLayout.addWidget(self.mBlueBandSlider, 3, 1)
self.gridLayout.addWidget(self.mBlueBandComboBox, 3, 2)
self.gridLayout.addWidget(self.mBlueMinLineEdit, 3, 3)
self.gridLayout.addWidget(self.mBlueMaxLineEdit, 3, 4)
self.gridLayout.addWidget(self.mContrastEnhancementAlgorithmLabel, 4, 0, 1, 2)
self.gridLayout.addWidget(self.mContrastEnhancementAlgorithmComboBox, 4, 2, 1, 3)
self.setLayoutItemVisibility(self.gridLayout, True)
self.mRedBandLabel.setText('R')
self.mGreenBandLabel.setText('G')
self.mBlueBandLabel.setText('B')
self.mDefaultRenderer = layer.renderer()
def initActionButtons(self):
from enmapbox.gui.utils import parseWavelength
wl, wlu = parseWavelength(self.rasterLayer())
self.wavelengths = wl
self.wavelengthUnit = wlu
self.actionSetDefault = QAction('Default')
self.actionSetTrueColor = QAction('RGB')
self.actionSetCIR = QAction('nIR')
self.actionSet453 = QAction('swIR')
self.actionSetDefault.triggered.connect(lambda: self.setBandSelection('default'))
self.actionSetTrueColor.triggered.connect(lambda: self.setBandSelection('R,G,B'))
self.actionSetCIR.triggered.connect(lambda: self.setBandSelection('nIR,R,G'))
self.actionSet453.triggered.connect(lambda: self.setBandSelection('nIR,swIR,R'))
def addBtnAction(action):
btn = QToolButton()
btn.setDefaultAction(action)
self.mBtnBar.layout().addWidget(btn)
self.insertAction(None, action)
return btn
self.btnDefault = addBtnAction(self.actionSetDefault)
self.btnTrueColor = addBtnAction(self.actionSetTrueColor)
self.btnCIR = addBtnAction(self.actionSetCIR)
self.btn453 = addBtnAction(self.actionSet453)
b = self.wavelengths is not None
for a in [self.actionSetCIR, self.actionSet453, self.actionSetTrueColor]:
a.setEnabled(b)
class RendererWidgetModifications(object):
def __init__(self):
self.initWidgetNames()
self.mBandComboBoxes = []
def modifyGridLayout(self):
gridLayoutOld = self.layout().children()[0]
self.gridLayout = QGridLayout()
while gridLayoutOld.count() > 0:
w = gridLayoutOld.takeAt(0)
w = w.widget()
gridLayoutOld.removeWidget(w)
w.setVisible(False)
self.gridLayout.setSpacing(2)
l.removeItem(gridLayoutOld)
if isinstance(l, QBoxLayout):
l.insertItem(0, self.gridLayout)
self.layout().addStretch()
elif isinstance(l, QGridLayout):
l.addItem(self.gridLayout, 0, 0)
minMaxWidget = self.minMaxWidget()
if isinstance(minMaxWidget, QWidget):
minMaxWidget.layout().itemAt(0).widget().collapsedStateChanged.connect(self.onCollapsed)
def initWidgetNames(self):
for c in self.children():
setattr(self, c.objectName(), c)
def onCollapsed(self, b):
hint = self.sizeHint()
self.parent().adjustSize()
# self.parent().setFixedSize(hint)
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
self.parent().parent().adjustSize()
def connectSliderWithBandComboBox(self, slider, combobox):
"""
Connects a band-selection slider with a band-selection combobox
:param widget: QgsRasterRendererWidget
:param slider: QSlider to show the band number
:param combobox: QComboBox to show the band name
:return:
"""
assert isinstance(self, QgsRasterRendererWidget)
assert isinstance(slider, QSlider)
assert isinstance(combobox, QComboBox)
# init the slider
nb = self.rasterLayer().dataProvider().bandCount()
slider.setTickPosition(QSlider.TicksAbove)
slider.valueChanged.connect(combobox.setCurrentIndex)
slider.setMinimum(1)
slider.setMaximum(nb)
intervals = [1, 2, 5, 10, 25, 50]
for interval in intervals:
if nb / interval < 10:
break
slider.setTickInterval(interval)
slider.setPageStep(interval)
def onBandValueChanged(self, idx, slider):
assert isinstance(self, QgsRasterRendererWidget)
assert isinstance(idx, int)
assert isinstance(slider, QSlider)
# i = slider.value()
slider.blockSignals(True)
slider.setValue(idx)
slider.blockSignals(False)
# self.minMaxWidget().setBands(myBands)
# self.widgetChanged.emit()
if self.comboBoxWithNotSetItem(combobox):
combobox.currentIndexChanged[int].connect(lambda idx: onBandValueChanged(self, idx, slider))
else:
combobox.currentIndexChanged[int].connect(lambda idx: onBandValueChanged(self, idx + 1, slider))
def comboBoxWithNotSetItem(self, cb):
assert isinstance(cb, QComboBox)
return cb.itemData(0, role=Qt.DisplayRole).lower() == 'not set'
def setLayoutItemVisibility(self, grid, isVisible):
assert isinstance(self, QgsRasterRendererWidget)
for i in range(grid.count()):
item = grid.itemAt(i)
if isinstance(item, QLayout):
s = ""
elif isinstance(item, QWidgetItem):
item.widget().setVisible(isVisible)
item.widget().setParent(self)
else:
s = ""
def setBandSelection(self, key):
if key == 'default':
bandIndices = defaultBands(self.rasterLayer())
else:
colors = re.split('[ ,;:]', key)
bandIndices = [bandClosestToWavelength(self.rasterLayer(), c) for c in colors]
n = min(len(bandIndices), len(self.mBandComboBoxes))
for i in range(n):
cb = self.mBandComboBoxes[i]
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
if self.comboBoxWithNotSetItem(cb):
cb.setCurrentIndex(bandIndex+1)
else:
cb.setCurrentIndex(bandIndex)
def fixBandNames(self, comboBox):
"""
Changes the QGIS default bandnames ("Band 001") to more meaning ful information including gdal.Dataset.Descriptions.
:param widget:
:param comboBox:
"""
assert isinstance(self, QgsRasterRendererWidget)
if type(comboBox) is QComboBox:
bandNames = displayBandNames(self.rasterLayer())
for i in range(comboBox.count()):
# text = cb.itemText(i)
if i > 0:
comboBox.setItemText(i, bandNames[i - 1])
else:
raise NotImplementedError()
def displayBandNames(provider_or_dataset, bands=None):
results = None
if isinstance(provider_or_dataset, QgsRasterLayer):
return displayBandNames(provider_or_dataset.dataProvider())
elif isinstance(provider_or_dataset, QgsRasterDataProvider):
if provider_or_dataset.name() == 'gdal':
ds = gdal.Open(provider_or_dataset.dataSourceUri())
results = displayBandNames(ds, bands=bands)
else:
# same as in QgsRasterRendererWidget::displayBandName
results = []
if bands is None:
bands = range(1, provider_or_dataset.bandCount() + 1)
for band in bands:
result = provider_or_dataset.generateBandName(band)
colorInterp ='{}'.format(provider_or_dataset.colorInterpretationName(band))
if colorInterp != 'Undefined':
result += '({})'.format(colorInterp)
results.append(result)
elif isinstance(provider_or_dataset, gdal.Dataset):
results = []
if bands is None:
bands = range(1, provider_or_dataset.RasterCount+1)
for band in bands:
b = provider_or_dataset.GetRasterBand(band)
descr = b.GetDescription()
if len(descr) == 0:
descr = 'Band {}'.format(band)
results.append(descr)
return results
class SingleBandGrayRendererWidget(QgsSingleBandGrayRendererWidget, RendererWidgetModifications):
@staticmethod
def create(layer, extent):
return SingleBandGrayRendererWidget(layer, extent)
def __init__(self, layer, extent):
super(SingleBandGrayRendererWidget, self).__init__(layer, extent)
self.modifyGridLayout()
self.mGrayBandSlider = QSlider(Qt.Horizontal)
self.mBandComboBoxes.append(self.mGrayBandComboBox)
self.fixBandNames(self.mGrayBandComboBox)
self.connectSliderWithBandComboBox(self.mGrayBandSlider, self.mGrayBandComboBox)
self.mBtnBar = QFrame()
self.initActionButtons()
self.gridLayout.addWidget(self.mGrayBandLabel, 0, 0)
self.gridLayout.addWidget(self.mBtnBar, 0, 1, 1, 4, Qt.AlignLeft)
self.gridLayout.addWidget(self.mGrayBandSlider, 1, 1, 1, 2)
self.gridLayout.addWidget(self.mGrayBandComboBox, 1, 3,1,2)
self.gridLayout.addWidget(self.label, 2, 0)
self.gridLayout.addWidget(self.mGradientComboBox, 2, 1, 1, 4)
self.gridLayout.addWidget(self.mMinLabel, 3, 1)
self.gridLayout.addWidget(self.mMinLineEdit, 3, 2)
self.gridLayout.addWidget(self.mMaxLabel, 3, 3)
self.gridLayout.addWidget(self.mMaxLineEdit, 3, 4)
self.gridLayout.addWidget(self.mContrastEnhancementLabel, 4, 0)
self.gridLayout.addWidget(self.mContrastEnhancementComboBox, 4, 1, 1 ,4)
self.gridLayout.setSpacing(2)
self.setLayoutItemVisibility(self.gridLayout, True)
self.mDefaultRenderer = layer.renderer()
def initActionButtons(self):
wl, wlu = parseWavelength(self.rasterLayer())
self.wavelengths = wl
self.wavelengthUnit = wlu
self.mBtnBar.setLayout(QHBoxLayout())
self.mBtnBar.layout().addStretch()
self.mBtnBar.layout().setContentsMargins(0, 0, 0, 0)
self.mBtnBar.layout().setSpacing(2)
self.actionSetDefault = QAction('Default')
self.actionSetRed = QAction('R')
self.actionSetGreen = QAction('G')
self.actionSetBlue = QAction('B')
self.actionSetNIR = QAction('nIR')
self.actionSetSWIR = QAction('swIR')
self.actionSetDefault.triggered.connect(lambda: self.setBandSelection('default'))
self.actionSetRed.triggered.connect(lambda: self.setBandSelection('R'))
self.actionSetGreen.triggered.connect(lambda: self.setBandSelection('G'))
self.actionSetBlue.triggered.connect(lambda: self.setBandSelection('B'))
self.actionSetNIR.triggered.connect(lambda: self.setBandSelection('nIR'))
self.actionSetSWIR.triggered.connect(lambda: self.setBandSelection('swIR'))
def addBtnAction(action):
btn = QToolButton()
btn.setDefaultAction(action)
self.mBtnBar.layout().addWidget(btn)
self.insertAction(None, action)
return btn
self.btnDefault = addBtnAction(self.actionSetDefault)
self.btnRed = addBtnAction(self.actionSetRed)
self.btnGreen = addBtnAction(self.actionSetGreen)
self.btnBlue = addBtnAction(self.actionSetRed)
self.btnNIR = addBtnAction(self.actionSetNIR)
self.btnSWIR = addBtnAction(self.actionSetSWIR)
b = self.wavelengths is not None
for a in [self.actionSetRed, self.actionSetGreen, self.actionSetBlue, self.actionSetNIR, self.actionSetSWIR]:
a.setEnabled(b)
class SingleBandPseudoColorRendererWidget(QgsSingleBandPseudoColorRendererWidget, RendererWidgetModifications):
@staticmethod
def create(layer, extent):
return SingleBandPseudoColorRendererWidget(layer, extent)
def __init__(self, layer, extent):
super(SingleBandPseudoColorRendererWidget, self).__init__(layer, extent)
self.mColormapTreeWidget.setMinimumSize(QSize(1,1))
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
self.gridLayout = self.layout()
assert isinstance(self.gridLayout, QGridLayout)
for i in range(self.gridLayout.count()):
w = self.gridLayout.itemAt(i)
w = w.widget()
if isinstance(w, QWidget):
setattr(self, w.objectName(), w)
toReplace = [self.mBandComboBox,self.mMinLabel,self.mMaxLabel, self.mMinLineEdit, self.mMaxLineEdit ]
for w in toReplace:
self.gridLayout.removeWidget(w)
w.setVisible(False)
self.mBandSlider = QSlider(Qt.Horizontal)
self.mBandComboBoxes.append(self.mBandComboBox)
self.fixBandNames(self.mBandComboBox)
self.connectSliderWithBandComboBox(self.mBandSlider, self.mBandComboBox)
self.mBtnBar = QFrame()
self.initActionButtons()
grid = QGridLayout()
grid.addWidget(self.mBtnBar,0,0,1,4, Qt.AlignLeft)
grid.addWidget(self.mBandSlider, 1,0, 1,2)
grid.addWidget(self.mBandComboBox, 1,2, 1,2)
grid.addWidget(self.mMinLabel, 2, 0)
grid.addWidget(self.mMinLineEdit, 2, 1)
grid.addWidget(self.mMaxLabel, 2, 2)
grid.addWidget(self.mMaxLineEdit, 2, 3)
#grid.setContentsMargins(2, 2, 2, 2, )
grid.setColumnStretch(0, 0)
grid.setColumnStretch(1, 2)
grid.setColumnStretch(2, 0)
grid.setColumnStretch(3, 2)
grid.setSpacing(2)
self.gridLayout.addItem(grid, 0,1,2,4)
self.gridLayout.setSpacing(2)
self.setLayoutItemVisibility(grid, True)
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
def initActionButtons(self):
wl, wlu = parseWavelength(self.rasterLayer())
self.wavelengths = wl
self.wavelengthUnit = wlu
self.mBtnBar.setLayout(QHBoxLayout())
self.mBtnBar.layout().addStretch()
self.mBtnBar.layout().setContentsMargins(0, 0, 0, 0)
self.mBtnBar.layout().setSpacing(2)
self.actionSetDefault = QAction('Default')
self.actionSetRed = QAction('R')
self.actionSetGreen = QAction('G')
self.actionSetBlue = QAction('B')
self.actionSetNIR = QAction('nIR')
self.actionSetSWIR = QAction('swIR')
self.actionSetDefault.triggered.connect(lambda: self.setBandSelection('default'))
self.actionSetRed.triggered.connect(lambda: self.setBandSelection('R'))
self.actionSetGreen.triggered.connect(lambda: self.setBandSelection('G'))
self.actionSetBlue.triggered.connect(lambda: self.setBandSelection('B'))
self.actionSetNIR.triggered.connect(lambda: self.setBandSelection('nIR'))
self.actionSetSWIR.triggered.connect(lambda: self.setBandSelection('swIR'))
def addBtnAction(action):
btn = QToolButton()
btn.setDefaultAction(action)
self.mBtnBar.layout().addWidget(btn)
self.insertAction(None, action)
return btn
self.btnDefault = addBtnAction(self.actionSetDefault)
self.btnRed = addBtnAction(self.actionSetRed)
self.btnGreen = addBtnAction(self.actionSetGreen)
self.btnBlue = addBtnAction(self.actionSetRed)
self.btnNIR = addBtnAction(self.actionSetNIR)
self.btnSWIR = addBtnAction(self.actionSetSWIR)
b = self.wavelengths is not None
for a in [self.actionSetRed, self.actionSetGreen, self.actionSetBlue, self.actionSetNIR, self.actionSetSWIR]:
a.setEnabled(b)
class PalettedRendererWidget(QgsPalettedRendererWidget, RendererWidgetModifications):
@staticmethod
def create(layer, extent):
return PalettedRendererWidget(layer, extent)
def __init__(self, layer, extent):
super(PalettedRendererWidget, self).__init__(layer, extent)
#self.modifyGridLayout()
self.mTreeView.setMinimumSize(QSize(10,10))
s = ""
class MultiBandColorRendererWidget(QgsMultiBandColorRendererWidget, RendererWidgetModifications):
@staticmethod
def create(layer, extent):
return MultiBandColorRendererWidget(layer, extent)
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
def __init__(self, layer, extent):
super(MultiBandColorRendererWidget, self).__init__(layer, extent)
self.modifyGridLayout()
self.mRedBandSlider = QSlider(Qt.Horizontal)
self.mGreenBandSlider = QSlider(Qt.Horizontal)
self.mBlueBandSlider = QSlider(Qt.Horizontal)
self.mBandComboBoxes.extend([self.mRedBandComboBox, self.mGreenBandComboBox, self.mBlueBandComboBox])
self.mSliders = [self.mRedBandSlider, self.mGreenBandSlider, self.mBlueBandSlider]
nb = self.rasterLayer().dataProvider().bandCount()
for cbox, slider in zip(self.mBandComboBoxes, self.mSliders):
self.connectSliderWithBandComboBox(slider, cbox)
self.fixBandNames(self.mRedBandComboBox)
self.fixBandNames(self.mGreenBandComboBox)
self.fixBandNames(self.mBlueBandComboBox)
self.mBtnBar = QFrame()
self.mBtnBar.setLayout(QHBoxLayout())
self.initActionButtons()
self.mBtnBar.layout().addStretch()
self.mBtnBar.layout().setContentsMargins(0, 0, 0, 0)
self.mBtnBar.layout().setSpacing(2)
#self.gridLayout.deleteLater()
# self.gridLayout = newGrid
self.gridLayout.addWidget(self.mBtnBar, 0, 1, 1, 3)
self.gridLayout.addWidget(self.mRedBandLabel, 1, 0)
self.gridLayout.addWidget(self.mRedBandSlider, 1, 1)
self.gridLayout.addWidget(self.mRedBandComboBox, 1, 2)
self.gridLayout.addWidget(self.mRedMinLineEdit, 1, 3)
self.gridLayout.addWidget(self.mRedMaxLineEdit, 1, 4)
self.gridLayout.addWidget(self.mGreenBandLabel, 2, 0)
self.gridLayout.addWidget(self.mGreenBandSlider, 2, 1)
self.gridLayout.addWidget(self.mGreenBandComboBox, 2, 2)
self.gridLayout.addWidget(self.mGreenMinLineEdit, 2, 3)
self.gridLayout.addWidget(self.mGreenMaxLineEdit, 2, 4)
self.gridLayout.addWidget(self.mBlueBandLabel, 3, 0)
self.gridLayout.addWidget(self.mBlueBandSlider, 3, 1)
self.gridLayout.addWidget(self.mBlueBandComboBox, 3, 2)
self.gridLayout.addWidget(self.mBlueMinLineEdit, 3, 3)
self.gridLayout.addWidget(self.mBlueMaxLineEdit, 3, 4)
self.gridLayout.addWidget(self.mContrastEnhancementAlgorithmLabel, 4, 0, 1, 2)
self.gridLayout.addWidget(self.mContrastEnhancementAlgorithmComboBox, 4, 2, 1, 3)
self.setLayoutItemVisibility(self.gridLayout, True)
self.mRedBandLabel.setText('R')
self.mGreenBandLabel.setText('G')
self.mBlueBandLabel.setText('B')
self.mDefaultRenderer = layer.renderer()
def initActionButtons(self):
wl, wlu = parseWavelength(self.rasterLayer())
self.wavelengths = wl
self.wavelengthUnit = wlu
self.actionSetDefault = QAction('Default')
self.actionSetTrueColor = QAction('RGB')
self.actionSetCIR = QAction('nIR')
self.actionSet453 = QAction('swIR')
self.actionSetDefault.triggered.connect(lambda: self.setBandSelection('default'))
self.actionSetTrueColor.triggered.connect(lambda: self.setBandSelection('R,G,B'))
self.actionSetCIR.triggered.connect(lambda: self.setBandSelection('nIR,R,G'))
self.actionSet453.triggered.connect(lambda: self.setBandSelection('nIR,swIR,R'))
def addBtnAction(action):
btn = QToolButton()
btn.setDefaultAction(action)
self.mBtnBar.layout().addWidget(btn)
self.insertAction(None, action)
return btn
self.btnDefault = addBtnAction(self.actionSetDefault)
self.btnTrueColor = addBtnAction(self.actionSetTrueColor)
self.btnCIR = addBtnAction(self.actionSetCIR)
self.btn453 = addBtnAction(self.actionSet453)
b = self.wavelengths is not None
for a in [self.actionSetCIR, self.actionSet453, self.actionSetTrueColor]:
a.setEnabled(b)

benjamin.jakimow@geo.hu-berlin.de
committed
class MapView(QObject):
sigRemoveMapView = pyqtSignal(object)
sigMapViewVisibility = pyqtSignal(bool)
#sigVectorVisibility = pyqtSignal(bool)
#sigRasterVisibility = pyqtSignal(bool)

benjamin.jakimow@geo.hu-berlin.de
committed
sigTitleChanged = pyqtSignal(str)

benjamin.jakimow@geo.hu-berlin.de
committed
sigSensorRendererChanged = pyqtSignal(SensorInstrument, QgsRasterRenderer)

benjamin.jakimow@geo.hu-berlin.de
committed
sigCrosshairStyleChanged = pyqtSignal(CrosshairStyle)
sigShowCrosshair = pyqtSignal(bool)
sigVectorLayerChanged = pyqtSignal()
sigShowProfiles = pyqtSignal(SpatialPoint, MapCanvas, str)

benjamin.jakimow@geo.hu-berlin.de
committed

benjamin.jakimow@geo.hu-berlin.de
committed
def __init__(self, mapViewCollectionDock, name='Map View', recommended_bands=None, parent=None):

benjamin.jakimow@geo.hu-berlin.de
committed
super(MapView, self).__init__()

benjamin.jakimow@geo.hu-berlin.de
committed
assert isinstance(mapViewCollectionDock, MapViewCollectionDock)

benjamin.jakimow@geo.hu-berlin.de
committed
self.ui = MapViewUI(mapViewCollectionDock.stackedWidget)
self.ui.show()
self.ui.cbQgsVectorLayer.setFilters(QgsMapLayerProxyModel.VectorLayer)
self.ui.cbQgsVectorLayer.layerChanged.connect(self.setVectorLayer)
self.ui.tbName.textChanged.connect(self.sigTitleChanged)
from timeseriesviewer.crosshair import getCrosshairStyle
self.ui.actionSetCrosshairStyle.triggered.connect(
lambda : self.setCrosshairStyle(getCrosshairStyle(
parent=self.ui,
crosshairStyle=self.mCrosshairStyle))
)

benjamin.jakimow@geo.hu-berlin.de
committed
self.mapViewCollection = mapViewCollectionDock
self.mSensorViews = collections.OrderedDict()

benjamin.jakimow@geo.hu-berlin.de
committed
self.mVectorLayer = None

benjamin.jakimow@geo.hu-berlin.de
committed
self.setVectorLayer(None)
self.mCrosshairStyle = CrosshairStyle()
self.mShowCrosshair = True
self.ui.actionToggleVectorVisibility.toggled.connect(self.setVectorVisibility)
self.ui.actionToggleRasterVisibility.toggled.connect(self.setRasterVisibility)
self.ui.actionToggleCrosshairVisibility.toggled.connect(self.setShowCrosshair)
self.ui.actionToggleMapViewHidden.toggled.connect(lambda b: self.setIsVisible(not b))
self.ui.actionToggleVectorVisibility.setChecked(False)
self.ui.actionToggleRasterVisibility.setChecked(True)

benjamin.jakimow@geo.hu-berlin.de
committed
self.ui.actionSetVectorStyle.triggered.connect(self.setVectorLayerStyle)
for sensor in self.mapViewCollection.TS.Sensors:
self.addSensor(sensor)
self.setTitle(name)
#forward actions with reference to this band view
def dummy(self, *args):
print(args)
def setIsVisible(self, b):
assert isinstance(b, bool)
changed = False
for mapCanvas in self.mapCanvases():
assert isinstance(mapCanvas, MapCanvas)
mapCanvas.setVisible(b)
if self.ui.actionToggleMapViewHidden.isChecked() == b:
self.ui.actionToggleMapViewHidden.setChecked(not b)
if changed:
self.sigMapViewVisibility.emit(b)
def isVisible(self):
return not self.ui.actionToggleMapViewHidden.isChecked()
def mapCanvases(self):
m = []
for sensor, sensorView in self.mSensorViews.items():
m.extend(sensorView.mapCanvases())
return m

benjamin.jakimow@geo.hu-berlin.de
committed
def setVectorLayerStyle(self, *args):
if isinstance(self.mVectorLayer, QgsVectorLayer):
d = QgsRendererPropertiesDialog(self.mVectorLayer, QgsStyle.defaultStyle())
d.exec_()

benjamin.jakimow@geo.hu-berlin.de
committed
def vectorLayerRenderer(self):
if isinstance(self.mVectorLayer, QgsVectorLayer):

benjamin.jakimow@geo.hu-berlin.de
committed
return self.mVectorLayer.renderer()
return None

benjamin.jakimow@geo.hu-berlin.de
committed
def setVectorLayerRenderer(self, renderer):

benjamin.jakimow@geo.hu-berlin.de
committed
if isinstance(renderer, QgsFeatureRenderer) and \
isinstance(self.mVectorLayer, QgsVectorLayer):
self.mVectorLayer.setRendererV2(renderer)

benjamin.jakimow@geo.hu-berlin.de
committed
def setVectorLayer(self, lyr):

Benjamin Jakimow
committed
if isinstance(lyr, QgsVectorLayer) and self.ui.gbVectorRendering.isChecked():
#add vector layer
self.mVectorLayer = lyr
self.mVectorLayer.rendererChanged.connect(self.sigVectorLayerChanged)

benjamin.jakimow@geo.hu-berlin.de
committed
for mapCanvas in self.mapCanvases():
assert isinstance(mapCanvas, MapCanvas)
mapCanvas.layerModel().setVectorLayerSources([self.mVectorLayer])
#mapCanvas.setLayers([l for l in mapCanvas.layers() if isinstance(l, QgsRasterLayer)])
#mapCanvas.setLazyVectorSources([lyr])
mapCanvas.refresh()

benjamin.jakimow@geo.hu-berlin.de
committed
else:
#remove vector layers
self.mVectorLayer = None
for mapCanvas in self.mapCanvases():
mapCanvas.layerModel().setVectorLayerSources([])
#mapCanvas.setLayers([l for l in mapCanvas.mLayers if not isinstance(l, QgsVectorLayer)])
mapCanvas.refresh()

benjamin.jakimow@geo.hu-berlin.de
committed
def applyStyles(self):
for sensorView in self.mSensorViews.values():

benjamin.jakimow@geo.hu-berlin.de
committed
sensorView.applyStyle()
def setTitle(self, title):
old = self.title()
if old != title:
self.ui.tbName.setText(title)

benjamin.jakimow@geo.hu-berlin.de
committed

benjamin.jakimow@geo.hu-berlin.de
committed
def title(self):

benjamin.jakimow@geo.hu-berlin.de
committed
def refreshMapView(self, *args):
for renderSettings in self.mSensorViews.values():
assert isinstance(renderSettings, MapViewRenderSettingsV2)
renderSettings.applyStyle()
#for mapCanvas in self.mapCanvases():
# assert isinstance(mapCanvas, MapCanvas)
# mapCanvas.refresh()

benjamin.jakimow@geo.hu-berlin.de
committed
def setCrosshairStyle(self, crosshairStyle):
if isinstance(crosshairStyle, CrosshairStyle):
old = self.mCrosshairStyle
self.mCrosshairStyle = crosshairStyle
if old != self.mCrosshairStyle:
self.sigCrosshairStyleChanged.emit(self.mCrosshairStyle)

benjamin.jakimow@geo.hu-berlin.de
committed
def setHighlighted(self, b=True, timeout=1000):
styleOn = """.MapCanvas {
border: 4px solid red;
border-radius: 4px;
}"""
styleOff = """"""
if b is True:
for mapCanvas in self.mapCanvases():
mapCanvas.setStyleSheet(styleOn)
if timeout > 0:
QTimer.singleShot(timeout, lambda : self.setHighlighted(False))
else:
for mapCanvas in self.mapCanvases():
mapCanvas.setStyleSheet(styleOff)

benjamin.jakimow@geo.hu-berlin.de
committed
def setShowCrosshair(self, b):

benjamin.jakimow@geo.hu-berlin.de
committed
self.sigShowCrosshair.emit(b)
def showCrosshair(self):
return self.mShowCrosshair and self.mCrosshairStyle is not None
def rasterVisibility(self):
return self.ui.actionToggleRasterVisibility.isChecked()
def vectorVisibility(self):
return self.ui.actionToggleVectorVisibility.isChecked()
def setRasterVisibility(self, b):

Benjamin Jakimow
committed
self.mRastersVisible = b
self.ui.actionToggleRasterVisibility.setChecked(b)
for mapCanvas in self.mapCanvases():
assert isinstance(mapCanvas, MapCanvas)
mapCanvas.layerModel().setRasterLayerVisibility(b)
mapCanvas.refresh()
def setVectorVisibility(self, b):
assert isinstance(b, bool)

Benjamin Jakimow
committed
self.mVectorsVisible = b
self.ui.actionToggleVectorVisibility.setChecked(b)

Benjamin Jakimow
committed
for mapCanvas in self.mapCanvases():
assert isinstance(mapCanvas, MapCanvas)
mapCanvas.layerModel().setVectorLayerVisibility(self.mVectorsVisible)
mapCanvas.refresh()

benjamin.jakimow@geo.hu-berlin.de
committed
def removeSensor(self, sensor):
assert sensor in self.mSensorViews.keys()
self.mSensorViews.pop(sensor)

benjamin.jakimow@geo.hu-berlin.de
committed
def hasSensor(self, sensor):
assert type(sensor) is SensorInstrument
return sensor in self.mSensorViews.keys()

benjamin.jakimow@geo.hu-berlin.de
committed
def registerMapCanvas(self, sensor, mapCanvas):
from timeseriesviewer.mapcanvas import MapCanvas
assert isinstance(mapCanvas, MapCanvas)
assert isinstance(sensor, SensorInstrument)
mapViewRenderSettings = self.mSensorViews[sensor]
assert isinstance(mapViewRenderSettings, MapViewRenderSettingsV2)
mapViewRenderSettings.registerMapCanvas(mapCanvas)
#register signals sensor specific signals
mapCanvas.setRenderer(mapViewRenderSettings.rasterRenderer())
mapCanvas.setRenderer(self.vectorLayerRenderer())
#register non-sensor specific signals for this mpa view
self.sigMapViewVisibility.connect(mapCanvas.refresh)
self.sigCrosshairStyleChanged.connect(mapCanvas.setCrosshairStyle)
self.sigShowCrosshair.connect(mapCanvas.setShowCrosshair)
self.sigVectorLayerChanged.connect(mapCanvas.refresh)
# self.sigVectorVisibility.connect(mapCanvas.refresh)

benjamin.jakimow@geo.hu-berlin.de
committed
def addSensor(self, sensor):
"""
:param sensor:
:return:
"""
if isinstance(sensor, SensorInstrument) and sensor not in self.mSensorViews.keys():

benjamin.jakimow@geo.hu-berlin.de
committed
#w.showSensorName(False)
w = self.ui.addSensor(sensor)
#w.sigSensorRendererChanged.connect(self.onSensorRenderingChanged)
self.mSensorViews[sensor] = w
s =""
def onSensorRenderingChanged(self, renderer):
sensorSettings = self.sender()
assert isinstance(sensorSettings, MapViewSensorSettings)
for mapCanvas in sensorSettings.mapCanvases():
mapCanvas.setRenderer(renderer)
#mapCanvas.refresh()

benjamin.jakimow@geo.hu-berlin.de
committed
def getSensorWidget(self, sensor):
assert type(sensor) is SensorInstrument
return self.mSensorViews[sensor]

benjamin.jakimow@geo.hu-berlin.de
committed
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
def displayBandNames(provider_or_dataset, bands=None):
results = None
if isinstance(provider_or_dataset, QgsRasterLayer):
return displayBandNames(provider_or_dataset.dataProvider())
elif isinstance(provider_or_dataset, QgsRasterDataProvider):
if provider_or_dataset.name() == 'gdal':
ds = gdal.Open(provider_or_dataset.dataSourceUri())
results = displayBandNames(ds, bands=bands)
else:
# same as in QgsRasterRendererWidget::displayBandName
results = []
if bands is None:
bands = range(1, provider_or_dataset.bandCount() + 1)
for band in bands:
result = provider_or_dataset.generateBandName(band)
colorInterp ='{}'.format(provider_or_dataset.colorInterpretationName(band))
if colorInterp != 'Undefined':
result += '({})'.format(colorInterp)
results.append(result)
elif isinstance(provider_or_dataset, gdal.Dataset):
results = []
if bands is None:
bands = range(1, provider_or_dataset.RasterCount+1)
for band in bands:
b = provider_or_dataset.GetRasterBand(band)
descr = b.GetDescription()
if len(descr) == 0:
descr = 'Band {}'.format(band)
results.append(descr)
return results
class RasterDataProviderMockup(QgsRasterDataProvider):
def __init__(self):
super(RasterDataProviderMockup, self).__init__('')
class MapViewRenderSettingsV2(QgsCollapsibleGroupBox, loadUI('mapviewrendersettingsV2.ui')):
LUT_RENDERER = {QgsMultiBandColorRenderer:QgsMultiBandColorRendererWidget,
QgsSingleBandGrayRenderer:QgsSingleBandGrayRendererWidget,
QgsSingleBandPseudoColorRenderer:QgsSingleBandPseudoColorRendererWidget,
QgsPalettedRasterRenderer:QgsPalettedRendererWidget}
LUT_RENDERER[QgsMultiBandColorRenderer]=MultiBandColorRendererWidget
LUT_RENDERER[QgsSingleBandPseudoColorRenderer]=SingleBandPseudoColorRendererWidget
LUT_RENDERER[QgsSingleBandGrayRenderer]=SingleBandGrayRendererWidget
LUT_RENDERER[QgsPalettedRasterRenderer] = PalettedRendererWidget
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
def __init__(self, sensor, parent=None):
"""Constructor."""
super(MapViewRenderSettingsV2, self).__init__(parent)
# Set up the user interface from Designer.
# After setupUI you can access any designer object by doing
# self.<objectname>, and you can use autoconnect slots - see
# http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
# #widgets-and-dialogs-with-auto-connect
self.setupUi(self)
QApplication.clipboard().dataChanged.connect(self.onClipboardChanged)
assert isinstance(sensor, SensorInstrument)
self.mSensor = sensor
self.mSensor.sigNameChanged.connect(self.onSensorNameChanged)
self.setTitle(self.mSensor.name())
from timeseriesviewer.models import OptionListModel, Option
rasterRendererModel = OptionListModel()
#rasterRendererModel.addOption(Option(QgsMultiBandColorRendererWidget, name='multibandcolor (QGIS)', mRenderType = QgsMultiBandColorRenderer))
#rasterRendererModel.addOption(Option(QgsPalettedRendererWidget, name='paletted (QGIS)', mRenderType = QgsPalettedRasterRenderer))
#rasterRendererModel.addOption(Option(QgsSingleBandGrayRendererWidget, name='singlegray (QGIS)', mRenderType = QgsSingleBandGrayRenderer))
#rasterRendererModel.addOption(Option(QgsSingleBandPseudoColorRendererWidget, name='singlebandpseudocolor (QGIS)', mRenderType = QgsSingleBandPseudoColorRenderer))
rasterRendererModel.addOption(Option(MultiBandColorRendererWidget, name='Multibandcolor', mRenderType=QgsMultiBandColorRenderer))
rasterRendererModel.addOption(Option(SingleBandGrayRendererWidget, name='Singlegray', mRenderType=QgsSingleBandGrayRenderer))
rasterRendererModel.addOption(Option(SingleBandPseudoColorRendererWidget, name='Singleband Pseudocolor', mRenderType=QgsSingleBandPseudoColorRenderer))
rasterRendererModel.addOption(Option(PalettedRendererWidget, name='Paletted', mRenderType=QgsPalettedRasterRenderer))
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
self.mRasterRendererModel = rasterRendererModel
self.cbRenderType.setModel(self.mRasterRendererModel)
assert isinstance(self.stackedWidget, QStackedWidget)
self.mMockupCanvas = QgsMapCanvas()
self.mMockupRasterLayer = QgsRasterLayer(self.mSensor.pathImg)
self.mMockupCanvas.setLayers([self.mMockupRasterLayer])
for func in rasterRendererModel.optionValues():
#extent = self.canvas.extent()
#w = func.create(self.mMockupRasterLayer, self.mMockupRasterLayer.extent())
w = func(self.mMockupRasterLayer, self.mMockupRasterLayer.extent())
#w = func(QgsRasterLayer(), QgsRectangle())
w.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred))
#w.sizeHint = lambda : QSize(300, 50)
w.setMapCanvas(self.mMockupCanvas)
self.stackedWidget.addWidget(w)
self.initActions()
def initActions(self):
self.btnPasteStyle.setDefaultAction(self.actionPasteStyle)
self.btnCopyStyle.setDefaultAction(self.actionCopyStyle)
self.btnApplyStyle.setDefaultAction(self.actionApplyStyle)
clipboardRenderer = rendererFromXml(QApplication.clipboard().mimeData())
self.actionPasteStyle.setEnabled(isinstance(clipboardRenderer, QgsRasterRenderer))
self.actionPasteStyle.triggered.connect(self.pasteStyleFromClipboard)
self.actionCopyStyle.triggered.connect(self.pasteStyleToClipboard)
self.actionApplyStyle.triggered.connect(self.applyStyle)
def mapCanvases(self):
return self.mMapCanvases[:]
def registerMapCanvas(self, mapCanvas):
assert isinstance(mapCanvas, MapCanvas)
self.mMapCanvases.append(mapCanvas)
mapCanvas.sigChangeSVRequest.connect(self.onMapCanvasRendererChangeRequest)
def onMapCanvasRendererChangeRequest(self, mapCanvas, renderer):
self.setRasterRenderer(renderer)
self.applyStyle()
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
def onSensorNameChanged(self, newName):
self.setTitle(self.sensor.name())
self.actionApplyStyle.setToolTip('Apply style to all map view images from "{}"'.format(self.sensor.name()))
def currentRenderWidget(self):
"""
Returns the current QgsRasterRendererWidget
:return: QgsRasterRendererWidget
"""
return self.stackedWidget.currentWidget()
def setRasterRenderer(self, renderer):
assert isinstance(renderer, QgsRasterRenderer)
assert isinstance(self.stackedWidget, QStackedWidget)
self.mMockupRasterLayer.setRenderer(renderer)
#find the widget class that fits
cls = None
for option in self.mRasterRendererModel:
if type(renderer) == option.mRenderType:
cls = option.value()
break
if cls == None:
return
widgets = []
for i in range(self.stackedWidget.count()):
w = self.stackedWidget.widget(i)
if isinstance(w, cls):
widgets.append(w)
if len(widgets) > 0:
for w in widgets:
assert isinstance(w, QgsRasterRendererWidget)
#w.setRasterLayer(self.mMockupRasterLayer)
#w.setFromRenderer(cloneRenderer(renderer))
w.setFromRenderer(renderer)
#w.doComputations()
w = widgets[0]
self.stackedWidget.setCurrentWidget(w)
self.cbRenderType.setCurrentIndex(self.stackedWidget.currentIndex())
def rasterRenderer(self):
return self.stackedWidget.currentWidget().renderer()
def apply(self):
mRendererWidget = self.currentRenderWidget()
mRendererWidget.doComputations()

benjamin.jakimow@geo.hu-berlin.de
committed
def onClipboardChanged(self):
mimeData = QApplication.clipboard().mimeData()
renderer = rendererFromXml(mimeData)
b = isinstance(renderer, QgsRasterRenderer)
#if b == False:
# print(mimeData.formats())
# s = ""
self.actionPasteStyle.setEnabled(b)

benjamin.jakimow@geo.hu-berlin.de
committed
def pasteStyleFromClipboard(self):
mimeData = QApplication.clipboard().mimeData()
renderer = rendererFromXml(mimeData)
if isinstance(renderer, QgsRasterRenderer):
self.setRasterRenderer(renderer)
def pasteStyleToClipboard(self):
xml = rendererToXml(self.rasterRenderer())
assert isinstance(xml, QDomDocument)
md = QMimeData()
#['application/qgis.style', 'text/plain']
md.setData('application/qgis.style', xml.toByteArray())
md.setData('text/plain', xml.toByteArray())
QApplication.clipboard().setMimeData(md)
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
for mapCanvas in self.mMapCanvases:
assert isinstance(mapCanvas, MapCanvas)
mapCanvas.layerModel().setRenderer(r)
mapCanvas.refresh()
RENDER_CLASSES = {}
RENDER_CLASSES['rasterrenderer'] = {
'singlebandpseudocolor':QgsSingleBandPseudoColorRenderer,
'singlebandgray': QgsSingleBandGrayRenderer,
'paletted':QgsPalettedRasterRenderer,
'multibandcolor': QgsMultiBandColorRenderer,
'hillshade': QgsHillshadeRenderer
}
RENDER_CLASSES['renderer-v2'] = {
'categorizedSymbol':QgsCategorizedSymbolRenderer,
'singleSymbol':QgsSingleSymbolRenderer
}
def rendererToXml(renderer):
doc = QDomDocument()
if isinstance(renderer, QgsRasterRenderer):
path = os.path.join(os.path.dirname(__file__), 'dummy_gdal.vrt')
lyr = QgsRasterLayer(path)
lyr.setRenderer(renderer.clone())
elif isinstance(renderer, QgsFeatureRenderer):
#todo: distinguish vector type from requested renderer
lyr = QgsVectorLayer('Point?crs=epsg:4326&field=id:integer', 'dummy', 'memory')
lyr.setRenderer(renderer.clone())
else:
raise NotImplementedError()
err = ''
lyr.exportNamedStyle(doc, err)
return doc
def rendererFromXml(xml):
"""
Reads a string `text` and returns the first QgsRasterRenderer or QgsFeatureRenderer (if defined).
:param text:
:return:
"""
if isinstance(xml, QMimeData):
for format in ['application/qgis.style', 'text/plain']:
if format in xml.formats():
dom = QDomDocument()
dom.setContent(xml.data(format))
return rendererFromXml(dom)
return None
elif isinstance(xml, str):
dom = QDomDocument()
dom.setContent(xml)
return rendererFromXml(dom)
assert isinstance(xml, QDomDocument)
root = xml.documentElement()
for baseClass, renderClasses in RENDER_CLASSES.items():
elements = root.elementsByTagName(baseClass)
if elements.count() > 0:
elem = elements.item(0).toElement()
typeName = elem.attributes().namedItem('type').nodeValue()
if typeName in renderClasses.keys():
rClass = renderClasses[typeName]
if baseClass == 'rasterrenderer':
return rClass.create(elem, DUMMY_RASTERINTERFACE)
elif baseClass == 'renderer-v2':
context = QgsReadWriteContext()
return rClass.load(elem, context)
#return rClass.create(elem)
else:
print(typeName)
s =""
return None

benjamin.jakimow@geo.hu-berlin.de
committed
class DatumViewUI(QFrame, loadUI('timeseriesdatumview.ui')):
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
"""
Widget to host the MapCanvases of all map views that relate to a single Datum-Sensor combinbation.
"""
def __init__(self, title='<#>', parent=None):
super(DatumViewUI, self).__init__(parent)
self.setupUi(self)
def sizeHint(self):
m = self.layout().contentsMargins()
s = QSize(0, 0)
map = None
widgets = [self.layout().itemAt(i).widget() for i in range(self.layout().count())]
widgets = [w for w in widgets if isinstance(w, QWidget)]
maps = [w for w in widgets if isinstance(w, MapCanvas)]
others = [w for w in widgets if not isinstance(w, MapCanvas)]
s = self.layout().spacing()
m = self.layout().contentsMargins()
def totalHeight(widgetList):
total = QSize(0,0)
for w in widgetList:
ws = w.size()
if ws.width() == 0:
ws = w.sizeHint()
if w.isVisible():
total.setWidth(max([total.width(), ws.width()]))
total.setHeight(total.height() + ws.height())
return total
baseSize = totalHeight(widgets)
if baseSize.width() == 0:
for o in others:
baseSize.setWidth(9999)
s = QSize(baseSize.width() + m.left() + m.right(),
baseSize.height() + m.top() + m.bottom())
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
return s
"""
def sizeHint(self):
if not self.ui.isVisible():
return QSize(0,0)
else:
#return self.ui.sizeHint()
size = self.ui.sizeHint()
s = self.ui.layout().spacing()
m = self.ui.layout().contentsMargins()
dx = m.left() + m.right() + s
dy = self.ui.layout().spacing()
n = len([m for m in self.mapCanvases.keys() if m.isVisible()])
if n > 0:
baseSize = self.mapCanvases.values()[0].size()
size = QSize(baseSize.width()+ dx, \
size.height()+ (n+1)*(dy+2*s))
else:
s = ""
return size
"""

benjamin.jakimow@geo.hu-berlin.de
committed
sigRenderProgress = pyqtSignal(int,int)
sigLoadingStarted = pyqtSignal(MapView, TimeSeriesDatum)
sigLoadingFinished = pyqtSignal(MapView, TimeSeriesDatum)
sigVisibilityChanged = pyqtSignal(bool)
assert isinstance(timeSeriesDatum, TimeSeriesDatum)
assert isinstance(stv, SpatialTemporalVisualization)

benjamin.jakimow@geo.hu-berlin.de
committed

benjamin.jakimow@geo.hu-berlin.de
committed
self.ui.create()
self.showLoading(False)
self.wOffset = self.ui.layout().count()-1

benjamin.jakimow@geo.hu-berlin.de
committed
self.minHeight = self.ui.height()

benjamin.jakimow@geo.hu-berlin.de
committed
self.renderProgress = dict()
assert isinstance(stv, SpatialTemporalVisualization)
self.STV = stv
self.mSensor = self.TSD.sensor
self.mSensor.sigNameChanged.connect(lambda :self.setColumnInfo())
self.TSD.sigVisibilityChanged.connect(self.setVisibility)

benjamin.jakimow@geo.hu-berlin.de
committed
self.setColumnInfo()

benjamin.jakimow@geo.hu-berlin.de
committed
self.mapCanvases = dict()
self.mRenderState = dict()

benjamin.jakimow@geo.hu-berlin.de
committed

benjamin.jakimow@geo.hu-berlin.de
committed
def setColumnInfo(self):
labelTxt = '{}\n{}'.format(str(self.TSD.date), self.TSD.sensor.name())
tooltip = '{}'.format(self.TSD.pathImg)

benjamin.jakimow@geo.hu-berlin.de
committed
self.ui.labelTitle.setText(labelTxt)
self.ui.labelTitle.setToolTip(tooltip)

benjamin.jakimow@geo.hu-berlin.de
committed
def setVisibility(self, b):
self.ui.setVisible(b)
self.sigVisibilityChanged.emit(b)

benjamin.jakimow@geo.hu-berlin.de
committed
def setHighlighted(self, b=True, timeout=1000):
styleOn = """.QFrame {
border: 4px solid red;
border-radius: 4px;
}"""
styleOff = """"""
if b is True:
self.ui.setStyleSheet(styleOn)
if timeout > 0:
QTimer.singleShot(timeout, lambda : self.setHighlighted(b=False))
else:
self.ui.setStyleSheet(styleOff)

benjamin.jakimow@geo.hu-berlin.de
committed
def removeMapView(self, mapView):
canvas = self.mapCanvases.pop(mapView)
self.ui.layout().removeWidget(canvas)

benjamin.jakimow@geo.hu-berlin.de
committed
canvas.close()

benjamin.jakimow@geo.hu-berlin.de
committed
def refresh(self):

benjamin.jakimow@geo.hu-berlin.de
committed
if self.ui.isVisible():
for c in self.mapCanvases.values():
if c.isVisible():

benjamin.jakimow@geo.hu-berlin.de
committed
def insertMapView(self, mapView):
assert isinstance(mapView, MapView)
from timeseriesviewer.mapcanvas import MapCanvas

benjamin.jakimow@geo.hu-berlin.de
committed
mapCanvas.setObjectName('MapCanvas {} {}'.format(mapView.title(), self.TSD.date))
mapCanvas.setMapView(mapView)
mapCanvas.setTSD(self.TSD)
self.registerMapCanvas(mapView, mapCanvas)

benjamin.jakimow@geo.hu-berlin.de
committed
mapView.registerMapCanvas(self.mSensor, mapCanvas)
# register MapCanvas on STV level
self.STV.registerMapCanvas(mapCanvas)
mapCanvas.renderComplete.connect(lambda : self.onRenderingChange(False))
mapCanvas.renderStarting.connect(lambda : self.onRenderingChange(True))

benjamin.jakimow@geo.hu-berlin.de
committed
mapCanvas.sigDataLoadingFinished.connect(
lambda dt: self.STV.TSV.ui.dockSystemInfo.addTimeDelta('Map {}'.format(self.mSensor.name()), dt))

benjamin.jakimow@geo.hu-berlin.de
committed
mapCanvas.sigDataLoadingFinished.connect(
lambda dt: self.STV.TSV.ui.dockSystemInfo.addTimeDelta('All Sensors', dt))
def showLoading(self, b):
if b:
self.ui.progressBar.setRange(0,0)
self.ui.progressBar.setValue(-1)
else:
self.ui.progressBar.setRange(0,1)
self.ui.progressBar.setValue(0)
def onRenderingChange(self, b):
mc = self.sender()
#assert isinstance(mc, QgsMapCanvas)
self.mRenderState[mc] = b
self.showLoading(any(self.mRenderState.values()))
def onRendering(self, *args):
renderFlags = [m.renderFlag() for m in self.mapCanvases.values()]
drawFlags = [m.isDrawing() for m in self.mapCanvases.values()]

benjamin.jakimow@geo.hu-berlin.de
committed
# print((renderFlags, drawFlags))
isLoading = any(renderFlags)
self.showLoading(isLoading)
s = ""

benjamin.jakimow@geo.hu-berlin.de
committed
def registerMapCanvas(self, mapView, mapCanvas):
from timeseriesviewer.mapcanvas import MapCanvas
assert isinstance(mapCanvas, MapCanvas)
#mapView.sigTitleChanged.connect(lambda title : mapCanvas.setSaveFileName('{}_{}'.format(self.TSD.date, title)))
mapCanvas.layerModel().setRasterLayerSources([self.TSD.pathImg])
self.ui.layout().insertWidget(self.wOffset + len(self.mapCanvases), mapCanvas)
self.ui.update()
#register signals handled on (this) DV level
mapCanvas.renderStarting.connect(lambda: self.sigLoadingStarted.emit(mapView, self.TSD))
mapCanvas.mapCanvasRefreshed.connect(lambda: self.sigLoadingFinished.emit(mapView, self.TSD))
mapCanvas.sigShowProfiles.connect(lambda c, t : mapView.sigShowProfiles.emit(c,mapCanvas, t))
mapCanvas.sigChangeDVRequest.connect(self.onMapCanvasRequest)

benjamin.jakimow@geo.hu-berlin.de
committed
def onMapCanvasRequest(self, mapCanvas, key):
if key == 'hide_date':
self.TSD.setVisibility(False)
if key == 'copy_sensor':
QApplication.clipboard().setText(self.TSD.sensor.name())
if key == 'copy_date':
QApplication.clipboard().setText(str(self.TSD.date))
if key == 'copy_path':
QApplication.clipboard().setText(str(self.TSD.pathImg))

benjamin.jakimow@geo.hu-berlin.de
committed
def __lt__(self, other):
assert isinstance(other, DatumView)
return self.TSD < other.TSD

benjamin.jakimow@geo.hu-berlin.de
committed
def __eq__(self, other):
assert isinstance(other, DatumView)
return self.TSD == other.TSD

benjamin.jakimow@geo.hu-berlin.de
committed
class SpatialTemporalVisualization(QObject):
"""
"""
sigLoadingStarted = pyqtSignal(DatumView, MapView)
sigLoadingFinished = pyqtSignal(DatumView, MapView)
sigShowProfiles = pyqtSignal(SpatialPoint, MapCanvas, str)

benjamin.jakimow@geo.hu-berlin.de
committed
sigShowMapLayerInfo = pyqtSignal(dict)
sigSpatialExtentChanged = pyqtSignal(SpatialExtent)
sigCRSChanged = pyqtSignal(QgsCoordinateReferenceSystem)

benjamin.jakimow@geo.hu-berlin.de
committed
def __init__(self, timeSeriesViewer):
super(SpatialTemporalVisualization, self).__init__()

benjamin.jakimow@geo.hu-berlin.de
committed
#assert isinstance(timeSeriesViewer, TimeSeriesViewer), timeSeriesViewer
#default map settings
self.mSpatialExtent = SpatialExtent.world()
self.mCRS = self.mSpatialExtent.crs()
self.mSize = QSize(200,200)
self.mColor = Qt.black

benjamin.jakimow@geo.hu-berlin.de
committed
self.ui = timeSeriesViewer.ui
#map-tool handling
self.mMapToolActivator = None
self.mMapTools = []

benjamin.jakimow@geo.hu-berlin.de
committed
self.scrollArea = self.ui.scrollAreaSubsets
assert isinstance(self.scrollArea, MapViewScrollArea)
self.mRefreshTimer = QTimer(self)
self.mRefreshTimer.setInterval(1000)
self.mRefreshTimer.timeout.connect(self.refresh)
self.scrollArea.sigResized.connect(self.mRefreshTimer.start)
self.scrollArea.horizontalScrollBar().valueChanged.connect(self.mRefreshTimer.start)

benjamin.jakimow@geo.hu-berlin.de
committed
self.TSV = timeSeriesViewer
self.TS = timeSeriesViewer.TS

benjamin.jakimow@geo.hu-berlin.de
committed
self.targetLayout = self.ui.scrollAreaSubsetContent.layout()
#self.MVC = MapViewCollection(self)
#self.MVC.sigShowProfiles.connect(self.sigShowProfiles.emit)
self.MVC = self.ui.dockMapViews
assert isinstance(self.MVC, MapViewCollectionDock)

benjamin.jakimow@geo.hu-berlin.de
committed
self.MVC.sigShowProfiles.connect(self.sigShowProfiles.emit)
self.vectorOverlay = None
self.DVC.sigResizeRequired.connect(self.adjustScrollArea)

Benjamin Jakimow
committed
#self.DVC.sigLoadingStarted.connect(self.ui.dockRendering.addStartedWork)
#self.DVC.sigLoadingFinished.connect(self.ui.dockRendering.addFinishedWork)
#self.timeSeriesDateViewCollection.sigSpatialExtentChanged.connect(self.setSpatialExtent)
self.TS.sigTimeSeriesDatesAdded.connect(self.DVC.addDates)
self.TS.sigTimeSeriesDatesRemoved.connect(self.DVC.removeDates)

benjamin.jakimow@geo.hu-berlin.de
committed
#add dates, if already existing

benjamin.jakimow@geo.hu-berlin.de
committed
if len(self.TS) > 0:
self.setSpatialExtent(self.TS.getMaxSpatialExtent())

benjamin.jakimow@geo.hu-berlin.de
committed

benjamin.jakimow@geo.hu-berlin.de
committed
def createMapView(self):
self.MVC.createMapView()
def registerMapCanvas(self, mapCanvas):
from timeseriesviewer.mapcanvas import MapCanvas
assert isinstance(mapCanvas, MapCanvas)
self.mMapCanvases.append(mapCanvas)
#set general canvas properties
mapCanvas.setFixedSize(self.mSize)
mapCanvas.setCrs(self.mCRS)
mapCanvas.setSpatialExtent(self.mSpatialExtent)
#register on map canvas signals
mapCanvas.sigSpatialExtentChanged.connect(lambda e: self.setSpatialExtent(e, mapCanvas))

benjamin.jakimow@geo.hu-berlin.de
committed
def setCrosshairStyle(self, crosshairStyle):
from timeseriesviewer.mapcanvas import MapCanvas
for mapCanvas in self.mMapCanvases:
assert isinstance(mapCanvas, MapCanvas)
mapCanvas.setCrosshairStyle(crosshairStyle)
#self.MVC.setCrosshairStyle(crosshairStyle)

benjamin.jakimow@geo.hu-berlin.de
committed
def setShowCrosshair(self, b):
self.MVC.setShowCrosshair(b)
def setVectorLayer(self, lyr):
self.MVC.setVectorLayer(lyr)

benjamin.jakimow@geo.hu-berlin.de
committed
assert isinstance(size, QSize)
from timeseriesviewer.mapcanvas import MapCanvas
for mapCanvas in self.mMapCanvases:
assert isinstance(mapCanvas, MapCanvas)
mapCanvas.setFixedSize(size)
self.sigMapSizeChanged.emit(self.mSize)

benjamin.jakimow@geo.hu-berlin.de
committed
self.adjustScrollArea()
def subsetSize(self):
return QSize(self.mSize)

benjamin.jakimow@geo.hu-berlin.de
committed
def refresh(self):

benjamin.jakimow@geo.hu-berlin.de
committed
tsdView.refresh()

benjamin.jakimow@geo.hu-berlin.de
committed
def adjustScrollArea(self):
#adjust scroll area widget to fit all visible widgets
m = self.targetLayout.contentsMargins()

benjamin.jakimow@geo.hu-berlin.de
committed
w = h = 0
s = QSize()
r = None
tsdViews = [v for v in self.DVC if v.ui.isVisible()]
mapViews = [v for v in self.MVC if v.isVisible()]
nX = len(tsdViews)
nY = len(mapViews)
spacing = self.targetLayout.spacing()
margins = self.targetLayout.contentsMargins()

benjamin.jakimow@geo.hu-berlin.de
committed
sizeX = 1
sizeY = 50
if nX > 0:
s = tsdViews[0].ui.sizeHint().width()
s = nX * (s + spacing) + margins.left() + margins.right()
sizeX = s
if nY > 0 and nX > 0:
s = tsdViews[0].ui.sizeHint().height()
s = s + margins.top() + margins.bottom()

benjamin.jakimow@geo.hu-berlin.de
committed
#s = tsdViews[0].ui.sizeHint()
#s = QSize(nX * (s.width() + spacing) + margins.left() + margins.right(),
# s.height() + margins.top() + margins.bottom())

benjamin.jakimow@geo.hu-berlin.de
committed
#print(sizeX, sizeY)
self.targetLayout.parentWidget().setFixedSize(QSize(sizeX, sizeY))

benjamin.jakimow@geo.hu-berlin.de
committed
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
def setMapTool(self, mapToolKey, *args, **kwds):
# filter map tools
self.mMapToolActivator = self.sender()
del self.mMapTools[:]
from timeseriesviewer.mapcanvas import MapTools, CursorLocationMapTool, SpectralProfileMapTool, TemporalProfileMapTool
for canvas in self.mMapCanvases:
mt = None
if mapToolKey in MapTools.mapToolKeys():
mt = MapTools.create(mapToolKey, canvas, *args, **kwds)
if isinstance(mapToolKey, QgsMapTool):
mt = MapTools.copy(mapToolKey, canvas, *args, **kwds)
if isinstance(mt, QgsMapTool):
canvas.setMapTool(mt)
self.mMapTools.append(mt)
#if required, link map-tool with specific EnMAP-Box slots
if isinstance(mt, CursorLocationMapTool):
mt.sigLocationRequest[SpatialPoint, QgsMapCanvas].connect(lambda c, m : self.sigShowProfiles.emit(c,m, mapToolKey))
return self.mMapTools

benjamin.jakimow@geo.hu-berlin.de
committed
def setMaxTSDViews(self, n=-1):
self.nMaxTSDViews = n
#todo: remove views
def setSpatialCenter(self, center, mapCanvas0=None):
if self.mBlockCanvasSignals:
return True
assert isinstance(center, SpatialPoint)
center = center.toCrs(self.mCRS)
if not isinstance(center, SpatialPoint):
return
self.mBlockCanvasSignals = True
self.mSpatialExtent.setCenter(center)
for mapCanvas in self.mMapCanvases:
if mapCanvas != mapCanvas0:
oldState = mapCanvas.blockSignals(True)
mapCanvas.setCenter(center)
mapCanvas.blockSignals(oldState)
self.mBlockCanvasSignals = False
self.sigSpatialExtentChanged.emit(self.mSpatialExtent)
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
def setSpatialCenter(self, center, mapCanvas0=None):
if self.mBlockCanvasSignals:
return True
assert isinstance(center, SpatialPoint)
center = center.toCrs(self.mCRS)
if not isinstance(center, SpatialPoint):
return None
self.mBlockCanvasSignals = True
for mapCanvas in self.mMapCanvases:
if mapCanvas != mapCanvas0:
oldState = mapCanvas.blockSignals(True)
mapCanvas.setCenter(center)
mapCanvas.blockSignals(oldState)
self.mBlockCanvasSignals = False
#for mapCanvas in self.mMapCanvases:
# mapCanvas.refresh()
self.mRefreshTimer.start()
def setSpatialExtent(self, extent, mapCanvas0=None):
if self.mBlockCanvasSignals:
return True
assert isinstance(extent, SpatialExtent)
extent = extent.toCrs(self.mCRS)
if not isinstance(extent, SpatialExtent) \
or extent.isEmpty() or not extent.isFinite() \
or extent.width() <= 0 \
or extent.height() <= 0 \
or extent == self.mSpatialExtent:
self.mBlockCanvasSignals = True
self.mSpatialExtent = extent
for mapCanvas in self.mMapCanvases:
if mapCanvas != mapCanvas0:
oldState = mapCanvas.blockSignals(True)
mapCanvas.setExtent(extent)
mapCanvas.blockSignals(oldState)
#for mapCanvas in self.mMapCanvases:
# mapCanvas.refresh()
self.sigSpatialExtentChanged.emit(extent)

benjamin.jakimow@geo.hu-berlin.de
committed
def setBackgroundColor(self, color):
assert isinstance(color, QColor)
self.mColor = color
for mapCanvas in self.mMapCanvases:
assert isinstance(mapCanvas, MapCanvas)
mapCanvas.setCanvasColor(color)
mapCanvas.refresh()
def backgroundColor(self):
return self.mColor
def mapCanvasIterator(self):
return self.mMapCanvases[:]
def setCrs(self, crs):
assert isinstance(crs, QgsCoordinateReferenceSystem)
from timeseriesviewer.utils import saveTransform
if saveTransform(self.mSpatialExtent, self.mCRS, crs):
self.mCRS = crs
for mapCanvas in self.mapCanvasIterator():
#print(('STV set CRS {} {}', str(mapCanvas), self.mCRS.description()))
mapCanvas.setCrs(crs)
else:
pass
self.sigCRSChanged.emit(self.mCRS)

benjamin.jakimow@geo.hu-berlin.de
committed
def spatialExtent(self):
return self.mSpatialExtent

benjamin.jakimow@geo.hu-berlin.de
committed
def navigateToTSD(self, TSD):
assert isinstance(TSD, TimeSeriesDatum)
#get widget related to TSD

benjamin.jakimow@geo.hu-berlin.de
committed
assert isinstance(self.scrollArea, QScrollArea)
self.scrollArea.ensureWidgetVisible(tsdv.ui)

benjamin.jakimow@geo.hu-berlin.de
committed
sigResizeRequired = pyqtSignal()
sigLoadingStarted = pyqtSignal(MapView, TimeSeriesDatum)
sigLoadingFinished = pyqtSignal(MapView, TimeSeriesDatum)

benjamin.jakimow@geo.hu-berlin.de
committed
sigShowProfiles = pyqtSignal(SpatialPoint)
sigSpatialExtentChanged = pyqtSignal(SpatialExtent)

benjamin.jakimow@geo.hu-berlin.de
committed
def __init__(self, STViz):
assert isinstance(STViz, SpatialTemporalVisualization)
super(DateViewCollection, self).__init__()

benjamin.jakimow@geo.hu-berlin.de
committed
#self.tsv = tsv
#self.timeSeries = tsv.TS
self.views = list()
self.STV = STViz
self.ui = self.STV.targetLayout.parentWidget()

benjamin.jakimow@geo.hu-berlin.de
committed
self.scrollArea = self.ui.parentWidget().parentWidget()
#potentially there are many more dates than views.
#therefore we implement the addinng/removing of mapviews here
#we reduce the number of layout refresh calls by
#suspending signals, adding the new map view canvases, and sending sigResizeRequired
self.STV.MVC.sigMapViewAdded.connect(self.addMapView)
self.STV.MVC.sigMapViewRemoved.connect(self.removeMapView)

benjamin.jakimow@geo.hu-berlin.de
committed
self.setFocusView(None)

benjamin.jakimow@geo.hu-berlin.de
committed
def tsdFromMapCanvas(self, mapCanvas):
assert isinstance(mapCanvas, MapCanvas)
for view in self.views:
assert isinstance(view, DatumView)
if mapCanvas in view.mapCanvases.values():
return view.TSD
return None

benjamin.jakimow@geo.hu-berlin.de
committed
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
def tsdView(self, tsd):
r = [v for v in self.views if v.TSD == tsd]
if len(r) == 1:
return r[0]
else:
raise Exception('TSD not in list')
def addMapView(self, mapView):
assert isinstance(mapView, MapView)
w = self.ui
w.setUpdatesEnabled(False)
for tsdv in self.views:
tsdv.ui.setUpdatesEnabled(False)
for tsdv in self.views:
tsdv.insertMapView(mapView)
for tsdv in self.views:
tsdv.ui.setUpdatesEnabled(True)
#mapView.sigSensorRendererChanged.connect(lambda *args : self.setRasterRenderer(mapView, *args))
mapView.sigMapViewVisibility.connect(lambda: self.sigResizeRequired.emit())
mapView.sigShowProfiles.connect(self.sigShowProfiles.emit)

benjamin.jakimow@geo.hu-berlin.de
committed
w.setUpdatesEnabled(True)

benjamin.jakimow@geo.hu-berlin.de
committed
self.sigResizeRequired.emit()
def removeMapView(self, mapView):
assert isinstance(mapView, MapView)
for tsdv in self.views:
tsdv.removeMapView(mapView)
self.sigResizeRequired.emit()

benjamin.jakimow@geo.hu-berlin.de
committed
def highlightDate(self, tsd):
"""
Highlights a time series data for a specific time our
:param tsd:
:return:
"""
tsdView = self.tsdView(tsd)
if isinstance(tsdView, DatumView):
tsdView.setHighlight(True)

benjamin.jakimow@geo.hu-berlin.de
committed
def setFocusView(self, tsd):
self.focusView = tsd
def orderedViews(self):
#returns the
if self.focusView is not None:
assert isinstance(self.focusView, DatumView)

benjamin.jakimow@geo.hu-berlin.de
committed
return sorted(self.views,key=lambda v: np.abs(v.TSD.date - self.focusView.TSD.date))
else:
return self.views

benjamin.jakimow@geo.hu-berlin.de
committed
def setSubsetSize(self, size):
assert isinstance(size, QSize)
self.subsetSize = size
for tsdView in self.orderedViews():
tsdView.blockSignals(True)
for tsdView in self.orderedViews():
tsdView.setSubsetSize(size)
for tsdView in self.orderedViews():
tsdView.blockSignals(False)

benjamin.jakimow@geo.hu-berlin.de
committed
def addDates(self, tsdList):
"""
Create a new TSDView
:param tsdList:
:return:
"""
for tsd in tsdList:
assert isinstance(tsd, TimeSeriesDatum)
#tsdView.setSubsetSize(self.subsetSize)
DV.sigLoadingStarted.connect(self.sigLoadingStarted.emit)
DV.sigLoadingFinished.connect(self.sigLoadingFinished.emit)
DV.sigVisibilityChanged.connect(lambda: self.STV.adjustScrollArea())

benjamin.jakimow@geo.hu-berlin.de
committed
for i, mapView in enumerate(self.STV.MVC):
DV.insertMapView(mapView)

benjamin.jakimow@geo.hu-berlin.de
committed
bisect.insort(self.views, DV)
i = self.views.index(DV)

benjamin.jakimow@geo.hu-berlin.de
committed
DV.ui.setParent(self.STV.targetLayout.parentWidget())
self.STV.targetLayout.insertWidget(i, DV.ui)
DV.ui.show()

benjamin.jakimow@geo.hu-berlin.de
committed
if len(tsdList) > 0:
self.sigResizeRequired.emit()
def removeDates(self, tsdList):
toRemove = [v for v in self.views if v.TSD in tsdList]
removedDates = []
for DV in toRemove:
self.views.remove(DV)

benjamin.jakimow@geo.hu-berlin.de
committed
for mapCanvas in DV.mapCanvases.values():
toRemove = mapCanvas.layers()
mapCanvas.setLayers([])
toRemove = [l for l in toRemove if isinstance(l, QgsRasterLayer)]
if len(toRemove) > 0:
QgsProject.instance().removeMapLayers([l.id() for l in toRemove])

benjamin.jakimow@geo.hu-berlin.de
committed
DV.ui.parent().layout().removeWidget(DV.ui)
DV.ui.hide()
DV.ui.close()
removedDates.append(DV.TSD)
del DV

benjamin.jakimow@geo.hu-berlin.de
committed
if len(removedDates) > 0:
self.sigResizeRequired.emit()
def __len__(self):
return len(self.views)
def __iter__(self):
return iter(self.views)
def __getitem__(self, slice):
return self.views[slice]
def __delitem__(self, slice):
self.removeDates(self.views[slice])
class MapViewListModel(QAbstractListModel):
"""
A model to keep a list of map views.
"""
sigMapViewsAdded = pyqtSignal(list)
sigMapViewsRemoved = pyqtSignal(list)
def __init__(self, parent=None):
super(MapViewListModel, self).__init__(parent)
self.mMapViewList = []
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
def addMapView(self, mapView):
i = len(self.mMapViewList)
self.insertMapView(i, mapView)
def insertMapView(self, i, mapView):
self.insertMapViews(i, [mapView])
def insertMapViews(self, i, mapViews):
assert isinstance(mapViews, list)
assert i >= 0 and i <= len(self.mMapViewList)
self.beginInsertRows(QModelIndex(), i, i + len(mapViews) - 1)
for j in range(len(mapViews)):
mapView = mapViews[j]
assert isinstance(mapView, MapView)
mapView.sigTitleChanged.connect(
lambda : self.doRefresh([mapView])
)
self.mMapViewList.insert(i + j, mapView)
self.endInsertRows()
self.sigMapViewsAdded.emit(mapViews)
def doRefresh(self, mapViews):
for mapView in mapViews:
idx = self.mapView2idx(mapView)
self.dataChanged.emit(idx, idx)
def removeMapView(self, mapView):
self.removeMapViews([mapView])
def removeMapViews(self, mapViews):
assert isinstance(mapViews, list)
for mv in mapViews:
assert mv in self.mMapViewList
idx = self.mapView2idx(mv)
self.beginRemoveRows(idx.parent(), idx.row(), idx.row())
self.mMapViewList.remove(mv)
self.endRemoveRows()
self.sigMapViewsRemoved.emit(mapViews)
def rowCount(self, parent=None, *args, **kwargs):
return len(self.mMapViewList)
def columnCount(self, QModelIndex_parent=None, *args, **kwargs):
return 1
def idx2MapView(self, index):
if isinstance(index, QModelIndex):
if index.isValid():
index = index.row()
else:
return None
assert index >= 0 and index < len(self.mMapViewList)
return self.mMapViewList[index]
def mapView2idx(self, mapView):
assert isinstance(mapView, MapView)
row = self.mMapViewList.index(mapView)
return self.createIndex(row, 0, mapView)
def __len__(self):
return len(self.mMapViewList)
def __iter__(self):
return iter(self.mMapViewList)
def __getitem__(self, slice):
return self.mMapViewList[slice]
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return None
if (index.row() >= len(self.mMapViewList)) or (index.row() < 0):
return None
mapView = self.idx2MapView(index)
assert isinstance(mapView, MapView)
value = None
if role == Qt.DisplayRole:
value = '{} {}'.format(index.row() +1 , mapView.title())
#if role == Qt.DecorationRole:
#value = classInfo.icon(QSize(20,20))
if role == Qt.UserRole:
value = mapView
return value

benjamin.jakimow@geo.hu-berlin.de
committed
class MapViewCollectionDock(QgsDockWidget, loadUI('mapviewdock.ui')):
sigMapViewAdded = pyqtSignal(MapView)
sigMapViewRemoved = pyqtSignal(MapView)
sigShowProfiles = pyqtSignal(SpatialPoint, MapCanvas, str)

Benjamin Jakimow
committed
sigMapCanvasColorChanged = pyqtSignal(QColor)
sigSpatialExtentChanged = pyqtSignal(SpatialExtent)
sigCrsChanged = pyqtSignal(QgsCoordinateReferenceSystem)
sigMapSizeChanged = pyqtSignal(QSize)
def setTimeSeries(self, timeSeries):
assert isinstance(timeSeries, TimeSeries)
self.TS = timeSeries
self.TS.sigSensorAdded.connect(self.addSensor)
self.TS.sigSensorRemoved.connect(self.removeSensor)
self.mMapViews = MapViewListModel()
self.btnAddMapView.setDefaultAction(self.actionAddMapView)
self.btnRemoveMapView.setDefaultAction(self.actionRemoveMapView)
self.btnRefresh.setDefaultAction(self.actionApplyStyles)

benjamin.jakimow@geo.hu-berlin.de
committed
self.btnHighlightMapView.setDefaultAction(self.actionHighlightMapView)

Benjamin Jakimow
committed
self.btnCrs.crsChanged.connect(self.sigCrsChanged)
self.btnMapCanvasColor.colorChanged.connect(self.sigMapCanvasColorChanged)
self.btnApplySizeChanges.clicked.connect(lambda : self.sigMapSizeChanged.emit(QSize(self.spinBoxMapSizeX.value(),self.spinBoxMapSizeY.value())))
self.actionAddMapView.triggered.connect(self.createMapView)
self.actionRemoveMapView.triggered.connect(lambda : self.removeMapView(self.currentMapView()) if self.currentMapView() else None)
self.actionHighlightMapView.triggered.connect(lambda : self.currentMapView().setHighlighted(True) if self.currentMapView() else None)
self.actionApplyStyles.triggered.connect(self.refreshCurrentMapView)
#self.actionApplyStyles.triggered.connect(self.dummySlot)
self.mMapViews.sigMapViewsRemoved.connect(self.onMapViewsRemoved)
self.mMapViews.sigMapViewsAdded.connect(self.onMapViewsAdded)
self.mMapViews.sigMapViewsAdded.connect(self.updateButtons)
self.mMapViews.sigMapViewsRemoved.connect(self.updateButtons)
self.cbMapView.currentIndexChanged[int].connect(lambda i : None if i < 0 else self.setCurrentMapView(self.mMapViews.idx2MapView(i)) )

Benjamin Jakimow
committed
self.spinBoxMapSizeX.valueChanged.connect(lambda: self.onMapSizeChanged('X'))
self.spinBoxMapSizeY.valueChanged.connect(lambda: self.onMapSizeChanged('Y'))
self.mLastMapSize = self.mapSize()
#self.mapSize() #inits mLastMapSize

Benjamin Jakimow
committed
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
def setCrs(self, crs):
assert isinstance(crs, QgsCoordinateReferenceSystem)
self.btnCrs.setCrs(crs)
self.btnCrs.setLayerCrs(crs)
def setMapSize(self, size):
assert isinstance(size, QSize)
ws = [self.spinBoxMapSizeX, self.spinBoxMapSizeY]
oldSize = self.mapSize()
b = oldSize != size
for w in ws:
w.blockSignals(True)
self.spinBoxMapSizeX.setValue(size.width()),
self.spinBoxMapSizeY.setValue(size.height())
self.mLastMapSize = QSize(size)
for w in ws:
w.blockSignals(False)
self.mLastMapSize = QSize(size)
if b:
self.sigMapSizeChanged.emit(size)
def onMapSizeChanged(self, dim):
newSize = self.mapSize()
#1. set size of other dimension accordingly
if dim is not None:
if self.checkBoxKeepSubsetAspectRatio.isChecked():
if dim == 'X':
vOld = self.mLastMapSize.width()
vNew = newSize.width()
targetSpinBox = self.spinBoxMapSizeY
elif dim == 'Y':
vOld = self.mLastMapSize.height()
vNew = newSize.height()
targetSpinBox = self.spinBoxMapSizeX
oldState = targetSpinBox.blockSignals(True)
targetSpinBox.setValue(int(round(float(vNew) / vOld * targetSpinBox.value())))
targetSpinBox.blockSignals(oldState)
newSize = self.mapSize()
if newSize != self.mLastMapSize:
self.btnApplySizeChanges.setEnabled(True)
else:
self.sigMapSizeChanged.emit(self.mapSize())
self.btnApplySizeChanges.setEnabled(False)
self.setMapSize(newSize)
def mapSize(self):
return QSize(self.spinBoxMapSizeX.value(),
self.spinBoxMapSizeY.value())
def refreshCurrentMapView(self, *args):
mv = self.currentMapView()
if isinstance(mv, MapView):
mv.refreshMapView()
else:
s =""
def dummySlot(self):
s =""
for mapView in mapViews:
idx = self.stackedWidget.indexOf(mapView.ui)
if idx >= 0:
self.stackedWidget.removeWidget(mapView.ui)
mapView.ui.close()
else:
s = ""
self.actionRemoveMapView.setEnabled(len(self.mMapViews) > 0)
def onMapViewsAdded(self, mapViews):
nextShown = None
for mapView in mapViews:
mapView.sigTitleChanged.connect(self.updateTitle)
self.stackedWidget.addWidget(mapView.ui)
if nextShown is None:
nextShown = mapView
contents = mapView.ui.scrollAreaWidgetContents
size = contents.size()
hint = contents.sizeHint()
#mapView.ui.scrollArea.update()
s = ""
#setMinimumSize(mapView.ui.scrollAreaWidgetContents.sizeHint())
#hint = contents.sizeHint()
#contents.setMinimumSize(hint)
if isinstance(nextShown, MapView):
self.setCurrentMapView(nextShown)
def updateButtons(self, *args):
b = len(self.mMapViews) > 0
self.actionRemoveMapView.setEnabled(b)
self.actionApplyStyles.setEnabled(b)
self.actionHighlightMapView.setEnabled(b)
n = len(self.mMapViews) + 1
title = 'Map View {}'.format(n)
while title in [m.title() for m in self.mMapViews]:
n += 1
title = 'Map View {}'.format(n)
mapView.setTitle(title)
mapView.sigShowProfiles.connect(self.sigShowProfiles)
if isinstance(mapView, MapView):
assert mapView in self.mMapViews
i = self.mMapViews.mapView2idx(mapView)
if not i == self.stackedWidget.indexOf(mapView.ui):
s = ""
self.mMapViews.removeMapView(mapView)
self.sigMapViewRemoved.emit(mapView)
def __getitem__(self, slice):
return self.mMapViews[slice]
def __contains__(self, mapView):
return mapView in self.mMapViews
def index(self, mapView):
assert isinstance(mapView, MapView)
return self.mMapViews.index(mapView)
def setVectorLayer(self, lyr):
for mapView in self.mMapViews:
assert isinstance(mapView, MapView)
mapView.setVectorLayer(lyr)
def addSensor(self, sensor):
for mapView in self.mMapViews:
mapView.addSensor(sensor)
def removeSensor(self, sensor):
for mapView in self.mMapViews:
mapView.removeSensor(sensor)
def applyStyles(self):
for mapView in self.mMapViews:
mapView.applyStyles()
def setCrosshairStyle(self, crosshairStyle):
for mapView in self.mMapViews:
mapView.setCrosshairStyle(crosshairStyle)
def setShowCrosshair(self, b):
for mapView in self.mMapViews:
mapView.setShowCrosshair(b)
def index(self, mapView):
assert isinstance(mapView, MapView)
return self.mapViewsDefinitions.index(mapView)
def setCurrentMapView(self, mapView):
assert isinstance(mapView, MapView) and mapView in self.mMapViews
idx = self.stackedWidget.indexOf(mapView.ui)
if idx >= 0:
self.stackedWidget.setCurrentIndex(idx)
self.cbMapView.setCurrentIndex(self.mMapViews.mapView2idx(mapView).row())
self.updateTitle()
def updateTitle(self, *args):
# self.btnToggleMapViewVisibility.setChecked(mapView)
mapView = self.currentMapView()
if isinstance(mapView, MapView):
if mapView in self.mMapViews:
i = str(self.mMapViews.mapView2idx(mapView).row()+1)
else:
i = ''
#title = '{} | {} "{}"'.format(self.baseTitle, i, mapView.title())
title = '{} | {}'.format(self.baseTitle, i)
self.setWindowTitle(title)
if len(self.mMapViews) == 0:
return None
else:
i = self.cbMapView.currentIndex()
if i >= 0:
return self.mMapViews.idx2MapView(i)
else:
return None

benjamin.jakimow@geo.hu-berlin.de
committed

benjamin.jakimow@geo.hu-berlin.de
committed
if __name__ == '__main__':
from timeseriesviewer import utils
from timeseriesviewer.mapcanvas import MapCanvas
from example.Images import Img_2014_01_15_LC82270652014015LGN00_BOA, re_2014_06_25

benjamin.jakimow@geo.hu-berlin.de
committed

benjamin.jakimow@geo.hu-berlin.de
committed
from example import exampleEvents
rDir = r'C:\Users\geo_beja\Repositories\QGIS_Plugins\eo-time-series-viewer\qgisresources'
qgsApp = utils.initQgisApplication(qgisResourceDir=rDir)
TS = TimeSeries()
TS.addFiles([Img_2014_01_15_LC82270652014015LGN00_BOA, re_2014_06_25])
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
dock = MapViewCollectionDock()
dock.setTimeSeries(TS)
dock.show()
mv1 = dock.createMapView()
mv2 = dock.createMapView()
dock.setCurrentMapView(mv1)
assert dock.currentMapView() == mv1
dock.setCurrentMapView(mv2)
assert dock.currentMapView() == mv2
vl = QgsVectorLayer(exampleEvents, 'ogr')
QgsProject.instance().addMapLayer(vl)
#d = QgsRendererPropertiesDialog(vl, QgsStyle.defaultStyle())
#d.show()
else:
w = MapViewRenderSettingsV2(TS.sensors()[0])
w.show()
w.setRasterRenderer(w.rasterRenderer())
#renderer2 = w.rasterRenderer()
#print(renderer2)

benjamin.jakimow@geo.hu-berlin.de
committed

benjamin.jakimow@geo.hu-berlin.de
committed
qgsApp.exec_()