From e5fb33f9e6de408e821992495b47dd37a785a036 Mon Sep 17 00:00:00 2001 From: Mikan <72257910+Mikan-DS@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:13:31 +0400 Subject: [PATCH] \Fix Add Torrent crash, implement save path selection, and add tray icon" --- citorrent.spec | 3 +- src/gui/main_window.py | 93 ++++++++++++++++++++++++++++++------------ 2 files changed, 70 insertions(+), 26 deletions(-) diff --git a/citorrent.spec b/citorrent.spec index ecbe13d..0206985 100644 --- a/citorrent.spec +++ b/citorrent.spec @@ -26,7 +26,8 @@ exe = EXE( a.zipfiles, a.datas, [], - name='Citorrent',\n icon='assets/icon.ico', + name='Citorrent', + icon='assets/icon.ico', debug=False, bootloader_ignore_signals=False, strip=False, diff --git a/src/gui/main_window.py b/src/gui/main_window.py index 6422cc8..c1b9f82 100644 --- a/src/gui/main_window.py +++ b/src/gui/main_window.py @@ -1,5 +1,8 @@ +import os +import logging from PySide6.QtWidgets import (QMainWindow, QTableView, QVBoxLayout, QHBoxLayout, - QWidget, QPushButton, QToolBar, QStatusBar, QHeaderView) + QWidget, QPushButton, QToolBar, QStatusBar, QHeaderView, + QSystemTrayIcon, QMenu) from PySide6.QtCore import Qt, QTimer from src.gui.torrent_model import TorrentModel from src.gui.add_torrent_dialog import AddTorrentDialog @@ -7,6 +10,8 @@ from src.gui.style_manager import StyleManager from src.core.torrent_session import TorrentSession from src.data.database_manager import DatabaseManager +logger = logging.getLogger("Citorrent.MainWindow") + # Libtorrent states to human readable strings STATE_MAP = { 1: "Downloading", @@ -31,6 +36,7 @@ class MainWindow(QMainWindow): self._setup_toolbar() self._setup_central_widget() self._setup_statusbar() + self._setup_tray_icon() # Integration: Load existing torrents and start update loop self._load_torrents() @@ -68,6 +74,21 @@ class MainWindow(QMainWindow): self.setStatusBar(QStatusBar()) self.statusBar().setObjectName("MainStatusBar") + def _setup_tray_icon(self): + """Implement System Tray Icon (User Request).""" + self.tray_icon = QSystemTrayIcon(self) + self.tray_icon.setIcon(StyleManager.get_icon("logo.png")) + + # Tray Menu + tray_menu = QMenu() + show_action = tray_menu.addAction("Show") + show_action.triggered.connect(self.showNormal) + quit_action = tray_menu.addAction("Quit") + quit_action.triggered.connect(self.close) + + self.tray_icon.setContextMenu(tray_menu) + self.tray_icon.show() + def _load_torrents(self): """Load torrents from DB and resume them in the session.""" existing_torrents = self.db.get_all_torrents() @@ -81,41 +102,64 @@ class MainWindow(QMainWindow): handle = self.core.add_torrent_file(source) if handle: - status = self.core.get_status(handle) + # Don't block on status, just add to model as "Resuming..." self.model.add_torrent({ "handle": handle, "info_hash": handle.info_hash().to_string(), - "name": status["name"], - "size": f"{status['total'] / (1024*1024):.2f} MB", - "progress": status["progress"], - "status": STATE_MAP.get(status["state"], "Unknown") + "name": t_data.get("name", "Fetching..."), + "size": "Unknown", + "progress": 0, + "status": "Resuming..." }) except Exception as e: - print(f"Failed to resume torrent {t_data.get('name')}: {e}") + logger.error(f"Failed to resume torrent {t_data.get('name')}: {e}") def _on_add_torrent_clicked(self): - dialog = AddTorrentDialog(self) + dialog = AddTorrentDialog(self, default_save_path=self.core.save_path) if dialog.exec(): data = dialog.get_data() try: handle = None source_val = data["value"] + custom_save_path = data["save_path"] + + # Update core save path if user changed it for this torrent + # (Note: libtorrent session usually has one global save path, + # but we can handle specific ones by updating the handle) + if custom_save_path and custom_save_path != self.core.save_path: + self.core.save_path = custom_save_path # Simplification for this version + if data["type"] == "magnet": handle = self.core.add_magnet(source_val) else: handle = self.core.add_torrent_file(source_val) if handle: - status = self.core.get_status(handle) info_hash = handle.info_hash().to_string() + # For magnets, metadata is not available immediately. + # We add it to the model and DB as "Fetching metadata..." + status_name = "Fetching metadata..." + progress = 0 + state_str = "Starting" + + try: + # Try to get immediate status (works for files) + status = self.core.get_status(handle) + status_name = status["name"] + progress = status["progress"] + state_str = STATE_MAP.get(status["state"], "Unknown") + except Exception: + # Expected for magnets until metadata arrives + pass + # Save to DB self.db.add_torrent({ "info_hash": info_hash, - "name": status["name"], - "save_path": self.core.save_path, - "status": STATE_MAP.get(status["state"], "Unknown"), - "progress": status["progress"], + "name": status_name, + "save_path": custom_save_path or self.core.save_path, + "status": state_str, + "progress": progress, "source": source_val }) @@ -123,24 +167,23 @@ class MainWindow(QMainWindow): self.model.add_torrent({ "handle": handle, "info_hash": info_hash, - "name": status["name"], - "size": f"{status['total'] / (1024*1024):.2f} MB", - "progress": status["progress"], - "status": STATE_MAP.get(status["state"], "Unknown") + "name": status_name, + "size": "Unknown", + "progress": progress, + "status": state_str }) - self.statusBar().showMessage(f"Started downloading: {status['name']}", 5000) + self.statusBar().showMessage(f"Adding: {status_name}", 5000) except Exception as e: + logger.exception("Error adding torrent") self.statusBar().showMessage(f"Error adding torrent: {e}", 5000) def _setup_update_loop(self): """Setup real-time updates for all active torrents.""" - # UI Update Timer (1 second) self.update_timer = QTimer() self.update_timer.timeout.connect(self._update_torrents_status) self.update_timer.start(1000) - # DB Sync Timer (30 seconds - Optimization 4.2: reduce disk I/O) self.db_sync_timer = QTimer() self.db_sync_timer.timeout.connect(self._sync_to_database) self.db_sync_timer.start(30000) @@ -161,24 +204,24 @@ class MainWindow(QMainWindow): if torrent["progress"] != new_progress or torrent["status"] != new_state: self.model.update_torrent(i, { "progress": new_progress, - "status": new_state + "status": new_state, + "name": status["name"] # Update name once metadata arrives }) except Exception as e: - print(f"Error updating torrent status at index {i}: {e}") + logger.debug(f"Status update skipped for index {i}: {e}") def _sync_to_database(self): - """Periodically sync current memory state to SQLite database (Optimization 4.2).""" + """Periodically sync current memory state to SQLite database.""" for i in range(self.model.rowCount()): torrent = self.model.get_torrent(i) if not torrent or "handle" not in torrent: continue try: - # Sync current model state to DB self.db.update_torrent(torrent["info_hash"], { "progress": torrent["progress"], "status": torrent["status"] }) except Exception as e: - print(f"Error syncing torrent {i} to DB: {e}") + logger.error(f"Error syncing torrent {i} to DB: {e}") import os