forked from archesproject/arches-qgis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharches_project.py
1061 lines (830 loc) · 50.6 KB
/
arches_project.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 -*-
"""
/***************************************************************************
ArchesProject
A QGIS plugin
This plugin links QGIS to an Arches project.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2023-09-15
git sha : $Format:%H$
copyright : (C) 2023 by Knowledge Integration
email : [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 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt5.QtCore import Qt
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, QDir
from qgis.PyQt.QtGui import QIcon, QFontDatabase, QPixmap, QCursor, QTransform
from qgis.PyQt.QtWidgets import QAction, QTableView, QTableWidgetItem, QApplication
from qgis.core import QgsProject, QgsVectorLayer, QgsVectorLayerCache, QgsWkbTypes
from qgis.gui import (QgsAttributeTableView,
QgsAttributeTableModel,
QgsAttributeTableFilterModel,
QgsMapLayerComboBox
)
# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the dialog
from .arches_project_dialog import ArchesProjectDialog
# Import the confirmation dialogs
from .dialog.create_resource_confirmation_dialog import CreateResourceConfirmation
from .dialog.edit_resource_add_confirmation_dialog import EditResourceAddConfirmation
from .dialog.edit_resource_replace_confirmation_dialog import EditResourceReplaceConfirmation
import os.path
import sys
#from shapely import GeometryCollection
import requests
from datetime import datetime
class ArchesProject:
"""QGIS Plugin Implementation."""
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'ArchesProject_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&Arches Project')
# Check if plugin was started the first time in current QGIS session
# Must be set in initGui() to survive plugin reloads
self.first_start = None
# Comfirmation additional dialogs
## ARCHES PLUGIN SPECIFIC VARIABLES
# Cache connection details to prevent firing duplicate connections
self.arches_connection_cache = {}
# Store token data to avoid regenerating every connection
self.arches_token = {}
self.arches_graphs_list = []
self.arches_user_info = {}
# Store selected arches resource
self.layers = []
self.arches_selected_resource = {"resourceinstanceid": "",
"nodeid": "",
"tileid": ""
}
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('ArchesProject', message)
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
# Adds plugin icon to Plugins toolbar
self.iface.addToolBarIcon(action)
if add_to_menu:
self.iface.addPluginToMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = ':/plugins/arches_project/icons/arches.png'
self.add_action(
icon_path,
text=self.tr(u'Arches Project'),
callback=self.run,
parent=self.iface.mainWindow())
# will be set False in run()
self.first_start = True
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
for action in self.actions:
self.iface.removePluginMenu(
self.tr(u'&Arches Project'),
action)
self.iface.removeToolBarIcon(action)
def run(self):
"""Run method that performs all the real work"""
# Create the dialog with elements (after translation) and keep reference
# Only create GUI ONCE in callback, so that it will only load when the plugin is started
if self.first_start == True:
self.first_start = False
self.dlg = ArchesProjectDialog()
self.dlg_resource_creation = CreateResourceConfirmation()
self.dlg_edit_resource_add = EditResourceAddConfirmation()
self.dlg_edit_resource_replace = EditResourceReplaceConfirmation()
# Setup Arches Stylesheet
self.stylesheet_change(on_start=True)
# if stylesheet is disabled
self.dlg.useStylesheetCheckbox.stateChanged.connect(lambda: self.stylesheet_change(on_start=False))
## Have everything called in here so multiple connections aren't made when plugin button pressed
# This way only one connection is made at a time
# Set tab index to 0 always
self.dlg.tabWidget.setCurrentIndex(0)
self.dlg.tabWidget.setTabVisible(1, False)
self.dlg.tabWidget.setTabVisible(5, False)
self.dlg.enableLoggingCheckbox.stateChanged.connect(self.enable_logging)
# initiate the current selected layer
self.map_selection()
# Connection to Arches instance
self.dlg.btnSave.clicked.connect(self.arches_connection_save)
self.dlg.btnReset.clicked.connect(lambda: self.arches_connection_reset(hard_reset=True))
# Get the map selection and update when changed
self.iface.mapCanvas().selectionChanged.connect(self.map_selection)
## Set "Create resource" to false to begin with and only update once Arches connection made
self.dlg.createResModelSelect.setEnabled(False)
self.dlg.createResFeatureSelect.setEnabled(False)
self.dlg.addNewRes.setEnabled(False)
# to run when layer is changed in create resource and edit resource tabs
self.dlg.hidePostgresLayers.setChecked(True)
self.dlg.createResFeatureSelect.highlighted.connect(lambda: self.update_map_layers(checkbox=self.dlg.hidePostgresLayers))
self.dlg.editResSelectFeatures.highlighted.connect(lambda: self.update_map_layers(checkbox=self.dlg.hidePostgresLayers))
self.dlg.hidePostgresLayers.stateChanged.connect(lambda: self.show_hide_psql_layers(combobox1=self.dlg.createResFeatureSelect,
combobox2=self.dlg.editResSelectFeatures))
# to run when graph is changed in create resource
# self.dlg.createResModelSelect.currentIndexChanged.connect(self.update_graph_options)
# click add button - should bring up new dialog for confirmation
self.dlg.addNewRes.clicked.connect(self.create_resource)
## Set "Edit Resource" to false to begin with
self.dlg.selectedResUUID.setText("Connect to your Arches instance to edit resources.")
self.dlg.addEditRes.setEnabled(False)
self.dlg.replaceEditRes.setEnabled(False)
self.dlg.editResSelectFeatures.setEnabled(False)
#self.dlg.selectedResAttributeTable.setRowCount(0)
self.dlg.selectedResAttributeTable.setEnabled(False)
self.dlg.addEditRes.clicked.connect(lambda: self.edit_resource(replace=False))
self.dlg.replaceEditRes.clicked.connect(lambda: self.edit_resource(replace=True))
# Hide multiple geometry node selection by default
self.dlg.geometryNodeSelectFrame.hide()
# Check if selected graph has multiple geometry nodes
self.dlg.createResModelSelect.currentIndexChanged.connect(self.multiple_geometry_node_check)
# show the dialog
self.dlg.show()
# Run the dialog event loop
result = self.dlg.exec_()
# See if OK was pressed
if result:
# Do something useful here - delete the line containing pass and
# substitute with your code.
pass
def map_selection(self):
"""Get the Arches Resource from the map"""
active_layer = self.iface.activeLayer()
canvas = self.iface.mapCanvas()
# If plugin is opened before QGIS project opened/setup selectedFeatures is None
try:
features = active_layer.selectedFeatures()
except AttributeError:
features = None
print("\nmap selection has been fired because selection changed")
print("layer:",active_layer, "features:",features)
if features:
if len(features) > 1:
print("Select one feature")
self.dlg.selectedResAttributeTable.setRowCount(0)
if self.arches_token:
self.dlg.selectedResUUID.setText("Multiple features selected, select one feature to proceed.")
else:
self.dlg.selectedResUUID.setText("Connect to your Arches instance to edit resources.")
return
elif len(features) == 0:
print("No feature selected")
self.dlg.selectedResAttributeTable.setRowCount(0)
if self.arches_token:
self.dlg.selectedResUUID.setText("Select a feature to proceed.")
self.dlg.addEditRes.setEnabled(False)
self.dlg.replaceEditRes.setEnabled(False)
else:
self.dlg.selectedResUUID.setText("Connect to your Arches instance to edit resources.")
return
else:
print("FEATURE SELECTED")
for f in features:
if "resourceinstanceid" in f.attributeMap():
# Initialise attribute table in the plugin window if the geom is recognised as an Arches res
# if initialised when arches_token exists then would have to click off and back on to recognise
no_rows = len(f.attributes())
no_cols = 2
self.dlg.selectedResAttributeTable.setRowCount(no_rows)
self.dlg.selectedResAttributeTable.setColumnCount(no_cols)
# Fill table with attributes
for i, (k, v) in enumerate(f.attributeMap().items()):
feat = QTableWidgetItem(str(k))
val = QTableWidgetItem(str(v))
self.dlg.selectedResAttributeTable.setItem(i, 0, feat)
self.dlg.selectedResAttributeTable.setItem(i, 1, val)
self.dlg.selectedResAttributeTable.setRowHeight(i, 5)
# Store current resource info
if k == "resourceinstanceid":
self.arches_selected_resource["resourceinstanceid"] = v
elif k == "nodeid":
self.arches_selected_resource["nodeid"] = v
elif k == "tileid":
self.arches_selected_resource["tileid"] = v
self.dlg.selectedResAttributeTable.setHorizontalHeaderLabels([u'Feature',u'Values'])
self.dlg.selectedResAttributeTable.resizeColumnsToContents()
# if the token exists then enable the UI elements
if self.arches_token:
resource_string = "Resource: %s" % (f['resourceinstanceid'])
self.dlg.selectedResUUID.setText(resource_string)
self.dlg.addEditRes.setEnabled(True)
self.dlg.replaceEditRes.setEnabled(True)
# Save resource instance details once selected
else:
self.dlg.selectedResUUID.setText("Connect to your Arches instance to edit resources.")
self.dlg.addEditRes.setEnabled(False)
self.dlg.replaceEditRes.setEnabled(False)
else:
if self.arches_token:
self.dlg.selectedResUUID.setText("The feature selected is not an Arches resource.")
else:
self.dlg.selectedResUUID.setText("Connect to your Arches instance to edit resources.")
def update_map_layers(self, checkbox):
"""Function to update new vector layers dynamically """
if checkbox.isChecked():
all_current_layers = [l for l in QgsProject.instance().mapLayers().values() if l.type() == QgsVectorLayer.VectorLayer if str(l.dataProvider().name()) != "postgres"]
elif not checkbox.isChecked():
all_current_layers = [l for l in QgsProject.instance().mapLayers().values() if l.type() == QgsVectorLayer.VectorLayer]
if self.layers != all_current_layers:
self.layers = all_current_layers
def show_hide_psql_layers(self, combobox1, combobox2):
"""Reflect change made by checkbox to show or hide PSQL layers from self.layers"""
# TODO: Not sure I like the way this works but it works
def change_both_comboboxes(c):
c.blockSignals(True)
c.clear()
c.addItems([layer.name() for layer in self.layers])
c.blockSignals(False)
if self.dlg.hidePostgresLayers.isChecked():
self.layers = [l for l in QgsProject.instance().mapLayers().values() if l.type() == QgsVectorLayer.VectorLayer if str(l.dataProvider().name()) != "postgres"]
change_both_comboboxes(combobox1)
change_both_comboboxes(combobox2)
elif not self.dlg.hidePostgresLayers.isChecked():
self.layers = [l for l in QgsProject.instance().mapLayers().values() if l.type() == QgsVectorLayer.VectorLayer]
change_both_comboboxes(combobox1)
change_both_comboboxes(combobox2)
def stylesheet_change(self, on_start):
def on_by_default():
try:
self.dlg.useStylesheetCheckbox.setChecked(True)
stylesheet_path = os.path.join(self.plugin_dir, "stylesheets", "arches_styling.qss")
with open(stylesheet_path, "r") as f:
arches_styling = f.read()
# self.dlg.setAutoFillBackground(False)
# self.dlg.setContentsMargins(0,0,0,0)
# # self.dlg.setStyleSheet("QDialog{background-color: green;}")
self.dlg.setStyleSheet(arches_styling)
self.dlg_resource_creation.setStyleSheet(arches_styling)
self.dlg_edit_resource_add.setStyleSheet(arches_styling)
self.dlg_edit_resource_replace.setStyleSheet(arches_styling)
QDir.addSearchPath('images', os.path.join(self.plugin_dir, "icons"))
self.dlg.btnSave.setIcon(QIcon(os.path.join(self.plugin_dir, "icons", "ion-log-in.svg")))
self.dlg.btnSave.setIconSize(QtCore.QSize(12,12))
self.dlg.btnSave.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.dlg.btnReset.setIcon(QIcon(os.path.join(self.plugin_dir, "icons", "ion-arrow-undo.svg")))
self.dlg.btnReset.setIconSize(QtCore.QSize(12,12))
self.dlg.btnReset.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.dlg.addNewRes.setIcon(QIcon(os.path.join(self.plugin_dir, "icons", "mdi-pencil.svg")))
self.dlg.addNewRes.setIconSize(QtCore.QSize(12,12))
self.dlg.addNewRes.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.dlg.addEditRes.setIcon(QIcon(os.path.join(self.plugin_dir, "icons", "fa-plus.svg")))
self.dlg.addEditRes.setIconSize(QtCore.QSize(12,12))
self.dlg.addEditRes.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.dlg.replaceEditRes.setIcon(QIcon(os.path.join(self.plugin_dir, "icons", "mi-replace.svg")))
self.dlg.replaceEditRes.setIconSize(QtCore.QSize(12,12))
self.dlg.replaceEditRes.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.dlg_resource_creation.createDialogCancel.setIcon(QIcon(os.path.join(self.plugin_dir, "icons", "fa-times.svg")))
self.dlg_resource_creation.createDialogCancel.setIconSize(QtCore.QSize(12,12))
self.dlg_resource_creation.createDialogCancel.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.dlg_resource_creation.createDialogCreate.setIcon(QIcon(os.path.join(self.plugin_dir, "icons", "fa-plus.svg")))
self.dlg_resource_creation.createDialogCreate.setIconSize(QtCore.QSize(12,12))
self.dlg_resource_creation.createDialogCreate.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.dlg_edit_resource_add.editDialogCancel.setIcon(QIcon(os.path.join(self.plugin_dir, "icons", "fa-times.svg")))
self.dlg_edit_resource_add.editDialogCancel.setIconSize(QtCore.QSize(12,12))
self.dlg_edit_resource_add.editDialogCancel.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.dlg_edit_resource_add.editDialogCreate.setIcon(QIcon(os.path.join(self.plugin_dir, "icons", "fa-plus.svg")))
self.dlg_edit_resource_add.editDialogCreate.setIconSize(QtCore.QSize(12,12))
self.dlg_edit_resource_add.editDialogCreate.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.dlg_edit_resource_replace.editDialogCancel.setIcon(QIcon(os.path.join(self.plugin_dir, "icons", "fa-times.svg")))
self.dlg_edit_resource_replace.editDialogCancel.setIconSize(QtCore.QSize(12,12))
self.dlg_edit_resource_replace.editDialogCancel.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.dlg_edit_resource_replace.editDialogCreate.setIcon(QIcon(os.path.join(self.plugin_dir, "icons", "fa-times.svg")))
self.dlg_edit_resource_replace.editDialogCreate.setIconSize(QtCore.QSize(12,12))
self.dlg_edit_resource_replace.editDialogCreate.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
self.dlg.tabWidget.setDocumentMode(True)
self.dlg.tabWidget.setTabIcon(0, QIcon(QPixmap(os.path.join(self.plugin_dir, "icons", "mdi-connection.svg")).transformed(QTransform().rotate(90))))
self.dlg.tabWidget.setIconSize(QtCore.QSize(16,16))
self.dlg.tabWidget.setTabText(0, "")
self.dlg.tabWidget.setTabIcon(1, QIcon(QPixmap(os.path.join(self.plugin_dir, "icons", "ti-home.svg")).transformed(QTransform().rotate(90))))
self.dlg.tabWidget.setIconSize(QtCore.QSize(16,16))
self.dlg.tabWidget.setTabText(1, "")
self.dlg.tabWidget.setTabIcon(2, QIcon(QPixmap(os.path.join(self.plugin_dir, "icons", "fa-building.svg")).transformed(QTransform().rotate(90))))
self.dlg.tabWidget.setIconSize(QtCore.QSize(16,16))
self.dlg.tabWidget.setTabText(2, "")
self.dlg.tabWidget.setTabIcon(3, QIcon(QPixmap(os.path.join(self.plugin_dir, "icons", "mdi-pencil.svg")).transformed(QTransform().rotate(90))))
self.dlg.tabWidget.setIconSize(QtCore.QSize(16,16))
self.dlg.tabWidget.setTabText(3, "")
self.dlg.tabWidget.setTabIcon(4, QIcon(QPixmap(os.path.join(self.plugin_dir, "icons", "fa-cog.svg")).transformed(QTransform().rotate(90))))
self.dlg.tabWidget.setIconSize(QtCore.QSize(16,16))
self.dlg.tabWidget.setTabText(4, "")
self.dlg.tabWidget.setTabIcon(5, QIcon(QPixmap(os.path.join(self.plugin_dir, "icons", "ti-ticket.svg")).transformed(QTransform().rotate(90))))
self.dlg.tabWidget.setIconSize(QtCore.QSize(16,16))
self.dlg.tabWidget.setTabText(5, "")
except:
# Prevent the use of the Arches stylesheet if error occurs
default_stylesheet()
self.dlg.useStylesheetCheckbox.setEnabled(False)
self.dlg.useStylesheetCheckbox.setChecked(False)
def default_stylesheet():
# reset stylesheets
self.dlg.setStyleSheet("")
self.dlg_resource_creation.setStyleSheet("")
self.dlg_edit_resource_add.setStyleSheet("")
self.dlg_edit_resource_replace.setStyleSheet("")
# remove icons from buttons
self.dlg.btnSave.setIcon(QIcon(""))
self.dlg.btnReset.setIcon(QIcon(""))
self.dlg.addNewRes.setIcon(QIcon(""))
self.dlg.addEditRes.setIcon(QIcon(""))
self.dlg.replaceEditRes.setIcon(QIcon(""))
self.dlg_resource_creation.createDialogCancel.setIcon(QIcon(""))
self.dlg_resource_creation.createDialogCreate.setIcon(QIcon(""))
self.dlg_edit_resource_add.editDialogCancel.setIcon(QIcon(""))
self.dlg_edit_resource_add.editDialogCreate.setIcon(QIcon(""))
self.dlg_edit_resource_replace.editDialogCancel.setIcon(QIcon(""))
self.dlg_edit_resource_replace.editDialogCreate.setIcon(QIcon(""))
# nav bar
# TODO: don't like the fact I have to add the exact strings (from qtcreator) back to the tab titles, seems like could be a better method...
self.dlg.tabWidget.setStyleSheet(" QTabWidget {qproperty-tabPosition: North;} ")
self.dlg.tabWidget.setStyleSheet("")
self.dlg.tabWidget.setAutoFillBackground(False)
self.dlg.tabWidget.setTabIcon(0, QIcon(""))
self.dlg.tabWidget.setTabText(0, "Arches Connection")
self.dlg.tabWidget.setTabIcon(1, QIcon(""))
self.dlg.tabWidget.setTabText(1, "Arches Connection")
self.dlg.tabWidget.setTabIcon(2, QIcon(""))
self.dlg.tabWidget.setTabText(2, "Create Resource")
self.dlg.tabWidget.setTabIcon(3, QIcon(""))
self.dlg.tabWidget.setTabText(3, "Edit Resource")
self.dlg.tabWidget.setTabIcon(4, QIcon(""))
self.dlg.tabWidget.setTabText(4, "Settings")
self.dlg.tabWidget.setTabIcon(5, QIcon(""))
self.dlg.tabWidget.setTabText(5, "Log")
if not self.dlg.useStylesheetCheckbox.isChecked():
default_stylesheet()
elif self.dlg.useStylesheetCheckbox.isChecked():
on_by_default()
if on_start == True:
on_by_default()
def enable_logging(self):
if self.dlg.enableLoggingCheckbox.isChecked():
self.dlg.tabWidget.setTabVisible(5, True)
elif not self.dlg.enableLoggingCheckbox.isChecked():
self.dlg.tabWidget.setTabVisible(5, False)
def geometry_conversion(self, selectedLayer):
"""Convert QGIS geometries into Arches"""
# TODO: QGIS stores all polygons named as multipolygons even though they're separate and
# all multipoints as individual multipoints - these should be separated
geom_and_count = {} # to store geom type and how many
# Find what type and how many we are dealing with
# for feature in selectedLayer.getFeatures():
# geomtype = str(feature.geometry().type()).split(".")
# if geomtype[-1] not in geom_and_count:
# geom_and_count[geomtype[-1]] = 1
# else:
# geom_and_count[geomtype[-1]] += 1
# print(feature.geometry().asPolygon())
# if "Polygon" in geom_and_count.keys():
# if geom_and_count["Polygon"] == 1:
# all_features = [feature.geometry().asWkt() for feature in selectedLayer.getFeatures()]
# combined_feature = (','.join(all_features))
# combined_feature = combined_feature.replace("MultiPolygon","Polygon")
# return combined_feature
# Return info for the confirmation dialog text box
geometry_type_dict = {}
print(selectedLayer.getFeatures())
for feature in selectedLayer.getFeatures():
geom = feature.geometry()
print(geom)
geomtype = str(geom.type()).split(".")
if geomtype[-1] not in geometry_type_dict:
geometry_type_dict[geomtype[-1]] = 1
else:
geometry_type_dict[geomtype[-1]] += 1
# Would use shapely to create GEOMETRYCOLLECTION but that'd require users to install the dependency themselves
# this is the alternative
all_features = [feature.geometry().asWkt() for feature in selectedLayer.getFeatures()]
geomcoll = "GEOMETRYCOLLECTION (%s)" % (','.join(all_features))
return geomcoll, geometry_type_dict
def multiple_geometry_node_check(self):
selectedGraphIndex = self.dlg.createResModelSelect.currentIndex()
selectedGraph = self.arches_graphs_list[selectedGraphIndex]
self.geometry_nodes = []
self.dlg.geometryNodeSelect.setEnabled(False)
self.dlg.geometryNodeSelectFrame.hide()
if selectedGraph:
if selectedGraph["multiple_geometry_nodes"] == True:
for k,v in selectedGraph["geometry_node_data"].items():
self.geometry_nodes.append({"node_id": k, "nodegroup_id": v["nodegroup_id"], "name": v["name"]})
self.dlg.geometryNodeSelect.setEnabled(True)
self.dlg.geometryNodeSelect.clear()
self.dlg.geometryNodeSelect.addItems([n["name"] for n in self.geometry_nodes])
self.dlg.geometryNodeSelectFrame.show()
def create_resource(self):
"""Create Resource dialog and functionality"""
def send_new_resource_to_arches():
if selectedNode["nodegroup_id"] in self.arches_user_info["editable_nodegroups"]:
try:
results = self.save_to_arches(tileid=None,
nodeid = selectedNode["node_id"],
geometry_collection=geomcoll,
geometry_format=None,
arches_operation="create")
self.dlg.createResOutputBox.setText("""Successfully created a new resource with the selected geometry.
\nTo continue the creation of your new resource, navigate to...\n%s/resource/%s""" %
(self.arches_token["formatted_url"], results["resourceinstance_id"]))
self.dlg_resource_creation.close()
except:
self.dlg.createResOutputBox.setText("Resource creation FAILED.")
self.dlg_resource_creation.close()
else:
self.dlg.createResOutputBox.setText("This user does not have permission to create data for the geometry nodegroup in this resource model. An Arches resource has not been created.")
self.dlg_resource_creation.close()
def close_dialog():
self.dlg_resource_creation.close()
# Get info on current layer and selected graph
selectedLayerIndex = self.dlg.createResFeatureSelect.currentIndex()
selectedLayer = self.layers[selectedLayerIndex]
selectedGraphIndex = self.dlg.createResModelSelect.currentIndex()
selectedGraph = self.arches_graphs_list[selectedGraphIndex]
if selectedGraph["multiple_geometry_nodes"] == True:
selectedNodeIndex = self.dlg.geometryNodeSelect.currentIndex()
selectedNode = self.geometry_nodes[selectedNodeIndex]
elif selectedGraph["multiple_geometry_nodes"] == False:
node_id = list(selectedGraph["geometry_node_data"].keys())[0]
nodegroup_id = selectedGraph["geometry_node_data"][node_id]["nodegroup_id"]
selectedNode = {"node_id": node_id, "nodegroup_id": nodegroup_id, "name": selectedGraph["geometry_node_data"][node_id]["name"]}
geomcoll, geometry_type_dict = self.geometry_conversion(selectedLayer)
# Format text box
self.dlg_resource_creation.infoText.viewport().setAutoFillBackground(False) # Sets the text box to be invisible
self.dlg_resource_creation.infoText.setText("")
self.dlg_resource_creation.infoText.append("An Arches resource will be created with the following geometries:\n")
for k,v in geometry_type_dict.items():
self.dlg_resource_creation.infoText.append(f"{k}: {v}")
# open dialog
self.dlg_resource_creation.show()
# Push button responses
self.dlg_resource_creation.createDialogCreate.clicked.connect(send_new_resource_to_arches)
self.dlg_resource_creation.createDialogCancel.clicked.connect(close_dialog)
def edit_resource(self, replace):
"""Save geometries to existing resource - either replace or add"""
def send_edited_data_to_arches(operation_type, dialog):
if nodegroup_value in self.arches_user_info["editable_nodegroups"]:
try:
results = self.save_to_arches(tileid=self.arches_selected_resource["tileid"],
nodeid = self.arches_selected_resource["nodeid"],
geometry_collection=geomcoll,
geometry_format=None,
arches_operation=operation_type)
dialog.close()
except:
print(f"Couldn't {operation_type} geometry in resource")
dialog.close()
else:
print("This user does not have permission to update data for the geometry nodegroup in this resource model.")
dialog.close()
def close_dialog(dialog):
dialog.close()
if self.arches_selected_resource:
selectedLayerIndex = self.dlg.editResSelectFeatures.currentIndex()
selectedLayer = self.layers[selectedLayerIndex]
geomcoll, geometry_type_dict = self.geometry_conversion(selectedLayer)
# Get nodegroup from graph
for graph in self.arches_graphs_list:
for k,v in graph["geometry_node_data"].items():
if k == self.arches_selected_resource["nodeid"]:
nodegroup_value = v["nodegroup_id"]
break
# Replace geometry
if replace == True:
# Format text box
self.dlg_edit_resource_replace.infoText.viewport().setAutoFillBackground(False) # Sets the text box to be invisible
self.dlg_edit_resource_replace.infoText.setText("")
self.dlg_edit_resource_replace.infoText.append("The following geometries will be replace the existing Arches resource's geometries:\n")
for k,v in geometry_type_dict.items():
self.dlg_edit_resource_replace.infoText.append(f"{k}: {v}")
self.dlg_edit_resource_replace.editDialogCreate.disconnect()
self.dlg_edit_resource_replace.editDialogCreate.clicked.connect(lambda: send_edited_data_to_arches(operation_type="create",
dialog=self.dlg_edit_resource_replace))
self.dlg_edit_resource_replace.editDialogCancel.disconnect()
self.dlg_edit_resource_replace.editDialogCancel.clicked.connect(lambda: close_dialog(dialog=self.dlg_edit_resource_replace))
# Show confirmation dialog
self.dlg_edit_resource_replace.show()
# Add geometry to the resource
else:
# Format text box
self.dlg_edit_resource_add.infoText.viewport().setAutoFillBackground(False) # Sets the text box to be invisible
self.dlg_edit_resource_add.infoText.setText("")
self.dlg_edit_resource_add.infoText.append("The following geometries will be added to the Arches resource:\n")
for k,v in geometry_type_dict.items():
self.dlg_edit_resource_add.infoText.append(f"{k}: {v}")
self.dlg_edit_resource_add.editDialogCreate.disconnect()
self.dlg_edit_resource_add.editDialogCreate.clicked.connect(lambda: send_edited_data_to_arches(operation_type="append",
dialog=self.dlg_edit_resource_add))
self.dlg_edit_resource_add.editDialogCancel.disconnect()
self.dlg_edit_resource_add.editDialogCancel.clicked.connect(lambda: close_dialog(dialog=self.dlg_edit_resource_add))
# Show confirmation dialog
self.dlg_edit_resource_add.show()
def save_to_arches(self, tileid, nodeid, geometry_collection, geometry_format, arches_operation):
"""Save data to arches resource"""
if self.arches_token:
try:
files = {
'tileid': (None, tileid),
'nodeid': (None, nodeid),
'data': (None, geometry_collection),
'format': (None, geometry_format),
'operation': (None, arches_operation),
}
headers = {"Authorization": "Bearer %s" % (self.arches_token["access_token"])}
response = requests.post("%s/api/node_value/" % (self.arches_token["formatted_url"]), headers=headers, data=files)
if response.ok == True:
arches_created_resource = {"nodegroup_id": response.json()["nodegroup_id"],
"resourceinstance_id": response.json()["resourceinstance_id"],
"tile_id": response.json()["tileid"]}
return arches_created_resource
else:
print("Resource creation faiiled with response code:%s" % (response.status_code))
except:
print("Cannot create new resource")
def arches_connection_reset(self, hard_reset):
"""Reset Arches connection"""
if hard_reset == True:
# Reset connection inputs
self.dlg.connection_status.setText("Logged out of Arches instance. Please reconnect to use the plugin.")
self.dlg.arches_server_input.setText("")
self.dlg.username_input.setText("")
self.dlg.password_input.setText("")
# Replace login tab with logged in tab
self.dlg.tabWidget.setTabVisible(0, True)
self.dlg.tabWidget.setTabVisible(1, False)
self.dlg.tabWidget.setCurrentIndex(0)
# Reset stored data
self.arches_user_info = {}
self.arches_connection_cache = {}
self.arches_token = {}
self.arches_graphs_list = []
# Reset Create Resource tab as no longer useable
self.dlg.createResModelSelect.setEnabled(False)
self.dlg.createResFeatureSelect.setEnabled(False)
self.dlg.addNewRes.setEnabled(False)
self.dlg.createResOutputBox.setText("")
## Set "Edit Resource" to false to begin with
self.dlg.addEditRes.setEnabled(False)
self.dlg.replaceEditRes.setEnabled(False)
self.dlg.editResSelectFeatures.setEnabled(False)
self.dlg.selectedResAttributeTable.setRowCount(0)
self.dlg.selectedResAttributeTable.setEnabled(False)
self.dlg.selectedResUUID.setText("Connect to your Arches instance to edit resources.")
# Hide multiple nodegroup dropdown
self.dlg.geometryNodeSelect.setEnabled(False)
def arches_connection_save(self):
"""Data for connection to Arches project server"""
# strip and remove ending slash
def format_url():
formatted_url = self.dlg.arches_server_input.text().strip()
if formatted_url[-1] == "/":
formatted_url = formatted_url[:-1]
return formatted_url
# once Oauth registered the clientID can be fetched and used
def get_clientid(url):
try:
files = {
'username': (None, self.dlg.username_input.text()),
'password': (None, self.dlg.password_input.text()),
}
response = requests.post(url+"/auth/get_client_id", data=files)
clientid = response.json()["clientid"]
return clientid
except:
self.dlg.connection_status.setText("Failed to connect.\n- Check URL, username and password are correct.\n- Check the Arches instance is running.\n- Check the instance has a registered Oauth application.")
return None
def get_user_permissions(url):
try:
files = {
'username': (None, self.dlg.username_input.text()),
'password': (None, self.dlg.password_input.text()),
}
response = requests.post(url+"/auth/user_profile", data=files)
self.arches_user_info["deletable_nodegroups"] = response.json()["deletable_nodegroups"]
self.arches_user_info["editable_nodegroups"] = response.json()["editable_nodegroups"]
self.arches_user_info["groups"] = response.json()["groups"]
self.arches_user_info["is_active"] = response.json()["is_active"]
except:
self.arches_user_info["deletable_nodegroups"] = None
self.arches_user_info["editable_nodegroups"] = None
self.arches_user_info["is_active"] = None
self.arches_user_info["groups"] = []
def get_token(url, clientid):
try:
files = {
'username': (None, self.dlg.username_input.text()),
'password': (None, self.dlg.password_input.text()),
'client_id': (None, clientid),
'grant_type': (None, "password")
}
response = requests.post(url+"/o/token/", data=files)
self.arches_token = response.json()
self.arches_token["formatted_url"] = url
self.arches_token["time"] = str(datetime.now())
# If the token has an error status in it then break
if "error" in self.arches_token.keys():
error_msg = self.arches_token["error"]
self.arches_token = {} # reset token to empty
self.dlg.connection_status.setText(f"Error connecting to token: {error_msg}.")
except:
self.dlg.connection_status.setText("Can't get Arches oauth2 token.")
def get_graphs(url):
try:
response = requests.get("%s/graphs/" % (url))
graphids = [x["graphid"] for x in response.json() if x["graphid"] != "ff623370-fa12-11e6-b98b-6c4008b05c4c"] # sys settings
for graph in graphids:
geometry_node_data = {}
contains_geom = False
geom_node_count = 0
req = requests.get("%s/graphs/%s" % (url, graph))
if req.json()["graph"]["publication_id"]: # if graph is published
for nodes in req.json()["graph"]["nodes"]:
if nodes["datatype"] == "geojson-feature-collection":
contains_geom = True
geom_node_count += 1
nodegroupid = nodes["nodegroup_id"]
nodeid = nodes["nodeid"]
node_name = nodes["name"]
geometry_node_data[nodeid] = {"nodegroup_id": nodegroupid, "name": node_name}
if contains_geom == True:
if geom_node_count > 1: multiple = True
else: multiple = False
self.arches_graphs_list.append({
"graph_id":graph,
"name":req.json()["graph"]["name"],
"geometry_node_data": geometry_node_data,
"multiple_geometry_nodes": multiple
})
except:
pass
# reset connection status on button press
self.dlg.connection_status.setText("")
is_valid_input = True
if self.dlg.arches_server_input.text() == "" or str(self.dlg.arches_server_input.text()).isspace() == True:
self.dlg.connection_status.append("Please enter the URL to your Arches project.")
is_valid_input = False
if self.dlg.username_input.text() == "":
self.dlg.connection_status.append("Please enter your username.")
is_valid_input = False
if self.dlg.password_input.text() == "":
self.dlg.connection_status.append("Please enter your password.")
is_valid_input = False
# URL field has data in
if is_valid_input == True:
if self.dlg.arches_server_input.text() != "":
formatted_url = format_url()
self.dlg.connection_status.setText("Connecting...")
clientid = get_clientid(formatted_url)
if clientid:
# If client id NOT None then connection has been made
# check cache first before firing connection again
# get/update user info on the logged in user
self.arches_user_info = {}
get_user_permissions(formatted_url)
# re-fetch graphs before checking cache as updates may have occurred
self.arches_graphs_list = []
get_graphs(formatted_url)
if self.arches_connection_cache:
# IF THE CACHE IS UNCHANGED THEN DON'T REFIRE CONNECTION
if (self.dlg.arches_server_input.text() == self.arches_connection_cache["url"] and
self.dlg.username_input.text() == self.arches_connection_cache["username"]):
self.dlg.connection_status.setText("Connection reattempt prevented as login details remain unchanged. \nGraphs have been refetched to reflect changed made on Arches.")
# Re-fetch the graphs with updated list
if self.arches_graphs_list:
self.dlg.createResModelSelect.clear()
self.dlg.createResModelSelect.addItems([graph["name"] for graph in self.arches_graphs_list])
# Re-fill the comboboxes
self.layers = [l for l in QgsProject.instance().mapLayers().values() if l.type() == QgsVectorLayer.VectorLayer if str(l.dataProvider().name()) != "postgres"]
self.dlg.createResFeatureSelect.clear()
self.dlg.createResFeatureSelect.addItems([layer.name() for layer in self.layers])
self.dlg.editResSelectFeatures.clear()