-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
324 lines (267 loc) · 11.6 KB
/
Copy pathmain.py
File metadata and controls
324 lines (267 loc) · 11.6 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
import os
import sys
import logging
import traceback
from logging.handlers import RotatingFileHandler
from PySide6.QtWidgets import (QApplication, QMessageBox, QWidget, QVBoxLayout,
QHBoxLayout, QLabel, QGraphicsOpacityEffect)
from PySide6.QtCore import (Qt, QPropertyAnimation, QEasingCurve, QTimer,
QObject, Signal, QStandardPaths)
from PySide6.QtGui import QIcon, QPixmap, QFileOpenEvent, QFontDatabase
from src.ui.main_window import MainWindow
from src.ui.theme_manager import ThemeManager
from src.core.utils import resource_path, app_settings, set_icon_theme
from src.ui.typography import DESIGN_BASE_PT
from src.core.constants import APP_VERSION
log = logging.getLogger(__name__)
class CustomSplashScreen(QWidget):
"""
A Splash screen that fades out smoothly.
"""
def __init__(self, pixmap: QPixmap):
super().__init__()
self.setWindowFlags(
Qt.SplashScreen |
Qt.FramelessWindowHint |
Qt.WindowStaysOnTopHint
)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setFixedSize(600, 300)
self._init_ui(pixmap)
def _init_ui(self, pixmap: QPixmap):
main_layout = QHBoxLayout(self)
main_layout.setContentsMargins(0, 0, 0, 0)
container = QWidget()
container.setObjectName("SplashContainer")
container_layout = QHBoxLayout(container)
container_layout.setContentsMargins(30, 20, 30, 20)
container_layout.setSpacing(25)
# Icon on the left
icon_label = QLabel()
icon_label.setPixmap(pixmap.scaled(128, 128, Qt.KeepAspectRatio, Qt.SmoothTransformation))
icon_label.setAlignment(Qt.AlignCenter)
# Vertical layout for text on the right
text_container = QWidget()
text_layout = QVBoxLayout(text_container)
text_layout.setAlignment(Qt.AlignCenter)
text_layout.setContentsMargins(0, 0, 0, 0)
# Title
title_label = QLabel("ZebraFET")
title_font = self.font()
title_font.setPointSize(48)
title_font.setBold(True)
title_label.setFont(title_font)
title_label.setAlignment(Qt.AlignCenter)
# Loading message
self.message_label = QLabel("Loading application...")
message_font = self.font()
message_font.setPointSize(12)
self.message_label.setFont(message_font)
self.message_label.setAlignment(Qt.AlignCenter)
text_layout.addWidget(title_label)
text_layout.addWidget(self.message_label)
container_layout.addWidget(icon_label)
container_layout.addWidget(text_container, 1)
main_layout.addWidget(container)
self.setStyleSheet("""
#SplashContainer {
background-color: #2c3e50;
border-radius: 15px;
}
QLabel {
background-color: transparent;
color: #ecf0f1;
}
""")
def close_splash(self):
self.opacity_effect = QGraphicsOpacityEffect(self)
self.setGraphicsEffect(self.opacity_effect)
self.animation = QPropertyAnimation(self.opacity_effect, b"opacity")
self.animation.setDuration(400)
self.animation.setStartValue(1.0)
self.animation.setEndValue(0.0)
self.animation.setEasingCurve(QEasingCurve.Type.OutQuad)
self.animation.finished.connect(self.close)
self.animation.start()
class _ExceptionRelay(QObject):
"""
Routes unhandled exceptions from any thread to the GUI thread via a
Qt queued signal, preventing PySide6 segfaults that occur when
QMessageBox is called directly from a non-GUI thread.
Note: QThread exceptions not re-emitted via a signal are silently
swallowed by Qt. Worker threads should catch and emit errors explicitly.
"""
_exception_occurred = Signal(str)
def __init__(self, parent=None):
super().__init__(parent)
self._in_dialog = False
self._exception_occurred.connect(self._show_dialog, Qt.QueuedConnection)
sys.excepthook = self._hook
def _hook(self, exc_type, exc_value, exc_tb):
try:
msg = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
log.critical(f"Unhandled exception:\n{msg}")
self._exception_occurred.emit(msg)
except Exception:
pass # prevent recursive exception hook invocation
def _show_dialog(self, msg: str):
if self._in_dialog:
return
self._in_dialog = True
try:
QMessageBox.critical(
None, "Unexpected Error",
"An unexpected error occurred and has been written to zebrafet.log.\n\n"
"Help > Open Log Folder will reveal the file."
)
finally:
self._in_dialog = False
class ZebraFETApp(QApplication):
"""QApplication subclass that captures QFileOpenEvent (macOS file associations)."""
def __init__(self, argv):
super().__init__(argv)
self._pending_file: str | None = None
self._window = None
def set_window(self, window) -> None:
self._window = window
def consume_pending_file(self) -> str | None:
path, self._pending_file = self._pending_file, None
return path
def event(self, event):
if isinstance(event, QFileOpenEvent):
from src.core.project_exporter import is_importable_archive
path = event.file()
if is_importable_archive(path) and os.path.isfile(path):
if self._window is not None:
self._window.open_archive(path)
else:
self._pending_file = path
return super().event(event)
def setup_logging(log_file_path: str | None = None):
log_formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - [%(name)s] - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
if sys.stdout is not None:
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(log_formatter)
root_logger.addHandler(console_handler)
if log_file_path:
file_handler = RotatingFileHandler(log_file_path, maxBytes=5*1024*1024, backupCount=3)
file_handler.setFormatter(log_formatter)
root_logger.addHandler(file_handler)
logging.info("Logging configured successfully.")
def _kick_off_update_check(window, settings):
from src.core.task_manager import TaskManager
from src.core.update_checker import check_for_update
worker = TaskManager.instance().submit(check_for_update)
worker.signals.result.connect(lambda info: _on_update_result(info, window, settings))
def _on_update_result(info, window, settings):
if info is None:
return
if settings.value("update/skipped_version", "", type=str) == info.version:
return
from src.ui.dialogs.update_dialog import UpdateAvailableDialog
dlg = UpdateAvailableDialog(APP_VERSION, info, parent=window)
dlg.exec()
if dlg.choice == UpdateAvailableDialog.SKIP:
settings.setValue("update/skipped_version", info.version)
def main():
# Console-only logging until QApplication (and thus QStandardPaths) is available
setup_logging()
QApplication.setHighDpiScaleFactorRoundingPolicy(
Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
)
app = ZebraFETApp(sys.argv)
app.setApplicationName("ZebraFET")
app.setApplicationVersion(APP_VERSION)
app.setOrganizationName("ZebraFET")
# Register bundled Inter font so the QSS "font-family: Inter" rule resolves
# consistently across platforms. Without this, Windows falls back to Segoe UI,
# which has taller line metrics and causes descenders to clip in inputs.
for _font in (
"resources/fonts/Inter/Inter-VariableFont_opsz,wght.ttf",
"resources/fonts/Inter/Inter-Italic-VariableFont_opsz,wght.ttf",
):
_fid = QFontDatabase.addApplicationFont(resource_path(_font))
if _fid == -1:
log.warning(f"Failed to load bundled font: {_font}")
# Take the family from the bundled font but the size from the system, so the
# OS text-size setting reaches the interface. The QSS used to pin 11pt on
# QWidget, which overrode it everywhere. The floor is that same 11pt, so the
# default appearance is unchanged and only a larger system setting moves it.
_base_font = app.font()
_base_font.setFamily("Inter")
if _base_font.pointSizeF() > 0:
_base_font.setPointSizeF(max(_base_font.pointSizeF(), DESIGN_BASE_PT))
app.setFont(_base_font)
# Add file handler now that QStandardPaths is available
_app_data = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppDataLocation)
os.makedirs(_app_data, exist_ok=True)
_log_path = os.path.join(_app_data, "zebrafet.log")
_fh = RotatingFileHandler(_log_path, maxBytes=5 * 1024 * 1024, backupCount=3)
_fh.setFormatter(logging.Formatter(
'%(asctime)s - %(levelname)s - [%(name)s] - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
))
logging.getLogger().addHandler(_fh)
logging.info(f"File logging enabled at: {_log_path}")
# Must be instantiated after QApplication so the Signal/Slot mechanism is ready
_relay = _ExceptionRelay()
# Set Application Icon
icon_path = resource_path("resources/icons/fishapp_icon.png")
app.setWindowIcon(QIcon(icon_path))
# Splash Screen Implementation
splash = None
try:
pixmap = QPixmap(icon_path)
splash = CustomSplashScreen(pixmap)
screen_geometry = app.primaryScreen().geometry()
splash.move(screen_geometry.center() - splash.rect().center())
splash.show()
app.processEvents()
except Exception as e:
log.error(f"Could not create or show splash screen: {e}")
settings = app_settings()
# The theme is applied before anything is shown: the setup wizard is the
# first window a new user sees, and it was being drawn unstyled.
theme_manager = ThemeManager(app, settings)
theme_manager.apply_last_theme()
# Icons set from Python pick their variant from here, so the theme has to be
# known before the first window is drawn.
set_icon_theme(theme_manager.current_theme)
# First-run setup wizard — shown before the main window on a fresh install
if not settings.value("setup/completed", False, type=bool):
if splash:
splash.hide()
from src.ui.setup_wizard import SetupWizard
from PySide6.QtWidgets import QDialog
wizard = SetupWizard(settings)
if wizard.exec() != QDialog.DialogCode.Accepted:
sys.exit(0)
if splash:
splash.show()
app.processEvents()
window = MainWindow(settings, theme_manager)
app.set_window(window)
QTimer.singleShot(500, window.show)
if splash:
QTimer.singleShot(600, splash.close_splash)
startup_file = app.consume_pending_file()
if not startup_file and len(sys.argv) > 1:
from src.core.project_exporter import is_importable_archive
candidate = sys.argv[1]
if is_importable_archive(candidate) and os.path.isfile(candidate):
startup_file = candidate
if startup_file:
QTimer.singleShot(900, lambda: window.open_archive(startup_file))
QTimer.singleShot(3000, lambda: _kick_off_update_check(window, settings))
try:
sys.exit(app.exec())
except Exception as e:
logging.critical(f"Application exited with an exception: {e}")
sys.exit(1)
if __name__ == "__main__":
main()