SXXXXXXX_CppPythonDebug/cpp_python_debug/__main__.py
2025-05-22 07:22:53 +02:00

125 lines
5.3 KiB
Python

# File: cpp_python_debug/__main__.py
# Main entry point for the Cpp-Python Debug Helper application.
# This script initializes logging and starts the Tkinter GUI.
import logging
import sys # For stream handler to output to console
import os # For path manipulation and log file deletion
# Use relative import to get the GDBGui class from the gui subpackage
from .gui.main_window import GDBGui
# --- Application Constants ---
APP_NAME = "Cpp-Python GDB Debug Helper"
APP_VERSION = "1.1.0" # Example version
# --- PERCORSO DEL FILE DI LOG DEL DUMPER ---
# Questo percorso deve essere coerente con come GDB_DUMPER_LOG_PATH è definito in gdb_dumper.py
GDB_DUMPER_LOG_TO_DELETE = None # Inizializza a None
try:
# Se __file__ è definito per __main__.py (di solito lo è)
if '__file__' in globals():
# Assumendo la struttura:
# cpp_python_debug/
# |-- __main__.py (questo file, os.path.dirname(__file__) è cpp_python_debug/)
# |-- core/
# |-- gdb_dumper.py (e gdb_dumper_debug.log viene creato qui)
# |-- ...
# |-- gui/
# |-- ...
main_script_dir = os.path.dirname(os.path.abspath(__file__))
gdb_dumper_script_dir = os.path.join(main_script_dir, "core")
GDB_DUMPER_LOG_TO_DELETE = os.path.join(gdb_dumper_script_dir, "gdb_dumper_debug.log")
else:
# Fallback se __file__ non è definito (raro per __main__.py)
# In questo caso, assumiamo che gdb_dumper.py scriva nella home dell'utente
# come suo fallback.
GDB_DUMPER_LOG_TO_DELETE = os.path.join(os.path.expanduser("~"), "gdb_dumper_debug.log")
except Exception:
# Se c'è un errore nel determinare il percorso, non tentare di cancellare.
# GDB_DUMPER_LOG_TO_DELETE rimarrà None.
pass
def setup_global_logging():
"""
Configures basic logging for the application.
- Logs to console (stdout).
- GUI will have its own handler to display logs within the application window.
"""
# Definizione di log_level qui, così è nello scope corretto
log_level = logging.DEBUG # Or logging.INFO for less verbosity in console
logging.basicConfig(level=log_level,
format='%(asctime)s - %(name)-25s - %(levelname)-8s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
# Opzionale: Se si vuole un controllo più fine sull'handler della console (es. stdout invece di stderr)
# root_logger = logging.getLogger()
# # Rimuovi handler di default se presenti e se si vuole solo il proprio
# for handler in root_logger.handlers[:]:
# root_logger.removeHandler(handler)
# console_handler = logging.StreamHandler(sys.stdout)
# console_formatter = logging.Formatter('%(asctime)s - %(name)-25s - %(levelname)-8s - %(message)s',
# datefmt='%Y-%m-%d %H:%M:%S')
# console_handler.setFormatter(console_formatter)
# console_handler.setLevel(log_level)
# root_logger.addHandler(console_handler)
logger = logging.getLogger(__name__) # Logger per questo modulo (__main__)
logger.info(f"Global logging initialized. Console log level: {logging.getLevelName(log_level)}.")
logger.info(f"Starting {APP_NAME} v{APP_VERSION}")
# --- CANCELLA IL VECCHIO LOG DEL DUMPER ---
if GDB_DUMPER_LOG_TO_DELETE: # Controlla se il percorso è stato determinato
if os.path.exists(GDB_DUMPER_LOG_TO_DELETE):
try:
os.remove(GDB_DUMPER_LOG_TO_DELETE)
logger.info(f"Previous GDB dumper log deleted: {GDB_DUMPER_LOG_TO_DELETE}")
except Exception as e_remove:
logger.warning(f"Could not delete previous GDB dumper log ('{GDB_DUMPER_LOG_TO_DELETE}'): {e_remove}")
else:
logger.info(f"GDB dumper log not found (no previous log to delete): {GDB_DUMPER_LOG_TO_DELETE}")
else:
logger.warning("Path for GDB dumper log to delete could not be determined.")
# --- FINE CANCELLAZIONE ---
def main():
"""
Main function to set up logging and launch the GDB GUI.
"""
setup_global_logging() # Initialize logging first
app_logger = logging.getLogger(APP_NAME) # Logger per l'applicazione in generale
try:
app_logger.info("Creating GDBGui instance...")
app = GDBGui()
app_logger.info("Starting Tkinter main event loop.")
app.mainloop()
app_logger.info("Tkinter main event loop finished.")
except Exception as e:
app_logger.critical(f"An unhandled critical error occurred: {e}", exc_info=True)
try:
# Prova a mostrare un errore Tkinter se possibile
import tkinter as tk
from tkinter import messagebox
root_for_error = tk.Tk()
root_for_error.withdraw()
messagebox.showerror("Critical Application Error",
f"A critical error occurred:\n{e}\n\nPlease check the logs for more details.")
root_for_error.destroy()
except Exception:
# Se Tkinter stesso è rotto, non si può fare molto altro che loggare
pass
finally:
app_logger.info(f"{APP_NAME} is shutting down.")
logging.shutdown() # Chiude gli handler di logging
if __name__ == "__main__":
# Permette l'esecuzione come script diretto o come modulo
main()