Mainthread tool is a singleton that's reused to avoid C++ thread deletion issues. Also the sync screen initial load flow is improved

This commit is contained in:
SimplifiedPrivacy 2026-10-30 15:03:30 -04:00
parent 3315cffda3
commit 5030317b3b
16 changed files with 258 additions and 306 deletions

View file

@ -1,3 +1,4 @@
from core.errors.logger import logger from core.errors.logger import logger
from core.models.manage.session_management import init_session, get_session, close_session, create_ALL_tables, create_ONLY_db_version_table, get_path, does_it_exist, does_db_version_table_exist from core.models.manage.session_management import init_session, get_session, close_session, create_ALL_tables, create_ONLY_db_version_table, get_path, does_it_exist, does_db_version_table_exist
from core.models.manage.version_check import check_database_compatibility, insert_new_version, get_custom_message from core.models.manage.version_check import check_database_compatibility, insert_new_version, get_custom_message
@ -72,36 +73,8 @@ def recovery_dialog(custom_error, db_version_you_have):
def emergency_sync(): def emergency_sync():
from gui.v2.ui.popups.generic_choice import show_generic_options from gui.main_ui import start_ui
from gui.v2.ui.popups.terminal_threading import show_terminal start_ui(force_sync=True)
option = show_generic_options(
title="Sync the Database",
option_one="Clearweb (fastest)",
option_two="Tor",
option_three="No, Exit."
)
if option == 3:
sys.exit()
client_observer = ClientObserver()
connection_observer = ConnectionObserver()
if option == 1:
ConfigurationController.set_connection("system")
elif option == 2:
ConfigurationController.set_connection("tor")
# setup the function to be able to have the UI background thread run it.
do_this_function = partial(new_sync, client_observer, connection_observer)
return show_terminal(
do_this_function=do_this_function,
connection_observer=connection_observer,
client_observer=client_observer
)
# ============================================================================ # ============================================================================
# BEGIN PROGRAM # BEGIN PROGRAM

View file

@ -28,8 +28,10 @@ from core.infrastructure.global_state_coordinator import quantity_connected
core_logger.propagate = False core_logger.propagate = False
from gui.v2.infrastructure.ThreadSafetyTool import ThreadSafetyTool from gui.v2.ui.popups.generic_choice import GenericOptionMenu
mainthread = ThreadSafetyTool() from gui.v2.ui.popups.terminal_threading import NotificationTerminalUI
from gui.v2.infrastructure.thread_singleton import get_main_thread_dispatcher
mainthread = get_main_thread_dispatcher()
# Sync: # Sync:
from gui.v2.actions.menu_coordinator import sync_now from gui.v2.actions.menu_coordinator import sync_now
@ -930,8 +932,75 @@ class CustomWindow(QMainWindow):
self.page_history.append(current_page) self.page_history.append(current_page)
# Global variable to prevent the window from being garbage collected
main_window = None
def force_shutdown():
app = QApplication.instance()
if app:
print("Exiting due to failed initial sync.")
app.quit()
else:
print("No application instance running.")
def launch_app():
global main_window
print("Showing window")
main_window = CustomWindow() # Assign to global so it doesn't disappear
main_window.show()
def finish_sync(result):
if result.valid:
print("finished sync, launching UI..")
launch_app() # Now this ONLY calls .show(), not .exec()
def initiate_force_sync():
menu = GenericOptionMenu(
title="Sync the Database",
option_one="Clearweb (fastest)",
option_two="Tor",
option_three="No, Exit."
)
# Show the menu and get the result
result = menu.exec()
# Get Choice:
if result == QDialog.DialogCode.Accepted:
print(f"User selected option: {menu.selected_option}")
option = menu.selected_option
else:
print("User cancelled selecting")
option = 1
# Option Choice:
if option == 1:
ConfigurationController.set_connection("system")
elif option == 2:
ConfigurationController.set_connection("tor")
elif option == 3:
sys.exit()
else:
print("Invalid option")
sys.exit()
# Start the sync process
sync_now(ui_caller=finish_sync)
# starts a LOCAL event loop. It blocks here until the dialog is closed.
dialog = NotificationTerminalUI()
dialog.exec()
def start_ui(force_sync): def start_ui(force_sync):
app = QApplication(sys.argv) app = QApplication(sys.argv)
calculate_max_screensize(app)
window = CustomWindow(force_sync=force_sync) if force_sync:
# blocks until the popup is closed
initiate_force_sync()
else:
# Just show the window immediately
launch_app()
# finally, start the GLOBAL event loop for the entire application.
sys.exit(app.exec()) sys.exit(app.exec())

