-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.py
More file actions
470 lines (381 loc) · 15.6 KB
/
application.py
File metadata and controls
470 lines (381 loc) · 15.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
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
#!/usr/bin/env python3
# src/core/application.py
from __future__ import annotations
from typing import Optional, Iterable
from PyQt5.QtCore import pyqtSignal, Qt, QThread
from PyQt5.QtWidgets import QProxyStyle, QStyle, QApplication, QProgressDialog, QPushButton
from .helper import Helper
from .configuration import Configuration
from .log import Log
from .ui import MsgBox
import os
import subprocess
# ---------------------------------------------------------------------------
# Custom Style to suppress focus rectangles
# ---------------------------------------------------------------------------
class NoFocusRectStyle(QProxyStyle):
def drawPrimitive(self, element, option, painter, widget=None):
if element == QStyle.PE_FrameFocusRect:
return # skip drawing the focus rect completely
super().drawPrimitive(element, option, painter, widget)
# ---------------------------------------------------------------------------
# Application update dialog
# ---------------------------------------------------------------------------
class ApplicationDialog(QProgressDialog):
canceled_by_user = pyqtSignal()
def __init__(self, parent=None):
super().__init__("Updating...", "Cancel", 0, 0, parent)
self.setWindowModality(Qt.WindowModal)
self.setWindowFlags(
Qt.Dialog | Qt.WindowTitleHint
| Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint
)
self.setObjectName("ApplicationDialog")
self.setMinimumDuration(0)
self.setAutoReset(False)
self.setFixedWidth(300)
# Replace default Cancel button with our own so we can style it if needed
btn = QPushButton("Cancel", self)
btn.clicked.connect(self._on_cancel)
self.setCancelButton(btn)
def _on_cancel(self):
self.canceled_by_user.emit()
self.reject()
# ---------------------------------------------------------------------------
# Background worker for application update
# ---------------------------------------------------------------------------
class ApplicationThread(QThread):
finished_with_result = pyqtSignal(int, bool) # rc, canceled
progress_text = pyqtSignal(str) # label to show in dialog
def __init__(
self,
repo_root: str,
tasks: list[tuple[list[str], str | None]] | None = None,
logger: Log | None = None,
parent=None,
):
super().__init__(parent)
self._repo_root = repo_root
self._tasks = tasks or []
self._logger = logger
def run(self) -> None:
import time
rc = -1
canceled = False
def run_command(args: list[str]) -> int:
nonlocal canceled
try:
proc = subprocess.Popen(args)
except Exception as e:
if self._logger:
self._logger.append(
f"[ApplicationThread] Failed to start command {args!r}: {e}",
channel="system",
level="error",
)
return -1
while True:
if self.isInterruptionRequested():
canceled = True
try:
proc.terminate()
except Exception:
pass
try:
return proc.wait()
except Exception:
return -1
r = proc.poll()
if r is not None:
return r
time.sleep(0.05)
# ---- 1) update repository ---------------------------------------------------
if self._logger:
self._logger.append(
f"[ApplicationThread] Starting git pull in {self._repo_root}",
channel="system",
level="info",
)
self.progress_text.emit("Updating application files...")
rc = run_command(["sudo", "git", "-C", self._repo_root, "pull", "--recurse-submodules"])
if self._logger:
self._logger.append(
f"[ApplicationThread] git pull finished ({rc})",
channel="system",
level="info" if rc == 0 else "error",
)
if rc != 0 or canceled:
self.finished_with_result.emit(rc if rc is not None else -1, canceled)
return
# ---- 2) Post-update tasks -----------------------------------------
for args, label in self._tasks:
if label:
self.progress_text.emit(label)
rc = run_command(args)
if self._logger:
self._logger.append(
f"[ApplicationThread] Command finished ({rc}): {' '.join(args)}",
channel="system",
level="info" if rc == 0 else "error",
)
if rc != 0 or canceled:
break
self.finished_with_result.emit(rc if rc is not None else -1, canceled)
# ---------------------------------------------------------------------------
# Application class
# ---------------------------------------------------------------------------
class Application(QApplication):
updating = pyqtSignal(object)
def __init__(self, name: Optional[str] = None, argv=None):
# Initialize QApplication
super().__init__(argv or [])
# Application name
if name:
self.setApplicationName(name)
# Set application mode
self._mode = "gui"
# Set application style
self.setStyle('Fusion')
# Use custom style to suppress focus rectangles
self.setStyle(NoFocusRectStyle(self.style()))
# Main window placeholder (e.g. Client)
self._mainWindow = None
# Helper
self._helper = Helper()
# Configuration manager
self._configuration = Configuration()
self._configuration.configChanged.connect(self.reset)
# Default configuration entries
self._configuration.add("administration.update", None, "button", label="Check for Updates", action=self.update)
# Save any new defaults
self._configuration.save()
# Logger
self._logger = Log()
# Initial stylesheet load
self._loadStylesheet()
# ------------------------------------------------------------------
# Properties / accessors
# ------------------------------------------------------------------
@property
def helper(self) -> Helper:
return self._helper
@property
def logger(self) -> Log:
return self._logger
@property
def configuration(self) -> Configuration:
return self._configuration
@property
def mainWindow(self):
return self._mainWindow
@property
def name(self) -> str:
return self.applicationName()
@property
def mode(self) -> str:
return self._mode
# ------------------------------------------------------------------
# Main window management
# ------------------------------------------------------------------
def set_mainWindow(self, window):
self._mainWindow = window
self._loadStylesheet()
self._mainWindow.show()
# ------------------------------------------------------------------
# Stylesheet handling
# ------------------------------------------------------------------
def _loadStylesheet(self):
# Base stylesheet (e.g. core/styles/style.css)
base_css = self._helper.load_stylesheet("core/styles/style.css") # you can implement this in Helper
# Retrieve icon paths
check_svg = self._helper.get_path("core/icons/check.svg")
chevron_up_svg = self._helper.get_path("core/icons/chevron-up.svg")
chevron_down_svg = self._helper.get_path("core/icons/chevron-down.svg")
chevron_expand_svg = self._helper.get_path("core/icons/chevron-expand.svg")
# Override styles
override = (
"\n"
"QCheckBox::indicator:checked { "
f"image: {self._helper.qss_url(check_svg)};"
" }\n"
"QComboBox::down-arrow { "
f"image: {self._helper.qss_url(chevron_expand_svg)};"
" }\n"
"QSpinBox::up-arrow { "
f"image: {self._helper.qss_url(chevron_up_svg)};"
" }\n"
"QSpinBox::down-arrow { "
f"image: {self._helper.qss_url(chevron_down_svg)};"
" }\n"
)
# Start with base + global overrides
css = (base_css or "") + override
# If main window has its own override, append it
if self._mainWindow and hasattr(self._mainWindow, "override"):
css += self._mainWindow.override()
# Apply combined stylesheet
self.setStyleSheet(css)
# ------------------------------------------------------------------
# UI reset on configuration change
# ------------------------------------------------------------------
def reset(self):
# Do nothing if no main window
if not self._mainWindow:
return
# Call main window reset if available
if hasattr(self._mainWindow, 'reset'):
self._loadStylesheet()
self._mainWindow.reset()
# ------------------------------------------------------------------
# System Helpers
# ------------------------------------------------------------------
def _run_system_command(self, args: list[str], wait: bool = False) -> int | None:
# Only attempt on Linux; ignore silently on other platforms
try:
os_name = self._helper.get_os()
except Exception:
os_name = None
if os_name != "linux":
if self._logger:
self._logger.append(
f"[Application] Ignoring system command {args!r} on non-Linux OS: {os_name}",
channel="system",
level="warning",
)
return None
try:
if wait:
proc = subprocess.Popen(args)
rc = proc.wait()
if self._logger:
self._logger.append(
f"[Application] (wait) Command finished ({rc}): {' '.join(args)}",
channel="system",
level="info",
)
return rc
else:
subprocess.Popen(args)
if self._logger:
self._logger.append(
f"[Application] Executed system command: {' '.join(args)}",
channel="system",
level="info",
)
return None
except Exception as e:
if self._logger:
self._logger.append(
f"[Application] Failed to execute system command {args!r}: {e}",
channel="system",
level="error",
)
return None
def shutdown(self) -> None:
self._run_system_command(["systemctl", "poweroff"])
def restart(self) -> None:
self._run_system_command(["systemctl", "reboot"])
# ------------------------------------------------------------------
# Application Helpers
# ------------------------------------------------------------------
def update(self):
# Determine repo root
try:
here = os.path.abspath(os.path.dirname(__file__))
repo_root = os.path.abspath(os.path.join(here, "..", ".."))
except Exception as e:
if self._logger:
self._logger.append(
f"[Application] Failed to determine repository root for update: {e}",
channel="system",
level="error",
)
MsgBox.show(
parent=self._mainWindow,
title="Update Failed",
message="Failed to determine the repository root for the update.",
icon="error",
buttons=("OK"),
default="OK",
icon_lookup_fn=self._helper.get_path,
)
return
# Only attempt on Linux
try:
os_name = self._helper.get_os()
except Exception:
os_name = None
if os_name != "linux":
if self._logger:
self._logger.append(
"[Application] Update ignored on non-Linux OS.",
channel="system",
level="warning",
)
MsgBox.show(
parent=self._mainWindow,
title="Update Not Available",
message="Updating is only supported on Linux systems.",
icon="info",
buttons=("OK"),
default="OK",
icon_lookup_fn=self._helper.get_path,
)
return
# --- Build post-update task list via listener -------------------------
tasks: list[tuple[list[str], str | None]] = []
def add_task(args: list[str], label: str | None = None) -> None:
tasks.append((args, label))
# Let external code (main.py) register tasks.
# Those tasks *will* run after git pull in ApplicationThread.
self.updating.emit(add_task)
# --- Create dialog + worker ------------------------------------------
dlg_parent = self._mainWindow if self._mainWindow is not None else None
progress = ApplicationDialog(parent=dlg_parent)
progress.setLabelText(f"Updating {self.name}...")
worker = ApplicationThread(repo_root, tasks=tasks, logger=self._logger, parent=self)
# Update label whenever the worker reports a progress text
worker.progress_text.connect(progress.setLabelText)
def on_worker_finished(rc: int, canceled: bool) -> None:
progress.close()
if canceled:
MsgBox.show(
parent=self._mainWindow,
title="Update Canceled",
message="The update was canceled. The application may not be fully up to date.",
icon="warning",
buttons=("OK"),
default="OK",
icon_lookup_fn=self._helper.get_path,
)
return
if rc not in (0, None):
MsgBox.show(
parent=self._mainWindow,
title="Update Failed",
message=f"Update failed with exit code {rc}. Check the logs for details.",
icon="error",
buttons=("OK"),
default="OK",
icon_lookup_fn=self._helper.get_path,
)
return
# Everything (git + tasks) succeeded
buttons: Iterable[str] = ("Exit", "OK")
choice = MsgBox.show(
parent=self._mainWindow,
title="Update Successful",
message="The application has been updated. Please restart the application to apply the latest changes.",
icon="info",
buttons=buttons,
default="OK",
icon_lookup_fn=self._helper.get_path,
)
if choice == "Exit":
self.quit()
def on_user_cancel() -> None:
worker.requestInterruption()
progress.canceled_by_user.connect(on_user_cancel)
worker.finished_with_result.connect(on_worker_finished)
progress.show()
worker.start()