-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.py
4052 lines (2988 loc) · 189 KB
/
Main.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
"""
This file is part of the PROPheT tool.
http://mklab.iti.gr/project/prophet-ontology-populator
https://github.com/MKLab-ITI/prophet
Licensed under the Apache License, Version 2.0 (the "License").
You may use this file in compliance with the License.
For more details, see LICENCE file.
"""
__authors__ = 'Panagiotis Mitzias ([email protected]), Marina Riga ([email protected])'
import sys, time
# This line disables the creation of a log file from py2exe
sys.stderr = sys.stdout
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import *
import Functions
from PyQt4.QtGui import QTreeWidgetItem, QWizard
from rdflib import Graph, util
from rdflib.namespace import NamespaceManager
from shutil import copyfile
from subprocess import Popen
from os import remove, path
from modules.MainWindow import Ui_MainWindow
from modules.AddEndpoint import Ui_AddEndpoint
from modules.AddNamespace import Ui_AddNamespace
from modules.AddMyModel import Ui_AddMyModel
from modules.Preferences import Ui_Preferences
from modules.SearchByClassWizard import Ui_WizardSearchByClassName
from modules.SearchByInstanceWizard import Ui_WizardSearchByInstanceName
from modules.EnrichInstanceWizard import Ui_WizardEnrichInstance
from modules.SearchByInstanceLabelWizard import Ui_WizardSearchByInstanceLabel
from modules.About import Ui_DialogAbout
from modules.UpdatesDownloader import Ui_UpdatesDownloader
import modules.main_window_resources_rc
import modules.preferences_resources_rc
import modules.search_by_class_wizard_resources_rc
import modules.search_by_existing_instance_wizard_resources_rc
import modules.search_by_instance_label_wizard_resources_rc
import modules.enrich_instance_wizard_resources_rc
import modules.messagebox_resources_rc
class Main(QtGui.QMainWindow):
graph = Graph()
myModelName = ''
changesMadeToModel = False
# Main window constructor
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# MAKE CONNECTIONS
self.ui.actionSelect_endpoint.triggered.connect(self.showEndpointPreferences)
self.ui.actionToolBarSelect_endpoint.triggered.connect(self.showEndpointPreferences)
self.ui.actionView_Log.triggered.connect(self.showLog)
self.ui.actionToolBarLog.triggered.connect(self.showLog)
self.ui.actionPreferences.triggered.connect(self.showDialogPreferences)
self.ui.actionPreferencesToolBar.triggered.connect(self.showDialogPreferences)
self.ui.actionEdit_namespaces.triggered.connect(self.showNamespacesPreferences)
self.ui.actionToolBarNamespaces.triggered.connect(self.showNamespacesPreferences)
self.ui.actionLoad_model.triggered.connect(self.showMyModelsPreferences)
self.ui.actionToolBarLoad_my_model.triggered.connect(self.showMyModelsPreferences)
self.ui.actionEdit_mapping.triggered.connect(self.showMappingPreferences)
self.ui.actionToolBarMapping.triggered.connect(self.showMappingPreferences)
self.ui.actionExit.triggered.connect(self.close)
self.ui.actionSearch_by_class_name.triggered.connect(self.showSearchByClassWizard)
self.ui.actionSearch_endpoint_by_class_name.triggered.connect(self.showSearchByClassWizard)
self.ui.actionSearch_by_existing_instance.triggered.connect(self.showSearchByInstanceWizard)
self.ui.actionSearch_endpoint_by_existing_instance.triggered.connect(self.showSearchByInstanceWizard)
self.ui.actionSearch_by_instance_label.triggered.connect(self.showSearchByInstanceLabelWizard)
self.ui.actionSearch_endpoint_by_instance_label.triggered.connect(self.showSearchByInstanceLabelWizard)
self.ui.actionEnrich_instance.triggered.connect(self.showEnrichInstanceWizard)
self.ui.actionEnrich_Instance_2.triggered.connect(self.showEnrichInstanceWizard)
self.ui.actionExport_to_file.triggered.connect(self.showFileDialogSaveGraph)
self.ui.actionExport_to_file_2.triggered.connect(self.showFileDialogSaveGraph)
self.ui.actionDatabase_actions.triggered.connect(self.showDatabasePreferences)
self.ui.actionDatabase_actions_2.triggered.connect(self.showDatabasePreferences)
self.ui.actionAbout.triggered.connect(self.showAboutDialog)
self.ui.actionOnline_documentation.triggered.connect(lambda: Functions.openLinkToBrowser('http://mklab.iti.gr/project/prophet-ontology-populator'))
self.ui.actionQuick_presentation.triggered.connect(lambda: Functions.openLinkToBrowser('https://www.youtube.com/embed/9oLBwkR-GOc'))
self.ui.actionCheck_for_updates.triggered.connect(self.checkForUpdates)
self.ui.lineEditSearchMyModel.textChanged.connect(lambda: Functions.searchTree(self.ui.lineEditSearchMyModel, self.ui.treeWidgetMyModel))
self.ui.lineEditSearchMyModel.returnPressed.connect(lambda: Functions.searchAndGiveFocusToTree(self.ui.lineEditSearchMyModel, self.ui.treeWidgetMyModel))
self.ui.btnExpandAll.clicked.connect(self.ui.treeWidgetMyModel.expandAll)
self.ui.btnCollapseAll.clicked.connect(self.ui.treeWidgetMyModel.collapseAll)
# Context Menu connections
self.ui.treeWidgetMyModel.customContextMenuRequested.connect(lambda: Functions.openContextMenuInTree(self.ui.treeWidgetMyModel, self, self.getGraph()))
# Key shortcuts
QtGui.QShortcut(QtGui.QKeySequence('Ctrl+F'), self).activated.connect(self.ui.lineEditSearchMyModel.setFocus)
# Threads
self.checkInternetConnectionThread = CheckInternetConnectionThread(self)
QtCore.QObject.connect(self.checkInternetConnectionThread, QtCore.SIGNAL("checkIfInternetConnectionIsOn"), self.checkIfInternetConnectionIsOn)
self.checkInternetConnectionThread.start()
# If check for updates is enabled
if Functions.getSettingFromDB('auto_update') == 1:
self.checkForUpdates()
# CONSTRUCT UI ELEMENTS
itemEndpoint = QtGui.QTableWidgetItem(Functions.getEndpointName())
itemEndpoint.setTextAlignment(QtCore.Qt.AlignHCenter)
itemEndpoint.setTextColor(QtGui.QColor(55, 122, 151)) #rgb numbers of hex #377a97 color
boldFont = QFont(); boldFont.setBold(True)
itemEndpoint.setFont(boldFont)
self.ui.tableWidgetMyModelStats.setItem(0, 0, itemEndpoint)
# Icons
self.class_icon = QtGui.QIcon(':/images/class.png')
self.instance_icon = QtGui.QIcon(':/images/instance.png')
self.property_icon = QtGui.QIcon(':/images/property.png')
self.value_icon = QtGui.QIcon(':/images/value.png')
self.annotation_icon = QtGui.QIcon(':/images/annotation.png')
def getGraph(self):
return self.graph
def setGraph(self, newGraph):
self.graph = newGraph
def getMyModelName(self):
return self.myModelName
def setMyModelName(self, newName):
self.myModelName = newName
def getChangesMadeToModel(self):
return self.changesMadeToModel
def setChangesMadeToModel(self, bool_to_set):
self.changesMadeToModel = bool_to_set
def showSearchByClassWizard(self):
# Check if user has loaded a my_model yet
if self.getMyModelName() == '':
# Show message box with error
QtGui.QMessageBox.critical(self, 'Error', "Please load a model first.", QtGui.QMessageBox.Close)
self.showMyModelsPreferences()
return
wizard = SearchByClassWizard()
wizard.exec_()
# Reload main graph tree and stats
self.loadMyModelToTree(self.getGraph(), self.getMyModelName())
self.loadMyModelStatsToTable(self.getGraph(), self.getMyModelName())
def showSearchByInstanceWizard(self):
# Check if user has loaded a my_model yet
if self.getMyModelName() == '':
# Show message box with error
QtGui.QMessageBox.critical(self, 'Error', "Please load a model first.", QtGui.QMessageBox.Close)
self.showMyModelsPreferences()
return
# If there are no instances in the graph, stop
if len(Functions.getAllInstancesFromGraph(self.getGraph())) == 0:
# Show message box with error
QtGui.QMessageBox.critical(self, 'Error', "Model <span style='font-size:9pt; font-weight:550; color:#58ae82;'>" + self.getMyModelName() + "</span> does not have any instances.", QtGui.QMessageBox.Close)
return
wizard = SearchByInstanceName()
wizard.exec_()
# Reload main graph tree and stats
self.loadMyModelToTree(self.getGraph(), self.getMyModelName())
self.loadMyModelStatsToTable(self.getGraph(), self.getMyModelName())
def showSearchByInstanceLabelWizard(self):
# Check if user has loaded a my_model yet
if self.getMyModelName() == '':
# Show message box with error
QtGui.QMessageBox.critical(self, 'Error', "Please load a model first.", QtGui.QMessageBox.Close)
self.showMyModelsPreferences()
return
wizard = SearchByInstanceLabel()
wizard.exec_()
# Reload main graph tree and stats
self.loadMyModelToTree(self.getGraph(), self.getMyModelName())
self.loadMyModelStatsToTable(self.getGraph(), self.getMyModelName())
def showEnrichInstanceWizard(self):
# Check if user has loaded a my_model yet
if self.getMyModelName() == '':
# Show message box with error
QtGui.QMessageBox.critical(self, 'Error', "Please load a model first.", QtGui.QMessageBox.Close)
self.showMyModelsPreferences()
return
# If there are no instances in the graph, stop
if len(Functions.getAllInstancesFromGraph(self.getGraph())) == 0:
# Show message box with error)
QtGui.QMessageBox.critical(self, 'Error', "Model <span style='font-size:9pt; font-weight:550; color:#58ae82;'>" + self.getMyModelName() + "</span> does not have any instances.", QtGui.QMessageBox.Close)
return
wizard = EnrichInstance()
wizard.exec_()
# Reload main graph tree and stats
self.loadMyModelToTree(self.getGraph(), self.getMyModelName())
self.loadMyModelStatsToTable(self.getGraph(), self.getMyModelName())
def showMyModelsPreferences(self):
dialog = PreferencesDialog(1)
dialog.exec_()
del dialog
# Reload Graph area
self.loadMyModelToTree(self.getGraph(), self.getMyModelName())
def showEndpointPreferences(self):
dialog = PreferencesDialog(2)
dialog.exec_()
del dialog
# Reload Graph area
self.loadMyModelToTree(self.getGraph(), self.getMyModelName())
def showLog(self):
dialog = PreferencesDialog(5)
dialog.exec_()
del dialog
# Reload Graph area
self.loadMyModelToTree(self.getGraph(), self.getMyModelName())
def showNamespacesPreferences(self):
dialog = PreferencesDialog(3)
dialog.exec_()
del dialog
# Reload Graph area
self.loadMyModelToTree(self.getGraph(), self.getMyModelName())
def showMappingPreferences(self):
dialog = PreferencesDialog(4)
dialog.exec_()
del dialog
# Reload Graph area
self.loadMyModelToTree(self.getGraph(), self.getMyModelName())
def showDialogPreferences(self):
dialog = PreferencesDialog(0)
dialog.exec_()
del dialog
# Reload Graph area
self.loadMyModelToTree(self.getGraph(), self.getMyModelName())
def showDatabasePreferences(self):
dialog = PreferencesDialog(6)
dialog.exec_()
del dialog
# Reload Graph area
self.loadMyModelToTree(self.getGraph(), self.getMyModelName())
def showAboutDialog(self):
dialog = AboutDialog()
dialog.exec_()
del dialog
def loadMyModelToTree(self, my_graph, myModelName):
# Clear Tree
self.ui.treeWidgetMyModel.clear()
# Clear search lineedit
self.ui.lineEditSearchMyModel.clear()
# Get list of classes for this graph
classes = Functions.getAllClassesFromGraph(my_graph)
# Fill the tree with my graph
# For each class
for clas in classes:
# Initialize new parent for QTree
class_level = QTreeWidgetItem()
clas_x = Functions.getPhraseWithPrefix(clas)
class_level.setText(0, clas_x)
class_level.setToolTip(0, "<b>Class:</b><br> " + clas_x)
# Set icon
class_level.setIcon(0, self.class_icon)
# Get all instances of class
class_instances = Functions.getInstancesOfClassFromGraph(my_graph, clas)
# For each instance
for instance in class_instances:
# Initialize new parent for QTree
instance_level = QTreeWidgetItem()
instance_x = Functions.getPhraseWithPrefix(instance)
instance_level.setText(0, instance_x)
instance_level.setToolTip(0, "<b>Instance:</b><br> " + instance_x)
# Set icon
instance_level.setIcon(0, self.instance_icon)
class_level.addChild(instance_level)
instance_properties = Functions.getDataPropertiesOfInstanceFromGraph(my_graph, instance)
for instance_property in instance_properties:
property_level = QTreeWidgetItem()
property_x = Functions.getPhraseWithPrefix(instance_property[0])
value_x = instance_property[1].toPython()
#property_level.setText(0, "Property: " + property_x + " Value: " + value_x)
property_level.setText(0, property_x)
property_level.setText(1, value_x)
property_level.setToolTip(0, "<b>Property:</b><br> " + property_x + " <br><b>Value:</b><br> " + value_x)
property_level.setToolTip(1, "<b>Property:</b><br> " + property_x + " <br><b>Value:</b><br> " + value_x)
# Set icons
property_level.setIcon(0, self.property_icon)
property_level.setIcon(1, self.value_icon)
instance_level.addChild(property_level)
# Get sameAs values and add them to tree
# allSameAsValues = Functions.getSameAsValueForInstanceFromGraph(my_graph, instance)
allSameAsValues = Functions.getSameAsSeeAlsoValueForInstanceFromGraph(my_graph, instance) # result is a list of ['predicate', 'instance']
for sameAsValue in allSameAsValues:
property_level = QTreeWidgetItem()
# property_x = Functions.getPhraseWithPrefix('http://www.w3.org/2002/07/owl#sameAs')
property_x = Functions.getPhraseWithPrefix(sameAsValue[0])
# value_x = Functions.getPhraseWithPrefix(sameAsValue)
value_x = Functions.getPhraseWithPrefix(sameAsValue[1])
# property_level.setText(0, "Property: " + property_x + " Value: " + value_x)
property_level.setText(0, property_x)
property_level.setText(1, value_x)
property_level.setToolTip(0, "<b>Property:</b><br> " + property_x + " <br><b>Value:</b><br> " + value_x)
property_level.setToolTip(1, "<b>Property:</b><br> " + property_x + " <br><b>Value:</b><br> " + value_x)
# Set icons
property_level.setIcon(0, self.annotation_icon)
property_level.setIcon(1, self.value_icon)
instance_level.addChild(property_level)
# Get rdfs:label values and add them to tree
allLabelValues = Functions.getLabelsOfInstanceFromGraph(my_graph, instance)
for labelValue in allLabelValues:
property_level = QTreeWidgetItem()
property_x = Functions.getPhraseWithPrefix('http://www.w3.org/2000/01/rdf-schema#label')
value_x = labelValue
property_level.setText(0, property_x)
property_level.setText(1, value_x)
property_level.setToolTip(0, "<b>Property:</b><br> " + property_x + " <br><b>Value:</b><br> " + value_x)
property_level.setToolTip(1, "<b>Property:</b><br> " + property_x + " <br><b>Value:</b><br> " + value_x)
# Set icons
property_level.setIcon(0, self.annotation_icon)
property_level.setIcon(1, self.value_icon)
instance_level.addChild(property_level)
self.ui.treeWidgetMyModel.insertTopLevelItem(0, class_level)
self.ui.treeWidgetMyModel.sortItems(0, 0) # sortItems(column, Qt.AscendingOrder)
self.ui.treeWidgetMyModel.expandAll()
# Make column 0 wide enough to fit contents
self.ui.treeWidgetMyModel.resizeColumnToContents(0)
def loadMyModelStatsToTable(self, my_graph, myModelName):
# Clear stats table
self.ui.tableWidgetMyModelStats.clearContents()
# Get list of classes for this graph
classes = Functions.getAllClassesFromGraph(my_graph)
# Get list of instances from graph
instances = Functions.getAllInstancesFromGraph(my_graph)
# Get all object properties from graph
dataProperties = Functions.getAllDataPropertiesFromGraph(my_graph)
# Complete stats table
itemEndpoint = QtGui.QTableWidgetItem(Functions.getEndpointName())
itemEndpoint.setTextAlignment(QtCore.Qt.AlignHCenter)
itemEndpoint.setTextColor(QtGui.QColor(55, 122, 151)) #rgb numbers of hex #377a97 color
boldFont = QFont(); boldFont.setBold(True)
itemEndpoint.setFont(boldFont)
self.ui.tableWidgetMyModelStats.setItem(0, 0, itemEndpoint)
itemMyModel = QtGui.QTableWidgetItem(myModelName)
itemMyModel.setTextAlignment(QtCore.Qt.AlignHCenter)
itemMyModel.setTextColor(QtGui.QColor(88, 174, 130)) #rgb numbers of hex #58ae82 color
itemMyModel.setFont(boldFont)
self.ui.tableWidgetMyModelStats.setItem(0, 1, itemMyModel)
itemClasses = QtGui.QTableWidgetItem(str(len(classes)))
itemClasses.setTextAlignment(QtCore.Qt.AlignHCenter)
self.ui.tableWidgetMyModelStats.setItem(0, 2, itemClasses)
itemInstances = QtGui.QTableWidgetItem(str(len(instances)))
itemInstances.setTextAlignment(QtCore.Qt.AlignHCenter)
self.ui.tableWidgetMyModelStats.setItem(0, 3, itemInstances)
itemDataProperties = QtGui.QTableWidgetItem(str(len(dataProperties)))
itemDataProperties.setTextAlignment(QtCore.Qt.AlignHCenter)
self.ui.tableWidgetMyModelStats.setItem(0, 4, itemDataProperties)
def toggleAllFunctionsButtons(self, status):
self.ui.actionExport_to_file.setEnabled(status)
self.ui.actionExport_to_file_2.setEnabled(status)
self.ui.actionEnrich_instance.setEnabled(status)
self.ui.actionEnrich_Instance_2.setEnabled(status)
self.ui.actionSearch_by_class_name.setEnabled(status)
self.ui.actionSearch_endpoint_by_class_name.setEnabled(status)
self.ui.actionSearch_by_existing_instance.setEnabled(status)
self.ui.actionSearch_endpoint_by_existing_instance.setEnabled(status)
self.ui.actionSearch_by_instance_label.setEnabled(status)
self.ui.actionSearch_endpoint_by_instance_label.setEnabled(status)
self.ui.lineEditSearchMyModel.setEnabled(status)
self.ui.btnExpandAll.setEnabled(status)
self.ui.btnCollapseAll.setEnabled(status)
def toggleEndpointRelatedFunctionsButtons(self, status):
self.ui.actionEnrich_instance.setEnabled(status)
self.ui.actionEnrich_Instance_2.setEnabled(status)
self.ui.actionSearch_by_class_name.setEnabled(status)
self.ui.actionSearch_endpoint_by_class_name.setEnabled(status)
self.ui.actionSearch_by_existing_instance.setEnabled(status)
self.ui.actionSearch_endpoint_by_existing_instance.setEnabled(status)
self.ui.actionSearch_by_instance_label.setEnabled(status)
self.ui.actionSearch_endpoint_by_instance_label.setEnabled(status)
def showFileDialogSaveGraph(self):
# if there is no graph to save
if (self.getGraph()).__len__() == 0:
# Show message box with error
QtGui.QMessageBox.critical(self, 'Error', "There is no model to export.", QtGui.QMessageBox.Close)
else:
fileDialog = QtGui.QFileDialog()
fileNameAndPath = fileDialog.getSaveFileName(self, "Export Graph to file", "", '*.owl;;*.rdf;;*.ttl;;*.nt;;*.n3')
try:
str(fileNameAndPath)
except UnicodeEncodeError:
QtGui.QMessageBox.critical(self, 'Error', "Export Graph to file failed.\nPlease select a filename and path with latin characters.", QtGui.QMessageBox.Close)
return
# If user selected a file
if fileNameAndPath != "":
# Define a file inside our directory to export
tempLocalFile = str('temp_export_file.' + fileNameAndPath.split('.')[-1])
tempLocalFileAbsolutePath = path.abspath(tempLocalFile)
# Serialize graph to temp file
(window.getGraph()).serialize(tempLocalFileAbsolutePath, util.guess_format(tempLocalFileAbsolutePath))
# Copy temp file to selected fileNameAndPath
copyfile(tempLocalFile, str(fileNameAndPath))
# Delete temp file
remove(tempLocalFile)
# Prepare strings for message
fileName = str(fileNameAndPath).split("/")[-1]
filePath = '/'.join(str(fileNameAndPath).split('/')[:-1])
QtGui.QMessageBox.information(self, 'Success', "File " + fileName + "\n was successfully saved in\n " + filePath + ".", QtGui.QMessageBox.Close)
# Log
Functions.addEntryToLog("Model " + self.getMyModelName() + " was exported to " + fileNameAndPath)
# Change changesMadeToModel boolean to false, since all changes are considered saved
self.setChangesMadeToModel(False)
def checkIfInternetConnectionIsOn(self):
if Functions.checkIfInternetConnectionIsOn() == False:
self.ui.statusbar.showMessage("No Internet connection. Please check your network settings.")
self.toggleEndpointRelatedFunctionsButtons(status=False)
else:
self.ui.statusbar.showMessage("", 1)
# If a my model has been loaded earlier
if self.getMyModelName() != '':
self.toggleEndpointRelatedFunctionsButtons(status=True)
def closeEvent(self, event):
# If previous model not saved, prompt for export
if self.getChangesMadeToModel() == True:
# Show message box with prompt
reply = QtGui.QMessageBox.question(self, 'Are you sure?', "Model <span style='font-size:9pt; font-weight:550; color:#58ae82;'>" + window.getMyModelName() +
"</span> was changed but not saved. <br>\n Do you want to export it now?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No, QMessageBox.Cancel)
if reply == QMessageBox.Yes:
window.showFileDialogSaveGraph()
event.ignore()
elif reply == QMessageBox.No:
self.close()
elif reply == QMessageBox.Cancel:
event.ignore()
def checkForUpdates(self):
self.checkForUpdatesThread = CheckForUpdates(self)
QtCore.QObject.connect(self.checkForUpdatesThread, QtCore.SIGNAL("updateFound"), self.runUpdate)
self.checkForUpdatesThread.start()
def runUpdate(self):
# Show message box with prompt
reply = QtGui.QMessageBox.information(self, 'Update available', "A newer version of PROPheT was found.\nWould you like to "
"update now?\n(PROPheT will restart automatically)", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
# If user declines update
if reply == QMessageBox.No:
return
# If user accepts update
elif reply == QMessageBox.Yes:
# TODO: Get this code and put to wizards exec_ so that they do not block main window
# setWindowModality(QtCore.Qt.NonModal)
# Show UpdateDownloader
dialog = UpdateDownloader()
# dialog.exec_()
# dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
dialog.setModal(True)
dialog.show()
dialog.downloadFilesToUpdate()
# If download succeeded
if dialog.downloadSucceeded == True:
# Run Updater.exe
DETACHED_PROCESS = 0x00000008
p = Popen("Updater.exe", shell=False, stdin=None, stdout=None, stderr=None, close_fds=True, creationflags=DETACHED_PROCESS)
# Close PROPheT
self.close()
class CheckInternetConnectionThread(QtCore.QThread):
def __init__(self, parent):
QtCore.QThread.__init__(self, parent)
def run(self):
while True:
self.emit(QtCore.SIGNAL("checkIfInternetConnectionIsOn"))
time.sleep(5)
# About dialog
class AboutDialog(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
self.ui = Ui_DialogAbout()
self.ui.setupUi(self)
self.ui.btnOK.clicked.connect(self.close)
# Preferences implementation
class PreferencesDialog(QtGui.QDialog):
def __init__(self, tabIndex):
QtGui.QDialog.__init__(self)
self.ui = Ui_Preferences()
self.ui.setupUi(self)
# MAKE CONNECTIONS
self.ui.btnSelectEndpoint.clicked.connect(self.btnSelectEndpoint_clicked)
self.ui.tableWidgetKnownEndpoints.itemDoubleClicked.connect(self.endpointDoubleClicked)
self.ui.tableWidgetKnownEndpoints.itemSelectionChanged.connect(self.endpointSelectionChanged)
self.ui.btnAddEndpoint.clicked.connect(self.showDialogAddEndpoint)
self.ui.btnDeleteEndpoint.clicked.connect(self.deleteEndpoint)
self.ui.btnClearLog.clicked.connect(self.clearLogEntries)
self.ui.btnAddNamespace.clicked.connect(self.showDialogAddNamespaces)
self.ui.btnDeleteNamespace.clicked.connect(self.deleteNamespace)
self.ui.btnRestoreDefaultNamespaces.clicked.connect(self.restoreDefaultNamespaces)
self.ui.btnAddMyModel.clicked.connect(self.showDialogAddMyModel)
self.ui.btnDeleteMyModel.clicked.connect(self.deleteMyModel)
self.ui.btnLoadMyModel.clicked.connect(self.loadMyModel)
self.ui.tableWidgetMyModels.itemDoubleClicked.connect(lambda: self.ui.tableWidgetMyModels.editItem(self.ui.tableWidgetMyModels.currentItem()))
self.ui.tableWidgetKnownNamespaces.itemDoubleClicked.connect(lambda: self.ui.tableWidgetKnownNamespaces.editItem(self.ui.tableWidgetKnownNamespaces.currentItem()))
self.ui.btnDeleteMapping.clicked.connect(self.deleteMapping)
self.ui.btnDeleteAllMappings.clicked.connect(self.deleteAllMappings)
self.ui.btnSaveChangesInGeneralTab.clicked.connect(self.saveSettingsFromGeneralTab)
self.ui.btnClose.clicked.connect(self.close)
self.ui.btnExportDatabase.clicked.connect(self.exportDatabase)
self.ui.btnImportDatabase.clicked.connect(self.importDatabase)
self.ui.btnResetToDefaultDatabase.clicked.connect(self.restoreDatabaseToDefault)
self.ui.tableWidgetKnownNamespaces.cellChanged.connect(self.editNamespaceInDB)
self.ui.tableWidgetKnownEndpoints.cellChanged.connect(self.editEndpointInDB)
self.ui.tableWidgetMyModels.cellChanged.connect(self.editMyModelInDB)
# Show the requested tab
self.tabIndex = tabIndex
self.ui.tabWidgetPreferences.setCurrentIndex(self.tabIndex)
# Context Menu connections
self.ui.tableWidgetKnownNamespaces.customContextMenuRequested.connect(self.openContextMenuNamespacesTable)
self.ui.tableWidgetKnownEndpoints.customContextMenuRequested.connect(self.openContextMenuEndpointsTable)
self.ui.tableWidgetMyModels.customContextMenuRequested.connect(self.openContextMenuMyModelsTable)
self.ui.tableWidgetKnownMappings.customContextMenuRequested.connect(self.openContextMenuMappingsTable)
# Load tables
self.loadAllTablesInPreferences()
def loadAllTablesInPreferences(self):
# Load EM instances limit from DB
self.loadEMInstancesLimit()
# Load sameAs option from DB
self.loadSameAsOptionSetting()
# Load owl:equivalentProperty option from DB
self.loadEquivalentPropertyOptionSetting()
# Load rdfs:label option from DB
self.loadLabelOptionSetting()
# Load Check for updates option from DB
self.loadCheckForUpdatesOptionSetting()
# Load endpoint list from DB to table
self.loadEndpointsToTable()
# Load log entries from DB to table
self.loadLogEntriesToTable()
# Load namespaces from DB to table
self.loadNamespacesToTable()
# Load my models from DB to table
self.loadMyModelsToTable()
# Load mappings from DB to table
self.loadMappingsToTable()
# Load database stats from DB to table
self.loadDatabaseStatisticsToTable()
# Make my model progressbar invisible
self.ui.progressBarLoad.setVisible(False)
# GENERAL TAB FUNCTIONS
def loadEMInstancesLimit(self):
self.ui.spinBoxEMInstancesLimit.setValue(int(Functions.getSettingFromDB('em_instances_limit')))
def saveSettingsFromGeneralTab(self):
# Set instances limit setting to DB
Functions.setSettingToDB('em_instances_limit', self.ui.spinBoxEMInstancesLimit.value())
# Set sameAs option to DB
Functions.setSettingToDB('sameas_option', str(self.ui.comboBoxSameAsOption.currentText()))
# Set owl:equivalentProperty option to DB
if self.ui.checkBoxPropertyEquivalentToOption.isChecked():
Functions.setSettingToDB('equivalent_property_option', 1)
else:
Functions.setSettingToDB('equivalent_property_option', 0)
# Set rdfs:label option to DB
if self.ui.checkBoxLabelOption.isChecked():
Functions.setSettingToDB('label_option', 1)
else:
Functions.setSettingToDB('label_option', 0)
# Set Check for updates option to DB
if self.ui.checkBoxCheckForUpdatesAtStartupOption.isChecked():
Functions.setSettingToDB('auto_update', 1)
else:
Functions.setSettingToDB('auto_update', 0)
# Show message box with success
QtGui.QMessageBox.information(self, 'Success', "Settings were saved successfully.", QtGui.QMessageBox.Close)
#Log
Functions.addEntryToLog("General settings were saved successfully")
# Load log entries to table
self.loadLogEntriesToTable()
def loadSameAsOptionSetting(self):
self.ui.comboBoxSameAsOption.setCurrentIndex(self.ui.comboBoxSameAsOption.findText(Functions.getSettingFromDB('sameas_option')))
def loadEquivalentPropertyOptionSetting(self):
if Functions.getSettingFromDB('equivalent_property_option') == 1:
self.ui.checkBoxPropertyEquivalentToOption.setChecked(True)
else:
self.ui.checkBoxPropertyEquivalentToOption.setChecked(False)
def loadLabelOptionSetting(self):
if Functions.getSettingFromDB('label_option') == 1:
self.ui.checkBoxLabelOption.setChecked(True)
else:
self.ui.checkBoxLabelOption.setChecked(False)
def loadCheckForUpdatesOptionSetting(self):
if Functions.getSettingFromDB('auto_update') == 1:
self.ui.checkBoxCheckForUpdatesAtStartupOption.setChecked(True)
else:
self.ui.checkBoxCheckForUpdatesAtStartupOption.setChecked(False)
# ENDPOINTS TAB FUNCTIONS
def showDialogAddEndpoint(self):
dialog = AddEndpointDialog()
dialog.exec_()
del dialog
# Reload all tables in preferences
self.loadAllTablesInPreferences()
def loadEndpointsToTable(self):
# Clear table
self.ui.tableWidgetKnownEndpoints.setRowCount(0)
# Load known endpoints from DB
endpoints = Functions.getListOfEndpointsFromDB()
# Get the currently selected endpoint
currentEndpointName = Functions.getEndpointName()
# Put the to table
for endpoint in endpoints:
# Add an empty row to the table
rowPosition = self.ui.tableWidgetKnownEndpoints.rowCount()
self.ui.tableWidgetKnownEndpoints.insertRow(rowPosition)
name_item = QtGui.QTableWidgetItem(endpoint[0])
uri_item = QtGui.QTableWidgetItem(endpoint[1])
if endpoint[0] == currentEndpointName:
name_item.setToolTip('Currently selected')
uri_item.setToolTip('Currently selected')
name_item.setIcon(QtGui.QIcon(':/images/on.png'))
# Insert the endpoint
self.ui.tableWidgetKnownEndpoints.setItem(rowPosition, 0, name_item)
self.ui.tableWidgetKnownEndpoints.setItem(rowPosition, 1, uri_item)
# Highlight the currently selected endpoint
for i in range(self.ui.tableWidgetKnownEndpoints.rowCount()):
if self.ui.tableWidgetKnownEndpoints.item(i, 0).text() == currentEndpointName:
self.ui.tableWidgetKnownEndpoints.selectRow(i)
def deleteEndpoint(self):
# If no selection has been made
if self.ui.tableWidgetKnownEndpoints.currentRow() == -1:
# Show message box with error
QtGui.QMessageBox.critical(self, 'Error', "Please select an endpoint from the list.", QtGui.QMessageBox.Close)
return
# Take the endpoint selected from table
endpointName = self.ui.tableWidgetKnownEndpoints.item(self.ui.tableWidgetKnownEndpoints.currentRow(), 0).text()
endpointUrl = self.ui.tableWidgetKnownEndpoints.item(self.ui.tableWidgetKnownEndpoints.currentRow(), 1).text()
# If the desired endpoint is the current in settings
if endpointName == Functions.getCurrentEndpointName():
# Show message box with error
QtGui.QMessageBox.critical(self, 'Error', "This endpoint is currently in use.\nCould not be deleted.", QtGui.QMessageBox.Close)
return
# Or is DBpedia
elif endpointUrl == 'http://dbpedia.org/sparql':
# Show message box with error
QtGui.QMessageBox.critical(self, 'Error', "This endpoint cannot be deleted.", QtGui.QMessageBox.Close)
return
Functions.deleteEndpointFromDatabase(endpointName)
# Log
Functions.addEntryToLog("Endpoint " + endpointName + " was deleted")
# Reload all tables in preferences
self.loadAllTablesInPreferences()
def endpointDoubleClicked(self):
selected_name = self.ui.tableWidgetKnownEndpoints.item(self.ui.tableWidgetKnownEndpoints.currentRow(), 0).text()
# If the right-clicked name is the current name, editing should not be allowed
if selected_name == Functions.getEndpointName() or selected_name == 'DBpedia':
return
self.ui.tableWidgetKnownEndpoints.editItem(self.ui.tableWidgetKnownEndpoints.currentItem())
def endpointSelectionChanged(self):
try:
selected_name = self.ui.tableWidgetKnownEndpoints.item(self.ui.tableWidgetKnownEndpoints.currentRow(), 0).text()
current_endpoint = Functions.getEndpointName()
if selected_name == 'DBpedia' or selected_name == current_endpoint:
self.ui.btnDeleteEndpoint.setEnabled(False)
else:
self.ui.btnDeleteEndpoint.setEnabled(True)
if selected_name == current_endpoint:
self.ui.btnSelectEndpoint.setEnabled(False)
else:
self.ui.btnSelectEndpoint.setEnabled(True)
except:
pass
def btnSelectEndpoint_clicked(self):
# If no selection has been made
if self.ui.tableWidgetKnownEndpoints.currentRow() == -1:
# Show message box with error
QtGui.QMessageBox.critical(self, 'Error', "Please select an endpoint from the list.", QtGui.QMessageBox.Close)
return
# TODO: Log if this is True
self.setSelectedEndpointURLAsSetting()
# Update table of stats in main window
itemEndpoint = QtGui.QTableWidgetItem(Functions.getEndpointName())
itemEndpoint.setTextAlignment(QtCore.Qt.AlignHCenter)
itemEndpoint.setTextColor(QtGui.QColor(55, 122, 151)) #rgb numbers of hex #377a97 color
boldFont = QFont(); boldFont.setBold(True)
itemEndpoint.setFont(boldFont)
window.ui.tableWidgetMyModelStats.setItem(0, 0, itemEndpoint)
# Reload all tables in preferences
self.loadAllTablesInPreferences()
def setSelectedEndpointURLAsSetting(self):
# Get the old URL from settings
oldEndpointURL = Functions.getEndpointURL()
# Take the endpoint selected from table
newEndpointName = self.ui.tableWidgetKnownEndpoints.item(self.ui.tableWidgetKnownEndpoints.currentRow(), 0).text()
newEndpointURL = self.ui.tableWidgetKnownEndpoints.item(self.ui.tableWidgetKnownEndpoints.currentRow(), 1).text()
# Set the new URL to DB
# If it is set successfully
if Functions.setEndpointURL(oldEndpointURL, newEndpointURL):
# Log
Functions.addEntryToLog("Endpoint " + newEndpointName + " was selected")
# Show message box with success
QtGui.QMessageBox.information(self, 'Success', "Endpoint <span style='font-size:9pt; font-weight:550; color:#377a97;'>" + newEndpointName + "</span> was selected as External Model.", QtGui.QMessageBox.Close)
# If it fails
else:
# Show message box with error
QtGui.QMessageBox.critical(self, 'Error', "Could not reach the requested endpoint.", QtGui.QMessageBox.Close)
# LOG TAB FUNCTIONS
def loadLogEntriesToTable(self):
# Clear table
self.ui.tableWidgetLogEntries.setRowCount(0)
# Load log entries from DB
entries = Functions.getListOfLogEntries()
# Put the entry to table
for entry in entries:
# Add an empty row to the table
rowPosition = self.ui.tableWidgetLogEntries.rowCount()
self.ui.tableWidgetLogEntries.insertRow(rowPosition)
# Insert the endpoint
self.ui.tableWidgetLogEntries.setItem(rowPosition, 0, QtGui.QTableWidgetItem(entry[0]))
self.ui.tableWidgetLogEntries.setItem(rowPosition, 1, QtGui.QTableWidgetItem(entry[1]))
# Highlight the first entry
self.ui.tableWidgetLogEntries.selectRow(self.ui.tableWidgetLogEntries.rowCount() - 1)
# Sort table
self.ui.tableWidgetLogEntries.sortItems(0, QtCore.Qt.DescendingOrder) # latest entry will appear as first
def clearLogEntries(self):
# Clear table
self.ui.tableWidgetLogEntries.setRowCount(0)
# Delete entries from DB table
Functions.clearLog()
# Reload all tables in preferences
self.loadAllTablesInPreferences()
# NAMESPACES TAB FUNCTIONS
def showDialogAddNamespaces(self):
dialog = AddNamespaceDialog()
dialog.exec_()
del dialog
# Reload all tables in preferences
self.loadAllTablesInPreferences()
# Reload Graph area
window.loadMyModelToTree(window.getGraph(), window.getMyModelName())
def loadNamespacesToTable(self):
# Clear table
self.ui.tableWidgetKnownNamespaces.setRowCount(0)
# Load known namespaces from DB
namespaces = Functions.getListOfNamespaces()
# Put the to table
for namespace in namespaces:
# Add an empty row to the table
rowPosition = self.ui.tableWidgetKnownNamespaces.rowCount()
self.ui.tableWidgetKnownNamespaces.insertRow(rowPosition)
# Insert the namespace
self.ui.tableWidgetKnownNamespaces.setItem(rowPosition, 0, QtGui.QTableWidgetItem(str(namespace[0])))
self.ui.tableWidgetKnownNamespaces.setItem(rowPosition, 1, QtGui.QTableWidgetItem(str(namespace[1])))
def restoreDefaultNamespaces(self):
# Delete all namespaces from db
query = 'DELETE FROM namespaces'
Functions.executeSQLSubmit(query)
# Copy backup