-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGeosismaWindow.py
1831 lines (1538 loc) · 80.9 KB
/
GeosismaWindow.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
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
793
794
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
832
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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
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
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
'''
# -*- coding: utf-8 -*-
# Copyright (C) 2013 Luigi Pirelli ([email protected])
#
# 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 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
Created on Oct 7, 2013
@author: Luigi Pirelli ([email protected])
'''
import traceback
import os
import json # used to dump dicts in strings
import ast # used to convert string indict because json.loads could fail
import inspect
import copy
from datetime import date
from psycopg2.extensions import adapt
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtNetwork import *
from qgis.core import *
from qgis.gui import *
from Utils import *
# import cache manager
from DlgWmsLayersManager import DlgWmsLayersManager, WmsLayersBridge
currentPath = os.path.dirname(__file__)
class GeosismaWindow(QDockWidget):
# signals
downloadTeamsDone = pyqtSignal(bool)
archiveTeamsDone = pyqtSignal(bool)
downloadRequestsDone = pyqtSignal(bool)
uploadSafetiesDone = pyqtSignal(bool)
selectRequestDone = pyqtSignal()
updatedCurrentSafety = pyqtSignal()
initNewCurrentSafetyDone = pyqtSignal()
# static global vars
MESSAGELOG_CLASS = "rt_geosisma_offline"
GEOSISMA_DBNAME = "geosismadb.sqlite"
GEOSISMA_GEODBNAME = "geosisma_geo.sqlite"
DEFAULT_SRID = 3003
GEODBDEFAULT_SRID = 32632
# nomi dei layer in TOC
LAYER_GEOM_ORIG = "Catasto"
LAYER_GEOM_MODIF = "Schede"
LAYER_GEOM_FAB10K = "Aggregati"
LAYER_FOTO = "Foto Edifici"
# stile per i layer delle geometrie
STYLE_FOLDER = "styles"
STYLE_GEOM_ORIG = "stile_geometrie_originali.qml"
STYLE_GEOM_MODIF = "stile_geometrie_modificate.qml"
STYLE_GEOM_FAB10K = "stile_geometrie_aggregati.qml"
STYLE_FOTO = "stile_fotografie.qml"
SCALE_IDENTIFY = 5000
SCALE_MODIFY = 2000
# nomi tabelle contenenti le geometrie
TABLE_GEOM_ORIG = "fab_catasto".lower()
TABLE_GEOM_MODIF = "missions_safety".lower()
TABLE_GEOM_FAB10K = "fab_10k".lower()
# ID dei layer contenenti geometrie e wms
VLID_GEOM_ORIG = ''
VLID_GEOM_MODIF = ''
VLID_GEOM_FAB10K = ''
VLID_FOTO = ''
RLID_WMS = {}
_instance = None
# singleton interface
@classmethod
def instance(cls, parent=None, iface=None):
'''
Singleton interface
@param parent: passed to init() function
@param dbName: passed to init() function
'''
if cls._instance == None:
cls._instance = GeosismaWindow()
cls._instance.init(parent, iface)
return cls._instance
def __init__(self):
pass
def cleanUp(self):
try:
from ArchiveManager import ArchiveManager
ArchiveManager.instance().cleanUp()
except:
pass
try:
if self.safetyDlg is not None:
self.safetyDlg.deleteLater()
self.safetyDlg = None
except:
pass
try:
GeosismaWindow._instance = None
except:
pass
def init(self, parent=None, iface=None):
QDockWidget.__init__(self, parent)
QObject.connect(self, SIGNAL("destroyed()"), self.cleanUp)
self.setAttribute(Qt.WA_DeleteOnClose)
self.setupUi()
self.iface = iface
self.canvas = self.iface.mapCanvas()
self.safetyDlg = None
self.isApriScheda = True
self.srid = GeosismaWindow.DEFAULT_SRID
# get bds path
self.settings = QSettings()
dbsPath = self.settings.value("/rt_geosisma_offline/pathToDbs", "./offlinedata/dbs/")
if not os.path.isabs(dbsPath):
currentpath = os.path.dirname(os.path.abspath(inspect.getfile( inspect.currentframe() )))
dbsPath = os.path.join(currentpath, dbsPath)
self.DATABASE_OUTNAME = os.path.join(dbsPath, GeosismaWindow.GEOSISMA_DBNAME)
self.GEODATABASE_OUTNAME = os.path.join(dbsPath, GeosismaWindow.GEOSISMA_GEODBNAME)
QgsLogger.debug(self.tr("Default dbname: %s" % self.DATABASE_OUTNAME) )
QgsLogger.debug(self.tr("Default geodbname: %s" % self.GEODATABASE_OUTNAME) )
# get default srid
self.DEFAULT_SRID = self.settings.value("/rt_geosisma_offline/safetyDbDefaultSrid", self.DEFAULT_SRID, int )
self.GEODBDEFAULT_SRID = self.settings.value("/rt_geosisma_offline/geoDbDefaultSrid", self.GEODBDEFAULT_SRID, int )
QgsLogger.debug(self.tr("Default srid: %d" % self.DEFAULT_SRID) )
#geosisma api connection data
self.user = None
self.pwd = None
self.autenthicated = False
self.maxAuthenticationError = 5
self.authenticationRetryCounter = 0
# list of dict of requests, tems and safeties
self.requests = []
self.currentRequest = None
self.downloadedTeams = []
self.downloadedRequests = []
self.currentSafety = None
self.safeties = []
self.teams = None
MapTool.canvas = self.canvas
self.nuovaPointEmitter = FeatureFinder()
self.nuovaPointEmitter.registerStatusMsg( u"Click per identificare la geometria da associare alla nuova scheda" )
QObject.connect(self.nuovaPointEmitter, SIGNAL("pointEmitted"), self.linkSafetyGeometry)
self.lookForSafetiesEmitter = FeatureFinder()
self.lookForSafetiesEmitter.registerStatusMsg( u"Click per identificare la geometria di cui cercare le schede" )
QObject.connect(self.lookForSafetiesEmitter, SIGNAL("pointEmitted"), self.listLinkedSafeties)
self.polygonDrawer = PolygonDrawer()
self.polygonDrawer.registerStatusMsg( u"Click sx per disegnare la nuova gemetria, click dx per chiuderla" )
QObject.connect(self.polygonDrawer, SIGNAL("geometryEmitted"), self.createNewSafetyGeometry)
self.connect(self.btnNewSafety, SIGNAL("clicked()"), self.initNewCurrentSafety)
self.connect(self.btnModifyCurrentSafety, SIGNAL("clicked()"), self.updateSafetyForm)
self.connect(self.btnDeleteCurrentSafety, SIGNAL("clicked()"), self.deleteCurrentSafety)
self.connect(self.btnSelectSafety, SIGNAL("clicked()"), self.selectSafety)
self.connect(self.btnSelectRequest, SIGNAL("clicked()"), self.selectRequest)
self.connect(self.btnDownloadRequests, SIGNAL("clicked()"), self.downloadTeams)
self.connect(self.btnReset, SIGNAL("clicked()"), self.reset)
self.connect(self.btnLinkSafetyGeometry, SIGNAL("clicked()"), self.linkSafetyGeometry)
self.connect(self.btnListLinkedSafeties, SIGNAL("clicked()"), self.listLinkedSafeties)
self.connect(self.btnNewSafetyGeometry, SIGNAL("clicked()"), self.createNewSafetyGeometry)
self.connect(self.btnZoomToSafety, SIGNAL("clicked()"), self.zoomToSafety)
self.connect(self.btnCleanUnlinkedSafeties, SIGNAL("clicked()"), self.cleanUnlinkedSafeties)
self.connect(self.btnManageAttachments, SIGNAL("clicked()"), self.manageAttachments)
# custom signal
self.downloadTeamsDone.connect(self.archiveTeams)
self.archiveTeamsDone.connect(self.downloadRequests)
self.downloadRequestsDone.connect( self.archiveRequests )
self.updatedCurrentSafety.connect(self.updateSafetyForm)
self.updatedCurrentSafety.connect(self.updateArchivedCurrentSafety)
self.updatedCurrentSafety.connect(self.repaintSafetyGeometryLayer)
self.updatedCurrentSafety.connect(self.zoomToSafety)
self.updatedCurrentSafety.connect(self.selectCurrentSafetyFeature)
# GUI state based on signals
self.selectRequestDone.connect(self.manageGuiStatus)
self.updatedCurrentSafety.connect(self.manageGuiStatus)
self.manageGuiStatus()
# self.connect(self.iface, SIGNAL("newProjectCreated()"), self.close)
def setupUi(self):
self.setObjectName( "rt_geosisma_dockwidget" )
self.setWindowTitle( "Geosisma Offline RT" )
child = QWidget()
vLayout = QVBoxLayout( child )
group = QGroupBox( "Schede Sopralluoghi", child )
vLayout.addWidget( group )
gridLayout = QGridLayout( group )
text = u"Nuova"
self.btnNewSafety = QPushButton( QIcon(":/icons/nuova_scheda.png"), text, group )
#text = u"Identifica la geometria per la creazione di una nuova scheda edificio"
text = u"Crea una nuova scheda sopralluogo"
self.btnNewSafety.setToolTip( text )
#self.btnNewSafety.setCheckable(True)
gridLayout.addWidget(self.btnNewSafety, 0, 0, 1, 1)
text = u"Modifica"
self.btnModifyCurrentSafety = QPushButton( QIcon(":/icons/modifica_scheda.png"), text, group )
#text = u"Identifica la geometria per l'apertura di una scheda gia' esistente su di essa"
text = u"Modifica scheda sopralluogo corrente"
self.btnModifyCurrentSafety.setToolTip( text )
#self.btnModifyCurrentSafety.setCheckable(True)
gridLayout.addWidget(self.btnModifyCurrentSafety, 0, 1, 1, 1)
text = u"Elimina"
self.btnDeleteCurrentSafety = QPushButton( QIcon(":/icons/cancella_scheda.png"), text, group )
text = u"Elimina scheda sopralluogo"
self.btnDeleteCurrentSafety.setToolTip( text )
#self.btnDeleteCurrentSafety.setCheckable(True)
gridLayout.addWidget(self.btnDeleteCurrentSafety, 0, 2, 1, 1)
text = u"Seleziona Scheda"
self.btnSelectSafety = QPushButton( QIcon(":/icons/riepilogo_schede.png"), text, group )
self.btnSelectSafety.setToolTip( text )
gridLayout.addWidget(self.btnSelectSafety, 1, 0, 1, 3)
text = u"Seleziona Richiesta"
self.btnSelectRequest = QPushButton( QIcon(":/icons/riepilogo_schede.png"), text, group )
self.btnSelectRequest.setToolTip( text )
gridLayout.addWidget(self.btnSelectRequest, 2, 0, 1, 3)
text = u"Download Richieste"
self.btnDownloadRequests = QPushButton( QIcon(":/icons/riepilogo_schede.png"), text, group )
self.btnDownloadRequests.setToolTip( text )
gridLayout.addWidget(self.btnDownloadRequests, 3, 0, 1, 2)
text = u"Reset"
self.btnReset = QPushButton( QIcon(":/icons/riepilogo_schede.png"), text, group )
self.btnReset.setToolTip( text )
gridLayout.addWidget(self.btnReset, 3, 2, 1, 1)
group = QGroupBox( "Geometrie e allegati", child )
vLayout.addWidget( group )
gridLayout = QGridLayout( group )
text = u"Nuova"
self.btnNewSafetyGeometry = QPushButton( QIcon(":/icons/crea_geometria.png"), text, group )
text = u"Disegna un poligono da associare alla scheda"
self.btnNewSafetyGeometry.setToolTip( text )
self.btnNewSafetyGeometry.setCheckable(True)
gridLayout.addWidget(self.btnNewSafetyGeometry, 0, 0, 1, 2)
text = u"Zoom"
self.btnZoomToSafety = QPushButton( QIcon(":/icons/crea_geometria.png"), text, group )
text = u"Zoom al poligono della scheda"
self.btnZoomToSafety.setToolTip( text )
gridLayout.addWidget(self.btnZoomToSafety, 0, 2, 1, 1)
text = u"Associa"
self.btnLinkSafetyGeometry = QPushButton( QIcon(":/icons/crea_geometria.png"), text, group )
text = u"Seleziona una particella da associare alla scheda"
self.btnLinkSafetyGeometry.setToolTip( text )
self.btnLinkSafetyGeometry.setCheckable(True)
gridLayout.addWidget(self.btnLinkSafetyGeometry, 1, 0, 1, 1)
text = u"Elenco"
self.btnListLinkedSafeties = QPushButton( QIcon(":/icons/crea_geometria.png"), text, group )
text = u"Elencare le scehde associate a una particella"
self.btnListLinkedSafeties.setToolTip( text )
self.btnListLinkedSafeties.setCheckable(True)
gridLayout.addWidget(self.btnListLinkedSafeties, 1, 1, 1, 1)
text = u"Ripulisci"
self.btnCleanUnlinkedSafeties = QPushButton( QIcon(":/icons/crea_geometria.png"), text, group )
text = u"Elimina schede non associate a nessuna particella"
self.btnCleanUnlinkedSafeties.setToolTip( text )
gridLayout.addWidget(self.btnCleanUnlinkedSafeties, 1, 2, 1, 1)
text = u"Gestisci allegati"
self.btnManageAttachments = QPushButton( QIcon(":/icons/crea_geometria.png"), text, group )
text = u"Aggiuinta e rimozione degli allegati alla scheda corrente"
self.btnManageAttachments.setToolTip( text )
gridLayout.addWidget(self.btnManageAttachments, 3, 0, 1, 3)
# text = u"About"
# self.btnAbout = QPushButton( QIcon(":/icons/about.png"), text, child )
# self.btnAbout.setToolTip( text )
# vLayout.addWidget( self.btnAbout )
# #gridLayout.addWidget(self.btnAbout, 7, 1, 1, 1)
self.setWidget(child)
def exec_(self):
if not self.startPlugin():
return False
# # load test data to test functions
# self.settings = QSettings()
# dbsPath = self.settings.value("/rt_geosisma_offline/pathToDbs", "./offlinedata/dbs/")
# path = dbsPath + '/../../doc/downloadedTeams+downloadedRequests.json'
# json_data=open(path)
# data = json.load(json_data)
# self.downloadedTeams = data
# self.archiveRequests(True)
# return
# from ArchiveManager import ArchiveManager # import here to avoid circular import
# req = ArchiveManager.instance().loadRequests([533, 554])
# print req
# return
# dbsPath = self.settings.value("/rt_geosisma_offline/pathToDbs", "./offlinedata/dbs/")
# path = dbsPath + '/../../doc/downloadedSafeties.json'
# with open(path,'r') as inf:
# dict_from_file = eval(inf.read())
# from ArchiveManager import ArchiveManager
# for safety in dict_from_file["objects"]:
#
# for k,v in safety.items():
# print k,v
# print "------------------"
# ArchiveManager.instance().archiveSafety(None, "123", safety)
# ArchiveManager.instance().commit()
# return
# self.currentSafety = {u'created': u'2013-11-21', u'gid_catasto': None, u'number': 2, u'team_id': 123, u'safety': u'{"s1istatprov":"045","s1istatcom":"004","sdate":"21/11/2013","number":2,"s1catfoglio":"24","s1com":"Casola in Lunigiana","s1istatcens":"001","s1istatloc":"10003","s1istatreg":"009","s1loc":"Casola in Lunigiana","s1prov":"MS","s1catpart1":"966"}', u'request_id': 51, u'date': u'2013-11-21', u'the_geom': None, u'id': 2}
# self.updatedCurrentSafety.emit()
# return
self.reloadCrs()
# load all the layers from db
self.wmsLayersBridge = WmsLayersBridge(self.iface, self.showMessage)
self.wmsLayersBridge.instance.offlineMode = True
firstTime = True
if not DlgWmsLayersManager.loadWmsLayers(firstTime): # static method
message = self.tr("Impossibile caricare i layer WMS")
self.showMessage(message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
# continue
self.loadLayerGeomOrig()
self.loadFab10kGeometries()
self.loadSafetyGeometries()
self.setProjectDefaultSetting()
self.manageEditingSignals()
return True
def reloadCrs(self):
#self.srid = self.getSridFromDb()
self.srid = self.DEFAULT_SRID
crs = QgsCoordinateReferenceSystem( self.srid, QgsCoordinateReferenceSystem.EpsgCrsId )
# manage deprecated api using newest. If it's not available then use deprecated one
try:
mapSettings = self.canvas.mapSettings()
mapSettings.setDestinationCrs(crs)
mapSettings.setMapUnits( crs.mapUnits() if crs.mapUnits() != QGis.UnknownUnit else QGis.Meters )
self.iface.mapCanvas().setCrsTransformEnabled(True)
except:
renderer = self.canvas.mapRenderer()
self._setRendererCrs(renderer, crs)
renderer.setMapUnits( crs.mapUnits() if crs.mapUnits() != QGis.UnknownUnit else QGis.Meters )
renderer.setProjectionsEnabled(True)
def setProjectDefaultSetting(self):
project = QgsProject.instance()
layerSnappingList = [GeosismaWindow.VLID_GEOM_ORIG, GeosismaWindow.VLID_GEOM_FAB10K]
layerSnappingEnabledList = ["enabled", "enabled"]
layerSnappingToleranceUnitList = ["0", "0"]
layerSnapToList = ["to_vertex", "to_vertex"]
layerSnappingToleranceList = ["0.300000", "0.300000"]
project.writeEntry("Digitizing", "/IntersectionSnapping", Qt.Checked)
project.writeEntry("Digitizing", "/LayerSnappingList", layerSnappingList)
project.writeEntry("Digitizing", "/LayerSnappingEnabledList", layerSnappingEnabledList)
project.writeEntry("Digitizing", "/LayerSnappingToleranceUnitList", layerSnappingToleranceUnitList)
project.writeEntry("Digitizing", "/LayerSnapToList", layerSnapToList)
project.writeEntry("Digitizing", "/LayerSnappingToleranceList", layerSnappingToleranceList)
def emitGeometryUpdate(self):
QgsLogger.debug("emitGeometryUpdate entered",2 )
layers = QgsMapLayerRegistry.instance().mapLayersByName(self.LAYER_GEOM_MODIF)
if len(layers) > 0:
layer = layers[0]
features = layer.selectedFeatures()
if len(features) == 0 or len(features) > 1:
message = self.tr(u"Nessuno o troppi [%d] record selezionati su %s" % (len(features), self.LAYER_GEOM_ORIG) )
self.showMessage(message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
return
# get updated geometry and update currentSafety
self.currentSafety["the_geom"] = features[0].geometry().exportToWkt()
self.updateArchivedCurrentSafety()
def manageEditingSignals(self):
layers = QgsMapLayerRegistry.instance().mapLayersByName(self.LAYER_GEOM_MODIF)
if len(layers) > 0:
layers[0].editingStopped.connect(self.emitGeometryUpdate)
def loadLayerGeomOrig(self):
# skip if already present
layers = QgsMapLayerRegistry.instance().mapLayersByName(self.LAYER_GEOM_ORIG)
if len(layers) > 0:
# get id of the Geosisma layer
valid = False
for layer in layers:
prop = layer.customProperty( "loadedByGeosismaRTPlugin" )
if prop == "VLID_GEOM_ORIG":
valid = True
GeosismaWindow.VLID_GEOM_ORIG = self._getLayerId( layer )
if not valid:
message = self.tr("Manca il layer %s, ricaricando il plugin verrà caricato automaticamente" % self.LAYER_GEOM_ORIG)
self.showMessage(message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
return
# carica il layer con le geometrie originali
if QgsMapLayerRegistry.instance().mapLayer( GeosismaWindow.VLID_GEOM_ORIG ) == None:
GeosismaWindow.VLID_GEOM_ORIG = ''
uri = QgsDataSourceURI()
uri.setDatabase(self.GEODATABASE_OUTNAME)
uri.setDataSource('', self.TABLE_GEOM_ORIG, 'the_geom')
vl = QgsVectorLayer( uri.uri(), self.LAYER_GEOM_ORIG, "spatialite" )
if vl == None or not vl.isValid() or not vl.setReadOnly(True):
return False
# imposta lo stile del layer
style_path = os.path.join( currentPath, GeosismaWindow.STYLE_FOLDER, GeosismaWindow.STYLE_GEOM_ORIG )
errorMsg, success= vl.loadNamedStyle( style_path )
if not success:
message = self.tr("Non posso caricare lo stile %s - %s: %s" % (GeosismaWindow.STYLE_GEOM_ORIG, errorMsg, style_path) )
self.showMessage(message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
self.iface.legendInterface().refreshLayerSymbology(vl)
GeosismaWindow.VLID_GEOM_ORIG = self._getLayerId(vl)
self._addMapLayer(vl)
# set custom property
vl.setCustomProperty( "loadedByGeosismaRTPlugin", "VLID_GEOM_ORIG" )
return True
def loadSafetyGeometries(self):
# skip if already present
layers = QgsMapLayerRegistry.instance().mapLayersByName(self.LAYER_GEOM_MODIF)
if len(layers) > 0:
# get id of the Geosisma layer
valid = False
for layer in layers:
prop = layer.customProperty( "loadedByGeosismaRTPlugin" )
if prop == "VLID_GEOM_MODIF":
valid = True
GeosismaWindow.VLID_GEOM_MODIF = self._getLayerId( layer )
if not valid:
message = self.tr("Manca il layer %s, ricaricando il plugin verrà caricato automaticamente" % self.LAYER_GEOM_MODIF)
self.showMessage(message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
return
# carica il layer con le geometrie delle safety
if QgsMapLayerRegistry.instance().mapLayer( GeosismaWindow.VLID_GEOM_MODIF ) == None:
GeosismaWindow.VLID_GEOM_MODIF = ''
uri = QgsDataSourceURI()
uri.setDatabase(self.DATABASE_OUTNAME)
uri.setDataSource('', self.TABLE_GEOM_MODIF, 'the_geom')
vl = QgsVectorLayer( uri.uri(), self.LAYER_GEOM_MODIF, "spatialite" )
if vl == None or not vl.isValid():
return False
# imposta lo stile del layer
style_path = os.path.join( currentPath, GeosismaWindow.STYLE_FOLDER, GeosismaWindow.STYLE_GEOM_MODIF )
errorMsg, success= vl.loadNamedStyle( style_path )
if not success:
message = self.tr("Non posso caricare lo stile %s - %s: %s" % (GeosismaWindow.STYLE_GEOM_MODIF, errorMsg, style_path) )
self.showMessage(message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
self.iface.legendInterface().refreshLayerSymbology(vl)
GeosismaWindow.VLID_GEOM_MODIF = self._getLayerId(vl)
self._addMapLayer(vl)
# set custom property
vl.setCustomProperty( "loadedByGeosismaRTPlugin", "VLID_GEOM_MODIF" )
return True
def loadFab10kGeometries(self):
# skip if already present
layers = QgsMapLayerRegistry.instance().mapLayersByName(self.LAYER_GEOM_FAB10K)
if len(layers) > 0:
# get id of the Geosisma layer
valid = False
for layer in layers:
prop = layer.customProperty( "loadedByGeosismaRTPlugin" )
if prop == "VLID_GEOM_FAB10K":
valid = True
GeosismaWindow.VLID_GEOM_FAB10K = self._getLayerId( layer )
if not valid:
message = self.tr("Manca il layer %s, ricaricando il plugin verrà caricato automaticamente" % self.LAYER_GEOM_FAB10K)
self.showMessage(message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
return
# carica il layer con le geometrie delle safety
if QgsMapLayerRegistry.instance().mapLayer( GeosismaWindow.VLID_GEOM_FAB10K ) == None:
GeosismaWindow.VLID_GEOM_FAB10K = ''
uri = QgsDataSourceURI()
uri.setDatabase(self.GEODATABASE_OUTNAME)
uri.setDataSource('', self.TABLE_GEOM_FAB10K, 'the_geom')
vl = QgsVectorLayer( uri.uri(), self.LAYER_GEOM_FAB10K, "spatialite" )
if vl == None or not vl.isValid():
return False
# imposta lo stile del layer
style_path = os.path.join( currentPath, GeosismaWindow.STYLE_FOLDER, GeosismaWindow.STYLE_GEOM_FAB10K )
errorMsg, success= vl.loadNamedStyle( style_path )
if not success:
message = self.tr("Non posso caricare lo stile %s - %s: %s" % (GeosismaWindow.STYLE_GEOM_FAB10K, errorMsg, style_path) )
self.showMessage(message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
self.iface.legendInterface().refreshLayerSymbology(vl)
GeosismaWindow.VLID_GEOM_FAB10K = self._getLayerId(vl)
self._addMapLayer(vl)
# set custom property
vl.setCustomProperty( "loadedByGeosismaRTPlugin", "VLID_GEOM_FAB10K" )
return True
def showMessage(self, message, messagetype):
QgsMessageLog.logMessage(message, GeosismaWindow.MESSAGELOG_CLASS, messagetype)
#self.ui.logLabel.setText(message)
def startPlugin(self):
# try to restore position from stored main window state
if not self.iface.mainWindow().restoreDockWidget(self):
self.iface.mainWindow().addDockWidget(Qt.LeftDockWidgetArea, self)
# force show even if it was restored as hidden
self.show()
self.activateWindow()
self.raise_()
QApplication.processEvents( QEventLoop.ExcludeUserInputEvents )
return True
def about(self):
if self.canvas.isDrawing():
return # wait until the renderer ends
# from DlgAbout import DlgAbout
# DlgAbout(self).exec_()
def reset(self):
self.user = None
self.pwd = None
self.autenthicated = False
self.authenticationRetryCounter = 0
# close Archive db is opened
from ArchiveManager import ArchiveManager
ArchiveManager.instance().cleanUp()
# remove layer of safety geometrys and reload it
self._removeMapLayer(self.VLID_GEOM_MODIF)
# now reset db
from ResetDB import ResetDB
self.resetDbDlg = ResetDB()
self.resetDbDlg.resetDone.connect( self.manageEndResetDbDlg )
self.resetDbDlg.exec_()
# reload safety geometrys layer
self.loadSafetyGeometries()
# reset some important globals
self.requests = []
self.currentRequest = None
self.downloadedTeams = []
self.downloadedRequests = []
self.teams = None
self.currentSafety = None
self.updatedCurrentSafety.emit()
def manageEndResetDbDlg(self, success):
self.resetDbDlg.hide()
QApplication.restoreOverrideCursor()
if not success:
message = self.tr("Fallito il reset del database. Controlla il Log")
self.showMessage(message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
else:
message = self.tr("Reset avvenuto con successo")
self.showMessage(message, QgsMessageLog.INFO)
QMessageBox.information(self, GeosismaWindow.MESSAGELOG_CLASS, message)
if self.resetDbDlg:
self.resetDbDlg.deleteLater()
self.resetDbDlg = None
def downloadTeams(self):
self.downloadedTeams = []
from DownloadTeams import DownloadTeams
self.downloadTeamsDlg = DownloadTeams()
self.downloadTeamsDlg.done.connect( self.manageEndDownloadTeamsDlg )
self.downloadTeamsDlg.message.connect(self.showMessage)
self.downloadTeamsDlg.exec_()
def manageEndDownloadTeamsDlg(self, success):
if self.downloadTeamsDlg is None:
return
self.downloadTeamsDlg.hide()
QApplication.restoreOverrideCursor()
if not success:
message = self.tr("Fallito lo scaricamento dei teams. Controlla il Log")
self.showMessage(message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
else:
message = self.tr("Scaricate i dati di %d teams" % self.downloadedTeams.__len__())
self.showMessage(message, QgsMessageLog.INFO)
# notify end of download
self.downloadTeamsDone.emit(success)
if self.downloadTeamsDlg:
self.downloadTeamsDlg.deleteLater()
self.downloadTeamsDlg = None
def archiveTeams(self, success):
if not success:
return
QgsLogger.debug(self.tr("Dump di Teams e Requests scaricate: %s" % json.dumps( self.downloadedTeams )) )
try:
from ArchiveManager import ArchiveManager # import here to avoid circular import
ArchiveManager.instance().saveAll = False
for team in self.downloadedTeams:
ArchiveManager.instance().archiveTeam(team)
ArchiveManager.instance().commit()
self.archiveTeamsDone.emit(success)
except Exception as ex:
try:
traceback.print_exc()
except:
pass
ArchiveManager.instance().close() # to avoid locking
message = self.tr("Fallito l'archiviazione dei team")
self.showMessage(message + ": "+ex.message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
finally:
ArchiveManager.instance().close() # to avoid locking
def downloadRequests(self, success):
if not success:
return
# get all sopralluoghiRequests
for index,team in enumerate(self.downloadedTeams):
# add a dict of dict with all requests to be donwloaded
# key will be the request api
self.downloadedTeams[index]["downloadedRequests"] = {}
for request in team["requests"]:
self.downloadedTeams[index]["downloadedRequests"][request] = None
# download all requests
self.downloadedRequests = []
from DownloadRequests import DownloadRequests
self.downloadRequestsDlg = DownloadRequests()
self.downloadRequestsDlg.done.connect( self.manageEndDownloadRequestsDlg )
self.downloadRequestsDlg.message.connect(self.showMessage)
self.downloadRequestsDlg.exec_()
def manageEndDownloadRequestsDlg(self, success):
if self.downloadRequestsDlg is None:
return
self.downloadRequestsDlg.hide()
QApplication.restoreOverrideCursor()
if not success:
message = self.tr("Fallito lo scaricamento delle richieste sopralluogo. Controlla il Log")
self.showMessage(message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
else:
message = self.tr("Scaricate %s schede soralluoghi" % self.downloadedRequests.__len__())
self.showMessage(message, QgsMessageLog.INFO)
QMessageBox.information(self, GeosismaWindow.MESSAGELOG_CLASS, message)
# notify end of download
self.downloadRequestsDone.emit(success)
if self.downloadRequestsDlg:
self.downloadRequestsDlg.deleteLater()
self.downloadRequestsDlg = None
def archiveRequests(self, success):
if not success:
return
#QgsLogger.debug(self.tr("Dump di Teams e Requests scaricate: %s" % json.dumps( self.downloadedTeams )), 2 )
try:
from ArchiveManager import ArchiveManager # import here to avoid circular import
ArchiveManager.instance().saveAll = False
for team in self.downloadedTeams:
# get event_id and team_id from meta
team_id = team["id"]
#team_name = team["name"]
for request in team["downloadedRequests"].values():
ArchiveManager.instance().archiveRequest(team_id, request)
ArchiveManager.instance().commit()
except Exception as ex:
try:
traceback.print_exc()
except:
pass
ArchiveManager.instance().close() # to avoid locking
message = self.tr("Fallito l'archiviazione delle richieste di sopralluogo")
self.showMessage(message + ": "+ex.message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
finally:
ArchiveManager.instance().close() # to avoid locking
def selectRequest(self):
from DlgSelectRequest import DlgSelectRequest
dlg = DlgSelectRequest()
ret = dlg.exec_()
# check if result set
if ret == 0:
return
# get selected request
self.currentRequest = dlg.currentRequest
self.requests = dlg.records
self.selectRequestDone.emit()
def zoomToExtent(self, boundingBox, transform=True):
geom = QgsGeometry.fromWkt(boundingBox.asWktPolygon())
if transform:
# bbox arrive in DB coordinate 32632 => convert in default view coordinate 3003
defaultCrs = QgsCoordinateReferenceSystem(self.DEFAULT_SRID) # WGS 84 / UTM zone 33N
geoDbCrs = QgsCoordinateReferenceSystem(self.GEODBDEFAULT_SRID) # WGS 84 / UTM zone 33N
xform = QgsCoordinateTransform(geoDbCrs, defaultCrs)
if geom.transform(xform):
message = self.tr("Errore nella conversione del bbox del DB a quello del progetto")
self.showMessage(message, QgsMessageLog.WARNING)
return
self.iface.mapCanvas().setExtent(geom.boundingBox())
self.iface.mapCanvas().refresh()
def selectCatastoGeometry(self, catastos):
if len(catastos) == 0:
return
# get only the first record
catasto = catastos[0]
if len(catastos) != 1:
message = self.tr("Ottenuti %d records. Verrà considerato solo il primo con gid: %d" % (len(catastos), catasto["gid"]))
self.showMessage(message, QgsMessageLog.INFO)
# now get feature related to the record
# probabily bettere use Nathan query lib: http://nathanw.net/2013/07/24/the-little-query-engine-for-pyqgis/
QgsLogger.debug(self.tr("Dump del record catasto %s" % json.dumps(catasto)) )
layer = QgsMapLayerRegistry.instance().mapLayer( GeosismaWindow.VLID_GEOM_ORIG )
layer.removeSelection()
exp = QgsExpression("gid = %d" % catasto["gid"])
fields = layer.pendingFields()
exp.prepare(fields)
features = filter(exp.evaluate, layer.getFeatures())
layer.setSelectedFeatures( [f.id() for f in features] )
self.iface.mapCanvas().zoomToSelected(layer)
self.iface.mapCanvas().refresh()
def selectSafety(self, gid=None):
# get id of the current selected safety
local_id = None
if self.currentSafety is not None and not gid:
local_id = self.currentSafety["local_id"]
from DlgSelectSafety import DlgSelectSafety
dlg = DlgSelectSafety(currentSafetyId=local_id, gid=gid)
# delete because no results to show
if len(dlg.records) == 0 :
if gid:
message = u"Nessuna scheda associata alla particella"
elif local_id:
message = u"Nessuna scheda con local_id %" % local_id
else:
message = u"Nessuna scheda disponibile"
msgBox = QMessageBox()
msgBox.setIcon(QMessageBox.Information)
msgBox.setText("RT Geosisma")
msgBox.setInformativeText(self.tr( message ))
msgBox.setStandardButtons(QMessageBox.Yes)
msgBox.setButtonText(QMessageBox.Yes, self.tr("Ok"))
ret = msgBox.exec_()
dlg.deleteLater()
return
ret = dlg.exec_()
# check if result set
if ret != 0:
if (dlg.buttonSelected == "Ok"):
# deselect all safety geometries
layer = QgsMapLayerRegistry.instance().mapLayer( GeosismaWindow.VLID_GEOM_ORIG )
layer.removeSelection()
# get selected request
self.currentSafety = dlg.currentSafety
self.updatedCurrentSafety.emit()
elif (dlg.buttonSelected == "Save"): # Means Upload current safety
if dlg.currentSafety is None:
return
# get selected request
self.safeties = dlg.records
self.currentSafety = dlg.currentSafety
self.updatedCurrentSafety.emit()
# now upload currentSafety if not already uploaded
if str(self.currentSafety["id"]) == "-1":
self.uploadSafeties([self.currentSafety])
else:
message = self.tr("Scheda %s gia' archiviata con il numero: %s" % (self.currentSafety["local_id"], self.currentSafety["number"]))
self.showMessage(message, QgsMessageLog.WARNING)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
elif (dlg.buttonSelected == "SaveAll"): # means upload all safeties
self.safeties = dlg.records
# add to the list only safety to be uploaded
safetyToUpload = []
for safety in self.safeties:
if str(safety["id"]) != "-1":
continue
safetyToUpload.append(safety)
self.uploadSafeties(safetyToUpload)
def openCurrentSafety(self):
QgsLogger.debug("openCurrentSafety entered",2 )
if self.currentSafety == None:
return
# get teamName
from ArchiveManager import ArchiveManager # import here to avoid circular import
if self.teams == None:
self.teams = ArchiveManager.instance().loadTeams()
teamName = ""
for team in self.teams:
if team["id"] == self.currentSafety["team_id"]:
teamName = team["name"]
# update safetyForm is opened
if self.safetyDlg is not None:
self.updateSafetyForm()
else:
self.safetyDlg = None
from DlgSafetyForm import DlgSafetyForm
self.safetyDlg = DlgSafetyForm( teamName, self.currentSafety, self.iface, self.iface.mainWindow() )
self.safetyDlg.currentSafetyModifed.connect(self.updateCurrentSafetyFromForm)
self.safetyDlg.destroyed.connect(self.cleanUpSafetyForm)
self.safetyDlg.exec_()
QgsLogger.debug("openCurrentSafety exit",2 )
def cleanUpSafetyForm(self):
try:
QgsLogger.debug("cleanUpSafetyForm entered",2 )
self.safetyDlg = None
QgsLogger.debug("cleanUpSafetyForm exit",2 )
except:
pass
def updateSafetyForm(self):
QgsLogger.debug("updateSafetyForm entered",2 )
# remove dialog is safety == None
if self.currentSafety == None:
if self.safetyDlg is not None:
self.safetyDlg.deleteLater()
self.safetyDlg = None
return
if self.safetyDlg is None:
# open e new one
self.openCurrentSafety()
else:
# could be managed passing safety in the signal managed by the form
self.safetyDlg.currentSafety = self.currentSafety
self.safetyDlg.update()
QgsLogger.debug("updateSafetyForm exit",2 )
def updateCurrentSafetyFromForm(self, safetyDict):
QgsLogger.debug("updateCurrentSafetyFromForm entered",2 )
if safetyDict == None:
return
# check if safetyNumber is changed
subSafetyDict = json.loads( safetyDict["safety"] )
if self.currentSafety["number"] != subSafetyDict["number"]:
# check if number is laready kept
from ArchiveManager import ArchiveManager # import here to avoid circular import
safety_numbers = ArchiveManager.instance().loadSafetyNumbers()
if int(subSafetyDict["number"]) in [int(v) for v in safety_numbers]:
message = self.tr(u"Scheda non salvata. Il numero di scheda %s è giá presente. Scegline un'altro" % subSafetyDict["number"])
self.showMessage(message, QgsMessageLog.WARNING)
QMessageBox.warning(self, GeosismaWindow.MESSAGELOG_CLASS, message)
return
#modify safetyNumber of the record
self.currentSafety["number"] = subSafetyDict["number"]
self.currentSafety["safety"] = safetyDict["safety"]
self.updatedCurrentSafety.emit()
QgsLogger.debug("updateCurrentSafetyFromForm exit",2 )
def updateArchivedCurrentSafety(self):
QgsLogger.debug("updateArchivedCurrentSafety entered",2 )
if self.currentSafety == None:
return
tempSafety = self.updateArchivedSafety(self.currentSafety)
if not tempSafety is None:
self.currentSafety = tempSafety
QgsLogger.debug("updateArchivedCurrentSafety exit",2 )
def updateArchivedSafety(self, safety):
QgsLogger.debug("updateArchivedSafety entered",2 )
if safety == None:
return safety
QgsLogger.debug(self.tr("Dump di safety %s" % json.dumps( safety )) )
try:
from ArchiveManager import ArchiveManager # import here to avoid circular import
overwrite = True
ArchiveManager.instance().archiveSafety(safety["request_id"], safety["team_id"], safety, overwrite)
ArchiveManager.instance().commit()
# if it's a new record get new id to update currentSafety
if safety["local_id"] == None:
lastId = ArchiveManager.instance().getLastRowId()
if lastId != self.currentSafety["local_id"]:
safety["local_id"] = lastId
message = self.tr("Inserita nuova scheda con id %s" % safety["local_id"])
self.showMessage(message, QgsMessageLog.INFO)
except Exception as ex:
try:
traceback.print_exc()
except:
pass
ArchiveManager.instance().close() # to avoid locking
message = self.tr("Fallito l'update della scheda di sopralluogo")
self.showMessage(message + ": "+ex.message, QgsMessageLog.CRITICAL)
QMessageBox.critical(self, GeosismaWindow.MESSAGELOG_CLASS, message)
safety = None
finally:
ArchiveManager.instance().close() # to avoid locking
QgsLogger.debug("updateArchivedSafety exit",2 )