\Fix Add Torrent crash, implement save path selection, and add tray icon"

This commit is contained in:
Mikan
2026-11-17 20:13:31 +04:00
parent ea14e5d71a
commit e5fb33f9e6
2 changed files with 70 additions and 26 deletions

View File

@@ -26,7 +26,8 @@ exe = EXE(
a.zipfiles, a.zipfiles,
a.datas, a.datas,
[], [],
name='Citorrent',\n icon='assets/icon.ico', name='Citorrent',
icon='assets/icon.ico',
debug=False, debug=False,
bootloader_ignore_signals=False, bootloader_ignore_signals=False,
strip=False, strip=False,

View File

@@ -1,5 +1,8 @@
import os
import logging
from PySide6.QtWidgets import (QMainWindow, QTableView, QVBoxLayout, QHBoxLayout, 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 PySide6.QtCore import Qt, QTimer
from src.gui.torrent_model import TorrentModel from src.gui.torrent_model import TorrentModel
from src.gui.add_torrent_dialog import AddTorrentDialog 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.core.torrent_session import TorrentSession
from src.data.database_manager import DatabaseManager from src.data.database_manager import DatabaseManager
logger = logging.getLogger("Citorrent.MainWindow")
# Libtorrent states to human readable strings # Libtorrent states to human readable strings
STATE_MAP = { STATE_MAP = {
1: "Downloading", 1: "Downloading",
@@ -31,6 +36,7 @@ class MainWindow(QMainWindow):
self._setup_toolbar() self._setup_toolbar()
self._setup_central_widget() self._setup_central_widget()
self._setup_statusbar() self._setup_statusbar()
self._setup_tray_icon()
# Integration: Load existing torrents and start update loop # Integration: Load existing torrents and start update loop
self._load_torrents() self._load_torrents()
@@ -68,6 +74,21 @@ class MainWindow(QMainWindow):
self.setStatusBar(QStatusBar()) self.setStatusBar(QStatusBar())
self.statusBar().setObjectName("MainStatusBar") 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): def _load_torrents(self):
"""Load torrents from DB and resume them in the session.""" """Load torrents from DB and resume them in the session."""
existing_torrents = self.db.get_all_torrents() existing_torrents = self.db.get_all_torrents()
@@ -81,41 +102,64 @@ class MainWindow(QMainWindow):
handle = self.core.add_torrent_file(source) handle = self.core.add_torrent_file(source)
if handle: if handle:
status = self.core.get_status(handle) # Don't block on status, just add to model as "Resuming..."
self.model.add_torrent({ self.model.add_torrent({
"handle": handle, "handle": handle,
"info_hash": handle.info_hash().to_string(), "info_hash": handle.info_hash().to_string(),
"name": status["name"], "name": t_data.get("name", "Fetching..."),
"size": f"{status['total'] / (1024*1024):.2f} MB", "size": "Unknown",
"progress": status["progress"], "progress": 0,
"status": STATE_MAP.get(status["state"], "Unknown") "status": "Resuming..."
}) })
except Exception as e: 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): def _on_add_torrent_clicked(self):
dialog = AddTorrentDialog(self) dialog = AddTorrentDialog(self, default_save_path=self.core.save_path)
if dialog.exec(): if dialog.exec():
data = dialog.get_data() data = dialog.get_data()
try: try:
handle = None handle = None
source_val = data["value"] 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": if data["type"] == "magnet":
handle = self.core.add_magnet(source_val) handle = self.core.add_magnet(source_val)
else: else:
handle = self.core.add_torrent_file(source_val) handle = self.core.add_torrent_file(source_val)
if handle: if handle:
status = self.core.get_status(handle)
info_hash = handle.info_hash().to_string() 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 # Save to DB
self.db.add_torrent({ self.db.add_torrent({
"info_hash": info_hash, "info_hash": info_hash,
"name": status["name"], "name": status_name,
"save_path": self.core.save_path, "save_path": custom_save_path or self.core.save_path,
"status": STATE_MAP.get(status["state"], "Unknown"), "status": state_str,
"progress": status["progress"], "progress": progress,
"source": source_val "source": source_val
}) })
@@ -123,24 +167,23 @@ class MainWindow(QMainWindow):
self.model.add_torrent({ self.model.add_torrent({
"handle": handle, "handle": handle,
"info_hash": info_hash, "info_hash": info_hash,
"name": status["name"], "name": status_name,
"size": f"{status['total'] / (1024*1024):.2f} MB", "size": "Unknown",
"progress": status["progress"], "progress": progress,
"status": STATE_MAP.get(status["state"], "Unknown") "status": state_str
}) })
self.statusBar().showMessage(f"Started downloading: {status['name']}", 5000) self.statusBar().showMessage(f"Adding: {status_name}", 5000)
except Exception as e: except Exception as e:
logger.exception("Error adding torrent")
self.statusBar().showMessage(f"Error adding torrent: {e}", 5000) self.statusBar().showMessage(f"Error adding torrent: {e}", 5000)
def _setup_update_loop(self): def _setup_update_loop(self):
"""Setup real-time updates for all active torrents.""" """Setup real-time updates for all active torrents."""
# UI Update Timer (1 second)
self.update_timer = QTimer() self.update_timer = QTimer()
self.update_timer.timeout.connect(self._update_torrents_status) self.update_timer.timeout.connect(self._update_torrents_status)
self.update_timer.start(1000) 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 = QTimer()
self.db_sync_timer.timeout.connect(self._sync_to_database) self.db_sync_timer.timeout.connect(self._sync_to_database)
self.db_sync_timer.start(30000) self.db_sync_timer.start(30000)
@@ -161,24 +204,24 @@ class MainWindow(QMainWindow):
if torrent["progress"] != new_progress or torrent["status"] != new_state: if torrent["progress"] != new_progress or torrent["status"] != new_state:
self.model.update_torrent(i, { self.model.update_torrent(i, {
"progress": new_progress, "progress": new_progress,
"status": new_state "status": new_state,
"name": status["name"] # Update name once metadata arrives
}) })
except Exception as e: 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): 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()): for i in range(self.model.rowCount()):
torrent = self.model.get_torrent(i) torrent = self.model.get_torrent(i)
if not torrent or "handle" not in torrent: if not torrent or "handle" not in torrent:
continue continue
try: try:
# Sync current model state to DB
self.db.update_torrent(torrent["info_hash"], { self.db.update_torrent(torrent["info_hash"], {
"progress": torrent["progress"], "progress": torrent["progress"],
"status": torrent["status"] "status": torrent["status"]
}) })
except Exception as e: 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 import os