-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
245 lines (195 loc) · 7.01 KB
/
app.py
File metadata and controls
245 lines (195 loc) · 7.01 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
"""
Network Intelligence - Main Application Entry Point
A professional 3D network visualization system.
"""
import sys
import threading
import webbrowser
from pathlib import Path
import tkinter as tk
from tkinter import ttk, messagebox
from flask import Flask
# Import configuration
import config
from utils.logger import setup_logger, get_logger
from storage.io_manager import load_or_init_graph
from visualization.network_visualizer import NetworkVisualizer
from api.controllers import AppController
from api.routes import init_routes
# Setup logging
setup_logger()
logger = get_logger(__name__)
class LaunchDialog:
"""Launch mode selection dialog."""
def __init__(self):
self.result = "browser"
self.root = None
def show(self) -> str:
"""Display dialog and return selected mode."""
self.root = tk.Tk()
self.root.title(f"{config.APP_NAME} - Launch Options")
self.root.geometry("450x220")
self.root.resizable(False, False)
# Center window
self.root.update_idletasks()
x = (self.root.winfo_screenwidth() // 2) - (450 // 2)
y = (self.root.winfo_screenheight() // 2) - (220 // 2)
self.root.geometry(f"+{x}+{y}")
# Configure style
style = ttk.Style()
style.theme_use('clam')
# Title
title_frame = ttk.Frame(self.root, padding="20")
title_frame.pack(fill="x")
ttk.Label(
title_frame,
text=config.APP_NAME,
font=("Segoe UI", 16, "bold")
).pack()
ttk.Label(
title_frame,
text=f"Version {config.VERSION}",
font=("Segoe UI", 9),
foreground="gray"
).pack()
# Description
desc_frame = ttk.Frame(self.root, padding="10 0")
desc_frame.pack(fill="x")
ttk.Label(
desc_frame,
text="Choose how to launch the visualization:",
font=("Segoe UI", 10)
).pack()
# Buttons
btn_frame = ttk.Frame(self.root, padding="20")
btn_frame.pack(fill="x")
browser_btn = ttk.Button(
btn_frame,
text="🌐 Open in Browser (Recommended)",
command=lambda: self._select("browser"),
width=35
)
browser_btn.pack(pady=5)
desktop_btn = ttk.Button(
btn_frame,
text="🖥️ Open Desktop Application",
command=lambda: self._select("desktop"),
width=35
)
desktop_btn.pack(pady=5)
# Info
info_frame = ttk.Frame(self.root, padding="10")
info_frame.pack(fill="x", side="bottom")
ttk.Label(
info_frame,
text="Browser mode recommended for best compatibility",
font=("Segoe UI", 8),
foreground="gray"
).pack()
# Handle window close
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
# Set focus
browser_btn.focus_set()
self.root.mainloop()
return self.result
def _select(self, mode: str):
"""Handle mode selection."""
self.result = mode
if self.root:
self.root.destroy()
def _on_close(self):
"""Handle window close."""
if self.root:
self.root.destroy()
sys.exit(0)
def create_flask_app() -> Flask:
"""Create and configure Flask application."""
logger.info("Initializing Flask application...")
# Load or create graph model
graph_model = load_or_init_graph(config.DEFAULT_NETWORK_FILE)
logger.info(f"Loaded graph: {graph_model.summary()[0]} nodes, {graph_model.summary()[1]} edges")
# Initialize visualizer
visualizer = NetworkVisualizer(config.PHYSICS_CONFIG_FILE)
# Create Flask app
app = Flask(__name__,
template_folder='ui/web/templates',
static_folder='ui/web/static')
app.config['SECRET_KEY'] = 'dev-secret-key-change-in-production'
app.config['JSON_SORT_KEYS'] = False
# Initialize controller and routes
controller = AppController(graph_model, visualizer)
init_routes(app, controller, visualizer)
logger.info("Flask application initialized successfully")
return app
def run_server(app: Flask, host: str, port: int):
"""Run Flask server in a separate thread."""
try:
logger.info(f"Starting server on http://{host}:{port}")
app.run(host=host, port=port, debug=config.DEBUG, use_reloader=False)
except Exception as e:
logger.error(f"Server error: {e}")
raise
def launch_browser(url: str):
"""Launch browser with slight delay to ensure server is ready."""
import time
time.sleep(1.5) # Wait for server to start
logger.info(f"Opening browser: {url}")
webbrowser.open(url)
def launch_desktop(url: str):
"""Launch desktop application."""
try:
from ui.desktop.tk_app import launch_desktop_app
logger.info("Launching desktop application...")
launch_desktop_app(url)
except ImportError as e:
logger.error(f"Desktop app dependencies not available: {e}")
messagebox.showerror(
"Missing Dependencies",
"Desktop mode requires 'pywebview'. Install it with:\npip install pywebview\n\nLaunching browser instead..."
)
launch_browser(url)
except Exception as e:
logger.error(f"Failed to launch desktop app: {e}")
messagebox.showerror(
"Launch Error",
f"Failed to launch desktop app:\n{e}\n\nLaunching browser instead..."
)
launch_browser(url)
def main():
"""Main application entry point."""
try:
logger.info(f"Starting {config.APP_NAME} v{config.VERSION}")
# Show launch dialog
dialog = LaunchDialog()
mode = dialog.show()
logger.info(f"Launch mode selected: {mode}")
# Create Flask app
app = create_flask_app()
# Server URL
url = f"http://{config.HOST}:{config.PORT}/"
# Start server in background thread
server_thread = threading.Thread(
target=run_server,
args=(app, config.HOST, config.PORT),
daemon=True
)
server_thread.start()
# Launch UI based on mode
if mode == "desktop":
launch_desktop(url)
else:
launch_browser(url)
# Keep main thread alive
logger.info("Application running. Press Ctrl+C to exit.")
try:
while True:
threading.Event().wait(1)
except KeyboardInterrupt:
logger.info("Shutting down...")
sys.exit(0)
except Exception as e:
logger.exception(f"Fatal error: {e}")
messagebox.showerror("Fatal Error", f"Application failed to start:\n{e}")
sys.exit(1)
if __name__ == "__main__":
main()