-
Notifications
You must be signed in to change notification settings - Fork 22
/
LinkScope.py
3256 lines (2785 loc) · 155 KB
/
LinkScope.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
#!/usr/bin/env python3
# Load modules
import contextlib
import platform
import re
import sys
import time
import itertools
import threading
import networkx as nx
import qdarktheme
from ast import literal_eval
from uuid import uuid4
from shutil import move
from inspect import getsourcefile
from os import access, R_OK, W_OK, getpid, kill
from os.path import abspath, dirname
from msgpack import load
from pathlib import Path
from datetime import datetime
from typing import Union
from PySide6 import QtWidgets, QtGui, QtCore
from Core import MessageHandler, SettingsObject
from Core import ResourceHandler
from Core import ModuleManager
from Core import EntityDB
from Core import ResolutionManager
from Core import URLManager
from Core import FrontendCommunicationsHandler
from Core.UpdateManager import UpdateManager, UpdaterWindow
from Core.ResourceHandler import resizePictureFromBuffer
from Core.Interface import CentralPane
from Core.Interface import DockBarOne, DockBarTwo, DockBarThree
from Core.Interface import ToolBarOne
from Core.Interface import MenuBar
from Core.Interface.Entity import BaseNode, BaseConnector, GroupNode
from Core.LQL import LQLQueryBuilder, QueryBuilderWizard
from Core.ReportGeneration import ReportWizard
from Core.PathHelper import is_path_exists_or_creatable_portable
# Main Window of Application
class MainWindow(QtWidgets.QMainWindow):
facilitateResolutionSignalListener = QtCore.Signal(str, list)
notifyUserSignalListener = QtCore.Signal(str, str, bool)
statusBarSignalListener = QtCore.Signal(str)
warningSignalListener = QtCore.Signal(str, bool)
errorSignalListener = QtCore.Signal(str, bool, bool)
runningMacroResolutionFinishedSignalListener = QtCore.Signal(str, str, list)
# Redefining the function to adjust its signature.
def centralWidget(self) -> Union[QtWidgets.QWidget, QtWidgets.QWidget, CentralPane.WorkspaceWidget]:
return super(MainWindow, self).centralWidget()
def getSettings(self) -> SettingsObject.SettingsObject:
return self.SETTINGS
# Duplicate and alter a group entity to make it
def copyGroupEntity(self, existingGroupUID: str, targetCanvas: CentralPane.CanvasScene) -> Union[dict, None]:
# Have to make a new group entity, so that ungrouping in one canvas doesn't delete the entity
# group in another.
entityJSON = self.LENTDB.getEntity(existingGroupUID)
# Dereference the list, so we don't have issues w/ the original Group Node.
newChildren = [childUID for childUID in list(entityJSON['Child UIDs'])
if childUID not in targetCanvas.sceneGraph.nodes]
# Don't create the entity if all the nodes in it already exist on the target canvas.
if not newChildren:
return None
newEntity = self.LENTDB.addEntity(
{'Group Name': entityJSON['Group Name'] + ' Copy',
'Child UIDs': newChildren,
'Entity Type': 'EntityGroup'})
newUID = newEntity['uid']
# Need to re-create the links too
for linkUID in self.LENTDB.getOutgoingLinks(entityJSON['uid']):
newLinkJSON = dict(self.LENTDB.getLink(linkUID))
newLinkJSON['uid'] = (newUID, linkUID[1])
self.LENTDB.addLink(newLinkJSON)
for linkUID in self.LENTDB.getIncomingLinks(entityJSON['uid']):
newLinkJSON = dict(self.LENTDB.getLink(linkUID))
newLinkJSON['uid'] = (linkUID[0], newUID)
self.LENTDB.addLink(newLinkJSON)
return newEntity
# What happens when the software is closed
def closeEvent(self, event) -> None:
self.dockbarThree.logViewerUpdateThread.endLogging = True
self.saveTimer.stop()
# Save the window settings
self.SETTINGS.setGlobalValue("MainWindow/Geometry", self.saveGeometry().data())
self.SETTINGS.setGlobalValue("MainWindow/WindowState", self.saveState().data())
self.SETTINGS.setGlobalValue("Program/Usage/First Time Start", False)
if self.FCOM.isConnected():
self.FCOM.close()
self.SETTINGS.setValue("Project/Server/Project", "")
self.saveProject()
# Wait just a little for the logging thread to close.
# We don't _have_ to do this, but it stops errors from popping up due to threads being rudely interrupted.
while not self.dockbarThree.logViewerUpdateThread.isFinished():
time.sleep(0.01)
super(MainWindow, self).closeEvent(event)
# Terminating ThreadPoolExecutor threads, so that the application quits.
for thread in threading.enumerate():
if 'ThreadPoolExecutor' in thread.name:
# Yes, this is terrible. Whenever ThreadPoolExecutor allows for the creation of actual daemon threads
# that don't cause the program to hang, this will be removed.
kill(getpid(), 9)
def saveHelper(self) -> None:
"""
This is where all the saving is done.
Add all save methods here.
NOTE: This function should only be called inside a try/catch.
@return:
"""
self.LENTDB.save()
self.RESOLUTIONMANAGER.save()
self.MODULEMANAGER.save()
self.SETTINGS.save()
self.centralWidget().tabbedPane.save()
def resetMainWindowTitle(self):
self.setWindowTitle(f"LinkScope {self.SETTINGS.value('Program/Version', 'N/A')}"
f" - {self.SETTINGS.value('Project/Name', 'Untitled')}")
def saveProject(self) -> None:
try:
self.saveHelper()
self.setStatus("Project Saved.", 3000)
self.MESSAGEHANDLER.info('Project Saved')
except Exception as e:
errorMessage = f"Could not Save Project: {repr(e)}"
self.MESSAGEHANDLER.error(errorMessage, exc_info=True)
self.setStatus("Failed Saving Project.", 3000)
self.MESSAGEHANDLER.info("Failed Saving Project " + self.SETTINGS.value("Project/Name", 'Untitled'))
def autoSaveProject(self):
try:
self.saveHelper()
self.setStatus("Project Autosaved.", 3000)
except Exception:
self.setStatus("Failed Autosaving Project " + self.SETTINGS.value("Project/Name", 'Untitled'))
def saveAsProject(self) -> None:
if len(self.resolutions) > 0:
self.MESSAGEHANDLER.warning('Cannot Save As project while resolutions are running. Running resolutions: '
+ str(self.resolutions), popUp=True)
return
# Native file dialogs (at least on Ubuntu) return sandboxed paths in some occasions, which messes with the
# saving of the project, since we need to create a directory to save the project in.
saveAsDialog = QtWidgets.QFileDialog()
saveAsDialog.setOption(QtWidgets.QFileDialog.Option.DontUseNativeDialog, True)
saveAsDialog.setViewMode(QtWidgets.QFileDialog.ViewMode.List)
saveAsDialog.setFileMode(QtWidgets.QFileDialog.FileMode.AnyFile)
saveAsDialog.setAcceptMode(QtWidgets.QFileDialog.AcceptMode.AcceptSave)
saveAsDialog.setDirectory(str(Path.home()))
if not saveAsDialog.exec():
self.setStatus('Save As operation cancelled.')
return
fileName = saveAsDialog.selectedFiles()[0]
newProjectPath = Path(fileName)
# There is a limit to how long path names can be. This will not prevent all edge cases with nested files,
# since users can have files with absurdly long names, but it should be a reasonable precaution.
if not is_path_exists_or_creatable_portable(str(newProjectPath)):
self.MESSAGEHANDLER.error(
'Invalid project name or path to save at.', popUp=True, exc_info=False)
return
try:
newProjectPath.mkdir(0o700, parents=False, exist_ok=False)
except FileExistsError:
self.MESSAGEHANDLER.error('Cannot save project to an existing directory. Please choose a unique name.',
popUp=True, exc_info=False)
return
except FileNotFoundError:
self.MESSAGEHANDLER.error('Cannot save project into a non-existing parent directory. '
'Please create the required parent directories and try again.',
popUp=True, exc_info=False)
return
oldName = self.SETTINGS.value("Project/Name")
oldBaseDir = self.SETTINGS.value("Project/BaseDir")
oldFilesDir = self.SETTINGS.value("Project/FilesDir")
self.SETTINGS.setValue("Project/BaseDir", str(newProjectPath))
self.SETTINGS.setValue("Project/FilesDir",
str(Path(self.SETTINGS.value("Project/BaseDir")).joinpath("Project Files")))
self.SETTINGS.setValue("Project/Name", newProjectPath.name)
try:
Path(self.SETTINGS.value("Project/FilesDir")).mkdir(0o700, parents=False, exist_ok=False)
except FileExistsError:
self.MESSAGEHANDLER.error('Cannot save project to an existing directory. Please choose a unique name.',
popUp=True, exc_info=False)
self.SETTINGS.setValue("Project/BaseDir", oldBaseDir)
self.SETTINGS.setValue("Project/FilesDir", oldFilesDir)
self.SETTINGS.setValue("Project/Name", oldName)
return
except FileNotFoundError:
self.MESSAGEHANDLER.error('Cannot save project into a non-existing parent directory. '
'Please create the required parent directories and try again.',
popUp=True, exc_info=False)
self.SETTINGS.setValue("Project/BaseDir", oldBaseDir)
self.SETTINGS.setValue("Project/FilesDir", oldFilesDir)
self.SETTINGS.setValue("Project/Name", oldName)
return
self.resetMainWindowTitle()
self.saveProject()
self.setStatus(f'Project Saved As: {newProjectPath.name}')
# https://networkx.org/documentation/stable/reference/readwrite/graphml.html
def exportCanvasToGraphML(self):
currentCanvasGraph = self.centralWidget().tabbedPane.getCurrentScene().sceneGraph
saveAsDialog = QtWidgets.QFileDialog()
saveAsDialog.setOption(QtWidgets.QFileDialog.Option.DontUseNativeDialog, True)
saveAsDialog.setViewMode(QtWidgets.QFileDialog.ViewMode.List)
saveAsDialog.setNameFilter("GraphML (*.xml)")
saveAsDialog.setAcceptMode(QtWidgets.QFileDialog.AcceptMode.AcceptSave)
saveAsDialog.setDirectory(str(Path.home()))
if saveAsDialog.exec():
try:
filePath = saveAsDialog.selectedFiles()[0]
if Path(filePath).suffix != '.xml':
filePath += '.xml'
nx.write_graphml(currentCanvasGraph, filePath)
self.setStatus('Canvas exported successfully.')
except Exception as exc:
self.MESSAGEHANDLER.error(f"Could not export canvas to file: {str(exc)}", popUp=True)
self.setStatus('Canvas export failed.')
def importCanvasFromGraphML(self):
openDialog = QtWidgets.QFileDialog()
openDialog.setOption(QtWidgets.QFileDialog.Option.DontUseNativeDialog, True)
openDialog.setViewMode(QtWidgets.QFileDialog.ViewMode.List)
openDialog.setNameFilter("GraphML (*.xml)")
openDialog.setDirectory(str(Path.home()))
if openDialog.exec():
filePath = openDialog.selectedFiles()[0]
try:
read_graphml = nx.read_graphml(filePath)
currentScene = self.centralWidget().tabbedPane.getCurrentScene()
# Deduplication, just in case.
graphMLNodes = set(read_graphml.nodes())
nodesToReadFirst = [self.LENTDB.getEntity(node) for node in graphMLNodes
if not read_graphml.nodes[node].get('groupID')]
nodesToReadFirst = [entity for entity in nodesToReadFirst if entity is not None and
entity['Entity Type'] == 'EntityGroup']
for entity in nodesToReadFirst:
# Create new group entity, so we don't mess with the contents of the original.
if entity['uid'] not in currentScene.sceneGraph.nodes:
newGroupEntity = self.copyGroupEntity(entity['uid'], currentScene)
if newGroupEntity is not None:
currentScene.addNodeProgrammatic(newGroupEntity['uid'], newGroupEntity['Child UIDs'])
graphMLNodes.remove(entity['uid'])
for node in graphMLNodes:
# Need to check as existing group nodes could have been updated with new nodes after export
# but before the import.
if node not in currentScene.sceneGraph.nodes:
currentScene.addNodeProgrammatic(node)
currentScene.rearrangeGraph()
self.setStatus('Canvas imported successfully.')
except KeyError:
self.MESSAGEHANDLER.error("Aborted canvas import: One or more nodes in the graph "
"do not exist in the database.", popUp=True)
self.setStatus('Canvas import aborted.')
except Exception as exc:
self.MESSAGEHANDLER.error(f"Cannot import canvas: {str(exc)}", popUp=True)
self.setStatus('Canvas import failed.')
def exportDatabaseToGraphML(self):
# Need to create a new database to remove the icons
with self.LENTDB.dbLock:
currentDatabase = self.LENTDB.database.copy()
for node in currentDatabase.nodes:
# Remove icons. Will reset custom icons to default, but saves space.
del currentDatabase.nodes[node]['Icon']
if currentDatabase.nodes[node].get('Child UIDs'):
currentDatabase.nodes[node]['Child UIDs'] = str(currentDatabase.nodes[node]['Child UIDs'])
for edge in currentDatabase.edges:
currentDatabase.edges[edge]['uid'] = str(currentDatabase.edges[edge]['uid'])
saveAsDialog = QtWidgets.QFileDialog()
saveAsDialog.setOption(QtWidgets.QFileDialog.Option.DontUseNativeDialog, True)
saveAsDialog.setViewMode(QtWidgets.QFileDialog.ViewMode.List)
saveAsDialog.setNameFilter("GraphML (*.xml)")
saveAsDialog.setAcceptMode(QtWidgets.QFileDialog.AcceptMode.AcceptSave)
saveAsDialog.setDirectory(str(Path.home()))
if saveAsDialog.exec():
try:
filePath = saveAsDialog.selectedFiles()[0]
if Path(filePath).suffix != '.xml':
filePath += '.xml'
nx.write_graphml(currentDatabase, filePath)
self.setStatus('Database exported successfully.')
except Exception as exc:
self.MESSAGEHANDLER.error(f"Could not export database to file: {str(exc)}", popUp=True)
self.setStatus('Database export failed.')
def importDatabaseFromGraphML(self):
openDialog = QtWidgets.QFileDialog()
openDialog.setOption(QtWidgets.QFileDialog.Option.DontUseNativeDialog, True)
openDialog.setViewMode(QtWidgets.QFileDialog.ViewMode.List)
openDialog.setNameFilter("GraphML (*.xml)")
openDialog.setDirectory(str(Path.home()))
if openDialog.exec():
try:
filePath = openDialog.selectedFiles()[0]
read_graphml = nx.read_graphml(filePath)
read_graphml_nodes = {key: read_graphml.nodes[key] for key in read_graphml.nodes}
read_graphml_edges = {key: read_graphml.edges[key] for key in read_graphml.edges}
for nodeValue in read_graphml_nodes.values():
# Make sure that all the necessary values are assigned.
# This will throw an exception if the user imports an entity without a type.
nodeValue = self.RESOURCEHANDLER.getEntityJson(nodeValue['Entity Type'], nodeValue)
if nodeValue.get('Child UIDs'):
nodeValue['Child UIDs'] = literal_eval(nodeValue['Child UIDs'])
for edge in read_graphml_edges:
read_graphml_edges[edge]['uid'] = literal_eval(read_graphml_edges[edge]['uid'])
# Make sure that all the necessary values are assigned.
read_graphml_edges[edge] = self.RESOURCEHANDLER.getLinkJson(read_graphml_edges[edge])
self.LENTDB.mergeDatabases(read_graphml_nodes, read_graphml_edges, fromServer=False)
self.dockbarOne.existingEntitiesPalette.loadEntities()
self.LENTDB.resetTimeline()
self.setStatus('Database imported successfully.')
except Exception as exc:
self.MESSAGEHANDLER.error(f"Could not import database from file: {str(exc)}", popUp=True)
self.setStatus('Database import failed.')
def generateReport(self):
wizard = ReportWizard(self)
wizard.show()
def openDirectoryInNativeFileBrowser(self, target_dir) -> None:
QtGui.QDesktopServices.openUrl(QtCore.QUrl.fromLocalFile(target_dir))
def renameProjectPromptName(self) -> None:
newName, confirm = QtWidgets.QInputDialog.getText(self,
'Rename Project',
'New Name:',
QtWidgets.QLineEdit.EchoMode.Normal,
text=self.SETTINGS.value("Project/Name"))
if confirm:
if newName == self.SETTINGS.value("Project/Name"):
self.MESSAGEHANDLER.warning(
"New name must be different than current name.", popUp=True)
return
if newName == '':
self.MESSAGEHANDLER.warning("New name cannot be blank.", popUp=True)
return
self.renameProject(newName)
def renameProject(self, newName: str) -> None:
if len(self.resolutions) > 0:
self.MESSAGEHANDLER.warning('Cannot Rename project while resolutions are running. Running resolutions: '
+ str(self.resolutions), popUp=True)
return
oldName = self.SETTINGS.value("Project/Name")
oldBaseDir = self.SETTINGS.value("Project/BaseDir")
newBaseDir = Path(oldBaseDir).parent.joinpath(newName)
if newBaseDir.exists():
self.MESSAGEHANDLER.error('Path already exists.', popUp=True, exc_info=False)
return
if not is_path_exists_or_creatable_portable(str(newBaseDir)):
self.MESSAGEHANDLER.error(
'Invalid project name or path to save at.', popUp=True, exc_info=False)
return
self.SETTINGS.setValue("Project/BaseDir", str(newBaseDir))
self.SETTINGS.setValue("Project/FilesDir",
str(Path(self.SETTINGS.value("Project/BaseDir")).joinpath("Project Files")))
self.SETTINGS.setValue("Project/Name", newName)
move(oldBaseDir, self.SETTINGS.value("Project/BaseDir"))
oldProjectFile = newBaseDir.joinpath(f'{oldName}.linkscope')
oldProjectFile.unlink(missing_ok=True)
self.resetMainWindowTitle()
self.saveProject()
statusMessage = f'Project Renamed to: {newName}'
self.setStatus(statusMessage)
self.MESSAGEHANDLER.info(statusMessage)
def addCanvas(self) -> None:
# Create or open canvas
connected = self.FCOM.isConnected()
with self.syncedCanvasesLock:
availableSyncedCanvases = self.syncedCanvases
newCanvasPopup = CreateOrOpenCanvas(self, connected, availableSyncedCanvases)
if newCanvasPopup.exec():
self.MESSAGEHANDLER.info(f"New Canvas added: {newCanvasPopup.canvasName}")
def toggleWorldDoc(self) -> None:
if self.centralWidget() is not None:
self.centralWidget().toggleLayout()
def toggleLinkingMode(self) -> None:
currentScene = self.centralWidget().tabbedPane.getCurrentScene()
if currentScene.appendingToGroup:
message = 'Cannot create manual link at this moment: Currently adding entities to group.'
self.MESSAGEHANDLER.info(message, popUp=True)
self.setStatus(message)
return
if self.linkingNodes:
self.centralWidget().tabbedPane.enableAllTabs()
currentScene.linking = False
self.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.ArrowCursor))
self.linkingNodes = False
else:
self.centralWidget().tabbedPane.disableAllTabsExceptCurrent()
currentScene.linking = True
currentScene.itemsToLink = []
currentScene.clearSelection()
self.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.CrossCursor))
self.linkingNodes = True
def deleteSpecificEntity(self, itemUID: str) -> None:
self.centralWidget().tabbedPane.nodeRemoveAllHelper(itemUID)
self.LENTDB.removeEntity(itemUID)
self.MESSAGEHANDLER.info(f"Deleted node: {itemUID}")
def deleteSpecificLink(self, linkUIDs: set) -> None:
"""
Remove a set of connections between two nodes. This takes as an argument the set of link UIDs to remove
(i.e. {(uid, uid), ...}) and it removes them from all canvases.
:param linkUIDs: A list of link uid tuples to delete.
:return:
"""
linkUIDs = list(linkUIDs)
for canvas in self.centralWidget().tabbedPane.canvasTabs:
scene = self.centralWidget().tabbedPane.canvasTabs[canvas].scene()
for linkUID in linkUIDs:
scene.removeUIDFromLink(linkUID)
for linkUID in linkUIDs:
self.LENTDB.removeLink(linkUID)
self.MESSAGEHANDLER.info(f"Deleted link: {str(linkUID)}")
def setGroupAppendMode(self, enable: bool) -> None:
if self.centralWidget().tabbedPane.getCurrentScene().linking:
message = 'Cannot append to group: Currently creating new link.'
self.setStatus(message)
self.MESSAGEHANDLER.info(message, popUp=True)
return
if enable:
self.centralWidget().tabbedPane.disableAllTabsExceptCurrent()
self.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.PointingHandCursor))
else:
self.centralWidget().tabbedPane.enableAllTabs()
self.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.ArrowCursor))
def selectLeafNodes(self) -> None:
"""
Select the nodes with at least one link coming into them, and no outgoing links.
(i.e. They are a child node in at least 1 relationship, but are not a parent node in any relationship.)
:return:
"""
self.centralWidget().tabbedPane.getCurrentScene().clearSelection()
currentCanvasGraph = self.centralWidget().tabbedPane.getCurrentScene().sceneGraph
leaves = [x for x in currentCanvasGraph.nodes()
if currentCanvasGraph.out_degree(x) == 0 and currentCanvasGraph.in_degree(x) >= 1]
for item in [node for node in self.centralWidget().tabbedPane.getCurrentScene().items()
if isinstance(node, BaseNode)]:
if item.uid in leaves:
item.setSelected(True)
def selectRootNodes(self) -> None:
"""
Select all the nodes that have at least one link going out of them, and no incoming links.
(i.e. They are a parent node in at least 1 relationship, but are not a child node in any relationship.)
:return:
"""
self.centralWidget().tabbedPane.getCurrentScene().clearSelection()
currentCanvasGraph = self.centralWidget().tabbedPane.getCurrentScene().sceneGraph
roots = [x for x in currentCanvasGraph.nodes()
if currentCanvasGraph.out_degree(x) >= 1 and currentCanvasGraph.in_degree(x) == 0]
for item in [node for node in self.centralWidget().tabbedPane.getCurrentScene().items()
if isinstance(node, BaseNode)]:
if item.uid in roots:
item.setSelected(True)
def selectIsolatedNodes(self) -> None:
"""
Select all the nodes that have no links coming into or going out of them.
:return:
"""
currentScene = self.centralWidget().tabbedPane.getCurrentScene()
currentScene.clearSelection()
for isolatedNodeUID in nx.isolates(currentScene.sceneGraph):
currentScene.nodesDict[isolatedNodeUID].setSelected(True)
def selectNonIsolatedNodes(self) -> None:
"""
Select all nodes with at least one link going into or out of them.
:return:
"""
currentScene = self.centralWidget().tabbedPane.getCurrentScene()
currentScene.clearSelection()
isolatedNodes = list(nx.isolates(currentScene.sceneGraph))
for node in currentScene.nodesDict:
if node not in isolatedNodes:
currentScene.nodesDict[node].setSelected(True)
def findShortestPath(self) -> None:
"""
Find the shortest path between two nodes, if it exists.
Exactly two nodes must be selected.
:return:
"""
currentScene = self.centralWidget().tabbedPane.getCurrentScene()
endPoints = [item.uid for item in currentScene.selectedItems()
if isinstance(item, BaseNode)]
if len(endPoints) != 2:
self.MESSAGEHANDLER.warning('Exactly two entities must be selected for the Shortest Path function to work.',
popUp=True)
return
currentCanvasGraph = currentScene.sceneGraph
try:
shortestPath = nx.shortest_path(currentCanvasGraph, endPoints[0], endPoints[1])
except nx.NetworkXNoPath:
try:
shortestPath = nx.shortest_path(currentCanvasGraph, endPoints[1], endPoints[0])
except nx.NetworkXNoPath:
shortestPath = None
if shortestPath is None:
messagePathNotFound = f'No path found connecting the selected nodes: {endPoints}'
self.setStatus(messagePathNotFound)
self.MESSAGEHANDLER.info(messagePathNotFound, popUp=True)
else:
currentScene.clearSelection()
for itemUID in currentScene.nodesDict:
if itemUID in shortestPath:
currentScene.nodesDict[itemUID].setSelected(True)
linksToSelect = list(zip(shortestPath, shortestPath[1:]))
for linkItem in [link for link in currentScene.items() if isinstance(link, BaseConnector)]:
if linkItem.uid.intersection(linksToSelect):
linkItem.setSelected(True)
self.setStatus('Shortest path found.')
def extractCycles(self) -> None:
"""
Find cycles in the graph, optionally involving selected nodes.
:return:
"""
currentScene = self.centralWidget().tabbedPane.getCurrentScene()
canvasName = currentScene.getSelfName()
endPoints = [item.uid for item in currentScene.selectedItems()
if isinstance(item, BaseNode)]
currentCanvasGraph = currentScene.sceneGraph
tempGraph = currentCanvasGraph.copy()
# Just in case.
tempGraph.remove_edges_from(nx.selfloop_edges(currentCanvasGraph))
newCyclesThread = ExtractCyclesThread(tempGraph, endPoints, canvasName)
newCyclesThread.cyclesSignal.connect(self.extractCyclesResultHandler)
self.MESSAGEHANDLER.info(f'Extracting Cycles from Canvas: {canvasName}')
newCyclesThread.start()
self.cycleExtractionThreads.append(newCyclesThread)
def extractCyclesResultHandler(self, results: list, canvasName: str) -> None:
if not results:
self.MESSAGEHANDLER.info(f'No Cycles in Canvas: {canvasName}')
else:
count = 0
while True:
newCanvasName = f'{canvasName} Cycles #{str(count)}'
if self.centralWidget().tabbedPane.addCanvas(newCanvasName):
break
else:
count += 1
nodesToAdd = results[0]
groupsToMake = results[1]
newCanvas = self.centralWidget().tabbedPane.canvasTabs[newCanvasName].scene()
for node in nodesToAdd:
newCanvas.addNodeProgrammatic(node)
entitiesAlreadyInGroups = set()
for count, group in enumerate(groupsToMake, start=1):
newGroup = set()
for groupEntity in group:
if groupEntity not in entitiesAlreadyInGroups:
newGroup.add(groupEntity)
entitiesAlreadyInGroups.add(groupEntity)
newCanvas.groupItemsProgrammatic(newGroup, f'Group {str(count)}')
newCanvas.rearrangeGraph('circular')
for cycleThread in list(self.cycleExtractionThreads):
if cycleThread.isFinished():
cycleThread.deleteLater()
self.cycleExtractionThreads.remove(cycleThread)
def findEntityOrLinkOnCanvas(self, regex: bool = False) -> None:
currentScene = self.centralWidget().tabbedPane.getCurrentScene()
currentUIDs = [item.uid for item in currentScene.items() if isinstance(item, (BaseNode, BaseConnector))]
entityPrimaryFields = {}
for uid in currentUIDs:
if isinstance(uid, str):
item = self.LENTDB.getEntity(uid)
if item is not None:
if not entityPrimaryFields.get(item[list(item)[1]]):
entityPrimaryFields[item[list(item)[1]]] = set()
entityPrimaryFields[item[list(item)[1]]].add(uid)
elif isinstance(uid, set):
for potentialLinkItem in uid:
item = self.LENTDB.getLink(potentialLinkItem)
if item is not None:
if not entityPrimaryFields.get(item['Resolution']):
entityPrimaryFields[item['Resolution']] = set()
entityPrimaryFields[item['Resolution']].add(str(uid))
findPrompt = FindEntityOnCanvasDialog(list(entityPrimaryFields), regex)
if findPrompt.exec():
findText = findPrompt.findInput.text()
if findText != "":
uidsToSelect = []
try:
if regex:
expression = re.compile(findText)
for item in entityPrimaryFields:
if expression.match(item):
# Add the elements in each index to uidsToSelect instead of the sets themselves.
uidsToSelect.extend(entityPrimaryFields[item])
else:
for item in entityPrimaryFields:
if item.startswith(findText):
# Add the elements in each index to uidsToSelect instead of the sets themselves.
uidsToSelect.extend(entityPrimaryFields[item])
currentScene.clearSelection()
for item in [linkOrEntity for linkOrEntity in currentScene.items()
if isinstance(linkOrEntity, (BaseNode, BaseConnector))]:
if str(item.uid) in uidsToSelect:
item.setSelected(True)
if len(uidsToSelect) == 1 and ',' not in uidsToSelect[0]:
self.centralWidget().tabbedPane.getCurrentView().centerViewportOnNode(uidsToSelect[0])
except re.error:
self.MESSAGEHANDLER.error('Invalid Regex Specified!', popUp=True, exc_info=False)
def findEntityOfTypeOnCanvas(self, regex: bool = False) -> None:
currentScene = self.centralWidget().tabbedPane.getCurrentScene()
currentUIDs = [item.uid for item in currentScene.items() if isinstance(item, BaseNode)]
# Keys: Entity Types. Values: dicts, where the key is the primary field and the value is the UID.
entityTypesOnCanvas = {}
for uid in currentUIDs:
item = self.LENTDB.getEntity(uid)
if item is not None:
itemType = item.get('Entity Type')
itemPrimaryFieldValue = item[self.RESOURCEHANDLER.getPrimaryFieldForEntityType(itemType)]
if itemType not in entityTypesOnCanvas:
entityTypesOnCanvas[itemType] = {}
if itemPrimaryFieldValue not in entityTypesOnCanvas[itemType]:
entityTypesOnCanvas[itemType][itemPrimaryFieldValue] = set()
entityTypesOnCanvas[itemType][itemPrimaryFieldValue].add(uid)
findPrompt = FindEntityOfTypeOnCanvasDialog(self, entityTypesOnCanvas, regex)
if findPrompt.exec():
findText = findPrompt.findInput.text()
findType = findPrompt.typeInput.currentText()
if findText != "":
uidsToSelect = []
try:
if regex:
expression = re.compile(findText)
for item in entityTypesOnCanvas[findType]:
if expression.match(item):
# Add the elements in each index to uidsToSelect instead of the sets themselves.
uidsToSelect.extend(entityTypesOnCanvas[findType][item])
else:
for item in entityTypesOnCanvas[findType]:
if item.startswith(findText):
# Add the elements in each index to uidsToSelect instead of the sets themselves.
uidsToSelect.extend(entityTypesOnCanvas[findType][item])
currentScene.clearSelection()
for item in [sceneEntity for sceneEntity in currentScene.items()
if isinstance(sceneEntity, BaseNode)]:
if item.uid in uidsToSelect:
item.setSelected(True)
if len(uidsToSelect) == 1:
self.centralWidget().tabbedPane.getCurrentView().centerViewportOnNode(uidsToSelect[0])
except re.error:
self.MESSAGEHANDLER.error('Invalid Regex Specified!', popUp=True, exc_info=False)
def findResolution(self) -> None:
# Dereference the entities and resolutions, just to be safe.
findDialog = ResolutionManager.FindResolutionDialog(self, list(self.RESOURCEHANDLER.getAllEntities()),
dict(self.RESOLUTIONMANAGER.resolutions))
findDialog.exec()
def mergeEntities(self) -> None:
"""
Show table of entities w/ primary fields, and incoming / outgoing links.
Let user choose which entity should be the primary one. For all the rest:
Get all links to and from them, and add them to the primary one.
Add their fields to the primary one, if they are not the same.
Delete them when done.
:return:
"""
entitiesToMerge = [self.LENTDB.getEntity(item.uid)
for item in self.centralWidget().tabbedPane.getCurrentScene().selectedItems()
if isinstance(item, BaseNode) and not isinstance(item, GroupNode)]
if len(entitiesToMerge) < 2:
self.MESSAGEHANDLER.info('Not enough valid entities to merge selected! Please choose at least two'
' non-Meta entities.', popUp=True)
return
mergeDialog = MergeEntitiesDialog(self, entitiesToMerge)
if mergeDialog.exec():
primaryEntityUID = mergeDialog.primaryEntityUID
primaryEntity = [entity for entity in entitiesToMerge if entity['uid'] == primaryEntityUID][0]
otherEntitiesUIDs = mergeDialog.otherEntitiesUIDs # First entity is written first. No overwrites.
allParentsPrimary = [link[0] for link in self.LENTDB.getIncomingLinks(primaryEntityUID)]
allChildrenPrimary = [link[1] for link in self.LENTDB.getOutgoingLinks(primaryEntityUID)]
# Do not want links pointing to itself.
allParentsPrimary.append(primaryEntityUID)
allChildrenPrimary.append(primaryEntityUID)
linksToAdd = []
for entityUID in otherEntitiesUIDs:
otherEntity = [otherEntity for otherEntity in entitiesToMerge if otherEntity['uid'] == entityUID][0]
# Do not include links to / from entities where such links exist already on the primary entity.
# Also do not include links to / from other entities that are being merged.
allIncomingLinks = [link for link in self.LENTDB.getIncomingLinks(entityUID)
if link[0] not in allParentsPrimary and
link[0] not in otherEntitiesUIDs]
allOutgoingLinks = [link for link in self.LENTDB.getOutgoingLinks(entityUID)
if link[1] not in allChildrenPrimary
and link[1] not in otherEntitiesUIDs]
for field in otherEntity:
# Check if field does not exist, or if it does, but contains 'None' value.
if str(primaryEntity.get(field)) == 'None':
primaryEntity[field] = otherEntity[field]
for incomingLink in allIncomingLinks:
linkJson = self.LENTDB.getLink(incomingLink)
linksToAdd.append([incomingLink[0], primaryEntity['uid'], linkJson['Resolution'],
linkJson['Notes']])
for outgoingLink in allOutgoingLinks:
linkJson = self.LENTDB.getLink(outgoingLink)
linksToAdd.append([primaryEntity['uid'], outgoingLink[1], linkJson['Resolution'],
linkJson['Notes']])
self.deleteSpecificEntity(entityUID)
self.centralWidget().tabbedPane.linkAddHelper(linksToAdd)
def splitEntity(self) -> None:
entityToSplit = [self.LENTDB.getEntity(item.uid)
for item in self.centralWidget().tabbedPane.getCurrentScene().selectedItems()
if isinstance(item, BaseNode)]
validEntityToSplit = [entity for entity in entityToSplit
if entity['Entity Type'] != 'EntityGroup']
if not validEntityToSplit:
self.MESSAGEHANDLER.info('No valid entities to split selected! Please choose at least one non-Meta entity.',
popUp=True)
return
elif len(validEntityToSplit) > 1:
self.MESSAGEHANDLER.info('Multiple entities selected. Please pick one valid entity to split.',
popUp=True)
return
# Continue only if a single entity is selected.
entityToSplit = validEntityToSplit[0]
entityToSplitPrimaryFieldKey = list(entityToSplit)[1]
entityToSplitUID = entityToSplit['uid']
splitDialog = SplitEntitiesDialog(self, entityToSplit)
if splitDialog.exec():
canvasTabs = self.centralWidget().tabbedPane.canvasTabs
allScenesWithNode = [canvasTabs[view].scene() for view in canvasTabs
if entityToSplitUID in canvasTabs[view].scene().sceneGraph.nodes()]
for newEntityWithLinks in splitDialog.splitEntitiesWithLinks:
newEntity = {entityToSplitPrimaryFieldKey: newEntityWithLinks[0]}
for field in entityToSplit:
if field not in ['uid', entityToSplitPrimaryFieldKey]:
newEntity[field] = entityToSplit[field]
newEntity = self.LENTDB.addEntity(newEntity)
for link in newEntityWithLinks[1]:
newLink = {field: link[field] for field in link}
if newLink['uid'][0] == entityToSplitUID:
newLink['uid'] = (newEntity['uid'], newLink['uid'][1])
else:
newLink['uid'] = (newLink['uid'][0], newEntity['uid'])
self.LENTDB.addLink(newLink)
for scene in allScenesWithNode:
scene.addNodeProgrammatic(newEntity['uid'])
self.deleteSpecificEntity(entityToSplitUID)
for scene in allScenesWithNode:
scene.rearrangeGraph()
def launchQueryWizard(self):
queryWizard = QueryBuilderWizard(self)
queryWizard.exec()
def handleGroupNodeUpdateAfterEntityDeletion(self, entityUID) -> None:
for canvas in self.centralWidget().tabbedPane.canvasTabs:
self.centralWidget().tabbedPane.canvasTabs[canvas].cleanDeletedNodeFromGroupsIfExists(entityUID)
def editProjectSettings(self) -> None:
settingsDialog = ProjectEditDialog(self.SETTINGS)
if settingsDialog.exec():
# Save new settings
newSettings = settingsDialog.newSettings
for key in newSettings:
newSettingValue = newSettings[key]
if newSettingValue[1]:
# Delete key
self.SETTINGS.removeKey(key)
elif newSettingValue[0] != '':
# Do not allow blank settings.
if key in ['Project/Resolution Result Grouping Threshold', 'Project/Number of Answers Returned',
'Project/Question Answering Retriever Value', 'Project/Question Answering Reader Value']:
with contextlib.suppress(ValueError):
int(newSettingValue[1])
self.SETTINGS.setValue(key, newSettingValue[0])
elif newSettingValue[0] in ['Copy', 'Symlink']:
self.SETTINGS.setValue(key, newSettingValue[0])
self.saveProject()
def editResolutionsSettings(self) -> None:
settingsDialog = ResolutionsEditDialog(self.SETTINGS)
if settingsDialog.exec():
# Save new settings
newSettings = settingsDialog.newSettings
for key in newSettings:
newSettingValue = newSettings[key]
if newSettingValue[1]:
# Delete key
self.SETTINGS.removeKey(key)
elif newSettingValue[0] != '':
# Do not allow blank settings.
self.SETTINGS.setValue(key, newSettingValue[0])
self.saveProject()
def editLogSettings(self) -> None:
settingsDialog = LoggingSettingsDialog(self.SETTINGS)
if settingsDialog.exec():
# Save new settings
newSettings = settingsDialog.newSettings
for key in newSettings:
newSettingValue = newSettings[key]
if newSettingValue[1]:
# Delete key
self.SETTINGS.removeKey(key)
elif newSettingValue[0] != '':
# Do not allow blank settings.
self.SETTINGS.setValue(key, newSettingValue[0])
self.MESSAGEHANDLER.setSeverityLevel(self.SETTINGS.value('Logging/Severity'))
self.MESSAGEHANDLER.changeLogfile(self.SETTINGS.value('Logging/Logfile'))
self.saveProject()
def editProgramSettings(self) -> None:
settingsDialog = ProgramEditDialog(self)
if settingsDialog.exec():
# Save new settings
newSettings = settingsDialog.newSettings
for key in newSettings:
newSettingValue = newSettings[key]
if newSettingValue[1]:
# Delete key
self.SETTINGS.removeKey(key)
elif newSettingValue[0] != '':
# Do not allow blank settings.
self.SETTINGS.setValue(key, newSettingValue[0])
self.saveProject()
def changeGraphics(self) -> None:
settingsDialog = GraphicsEditDialog(self.SETTINGS, self.RESOURCEHANDLER)
if settingsDialog.exec():
newSettings = settingsDialog.newSettings
with contextlib.suppress(ValueError):
etfVal = int(newSettings["ETF"])
self.centralWidget().tabbedPane.entityTextFont.setPointSize(etfVal)
self.SETTINGS.setGlobalValue("Program/Graphics/Entity Text Font Size", str(newSettings["ETF"]))
with contextlib.suppress(ValueError):
ltfVal = int(newSettings["LTF"])
self.centralWidget().tabbedPane.linkTextFont.setPointSize(ltfVal)
self.SETTINGS.setGlobalValue("Program/Graphics/Link Text Font Size", str(newSettings["LTF"]))
with contextlib.suppress(ValueError):
lfVal = int(newSettings["LF"])
self.centralWidget().tabbedPane.hideZoom = -lfVal
self.centralWidget().tabbedPane.updateCanvasHideZoom()
self.SETTINGS.setGlobalValue("Program/Graphics/Label Fade Scroll Distance", str(newSettings["LF"]))
etcVal = newSettings["ETC"]
newEtcColor = QtGui.QColor(etcVal)
if newEtcColor.isValid():
self.centralWidget().tabbedPane.entityTextBrush.setColor(newEtcColor)
self.SETTINGS.setGlobalValue("Program/Graphics/Entity Text Color", newEtcColor.name())
ltcVal = newSettings["LTC"]
newLtcColor = QtGui.QColor(ltcVal)
if newLtcColor.isValid():
self.centralWidget().tabbedPane.linkTextBrush.setColor(newLtcColor)
self.SETTINGS.setGlobalValue("Program/Graphics/Link Text Color", newLtcColor.name())
self.centralWidget().tabbedPane.updateCanvasGraphics()
self.saveProject()
def loadModules(self) -> None:
"""
Loads user-defined modules from the Modules folder in the installation directory.
:return:
"""
self.MODULEMANAGER.loadAllModules()
self.setStatus('Loaded Modules.')
def reloadModules(self, onlyUpdateDockbar: bool = False) -> None:
"""
Same as loadModules, except this one updates the GUI to show newly loaded entities and resolutions.
This is meant to be run after the application started, in case the user wants to load a module without
closing and reopening the application.
:return:
"""
if not onlyUpdateDockbar:
self.MODULEMANAGER.loadAllModules()
self.dockbarOne.existingEntitiesPalette.loadEntities()
self.dockbarOne.resolutionsPalette.loadAllResolutions()
self.dockbarOne.nodesPalette.loadEntities()
self.setStatus('Reloaded Modules.')
def setStatus(self, message: str, timeout: int = 5000) -> None:
"""
Show the message provided in the status bar.
Timeout dictates how long the message is shown, in milliseconds.
Translates the message automatically, no need to call 'tr' on the message parameter used.
"""
self.statusBar().showMessage(self.tr(message), timeout)
def notifyUser(self, message: str, title: str = "LinkScope Notification", beep: bool = True,
icon: QtGui.QIcon = None) -> None:
if icon is not None:
self.trayIcon.showMessage(self.tr(title), self.tr(message), icon)
else:
self.trayIcon.showMessage(self.tr(title), self.tr(message))
if beep:
application.beep()
def getPictureOfCanvas(self, canvasName: str, justViewport: bool = True,
transparentBackground: bool = False) -> Union[QtGui.QPicture, None]:
view = self.centralWidget().tabbedPane.canvasTabs.get(canvasName)
if view is None:
return None
return view.takePictureOfView(justViewport, transparentBackground)
def resetTimeline(self, graph: nx.DiGraph) -> None:
self.dockbarThree.timeWidget.resetTimeline(graph, True)
def updateTimeline(self, node, added: bool = True, updateGraph: bool = True) -> None:
self.dockbarThree.timeWidget.updateTimeline(node, added, updateGraph)
def timelineSelectMatchingEntities(self, timescale: list) -> None:
if not timescale: # i.e. if timescale == []
return
scene = self.centralWidget().tabbedPane.getCurrentScene()
scene.clearSelection()
for uid in scene.nodesDict:
if self.LENTDB.isNode(uid):
createdDate = datetime.fromisoformat(self.LENTDB.getEntity(uid)['Date Created'])
try:
year = timescale[0]
except IndexError:
year = None
try:
month = timescale[1]
except IndexError:
month = None
try:
day = timescale[2]
except IndexError:
day = None
try:
hour = timescale[3]