View file

@ -299,8 +299,8 @@ def menu_icon_path(btn_path: str, label_name: str, value: Mapping[str, Any], con
"""Choose menu asset paths outside Qt so protocol mapping remains declarative and reusable.""" """Choose menu asset paths outside Qt so protocol mapping remains declarative and reusable."""
# print(f"menu_icon_path btn_path is {btn_path}") # print(f"menu_icon_path btn_path is {btn_path}")
print(f"menu_icon_path label_name is {label_name}") # print(f"menu_icon_path label_name is {label_name}")
print(f"menu_icon_path value is {value}") # print(f"menu_icon_path value is {value}")
# if label_name == "location": # if label_name == "location":
# print(f"converting location ({label_name}) to lowercase for {value[label_name]}") # print(f"converting location ({label_name}) to lowercase for {value[label_name]}")

View file

@ -17,7 +17,7 @@ from core.observers.Notifications import Notifications, EventType
# gui # gui
from gui.v2.infrastructure.action_registry import register_action from gui.v2.infrastructure.action_registry import register_action
from gui.v2.actions.ticket_actions import fetch_ticket_invoice from gui.v2.actions.ticket_actions import fetch_ticket_invoice
from gui.v2.infrastructure.ThreadSafetyTool import ThreadSafetyTool from gui.v2.infrastructure.thread_singleton import get_main_thread_dispatcher
from gui.v2.infrastructure.take_plumbing_action import take_action from gui.v2.infrastructure.take_plumbing_action import take_action
from gui.v2.infrastructure.setup_observers import connection_observer from gui.v2.infrastructure.setup_observers import connection_observer
from gui.v2.actions.error_handlers import navigate_to_new_sub_page from gui.v2.actions.error_handlers import navigate_to_new_sub_page
@ -168,7 +168,7 @@ def start_polling(billing_code: str, profile_id: int, ui_caller: Callable) -> st
logger.info("Starting a check paid timer..") logger.info("Starting a check paid timer..")
# Setup PyQt6 GUI as mainthread to bring back to: # Setup PyQt6 GUI as mainthread to bring back to:
pyqt_threader = ThreadSafetyTool() pyqt_threader = get_main_thread_dispatcher()
# update the global singleton: # update the global singleton:
payment_cycle.already_polling = True payment_cycle.already_polling = True
@ -384,7 +384,7 @@ def stop_payment_timer() -> Result:
# return False # return False
# # Setup PyQt6 GUI as mainthread to bring back to: # # Setup PyQt6 GUI as mainthread to bring back to:
# pyqt_threader = ThreadSafetyTool() # pyqt_threader =
# # setup the timer with the callback: # # setup the timer with the callback:
# # it doesn't return result here. It calls the gui_callback function. # # it doesn't return result here. It calls the gui_callback function.

View file

@ -26,4 +26,3 @@ class ThreadSafetyTool(QObject):
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
self._signal.emit(func, args, kwargs) self._signal.emit(func, args, kwargs)
return wrapper return wrapper

View file

@ -1,8 +1,8 @@
from core.infrastructure.plumbing import ThreadPlumbing from core.infrastructure.plumbing import ThreadPlumbing
from core.models.Result import ResultError from core.models.Result import ResultError
from gui.v2.infrastructure.thread_singleton import get_main_thread_dispatcher
from gui.v2.infrastructure.action_registry import ENUM_MAP from gui.v2.infrastructure.action_registry import ENUM_MAP
from gui.v2.infrastructure.ThreadSafetyTool import ThreadSafetyTool
from gui.v2.ui.popups.error_popup import ErrorPopup from gui.v2.ui.popups.error_popup import ErrorPopup
from gui.v2.ui.popups.stack_error_popup import ErrorStackPrompt from gui.v2.ui.popups.stack_error_popup import ErrorStackPrompt
@ -18,7 +18,7 @@ def take_action(action: Callable, ui_caller: Callable, *args, **kwargs):
controller = ThreadPlumbing( controller = ThreadPlumbing(
action=action, action=action,
ui_dispatcher=ThreadSafetyTool(), # PyQt6 as mainthread ui_dispatcher=get_main_thread_dispatcher(), # PyQt6 same instance
error_implementation=ErrorPopup, # PyQt6 ErrorPopup error_implementation=ErrorPopup, # PyQt6 ErrorPopup
stack_error_implementation=ErrorStackPrompt, # PyQt6 stack_error_implementation=ErrorStackPrompt, # PyQt6
ENUM_MAP=ENUM_MAP, ENUM_MAP=ENUM_MAP,

View file

@ -0,0 +1,11 @@
from gui.v2.infrastructure.ThreadSafetyTool import ThreadSafetyTool
# singleton that lives for the entire life of the app.
_global_main_thread_tool = None
def get_main_thread_dispatcher():
global _global_main_thread_tool
if _global_main_thread_tool is None:
print("Initializing Global Thread Safety Tool...")
_global_main_thread_tool = ThreadSafetyTool()
return _global_main_thread_tool

View file

@ -4,8 +4,8 @@ from core.errors.logger import logger
from gui.v2.ui.popups.error_popup import ErrorPopup from gui.v2.ui.popups.error_popup import ErrorPopup
from gui.v2.infrastructure.ThreadSafetyTool import ThreadSafetyTool from gui.v2.infrastructure.thread_singleton import get_main_thread_dispatcher
mainthread = ThreadSafetyTool() mainthread = get_main_thread_dispatcher()
import os import os

View file

@ -11,8 +11,8 @@ from core.models.Result import Result
from gui.v2.ui.styles.payment_styles import DURATION_SELECTION_STYLE, NEXT_BUTTON_STYLE from gui.v2.ui.styles.payment_styles import DURATION_SELECTION_STYLE, NEXT_BUTTON_STYLE
from gui.v2.ui.pages.Page import Page from gui.v2.ui.pages.Page import Page
from gui.v2.infrastructure.ThreadSafetyTool import ThreadSafetyTool from gui.v2.infrastructure.thread_singleton import get_main_thread_dispatcher
mainthread = ThreadSafetyTool() mainthread = get_main_thread_dispatcher()
from PyQt6.QtWidgets import QComboBox, QLabel, QPushButton from PyQt6.QtWidgets import QComboBox, QLabel, QPushButton
from PyQt6 import QtCore from PyQt6 import QtCore

View file

@ -39,8 +39,8 @@ from gui.v2.infrastructure.setup_observers import (
profile_observer profile_observer
) )
from gui.v2.infrastructure.ThreadSafetyTool import ThreadSafetyTool from gui.v2.infrastructure.thread_singleton import get_main_thread_dispatcher
mainthread = ThreadSafetyTool() mainthread = get_main_thread_dispatcher()
from typing import Optional from typing import Optional

View file

@ -18,9 +18,8 @@ from gui.v2.ui.popups.qrcode_dialog import QRCodeDialog
from gui.v2.ui.styles.css.payment_styles import PAYMENT_STYLE_SHEET from gui.v2.ui.styles.css.payment_styles import PAYMENT_STYLE_SHEET
# Bring background threads to the main thread UI: # Bring background threads to the main thread UI:
from gui.v2.infrastructure.ThreadSafetyTool import ThreadSafetyTool from gui.v2.infrastructure.thread_singleton import get_main_thread_dispatcher
mainthread = get_main_thread_dispatcher()
mainthread = ThreadSafetyTool()
# generic # generic
from typing import Optional from typing import Optional

View file

@ -9,8 +9,8 @@ from core.models.Result import Result
from gui.v2.actions.menu_coordinator import sync_now from gui.v2.actions.menu_coordinator import sync_now
from gui.v2.ui.pages.Page import Page from gui.v2.ui.pages.Page import Page
from gui.v2.workers.worker_thread import WorkerThread from gui.v2.workers.worker_thread import WorkerThread
from gui.v2.infrastructure.ThreadSafetyTool import ThreadSafetyTool from gui.v2.infrastructure.thread_singleton import get_main_thread_dispatcher
mainthread = ThreadSafetyTool() mainthread = get_main_thread_dispatcher()
class SyncScreen(Page): class SyncScreen(Page):

View file

@ -12,8 +12,9 @@ from gui.v2.infrastructure.take_plumbing_action import take_action
from gui.v2.actions.ticket_actions import get_ticket_data, use_a_ticket from gui.v2.actions.ticket_actions import get_ticket_data, use_a_ticket
# Bring background threads to the main thread UI: # Bring background threads to the main thread UI:
from gui.v2.infrastructure.ThreadSafetyTool import ThreadSafetyTool
mainthread = ThreadSafetyTool() from gui.v2.infrastructure.thread_singleton import get_main_thread_dispatcher
mainthread = get_main_thread_dispatcher()
from PyQt6.QtWidgets import QLabel, QListWidget, QListWidgetItem, QPushButton from PyQt6.QtWidgets import QLabel, QListWidget, QListWidgetItem, QPushButton

View file

@ -133,31 +133,34 @@ class GenericOptionMenu(QDialog):
self.selected_option = button_num self.selected_option = button_num
self.accept() self.accept()
def show_generic_options( # prior version as standalone helper:
title: str,
option_one: str,
option_two: str,
option_three: str
) -> int:
app = QApplication(sys.argv) # def show_generic_options(
# app: QApplication,
# title: str,
# option_one: str,
# option_two: str,
# option_three: str
# ) -> int:
# Create the menu with custom title and options # # app = QApplication(sys.argv)
menu = GenericOptionMenu(
title=title,
option_one=option_one,
option_two=option_two,
option_three=option_three
)
# Show the menu and get the result # # Create the menu with custom title and options
result = menu.exec() # menu = GenericOptionMenu(
# title=title,
# option_one=option_one,
# option_two=option_two,
# option_three=option_three
# )
if result == QDialog.DialogCode.Accepted: # # Show the menu and get the result
print(f"User selected option: {menu.selected_option}") # result = menu.show()
return menu.selected_option
else:
print("User cancelled")
return None
sys.exit(0) # if result == QDialog.DialogCode.Accepted:
# print(f"User selected option: {menu.selected_option}")
# return menu.selected_option
# else:
# print("User cancelled")
# return None
# sys.exit(0)

View file

@ -1,85 +1,38 @@
from gui.v2.infrastructure.ThreadSafetyTool import ThreadSafetyTool from gui.v2.infrastructure.thread_singleton import get_main_thread_dispatcher
from core.observers.Notifications import Notifications, EventType from core.observers.Notifications import Notifications, EventType
from core.observers.ConnectionObserver import ConnectionObserver from gui.v2.ui.styles.css.terminal_style import (
from core.observers.ClientObserver import ClientObserver TERMINAL_TITLE_LABEL, OVERALL_STYLE_SHEET_COLORS,
from core.services.networking.api_requests.ApiResponseModel import ApiResponse, ErrorType STATUS_LABEL_STYLE, OUTPUT_TEXT_STYLE
from core.controllers.SyncController import new_sync )
from core.models.Result import Result, ResultError
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QTextEdit, from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QTextEdit,
QLabel, QPushButton, QApplication) QLabel)
from PyQt6.QtGui import QFont, QColor, QTextCursor from PyQt6.QtGui import QFont, QColor
from PyQt6.QtCore import Qt, QTimer, QThread, pyqtSignal, pyqtSlot from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtWidgets import QGraphicsDropShadowEffect from PyQt6.QtWidgets import QGraphicsDropShadowEffect
import sys
import traceback
from typing import Callable, Any
from PyQt6.QtGui import QTextCharFormat from PyQt6.QtGui import QTextCharFormat
import threading mainthread = get_main_thread_dispatcher()
from threading import Thread
INITIAL_PLACEHOLDER = "◄ WAITING FOR TASK START ►"
DISPLAYED_TITLE = "▓░ NOTIFICATION TERMINAL ░▓"
INIT_WINDOW_TITLE = "SYNC PROCESS"
class NotificationTerminalUI(QDialog): class NotificationTerminalUI(QDialog):
def __init__(self, connection_observer: ConnectionObserver, client_observer: ClientObserver): def __init__(self):
super().__init__() super().__init__()
self.mainthread = ThreadSafetyTool()
self.connection_observer = connection_observer
self.client_observer = client_observer
self.synchronized = False self.synchronized = False
self.worker_thread = None self.worker_thread = None
self.task_success = False self.task_success = False
Notifications.subscribe(EventType.STATUS_UPDATE, self.add_notification_from_eventbus) Notifications.subscribe(EventType.STATUS_UPDATE, self.add_notification)
Notifications.subscribe(EventType.SYNC_COMPLETE, self.on_synchronized)
# self.connection_observer.subscribe("message",
# lambda msg: self.add_notification("UPDATE", msg, "#00ff88"))
# self.connection_observer.subscribe("connecting",
# lambda msg: self.add_notification("CONNECT", msg, "#00ff88"))
# self.connection_observer.subscribe("tor_bootstrapping",
# lambda msg: self.add_notification("BOOTSTRAP", msg, "#00d4ff"))
# self.connection_observer.subscribe("tor_bootstrap_progressing",
# lambda msg: self.add_notification("PROGRESS", msg, "#ff0088"))
# self.connection_observer.subscribe("tor_bootstrapped",
# lambda msg: self.add_notification("SUCCESS", msg, "#00ff88"))
# self.connection_observer.subscribe("custom_message",
# lambda msg: self.add_notification("INFO", msg, "#ffff00"))
# Subscribe to client_observer events
self.client_observer.subscribe("synchronizing",
lambda event: self.add_notification("SYNC",
event.subject if event.subject else "Sync in progress...", "#00d4ff"))
self.client_observer.subscribe("synchronized",
lambda event: self.on_synchronized())
self.client_observer.subscribe("updating",
lambda event: self.add_notification("UPDATE", "Updating client...", "#ff0088"))
self.client_observer.subscribe("update_progressing",
lambda event: self.add_notification("PROGRESS",
f'Current progress: {event.meta.get("progress", 0):.2f}%', "#ffff00"))
self.client_observer.subscribe("updated",
lambda event: self.add_notification("COMPLETE",
"Restart client to apply update.", "#00ff88"))
self.client_observer.subscribe("custom_message",
lambda event: self.add_notification("ERROR",
event.subject if event.subject else "Error, check logs", "#ff0088"))
self.init_ui() self.init_ui()
def init_ui(self): def init_ui(self):
self.setWindowTitle("SYNC PROCESS") self.setWindowTitle(INIT_WINDOW_TITLE)
self.setGeometry(100, 100, 700, 600) self.setGeometry(100, 100, 700, 600)
self.setModal(True) self.setModal(True)
@ -87,27 +40,13 @@ class NotificationTerminalUI(QDialog):
layout.setSpacing(15) layout.setSpacing(15)
layout.setContentsMargins(30, 30, 30, 30) layout.setContentsMargins(30, 30, 30, 30)
self.setStyleSheet(""" self.setStyleSheet(OVERALL_STYLE_SHEET_COLORS)
QDialog {
background-color: #0a0e27;
color: #00ff88;
}
""")
# Title Label # Title Label
title_label = QLabel("▓░ NOTIFICATION TERMINAL ░▓") title_label = QLabel(DISPLAYED_TITLE)
title_label.setFont(QFont("Courier New", 14, QFont.Weight.Bold)) title_label.setFont(QFont("Courier New", 14, QFont.Weight.Bold))
title_label.setAlignment(Qt.AlignmentFlag.AlignCenter) title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
title_label.setStyleSheet(""" title_label.setStyleSheet(TERMINAL_TITLE_LABEL)
QLabel {
color: #00ff88;
background-color: transparent;
padding: 15px;
border: 2px solid #00ff88;
border-radius: 5px;
letter-spacing: 2px;
}
""")
title_shadow = QGraphicsDropShadowEffect() title_shadow = QGraphicsDropShadowEffect()
title_shadow.setBlurRadius(15) title_shadow.setBlurRadius(15)
title_shadow.setColor(QColor(0, 255, 136, 200)) title_shadow.setColor(QColor(0, 255, 136, 200))
@ -120,177 +59,60 @@ class NotificationTerminalUI(QDialog):
self.output_text.setReadOnly(True) self.output_text.setReadOnly(True)
self.output_text.setFont(QFont("Courier New", 10)) self.output_text.setFont(QFont("Courier New", 10))
self.output_text.setMinimumHeight(400) self.output_text.setMinimumHeight(400)
self.output_text.setStyleSheet(""" self.output_text.setStyleSheet(OUTPUT_TEXT_STYLE)
QTextEdit {
background-color: #1a1f3a;
color: #00ff88;
border: 2px solid #00ff88;
border-radius: 5px;
padding: 15px;
font-size: 16pt;
font-family: 'Courier New', monospace;
selection-background-color: #ff0088;
}
QScrollBar:vertical {
background-color: #0a0e27;
width: 12px;
border-radius: 6px;
}
QScrollBar::handle:vertical {
background-color: #00ff88;
border-radius: 6px;
min-height: 20px;
}
QScrollBar::handle:vertical:hover {
background-color: #00d4ff;
}
""")
layout.addWidget(self.output_text) layout.addWidget(self.output_text)
# Status label # Status label
self.status_label = QLabel("◄ WAITING FOR TASK START ►") self.status_label = QLabel(INITIAL_PLACEHOLDER)
self.status_label.setFont(QFont("Courier New", 9)) self.status_label.setFont(QFont("Courier New", 9))
self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter) self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.status_label.setStyleSheet(""" self.status_label.setStyleSheet(STATUS_LABEL_STYLE)
QLabel {
color: #ff0088;
background-color: transparent;
padding: 8px;
letter-spacing: 1px;
}
""")
layout.addWidget(self.status_label) layout.addWidget(self.status_label)
# Button layout # Button layout
button_layout = QHBoxLayout() # button_layout = QHBoxLayout()
clear_btn = QPushButton("CLEAR") # # clear_btn = QPushButton("CLEAR")
clear_btn.setFont(QFont("Courier New", 10, QFont.Weight.Bold)) # # clear_btn.setFont(QFont("Courier New", 10, QFont.Weight.Bold))
clear_btn.setMinimumHeight(40) # # clear_btn.setMinimumHeight(40)
clear_btn.setCursor(Qt.CursorShape.PointingHandCursor) # # clear_btn.setCursor(Qt.CursorShape.PointingHandCursor)
clear_btn.setStyleSheet(""" # # clear_btn.setStyleSheet(CLEAR_BUTTON_STYLE)
QPushButton { # # clear_btn.clicked.connect(self.clear_output)
background-color: #1a1f3a; # shadow = QGraphicsDropShadowEffect()
color: #00d4ff; # shadow.setBlurRadius(15)
border: 2px solid #00d4ff; # shadow.setColor(QColor(0, 212, 255))
border-radius: 5px; # shadow.setOffset(0, 0)
padding: 8px 20px; # clear_btn.setGraphicsEffect(shadow)
font-weight: bold; # button_layout.addWidget(clear_btn)
} # button_layout.addStretch()
QPushButton:hover { # layout.addLayout(button_layout)
background-color: #00d4ff;
color: #0a0e27;
}
QPushButton:pressed {
background-color: #0a0e27;
border: 3px solid #00d4ff;
}
""")
clear_btn.clicked.connect(self.clear_output)
shadow = QGraphicsDropShadowEffect()
shadow.setBlurRadius(15)
shadow.setColor(QColor(0, 212, 255))
shadow.setOffset(0, 0)
clear_btn.setGraphicsEffect(shadow)
button_layout.addWidget(clear_btn)
button_layout.addStretch()
layout.addLayout(button_layout)
def add_notification_from_eventbus(self, message: str): @mainthread
def add_notification(self, message: str, *args, **kwargs):
"""Queue to main thread safely.""" """Queue to main thread safely."""
self.mainthread(lambda: self._add_notification_impl(prefix="Connect/Sync", message=message, color="#00ff88"))() prefix = "Connect/Sync"
color = "#00ff88"
def add_notification(self, prefix: str, message: str, color: str = "#00ff88"):
"""Queue to main thread safely."""
self.mainthread(lambda: self._add_notification_impl(prefix, message, color))()
def _add_notification_impl(self, prefix: str, message: str, color: str):
"""Actual implementation on main thread."""
cursor = self.output_text.textCursor() cursor = self.output_text.textCursor()
cursor.movePosition(cursor.MoveOperation.End) cursor.movePosition(cursor.MoveOperation.End)
fmt = QTextCharFormat() fmt = QTextCharFormat()
fmt.setForeground(QColor(color)) fmt.setForeground(QColor(color))
cursor.insertText(f"[{prefix}] {message}\n", fmt) cursor.insertText(f"[{prefix}] {message}\n", fmt)
self.output_text.setTextCursor(cursor) self.output_text.setTextCursor(cursor)
self.output_text.ensureCursorVisible() self.output_text.ensureCursorVisible()
if message == "Finshed sync.": @mainthread
print("Close Event")
self.accept()
def set_status(self, text: str): def set_status(self, text: str):
"""This runs on the main thread, safely.""" """This runs on the main thread, safely."""
self.status_label.setText(text) self.status_label.setText(text)
def on_synchronized(self): @mainthread
def on_synchronized(self, message: str):
"""Handle synchronized notification and exit.""" """Handle synchronized notification and exit."""
self.add_notification("SYNC", "Sync complete ✓", "#00ff88") self.add_notification("SYNC", message, "#00ff88")
self.set_status("◄ SYNCHRONIZED - CLOSING ►") self.set_status("◄ SYNCHRONIZED - CLOSING ►")
self.synchronized = True
self.task_success = True
QTimer.singleShot(500, self.accept) QTimer.singleShot(500, self.accept)
# "Sync complete ✓"
def run_task(self, task_func: Callable):
"""
Purpose:
Insert any function for a pure python background thread.
Which then pushes to the main UI via ThreadSafety
"""
if self.worker_thread is not None and self.worker_thread.is_alive():
self.add_notification("SYSTEM", "Task already running!", "#ff0088")
return
self.set_status("◄ TASK RUNNING ►")
self.add_notification("SYSTEM", "Background task started", "#00d4ff")
# Start in pure Python thread (daemon=True so it doesn't block exit)
self.worker_thread = Thread(target=self._run_task_wrapper, args=(task_func,), daemon=True)
self.worker_thread.start()
def _run_task_wrapper(self, task_func: Callable):
"""Wrapper that runs task and handles errors."""
try:
task_func()
self.task_success = True
except Exception as e:
self.add_notification("ERROR", f"Task failed: {str(e)}", "#ff0088")
self.set_status("◄ TASK FAILED ►")
self.task_success = False
def clear_output(self):
"""Clear the terminal output."""
self.output_text.clear()
self.add_notification("SYSTEM", "Terminal cleared", "#00d4ff")
def get_result(self) -> bool:
"""Return True if synchronized, False otherwise."""
return self.synchronized and self.task_success
def closeEvent(self, event):
"""Ensure thread is properly cleaned up on close."""
if self.worker_thread is not None and self.worker_thread.is_alive():
self.worker_thread.join(timeout=1)
event.accept()
def show_terminal(
do_this_function: Callable[[Any, Any], None],
connection_observer: ConnectionObserver,
client_observer: ClientObserver
) -> bool:
app = QApplication.instance() or QApplication(sys.argv)
# Create the UI
dialog = NotificationTerminalUI(connection_observer=connection_observer, client_observer=client_observer)
# Start the background task
dialog.run_task(do_this_function)
# Show dialog and wait
dialog.exec()
# Return success
return dialog.get_result()

