diff --git a/TODO b/TODO index 50ad4fb23..e0bdf6d97 100644 --- a/TODO +++ b/TODO @@ -46,7 +46,7 @@ - update sorting when a new torrent is added? - Keep documention up to date - Windows port (Chris - Peerkoel) -- wait for fastresume data on exit should be in a thread? +- write a patch for file_priority(int index); * beta5 - Translations update (IN PROGRESS) - Wait for some bug fixes in libtorrent : @@ -76,6 +76,7 @@ beta4->beta5 changelog: - FEATURE: Allow to remove url seeds, even hard-coded ones - FEATURE: Improved code for handling of finished torrents - FEATURE: Optimized download list refreshing a little +- FEATURE: Big code cleanup - BUGFIX: Wait for torrent_paused_alert before saving fast resume data on exit - BUGFIX: Wait for torrent_paused_alert before reloading a torrent for full allocation mode - BUFFIG: Fixed overflow causing ratio data to be negative diff --git a/src/DLListDelegate.h b/src/DLListDelegate.h index 902cb6052..b2b928981 100644 --- a/src/DLListDelegate.h +++ b/src/DLListDelegate.h @@ -67,14 +67,14 @@ class DLListDelegate: public QItemDelegate { QItemDelegate::drawBackground(painter, opt, index); float speed = index.data().toDouble(); snprintf(tmp, MAX_CHAR_TMP, "%.1f", speed/1024.); - QItemDelegate::drawDisplay(painter, opt, opt.rect, QString(tmp)+" "+tr("KiB/s")); + QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::fromUtf8(tmp)+QString::fromUtf8(" ")+tr("KiB/s")); break; } case RATIO:{ QItemDelegate::drawBackground(painter, opt, index); float ratio = index.data().toDouble(); snprintf(tmp, MAX_CHAR_TMP, "%.1f", ratio); - QItemDelegate::drawDisplay(painter, opt, opt.rect, QString(tmp)); + QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::fromUtf8(tmp)); break; } case PROGRESS:{ @@ -83,7 +83,7 @@ class DLListDelegate: public QItemDelegate { progress = index.data().toDouble()*100.; snprintf(tmp, MAX_CHAR_TMP, "%.1f", progress); newopt.rect = opt.rect; - newopt.text = QString(tmp)+"%"; + newopt.text = QString::fromUtf8(tmp)+QString::fromUtf8("%"); newopt.progress = (int)progress; newopt.maximum = 100; newopt.minimum = 0; diff --git a/src/FinishedListDelegate.h b/src/FinishedListDelegate.h index 2484623b1..83b0e8cb7 100644 --- a/src/FinishedListDelegate.h +++ b/src/FinishedListDelegate.h @@ -60,14 +60,14 @@ class FinishedListDelegate: public QItemDelegate { QItemDelegate::drawBackground(painter, opt, index); float speed = index.data().toDouble(); snprintf(tmp, MAX_CHAR_TMP, "%.1f", speed/1024.); - QItemDelegate::drawDisplay(painter, opt, opt.rect, QString(tmp)+" "+tr("KiB/s")); + QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::fromUtf8(tmp)+QString::fromUtf8(" ")+tr("KiB/s")); break; } case F_RATIO:{ QItemDelegate::drawBackground(painter, opt, index); float ratio = index.data().toDouble(); snprintf(tmp, MAX_CHAR_TMP, "%.1f", ratio); - QItemDelegate::drawDisplay(painter, opt, opt.rect, QString(tmp)); + QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::fromUtf8(tmp)); break; } case F_PROGRESS:{ @@ -76,7 +76,7 @@ class FinishedListDelegate: public QItemDelegate { progress = index.data().toDouble()*100.; snprintf(tmp, MAX_CHAR_TMP, "%.1f", progress); newopt.rect = opt.rect; - newopt.text = QString(tmp)+"%"; + newopt.text = QString::fromUtf8(tmp)+QString::fromUtf8("%"); newopt.progress = (int)progress; newopt.maximum = 100; newopt.minimum = 0; diff --git a/src/FinishedTorrents.cpp b/src/FinishedTorrents.cpp index e9f48e743..35dd2698e 100644 --- a/src/FinishedTorrents.cpp +++ b/src/FinishedTorrents.cpp @@ -78,14 +78,14 @@ void FinishedTorrents::addFinishedTorrent(QString hash){ int row = getRowFromHash(hash); if(row != -1) return; row = finishedListModel->rowCount(); - torrent_handle h = BTSession->getTorrentHandle(hash); + QTorrentHandle h = BTSession->getTorrentHandle(hash); // Adding torrent to download list finishedListModel->insertRow(row); - finishedListModel->setData(finishedListModel->index(row, F_NAME), QVariant(h.name().c_str())); - finishedListModel->setData(finishedListModel->index(row, F_SIZE), QVariant((qlonglong)h.get_torrent_info().total_size())); + finishedListModel->setData(finishedListModel->index(row, F_NAME), QVariant(h.name())); + finishedListModel->setData(finishedListModel->index(row, F_SIZE), QVariant((qlonglong)h.total_size())); finishedListModel->setData(finishedListModel->index(row, F_UPSPEED), QVariant((double)0.)); finishedListModel->setData(finishedListModel->index(row, F_SEEDSLEECH), QVariant("0/0")); - finishedListModel->setData(finishedListModel->index(row, F_RATIO), QVariant(QString(misc::toString(BTSession->getRealRatio(hash)).c_str()))); + finishedListModel->setData(finishedListModel->index(row, F_RATIO), QVariant(QString::fromUtf8(misc::toString(BTSession->getRealRatio(hash)).c_str()))); finishedListModel->setData(finishedListModel->index(row, F_HASH), QVariant(hash)); finishedListModel->setData(finishedListModel->index(row, F_PROGRESS), QVariant((double)1.)); if(h.is_paused()) { @@ -101,7 +101,7 @@ void FinishedTorrents::addFinishedTorrent(QString hash){ finished_file.close(); // Update the number of finished torrents ++nbFinished; - ((GUI*)parent)->setTabText(1, tr("Finished") +" ("+QString(misc::toString(nbFinished).c_str())+")"); + ((GUI*)parent)->setTabText(1, tr("Finished") +" ("+QString::fromUtf8(misc::toString(nbFinished).c_str())+")"); } // Set the color of a row in data model @@ -138,7 +138,7 @@ void FinishedTorrents::saveColWidthFinishedList() const{ QStringList width_list; unsigned int nbColumns = finishedListModel->columnCount()-1; for(unsigned int i=0; icolumnWidth(i)).c_str()); + width_list << QString::fromUtf8(misc::toString(finishedList->columnWidth(i)).c_str()); } settings.setValue("FinishedListColsWidth", width_list.join(" ")); qDebug("Finished list columns width saved"); @@ -162,12 +162,11 @@ void FinishedTorrents::updateFinishedList(){ QString hash; QStringList finishedSHAs = BTSession->getFinishedTorrents(); foreach(hash, finishedSHAs){ - torrent_handle h = BTSession->getTorrentHandle(hash); + QTorrentHandle h = BTSession->getTorrentHandle(hash); if(!h.is_valid()){ qDebug("Problem: This torrent is not valid in finished list"); continue; } - torrent_status torrentStatus = h.status(); int row = getRowFromHash(hash); if(row == -1){ qDebug("Cannot find torrent in finished list, adding it"); @@ -175,8 +174,8 @@ void FinishedTorrents::updateFinishedList(){ continue; } if(h.is_paused()) continue; - Q_ASSERT(torrentStatus.progress <= 1. && torrentStatus.progress >= 0.); - if(torrentStatus.state == torrent_status::downloading || (torrentStatus.state != torrent_status::checking_files && torrentStatus.state != torrent_status::queued_for_checking && torrentStatus.progress < 1.)) { + Q_ASSERT(h.progress() <= 1. && h.progress() >= 0.); + if(h.state() == torrent_status::downloading || (h.state() != torrent_status::checking_files && h.state() != torrent_status::queued_for_checking && h.progress() < 1.)) { // What are you doing here? go back to download tab! qDebug("Info: a torrent was moved from finished to download tab"); deleteFromFinishedList(hash); @@ -184,9 +183,9 @@ void FinishedTorrents::updateFinishedList(){ emit torrentMovedFromFinishedList(h); continue; } - finishedListModel->setData(finishedListModel->index(row, F_UPSPEED), QVariant((double)torrentStatus.upload_payload_rate)); - finishedListModel->setData(finishedListModel->index(row, F_SEEDSLEECH), QVariant(QString(misc::toString(torrentStatus.num_seeds, true).c_str())+"/"+QString(misc::toString(torrentStatus.num_peers - torrentStatus.num_seeds, true).c_str()))); - finishedListModel->setData(finishedListModel->index(row, F_RATIO), QVariant(QString(misc::toString(BTSession->getRealRatio(hash)).c_str()))); + finishedListModel->setData(finishedListModel->index(row, F_UPSPEED), QVariant((double)h.upload_payload_rate())); + finishedListModel->setData(finishedListModel->index(row, F_SEEDSLEECH), QVariant(misc::toQString(h.num_seeds(), true)+"/"+misc::toQString(h.num_peers() - h.num_seeds(), true))); + finishedListModel->setData(finishedListModel->index(row, F_RATIO), QVariant(misc::toQString(BTSession->getRealRatio(hash)))); } } @@ -207,7 +206,7 @@ void FinishedTorrents::deleteFromFinishedList(QString hash){ finishedListModel->removeRow(row); QFile::remove(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".finished"); --nbFinished; - ((GUI*)parent)->setTabText(1, tr("Finished") +" ("+QString(misc::toString(nbFinished).c_str())+")"); + ((GUI*)parent)->setTabText(1, tr("Finished") +" ("+QString::fromUtf8(misc::toString(nbFinished).c_str())+")"); BTSession->setUnfinishedTorrent(hash); } @@ -222,17 +221,18 @@ QStandardItemModel* FinishedTorrents::getFinishedListModel(){ // Show torrent properties dialog void FinishedTorrents::showProperties(const QModelIndex &index){ int row = index.row(); - QString fileHash = finishedListModel->data(finishedListModel->index(row, F_HASH)).toString(); - torrent_handle h = BTSession->getTorrentHandle(fileHash); + QString hash = finishedListModel->data(finishedListModel->index(row, F_HASH)).toString(); + QTorrentHandle h = BTSession->getTorrentHandle(hash); properties *prop = new properties(this, BTSession, h); - connect(prop, SIGNAL(mustHaveFullAllocationMode(torrent_handle)), BTSession, SLOT(reloadTorrent(torrent_handle))); + connect(prop, SIGNAL(mustHaveFullAllocationMode(QTorrentHandle)), BTSession, SLOT(reloadTorrent(QTorrentHandle))); connect(prop, SIGNAL(filteredFilesChanged(QString)), this, SLOT(updateFileSize(QString))); prop->show(); } void FinishedTorrents::updateFileSize(QString hash){ int row = getRowFromHash(hash); - finishedListModel->setData(finishedListModel->index(row, F_SIZE), QVariant((qlonglong)BTSession->torrentEffectiveSize(hash))); + QTorrentHandle h = BTSession->getTorrentHandle(hash); + finishedListModel->setData(finishedListModel->index(row, F_SIZE), QVariant((qlonglong)h.actual_size())); } // display properties of selected items @@ -256,13 +256,13 @@ void FinishedTorrents::displayFinishedListMenu(const QPoint& pos){ foreach(index, selectedIndexes){ if(index.column() == F_NAME){ // Get the file name - QString fileHash = finishedListModel->data(finishedListModel->index(index.row(), F_HASH)).toString(); - torrent_handle h = BTSession->getTorrentHandle(fileHash); + QString hash = finishedListModel->data(finishedListModel->index(index.row(), F_HASH)).toString(); + QTorrentHandle h = BTSession->getTorrentHandle(hash); myFinishedListMenu.addAction(actionDelete); myFinishedListMenu.addAction(actionDelete_Permanently); myFinishedListMenu.addAction(actionSet_upload_limit); myFinishedListMenu.addAction(actionTorrent_Properties); - if(!previewProgram.isEmpty() && BTSession->isFilePreviewPossible(fileHash) && selectedIndexes.size()<=finishedListModel->columnCount()){ + if(!previewProgram.isEmpty() && BTSession->isFilePreviewPossible(hash) && selectedIndexes.size()<=finishedListModel->columnCount()){ myFinishedListMenu.addAction(actionPreview_file); } break; diff --git a/src/FinishedTorrents.h b/src/FinishedTorrents.h index 529b1f6a7..c309c6835 100644 --- a/src/FinishedTorrents.h +++ b/src/FinishedTorrents.h @@ -24,7 +24,7 @@ #include "ui_seeding.h" #include "FinishedListDelegate.h" -#include +#include "qtorrenthandle.h" class QStandardItemModel; class bittorrent; @@ -68,7 +68,7 @@ class FinishedTorrents : public QWidget, public Ui::seeding{ void on_actionSet_upload_limit_triggered(); signals: - void torrentMovedFromFinishedList(torrent_handle); + void torrentMovedFromFinishedList(QTorrentHandle); }; diff --git a/src/GUI.cpp b/src/GUI.cpp index 43c1432dd..f18d23faa 100644 --- a/src/GUI.cpp +++ b/src/GUI.cpp @@ -48,6 +48,9 @@ #include "previewSelect.h" #include "options_imp.h" +using namespace libtorrent; +namespace fs = boost::filesystem; + /***************************************************** * * * GUI * @@ -55,14 +58,14 @@ *****************************************************/ // Constructor -GUI::GUI(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent){ +GUI::GUI(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent) { setupUi(this); - setWindowTitle(tr("qBittorrent %1", "e.g: qBittorrent v0.x").arg(VERSION)); - QSettings settings("qBittorrent", "qBittorrent"); - systrayIntegration = settings.value("Options/Misc/Behaviour/SystrayIntegration", true).toBool(); + setWindowTitle(tr("qBittorrent %1", "e.g: qBittorrent v0.x").arg(QString::fromUtf8(VERSION))); + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + systrayIntegration = settings.value(QString::fromUtf8("Options/Misc/Behaviour/SystrayIntegration"), true).toBool(); // Create tray icon - if (QSystemTrayIcon::isSystemTrayAvailable()){ - if(systrayIntegration){ + if (QSystemTrayIcon::isSystemTrayAvailable()) { + if(systrayIntegration) { createTrayIcon(); } }else{ @@ -75,11 +78,11 @@ GUI::GUI(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent){ finishedTorrentTab = new FinishedTorrents(this, BTSession); tabs->addTab(finishedTorrentTab, tr("Finished")); tabs->setTabIcon(1, QIcon(QString::fromUtf8(":/Icons/skin/seeding.png"))); - connect(finishedTorrentTab, SIGNAL(torrentMovedFromFinishedList(torrent_handle)), this, SLOT(restoreInDownloadList(torrent_handle))); + connect(finishedTorrentTab, SIGNAL(torrentMovedFromFinishedList(QTorrentHandle)), this, SLOT(restoreInDownloadList(QTorrentHandle))); // Tabs text nbTorrents = 0; - tabs->setTabText(0, tr("Downloads") + " (0)"); - tabs->setTabText(1, tr("Finished") + " (0)"); + tabs->setTabText(0, tr("Downloads") + QString::fromUtf8(" (0)")); + tabs->setTabText(1, tr("Finished") + QString::fromUtf8(" (0)")); // Setting icons this->setWindowIcon(QIcon(QString::fromUtf8(":/Icons/qbittorrent32.png"))); actionOpen->setIcon(QIcon(QString::fromUtf8(":/Icons/skin/open.png"))); @@ -104,7 +107,7 @@ GUI::GUI(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent){ connecStatusLblIcon = new QLabel(); connecStatusLblIcon->setFrameShape(QFrame::NoFrame); connecStatusLblIcon->setPixmap(QPixmap(QString::fromUtf8(":/Icons/skin/disconnected.png"))); - connecStatusLblIcon->setToolTip(""+tr("Connection status:")+"
"+tr("Offline")+"
"+tr("No peers found...")+""); + connecStatusLblIcon->setToolTip(QString::fromUtf8("")+tr("Connection status:")+QString::fromUtf8("
")+tr("Offline")+QString::fromUtf8("
")+tr("No peers found...")+QString::fromUtf8("")); toolBar->addWidget(connecStatusLblIcon); actionDelete_Permanently->setIcon(QIcon(QString::fromUtf8(":/Icons/skin/delete_perm.png"))); actionTorrent_Properties->setIcon(QIcon(QString::fromUtf8(":/Icons/skin/properties.png"))); @@ -132,13 +135,13 @@ GUI::GUI(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent){ // Hide hash column downloadList->hideColumn(HASH); - connect(BTSession, SIGNAL(addedTorrent(QString, torrent_handle&, bool)), this, SLOT(torrentAdded(QString, torrent_handle&, bool))); + connect(BTSession, SIGNAL(addedTorrent(QString, QTorrentHandle&, bool)), this, SLOT(torrentAdded(QString, QTorrentHandle&, bool))); connect(BTSession, SIGNAL(duplicateTorrent(QString)), this, SLOT(torrentDuplicate(QString))); connect(BTSession, SIGNAL(invalidTorrent(QString)), this, SLOT(torrentCorrupted(QString))); - connect(BTSession, SIGNAL(finishedTorrent(torrent_handle&)), this, SLOT(finishedTorrent(torrent_handle&))); - connect(BTSession, SIGNAL(fullDiskError(torrent_handle&)), this, SLOT(fullDiskError(torrent_handle&))); + connect(BTSession, SIGNAL(finishedTorrent(QTorrentHandle&)), this, SLOT(finishedTorrent(QTorrentHandle&))); + connect(BTSession, SIGNAL(fullDiskError(QTorrentHandle&)), this, SLOT(fullDiskError(QTorrentHandle&))); connect(BTSession, SIGNAL(portListeningFailure()), this, SLOT(portListeningFailure())); - connect(BTSession, SIGNAL(trackerAuthenticationRequired(torrent_handle&)), this, SLOT(trackerAuthenticationRequired(torrent_handle&))); + connect(BTSession, SIGNAL(trackerAuthenticationRequired(QTorrentHandle&)), this, SLOT(trackerAuthenticationRequired(QTorrentHandle&))); connect(BTSession, SIGNAL(peerBlocked(QString)), this, SLOT(addLogPeerBlocked(const QString))); connect(BTSession, SIGNAL(fastResumeDataRejected(QString)), this, SLOT(addFastResumeRejectedAlert(QString))); connect(BTSession, SIGNAL(scanDirFoundTorrents(const QStringList&)), this, SLOT(processScannedFiles(const QStringList&))); @@ -156,7 +159,7 @@ GUI::GUI(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent){ // Resume unfinished torrents BTSession->resumeUnfinishedTorrents(); // Load last columns width for download list - if(!loadColWidthDLList()){ + if(!loadColWidthDLList()) { downloadList->header()->resizeSection(0, 200); } // Search engine tab @@ -197,21 +200,21 @@ GUI::GUI(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent){ // Accept drag 'n drops setAcceptDrops(true); // Set info Bar infos - setInfoBar(tr("qBittorrent %1 started.", "e.g: qBittorrent v0.x started.").arg(QString(VERSION))); - setInfoBar(tr("Be careful, sharing copyrighted material without permission is against the law."), "red"); + setInfoBar(tr("qBittorrent %1 started.", "e.g: qBittorrent v0.x started.").arg(QString::fromUtf8(""VERSION))); + setInfoBar(tr("Be careful, sharing copyrighted material without permission is against the law."), QString::fromUtf8("red")); show(); createKeyboardShortcuts(); qDebug("GUI Built"); } // Destructor -GUI::~GUI(){ +GUI::~GUI() { qDebug("GUI destruction"); delete searchEngine; delete finishedTorrentTab; delete checkConnect; delete refresher; - if(systrayIntegration){ + if(systrayIntegration) { delete myTrayIcon; delete myTrayIconMenu; } @@ -231,30 +234,30 @@ GUI::~GUI(){ delete BTSession; } -void GUI::on_actionWebsite_triggered(){ - QDesktopServices::openUrl(QUrl("http://www.qbittorrent.org")); +void GUI::on_actionWebsite_triggered() { + QDesktopServices::openUrl(QUrl(QString::fromUtf8("http://www.qbittorrent.org"))); } -void GUI::on_actionDocumentation_triggered(){ - QDesktopServices::openUrl(QUrl("http://wiki.qbittorrent.org")); +void GUI::on_actionDocumentation_triggered() { + QDesktopServices::openUrl(QUrl(QString::fromUtf8("http://wiki.qbittorrent.org"))); } -void GUI::on_actionBugReport_triggered(){ - QDesktopServices::openUrl(QUrl("http://bugs.qbittorrent.org")); +void GUI::on_actionBugReport_triggered() { + QDesktopServices::openUrl(QUrl(QString::fromUtf8("http://bugs.qbittorrent.org"))); } void GUI::writeSettings() { - QSettings settings("qBittorrent", "qBittorrent"); - settings.beginGroup("MainWindow"); - settings.setValue("size", size()); - settings.setValue("pos", pos()); + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + settings.beginGroup(QString::fromUtf8("MainWindow")); + settings.setValue(QString::fromUtf8("size"), size()); + settings.setValue(QString::fromUtf8("pos"), pos()); settings.endGroup(); } -void GUI::createKeyboardShortcuts(){ - actionCreate_torrent->setShortcut(QKeySequence("Ctrl+N")); - actionOpen->setShortcut(QKeySequence("Ctrl+O")); - actionExit->setShortcut(QKeySequence("Ctrl+Q")); +void GUI::createKeyboardShortcuts() { + actionCreate_torrent->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+N"))); + actionOpen->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+O"))); + actionExit->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+Q"))); switchDownShortcut = new QShortcut(QKeySequence(tr("Alt+1", "shortcut to switch to first tab")), this); connect(switchDownShortcut, SIGNAL(activated()), this, SLOT(displayDownTab())); switchUpShortcut = new QShortcut(QKeySequence(tr("Alt+2", "shortcut to switch to second tab")), this); @@ -265,77 +268,77 @@ void GUI::createKeyboardShortcuts(){ connect(switchSearchShortcut2, SIGNAL(activated()), this, SLOT(displaySearchTab())); switchRSSShortcut = new QShortcut(QKeySequence(tr("Alt+4", "shortcut to switch to fourth tab")), this); connect(switchRSSShortcut, SIGNAL(activated()), this, SLOT(displayRSSTab())); - actionTorrent_Properties->setShortcut(QKeySequence("Alt+P")); - actionOptions->setShortcut(QKeySequence("Alt+O")); - actionDelete->setShortcut(QKeySequence("Del")); - actionDelete_Permanently->setShortcut(QKeySequence("Shift+Del")); - actionStart->setShortcut(QKeySequence("Ctrl+S")); - actionStart_All->setShortcut(QKeySequence("Ctrl+Shift+S")); - actionPause->setShortcut(QKeySequence("Ctrl+P")); - actionPause_All->setShortcut(QKeySequence("Ctrl+Shift+P")); + actionTorrent_Properties->setShortcut(QKeySequence(QString::fromUtf8("Alt+P"))); + actionOptions->setShortcut(QKeySequence(QString::fromUtf8("Alt+O"))); + actionDelete->setShortcut(QKeySequence(QString::fromUtf8("Del"))); + actionDelete_Permanently->setShortcut(QKeySequence(QString::fromUtf8("Shift+Del"))); + actionStart->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+S"))); + actionStart_All->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+Shift+S"))); + actionPause->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+P"))); + actionPause_All->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+Shift+P"))); } // Keyboard shortcuts slots -void GUI::displayDownTab(){ +void GUI::displayDownTab() { tabs->setCurrentIndex(0); } -void GUI::displayUpTab(){ +void GUI::displayUpTab() { tabs->setCurrentIndex(1); } -void GUI::displaySearchTab(){ +void GUI::displaySearchTab() { tabs->setCurrentIndex(2); } -void GUI::displayRSSTab(){ +void GUI::displayRSSTab() { tabs->setCurrentIndex(3); } // End of keyboard shortcuts slots void GUI::readSettings() { - QSettings settings("qBittorrent", "qBittorrent"); - settings.beginGroup("MainWindow"); - resize(settings.value("size", size()).toSize()); - move(settings.value("pos", screenCenter()).toPoint()); + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + settings.beginGroup(QString::fromUtf8("MainWindow")); + resize(settings.value(QString::fromUtf8("size"), size()).toSize()); + move(settings.value(QString::fromUtf8("pos"), screenCenter()).toPoint()); settings.endGroup(); } -void GUI::addLogPeerBlocked(QString ip){ +void GUI::addLogPeerBlocked(QString ip) { static unsigned short nbLines = 0; ++nbLines; - if(nbLines > 200){ + if(nbLines > 200) { textBlockedUsers->clear(); nbLines = 1; } - textBlockedUsers->append(""+ QTime::currentTime().toString("hh:mm:ss") + " - "+tr("%1 was blocked", "x.y.z.w was blocked").arg(ip)); + textBlockedUsers->append(QString::fromUtf8("")+ QTime::currentTime().toString(QString::fromUtf8("hh:mm:ss")) + QString::fromUtf8(" - ")+tr("%1 was blocked", "x.y.z.w was blocked").arg(ip)); } // Update Info Bar information -void GUI::setInfoBar(QString info, QString color){ +void GUI::setInfoBar(QString info, QString color) { static unsigned short nbLines = 0; ++nbLines; // Check log size, clear it if too big - if(nbLines > 200){ + if(nbLines > 200) { infoBar->clear(); nbLines = 1; } - infoBar->append(""+ QTime::currentTime().toString("hh:mm:ss") + " - " + info + ""); + infoBar->append(QString::fromUtf8("")+ QTime::currentTime().toString(QString::fromUtf8("hh:mm:ss")) + QString::fromUtf8(" - ") + info + QString::fromUtf8("")); } -void GUI::addFastResumeRejectedAlert(QString name){ - setInfoBar(tr("Fast resume data was rejected for torrent %1, checking again...").arg(name), "red"); +void GUI::addFastResumeRejectedAlert(QString name) { + setInfoBar(tr("Fast resume data was rejected for torrent %1, checking again...").arg(name), QString::fromUtf8("red")); } -void GUI::addUrlSeedError(QString url, QString msg){ - setInfoBar(tr("Url seed lookup failed for url: %1, message: %2").arg(url).arg(msg), "red"); +void GUI::addUrlSeedError(QString url, QString msg) { + setInfoBar(tr("Url seed lookup failed for url: %1, message: %2").arg(url).arg(msg), QString::fromUtf8("red")); } -void GUI::balloonClicked(){ - if(isHidden()){ +void GUI::balloonClicked() { + if(isHidden()) { show(); - if(isMinimized()){ + if(isMinimized()) { showNormal(); } raise(); @@ -343,28 +346,28 @@ void GUI::balloonClicked(){ } } -void GUI::acceptConnection(){ +void GUI::acceptConnection() { clientConnection = tcpServer->nextPendingConnection(); connect(clientConnection, SIGNAL(disconnected()), this, SLOT(readParamsOnSocket())); qDebug("accepted connection from another instance"); } -void GUI::readParamsOnSocket(){ - if(clientConnection != 0){ +void GUI::readParamsOnSocket() { + if(clientConnection != 0) { QByteArray params = clientConnection->readAll(); - if(!params.isEmpty()){ - processParams(QString(params.data()).split("\n")); + if(!params.isEmpty()) { + processParams(QString::fromUtf8(params.data()).split(QString::fromUtf8("\n"))); qDebug("Received parameters from another instance"); } } } -void GUI::on_actionSet_download_limit_triggered(){ +void GUI::on_actionSet_download_limit_triggered() { QModelIndexList selectedIndexes = downloadList->selectionModel()->selectedIndexes(); QModelIndex index; QStringList hashes; - foreach(index, selectedIndexes){ - if(index.column() == NAME){ + foreach(index, selectedIndexes) { + if(index.column() == NAME) { // Get the file hash hashes << DLListModel->data(DLListModel->index(index.row(), HASH)).toString(); } @@ -373,12 +376,12 @@ void GUI::on_actionSet_download_limit_triggered(){ new BandwidthAllocationDialog(this, false, BTSession, hashes); } -void GUI::on_actionSet_upload_limit_triggered(){ +void GUI::on_actionSet_upload_limit_triggered() { QModelIndexList selectedIndexes = downloadList->selectionModel()->selectedIndexes(); QModelIndex index; QStringList hashes; - foreach(index, selectedIndexes){ - if(index.column() == NAME){ + foreach(index, selectedIndexes) { + if(index.column() == NAME) { // Get the file hash hashes << DLListModel->data(DLListModel->index(index.row(), HASH)).toString(); } @@ -392,17 +395,17 @@ void GUI::handleDownloadFromUrlFailure(QString url, QString reason) const{ QMessageBox::critical(0, tr("Url download error"), tr("Couldn't download file at url: %1, reason: %2.").arg(url).arg(reason)); } -void GUI::on_actionSet_global_upload_limit_triggered(){ +void GUI::on_actionSet_global_upload_limit_triggered() { qDebug("actionSet_global_upload_limit_triggered"); new BandwidthAllocationDialog(this, true, BTSession, QStringList()); } -void GUI::on_actionSet_global_download_limit_triggered(){ +void GUI::on_actionSet_global_download_limit_triggered() { qDebug("actionSet_global_download_limit_triggered"); new BandwidthAllocationDialog(this, false, BTSession, QStringList()); } -void GUI::on_actionPreview_file_triggered(){ +void GUI::on_actionPreview_file_triggered() { if(tabs->currentIndex() > 1) return; bool inDownloadList = true; if(tabs->currentIndex()) @@ -413,54 +416,54 @@ void GUI::on_actionPreview_file_triggered(){ selectedIndexes = downloadList->selectionModel()->selectedIndexes(); else selectedIndexes = finishedTorrentTab->getFinishedList()->selectionModel()->selectedIndexes(); - foreach(index, selectedIndexes){ - if(index.column() == NAME){ + foreach(index, selectedIndexes) { + if(index.column() == NAME) { // Get the file hash - QString fileHash; + QString hash; if(inDownloadList) - fileHash = DLListModel->data(DLListModel->index(index.row(), HASH)).toString(); + hash = DLListModel->data(DLListModel->index(index.row(), HASH)).toString(); else - fileHash = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(index.row(), F_HASH)).toString(); - torrent_handle h = BTSession->getTorrentHandle(fileHash); + hash = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(index.row(), F_HASH)).toString(); + QTorrentHandle h = BTSession->getTorrentHandle(hash); previewSelection = new previewSelect(this, h); break; } } } -void GUI::cleanTempPreviewFile(int, QProcess::ExitStatus){ - if(!QFile::remove(QDir::tempPath()+QDir::separator()+"qBT_preview.tmp")){ - std::cerr << "Couldn't remove temporary file: " << (const char*)(QDir::tempPath()+QDir::separator()+"qBT_preview.tmp").toUtf8() << "\n"; +void GUI::cleanTempPreviewFile(int, QProcess::ExitStatus) { + if(!QFile::remove(QDir::tempPath()+QDir::separator()+QString::fromUtf8("qBT_preview.tmp"))) { + std::cerr << "Couldn't remove temporary file: " << (QDir::tempPath()+QDir::separator()+QString::fromUtf8("qBT_preview.tmp")).toUtf8().data() << "\n"; } } -void GUI::displayDLListMenu(const QPoint& pos){ +void GUI::displayDLListMenu(const QPoint& pos) { QMenu myDLLlistMenu(this); QModelIndex index; // Enable/disable pause/start action given the DL state QModelIndexList selectedIndexes = downloadList->selectionModel()->selectedIndexes(); - QSettings settings("qBittorrent", "qBittorrent"); - QString previewProgram = settings.value("Options/Misc/PreviewProgram", QString()).toString(); + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + QString previewProgram = settings.value(QString::fromUtf8("Options/Misc/PreviewProgram"), QString()).toString(); bool has_pause = false, has_start = false, has_preview = false; - foreach(index, selectedIndexes){ - if(index.column() == NAME){ + foreach(index, selectedIndexes) { + if(index.column() == NAME) { // Get the file name - QString fileHash = DLListModel->data(DLListModel->index(index.row(), HASH)).toString(); + QString hash = DLListModel->data(DLListModel->index(index.row(), HASH)).toString(); // Get handle and pause the torrent - torrent_handle h = BTSession->getTorrentHandle(fileHash); + QTorrentHandle h = BTSession->getTorrentHandle(hash); if(!h.is_valid()) continue; - if(h.is_paused()){ - if(!has_start){ + if(h.is_paused()) { + if(!has_start) { myDLLlistMenu.addAction(actionStart); has_start = true; } }else{ - if(!has_pause){ + if(!has_pause) { myDLLlistMenu.addAction(actionPause); has_pause = true; } } - if(!previewProgram.isEmpty() && BTSession->isFilePreviewPossible(fileHash) && !has_preview){ + if(!previewProgram.isEmpty() && BTSession->isFilePreviewPossible(hash) && !has_preview) { myDLLlistMenu.addAction(actionPreview_file); has_preview = true; } @@ -482,34 +485,34 @@ void GUI::displayDLListMenu(const QPoint& pos){ // Necessary if we want to close the window // in one time if "close to systray" is enabled -void GUI::on_actionExit_triggered(){ +void GUI::on_actionExit_triggered() { force_exit = true; close(); } -void GUI::previewFile(QString filePath){ +void GUI::previewFile(QString filePath) { // Check if there is already one preview running - if(previewProcess->state() == QProcess::NotRunning){ + if(previewProcess->state() == QProcess::NotRunning) { // First copy temporarily - QString tmpPath = QDir::tempPath()+QDir::separator()+"qBT_preview.tmp"; + QString tmpPath = QDir::tempPath()+QDir::separator()+QString::fromUtf8("qBT_preview.tmp"); QFile::remove(tmpPath); QFile::copy(filePath, tmpPath); // Launch program preview QStringList params; params << tmpPath; - QSettings settings("qBittorrent", "qBittorrent"); - QString previewProgram = settings.value("Options/Misc/PreviewProgram", QString()).toString(); + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + QString previewProgram = settings.value(QString::fromUtf8("Options/Misc/PreviewProgram"), QString()).toString(); previewProcess->start(previewProgram, params, QIODevice::ReadOnly); }else{ QMessageBox::critical(0, tr("Preview process already running"), tr("There is already another preview process running.\nPlease close the other one first.")); } } -void GUI::on_actionClearLog_triggered(){ +void GUI::on_actionClearLog_triggered() { infoBar->clear(); } -void GUI::displayInfoBarMenu(const QPoint& pos){ +void GUI::displayInfoBarMenu(const QPoint& pos) { // Log Menu QMenu myLogMenu(this); myLogMenu.addAction(actionClearLog); @@ -518,7 +521,7 @@ void GUI::displayInfoBarMenu(const QPoint& pos){ } void GUI::sortProgressColumnDelayed() { - if(delayedSorting){ + if(delayedSorting) { sortDownloadListFloat(PROGRESS, delayedSortingOrder); qDebug("Delayed sorting of progress column"); } @@ -526,101 +529,98 @@ void GUI::sortProgressColumnDelayed() { // get information from torrent handles and // update download list accordingly -void GUI::updateDlList(bool force){ +void GUI::updateDlList(bool force) { char tmp[MAX_CHAR_TMP]; char tmp2[MAX_CHAR_TMP]; // update global informations snprintf(tmp, MAX_CHAR_TMP, "%.1f", BTSession->getPayloadUploadRate()/1024.); snprintf(tmp2, MAX_CHAR_TMP, "%.1f", BTSession->getPayloadDownloadRate()/1024.); - if(systrayIntegration){ - myTrayIcon->setToolTip(""+tr("qBittorrent")+"
"+tr("DL speed: %1 KiB/s", "e.g: Download speed: 10 KiB/s").arg(QString(tmp2))+"
"+tr("UP speed: %1 KiB/s", "e.g: Upload speed: 10 KiB/s").arg(QString(tmp))); // tray icon + if(systrayIntegration) { + myTrayIcon->setToolTip(QString::fromUtf8("")+tr("qBittorrent")+QString::fromUtf8("
")+tr("DL speed: %1 KiB/s", "e.g: Download speed: 10 KiB/s").arg(QString::fromUtf8(tmp2))+QString::fromUtf8("
")+tr("UP speed: %1 KiB/s", "e.g: Upload speed: 10 KiB/s").arg(QString::fromUtf8(tmp))); // tray icon } - if(getCurrentTabIndex() == 1){ + if(getCurrentTabIndex() == 1) { finishedTorrentTab->updateFinishedList(); return; } - if(!force && getCurrentTabIndex() != 0){ + if(!force && getCurrentTabIndex() != 0) { // No need to update if qBittorrent DL list is hidden return; } //BTSession->printPausedTorrents(); - LCD_UpSpeed->display(tmp); // UP LCD - LCD_DownSpeed->display(tmp2); // DL LCD + LCD_UpSpeed->display(QString::fromUtf8(tmp)); // UP LCD + LCD_DownSpeed->display(QString::fromUtf8(tmp2)); // DL LCD // browse handles QStringList unfinishedTorrents = BTSession->getUnfinishedTorrents(); QString hash; - foreach(hash, unfinishedTorrents){ - torrent_handle h = BTSession->getTorrentHandle(hash); + foreach(hash, unfinishedTorrents) { + QTorrentHandle h = BTSession->getTorrentHandle(hash); try{ - torrent_status torrentStatus = h.status(); - QString fileHash = QString(misc::toString(h.info_hash()).c_str()); - int row = getRowFromHash(fileHash); - if(row == -1){ + QString hash = h.hash(); + int row = getRowFromHash(hash); + if(row == -1) { qDebug("Info: Could not find filename in download list, adding it..."); restoreInDownloadList(h); - row = getRowFromHash(fileHash); + row = getRowFromHash(hash); } Q_ASSERT(row != -1); // No need to update a paused torrent if(h.is_paused()) continue; // Parse download state - torrent_info ti = h.get_torrent_info(); // Setting download state - switch(torrentStatus.state){ + switch(h.state()) { case torrent_status::finished: case torrent_status::seeding: qDebug("A torrent that was in download tab just finished, moving it to finished tab"); - BTSession->setFinishedTorrent(fileHash); + BTSession->setFinishedTorrent(hash); finishedTorrent(h); continue; case torrent_status::checking_files: case torrent_status::queued_for_checking: - if(BTSession->getTorrentsToPauseAfterChecking().indexOf(fileHash) == -1){ - DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(":/Icons/time.png")), Qt::DecorationRole); - setRowColor(row, "grey"); - Q_ASSERT(torrentStatus.progress <= 1. && torrentStatus.progress >= 0.); - DLListModel->setData(DLListModel->index(row, PROGRESS), QVariant((double)torrentStatus.progress)); + if(BTSession->getTorrentsToPauseAfterChecking().indexOf(hash) == -1) { + DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/time.png"))), Qt::DecorationRole); + setRowColor(row, QString::fromUtf8("grey")); + Q_ASSERT(h.progress() <= 1. && h.progress() >= 0.); + DLListModel->setData(DLListModel->index(row, PROGRESS), QVariant((double)h.progress())); } break; case torrent_status::connecting_to_tracker: - if(torrentStatus.download_payload_rate > 0){ + if(h.download_payload_rate() > 0) { // Display "Downloading" status when connecting if download speed > 0 - DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)BTSession->getETA(fileHash))); - DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(":/Icons/skin/downloading.png")), Qt::DecorationRole); - setRowColor(row, "green"); + DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)BTSession->getETA(hash))); + DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/downloading.png"))), Qt::DecorationRole); + setRowColor(row, QString::fromUtf8("green")); }else{ DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)-1)); - DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(":/Icons/skin/connecting.png")), Qt::DecorationRole); - setRowColor(row, "grey"); + DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/connecting.png"))), Qt::DecorationRole); + setRowColor(row, QString::fromUtf8("grey")); } - Q_ASSERT(torrentStatus.progress <= 1. && torrentStatus.progress >= 0.); - DLListModel->setData(DLListModel->index(row, PROGRESS), QVariant((double)torrentStatus.progress)); - DLListModel->setData(DLListModel->index(row, DLSPEED), QVariant((double)torrentStatus.download_payload_rate)); - DLListModel->setData(DLListModel->index(row, UPSPEED), QVariant((double)torrentStatus.upload_payload_rate)); + Q_ASSERT(h.progress() <= 1. && h.progress() >= 0.); + DLListModel->setData(DLListModel->index(row, PROGRESS), QVariant((double)h.progress())); + DLListModel->setData(DLListModel->index(row, DLSPEED), QVariant((double)h.download_payload_rate())); + DLListModel->setData(DLListModel->index(row, UPSPEED), QVariant((double)h.upload_payload_rate())); break; case torrent_status::downloading: case torrent_status::downloading_metadata: - if(torrentStatus.download_payload_rate > 0){ - //qDebug("%s is downloading", (const char*)fileHash.toUtf8()); - DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(":/Icons/skin/downloading.png")), Qt::DecorationRole); - DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)BTSession->getETA(fileHash))); - setRowColor(row, "green"); + if(h.download_payload_rate() > 0) { + DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/downloading.png"))), Qt::DecorationRole); + DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)BTSession->getETA(hash))); + setRowColor(row, QString::fromUtf8("green")); }else{ - DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(":/Icons/skin/stalled.png")), Qt::DecorationRole); + DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/stalled.png"))), Qt::DecorationRole); DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)-1)); - setRowColor(row, "black"); + setRowColor(row, QString::fromUtf8("black")); } - Q_ASSERT(torrentStatus.progress <= 1. && torrentStatus.progress >= 0.); - DLListModel->setData(DLListModel->index(row, PROGRESS), QVariant((double)torrentStatus.progress)); - DLListModel->setData(DLListModel->index(row, DLSPEED), QVariant((double)torrentStatus.download_payload_rate)); - DLListModel->setData(DLListModel->index(row, UPSPEED), QVariant((double)torrentStatus.upload_payload_rate)); + Q_ASSERT(h.progress() <= 1. && h.progress() >= 0.); + DLListModel->setData(DLListModel->index(row, PROGRESS), QVariant((double)h.progress())); + DLListModel->setData(DLListModel->index(row, DLSPEED), QVariant((double)h.download_payload_rate())); + DLListModel->setData(DLListModel->index(row, UPSPEED), QVariant((double)h.upload_payload_rate())); break; default: DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)-1)); } - DLListModel->setData(DLListModel->index(row, SEEDSLEECH), QVariant(QString(misc::toString(torrentStatus.num_seeds, true).c_str())+"/"+QString(misc::toString(torrentStatus.num_peers - torrentStatus.num_seeds, true).c_str()))); - DLListModel->setData(DLListModel->index(row, RATIO), QVariant(QString(misc::toString(BTSession->getRealRatio(fileHash)).c_str()))); - }catch(invalid_handle e){ + DLListModel->setData(DLListModel->index(row, SEEDSLEECH), QVariant(misc::toQString(h.num_seeds(), true)+QString::fromUtf8("/")+misc::toQString(h.num_peers() - h.num_seeds(), true))); + DLListModel->setData(DLListModel->index(row, RATIO), QVariant(misc::toQString(BTSession->getRealRatio(hash)))); + }catch(invalid_handle e) { continue; } } @@ -632,49 +632,49 @@ unsigned int GUI::getCurrentTabIndex() const{ return tabs->currentIndex(); } -void GUI::restoreInDownloadList(torrent_handle h){ - QString hash = QString(misc::toString(h.info_hash()).c_str()); +void GUI::restoreInDownloadList(QTorrentHandle h) { + QString hash = h.hash(); int row = getRowFromHash(hash); if(row != -1) return; row = DLListModel->rowCount(); // Adding torrent to download list DLListModel->insertRow(row); - DLListModel->setData(DLListModel->index(row, NAME), QVariant(h.name().c_str())); - DLListModel->setData(DLListModel->index(row, SIZE), QVariant((qlonglong)BTSession->torrentEffectiveSize(hash))); + DLListModel->setData(DLListModel->index(row, NAME), QVariant(h.name())); + DLListModel->setData(DLListModel->index(row, SIZE), QVariant((qlonglong)h.actual_size())); DLListModel->setData(DLListModel->index(row, DLSPEED), QVariant((double)0.)); DLListModel->setData(DLListModel->index(row, UPSPEED), QVariant((double)0.)); - DLListModel->setData(DLListModel->index(row, SEEDSLEECH), QVariant("0/0")); + DLListModel->setData(DLListModel->index(row, SEEDSLEECH), QVariant(QString::fromUtf8("0/0"))); DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)-1)); DLListModel->setData(DLListModel->index(row, HASH), QVariant(hash)); // Pause torrent if it was paused last time if(BTSession->isPaused(hash)) { - DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(":/Icons/skin/paused.png")), Qt::DecorationRole); - setRowColor(row, "red"); + DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/paused.png"))), Qt::DecorationRole); + setRowColor(row, QString::fromUtf8("red")); }else{ - DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(":/Icons/skin/connecting.png")), Qt::DecorationRole); - setRowColor(row, "grey"); + DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/connecting.png"))), Qt::DecorationRole); + setRowColor(row, QString::fromUtf8("grey")); } ++nbTorrents; } -void GUI::setTabText(int index, QString text){ +void GUI::setTabText(int index, QString text) { tabs->setTabText(index, text); } -void GUI::sortDownloadListFloat(int index, Qt::SortOrder sortOrder){ +void GUI::sortDownloadListFloat(int index, Qt::SortOrder sortOrder) { QList > lines; // insertion sorting unsigned int nbRows = DLListModel->rowCount(); - for(unsigned int i=0; i(i, DLListModel->data(DLListModel->index(i, index)).toDouble()), sortOrder); } // Insert items in new model, in correct order unsigned int nbRows_old = lines.size(); - for(unsigned int row=0; rowinsertRow(DLListModel->rowCount()); unsigned int sourceRow = lines[row].first; unsigned int nbColumns = DLListModel->columnCount(); - for(unsigned int col=0; colsetData(DLListModel->index(nbRows_old+row, col), DLListModel->data(DLListModel->index(sourceRow, col))); DLListModel->setData(DLListModel->index(nbRows_old+row, col), DLListModel->data(DLListModel->index(sourceRow, col), Qt::DecorationRole), Qt::DecorationRole); DLListModel->setData(DLListModel->index(nbRows_old+row, col), DLListModel->data(DLListModel->index(sourceRow, col), Qt::ForegroundRole), Qt::ForegroundRole); @@ -684,20 +684,20 @@ void GUI::sortDownloadListFloat(int index, Qt::SortOrder sortOrder){ DLListModel->removeRows(0, nbRows_old); } -void GUI::sortDownloadListString(int index, Qt::SortOrder sortOrder){ +void GUI::sortDownloadListString(int index, Qt::SortOrder sortOrder) { QList > lines; // Insertion sorting unsigned int nbRows = DLListModel->rowCount(); - for(unsigned int i=0; i(i, DLListModel->data(DLListModel->index(i, index)).toString()), sortOrder); } // Insert items in new model, in correct order unsigned int nbRows_old = lines.size(); - for(unsigned int row=0; rowinsertRow(DLListModel->rowCount()); unsigned int sourceRow = lines[row].first; unsigned int nbColumns = DLListModel->columnCount(); - for(unsigned int col=0; colsetData(DLListModel->index(nbRows_old+row, col), DLListModel->data(DLListModel->index(sourceRow, col))); DLListModel->setData(DLListModel->index(nbRows_old+row, col), DLListModel->data(DLListModel->index(sourceRow, col), Qt::DecorationRole), Qt::DecorationRole); DLListModel->setData(DLListModel->index(nbRows_old+row, col), DLListModel->data(DLListModel->index(sourceRow, col), Qt::ForegroundRole), Qt::ForegroundRole); @@ -707,11 +707,11 @@ void GUI::sortDownloadListString(int index, Qt::SortOrder sortOrder){ DLListModel->removeRows(0, nbRows_old); } -void GUI::sortDownloadList(int index, Qt::SortOrder startSortOrder, bool fromLoadColWidth){ +void GUI::sortDownloadList(int index, Qt::SortOrder startSortOrder, bool fromLoadColWidth) { qDebug("Called sort download list"); static Qt::SortOrder sortOrder = startSortOrder; - if(!fromLoadColWidth && downloadList->header()->sortIndicatorSection() == index){ - if(sortOrder == Qt::AscendingOrder){ + if(!fromLoadColWidth && downloadList->header()->sortIndicatorSection() == index) { + if(sortOrder == Qt::AscendingOrder) { sortOrder = Qt::DescendingOrder; }else{ sortOrder = Qt::AscendingOrder; @@ -719,9 +719,9 @@ void GUI::sortDownloadList(int index, Qt::SortOrder startSortOrder, bool fromLoa } QString sortOrderLetter; if(sortOrder == Qt::AscendingOrder) - sortOrderLetter = "a"; + sortOrderLetter = QString::fromUtf8("a"); else - sortOrderLetter = "d"; + sortOrderLetter = QString::fromUtf8("d"); if(fromLoadColWidth) { // XXX: Why is this needed? if(sortOrder == Qt::DescendingOrder) @@ -731,7 +731,7 @@ void GUI::sortDownloadList(int index, Qt::SortOrder startSortOrder, bool fromLoa } else { downloadList->header()->setSortIndicator(index, sortOrder); } - switch(index){ + switch(index) { case SIZE: case ETA: case UPSPEED: @@ -739,7 +739,7 @@ void GUI::sortDownloadList(int index, Qt::SortOrder startSortOrder, bool fromLoa sortDownloadListFloat(index, sortOrder); break; case PROGRESS: - if(fromLoadColWidth){ + if(fromLoadColWidth) { // Progress sorting must be delayed until files are checked (on startup) delayedSorting = true; qDebug("Delayed sorting of the progress column"); @@ -751,17 +751,17 @@ void GUI::sortDownloadList(int index, Qt::SortOrder startSortOrder, bool fromLoa default: sortDownloadListString(index, sortOrder); } - QSettings settings("qBittorrent", "qBittorrent"); - settings.setValue("DownloadListSortedCol", QString(misc::toString(index).c_str())+sortOrderLetter); + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + settings.setValue(QString::fromUtf8("DownloadListSortedCol"), misc::toQString(index)+sortOrderLetter); } // Toggle Main window visibility -void GUI::toggleVisibility(QSystemTrayIcon::ActivationReason e){ - if(e == QSystemTrayIcon::Trigger || e == QSystemTrayIcon::DoubleClick){ - if(isHidden()){ +void GUI::toggleVisibility(QSystemTrayIcon::ActivationReason e) { + if(e == QSystemTrayIcon::Trigger || e == QSystemTrayIcon::DoubleClick) { + if(isHidden()) { show(); - if(isMinimized()){ - if(isMaximized()){ + if(isMinimized()) { + if(isMaximized()) { showMaximized(); }else{ showNormal(); @@ -795,38 +795,38 @@ QPoint GUI::screenCenter() const{ // (download list) void GUI::saveColWidthDLList() const{ qDebug("Saving columns width in download list"); - QSettings settings("qBittorrent", "qBittorrent"); + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QStringList width_list; unsigned int nbColumns = DLListModel->columnCount()-1; - for(unsigned int i=0; icolumnWidth(i)).c_str()); + for(unsigned int i=0; icolumnWidth(i)); } - settings.setValue("DownloadListColsWidth", width_list.join(" ")); + settings.setValue(QString::fromUtf8("DownloadListColsWidth"), width_list.join(QString::fromUtf8(" "))); qDebug("Download list columns width saved"); } // Load columns width in a file that were saved previously // (download list) -bool GUI::loadColWidthDLList(){ +bool GUI::loadColWidthDLList() { qDebug("Loading columns width for download list"); - QSettings settings("qBittorrent", "qBittorrent"); - QString line = settings.value("DownloadListColsWidth", QString()).toString(); + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + QString line = settings.value(QString::fromUtf8("DownloadListColsWidth"), QString()).toString(); if(line.isEmpty()) return false; - QStringList width_list = line.split(' '); - if(width_list.size() != DLListModel->columnCount()-1){ + QStringList width_list = line.split(QString::fromUtf8(" ")); + if(width_list.size() != DLListModel->columnCount()-1) { qDebug("Corrupted values for download list columns sizes"); return false; } unsigned int listSize = width_list.size(); - for(unsigned int i=0; iheader()->resizeSection(i, width_list.at(i).toInt()); } // Loading last sorted column - QString sortedCol = settings.value("DownloadListSortedCol", QString()).toString(); - if(!sortedCol.isEmpty()){ + QString sortedCol = settings.value(QString::fromUtf8("DownloadListSortedCol"), QString()).toString(); + if(!sortedCol.isEmpty()) { Qt::SortOrder sortOrder; - if(sortedCol.endsWith("d")) + if(sortedCol.endsWith(QString::fromUtf8("d"))) sortOrder = Qt::DescendingOrder; else sortOrder = Qt::AscendingOrder; @@ -839,36 +839,36 @@ bool GUI::loadColWidthDLList(){ } // Display About Dialog -void GUI::on_actionAbout_triggered(){ +void GUI::on_actionAbout_triggered() { //About dialog aboutdlg = new about(this); } // Called when we close the program -void GUI::closeEvent(QCloseEvent *e){ +void GUI::closeEvent(QCloseEvent *e) { qDebug("Mainwindow received closeEvent"); - QSettings settings("qBittorrent", "qBittorrent"); - bool goToSystrayOnExit = settings.value("Options/Misc/Behaviour/GoToSystrayOnExit", false).toBool(); - if(!force_exit && systrayIntegration && goToSystrayOnExit && !this->isHidden()){ + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + bool goToSystrayOnExit = settings.value(QString::fromUtf8("Options/Misc/Behaviour/GoToSystrayOnExit"), false).toBool(); + if(!force_exit && systrayIntegration && goToSystrayOnExit && !this->isHidden()) { hide(); e->ignore(); return; } - if(settings.value("Options/Misc/Behaviour/ConfirmOnExit", true).toBool() && nbTorrents != 0){ + if(settings.value(QString::fromUtf8("Options/Misc/Behaviour/ConfirmOnExit"), true).toBool() && nbTorrents != 0) { show(); if(!isMaximized()) showNormal(); if(QMessageBox::question(this, - tr("Are you sure you want to quit?")+" -- "+tr("qBittorrent"), + tr("Are you sure you want to quit?")+QString::fromUtf8(" -- ")+tr("qBittorrent"), tr("The download list is not empty.\nAre you sure you want to quit qBittorrent?"), tr("&Yes"), tr("&No"), - QString(), 0, 1)){ + QString(), 0, 1)) { e->ignore(); return; } } hide(); - if(systrayIntegration){ + if(systrayIntegration) { // Hide tray icon myTrayIcon->hide(); } @@ -881,14 +881,14 @@ void GUI::closeEvent(QCloseEvent *e){ } // Display window to create a torrent -void GUI::on_actionCreate_torrent_triggered(){ +void GUI::on_actionCreate_torrent_triggered() { createWindow = new createtorrent(this); } // Called when we minimize the program -void GUI::hideEvent(QHideEvent *e){ - QSettings settings("qBittorrent", "qBittorrent"); - if(systrayIntegration && settings.value("Options/Misc/Behaviour/GoToSystray", true).toBool() && !e->spontaneous()){ +void GUI::hideEvent(QHideEvent *e) { + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + if(systrayIntegration && settings.value(QString::fromUtf8("Options/Misc/Behaviour/GoToSystray"), true).toBool() && !e->spontaneous()) { // Hide window hide(); } @@ -897,20 +897,20 @@ void GUI::hideEvent(QHideEvent *e){ } // Action executed when a file is dropped -void GUI::dropEvent(QDropEvent *event){ +void GUI::dropEvent(QDropEvent *event) { event->acceptProposedAction(); - QStringList files=event->mimeData()->text().split('\n'); + QStringList files=event->mimeData()->text().split(QString::fromUtf8("\n")); // Add file to download list QString file; - QSettings settings("qBittorrent", "qBittorrent"); - bool useTorrentAdditionDialog = settings.value("Options/Misc/TorrentAdditionDialog/Enabled", true).toBool(); - foreach(file, files){ - file = file.trimmed().replace("file://", ""); - if(file.startsWith("http://", Qt::CaseInsensitive) || file.startsWith("ftp://", Qt::CaseInsensitive) || file.startsWith("https://", Qt::CaseInsensitive)){ + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Options/Misc/TorrentAdditionDialog/Enabled"), true).toBool(); + foreach(file, files) { + file = file.trimmed().replace(QString::fromUtf8("file://"), QString::fromUtf8("")); + if(file.startsWith(QString::fromUtf8("http://"), Qt::CaseInsensitive) || file.startsWith(QString::fromUtf8("ftp://"), Qt::CaseInsensitive) || file.startsWith(QString::fromUtf8("https://"), Qt::CaseInsensitive)) { BTSession->downloadFromUrl(file); continue; } - if(useTorrentAdditionDialog){ + if(useTorrentAdditionDialog) { torrentAdditionDialog *dialog = new torrentAdditionDialog(this); connect(dialog, SIGNAL(torrentAddition(QString, bool, QString)), BTSession, SLOT(addTorrent(QString, bool, QString))); connect(dialog, SIGNAL(setInfoBarGUI(QString, QString)), this, SLOT(setInfoBar(QString, QString))); @@ -922,8 +922,8 @@ void GUI::dropEvent(QDropEvent *event){ } // Decode if we accept drag 'n drop or not -void GUI::dragEnterEvent(QDragEnterEvent *event){ - if (event->mimeData()->hasFormat("text/plain")){ +void GUI::dragEnterEvent(QDragEnterEvent *event) { + if (event->mimeData()->hasFormat(QString::fromUtf8("text/plain"))) { event->acceptProposedAction(); } } @@ -936,20 +936,20 @@ void GUI::dragEnterEvent(QDragEnterEvent *event){ // Display a dialog to allow user to add // torrents to download list -void GUI::on_actionOpen_triggered(){ +void GUI::on_actionOpen_triggered() { QStringList pathsList; - QSettings settings("qBittorrent", "qBittorrent"); + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); // Open File Open Dialog // Note: it is possible to select more than one file pathsList = QFileDialog::getOpenFileNames(0, - tr("Open Torrent Files"), settings.value("MainWindowLastDir", QDir::homePath()).toString(), - tr("Torrent Files")+" (*.torrent)"); - if(!pathsList.empty()){ - QSettings settings("qBittorrent", "qBittorrent"); - bool useTorrentAdditionDialog = settings.value("Options/Misc/TorrentAdditionDialog/Enabled", true).toBool(); + tr("Open Torrent Files"), settings.value(QString::fromUtf8("MainWindowLastDir"), QDir::homePath()).toString(), + tr("Torrent Files")+QString::fromUtf8(" (*.torrent)")); + if(!pathsList.empty()) { + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Options/Misc/TorrentAdditionDialog/Enabled"), true).toBool(); unsigned int listSize = pathsList.size(); - for(unsigned int i=0; icurrentIndex() > 1) return; QModelIndexList selectedIndexes; bool inDownloadList; @@ -977,7 +977,7 @@ void GUI::on_actionDelete_Permanently_triggered(){ selectedIndexes = finishedTorrentTab->getFinishedList()->selectionModel()->selectedIndexes(); inDownloadList = false; } - if(!selectedIndexes.isEmpty()){ + if(!selectedIndexes.isEmpty()) { int ret; if(inDownloadList) { ret = QMessageBox::question( @@ -998,36 +998,36 @@ void GUI::on_actionDelete_Permanently_triggered(){ //User clicked YES QModelIndex index; QStringList hashesToDelete; - foreach(index, selectedIndexes){ - if(index.column() == NAME){ + foreach(index, selectedIndexes) { + if(index.column() == NAME) { if(inDownloadList) hashesToDelete << DLListModel->data(DLListModel->index(index.row(), HASH)).toString(); else hashesToDelete << finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(index.row(), F_HASH)).toString(); } } - QString fileHash; - foreach(fileHash, hashesToDelete){ + QString hash; + foreach(hash, hashesToDelete) { // Get the file name & hash QString fileName; int row = -1; - if(inDownloadList){ - row = getRowFromHash(fileHash); + if(inDownloadList) { + row = getRowFromHash(hash); fileName = DLListModel->data(DLListModel->index(row, NAME)).toString(); }else{ - row = finishedTorrentTab->getRowFromHash(fileHash); + row = finishedTorrentTab->getRowFromHash(hash); fileName = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME)).toString(); } Q_ASSERT(row != -1); // Remove the torrent - BTSession->deleteTorrent(fileHash, true); + BTSession->deleteTorrent(hash, true); // Delete item from download list if(inDownloadList) { DLListModel->removeRow(row); --nbTorrents; - tabs->setTabText(0, tr("Downloads") +" ("+QString(misc::toString(nbTorrents).c_str())+")"); + tabs->setTabText(0, tr("Downloads") +QString::fromUtf8(" (")+misc::toQString(nbTorrents)+QString::fromUtf8(")")); } else { - finishedTorrentTab->deleteFromFinishedList(fileHash); + finishedTorrentTab->deleteFromFinishedList(hash); } // Update info bar setInfoBar(tr("'%1' was removed permanently.", "'xxx.avi' was removed permanently.").arg(fileName)); @@ -1037,9 +1037,9 @@ void GUI::on_actionDelete_Permanently_triggered(){ } // delete selected items in the list -void GUI::on_actionDelete_triggered(){ +void GUI::on_actionDelete_triggered() { if(tabs->currentIndex() == 2) return; // No deletion in search tab - if(tabs->currentIndex() == 3){ + if(tabs->currentIndex() == 3) { rssWidget->on_delStream_button_clicked(); return; } @@ -1052,7 +1052,7 @@ void GUI::on_actionDelete_triggered(){ selectedIndexes = finishedTorrentTab->getFinishedList()->selectionModel()->selectedIndexes(); inDownloadList = false; } - if(!selectedIndexes.isEmpty()){ + if(!selectedIndexes.isEmpty()) { int ret; if(inDownloadList) { ret = QMessageBox::question( @@ -1073,36 +1073,36 @@ void GUI::on_actionDelete_triggered(){ //User clicked YES QModelIndex index; QStringList hashesToDelete; - foreach(index, selectedIndexes){ - if(index.column() == NAME){ + foreach(index, selectedIndexes) { + if(index.column() == NAME) { if(inDownloadList) hashesToDelete << DLListModel->data(DLListModel->index(index.row(), HASH)).toString(); else hashesToDelete << finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(index.row(), F_HASH)).toString(); } } - QString fileHash; - foreach(fileHash, hashesToDelete){ + QString hash; + foreach(hash, hashesToDelete) { // Get the file name & hash QString fileName; int row = -1; - if(inDownloadList){ - row = getRowFromHash(fileHash); + if(inDownloadList) { + row = getRowFromHash(hash); fileName = DLListModel->data(DLListModel->index(row, NAME)).toString(); }else{ - row = finishedTorrentTab->getRowFromHash(fileHash); + row = finishedTorrentTab->getRowFromHash(hash); fileName = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME)).toString(); } Q_ASSERT(row != -1); // Remove the torrent - BTSession->deleteTorrent(fileHash, false); + BTSession->deleteTorrent(hash, false); // Delete item from download list if(inDownloadList) { DLListModel->removeRow(row); --nbTorrents; - tabs->setTabText(0, tr("Downloads") +" ("+QString(misc::toString(nbTorrents).c_str())+")"); + tabs->setTabText(0, tr("Downloads") +QString::fromUtf8(" (")+misc::toQString(nbTorrents)+QString::fromUtf8(")")); } else { - finishedTorrentTab->deleteFromFinishedList(fileHash); + finishedTorrentTab->deleteFromFinishedList(hash); } // Update info bar setInfoBar(tr("'%1' was removed.", "'xxx.avi' was removed.").arg(fileName)); @@ -1112,8 +1112,8 @@ void GUI::on_actionDelete_triggered(){ } // Called when a torrent is added -void GUI::torrentAdded(QString path, torrent_handle& h, bool fastResume){ - QString hash = QString(misc::toString(h.info_hash()).c_str()); +void GUI::torrentAdded(QString path, QTorrentHandle& h, bool fastResume) { + QString hash = h.hash(); if(BTSession->isFinished(hash)) { finishedTorrentTab->addFinishedTorrent(hash); return; @@ -1121,56 +1121,56 @@ void GUI::torrentAdded(QString path, torrent_handle& h, bool fastResume){ int row = DLListModel->rowCount(); // Adding torrent to download list DLListModel->insertRow(row); - DLListModel->setData(DLListModel->index(row, NAME), QVariant(h.name().c_str())); - DLListModel->setData(DLListModel->index(row, SIZE), QVariant((qlonglong)BTSession->torrentEffectiveSize(hash))); + DLListModel->setData(DLListModel->index(row, NAME), QVariant(h.name())); + DLListModel->setData(DLListModel->index(row, SIZE), QVariant((qlonglong)h.actual_size())); DLListModel->setData(DLListModel->index(row, DLSPEED), QVariant((double)0.)); DLListModel->setData(DLListModel->index(row, UPSPEED), QVariant((double)0.)); - DLListModel->setData(DLListModel->index(row, SEEDSLEECH), QVariant("0/0")); - DLListModel->setData(DLListModel->index(row, RATIO), QVariant(QString(misc::toString(BTSession->getRealRatio(hash)).c_str()))); + DLListModel->setData(DLListModel->index(row, SEEDSLEECH), QVariant(QString::fromUtf8("0/0"))); + DLListModel->setData(DLListModel->index(row, RATIO), QVariant(misc::toQString(BTSession->getRealRatio(hash)))); DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)-1)); DLListModel->setData(DLListModel->index(row, HASH), QVariant(hash)); // Pause torrent if it was paused last time // Not using isPaused function because torrents are paused after checking now - if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".paused")) { - DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(":/Icons/skin/paused.png")), Qt::DecorationRole); - setRowColor(row, "red"); + if(QFile::exists(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".paused"))) { + DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/paused.png"))), Qt::DecorationRole); + setRowColor(row, QString::fromUtf8("red")); }else{ - DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(":/Icons/skin/connecting.png")), Qt::DecorationRole); - setRowColor(row, "grey"); + DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/connecting.png"))), Qt::DecorationRole); + setRowColor(row, QString::fromUtf8("grey")); } - if(!fastResume){ + if(!fastResume) { setInfoBar(tr("'%1' added to download list.", "'/home/y/xxx.torrent' was added to download list.").arg(path)); }else{ setInfoBar(tr("'%1' resumed. (fast resume)", "'/home/y/xxx.torrent' was resumed. (fast resume)").arg(path)); } ++nbTorrents; - tabs->setTabText(0, tr("Downloads") +" ("+QString(misc::toString(nbTorrents).c_str())+")"); + tabs->setTabText(0, tr("Downloads") +QString::fromUtf8(" (")+misc::toQString(nbTorrents)+QString::fromUtf8(")")); } // Called when trying to add a duplicate torrent -void GUI::torrentDuplicate(QString path){ +void GUI::torrentDuplicate(QString path) { setInfoBar(tr("'%1' is already in download list.", "e.g: 'xxx.avi' is already in download list.").arg(path)); } -void GUI::torrentCorrupted(QString path){ - setInfoBar(tr("Unable to decode torrent file: '%1'", "e.g: Unable to decode torrent file: '/home/y/xxx.torrent'").arg(path), "red"); - setInfoBar(tr("This file is either corrupted or this isn't a torrent."),"red"); +void GUI::torrentCorrupted(QString path) { + setInfoBar(tr("Unable to decode torrent file: '%1'", "e.g: Unable to decode torrent file: '/home/y/xxx.torrent'").arg(path), QString::fromUtf8("red")); + setInfoBar(tr("This file is either corrupted or this isn't a torrent."),QString::fromUtf8("red")); } // As program parameters, we can get paths or urls. // This function parse the parameters and call // the right addTorrent function, considering // the parameter type. -void GUI::processParams(const QStringList& params){ +void GUI::processParams(const QStringList& params) { QString param; - QSettings settings("qBittorrent", "qBittorrent"); - bool useTorrentAdditionDialog = settings.value("Options/Misc/TorrentAdditionDialog/Enabled", true).toBool(); - foreach(param, params){ + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Options/Misc/TorrentAdditionDialog/Enabled"), true).toBool(); + foreach(param, params) { param = param.trimmed(); - if(param.startsWith("http://", Qt::CaseInsensitive) || param.startsWith("ftp://", Qt::CaseInsensitive) || param.startsWith("https://", Qt::CaseInsensitive)){ + if(param.startsWith(QString::fromUtf8("http://"), Qt::CaseInsensitive) || param.startsWith(QString::fromUtf8("ftp://"), Qt::CaseInsensitive) || param.startsWith(QString::fromUtf8("https://"), Qt::CaseInsensitive)) { BTSession->downloadFromUrl(param); }else{ - if(useTorrentAdditionDialog){ + if(useTorrentAdditionDialog) { torrentAdditionDialog *dialog = new torrentAdditionDialog(this); connect(dialog, SIGNAL(torrentAddition(QString, bool, QString)), BTSession, SLOT(addTorrent(QString, bool, QString))); connect(dialog, SIGNAL(setInfoBarGUI(QString, QString)), this, SLOT(setInfoBar(QString, QString))); @@ -1182,12 +1182,12 @@ void GUI::processParams(const QStringList& params){ } } -void GUI::processScannedFiles(const QStringList& params){ +void GUI::processScannedFiles(const QStringList& params) { QString param; - QSettings settings("qBittorrent", "qBittorrent"); - bool useTorrentAdditionDialog = settings.value("Options/Misc/TorrentAdditionDialog/Enabled", true).toBool(); - foreach(param, params){ - if(useTorrentAdditionDialog){ + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Options/Misc/TorrentAdditionDialog/Enabled"), true).toBool(); + foreach(param, params) { + if(useTorrentAdditionDialog) { torrentAdditionDialog *dialog = new torrentAdditionDialog(this); connect(dialog, SIGNAL(torrentAddition(QString, bool, QString)), BTSession, SLOT(addTorrent(QString, bool, QString))); connect(dialog, SIGNAL(setInfoBarGUI(QString, QString)), this, SLOT(setInfoBar(QString, QString))); @@ -1198,10 +1198,10 @@ void GUI::processScannedFiles(const QStringList& params){ } } -void GUI::processDownloadedFiles(QString path, QString url){ - QSettings settings("qBittorrent", "qBittorrent"); - bool useTorrentAdditionDialog = settings.value("Options/Misc/TorrentAdditionDialog/Enabled", true).toBool(); - if(useTorrentAdditionDialog){ +void GUI::processDownloadedFiles(QString path, QString url) { + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Options/Misc/TorrentAdditionDialog/Enabled"), true).toBool(); + if(useTorrentAdditionDialog) { torrentAdditionDialog *dialog = new torrentAdditionDialog(this); connect(dialog, SIGNAL(torrentAddition(QString, bool, QString)), BTSession, SLOT(addTorrent(QString, bool, QString))); connect(dialog, SIGNAL(setInfoBarGUI(QString, QString)), this, SLOT(setInfoBar(QString, QString))); @@ -1212,27 +1212,26 @@ void GUI::processDownloadedFiles(QString path, QString url){ } // Show torrent properties dialog -void GUI::showProperties(const QModelIndex &index){ +void GUI::showProperties(const QModelIndex &index) { int row = index.row(); - QString fileHash = DLListModel->data(DLListModel->index(row, HASH)).toString(); - torrent_handle h = BTSession->getTorrentHandle(fileHash); + QString hash = DLListModel->data(DLListModel->index(row, HASH)).toString(); + QTorrentHandle h = BTSession->getTorrentHandle(hash); properties *prop = new properties(this, BTSession, h); connect(prop, SIGNAL(filteredFilesChanged(QString)), this, SLOT(updateFileSizeAndProgress(QString))); prop->show(); } -void GUI::updateFileSizeAndProgress(QString hash){ +void GUI::updateFileSizeAndProgress(QString hash) { int row = getRowFromHash(hash); Q_ASSERT(row != -1); - DLListModel->setData(DLListModel->index(row, SIZE), QVariant((qlonglong)BTSession->torrentEffectiveSize(hash))); - torrent_handle h = BTSession->getTorrentHandle(hash); - torrent_status torrentStatus = h.status(); - Q_ASSERT(torrentStatus.progress <= 1.); - DLListModel->setData(DLListModel->index(row, PROGRESS), QVariant((double)torrentStatus.progress)); + QTorrentHandle h = BTSession->getTorrentHandle(hash); + DLListModel->setData(DLListModel->index(row, SIZE), QVariant((qlonglong)h.actual_size())); + Q_ASSERT(h.progress() <= 1.); + DLListModel->setData(DLListModel->index(row, PROGRESS), QVariant((double)h.progress())); } // Set BT session configuration -void GUI::configureSession(bool deleteOptions){ +void GUI::configureSession(bool deleteOptions) { qDebug("Configuring session"); QPair limits; unsigned short old_listenPort, new_listenPort; @@ -1244,13 +1243,13 @@ void GUI::configureSession(bool deleteOptions){ old_listenPort = BTSession->getListenPort(); BTSession->setListeningPortsRange(options->getPorts()); new_listenPort = BTSession->getListenPort(); - if(new_listenPort != old_listenPort){ + if(new_listenPort != old_listenPort) { setInfoBar(tr("qBittorrent is bind to port: %1", "e.g: qBittorrent is bind to port: 1666").arg( QString(misc::toString(new_listenPort).c_str()))); } // Apply max connec limit (-1 if disabled) BTSession->setMaxConnections(options->getMaxConnec()); limits = options->getLimits(); - switch(limits.first){ + switch(limits.first) { case -1: // Download limit disabled case 0: BTSession->setDownloadRateLimit(-1); @@ -1258,7 +1257,7 @@ void GUI::configureSession(bool deleteOptions){ default: BTSession->setDownloadRateLimit(limits.first*1024); } - switch(limits.second){ + switch(limits.second) { case -1: // Upload limit disabled case 0: BTSession->setUploadRateLimit(-1); @@ -1269,50 +1268,50 @@ void GUI::configureSession(bool deleteOptions){ // Apply ratio (0 if disabled) BTSession->setGlobalRatio(options->getRatio()); // DHT (Trackerless) - if(options->isDHTEnabled()){ - setInfoBar(tr("DHT support [ON], port: %1").arg(options->getDHTPort()), "blue"); + if(options->isDHTEnabled()) { + setInfoBar(tr("DHT support [ON], port: %1").arg(options->getDHTPort()), QString::fromUtf8("blue")); BTSession->enableDHT(); // Set DHT Port BTSession->setDHTPort(options->getDHTPort()); }else{ - setInfoBar(tr("DHT support [OFF]"), "blue"); + setInfoBar(tr("DHT support [OFF]"), QString::fromUtf8("blue")); BTSession->disableDHT(); } // UPnP can't be disabled - setInfoBar(tr("UPnP support [ON]"), "blue"); + setInfoBar(tr("UPnP support [ON]"), QString::fromUtf8("blue")); // Encryption settings int encryptionState = options->getEncryptionSetting(); // The most secure, rc4 only so that all streams and encrypted encryptionSettings.allowed_enc_level = pe_settings::rc4; encryptionSettings.prefer_rc4 = true; - switch(encryptionState){ + switch(encryptionState) { case 0: //Enabled encryptionSettings.out_enc_policy = pe_settings::enabled; encryptionSettings.in_enc_policy = pe_settings::enabled; - setInfoBar(tr("Encryption support [ON]"), "blue"); + setInfoBar(tr("Encryption support [ON]"), QString::fromUtf8("blue")); break; case 1: // Forced encryptionSettings.out_enc_policy = pe_settings::forced; encryptionSettings.in_enc_policy = pe_settings::forced; - setInfoBar(tr("Encryption support [FORCED]"), "blue"); + setInfoBar(tr("Encryption support [FORCED]"), QString::fromUtf8("blue")); break; default: // Disabled encryptionSettings.out_enc_policy = pe_settings::disabled; encryptionSettings.in_enc_policy = pe_settings::disabled; - setInfoBar(tr("Encryption support [OFF]"), "blue"); + setInfoBar(tr("Encryption support [OFF]"), QString::fromUtf8("blue")); } BTSession->applyEncryptionSettings(encryptionSettings); // PeX - if(!options->isPeXDisabled()){ + if(!options->isPeXDisabled()) { qDebug("Enabling Peer eXchange (PeX)"); - setInfoBar(tr("PeX support [ON]"), "blue"); + setInfoBar(tr("PeX support [ON]"), QString::fromUtf8("blue")); BTSession->enablePeerExchange(); }else{ - setInfoBar(tr("PeX support [OFF]"), "blue"); + setInfoBar(tr("PeX support [OFF]"), QString::fromUtf8("blue")); qDebug("Peer eXchange (PeX) disabled"); } // Apply filtering settings - if(options->isFilteringEnabled()){ + if(options->isFilteringEnabled()) { BTSession->enableIPFilter(options->getFilter()); tabBottom->setTabEnabled(1, true); }else{ @@ -1321,8 +1320,8 @@ void GUI::configureSession(bool deleteOptions){ tabBottom->setTabEnabled(1, false); } // Apply Proxy settings - if(options->isProxyEnabled()){ - switch(options->getProxyType()){ + if(options->isProxyEnabled()) { + switch(options->getProxyType()) { case HTTP_PW: proxySettings.type = proxy_settings::http_pw; break; @@ -1337,7 +1336,7 @@ void GUI::configureSession(bool deleteOptions){ } proxySettings.hostname = options->getProxyIp().toStdString(); proxySettings.port = options->getProxyPort(); - if(options->isProxyAuthEnabled()){ + if(options->isProxyAuthEnabled()) { proxySettings.username = options->getProxyUsername().toStdString(); proxySettings.password = options->getProxyPassword().toStdString(); } @@ -1346,61 +1345,61 @@ void GUI::configureSession(bool deleteOptions){ sessionSettings.user_agent = "qBittorrent "VERSION; BTSession->setSessionSettings(sessionSettings); // Scan dir stuff - if(options->getScanDir().isNull()){ + if(options->getScanDir().isNull()) { BTSession->disableDirectoryScanning(); }else{ BTSession->enableDirectoryScanning(options->getScanDir()); } - if(deleteOptions){ + if(deleteOptions) { delete options; } qDebug("Session configured"); } // Toggle paused state of selected torrent -void GUI::togglePausedState(const QModelIndex& index){ +void GUI::togglePausedState(const QModelIndex& index) { int row = index.row(); bool inDownloadList = true; if(tabs->currentIndex() > 1) return; if(tabs->currentIndex() == 1) inDownloadList = false; - QString fileHash; + QString hash; if(inDownloadList) - fileHash = DLListModel->data(DLListModel->index(row, HASH)).toString(); + hash = DLListModel->data(DLListModel->index(row, HASH)).toString(); else - fileHash = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(row, F_HASH)).toString(); - if(BTSession->isPaused(fileHash)){ - BTSession->resumeTorrent(fileHash); - setInfoBar(tr("'%1' resumed.", "e.g: xxx.avi resumed.").arg(QString(BTSession->getTorrentHandle(fileHash).name().c_str()))); - if(inDownloadList){ - DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(":/Icons/skin/connecting.png")), Qt::DecorationRole); - setRowColor(row, "grey"); + hash = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(row, F_HASH)).toString(); + if(BTSession->isPaused(hash)) { + BTSession->resumeTorrent(hash); + setInfoBar(tr("'%1' resumed.", "e.g: xxx.avi resumed.").arg(BTSession->getTorrentHandle(hash).name())); + if(inDownloadList) { + DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/connecting.png"))), Qt::DecorationRole); + setRowColor(row, QString::fromUtf8("grey")); }else{ - finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME), QVariant(QIcon(":/Icons/skin/seeding.png")), Qt::DecorationRole); - finishedTorrentTab->setRowColor(row, "orange"); + finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/seeding.png"))), Qt::DecorationRole); + finishedTorrentTab->setRowColor(row, QString::fromUtf8("orange")); } }else{ - BTSession->pauseTorrent(fileHash); - if(inDownloadList){ + BTSession->pauseTorrent(hash); + if(inDownloadList) { DLListModel->setData(DLListModel->index(row, DLSPEED), QVariant((double)0.0)); DLListModel->setData(DLListModel->index(row, UPSPEED), QVariant((double)0.0)); DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)-1)); - DLListModel->setData(DLListModel->index(row, NAME), QIcon(":/Icons/skin/paused.png"), Qt::DecorationRole); - DLListModel->setData(DLListModel->index(row, SEEDSLEECH), QVariant("0/0")); - setRowColor(row, "red"); + DLListModel->setData(DLListModel->index(row, NAME), QIcon(QString::fromUtf8(":/Icons/skin/paused.png")), Qt::DecorationRole); + DLListModel->setData(DLListModel->index(row, SEEDSLEECH), QVariant(QString::fromUtf8("0/0"))); + setRowColor(row, QString::fromUtf8("red")); }else{ finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_UPSPEED), QVariant((double)0.0)); - finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME), QIcon(":/Icons/skin/paused.png"), Qt::DecorationRole); - finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_SEEDSLEECH), QVariant("0/0")); - setRowColor(row, "red"); + finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME), QIcon(QString::fromUtf8(":/Icons/skin/paused.png")), Qt::DecorationRole); + finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_SEEDSLEECH), QVariant(QString::fromUtf8("0/0"))); + setRowColor(row, QString::fromUtf8("red")); } - setInfoBar(tr("'%1' paused.", "xxx.avi paused.").arg(QString(BTSession->getTorrentHandle(fileHash).name().c_str()))); + setInfoBar(tr("'%1' paused.", "xxx.avi paused.").arg(BTSession->getTorrentHandle(hash).name())); } } // Pause All Downloads in DL list -void GUI::on_actionPause_All_triggered(){ - QString fileHash; +void GUI::on_actionPause_All_triggered() { + QString hash; bool change = false; bool inDownloadList = true; if(tabs->currentIndex() > 1) return; @@ -1411,26 +1410,26 @@ void GUI::on_actionPause_All_triggered(){ nbRows = DLListModel->rowCount(); else nbRows = finishedTorrentTab->getFinishedListModel()->rowCount(); - for(unsigned int i=0; idata(DLListModel->index(i, HASH)).toString(); + hash = DLListModel->data(DLListModel->index(i, HASH)).toString(); else - fileHash = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(i, F_HASH)).toString(); - if(BTSession->pauseTorrent(fileHash)){ - if(inDownloadList){ + hash = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(i, F_HASH)).toString(); + if(BTSession->pauseTorrent(hash)) { + if(inDownloadList) { // Update DL list items DLListModel->setData(DLListModel->index(i, DLSPEED), QVariant((double)0.)); DLListModel->setData(DLListModel->index(i, UPSPEED), QVariant((double)0.)); DLListModel->setData(DLListModel->index(i, ETA), QVariant((qlonglong)-1)); - DLListModel->setData(DLListModel->index(i, NAME), QVariant(QIcon(":/Icons/skin/paused.png")), Qt::DecorationRole); - DLListModel->setData(DLListModel->index(i, SEEDSLEECH), QVariant("0/0")); - setRowColor(i, "red"); + DLListModel->setData(DLListModel->index(i, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/paused.png"))), Qt::DecorationRole); + DLListModel->setData(DLListModel->index(i, SEEDSLEECH), QVariant(QString::fromUtf8("0/0"))); + setRowColor(i, QString::fromUtf8("red")); }else{ // Update finished list items finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(i, F_UPSPEED), QVariant((double)0.)); - finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(i, F_NAME), QVariant(QIcon(":/Icons/skin/paused.png")), Qt::DecorationRole); - finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(i, F_SEEDSLEECH), QVariant("0/0")); - finishedTorrentTab->setRowColor(i, "red"); + finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(i, F_NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/paused.png"))), Qt::DecorationRole); + finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(i, F_SEEDSLEECH), QVariant(QString::fromUtf8("0/0"))); + finishedTorrentTab->setRowColor(i, QString::fromUtf8("red")); } change = true; } @@ -1440,7 +1439,7 @@ void GUI::on_actionPause_All_triggered(){ } // pause selected items in the list -void GUI::on_actionPause_triggered(){ +void GUI::on_actionPause_triggered() { QModelIndexList selectedIndexes; bool inDownloadList = true; if(tabs->currentIndex() > 1) return; @@ -1451,39 +1450,39 @@ void GUI::on_actionPause_triggered(){ else selectedIndexes = finishedTorrentTab->getFinishedList()->selectionModel()->selectedIndexes(); QModelIndex index; - foreach(index, selectedIndexes){ - if(index.column() == NAME){ + foreach(index, selectedIndexes) { + if(index.column() == NAME) { // Get the file name - QString fileHash; + QString hash; if(inDownloadList) - fileHash = DLListModel->data(DLListModel->index(index.row(), HASH)).toString(); + hash = DLListModel->data(DLListModel->index(index.row(), HASH)).toString(); else - fileHash = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(index.row(), F_HASH)).toString(); - if(BTSession->pauseTorrent(fileHash)){ + hash = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(index.row(), F_HASH)).toString(); + if(BTSession->pauseTorrent(hash)) { // Update DL status int row = index.row(); - if(inDownloadList){ + if(inDownloadList) { DLListModel->setData(DLListModel->index(row, DLSPEED), QVariant((double)0.0)); DLListModel->setData(DLListModel->index(row, UPSPEED), QVariant((double)0.0)); DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)-1)); - DLListModel->setData(DLListModel->index(row, NAME), QIcon(":/Icons/skin/paused.png"), Qt::DecorationRole); - DLListModel->setData(DLListModel->index(row, SEEDSLEECH), QVariant("0/0")); - setRowColor(row, "red"); + DLListModel->setData(DLListModel->index(row, NAME), QIcon(QString::fromUtf8(":/Icons/skin/paused.png")), Qt::DecorationRole); + DLListModel->setData(DLListModel->index(row, SEEDSLEECH), QVariant(QString::fromUtf8("0/0"))); + setRowColor(row, QString::fromUtf8("red")); }else{ finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_UPSPEED), QVariant((double)0.0)); - finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME), QIcon(":/Icons/skin/paused.png"), Qt::DecorationRole); - finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_SEEDSLEECH), QVariant("0/0")); - finishedTorrentTab->setRowColor(row, "red"); + finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME), QIcon(QString::fromUtf8(":/Icons/skin/paused.png")), Qt::DecorationRole); + finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_SEEDSLEECH), QVariant(QString::fromUtf8("0/0"))); + finishedTorrentTab->setRowColor(row, QString::fromUtf8("red")); } - setInfoBar(tr("'%1' paused.", "xxx.avi paused.").arg(QString(BTSession->getTorrentHandle(fileHash).name().c_str()))); + setInfoBar(tr("'%1' paused.", "xxx.avi paused.").arg(BTSession->getTorrentHandle(hash).name())); } } } } // Resume All Downloads in DL list -void GUI::on_actionStart_All_triggered(){ - QString fileHash; +void GUI::on_actionStart_All_triggered() { + QString hash; bool change = false; bool inDownloadList = true; if(tabs->currentIndex() > 1) return; @@ -1494,19 +1493,19 @@ void GUI::on_actionStart_All_triggered(){ nbRows = DLListModel->rowCount(); else nbRows = finishedTorrentTab->getFinishedListModel()->rowCount(); - for(unsigned int i=0; idata(DLListModel->index(i, HASH)).toString(); + hash = DLListModel->data(DLListModel->index(i, HASH)).toString(); else - fileHash = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(i, F_HASH)).toString(); + hash = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(i, F_HASH)).toString(); // Remove .paused file - if(BTSession->resumeTorrent(fileHash)){ - if(inDownloadList){ - DLListModel->setData(DLListModel->index(i, NAME), QVariant(QIcon(":/Icons/skin/connecting.png")), Qt::DecorationRole); - setRowColor(i, "grey"); + if(BTSession->resumeTorrent(hash)) { + if(inDownloadList) { + DLListModel->setData(DLListModel->index(i, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/connecting.png"))), Qt::DecorationRole); + setRowColor(i, QString::fromUtf8("grey")); }else{ - finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(i, F_NAME), QVariant(QIcon(":/Icons/skin/seeding.png")), Qt::DecorationRole); - finishedTorrentTab->setRowColor(i, "orange"); + finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(i, F_NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/seeding.png"))), Qt::DecorationRole); + finishedTorrentTab->setRowColor(i, QString::fromUtf8("orange")); } change = true; } @@ -1516,7 +1515,7 @@ void GUI::on_actionStart_All_triggered(){ } // start selected items in the list -void GUI::on_actionStart_triggered(){ +void GUI::on_actionStart_triggered() { QModelIndexList selectedIndexes; bool inDownloadList = true; if(tabs->currentIndex() > 1) return; @@ -1527,74 +1526,74 @@ void GUI::on_actionStart_triggered(){ else selectedIndexes = finishedTorrentTab->getFinishedList()->selectionModel()->selectedIndexes(); QModelIndex index; - foreach(index, selectedIndexes){ - if(index.column() == NAME){ + foreach(index, selectedIndexes) { + if(index.column() == NAME) { // Get the file name - QString fileHash; + QString hash; if(inDownloadList) - fileHash = DLListModel->data(DLListModel->index(index.row(), HASH)).toString(); + hash = DLListModel->data(DLListModel->index(index.row(), HASH)).toString(); else - fileHash = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(index.row(), F_HASH)).toString(); - if(BTSession->resumeTorrent(fileHash)){ + hash = finishedTorrentTab->getFinishedListModel()->data(finishedTorrentTab->getFinishedListModel()->index(index.row(), F_HASH)).toString(); + if(BTSession->resumeTorrent(hash)) { // Update DL status int row = index.row(); - if(inDownloadList){ - DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(":/Icons/skin/connecting.png")), Qt::DecorationRole); - setRowColor(row, "grey"); + if(inDownloadList) { + DLListModel->setData(DLListModel->index(row, NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/connecting.png"))), Qt::DecorationRole); + setRowColor(row, QString::fromUtf8("grey")); }else{ - finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME), QVariant(QIcon(":/Icons/skin/seeding.png")), Qt::DecorationRole); - finishedTorrentTab->setRowColor(row, "orange"); + finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME), QVariant(QIcon(QString::fromUtf8(":/Icons/skin/seeding.png"))), Qt::DecorationRole); + finishedTorrentTab->setRowColor(row, QString::fromUtf8("orange")); } - setInfoBar(tr("'%1' resumed.", "e.g: xxx.avi resumed.").arg(QString(BTSession->getTorrentHandle(fileHash).name().c_str()))); + setInfoBar(tr("'%1' resumed.", "e.g: xxx.avi resumed.").arg(BTSession->getTorrentHandle(hash).name())); } } } } -void GUI::addUnauthenticatedTracker(QPair tracker){ +void GUI::addUnauthenticatedTracker(QPair tracker) { // Trackers whose authentication was cancelled - if(unauthenticated_trackers.indexOf(tracker) < 0){ + if(unauthenticated_trackers.indexOf(tracker) < 0) { unauthenticated_trackers << tracker; } } // display properties of selected items -void GUI::on_actionTorrent_Properties_triggered(){ +void GUI::on_actionTorrent_Properties_triggered() { if(tabs->currentIndex() > 1) return; - if(tabs->currentIndex() == 1){ + if(tabs->currentIndex() == 1) { finishedTorrentTab->propertiesSelection(); return; } QModelIndexList selectedIndexes = downloadList->selectionModel()->selectedIndexes(); QModelIndex index; - foreach(index, selectedIndexes){ - if(index.column() == NAME){ + foreach(index, selectedIndexes) { + if(index.column() == NAME) { showProperties(index); } } } // called when a torrent has finished -void GUI::finishedTorrent(torrent_handle& h){ - QSettings settings("qBittorrent", "qBittorrent"); +void GUI::finishedTorrent(QTorrentHandle& h) { + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); bool show_msg = true; - QString fileName = QString(h.name().c_str()); - int useOSD = settings.value("Options/OSDEnabled", 1).toInt(); + QString fileName = h.name(); + int useOSD = settings.value(QString::fromUtf8("Options/OSDEnabled"), 1).toInt(); // Add it to finished tab - QString hash = QString(misc::toString(h.info_hash()).c_str()); - if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".finished")){ + QString hash = h.hash(); + if(QFile::exists(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".finished"))) { show_msg = false; - qDebug("We received a finished signal for torrent %s, but it already has a .finished file", (const char*)hash.toUtf8()); + qDebug("We received a finished signal for torrent %s, but it already has a .finished file", hash.toUtf8().data()); } if(show_msg) setInfoBar(tr("%1 has finished downloading.", "e.g: xxx.avi has finished downloading.").arg(fileName)); int row = getRowFromHash(hash); - if(row != -1){ + if(row != -1) { DLListModel->removeRow(row); --nbTorrents; - tabs->setTabText(0, tr("Downloads") +" ("+QString(misc::toString(nbTorrents).c_str())+")"); + tabs->setTabText(0, tr("Downloads") +QString::fromUtf8(" (")+misc::toQString(nbTorrents)+QString::fromUtf8(")")); }else{ - qDebug("finished torrent %s is not in download list, nothing to do", (const char*)hash.toUtf8()); + qDebug("finished torrent %s is not in download list, nothing to do", hash.toUtf8().data()); } finishedTorrentTab->addFinishedTorrent(hash); if(show_msg && systrayIntegration && (useOSD == 1 || (useOSD == 2 && (isMinimized() || isHidden())))) { @@ -1603,28 +1602,27 @@ void GUI::finishedTorrent(torrent_handle& h){ } // Called when a torrent finished checking -void GUI::torrentChecked(QString hash){ +void GUI::torrentChecked(QString hash) { // Check if the torrent was paused after checking - if(BTSession->isPaused(hash)){ + if(BTSession->isPaused(hash)) { // Was paused, change its icon/color - if(BTSession->isFinished(hash)){ + if(BTSession->isFinished(hash)) { // In finished list qDebug("Automatically paused torrent was in finished list"); int row = finishedTorrentTab->getRowFromHash(hash); - if(row == -1){ + if(row == -1) { finishedTorrentTab->addFinishedTorrent(hash); row = finishedTorrentTab->getRowFromHash(hash); } Q_ASSERT(row != -1); finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_UPSPEED), QVariant((double)0.0)); - finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME), QIcon(":/Icons/skin/paused.png"), Qt::DecorationRole); - finishedTorrentTab->setRowColor(row, "red"); + finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME), QIcon(QString::fromUtf8(":/Icons/skin/paused.png")), Qt::DecorationRole); + finishedTorrentTab->setRowColor(row, QString::fromUtf8("red")); }else{ // In download list int row = getRowFromHash(hash); - torrent_handle h = BTSession->getTorrentHandle(hash); - torrent_status torrentStatus = h.status(); - if(row ==-1){ + QTorrentHandle h = BTSession->getTorrentHandle(hash); + if(row ==-1) { restoreInDownloadList(h); row = getRowFromHash(hash); } @@ -1632,11 +1630,11 @@ void GUI::torrentChecked(QString hash){ DLListModel->setData(DLListModel->index(row, DLSPEED), QVariant((double)0.0)); DLListModel->setData(DLListModel->index(row, UPSPEED), QVariant((double)0.0)); DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)-1)); - DLListModel->setData(DLListModel->index(row, NAME), QIcon(":/Icons/skin/paused.png"), Qt::DecorationRole); - setRowColor(row, "red"); + DLListModel->setData(DLListModel->index(row, NAME), QIcon(QString::fromUtf8(":/Icons/skin/paused.png")), Qt::DecorationRole); + setRowColor(row, QString::fromUtf8("red")); // Update progress in download list - Q_ASSERT(torrentStatus.progress <= 1. && torrentStatus.progress >= 0.); - DLListModel->setData(DLListModel->index(row, PROGRESS), QVariant((double)torrentStatus.progress)); + Q_ASSERT(h.progress() <= 1. && h.progress() >= 0.); + DLListModel->setData(DLListModel->index(row, PROGRESS), QVariant((double)h.progress())); // Delayed Sorting sortProgressColumnDelayed(); } @@ -1644,31 +1642,31 @@ void GUI::torrentChecked(QString hash){ } // Notification when disk is full -void GUI::fullDiskError(torrent_handle& h){ - QSettings settings("qBittorrent", "qBittorrent"); - int useOSD = settings.value("Options/OSDEnabled", 1).toInt(); - if(systrayIntegration && (useOSD == 1 || (useOSD == 2 && (isMinimized() || isHidden())))){ - myTrayIcon->showMessage(tr("I/O Error", "i.e: Input/Output Error"), tr("An error occured when trying to read or write %1. The disk is probably full, download has been paused", "e.g: An error occured when trying to read or write xxx.avi. The disk is probably full, download has been paused").arg(QString(h.name().c_str())), QSystemTrayIcon::Critical, TIME_TRAY_BALLOON); +void GUI::fullDiskError(QTorrentHandle& h) { + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + int useOSD = settings.value(QString::fromUtf8("Options/OSDEnabled"), 1).toInt(); + if(systrayIntegration && (useOSD == 1 || (useOSD == 2 && (isMinimized() || isHidden())))) { + myTrayIcon->showMessage(tr("I/O Error", "i.e: Input/Output Error"), tr("An error occured when trying to read or write %1. The disk is probably full, download has been paused", "e.g: An error occured when trying to read or write xxx.avi. The disk is probably full, download has been paused").arg(h.name()), QSystemTrayIcon::Critical, TIME_TRAY_BALLOON); } // Download will be paused by libtorrent. Updating GUI information accordingly - QString hash = QString(misc::toString(h.info_hash()).c_str()); - qDebug("Full disk error, pausing torrent %s", (const char*)hash.toUtf8()); - if(BTSession->isFinished(hash)){ + QString hash = h.hash(); + qDebug("Full disk error, pausing torrent %s", hash.toUtf8().data()); + if(BTSession->isFinished(hash)) { // In finished list qDebug("Automatically paused torrent was in finished list"); int row = finishedTorrentTab->getRowFromHash(hash); - if(row == -1){ + if(row == -1) { finishedTorrentTab->addFinishedTorrent(hash); row = finishedTorrentTab->getRowFromHash(hash); } Q_ASSERT(row != -1); finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_UPSPEED), QVariant((double)0.0)); - finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME), QIcon(":/Icons/skin/paused.png"), Qt::DecorationRole); - finishedTorrentTab->setRowColor(row, "red"); + finishedTorrentTab->getFinishedListModel()->setData(finishedTorrentTab->getFinishedListModel()->index(row, F_NAME), QIcon(QString::fromUtf8(":/Icons/skin/paused.png")), Qt::DecorationRole); + finishedTorrentTab->setRowColor(row, QString::fromUtf8("red")); }else{ // In download list int row = getRowFromHash(hash); - if(row == -1){ + if(row == -1) { restoreInDownloadList(BTSession->getTorrentHandle(hash)); row = getRowFromHash(hash); } @@ -1676,34 +1674,34 @@ void GUI::fullDiskError(torrent_handle& h){ DLListModel->setData(DLListModel->index(row, DLSPEED), QVariant((double)0.0)); DLListModel->setData(DLListModel->index(row, UPSPEED), QVariant((double)0.0)); DLListModel->setData(DLListModel->index(row, ETA), QVariant((qlonglong)-1)); - DLListModel->setData(DLListModel->index(row, NAME), QIcon(":/Icons/skin/paused.png"), Qt::DecorationRole); - setRowColor(row, "red"); + DLListModel->setData(DLListModel->index(row, NAME), QIcon(QString::fromUtf8(":/Icons/skin/paused.png")), Qt::DecorationRole); + setRowColor(row, QString::fromUtf8("red")); } - setInfoBar(tr("An error occured (full disk?), '%1' paused.", "e.g: An error occured (full disk?), 'xxx.avi' paused.").arg(QString(h.get_torrent_info().name().c_str()))); + setInfoBar(tr("An error occured (full disk?), '%1' paused.", "e.g: An error occured (full disk?), 'xxx.avi' paused.").arg(h.name())); } // Called when we couldn't listen on any port // in the given range. -void GUI::portListeningFailure(){ - setInfoBar(tr("Couldn't listen on any of the given ports."), "red"); +void GUI::portListeningFailure() { + setInfoBar(tr("Couldn't listen on any of the given ports."), QString::fromUtf8("red")); } // Called when a tracker requires authentication -void GUI::trackerAuthenticationRequired(torrent_handle& h){ - if(unauthenticated_trackers.indexOf(QPair(h, h.status().current_tracker)) < 0){ +void GUI::trackerAuthenticationRequired(QTorrentHandle& h) { + if(unauthenticated_trackers.indexOf(QPair(h, h.current_tracker())) < 0) { // Tracker login new trackerLogin(this, h); } } // Check connection status and display right icon -void GUI::checkConnectionStatus(){ +void GUI::checkConnectionStatus() { // qDebug("Checking connection status"); char tmp[MAX_CHAR_TMP]; session_status sessionStatus = BTSession->getSessionStatus(); // Update ratio info float ratio = 1.; - if(sessionStatus.total_payload_download == 0){ + if(sessionStatus.total_payload_download == 0) { if(sessionStatus.total_payload_upload == 0) ratio = 1.; else @@ -1715,28 +1713,28 @@ void GUI::checkConnectionStatus(){ } snprintf(tmp, MAX_CHAR_TMP, "%.1f", ratio); LCD_Ratio->display(tmp); - if(ratio < 0.5){ + if(ratio < 0.5) { lbl_ratio_icon->setPixmap(QPixmap(QString::fromUtf8(":/Icons/unhappy.png"))); }else{ - if(ratio > 1.0){ + if(ratio > 1.0) { lbl_ratio_icon->setPixmap(QPixmap(QString::fromUtf8(":/Icons/smile.png"))); }else{ lbl_ratio_icon->setPixmap(QPixmap(QString::fromUtf8(":/Icons/stare.png"))); } } - if(sessionStatus.has_incoming_connections){ + if(sessionStatus.has_incoming_connections) { // Connection OK connecStatusLblIcon->setPixmap(QPixmap(QString::fromUtf8(":/Icons/skin/connected.png"))); - connecStatusLblIcon->setToolTip(""+tr("Connection Status:")+"
"+tr("Online")); + connecStatusLblIcon->setToolTip(QString::fromUtf8("")+tr("Connection Status:")+QString::fromUtf8("
")+tr("Online")); }else{ - if(sessionStatus.num_peers){ + if(sessionStatus.num_peers) { // Firewalled ? connecStatusLblIcon->setPixmap(QPixmap(QString::fromUtf8(":/Icons/skin/firewalled.png"))); - connecStatusLblIcon->setToolTip(""+tr("Connection Status:")+"
"+tr("Firewalled?", "i.e: Behind a firewall/router?")+"
"+tr("No incoming connections...")+""); + connecStatusLblIcon->setToolTip(""+tr("Connection Status:")+QString::fromUtf8("
")+tr("Firewalled?", "i.e: Behind a firewall/router?")+QString::fromUtf8("
")+tr("No incoming connections...")+QString::fromUtf8("")); }else{ // Disconnected connecStatusLblIcon->setPixmap(QPixmap(QString::fromUtf8(":/Icons/skin/disconnected.png"))); - connecStatusLblIcon->setToolTip(""+tr("Connection status:")+"
"+tr("Offline")+"
"+tr("No peers found...")+""); + connecStatusLblIcon->setToolTip(QString::fromUtf8("")+tr("Connection status:")+QString::fromUtf8("
")+tr("Offline")+QString::fromUtf8("
")+tr("No peers found...")+QString::fromUtf8("")); } } } @@ -1748,31 +1746,31 @@ void GUI::checkConnectionStatus(){ *****************************************************/ // Set the color of a row in data model -void GUI::setRowColor(int row, QString color){ +void GUI::setRowColor(int row, QString color) { unsigned int nbColumns = DLListModel->columnCount(); - for(unsigned int i=0; isetData(DLListModel->index(row, i), QVariant(QColor(color)), Qt::ForegroundRole); } } // return the row of in data model -// corresponding to the given the filehash +// corresponding to the given the hash int GUI::getRowFromHash(QString hash) const{ unsigned int nbRows = DLListModel->rowCount(); - for(unsigned int i=0; idata(DLListModel->index(i, HASH)) == hash){ + for(unsigned int i=0; idata(DLListModel->index(i, HASH)) == hash) { return i; } } return -1; } -void GUI::downloadFromURLList(const QStringList& urls){ +void GUI::downloadFromURLList(const QStringList& urls) { BTSession->downloadFromURLList(urls); } -void GUI::displayDownloadingUrlInfos(QString url){ - setInfoBar(tr("Downloading '%1', please wait...", "e.g: Downloading 'xxx.torrent', please wait...").arg(url), "black"); +void GUI::displayDownloadingUrlInfos(QString url) { + setInfoBar(tr("Downloading '%1', please wait...", "e.g: Downloading 'xxx.torrent', please wait...").arg(url), QString::fromUtf8("black")); } /***************************************************** @@ -1781,9 +1779,9 @@ void GUI::displayDownloadingUrlInfos(QString url){ * * *****************************************************/ -void GUI::createTrayIcon(){ +void GUI::createTrayIcon() { // Tray icon - myTrayIcon = new QSystemTrayIcon(QIcon(":/Icons/qbittorrent22.png"), this); + myTrayIcon = new QSystemTrayIcon(QIcon(QString::fromUtf8(":/Icons/qbittorrent22.png")), this); // Tray icon Menu myTrayIconMenu = new QMenu(this); myTrayIconMenu->addAction(actionOpen); @@ -1804,20 +1802,20 @@ void GUI::createTrayIcon(){ } // Display Program Options -void GUI::on_actionOptions_triggered(){ +void GUI::on_actionOptions_triggered() { options = new options_imp(this); connect(options, SIGNAL(status_changed(QString, bool)), this, SLOT(OptionsSaved(QString, bool))); options->show(); } // Is executed each time options are saved -void GUI::OptionsSaved(QString info, bool deleteOptions){ +void GUI::OptionsSaved(QString info, bool deleteOptions) { bool newSystrayIntegration = options->useSystrayIntegration(); - if(newSystrayIntegration && !systrayIntegration){ + if(newSystrayIntegration && !systrayIntegration) { // create the trayicon createTrayIcon(); } - if(!newSystrayIntegration && systrayIntegration){ + if(!newSystrayIntegration && systrayIntegration) { // Destroy trayicon delete myTrayIcon; delete myTrayIconMenu; @@ -1837,7 +1835,7 @@ void GUI::OptionsSaved(QString info, bool deleteOptions){ // Display an input dialog to prompt user for // an url -void GUI::on_actionDownload_from_URL_triggered(){ +void GUI::on_actionDownload_from_URL_triggered() { downloadFromURLDialog = new downloadFromURL(this); connect(downloadFromURLDialog, SIGNAL(urlsReadyToBeDownloaded(const QStringList&)), BTSession, SLOT(downloadFromURLList(const QStringList&))); } diff --git a/src/GUI.h b/src/GUI.h index 6f0db7609..d8083d72e 100644 --- a/src/GUI.h +++ b/src/GUI.h @@ -24,9 +24,9 @@ #include #include -#include #include "ui_MainWindow.h" +#include "qtorrenthandle.h" class bittorrent; class createtorrent; @@ -46,9 +46,6 @@ class previewSelect; class options_imp; class QStandardItemModel; -using namespace libtorrent; -namespace fs = boost::filesystem; - class GUI : public QMainWindow, private Ui::MainWindow{ Q_OBJECT @@ -56,7 +53,7 @@ class GUI : public QMainWindow, private Ui::MainWindow{ // Bittorrent bittorrent *BTSession; QTimer *checkConnect; - QList > unauthenticated_trackers; + QList > unauthenticated_trackers; downloadFromURL *downloadFromURLDialog; // GUI related options_imp *options; @@ -135,7 +132,7 @@ class GUI : public QMainWindow, private Ui::MainWindow{ void on_actionTorrent_Properties_triggered(); void on_actionPause_triggered(); void on_actionPause_All_triggered(); - void restoreInDownloadList(torrent_handle h); + void restoreInDownloadList(QTorrentHandle h); void on_actionStart_triggered(); void on_actionStart_All_triggered(); void on_actionOpen_triggered(); @@ -149,7 +146,7 @@ class GUI : public QMainWindow, private Ui::MainWindow{ void checkConnectionStatus(); void configureSession(bool deleteOptions); void processParams(const QStringList& params); - void addUnauthenticatedTracker(QPair tracker); + void addUnauthenticatedTracker(QPair tracker); void processScannedFiles(const QStringList& params); void processDownloadedFiles(QString path, QString url); void downloadFromURLList(const QStringList& urls); @@ -165,13 +162,13 @@ class GUI : public QMainWindow, private Ui::MainWindow{ public slots: - void torrentAdded(QString path, torrent_handle& h, bool fastResume); + void torrentAdded(QString path, QTorrentHandle& h, bool fastResume); void torrentDuplicate(QString path); void torrentCorrupted(QString path); - void finishedTorrent(torrent_handle& h); - void fullDiskError(torrent_handle& h); + void finishedTorrent(QTorrentHandle& h); + void fullDiskError(QTorrentHandle& h); void portListeningFailure(); - void trackerAuthenticationRequired(torrent_handle& h); + void trackerAuthenticationRequired(QTorrentHandle& h); void setTabText(int index, QString text); void updateFileSizeAndProgress(QString hash); void sortProgressColumnDelayed(); diff --git a/src/PreviewListDelegate.h b/src/PreviewListDelegate.h index 224894f89..31129f25a 100644 --- a/src/PreviewListDelegate.h +++ b/src/PreviewListDelegate.h @@ -54,25 +54,18 @@ class PreviewListDelegate: public QItemDelegate { QItemDelegate::drawDisplay(painter, opt, option.rect, misc::friendlyUnit(index.data().toLongLong())); break; case PROGRESS:{ - QPalette::ColorGroup cg = option.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; float progress = index.data().toDouble()*100.; snprintf(tmp, MAX_CHAR_TMP, "%.1f", progress); QStyleOptionProgressBarV2 newopt; newopt.rect = opt.rect; - newopt.text = QString(tmp)+"%"; + newopt.text = QString::fromUtf8(tmp)+QString::fromUtf8("%"); newopt.progress = (int)progress; newopt.maximum = 100; newopt.minimum = 0; newopt.state |= QStyle::State_Enabled; - newopt.textVisible = false; + newopt.textVisible = true; QApplication::style()->drawControl(QStyle::CE_ProgressBar, &newopt, painter); - //We prefer to display text manually to control color/font/boldness - if (option.state & QStyle::State_Selected){ - opt.palette.setColor(QPalette::Text, QColor("grey")); - painter->setPen(opt.palette.color(cg, QPalette::Text)); - } - painter->drawText(option.rect, Qt::AlignCenter, newopt.text); break; } default: diff --git a/src/PropListDelegate.h b/src/PropListDelegate.h index ecdeb005c..af9b121df 100644 --- a/src/PropListDelegate.h +++ b/src/PropListDelegate.h @@ -71,7 +71,7 @@ class PropListDelegate: public QItemDelegate { float progress = index.data().toDouble()*100.; snprintf(tmp, MAX_CHAR_TMP, "%.1f", progress); newopt.rect = opt.rect; - newopt.text = QString(tmp)+"%"; + newopt.text = QString::fromUtf8(tmp)+QString::fromUtf8("%"); newopt.progress = (int)progress; newopt.maximum = 100; newopt.minimum = 0; @@ -106,7 +106,7 @@ class PropListDelegate: public QItemDelegate { painter); opt.palette.setColor(QPalette::Text, QColor("black")); painter->setPen(opt.palette.color(cg, QPalette::Text)); - painter->drawText(option.rect, Qt::AlignLeft, " "+newopt.currentText); + painter->drawText(option.rect, Qt::AlignLeft, QString::fromUtf8(" ")+newopt.currentText); break; } default: @@ -175,9 +175,9 @@ class PropListDelegate: public QItemDelegate { qDebug("Setting combobox value in index: %d", value); QString color; if(value) { - color = "green"; + color = QString::fromUtf8("green"); } else { - color = "red"; + color = QString::fromUtf8("red"); } unsigned short old_val = index.model()->data(index, Qt::DisplayRole).toInt(); switch(value){ diff --git a/src/about_imp.h b/src/about_imp.h index 3d7230ad9..e97185228 100644 --- a/src/about_imp.h +++ b/src/about_imp.h @@ -36,18 +36,18 @@ class about : public QDialog, private Ui::AboutDlg{ logo->setPixmap(QPixmap(QString::fromUtf8(":/Icons/qbittorrent22.png"))); mascot_lbl->setPixmap(QPixmap(QString::fromUtf8(":/Icons/mascot.png"))); //Title - lb_name->setText("

"+tr("qBittorrent")+" "VERSION"

"); + lb_name->setText(QString::fromUtf8("

")+tr("qBittorrent")+QString::fromUtf8(" "VERSION"

")); // Thanks - te_thanks->append(""); - te_thanks->append("
  • I would like to thank sourceforge.net for hosting qBittorrent project.
  • "); + te_thanks->append(QString::fromUtf8("")); + te_thanks->append(QString::fromUtf8("
    • I would like to thank sourceforge.net for hosting qBittorrent project.
    • ")); te_thanks->append(QString::fromUtf8("
    • I am happy that Arnaud Demaizière joined the project as a programmer. His help is greatly appreciated
    • ")); - te_thanks->append("
    • I also want to thank Jeffery Fernandez (jeffery@qbittorrent.org), project consultant, webdevelopper and RPM packager, for his help.
    • "); - te_thanks->append("
    • I am gratefull to Peter Koeleman (peter@qbittorrent.org) who is helping port qBittorrent to Windows.
    • "); + te_thanks->append(QString::fromUtf8("
    • I also want to thank Jeffery Fernandez (jeffery@qbittorrent.org), project consultant, webdevelopper and RPM packager, for his help.
    • ")); + te_thanks->append(QString::fromUtf8("
    • I am gratefull to Peter Koeleman (peter@qbittorrent.org) who is helping port qBittorrent to Windows.
    • ")); te_thanks->append(QString::fromUtf8("
    • Thanks a lot to our graphist Mateusz ToboÅ‚a (tobejodok@qbittorrent.org) for his great work.


    ")); - te_thanks->scrollToAnchor("top"); + te_thanks->scrollToAnchor(QString::fromUtf8("top")); // Translation - te_translation->append(""); - te_translation->append(tr("I would like to thank the following people who volunteered to translate qBittorrent:")+"
    "); + te_translation->append(QString::fromUtf8("")); + te_translation->append(tr("I would like to thank the following people who volunteered to translate qBittorrent:")+QString::fromUtf8("
    ")); te_translation->append(QString::fromUtf8( "- Brazilian: Nick Marinho (nickmarinho@gmail.com)
    \ - Bulgarian: Tsvetan & Boiko Bankov (emerge_life@users.sourceforge.net)
    \ @@ -74,10 +74,10 @@ class about : public QDialog, private Ui::AboutDlg{ - Turkish: Erdem Bingöl (erdem84@gmail.com)
    \ - Ukrainian: Andrey Shpachenko (masterfix@users.sourceforge.net)

    ")); te_translation->append(tr("Please contact me if you would like to translate qBittorrent into your own language.")); - te_translation->scrollToAnchor("top"); + te_translation->scrollToAnchor(QString::fromUtf8("top")); // License - te_license->append(""); - te_license->append("
    GNU GENERAL PUBLIC LICENSE

    \ + te_license->append(QString::fromUtf8("")); + te_license->append(QString::fromUtf8("
    GNU GENERAL PUBLIC LICENSE

    \
    Version 2, June 1991

    \ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
    \ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
    \ @@ -410,8 +410,8 @@ class about : public QDialog, private Ui::AboutDlg{ proprietary programs. If your program is a subroutine library, you may
    \ consider it more useful to permit linking proprietary applications with the
    \ library. If this is what you want to do, use the GNU Library General
    \ - Public License instead of this License.
    "); - te_license->scrollToAnchor("top"); + Public License instead of this License.
    ")); + te_license->scrollToAnchor(QString::fromUtf8("top")); show(); } }; diff --git a/src/allocationDlg.h b/src/allocationDlg.h index 3cfa65d30..fb94b9aa0 100644 --- a/src/allocationDlg.h +++ b/src/allocationDlg.h @@ -55,7 +55,7 @@ class BandwidthAllocationDialog : public QDialog, private Ui_bandwidth_dlg { int val = 0; int max = -1; if(nbTorrents == 1){ - torrent_handle h = BTSession->getTorrentHandle(hashes.at(0)); + QTorrentHandle h = BTSession->getTorrentHandle(hashes.at(0)); if(uploadMode){ if(h.upload_limit() > 0) val = (int)(h.upload_limit() / 1024.); @@ -79,15 +79,15 @@ class BandwidthAllocationDialog : public QDialog, private Ui_bandwidth_dlg { bandwidthSlider->setValue(val); if(val == 0) { limit_lbl->setText(tr("Unlimited", "Unlimited (bandwidth)")); - kb_lbl->setText(""); + kb_lbl->setText(QString::fromUtf8("")); } else { - limit_lbl->setText(QString(misc::toString(val).c_str())); + limit_lbl->setText(misc::toQString(val)); } }else{ qDebug("More than one torrent selected, no initilization"); bandwidthSlider->setValue(0); limit_lbl->setText(tr("Unlimited", "Unlimited (bandwidth)")); - kb_lbl->setText(""); + kb_lbl->setText(QString::fromUtf8("")); } }else{ // Global limit @@ -103,7 +103,7 @@ class BandwidthAllocationDialog : public QDialog, private Ui_bandwidth_dlg { if(val == 0){ bandwidthSlider->setValue(0); limit_lbl->setText(tr("Unlimited", "Unlimited (bandwidth)")); - kb_lbl->setText(""); + kb_lbl->setText(QString::fromUtf8("")); }else{ bandwidthSlider->setValue(val); } @@ -120,9 +120,9 @@ class BandwidthAllocationDialog : public QDialog, private Ui_bandwidth_dlg { void updateBandwidthLabel(int val){ if(val == 0){ limit_lbl->setText(tr("Unlimited", "Unlimited (bandwidth)")); - kb_lbl->setText(""); + kb_lbl->setText(QString::fromUtf8("")); }else{ - limit_lbl->setText(QString(misc::toString(val).c_str())); + limit_lbl->setText(misc::toQString(val)); kb_lbl->setText(tr("KiB/s")); } } @@ -150,20 +150,20 @@ class BandwidthAllocationDialog : public QDialog, private Ui_bandwidth_dlg { } } }else{ - QSettings settings("qBittorrent", "qBittorrent"); + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); session *s = BTSession->getSession(); if(uploadMode){ if(!val) s->set_upload_rate_limit(-1); else s->set_upload_rate_limit(val*1024); - settings.setValue("Options/Main/UPLimit", val); + settings.setValue(QString::fromUtf8("Options/Main/UPLimit"), val); }else{ if(!val) s->set_download_rate_limit(-1); else s->set_download_rate_limit(val*1024); - settings.setValue("Options/Main/DLLimit", val); + settings.setValue(QString::fromUtf8("Options/Main/DLLimit"), val); } } close(); diff --git a/src/bittorrent.cpp b/src/bittorrent.cpp index 8c8b4c4cc..630586eb7 100644 --- a/src/bittorrent.cpp +++ b/src/bittorrent.cpp @@ -42,7 +42,7 @@ #define ETAS_MAX_VALUES 8 // Main constructor -bittorrent::bittorrent(){ +bittorrent::bittorrent() { // To avoid some exceptions fs::path::default_name_check(fs::no_check); timerScan = 0; @@ -76,7 +76,7 @@ bittorrent::bittorrent(){ } // Main destructor -bittorrent::~bittorrent(){ +bittorrent::~bittorrent() { // Disable directory scanning disableDirectoryScanning(); // Delete our objects @@ -91,44 +91,42 @@ bittorrent::~bittorrent(){ delete s; } -void bittorrent::setDownloadLimit(QString hash, long val){ - torrent_handle h = getTorrentHandle(hash); +void bittorrent::setDownloadLimit(QString hash, long val) { + QTorrentHandle h = getTorrentHandle(hash); if(h.is_valid()) h.set_download_limit(val); saveTorrentSpeedLimits(hash); } -void bittorrent::setUploadLimit(QString hash, long val){ +void bittorrent::setUploadLimit(QString hash, long val) { qDebug("Set upload limit rate to %ld", val); - torrent_handle h = getTorrentHandle(hash); + QTorrentHandle h = getTorrentHandle(hash); if(h.is_valid()) h.set_upload_limit(val); saveTorrentSpeedLimits(hash); } -void bittorrent::HandleDownloadFailure(QString url, QString reason){ +void bittorrent::HandleDownloadFailure(QString url, QString reason) { emit downloadFromUrlFailure(url, reason); } -void bittorrent::updateETAs(){ +void bittorrent::updateETAs() { std::vector handles = s->get_torrents(); unsigned int nbHandles = handles.size(); - for(unsigned int i=0; i listEtas = ETAstats.value(hash, QList()); - if(listEtas.size() == ETAS_MAX_VALUES){ + if(listEtas.size() == ETAS_MAX_VALUES) { listEtas.removeFirst(); } - torrent_status torrentStatus = h.status(); - torrent_info ti = h.get_torrent_info(); - if(torrentStatus.download_payload_rate != 0){ - listEtas << (long)((ti.total_size()-torrentStatus.total_done)/(double)torrentStatus.download_payload_rate); + if(h.download_payload_rate() != 0) { + listEtas << (long)((h.total_size()-h.total_done())/(double)h.download_payload_rate()); ETAstats[hash] = listEtas; long moy = 0; long val; - foreach(val, listEtas){ + foreach(val, listEtas) { moy += val; } ETAs[hash] = (long) ((double)moy/(double)listEtas.size()); @@ -142,15 +140,15 @@ long bittorrent::getETA(QString hash) const{ } // Return the torrent handle, given its hash -torrent_handle bittorrent::getTorrentHandle(QString hash) const{ - return s->find_torrent(misc::fromString((hash.toStdString()))); +QTorrentHandle bittorrent::getTorrentHandle(QString hash) const{ + return QTorrentHandle(s->find_torrent(misc::fromString((hash.toStdString())))); } // Return true if the torrent corresponding to the // hash is paused bool bittorrent::isPaused(QString hash) const{ - torrent_handle h = s->find_torrent(misc::fromString((hash.toStdString()))); - if(!h.is_valid()){ + QTorrentHandle h = getTorrentHandle(hash); + if(!h.is_valid()) { qDebug("/!\\ Error: Invalid handle"); return true; } @@ -159,24 +157,24 @@ bool bittorrent::isPaused(QString hash) const{ // Delete a torrent from the session, given its hash // permanent = true means that the torrent will be removed from the hard-drive too -void bittorrent::deleteTorrent(QString hash, bool permanent){ - qDebug("Deleting torrent with hash: %s", (const char*)hash.toUtf8()); - torrent_handle h = s->find_torrent(misc::fromString((hash.toStdString()))); - if(!h.is_valid()){ +void bittorrent::deleteTorrent(QString hash, bool permanent) { + qDebug("Deleting torrent with hash: %s", hash.toUtf8().data()); + QTorrentHandle h = getTorrentHandle(hash); + if(!h.is_valid()) { qDebug("/!\\ Error: Invalid handle"); return; } - QString savePath = QString::fromUtf8(h.save_path().string().c_str()); - QString fileName = QString(h.name().c_str()); + QString savePath = h.save_path(); + QString fileName = h.name(); // Remove it from session - s->remove_torrent(h); + s->remove_torrent(h.get_torrent_handle()); // Remove it from torrent backup directory QDir torrentBackup(misc::qBittorrentPath() + "BT_backup"); QStringList filters; filters << hash+".*"; QStringList files = torrentBackup.entryList(filters, QDir::Files, QDir::Unsorted); QString file; - foreach(file, files){ + foreach(file, files) { torrentBackup.remove(file); } // Remove it from ETAs hash tables @@ -187,26 +185,26 @@ void bittorrent::deleteTorrent(QString hash, bool permanent){ // Remove it from ratio table ratioData.remove(hash); int index = fullAllocationModeList.indexOf(hash); - if(index != -1){ + if(index != -1) { fullAllocationModeList.removeAt(index); } // Remove it from pausedTorrents list index = pausedTorrents.indexOf(hash); - if(index != -1){ + if(index != -1) { pausedTorrents.removeAt(index); } index = finishedTorrents.indexOf(hash); - if(index != -1){ + if(index != -1) { finishedTorrents.removeAt(index); }else{ index = unfinishedTorrents.indexOf(hash); - if(index != -1){ + if(index != -1) { unfinishedTorrents.removeAt(index); }else{ std::cerr << "Error: Torrent " << hash.toStdString() << " is neither in finished or unfinished list\n"; } } - if(permanent){ + if(permanent) { // Remove from Hard drive qDebug("Removing this on hard drive: %s", qPrintable(savePath+QDir::separator()+fileName)); // Deleting in a thread to avoid GUI freeze @@ -230,42 +228,42 @@ bool bittorrent::isFinished(QString hash) const { // Remove the given hash from the list of finished torrents void bittorrent::setUnfinishedTorrent(QString hash) { int index = finishedTorrents.indexOf(hash); - if(index != -1){ + if(index != -1) { finishedTorrents.removeAt(index); } - if(!unfinishedTorrents.contains(hash)){ + if(!unfinishedTorrents.contains(hash)) { unfinishedTorrents << hash; } } // Add the given hash to the list of finished torrents -void bittorrent::setFinishedTorrent(QString hash){ - if(!finishedTorrents.contains(hash)){ +void bittorrent::setFinishedTorrent(QString hash) { + if(!finishedTorrents.contains(hash)) { finishedTorrents << hash; } int index = unfinishedTorrents.indexOf(hash); - if(index != -1){ + if(index != -1) { unfinishedTorrents.removeAt(index); } } // Pause a running torrent -bool bittorrent::pauseTorrent(QString hash){ +bool bittorrent::pauseTorrent(QString hash) { bool change = false; - torrent_handle h = s->find_torrent(misc::fromString((hash.toStdString()))); - if(h.is_valid() && !h.is_paused()){ + QTorrentHandle h = getTorrentHandle(hash); + if(h.is_valid() && !h.is_paused()) { h.pause(); change = true; qDebug("Torrent paused successfully"); }else{ - if(!h.is_valid()){ - qDebug("Could not pause torrent %s, reason: invalid", (const char*)hash.toUtf8()); + if(!h.is_valid()) { + qDebug("Could not pause torrent %s, reason: invalid", hash.toUtf8().data()); }else{ - qDebug("Could not pause torrent %s, reason: already paused", (const char*)hash.toUtf8()); + qDebug("Could not pause torrent %s, reason: already paused", hash.toUtf8().data()); } } // Create .paused file if necessary - if(!QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".paused")){ + if(!QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".paused")) { QFile paused_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".paused"); paused_file.open(QIODevice::WriteOnly | QIODevice::Text); paused_file.close(); @@ -279,10 +277,10 @@ bool bittorrent::pauseTorrent(QString hash){ } // Resume a torrent in paused state -bool bittorrent::resumeTorrent(QString hash){ +bool bittorrent::resumeTorrent(QString hash) { bool success = false; - torrent_handle h = s->find_torrent(misc::fromString((hash.toStdString()))); - if(h.is_valid() && h.is_paused()){ + QTorrentHandle h = getTorrentHandle(hash); + if(h.is_valid() && h.is_paused()) { h.resume(); success = true; } @@ -290,7 +288,7 @@ bool bittorrent::resumeTorrent(QString hash){ if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".paused")) QFile::remove(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".paused"); int index = torrentsToPauseAfterChecking.indexOf(hash); - if(index != -1){ + if(index != -1) { torrentsToPauseAfterChecking.removeAt(index); success = true; } @@ -303,43 +301,40 @@ bool bittorrent::resumeTorrent(QString hash){ return success; } -void bittorrent::loadWebSeeds(QString fileHash){ - QFile urlseeds_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".urlseeds"); +void bittorrent::loadWebSeeds(QString hash) { + QFile urlseeds_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".urlseeds"); if(!urlseeds_file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QByteArray urlseeds_lines = urlseeds_file.readAll(); urlseeds_file.close(); QList url_seeds = urlseeds_lines.split('\n'); QByteArray url_seed; - torrent_handle h = getTorrentHandle(fileHash); - torrent_info torrentInfo = h.get_torrent_info(); + QTorrentHandle h = getTorrentHandle(hash); // First remove from the torrent the url seeds that were deleted // in a previous session QStringList seeds_to_delete; - std::vector existing_seeds = torrentInfo.url_seeds(); - unsigned int nbSeeds = existing_seeds.size(); + QStringList existing_seeds = h.url_seeds(); QString existing_seed; - for(unsigned int i=0; i(in), std::istream_iterator()); // Getting torrent file informations torrent_info t(e); - QString hash = QString(misc::toString(t.info_hash()).c_str()); - if(s->find_torrent(t.info_hash()).is_valid()){ + QString hash = QString::fromUtf8(misc::toString(t.info_hash()).c_str()); + if(s->find_torrent(t.info_hash()).is_valid()) { // Update info Bar - if(!fromScanDir){ - if(!from_url.isNull()){ + if(!fromScanDir) { + if(!from_url.isNull()) { // If download from url, remove temp file QFile::remove(file); emit duplicateTorrent(from_url); @@ -385,11 +380,11 @@ void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url){ return; } //Getting fast resume data if existing - if(torrentBackup.exists(hash+".fastresume")){ + if(torrentBackup.exists(hash+".fastresume")) { try{ std::stringstream strStream; strStream << hash.toStdString() << ".fastresume"; - boost::filesystem::ifstream resume_file(fs::path((const char*)torrentBackup.path().toUtf8()) / strStream.str(), std::ios_base::binary); + boost::filesystem::ifstream resume_file(fs::path(torrentBackup.path().toUtf8().data()) / strStream.str(), std::ios_base::binary); resume_file.unsetf(std::ios_base::skipws); resume_data = bdecode(std::istream_iterator(resume_file), std::istream_iterator()); fastResume=true; @@ -398,18 +393,18 @@ void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url){ } QString savePath = getSavePath(hash); // Adding files to bittorrent session - if(hasFilteredFiles(hash)){ - h = s->add_torrent(t, fs::path((const char*)savePath.toUtf8()), resume_data, false); + if(has_filtered_files(hash)) { + h = s->add_torrent(t, fs::path(savePath.toUtf8().data()), resume_data, false); int index = fullAllocationModeList.indexOf(hash); - if(index == -1){ + if(index == -1) { fullAllocationModeList << hash; } qDebug("Full allocation mode"); }else{ - h = s->add_torrent(t, fs::path((const char*)savePath.toUtf8()), resume_data, true); + h = s->add_torrent(t, fs::path(savePath.toUtf8().data()), resume_data, true); qDebug("Compact allocation mode"); } - if(!h.is_valid()){ + if(!h.is_valid()) { // No need to keep on, it failed. qDebug("/!\\ Error: Invalid handle"); // If download from url, remove temp file @@ -431,13 +426,12 @@ void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url){ // Load trackers bool loaded_trackers = loadTrackerFile(hash); // Doing this to order trackers well - if(!loaded_trackers){ + if(!loaded_trackers) { saveTrackerFile(hash); loadTrackerFile(hash); } - torrent_status torrentStatus = h.status(); QString newFile = torrentBackup.path() + QDir::separator() + hash + ".torrent"; - if(file != newFile){ + if(file != newFile) { // Delete file from torrentBackup directory in case it exists because // QFile::copy() do not overwrite QFile::remove(newFile); @@ -445,16 +439,16 @@ void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url){ QFile::copy(file, newFile); } // Pause torrent if it was paused last time - if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".paused")){ + if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".paused")) { torrentsToPauseAfterChecking << hash; qDebug("Adding a torrent to the torrentsToPauseAfterChecking list"); } // Incremental download - if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".incremental")){ + if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".incremental")) { qDebug("Incremental download enabled for %s", t.name().c_str()); h.set_sequenced_download_threshold(1); } - if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".finished")){ + if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".finished")) { finishedTorrents << hash; }else{ unfinishedTorrents << hash; @@ -462,38 +456,38 @@ void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url){ // If download from url, remove temp file if(!from_url.isNull()) QFile::remove(file); // Delete from scan dir to avoid trying to download it again - if(fromScanDir){ + if(fromScanDir) { QFile::remove(file); } // Send torrent addition signal - if(!from_url.isNull()){ + if(!from_url.isNull()) { emit addedTorrent(from_url, h, fastResume); }else{ emit addedTorrent(file, h, fastResume); } - }catch (invalid_encoding& e){ // Raised by bdecode() + }catch (invalid_encoding& e) { // Raised by bdecode() std::cerr << "Could not decode file, reason: " << e.what() << '\n'; // Display warning to tell user we can't decode the torrent file - if(!from_url.isNull()){ + if(!from_url.isNull()) { emit invalidTorrent(from_url); }else{ emit invalidTorrent(file); } - if(fromScanDir){ + if(fromScanDir) { // Remove .corrupt file in case it already exists QFile::remove(file+".corrupt"); //Rename file extension so that it won't display error message more than once QFile::rename(file,file+".corrupt"); } } - catch (invalid_torrent_file&){ // Raised by torrent_info constructor + catch (invalid_torrent_file&) { // Raised by torrent_info constructor // Display warning to tell user we can't decode the torrent file - if(!from_url.isNull()){ + if(!from_url.isNull()) { emit invalidTorrent(from_url); }else{ emit invalidTorrent(file); } - if(fromScanDir){ + if(fromScanDir) { // Remove .corrupt file in case it already exists QFile::remove(file+".corrupt"); //Rename file extension so that it won't display error message more than once @@ -502,76 +496,42 @@ void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url){ } } -// Set the maximum number of opened connections -void bittorrent::setMaxConnections(int maxConnec){ - s->set_max_connections(maxConnec); -} - // Check in .priorities file if the user filtered files // in this torrent. -bool bittorrent::hasFilteredFiles(QString fileHash) const{ - QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".priorities"); +bool bittorrent::has_filtered_files(QString hash) const{ + QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".priorities"); // Read saved file - if(!pieces_file.open(QIODevice::ReadOnly | QIODevice::Text)){ + if(!pieces_file.open(QIODevice::ReadOnly | QIODevice::Text)) { return false; } QByteArray pieces_text = pieces_file.readAll(); pieces_file.close(); QList pieces_priorities_list = pieces_text.split('\n'); unsigned int listSize = pieces_priorities_list.size(); - for(unsigned int i=0; i 7){ + if( priority < 0 || priority > 7) { priority = 1; } - if(!priority){ + if(!priority) { return true; } } return false; } +// Set the maximum number of opened connections +void bittorrent::setMaxConnections(int maxConnec) { + s->set_max_connections(maxConnec); +} + // For debug only -void bittorrent::printPausedTorrents(){ +void bittorrent::printPausedTorrents() { QString hash; qDebug("Paused Torrents:"); - foreach(hash, pausedTorrents){ - qDebug("%s ", (const char*)hash.toUtf8()); - } -} - -// get the size of the torrent without the filtered files -size_type bittorrent::torrentEffectiveSize(QString hash) const{ - torrent_handle h = getTorrentHandle(hash); - torrent_info t = h.get_torrent_info(); - unsigned int nbFiles = t.num_files(); - if(!h.is_valid()){ - qDebug("/!\\ Error: Invalid handle"); - return t.total_size(); - } - QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".priorities"); - // Read saved file - if(!pieces_file.open(QIODevice::ReadOnly | QIODevice::Text)){ - qDebug("* Error: Couldn't open priorities file"); - return t.total_size(); - } - QByteArray pieces_priorities = pieces_file.readAll(); - pieces_file.close(); - QList pieces_priorities_list = pieces_priorities.split('\n'); - if((unsigned int)pieces_priorities_list.size() != nbFiles+1){ - std::cerr << "* Error: Corrupted priorities file\n"; - return t.total_size(); + foreach(hash, pausedTorrents) { + qDebug("%s ", hash.toUtf8().data()); } - size_type effective_size = 0; - for(unsigned int i=0; i 7){ - priority = 1; - } - if(priority) - effective_size += t.file_at(i).size; - } - return effective_size; } // Return DHT state @@ -580,9 +540,9 @@ bool bittorrent::isDHTEnabled() const{ } // Enable DHT -void bittorrent::enableDHT(){ - if(!DHTEnabled){ - boost::filesystem::ifstream dht_state_file((const char*)(misc::qBittorrentPath()+QString("dht_state")).toUtf8(), std::ios_base::binary); +void bittorrent::enableDHT() { + if(!DHTEnabled) { + boost::filesystem::ifstream dht_state_file((misc::qBittorrentPath()+QString::fromUtf8("dht_state")).toUtf8().data(), std::ios_base::binary); dht_state_file.unsetf(std::ios_base::skipws); entry dht_state; try{ @@ -598,39 +558,39 @@ void bittorrent::enableDHT(){ } // Disable DHT -void bittorrent::disableDHT(){ - if(DHTEnabled){ +void bittorrent::disableDHT() { + if(DHTEnabled) { DHTEnabled = false; s->stop_dht(); qDebug("DHT disabled"); } } -void bittorrent::saveTorrentSpeedLimits(QString hash){ - qDebug("Saving speedLimits file for %s", (const char*)hash.toUtf8()); - torrent_handle h = getTorrentHandle(hash); +void bittorrent::saveTorrentSpeedLimits(QString hash) { + qDebug("Saving speedLimits file for %s", hash.toUtf8().data()); + QTorrentHandle h = getTorrentHandle(hash); int download_limit = h.download_limit(); int upload_limit = h.upload_limit(); QFile speeds_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".speedLimits"); - if(!speeds_file.open(QIODevice::WriteOnly | QIODevice::Text)){ - qDebug("* Error: Couldn't open speed limits file for torrent: %s", (const char*)hash.toUtf8()); + if(!speeds_file.open(QIODevice::WriteOnly | QIODevice::Text)) { + qDebug("* Error: Couldn't open speed limits file for torrent: %s", hash.toUtf8().data()); return; } - speeds_file.write(QByteArray(misc::toString(download_limit).c_str())+QByteArray(" ")+QByteArray(misc::toString(upload_limit).c_str())); + speeds_file.write(misc::toQByteArray(download_limit)+QByteArray(" ")+misc::toQByteArray(upload_limit)); speeds_file.close(); } -void bittorrent::loadTorrentSpeedLimits(QString hash){ - qDebug("Loading speedLimits file for %s", (const char*)hash.toUtf8()); - torrent_handle h = getTorrentHandle(hash); +void bittorrent::loadTorrentSpeedLimits(QString hash) { + qDebug("Loading speedLimits file for %s", hash.toUtf8().data()); + QTorrentHandle h = getTorrentHandle(hash); QFile speeds_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".speedLimits"); - if(!speeds_file.open(QIODevice::ReadOnly | QIODevice::Text)){ + if(!speeds_file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } QByteArray speed_limits = speeds_file.readAll(); speeds_file.close(); QList speeds = speed_limits.split(' '); - if(speeds.size() != 2){ + if(speeds.size() != 2) { std::cerr << "Invalid .speedLimits file for " << hash.toStdString() << '\n'; return; } @@ -639,32 +599,31 @@ void bittorrent::loadTorrentSpeedLimits(QString hash){ } // Read pieces priorities from .priorities file -// and ask torrent_handle to consider them -void bittorrent::loadFilesPriorities(torrent_handle &h){ - torrent_info torrentInfo = h.get_torrent_info(); - unsigned int nbFiles = torrentInfo.num_files(); - if(!h.is_valid()){ +// and ask QTorrentHandle to consider them +void bittorrent::loadFilesPriorities(QTorrentHandle &h) { + if(!h.is_valid()) { qDebug("/!\\ Error: Invalid handle"); return; } - QString fileHash = QString(misc::toString(torrentInfo.info_hash()).c_str()); - QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".priorities"); + unsigned int nbFiles = h.num_files(); + QString hash = h.hash(); + QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".priorities"); // Read saved file - if(!pieces_file.open(QIODevice::ReadOnly | QIODevice::Text)){ + if(!pieces_file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug("* Error: Couldn't open priorities file"); return; } QByteArray pieces_priorities = pieces_file.readAll(); pieces_file.close(); QList pieces_priorities_list = pieces_priorities.split('\n'); - if((unsigned int)pieces_priorities_list.size() != nbFiles+1){ + if((unsigned int)pieces_priorities_list.size() != nbFiles+1) { std::cerr << "* Error: Corrupted priorities file\n"; return; } std::vector v; - for(unsigned int i=0; i 7){ + if( priority < 0 || priority > 7) { priority = 1; } //qDebug("Setting piece piority to %d", priority); @@ -673,21 +632,21 @@ void bittorrent::loadFilesPriorities(torrent_handle &h){ h.prioritize_files(v); } -void bittorrent::loadDownloadUploadForTorrent(QString hash){ +void bittorrent::loadDownloadUploadForTorrent(QString hash) { QDir torrentBackup(misc::qBittorrentPath() + "BT_backup"); // Checking if torrentBackup Dir exists // create it if it is not - if(! torrentBackup.exists()){ + if(! torrentBackup.exists()) { torrentBackup.mkpath(torrentBackup.path()); } - qDebug("Loading ratio data for %s", (const char*)hash.toUtf8()); + qDebug("Loading ratio data for %s", hash.toUtf8().data()); QFile ratio_file(torrentBackup.path()+QDir::separator()+ hash + ".ratio"); - if(!ratio_file.open(QIODevice::ReadOnly | QIODevice::Text)){ + if(!ratio_file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } QByteArray data = ratio_file.readAll(); QList data_list = data.split(' '); - if(data_list.size() != 2){ + if(data_list.size() != 2) { std::cerr << "Corrupted ratio file for torrent: " << hash.toStdString() << '\n'; return; } @@ -698,35 +657,52 @@ void bittorrent::loadDownloadUploadForTorrent(QString hash){ ratioData[hash] = downUp; } +float bittorrent::getRealRatio(QString hash) const{ + QPair downUpInfo = ratioData.value(hash, QPair(0,0)); + size_type download = downUpInfo.first; + size_type upload = downUpInfo.second; + QTorrentHandle h = getTorrentHandle(hash); + download += h.total_payload_download(); + upload += h.total_payload_upload(); + if(download == 0){ + if(upload == 0) + return 1.; + return 10.; + } + float ratio = (double)upload / (double)download; + Q_ASSERT(ratio >= 0.); + if(ratio > 10.) + ratio = 10.; + return ratio; +} + // To remember share ratio or a torrent, we must save current // total_upload and total_upload and reload them on startup -void bittorrent::saveDownloadUploadForTorrent(QString hash){ - qDebug("Saving ratio data for torrent %s", (const char*)hash.toUtf8()); - QDir torrentBackup(misc::qBittorrentPath() + "BT_backup"); +void bittorrent::saveDownloadUploadForTorrent(QString hash) { + qDebug("Saving ratio data for torrent %s", hash.toUtf8().data()); + QDir torrentBackup(misc::qBittorrentPath() + QString::fromUtf8("BT_backup")); // Checking if torrentBackup Dir exists // create it if it is not - if(! torrentBackup.exists()){ + if(! torrentBackup.exists()) { torrentBackup.mkpath(torrentBackup.path()); } - torrent_handle h = getTorrentHandle(hash); - if(!h.is_valid()){ + QTorrentHandle h = getTorrentHandle(hash); + if(!h.is_valid()) { qDebug("/!\\ Error: Invalid handle"); return; } - torrent_status torrentStatus = h.status(); - QString fileHash = QString(misc::toString(h.info_hash()).c_str()); - QPair ratioInfo = ratioData.value(fileHash, QPair(0,0)); - size_type download = torrentStatus.total_payload_download; + QPair ratioInfo = ratioData.value(hash, QPair(0,0)); + size_type download = h.total_payload_download(); download += ratioInfo.first; - size_type upload = torrentStatus.total_payload_upload; + size_type upload = h.total_payload_upload(); upload += ratioInfo.second; Q_ASSERT(download >= 0 && upload >= 0); - QFile ratio_file(torrentBackup.path()+QDir::separator()+ fileHash + ".ratio"); - if(!ratio_file.open(QIODevice::WriteOnly | QIODevice::Text)){ - std::cerr << "Couldn't save ratio data for torrent: " << fileHash.toStdString() << '\n'; + QFile ratio_file(torrentBackup.path()+QDir::separator()+ hash + QString::fromUtf8(".ratio")); + if(!ratio_file.open(QIODevice::WriteOnly | QIODevice::Text)) { + std::cerr << "Couldn't save ratio data for torrent: " << hash.toStdString() << '\n'; return; } - ratio_file.write(QByteArray(misc::toString(download).c_str()) + QByteArray(" ") + QByteArray(misc::toString(upload).c_str())); + ratio_file.write(misc::toQByteArray(download) + QByteArray(" ") + misc::toQByteArray(upload)); ratio_file.close(); } @@ -736,20 +712,20 @@ bool bittorrent::receivedPausedAlert(QString hash) const{ // Save fastresume data for all torrents // and remove them from the session -void bittorrent::saveFastResumeAndRatioData(){ +void bittorrent::saveFastResumeAndRatioData() { qDebug("Saving fast resume and ratio data"); QString file; QDir torrentBackup(misc::qBittorrentPath() + "BT_backup"); // Checking if torrentBackup Dir exists // create it if it is not - if(! torrentBackup.exists()){ + if(! torrentBackup.exists()) { torrentBackup.mkpath(torrentBackup.path()); } // Pause torrents std::vector handles = s->get_torrents(); - for(unsigned int i=0; i(out), resumeData); } // Save ratio data - saveDownloadUploadForTorrent(fileHash); + saveDownloadUploadForTorrent(hash); // Save trackers - saveTrackerFile(fileHash); + saveTrackerFile(hash); } // Remove torrent - s->remove_torrent(h); + s->remove_torrent(h.get_torrent_handle()); } qDebug("Fast resume and ratio data saved"); } bool bittorrent::isFilePreviewPossible(QString hash) const{ // See if there are supported files in the torrent - torrent_handle h = s->find_torrent(misc::fromString((hash.toStdString()))); - if(!h.is_valid()){ + QTorrentHandle h = getTorrentHandle(hash); + if(!h.is_valid()) { qDebug("/!\\ Error: Invalid handle"); return false; } - torrent_info torrentInfo = h.get_torrent_info(); - for(int i=0; i= 0){ + if(supported_preview_extensions.indexOf(extension) >= 0) { return true; } } @@ -813,30 +789,30 @@ bool bittorrent::isFilePreviewPossible(QString hash) const{ // Scan the first level of the directory for torrent files // and add them to download list -void bittorrent::scanDirectory(){ +void bittorrent::scanDirectory() { QString file; - if(!scan_dir.isNull()){ + if(!scan_dir.isNull()) { QStringList to_add; QDir dir(scan_dir); QStringList filters; filters << "*.torrent"; QStringList files = dir.entryList(filters, QDir::Files, QDir::Unsorted); - foreach(file, files){ + foreach(file, files) { QString fullPath = dir.path()+QDir::separator()+file; - QFile::rename(fullPath, fullPath+QString(".old")); - to_add << fullPath+QString(".old"); + QFile::rename(fullPath, fullPath+QString::fromUtf8(".old")); + to_add << fullPath+QString::fromUtf8(".old"); } emit scanDirFoundTorrents(to_add); } } -void bittorrent::setDefaultSavePath(QString savepath){ +void bittorrent::setDefaultSavePath(QString savepath) { defaultSavePath = savepath; } // Enable directory scanning -void bittorrent::enableDirectoryScanning(QString _scan_dir){ - if(!_scan_dir.isEmpty()){ +void bittorrent::enableDirectoryScanning(QString _scan_dir) { + if(!_scan_dir.isEmpty()) { scan_dir = _scan_dir; timerScan = new QTimer(this); connect(timerScan, SIGNAL(timeout()), this, SLOT(scanDirectory())); @@ -845,10 +821,10 @@ void bittorrent::enableDirectoryScanning(QString _scan_dir){ } // Disable directory scanning -void bittorrent::disableDirectoryScanning(){ - if(!scan_dir.isNull()){ +void bittorrent::disableDirectoryScanning() { + if(!scan_dir.isNull()) { scan_dir = QString::null; - if(timerScan->isActive()){ + if(timerScan->isActive()) { timerScan->stop(); } } @@ -858,13 +834,13 @@ void bittorrent::disableDirectoryScanning(){ // Set the ports range in which is chosen the port the bittorrent // session will listen to -void bittorrent::setListeningPortsRange(std::pair ports){ +void bittorrent::setListeningPortsRange(std::pair ports) { s->listen_on(ports); } // Set download rate limit // -1 to disable -void bittorrent::setDownloadRateLimit(long rate){ +void bittorrent::setDownloadRateLimit(long rate) { qDebug("Setting a global download rate limit at %ld", rate); s->set_download_rate_limit(rate); } @@ -875,19 +851,19 @@ session* bittorrent::getSession() const{ // Set upload rate limit // -1 to disable -void bittorrent::setUploadRateLimit(long rate){ +void bittorrent::setUploadRateLimit(long rate) { qDebug("set upload_limit to %fkb/s", rate/1024.); s->set_upload_rate_limit(rate); } // libtorrent allow to adjust ratio for each torrent // This function will apply to same ratio to all torrents -void bittorrent::setGlobalRatio(float ratio){ +void bittorrent::setGlobalRatio(float ratio) { std::vector handles = s->get_torrents(); unsigned int nbHandles = handles.size(); - for(unsigned int i=0; i trackers; QString line; - foreach(line, lines){ + foreach(line, lines) { QStringList parts = line.split("|"); if(parts.size() != 2) continue; announce_entry t(parts[0].toStdString()); t.tier = parts[1].toInt(); trackers.push_back(t); } - if(trackers.size() != 0){ - torrent_handle h = getTorrentHandle(hash); + if(trackers.size() != 0) { + QTorrentHandle h = getTorrentHandle(hash); h.replace_trackers(trackers); return true; }else{ @@ -919,30 +895,30 @@ bool bittorrent::loadTrackerFile(QString hash){ } } -void bittorrent::saveTrackerFile(QString hash){ +void bittorrent::saveTrackerFile(QString hash) { QDir torrentBackup(misc::qBittorrentPath() + "BT_backup"); QFile tracker_file(torrentBackup.path()+QDir::separator()+ hash + ".trackers"); - if(tracker_file.exists()){ + if(tracker_file.exists()) { tracker_file.remove(); } tracker_file.open(QIODevice::WriteOnly | QIODevice::Text); - torrent_handle h = getTorrentHandle(hash); + QTorrentHandle h = getTorrentHandle(hash); std::vector trackers = h.trackers(); - for(unsigned int i=0; iadd_extension(&create_ut_pex_plugin); } // Set DHT port (>= 1000) -void bittorrent::setDHTPort(int dht_port){ - if(dht_port >= 1000){ +void bittorrent::setDHTPort(int dht_port) { + if(dht_port >= 1000) { struct dht_settings DHTSettings; DHTSettings.service_port = dht_port; s->set_dht_settings(DHTSettings); @@ -951,26 +927,25 @@ void bittorrent::setDHTPort(int dht_port){ } // Enable IP Filtering -void bittorrent::enableIPFilter(ip_filter filter){ +void bittorrent::enableIPFilter(ip_filter filter) { qDebug("Enabling IPFiler"); s->set_ip_filter(filter); } // Disable IP Filtering -void bittorrent::disableIPFilter(){ - qDebug("Disable IPFilter"); +void bittorrent::disableIPFilter() { + qDebug("Disabling IPFilter"); s->set_ip_filter(ip_filter()); - qDebug("IPFilter disabled"); } // Set BT session settings (user_agent) -void bittorrent::setSessionSettings(session_settings sessionSettings){ +void bittorrent::setSessionSettings(session_settings sessionSettings) { qDebug("Set session settings"); s->set_settings(sessionSettings); } // Set Proxy -void bittorrent::setProxySettings(proxy_settings proxySettings, bool trackers, bool peers, bool web_seeds, bool dht){ +void bittorrent::setProxySettings(proxy_settings proxySettings, bool trackers, bool peers, bool web_seeds, bool dht) { qDebug("Set Proxy settings"); if(trackers) s->set_tracker_proxy(proxySettings); @@ -978,49 +953,52 @@ void bittorrent::setProxySettings(proxy_settings proxySettings, bool trackers, b s->set_peer_proxy(proxySettings); if(web_seeds) s->set_web_seed_proxy(proxySettings); - if(DHTEnabled && dht){ + if(DHTEnabled && dht) { s->set_dht_proxy(proxySettings); } } // Read alerts sent by the bittorrent session -void bittorrent::readAlerts(){ +void bittorrent::readAlerts() { // look at session alerts and display some infos std::auto_ptr a = s->pop_alert(); - while (a.get()){ - if (torrent_finished_alert* p = dynamic_cast(a.get())){ - QString hash = QString(misc::toString(p->handle.info_hash()).c_str()); + while (a.get()) { + if (torrent_finished_alert* p = dynamic_cast(a.get())) { + QTorrentHandle h(p->handle); + QString hash = h.hash(); setFinishedTorrent(hash); - emit finishedTorrent(p->handle); + emit finishedTorrent(h); } - else if (file_error_alert* p = dynamic_cast(a.get())){ - emit fullDiskError(p->handle); + else if (file_error_alert* p = dynamic_cast(a.get())) { + QTorrentHandle h(p->handle); + emit fullDiskError(h); } - else if (dynamic_cast(a.get())){ + else if (dynamic_cast(a.get())) { // Level: fatal emit portListeningFailure(); } - else if (tracker_alert* p = dynamic_cast(a.get())){ + else if (tracker_alert* p = dynamic_cast(a.get())) { // Level: fatal - QString hash = QString(misc::toString(p->handle.info_hash()).c_str()); + QTorrentHandle h(p->handle); + QString hash = h.hash(); QList > errors = trackersErrors.value(hash, QList >()); if(errors.size() > 5) errors.removeAt(0); - errors << QPair(QTime::currentTime().toString("hh:mm:ss"), QString(a->msg().c_str())); + errors << QPair(QTime::currentTime().toString("hh:mm:ss"), QString::fromUtf8(a->msg().c_str())); trackersErrors[hash] = errors; // Authentication - if(p->status_code == 401){ - emit trackerAuthenticationRequired(p->handle); + if(p->status_code == 401) { + emit trackerAuthenticationRequired(h); } } - else if (torrent_paused_alert* p = dynamic_cast(a.get())){ - QString hash = QString(misc::toString(p->handle.info_hash()).c_str()); - qDebug("Received torrent_paused_alert for %s", (const char*)hash.toUtf8()); - if(!pausedTorrents.contains(hash)){ - torrent_handle h = p->handle; - if(h.is_valid() && h.is_paused()){ + else if (torrent_paused_alert* p = dynamic_cast(a.get())) { + QTorrentHandle h(p->handle); + QString hash = h.hash(); + qDebug("Received torrent_paused_alert for %s", hash.toUtf8().data()); + if(!pausedTorrents.contains(hash)) { + if(h.is_valid() && h.is_paused()) { pausedTorrents << hash; - if(reloadingTorrents.indexOf(hash) != -1){ + if(reloadingTorrents.indexOf(hash) != -1) { reloadTorrent(h); } }else{ @@ -1030,24 +1008,26 @@ void bittorrent::readAlerts(){ qDebug("Received alert for already paused torrent"); } } - else if (peer_blocked_alert* p = dynamic_cast(a.get())){ - emit peerBlocked(QString(p->ip.to_string().c_str())); + else if (peer_blocked_alert* p = dynamic_cast(a.get())) { + emit peerBlocked(QString::fromUtf8(p->ip.to_string().c_str())); } - else if (fastresume_rejected_alert* p = dynamic_cast(a.get())){ - qDebug("/!\\ Fast resume failed for %s, reason: %s", p->handle.name().c_str(), p->msg().c_str()); - emit fastResumeDataRejected(QString(p->handle.name().c_str())); + else if (fastresume_rejected_alert* p = dynamic_cast(a.get())) { + QTorrentHandle h(p->handle); + qDebug("/!\\ Fast resume failed for %s, reason: %s", h.name().toUtf8().data(), p->msg().c_str()); + emit fastResumeDataRejected(QString::fromUtf8(p->handle.name().c_str())); } - else if (url_seed_alert* p = dynamic_cast(a.get())){ - emit urlSeedProblem(QString(p->url.c_str()), QString(p->msg().c_str())); + else if (url_seed_alert* p = dynamic_cast(a.get())) { + emit urlSeedProblem(QString::fromUtf8(p->url.c_str()), QString::fromUtf8(p->msg().c_str())); } - else if (torrent_checked_alert* p = dynamic_cast(a.get())){ - QString hash = QString(misc::toString(p->handle.info_hash()).c_str()); - qDebug("%s have just finished checking", (const char*)hash.toUtf8()); + else if (torrent_checked_alert* p = dynamic_cast(a.get())) { + QTorrentHandle h(p->handle); + QString hash = h.hash(); + qDebug("%s have just finished checking", hash.toUtf8().data()); int index = torrentsToPauseAfterChecking.indexOf(hash); - if(index != -1){ + if(index != -1) { // Pause torrent pauseTorrent(hash); - qDebug("%s was paused after checking", (const char*)hash.toUtf8()); + qDebug("%s was paused after checking", hash.toUtf8().data()); } emit torrentFinishedChecking(hash); } @@ -1065,14 +1045,14 @@ QStringList bittorrent::getTorrentsToPauseAfterChecking() const{ // Function to reload the torrent async after the torrent is actually // paused so that we can get fastresume data -void bittorrent::pauseAndReloadTorrent(const torrent_handle &h){ - if(!h.is_valid()){ +void bittorrent::pauseAndReloadTorrent(QTorrentHandle h) { + if(!h.is_valid()) { std::cerr << "/!\\ Error: Invalid handle\n"; return; } // ask to pause the torrent (async) h.pause(); - QString hash = QString(misc::toString(h.info_hash()).c_str()); + QString hash = h.hash(); // Add it to reloadingTorrents list so that we now we // we should reload the torrent once we receive the // torrent_paused_alert. pause() is async now... @@ -1080,69 +1060,64 @@ void bittorrent::pauseAndReloadTorrent(const torrent_handle &h){ } // Reload a torrent with full allocation mode -void bittorrent::reloadTorrent(const torrent_handle &h){ +void bittorrent::reloadTorrent(const QTorrentHandle &h) { qDebug("** Reloading a torrent"); - if(!h.is_valid()){ + if(!h.is_valid()) { qDebug("/!\\ Error: Invalid handle"); return; } QDir torrentBackup(misc::qBittorrentPath() + "BT_backup"); - fs::path saveDir = h.save_path(); - QString fileName = QString(h.name().c_str()); - QString fileHash = QString(misc::toString(h.info_hash()).c_str()); - int index = fullAllocationModeList.indexOf(fileHash); - if(index == -1){ - fullAllocationModeList << fileHash; - } - qDebug("Reloading torrent: %s", (const char*)fileName.toUtf8()); - torrent_handle new_h; - entry resumeData; + fs::path saveDir = h.save_path_boost(); + QString fileName = h.name(); + QString hash = h.hash(); torrent_info t = h.get_torrent_info(); + int index = fullAllocationModeList.indexOf(hash); + if(index == -1) { + fullAllocationModeList << hash; + } + qDebug("Reloading torrent: %s", fileName.toUtf8().data()); + QTorrentHandle new_h; + entry resumeData; // Checking if torrentBackup Dir exists // create it if it is not - if(! torrentBackup.exists()){ + if(! torrentBackup.exists()) { torrentBackup.mkpath(torrentBackup.path()); } // Write fast resume data // Torrent is already paused - Q_ASSERT(pausedTorrents.indexOf(fileHash) != -1); + Q_ASSERT(pausedTorrents.indexOf(hash) != -1); // Extracting resume data - if (h.has_metadata()){ + if (h.has_metadata()) { // get fast resume data resumeData = h.write_resume_data(); } // Remove torrent - s->remove_torrent(h); + s->remove_torrent(h.get_torrent_handle()); // Add torrent again to session unsigned short timeout = 0; - while(h.is_valid() && timeout < 6){ + while(h.is_valid() && timeout < 6) { SleeperThread::msleep(1000); ++timeout; } - if(h.is_valid()){ - std::cerr << "Error: Couldn't reload the torrent\n"; - return; - } new_h = s->add_torrent(t, saveDir, resumeData, false); qDebug("Using full allocation mode"); -// new_h.set_max_connections(60); new_h.set_max_uploads(-1); // Load filtered Files loadFilesPriorities(new_h); // Load speed limit from hard drive - loadTorrentSpeedLimits(fileHash); + loadTorrentSpeedLimits(hash); // Load custom url seeds - loadWebSeeds(fileHash); + loadWebSeeds(hash); // Load ratio data - loadDownloadUploadForTorrent(fileHash); + loadDownloadUploadForTorrent(hash); // Pause torrent if it was paused last time - if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".paused")){ + if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".paused")) { new_h.pause(); } // Incremental download - if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".incremental")){ - qDebug("Incremental download enabled for %s", (const char*)fileName.toUtf8()); + if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".incremental")) { + qDebug("Incremental download enabled for %s", fileName.toUtf8().data()); new_h.set_sequenced_download_threshold(1); } } @@ -1153,26 +1128,6 @@ int bittorrent::getListenPort() const{ return s->listen_port(); } -float bittorrent::getRealRatio(QString hash) const{ - QPair downUpInfo = ratioData.value(hash, QPair(0,0)); - size_type download = downUpInfo.first; - size_type upload = downUpInfo.second; - torrent_handle h = getTorrentHandle(hash); - torrent_status torrentStatus = h.status(); - download += torrentStatus.total_payload_download; - upload += torrentStatus.total_payload_upload; - if(download == 0){ - if(upload == 0) - return 1.; - return 10.; - } - float ratio = (double)upload / (double)download; - Q_ASSERT(ratio >= 0.); - if(ratio > 10.) - ratio = 10.; - return ratio; -} - session_status bittorrent::getSessionStatus() const{ return s->status(); } @@ -1183,11 +1138,11 @@ bool bittorrent::inFullAllocationMode(QString hash) const{ return false; } -QString bittorrent::getSavePath(QString hash){ +QString bittorrent::getSavePath(QString hash) { QFile savepath_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".savepath"); QByteArray line; QString savePath; - if(savepath_file.open(QIODevice::ReadOnly | QIODevice::Text)){ + if(savepath_file.open(QIODevice::ReadOnly | QIODevice::Text)) { line = savepath_file.readAll(); savepath_file.close(); qDebug("Save path: %s", line.data()); @@ -1199,9 +1154,9 @@ QString bittorrent::getSavePath(QString hash){ // Checking if savePath Dir exists // create it if it is not QDir saveDir(savePath); - if(!saveDir.exists()){ - if(!saveDir.mkpath(saveDir.path())){ - std::cerr << "Couldn't create the save directory: " << (const char*)saveDir.path().toUtf8() << "\n"; + if(!saveDir.exists()) { + if(!saveDir.mkpath(saveDir.path())) { + std::cerr << "Couldn't create the save directory: " << saveDir.path().toUtf8().data() << "\n"; // XXX: handle this better return QDir::homePath(); } @@ -1212,22 +1167,22 @@ QString bittorrent::getSavePath(QString hash){ // Take an url string to a torrent file, // download the torrent file to a tmp location, then // add it to download list -void bittorrent::downloadFromUrl(QString url){ +void bittorrent::downloadFromUrl(QString url) { emit aboutToDownloadFromUrl(url); // Launch downloader thread downloader->downloadUrl(url); } // Add to bittorrent session the downloaded torrent file -void bittorrent::processDownloadedFile(QString url, QString file_path){ +void bittorrent::processDownloadedFile(QString url, QString file_path) { // Add file to torrent download list emit newDownloadedTorrent(file_path, url); } -void bittorrent::downloadFromURLList(const QStringList& url_list){ +void bittorrent::downloadFromURLList(const QStringList& url_list) { QString url; qDebug("DownloadFromUrlList"); - foreach(url, url_list){ + foreach(url, url_list) { downloadFromUrl(url); } } @@ -1248,35 +1203,30 @@ float bittorrent::getPayloadUploadRate() const{ return sessionStatus.payload_upload_rate; } -// Return a vector with all torrent handles in it -std::vector bittorrent::getTorrentHandles() const{ - return s->get_torrents(); -} - // Save DHT entry to hard drive -void bittorrent::saveDHTEntry(){ +void bittorrent::saveDHTEntry() { // Save DHT entry - if(DHTEnabled){ + if(DHTEnabled) { try{ entry dht_state = s->dht_state(); - boost::filesystem::ofstream out((const char*)(misc::qBittorrentPath()+QString("dht_state")).toUtf8(), std::ios_base::binary); + boost::filesystem::ofstream out((misc::qBittorrentPath()+QString::fromUtf8("dht_state")).toUtf8().data(), std::ios_base::binary); out.unsetf(std::ios_base::skipws); bencode(std::ostream_iterator(out), dht_state); qDebug("DHT entry saved"); - }catch (std::exception& e){ + }catch (std::exception& e) { std::cerr << e.what() << "\n"; } } } -void bittorrent::applyEncryptionSettings(pe_settings se){ +void bittorrent::applyEncryptionSettings(pe_settings se) { qDebug("Applying encryption settings"); s->set_pe_settings(se); } // Will fast resume unfinished torrents in // backup directory -void bittorrent::resumeUnfinishedTorrents(){ +void bittorrent::resumeUnfinishedTorrents() { qDebug("Resuming unfinished torrents"); QDir torrentBackup(misc::qBittorrentPath() + "BT_backup"); QStringList fileNames, filePaths; @@ -1285,11 +1235,11 @@ void bittorrent::resumeUnfinishedTorrents(){ filters << "*.torrent"; fileNames = torrentBackup.entryList(filters, QDir::Files, QDir::Unsorted); QString fileName; - foreach(fileName, fileNames){ + foreach(fileName, fileNames) { filePaths.append(torrentBackup.path()+QDir::separator()+fileName); } // Resume downloads - foreach(fileName, filePaths){ + foreach(fileName, filePaths) { addTorrent(fileName, false); } qDebug("Unfinished torrents resumed"); diff --git a/src/bittorrent.h b/src/bittorrent.h index 8cd02db79..c71e5996b 100644 --- a/src/bittorrent.h +++ b/src/bittorrent.h @@ -26,8 +26,8 @@ #include #include -#include #include +#include "qtorrenthandle.h" using namespace libtorrent; @@ -67,10 +67,8 @@ class bittorrent : public QObject{ // Constructor / Destructor bittorrent(); ~bittorrent(); - torrent_handle getTorrentHandle(QString hash) const; - std::vector getTorrentHandles() const; + QTorrentHandle getTorrentHandle(QString hash) const; bool isPaused(QString hash) const; - bool hasFilteredFiles(QString fileHash) const; bool isFilePreviewPossible(QString fileHash) const; bool isDHTEnabled() const; float getPayloadDownloadRate() const; @@ -79,7 +77,6 @@ class bittorrent : public QObject{ int getListenPort() const; QStringList getTorrentsToPauseAfterChecking() const; long getETA(QString hash) const; - size_type torrentEffectiveSize(QString hash) const; bool inFullAllocationMode(QString hash) const; float getRealRatio(QString hash) const; session* getSession() const; @@ -89,6 +86,7 @@ class bittorrent : public QObject{ QStringList getFinishedTorrents() const; QStringList getUnfinishedTorrents() const; bool isFinished(QString hash) const; + bool has_filtered_files(QString hash) const; public slots: void addTorrent(QString path, bool fromScanDir = false, QString from_url = QString()); @@ -106,7 +104,7 @@ class bittorrent : public QObject{ void enablePeerExchange(); void enableIPFilter(ip_filter filter); void disableIPFilter(); - void pauseAndReloadTorrent(const torrent_handle &h); + void pauseAndReloadTorrent(QTorrentHandle h); void resumeUnfinishedTorrents(); void updateETAs(); void saveTorrentSpeedLimits(QString hash); @@ -126,7 +124,7 @@ class bittorrent : public QObject{ void setSessionSettings(session_settings sessionSettings); void setDefaultSavePath(QString savepath); void applyEncryptionSettings(pe_settings se); - void loadFilesPriorities(torrent_handle& h); + void loadFilesPriorities(QTorrentHandle& h); void setDownloadLimit(QString hash, long val); void setUploadLimit(QString hash, long val); void setUnfinishedTorrent(QString hash); @@ -138,17 +136,17 @@ class bittorrent : public QObject{ void processDownloadedFile(QString, QString); bool loadTrackerFile(QString hash); void saveTrackerFile(QString hash); - void reloadTorrent(const torrent_handle &h); // This is protected now, call pauseAndReloadTorrent() instead + void reloadTorrent(const QTorrentHandle &h); // This is protected now, call pauseAndReloadTorrent() instead signals: void invalidTorrent(QString path); void duplicateTorrent(QString path); - void addedTorrent(QString path, torrent_handle& h, bool fastResume); - void finishedTorrent(torrent_handle& h); - void fullDiskError(torrent_handle& h); + void addedTorrent(QString path, QTorrentHandle& h, bool fastResume); + void finishedTorrent(QTorrentHandle& h); + void fullDiskError(QTorrentHandle& h); void trackerError(QString hash, QString time, QString msg); void portListeningFailure(); - void trackerAuthenticationRequired(torrent_handle& h); + void trackerAuthenticationRequired(QTorrentHandle& h); void scanDirFoundTorrents(const QStringList& pathList); void newDownloadedTorrent(QString path, QString url); void aboutToDownloadFromUrl(QString url); diff --git a/src/downloadFromURLImp.h b/src/downloadFromURLImp.h index 7d0079d76..46d7d5bbc 100644 --- a/src/downloadFromURLImp.h +++ b/src/downloadFromURLImp.h @@ -48,7 +48,7 @@ class downloadFromURL : public QDialog, private Ui::downloadFromURL{ public slots: void on_downloadButton_clicked(){ QString urls = textUrls->toPlainText(); - QStringList url_list = urls.split("\n"); + QStringList url_list = urls.split(QString::fromUtf8("\n")); QString url; QStringList url_list_cleaned; foreach(url, url_list){ diff --git a/src/misc.h b/src/misc.h index 160bf71bb..9b4a13b5b 100644 --- a/src/misc.h +++ b/src/misc.h @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -43,7 +44,7 @@ class misc : public QObject{ public: // Convert any type of variable to C++ String // convert=true will convert -1 to 0 - template static std::string toString(const T& x, bool convert=false){ + template static std::string toString(const T& x, bool convert=false) { std::ostringstream o; if(!(o< static QString toQString(const T& x, bool convert=false) { + std::ostringstream o; + if(!(o< static QByteArray toQByteArray(const T& x, bool convert=false) { + std::ostringstream o; + if(!(o< static T fromString(const std::string& s){ + template static T fromString(const std::string& s) { T x; std::istringstream i(s); - if(!(i>>x)){ + if(!(i>>x)) { throw std::runtime_error("::fromString()"); } return x; } +// template static T fromQString::fromUtf8(const QString& s) { +// T x; +// std::istringstream i((const char*)s.toUtf8()); +// if(!(i>>x)) { +// throw std::runtime_error("::fromString()"); +// } +// return x; +// } +// +// template static T fromQByteArray(const QByteArray& s) { +// T x; +// std::istringstream i((const char*)s); +// if(!(i>>x)) { +// throw std::runtime_error("::fromString()"); +// } +// return x; +// } + // return best userfriendly storage unit (B, KiB, MiB, GiB, TiB) // use Binary prefix standards from IEC 60027-2 // see http://en.wikipedia.org/wiki/Kilobyte // value must be given in bytes - static QString friendlyUnit(float val){ + static QString friendlyUnit(float val) { char tmp[MAX_CHAR_TMP]; - if(val < 0){ - return QString(tr("Unknown", "Unknown (size)")); + if(val < 0) { + return tr("Unknown", "Unknown (size)"); } const QString units[4] = {tr("B", "bytes"), tr("KiB", "kibibytes (1024 bytes)"), tr("MiB", "mebibytes (1024 kibibytes)"), tr("GiB", "gibibytes (1024 mibibytes)")}; - for(unsigned short i=0; i<5; ++i){ - if (val < 1024.){ + for(unsigned short i=0; i<5; ++i) { + if (val < 1024.) { snprintf(tmp, MAX_CHAR_TMP, "%.1f", val); - return QString(tmp) + " " + units[i]; + return QString::fromUtf8(tmp) + QString::fromUtf8(" ") + units[i]; } val /= 1024.; } snprintf(tmp, MAX_CHAR_TMP, "%.1f", val); - return QString(tmp) + " " + tr("TiB", "tebibytes (1024 gibibytes)"); + return QString::fromUtf8(tmp) + QString::fromUtf8(" ") + tr("TiB", "tebibytes (1024 gibibytes)"); } // return qBittorrent config path static QString qBittorrentPath() { QString qBtPath = QDir::homePath(); - if(qBtPath.isNull()){ + if(qBtPath.isNull()) { return QString(); } - if(qBtPath[qBtPath.length()-1] == QDir::separator()){ - qBtPath = qBtPath + ".qbittorrent" + QDir::separator(); + if(qBtPath[qBtPath.length()-1] == QDir::separator()) { + qBtPath = qBtPath + QString::fromUtf8(".qbittorrent") + QDir::separator(); }else{ - qBtPath = qBtPath + QDir::separator() + ".qbittorrent" + QDir::separator(); + qBtPath = qBtPath + QDir::separator() + QString::fromUtf8(".qbittorrent") + QDir::separator(); } // Create dir if it does not exist QDir dir(qBtPath); - if(!dir.exists()){ + if(!dir.exists()) { dir.mkpath(qBtPath); } return qBtPath; } - static bool removePath(QString path){ - qDebug((QString("file to delete:") + path).toUtf8()); - if(!QFile::remove(path)){ + static bool removePath(QString path) { + qDebug((QString::fromUtf8("file to delete:") + path).toUtf8()); + if(!QFile::remove(path)) { // Probably a folder QDir current_dir(path); - if(current_dir.exists()){ + if(current_dir.exists()) { //Remove sub items QStringList subItems = current_dir.entryList(); QString item; - foreach(item, subItems){ - if(item != "." && item != ".."){ + foreach(item, subItems) { + if(item != QString::fromUtf8(".") && item != QString::fromUtf8("..")) { qDebug("-> Removing "+(path+QDir::separator()+item).toUtf8()); removePath(path+QDir::separator()+item); } } // Remove empty folder - if(current_dir.rmdir(path)){ + if(current_dir.rmdir(path)) { return true; }else{ return false; @@ -131,53 +170,53 @@ class misc : public QObject{ return true; } - static QString findFileInDir(QString dir_path, QString fileName){ + static QString findFileInDir(QString dir_path, QString fileName) { QDir dir(dir_path); - if(dir.exists(fileName)){ + if(dir.exists(fileName)) { return dir.filePath(fileName); } QStringList subDirs = dir.entryList(QDir::Dirs); QString subdir_name; - foreach(subdir_name, subDirs){ + foreach(subdir_name, subDirs) { QString result = findFileInDir(dir.path()+QDir::separator()+subdir_name, fileName); - if(!result.isNull()){ + if(!result.isNull()) { return result; } } return QString(); } - static void fixTrackersTiers(std::vector trackers){ + static void fixTrackersTiers(std::vector trackers) { unsigned int nbTrackers = trackers.size(); - for(unsigned int i=0; i static void insertSort(QList > &list, const QPair& value, Qt::SortOrder sortOrder){ + template static void insertSort(QList > &list, const QPair& value, Qt::SortOrder sortOrder) { int i = 0; - if(sortOrder == Qt::AscendingOrder){ - while(i < list.size() and value.second > list.at(i).second){ + if(sortOrder == Qt::AscendingOrder) { + while(i < list.size() and value.second > list.at(i).second) { ++i; } }else{ - while(i < list.size() and value.second < list.at(i).second){ + while(i < list.size() and value.second < list.at(i).second) { ++i; } } list.insert(i, value); } - template static void insertSort2(QList > &list, const QPair& value, Qt::SortOrder sortOrder){ + template static void insertSort2(QList > &list, const QPair& value, Qt::SortOrder sortOrder) { int i = 0; - if(sortOrder == Qt::AscendingOrder){ - while(i < list.size() and value.first > list.at(i).first){ + if(sortOrder == Qt::AscendingOrder) { + while(i < list.size() and value.first > list.at(i).first) { ++i; } }else{ - while(i < list.size() and value.first < list.at(i).first){ + while(i < list.size() and value.first < list.at(i).first) { ++i; } } @@ -186,14 +225,14 @@ class misc : public QObject{ // Can't use template class for QString because >,< use unicode code for sorting // which is not what a human would expect when sorting strings. - static void insertSortString(QList > &list, QPair value, Qt::SortOrder sortOrder){ + static void insertSortString(QList > &list, QPair value, Qt::SortOrder sortOrder) { int i = 0; - if(sortOrder == Qt::AscendingOrder){ - while(i < list.size() and QString::localeAwareCompare(value.second, list.at(i).second) > 0){ + if(sortOrder == Qt::AscendingOrder) { + while(i < list.size() and QString::localeAwareCompare(value.second, list.at(i).second) > 0) { ++i; } }else{ - while(i < list.size() and QString::localeAwareCompare(value.second, list.at(i).second) < 0){ + while(i < list.size() and QString::localeAwareCompare(value.second, list.at(i).second) < 0) { ++i; } } @@ -202,28 +241,28 @@ class misc : public QObject{ // Take a number of seconds and return an user-friendly // time duration like "1d 2h 10m". - static QString userFriendlyDuration(const long int seconds){ - if(seconds < 0){ - return QString::QString(tr("Unknown")); + static QString userFriendlyDuration(const long int seconds) { + if(seconds < 0) { + return tr("Unknown"); } - if(seconds < 60){ + if(seconds < 60) { return tr("< 1m", "< 1 minute"); } int minutes = seconds / 60; - if(minutes < 60){ - return tr("%1m","e.g: 10minutes").arg(QString::QString(misc::toString(minutes).c_str())); + if(minutes < 60) { + return tr("%1m","e.g: 10minutes").arg(QString::QString::fromUtf8(misc::toString(minutes).c_str())); } int hours = minutes / 60; minutes = minutes - hours*60; - if(hours < 24){ - return tr("%1h%2m", "e.g: 3hours 5minutes").arg(QString(misc::toString(hours).c_str())).arg(QString(misc::toString(minutes).c_str())); + if(hours < 24) { + return tr("%1h%2m", "e.g: 3hours 5minutes").arg(QString::fromUtf8(misc::toString(hours).c_str())).arg(QString::fromUtf8(misc::toString(minutes).c_str())); } int days = hours / 24; hours = hours - days * 24; - if(days < 100){ - return tr("%1d%2h%3m", "e.g: 2days 10hours 2minutes").arg(QString(misc::toString(days).c_str())).arg(QString(misc::toString(hours).c_str())).arg(QString(misc::toString(minutes).c_str())); + if(days < 100) { + return tr("%1d%2h%3m", "e.g: 2days 10hours 2minutes").arg(QString::fromUtf8(misc::toString(days).c_str())).arg(QString::fromUtf8(misc::toString(hours).c_str())).arg(QString::fromUtf8(misc::toString(minutes).c_str())); } - return QString::QString(tr("Unknown")); + return tr("Unknown"); } }; diff --git a/src/options_imp.cpp b/src/options_imp.cpp index 2b1648d1b..75eced5fb 100644 --- a/src/options_imp.cpp +++ b/src/options_imp.cpp @@ -263,89 +263,89 @@ void options_imp::saveOptions(){ settings.beginGroup("Options"); // Main options settings.beginGroup("Main"); - settings.setValue("DLLimit", getLimits().first); - settings.setValue("UPLimit", getLimits().second); - settings.setValue("MaxConnecs", getMaxConnec()); - settings.setValue("PortRangeMin", getPorts().first); - settings.setValue("PortRangeMax", getPorts().second); - settings.setValue("ShareRatio", getRatio()); - settings.setValue("EncryptionState", getEncryptionSetting()); - settings.setValue("PeXState", !isPeXDisabled()); - settings.setValue("DHTPort", getDHTPort()); - settings.setValue("ScanDir", getScanDir()); + settings.setValue(QString::fromUtf8("DLLimit"), getLimits().first); + settings.setValue(QString::fromUtf8("UPLimit"), getLimits().second); + settings.setValue(QString::fromUtf8("MaxConnecs"), getMaxConnec()); + settings.setValue(QString::fromUtf8("PortRangeMin"), getPorts().first); + settings.setValue(QString::fromUtf8("PortRangeMax"), getPorts().second); + settings.setValue(QString::fromUtf8("ShareRatio"), getRatio()); + settings.setValue(QString::fromUtf8("EncryptionState"), getEncryptionSetting()); + settings.setValue(QString::fromUtf8("PeXState"), !isPeXDisabled()); + settings.setValue(QString::fromUtf8("DHTPort"), getDHTPort()); + settings.setValue(QString::fromUtf8("ScanDir"), getScanDir()); // End Main options settings.endGroup(); // Language options - settings.beginGroup("Language"); - settings.setValue("Locale", getLocale()); + settings.beginGroup(QString::fromUtf8("Language")); + settings.setValue(QString::fromUtf8("Locale"), getLocale()); // End Language options settings.endGroup(); // IPFilter options - settings.beginGroup("IPFilter"); + settings.beginGroup(QString::fromUtf8("IPFilter")); bool enabled = isFilteringEnabled(); - settings.setValue("Enabled", enabled); + settings.setValue(QString::fromUtf8("Enabled"), enabled); if(enabled){ - settings.setValue("File", filterFile->text()); + settings.setValue(QString::fromUtf8("File"), filterFile->text()); } // End IPFilter options settings.endGroup(); // Proxy options - settings.beginGroup("Proxy"); + settings.beginGroup(QString::fromUtf8("Proxy")); enabled = isProxyEnabled(); - settings.setValue("Enabled", enabled); + settings.setValue(QString::fromUtf8("Enabled"), enabled); if(enabled){ - settings.setValue("IP", getProxyIp()); - settings.setValue("Port", getProxyPort()); + settings.setValue(QString::fromUtf8("IP"), getProxyIp()); + settings.setValue(QString::fromUtf8("Port"), getProxyPort()); unsigned short val = getProxyType(); if(val == HTTP || val == HTTP_PW){ - settings.setValue("ProxyType", HTTP); + settings.setValue(QString::fromUtf8("ProxyType"), HTTP); }else{ - settings.setValue("ProxyType", SOCKS5); + settings.setValue(QString::fromUtf8("ProxyType"), SOCKS5); } - settings.setValue("UseProxyForTrackers", useProxyForTrackers()); - settings.setValue("UseProxyForPeers", useProxyForPeers()); - settings.setValue("UseProxyForWebseeds", useProxyForWebseeds()); - settings.setValue("UseProxyForDHT", useProxyForDHT()); + settings.setValue(QString::fromUtf8("UseProxyForTrackers"), useProxyForTrackers()); + settings.setValue(QString::fromUtf8("UseProxyForPeers"), useProxyForPeers()); + settings.setValue(QString::fromUtf8("UseProxyForWebseeds"), useProxyForWebseeds()); + settings.setValue(QString::fromUtf8("UseProxyForDHT"), useProxyForDHT()); enabled = isProxyAuthEnabled(); - settings.beginGroup("Authentication"); - settings.setValue("Enabled", enabled); + settings.beginGroup(QString::fromUtf8("Authentication")); + settings.setValue(QString::fromUtf8("Enabled"), enabled); if(enabled){ - settings.setValue("Username", getProxyUsername()); - settings.setValue("Password", getProxyPassword()); + settings.setValue(QString::fromUtf8("Username"), getProxyUsername()); + settings.setValue(QString::fromUtf8("Password"), getProxyPassword()); } settings.endGroup(); } // End Proxy options settings.endGroup(); // Misc options - settings.beginGroup("Misc"); - settings.beginGroup("TorrentAdditionDialog"); + settings.beginGroup(QString::fromUtf8("Misc")); + settings.beginGroup(QString::fromUtf8("TorrentAdditionDialog")); enabled = useAdditionDialog(); - settings.setValue("Enabled", enabled); + settings.setValue(QString::fromUtf8("Enabled"), enabled); if(!enabled){ - settings.setValue("SavePath", getSavePath()); + settings.setValue(QString::fromUtf8("SavePath"), getSavePath()); } settings.endGroup(); - settings.beginGroup("Behaviour"); - settings.setValue("ConfirmOnExit", getConfirmOnExit()); - settings.setValue("GoToSystray", getGoToSysTrayOnMinimizingWindow()); - settings.setValue("GoToSystrayOnExit", getGoToSysTrayOnExitingWindow()); - settings.setValue("SystrayIntegration", useSystrayIntegration()); + settings.beginGroup(QString::fromUtf8("Behaviour")); + settings.setValue(QString::fromUtf8("ConfirmOnExit"), getConfirmOnExit()); + settings.setValue(QString::fromUtf8("GoToSystray"), getGoToSysTrayOnMinimizingWindow()); + settings.setValue(QString::fromUtf8("GoToSystrayOnExit"), getGoToSysTrayOnExitingWindow()); + settings.setValue(QString::fromUtf8("SystrayIntegration"), useSystrayIntegration()); // End Behaviour group settings.endGroup(); - settings.setValue("PreviewProgram", getPreviewProgram()); + settings.setValue(QString::fromUtf8("PreviewProgram"), getPreviewProgram()); // End Misc options settings.endGroup(); if(getUseOSDAlways()){ - settings.setValue("OSDEnabled", 1); + settings.setValue(QString::fromUtf8("OSDEnabled"), 1); }else{ if(getUseOSDWhenHiddenOnly()){ - settings.setValue("OSDEnabled", 2); + settings.setValue(QString::fromUtf8("OSDEnabled"), 2); }else{ - settings.setValue("OSDEnabled", 0); + settings.setValue(QString::fromUtf8("OSDEnabled"), 0); } } - settings.setValue("Style", getStyle()); + settings.setValue(QString::fromUtf8("Style"), getStyle()); // End Options group settings.endGroup(); } @@ -387,39 +387,39 @@ bool options_imp::useProxyForDHT() const{ } QString options_imp::getStyle() const{ - if(radioPlastiqueStyle->isChecked()) return "Plastique"; - if(radioCleanlooksStyle->isChecked()) return "Cleanlooks"; - if(radioMotifStyle->isChecked()) return "Motif"; - if(radioCDEStyle->isChecked()) return "CDE"; - if(radioMacOSStyle->isChecked()) return "MacOS"; - if(radioWinXPStyle->isChecked()) return "WinXP"; + if(radioPlastiqueStyle->isChecked()) return QString::fromUtf8("Plastique"); + if(radioCleanlooksStyle->isChecked()) return QString::fromUtf8("Cleanlooks"); + if(radioMotifStyle->isChecked()) return QString::fromUtf8("Motif"); + if(radioCDEStyle->isChecked()) return QString::fromUtf8("CDE"); + if(radioMacOSStyle->isChecked()) return QString::fromUtf8("MacOS"); + if(radioWinXPStyle->isChecked()) return QString::fromUtf8("WinXP"); #ifdef Q_WS_WIN - return "WinXP"; + return QString::fromUtf8("WinXP"); #endif #ifdef Q_WS_MAC - return "MacOS"; + return QString::fromUtf8("MacOS"); #endif - return "Plastique"; + return QString::fromUtf8("Plastique"); } void options_imp::setStyle(QString style){ - if(style == "Cleanlooks"){ + if(style == QString::fromUtf8("Cleanlooks")){ radioCleanlooksStyle->setChecked(true); return; } - if(style == "Motif"){ + if(style == QString::fromUtf8("Motif")){ radioMotifStyle->setChecked(true); return; } - if(style == "CDE"){ + if(style == QString::fromUtf8("CDE")){ radioCDEStyle->setChecked(true); return; } - if(style == "MacOS"){ + if(style == QString::fromUtf8("MacOS")){ radioMacOSStyle->setChecked(true); return; } - if(style == "WinXP"){ + if(style == QString::fromUtf8("WinXP")){ radioWinXPStyle->setChecked(true); return; } @@ -434,10 +434,10 @@ void options_imp::loadOptions(){ QSettings settings("qBittorrent", "qBittorrent"); // Check if min port < max port checkPortsLogic(); - settings.beginGroup("Options"); + settings.beginGroup(QString::fromUtf8("Options")); // Main options - settings.beginGroup("Main"); - value = settings.value("DLLimit", -1).toInt(); + settings.beginGroup(QString::fromUtf8("Main")); + value = settings.value(QString::fromUtf8("DLLimit"), -1).toInt(); if(value < 0){ disableDLLimit->setChecked(true); spin_download->setEnabled(false); @@ -446,7 +446,7 @@ void options_imp::loadOptions(){ spin_download->setEnabled(true); spin_download->setValue(value); } - value = settings.value("UPLimit", -1).toInt(); + value = settings.value(QString::fromUtf8("UPLimit"), -1).toInt(); if(value < 0){ disableUPLimit->setChecked(true); spin_upload->setEnabled(false); @@ -455,7 +455,7 @@ void options_imp::loadOptions(){ spin_upload->setEnabled(true); spin_upload->setValue(value); } - value = settings.value("MaxConnecs", -1).toInt(); + value = settings.value(QString::fromUtf8("MaxConnecs"), -1).toInt(); if(value < 0){ disableMaxConnec->setChecked(true); spin_max_connec->setEnabled(false); @@ -464,9 +464,9 @@ void options_imp::loadOptions(){ spin_max_connec->setEnabled(true); spin_max_connec->setValue(value); } - spin_port_min->setValue(settings.value("PortRangeMin", 6881).toInt()); - spin_port_max->setValue(settings.value("PortRangeMax", 6889).toInt()); - floatValue = settings.value("ShareRatio", 0).toDouble(); + spin_port_min->setValue(settings.value(QString::fromUtf8("PortRangeMin"), 6881).toInt()); + spin_port_max->setValue(settings.value(QString::fromUtf8("PortRangeMax"), 6889).toInt()); + floatValue = settings.value(QString::fromUtf8("ShareRatio"), 0).toDouble(); if(floatValue == 0){ disableRatio->setChecked(true); spin_ratio->setEnabled(false); @@ -475,7 +475,7 @@ void options_imp::loadOptions(){ spin_ratio->setEnabled(true); spin_ratio->setValue(floatValue); } - value = settings.value("DHTPort", 6881).toInt(); + value = settings.value(QString::fromUtf8("DHTPort"), 6881).toInt(); if(value < 0){ disableDHT->setChecked(true); groupDHT->setEnabled(false); @@ -487,9 +487,9 @@ void options_imp::loadOptions(){ } spin_dht_port->setValue(value); } - value = settings.value("EncryptionState", 0).toInt(); + value = settings.value(QString::fromUtf8("EncryptionState"), 0).toInt(); comboEncryption->setCurrentIndex(value); - boolValue = settings.value("PeXState", true).toBool(); + boolValue = settings.value(QString::fromUtf8("PeXState"), true).toBool(); if(boolValue){ // Pex disabled disablePeX->setChecked(false); @@ -497,7 +497,7 @@ void options_imp::loadOptions(){ // PeX enabled disablePeX->setChecked(true); } - strValue = settings.value("ScanDir", QString()).toString(); + strValue = settings.value(QString::fromUtf8("ScanDir"), QString()).toString(); if(!strValue.isEmpty()){ enableScan_checkBox->setChecked(true); lbl_scanDir->setEnabled(true); @@ -513,15 +513,15 @@ void options_imp::loadOptions(){ // End Main options settings.endGroup(); // Language options - settings.beginGroup("Language"); - strValue = settings.value("Locale", "en_GB").toString(); + settings.beginGroup(QString::fromUtf8("Language")); + strValue = settings.value(QString::fromUtf8("Locale"), QString::fromUtf8("en_GB")).toString(); setLocale(strValue); // End Language options settings.endGroup(); // IPFilter options - settings.beginGroup("IPFilter"); - if(settings.value("Enabled", false).toBool()){ - strValue = settings.value("File", QString()).toString(); + settings.beginGroup(QString::fromUtf8("IPFilter")); + if(settings.value(QString::fromUtf8("Enabled"), false).toBool()){ + strValue = settings.value(QString::fromUtf8("File"), QString()).toString(); activateFilter->setChecked(true); filterGroup->setEnabled(true); filterFile->setText(strValue); @@ -533,9 +533,9 @@ void options_imp::loadOptions(){ // End IPFilter options settings.endGroup(); // Proxy options - settings.beginGroup("Proxy"); - if(settings.value("Enabled", false).toBool()){ - strValue = settings.value("IP", QString()).toString(); + settings.beginGroup(QString::fromUtf8("Proxy")); + if(settings.value(QString::fromUtf8("Enabled"), false).toBool()){ + strValue = settings.value(QString::fromUtf8("IP"), QString()).toString(); if(strValue.isEmpty()){ enableProxy_checkBox->setChecked(false); groupProxy->setEnabled(false); @@ -543,18 +543,18 @@ void options_imp::loadOptions(){ enableProxy_checkBox->setChecked(true); groupProxy->setEnabled(true); proxy_ip->setText(strValue); - proxy_port->setValue(settings.value("Port", 8080).toInt()); - comboProxyType->setCurrentIndex(settings.value("ProxyType", HTTP).toInt()); - checkProxyTrackers->setChecked(settings.value("useProxyForTrackers", true).toBool()); - checkProxyPeers->setChecked(settings.value("useProxyForPeers", true).toBool()); - checkProxyWebseeds->setChecked(settings.value("useProxyForWebseeds", true).toBool()); - checkProxyDHT->setChecked(settings.value("useProxyForDHT", true).toBool()); - settings.beginGroup("Authentication"); - if(settings.value("Enabled", false).toBool()){ + proxy_port->setValue(settings.value(QString::fromUtf8("Port"), 8080).toInt()); + comboProxyType->setCurrentIndex(settings.value(QString::fromUtf8("ProxyType"), HTTP).toInt()); + checkProxyTrackers->setChecked(settings.value(QString::fromUtf8("useProxyForTrackers"), true).toBool()); + checkProxyPeers->setChecked(settings.value(QString::fromUtf8("useProxyForPeers"), true).toBool()); + checkProxyWebseeds->setChecked(settings.value(QString::fromUtf8("useProxyForWebseeds"), true).toBool()); + checkProxyDHT->setChecked(settings.value(QString::fromUtf8("useProxyForDHT"), true).toBool()); + settings.beginGroup(QString::fromUtf8("Authentication")); + if(settings.value(QString::fromUtf8("Enabled"), false).toBool()){ enableProxyAuth_checkBox->setChecked(true); groupProxyAuth->setEnabled(true); - proxy_username->setText(settings.value("Username", QString()).toString()); - proxy_password->setText(settings.value("Password", QString()).toString()); + proxy_username->setText(settings.value(QString::fromUtf8("Username"), QString()).toString()); + proxy_password->setText(settings.value(QString::fromUtf8("Password"), QString()).toString()); }else{ enableProxyAuth_checkBox->setChecked(false); groupProxyAuth->setEnabled(false); @@ -568,30 +568,30 @@ void options_imp::loadOptions(){ // End Proxy options settings.endGroup(); // Misc options - settings.beginGroup("Misc"); - settings.beginGroup("TorrentAdditionDialog"); - if(settings.value("Enabled", true).toBool()){ + settings.beginGroup(QString::fromUtf8("Misc")); + settings.beginGroup(QString::fromUtf8("TorrentAdditionDialog")); + if(settings.value(QString::fromUtf8("Enabled"), true).toBool()){ checkAdditionDialog->setChecked(true); groupSavePath->setEnabled(false); }else{ checkAdditionDialog->setChecked(false); groupSavePath->setEnabled(true); - txt_savePath->setText(settings.value("SavePath", QString()).toString()); + txt_savePath->setText(settings.value(QString::fromUtf8("SavePath"), QString()).toString()); } settings.endGroup(); - settings.beginGroup("Behaviour"); - confirmExit_checkBox->setChecked(settings.value("ConfirmOnExit", true).toBool()); - check_goToSysTray->setChecked(settings.value("GoToSystray", true).toBool()); - check_closeToSysTray->setChecked(settings.value("GoToSystrayOnExit", false).toBool()); - boolValue = settings.value("SystrayIntegration", true).toBool(); + settings.beginGroup(QString::fromUtf8("Behaviour")); + confirmExit_checkBox->setChecked(settings.value(QString::fromUtf8("ConfirmOnExit"), true).toBool()); + check_goToSysTray->setChecked(settings.value(QString::fromUtf8("GoToSystray"), true).toBool()); + check_closeToSysTray->setChecked(settings.value(QString::fromUtf8("GoToSystrayOnExit"), false).toBool()); + boolValue = settings.value(QString::fromUtf8("SystrayIntegration"), true).toBool(); check_disableSystray->setChecked(!boolValue); systrayDisabled(!boolValue); // End Behaviour group settings.endGroup(); - preview_program->setText(settings.value("PreviewProgram", QString()).toString()); + preview_program->setText(settings.value(QString::fromUtf8("PreviewProgram"), QString()).toString()); // End Misc group settings.endGroup(); - value = settings.value("OSDEnabled", 1).toInt(); + value = settings.value(QString::fromUtf8("OSDEnabled"), 1).toInt(); if(value == 0){ neverOSD->setChecked(true); }else{ @@ -601,7 +601,7 @@ void options_imp::loadOptions(){ alwaysOSD->setChecked(true); } } - setStyle(settings.value("Style", QString()).toString()); + setStyle(settings.value(QString::fromUtf8("Style"), QString()).toString()); // End Options group settings.endGroup(); } @@ -716,7 +716,7 @@ QString options_imp::getSavePath() const{ home += QDir::separator(); } if(txt_savePath->text().trimmed().isEmpty()){ - txt_savePath->setText(home+"qBT_dir"); + txt_savePath->setText(home+QString::fromUtf8("qBT_dir")); } return txt_savePath->text(); } @@ -978,7 +978,7 @@ void options_imp::on_browse_button_clicked(){ void options_imp::processFilterFile(QString filePath){ qDebug("Processing filter files"); filtersList->clear(); - QString manualFilters= misc::qBittorrentPath() + "ipfilter.dat"; + QString manualFilters= misc::qBittorrentPath() + QString::fromUtf8("ipfilter.dat"); QStringList filterFiles(manualFilters); filterFiles.append(filePath); for(int i=0; i<2; ++i){ @@ -1018,8 +1018,8 @@ void options_imp::processFilterFile(QString filePath){ } // Split IP - QRegExp is_ipv6("^[0-9a-f]{4}(:[0-9a-f]{4}){7}$", Qt::CaseInsensitive, QRegExp::RegExp); - QRegExp is_ipv4("^(([0-1]?[0-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))(\\.(([0-1]?[0-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))){3}$", Qt::CaseInsensitive, QRegExp::RegExp); + QRegExp is_ipv6(QString::fromUtf8("^[0-9a-f]{4}(:[0-9a-f]{4}){7}$"), Qt::CaseInsensitive, QRegExp::RegExp); + QRegExp is_ipv4(QString::fromUtf8("^(([0-1]?[0-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))(\\.(([0-1]?[0-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))){3}$"), Qt::CaseInsensitive, QRegExp::RegExp); if(strStartIP.contains(is_ipv4) && strEndIP.contains(is_ipv4)) { // IPv4 @@ -1032,9 +1032,9 @@ void options_imp::processFilterFile(QString filePath){ QStringList item(QString(start.to_string().c_str())); item.append(QString(last.to_string().c_str())); if(!i){ - item.append("Manual"); + item.append(QString::fromUtf8("Manual")); }else{ - item.append("ipfilter.dat"); + item.append(QString::fromUtf8("ipfilter.dat")); } item.append(strComment); new QTreeWidgetItem(filtersList, item); @@ -1051,9 +1051,9 @@ void options_imp::processFilterFile(QString filePath){ QStringList item(QString(start.to_string().c_str())); item.append(QString(last.to_string().c_str())); if(!i){ - item.append("Manual"); + item.append(QString::fromUtf8("Manual")); }else{ - item.append("ipfilter.dat"); + item.append(QString::fromUtf8("ipfilter.dat")); } item.append(strComment); new QTreeWidgetItem(filtersList, item); @@ -1082,12 +1082,12 @@ void options_imp::on_addFilterRange_clicked(){ // Ask user for start ip QString startIP = QInputDialog::getText(this, tr("Range Start IP"), tr("Start IP:"), QLineEdit::Normal, - "0.0.0.0", &ok); + QString::fromUtf8("0.0.0.0"), &ok); QStringList IP1 = startIP.split('.'); // Check IP bool ipv4 = true; - QRegExp is_ipv6("^[0-9a-f]{4}(:[0-9a-f]{4}){7}$", Qt::CaseInsensitive, QRegExp::RegExp); - QRegExp is_ipv4("^(([0-1]?[0-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))(\\.(([0-1]?[0-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))){3}$", Qt::CaseInsensitive, QRegExp::RegExp); + QRegExp is_ipv6(QString::fromUtf8("^[0-9a-f]{4}(:[0-9a-f]{4}){7}$"), Qt::CaseInsensitive, QRegExp::RegExp); + QRegExp is_ipv4(QString::fromUtf8("^(([0-1]?[0-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))(\\.(([0-1]?[0-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))){3}$"), Qt::CaseInsensitive, QRegExp::RegExp); @@ -1121,12 +1121,12 @@ void options_imp::on_addFilterRange_clicked(){ // Ask user for Comment QString comment = QInputDialog::getText(this, tr("IP Range Comment"), tr("Comment:"), QLineEdit::Normal, - "", &ok); + QString::fromUtf8(""), &ok); if (!ok){ - comment = QString(""); + comment = QString::fromUtf8(""); return; } - QFile ipfilter(misc::qBittorrentPath() + "ipfilter.dat"); + QFile ipfilter(misc::qBittorrentPath() + QString::fromUtf8("ipfilter.dat")); if (!ipfilter.open(QIODevice::Append | QIODevice::WriteOnly | QIODevice::Text)){ std::cerr << "Error: Couldn't write in ipfilter.dat"; return; @@ -1146,7 +1146,7 @@ void options_imp::on_delFilterRange_clicked(){ // Delete from list for(int i=0;itext(2) == "Manual"){ + if(item->text(2) == QString::fromUtf8("Manual")){ delete item; changed = true; } @@ -1155,7 +1155,7 @@ void options_imp::on_delFilterRange_clicked(){ } } // Update ipfilter.dat - QFile ipfilter(misc::qBittorrentPath() + "ipfilter.dat"); + QFile ipfilter(misc::qBittorrentPath() + QString::fromUtf8("ipfilter.dat")); if (!ipfilter.open(QIODevice::WriteOnly | QIODevice::Text)){ std::cerr << "Error: Couldn't write in ipfilter.dat"; return; @@ -1163,7 +1163,7 @@ void options_imp::on_delFilterRange_clicked(){ QTextStream out(&ipfilter); for(int i=0; itopLevelItemCount();++i){ QTreeWidgetItem *item = filtersList->topLevelItem(i); - if(item->text(2) == "Manual"){ + if(item->text(2) == QString::fromUtf8("Manual")){ out << item->text(0) << " - " << item->text(1) << ", 0, " << item->text(3) << "\n"; } } diff --git a/src/previewSelect.h b/src/previewSelect.h index 468fe3b61..54bb0d036 100644 --- a/src/previewSelect.h +++ b/src/previewSelect.h @@ -30,6 +30,7 @@ #include "ui_preview.h" #include "PreviewListDelegate.h" #include "misc.h" +#include "qtorrenthandle.h" #define NAME 0 #define SIZE 1 @@ -44,7 +45,7 @@ class previewSelect: public QDialog, private Ui::preview { QStandardItemModel *previewListModel; PreviewListDelegate *listDelegate; QStringList supported_preview_extensions; - torrent_handle h; + QTorrentHandle h; signals: void readyToPreviewFile(QString) const; @@ -56,9 +57,9 @@ class previewSelect: public QDialog, private Ui::preview { QModelIndexList selectedIndexes = previewList->selectionModel()->selectedIndexes(); foreach(index, selectedIndexes){ if(index.column() == NAME){ - QString root_path = QString(h.save_path().string().c_str()); + QString root_path = h.save_path(); if(root_path.at(root_path.length()-1) != QDir::separator()){ - root_path += '/'; + root_path += QString::fromUtf8("/"); } // Get the file name QString fileName = index.data().toString(); @@ -68,7 +69,7 @@ class previewSelect: public QDialog, private Ui::preview { found = true; }else{ // Folder - QString folder_name = QString(h.get_torrent_info().name().c_str()); + QString folder_name = h.name(); // Will find the file even if it is in a sub directory QString result = misc::findFileInDir(root_path+folder_name, fileName); if(!result.isNull()){ @@ -90,7 +91,7 @@ class previewSelect: public QDialog, private Ui::preview { } public: - previewSelect(QWidget* parent, torrent_handle h): QDialog(parent){ + previewSelect(QWidget* parent, QTorrentHandle h): QDialog(parent){ setupUi(this); setAttribute(Qt::WA_DeleteOnClose); // Preview list @@ -101,21 +102,21 @@ class previewSelect: public QDialog, private Ui::preview { previewList->setModel(previewListModel); listDelegate = new PreviewListDelegate(this); previewList->setItemDelegate(listDelegate); - supported_preview_extensions << "AVI" << "DIVX" << "MPG" << "MPEG" << "MPE" << "MP3" << "OGG" << "WMV" << "WMA" << "RMV" << "RMVB" << "ASF" << "MOV" << "WAV" << "MP2" << "SWF" << "AC3" << "OGM" << "MP4" << "FLV" << "VOB" << "QT" << "MKV" << "AIF" << "AIFF" << "AIFC" << "MID" << "MPG" << "RA" << "RAM" << "AU" << "M4A" << "FLAC" << "M4P" << "3GP" << "AAC" << "RM" << "SWA" << "MPC" << "MPP"; + supported_preview_extensions << QString::fromUtf8("AVI") << QString::fromUtf8("DIVX") << QString::fromUtf8("MPG") << QString::fromUtf8("MPEG") << QString::fromUtf8("MPE") << QString::fromUtf8("MP3") << QString::fromUtf8("OGG") << QString::fromUtf8("WMV") << QString::fromUtf8("WMA") << QString::fromUtf8("RMV") << QString::fromUtf8("RMVB") << QString::fromUtf8("ASF") << QString::fromUtf8("MOV") << QString::fromUtf8("WAV") << QString::fromUtf8("MP2") << QString::fromUtf8("SWF") << QString::fromUtf8("AC3") << QString::fromUtf8("OGM") << QString::fromUtf8("MP4") << QString::fromUtf8("FLV") << QString::fromUtf8("VOB") << QString::fromUtf8("QT") << QString::fromUtf8("MKV") << QString::fromUtf8("AIF") << QString::fromUtf8("AIFF") << QString::fromUtf8("AIFC") << QString::fromUtf8("MID") << QString::fromUtf8("MPG") << QString::fromUtf8("RA") << QString::fromUtf8("RAM") << QString::fromUtf8("AU") << QString::fromUtf8("M4A") << QString::fromUtf8("FLAC") << QString::fromUtf8("M4P") << QString::fromUtf8("3GP") << QString::fromUtf8("AAC") << QString::fromUtf8("RM") << QString::fromUtf8("SWA") << QString::fromUtf8("MPC") << QString::fromUtf8("MPP"); previewList->header()->resizeSection(0, 200); // Fill list in this->h = h; - torrent_info torrentInfo = h.get_torrent_info(); std::vector fp; h.file_progress(fp); - for(int i=0; i= 0){ int row = previewListModel->rowCount(); previewListModel->insertRow(row); previewListModel->setData(previewListModel->index(row, NAME), QVariant(fileName)); - previewListModel->setData(previewListModel->index(row, SIZE), QVariant((qlonglong)torrentInfo.file_at(i).size)); + previewListModel->setData(previewListModel->index(row, SIZE), QVariant((qlonglong)h.filesize_at(i))); previewListModel->setData(previewListModel->index(row, PROGRESS), QVariant((double)fp[i])); } } diff --git a/src/properties_imp.cpp b/src/properties_imp.cpp index 2b20c6564..863a29a06 100644 --- a/src/properties_imp.cpp +++ b/src/properties_imp.cpp @@ -31,7 +31,7 @@ #include // Constructor -properties::properties(QWidget *parent, bittorrent *BTSession, torrent_handle &h): QDialog(parent), h(h){ +properties::properties(QWidget *parent, bittorrent *BTSession, QTorrentHandle &h): QDialog(parent), h(h){ setupUi(this); this->BTSession = BTSession; changedFilteredfiles = false; @@ -66,34 +66,32 @@ properties::properties(QWidget *parent, bittorrent *BTSession, torrent_handle &h connect(addWS_button, SIGNAL(clicked()), this, SLOT(askWebSeed())); connect(deleteWS_button, SIGNAL(clicked()), this, SLOT(deleteSelectedUrlSeeds())); // get Infos from torrent handle - fileHash = QString(misc::toString(h.info_hash()).c_str()); - torrent_status torrentStatus = h.status(); - torrent_info torrentInfo = h.get_torrent_info(); - fileName->setText(torrentInfo.name().c_str()); + hash = h.hash(); + fileName->setText(h.name()); // Torrent Infos - save_path->setText(QString(h.save_path().string().c_str())); - QString author = QString(torrentInfo.creator().c_str()).trimmed(); + save_path->setText(h.save_path()); + QString author = h.creator().trimmed(); if(author.isEmpty()) author = tr("Unknown"); creator->setText(author); - hash_lbl->setText(fileHash); - comment_txt->setText(QString(torrentInfo.comment().c_str())); + hash_lbl->setText(hash); + comment_txt->setText(h.comment()); //Trackers loadTrackers(); // Session infos char tmp[MAX_CHAR_TMP]; - failed->setText(misc::friendlyUnit(torrentStatus.total_failed_bytes)); - upTotal->setText(misc::friendlyUnit(torrentStatus.total_payload_upload)); - dlTotal->setText(misc::friendlyUnit(torrentStatus.total_payload_download)); + failed->setText(misc::friendlyUnit(h.total_failed_bytes())); + upTotal->setText(misc::friendlyUnit(h.total_payload_upload())); + dlTotal->setText(misc::friendlyUnit(h.total_payload_download())); // Update ratio info float ratio; - if(torrentStatus.total_payload_download == 0){ - if(torrentStatus.total_payload_upload == 0) + if(h.total_payload_download() == 0){ + if(h.total_payload_upload() == 0) ratio = 1.; else ratio = 10.; // Max ratio }else{ - ratio = (double)torrentStatus.total_payload_upload/(double)torrentStatus.total_payload_download; + ratio = (double)h.total_payload_upload()/(double)h.total_payload_download(); if(ratio > 10.){ ratio = 10.; } @@ -104,12 +102,12 @@ properties::properties(QWidget *parent, bittorrent *BTSession, torrent_handle &h std::vector fp; h.file_progress(fp); // List files in torrent - unsigned int nbFiles = torrentInfo.num_files(); + unsigned int nbFiles = h.num_files(); for(unsigned int i=0; irowCount(); PropListModel->insertRow(row); - PropListModel->setData(PropListModel->index(row, NAME), QVariant(torrentInfo.file_at(i).path.leaf().c_str())); - PropListModel->setData(PropListModel->index(row, SIZE), QVariant((qlonglong)torrentInfo.file_at(i).size)); + PropListModel->setData(PropListModel->index(row, NAME), QVariant(h.file_at(i))); + PropListModel->setData(PropListModel->index(row, SIZE), QVariant((qlonglong)h.filesize_at(i))); PropListModel->setData(PropListModel->index(row, PROGRESS), QVariant((double)fp[i])); } loadPiecesPriorities(); @@ -117,7 +115,7 @@ properties::properties(QWidget *parent, bittorrent *BTSession, torrent_handle &h loadWebSeedsFromFile(); loadWebSeeds(); // Incremental download - if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".incremental")){ + if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".incremental")){ incrementalDownload->setChecked(true); }else{ incrementalDownload->setChecked(false); @@ -136,12 +134,12 @@ properties::~properties(){ void properties::loadTrackersErrors(){ // Tracker Errors - QList > errors = BTSession->getTrackersErrors(fileHash); + QList > errors = BTSession->getTrackersErrors(hash); unsigned int nbTrackerErrors = errors.size(); trackerErrors->clear(); for(unsigned int i=0; i < nbTrackerErrors; ++i){ QPair pair = errors.at(i); - trackerErrors->append(""+pair.first+" - "+pair.second+""); + trackerErrors->append(QString::fromUtf8("")+pair.first+QString::fromUtf8(" - ")+pair.second+QString::fromUtf8("")); } if(!nbTrackerErrors) trackerErrors->append(tr("None", "i.e: No error message")); @@ -154,15 +152,14 @@ void properties::loadWebSeeds(){ // Add manually added url seeds foreach(url_seed, urlSeeds){ listWebSeeds->addItem(url_seed); - qDebug("Added custom url seed to list: %s", (const char*)url_seed.toUtf8()); + qDebug("Added custom url seed to list: %s", url_seed.toUtf8().data()); } } void properties::loadPiecesPriorities(){ - torrent_info torrentInfo = h.get_torrent_info(); - unsigned int nbFiles = torrentInfo.num_files(); - QString fileName = QString(torrentInfo.name().c_str()); - QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".priorities"); + unsigned int nbFiles = h.num_files(); + QString fileName = h.name(); + QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".priorities"); has_filtered_files = false; qDebug("Loading pieces priorities"); // Read saved file @@ -308,8 +305,7 @@ void properties::loadTrackers(){ for(unsigned int i=0; iaddItem(QString(trackers[i].url.c_str())); } - torrent_status torrentStatus = h.status(); - QString tracker = QString(torrentStatus.current_tracker.c_str()).trimmed(); + QString tracker = h.current_tracker().trimmed(); if(!tracker.isEmpty()){ trackerURL->setText(tracker); }else{ @@ -322,10 +318,9 @@ void properties::askWebSeed(){ // Ask user for a new url seed QString url_seed = QInputDialog::getText(this, tr("New url seed", "New HTTP source"), tr("New url seed:"), QLineEdit::Normal, - "http://www.", &ok); + QString::fromUtf8("http://www."), &ok); if(!ok) return; - torrent_info torrentInfo = h.get_torrent_info(); - qDebug("Adding %s web seed", (const char*)url_seed.toUtf8()); + qDebug("Adding %s web seed", url_seed.toUtf8().data()); if(urlSeeds.indexOf(url_seed) != -1) { QMessageBox::warning(this, tr("qBittorrent"), tr("This url seed is already in the list."), @@ -333,7 +328,7 @@ void properties::askWebSeed(){ return; } urlSeeds << url_seed; - torrentInfo.add_url_seed(url_seed.toStdString()); + h.add_url_seed(url_seed); saveWebSeeds(); // Refresh the seeds list loadWebSeeds(); @@ -351,7 +346,7 @@ void properties::askForTracker(){ if(!ok) return; // Add the tracker to the list std::vector trackers = h.trackers(); - announce_entry new_tracker(trackerUrl.toStdString()); + announce_entry new_tracker(misc::toString(trackerUrl.toUtf8().data())); new_tracker.tier = 0; // Will be fixed a bit later trackers.push_back(new_tracker); misc::fixTrackersTiers(trackers); @@ -371,7 +366,7 @@ void properties::deleteSelectedUrlSeeds(){ int index = urlSeeds.indexOf(url_seed); Q_ASSERT(index != -1); urlSeeds.removeAt(index); - h.remove_url_seed(misc::toString((const char*)url_seed.toUtf8())); + h.remove_url_seed(url_seed); change = true; } if(change){ @@ -397,7 +392,7 @@ void properties::deleteSelectedTrackers(){ foreach(item, selectedItems){ QString url = item->text(); for(unsigned int i=0; itext(); for(i=0; i 0){ @@ -481,8 +476,8 @@ void properties::updateInfos(){ std::vector fp; try{ h.file_progress(fp); - torrent_info torrentInfo = h.get_torrent_info(); - for(int i=0; isetData(PropListModel->index(i, PROGRESS), QVariant((double)fp[i])); } }catch(invalid_handle e){ @@ -490,8 +485,7 @@ void properties::updateInfos(){ close(); } // Update current tracker - torrent_status torrentStatus = h.status(); - QString tracker = QString(torrentStatus.current_tracker.c_str()).trimmed(); + QString tracker = h.current_tracker().trimmed(); if(!tracker.isEmpty()){ trackerURL->setText(tracker); }else{ @@ -501,14 +495,15 @@ void properties::updateInfos(){ // Set the color of a row in data model void properties::setRowColor(int row, QString color){ - for(int i=0; icolumnCount(); ++i){ + unsigned int nbCol = PropListModel->columnCount(); + for(unsigned int i=0; isetData(PropListModel->index(row, i), QVariant(QColor(color)), Qt::ForegroundRole); } } void properties::setAllPiecesState(unsigned short priority){ - torrent_info torrentInfo = h.get_torrent_info(); - for(int i=0; iisChecked()){ - // Create .incremental file - QFile incremental_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".incremental"); - incremental_file.open(QIODevice::WriteOnly | QIODevice::Text); - incremental_file.close(); - h.set_sequenced_download_threshold(15); + if(!QFile::exists(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".incremental"))) { + // Create .incremental file + QFile incremental_file(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".incremental")); + incremental_file.open(QIODevice::WriteOnly | QIODevice::Text); + incremental_file.close(); + h.set_sequenced_download_threshold(1); + } }else{ - QFile::remove(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".incremental"); - h.set_sequenced_download_threshold(100); + QFile::remove(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".incremental"); + h.set_sequenced_download_threshold(100); // Disabled } } @@ -539,7 +535,7 @@ void properties::on_okButton_clicked(){ } void properties::loadWebSeedsFromFile(){ - QFile urlseeds_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".urlseeds"); + QFile urlseeds_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".urlseeds"); if(!urlseeds_file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QByteArray urlseeds_lines = urlseeds_file.readAll(); urlseeds_file.close(); @@ -551,13 +547,10 @@ void properties::loadWebSeedsFromFile(){ urlSeeds << url_seed; } // Load the hard-coded url seeds - torrent_info torrentInfo = h.get_torrent_info(); - std::vector hc_seeds = torrentInfo.url_seeds(); - unsigned int nbSeeds = hc_seeds.size(); + QStringList hc_seeds = h.url_seeds(); QString hc_seed; // Add hard coded url seeds - for(unsigned int i=0; iinFullAllocationMode(fileHash)){ + if(hasFilteredFiles && !BTSession->inFullAllocationMode(hash)){ BTSession->pauseAndReloadTorrent(h); } BTSession->loadFilesPriorities(h); - emit filteredFilesChanged(fileHash); + emit filteredFilesChanged(hash); has_filtered_files = hasFilteredFiles; } diff --git a/src/properties_imp.h b/src/properties_imp.h index c1b63634a..26ea04608 100644 --- a/src/properties_imp.h +++ b/src/properties_imp.h @@ -23,7 +23,7 @@ #define PROPERTIES_H #include "ui_properties.h" -#include +#include "qtorrenthandle.h" class PropListDelegate; class QTimer; @@ -35,8 +35,8 @@ using namespace libtorrent; class properties : public QDialog, private Ui::properties{ Q_OBJECT private: - torrent_handle h; - QString fileHash; + QTorrentHandle h; + QString hash; PropListDelegate *PropDelegate; QStandardItemModel *PropListModel; QTimer *updateInfosTimer; @@ -71,12 +71,12 @@ class properties : public QDialog, private Ui::properties{ void loadTrackersErrors(); signals: - void filteredFilesChanged(QString fileHash); - void fileSizeChanged(QString fileHash); + void filteredFilesChanged(QString hash); + void fileSizeChanged(QString hash); public: // Constructor - properties(QWidget *parent, bittorrent *BTSession, torrent_handle &h); + properties(QWidget *parent, bittorrent *BTSession, QTorrentHandle &h); ~properties(); bool onlyOneItem() const; }; diff --git a/src/qtorrenthandle.cpp b/src/qtorrenthandle.cpp new file mode 100644 index 000000000..95f1806b3 --- /dev/null +++ b/src/qtorrenthandle.cpp @@ -0,0 +1,275 @@ +/* + * Bittorrent Client using Qt4 and libtorrent. + * Copyright (C) 2006 Christophe Dumez + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * Contact : chris@qbittorrent.org + */ + +#include +#include +#include +#include "misc.h" +#include "qtorrenthandle.h" + +QTorrentHandle::QTorrentHandle(torrent_handle h) : h(h) { + t = h.get_torrent_info(); + s = h.status(); +} + +// +// Getters +// + +torrent_handle QTorrentHandle::get_torrent_handle() const { + return h; +} + +torrent_info QTorrentHandle::get_torrent_info() const { + return t; +} + +QString QTorrentHandle::hash() const { + return misc::toQString(t.info_hash()); +} + +QString QTorrentHandle::name() const { + return misc::toQString(h.name()); +} + +float QTorrentHandle::progress() const { + return s.progress; +} + +QString QTorrentHandle::current_tracker() const { + return misc::toQString(s.current_tracker); +} + +bool QTorrentHandle::is_valid() const { + return h.is_valid(); +} + +bool QTorrentHandle::is_paused() const { + return h.is_paused(); +} + +size_type QTorrentHandle::total_size() const { + return t.total_size(); +} + +size_type QTorrentHandle::total_done() const { + return s.total_done; +} + +float QTorrentHandle::download_payload_rate() const { + return s.download_payload_rate; +} + +float QTorrentHandle::upload_payload_rate() const { + return s.upload_payload_rate; +} + +int QTorrentHandle::num_peers() const { + return s.num_peers; +} + +int QTorrentHandle::num_seeds() const { + return s.num_seeds; +} + +QString QTorrentHandle::save_path() const { + return misc::toQString(h.save_path().string()); +} + +fs::path QTorrentHandle::save_path_boost() const { + return h.save_path(); +} + +QStringList QTorrentHandle::url_seeds() const { + QStringList res; + std::vector existing_seeds = t.url_seeds(); + unsigned int nbSeeds = existing_seeds.size(); + QString existing_seed; + for(unsigned int i=0; i pieces_priorities_list = pieces_priorities.split('\n'); + if((unsigned int)pieces_priorities_list.size() != nbFiles+1){ + std::cerr << "* Error: Corrupted priorities file\n"; + return t.total_size(); + } + size_type effective_size = 0; + for(unsigned int i=0; i 7){ + priority = 1; + } + if(priority) + effective_size += t.file_at(i).size; + } + return effective_size; +} + +int QTorrentHandle::download_limit() const { + return h.download_limit(); +} + +int QTorrentHandle::upload_limit() const { + return h.upload_limit(); +} + +int QTorrentHandle::num_files() const { + return t.num_files(); +} + +bool QTorrentHandle::has_metadata() const { + return h.has_metadata(); +} + +entry QTorrentHandle::write_resume_data() const { + return h.write_resume_data(); +} + +QString QTorrentHandle::file_at(int index) const { + return misc::toQString(t.file_at(index).path.leaf()); +} + +size_type QTorrentHandle::filesize_at(int index) const { + return t.file_at(index).size; +} + +std::vector const& QTorrentHandle::trackers() const { + return h.trackers(); +} + +torrent_status::state_t QTorrentHandle::state() const { + return s.state; +} + +QString QTorrentHandle::creator() const { + return misc::toQString(t.creator()); +} + +QString QTorrentHandle::comment() const { + return misc::toQString(t.comment()); +} + +size_type QTorrentHandle::total_failed_bytes() const { + return s.total_failed_bytes; +} + +void QTorrentHandle::file_progress(std::vector& fp) { + return h.file_progress(fp); +} + +size_type QTorrentHandle::total_payload_download() { + return s.total_payload_download; +} + +size_type QTorrentHandle::total_payload_upload() { + return s.total_payload_upload; +} + +// +// Setters +// + +void QTorrentHandle::set_download_limit(int limit) { + h.set_download_limit(limit); +} + +void QTorrentHandle::set_upload_limit(int limit) { + h.set_upload_limit(limit); +} + +void QTorrentHandle::pause() { + h.pause(); +} + +void QTorrentHandle::resume() { + h.resume(); +} + +void QTorrentHandle::remove_url_seed(QString seed) { + h.remove_url_seed(misc::toString((const char*)seed.toUtf8())); +} + +void QTorrentHandle::add_url_seed(QString seed) { + h.add_url_seed(misc::toString((const char*)seed.toUtf8())); +} + +void QTorrentHandle::set_max_uploads(int val){ + h.set_max_uploads(val); +} + +void QTorrentHandle::prioritize_files(std::vector v) { + h.prioritize_files(v); +} + +void QTorrentHandle::set_ratio(float ratio) const { + h.set_ratio(ratio); +} + +void QTorrentHandle::replace_trackers(std::vector const& v) const { + h.replace_trackers(v); +} + +void QTorrentHandle::force_reannounce() { + h.force_reannounce(); +} + +void QTorrentHandle::set_sequenced_download_threshold(int val) { + h.set_sequenced_download_threshold(val); +} + +void QTorrentHandle::set_tracker_login(QString username, QString password){ + h.set_tracker_login(std::string(username.toUtf8().data()), std::string(password.toUtf8().data())); +} + +// +// Operators +// + +QTorrentHandle& QTorrentHandle::operator =(const torrent_handle& new_h) { + h = new_h; + t = h.get_torrent_info(); + s = h.status(); + return *this; +} + +bool QTorrentHandle::operator ==(const QTorrentHandle& new_h) const{ + QString hash = misc::toQString(t.info_hash()); + return (hash == new_h.hash()); +} diff --git a/src/qtorrenthandle.h b/src/qtorrenthandle.h new file mode 100644 index 000000000..c16ba34ba --- /dev/null +++ b/src/qtorrenthandle.h @@ -0,0 +1,111 @@ +/* + * Bittorrent Client using Qt4 and libtorrent. + * Copyright (C) 2006 Christophe Dumez + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * Contact : chris@qbittorrent.org + */ + +#ifndef QTORRENTHANDLE_H +#define QTORRENTHANDLE_H + +#include +using namespace libtorrent; + +class QString; + +// A wrapper for torrent_handle in libtorrent +// to interact well with Qt types +class QTorrentHandle { + private: + torrent_handle h; + torrent_info t; + torrent_status s; + + public: + + // + // Constructors + // + + QTorrentHandle() {} + QTorrentHandle(torrent_handle h); + + // + // Getters + // + + torrent_handle get_torrent_handle() const; + torrent_info get_torrent_info() const; + QString hash() const; + QString name() const; + float progress() const; + QString current_tracker() const; + bool is_valid() const; + bool is_paused() const; + size_type total_size() const; + size_type total_done() const; + float download_payload_rate() const; + float upload_payload_rate() const; + int num_peers() const; + int num_seeds() const; + QString save_path() const; + fs::path save_path_boost() const; + QStringList url_seeds() const; + size_type actual_size() const; + int download_limit() const; + int upload_limit() const; + int num_files() const; + bool has_metadata() const; + entry write_resume_data() const; + QString file_at(int index) const; + size_type filesize_at(int index) const; + std::vector const& trackers() const; + torrent_status::state_t state() const; + QString creator() const; + QString comment() const; + size_type total_failed_bytes() const; + void file_progress(std::vector& fp); + size_type total_payload_download(); + size_type total_payload_upload(); + + // + // Setters + // + + void set_download_limit(int limit); + void set_upload_limit(int limit); + void pause(); + void resume(); + void remove_url_seed(QString seed); + void add_url_seed(QString seed); + void set_max_uploads(int val); + void prioritize_files(std::vector v); + void set_ratio(float ratio) const; + void replace_trackers(std::vector const&) const; + void force_reannounce(); + void set_sequenced_download_threshold(int val); + void set_tracker_login(QString username, QString password); + + // + // Operators + // + + QTorrentHandle& operator =(const torrent_handle& new_h); + bool operator ==(const QTorrentHandle& new_h) const; +}; + +#endif diff --git a/src/src.pro b/src/src.pro index 8c74520a8..40457f9e4 100644 --- a/src/src.pro +++ b/src/src.pro @@ -35,6 +35,7 @@ PKGCONFIG += libtorrent libccext2 libccgnu2 QT += network xml DEFINES += QT_NO_CAST_TO_ASCII +#QT_NO_CAST_FROM_ASCII contains(DEBUG_MODE, 0){ contains(QT_VERSION, 4.2.0) { @@ -142,7 +143,8 @@ HEADERS += GUI.h misc.h options_imp.h about_imp.h \ torrentAddition.h deleteThread.h \ bittorrent.h searchEngine.h \ rss.h rss_imp.h FinishedTorrents.h \ - allocationDlg.h FinishedListDelegate.h + allocationDlg.h FinishedListDelegate.h \ + qtorrenthandle.h FORMS += MainWindow.ui options.ui about.ui \ properties.ui createtorrent.ui preview.ui \ login.ui downloadFromURL.ui addTorrentDialog.ui \ @@ -155,5 +157,6 @@ SOURCES += GUI.cpp \ bittorrent.cpp \ searchEngine.cpp \ rss_imp.cpp \ - FinishedTorrents.cpp + FinishedTorrents.cpp \ + qtorrenthandle.cpp diff --git a/src/torrentAddition.h b/src/torrentAddition.h index 29843d9f0..8d9537db6 100644 --- a/src/torrentAddition.h +++ b/src/torrentAddition.h @@ -49,7 +49,7 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{ private: QString fileName; - QString fileHash; + QString hash; QString filePath; bool fromScanDir; QString from_url; @@ -81,15 +81,15 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{ if(home[home.length()-1] != QDir::separator()){ home += QDir::separator(); } - QSettings settings("qBittorrent", "qBittorrent"); - savePathTxt->setText(settings.value("LastDirTorrentAdd", home+"qBT_dir").toString()); + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + savePathTxt->setText(settings.value(QString::fromUtf8("LastDirTorrentAdd"), home+QString::fromUtf8("qBT_dir")).toString()); } void showLoad(QString filePath, bool fromScanDir=false, QString from_url=QString::null){ this->filePath = filePath; this->fromScanDir = fromScanDir; this->from_url = from_url; - std::ifstream in((const char*)filePath.toUtf8(), std::ios_base::binary); + std::ifstream in(filePath.toUtf8().data(), std::ios_base::binary); in.unsetf(std::ios_base::skipws); try{ // Decode torrent file @@ -97,39 +97,39 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{ // Getting torrent file informations torrent_info t(e); // Setting file name - fileName = QString(t.name().c_str()); - fileHash = QString(misc::toString(t.info_hash()).c_str()); + fileName = misc::toQString(t.name()); + hash = misc::toQString(t.info_hash()); // Use left() to remove .old extension QString newFileName; - if(fileName.endsWith(".old")){ + if(fileName.endsWith(QString::fromUtf8(".old"))){ newFileName = fileName.left(fileName.size()-4); }else{ newFileName = fileName; } - fileNameLbl->setText("
    "+newFileName+"
    "); + fileNameLbl->setText(QString::fromUtf8("
    ")+newFileName+QString::fromUtf8("
    ")); // List files in torrent unsigned int nbFiles = t.num_files(); for(unsigned int i=0; irowCount(); PropListModel->insertRow(row); - PropListModel->setData(PropListModel->index(row, NAME), QVariant(t.file_at(i).path.leaf().c_str())); + PropListModel->setData(PropListModel->index(row, NAME), QVariant(misc::toQString(t.file_at(i).path.leaf()))); PropListModel->setData(PropListModel->index(row, SIZE), QVariant((qlonglong)t.file_at(i).size)); PropListModel->setData(PropListModel->index(i, PRIORITY), QVariant(NORMAL)); - setRowColor(i, "green"); + setRowColor(i, QString::fromUtf8("green")); } }catch (invalid_torrent_file&){ // Raised by torrent_info constructor // Display warning to tell user we can't decode the torrent file if(!from_url.isNull()){ - emit setInfoBarGUI(tr("Unable to decode torrent file:")+" '"+from_url+"'", "red"); + emit setInfoBarGUI(tr("Unable to decode torrent file:")+QString::fromUtf8(" '")+from_url+QString::fromUtf8("'"), QString::fromUtf8("red")); }else{ - emit setInfoBarGUI(tr("Unable to decode torrent file:")+" '"+filePath+"'", "red"); + emit setInfoBarGUI(tr("Unable to decode torrent file:")+QString::fromUtf8(" '")+filePath+QString::fromUtf8("'"), QString::fromUtf8("red")); } - emit setInfoBarGUI(tr("This file is either corrupted or this isn't a torrent."), "red"); + emit setInfoBarGUI(tr("This file is either corrupted or this isn't a torrent."), QString::fromUtf8("red")); if(fromScanDir){ // Remove .corrupt file in case it already exists - QFile::remove(filePath+".corrupt"); + QFile::remove(filePath+QString::fromUtf8(".corrupt")); //Rename file extension so that it won't display error message more than once - QFile::rename(filePath,filePath+".corrupt"); + QFile::rename(filePath,filePath+QString::fromUtf8(".corrupt")); } close(); } @@ -137,16 +137,16 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{ std::cerr << "Could not decode file, reason: " << e.what() << '\n'; // Display warning to tell user we can't decode the torrent file if(!from_url.isNull()){ - emit setInfoBarGUI(tr("Unable to decode torrent file:")+" '"+from_url+"'", "red"); + emit setInfoBarGUI(tr("Unable to decode torrent file:")+QString::fromUtf8(" '")+from_url+QString::fromUtf8("'"), QString::fromUtf8("red")); }else{ - emit setInfoBarGUI(tr("Unable to decode torrent file:")+" '"+filePath+"'", "red"); + emit setInfoBarGUI(tr("Unable to decode torrent file:")+QString::fromUtf8(" '")+filePath+QString::fromUtf8("'"), QString::fromUtf8("red")); } - emit setInfoBarGUI(tr("This file is either corrupted or this isn't a torrent."), "red"); + emit setInfoBarGUI(tr("This file is either corrupted or this isn't a torrent."), QString::fromUtf8("red")); if(fromScanDir){ // Remove .corrupt file in case it already exists - QFile::remove(filePath+".corrupt"); + QFile::remove(filePath+QString::fromUtf8(".corrupt")); //Rename file extension so that it won't display error message more than once - QFile::rename(filePath,filePath+".corrupt"); + QFile::rename(filePath,filePath+QString::fromUtf8(".corrupt")); } close(); } @@ -227,7 +227,7 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{ PropListModel->setData(index, QVariant(IGNORED)); } for(int i=0; icolumnCount(); ++i){ - PropListModel->setData(PropListModel->index(index.row(), i), QVariant(QColor("red")), Qt::ForegroundRole); + PropListModel->setData(PropListModel->index(index.row(), i), QVariant(QColor(QString::fromUtf8("red"))), Qt::ForegroundRole); } } } @@ -240,7 +240,7 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{ PropListModel->setData(index, QVariant(NORMAL)); } for(int i=0; icolumnCount(); ++i){ - PropListModel->setData(PropListModel->index(index.row(), i), QVariant(QColor("green")), Qt::ForegroundRole); + PropListModel->setData(PropListModel->index(index.row(), i), QVariant(QColor(QString::fromUtf8("green"))), Qt::ForegroundRole); } } } @@ -266,14 +266,14 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{ PropListModel->setData(index, QVariant(MAXIMUM)); } for(int i=0; icolumnCount(); ++i){ - PropListModel->setData(PropListModel->index(index.row(), i), QVariant(QColor("green")), Qt::ForegroundRole); + PropListModel->setData(PropListModel->index(index.row(), i), QVariant(QColor(QString::fromUtf8("green"))), Qt::ForegroundRole); } } } void savePiecesPriorities(){ qDebug("Saving pieces priorities"); - QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".priorities"); + QFile pieces_file(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".priorities")); // First, remove old file pieces_file.remove(); // Write new files @@ -285,7 +285,7 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{ for(unsigned int i=0; iitem(i, PRIORITY); unsigned short priority = item->text().toInt(); - pieces_file.write(QByteArray((misc::toString(priority)+"\n").c_str())); + pieces_file.write((misc::toQByteArray(priority)+misc::toQByteArray("\n"))); } pieces_file.close(); } @@ -304,28 +304,28 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{ } } // Save savepath - QFile savepath_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".savepath"); + QFile savepath_file(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".savepath")); savepath_file.open(QIODevice::WriteOnly | QIODevice::Text); savepath_file.write(savePath.path().toUtf8()); savepath_file.close(); // Save last dir to remember it - QSettings settings("qBittorrent", "qBittorrent"); - settings.setValue("LastDirTorrentAdd", savePathTxt->text()); + QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); + settings.setValue(QString::fromUtf8("LastDirTorrentAdd"), savePathTxt->text()); // Create .incremental file if necessary if(checkIncrementalDL->isChecked()){ - QFile incremental_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".incremental"); + QFile incremental_file(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".incremental")); incremental_file.open(QIODevice::WriteOnly | QIODevice::Text); incremental_file.close(); }else{ - QFile::remove(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".incremental"); + QFile::remove(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".incremental")); } // Create .paused file if necessary if(addInPause->isChecked()){ - QFile paused_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".paused"); + QFile paused_file(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".paused")); paused_file.open(QIODevice::WriteOnly | QIODevice::Text); paused_file.close(); }else{ - QFile::remove(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".paused"); + QFile::remove(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".paused")); } // Check if there is at least one selected file if(!hasSelectedFiles()){ diff --git a/src/trackerLogin.h b/src/trackerLogin.h index cb834af01..934ebf4ed 100644 --- a/src/trackerLogin.h +++ b/src/trackerLogin.h @@ -26,6 +26,7 @@ #include #include #include "ui_login.h" +#include "qtorrenthandle.h" using namespace libtorrent; @@ -33,34 +34,34 @@ class trackerLogin : public QDialog, private Ui::authentication{ Q_OBJECT private: - torrent_handle h; + QTorrentHandle h; public: - trackerLogin(QWidget *parent, torrent_handle h): QDialog(parent){ + trackerLogin(QWidget *parent, QTorrentHandle h): QDialog(parent){ setupUi(this); setAttribute(Qt::WA_DeleteOnClose); login_logo->setPixmap(QPixmap(QString::fromUtf8(":/Icons/encrypted.png"))); this->h = h; - tracker_url->setText(QString(h.status().current_tracker.c_str())); - connect(this, SIGNAL(trackerLoginCancelled(QPair)), parent, SLOT(addUnauthenticatedTracker(QPair))); + tracker_url->setText(h.current_tracker()); + connect(this, SIGNAL(trackerLoginCancelled(QPair)), parent, SLOT(addUnauthenticatedTracker(QPair))); show(); } ~trackerLogin(){} signals: - void trackerLoginCancelled(QPair tracker); + void trackerLoginCancelled(QPair tracker); public slots: void on_loginButton_clicked(){ // login - h.set_tracker_login(std::string((const char*)lineUsername->text().toUtf8()), std::string((const char*)linePasswd->text().toUtf8())); + h.set_tracker_login(lineUsername->text(), linePasswd->text()); close(); } void on_cancelButton_clicked(){ // Emit a signal to GUI to stop asking for authentication - emit trackerLoginCancelled(QPair(h, h.status().current_tracker)); + emit trackerLoginCancelled(QPair(h, h.current_tracker())); close(); } };