Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
210 lines (164 loc) · 7.22 KB
/
Copy pathmain.py
File metadata and controls
210 lines (164 loc) · 7.22 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
import os
import sys
from pathlib import Path
# Must be set before QGuiApplication is created. Without an explicit style,
# Qt Quick Controls falls back to the native platform style (e.g. Windows/
# WindowsVista/Fusion), which paints its own pressed/hover state on top of
# buttons - on Windows in particular this shows up as a white flash when a
# button is clicked, even though Btn.qml/IconButton.qml define a custom
# "background". "Basic" is a pure-QML style, so it always renders exactly
# the colors defined in the QML files below and nothing else.
os.environ.setdefault("QT_QUICK_CONTROLS_STYLE", "Basic")
from PySide6.QtCore import QObject, Signal, Slot, Property, QUrl
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from graph.domain.graph import Graph
from graph.facade import GraphFacade
from persistence.json_graph_repository import JsonGraphRepository
from controllers.main_controller import MainController
# All saved/loaded graphs live in this single, fixed folder so users never
# have to type a full path - only a name (Save) or pick a file (Load).
DATA_DIR = Path(__file__).resolve().parent / "data"
class QmlBridge(QObject):
"""
Takes the place of the old QWidget MainWindow. MainController calls
set_controller / refresh_graph / refresh_users / show_result /
show_error on whatever "main window" object it's given - this class
implements that same interface but turns each call into a Qt signal
that the QML UI listens to, and exposes slots QML can call back into
the controller with.
NOTE: refresh_graph/refresh_users assume graph.get_users(),
user.get_id()/get_name(), graph.get_neighbors(user_id) exist, per
the UML diagram. Adjust here if the real method names differ.
"""
usersChanged = Signal(list)
graphChanged = Signal(list, list)
resultReady = Signal(str, str)
errorOccurred = Signal(str)
pathHighlighted = Signal(list)
def __init__(self, parent=None):
super().__init__(parent)
self._controller = None
# ---- data folder (used by QML's Load Graph file picker) -----------
@Property(QUrl, constant=True)
def dataDirectoryUrl(self):
return QUrl.fromLocalFile(str(DATA_DIR))
@Slot(QUrl, result=str)
def toLocalFile(self, url):
return url.toLocalFile()
# ---- called by MainController ------------------------------------
def set_controller(self, controller):
self._controller = controller
def refresh_graph(self, graph):
nodes, edges = [], []
try:
seen = set()
for user in graph.get_users():
uid = user.get_id()
nodes.append({"id": uid, "name": user.get_name()})
for neighbor_id in graph.get_neighbors(uid):
key = tuple(sorted((str(uid), str(neighbor_id))))
if key not in seen:
seen.add(key)
edges.append({"source": uid, "target": neighbor_id})
except Exception as exc: # noqa: BLE001
self.show_error(f"Could not read graph for display: {exc}")
return
self.graphChanged.emit(nodes, edges)
def refresh_users(self, users):
try:
user_list = [{"id": u.get_id(), "name": u.get_name()} for u in users]
except Exception as exc: # noqa: BLE001
self.show_error(f"Could not read user list: {exc}")
return
self.usersChanged.emit(user_list)
def show_result(self, title, content):
self.resultReady.emit(title, str(content))
def show_error(self, message):
self.errorOccurred.emit(str(message))
def highlight_path(self, user_ids):
self.pathHighlighted.emit([str(uid) for uid in user_ids])
# ---- called by QML -------------------------------------------------
@Slot(str, str)
def addUser(self, user_id, name):
self._run(lambda: self._controller.handle_add_user(user_id, name))
@Slot(str, str)
def addFriendship(self, user1_id, user2_id):
self._run(lambda: self._controller.handle_add_friendship(user1_id, user2_id))
@Slot(str)
def removeUser(self, user_id):
self._run(lambda: self._controller.handle_remove_user(user_id))
@Slot(str, str)
def removeFriendship(self, user1_id, user2_id):
self._run(lambda: self._controller.handle_remove_friendship(user1_id, user2_id))
@Slot(str, str)
def updateUser(self, user_id, new_name):
self._run(lambda: self._controller.handle_update_user(user_id, new_name))
@Slot(str, str)
def checkConnection(self, user1_id, user2_id):
self._run(lambda: self._controller.handle_check_connection(user1_id, user2_id))
@Slot(str, str)
def findShortestPath(self, source_id, target_id):
self._run(lambda: self._controller.handle_shortest_path(source_id, target_id))
@Slot()
def showComponents(self):
self._run(lambda: self._controller.handle_show_components())
@Slot()
def showLargestComponents(self):
self._run(lambda: self._controller.handle_show_largest_components())
@Slot()
def showStatistics(self):
self._run(lambda: self._controller.handle_show_graph_statistics())
@Slot(str)
def suggestFriends(self, user_id):
self._run(lambda: self._controller.handle_suggest_friends(user_id))
@Slot(str)
def distancesFromUser(self, source_id):
self._run(lambda: self._controller.handle_distances_from_user(source_id))
@Slot(str)
def saveGraph(self, file_path):
self._run(lambda: self._controller.handle_save_graph(file_path))
@Slot(str)
def loadGraph(self, file_path):
self._run(lambda: self._controller.handle_load_graph(file_path))
def _run(self, action):
if self._controller is None:
self.show_error("Controller is not connected yet.")
return
try:
action()
except Exception as exc: # noqa: BLE001
self.show_error(str(exc))
@Slot(str)
def listFriends(self, user_id):
self._run(lambda: self._controller.handle_list_friends(user_id))
@Slot(str, str)
def mutualFriends(self, user1_id, user2_id):
self._run(lambda: self._controller.handle_mutual_friends(user1_id, user2_id))
def main():
""" Application entry point for the Social Network Analysis project.
Initializes the Qt/QML application, creates the core objects (graph,
facade, repository, controller), connects them to the QML UI
(views/qml/App.qml) through a QmlBridge, and starts the event loop. """
app = QGuiApplication(sys.argv)
DATA_DIR.mkdir(parents=True, exist_ok=True)
graph = Graph()
facade = GraphFacade(graph)
repository = JsonGraphRepository()
bridge = QmlBridge()
controller = MainController(
graph=graph,
facade=facade,
repository=repository,
main_window=bridge,
)
bridge.set_controller(controller)
engine = QQmlApplicationEngine()
engine.rootContext().setContextProperty("bridge", bridge)
qml_entry_point = Path(__file__).resolve().parent / "views" / "qml" / "App.qml"
engine.load(str(qml_entry_point))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec())
if __name__ == "__main__":
main()