mirror of
https://github.com/Project-Babble/ProjectBabble.git
synced 2026-11-20 00:51:16 -08:00
Merge pull request #98 from BigMrLemon/app_improvements
thread handling improvements, seperate file for constants, async impr…
This commit is contained in:
20 files changed
+270
-86
No files matched your search
@@ -1 +1,3 @@
|
||||
*.log
|
||||
eval/id_rsa
|
||||
eval/id_rsa.pub
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Algo Settings",
|
||||
"babble.calibrationPage": "Calibration",
|
||||
"babble.exit": "Exiting Babble App",
|
||||
"babble.invalidVersionFormat": "Invalid version format received from GitHub API.",
|
||||
"babble.updateTimeout": "Timeout occurred while checking for updates.",
|
||||
"babble.updateHttpError": "HTTP error occurred while checking for updates.",
|
||||
"babble.updateCheckFailed": "Failed to check for updates due to an unexpected error.",
|
||||
"calibration.header": "Calibration Settings",
|
||||
"calibration.mode": "Calibration Mode",
|
||||
"calibration.modeTooltip": "Neutral = Only Min values are set when starting and stopping calibration. Full = Min and Max values are set based on recorded values when starting calibration.",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Algo Settings",
|
||||
"babble.calibrationPage": "Calibration",
|
||||
"babble.exit": "Exiting Babble App",
|
||||
"babble.invalidVersionFormat": "Invalid version format received from GitHub API.",
|
||||
"babble.updateTimeout": "Timeout occurred while checking for updates.",
|
||||
"babble.updateHttpError": "HTTP error occurred while checking for updates.",
|
||||
"babble.updateCheckFailed": "Failed to check for updates due to an unexpected error.",
|
||||
"calibration.header": "Calibration Settings",
|
||||
"calibration.mode": "Calibration Mode",
|
||||
"calibration.modeTooltip": "Neutral = Only Min values are set when starting and stopping calibration. Full = Min and Max values are set based on recorded values when starting calibration.",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Algo-Einstellungen",
|
||||
"babble.calibrationPage": "Kalibrierung",
|
||||
"babble.exit": "Babble-App wird beendet",
|
||||
"babble.invalidVersionFormat": "Ungültiges Versionsformat von der GitHub API empfangen.",
|
||||
"babble.updateTimeout": "Timeout aufgetreten beim Prüfen auf Updates.",
|
||||
"babble.updateHttpError": "HTTP-Fehler aufgetreten beim Prüfen auf Updates.",
|
||||
"babble.updateCheckFailed": "Fehler beim Prüfen auf Updates wegen eines unerwarteten Fehlers.",
|
||||
"calibration.header": "Kalibrierung",
|
||||
"calibration.mode": "Kalibrierungs-Modus",
|
||||
"calibration.modeTooltip": "Neutral = Beim Starten und Stoppen der Kalibrierung werden nur Mindestwerte festgelegt. Voll = Beim Starten der Kalibrierung werden Mindest- und Höchstwerte basierend auf den aufgezeichneten Werten festgelegt.",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Also Settings",
|
||||
"babble.calibrationPage": "Calibration",
|
||||
"babble.exit": "Exiting Babble App",
|
||||
"babble.invalidVersionFormat": "Invalid version format received from GitHub API.",
|
||||
"babble.updateTimeout": "Timeout occurred while checking for updates.",
|
||||
"babble.updateHttpError": "HTTP error occurred while checking for updates.",
|
||||
"babble.updateCheckFailed": "Failed to check for updates due to an unexpected error.",
|
||||
"calibration.header": "Calibration Settings",
|
||||
"calibration.mode": "Calibration Mode",
|
||||
"calibration.modeTooltip": "Neutral = Only Min values are set when starting and stopping calibration. Full = Min and Max values are set based on recorded values when starting calibration.",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Ajustes de Algoritmo",
|
||||
"babble.calibrationPage": "Calibración",
|
||||
"babble.exit": "Saliendo de la App Babble",
|
||||
"babble.invalidVersionFormat": "Formato de versión inválido recibido de la API de GitHub.",
|
||||
"babble.updateTimeout": "Se produjo un timeout al verificar actualizaciones.",
|
||||
"babble.updateHttpError": "Se produjo un error HTTP al verificar actualizaciones.",
|
||||
"babble.updateCheckFailed": "No se pudieron verificar las actualizaciones debido a un error inesperado.",
|
||||
"calibration.header": "Configuración de Calibración",
|
||||
"calibration.mode": "Modo de Calibración",
|
||||
"calibration.modeTooltip": "Neutral = Solo se establecen los valores mínimos al iniciar y detener la calibración. Completa = Se establecen los valores Mín y Máx en base a los valores registrados al iniciar la calibración.",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Paramètres d'algorithme",
|
||||
"babble.calibrationPage": "Calibration",
|
||||
"babble.exit": "Sortie de l'application Babble",
|
||||
"babble.invalidVersionFormat": "Format de version invalide reçu de l'API GitHub.",
|
||||
"babble.updateTimeout": "Délai d'attente dépassé lors de la vérification des mises à jour.",
|
||||
"babble.updateHttpError": "Erreur HTTP lors de la vérification des mises à jour.",
|
||||
"babble.updateCheckFailed": "Échec de la vérification des mises à jour en raison d'une erreur inattendue.",
|
||||
"calibration.header": "Paramètres de calibration",
|
||||
"calibration.mode": "Mode de calibration",
|
||||
"calibration.modeTooltip": "Neutre = Seulement les valeurs minimales sont appliquées au démarrage et à l'arrêt de la calibration. Entière = Les valeurs minimales et maximales sont appliquées en fonction des valeurs enregistrées au début de la calibration.",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Pengaturan Algo",
|
||||
"babble.calibrationPage": "Kalibrasi",
|
||||
"babble.exit": "Tutup App Babble",
|
||||
"babble.invalidVersionFormat": "Format versi tidak valid diterima dari API GitHub.",
|
||||
"babble.updateTimeout": "Waktu tunggu habis saat memeriksa pembaruan.",
|
||||
"babble.updateHttpError": "Kesalahan HTTP saat memeriksa pembaruan.",
|
||||
"babble.updateCheckFailed": "Pemeriksaan pembaruan gagal karena kesalahan yang tidak terduga.",
|
||||
"calibration.header": "Pengaturan Kalibrasi",
|
||||
"calibration.mode": "Mode Kalibrasi",
|
||||
"calibration.modeTooltip": "Neutral = Hanya nilai Min ditentukan ketika mulai dan berhenti kalibrasi. Full = Nilai Min dan Maks menjadi dasar nilai yang terekam ketika memulai kalibrasi.",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Impostazioni Algoritmo",
|
||||
"babble.calibrationPage": "Calibrazione",
|
||||
"babble.exit": "Uscendo Dall'App Babble",
|
||||
"babble.invalidVersionFormat": "Formato versione non valido ricevuto dall'API GitHub.",
|
||||
"babble.updateTimeout": "Timeout superato durante la verifica degli aggiornamenti.",
|
||||
"babble.updateHttpError": "Errore HTTP durante la verifica degli aggiornamenti.",
|
||||
"babble.updateCheckFailed": "Verifica degli aggiornamenti non riuscita a causa di un errore imprevisto.",
|
||||
"calibration.header": "Impostazioni Calibrazione",
|
||||
"calibration.mode": "Modalità Calibrazione",
|
||||
"calibration.modeTooltip": "Neutrale = Vengono impostati solo i valori minimi all'avvio e all'arresto della calibrazione. Completo = Valori minimi e massimi sono impostati in base ai valori registrati quando si inizia la calibrazione.",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Algo Instellingen",
|
||||
"babble.calibrationPage": "Kalibratie",
|
||||
"babble.exit": "Babble App Verlaten",
|
||||
"babble.invalidVersionFormat": "Ongeldig versieformaat ontvangen van de GitHub API.",
|
||||
"babble.updateTimeout": "Time-out opgetreden bij het controleren op updates.",
|
||||
"babble.updateHttpError": "HTTP-fout bij het controleren op updates.",
|
||||
"babble.updateCheckFailed": "Controleren op updates mislukt vanwege een onverwachte fout.",
|
||||
"calibration.header": "Kalibratie-Instellingen",
|
||||
"calibration.mode": "Kalibratie-Modus",
|
||||
"calibration.modeTooltip": "Neutraal = Alleen Min waardes zijn ingesteld bij het starten en stoppen van de kalibratie. Volledig = Min en Max waardes zijn ingesteld d.m.v opgenomen waardes bij het starten van de kalibratie",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "awgo settings :3",
|
||||
"babble.calibrationPage": "cawibwation OwO",
|
||||
"babble.exit": "Qwiting Babble App~ Nyaa~",
|
||||
"babble.invalidVersionFormat": "Invawid vewsion fowmat weceived fwom the GitHub API nya~",
|
||||
"babble.updateTimeout": "Timeout occuwwed while checking fow updates UwU",
|
||||
"babble.updateHttpError": "HTTP ewwow occuwwed while checking fow updates >w<",
|
||||
"babble.updateCheckFailed": "Fwailed to check fow updates due to an unexpected ewwow :3",
|
||||
"calibration.header": "cawibwation Settings >w<",
|
||||
"calibration.mode": "cawibwation Mode nya~",
|
||||
"calibration.modeTooltip": "neutwaw = onwy min vawues awe set when stawting and stopping cawibwation. fuww = min and max vawues awe set based on wecowded vawues when stawting cawibwation. :3",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Algo Riggin's",
|
||||
"babble.calibrationPage": "Calibration",
|
||||
"babble.exit": "Exiting Babble App",
|
||||
"babble.invalidVersionFormat": "Arrr! GitHub API's sent us a crooked version map that makes no sense.",
|
||||
"babble.updateTimeout": "Blast! Our hunt fer booty updates ran out o' time on the high seas.",
|
||||
"babble.updateHttpError": "Shiver me timbers! An HTTP error struck while scoutin' fer fresh booty.",
|
||||
"babble.updateCheckFailed": "Yo-ho-ho! The update check be marooned by an unexpected squall.",
|
||||
"calibration.header": "Calibration Riggin's",
|
||||
"calibration.mode": "Calibration Mode",
|
||||
"calibration.modeTooltip": "Neutral = Only Min values be set when startin' and stoppin' calibration. Full = Min and Max values be set based on recorded values when startin' calibration.",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Ustawienia algorytmu",
|
||||
"babble.calibrationPage": "Kalibracja",
|
||||
"babble.exit": "Wychodzenie z aplikacji",
|
||||
"babble.invalidVersionFormat": "Nieprawidłowy format wersji otrzymany z GitHub API.",
|
||||
"babble.updateTimeout": "Przekroczono limit czasu podczas sprawdzania aktualizacji.",
|
||||
"babble.updateHttpError": "Wystąpił błąd HTTP podczas sprawdzania aktualizacji.",
|
||||
"babble.updateCheckFailed": "Nie udało się sprawdzić aktualizacji z powodu nieoczekiwanego błędu.",
|
||||
"calibration.header": "Ustawienia kalibracji",
|
||||
"calibration.mode": "Tryb kalibracji",
|
||||
"calibration.modeTooltip": "Neutralna = Tylko Minimalne wartości są ustawiane podczas rozpoczynania i zakańczania kalibracji. Pełna = Minimalne I maksymalne wartości są ustawione na podstawie zapisanych wartości podczas kalibracji.",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Настройки алгоритма",
|
||||
"babble.calibrationPage": "Калибровка",
|
||||
"babble.exit": "Выход из приложения Babble",
|
||||
"babble.invalidVersionFormat": "Получен недопустимый формат версии от GitHub API.",
|
||||
"babble.updateTimeout": "Произошло превышение времени ожидания при проверке обновлений.",
|
||||
"babble.updateHttpError": "При проверке обновлений произошла HTTP-ошибка.",
|
||||
"babble.updateCheckFailed": "Не удалось проверить обновления из-за непредвиденной ошибки.",
|
||||
"calibration.header": "Настройки калибровки",
|
||||
"calibration.mode": "Режим калибровки",
|
||||
"calibration.modeTooltip": "Нейтральный = Устанавливаются только минимальные значения при начале и завершении калибровки. Полный = Устанавливаются минимальные и максимальные значения на основе записанных данных при начале калибровки.",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "Algo Inställningar",
|
||||
"babble.calibrationPage": "Kalibrering",
|
||||
"babble.exit": "Babble Avslutas",
|
||||
"babble.invalidVersionFormat": "Ogiltigt versionsformat mottaget från GitHub API.",
|
||||
"babble.updateTimeout": "Tidsgräns överskreds vid sökning efter uppdateringar.",
|
||||
"babble.updateHttpError": "HTTP-fel inträffade vid sökning efter uppdateringar.",
|
||||
"babble.updateCheckFailed": "Misslyckades med att söka efter uppdateringar på grund av ett oväntat fel.",
|
||||
"calibration.header": "Kalibreringsinställningar",
|
||||
"calibration.mode": "Kalibreringsläge",
|
||||
"calibration.modeTooltip": "Neutralt = Endast Min värden är inställda vid kalibrering. Full = Min och Max värden är inställda baserat på tidigare sparade värden vid kalibrering.",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "算法设定",
|
||||
"babble.calibrationPage": "校准",
|
||||
"babble.exit": "退出Babble",
|
||||
"babble.invalidVersionFormat": "从 GitHub API 接收到的版本格式无效。",
|
||||
"babble.updateTimeout": "检查更新时发生了超时。",
|
||||
"babble.updateHttpError": "检查更新时发生了 HTTP 错误。",
|
||||
"babble.updateCheckFailed": "由于意外错误,检查更新失败。",
|
||||
"calibration.header": "校准设定",
|
||||
"calibration.mode": "校准模式",
|
||||
"calibration.modeTooltip": "中性:开始和停止校准时仅设置最小值。\n完整:开始校准时根据记录值设置最小值和最大值",
|
||||
|
||||
@@ -130,6 +130,10 @@
|
||||
"babble.algoSettingsPage": "演算法設定",
|
||||
"babble.calibrationPage": "校正",
|
||||
"babble.exit": "結束 Babble App",
|
||||
"babble.invalidVersionFormat": "從 GitHub API 接收到的版本格式無效。",
|
||||
"babble.updateTimeout": "檢查更新時發生超時。",
|
||||
"babble.updateHttpError": "檢查更新時發生 HTTP 錯誤。",
|
||||
"babble.updateCheckFailed": "由於意外錯誤,無法檢查更新。",
|
||||
"calibration.header": "校正設定",
|
||||
"calibration.mode": "校正模式",
|
||||
"calibration.modeTooltip": "自然校正 = 僅在開始和停止校正時設定最小值。完整校正 = 根據開始校正時記錄的數值設定最小值和最大值。",
|
||||
|
||||
+178
-86
@@ -36,42 +36,38 @@ from notification_manager import NotificationManager
|
||||
from utils.misc_utils import ensurePath, os_type, bg_color_highlight, bg_color_clear
|
||||
from lang_manager import LocaleStringManager as lang
|
||||
from logger import setup_logging
|
||||
from constants import UIConstants, AppConstants
|
||||
|
||||
winmm = None
|
||||
|
||||
if os_type == 'Windows':
|
||||
if os_type == "Windows":
|
||||
try:
|
||||
from ctypes import windll
|
||||
|
||||
winmm = windll.winmm
|
||||
except OSError:
|
||||
print(f'\033[91m[{lang._instance.get_string("log.error")}] {lang._instance.get_string("error.winmm")}.\033[0m')
|
||||
|
||||
print(
|
||||
f'\033[91m[{lang._instance.get_string("log.error")}] {lang._instance.get_string("error.winmm")}.\033[0m'
|
||||
)
|
||||
|
||||
os.system("color") # init ANSI color
|
||||
|
||||
# Random environment variable to speed up webcam opening on the MSMF backend.
|
||||
# https://github.com/opencv/opencv/issues/17687
|
||||
os.environ["OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS"] = "0"
|
||||
|
||||
WINDOW_NAME = "Babble App"
|
||||
CAM_NAME = "-CAMWIDGET-"
|
||||
SETTINGS_NAME = "-SETTINGSWIDGET-"
|
||||
ALGO_SETTINGS_NAME = "-ALGOSETTINGSWIDGET-"
|
||||
CALIB_SETTINGS_NAME = "-CALIBSETTINGSWIDGET-"
|
||||
CAM_RADIO_NAME = "-CAMRADIO-"
|
||||
SETTINGS_RADIO_NAME = "-SETTINGSRADIO-"
|
||||
ALGO_SETTINGS_RADIO_NAME = "-ALGOSETTINGSRADIO-"
|
||||
CALIB_SETTINGS_RADIO_NAME = "-CALIBSETTINGSRADIO-"
|
||||
|
||||
page_url = "https://github.com/Project-Babble/ProjectBabble/releases/latest"
|
||||
appversion = "Babble v2.0.7"
|
||||
|
||||
|
||||
def timerResolution(toggle):
|
||||
if winmm != None:
|
||||
if toggle:
|
||||
rc = c_int(winmm.timeBeginPeriod(1))
|
||||
if rc.value != 0:
|
||||
# TIMEERR_NOCANDO = 97
|
||||
print(f'\033[93m[{lang._instance.get_string("log.warn")}] {lang._instance.get_string("warn.timerRes")} {rc.value}\033[0m')
|
||||
print(
|
||||
f'\033[93m[{lang._instance.get_string("log.warn")}] {lang._instance.get_string("warn.timerRes")} {rc.value}\033[0m'
|
||||
)
|
||||
else:
|
||||
winmm.timeEndPeriod(1)
|
||||
|
||||
@@ -80,9 +76,19 @@ async def check_for_updates(config, notification_manager):
|
||||
if config.settings.gui_update_check:
|
||||
try:
|
||||
response = requests.get(
|
||||
"https://api.github.com/repos/Project-Babble/ProjectBabble/releases/latest"
|
||||
"https://api.github.com/repos/Project-Babble/ProjectBabble/releases/latest",
|
||||
timeout=10, # Add timeout
|
||||
)
|
||||
latestversion = response.json()["name"]
|
||||
response.raise_for_status() # Will raise exception for HTTP errors
|
||||
|
||||
data = response.json()
|
||||
latestversion = data.get("name")
|
||||
|
||||
if not latestversion:
|
||||
print(
|
||||
f'[{lang._instance.get_string("log.warn")}] {lang._instance.get_string("babble.invalidVersionFormat")}'
|
||||
)
|
||||
return
|
||||
|
||||
if appversion == latestversion:
|
||||
print(
|
||||
@@ -92,12 +98,78 @@ async def check_for_updates(config, notification_manager):
|
||||
print(
|
||||
f'\033[93m[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.needUpdateOne")} [{appversion}] {lang._instance.get_string("babble.needUpdateTwo")} [{latestversion}] {lang._instance.get_string("babble.needUpdateThree")}.\033[0m'
|
||||
)
|
||||
await notification_manager.show_notification(appversion, latestversion, page_url)
|
||||
await notification_manager.show_notification(
|
||||
appversion, latestversion, page_url
|
||||
)
|
||||
|
||||
except requests.exceptions.Timeout:
|
||||
print(
|
||||
f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateTimeout")}'
|
||||
)
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(
|
||||
f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateHttpError")}: {e}'
|
||||
)
|
||||
except requests.exceptions.ConnectionError:
|
||||
print(
|
||||
f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.noInternet")}'
|
||||
)
|
||||
except Exception as e:
|
||||
print(
|
||||
f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.noInternet")}. Error: {e}'
|
||||
f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateCheckFailed")}: {e}'
|
||||
)
|
||||
|
||||
|
||||
class ThreadManager:
|
||||
def __init__(self, cancellation_event):
|
||||
"""Initialize ThreadManager with a cancellation event for signaling threads."""
|
||||
self.threads = [] # List of (thread, shutdown_obj) tuples
|
||||
self.cancellation_event = cancellation_event
|
||||
self.logger = logging.getLogger("ThreadManager")
|
||||
|
||||
def add_thread(self, thread, shutdown_obj=None):
|
||||
"""Add a thread and its optional shutdown object to the manager."""
|
||||
self.threads.append((thread, shutdown_obj))
|
||||
thread.start()
|
||||
self.logger.debug(f"Started thread: {thread.name}")
|
||||
|
||||
def shutdown_all(self, timeout=5.0):
|
||||
"""Shutdown all managed threads with a configurable timeout."""
|
||||
self.logger.info("Initiiating shutdown of all threads")
|
||||
self.cancellation_event.set() # Signal all threads to stop
|
||||
|
||||
# Call shutdown methods on associated objects if available
|
||||
for thread, shutdown_obj in self.threads:
|
||||
if (
|
||||
shutdown_obj
|
||||
and hasattr(shutdown_obj, "shutdown")
|
||||
and callable(shutdown_obj.shutdown)
|
||||
):
|
||||
try:
|
||||
self.logger.debug(f"Calling shutdown on {shutdown_obj}")
|
||||
shutdown_obj.shutdown()
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error shutting down {shutdown_obj}: {e}")
|
||||
|
||||
# Join threads with the specified timeout
|
||||
for thread, _ in self.threads:
|
||||
if thread.is_alive():
|
||||
self.logger.debug(
|
||||
f"Joining thread: {thread.name} with timeout {timeout}s"
|
||||
)
|
||||
thread.join(timeout=timeout)
|
||||
|
||||
# Remove terminated threads from the list
|
||||
self.threads = [(t, s) for t, s in self.threads if t.is_alive()]
|
||||
|
||||
if self.threads:
|
||||
self.logger.warning(
|
||||
f"{len(self.threads)} threads still alive: {[t.name for t, _ in self.threads]}"
|
||||
)
|
||||
else:
|
||||
self.logger.info("All threads terminated successfully")
|
||||
|
||||
|
||||
async def async_main():
|
||||
ensurePath()
|
||||
setup_logging()
|
||||
@@ -109,13 +181,13 @@ async def async_main():
|
||||
lang("Locale", config.settings.gui_language)
|
||||
|
||||
config.save()
|
||||
|
||||
|
||||
notification_manager = NotificationManager()
|
||||
await notification_manager.initialize()
|
||||
|
||||
|
||||
# Run the update check
|
||||
await check_for_updates(config, notification_manager)
|
||||
|
||||
|
||||
# Uncomment for low-level Vive Facial Tracker logging
|
||||
# logging.basicConfig(filename='BabbleApp.log', filemode='w', encoding='utf-8', level=logging.INFO)
|
||||
|
||||
@@ -124,11 +196,12 @@ async def async_main():
|
||||
|
||||
timerResolution(True)
|
||||
|
||||
thread_manager = ThreadManager(cancellation_event)
|
||||
|
||||
osc_queue: queue.Queue[tuple[bool, int, int]] = queue.Queue(maxsize=10)
|
||||
osc = VRChatOSC(cancellation_event, osc_queue, config)
|
||||
osc_thread = threading.Thread(target=osc.run)
|
||||
osc_thread.start()
|
||||
|
||||
osc_thread = threading.Thread(target=osc.run, name="OSCThread")
|
||||
thread_manager.add_thread(osc_thread, shutdown_obj=osc)
|
||||
cams = [
|
||||
CameraWidget(Tab.CAM, config, osc_queue),
|
||||
]
|
||||
@@ -146,62 +219,72 @@ async def async_main():
|
||||
"TABSELECTRADIO",
|
||||
background_color=bg_color_clear,
|
||||
default=(config.cam_display_id == Tab.CAM),
|
||||
key=CAM_RADIO_NAME,
|
||||
key=UIConstants.CAM_RADIO_NAME,
|
||||
),
|
||||
sg.Radio(
|
||||
lang._instance.get_string("babble.settingsPage"),
|
||||
"TABSELECTRADIO",
|
||||
background_color=bg_color_clear,
|
||||
default=(config.cam_display_id == Tab.SETTINGS),
|
||||
key=SETTINGS_RADIO_NAME,
|
||||
key=UIConstants.SETTINGS_RADIO_NAME,
|
||||
),
|
||||
sg.Radio(
|
||||
lang._instance.get_string("babble.algoSettingsPage"),
|
||||
"TABSELECTRADIO",
|
||||
background_color=bg_color_clear,
|
||||
default=(config.cam_display_id == Tab.ALGOSETTINGS),
|
||||
key=ALGO_SETTINGS_RADIO_NAME,
|
||||
key=UIConstants.ALGO_SETTINGS_RADIO_NAME,
|
||||
),
|
||||
sg.Radio(
|
||||
lang._instance.get_string("babble.calibrationPage"),
|
||||
"TABSELECTRADIO",
|
||||
background_color=bg_color_clear,
|
||||
default=(config.cam_display_id == Tab.CALIBRATION),
|
||||
key=CALIB_SETTINGS_RADIO_NAME,
|
||||
key=UIConstants.CALIB_SETTINGS_RADIO_NAME,
|
||||
),
|
||||
],
|
||||
[
|
||||
sg.Column(
|
||||
cams[0].widget_layout,
|
||||
vertical_alignment="top",
|
||||
key=CAM_NAME,
|
||||
key=UIConstants.CAM_NAME,
|
||||
visible=(config.cam_display_id in [Tab.CAM]),
|
||||
background_color=bg_color_highlight,
|
||||
),
|
||||
sg.Column(
|
||||
settings[0].widget_layout,
|
||||
vertical_alignment="top",
|
||||
key=SETTINGS_NAME,
|
||||
key=UIConstants.SETTINGS_NAME,
|
||||
visible=(config.cam_display_id in [Tab.SETTINGS]),
|
||||
background_color=bg_color_highlight,
|
||||
),
|
||||
sg.Column(
|
||||
settings[1].widget_layout,
|
||||
vertical_alignment="top",
|
||||
key=ALGO_SETTINGS_NAME,
|
||||
key=UIConstants.ALGO_SETTINGS_NAME,
|
||||
visible=(config.cam_display_id in [Tab.ALGOSETTINGS]),
|
||||
background_color=bg_color_highlight,
|
||||
),
|
||||
sg.Column(
|
||||
settings[2].widget_layout,
|
||||
vertical_alignment="top",
|
||||
key=CALIB_SETTINGS_NAME,
|
||||
key=UIConstants.CALIB_SETTINGS_NAME,
|
||||
visible=(config.cam_display_id in [Tab.CALIBRATION]),
|
||||
background_color=bg_color_highlight,
|
||||
),
|
||||
],
|
||||
# Keep at bottom!
|
||||
[sg.Text(f'- - - {lang._instance.get_string("general.windowFocus")} - - -', key="-WINFOCUS-", background_color=bg_color_clear, text_color="#F0F0F0", justification="center", expand_x=True, visible=False)],
|
||||
[
|
||||
sg.Text(
|
||||
f'- - - {lang._instance.get_string("general.windowFocus")} - - -',
|
||||
key="-WINFOCUS-",
|
||||
background_color=bg_color_clear,
|
||||
text_color="#F0F0F0",
|
||||
justification="center",
|
||||
expand_x=True,
|
||||
visible=False,
|
||||
)
|
||||
],
|
||||
]
|
||||
|
||||
if config.cam_display_id in [Tab.CAM]:
|
||||
@@ -216,43 +299,43 @@ async def async_main():
|
||||
# the cam needs to be running before it is passed to the OSC
|
||||
if config.settings.gui_ROSC:
|
||||
osc_receiver = VRChatOSCReceiver(cancellation_event, config, cams)
|
||||
osc_receiver_thread = threading.Thread(target=osc_receiver.run)
|
||||
osc_receiver_thread.start()
|
||||
osc_receiver_thread = threading.Thread(
|
||||
target=osc_receiver.run, name="OSCReceiverThread"
|
||||
)
|
||||
thread_manager.add_thread(osc_receiver_thread, shutdown_obj=osc_receiver)
|
||||
ROSC = True
|
||||
|
||||
# Create the window
|
||||
window = sg.Window(
|
||||
f"{appversion}", layout, icon="Images/logo.ico", background_color=bg_color_clear
|
||||
f"{AppConstants.VERSION}",
|
||||
layout,
|
||||
icon=os.path.join("Images", "logo.ico"),
|
||||
background_color=bg_color_clear,
|
||||
)
|
||||
|
||||
tint = 33
|
||||
# Run the main loop
|
||||
await main_loop(window, config, cams, settings, thread_manager)
|
||||
|
||||
# Cleanup after main loop exits
|
||||
timerResolution(False)
|
||||
print(
|
||||
f'\033[94m[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.exit")}\033[0m'
|
||||
)
|
||||
|
||||
|
||||
async def main_loop(window, config, cams, settings, thread_manager):
|
||||
tint = AppConstants.DEFAULT_WINDOW_FOCUS_REFRESH
|
||||
fs = False
|
||||
|
||||
while True:
|
||||
# First off, check for any events from the GUI
|
||||
event, values = window.read(timeout=tint)
|
||||
|
||||
# If we're in either mode and someone hits q, quit immediately
|
||||
if event in ("Exit", sg.WIN_CLOSED):
|
||||
for (
|
||||
cam
|
||||
) in (
|
||||
cams
|
||||
): # yes we only have one cam page but im just gonna leave this incase
|
||||
# Exit code here
|
||||
for cam in cams:
|
||||
cam.stop()
|
||||
cancellation_event.set()
|
||||
# shut down worker threads
|
||||
osc_thread.join()
|
||||
# TODO: find a way to have this function run on join maybe??
|
||||
# threading.Event() wont work because pythonosc spawns its own thread.
|
||||
# only way i can see to get around this is an ugly while loop that only checks if a threading event is triggered
|
||||
# and then call the pythonosc shutdown function
|
||||
if ROSC:
|
||||
osc_receiver.shutdown()
|
||||
osc_receiver_thread.join()
|
||||
timerResolution(False)
|
||||
print(
|
||||
f'\033[94m[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.exit")}\033[0m'
|
||||
)
|
||||
thread_manager.shutdown_all()
|
||||
window.close()
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -260,71 +343,74 @@ async def async_main():
|
||||
if window.TKroot.focus_get():
|
||||
if fs:
|
||||
fs = False
|
||||
tint = 33
|
||||
window["-WINFOCUS-"].update(visible=False)
|
||||
window["-WINFOCUS-"].hide_row()
|
||||
tint = AppConstants.DEFAULT_WINDOW_FOCUS_REFRESH
|
||||
window[UIConstants.WINDOW_FOCUS_KEY].update(visible=False)
|
||||
window[UIConstants.WINDOW_FOCUS_KEY].hide_row()
|
||||
window.refresh()
|
||||
else:
|
||||
if not fs:
|
||||
fs = True
|
||||
tint = 100
|
||||
window["-WINFOCUS-"].update(visible=True)
|
||||
window["-WINFOCUS-"].unhide_row()
|
||||
tint = AppConstants.UNFOCUSED_WINDOW_REFRESH
|
||||
window[UIConstants.WINDOW_FOCUS_KEY].update(visible=True)
|
||||
window[UIConstants.WINDOW_FOCUS_KEY].unhide_row()
|
||||
continue
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
if values[CAM_RADIO_NAME] and config.cam_display_id != Tab.CAM:
|
||||
if values[UIConstants.CAM_RADIO_NAME] and config.cam_display_id != Tab.CAM:
|
||||
cams[0].start()
|
||||
settings[0].stop()
|
||||
settings[1].stop()
|
||||
settings[2].stop()
|
||||
window[CAM_NAME].update(visible=True)
|
||||
window[SETTINGS_NAME].update(visible=False)
|
||||
window[ALGO_SETTINGS_NAME].update(visible=False)
|
||||
window[CALIB_SETTINGS_NAME].update(visible=False)
|
||||
window[UIConstants.CAM_NAME].update(visible=True)
|
||||
window[UIConstants.SETTINGS_NAME].update(visible=False)
|
||||
window[UIConstants.ALGO_SETTINGS_NAME].update(visible=False)
|
||||
window[UIConstants.CALIB_SETTINGS_NAME].update(visible=False)
|
||||
config.cam_display_id = Tab.CAM
|
||||
config.save()
|
||||
|
||||
elif values[SETTINGS_RADIO_NAME] and config.cam_display_id != Tab.SETTINGS:
|
||||
elif (
|
||||
values[UIConstants.SETTINGS_RADIO_NAME]
|
||||
and config.cam_display_id != Tab.SETTINGS
|
||||
):
|
||||
cams[0].stop()
|
||||
settings[1].stop()
|
||||
settings[2].stop()
|
||||
settings[0].start()
|
||||
window[CAM_NAME].update(visible=False)
|
||||
window[SETTINGS_NAME].update(visible=True)
|
||||
window[ALGO_SETTINGS_NAME].update(visible=False)
|
||||
window[CALIB_SETTINGS_NAME].update(visible=False)
|
||||
window[UIConstants.CAM_NAME].update(visible=False)
|
||||
window[UIConstants.SETTINGS_NAME].update(visible=True)
|
||||
window[UIConstants.ALGO_SETTINGS_NAME].update(visible=False)
|
||||
window[UIConstants.CALIB_SETTINGS_NAME].update(visible=False)
|
||||
config.cam_display_id = Tab.SETTINGS
|
||||
config.save()
|
||||
|
||||
elif (
|
||||
values[ALGO_SETTINGS_RADIO_NAME]
|
||||
values[UIConstants.ALGO_SETTINGS_RADIO_NAME]
|
||||
and config.cam_display_id != Tab.ALGOSETTINGS
|
||||
):
|
||||
cams[0].stop()
|
||||
settings[0].stop()
|
||||
settings[2].stop()
|
||||
settings[1].start()
|
||||
window[CAM_NAME].update(visible=False)
|
||||
window[SETTINGS_NAME].update(visible=False)
|
||||
window[ALGO_SETTINGS_NAME].update(visible=True)
|
||||
window[CALIB_SETTINGS_NAME].update(visible=False)
|
||||
window[UIConstants.CAM_NAME].update(visible=False)
|
||||
window[UIConstants.SETTINGS_NAME].update(visible=False)
|
||||
window[UIConstants.ALGO_SETTINGS_NAME].update(visible=True)
|
||||
window[UIConstants.CALIB_SETTINGS_NAME].update(visible=False)
|
||||
config.cam_display_id = Tab.ALGOSETTINGS
|
||||
config.save()
|
||||
|
||||
elif (
|
||||
values[CALIB_SETTINGS_RADIO_NAME]
|
||||
values[UIConstants.CALIB_SETTINGS_RADIO_NAME]
|
||||
and config.cam_display_id != Tab.CALIBRATION
|
||||
):
|
||||
cams[0].start() # Allow tracking to continue in calibration tab
|
||||
settings[0].stop()
|
||||
settings[1].stop()
|
||||
settings[2].start()
|
||||
window[CAM_NAME].update(visible=False)
|
||||
window[SETTINGS_NAME].update(visible=False)
|
||||
window[ALGO_SETTINGS_NAME].update(visible=False)
|
||||
window[CALIB_SETTINGS_NAME].update(visible=True)
|
||||
window[UIConstants.CAM_NAME].update(visible=False)
|
||||
window[UIConstants.SETTINGS_NAME].update(visible=False)
|
||||
window[UIConstants.ALGO_SETTINGS_NAME].update(visible=False)
|
||||
window[UIConstants.CALIB_SETTINGS_NAME].update(visible=True)
|
||||
config.cam_display_id = Tab.CALIBRATION
|
||||
config.save()
|
||||
|
||||
@@ -335,9 +421,15 @@ async def async_main():
|
||||
for setting in settings:
|
||||
if setting.started():
|
||||
setting.render(window, event, values)
|
||||
|
||||
|
||||
# Rather than await asyncio.sleep(0), yield control periodically
|
||||
await asyncio.sleep(0.001) # Small sleep to allow other tasks to rundef main():
|
||||
asyncio.run(async_main())
|
||||
|
||||
|
||||
def main():
|
||||
asyncio.run(async_main())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -419,6 +419,10 @@ class CameraWidget:
|
||||
|
||||
if event == self.gui_autoroi:
|
||||
print(lang._instance.get_string("info.setROI"))
|
||||
if self.maybe_image is None:
|
||||
# Skip rendering or use a default/placeholder image
|
||||
return # Or handle appropriately
|
||||
|
||||
output = self.maybe_image[0].shape
|
||||
self.config.roi_window_x = 0
|
||||
self.config.roi_window_y = 0
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# New file with constants
|
||||
class UIConstants:
|
||||
WINDOW_NAME = "Babble App"
|
||||
CAM_NAME = "-CAMWIDGET-"
|
||||
SETTINGS_NAME = "-SETTINGSWIDGET-"
|
||||
ALGO_SETTINGS_NAME = "-ALGOSETTINGSWIDGET-"
|
||||
CALIB_SETTINGS_NAME = "-CALIBSETTINGSWIDGET-"
|
||||
CAM_RADIO_NAME = "-CAMRADIO-"
|
||||
SETTINGS_RADIO_NAME = "-SETTINGSRADIO-"
|
||||
ALGO_SETTINGS_RADIO_NAME = "-ALGOSETTINGSRADIO-"
|
||||
CALIB_SETTINGS_RADIO_NAME = "-CALIBSETTINGSRADIO-"
|
||||
WINDOW_FOCUS_KEY = "-WINFOCUS-"
|
||||
|
||||
|
||||
class AppConstants:
|
||||
VERSION = "Babble v2.0.7"
|
||||
GITHUB_REPO_URL = "https://github.com/Project-Babble/ProjectBabble/releases/latest"
|
||||
GITHUB_API_URL = (
|
||||
"https://api.github.com/repos/Project-Babble/ProjectBabble/releases/latest"
|
||||
)
|
||||
DEFAULT_WINDOW_FOCUS_REFRESH = 33
|
||||
UNFOCUSED_WINDOW_REFRESH = 100
|
||||
Reference in new issue
Block a user