forked from anitagraser/TimeManager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timemanagerguicontrol.py
462 lines (373 loc) · 19.1 KB
/
timemanagerguicontrol.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
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 29 10:13:39 2010
@author: agraser
"""
import os, sys
sys.path.append("~/.qgis/python")
from string import replace
from time import mktime
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import uic
from qgis.core import *
from timelayer import *
from timevectorlayer import *
from timerasterlayer import *
class TimeManagerGuiControl(QObject):
"""This class controls all plugin-related GUI elements. Emitted signals are defined here.
New TimeLayers are created here, in createTimeLayer()"""
showOptions = pyqtSignal()
exportVideo = pyqtSignal()
toggleTime = pyqtSignal()
back = pyqtSignal()
forward = pyqtSignal()
play = pyqtSignal()
signalCurrentTime = pyqtSignal(object)
signalTimeFrameType = pyqtSignal(str)
signalTimeFrameSize = pyqtSignal(int)
signalOptionsStart = pyqtSignal()
signalAnimationOptions = pyqtSignal(int,bool,bool)
saveOptionsStart = pyqtSignal()
saveOptionsEnd = pyqtSignal()
registerTimeLayer = pyqtSignal(object)
def __init__ (self,iface,timeLayerManager):
"""initialize the GUI control"""
QObject.__init__(self)
self.iface = iface
self.timeLayerManager = timeLayerManager
self.showLabel = False
self.optionsDialog = None
# load the form
path = os.path.dirname( os.path.abspath( __file__ ) )
self.dock = uic.loadUi( os.path.join( path, "dockwidget2.ui" ) )
self.iface.addDockWidget( Qt.BottomDockWidgetArea, self.dock )
self.dock.pushButtonExportVideo.setEnabled(False) # only enabled if there are managed layers
self.setTimeFrameType('days') # should be 'days'
self.dock.pushButtonOptions.clicked.connect(self.optionsClicked)
self.dock.pushButtonExportVideo.clicked.connect(self.exportVideoClicked)
self.dock.pushButtonToggleTime.clicked.connect(self.toggleTimeClicked)
self.dock.pushButtonBack.clicked.connect(self.backClicked)
self.dock.pushButtonForward.clicked.connect(self.forwardClicked)
self.dock.pushButtonPlay.clicked.connect(self.playClicked)
self.dock.dateTimeEditCurrentTime.dateTimeChanged.connect(self.currentTimeChanged)
self.dock.horizontalTimeSlider.valueChanged.connect(self.currentTimeChanged)
self.dock.comboBoxTimeExtent.currentIndexChanged[str].connect(self.currentTimeFrameTypeChanged)
self.dock.spinBoxTimeExtent.valueChanged.connect(self.currentTimeFrameSizeChanged)
self.iface.mapCanvas().renderComplete.connect(self.renderLabel)
def optionsClicked(self):
self.showOptions.emit()
def exportVideoClicked(self):
self.exportVideo.emit()
def toggleTimeClicked(self):
self.toggleTime.emit()
def backClicked(self):
self.back.emit()
def forwardClicked(self):
self.forward.emit()
def playClicked(self):
self.play.emit()
def currentTimeChanged(self,datetime):
self.signalCurrentTime.emit(datetime)
def currentTimeFrameTypeChanged(self,frameType):
self.signalTimeFrameType.emit(frameType)
def currentTimeFrameSizeChanged(self,frameSize):
self.signalTimeFrameSize.emit(frameSize)
def unload(self):
"""unload the plugin"""
self.iface.removeDockWidget(self.dock)
def showOptionsDialog(self,layerList,animationFrameLength,playBackwards,loopAnimation):
"""show the optionsDialog and populate it with settings from timeLayerManager"""
# check if the dialog is already showing
if self.optionsDialog is not None:
self.optionsDialog.raise_()
self.optionsDialog.activateWindow()
return
# load the form
path = os.path.dirname( os.path.abspath( __file__ ) )
self.optionsDialog = uic.loadUi(os.path.join(path,"options.ui"))
# restore options from layerList:
for layer in layerList:
layerName=layer.getName()
if layer.isEnabled():
checkState=Qt.Checked
else:
checkState=Qt.Unchecked
layerId=layer.getLayerId()
offset=layer.getOffset()
times=layer.getTimeAttributes()
startTime=times[0]
if times[0] != times[1]: # end time equals start time for timeLayers of type timePoint
endTime = times[1]
else:
endTime = ""
timeFormat=layer.getTimeFormat()
self.addRowToOptionsTable(layerName,checkState,layerId,offset,timeFormat,startTime,endTime)
# restore animation options
self.optionsDialog.spinBoxFrameLength.setValue(animationFrameLength)
self.optionsDialog.checkBoxBackwards.setChecked(playBackwards)
self.optionsDialog.checkBoxLabel.setChecked(self.showLabel)
self.optionsDialog.checkBoxLoop.setChecked(loopAnimation)
# show diaolg
self.optionsDialog.show()
# establish connections
self.optionsDialog.pushButtonAdd.clicked.connect(self.showAddLayerDialog)
self.optionsDialog.pushButtonRemove.clicked.connect(self.removeLayer)
self.optionsDialog.buttonBox.accepted.connect(self.saveOptions)
self.optionsDialog.buttonBox.accepted.connect(self.setOptionsDialogToNone)
self.optionsDialog.buttonBox.rejected.connect(self.setOptionsDialogToNone)
self.optionsDialog.rejected.connect(self.setOptionsDialogToNone)
self.optionsDialog.buttonBox.helpRequested.connect(self.showHelp)
self.mapLayers=QgsMapLayerRegistry.instance().mapLayers()
def showHelp(self):
"""show the help dialog"""
path = os.path.dirname( os.path.abspath( __file__ ) )
self.helpDialog = uic.loadUi(os.path.join(path,"help.ui"))
helpPath = QUrl('file:///'+replace(os.path.join(path,"help.htm"),'\\','/')) # windows hack: Qt expects / instead of \
#QMessageBox.information(self.iface.mainWindow(),'Error',str(helpPath))
self.helpDialog.textBrowser.setSource(helpPath)
self.helpDialog.show()
def saveOptions(self):
"""save the options from optionsDialog to timeLayerManager"""
#self.emit(SIGNAL('saveOptionsStart()'),)
self.saveOptionsStart.emit()
# loop through the rows in the table widget and add all layers accordingly
for row in range(0,self.optionsDialog.tableWidget.rowCount()):
if self.createTimeLayer(row):
# save animation options
animationFrameLength = self.optionsDialog.spinBoxFrameLength.value()
playBackwards = self.optionsDialog.checkBoxBackwards.isChecked()
self.showLabel = self.optionsDialog.checkBoxLabel.isChecked()
loopAnimation = self.optionsDialog.checkBoxLoop.isChecked()
self.signalAnimationOptions.emit(animationFrameLength,playBackwards,loopAnimation)
self.refreshMapCanvas('saveOptions')
if len(self.getManagedLayers()) > 0:
self.dock.pushButtonExportVideo.setEnabled(True)
else:
self.dock.pushButtonExportVideo.setEnabled(False)
self.saveOptionsEnd.emit()
else:
break
def createTimeLayer(self,row):
"""create a TimeLayer from options set in the table row"""
# layer
layer=QgsMapLayerRegistry.instance().mapLayer(self.optionsDialog.tableWidget.item(row,4).text())
if self.optionsDialog.tableWidget.item(row,3).checkState() == Qt.Checked:
isEnabled = True
else:
isEnabled = False
# offset
offset = int(self.optionsDialog.tableWidget.item(row,6).text()) # currently only seconds!
# start time
startTimeAttribute = self.optionsDialog.tableWidget.item(row,1).text()
# end time (optional)
if self.optionsDialog.tableWidget.item(row,2).text() == "": #QString(""):
endTimeAttribute = startTimeAttribute # end time equals start time for timeLayers of type timePoint
else:
endTimeAttribute = self.optionsDialog.tableWidget.item(row,2).text()
# time format
timeFormat = self.optionsDialog.tableWidget.item(row,5).text()
# this should be a python class factory
if type(layer).__name__ == "QgsVectorLayer":
timeLayerClass = TimeVectorLayer
elif type(layer).__name__ == "QgsRasterLayer":
timeLayerClass = TimeRasterLayer
try: # here we use the selected class
timeLayer = timeLayerClass(layer,startTimeAttribute,endTimeAttribute,isEnabled,timeFormat,offset)
except InvalidTimeLayerError, e:
QMessageBox.information(self.iface.mainWindow(),'Error','An error occured while trying to add layer '+layer.name()+' to TimeManager.\n'+e.value)
return False
self.registerTimeLayer.emit(timeLayer)
return True
def setOptionsDialogToNone(self):
"""set self.optionsDialog to None"""
self.optionsDialog = None
def removeLayer(self):
"""removes the currently selected layer (= row) from options"""
currentRow = self.optionsDialog.tableWidget.currentRow()
try:
layerName = self.optionsDialog.tableWidget.item(currentRow,0).text()
except AttributeError: # if no row is selected
return
if QMessageBox.question(self.optionsDialog,'Remove Layer','Do you really want to remove layer '+layerName+'?',QMessageBox.Ok,QMessageBox.Cancel) == QMessageBox.Ok:
self.optionsDialog.tableWidget.removeRow(self.optionsDialog.tableWidget.currentRow())
def showAddLayerDialog(self):
"""show the addLayerDialog and populate it with QgsVectorLayers from QgsMapLayerRegistry"""
path = os.path.dirname( os.path.abspath( __file__ ) )
self.addLayerDialog = uic.loadUi(os.path.join(path,"addLayer.ui"))
self.mapLayers=QgsMapLayerRegistry.instance().mapLayers()
self.layerIds=[]
managedLayers=self.getManagedLayers()
tempname=''
# fill the combo box with all available vector layers
for (name,layer) in self.mapLayers.iteritems():
#if type(layer).__name__ == "QgsVectorLayer" and layer not in managedLayers:
if layer not in managedLayers:
self.layerIds.append(name)
tempname = unicode(layer.name())#.rstrip('01234567890') # stripping out the trailing numeric code
self.addLayerDialog.comboBoxLayers.addItem(tempname)
if len(self.layerIds) == 0:
QMessageBox.information(self.optionsDialog,'Error','There are no unmanaged vector layers in the project!')
return
# get attributes of the first layer for gui initialization
self.getLayerAttributes(0)
self.addLayerDialog.show()
# establish connections
self.addLayerDialog.comboBoxLayers.currentIndexChanged.connect(self.getLayerAttributes)
self.addLayerDialog.buttonBox.accepted.connect(self.addLayerToOptions)
def getManagedLayers(self):
"""get list of QgsMapLayers listed in optionsDialog.tableWidget"""
layerList=[]
for row in range(0,self.optionsDialog.tableWidget.rowCount()):
# layer
layer=self.mapLayers[self.optionsDialog.tableWidget.item(row,4).text()]
layerList.append(layer)
return layerList
def getLayerAttributes(self,comboIndex):
"""get list layer attributes and fill the combo boxes"""
try:
layer=self.mapLayers[self.layerIds[comboIndex]]
except:
#QMessageBox.information(self.iface.mainWindow(),'Test Output','Error at: self.mapLayers[self.layerIds[comboIndex]]')
return
try:
provider=layer.dataProvider() # this will crash on OpenLayers layers
except AttributeError:
return
try:
fieldmap=provider.fields() # this function will crash on raster layers
except:
#QMessageBox.information(self.iface.mainWindow(),'Test Output','Error at: provider.fields()')
return
self.addLayerDialog.comboBoxStart.clear()
self.addLayerDialog.comboBoxEnd.clear()
self.addLayerDialog.comboBoxEnd.addItem('') # this box is optional, so we add an empty item
for attr in fieldmap:
self.addLayerDialog.comboBoxStart.addItem(attr.name())
self.addLayerDialog.comboBoxEnd.addItem(attr.name())
def addLayerToOptions(self):
"""write information from addLayerDialog to optionsDialog.tableWidget"""
layerName = self.addLayerDialog.comboBoxLayers.currentText()
startTime = self.addLayerDialog.comboBoxStart.currentText()
endTime = self.addLayerDialog.comboBoxEnd.currentText()
checkState = Qt.Checked
layerId = self.layerIds[self.addLayerDialog.comboBoxLayers.currentIndex()]
timeFormat = "%Y-%m-%d %H:%M:%S" # default
offset = self.addLayerDialog.spinBoxOffset.value()
self.addRowToOptionsTable(layerName,checkState,layerId,offset,timeFormat,startTime,endTime)
def addRowToOptionsTable(self,layerName,checkState,layerId,offset,timeFormat="",startTime="",endTime=""):
"""insert a new row into optionsDialog.tableWidget"""
# insert row
row=self.optionsDialog.tableWidget.rowCount()
self.optionsDialog.tableWidget.insertRow(row)
# insert values
layerItem = QTableWidgetItem()
layerItem.setText(layerName)
self.optionsDialog.tableWidget.setItem(row,0,layerItem)
startItem = QTableWidgetItem()
startItem.setText(startTime)
self.optionsDialog.tableWidget.setItem(row,1,startItem)
endItem = QTableWidgetItem()
endItem.setText(endTime)
self.optionsDialog.tableWidget.setItem(row,2,endItem)
checkBoxItem = QTableWidgetItem()
checkBoxItem.setCheckState(checkState)
self.optionsDialog.tableWidget.setItem(row,3,checkBoxItem)
indexItem = QTableWidgetItem()
indexItem.setText(layerId)
self.optionsDialog.tableWidget.setItem(row,4,indexItem)
timeFormatItem = QTableWidgetItem()
timeFormatItem.setText(timeFormat)
self.optionsDialog.tableWidget.setItem(row,5,timeFormatItem)
offsetItem = QTableWidgetItem()
offsetItem.setText(str(offset))
self.optionsDialog.tableWidget.setItem(row,6,offsetItem)
def updateTimeExtents(self,timeExtents):
"""update time extents showing in labels and represented by horizontalTimeSlider"""
#QMessageBox.information(self.iface.mainWindow(),'Debug','start: '+str(timeExtents[0])+' \nend: '+str(timeExtents[1]))
if timeExtents != (None,None):
self.dock.labelStartTime.setText(str(timeExtents[0])[0:23])
self.dock.labelEndTime.setText(str(timeExtents[1])[0:23])
self.dock.horizontalTimeSlider.setMinimum(mktime(timeExtents[0].timetuple()))
self.dock.horizontalTimeSlider.setMaximum(mktime(timeExtents[1].timetuple()))
else: # set to default values
self.dock.labelStartTime.setText('not set')
self.dock.labelEndTime.setText('not set')
self.dock.horizontalTimeSlider.setMinimum(0)
self.dock.horizontalTimeSlider.setMaximum(1)
def refreshTimeRestrictions(self,currentTimePosition,sender=None):
"""update current time showing in dateTimeEditCurrentTime and horizontalTimeSlider"""
#QMessageBox.information(self.iface.mainWindow(),'Test Output','Refresh!\n'+str(sender)+'\n'+str(currentTimePosition))
try:
self.dock.dateTimeEditCurrentTime.setDateTime(currentTimePosition)
self.dock.horizontalTimeSlider.setValue(mktime(currentTimePosition.timetuple()))
except:
pass
def disableAnimationExport(self):
"""disable the animation export button"""
self.dock.pushButtonExportVideo.setEnabled(False)
def enableAnimationExport(self):
"""enable the animation export button"""
self.dock.pushButtonExportVideo.setEnabled(True)
def refreshMapCanvas(self,sender=None):
"""refresh the map canvas"""
#QMessageBox.information(self.iface.mainWindow(),'Test Output','Refresh!\n'+str(sender))
self.iface.mapCanvas().refresh()
def setTimeFrameSize(self,frameSize):
"""set spinBoxTimeExtent to given framzeSize"""
self.dock.spinBoxTimeExtent.setValue(frameSize)
def setTimeFrameType(self,frameType):
"""set comboBoxTimeExtent to given frameType"""
i = self.dock.comboBoxTimeExtent.findText(frameType)
self.dock.comboBoxTimeExtent.setCurrentIndex(i)
def setActive(self, isActive):
"""set pushButtonToggleTime active/inactive"""
self.dock.pushButtonToggleTime.setChecked(isActive)
def addActionShowSettings(self, action):
"""add action to pushButttonOptions"""
self.dock.pushButtonOptions.addAction(action)
def turnPlayButtonOff(self):
"""turn pushButtonPlay off"""
if self.dock.pushButtonPlay.isChecked():
self.dock.pushButtonPlay.toggle()
def renderLabel(self, painter):
"""render the current timestamp on the map canvas"""
if not self.showLabel:
return
self.font = QFont("Arial")
self.labelString = str(self.dock.dateTimeEditCurrentTime.dateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"))
self.placementIndex = 3
fm = QFontMetrics(self.font, painter.device())
rect = fm.boundingRect(self.labelString)
# Determine placement of label from form combo box
index = self.placementIndex
flags = 0
if index == 0: # Bottom Left
flags = Qt.AlignBottom | Qt.AlignLeft
elif index == 1: # Top left
flags = Qt.AlignTop | Qt.AlignLeft
elif index == 2: # Top Right
flags = Qt.AlignTop | Qt.AlignRight
elif index == 3: # Bottom Right
flags = Qt.AlignBottom | Qt.AlignRight
else:
print "Unknown placement index of " + str(index)
# Get canvas dimensions
width = painter.device().width()
height = painter.device().height()
# TODO: set font, color
txt = QTextDocument()
txt.setHtml('<span style="background-color:#ffffff;">'+self.labelString+"</span>")
layout = txt.documentLayout()
size = layout.documentSize()
if flags & Qt.AlignRight:
x = width - 5 - size.width()
else:
x = 5
if flags & Qt.AlignBottom:
y = height - 5 - size.height()
else:
y = 5
painter.translate(x, y)
layout.draw(painter, QAbstractTextDocumentLayout.PaintContext())
painter.translate(-x, -y) # translate back