diff --git a/.gitignore b/.gitignore index 3773b9b..5fcd4f7 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,9 @@ dist/ .pytest_cache/ htmlcov/ .coverage + +# App data and downloads +downloads/ +*.log +*.data +*.torrent diff --git a/cli.py b/cli.py index 4dc1e1b..df0c6c0 100644 --- a/cli.py +++ b/cli.py @@ -1,6 +1,7 @@ import sys import os import argparse +import time from src.core.torrent_session import TorrentSession from src.data.database_manager import DatabaseManager @@ -24,10 +25,14 @@ def main(): status_parser = subparsers.add_parser("status", help="Get status of a specific torrent") status_parser.add_argument("hash", help="Info hash of the torrent") + # Monitor command + monitor_parser = subparsers.add_parser("monitor", help="Monitor status of a specific torrent in real-time") + monitor_parser.add_argument("hash", help="Info hash of the torrent") + args = parser.parse_args() app_dir = get_app_dir() - db_path = os.path.join(app_dir, "citorrent.db") + db_path = os.path.join(app_dir, "citorrent.data") save_path = os.path.join(app_dir, "downloads") os.makedirs(save_path, exist_ok=True) @@ -45,6 +50,9 @@ def main(): if handle: info_hash = handle.info_hash().to_string() + if isinstance(info_hash, bytes): + info_hash = info_hash.hex() + # Simplified adding to DB for CLI tool db.add_torrent({ "info_hash": info_hash, @@ -69,7 +77,10 @@ def main(): print(f"{'Hash':<40} {'Name':<30} {'Status':<15} {'Progress':<10}") print("-" * 95) for t in torrents: - print(f"{t.get('info_hash', 'N/A'):<40} {t.get('name', 'N/A'):<30} {t.get('status', 'N/A'):<15} {t.get('progress', 0):<10}") + h = t.get('info_hash', 'N/A') + if isinstance(h, bytes): + h = h.hex() + print(f"{h:<40} {t.get('name', 'N/A'):<30} {t.get('status', 'N/A'):<15} {t.get('progress', 0):<10}") elif args.command == "status": # For status, we need to check if it's currently in the session @@ -86,8 +97,12 @@ def main(): # Now check specific hash found = False - for handle in session.handles(): - if handle.info_hash().to_string() == args.hash: + print(f"Checking {len(session.get_all_handles())} active handles...") + for handle in session.get_all_handles(): + h = handle.info_hash().to_string() + if isinstance(h, bytes): h = h.hex() + print(f"Found handle: {h}") + if h == args.hash: status = session.get_status(handle) print(f"Torrent {args.hash} Status:") print(f" Name: {status['name']}") @@ -98,6 +113,38 @@ def main(): if not found: print(f"Torrent with hash {args.hash} not found in active session.") + elif args.command == "monitor": + import time + print("Resuming torrents from DB to monitor status...") + existing = db.get_all_torrents() + for t in existing: + source = t.get("source", "") + if source.startswith("magnet:"): + session.add_magnet(source) + elif os.path.exists(source): + session.add_torrent_file(source) + + print(f"Monitoring torrent {args.hash}. Press Ctrl+C to stop.") + try: + while True: + found = False + for handle in session.get_all_handles(): + h = handle.info_hash().to_string() + if isinstance(h, bytes): h = h.hex() + if h == args.hash: + status = session.get_status(handle) + print(f"[{time.strftime('%H:%M:%S')}] {status['name']} | Progress: {status['progress']:.2%} | State: {status['state']}") + found = True + if str(status['state']) == 'seeding': + print("Torrent is now seeding!") + break + break + if not found: + print(f"[{time.strftime('%H:%M:%S')}] Torrent {args.hash} not found in active session.") + time.sleep(5) + except KeyboardInterrupt: + print("\nMonitoring stopped.") + else: parser.print_help() diff --git a/main.py b/main.py index b441ac0..1e80a5d 100644 --- a/main.py +++ b/main.py @@ -1,10 +1,50 @@ import sys import os import logging -from PySide6.QtWidgets import QApplication +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") @@ -31,8 +71,26 @@ def main(): 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.db") + 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}") @@ -41,6 +99,7 @@ def main(): 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()) @@ -49,6 +108,17 @@ def main(): sys.exit(1) if __name__ == "__main__": - 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() diff --git a/src/core/torrent_session.py b/src/core/torrent_session.py index 9648fb1..db3dc39 100644 --- a/src/core/torrent_session.py +++ b/src/core/torrent_session.py @@ -1,11 +1,34 @@ import libtorrent as lt import os +import logging + +logger = logging.getLogger("Citorrent.Core") class TorrentSession: def __init__(self, save_path=None): # Initialize a libtorrent session self.lt_session = lt.session({'listen_interfaces': '0.0.0.0:6881'}) self.save_path = save_path or os.getcwd() + self.state_file = os.path.join(self.save_path, "citorrent.session") + + def load_session(self): + """Load the session state from file to resume downloads.""" + try: + if os.path.exists(self.state_file): + with open(self.state_file, 'rb') as f: + self.lt_session.load_save_state(f) + logger.info("Session state loaded successfully.") + except Exception as e: + logger.error(f"Failed to load session state: {e}") + + def save_session(self): + """Save the current session state to file.""" + try: + with open(self.state_file, 'wb') as f: + self.lt_session.save_state(f) + logger.info("Session state saved successfully.") + except Exception as e: + logger.error(f"Failed to save session state: {e}") def add_magnet(self, magnet_link): params = lt.parse_magnet_uri(magnet_link) @@ -17,24 +40,76 @@ class TorrentSession: if not os.path.exists(file_path): raise FileNotFoundError(f"Torrent file not found: {file_path}") - params = lt.read_torrent_file(file_path) - params.save_path = self.save_path - handle = self.lt_session.add_torrent(params) - return handle + try: + info = lt.torrent_info(file_path) + params = { + 'save_path': self.save_path, + 'ti': info + } + handle = self.lt_session.add_torrent(params) + return handle + except Exception as e: + logger.error(f"Error parsing torrent file: {e}") + return None def get_status(self, handle): # Get status from libtorrent handle s = handle.status() + + # Determine human-readable state + if s.paused: + state = "Paused" + elif not s.name or s.name == "": + state = "Metadata Fetching" + elif s.progress >= 1.0: + state = "Seeding" if s.upload_rate > 0 else "Completed" + else: + state = "Downloading" + return { 'progress': s.progress, - 'state': s.state, + 'state': state, # Now a string 'downloaded': s.total_done, + 'uploaded': s.total_upload, + 'down_rate': s.download_rate, + 'up_rate': s.upload_rate, 'total': s.total_wanted, 'num_peers': s.num_peers, 'name': s.name } def get_all_handles(self): - return self.lt_session.get_torrent_handles() + return self.lt_session.get_torrents() + def pause_torrent(self, handle): + handle.pause() + def resume_torrent(self, handle): + handle.resume() + + def remove_torrent(self, handle): + self.lt_session.remove_torrent(handle) + + def skip_torrent(self, handle): + """Stop download and delete associated files.""" + try: + info = handle.get_torrent_info() + save_path = os.path.join(self.save_path, info.name()) + self.lt_session.remove_torrent(handle) + if os.path.exists(save_path): + import shutil + shutil.rmtree(save_path) if os.path.isdir(save_path) else os.remove(save_path) + except Exception as e: + logger.error(f"Error skipping torrent: {e}") + self.lt_session.remove_torrent(handle) + + def force_recheck(self, handle): + handle.force_recheck() + + def set_priority(self, handle, priority): + # Priority: 0=Lowest, 1=Low, 2=Normal, 3=High, 4=Highest + handle.set_priority(priority) + + def set_file_priority(self, handle, index, priority): + """Set the priority of a specific file in the torrent.""" + handle.set_file_priority(index, priority) diff --git a/src/gui/add_torrent_dialog.py b/src/gui/add_torrent_dialog.py index 9d38317..549f641 100644 --- a/src/gui/add_torrent_dialog.py +++ b/src/gui/add_torrent_dialog.py @@ -1,17 +1,34 @@ from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, - QLineEdit, QPushButton, QFileDialog, QComboBox, QWidget) + QLineEdit, QPushButton, QFileDialog, QComboBox, QWidget, + QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QScrollArea) from PySide6.QtCore import Qt from .style_manager import StyleManager +import libtorrent as lt class AddTorrentDialog(QDialog): - def __init__(self, parent=None): + def __init__(self, parent=None, source_type=None, source_value=None, default_save_path=None): super().__init__(parent) self.setObjectName("AddTorrentDialog") self.setWindowTitle("Add Torrent") - self.setMinimumWidth(400) - + self.setMinimumWidth(500) + self.setMinimumHeight(400) + + self.default_save_path = default_save_path self._setup_ui() + + if source_type and source_value: + self.set_source(source_type, source_value) + + def set_source(self, s_type, s_value): + """Programmatically set the source (used for drag-and-drop).""" + if s_type == "file": + self.source_combo.setCurrentText("Torrent File") + self.file_path_input.setText(s_value) + self._load_torrent_files() + elif s_type == "magnet": + self.source_combo.setCurrentText("Magnet Link") + self.magnet_input.setText(s_value) def _setup_ui(self): layout = QVBoxLayout(self) @@ -30,9 +47,6 @@ class AddTorrentDialog(QDialog): layout.addLayout(source_layout) # Input Area - self.input_container = QVBoxLayout() - - # We will use a QStackedWidget for switching between Magnet and File inputs from PySide6.QtWidgets import QStackedWidget self.stack = QStackedWidget() self.stack.setObjectName("InputStack") @@ -60,6 +74,7 @@ class AddTorrentDialog(QDialog): self.file_path_input = QLineEdit() self.file_path_input.setObjectName("txtFilePath") self.file_path_input.setReadOnly(True) + self.file_path_input.textChanged.connect(self._load_torrent_files) browse_btn = QPushButton("Browse...") browse_btn.setObjectName("btnBrowse") browse_btn.setIcon(StyleManager.get_icon("folder.png")) @@ -68,13 +83,49 @@ class AddTorrentDialog(QDialog): path_lay.addWidget(browse_btn) file_lay.addWidget(self.file_label) file_lay.addLayout(path_lay) - file_lay.addStretch() + + # File Selection Table (only for .torrent files) + self.files_container = QWidget() + self.files_container.setObjectName("FilesContainer") + files_layout = QVBoxLayout(self.files_container) + files_layout.addWidget(QLabel("Select Files to Download:")) + self.files_table = QTableWidget() + self.files_table.setObjectName("AddTorrentFilesTable") + self.files_table.setColumnCount(2) + self.files_table.setHorizontalHeaderLabels(["Download", "File Name"]) + self.files_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch) + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setWidget(self.files_table) + scroll.setMaximumHeight(200) + files_layout.addWidget(scroll) + file_lay.addWidget(self.files_container) self.stack.addWidget(magnet_page) # index 0 self.stack.addWidget(file_page) # index 1 + layout.addWidget(self.stack) + + # Save Path Selection + save_path_layout = QVBoxLayout() + save_label = QLabel("Save Path:") + save_label.setObjectName("lblSavePath") + self.save_path_input = QLineEdit() + self.save_path_input.setObjectName("txtSavePath") + if self.default_save_path: + self.save_path_input.setText(self.default_save_path) - self.input_container.addWidget(self.stack) - layout.addLayout(self.input_container) + browse_save_btn = QPushButton("Browse...") + browse_save_btn.setObjectName("btnBrowseSave") + browse_save_btn.setIcon(StyleManager.get_icon("folder.png")) + browse_save_btn.clicked.connect(self._on_browse_save_clicked) + + save_path_row = QHBoxLayout() + save_path_row.addWidget(self.save_path_input) + save_path_row.addWidget(browse_save_btn) + + save_path_layout.addWidget(save_label) + save_path_layout.addLayout(save_path_row) + layout.addLayout(save_path_layout) # Buttons btn_layout = QHBoxLayout() @@ -94,18 +145,58 @@ class AddTorrentDialog(QDialog): def _on_source_changed(self, text): if text == "Magnet Link": self.stack.setCurrentIndex(0) + self.files_container.hide() else: self.stack.setCurrentIndex(1) + self._load_torrent_files() def _on_browse_clicked(self): file_path, _ = QFileDialog.getOpenFileName(self, "Select Torrent File", "", "Torrent Files (*.torrent);;All Files (*)") if file_path: self.file_path_input.setText(file_path) + def _on_browse_save_clicked(self): + dir_path = QFileDialog.getExistingDirectory(self, "Select Save Directory", self.save_path_input.text()) + if dir_path: + self.save_path_input.setText(dir_path) + + def _load_torrent_files(self): + """Load files from the .torrent file and populate the table.""" + file_path = self.file_path_input.text() + if not file_path or not os.path.exists(file_path): + return + + try: + info = lt.torrent_info(file_path) + self.files_table.setRowCount(0) + for i in range(info.num_files()): + row = self.files_table.rowCount() + self.files_table.insertRow(row) + + chk = QCheckBox() + chk.setChecked(True) + self.files_table.setCellWidget(row, 0, chk) + + item = QTableWidgetItem(info.file_name(i)) + self.files_table.setItem(row, 1, item) + except Exception as e: + print(f"Error loading torrent files: {e}") + def get_data(self): - """Return the selected source and value.""" + """Return the selected source, value, save path and file priorities.""" source = self.source_combo.currentText() + save_path = self.save_path_input.text() + + priorities = [] + if source == "Torrent File": + for i in range(self.files_table.rowCount()): + chk = self.files_table.cellWidget(i, 0) + # Priority 1 for enabled, 0 for disabled (Skip) + priorities.append(1 if chk.isChecked() else 0) + if source == "Magnet Link": - return {"type": "magnet", "value": self.magnet_input.text()} + return {"type": "magnet", "value": self.magnet_input.text(), "save_path": save_path, "priorities": None} else: - return {"type": "file", "value": self.file_path_input.text()} + return {"type": "file", "value": self.file_path_input.text(), "save_path": save_path, "priorities": priorities} + +import os \ No newline at end of file diff --git a/src/gui/delegates.py b/src/gui/delegates.py new file mode 100644 index 0000000..895ac28 --- /dev/null +++ b/src/gui/delegates.py @@ -0,0 +1,24 @@ +from PySide6.QtWidgets import QStyledItemDelegate, QStyleOptionProgressBar, QProgressBar, QStyle +from PySide6.QtCore import Qt + +class ProgressBarDelegate(QStyledItemDelegate): + """Custom delegate to render a progress bar instead of text for the Progress column.""" + def paint(self, painter, option, index): + # Use UserRole to get raw float value from model + progress = index.data(Qt.ItemDataRole.UserRole) + if not isinstance(progress, (float, int)): + return super().paint(painter, option, index) + + # Use a QStyleOptionProgressBar to draw the bar using the current style + opt = QStyleOptionProgressBar() + opt.rect = option.rect.adjusted(5, 2, -5, -2) # Add some padding + opt.minimum = 0 + opt.maximum = 100 + opt.progress = int(progress * 100) + opt.text = f"{int(progress * 100)}%" + opt.textVisible = True + + # Use the widget's style to draw the progress bar + self.parent().style().drawControl( + QStyle.ControlElement.CE_ProgressBar, opt, painter + ) diff --git a/src/gui/detail_widget.py b/src/gui/detail_widget.py new file mode 100644 index 0000000..842233f --- /dev/null +++ b/src/gui/detail_widget.py @@ -0,0 +1,142 @@ +from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, + QTableWidget, QTableWidgetItem, QHeaderView, + QCheckBox, QComboBox) +from PySide6.QtCore import Qt +import logging +from src.utils.helpers import format_size + +logger = logging.getLogger("Citorrent.DetailWidget") + +class TorrentDetailWidget(QWidget): + """Detailed information and control panel for a selected torrent.""" + def __init__(self, parent=None): + super().__init__(parent) + self.setObjectName("TorrentDetailWidget") + self._setup_ui() + self.current_handle = None + + def _setup_ui(self): + layout = QVBoxLayout(self) + + # Basic Info Section + info_container = QWidget() + info_layout = QVBoxLayout(info_container) + + row1 = QHBoxLayout() + self.name_label = QLabel("Name: -") + self.name_label.setObjectName("lblDetailName") + self.status_label = QLabel("Status: -") + self.status_label.setObjectName("lblDetailStatus") + self.size_label = QLabel("Size: -") + self.size_label.setObjectName("lblDetailSize") + row1.addWidget(self.name_label) + row1.addWidget(self.status_label) + row1.addWidget(self.size_label) + + row2 = QHBoxLayout() + self.down_rate_label = QLabel("DL: -") + self.down_rate_label.setObjectName("lblDetailDownRate") + self.up_rate_label = QLabel("UL: -") + self.up_rate_label.setObjectName("lblDetailUpRate") + self.peers_label = QLabel("Peers: -") + self.peers_label.setObjectName("lblDetailPeers") + row2.addWidget(self.down_rate_label) + row2.addWidget(self.up_rate_label) + row2.addWidget(self.peers_label) + + info_layout.addLayout(row1) + info_layout.addLayout(row2) + layout.addWidget(info_container) + + # Files Table + self.files_table = QTableWidget() + self.files_table.setObjectName("FilesTable") + self.files_table.setColumnCount(3) + self.files_table.setHorizontalHeaderLabels(["Enabled", "File Name", "Priority"]) + self.files_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch) + + # Column 0: Checkbox for enabled/disabled + layout.addWidget(QLabel("Files:")) + layout.addWidget(self.files_table) + + def update_info(self, handle): + self.current_handle = handle + if not handle: + self._clear() + return + + try: + status = handle.status() + + # Determine readable state + state_str = "Paused" if status.paused else ("Completed" if status.progress >= 1.0 else "Downloading") + if not status.name: + state_str = "Metadata Fetching" + + self.name_label.setText(f"Name: {status.name}") + self.status_label.setText(f"Status: {state_str}") + self.size_label.setText(f"Size: {format_size(status.total_wanted)}") + self.down_rate_label.setText(f"DL: {format_size(status.download_rate)}/s") + self.up_rate_label.setText(f"UL: {format_size(status.upload_rate)}/s") + self.peers_label.setText(f"Peers: {status.num_peers}") + + # Update file list + self._update_file_list() + except Exception as e: + logger.error(f"Error updating detail widget: {e}") + + def _update_file_list(self): + if not self.current_handle: return + + try: + info = self.current_handle.get_torrent_info() + self.files_table.setRowCount(0) + + for i in range(info.num_files()): + row = self.files_table.rowCount() + self.files_table.insertRow(row) + + # Enabled checkbox + chk = QCheckBox() + priority = self.current_handle.file_priority(i) + chk.setChecked(priority > 0) + chk.stateChanged.connect(lambda state, idx=i: self._on_priority_changed(idx, state)) + self.files_table.setCellWidget(row, 0, chk) + + # File Name + name = info.files().file_name(i) + item = QTableWidgetItem(name) + self.files_table.setItem(row, 1, item) + + # Priority Combo + combo = QComboBox() + priorities = {0: "Skip", 1: "Lowest", 2: "Low", 4: "Normal", 7: "High"} + for val, text in priorities.items(): + combo.addItem(text, val) + + # Set current index based on priority value + priority_list = list(priorities.keys()) + try: + idx = priority_list.index(priority) + except ValueError: + idx = 3 # Default to Normal (4) + combo.setCurrentIndex(idx) + combo.currentIndexChanged.connect(lambda idx, f_idx=i: self._on_priority_changed(f_idx, combo.currentData())) + self.files_table.setCellWidget(row, 2, combo) + except Exception as e: + logger.error(f"Error updating file list: {e}") + + def _on_priority_changed(self, file_idx, priority): + if self.current_handle: + # Convert checkbox state to priority if needed (Qt.CheckState 2 is Checked) + p = int(priority) if isinstance(priority, int) else (1 if priority == 2 else 0) + self.current_handle.file_priority(file_idx, p) + + def _clear(self): + self.name_label.setText("Name: -") + self.status_label.setText("Status: -") + self.size_label.setText("Size: -") + self.down_rate_label.setText("DL: -") + self.up_rate_label.setText("UL: -") + self.peers_label.setText("Peers: -") + self.files_table.setRowCount(0) \ No newline at end of file diff --git a/src/gui/main_window.py b/src/gui/main_window.py index d17fe56..5eeb73c 100644 --- a/src/gui/main_window.py +++ b/src/gui/main_window.py @@ -1,24 +1,20 @@ -import os +import os import logging from PySide6.QtWidgets import (QMainWindow, QTableView, QVBoxLayout, QHBoxLayout, - QWidget, QPushButton, QToolBar, QStatusBar, QHeaderView, - QSystemTrayIcon, QMenu) + QWidget, QPushButton, QToolBar, QStatusBar, QHeaderView, + QSystemTrayIcon, QMenu, QLabel, QSplitter) from PySide6.QtCore import Qt, QTimer from src.gui.torrent_model import TorrentModel from src.gui.add_torrent_dialog import AddTorrentDialog from src.gui.style_manager import StyleManager from src.core.torrent_session import TorrentSession from src.data.database_manager import DatabaseManager +from src.gui.delegates import ProgressBarDelegate +from src.utils.helpers import format_size logger = logging.getLogger("Citorrent.MainWindow") -# Libtorrent states to human readable strings -STATE_MAP = { - 1: "Downloading", - 2: "Paused", - 3: "Completed", - 4: "Error", -} +# Libtorrent states are now handled by TorrentSession and returned as strings class MainWindow(QMainWindow): def __init__(self, db_path, save_path): @@ -28,12 +24,14 @@ class MainWindow(QMainWindow): self.setWindowTitle("Citorrent") self.setWindowIcon(StyleManager.get_icon("logo.png")) self.resize(800, 600) + self.setAcceptDrops(True) # Enable Drag and Drop # Integration: Initialize Core and Data layers self.core = TorrentSession(save_path=save_path) self.db = DatabaseManager(db_path) # Setup UI components + self._setup_menu() self._setup_toolbar() self._setup_central_widget() self._setup_statusbar() @@ -43,6 +41,28 @@ class MainWindow(QMainWindow): self._load_torrents() self._setup_update_loop() + def _setup_menu(self): + menubar = self.menuBar() + settings_menu = menubar.addMenu("&Settings") + + # Minimize to Tray setting + minimize_to_tray_action = settings_menu.addAction("Minimize to Tray on Close") + is_enabled = self.db.get_setting("minimize_to_tray", "false") == "true" + minimize_to_tray_action.setCheckable(True) + minimize_to_tray_action.setChecked(is_enabled) + minimize_to_tray_action.triggered.connect(self._on_toggle_minimize_to_tray) + + def _on_toggle_minimize_to_tray(self, checked): + self.db.set_setting("minimize_to_tray", str(checked).lower()) + logger.info(f"Setting minimize_to_tray updated to: {checked}") + + def activate_and_show(self): + """Brings the window to front and restores it if minimized.""" + if self.isMinimized(): + self.showNormal() + self.activateWindow() + self.raise_() + def _setup_toolbar(self): toolbar = QToolBar("Main Toolbar") toolbar.setObjectName("MainToolbar") @@ -58,22 +78,158 @@ class MainWindow(QMainWindow): def _setup_central_widget(self): central_widget = QWidget() central_widget.setObjectName("CentralWidget") - layout = QVBoxLayout(central_widget) + main_layout = QVBoxLayout(central_widget) + splitter = QSplitter(Qt.Orientation.Vertical) + splitter.setObjectName("MainSplitter") + + # Top part: Torrent Table + table_container = QWidget() + table_layout = QVBoxLayout(table_container) self.torrent_table = QTableView() self.torrent_table.setObjectName("TorrentTable") self.model = TorrentModel() self.torrent_table.setModel(self.model) + # Enable context menu + self.torrent_table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.torrent_table.customContextMenuRequested.connect(self._on_table_context_menu) + + # Use custom progress bar delegate for the Progress column (index 2) + self.torrent_table.setItemDelegateForColumn(2, ProgressBarDelegate(self.torrent_table)) + header = self.torrent_table.horizontalHeader() header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch) - layout.addWidget(self.torrent_table) + # Connect selection changes to detail widget + self.torrent_table.selectionModel().selectionChanged.connect(self._on_selection_changed) + + table_layout.addWidget(self.torrent_table) + splitter.addWidget(table_container) + + # Bottom part: Detail Widget + from src.gui.detail_widget import TorrentDetailWidget + self.detail_widget = TorrentDetailWidget() + splitter.addWidget(self.detail_widget) + + main_layout.addWidget(splitter) self.setCentralWidget(central_widget) + def _on_selection_changed(self, selected, deselected): + if not selected.indexes(): + self.detail_widget._clear() + return + + index = selected.indexes()[0] + row = index.row() + torrent = self.model.get_torrent(row) + if torrent and "handle" in torrent: + self.detail_widget.update_info(torrent["handle"]) + else: + self.detail_widget._clear() + + def dragEnterEvent(self, event): + if event.mimeData().hasUrls(): + event.accept() + else: + event.ignore() + + def dropEvent(self, event): + urls = event.mimeData().urls() + for url in urls: + file_path = url.toLocalFile() + if file_path.lower().endswith(".torrent"): + # Reuse the "add torrent" logic from _on_add_torrent_clicked + # but for a specific file path. + self._add_torrent_by_file(file_path) + event.accept() + + def _add_torrent_by_file(self, file_path): + """Internal helper to add torrent from a file path (used by drag-drop).""" + # Instead of adding directly, open the dialog with pre-filled data + dialog = AddTorrentDialog( + self, + source_type="file", + source_value=file_path, + default_save_path=self.core.save_path + ) + if dialog.exec(): + self._process_add_torrent(dialog.get_data()) + def _setup_statusbar(self): self.setStatusBar(QStatusBar()) self.statusBar().setObjectName("MainStatusBar") + # Add a label for global stats + self.global_stats_label = QLabel("Citorrent | Ready") + self.statusBar().addWidget(self.global_stats_label) + self.global_stats_label.setObjectName("GlobalStatsLabel") + + def _on_table_context_menu(self, position): + index = self.torrent_table.indexAt(position) + if not index.isValid(): + return + + row = index.row() + torrent = self.model.get_torrent(row) + if not torrent or "handle" not in torrent: + return + + handle = torrent["handle"] + state_str = torrent["status"] + + menu = QMenu() + + # Pause/Resume toggle + pause_resume_text = "Resume" if state_str == "Paused" else "Pause" + pause_resume_action = menu.addAction(pause_resume_text) + + # Remove torrent (just remove from list) + remove_action = menu.addAction("Remove") + + # Skip torrent (stop and delete files) + skip_action = menu.addAction("Skip & Delete") + + # Force Recheck + recheck_action = menu.addAction("Force Recheck") + + # Priority Submenu + priority_menu = menu.addMenu("Set Priority") + priorities = { + "Lowest": 0, "Low": 1, "Normal": 2, "High": 3, "Highest": 4 + } + for name, val in priorities.items(): + action = priority_menu.addAction(name) + action.triggered.connect(lambda checked, v=val: self._set_priority(handle, v)) + + # Connect main actions + pause_resume_action.triggered.connect(lambda: self._toggle_pause(handle)) + remove_action.triggered.connect(lambda: self._remove_torrent(row, handle)) + skip_action.triggered.connect(lambda: self._skip_torrent(row, handle)) + recheck_action.triggered.connect(lambda: self.core.force_recheck(handle)) + + menu.exec(self.torrent_table.mapToGlobal(position)) + + def _toggle_pause(self, handle): + status = self.core.get_status(handle) + if status["state"] == "Paused": + self.core.resume_torrent(handle) + else: + self.core.pause_torrent(handle) + + def _remove_torrent(self, row, handle): + info_hash = self.model.get_torrent(row)["info_hash"] + self.core.remove_torrent(handle) + self.db.delete_torrent(info_hash) + self.model.remove_torrent(row) + + def _skip_torrent(self, row, handle): + info_hash = self.model.get_torrent(row)["info_hash"] + self.core.skip_torrent(handle) + self.db.delete_torrent(info_hash) + self.model.remove_torrent(row) + + def _set_priority(self, handle, priority): + self.core.set_priority(handle, priority) def _setup_tray_icon(self): """Implement System Tray Icon (User Request).""" @@ -92,92 +248,145 @@ class MainWindow(QMainWindow): def _load_torrents(self): """Load torrents from DB and resume them in the session.""" + # First, try to load the binary session state for true resume support + self.core.load_session() + + # Then sync with our database records existing_torrents = self.db.get_all_torrents() + current_handles = self.core.get_all_handles() + current_hashes = {h.info_hash().to_string(): h for h in current_handles} + for t_data in existing_torrents: - try: - handle = None - source = t_data.get("source", "") - if source.startswith("magnet:"): - handle = self.core.add_magnet(source) - elif os.path.exists(source): - handle = self.core.add_torrent_file(source) - - if handle: - # Don't block on status, just add to model as "Resuming..." + info_hash = t_data.get("info_hash") + if not info_hash: continue + + handle = current_hashes.get(info_hash) + if handle: + # Already loaded from session state, just add to model + try: + status = self.core.get_status(handle) self.model.add_torrent({ "handle": handle, - "info_hash": handle.info_hash().to_string(), + "info_hash": info_hash, + "name": status["name"], + "size": format_size(status["total"]), + "progress": status["progress"], + "status": status["state"] + }) + except Exception: + self.model.add_torrent({ + "handle": handle, + "info_hash": info_hash, "name": t_data.get("name", "Fetching..."), "size": "Unknown", "progress": 0, "status": "Resuming..." }) - except Exception as e: - logger.error(f"Failed to resume torrent {t_data.get('name')}: {e}") + else: + # Not in session state, try to re-add from source + try: + handle = None + source = t_data.get("source", "") + if source.startswith("magnet:"): + handle = self.core.add_magnet(source) + elif os.path.exists(source): + handle = self.core.add_torrent_file(source) + + if handle: + self.model.add_torrent({ + "handle": handle, + "info_hash": info_hash, + "name": t_data.get("name", "Fetching..."), + "size": "Unknown", + "progress": 0, + "status": "Resuming..." + }) + except Exception as e: + logger.error(f"Failed to resume torrent {t_data.get('name')}: {e}") def _on_add_torrent_clicked(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"] + self._process_add_torrent(dialog.get_data()) - # 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 + def _process_add_torrent(self, data): + """Unified logic to add torrent from dialog data.""" + try: + handle = None + source_val = data["value"] + custom_save_path = data["save_path"] - if data["type"] == "magnet": - handle = self.core.add_magnet(source_val) - else: - handle = self.core.add_torrent_file(source_val) + if not source_val: + self.statusBar().showMessage("Error: Source is empty", 5000) + return - if 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" + # Update core save path if user changed it (libtorrent usually has one global, but we can handle it) + if custom_save_path and custom_save_path != self.core.save_path: + self.core.save_path = custom_save_path - 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 + if data["type"] == "magnet": + handle = self.core.add_magnet(source_val) + else: + handle = self.core.add_torrent_file(source_val) - # Save to DB - self.db.add_torrent({ - "info_hash": info_hash, - "name": status_name, - "save_path": custom_save_path or self.core.save_path, - "status": state_str, - "progress": progress, - "source": source_val - }) + if handle: + info_hash = handle.info_hash().to_string() + status_name = "Fetching metadata..." + progress = 0 + state_str = "Starting" - # Add to model - self.model.add_torrent({ - "handle": handle, - "info_hash": info_hash, - "name": status_name, - "size": "Unknown", - "progress": progress, - "status": state_str - }) + try: + # Try to get immediate status (works for files) + status = self.core.get_status(handle) + status_name = status["name"] + progress = status["progress"] + state_str = status["state"] + except Exception: + pass - 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) + # Save to DB + self.db.add_torrent({ + "info_hash": info_hash, + "name": status_name, + "save_path": custom_save_path or self.core.save_path, + "status": state_str, + "progress": progress, + "source": source_val + }) + + # Add to model + self.model.add_torrent({ + "handle": handle, + "info_hash": info_hash, + "name": status_name, + "size": "Unknown", + "progress": progress, + "status": state_str + }) + + # Apply file priorities if provided (for .torrent files) + priorities = data.get("priorities") + if priorities: + for idx, p in enumerate(priorities): + self.core.set_file_priority(handle, idx, p) + + 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 closeEvent(self, event): + """Override close event to handle minimize-to-tray setting and session saving.""" + # Save session state before exiting + self.core.save_session() + + minimize_to_tray = self.db.get_setting("minimize_to_tray", "false") == "true" + if minimize_to_tray: + event.ignore() # Prevent actual closing + self.hide() # Just hide the window + logger.info("Window hidden to tray (minimize_to_tray=True)") + else: + super().closeEvent(event) def _setup_update_loop(self): """Setup real-time updates for all active torrents.""" @@ -191,6 +400,11 @@ class MainWindow(QMainWindow): def _update_torrents_status(self): """Poll status from all handles in the model and update view.""" + total_progress = 0 + active_count = 0 + global_down_rate = 0 + global_up_rate = 0 + for i in range(self.model.rowCount()): torrent = self.model.get_torrent(i) if not torrent or "handle" not in torrent: @@ -199,30 +413,60 @@ class MainWindow(QMainWindow): try: status = self.core.get_status(torrent["handle"]) new_progress = status["progress"] - new_state = STATE_MAP.get(status["state"], "Unknown") + new_state = status["state"] + new_size = format_size(status["total"]) + new_down_rate = format_size(status["down_rate"]) + "/s" + new_up_rate = format_size(status["up_rate"]) + "/s" + global_down_rate += status.get("down_rate", 0) + global_up_rate += status.get("up_rate", 0) + + total_progress += new_progress + if new_state in ["Downloading", "Seeding", "Metadata Fetching"]: + active_count += 1 + # Update model if changed for immediate UI feedback - if torrent["progress"] != new_progress or torrent["status"] != new_state: + if torrent["progress"] != new_progress or \ + torrent["status"] != new_state or \ + torrent.get("size") != new_size or \ + torrent.get("down_rate") != new_down_rate or \ + torrent.get("up_rate") != new_up_rate: self.model.update_torrent(i, { "progress": new_progress, "status": new_state, - "name": status["name"] # Update name once metadata arrives + "name": status["name"], # Update name once metadata arrives + "size": new_size, + "down_rate": new_down_rate, + "up_rate": new_up_rate }) except Exception as e: logger.debug(f"Status update skipped for index {i}: {e}") + + # Update global stats in status bar + avg_progress = (total_progress / self.model.rowCount() * 100) if self.model.rowCount() > 0 else 0 + status_text = f"Active: {active_count} | Progress: {avg_progress:.1f}% | DL: {format_size(global_down_rate)}/s | UL: {format_size(global_up_rate)}/s" + self.statusBar().showMessage(status_text, 0) def _sync_to_database(self): - """Periodically sync current memory state to SQLite database.""" + """Periodically sync only modified torrents to SQLite database.""" + synced_count = 0 for i in range(self.model.rowCount()): torrent = self.model.get_torrent(i) if not torrent or "handle" not in torrent: continue - try: - self.db.update_torrent(torrent["info_hash"], { - "progress": torrent["progress"], - "status": torrent["status"] - }) - except Exception as e: - logger.error(f"Error syncing torrent {i} to DB: {e}") - -import os + + # Only sync if the torrent is marked as 'dirty' (changed since last sync) + if torrent.get("dirty"): + try: + self.db.update_torrent(torrent["info_hash"], { + "progress": torrent["progress"], + "status": torrent["status"] + }) + # Reset dirty flag + torrent["dirty"] = False + synced_count += 1 + except Exception as e: + logger.error(f"Error syncing torrent {i} to DB: {e}") + + if synced_count > 0: + logger.info(f"Synced {synced_count} changed torrents to database.") diff --git a/src/gui/torrent_model.py b/src/gui/torrent_model.py index 3e92a76..c160a0c 100644 --- a/src/gui/torrent_model.py +++ b/src/gui/torrent_model.py @@ -5,7 +5,7 @@ class TorrentModel(QAbstractTableModel): super().__init__() # List of dicts: {"handle": lt_handle, "name": str, "size": str, "progress": float, "status": str} self._torrents = torrents or [] - self._headers = ["Name", "Size", "Progress", "Status"] + self._headers = ["Name", "Size", "Progress", "Status", "DL", "UL"] def rowCount(self, parent=QModelIndex()): return len(self._torrents) @@ -29,6 +29,14 @@ class TorrentModel(QAbstractTableModel): return f"{torrent['progress'] * 100:.1f}%" elif column == 3: return torrent["status"] + elif column == 4: + return torrent.get("down_rate", "0 B/s") + elif column == 5: + return torrent.get("up_rate", "0 B/s") + + if role == Qt.ItemDataRole.UserRole: + if column == 2: + return torrent["progress"] return None @@ -37,18 +45,30 @@ class TorrentModel(QAbstractTableModel): return self._headers[section] return None - def add_torrent(self, torrent_data): - """Add a new torrent to the model.""" - self.beginInsertRows(QModelIndex(), len(self._torrents), len(self._torrents)) - self._torrents.append(torrent_data) - self.endInsertRows() - def update_torrent(self, index, updates): """Update existing torrent data and notify the view.""" if 0 <= index < len(self._torrents): + # Mark as dirty if progress or status changed + if "progress" in updates or "status" in updates: + self._torrents[index]["dirty"] = True self._torrents[index].update(updates) - # Notify for columns that might have changed (Size, Progress, Status) - self.dataChanged.emit(self.index(index, 1), self.index(index, 3)) + # Notify for columns that might have changed (Size, Progress, Status, DL, UL) + self.dataChanged.emit(self.index(index, 1), self.index(index, 5)) + + def add_torrent(self, torrent_data): + """Add a new torrent to the model.""" + self.beginInsertRows(QModelIndex(), len(self._torrents), len(self._torrents)) + # Mark as dirty so it gets synced to DB immediately if not already there + torrent_data["dirty"] = True + self._torrents.append(torrent_data) + self.endInsertRows() + + def remove_torrent(self, index): + """Remove a torrent from the model.""" + if 0 <= index < len(self._torrents): + self.beginRemoveRows(QModelIndex(), index, index) + del self._torrents[index] + self.endRemoveRows() def get_torrent(self, index): if 0 <= index < len(self._torrents): diff --git a/src/utils/helpers.py b/src/utils/helpers.py new file mode 100644 index 0000000..dbd89a0 --- /dev/null +++ b/src/utils/helpers.py @@ -0,0 +1,9 @@ +def format_size(bytes): + """Convert bytes to human readable string.""" + if bytes is None: + return "Unknown" + for unit in ['B', 'KB', 'MB', 'GB', 'TB']: + if bytes < 1024.0: + return f"{bytes:.2f} {unit}" + bytes /= 1024.0 + return f"{bytes:.2f} PB" diff --git a/style.qss b/style.qss index 3e8042e..8c9393f 100644 --- a/style.qss +++ b/style.qss @@ -8,7 +8,7 @@ QToolBar { background-color: #313244; border-bottom: 1px solid #45475a; spacing: 10px; - padding: 5px; + padding: 8px; } /* Buttons */ @@ -16,7 +16,7 @@ QPushButton { background-color: #45475a; color: #cdd6f4; border: none; - border-radius: 4px; + border-radius: 6px; padding: 6px 12px; font-weight: bold; } @@ -51,12 +51,28 @@ QTableView { QHeaderView::section { background-color: #313244; color: #cdd6f4; - padding: 6px; + padding: 8px; border: none; font-weight: bold; border-bottom: 2px solid #89b4fa; } +/* Progress Bar (used in Delegate) */ +QProgressBar { + background-color: #313244; + color: transparent; + border: none; + border-radius: 4px; + text-align: center; + font-weight: bold; +} + +QProgressBar::chunk { + background-color: #89b4fa; + width: 2px; + margin: 0.1px; +} + /* Status Bar */ QStatusBar { background-color: #1e1e2e; @@ -64,6 +80,11 @@ QStatusBar { border-top: 1px solid #313244; } +#GlobalStatsLabel { + font-weight: bold; + color: #b4bef5; +} + /* Dialogs */ QDialog { background-color: #1e1e2e; @@ -78,7 +99,7 @@ QLineEdit { background-color: #313244; color: #cdd6f4; border: 1px solid #45475a; - border-radius: 4px; + border-radius: 6px; padding: 5px; } @@ -90,7 +111,7 @@ QComboBox { background-color: #313244; color: #cdd6f4; border: 1px solid #45475a; - border-radius: 4px; + border-radius: 6px; padding: 5px; }