Repository navigation
Expand file tree
/
Copy pathapp_ui.py
More file actions
1176 lines (963 loc) · 52.1 KB
/
Copy pathapp_ui.py
File metadata and controls
1176 lines (963 loc) · 52.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
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
import shutil
import pandas as pd
from PySide6.QtWidgets import (QApplication, QMainWindow, QMessageBox,
QFileDialog, QHeaderView, QCompleter,
QAbstractItemView, QTableWidgetItem, QMenu, QDialog,QCheckBox,QPushButton)
from PySide6.QtCore import Qt, QStringListModel, QSortFilterProxyModel, QItemSelectionModel, Slot
from PySide6.QtGui import QStandardItemModel, QStandardItem, QShortcut, QKeySequence
from PySide6 import QtSvg
# Import your generated UIs
from ui.mainform import Ui_MainWindow
from ui.settings_dialog import Ui_Dialog
from PySide6.QtGui import QColor, QPainter, QPixmap, QPolygon
from PySide6.QtCore import Qt, QPoint, QBuffer, QIODevice
from ui.stylesheet import STYLESHEET,LIGHT_STYLESHEET
import ctypes
from ctypes import wintypes
from engine import *
from settings_ui import AppSettingsDialog
from PySide6.QtGui import QAction
from settings_ui import GraphCommonsSettingsDialog
import sys
import webbrowser # Add to top of app_ui.py
from visualizer import GraphCommonsWindow # Update your visualizer import
def get_stylesheet_with_paths(sheet_string):
"""Dynamically injects the absolute path into the Qt Stylesheet."""
if getattr(sys, 'frozen', False):
# If running as an EXE, PyInstaller extracts resources here
base_path = sys._MEIPASS
else:
# If running from Python, use the current directory
base_path = os.path.abspath(".")
# Qt Stylesheets REQUIRE forward slashes (/) even on Windows!
res_path = os.path.join(base_path, "resources").replace("\\", "/")
return sheet_string.replace("url('resources/", f"url('{res_path}/")
STYLESHEET = get_stylesheet_with_paths(STYLESHEET)
LIGHT_STYLESHEET = get_stylesheet_with_paths(LIGHT_STYLESHEET)
class ViewerProxyModel(QSortFilterProxyModel):
def __init__(self, parent=None):
super().__init__(parent)
self.show_nodes = True
self.show_edges = True
def filterAcceptsRow(self, source_row, source_parent):
model = self.sourceModel()
item_class = model.index(source_row, 0, source_parent).data()
if item_class == "Node" and not self.show_nodes: return False
if item_class == "Edge" and not self.show_edges: return False
return super().filterAcceptsRow(source_row, source_parent)
class GMapFeederApp(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.settings = SettingsManager()
self.db = DataEngine(self.settings)
self.logger_prop_cache = {"source": {}, "target": {}}
self._skip_sync_confirm = False
self.setup_ui_defaults()
self.setup_signals()
self.setup_menus()
self.setStyleSheet(STYLESHEET)
self.visualizer_window = None
# --- Handle Startup Path ---
default_path = self.settings.config.get("startup_path", "")
if default_path and os.path.exists(default_path):
self.db.change_database(default_path)
self.refresh_ui_from_settings()
self.refresh_viewer_table()
self.update_type_completers()
self.statusbar.showMessage(f"Loaded default database: {os.path.basename(default_path)}", 5000)
else:
self.statusbar.showMessage("System Ready. Open or create a database to begin.", 7000)
def apply_windows_dark_bar(self):
"""Force the Windows title bar to dark mode and trigger an instant refresh."""
try:
hwnd = self.winId()
# 1. Set the Dark Mode Attribute
DWMWA_USE_IMMERSIVE_DARK_MODE = 20
dark_mode = ctypes.c_int(1)
ctypes.windll.dwmapi.DwmSetWindowAttribute(
hwnd,
DWMWA_USE_IMMERSIVE_DARK_MODE,
ctypes.byref(dark_mode),
ctypes.sizeof(dark_mode)
)
# 2. Force an instant Frame Refresh
# We call SetWindowPos with the 'Frame Changed' flag.
# SWP_NOMOVE (0x2) | SWP_NOSIZE (0x1) | SWP_NOZORDER (0x4) | SWP_FRAMECHANGED (0x20)
flags = 0x0002 | 0x0001 | 0x0004 | 0x0020
ctypes.windll.user32.SetWindowPos(hwnd, None, 0, 0, 0, 0, flags)
except Exception as e:
print(f"Title bar refresh failed: {e}")
def setup_ui_defaults(self):
self.source_nodename_combo.setEditable(True)
self.target_nodename_combo.setEditable(True)
self.edgetype_combo.setEditable(False)
# Separate models so each combo only shows nodes of the selected type
# Must be created BEFORE refresh_ui_from_settings() which calls update_type_completers()
self.source_completer_model = QStringListModel([], self)
self.target_completer_model = QStringListModel([], self)
self.source_completer = QCompleter(self.source_completer_model, self)
self.source_completer.setCaseSensitivity(Qt.CaseInsensitive)
self.source_completer.setFilterMode(Qt.MatchContains)
self.source_nodename_combo.setCompleter(self.source_completer)
self.target_completer = QCompleter(self.target_completer_model, self)
self.target_completer.setCaseSensitivity(Qt.CaseInsensitive)
self.target_completer.setFilterMode(Qt.MatchContains)
self.target_nodename_combo.setCompleter(self.target_completer)
# --- FIX FOR DARK MODE COMPLETER POPUPS ---
for completer in [self.source_completer, self.target_completer]:
popup = completer.popup()
popup.setStyleSheet(STYLESHEET)
# Now safe to call — completer models already exist
self.refresh_ui_from_settings()
self.properties_table.setColumnCount(2)
self.properties_table.setHorizontalHeaderLabels(["Property Key", "Property Value"])
self.properties_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.add_empty_property_row()
self.source_prop_radio.setChecked(True)
self.viewer_model = QStandardItemModel(0, 5, self)
self.viewer_model.setHorizontalHeaderLabels(["Class", "Entity / Source", "Type / Verb", "Target", "GhostData"])
self.proxy_model = ViewerProxyModel(self)
self.proxy_model.setSourceModel(self.viewer_model)
self.proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
self.proxy_model.setFilterKeyColumn(-1)
self.prop_tableview.setModel(self.proxy_model)
self.prop_tableview.setColumnHidden(4, True)
self.prop_tableview.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.prop_tableview.setSelectionBehavior(QAbstractItemView.SelectRows)
self.prop_tableview.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.details_tablewidget.setColumnCount(2)
self.details_tablewidget.setHorizontalHeaderLabels(["Property", "Value"])
self.details_tablewidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.details_tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.save_changes_btn.setEnabled(False)
self.edit_prop_btn.setEnabled(False)
self.details_tablewidget.setContextMenuPolicy(Qt.CustomContextMenu)
self.node_chk.setChecked(True)
self.edge_chk.setChecked(True)
def refresh_ui_from_settings(self):
"""Dynamically loads combos based on the active database schema."""
c = self.db.schema
src_t = self.source_nodetype_combo.currentText()
tgt_t = self.target_nodetype_combo.currentText()
edg_t = self.edgetype_combo.currentText()
self.source_nodetype_combo.clear()
self.target_nodetype_combo.clear()
self.edgetype_combo.clear()
self.source_nodetype_combo.addItems(c.get("node_types", []))
self.target_nodetype_combo.addItems(c.get("node_types", []))
self.edgetype_combo.addItems(c.get("edge_verbs", []))
if src_t in c.get("node_types", []): self.source_nodetype_combo.setCurrentText(src_t)
if tgt_t in c.get("node_types", []): self.target_nodetype_combo.setCurrentText(tgt_t)
if edg_t in c.get("edge_verbs", []): self.edgetype_combo.setCurrentText(edg_t)
# Rebuild type-filtered completers for the newly loaded schema
self.update_type_completers()
def setup_signals(self):
self.log_conn_btn.clicked.connect(self.handle_log_connection)
self.properties_table.cellChanged.connect(self.handle_properties_table_edit)
self.source_nodename_combo.currentTextChanged.connect(self.load_properties_to_logger_table)
self.target_nodename_combo.currentTextChanged.connect(self.load_properties_to_logger_table)
self.source_prop_radio.toggled.connect(self.load_properties_to_logger_table)
self.target_prop_radio.toggled.connect(self.load_properties_to_logger_table)
self.source_nodetype_combo.currentTextChanged.connect(self.load_properties_to_logger_table)
self.target_nodetype_combo.currentTextChanged.connect(self.load_properties_to_logger_table)
# Type selection drives the name completer filter
self.source_nodetype_combo.currentTextChanged.connect(
lambda _: self.update_type_completers())
self.target_nodetype_combo.currentTextChanged.connect(
lambda _: self.update_type_completers())
self.search_lineEdit.textChanged.connect(self.proxy_model.setFilterFixedString)
self.node_chk.stateChanged.connect(self.apply_checkbox_filters)
self.edge_chk.stateChanged.connect(self.apply_checkbox_filters)
self.shortcut_find = QShortcut(QKeySequence("Ctrl+F"), self)
self.shortcut_find.activated.connect(self.search_lineEdit.setFocus)
self.shortcut_delete = QShortcut(QKeySequence("Del"), self.prop_tableview)
self.shortcut_delete.setContext(Qt.WidgetShortcut)
self.shortcut_delete.activated.connect(self.handle_delete_item)
self.prop_tableview.selectionModel().selectionChanged.connect(self.populate_details_pane)
self.delete_item_btn.clicked.connect(self.handle_delete_item)
self.edit_prop_btn.clicked.connect(self.enable_property_editing)
self.save_changes_btn.clicked.connect(self.save_edited_properties)
self.details_tablewidget.customContextMenuRequested.connect(self.show_property_context_menu)
self.actionOpen_Database.triggered.connect(self.handle_open_database)
self.actionSave_Database.triggered.connect(self.handle_save_database)
self.actionSettings_2.triggered.connect(self.open_settings_dialog)
self.actionImport_CSV_2.triggered.connect(lambda: self.handle_import("csv"))
self.actionImport_Excel.triggered.connect(lambda: self.handle_import("excel"))
self.actionExport_to_CSV.triggered.connect(lambda: self.handle_export("csv"))
self.actionExport_to_Excel.triggered.connect(lambda: self.handle_export("excel"))
self.actionExit.triggered.connect(self.close)
# Tools Menu
self.actionGenerate_Summary.triggered.connect(self.handle_generate_summary)
# self.actionCheck_For_Conflicts.triggered.connect(self.handle_check_conflicts)
# Graph Commons menu
self.actionView_API_Settings.triggered.connect(self.open_gc_settings)
def open_settings_dialog(self):
"""Spawns the Settings UI and refreshes app defaults upon closing."""
dlg = AppSettingsDialog(self.settings, self.db, self)
dlg.exec()
self.refresh_ui_from_settings()
def update_type_completers(self):
"""Rebuild the two name completers so each only shows nodes whose
type matches the currently selected node type in its respective combo."""
src_type = self.source_nodetype_combo.currentText()
tgt_type = self.target_nodetype_combo.currentText()
src_names = [
name for name, data in self.db.data["nodes"].items()
if not src_type or data.get("type") == src_type
]
tgt_names = [
name for name, data in self.db.data["nodes"].items()
if not tgt_type or data.get("type") == tgt_type
]
self.source_completer_model.setStringList(sorted(src_names))
self.target_completer_model.setStringList(sorted(tgt_names))
def inject_property_to_type(self, node_type: str, prop_name: str):
"""Inject a new property key (empty value) into all existing nodes of that
type. Called when a new specific property is added via Settings, and also
internally after a successful log or viewer save adds a key that siblings
don't have yet."""
injected = 0
for name, node in self.db.data["nodes"].items():
if node.get("type") == node_type and prop_name not in node.get("properties", {}):
node.setdefault("properties", {})[prop_name] = ""
self.db._mark_node_updated(name)
injected += 1
if injected:
self.refresh_viewer_table()
if self.settings.config.get("autosave_prop") and self.db.db_path:
self.db.save_db()
self.statusbar.showMessage(
f"Injected '{prop_name}' into {injected} existing '{node_type}' node(s).", 5000
)
return injected
# def load_properties_to_logger_table(self, *args):
# self.properties_table.blockSignals(True)
# self.properties_table.setRowCount(0)
# is_source = self.source_prop_radio.isChecked()
# node_name = self.source_nodename_combo.currentText().strip() if is_source else self.target_nodename_combo.currentText().strip()
# if node_name and node_name in self.db.data["nodes"]:
# properties = self.db.data["nodes"][node_name].get("properties", {})
# for key, value in properties.items():
# row_idx = self.properties_table.rowCount()
# self.properties_table.insertRow(row_idx)
# self.properties_table.setItem(row_idx, 0, QTableWidgetItem(str(key)))
# self.properties_table.setItem(row_idx, 1, QTableWidgetItem(str(value)))
# self.properties_table.blockSignals(False)
# self.add_empty_property_row()
# def load_properties_to_logger_table(self, *args):
# """Fetches existing properties OR populates default schema for new nodes."""
# self.properties_table.blockSignals(True)
# self.properties_table.setRowCount(0)
# is_source = self.source_prop_radio.isChecked()
# # Figure out what we are currently looking at based on the radio button
# if is_source:
# node_name = self.source_nodename_combo.currentText().strip()
# node_type = self.source_nodetype_combo.currentText().strip()
# else:
# node_name = self.target_nodename_combo.currentText().strip()
# node_type = self.target_nodetype_combo.currentText().strip()
# properties_to_display = {}
# # SCENARIO A: The node already exists in the database. Load its saved data.
# if node_name and node_name in self.db.data["nodes"]:
# properties_to_display = self.db.data["nodes"][node_name].get("properties", {}).copy()
# # SCENARIO B: Brand new node (or empty name). Load the Schema Defaults.
# else:
# # 1. Grab Universal properties
# for p in self.settings.config.get("universal_props", []):
# properties_to_display[p] = ""
# # 2. Grab Type-Specific properties based on the current dropdown
# for p in self.settings.config.get("specific_props", {}).get(node_type, []):
# properties_to_display[p] = ""
# # Populate the table visually
# for key, value in properties_to_display.items():
# row_idx = self.properties_table.rowCount()
# self.properties_table.insertRow(row_idx)
# self.properties_table.setItem(row_idx, 0, QTableWidgetItem(str(key)))
# self.properties_table.setItem(row_idx, 1, QTableWidgetItem(str(value)))
# self.properties_table.blockSignals(False)
# self.add_empty_property_row()
def load_properties_to_logger_table(self, *args):
"""Merges default schema templates, saved data, AND the live UI cache."""
self.properties_table.blockSignals(True)
self.properties_table.setRowCount(0)
is_source = self.source_prop_radio.isChecked()
side = "source" if is_source else "target"
if is_source:
node_name = self.source_nodename_combo.currentText().strip()
node_type = self.source_nodetype_combo.currentText().strip()
else:
node_name = self.target_nodename_combo.currentText().strip()
node_type = self.target_nodetype_combo.currentText().strip()
properties_to_display = {}
# --- 1. CACHE CHECK: Did the user type something here recently? ---
cache = self.logger_prop_cache.get(side, {})
if cache.get("name") == node_name and cache.get("props") is not None:
properties_to_display = cache["props"].copy()
else:
# --- 2. NO CACHE: Build the UI Template & Overlay saved DB data ---
schema = self.db.schema
for p in schema.get("universal_props", []):
properties_to_display[p] = ""
for p in schema.get("specific_props", {}).get(node_type, []):
properties_to_display[p] = ""
if node_name and node_name in self.db.data["nodes"]:
saved_props = self.db.data["nodes"][node_name].get("properties", {})
properties_to_display.update(saved_props)
# 3. Draw the table visually
for key, value in properties_to_display.items():
row_idx = self.properties_table.rowCount()
self.properties_table.insertRow(row_idx)
self.properties_table.setItem(row_idx, 0, QTableWidgetItem(str(key)))
self.properties_table.setItem(row_idx, 1, QTableWidgetItem(str(value)))
self.properties_table.blockSignals(False)
self.add_empty_property_row()
def add_empty_property_row(self):
self.properties_table.blockSignals(True)
row_count = self.properties_table.rowCount()
self.properties_table.insertRow(row_count)
self.properties_table.blockSignals(False)
def handle_properties_table_edit(self, row, col):
if row == self.properties_table.rowCount() - 1:
item = self.properties_table.item(row, col)
if item and item.text().strip():
self.add_empty_property_row()
# --- THE LIVE CACHE ---
# Instantly back up the UI form as you type so radio button toggles don't wipe it
is_source = self.source_prop_radio.isChecked()
side = "source" if is_source else "target"
node_name = self.source_nodename_combo.currentText().strip() if is_source else self.target_nodename_combo.currentText().strip()
current_ui_state = {}
for r in range(self.properties_table.rowCount()):
k_item = self.properties_table.item(r, 0)
v_item = self.properties_table.item(r, 1)
if k_item and k_item.text().strip():
v_text = v_item.text().strip() if v_item else ""
current_ui_state[k_item.text().strip()] = v_text
self.logger_prop_cache[side] = {"name": node_name, "props": current_ui_state}
def get_properties_from_table(self, table_widget):
props = {}
for row in range(table_widget.rowCount()):
key_item = table_widget.item(row, 0)
val_item = table_widget.item(row, 1)
key = key_item.text().strip() if key_item else ""
if key:
# Include even if value is empty — empty string clears the value in GC
val = val_item.text().strip() if val_item else ""
props[key] = val
return props
def handle_log_connection(self):
source = self.source_nodename_combo.currentText().strip()
s_type = self.source_nodetype_combo.currentText().strip()
target = self.target_nodename_combo.currentText().strip()
t_type = self.target_nodetype_combo.currentText().strip()
verb = self.edgetype_combo.currentText().strip()
properties = self.get_properties_from_table(self.properties_table)
is_source_prop = self.source_prop_radio.isChecked()
success, msg = self.db.log_connection(source, s_type, target, t_type, verb, properties, is_source_prop)
if success:
self.logger_prop_cache = {"source": {}, "target": {}}
self.statusbar.showMessage(msg, 5000)
self.target_nodename_combo.clearEditText()
self.load_properties_to_logger_table()
self.refresh_viewer_table()
self.update_type_completers()
# ── Req 2: Propagate any new property keys to all siblings ───────
prop_node_name = source if is_source_prop else target
prop_node_type = s_type if is_source_prop else t_type
for key in properties:
self._propagate_new_prop_key(prop_node_type, key)
# --- Auto-Save Guard ---
if self.settings.config["autosave_new_conn"] and self.db.db_path:
self.db.save_db()
else:
self.statusbar.showMessage(msg, 5000)
def refresh_viewer_table(self):
self.viewer_model.removeRows(0, self.viewer_model.rowCount())
row_counter = 0
for name, data in self.db.data["nodes"].items():
props_string = " ".join([f"{k}:{v}" for k, v in data.get("properties", {}).items()])
row = [
QStandardItem("Node"),
QStandardItem(name),
QStandardItem(data["type"]),
QStandardItem("--"),
QStandardItem(props_string)
]
self.viewer_model.appendRow(row)
row_counter += 1
if row_counter % 500 == 0: QApplication.processEvents()
for edge in self.db.data["edges"]:
row = [
QStandardItem("Edge"),
QStandardItem(edge["source"]),
QStandardItem(edge["verb"]),
QStandardItem(edge["target"]),
QStandardItem("")
]
self.viewer_model.appendRow(row)
row_counter += 1
if row_counter % 500 == 0: QApplication.processEvents()
def apply_checkbox_filters(self):
self.proxy_model.show_nodes = self.node_chk.isChecked()
self.proxy_model.show_edges = self.edge_chk.isChecked()
self.proxy_model.invalidateFilter()
def populate_details_pane(self, selected, deselected):
self.details_tablewidget.setRowCount(0)
self.details_tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.save_changes_btn.setEnabled(False)
self.edit_prop_btn.setEnabled(False)
if not selected or not selected.indexes(): return
proxy_index = selected.indexes()[0]
source_index = self.proxy_model.mapToSource(proxy_index)
item_class = self.viewer_model.item(source_index.row(), 0).text()
entity_name = self.viewer_model.item(source_index.row(), 1).text()
if item_class == "Node" and entity_name in self.db.data["nodes"]:
self.edit_prop_btn.setEnabled(True)
node_type = self.viewer_model.item(source_index.row(), 2).text()
# 1. Build the UI Template (Universal + Specific defaults as empty strings)
properties_to_display = {}
schema = self.db.schema
for p in schema.get("universal_props", []):
properties_to_display[p] = ""
for p in schema.get("specific_props", {}).get(node_type, []):
properties_to_display[p] = ""
# 2. Overlay actual saved data
saved_props = self.db.data["nodes"][entity_name].get("properties", {})
properties_to_display.update(saved_props)
# 3. Draw the table visually
for key, value in properties_to_display.items():
row_idx = self.details_tablewidget.rowCount()
self.details_tablewidget.insertRow(row_idx)
self.details_tablewidget.setItem(row_idx, 0, QTableWidgetItem(str(key)))
self.details_tablewidget.setItem(row_idx, 1, QTableWidgetItem(str(value)))
def enable_property_editing(self):
self.details_tablewidget.setEditTriggers(QAbstractItemView.DoubleClicked | QAbstractItemView.AnyKeyPressed)
self.save_changes_btn.setEnabled(True)
self.edit_prop_btn.setEnabled(False)
row_count = self.details_tablewidget.rowCount()
self.details_tablewidget.insertRow(row_count)
self.statusbar.showMessage("Edit mode enabled. Double click cells to edit.", 4000)
def save_edited_properties(self):
selection = self.prop_tableview.selectionModel().selectedRows()
if not selection: return
proxy_index = selection[0]
source_index = self.proxy_model.mapToSource(proxy_index)
entity_name = self.viewer_model.item(source_index.row(), 1).text()
node_type = self.viewer_model.item(source_index.row(), 2).text()
new_props = self.get_properties_from_table(self.details_tablewidget)
self.db.update_node_properties(entity_name, new_props)
# ── Req 2: Propagate any new property keys to all siblings ───────────
for key in new_props:
self._propagate_new_prop_key(node_type, key)
if self.settings.config["autosave_prop"] and self.db.db_path:
self.db.save_db()
self.details_tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.save_changes_btn.setEnabled(False)
self.edit_prop_btn.setEnabled(True)
# Targeted UI Update (NO FULL REFRESH)
props_string = " ".join([f"{k}:{v}" for k, v in new_props.items()])
self.viewer_model.item(source_index.row(), 4).setText(props_string)
current_selection = self.prop_tableview.selectionModel().selection()
self.populate_details_pane(current_selection, None)
self.load_properties_to_logger_table()
self.statusbar.showMessage(f"Properties for '{entity_name}' saved successfully.", 4000)
def _propagate_new_prop_key(self, node_type: str, prop_key: str):
"""Req 2: If prop_key is not yet in the schema's specific_props for this
type, add it silently and inject an empty value into all sibling nodes.
Skips universal / locked props since they're already everywhere."""
LOCKED = {"Description", "Image URL", "Reference"}
if not prop_key or prop_key in LOCKED:
return
schema = self.db.schema
unv = schema.get("universal_props", [])
if prop_key in unv:
return # already a universal prop — all nodes have it
sp = schema.setdefault("specific_props", {})
if prop_key not in sp.get(node_type, []):
sp.setdefault(node_type, []).append(prop_key)
# Inject into every sibling that doesn't have this key yet (silently)
for name, node in self.db.data["nodes"].items():
if node.get("type") == node_type and prop_key not in node.get("properties", {}):
node.setdefault("properties", {})[prop_key] = ""
self.db._mark_node_updated(name)
def show_property_context_menu(self, pos):
# Property deletion has been removed — properties are managed at the
# node type schema level, not per-node. Right-click is a no-op.
pass
def delete_selected_property(self, row):
# Scrapped — property deletion not supported.
pass
def handle_delete_item(self):
selection = self.prop_tableview.selectionModel().selectedRows()
if not selection:
self.statusbar.showMessage("Error: No item selected to delete.", 4000)
return
source_index = self.proxy_model.mapToSource(selection[0])
item_class = self.viewer_model.item(source_index.row(), 0).text()
entity_name = self.viewer_model.item(source_index.row(), 1).text()
# --- Confirmation Guard ---
if self.settings.config["confirm_del_node_conn"]:
reply = QMessageBox.question(self, 'Confirm Deletion',
f"Are you sure you want to delete this {item_class} ('{entity_name}')?\n\nIf it's a Node, ALL related connections will also be destroyed.",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
else:
reply = QMessageBox.Yes
if reply == QMessageBox.Yes:
if item_class == "Node":
self.db.delete_node(entity_name)
self.update_type_completers()
elif item_class == "Edge":
target_name = self.viewer_model.item(source_index.row(), 3).text()
verb_name = self.viewer_model.item(source_index.row(), 2).text()
self.db.delete_edge(entity_name, target_name, verb_name)
# --- Auto-Save Guard ---
if self.settings.config["autosave_del_item"] and self.db.db_path:
self.db.save_db()
self.refresh_viewer_table()
self.details_tablewidget.setRowCount(0)
self.statusbar.showMessage(f"Successfully deleted {item_class}: {entity_name}", 5000)
self.load_properties_to_logger_table()
def handle_prune_isolated_nodes(self):
"""Finds and deletes nodes that have zero connections (edges)."""
all_nodes = set(self.db.data["nodes"].keys())
connected_nodes = set()
# Gather every node that exists in an edge
for edge in self.db.data["edges"]:
connected_nodes.add(edge["source"])
connected_nodes.add(edge["target"])
orphans = all_nodes - connected_nodes
if not orphans:
QMessageBox.information(self, "Prune Nodes", "Graph is clean! No isolated nodes found.")
return
reply = QMessageBox.question(
self,
"Prune Isolated Nodes",
f"Found {len(orphans)} isolated nodes with no connections.\n\nDo you want to permanently delete them?",
QMessageBox.Yes | QMessageBox.No
)
if reply == QMessageBox.Yes:
for node in orphans:
self.db.data["nodes"].pop(node, None)
# Auto-save check
if self.settings.config.get("autosave_del_item") and self.db.db_path:
self.db.save_db()
self.refresh_viewer_table()
self.update_type_completers()
self.statusbar.showMessage(f"Successfully pruned {len(orphans)} isolated nodes.", 5000)
def handle_generate_summary(self):
"""Generates a high-level overview of the database contents."""
num_nodes = len(self.db.data["nodes"])
num_edges = len(self.db.data["edges"])
# Count nodes by their Type
type_counts = {}
for data in self.db.data["nodes"].values():
t = data.get("type", "Unknown")
type_counts[t] = type_counts.get(t, 0) + 1
summary = f"Database Summary\n{'='*20}\n"
summary += f"Total Entities (Nodes): {num_nodes}\n"
summary += f"Total Connections (Edges): {num_edges}\n\n"
summary += "Breakdown by Type:\n"
# Sort types alphabetically for a clean display
for t in sorted(type_counts.keys()):
summary += f" • {t}: {type_counts[t]}\n"
QMessageBox.information(self, "Generate Summary", summary)
def handle_check_conflicts(self):
"""Scans the database for ghost nodes and case-sensitivity duplicates."""
nodes = self.db.data["nodes"].keys()
edges = self.db.data["edges"]
issues = []
# 1. Check for Ghost Nodes (Edges pointing to nodes that don't exist in the dictionary)
for edge in edges:
if edge["source"] not in nodes:
issues.append(f"[Ghost Source] '{edge['source']}' exists in an edge but has no Node data.")
if edge["target"] not in nodes:
issues.append(f"[Ghost Target] '{edge['target']}' exists in an edge but has no Node data.")
# 2. Check for Case Collisions (e.g., "Mathura" vs "mathura")
lower_map = {}
for n in nodes:
ln = n.lower()
if ln in lower_map:
issues.append(f"[Duplicate Warning] '{n}' and '{lower_map[ln]}' might be the same entity.")
else:
lower_map[ln] = n
if not issues:
QMessageBox.information(self, "Conflict Checker", "Your database is perfectly clean! No conflicts found.")
else:
report = "\n".join(issues[:15]) # Limit to 15 so the dialog doesn't overflow off the screen
if len(issues) > 15:
report += f"\n\n...and {len(issues) - 15} more issues."
QMessageBox.warning(self, f"Found {len(issues)} Conflicts", report)
def handle_view_statistics(self):
"""Calculates graph density and identifies the most heavily connected hubs."""
num_nodes = len(self.db.data["nodes"])
num_edges = len(self.db.data["edges"])
if num_nodes == 0:
QMessageBox.information(self, "Statistics", "The database is empty.")
return
in_degree = {}
out_degree = {}
# Tally up the connections
for edge in self.db.data["edges"]:
s, t = edge["source"], edge["target"]
out_degree[s] = out_degree.get(s, 0) + 1
in_degree[t] = in_degree.get(t, 0) + 1
# Combine in and out to find the busiest nodes
total_degree = {}
all_active_nodes = set(in_degree.keys()) | set(out_degree.keys())
for n in all_active_nodes:
total_degree[n] = in_degree.get(n, 0) + out_degree.get(n, 0)
top_nodes = sorted(total_degree.items(), key=lambda x: x[1], reverse=True)[:5]
avg_connections = num_edges / num_nodes
stats = f"Network Statistics\n{'='*20}\n"
stats += f"Average Connections per Node: {avg_connections:.2f}\n\n"
stats += "Top 5 Most Connected Hubs:\n"
for rank, (name, count) in enumerate(top_nodes, 1):
stats += f" {rank}. {name} ({count} connections)\n"
QMessageBox.information(self, "Graph Statistics", stats)
def closeEvent(self, event):
"""Intercepts the window close action to check for unsaved changes."""
p = self.db._pending()
has_unsynced = any([
p["creates"]["nodes"], p["creates"]["edges"],
p["updates"]["nodes"], p["updates"]["edges"],
p["deletes"]["nodes"], p["deletes"]["edges"]
])
if self.db.has_unsaved_changes():
# Build a context-aware message
if has_unsynced:
detail = ("You have changes that have not been saved to disk "
"and not synced to Graph Commons.")
else:
detail = "You have changes that have not been saved to disk."
reply = QMessageBox.warning(
self,
"Unsaved Changes",
f"{detail}\nDo you want to save them before exiting?",
QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel,
QMessageBox.Save
)
if reply == QMessageBox.Save:
self.handle_save_database()
if self.db.has_unsaved_changes():
event.ignore()
else:
event.accept()
elif reply == QMessageBox.Discard:
event.accept()
else:
event.ignore()
elif has_unsynced:
# File is saved but there are pending GC changes
reply = QMessageBox.warning(
self,
"Unsynced Changes",
"Your local file is saved, but you have changes not yet synced to Graph Commons.\n"
"Exit anyway?",
QMessageBox.Yes | QMessageBox.Cancel,
QMessageBox.Cancel
)
event.accept() if reply == QMessageBox.Yes else event.ignore()
else:
event.accept()
def handle_open_database(self):
file_path, _ = QFileDialog.getOpenFileName(self, "Open Database", "", "JSON Files (*.json)")
if file_path:
self.db.change_database(file_path)
self.refresh_ui_from_settings()
self.refresh_viewer_table()
self.update_type_completers()
self.details_tablewidget.setRowCount(0)
self._add_to_recent(file_path)
self.statusbar.showMessage(f"Switched database to: {os.path.basename(file_path)}", 5000)
def handle_save_database(self):
if not self.db.db_path:
file_path, _ = QFileDialog.getSaveFileName(self, "Save New Database", "", "JSON Files (*.json)")
if not file_path:
self.statusbar.showMessage("Save cancelled.", 4000)
return
self.db.db_path = file_path
self.statusbar.showMessage("Saving ...", 2000)
QApplication.processEvents()
try:
self.db.save_db()
filename = os.path.basename(self.db.db_path)
self.statusbar.showMessage(f"Disk Synced: '{filename}' is now up to date.", 5000)
except Exception as e:
QMessageBox.critical(self, "Save Failure", f"The system could not write to disk.\n\nError: {str(e)}\n\nTry saving to a different location.")
self.statusbar.showMessage("CRITICAL: Save Failed!", 7000)
def handle_import(self, format_type):
filter_str = "CSV Files (*.csv)" if format_type == "csv" else "Excel Files (*.xlsx *.xls)"
file_path, _ = QFileDialog.getOpenFileName(self, f"Import {format_type.upper()}", "", filter_str)
if file_path:
self.statusbar.showMessage("Analyzing file structure...", 2000)
QApplication.processEvents()
success, report, pending_data = self.db.prepare_import(file_path, format_type)
if success:
reply = QMessageBox.question(self, "Import Validation Report",
f"{report}\n\nDo you want to apply these changes to your current session?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
self.statusbar.showMessage("Merging data into RAM...", 2000)
QApplication.processEvents()
self.db.commit_import(pending_data)
self.refresh_viewer_table()
self.update_type_completers()
self.statusbar.showMessage("Import Successful! (Remember to click 'Save Database' to commit to disk)", 7000)
else:
self.statusbar.showMessage("Import cancelled by user.", 4000)
else:
QMessageBox.critical(self, "Import Failed", report)
self.statusbar.showMessage("Import aborted due to file errors.", 5000)
def handle_export(self, format_type):
export_dir = QFileDialog.getExistingDirectory(self, "Select Export Directory")
if export_dir:
self.statusbar.showMessage(f"Exporting to {format_type.upper()}...", 2000)
QApplication.processEvents()
success, msg = self.db.export_data(format_type, export_dir)
if success: self.statusbar.showMessage(msg, 7000)
else:
QMessageBox.warning(self, "Export Error", msg)
self.statusbar.showMessage("Export failed.", 5000)
def setup_menus(self):
"""Post-designer menu surgery:
- Remove Edit menu entirely
- Remove 'Open Graph Online' and 'View Statistics' from Graph Commons
- Add 'Open Recent...' as first item in File menu
- Add GC Sync/Load/View actions programmatically
"""
menubar = self.menuBar()
# ── Remove Edit menu ─────────────────────────────────────────────────
menubar.removeAction(self.menu_edit.menuAction())
# ── Clean Graph Commons menu ─────────────────────────────────────────
self.menuGraph_Commons.removeAction(self.actionOpen_Graph_Online)
self.menuGraph_Commons.removeAction(self.actionView_Statistics_2)
# ── Open Recent submenu (prepend to File menu) ────────────────────────
self.menu_recent = QMenu("Open Recent...", self)
# Insert before the very first action in menu_File (which is Open Database)
first_action = self.menu_File.actions()[0]
self.menu_File.insertMenu(first_action, self.menu_recent)
self.menu_File.insertSeparator(first_action)
self._rebuild_recent_menu()
# ── GC Sync / Load / View actions ─────────────────────────────────────
self.actionView_Graph = QAction("🎨 Open Graph Commons", self)
self.actionView_Graph.setShortcut("Ctrl+G")
self.actionView_Graph.triggered.connect(self.launch_visualizer)
self.actionSync_GC = QAction("☁️ Sync to Graph Commons", self)
self.actionSync_GC.triggered.connect(self.handle_gc_sync)
self.actionLoad_GC = QAction("⬇️ Load from Graph Commons", self)
self.actionLoad_GC.triggered.connect(self.handle_gc_load)
menubar.addAction(self.actionView_Graph)
menubar.addAction(self.actionSync_GC)
menubar.addAction(self.actionLoad_GC)
# Prune Isolated Nodes moves to Tools now that Edit is gone
# self.menu_Tools.addSeparator()
# self.menu_Tools.addAction(self.actionPrune_Isolated_Nodes)
# self.actionPrune_Isolated_Nodes.triggered.connect(self.handle_prune_isolated_nodes)
# ── Theme Toggle Button (Right Side of Menu Bar) ─────────────────────
self.theme_toggle_btn = QPushButton("☀️")
self.theme_toggle_btn.setCheckable(True)
self.theme_toggle_btn.setCursor(Qt.PointingHandCursor)
# Slick flat styling specifically for the menu bar
self.theme_toggle_btn.setStyleSheet("""
QPushButton {
background-color: transparent;
color: #88C0D0;
font-weight: bold;
border: none;
padding: 4px 16px;
margin-top: 2px;
margin-bottom: 2px;
margin-right: 8px;
}
QPushButton:hover {
background-color: #3B4252;
border-radius: 4px;
}
""")
self.theme_toggle_btn.clicked.connect(self.handle_theme_swap)
# Pin it to the top right corner of the menu bar
menubar.setCornerWidget(self.theme_toggle_btn, Qt.TopRightCorner)
def handle_theme_swap(self, checked):
"""Swaps the stylesheet and updates the button text/icon."""
if checked:
self.theme_toggle_btn.setText("🌙")
self.setStyleSheet(LIGHT_STYLESHEET)
self.statusbar.showMessage("Switched to Light Theme", 3000)
else:
self.theme_toggle_btn.setText("☀️")
# Restore your default dark stylesheet
self.setStyleSheet(STYLESHEET)
self.statusbar.showMessage("Switched to Dark Theme", 3000)
def _rebuild_recent_menu(self):
"""Rebuild the Open Recent submenu from settings."""
self.menu_recent.clear()
recents = self.settings.config.get("recent_databases", [])
if not recents:
placeholder = QAction("(No recent databases)", self)
placeholder.setEnabled(False)
self.menu_recent.addAction(placeholder)
return
for path in recents:
action = QAction(os.path.basename(path), self)
action.setToolTip(path)
action.triggered.connect(lambda checked=False, p=path: self._open_recent(p))
self.menu_recent.addAction(action)
self.menu_recent.addSeparator()
clear_action = QAction("Clear Recent", self)
clear_action.triggered.connect(self._clear_recent)
self.menu_recent.addAction(clear_action)
def _open_recent(self, path: str):
if not os.path.exists(path):
QMessageBox.warning(self, "File Not Found",
f"The file no longer exists:\n{path}\n\nIt will be removed from recent list.")
self._remove_from_recent(path)
return
self.db.change_database(path)
self.refresh_ui_from_settings()
self.refresh_viewer_table()
self.update_type_completers()