-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrelation_editor_feature_side_widget.py
More file actions
446 lines (352 loc) · 17.5 KB
/
relation_editor_feature_side_widget.py
File metadata and controls
446 lines (352 loc) · 17.5 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
# -*- coding: utf-8 -*-
# -----------------------------------------------------------
#
# QGIS Document Management System Plugin
# Copyright (C) 2021 Damiano Lombardi
#
# licensed under the terms of GNU GPL 2+
#
# -----------------------------------------------------------
try:
from qgis.PyQt.QtQuickWidgets import QQuickWidget
except ImportError:
# https://github.com/qgis/QGIS/pull/60123
from qgis.PyQt.QtQuickWidgets import QQuickWidget
import os
from enum import Enum
from qgis.PyQt.QtCore import QDir, QTimer, QUrl, QVariant, pyqtSignal, pyqtProperty, pyqtSlot
from qgis.PyQt.QtGui import QIcon, QGuiApplication
from qgis.PyQt.QtWidgets import QAction, QMessageBox
from qgis.PyQt.uic import loadUiType
from qgis.core import (
QgsExpression,
QgsExpressionContext,
QgsExpressionContextUtils,
QgsGeometry,
QgsLogger,
QgsProject,
QgsRelation,
QgsSettingsEntryString,
QgsVectorLayerUtils,
)
from qgis.gui import QgsAbstractRelationEditorWidget, QgsAttributeDialog
from document_management_system.core.document_model import DocumentModel
from document_management_system.core.file_type_icon_image_provider import FileTypeIconImageProvider
from document_management_system.core.preview_image_provider import PreviewImageProvider
from document_management_system.core.plugin_helper import PluginHelper
WidgetUi, _ = loadUiType(os.path.join(os.path.dirname(__file__), "../ui/relation_editor_feature_side_widget.ui"))
class RelationEditorFeatureSideWidget(QgsAbstractRelationEditorWidget, WidgetUi):
class LastView(str, Enum):
ListView = "ListView"
IconView = "IconView"
settingsLastView = QgsSettingsEntryString(
"relationEditorFeatureSideLastView",
PluginHelper.PLUGIN_SLUG,
LastView.ListView,
PluginHelper.tr("Last view used in the relation editor document side widget"),
)
signalCurrentViewChanged = pyqtSignal()
def __init__(self, config, parent):
super().__init__(config, parent)
self._updateUiTimer = QTimer()
self._updateUiTimer.setSingleShot(True)
self._updateUiTimer.timeout.connect(self.updateUiTimeout)
self.setupUi(self)
print("DocumentRelationEditorFeatureSideWidget.__init__")
self.documents_path = str()
self.document_filename = str()
self.model = DocumentModel()
self._nmRelation = QgsRelation()
self._layerInSameTransactionGroup = False
self._currentDocumentId = None
# Actions
self.actionToggleEditing = QAction(
QIcon(":/images/themes/default/mActionToggleEditing.svg"), self.tr("Toggle editing mode for child layers")
)
self.actionToggleEditing.setCheckable(True)
self.actionSaveEdits = QAction(
QIcon(":/images/themes/default/mActionSaveEdits.svg"), self.tr("Save child layer edits")
)
self.actionShowForm = QAction(QIcon(":/images/themes/default/mActionMultiEdit.svg"), self.tr("Show form"))
self.actionAddFeature = QAction(QIcon(":/images/themes/default/symbologyAdd.svg"), self.tr("Add document"))
self.actionDeleteFeature = QAction(
QIcon(":/images/themes/default/mActionDeleteSelected.svg"), self.tr("Drop document")
)
self.actionLinkFeature = QAction(QIcon(":/images/themes/default/mActionLink.svg"), self.tr("Link document"))
self.actionUnlinkFeature = QAction(
QIcon(":/images/themes/default/mActionUnlink.svg"), self.tr("Unlink document")
)
# Tool buttons
self.mToggleEditingToolButton.setDefaultAction(self.actionToggleEditing)
self.mSaveEditsToolButton.setDefaultAction(self.actionSaveEdits)
self.mShowFormToolButton.setDefaultAction(self.actionShowForm)
self.mAddFeatureToolButton.setDefaultAction(self.actionAddFeature)
self.mDeleteFeatureToolButton.setDefaultAction(self.actionDeleteFeature)
self.mLinkFeatureToolButton.setDefaultAction(self.actionLinkFeature)
self.mUnlinkFeatureToolButton.setDefaultAction(self.actionUnlinkFeature)
self.mListViewToolButton.setIcon(QIcon(":/images/themes/default/mIconListView.svg"))
self.mIconViewToolButton.setIcon(QIcon(":/images/themes/default/mActionIconView.svg"))
self.mListViewToolButton.setChecked(self.currentView == str(RelationEditorFeatureSideWidget.LastView.ListView))
self.mIconViewToolButton.setChecked(self.currentView == str(RelationEditorFeatureSideWidget.LastView.IconView))
# Quick image providers
self._previewImageProvider = PreviewImageProvider()
self._fileTypeSmallIconProvider = FileTypeIconImageProvider(32)
self._fileTypeBigIconProvider = FileTypeIconImageProvider(100)
# Setup QML part
self.view = QQuickWidget()
self.view.rootContext().setContextProperty("documentModel", self.model)
self.view.rootContext().setContextProperty("parentWidget", self)
self.view.rootContext().setContextProperty(
"CONST_LIST_VIEW", str(RelationEditorFeatureSideWidget.LastView.ListView)
)
self.view.rootContext().setContextProperty(
"CONST_ICON_VIEW", str(RelationEditorFeatureSideWidget.LastView.IconView)
)
self.view.engine().addImageProvider("previewImageProvider", self._previewImageProvider)
self.view.engine().addImageProvider("fileTypeSmallIconProvider", self._fileTypeSmallIconProvider)
self.view.engine().addImageProvider("fileTypeBigIconProvider", self._fileTypeBigIconProvider)
self.view.setSource(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__), "../qml/DocumentList.qml")))
self.view.setResizeMode(QQuickWidget.ResizeMode.SizeRootObjectToView)
self.layout().addWidget(self.view)
# Set initial state for add / remove etc.buttons
self.updateButtons()
# Signal slots
self.actionToggleEditing.triggered.connect(self.toggleEditing)
self.actionSaveEdits.triggered.connect(self.saveChildLayerEdits)
self.actionShowForm.triggered.connect(self.showDocumentForm)
self.actionAddFeature.triggered.connect(self.addDocument)
self.actionDeleteFeature.triggered.connect(self.dropDocument)
self.actionLinkFeature.triggered.connect(self.linkDocument)
self.actionUnlinkFeature.triggered.connect(self.unlinkDocument)
self.mListViewToolButton.toggled.connect(self.listViewToolButtonToggled)
self.mIconViewToolButton.toggled.connect(self.iconViewToolButtonToggled)
@pyqtProperty(str)
def currentView(self):
return self.settingsLastView.value()
def updateCurrentView(self):
if self.mListViewToolButton.isChecked():
self.settingsLastView.setValue(str(RelationEditorFeatureSideWidget.LastView.ListView))
else:
self.settingsLastView.setValue(str(RelationEditorFeatureSideWidget.LastView.IconView))
self.signalCurrentViewChanged.emit()
@pyqtProperty(QVariant)
def currentDocumentId(self):
return self._currentDocumentId
@pyqtSlot(QVariant)
def setCurrentDocumentId(self, value):
self._currentDocumentId = value
self.updateButtons()
def nmRelation(self):
return self._nmRelation
def config(self):
return {}
def setConfig(self, config):
self.documents_path = config["documents_path"]
self.document_filename = config["document_filename"]
def updateUi(self):
self._updateUiTimer.start(200)
def updateUiTimeout(self):
self.model.init(self.relation(), self.nmRelation(), self.feature(), self.documents_path, self.document_filename)
def updateButtons(self):
toggleEditingButtonEnabled = False
editable = False
linkable = False
selectionNotEmpty = self._currentDocumentId is not None
if self.relation().isValid():
toggleEditingButtonEnabled = self.relation().referencingLayer().supportsEditing()
editable = self.relation().referencingLayer().isEditable()
linkable = self.relation().referencingLayer().isEditable()
if self.nmRelation().isValid():
toggleEditingButtonEnabled |= self.nmRelation().referencedLayer().supportsEditing()
editable = self.nmRelation().referencedLayer().isEditable()
self.mToggleEditingToolButton.setEnabled(toggleEditingButtonEnabled)
self.mAddFeatureToolButton.setEnabled(editable)
self.mLinkFeatureToolButton.setEnabled(linkable)
self.mDeleteFeatureToolButton.setEnabled(editable and selectionNotEmpty)
self.mUnlinkFeatureToolButton.setEnabled(linkable and selectionNotEmpty)
self.mToggleEditingToolButton.setChecked(editable)
self.mSaveEditsToolButton.setEnabled(editable or linkable)
self.mShowFormToolButton.setEnabled(selectionNotEmpty)
self.mToggleEditingToolButton.setVisible(self._layerInSameTransactionGroup is False)
self.mSaveEditsToolButton.setVisible(self._layerInSameTransactionGroup is False)
def afterSetRelations(self):
self._nmRelation = QgsProject.instance().relationManager().relation(str(self.nmRelationId()))
if not self.relation().isValid():
QgsLogger.warning(self.tr(f"Invalid relation set, relation id: '{self.relation().id()}'"))
self.updateButtons()
return
self._checkTransactionGroup()
self.relation().referencingLayer().editingStopped.connect(self.updateButtons)
self.relation().referencingLayer().editingStarted.connect(self.updateButtons)
if self.nmRelation().isValid():
self.nmRelation().referencedLayer().editingStarted.connect(self.updateButtons)
self.nmRelation().referencedLayer().editingStopped.connect(self.updateButtons)
self.updateButtons()
def _checkTransactionGroup(self):
self._layerInSameTransactionGroup = False
referenced_layer = self.relation().referencedLayer()
if not self.relation().referencedLayer():
return
connectionString = PluginHelper.connectionString(referenced_layer.source())
transactionGroup = QgsProject.instance().transactionGroup(referenced_layer.providerType(), connectionString)
if transactionGroup is None:
return
if self.nmRelation().isValid():
if (
self.relation().referencedLayer() in transactionGroup.layers()
and self.relation().referencingLayer() in transactionGroup.layers()
and self.nmRelation().referencedLayer() in transactionGroup.layers()
):
self._layerInSameTransactionGroup = True
else:
if (
self.relation().referencedLayer() in transactionGroup.layers()
and self.relation().referencingLayer() in transactionGroup.layers()
):
self._layerInSameTransactionGroup = True
def parentFormValueChanged(self, attribute, newValue):
pass
def checkLayerEditingMode(self):
if self.relation().referencingLayer().isEditable() is False:
QMessageBox.critical(
self,
self.tr("Layer not editable"),
self.tr("Layer '{0}' is not in editing mode.").format(self.relation().referencingLayer().name()),
)
return False
if self.nmRelation().isValid():
if self.nmRelation().referencedLayer().isEditable() is False:
QMessageBox.critical(
self,
self.tr("Layer not editable"),
self.tr("Layer '{0}' is not in editing mode.").format(self.nmRelation().referencedLayer().name()),
)
return False
return True
@pyqtSlot(bool)
def toggleEditing(self, state):
super().toggleEditing(state)
self.updateButtons()
@pyqtSlot()
def saveChildLayerEdits(self):
super().saveEdits()
@pyqtSlot()
def addDocument(self):
# Workaround because of QGIS not resetting this property after linking features
self.editorContext().vectorLayerTools().setForceSuppressFormPopup(False)
self.addFeature()
@pyqtSlot()
def dropDocument(self):
if self._currentDocumentId is None:
return
self.deleteFeature(self._currentDocumentId)
@pyqtSlot(str)
def addDroppedDocument(self, fileUrl):
if self.checkLayerEditingMode() is False:
return
# Workaround because of QGIS not resetting this property after linking features
self.editorContext().vectorLayerTools().setForceSuppressFormPopup(False)
layer = self.relation().referencingLayer()
if self.nmRelation().isValid():
layer = self.nmRelation().referencedLayer()
default_documents_path = str()
if self.documents_path:
exp = QgsExpression(self.documents_path)
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))
default_documents_path = str(exp.evaluate(context))
filename = QUrl(fileUrl).toLocalFile()
if default_documents_path:
filename = QDir(default_documents_path).relativeFilePath(filename)
keyAttrs = dict()
# Fields of the linking table
fields = self.relation().referencingLayer().fields()
# For generated relations insert the referenced layer field
if self.relation().type() == QgsRelation.RelationType.Generated:
polyRel = self.relation().polymorphicRelation()
keyAttrs[fields.indexFromName(polyRel.referencedLayerField())] = polyRel.layerRepresentation(
self.relation().referencedLayer()
)
if self.nmRelation().isValid():
# only normal relations support m:n relation
if self.nmRelation().type() != QgsRelation.RelationType.Normal:
QMessageBox.critical(
self,
self.tr("Add document"),
self.tr("Invalid relation, Only normal relations support m:n relation."),
)
return
# Pre fill inserting document filepath
attributes = {self.nmRelation().referencedLayer().fields().indexFromName(self.document_filename): filename}
# n:m Relation: first let the user create a new feature on the other table
# and autocreate a new linking feature.
ok, feature = (
self.editorContext()
.vectorLayerTools()
.addFeature(self.nmRelation().referencedLayer(), attributes, QgsGeometry())
)
if not ok:
QMessageBox.critical(self, self.tr("Add document"), self.tr("Could not add a new linking feature."))
return
for key in self.relation().fieldPairs():
keyAttrs[fields.indexOf(key)] = self.feature().attribute(self.relation().fieldPairs()[key])
for key in self.nmRelation().fieldPairs():
keyAttrs[fields.indexOf(key)] = feature.attribute(self.nmRelation().fieldPairs()[key])
linkFeature = QgsVectorLayerUtils.createFeature(
self.relation().referencingLayer(),
QgsGeometry(),
keyAttrs,
self.relation().referencingLayer().createExpressionContext(),
)
if not self.relation().referencingLayer().addFeature(linkFeature):
QMessageBox.critical(self, self.tr("Add document"), self.tr("Could not add a new feature."))
return
else:
for key in self.relation().fieldPairs():
keyAttrs[fields.indexFromName(key)] = self.feature().attribute(self.relation().fieldPairs()[key])
# Pre fill inserting document filepath
keyAttrs[fields] = filename
ok, feature = (
self.editorContext()
.vectorLayerTools()
.addFeature(self.relation().referencingLayer(), keyAttrs, QgsGeometry())
)
if not ok:
QMessageBox.critical(self, self.tr("Add document"), self.tr("Could not add a new feature."))
return
self.updateUi()
@pyqtSlot()
def linkDocument(self):
self.linkFeature()
@pyqtSlot()
def unlinkDocument(self):
if self._currentDocumentId is None:
return
self.unlinkFeature(self._currentDocumentId)
@pyqtSlot()
def showDocumentForm(self):
if self._currentDocumentId is None:
return
layer = self.relation().referencingLayer()
if self.nmRelation().isValid():
layer = self.nmRelation().referencedLayer()
showDocumentFormDialog = QgsAttributeDialog(layer, layer.getFeature(self._currentDocumentId), False, self.parent(), True)
showDocumentFormDialog.exec()
self.updateUi()
@pyqtSlot(str)
def copyDocumentPath(self, documentPath):
if self._currentDocumentId is None:
return
QGuiApplication.clipboard().setText(documentPath)
@pyqtSlot(bool)
def listViewToolButtonToggled(self, checked):
self.mIconViewToolButton.blockSignals(True)
self.mIconViewToolButton.setChecked(checked is False)
self.mIconViewToolButton.blockSignals(False)
self.updateCurrentView()
@pyqtSlot(bool)
def iconViewToolButtonToggled(self, checked):
self.mListViewToolButton.blockSignals(True)
self.mListViewToolButton.setChecked(checked is False)
self.mListViewToolButton.blockSignals(False)
self.updateCurrentView()