-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathspeckle_qgis.py
1691 lines (1465 loc) · 63.5 KB
/
speckle_qgis.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 -*-
from copy import copy
import inspect
import os.path
import time
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from datetime import datetime
import threading
from plugin_utils.threads import KThread
from plugin_utils.helpers import (
constructCommitURL,
get_project_workspace_id,
getAppName,
removeSpecialCharacters,
)
try:
from qgis.core import (
Qgis,
QgsProject,
QgsRasterLayer,
QgsVectorLayer,
QgsUnitTypes,
)
from qgis.PyQt.QtCore import QCoreApplication, QSettings, Qt, QTranslator
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import (
QApplication,
QAction,
QMenu,
QDockWidget,
QVBoxLayout,
QWidget,
)
from qgis.PyQt import QtWidgets
from qgis import PyQt
except ModuleNotFoundError:
pass
from specklepy.core.api import operations
from specklepy.logging.exceptions import (
SpeckleException,
GraphQLException,
SpeckleInvalidUnitException,
)
from specklepy.core.api.models import Stream, Branch, Commit
from specklepy.core.api.wrapper import StreamWrapper
from specklepy.objects import Base
from specklepy.objects.other import Collection
from specklepy.objects.units import get_units_from_string
from specklepy.core.api.credentials import (
Account,
)
from specklepy.core.api.client import SpeckleClient
from specklepy.logging import metrics
# Initialize Qt resources from file resources.py
from resources import *
from plugin_utils.object_utils import callback, traverseObject
from speckle.converter.layers import (
getAllLayers,
getSavedLayers,
getSelectedLayers,
getSelectedLayersWithStructure,
)
from speckle.converter.layers.layer_conversions import (
addBimMainThread,
addCadMainThread,
addExcelMainThread,
addNonGeometryMainThread,
addRasterMainThread,
addVectorMainThread,
convertSelectedLayersToSpeckle,
)
from speckle.converter.layers import findAndClearLayerGroup
from specklepy_qt_ui.qt_ui.DataStorage import DataStorage
from specklepy_qt_ui.qt_ui.widget_add_stream import AddStreamModalDialog
from specklepy_qt_ui.qt_ui.widget_create_stream import CreateStreamModalDialog
from specklepy_qt_ui.qt_ui.widget_create_branch import CreateBranchModalDialog
from speckle.utils.panel_logging import logToUser
# Import the code for the dialog
from speckle.utils.validation import (
tryGetClient,
tryGetStream,
validateBranch,
validateCommit,
validateStream,
validateTransport,
)
from specklepy_qt_ui.qt_ui.widget_custom_crs import CustomCRSDialog
from plugin_utils.installer import _debug
SPECKLE_COLOR = (59, 130, 246)
SPECKLE_COLOR_LIGHT = (69, 140, 255)
class SpeckleQGIS:
"""Speckle Connector Plugin for QGIS"""
dockwidget: Optional["QDockWidget"]
version: str
gis_version: str
add_stream_modal: AddStreamModalDialog
create_stream_modal: CreateStreamModalDialog
current_streams: List[Tuple[StreamWrapper, Stream]] # {id:(sw,st),id2:()}
current_layers: List[Tuple[Union["QgsVectorLayer", "QgsRasterLayer"], str, str]] = (
[]
)
# current_layer_group: Any
receive_layer_tree: Dict
active_stream: Optional[Tuple[StreamWrapper, Stream]]
active_branch: Optional[Branch] = None
active_commit: Optional[Commit] = None
project: "QgsProject"
# lat: float
# lon: float
accounts: List[Account]
theads_total: int
dataStorage: DataStorage
# signal_groupCreate = pyqtSignal(object)
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.lock = threading.Lock()
self.dockwidget = None
self.version = "0.0.99"
self.gis_version = Qgis.QGIS_VERSION.encode(
"iso-8859-1", errors="ignore"
).decode("utf-8")
self.iface = iface
self.project = QgsProject.instance()
self.current_streams = []
self.active_stream = None
self.active_branch = None
self.active_commit = None
self.receive_layer_tree = None
# self.default_account = None
# self.accounts = []
# self.active_account = None
self.theads_total = 0
self.btnAction = 0
# self.lat = 0.0
# self.lon = 0.0
# 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", "SpeckleQGIS_{}.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("&SpeckleQGIS")
# Check if plugin was started the first time in current QGIS session
# Must be set in initGui() to survive plugin reloads
self.pluginIsActive = False
# noinspection PyMethodMayBeStatic
def tr(self, message: str):
"""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("SpeckleQGIS", message)
def add_action(
self,
icon_path: str,
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.addPluginToWebMenu(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/speckle_qgis/icon.png"
self.add_action(
icon_path,
text=self.tr("SpeckleQGIS"),
callback=self.run,
parent=self.iface.mainWindow(),
)
def onClosePlugin(self):
"""Cleanup necessary items here when plugin dockwidget is closed"""
# disconnects
if self.dockwidget:
try:
self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
except:
pass
# remove this statement if dockwidget is to remain
# for reuse if plugin is reopened
# Commented next statement since it causes QGIS crashe
# when closing the docked window:
# self.dockwidget = None
self.pluginIsActive = False
self.dockwidget.close()
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
try:
for action in self.actions:
self.iface.removePluginWebMenu(self.tr("&SpeckleQGIS"), action)
self.iface.removeToolBarIcon(action)
except Exception as e:
logToUser(e, level=2, func=inspect.stack()[0][3], plugin=self.dockwidget)
return
def onRunButtonClicked(self):
# print("onRUN")
# set QGIS threads number only the first time:
# if self.theads_total==0: self.theads_total = threading.active_count()
all_threads = threading.enumerate()
for t in all_threads:
if t.name.startswith("speckle"):
name = ""
if "receive" in t.name:
name = "Receive"
if "send" in t.name:
name = "Send"
logToUser(
f"Previous {name} operation is still running \nClick here to cancel",
level=2,
url="cancel",
plugin=self.dockwidget,
)
return
# set the project instance
self.project = QgsProject.instance()
self.dataStorage.project = self.project
self.dockwidget.msgLog.setGeometry(
0,
0,
self.dockwidget.frameSize().width(),
self.dockwidget.frameSize().height(),
)
self.dockwidget.reportBtn.setEnabled(True)
# https://www.opengis.ch/2016/09/07/using-threads-in-qgis-python-plugins/
# send
if self.btnAction == 0:
# Reset Survey point
# self.dockwidget.populateSurveyPoint(self)
# Get and clear message
message = str(self.dockwidget.messageInput.text())
self.dockwidget.messageInput.setText("")
try:
streamWrapper = self.active_stream[0]
client = streamWrapper.get_client()
self.dataStorage.active_account = client.account
logToUser(
f"Sending data... \nClick here to cancel",
level=0,
url="cancel",
plugin=self.dockwidget,
)
if _debug is True:
raise Exception
t = KThread(target=self.onSend, name="speckle_send", args=(message,))
t.start()
except:
self.onSend(message)
# receive
elif self.btnAction == 1:
################### repeated
try:
if not self.dockwidget:
return
# Check if stream id/url is empty
if self.active_stream is None:
logToUser(
"Please select a stream from the list",
level=2,
func=inspect.stack()[0][3],
plugin=self.dockwidget,
)
return
# Get the stream wrapper
streamWrapper = self.active_stream[0]
streamId = streamWrapper.stream_id
# client = streamWrapper.get_client()
client, stream = tryGetClient(
streamWrapper, self.dataStorage, False, self.dockwidget
)
stream = validateStream(stream, self.dockwidget)
if stream == None:
return
except Exception as e:
logToUser(
e, level=2, func=inspect.stack()[0][3], plugin=self.dockwidget
)
return
# Ensure the stream actually exists
try:
branchName = str(self.dockwidget.streamBranchDropdown.currentText())
branch = validateBranch(stream, branchName, True, self.dockwidget)
if branch == None:
return
commitId = str(self.dockwidget.commitDropdown.currentText())
commit = validateCommit(branch, commitId, self.dockwidget)
if commit == None:
return
# If group exists, remove layers inside
newGroupName = streamId + "_" + branch.name + "_" + commit.id
newGroupName = removeSpecialCharacters(newGroupName)
findAndClearLayerGroup(self.project.layerTreeRoot(), newGroupName, self)
except Exception as e:
logToUser(
str(e), level=2, func=inspect.stack()[0][3], plugin=self.dockwidget
)
return
########################################### end of repeated
try:
streamWrapper = self.active_stream[0]
client = streamWrapper.get_client()
self.dataStorage.active_account = client.account
logToUser(
"Receiving data... \nClick here to cancel",
level=0,
url="cancel",
plugin=self.dockwidget,
)
if _debug is True:
raise Exception
t = KThread(target=self.onReceive, name="speckle_receive", args=())
t.start()
except:
self.onReceive()
def onSend(self, message: str):
"""Handles action when Send button is pressed."""
# logToUser("Some message here", level = 0, func = inspect.stack()[0][3], plugin=self.dockwidget )
try:
if not self.dockwidget:
return
projectCRS = self.project.crs()
bySelection = True
if self.dockwidget.layerSendModeDropdown.currentIndex() == 1:
bySelection = False
layers, tree_structure = getSavedLayers(self)
else:
# layers = getSelectedLayers(self) # List[QgsLayerTreeNode]
layers, tree_structure = getSelectedLayersWithStructure(self)
# Check if stream id/url is empty
if self.active_stream is None:
logToUser(
"Please select a stream from the list",
level=2,
func=inspect.stack()[0][3],
plugin=self.dockwidget,
)
return
current_active_stream = copy(self.active_stream)
branchName = str(self.dockwidget.streamBranchDropdown.currentText())
# Check if no layers are selected
if len(layers) == 0 or layers is None: # len(selectedLayerNames) == 0:
logToUser(
"No valid layers selected",
level=1,
func=inspect.stack()[0][3],
plugin=self.dockwidget,
)
return
self.dataStorage.latestActionLayers = [l.name() for l in layers]
# print(layers)
root = self.dataStorage.project.layerTreeRoot()
self.dataStorage.all_layers = getAllLayers(root)
self.dockwidget.mappingSendDialog.populateSavedTransforms(self.dataStorage)
units = str(QgsUnitTypes.encodeUnit(projectCRS.mapUnits()))
self.dataStorage.latestActionUnits = units
try:
units_class = get_units_from_string(units)
units = units_class.value
except SpeckleInvalidUnitException:
units = "none"
self.dataStorage.currentUnits = units
if (
self.dataStorage.crs_offset_x is not None
and self.dataStorage.crs_offset_x
) != 0 or (
self.dataStorage.crs_offset_y is not None
and self.dataStorage.crs_offset_y
):
logToUser(
f"Applying CRS offsets: x={self.dataStorage.crs_offset_x}, y={self.dataStorage.crs_offset_y}",
level=0,
plugin=self.dockwidget,
)
if (
self.dataStorage.crs_rotation is not None
and self.dataStorage.crs_rotation
) != 0:
logToUser(
f"Applying CRS rotation: {self.dataStorage.crs_rotation}°",
level=0,
plugin=self.dockwidget,
)
self.dataStorage.latestActionReport = []
self.dataStorage.latestActionFeaturesReport = []
base_obj = Collection(
units=units,
collectionType="model",
name="QGIS commit",
elements=[],
)
# conversions
time_start_conversion = datetime.now()
base_obj = convertSelectedLayersToSpeckle(
base_obj, layers, tree_structure, projectCRS, self
)
time_end_conversion = datetime.now()
if (
base_obj is None
or base_obj.elements is None
or (isinstance(base_obj.elements, List) and len(base_obj.elements) == 0)
):
logToUser(f"No data to send", level=2, plugin=self.dockwidget)
return
logToUser(f"Sending data to the server...", level=0, plugin=self.dockwidget)
# Get the stream wrapper
streamWrapper = current_active_stream[0]
streamName = current_active_stream[1].name
streamId = streamWrapper.stream_id
# client = streamWrapper.get_client()
client, stream = tryGetClient(
streamWrapper, self.dataStorage, True, self.dockwidget
)
if not isinstance(client, SpeckleClient):
logToUser(
f"SpeckleClient invalid: {client}", level=2, plugin=self.dockwidget
)
return
stream = validateStream(stream, self.dockwidget)
if not isinstance(stream, Stream):
logToUser(f"Stream invalid: {stream}", level=2, plugin=self.dockwidget)
return
branch = validateBranch(stream, branchName, False, self.dockwidget)
branchId = branch.id
if branch == None:
logToUser(f"Branch invalid: {branch}", level=2, plugin=self.dockwidget)
return
transport = validateTransport(client, streamId)
if transport == None:
logToUser(
f"Transport invalid: {transport}", level=2, plugin=self.dockwidget
)
return
except Exception as e:
logToUser(e, level=2, func=inspect.stack()[0][3], plugin=self.dockwidget)
return
# data transfer
try:
self.dockwidget.signal_remove_btn_url.emit("cancel")
time_start_transfer = datetime.now()
# this serialises the block and sends it to the transport
objId = operations.send(base=base_obj, transports=[transport])
time_end_transfer = datetime.now()
except Exception as e:
logToUser(
"Error sending data: " + str(e),
level=2,
func=inspect.stack()[0][3],
plugin=self.dockwidget,
)
time_end_transfer = datetime.now()
try:
metr_filter = "Selected" if bySelection is True else "Saved"
metr_main = True if branchName == "main" else False
metr_saved_streams = len(self.current_streams)
metr_branches = len(current_active_stream[1].branches.items)
metr_collab = len(current_active_stream[1].collaborators)
metr_projected = True if not projectCRS.isGeographic() else False
if self.project.crs().isValid() is False:
metr_projected = None
try:
metr_crs = (
True
if self.dataStorage.custom_lat != 0
and self.dataStorage.custom_lon != 0
and str(self.dataStorage.custom_lat) in projectCRS.toWkt()
and str(self.dataStorage.custom_lon) in projectCRS.toWkt()
else False
)
except:
metr_crs = False
metrics.track(
metrics.SEND,
self.dataStorage.active_account,
{
"hostAppFullVersion": self.gis_version,
"branches": metr_branches,
"collaborators": metr_collab,
"connector_version": str(self.version),
"workspace_id": get_project_workspace_id(client, streamId),
"filter": metr_filter,
"isMain": metr_main,
"savedStreams": metr_saved_streams,
"projectedCRS": metr_projected,
"customCRS": metr_crs,
"time_conversion": (
time_end_conversion - time_start_conversion
).total_seconds(),
"time_transfer": (
time_end_transfer - time_start_transfer
).total_seconds(),
"error": str(e),
},
)
except:
metrics.track(
metrics.SEND,
self.dataStorage.active_account,
{
"hostAppFullVersion": self.gis_version,
"connector_version": str(self.version),
"time_conversion": (
time_end_conversion - time_start_conversion
).total_seconds(),
"time_transfer": (
time_end_transfer - time_start_transfer
).total_seconds(),
"error": str(e),
},
)
return
try:
# you can now create a commit on your stream with this object
commit_id = client.commit.create(
stream_id=streamId,
object_id=objId,
branch_name=branchName,
message="Sent objects from QGIS" if len(message) == 0 else message,
source_application="QGIS" + self.gis_version.split(".")[0],
)
# add time stats to the report
self.dataStorage.latestActionTime = str(
datetime.now().strftime("%d/%m/%Y, %H:%M:%S")
)
self.dataStorage.latestTransferTime = str(
time_end_transfer - time_start_transfer
)
self.dataStorage.latestConversionTime = str(
time_end_conversion - time_start_conversion
)
try:
metr_filter = "Selected" if bySelection is True else "Saved"
metr_main = True if branchName == "main" else False
metr_saved_streams = len(self.current_streams)
metr_branches = len(current_active_stream[1].branches.items)
metr_collab = len(current_active_stream[1].collaborators)
metr_projected = True if not projectCRS.isGeographic() else False
if self.project.crs().isValid() is False:
metr_projected = None
try:
metr_crs = (
True
if self.dataStorage.custom_lat != 0
and self.dataStorage.custom_lon != 0
and str(self.dataStorage.custom_lat) in projectCRS.toWkt()
and str(self.dataStorage.custom_lon) in projectCRS.toWkt()
else False
)
except:
metr_crs = False
metrics.track(
metrics.SEND,
self.dataStorage.active_account,
{
"hostAppFullVersion": self.gis_version,
"branches": metr_branches,
"collaborators": metr_collab,
"connector_version": str(self.version),
"filter": metr_filter,
"isMain": metr_main,
"savedStreams": metr_saved_streams,
"projectedCRS": metr_projected,
"customCRS": metr_crs,
"time_conversion": (
time_end_conversion - time_start_conversion
).total_seconds(),
"time_transfer": (
time_end_transfer - time_start_transfer
).total_seconds(),
"workspace_id": get_project_workspace_id(client, streamId),
},
)
except Exception as e:
metrics.track(
metrics.SEND,
self.dataStorage.active_account,
{
"hostAppFullVersion": self.gis_version,
"connector_version": str(self.version),
"time_conversion": (
time_end_conversion - time_start_conversion
).total_seconds(),
"time_transfer": (
time_end_transfer - time_start_transfer
).total_seconds(),
},
)
if isinstance(commit_id, SpeckleException):
logToUser(
"Error creating commit: " + str(commit_id.message),
level=2,
func=inspect.stack()[0][3],
plugin=self.dockwidget,
)
return
url: str = constructCommitURL(streamWrapper, branchId, commit_id)
if str(self.dockwidget.commitDropdown.currentText()).startswith("Latest"):
stream = client.stream.get(
id=streamId, branch_limit=100, commit_limit=100
)
branch = validateBranch(stream, branchName, False, self.dockwidget)
self.active_commit = branch.commits.items[0]
# self.dockwidget.hideWait()
# self.dockwidget.showLink(url, streamName)
# if self.dockwidget.experimental.isChecked(): time.sleep(3)
if (
self.project.crs().isGeographic() is True
or self.project.crs().isValid() is False
):
logToUser(
"Data has been sent in the units 'degrees'. It is advisable to set the project CRS to Projected type (e.g. EPSG:32631) to be able to receive geometry correctly in CAD/BIM software. You can also create a custom CRS by setting geographic coordinates and using 'Set as a project center' function.",
level=1,
plugin=self.dockwidget,
)
self.dockwidget.msgLog.dataStorage = self.dataStorage
logToUser(
"Data sent to '"
+ str(streamName)
+ "'"
+ "\nClick to view commit online",
level=0,
plugin=self.dockwidget,
url=url,
report=True,
)
except Exception as e:
# if self.dockwidget.experimental.isChecked():
time.sleep(1)
logToUser(
"Error creating commit: " + str(e),
level=2,
func=inspect.stack()[0][3],
plugin=self.dockwidget,
)
self.dockwidget.cancelOperations()
def onReceive(self):
"""Handles action when the Receive button is pressed"""
# print("Receive")
try:
if not self.dockwidget:
return
self.dataStorage.flat_report_latest = copy(
self.dataStorage.flat_report_receive
)
self.dataStorage.flat_report_receive = {}
self.dataStorage.latestHostApp = ""
# Check if stream id/url is empty
if self.active_stream is None:
logToUser(
"Please select a stream from the list",
level=2,
func=inspect.stack()[0][3],
plugin=self.dockwidget,
)
return
# Get the stream wrapper
streamWrapper = self.active_stream[0]
streamId = streamWrapper.stream_id
# client = streamWrapper.get_client()
client, stream = tryGetClient(
streamWrapper, self.dataStorage, False, self.dockwidget
)
if not isinstance(client, SpeckleClient) or not isinstance(stream, Stream):
return
stream = validateStream(stream, self.dockwidget)
if not isinstance(stream, Stream):
return
except Exception as e:
logToUser(e, level=2, func=inspect.stack()[0][3], plugin=self.dockwidget)
return
# Ensure the stream actually exists
try:
branchName = str(self.dockwidget.streamBranchDropdown.currentText())
if str(self.dockwidget.commitDropdown.currentText()).startswith("Latest"):
stream = client.stream.get(
id=stream.id, branch_limit=100, commit_limit=100
)
branch = validateBranch(stream, branchName, True, self.dockwidget)
if branch == None:
return
commitId = str(self.dockwidget.commitDropdown.currentText())
commit = validateCommit(branch, commitId, self.dockwidget)
if commit == None:
return
self.active_commit = commit
except Exception as e:
logToUser(
str(e), level=2, func=inspect.stack()[0][3], plugin=self.dockwidget
)
return
try:
objId = commit.referencedObject
if branch.name is None or commit.id is None or objId is None:
return
app_full = commit.sourceApplication
app = getAppName(commit.sourceApplication)
self.dataStorage.latestHostApp = app
client_id = client.account.userInfo.id
transport = validateTransport(client, streamId)
if transport == None:
logToUser(
"Transport not found",
level=2,
func=inspect.stack()[0][3],
plugin=self.dockwidget,
)
return
# data transfer
time_start_transfer = datetime.now()
commitObj = operations.receive(objId, transport, None)
time_end_transfer = datetime.now()
self.dockwidget.signal_remove_btn_url.emit("cancel")
projectCRS = self.project.crs()
units = str(QgsUnitTypes.encodeUnit(projectCRS.mapUnits()))
self.dataStorage.latestActionUnits = units
try:
metr_crs = (
True
if self.dataStorage.custom_lat != 0
and self.dataStorage.custom_lon != 0
and str(self.dataStorage.custom_lat) in projectCRS.toWkt()
and str(self.dataStorage.custom_lon) in projectCRS.toWkt()
else False
)
except:
metr_crs = False
metr_projected = True if not projectCRS.isGeographic() else False
if self.project.crs().isValid() is False:
metr_projected = None
client.commit.received(
streamId,
commit.id,
source_application="QGIS" + self.gis_version.split(".")[0],
message="Received commit in QGIS",
)
if app.lower() != "qgis" and app.lower() != "arcgis":
if (
self.project.crs().isGeographic() is True
or self.project.crs().isValid() is False
):
logToUser(
"Conversion from metric units to DEGREES not supported. It is advisable to set the project CRS to Projected type before receiving CAD/BIM geometry (e.g. EPSG:32631), or create a custom one from geographic coordinates",
level=1,
func=inspect.stack()[0][3],
plugin=self.dockwidget,
)
except Exception as e:
logToUser(
str(e), level=2, func=inspect.stack()[0][3], plugin=self.dockwidget
)
return
newGroupName = streamId + "_" + branch.name + "_" + commit.id
newGroupName = removeSpecialCharacters(newGroupName)
try:
if app.lower() != "qgis" and app.lower() != "arcgis":
if (
self.dataStorage.crs_offset_x is not None
and self.dataStorage.crs_offset_x
) != 0 or (
self.dataStorage.crs_offset_y is not None
and self.dataStorage.crs_offset_y
):
logToUser(
f"Applying CRS offsets: x={self.dataStorage.crs_offset_x}, y={self.dataStorage.crs_offset_y}",
level=0,
plugin=self.dockwidget,
)
if (
self.dataStorage.crs_rotation is not None
and self.dataStorage.crs_rotation
) != 0:
logToUser(
f"Applying CRS rotation: {self.dataStorage.crs_rotation}°",
level=0,
plugin=self.dockwidget,
)
except:
pass
try:
if app.lower() == "qgis" or app.lower() == "arcgis":
# print(app.lower())
check: Callable[[Base], bool] = lambda base: base.speckle_type and (
base.speckle_type.endswith("VectorLayer")
or base.speckle_type.endswith("Layer")
or base.speckle_type.endswith("RasterLayer")
)
else:
check: Callable[[Base], bool] = lambda base: (
base.speckle_type
) # and base.speckle_type.endswith("Base") )
self.receive_layer_tree = {str(newGroupName): {}}
# print(self.receive_layer_tree)
self.dataStorage.latestActionLayers = []
self.dataStorage.latestActionReport = []
# conversions
time_start_conversion = self.dataStorage.latestConversionTime = (
datetime.now()
)
traverseObject(self, commitObj, callback, check, str(newGroupName), "")
time_end_conversion = self.dataStorage.latestConversionTime
# add time stats to the report