-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathddmanager.py
More file actions
1530 lines (1231 loc) · 60.2 KB
/
ddmanager.py
File metadata and controls
1530 lines (1231 loc) · 60.2 KB
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 -*-
"""
ddmanager
--------
Class that steers the DataDrivenUI
"""
from __future__ import absolute_import
"""
/***************************************************************************
DataDrivenInputMask
A QGIS plugin
Applies a data-driven input mask to any PostGIS-Layer
-------------------
begin : 2012-06-21
copyright : (C) 2012 by Bernhard Strรถbl / Kommunale Immobilien Jena
email : bernhard.stroebl@jena.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. *
* *
***************************************************************************/
"""
from builtins import str
from builtins import range
from builtins import object
# Import the PyQt and QGIS libraries
from qgis.PyQt import QtCore, QtGui, QtWidgets
from .dderror import DdError, DbError
try:
from qgis.PyQt import QtSql
except:
DdError(QtWidgets.QApplication.translate(
"DdError", "QtSql cannot be located on your system. Please install and try again."),
fatal = True)
from qgis.core import *
from qgis.gui import *
import qgis.core
from .ddui import DataDrivenUi, DdFormWidget
from .ddattribute import *
from .dddialog import DdDialog, DdSearchDialog
from . import ddtools
import xml.etree.ElementTree as ET
import os, re
class DdManager(object):
"""DdManager manages all masks in the current project"""
def __init__(self, iface):
self.iface = iface
self.ddLayers = dict()
settings = QtCore.QSettings()
settings.beginGroup("Qgis/digitizing")
a = settings.value("line_color_alpha",200,type=int)
b = settings.value("line_color_blue",0,type=int)
g = settings.value("line_color_green",0,type=int)
r = settings.value("line_color_red",255,type=int)
lw = settings.value("line_width",1,type=int)
settings.endGroup()
self.rubberBandColor = QtGui.QColor(r, g, b, a)
self.rubberBandWidth = lw
self.showConfigInfo = True
self.latestConfigTablesVersion = False
# is set to true if config tabels are created or updated
def __debug(self, title, str):
QgsMessageLog.logMessage(title + "\n" + str)
def __str__(self):
return "<ddmanager.DdManager>"
def saveSearchPath(self, path = ""):
settings = QtCore.QSettings()
settings.beginGroup("DataDrivenInputMask")
settings.setValue(u"lastSearchPath", path)
settings.endGroup()
def getSearchPath(self):
settings = QtCore.QSettings()
settings.beginGroup("DataDrivenInputMask")
path = settings.value("lastSearchPath", "", type=str)
settings.endGroup()
return path
def setLastSearch(self, layer, root):
layerValues = self.__getLayerValues(layer)
if layerValues != None:
if root == None:
return False
else:
self.ddLayers[layer.id()][6] = root
return True
else:
return False
def highlightFeature(self, layer, feature):
'''highlight the feature if it has a geometry'''
geomType = layer.geometryType()
if geomType <= 2:
if geomType == 0:
marker = QgsVertexMarker(self.iface.mapCanvas())
marker.setIconType(3) # ICON_BOX
marker.setColor(self.rubberBandColor)
marker.setIconSize(12)
marker.setPenWidth (3)
try:
marker.setCenter(feature.geometry().centroid().asPoint())
return marker
except:
return None
else:
rubberBand = QgsRubberBand(self.iface.mapCanvas())
rubberBand.setColor(self.rubberBandColor)
rubberBand.setWidth(self.rubberBandWidth)
rubberBand.setToGeometry(feature.geometry(), layer)
return rubberBand
else:
return None
def initLayer(self, layer, skip = [], labels = {}, fieldOrder = [], fieldGroups = {}, minMax = {}, noSearchFields = [], \
showParents = True, createAction = True, db = None, inputMask = True, searchMask = True, \
inputUi = None, searchUi = None, helpText = "", fieldDisable = []):
'''api method initLayer: initialize this layer with a data-driven input mask.
In case there is configuration for this layer in the database read this
configuration and apply what is provided there.
Returns a Boolean stating the success of the initialization
Parameters:
WARNING: if config tables are used, the parameters' objects survive
and are thus applied to the next layer, too. Be sure to also pass ALL optional
paramerters when calling initLayer()
- layer [QgsVectorLayer]
- skip [array [string]]: field names to not show
- labels [dict] with entries: "fieldname": "label"
- fieldOrder [array[string]]: containing the field names in the order they should be shown
- fieldGroups [dict] with entries: fieldName: [tabTitle, tabTooltip] for each group a tab is created and the fields from fieldName onwards (refers to fieldOrder) are grouped in this tab; tabTooltip is optional
- minMax [dict] with entries: "fieldname": [min, max] - strings; use for numerical or date fields only!
- noSearchFields [array[string]] with fields not to be shown in the search form, if empty all fields are shown. Skipped fields are never shown in the search form, no matter if they are included here
- showParents [Boolean] show tabs for 1-to-1 relations (parents)
- createAction [Boolean]: add an action to the layer's list of actions
- db [QtSql.QSqlDatabase]
- inputMask [Boolean]: create a data-edit mask
- searchMask [Boolean]: create a data-search mask
- inputUi [ddui.DdDialogWidget]: apply this inputUi
- searchUi [ddui.DdDialogWidget]: apply this as search ui
- helpText [string] help text for this mask, may be html formatted
- fieldDisable [array[string]]: field names whose DdInputWidget shall be disabled in the inputMask'''
thisSize = None # stores the size of the DdDialog
root = ET.Element('DdSearch')
if inputUi != None:
inputMask = False # do not make one but use the one provided
if searchUi != None:
searchMask = False # do not make one but use the one provided
if u'PostgreSQL' != layer.dataProvider().storageType()[0:10] :
DdError(QtWidgets.QApplication.translate("DdError", "Layer is not a PostgreSQL layer: ") +
layer.name(), iface = self.iface)
return False
else:
if db == None:
db = self.__createDb(layer)
thisTable = self.makeDdTable(layer, db)
if thisTable == None:
return False
else:
if inputMask or searchMask:
# check for config tables
ddConfigTable = DdTable(schemaName = "public", tableName = "dd_table")
readConfigTables = self.existsInDb(ddConfigTable, db)
if not readConfigTables:
readConfigTables = self.createConfigTables(db)
if readConfigTables:
readConfigTables = self.isAccessible(db, ddConfigTable, showError = False)
if not readConfigTables:
if self.showConfigInfo:
self.iface.messageBar().pushMessage(QtWidgets.QApplication.translate("DdInfo",
"Config tables either not found or not accessible, loading default mask"))
self.showConfigInfo = False
else:
readConfigTables = self.updateConfigTables(db)
# we want at least one automatically created mask
ddui = DataDrivenUi(self.iface)
autoInputUi, autoSearchUi = ddui.createUi(
thisTable, db, skip, labels, fieldOrder, fieldGroups, minMax, \
noSearchFields, showParents, True, inputMask, searchMask, helpText, createAction, \
readConfigTables = readConfigTables, fieldDisable = fieldDisable)
if inputUi == None:
# use the automatically created mask if none has been provided
inputUi = autoInputUi
if searchUi == None:
searchUi = autoSearchUi
if not inputMask or not searchMask:
# at least one mask shall not be initialized
try:
layerValues = self.ddLayers[layer.id]
# see if the layer has been initialized already
except KeyError:
layerValues = None
if layerValues != None:
# layer has been initialized before!
if not inputMask and inputUi == None:
# user did not provide a mask
inputUi = layerValues[2] # keep current
if not searchMask and searchUi == None:
searchUi = layerValues[3] # keep current
#else:
#self.ddLayers.pop(layer.id(), None) # remove entries if they exist
self.ddLayers[layer.id()] = [thisTable, db, inputUi, searchUi, showParents, thisSize, root]
# parameter 6 holds the last search or None if no last search exists
self.__connectSignals(layer)
if createAction:
self.addAction(layer)
return True
else:
# no auto masks, both were provided
self.ddLayers[layer.id()] = [thisTable, db, inputUi, searchUi, showParents, thisSize, root]
return True
def createDdTable(self, db, schemaName, tableName,
withOid = True, withComment = True):
'''create a DdTable object from the passed in variables'''
thisTable = DdTable(schemaName = schemaName, tableName = tableName)
if db == None:
return None
if withOid:
thisTable.oid = self.__getOid(thisTable, db)
if withComment:
comment = self.__getComment(thisTable, db)
if comment:
thisTable.comment = comment
if not self.__isTable(thisTable, db):
DdError(
QtWidgets.QApplication.translate("DdError",
"Layer is not a PostgreSQL table: ") +
schemaName + "." + tableName, iface = self.iface,
showInLog = True)
return None
else:
return thisTable
def makeDdTable(self, layer, db = None):
'''make a DdTable object from the passed in layer, returns None, if layer is not suitable'''
if 0 != layer.type(): # not a vector layer
DdError(
QtWidgets.QApplication.translate("DdError",
"Layer is not a vector layer: ") +
layer.name(), iface = self.iface,
showInLog = True)
return None
else:
if u'PostgreSQL' != layer.dataProvider().storageType()[0:10] :
DdError(
QtWidgets.QApplication.translate("DdError",
"Layer is not a PostgreSQL layer: ") +
layer.name(), iface = self.iface,
showInLog = True)
return None
else:
layerSrc = self.__analyzeSource(layer)
relation = layerSrc["table"].split('"."')
schema = relation[0].replace('"', '')
table = relation[1].replace('"', '')
thisTable = DdTable(schemaName = schema, tableName = table, title = layer.name())
if db == None:
db = self.__createDb(layer)
if db == None:
return None
thisTable.oid = self.__getOid(thisTable, db)
comment = self.__getComment(thisTable, db)
if comment:
thisTable.comment = comment
if not self.__isTable(thisTable, db):
DdError(
QtWidgets.QApplication.translate("DdError",
"Layer is not a PostgreSQL table: ") +
layer.name(), iface = self.iface,
showInLog = True)
return None
else:
return thisTable
def addAction(self, layer, actionName = u'showDdForm', ddManagerName = "ddManager",
newIcon = None):
'''api method to add an action to the layer with a self defined name'''
defaultTitle = QtWidgets.QApplication.translate("DdLabel", "Show Input Form")
if actionName == u'showDdForm':
newTitle = defaultTitle
else:
newTitle = actionName
actionName = u'showDdForm'
createAction = True
actionToRemove = None
#check if the action is already attached
for act in layer.actions().actions():
if act.command().find(";ddManager.showDdForm([% $id %]);") != -1:
# action has already been attached
thisTitle = act.shortTitle()
if thisTitle == newTitle: # the action exists with the given title
createAction = False
break
else:
if newTitle == defaultTitle:
# action is already in place and we would replace it with an action with default title
# and that's what it is or it has a custom title, so nothing to do
createAction = False
break
else: # action with default title exists and is to be replaced
# with an action with a custom title
actionToRemove = thisTitle
if createAction:
if actionToRemove != None:
self.removeAction(layer, actionToRemove)
if not QtCore.QFile(newIcon).exists():
newIcon = os.path.abspath(os.path.dirname(__file__) + '/datadriveninputmask.png')
if qgis.core.Qgis.QGIS_VERSION_INT >= 33000:
actionType = QgsAction.GenericPython
else:
actionType = 1 # actionType 1: Python
newAction = QgsAction(actionType, actionName,
"app=QgsApplication.instance();ddManager=app." + ddManagerName +
";ddManager.showDdForm([% $id %]);", newIcon, False, newTitle, {'Field', 'Feature', 'Canvas'})
layer.actions().addAction(newAction)
def removeAction(self, layer, actionName, actionTitle = None):
'''api method to remove an action from the layer'''
actionToRemove = None
for act in layer.actions().actions():
if act.name() == actionName:
if actionTitle == None:
actionToRemove = act.id() # no matter which tiltle
break
else:
if actionTitle == act.shortTitle:
actionToRemove = act.id()
break
if actionToRemove != None:
layer.actions().removeAction(actionToRemove)
def showFeatureForm(self, layer, feature, showParents = True,
title = None, askForSave = True, multiEdit = False, forEdit = True):
'''
api method showFeatureForm: show the data-driven input mask for a layer and a feature
if the data provider allows editing and for Edit is True, the layer is turned into editing mode
if the user clicks OK all changes to the feature are committed (no undo!)
if askForSave is true and the layer has pending changes the user is asked if the changes
shall be commited before the mask is opened
if multiEdit is True then the changes are applied to all selected Features in the layer
returns 1 if user clicked OK, 0 if CANCEL
'''
layerValues = self.__getLayerValues(layer, inputMask = True, searchMask = False)
if layerValues != None:
parentsInMask = layerValues[4]
if parentsInMask and not showParents:
self.initLayer(layer, showParents = False, inputMask = True, searchMask = False, \
skip = [], labels = {}, fieldOrder = [], fieldGroups = {}, minMax = {}, noSearchFields = [], \
createAction = True, db = None, inputUi = None, searchUi = None, helpText = ""
)
layerValues = self.__getLayerValues(layer, inputMask = True, searchMask = False)
if layerValues != None:
result = 1
wasEditable = layer.isEditable()
if forEdit:
if wasEditable:
if layer.isModified() and askForSave:
#ask user to save or discard changes
reply = QtWidgets.QMessageBox.question(None, QtWidgets.QApplication.translate("DdInfo", "Unsaved changes"),
QtWidgets.QApplication.translate("DdInfo", "Do you want to save the changes to layer ") +
layer.name() + "?",
QtWidgets.QMessageBox.Discard | QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Save)
if reply == QtWidgets.QMessageBox.Cancel:
result = 0
else:
if reply == QtWidgets.QMessageBox.Discard:
if not layer.rollBack():
DdError(QtWidgets.QApplication.translate("DdError", "Could not discard changes for layer: ") +
layer.name(), iface = self.iface)
result = 0
else:
if feature.id() <= 0: # new feature discarded
result = 0
elif reply == QtWidgets.QMessageBox.Save:
if not layer.commitChanges():
DdError(QtWidgets.QApplication.translate("DdError", "Could not save changes for layer: ") +
layer.name(), iface = self.iface)
result = 0
if result == 1:
layer.startEditing()
else:
if self.isEditable(layer):
layer.startEditing()
if result == 1:
if multiEdit:
highlightGeom = None
else:
highlightGeom = self.highlightFeature(layer, feature)
db = layerValues[1]
if not db.isValid():
db = self.__createDb(layer)
if db == None:
return None
ui = layerValues[2]
thisSize = layerValues[5]
dlg = DdDialog(self, ui, layer, feature, db, multiEdit,
title = title)
dlg.show()
if thisSize != None:
dlg.resize(thisSize)
result = dlg.exec_()
if result == 1:
layer.layerModified.emit()
# store size
thisSize = dlg.size()
self.ddLayers[layer.id()][5] = thisSize
#handle highlightGeom
if highlightGeom != None:
self.iface.mapCanvas().scene().removeItem(highlightGeom)
highlightGeom = None
if not wasEditable:
layer.rollBack()
else:
result = 0
return result
def showSearchForm(self, layer, root = None):
'''api method showSearchForm: show the data-driven search mask for a layer
root is a search-XML Element to be applied upon startup, if not given lastSearch is applied
returns 1 if user clicked OK, 0 if CANCEL'''
layerValues = self.__getLayerValues(layer, inputMask = False, searchMask = True)
if layerValues != None:
#QtGui.QMessageBox.information(None, "", str(layerValues[2]))
db = layerValues[1]
if not db.isValid():
db = self.__createDb(layer)
if db != None:
self.setDb(layer, db)
else:
return None
searchUi = layerValues[3]
thisSize = layerValues[5]
dlg = DdSearchDialog(searchUi, layer, db, root = root)
dlg.show()
if thisSize != None:
dlg.resize(thisSize)
result = dlg.exec_()
newSize = dlg.size()
self.ddLayers[layer.id()][5] = newSize
return result
def showDdForm(self, fid):
aLayer = self.iface.activeLayer()
if aLayer != None:
feat = aLayer.getFeature(fid)
if feat != None:
self.showFeatureForm(aLayer, feat)
def setUi(self, layer, ui, searchUi = None, showParents = None, thisSize = None):
'''api method to exchange the default ui with a custom ui'''
layerValues = self.__getLayerValues(layer)
if layerValues != None:
#QtGui.QMessageBox.information(None, "", str(layerValues[2]))
thisTable = layerValues[0]
db = layerValues[1]
if searchUi == None:
searchUi = layerValues[3]
if showParents == None:
showParents = layerValues[4]
self.ddLayers[layer.id()] = [thisTable, db, ui, searchUi, showParents, thisSize, None]
def addFormWidget(self, layer, label, toolTip = None, toUi = True, toSearchUi = True):
layerValues = self.__getLayerValues(layer)
thisTable = layerValues[0]
aTable = DdTable(thisTable.oid, thisTable.schemaName,
thisTable.tableName, toolTip, label)
ui = layerValues[2]
searchUi = layerValues[3]
if toUi:
newUiForm = DdFormWidget(aTable)
ui.addFormWidget(newUiForm)
if toSearchUi:
newSearchUiForm = DdFormWidget(aTable)
searchUi.addFormWidget(newSearchUiForm)
def addInputWidget(self, layer, inputWidget, ddFormWidgetIndex = None,
beforeWidget = None, toUi = True, toSearchUi = True):
'''api method to add a DdWidget into the ui of a layer'''
layerValues = self.__getLayerValues(layer)
ui = layerValues[2]
searchUi = layerValues[3]
if ui != None and toUi:
ui.addInputWidget(inputWidget, ddFormWidgetIndex, beforeWidget)
if searchUi != None and toSearchUi:
searchUi.addInputWidget(inputWidget, ddFormWidgetIndex, beforeWidget)
def addInputWidgetBefore(self, layer, inputWidget, beforeAttributeName,
toUi = True, toSearchUi = True):
'''api method to add a DdWidget into the ui of a layer before
the widget of attribute with beforeAttributeName. Will
be placed in the same form'''
foundWidget = self.__getInputWidget(layer, beforeAttributeName)
if foundWidget != None:
formIndex = foundWidget[1]
widgetIndex = foundWidget[2]
else:
formIndex = None
widgetIndex = None
self.addInputWidget(layer, inputWidget, formIndex, widgetIndex,
toUi, toSearchUi)
def addInputWidgetAfter(self, layer, inputWidget, afterAttributeName,
toUi = True, toSearchUi = True):
'''api method to add a DdWidget into the ui of a layer after
the widget of attribute with afterAttributeName. Will
be placed in the same form'''
foundWidget = self.__getInputWidget(layer, afterAttributeName)
if foundWidget != None:
formIndex = foundWidget[1]
widgetIndex = foundWidget[2] +1
else:
formIndex = None
widgetIndex = None
self.addInputWidget(layer, inputWidget, formIndex, widgetIndex,
toUi, toSearchUi)
def removeInputWidget(self, layer, attributeName, fromUi = True,
fromSearchUi = True):
'''api method to remove the DdWidget for a certain attribute'''
layerValues = self.__getLayerValues(layer)
ui = layerValues[2]
searchUi = layerValues[3]
foundWidget = self.__getInputWidget(layer, attributeName)
if foundWidget != None:
formIndex = foundWidget[1]
widgetIndex = foundWidget[2]
if ui != None and fromUi:
ui.forms[formIndex].inputWidgets.pop(widgetIndex)
if searchUi != None and fromSearchUi:
searchUi.forms[formIndex].inputWidgets.pop(widgetIndex)
return None
def getInputWidget(self, layer, attributeName):
'''api method returning the DdWidget for a certain attribute'''
foundWidget = self.__getInputWidget(layer, attributeName)
if foundWidget != None:
return foundWidget[0]
else:
return None
def replaceInputWidget(self, layer, attributeName, newWidget,
toUi = True, toSearchUi = True):
'''api method to replace a DdWidget in the ui of a layer
with another one'''
retValue = False
foundWidget = self.__getInputWidget(layer, attributeName)
if foundWidget != None:
formIndex = foundWidget[1]
widgetIndex = foundWidget[2]
layerValues = self.__getLayerValues(layer)
ui = layerValues[2]
searchUi = layerValues[3]
if ui != None and toUi:
ui.forms[formIndex].inputWidgets[widgetIndex] = newWidget
retValue = True
if searchUi != None and toSearchUi:
searchUi.forms[formIndex].inputWidgets[widgetIndex] = newWidget
retValue = True
return retValue
def enableInputWidget(self, layer, attributeName, doEnable):
'''api method to enable a DdWidget, i.e. set its Ddattribute
to enableWidget'''
inputWidget = self.getInputWidget(layer, attributeName)
if inputWidget == None:
return False
else:
inputWidget.attribute.enableWidget = doEnable
def getDbForLayer(self, layer):
return self.__createDb(layer)
def existsInDb(self, ddTable, db):
return self.__getOid(ddTable, db) != None
def setDb(self, layer, db):
'''api method to set the db for a layer'''
layerValues = self.__getLayerValues(layer)
if layerValues != None:
thisTable = layerValues[0]
oldDb = layerValues[1]
self.__disconnectDb(oldDb)
ui = layerValues[2]
searchUi = layerValues[3]
showParents = layerValues[4]
thisSize = layerValues[5]
self.ddLayers[layer.id()] = [thisTable, db, ui, searchUi, showParents, thisSize, None]
def findPostgresLayer(self, db, ddTable):
procLayer = None # ini
for aTreeLayer in QgsProject.instance().layerTreeRoot().findLayers():
layer = aTreeLayer.layer()
if layer != None:
if 0 == layer.type(): # vectorLayer
src = layer.source()
if ("table=\"" + ddTable.schemaName + "\".\"" + ddTable.tableName + "\"" in src) and \
(db.databaseName() in src) and \
(db.hostName() in src):
procLayer = layer
break
return procLayer
def isEditable(self, layer):
'''check if data provider allows editing of table'''
dp = layer.dataProvider()
caps = dp.capabilities()
return (caps & QgsVectorDataProvider.AddFeatures and caps & QgsVectorDataProvider.DeleteFeatures and \
caps & QgsVectorDataProvider.ChangeAttributeValues)
def isAccessible(self, db, ddTable, showError = True):
'''check if user has right to access this table'''
query = QtSql.QSqlQuery(db)
sQuery = "SELECT * FROM \"" + ddTable.schemaName + "\".\"" + ddTable.tableName + "\" LIMIT 1;"
query.prepare(sQuery)
query.exec_()
if query.isActive():
query.finish()
return True
else:
query.finish()
if showError:
self.showQueryError(query, True)
return False
def shuffleGroup(self, groupName, toTop = True):
'''move position of group in layer panel to top or bottom'''
group = self.getGroup(groupName)
if group != None:
root = QgsProject.instance().layerTreeRoot()
if toTop:
group2 = root.insertGroup(0, groupName)
else:
group2 = root.addGroup(groupName)
root.removeChildNode(group)
return group2
else:
return None
def createGroup(self, groupName, atTop = True):
'''create group in layer panel'''
group = self.getGroup(groupName)
if group == None:
root = QgsProject.instance().layerTreeRoot()
if atTop:
return root.insertGroup(0, groupName)
else:
return root.addGroup(groupName)
else:
return self.shuffleGroup(groupName, atTop)
def getGroup(self, groupName):
'''Find group groupName in layer panel'''
return QgsProject.instance().layerTreeRoot().findGroup(groupName)
def moveLayerToGroup(self, layer, groupName):
'''move layer to group in layer panel'''
group = self.getGroup(groupName)
if group == None:
atTop = groupName != "DataDrivenInputMask"
group = self.createGroup(groupName, atTop)
else:
if group.findLayer(layer.id()) != None:
return True
if group != None:
root = QgsProject.instance().layerTreeRoot()
layerTreeLayer = root.findLayer(layer.id())
if layerTreeLayer != None:
wasVisible = layerTreeLayer.itemVisibilityChecked()
newLayerTreeLayer = group.addLayer(layer)
newLayerTreeLayer.setItemVisibilityChecked(wasVisible)
if root.removeLayer(layer) == None: # if layer in Root
try:
layerTreeLayer.parent().removeLayer(layer)
# if layer in root, crashed QGIS when calling parent() :-(
except:
pass
return True
else:
return False
else:
return False
def moveLayerintoDdGroup(self, layer):
self.moveLayerToGroup(layer, "DataDrivenInputMask")
def loadPostGISLayer(self, db, ddTable, displayName = None,
geomColumn = None, whereClause = None, keyColumn = None,
intoDdGroup = True):
if not self.isAccessible(db, ddTable):
DdError(QtWidgets.QApplication.translate("DdError", "Cannot not load table: ")+
ddTable.schemaName + "." + ddTable.tableName, fatal = True, iface = self.iface)
if not displayName:
displayName = ddTable.schemaName + "." + ddTable.tableName
uri = QgsDataSourceUri()
thisPort = db.port()
#these numbers are best guesses from the enumeration
if hasattr(db, "sslmode"):
if db.sslMode == "prefer":
sslMode = QgsDataSourceUri.SslPprefer
elif db.sslMode == "disable":
sslMode = QgsDataSourceUri.SslDisable
elif db.sslMode == "allow":
sslMode = QgsDataSourceUri.SslAllow
elif db.sslMode == "require":
sslMode = QgsDataSourceUri.SslRequire
elif db.sslMode == "verifyCA":
sslMode = QgsDataSourceUri.SslVerifyCA
elif db.sslMode == "verifyFull":
sslMode = QgsDataSourceUri.SslVerifyFull
else:
sslMode = QgsDataSourceUri.SslPrefer # default anyway
else:
sslMode = QgsDataSourceUri.SslPrefer
if thisPort == -1:
thisPort = 5432
# set host name, port, database name, username and password
authcfg = None #ini'
if hasattr(db, "authcfg"):
authcfg = db.authcfg
if authcfg != None:
uri.setConnection(db.hostName(), str(thisPort), db.databaseName(),
None, None, sslmode = sslMode, authConfigId = authcfg)
if authcfg == None:
uri.setConnection(db.hostName(), str(thisPort), db.databaseName(),
db.userName(), db.password(), sslmode = sslMode)
# set database schema, table name, geometry column and optionaly subset (WHERE clause)
uri.setDataSource(ddTable.schemaName, ddTable.tableName, geomColumn)
if whereClause:
uri.setSql(whereClause)
if keyColumn:
uri.setKeyColumn(keyColumn)
if authcfg != None:
layerUri = uri.uri(False)
else:
layerUri = uri.uri()
vlayer = QgsVectorLayer(layerUri, displayName, "postgres", QgsVectorLayer.LayerOptions(False,False))
# double check if layer is valid
if not vlayer.dataProvider().isValid():
DdError(QtWidgets.QApplication.translate("DdError", "Cannot not load table: ") +
ddTable.schemaName + "." + ddTable.tableName, fatal = True, iface = self.iface)
QgsProject.instance().addMapLayer(vlayer)
if intoDdGroup:
self.moveLayerintoDdGroup(vlayer)
return vlayer
def quit(self):
for ddLayer in list(self.ddLayers.values()):
db = ddLayer[1]
self.__disconnectDb(db)
#Slots
def editingStarted(self):
layer = self.iface.activeLayer()
if layer:
layerValues = self.__getLayerValues(layer)
if layerValues != None:
db = layerValues[1]
if not db:
db = self.__ceateDb(layer)
self.setDb(layer, db)
def editingStopped(self):
pass
# better keep the connection, if too many connections exist we must change this
#self.__disconnectDb(db)
#self.setDb(layer, None)
def __getLayerValues(self, layer, inputMask = True, searchMask = True):
'''Get this layer's values from ddLayers or create them'''
try:
layerValues = self.ddLayers[layer.id()]
except KeyError:
if self.initLayer(layer, skip = [], labels = {}, fieldOrder = [], fieldGroups = {}, minMax = {}, noSearchFields = [], \
showParents = True, createAction = True, db = None, inputMask = True, searchMask = True, \
inputUi = None, searchUi = None, helpText = ""):
layerValues = self.ddLayers[layer.id()]
else:
layerValues = None
if layerValues != None:
# check if needed masks are initialized
inputMask = (inputMask and layerValues[2] == None)
searchMask = (searchMask and layerValues[3] == None)
if inputMask or searchMask:
if self.initLayer(layer, skip = [], inputMask = inputMask, searchMask = searchMask):
layerValues = self.ddLayers[layer.id()]
else:
layerValues = None
return layerValues
def __getComment(self, thisTable, db):
''' query the DB to get a table's comment'''
query = QtSql.QSqlQuery(db)
sQuery = "SELECT description FROM pg_description \
WHERE objoid = :oid AND objsubid = 0"
# objsubid = 0 is the table, objsubid > 0 are comments on fields
query.prepare(sQuery)
query.bindValue(":oid", thisTable.oid)
query.exec_()
comment = None
if query.isActive():
if query.size() == 0:
query.finish()
else:
while query.next():
comment = query.value(0)
break
query.finish()
else:
DbError(query)
return comment
def __getOid(self, thisTable, db):
return ddtools.getOid(thisTable, db)
def __isTable(self, thisTable, db):
'''checks if the given relation is a table'''
query = QtSql.QSqlQuery(db)
sQuery = "SELECT * FROM pg_tables WHERE schemaname = :schema AND tablename = :table"
query.prepare(sQuery)
query.bindValue(":schema", thisTable.schemaName)
query.bindValue(":table", thisTable.tableName)
query.exec_()
if query.isActive():
if query.size() == 0:
query.finish()
return False
else:
query.finish()
return True
else:
DbError(query)
return False
def __connectSignals(self, layer):
layer.editingStarted.connect(self.editingStarted)
layer.editingStopped.connect(self.editingStopped)
def __analyzeSource(self, layer):
'''Split the layer's source information and return them as a dict'''
src = layer.source()
result = dict()
# allow spaces in dbname
p = re.match('(dbname=\'(?P<name>[^\']*)\' *)+', src)
if p != None: