import sys import os import logging import socket import threading from PySide6.QtWidgets import QApplication, QMessageBox from src.gui.main_window import MainWindow from src.gui.style_manager import StyleManager # Single instance lock and IPC _lock_socket = None def start_instance_listener(window): def listen(): global _lock_socket try: while True: conn, addr = _lock_socket.accept() conn.close() # Signal to activate window print("Received wakeup signal from another instance.") window.activate_and_show() except Exception as e: print(f"Listener thread error: {e}") listener = threading.Thread(target=listen, daemon=True) listener.start() def acquire_single_instance_lock(): global _lock_socket try: # Try to bind as a server socket _lock_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) _lock_socket.bind(('127.0.0.1', 49152)) _lock_socket.listen(5) return True except socket.error: # Try to signal the existing instance try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 49152)) s.close() return "ACTIVATE" except socket.error: # Port is blocked but no one listening -> Zombie or other app return "ERROR" # Configure Logging def setup_logging(app_dir): log_path = os.path.join(app_dir, "citorrent.log") logging.basicConfig( level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(name)s: %(message)s', handlers=[ logging.FileHandler(log_path, encoding='utf-8'), logging.StreamHandler(sys.stdout) ] ) return logging.getLogger("Citorrent") def get_app_dir(): if getattr(sys, 'frozen', False): return os.path.dirname(sys.executable) return os.path.dirname(os.path.abspath(__file__)) def main(): app_dir = get_app_dir() logger = setup_logging(app_dir) logger.info("Application starting...") try: app = QApplication(sys.argv) # Ensure single instance lock_result = acquire_single_instance_lock() if lock_result == "ACTIVATE": QMessageBox.information(None, "Citorrent", "Another instance of Citorrent is already running.\n\n" "It should open now. If the window does not appear, " "you may need to restart the application.") sys.exit(0) elif lock_result == "ERROR": QMessageBox.critical(None, "Citorrent", "A Citorrent instance seems to be stuck or another app is using its port.\n\n" "Please restart your computer or kill any existing Citorrent processes.") sys.exit(1) elif lock_result is not True: # This case should theoretically not be reached with current acquire_single_instance_lock QMessageBox.critical(None, "Citorrent", "Failed to acquire application lock.") sys.exit(1) # Portable mode: Determine app directory for DB and config db_path = os.path.join(app_dir, "citorrent.data") save_path = os.path.join(app_dir, "downloads") os.makedirs(save_path, exist_ok=True) logger.info(f"App directory: {app_dir}, DB path: {db_path}, Save path: {save_path}") # Apply the dark theme stylesheet StyleManager.apply_stylesheet(app, "style.qss") window = MainWindow(db_path=db_path, save_path=save_path) start_instance_listener(window) # Start listening for wake-up signals window.show() sys.exit(app.exec()) except Exception as e: logger.exception("Critical error during application execution") sys.exit(1) if __name__ == "__main__": # Integrate CLI mechanics into main executable # If any arguments are passed (other than the script name), launch as CLI if len(sys.argv) > 1: try: from cli import main as cli_main cli_main() sys.exit(0) except Exception as e: print(f"CLI Error: {e}") sys.exit(1) else: main()