View file

@ -0,0 +1,75 @@
TERMINAL_TITLE_LABEL = """
QLabel {
color: #00ff88;
background-color: transparent;
padding: 15px;
border: 2px solid #00ff88;
border-radius: 5px;
letter-spacing: 2px;
}
"""
OUTPUT_TEXT_STYLE = """
QTextEdit {
background-color: #1a1f3a;
color: #00ff88;
border: 2px solid #00ff88;
border-radius: 5px;
padding: 15px;
font-size: 16pt;
font-family: 'Courier New', monospace;
selection-background-color: #ff0088;
}
QScrollBar:vertical {
background-color: #0a0e27;
width: 12px;
border-radius: 6px;
}
QScrollBar::handle:vertical {
background-color: #00ff88;
border-radius: 6px;
min-height: 20px;
}
QScrollBar::handle:vertical:hover {
background-color: #00d4ff;
}
"""
STATUS_LABEL_STYLE = """
QLabel {
color: #ff0088;
background-color: transparent;
padding: 8px;
letter-spacing: 1px;
}
"""
CLEAR_BUTTON_STYLE = """
QPushButton {
background-color: #1a1f3a;
color: #00d4ff;
border: 2px solid #00d4ff;
border-radius: 5px;
padding: 8px 20px;
font-weight: bold;
}
QPushButton:hover {
background-color: #00d4ff;
color: #0a0e27;
}
QPushButton:pressed {
background-color: #0a0e27;
border: 3px solid #00d4ff;
}
"""
OVERALL_STYLE_SHEET_COLORS = """
QDialog {
background-color: #0a0e27;
color: #00ff88;
}
"""