-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbiorecdialog.py
1525 lines (1244 loc) · 64 KB
/
biorecdialog.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 -*-
"""
/***************************************************************************
BiorecDialog
A QGIS plugin
FSC QGIS plugin for biological recorders
-------------------
begin : 2014-02-17
copyright : (C) 2014 by Rich Burkmar, Field Studies Council
email : richardb@field-studies-council.org
***************************************************************************
/***************************************************************************
* *
* 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
import ntpath
import csv
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtNetwork import *
from PyQt5.QtWidgets import *
from qgis import *
from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from . import ui_biorec
from . import filedialog
from . import bioreclayer
from . import envmanager
from datetime import datetime
from PyQt5 import QtSql
import re, platform
from .ui_R6 import Ui_R6
from .ui_R6Credentials import Ui_R6Credentials
from qgis.PyQt import QtGui
if platform.system() == 'Windows':
import winreg
class BiorecDialog(QWidget, ui_biorec.Ui_Biorec):
def __init__(self, iface, dockwidget):
QWidget.__init__(self)
ui_biorec.Ui_Biorec.__init__(self)
self.setupUi(self)
self.canvas = iface.mapCanvas()
self.iface = iface
self.butBrowse.clicked.connect(self.browseDatasource)
self.butMap.clicked.connect(self.MapRecords)
self.butShowAll.clicked.connect(self.showAll)
self.butHideAll.clicked.connect(self.hideAll)
self.butGenTree.clicked.connect(self.listTaxa)
self.butSaveImage.clicked.connect(self.batchGeneration)
self.butRemoveMap.clicked.connect(self.removeMap)
self.butRemoveMaps.clicked.connect(self.removeMaps)
self.butExpand.clicked.connect(self.expandAll)
self.butContract.clicked.connect(self.collapseAll)
self.butCheckAll.clicked.connect(self.checkAll)
self.butUncheckAll.clicked.connect(self.uncheckAll)
self.pbBrowseImageFolder.clicked.connect(self.browseImageFolder)
self.pbBrowseStyleFile.clicked.connect(self.browseStyleFile)
self.pbCancel.clicked.connect(self.cancelBatch)
self.butHelp.clicked.connect(self.helpFile)
self.butGithub.clicked.connect(self.github)
self.fcbTaxonCol.fieldChanged.connect(self.taxonColChanged)
self.cboMapType.currentIndexChanged.connect(self.checkMapType)
self.mlcbSourceLayer.layerChanged.connect(self.layerSelected)
self.fcbGridRefCol.fieldChanged.connect(self.enableDisableGridRef)
self.fcbXCol.fieldChanged.connect(self.enableDisableXY)
self.fcbYCol.fieldChanged.connect(self.enableDisableXY)
self.pswInputCRS.crsChanged.connect(self.inputCrsSelected)
self.cboOutputFormat.currentIndexChanged.connect(self.outputFormatChanged)
self.rbOutCrsBritish.toggled.connect(self.outCrsRadio)
self.rbOutCrsIrish.toggled.connect(self.outCrsRadio)
self.rbOutCrsOther.toggled.connect(self.outCrsRadio)
self.rbOutCrsInput.toggled.connect(self.outCrsRadio)
# Load the environment stuff
self.env = envmanager.envManager()
# Globals
self.propogateDown = True
self.propogateUp = True
self.layers = []
self.stepLayerIndex = -1
self.folderError = False
self.imageError = False
self.cancelBatchMap = False
self.guiFile = None
self.infoFile = os.path.join(os.path.dirname( __file__ ), "infoBioRecTool.txt")
self.csvLayer = None
self.leImageFolder.setText(self.env.getEnvValue("biorec.r6SQLServerUserName"))
self.r6Credentials = {
"server": self.env.getEnvValue("biorec.r6SQLServer"),
"user": self.env.getEnvValue("biorec.r6SQLServerUserName"),
"pword": self.env.getEnvValue("biorec.r6SQLServerPassword")
}
# Set button graphics
self.pathPlugin = "%s%s%%s" % ( os.path.dirname( __file__ ), os.path.sep )
self.butMap.setIcon(QIcon( self.pathPlugin % "images/maptaxa.png" ))
self.butRemoveMap.setIcon(QIcon( self.pathPlugin % "images/removelayer.png" ))
self.butRemoveMaps.setIcon(QIcon( self.pathPlugin % "images/removelayers.png" ))
self.butHelp.setIcon(QIcon( self.pathPlugin % "images/info.png" ))
self.butGithub.setIcon(QIcon( self.pathPlugin % "images/github.png" ))
self.butSaveImage.setIcon(QIcon( self.pathPlugin % "images/saveimage.png" ))
self.butShowAll.setIcon(QIcon( self.pathPlugin % "images/layershow.png" ))
self.butHideAll.setIcon(QIcon( self.pathPlugin % "images/layerhide.png" ))
#Inits
self.blockGR = False
self.blockXY = False
self.dsbGridSize.setEnabled(False)
self.lastWaitMessage = None
self.rbOutCrsBritish.setChecked(True)
self.outCrsRadio()
self.isNBNCSV = None
self.pswInputCRS.setOptionVisible(self.pswInputCRS.CrsNotSet,True)
self.pswInputCRS.setNotSetText("CRS not set")
self.pswOutputCRS.setOptionVisible(self.pswOutputCRS.CrsNotSet,True)
self.pswOutputCRS.setNotSetText("CRS not set")
self.mlcbSourceLayer.setFilters( QgsMapLayerProxyModel.PointLayer | QgsMapLayerProxyModel.NoGeometry )
self.mlcbTaxonMetaDataLayer.setFilters( QgsMapLayerProxyModel.NoGeometry )
# Set scientific names checkbox if set in environment
if self.env.getEnvValue("biorec.scientificnames") == "True":
self.cbIsScientific.setChecked(True)
else:
self.cbIsScientific.setChecked(False)
#Programmatic selection of fields not currently working properly so can't set the filters
#self.fcbGridRefCol.setFilters( QgsFieldProxyModel.String )
#self.fcbXCol.setFilters( QgsFieldProxyModel.Numeric )
#self.fcbYCol.setFilters( QgsFieldProxyModel.Numeric )
#self.fcbGridRefCol.setAllowEmptyFieldName(True)
#self.fcbXCol.setAllowEmptyFieldName(True)
#self.fcbYCol.setAllowEmptyFieldName(True)
self.layerSelected()
def checkMapType(self):
if self.cboMapType.currentText().startswith("User-defined"):
self.dsbGridSize.setEnabled(True)
else:
self.dsbGridSize.setValue(0)
self.dsbGridSize.setEnabled(False)
def getR6Credentials(self):
dlg = R6CredentialsDialog(self.r6Credentials)
dlg.exec_()
okayed = dlg.okayed
if okayed:
self.r6Credentials = dlg.credentials
dlg.close()
return okayed
def ChkR6Setup(self):
dbOpen = False
db = QtSql.QSqlDatabase.addDatabase('QODBC')
if platform.system() == 'Windows':
try:
#r6Key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\WOW6432Node\Dropbox', 0, #For testing on non-R6 machine
r6Key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\WOW6432Node\Dorset Software', 0,
(winreg.KEY_WOW64_64KEY + winreg.KEY_READ))
except:
#There was some sort of error trying to retrieve the R6 registry key
r6Key = None
if r6Key:
#Registry R6 keys found, retrieve servername and user it to build trusted connection string
subname = winreg.EnumKey(r6Key, 0)
subkey = winreg.OpenKey(r6Key, subname, 0, (winreg.KEY_WOW64_64KEY + winreg.KEY_READ))
#self.r6Credentials["server"] = winreg.QueryValueEx(subkey, "Version")[0] #For testing on non-R6 machine
self.r6Credentials["server"] = winreg.QueryValueEx(subkey, "Server Name")[0]
con_str = "DRIVER={{SQL Server}};SERVER={0};DATABASE=NBNData;Trusted_Connection=yes;".format('{' + self.r6Credentials["server"] + '}')
#Attempt to open DB with trusted connection string
self.waitMessage("Connecting to DB", "attempting to connect to R6 DB with trusted connection...")
db.setDatabaseName(con_str)
self.waitMessage()
if db.open():
dbOpen = True
if not dbOpen:
#Prompt user for R6 servername (already initialised if r6Key found), username and password
if self.getR6Credentials():
con_str = 'DRIVER={{SQL Server}};SERVER={0};Database=NBNData;UID={1};PWD={2};'.format('{' + self.r6Credentials["server"] + '}',self.r6Credentials["user"],self.r6Credentials["pword"])
#Attempt connection with supplied credentials
self.waitMessage("Connecting to DB", "attempting to connect to R6 DB with supplied credentials...")
db.setDatabaseName(con_str)
self.waitMessage()
if db.open():
dbOpen = True
else:
self.errorMessage("Couldn't connect with those credentials")
else:
self.errorMessage("R6 only runs on Windows platform")
if dbOpen:
#Open dialog for user to generate CSV memory layer from SQL query
r6dlg = R6Dialog()
r6dlg.exec_()
if r6dlg.csvLayer:
self.mlcbSourceLayer.setLayer(r6dlg.csvLayer)
if r6dlg.message:
self.infoMessage(r6dlg.message)
r6dlg.close()
db.close()
def outputFormatChanged(self):
format = self.cboOutputFormat.currentText()
if (format == "GeoJSON") or (format == "Shapefile"):
self.qgsOutputCRS.setEnabled(True)
else:
self.qgsOutputCRS.setEnabled(False)
def showEvent(self, ev):
# Load the environment stuff
self.env = envmanager.envManager()
self.leImageFolder.setText(self.env.getEnvValue("biorec.atlasimagefolder"))
return QWidget.showEvent(self, ev)
def logMessage(self, strMessage, level=Qgis.Info):
QgsMessageLog.logMessage(strMessage, "Biological Records Tool", level)
def infoMessage(self, strMessage):
self.iface.messageBar().pushMessage("Info", strMessage, level=Qgis.Info)
def warningMessage(self, strMessage):
self.iface.messageBar().pushMessage("Warning", strMessage, level=Qgis.Warning)
def errorMessage(self, strMessage):
self.iface.messageBar().pushMessage("Error", strMessage, level=Qgis.Critical)
def waitMessage(self, str1="", str2=""):
try:
#This fails if self.lastWaitMessage already deleted so needs to be caught
iface.messageBar().popWidget(self.lastWaitMessage)
except:
pass
if str1 != "":
widget = iface.messageBar().createMessage(str1, str2)
self.lastWaitMessage = iface.messageBar().pushWidget(widget, Qgis.Info)
qApp.processEvents()
def helpFile(self):
QDesktopServices().openUrl(QUrl("http://www.fscbiodiversity.uk/qgisbiorecstool"))
def github(self):
QDesktopServices().openUrl(QUrl("https://github.com/FieldStudiesCouncil/QGIS-Biological-Recording-Tools/issues"))
def outCrsRadio(self):
if self.rbOutCrsBritish.isChecked():
self.pswOutputCRS.setEnabled(False)
self.pswOutputCRS.setCrs(QgsCoordinateReferenceSystem("EPSG:27700"))
elif self.rbOutCrsIrish.isChecked():
self.pswOutputCRS.setEnabled(False)
self.pswOutputCRS.setCrs(QgsCoordinateReferenceSystem("EPSG:29903"))
elif self.rbOutCrsInput.isChecked():
self.pswOutputCRS.setEnabled(False)
self.pswOutputCRS.setCrs(self.pswInputCRS.crs())
elif self.rbOutCrsOther.isChecked():
self.pswOutputCRS.setEnabled(True)
self.pswOutputCRS.setCrs(QgsCoordinateReferenceSystem(None))
def enableDisableGridRef(self):
if self.blockGR:
return
self.blockGR = True
if self.csvLayer != None:
if self.csvLayer.geometryType() == 3 or self.csvLayer.geometryType() == 4:
self.fcbGridRefCol.setEnabled(True)
self.lblGridRefCol.setEnabled(True)
self.fcbXCol.setEnabled(True)
self.lblXCol.setEnabled(True)
self.fcbYCol.setEnabled(True)
self.lblYCol.setEnabled(True)
if self.fcbGridRefCol.currentField() != "" and not self.blockXY:
if self.fcbXCol.currentField() != "":
self.fcbXCol.setField("not set")
if self.fcbYCol.currentField() != "":
self.fcbYCol.setField("not set")
if self.fcbGridRefCol.currentField() != "":
#When grid references are used for input, Input CRS is not set
self.pswInputCRS.setCrs(QgsCoordinateReferenceSystem(None))
self.pswInputCRS.setEnabled(False)
if self.cboMapType.currentText().startswith("User-defined"):
self.cboMapType.setCurrentIndex(0)
else:
self.pswInputCRS.setEnabled(True)
self.pswOutputCRS.setEnabled(not self.rbOutCrsInput.isChecked())
bClear = False
else:
self.pswInputCRS.setEnabled(False)
bClear = True
else:
bClear = True
if bClear:
if self.fcbGridRefCol.currentField() != "":
self.fcbGridRefCol.setField("not set")
if self.fcbXCol.currentField() != "":
self.fcbXCol.setField("not set")
if self.fcbYCol.currentField() != "":
self.fcbYCol.setField("not set")
self.fcbGridRefCol.setEnabled(False)
self.lblGridRefCol.setEnabled(False)
self.fcbXCol.setEnabled(False)
self.lblXCol.setEnabled(False)
self.fcbYCol.setEnabled(False)
self.lblYCol.setEnabled(False)
self.blockGR = False
def enableDisableXY(self):
if self.blockXY:
return
self.blockXY = True
if (self.fcbXCol.currentField() != "" or self.fcbYCol.currentField() != "") and not self.blockGR:
if self.fcbGridRefCol.currentField() != "":
self.fcbGridRefCol.setField("not set")
self.enableDisableGridRef()
self.blockXY = False
def enableDisableTaxa(self):
if self.fcbTaxonCol.currentIndex() == 0:
self.fcbGroupingCol.setCurrentIndex(0)
self.fcbGroupingCol.setEnabled(False)
self.lblGroupingCol.setEnabled(False)
self.cbIsScientific.setChecked(False)
self.cbIsScientific.setEnabled(False)
else:
self.fcbGroupingCol.setEnabled(True)
self.cbIsScientific.setEnabled(True)
self.lblGroupingCol.setEnabled(True)
def taxonColChanged(self):
self.enableDisableTaxa()
self.listTaxa(True)
def inputCrsSelected(self, crs):
if self.rbOutCrsInput.isChecked():
self.pswOutputCRS.setCrs(self.pswInputCRS.crs())
def browseImageFolder(self):
#Reload env
self.env.loadEnvironment()
dlg = QFileDialog
if os.path.exists(self.leImageFolder.text()):
strInitPath = self.leImageFolder.text()
else:
strInitPath = ""
folderName = dlg.getExistingDirectory(self, "Browse for image folder", strInitPath)
if folderName:
self.leImageFolder.setText(folderName)
self.leImageFolder.setToolTip(folderName)
def browseStyleFile(self):
#Reload env
self.env.loadEnvironment()
if os.path.exists(self.env.getEnvValue("biorec.stylefilefolder")):
strInitPath = self.env.getEnvValue("biorec.stylefilefolder")
else:
strInitPath = ""
dlg = QFileDialog
fileName = dlg.getOpenFileName(self, "Browse for style file", strInitPath, "QML Style Files (*.qml)")[0]
if fileName:
self.leStyleFile.setText(fileName)
self.leStyleFile.setToolTip(fileName)
def browseDatasource(self):
datasource = self.cboDatasource.currentText()
if (datasource == "Create source from CSV file"):
self.setCSV(None)
elif (datasource == "Create source from R6 database"):
self.ChkR6Setup()
def setCSV(self, nbnFile):
#Reload env
self.env.loadEnvironment()
if os.path.exists(self.env.getEnvValue("biorec.csvfolder")):
strInitPath = self.env.getEnvValue("biorec.csvfolder")
else:
strInitPath = ""
if nbnFile is None:
dlg = QFileDialog
fileName = dlg.getOpenFileName(self, "Browse for biological record file", strInitPath, "Record Files (*.csv)")[0]
#According to the documentation, this should return a string, but it returns a tuple of this form:
#('C:/Users/richardb/Documents/Work/GIS/Biological Records etc/Andy Musgrove Yorkshire BirdTrack records.csv', 'Record Files (*.csv)'
#or, if cancelled, ('', '').
else:
fileName = nbnFile
if fileName != "":
# Load the CSV and set controls
self.loadCsv(fileName, (not nbnFile is None))
def initTreeView(self):
#Initialise the tree model
modelTree = QStandardItemModel()
modelTree.itemChanged.connect(self.tvBoxChecked)
self.tvTaxa.setModel(modelTree)
self.modelTree = modelTree
def listTaxa(self, suppressMessage=False):
#Init the tree view
self.initTreeView()
if self.csvLayer is None:
return
if self.fcbTaxonCol.currentIndex() < 1:
if not suppressMessage:
self.infoMessage("No taxon column selected")
return
iColGrouping = self.fcbGroupingCol.currentIndex() - 1
iColTaxon = self.fcbTaxonCol.currentIndex() - 1
bScientific = self.cbIsScientific.isChecked()
if iColTaxon == -1:
return
self.waitMessage("Building taxon tree", "can take a minute or so for very large files...")
tree = {}
iter = self.csvLayer.getFeatures()
for feature in iter:
if iColGrouping > -1:
try:
group = feature.attributes()[iColGrouping].strip()
except:
group = "invalid"
if group not in tree.keys():
tree[group] = {}
try:
parent = tree[group]
except:
self.pteLog.appendPlainText("Grouping error " + str(group))
else:
parent = tree
try:
taxon = feature.attributes()[iColTaxon].strip()
except:
taxon = "invalid"
if bScientific:
splitTaxon = taxon.split(" ")
genus = splitTaxon[0]
if genus not in parent.keys():
parent[genus] = {}
parent = parent[genus]
if taxon not in parent.keys():
parent[taxon] = {}
#Build tree from nested lists (which are sorted on the fly)
#The technique for sorting dicts came from https://stackoverflow.com/questions/11089655/sorting-dictionary-python-3
for l1 in {k: tree[k] for k in sorted(tree)}:
itemL1 = QStandardItem(l1)
itemL1.setCheckable(True)
self.modelTree.appendRow(itemL1)
dictL2 = tree[l1]
for l2 in {k: dictL2[k] for k in sorted(dictL2)}:
itemL2 = QStandardItem(l2)
itemL2.setCheckable(True)
itemL1.appendRow(itemL2)
dictL3 = dictL2[l2]
for l3 in {k: dictL3[k] for k in sorted(dictL3)}:
itemL3 = QStandardItem(l3)
itemL3.setCheckable(True)
itemL2.appendRow(itemL3)
self.tvTaxa.header().close()
self.waitMessage()
def tvBoxChecked(self, item):
self.propogateUp = False
self.setChildrenItems(item, item.checkState())
self.propogateUp = True
if item.checkState() == False:
self.propogateDown = False
self.uncheckParents(item)
self.propogateDown = True
def uncheckParents(self, item):
if not self.propogateUp:
return
if item.parent() is None:
return
item.parent().setCheckState(False)
self.uncheckParents(item.parent())
def setChildrenItems(self, item, checked):
if not self.propogateDown:
return
for i in range (item.rowCount()):
item.child(i,0).setCheckState(checked)
self.setChildrenItems(item.child(i,0), checked)
def expandAll(self):
self.tvTaxa.expandAll()
def collapseAll(self):
self.tvTaxa.collapseAll()
def checkAll(self):
if self.tvTaxa.model() is None:
return
for i in range(self.tvTaxa.model().rowCount()):
self.tvTaxa.model().item(i,0).setCheckState(Qt.Checked)
self.setChildrenItems(self.tvTaxa.model().item(i,0), Qt.Checked)
def uncheckAll(self):
if self.tvTaxa.model() is None:
return
for i in range(self.tvTaxa.model().rowCount()):
self.tvTaxa.model().item(i,0).setCheckState(Qt.Unchecked)
self.setChildrenItems(self.tvTaxa.model().item(i,0), Qt.Unchecked)
def loadCsv(self, fileName, isNBNCSV):
self.isNBNCSV = isNBNCSV
#Reload the environment
self.env.loadEnvironment()
#Load as a CSV
uri = "file:///" + fileName + "?delimiter=%s" % (",")
self.waitMessage("Loading", fileName)
try:
lyr = QgsVectorLayer(uri, os.path.basename(fileName), "delimitedtext")
#Add to registry
QgsProject.instance().addMapLayer(lyr)
except:
lyr = None
self.waitMessage()
if lyr == None:
self.warningMessage("Couldn't open CSV file: '%s'" % (fileName))
else:
#Set in layer selection list.
self.mlcbSourceLayer.setLayer(lyr)
def layerSelected(self):
if self.csvLayer != self.mlcbSourceLayer.currentLayer():
# Clear taxon tree
self.initTreeView()
self.csvLayer = self.mlcbSourceLayer.currentLayer()
if self.csvLayer != None:
self.pswInputCRS.setCrs(self.csvLayer.crs())
#if self.cbMatchCRS.isChecked():
if self.rbOutCrsInput.isChecked():
self.pswOutputCRS.setCrs(self.pswInputCRS.crs())
#Need to enable field selectors in order to set values
self.fcbGridRefCol.setEnabled(True)
self.lblGridRefCol.setEnabled(True)
self.fcbXCol.setEnabled(True)
self.lblXCol.setEnabled(True)
self.fcbYCol.setEnabled(True)
self.lblYCol.setEnabled(True)
self.fcbGridRefCol.setLayer(self.csvLayer)
self.fcbXCol.setLayer(self.csvLayer)
self.fcbYCol.setLayer(self.csvLayer)
self.fcbAbundanceCol.setLayer(self.csvLayer)
self.fcbGroupingCol.setLayer(self.csvLayer)
self.fcbTaxonCol.setLayer(self.csvLayer)
self.fcbDateCol.setLayer(self.csvLayer)
self.fcbDate2Col.setLayer(self.csvLayer)
if self.csvLayer != None:
#Initialise the tree model
self.initTreeView()
# Set default value for GridRef column
if self.isNBNCSV:
index = 1
for field in self.csvLayer.dataProvider().fields():
if field.name() == "OSGR":
self.fcbGridRefCol.setField(field.name())
break
index += 1
else:
for colGridRef in self.env.getEnvValues("biorec.gridrefcol"):
index = 1
for field in self.csvLayer.dataProvider().fields():
if field.name() == colGridRef:
self.fcbGridRefCol.setField(field.name())
break
index += 1
if self.fcbGridRefCol.currentField() == "":
# Set default value for X column
for colX in self.env.getEnvValues("biorec.xcol"):
index = 1
for field in self.csvLayer.dataProvider().fields():
if field.name() == colX:
self.fcbXCol.setField(field.name())
break
index += 1
# Set default value for Y column
for colY in self.env.getEnvValues("biorec.ycol"):
index = 1
for field in self.csvLayer.dataProvider().fields():
if field.name() == colY:#
self.fcbYCol.setField(field.name())
break
index += 1
# Set default value for Taxon column
if self.isNBNCSV:
index = 1
for field in self.csvLayer.dataProvider().fields():
if field.name() == "Matched Scientific Name":
self.fcbTaxonCol.setCurrentIndex(index)
self.fcbTaxonCol.setCurrentIndex(index)
break
index += 1
else:
for colTaxon in self.env.getEnvValues("biorec.taxoncol"):
index = 1
for field in self.csvLayer.dataProvider().fields():
if field.name() == colTaxon:
self.fcbTaxonCol.setCurrentIndex(index)
break
index += 1
# Set default value for Grouping column
for colGrouping in self.env.getEnvValues("biorec.groupingcol"):
index = 1
for field in self.csvLayer.dataProvider().fields():
if field.name() == colGrouping:
self.fcbGroupingCol.setCurrentIndex(index)
break
index += 1
# Set default value for Abundance column
for colAbundance in self.env.getEnvValues("biorec.abundancecol"):
index = 1
for field in self.csvLayer.dataProvider().fields():
if field.name() == colAbundance:
self.fcbAbundanceCol.setCurrentIndex(index)
break
index += 1
# Set default value for start date column
for colDate in self.env.getEnvValues("biorec.datestartcol"):
index = 1
for field in self.csvLayer.dataProvider().fields():
if field.name() == colDate:
self.fcbDateCol.setCurrentIndex(index)
break
index += 1
# Set default value for end date column
for colDate in self.env.getEnvValues("biorec.dateendcol"):
index = 1
for field in self.csvLayer.dataProvider().fields():
if field.name() == colDate:
self.fcbDate2Col.setCurrentIndex(index)
break
index += 1
#If the maketree environment variable is set, then
#automatically create tree
#Take this out because it can really slow things down when layers
#automatically selected from drop-down.
#if self.env.getEnvValue("biorec.maketree") == "True":
#self.listTaxa(True)
self.enableDisableTaxa()
self.enableDisableGridRef()
self.enableDisableXY()
if self.cbLoadTaxa.isChecked():
self.listTaxa(False)
self.checkAll()
def MapRecords(self):
# Before creating new layers, for current list of layers, remove any from the list which are not
# listed in map registry. This accounts for people removing layers direct from registry.
tmpLayers = []
for layer in self.layers:
try:
regLayer = QgsProject.instance().mapLayer(layer.getVectorLayer().id())
layerFound = True
except:
layerFound = False
if layerFound:
tmpLayers.append(layer)
self.layers = list(tmpLayers)
# Initialise progress bar
self.progBatch.setValue(0)
# Return if no output CRS
if self.pswOutputCRS.crs().authid() == "":
self.iface.messageBar().pushMessage("Info", "You must specify an output CRS", level=Qgis.Info)
return
# Return if grid ref field set and user-defined grid is set
if self.fcbGridRefCol.currentField() != "" and self.cboMapType.currentText().startswith("User-defined"):
self.infoMessage("Can't set a user-defined grid size when using grid references as input")
return
# Return if output is records as grid squares but grid ref column not set
if self.cboMapType.currentText() == "Records as grid squares" and self.fcbGridRefCol.currentField() == "":
self.infoMessage("'Records as grid squares' only available for input as grid references")
return
# Return if no grid reference or X & Y fields selected - but only for layers without geometry
if self.csvLayer.geometryType() == 3 or self.csvLayer.geometryType() == 4:
self.fcbGridRefCol.currentField() == ""
if self.fcbGridRefCol.currentField() == "" and (self.fcbXCol.currentField() == "" or self.fcbYCol.currentField() == ""):
self.iface.messageBar().pushMessage("Info", "You must select either a Grid Ref column or both X and Y columns for CSV layers", level=Qgis.Info)
return
# Return if Grid ref selected with user-defined grid
if self.fcbGridRefCol.currentField() != "" and self.cboMapType.currentText().startswith("User-defined"):
self.iface.messageBar().pushMessage("Info", "You cannot specify a user-defined grid with input of grid references", level=Qgis.Info)
return
# Return if X & Y selected but no input CRS
if self.fcbXCol.currentField() != "" and self.pswInputCRS.crs().authid() == "":
self.iface.messageBar().pushMessage("Info", "You must specify an input CRS if specifying X and Y columns", level=Qgis.Info)
return
# Return if X & Y selected but no output CRS
if self.fcbXCol.currentField() != "" and self.pswOutputCRS.crs().authid() == "":
self.iface.messageBar().pushMessage("Info", "You must specify an output CRS if specifying X and Y columns", level=Qgis.Info)
return
# Return if user-defined atlas selected, but no grid size
if self.cboMapType.currentText().startswith("User-defined") and self.dsbGridSize.value() == 0:
self.iface.messageBar().pushMessage("Info", "You must specify a grid size if specifying a user-defined atlas", level=Qgis.Info)
return
# Return if a grid option selected, but the output CRS is not Irish or British Grid (unless input is grid references)
if self.fcbGridRefCol.currentField() == "" and not self.cboMapType.currentText().startswith("User-defined") and not self.cboMapType.currentText() == "Records as points":
if self.pswOutputCRS.crs().authid() != "EPSG:27700" and self.pswOutputCRS.crs().authid() != "EPSG:29903":
self.infoMessage("Only points or user-defined grid can be use for output CRS that is not either Irish or British Grid (EPSG:29903 or EPSG:2770) where input is not grid references")
return
# Make a list of all the selected taxa
selectedTaxa = []
if not self.tvTaxa.model() is None:
for i in range(self.tvTaxa.model().rowCount()):
selectedTaxa.extend(self.getCheckedTaxa(self.tvTaxa.model().item(i,0)))
if len(selectedTaxa) == 0 and self.fcbTaxonCol.currentIndex() > 0:
self.iface.messageBar().pushMessage("Info", "No taxa selected.", level=Qgis.Info)
return
if self.cboBatchMode.currentIndex() == 0 or self.fcbTaxonCol.currentIndex() == 0:
self.progBatch.setValue(0)
self.progBatch.setMaximum(100) #bioreclayer increments progress in percentage points
self.createMapLayer(selectedTaxa)
self.progBatch.setValue(0)
else:
self.progBatch.setMaximum(len(selectedTaxa) * 100)
i = 0
self.folderError = False
self.imageError = False
for taxa in selectedTaxa:
if not self.cancelBatchMap:
self.progBatch.setValue(i * 100) #bioreclayer increments progress in percentage points
i=i+1
self.createMapLayer([taxa])
#This is needed to allow interruptions. Now safe to use
#because layers not actually added to map until after all created.
qApp.processEvents()
self.progBatch.setValue(0)
self.cancelBatchMap = False
# Add all layers to the map in a single step
layerIDs = []
for layer in self.layers:
layerIDs.append(layer.getVectorLayer())
QgsProject.instance().addMapLayers(layerIDs)
# Make sure none of the layers expanded
for layer in self.layers:
##????????????????? Is this working?????
layer.setExpanded(False)
def batchGeneration(self):
#Check that there are temp layers to work with
if len(self.layers) == 0:
self.infoMessage("There are no temporary biorec layers to work with.")
return
#Check that an output folder is specified
imgFolder = self.leImageFolder.text()
if not os.path.exists(imgFolder):
if not self.folderError:
self.iface.messageBar().pushMessage("Error", "Output folder '%s' does not exist." % (imgFolder), level=Qgis.Warning)
return
format = self.cboOutputFormat.currentText()
if (format == "GeoJSON") or (format == "Shapefile"):
self.batchLayer(format)
elif (format == "Image"):
self.batchImageGenerate()
elif (format == "Composer image") or (format == "Composer PDF") or (format == "Composer SVG"):
self.batchPrintComposer()
def batchPrintComposer(self):
#Ensure that a layout desinger (and only one) is open
iLayouDesigners = len(iface.openLayoutDesigners())
if iLayouDesigners == 0:
self.warningMessage("Cannot connect to a layout. Make sure that the print layout (composer) you want to use is open.")
return
if iLayouDesigners > 1:
self.warningMessage("You have more than one layout open. Make sure that only one print layout (composer) is open.")
return
if len(self.layers) == 0:
return
self.progBatch.setValue(0)
self.progBatch.setMaximum(len(self.layers))
tempLayers = []
tempLayerNames = []
for layer in self.layers:
tempLayers.append(layer.vl)
tempLayerNames.append(layer.vl.name())
displayedLayers = self.canvas.mapSettings().layers()
backdropLayersBelow = []
backdropLayersAbove = []
insertPointFound = False
for lyr in displayedLayers:
if lyr.name() in tempLayerNames:
insertPointFound = True
else:
if insertPointFound:
backdropLayersBelow.append(lyr)
else:
backdropLayersAbove.append(lyr)
if not insertPointFound:
backdropLayersBelow = backdropLayersAbove
backdropLayersAbove = []
settings = self.canvas.mapSettings()
i=0
format = self.cboOutputFormat.currentText()
for layer in self.layers:
if not self.cancelBatchMap:
self.waitMessage("Creating " + format + " for " + layer.getName())
i=i+1
self.progBatch.setValue(i)
layersRender = backdropLayersAbove + [layer.vl] + backdropLayersBelow
self.saveComposerImage(layer.getName(), layersRender)
qApp.processEvents()
self.waitMessage()
self.progBatch.setValue(0)
self.cancelBatchMap = False
def batchLayer(self, format):
#Check that an output CRS has been set
if self.qgsOutputCRS.crs().authid() == "":
self.warningMessage("You must first specify a valid output CRS")
return
self.progBatch.setValue(0)
self.progBatch.setMaximum(len(self.layers))
i=0
for layer in self.layers:
if not self.cancelBatchMap:
self.waitMessage("Saving layer " + layer.getName() + " as " + format)
i=i+1
self.progBatch.setValue(i)
self.saveTempToLayer(layer, format)
self.waitMessage()
self.progBatch.setValue(0)
self.cancelBatchMap = False
def batchImageGenerate(self):
if len(self.layers) == 0:
return
self.progBatch.setValue(0)
self.progBatch.setMaximum(len(self.layers))
tempLayers = []
tempLayerNames = []
for layer in self.layers:
tempLayers.append(layer.vl)
tempLayerNames.append(layer.vl.name())
displayedLayers = self.canvas.mapSettings().layers()
backdropLayersBelow = []
backdropLayersAbove = []
insertPointFound = False
for lyr in displayedLayers:
if lyr.name() in tempLayerNames:
insertPointFound = True
else:
if insertPointFound:
backdropLayersBelow.append(lyr)
else:
backdropLayersAbove.append(lyr)
if not insertPointFound:
backdropLayersBelow = backdropLayersAbove
backdropLayersAbove = []