- Big code cleanup

- Added a Qwrapper for torrent_handle to make code more readable
This commit is contained in:
Christophe Dumez 2007-08-20 06:29:18 +00:00
parent 5946f20783
commit c9925eddb6
24 changed files with 1560 additions and 1201 deletions

3
TODO
View file

@ -46,7 +46,7 @@
- update sorting when a new torrent is added? - update sorting when a new torrent is added?
- Keep documention up to date - Keep documention up to date
- Windows port (Chris - Peerkoel) - Windows port (Chris - Peerkoel)
- wait for fastresume data on exit should be in a thread? - write a patch for file_priority(int index);
* beta5 * beta5
- Translations update (IN PROGRESS) - Translations update (IN PROGRESS)
- Wait for some bug fixes in libtorrent : - 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: Allow to remove url seeds, even hard-coded ones
- FEATURE: Improved code for handling of finished torrents - FEATURE: Improved code for handling of finished torrents
- FEATURE: Optimized download list refreshing a little - 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 saving fast resume data on exit
- BUGFIX: Wait for torrent_paused_alert before reloading a torrent for full allocation mode - BUGFIX: Wait for torrent_paused_alert before reloading a torrent for full allocation mode
- BUFFIG: Fixed overflow causing ratio data to be negative - BUFFIG: Fixed overflow causing ratio data to be negative

View file

@ -67,14 +67,14 @@ class DLListDelegate: public QItemDelegate {
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
float speed = index.data().toDouble(); float speed = index.data().toDouble();
snprintf(tmp, MAX_CHAR_TMP, "%.1f", speed/1024.); 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; break;
} }
case RATIO:{ case RATIO:{
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
float ratio = index.data().toDouble(); float ratio = index.data().toDouble();
snprintf(tmp, MAX_CHAR_TMP, "%.1f", ratio); 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; break;
} }
case PROGRESS:{ case PROGRESS:{
@ -83,7 +83,7 @@ class DLListDelegate: public QItemDelegate {
progress = index.data().toDouble()*100.; progress = index.data().toDouble()*100.;
snprintf(tmp, MAX_CHAR_TMP, "%.1f", progress); snprintf(tmp, MAX_CHAR_TMP, "%.1f", progress);
newopt.rect = opt.rect; newopt.rect = opt.rect;
newopt.text = QString(tmp)+"%"; newopt.text = QString::fromUtf8(tmp)+QString::fromUtf8("%");
newopt.progress = (int)progress; newopt.progress = (int)progress;
newopt.maximum = 100; newopt.maximum = 100;
newopt.minimum = 0; newopt.minimum = 0;

View file

@ -60,14 +60,14 @@ class FinishedListDelegate: public QItemDelegate {
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
float speed = index.data().toDouble(); float speed = index.data().toDouble();
snprintf(tmp, MAX_CHAR_TMP, "%.1f", speed/1024.); 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; break;
} }
case F_RATIO:{ case F_RATIO:{
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
float ratio = index.data().toDouble(); float ratio = index.data().toDouble();
snprintf(tmp, MAX_CHAR_TMP, "%.1f", ratio); 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; break;
} }
case F_PROGRESS:{ case F_PROGRESS:{
@ -76,7 +76,7 @@ class FinishedListDelegate: public QItemDelegate {
progress = index.data().toDouble()*100.; progress = index.data().toDouble()*100.;
snprintf(tmp, MAX_CHAR_TMP, "%.1f", progress); snprintf(tmp, MAX_CHAR_TMP, "%.1f", progress);
newopt.rect = opt.rect; newopt.rect = opt.rect;
newopt.text = QString(tmp)+"%"; newopt.text = QString::fromUtf8(tmp)+QString::fromUtf8("%");
newopt.progress = (int)progress; newopt.progress = (int)progress;
newopt.maximum = 100; newopt.maximum = 100;
newopt.minimum = 0; newopt.minimum = 0;

View file

@ -78,14 +78,14 @@ void FinishedTorrents::addFinishedTorrent(QString hash){
int row = getRowFromHash(hash); int row = getRowFromHash(hash);
if(row != -1) return; if(row != -1) return;
row = finishedListModel->rowCount(); row = finishedListModel->rowCount();
torrent_handle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = BTSession->getTorrentHandle(hash);
// Adding torrent to download list // Adding torrent to download list
finishedListModel->insertRow(row); finishedListModel->insertRow(row);
finishedListModel->setData(finishedListModel->index(row, F_NAME), QVariant(h.name().c_str())); finishedListModel->setData(finishedListModel->index(row, F_NAME), QVariant(h.name()));
finishedListModel->setData(finishedListModel->index(row, F_SIZE), QVariant((qlonglong)h.get_torrent_info().total_size())); 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_UPSPEED), QVariant((double)0.));
finishedListModel->setData(finishedListModel->index(row, F_SEEDSLEECH), QVariant("0/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_HASH), QVariant(hash));
finishedListModel->setData(finishedListModel->index(row, F_PROGRESS), QVariant((double)1.)); finishedListModel->setData(finishedListModel->index(row, F_PROGRESS), QVariant((double)1.));
if(h.is_paused()) { if(h.is_paused()) {
@ -101,7 +101,7 @@ void FinishedTorrents::addFinishedTorrent(QString hash){
finished_file.close(); finished_file.close();
// Update the number of finished torrents // Update the number of finished torrents
++nbFinished; ++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 // Set the color of a row in data model
@ -138,7 +138,7 @@ void FinishedTorrents::saveColWidthFinishedList() const{
QStringList width_list; QStringList width_list;
unsigned int nbColumns = finishedListModel->columnCount()-1; unsigned int nbColumns = finishedListModel->columnCount()-1;
for(unsigned int i=0; i<nbColumns; ++i){ for(unsigned int i=0; i<nbColumns; ++i){
width_list << QString(misc::toString(finishedList->columnWidth(i)).c_str()); width_list << QString::fromUtf8(misc::toString(finishedList->columnWidth(i)).c_str());
} }
settings.setValue("FinishedListColsWidth", width_list.join(" ")); settings.setValue("FinishedListColsWidth", width_list.join(" "));
qDebug("Finished list columns width saved"); qDebug("Finished list columns width saved");
@ -162,12 +162,11 @@ void FinishedTorrents::updateFinishedList(){
QString hash; QString hash;
QStringList finishedSHAs = BTSession->getFinishedTorrents(); QStringList finishedSHAs = BTSession->getFinishedTorrents();
foreach(hash, finishedSHAs){ foreach(hash, finishedSHAs){
torrent_handle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = BTSession->getTorrentHandle(hash);
if(!h.is_valid()){ if(!h.is_valid()){
qDebug("Problem: This torrent is not valid in finished list"); qDebug("Problem: This torrent is not valid in finished list");
continue; continue;
} }
torrent_status torrentStatus = h.status();
int row = getRowFromHash(hash); int row = getRowFromHash(hash);
if(row == -1){ if(row == -1){
qDebug("Cannot find torrent in finished list, adding it"); qDebug("Cannot find torrent in finished list, adding it");
@ -175,8 +174,8 @@ void FinishedTorrents::updateFinishedList(){
continue; continue;
} }
if(h.is_paused()) continue; if(h.is_paused()) continue;
Q_ASSERT(torrentStatus.progress <= 1. && torrentStatus.progress >= 0.); Q_ASSERT(h.progress() <= 1. && h.progress() >= 0.);
if(torrentStatus.state == torrent_status::downloading || (torrentStatus.state != torrent_status::checking_files && torrentStatus.state != torrent_status::queued_for_checking && torrentStatus.progress < 1.)) { 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! // What are you doing here? go back to download tab!
qDebug("Info: a torrent was moved from finished to download tab"); qDebug("Info: a torrent was moved from finished to download tab");
deleteFromFinishedList(hash); deleteFromFinishedList(hash);
@ -184,9 +183,9 @@ void FinishedTorrents::updateFinishedList(){
emit torrentMovedFromFinishedList(h); emit torrentMovedFromFinishedList(h);
continue; continue;
} }
finishedListModel->setData(finishedListModel->index(row, F_UPSPEED), QVariant((double)torrentStatus.upload_payload_rate)); finishedListModel->setData(finishedListModel->index(row, F_UPSPEED), QVariant((double)h.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_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(QString(misc::toString(BTSession->getRealRatio(hash)).c_str()))); 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); finishedListModel->removeRow(row);
QFile::remove(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".finished"); QFile::remove(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".finished");
--nbFinished; --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); BTSession->setUnfinishedTorrent(hash);
} }
@ -222,17 +221,18 @@ QStandardItemModel* FinishedTorrents::getFinishedListModel(){
// Show torrent properties dialog // Show torrent properties dialog
void FinishedTorrents::showProperties(const QModelIndex &index){ void FinishedTorrents::showProperties(const QModelIndex &index){
int row = index.row(); int row = index.row();
QString fileHash = finishedListModel->data(finishedListModel->index(row, F_HASH)).toString(); QString hash = finishedListModel->data(finishedListModel->index(row, F_HASH)).toString();
torrent_handle h = BTSession->getTorrentHandle(fileHash); QTorrentHandle h = BTSession->getTorrentHandle(hash);
properties *prop = new properties(this, BTSession, h); 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))); connect(prop, SIGNAL(filteredFilesChanged(QString)), this, SLOT(updateFileSize(QString)));
prop->show(); prop->show();
} }
void FinishedTorrents::updateFileSize(QString hash){ void FinishedTorrents::updateFileSize(QString hash){
int row = getRowFromHash(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 // display properties of selected items
@ -256,13 +256,13 @@ void FinishedTorrents::displayFinishedListMenu(const QPoint& pos){
foreach(index, selectedIndexes){ foreach(index, selectedIndexes){
if(index.column() == F_NAME){ if(index.column() == F_NAME){
// Get the file name // Get the file name
QString fileHash = finishedListModel->data(finishedListModel->index(index.row(), F_HASH)).toString(); QString hash = finishedListModel->data(finishedListModel->index(index.row(), F_HASH)).toString();
torrent_handle h = BTSession->getTorrentHandle(fileHash); QTorrentHandle h = BTSession->getTorrentHandle(hash);
myFinishedListMenu.addAction(actionDelete); myFinishedListMenu.addAction(actionDelete);
myFinishedListMenu.addAction(actionDelete_Permanently); myFinishedListMenu.addAction(actionDelete_Permanently);
myFinishedListMenu.addAction(actionSet_upload_limit); myFinishedListMenu.addAction(actionSet_upload_limit);
myFinishedListMenu.addAction(actionTorrent_Properties); 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); myFinishedListMenu.addAction(actionPreview_file);
} }
break; break;

View file

@ -24,7 +24,7 @@
#include "ui_seeding.h" #include "ui_seeding.h"
#include "FinishedListDelegate.h" #include "FinishedListDelegate.h"
#include <libtorrent/torrent_handle.hpp> #include "qtorrenthandle.h"
class QStandardItemModel; class QStandardItemModel;
class bittorrent; class bittorrent;
@ -68,7 +68,7 @@ class FinishedTorrents : public QWidget, public Ui::seeding{
void on_actionSet_upload_limit_triggered(); void on_actionSet_upload_limit_triggered();
signals: signals:
void torrentMovedFromFinishedList(torrent_handle); void torrentMovedFromFinishedList(QTorrentHandle);
}; };

File diff suppressed because it is too large Load diff

View file

@ -24,9 +24,9 @@
#include <QProcess> #include <QProcess>
#include <QSystemTrayIcon> #include <QSystemTrayIcon>
#include <libtorrent/torrent_handle.hpp>
#include "ui_MainWindow.h" #include "ui_MainWindow.h"
#include "qtorrenthandle.h"
class bittorrent; class bittorrent;
class createtorrent; class createtorrent;
@ -46,9 +46,6 @@ class previewSelect;
class options_imp; class options_imp;
class QStandardItemModel; class QStandardItemModel;
using namespace libtorrent;
namespace fs = boost::filesystem;
class GUI : public QMainWindow, private Ui::MainWindow{ class GUI : public QMainWindow, private Ui::MainWindow{
Q_OBJECT Q_OBJECT
@ -56,7 +53,7 @@ class GUI : public QMainWindow, private Ui::MainWindow{
// Bittorrent // Bittorrent
bittorrent *BTSession; bittorrent *BTSession;
QTimer *checkConnect; QTimer *checkConnect;
QList<QPair<torrent_handle,std::string> > unauthenticated_trackers; QList<QPair<QTorrentHandle,QString> > unauthenticated_trackers;
downloadFromURL *downloadFromURLDialog; downloadFromURL *downloadFromURLDialog;
// GUI related // GUI related
options_imp *options; options_imp *options;
@ -135,7 +132,7 @@ class GUI : public QMainWindow, private Ui::MainWindow{
void on_actionTorrent_Properties_triggered(); void on_actionTorrent_Properties_triggered();
void on_actionPause_triggered(); void on_actionPause_triggered();
void on_actionPause_All_triggered(); void on_actionPause_All_triggered();
void restoreInDownloadList(torrent_handle h); void restoreInDownloadList(QTorrentHandle h);
void on_actionStart_triggered(); void on_actionStart_triggered();
void on_actionStart_All_triggered(); void on_actionStart_All_triggered();
void on_actionOpen_triggered(); void on_actionOpen_triggered();
@ -149,7 +146,7 @@ class GUI : public QMainWindow, private Ui::MainWindow{
void checkConnectionStatus(); void checkConnectionStatus();
void configureSession(bool deleteOptions); void configureSession(bool deleteOptions);
void processParams(const QStringList& params); void processParams(const QStringList& params);
void addUnauthenticatedTracker(QPair<torrent_handle,std::string> tracker); void addUnauthenticatedTracker(QPair<QTorrentHandle,QString> tracker);
void processScannedFiles(const QStringList& params); void processScannedFiles(const QStringList& params);
void processDownloadedFiles(QString path, QString url); void processDownloadedFiles(QString path, QString url);
void downloadFromURLList(const QStringList& urls); void downloadFromURLList(const QStringList& urls);
@ -165,13 +162,13 @@ class GUI : public QMainWindow, private Ui::MainWindow{
public slots: public slots:
void torrentAdded(QString path, torrent_handle& h, bool fastResume); void torrentAdded(QString path, QTorrentHandle& h, bool fastResume);
void torrentDuplicate(QString path); void torrentDuplicate(QString path);
void torrentCorrupted(QString path); void torrentCorrupted(QString path);
void finishedTorrent(torrent_handle& h); void finishedTorrent(QTorrentHandle& h);
void fullDiskError(torrent_handle& h); void fullDiskError(QTorrentHandle& h);
void portListeningFailure(); void portListeningFailure();
void trackerAuthenticationRequired(torrent_handle& h); void trackerAuthenticationRequired(QTorrentHandle& h);
void setTabText(int index, QString text); void setTabText(int index, QString text);
void updateFileSizeAndProgress(QString hash); void updateFileSizeAndProgress(QString hash);
void sortProgressColumnDelayed(); void sortProgressColumnDelayed();

View file

@ -54,25 +54,18 @@ class PreviewListDelegate: public QItemDelegate {
QItemDelegate::drawDisplay(painter, opt, option.rect, misc::friendlyUnit(index.data().toLongLong())); QItemDelegate::drawDisplay(painter, opt, option.rect, misc::friendlyUnit(index.data().toLongLong()));
break; break;
case PROGRESS:{ case PROGRESS:{
QPalette::ColorGroup cg = option.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled;
float progress = index.data().toDouble()*100.; float progress = index.data().toDouble()*100.;
snprintf(tmp, MAX_CHAR_TMP, "%.1f", progress); snprintf(tmp, MAX_CHAR_TMP, "%.1f", progress);
QStyleOptionProgressBarV2 newopt; QStyleOptionProgressBarV2 newopt;
newopt.rect = opt.rect; newopt.rect = opt.rect;
newopt.text = QString(tmp)+"%"; newopt.text = QString::fromUtf8(tmp)+QString::fromUtf8("%");
newopt.progress = (int)progress; newopt.progress = (int)progress;
newopt.maximum = 100; newopt.maximum = 100;
newopt.minimum = 0; newopt.minimum = 0;
newopt.state |= QStyle::State_Enabled; newopt.state |= QStyle::State_Enabled;
newopt.textVisible = false; newopt.textVisible = true;
QApplication::style()->drawControl(QStyle::CE_ProgressBar, &newopt, QApplication::style()->drawControl(QStyle::CE_ProgressBar, &newopt,
painter); 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; break;
} }
default: default:

View file

@ -71,7 +71,7 @@ class PropListDelegate: public QItemDelegate {
float progress = index.data().toDouble()*100.; float progress = index.data().toDouble()*100.;
snprintf(tmp, MAX_CHAR_TMP, "%.1f", progress); snprintf(tmp, MAX_CHAR_TMP, "%.1f", progress);
newopt.rect = opt.rect; newopt.rect = opt.rect;
newopt.text = QString(tmp)+"%"; newopt.text = QString::fromUtf8(tmp)+QString::fromUtf8("%");
newopt.progress = (int)progress; newopt.progress = (int)progress;
newopt.maximum = 100; newopt.maximum = 100;
newopt.minimum = 0; newopt.minimum = 0;
@ -106,7 +106,7 @@ class PropListDelegate: public QItemDelegate {
painter); painter);
opt.palette.setColor(QPalette::Text, QColor("black")); opt.palette.setColor(QPalette::Text, QColor("black"));
painter->setPen(opt.palette.color(cg, QPalette::Text)); 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; break;
} }
default: default:
@ -175,9 +175,9 @@ class PropListDelegate: public QItemDelegate {
qDebug("Setting combobox value in index: %d", value); qDebug("Setting combobox value in index: %d", value);
QString color; QString color;
if(value) { if(value) {
color = "green"; color = QString::fromUtf8("green");
} else { } else {
color = "red"; color = QString::fromUtf8("red");
} }
unsigned short old_val = index.model()->data(index, Qt::DisplayRole).toInt(); unsigned short old_val = index.model()->data(index, Qt::DisplayRole).toInt();
switch(value){ switch(value){

View file

@ -36,18 +36,18 @@ class about : public QDialog, private Ui::AboutDlg{
logo->setPixmap(QPixmap(QString::fromUtf8(":/Icons/qbittorrent22.png"))); logo->setPixmap(QPixmap(QString::fromUtf8(":/Icons/qbittorrent22.png")));
mascot_lbl->setPixmap(QPixmap(QString::fromUtf8(":/Icons/mascot.png"))); mascot_lbl->setPixmap(QPixmap(QString::fromUtf8(":/Icons/mascot.png")));
//Title //Title
lb_name->setText("<b><h1>"+tr("qBittorrent")+" "VERSION"</h1></b>"); lb_name->setText(QString::fromUtf8("<b><h1>")+tr("qBittorrent")+QString::fromUtf8(" "VERSION"</h1></b>"));
// Thanks // Thanks
te_thanks->append("<a name='top'></a>"); te_thanks->append(QString::fromUtf8("<a name='top'></a>"));
te_thanks->append("<ul><li>I would like to thank sourceforge.net for hosting qBittorrent project.</li>"); te_thanks->append(QString::fromUtf8("<ul><li>I would like to thank sourceforge.net for hosting qBittorrent project.</li>"));
te_thanks->append(QString::fromUtf8("<li>I am happy that Arnaud Demaizière joined the project as a programmer. His help is greatly appreciated</li>")); te_thanks->append(QString::fromUtf8("<li>I am happy that Arnaud Demaizière joined the project as a programmer. His help is greatly appreciated</li>"));
te_thanks->append("<li>I also want to thank Jeffery Fernandez (jeffery@qbittorrent.org), project consultant, webdevelopper and RPM packager, for his help.</li>"); te_thanks->append(QString::fromUtf8("<li>I also want to thank Jeffery Fernandez (jeffery@qbittorrent.org), project consultant, webdevelopper and RPM packager, for his help.</li>"));
te_thanks->append("<li>I am gratefull to Peter Koeleman (peter@qbittorrent.org) who is helping port qBittorrent to Windows.</li>"); te_thanks->append(QString::fromUtf8("<li>I am gratefull to Peter Koeleman (peter@qbittorrent.org) who is helping port qBittorrent to Windows.</li>"));
te_thanks->append(QString::fromUtf8("<li>Thanks a lot to our graphist Mateusz Toboła (tobejodok@qbittorrent.org) for his great work.</li></ul><br><br>")); te_thanks->append(QString::fromUtf8("<li>Thanks a lot to our graphist Mateusz Toboła (tobejodok@qbittorrent.org) for his great work.</li></ul><br><br>"));
te_thanks->scrollToAnchor("top"); te_thanks->scrollToAnchor(QString::fromUtf8("top"));
// Translation // Translation
te_translation->append("<a name='top'></a>"); te_translation->append(QString::fromUtf8("<a name='top'></a>"));
te_translation->append(tr("I would like to thank the following people who volunteered to translate qBittorrent:")+"<br>"); te_translation->append(tr("I would like to thank the following people who volunteered to translate qBittorrent:")+QString::fromUtf8("<br>"));
te_translation->append(QString::fromUtf8( te_translation->append(QString::fromUtf8(
"<i>- <u>Brazilian:</u> Nick Marinho (nickmarinho@gmail.com)<br>\ "<i>- <u>Brazilian:</u> Nick Marinho (nickmarinho@gmail.com)<br>\
- <u>Bulgarian:</u> Tsvetan & Boiko Bankov (emerge_life@users.sourceforge.net)<br>\ - <u>Bulgarian:</u> Tsvetan & Boiko Bankov (emerge_life@users.sourceforge.net)<br>\
@ -74,10 +74,10 @@ class about : public QDialog, private Ui::AboutDlg{
- <u>Turkish:</u> Erdem Bingöl (erdem84@gmail.com)<br>\ - <u>Turkish:</u> Erdem Bingöl (erdem84@gmail.com)<br>\
- <u>Ukrainian:</u> Andrey Shpachenko (masterfix@users.sourceforge.net)<br><br>")); - <u>Ukrainian:</u> Andrey Shpachenko (masterfix@users.sourceforge.net)<br><br>"));
te_translation->append(tr("Please contact me if you would like to translate qBittorrent into your own language.")); 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 // License
te_license->append("<a name='top'></a>"); te_license->append(QString::fromUtf8("<a name='top'></a>"));
te_license->append("<center><b>GNU GENERAL PUBLIC LICENSE</b></center><br>\ te_license->append(QString::fromUtf8("<center><b>GNU GENERAL PUBLIC LICENSE</b></center><br>\
<center>Version 2, June 1991</center><br>\ <center>Version 2, June 1991</center><br>\
Copyright (C) 1989, 1991 Free Software Foundation, Inc.<br>\ Copyright (C) 1989, 1991 Free Software Foundation, Inc.<br>\
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA<br>\ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA<br>\
@ -410,8 +410,8 @@ class about : public QDialog, private Ui::AboutDlg{
proprietary programs. If your program is a subroutine library, you may<br>\ proprietary programs. If your program is a subroutine library, you may<br>\
consider it more useful to permit linking proprietary applications with the<br>\ consider it more useful to permit linking proprietary applications with the<br>\
library. If this is what you want to do, use the GNU Library General<br>\ library. If this is what you want to do, use the GNU Library General<br>\
Public License instead of this License.<br>"); Public License instead of this License.<br>"));
te_license->scrollToAnchor("top"); te_license->scrollToAnchor(QString::fromUtf8("top"));
show(); show();
} }
}; };

View file

@ -55,7 +55,7 @@ class BandwidthAllocationDialog : public QDialog, private Ui_bandwidth_dlg {
int val = 0; int val = 0;
int max = -1; int max = -1;
if(nbTorrents == 1){ if(nbTorrents == 1){
torrent_handle h = BTSession->getTorrentHandle(hashes.at(0)); QTorrentHandle h = BTSession->getTorrentHandle(hashes.at(0));
if(uploadMode){ if(uploadMode){
if(h.upload_limit() > 0) if(h.upload_limit() > 0)
val = (int)(h.upload_limit() / 1024.); val = (int)(h.upload_limit() / 1024.);
@ -79,15 +79,15 @@ class BandwidthAllocationDialog : public QDialog, private Ui_bandwidth_dlg {
bandwidthSlider->setValue(val); bandwidthSlider->setValue(val);
if(val == 0) { if(val == 0) {
limit_lbl->setText(tr("Unlimited", "Unlimited (bandwidth)")); limit_lbl->setText(tr("Unlimited", "Unlimited (bandwidth)"));
kb_lbl->setText(""); kb_lbl->setText(QString::fromUtf8(""));
} else { } else {
limit_lbl->setText(QString(misc::toString(val).c_str())); limit_lbl->setText(misc::toQString(val));
} }
}else{ }else{
qDebug("More than one torrent selected, no initilization"); qDebug("More than one torrent selected, no initilization");
bandwidthSlider->setValue(0); bandwidthSlider->setValue(0);
limit_lbl->setText(tr("Unlimited", "Unlimited (bandwidth)")); limit_lbl->setText(tr("Unlimited", "Unlimited (bandwidth)"));
kb_lbl->setText(""); kb_lbl->setText(QString::fromUtf8(""));
} }
}else{ }else{
// Global limit // Global limit
@ -103,7 +103,7 @@ class BandwidthAllocationDialog : public QDialog, private Ui_bandwidth_dlg {
if(val == 0){ if(val == 0){
bandwidthSlider->setValue(0); bandwidthSlider->setValue(0);
limit_lbl->setText(tr("Unlimited", "Unlimited (bandwidth)")); limit_lbl->setText(tr("Unlimited", "Unlimited (bandwidth)"));
kb_lbl->setText(""); kb_lbl->setText(QString::fromUtf8(""));
}else{ }else{
bandwidthSlider->setValue(val); bandwidthSlider->setValue(val);
} }
@ -120,9 +120,9 @@ class BandwidthAllocationDialog : public QDialog, private Ui_bandwidth_dlg {
void updateBandwidthLabel(int val){ void updateBandwidthLabel(int val){
if(val == 0){ if(val == 0){
limit_lbl->setText(tr("Unlimited", "Unlimited (bandwidth)")); limit_lbl->setText(tr("Unlimited", "Unlimited (bandwidth)"));
kb_lbl->setText(""); kb_lbl->setText(QString::fromUtf8(""));
}else{ }else{
limit_lbl->setText(QString(misc::toString(val).c_str())); limit_lbl->setText(misc::toQString(val));
kb_lbl->setText(tr("KiB/s")); kb_lbl->setText(tr("KiB/s"));
} }
} }
@ -150,20 +150,20 @@ class BandwidthAllocationDialog : public QDialog, private Ui_bandwidth_dlg {
} }
} }
}else{ }else{
QSettings settings("qBittorrent", "qBittorrent"); QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
session *s = BTSession->getSession(); session *s = BTSession->getSession();
if(uploadMode){ if(uploadMode){
if(!val) if(!val)
s->set_upload_rate_limit(-1); s->set_upload_rate_limit(-1);
else else
s->set_upload_rate_limit(val*1024); s->set_upload_rate_limit(val*1024);
settings.setValue("Options/Main/UPLimit", val); settings.setValue(QString::fromUtf8("Options/Main/UPLimit"), val);
}else{ }else{
if(!val) if(!val)
s->set_download_rate_limit(-1); s->set_download_rate_limit(-1);
else else
s->set_download_rate_limit(val*1024); s->set_download_rate_limit(val*1024);
settings.setValue("Options/Main/DLLimit", val); settings.setValue(QString::fromUtf8("Options/Main/DLLimit"), val);
} }
} }
close(); close();

View file

@ -92,7 +92,7 @@ bittorrent::~bittorrent(){
} }
void bittorrent::setDownloadLimit(QString hash, long val) { void bittorrent::setDownloadLimit(QString hash, long val) {
torrent_handle h = getTorrentHandle(hash); QTorrentHandle h = getTorrentHandle(hash);
if(h.is_valid()) if(h.is_valid())
h.set_download_limit(val); h.set_download_limit(val);
saveTorrentSpeedLimits(hash); saveTorrentSpeedLimits(hash);
@ -100,7 +100,7 @@ void bittorrent::setDownloadLimit(QString hash, long val){
void bittorrent::setUploadLimit(QString hash, long val) { void bittorrent::setUploadLimit(QString hash, long val) {
qDebug("Set upload limit rate to %ld", val); qDebug("Set upload limit rate to %ld", val);
torrent_handle h = getTorrentHandle(hash); QTorrentHandle h = getTorrentHandle(hash);
if(h.is_valid()) if(h.is_valid())
h.set_upload_limit(val); h.set_upload_limit(val);
saveTorrentSpeedLimits(hash); saveTorrentSpeedLimits(hash);
@ -114,17 +114,15 @@ void bittorrent::updateETAs(){
std::vector<torrent_handle> handles = s->get_torrents(); std::vector<torrent_handle> handles = s->get_torrents();
unsigned int nbHandles = handles.size(); unsigned int nbHandles = handles.size();
for(unsigned int i=0; i<nbHandles; ++i) { for(unsigned int i=0; i<nbHandles; ++i) {
torrent_handle h = handles[i]; QTorrentHandle h = handles[i];
if(h.is_valid()) { if(h.is_valid()) {
QString hash = QString(misc::toString(h.info_hash()).c_str()); QString hash = h.hash();
QList<long> listEtas = ETAstats.value(hash, QList<long>()); QList<long> listEtas = ETAstats.value(hash, QList<long>());
if(listEtas.size() == ETAS_MAX_VALUES) { if(listEtas.size() == ETAS_MAX_VALUES) {
listEtas.removeFirst(); listEtas.removeFirst();
} }
torrent_status torrentStatus = h.status(); if(h.download_payload_rate() != 0) {
torrent_info ti = h.get_torrent_info(); listEtas << (long)((h.total_size()-h.total_done())/(double)h.download_payload_rate());
if(torrentStatus.download_payload_rate != 0){
listEtas << (long)((ti.total_size()-torrentStatus.total_done)/(double)torrentStatus.download_payload_rate);
ETAstats[hash] = listEtas; ETAstats[hash] = listEtas;
long moy = 0; long moy = 0;
long val; long val;
@ -142,14 +140,14 @@ long bittorrent::getETA(QString hash) const{
} }
// Return the torrent handle, given its hash // Return the torrent handle, given its hash
torrent_handle bittorrent::getTorrentHandle(QString hash) const{ QTorrentHandle bittorrent::getTorrentHandle(QString hash) const{
return s->find_torrent(misc::fromString<sha1_hash>((hash.toStdString()))); return QTorrentHandle(s->find_torrent(misc::fromString<sha1_hash>((hash.toStdString()))));
} }
// Return true if the torrent corresponding to the // Return true if the torrent corresponding to the
// hash is paused // hash is paused
bool bittorrent::isPaused(QString hash) const{ bool bittorrent::isPaused(QString hash) const{
torrent_handle h = s->find_torrent(misc::fromString<sha1_hash>((hash.toStdString()))); QTorrentHandle h = getTorrentHandle(hash);
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("/!\\ Error: Invalid handle"); qDebug("/!\\ Error: Invalid handle");
return true; return true;
@ -160,16 +158,16 @@ bool bittorrent::isPaused(QString hash) const{
// Delete a torrent from the session, given its hash // Delete a torrent from the session, given its hash
// permanent = true means that the torrent will be removed from the hard-drive too // permanent = true means that the torrent will be removed from the hard-drive too
void bittorrent::deleteTorrent(QString hash, bool permanent) { void bittorrent::deleteTorrent(QString hash, bool permanent) {
qDebug("Deleting torrent with hash: %s", (const char*)hash.toUtf8()); qDebug("Deleting torrent with hash: %s", hash.toUtf8().data());
torrent_handle h = s->find_torrent(misc::fromString<sha1_hash>((hash.toStdString()))); QTorrentHandle h = getTorrentHandle(hash);
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("/!\\ Error: Invalid handle"); qDebug("/!\\ Error: Invalid handle");
return; return;
} }
QString savePath = QString::fromUtf8(h.save_path().string().c_str()); QString savePath = h.save_path();
QString fileName = QString(h.name().c_str()); QString fileName = h.name();
// Remove it from session // Remove it from session
s->remove_torrent(h); s->remove_torrent(h.get_torrent_handle());
// Remove it from torrent backup directory // Remove it from torrent backup directory
QDir torrentBackup(misc::qBittorrentPath() + "BT_backup"); QDir torrentBackup(misc::qBittorrentPath() + "BT_backup");
QStringList filters; QStringList filters;
@ -252,16 +250,16 @@ void bittorrent::setFinishedTorrent(QString hash){
// Pause a running torrent // Pause a running torrent
bool bittorrent::pauseTorrent(QString hash) { bool bittorrent::pauseTorrent(QString hash) {
bool change = false; bool change = false;
torrent_handle h = s->find_torrent(misc::fromString<sha1_hash>((hash.toStdString()))); QTorrentHandle h = getTorrentHandle(hash);
if(h.is_valid() && !h.is_paused()) { if(h.is_valid() && !h.is_paused()) {
h.pause(); h.pause();
change = true; change = true;
qDebug("Torrent paused successfully"); qDebug("Torrent paused successfully");
}else{ }else{
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("Could not pause torrent %s, reason: invalid", (const char*)hash.toUtf8()); qDebug("Could not pause torrent %s, reason: invalid", hash.toUtf8().data());
}else{ }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 // Create .paused file if necessary
@ -281,7 +279,7 @@ bool bittorrent::pauseTorrent(QString hash){
// Resume a torrent in paused state // Resume a torrent in paused state
bool bittorrent::resumeTorrent(QString hash) { bool bittorrent::resumeTorrent(QString hash) {
bool success = false; bool success = false;
torrent_handle h = s->find_torrent(misc::fromString<sha1_hash>((hash.toStdString()))); QTorrentHandle h = getTorrentHandle(hash);
if(h.is_valid() && h.is_paused()) { if(h.is_valid() && h.is_paused()) {
h.resume(); h.resume();
success = true; success = true;
@ -303,43 +301,40 @@ bool bittorrent::resumeTorrent(QString hash){
return success; return success;
} }
void bittorrent::loadWebSeeds(QString fileHash){ void bittorrent::loadWebSeeds(QString hash) {
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; if(!urlseeds_file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
QByteArray urlseeds_lines = urlseeds_file.readAll(); QByteArray urlseeds_lines = urlseeds_file.readAll();
urlseeds_file.close(); urlseeds_file.close();
QList<QByteArray> url_seeds = urlseeds_lines.split('\n'); QList<QByteArray> url_seeds = urlseeds_lines.split('\n');
QByteArray url_seed; QByteArray url_seed;
torrent_handle h = getTorrentHandle(fileHash); QTorrentHandle h = getTorrentHandle(hash);
torrent_info torrentInfo = h.get_torrent_info();
// First remove from the torrent the url seeds that were deleted // First remove from the torrent the url seeds that were deleted
// in a previous session // in a previous session
QStringList seeds_to_delete; QStringList seeds_to_delete;
std::vector<std::string> existing_seeds = torrentInfo.url_seeds(); QStringList existing_seeds = h.url_seeds();
unsigned int nbSeeds = existing_seeds.size();
QString existing_seed; QString existing_seed;
for(unsigned int i=0; i<nbSeeds; ++i){ foreach(existing_seed, existing_seeds) {
existing_seed = QString(existing_seeds[i].c_str()); if(!url_seeds.contains(existing_seed.toUtf8())) {
if(!url_seeds.contains(QByteArray((const char*)existing_seed.toUtf8()))){
seeds_to_delete << existing_seed; seeds_to_delete << existing_seed;
} }
} }
foreach(existing_seed, seeds_to_delete) { foreach(existing_seed, seeds_to_delete) {
h.remove_url_seed(misc::toString((const char*) existing_seed.toUtf8())); h.remove_url_seed(existing_seed);
} }
// Add the ones that were added in a previous session // Add the ones that were added in a previous session
foreach(url_seed, url_seeds) { foreach(url_seed, url_seeds) {
if(!url_seed.isEmpty()) { if(!url_seed.isEmpty()) {
// XXX: Should we check if it is already in the list before adding it // XXX: Should we check if it is already in the list before adding it
// or is libtorrent clever enough to know // or is libtorrent clever enough to know
torrentInfo.add_url_seed(misc::toString((const char*)url_seed.data())); h.add_url_seed(url_seed);
} }
} }
} }
// Add a torrent to the bittorrent session // Add a torrent to the bittorrent session
void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url) { void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url) {
torrent_handle h; QTorrentHandle h;
entry resume_data; entry resume_data;
bool fastResume=false; bool fastResume=false;
QDir torrentBackup(misc::qBittorrentPath() + "BT_backup"); QDir torrentBackup(misc::qBittorrentPath() + "BT_backup");
@ -349,7 +344,7 @@ void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url){
// create it if it is not // create it if it is not
if(! torrentBackup.exists()) { if(! torrentBackup.exists()) {
if(! torrentBackup.mkpath(torrentBackup.path())) { if(! torrentBackup.mkpath(torrentBackup.path())) {
std::cerr << "Couldn't create the directory: '" << (const char*)(torrentBackup.path().toUtf8()) << "'\n"; std::cerr << "Couldn't create the directory: '" << torrentBackup.path().toUtf8().data() << "'\n";
exit(1); exit(1);
} }
} }
@ -359,15 +354,15 @@ void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url){
return; return;
} }
Q_ASSERT(!file.startsWith("http://") && !file.startsWith("https://") && !file.startsWith("ftp://")); Q_ASSERT(!file.startsWith("http://") && !file.startsWith("https://") && !file.startsWith("ftp://"));
qDebug("Adding %s to download list", (const char*)file.toUtf8()); qDebug("Adding %s to download list", file.toUtf8().data());
std::ifstream in((const char*)file.toUtf8(), std::ios_base::binary); std::ifstream in(file.toUtf8().data(), std::ios_base::binary);
in.unsetf(std::ios_base::skipws); in.unsetf(std::ios_base::skipws);
try{ try{
// Decode torrent file // Decode torrent file
entry e = bdecode(std::istream_iterator<char>(in), std::istream_iterator<char>()); entry e = bdecode(std::istream_iterator<char>(in), std::istream_iterator<char>());
// Getting torrent file informations // Getting torrent file informations
torrent_info t(e); torrent_info t(e);
QString hash = QString(misc::toString(t.info_hash()).c_str()); QString hash = QString::fromUtf8(misc::toString(t.info_hash()).c_str());
if(s->find_torrent(t.info_hash()).is_valid()) { if(s->find_torrent(t.info_hash()).is_valid()) {
// Update info Bar // Update info Bar
if(!fromScanDir) { if(!fromScanDir) {
@ -389,7 +384,7 @@ void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url){
try{ try{
std::stringstream strStream; std::stringstream strStream;
strStream << hash.toStdString() << ".fastresume"; 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_file.unsetf(std::ios_base::skipws);
resume_data = bdecode(std::istream_iterator<char>(resume_file), std::istream_iterator<char>()); resume_data = bdecode(std::istream_iterator<char>(resume_file), std::istream_iterator<char>());
fastResume=true; fastResume=true;
@ -398,15 +393,15 @@ void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url){
} }
QString savePath = getSavePath(hash); QString savePath = getSavePath(hash);
// Adding files to bittorrent session // Adding files to bittorrent session
if(hasFilteredFiles(hash)){ if(has_filtered_files(hash)) {
h = s->add_torrent(t, fs::path((const char*)savePath.toUtf8()), resume_data, false); h = s->add_torrent(t, fs::path(savePath.toUtf8().data()), resume_data, false);
int index = fullAllocationModeList.indexOf(hash); int index = fullAllocationModeList.indexOf(hash);
if(index == -1) { if(index == -1) {
fullAllocationModeList << hash; fullAllocationModeList << hash;
} }
qDebug("Full allocation mode"); qDebug("Full allocation mode");
}else{ }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"); qDebug("Compact allocation mode");
} }
if(!h.is_valid()) { if(!h.is_valid()) {
@ -435,7 +430,6 @@ void bittorrent::addTorrent(QString path, bool fromScanDir, QString from_url){
saveTrackerFile(hash); saveTrackerFile(hash);
loadTrackerFile(hash); loadTrackerFile(hash);
} }
torrent_status torrentStatus = h.status();
QString newFile = torrentBackup.path() + QDir::separator() + hash + ".torrent"; QString newFile = torrentBackup.path() + QDir::separator() + hash + ".torrent";
if(file != newFile) { if(file != newFile) {
// Delete file from torrentBackup directory in case it exists because // Delete file from torrentBackup directory in case it exists because
@ -502,15 +496,10 @@ 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 // Check in .priorities file if the user filtered files
// in this torrent. // in this torrent.
bool bittorrent::hasFilteredFiles(QString fileHash) const{ bool bittorrent::has_filtered_files(QString hash) const{
QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".priorities"); QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".priorities");
// Read saved file // Read saved file
if(!pieces_file.open(QIODevice::ReadOnly | QIODevice::Text)) { if(!pieces_file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return false; return false;
@ -531,49 +520,20 @@ bool bittorrent::hasFilteredFiles(QString fileHash) const{
return false; return false;
} }
// Set the maximum number of opened connections
void bittorrent::setMaxConnections(int maxConnec) {
s->set_max_connections(maxConnec);
}
// For debug only // For debug only
void bittorrent::printPausedTorrents() { void bittorrent::printPausedTorrents() {
QString hash; QString hash;
qDebug("Paused Torrents:"); qDebug("Paused Torrents:");
foreach(hash, pausedTorrents) { foreach(hash, pausedTorrents) {
qDebug("%s ", (const char*)hash.toUtf8()); qDebug("%s ", hash.toUtf8().data());
} }
} }
// 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<QByteArray> 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<nbFiles; ++i){
int priority = pieces_priorities_list.at(i).toInt();
if( priority < 0 || priority > 7){
priority = 1;
}
if(priority)
effective_size += t.file_at(i).size;
}
return effective_size;
}
// Return DHT state // Return DHT state
bool bittorrent::isDHTEnabled() const{ bool bittorrent::isDHTEnabled() const{
return DHTEnabled; return DHTEnabled;
@ -582,7 +542,7 @@ bool bittorrent::isDHTEnabled() const{
// Enable DHT // Enable DHT
void bittorrent::enableDHT() { void bittorrent::enableDHT() {
if(!DHTEnabled) { if(!DHTEnabled) {
boost::filesystem::ifstream dht_state_file((const char*)(misc::qBittorrentPath()+QString("dht_state")).toUtf8(), std::ios_base::binary); 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); dht_state_file.unsetf(std::ios_base::skipws);
entry dht_state; entry dht_state;
try{ try{
@ -607,22 +567,22 @@ void bittorrent::disableDHT(){
} }
void bittorrent::saveTorrentSpeedLimits(QString hash) { void bittorrent::saveTorrentSpeedLimits(QString hash) {
qDebug("Saving speedLimits file for %s", (const char*)hash.toUtf8()); qDebug("Saving speedLimits file for %s", hash.toUtf8().data());
torrent_handle h = getTorrentHandle(hash); QTorrentHandle h = getTorrentHandle(hash);
int download_limit = h.download_limit(); int download_limit = h.download_limit();
int upload_limit = h.upload_limit(); int upload_limit = h.upload_limit();
QFile speeds_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".speedLimits"); QFile speeds_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".speedLimits");
if(!speeds_file.open(QIODevice::WriteOnly | QIODevice::Text)) { if(!speeds_file.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug("* Error: Couldn't open speed limits file for torrent: %s", (const char*)hash.toUtf8()); qDebug("* Error: Couldn't open speed limits file for torrent: %s", hash.toUtf8().data());
return; 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(); speeds_file.close();
} }
void bittorrent::loadTorrentSpeedLimits(QString hash) { void bittorrent::loadTorrentSpeedLimits(QString hash) {
qDebug("Loading speedLimits file for %s", (const char*)hash.toUtf8()); qDebug("Loading speedLimits file for %s", hash.toUtf8().data());
torrent_handle h = getTorrentHandle(hash); QTorrentHandle h = getTorrentHandle(hash);
QFile speeds_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".speedLimits"); 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; return;
@ -639,16 +599,15 @@ void bittorrent::loadTorrentSpeedLimits(QString hash){
} }
// Read pieces priorities from .priorities file // Read pieces priorities from .priorities file
// and ask torrent_handle to consider them // and ask QTorrentHandle to consider them
void bittorrent::loadFilesPriorities(torrent_handle &h){ void bittorrent::loadFilesPriorities(QTorrentHandle &h) {
torrent_info torrentInfo = h.get_torrent_info();
unsigned int nbFiles = torrentInfo.num_files();
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("/!\\ Error: Invalid handle"); qDebug("/!\\ Error: Invalid handle");
return; return;
} }
QString fileHash = QString(misc::toString(torrentInfo.info_hash()).c_str()); unsigned int nbFiles = h.num_files();
QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".priorities"); QString hash = h.hash();
QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".priorities");
// Read saved file // 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"); qDebug("* Error: Couldn't open priorities file");
@ -680,7 +639,7 @@ void bittorrent::loadDownloadUploadForTorrent(QString hash){
if(! torrentBackup.exists()) { if(! torrentBackup.exists()) {
torrentBackup.mkpath(torrentBackup.path()); 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"); 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; return;
@ -698,35 +657,52 @@ void bittorrent::loadDownloadUploadForTorrent(QString hash){
ratioData[hash] = downUp; ratioData[hash] = downUp;
} }
float bittorrent::getRealRatio(QString hash) const{
QPair<size_type,size_type> downUpInfo = ratioData.value(hash, QPair<size_type,size_type>(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 // To remember share ratio or a torrent, we must save current
// total_upload and total_upload and reload them on startup // total_upload and total_upload and reload them on startup
void bittorrent::saveDownloadUploadForTorrent(QString hash) { void bittorrent::saveDownloadUploadForTorrent(QString hash) {
qDebug("Saving ratio data for torrent %s", (const char*)hash.toUtf8()); qDebug("Saving ratio data for torrent %s", hash.toUtf8().data());
QDir torrentBackup(misc::qBittorrentPath() + "BT_backup"); QDir torrentBackup(misc::qBittorrentPath() + QString::fromUtf8("BT_backup"));
// Checking if torrentBackup Dir exists // Checking if torrentBackup Dir exists
// create it if it is not // create it if it is not
if(! torrentBackup.exists()) { if(! torrentBackup.exists()) {
torrentBackup.mkpath(torrentBackup.path()); torrentBackup.mkpath(torrentBackup.path());
} }
torrent_handle h = getTorrentHandle(hash); QTorrentHandle h = getTorrentHandle(hash);
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("/!\\ Error: Invalid handle"); qDebug("/!\\ Error: Invalid handle");
return; return;
} }
torrent_status torrentStatus = h.status(); QPair<size_type,size_type> ratioInfo = ratioData.value(hash, QPair<size_type, size_type>(0,0));
QString fileHash = QString(misc::toString(h.info_hash()).c_str()); size_type download = h.total_payload_download();
QPair<size_type,size_type> ratioInfo = ratioData.value(fileHash, QPair<size_type, size_type>(0,0));
size_type download = torrentStatus.total_payload_download;
download += ratioInfo.first; download += ratioInfo.first;
size_type upload = torrentStatus.total_payload_upload; size_type upload = h.total_payload_upload();
upload += ratioInfo.second; upload += ratioInfo.second;
Q_ASSERT(download >= 0 && upload >= 0); Q_ASSERT(download >= 0 && upload >= 0);
QFile ratio_file(torrentBackup.path()+QDir::separator()+ fileHash + ".ratio"); QFile ratio_file(torrentBackup.path()+QDir::separator()+ hash + QString::fromUtf8(".ratio"));
if(!ratio_file.open(QIODevice::WriteOnly | QIODevice::Text)) { if(!ratio_file.open(QIODevice::WriteOnly | QIODevice::Text)) {
std::cerr << "Couldn't save ratio data for torrent: " << fileHash.toStdString() << '\n'; std::cerr << "Couldn't save ratio data for torrent: " << hash.toStdString() << '\n';
return; 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(); ratio_file.close();
} }
@ -748,7 +724,7 @@ void bittorrent::saveFastResumeAndRatioData(){
// Pause torrents // Pause torrents
std::vector<torrent_handle> handles = s->get_torrents(); std::vector<torrent_handle> handles = s->get_torrents();
for(unsigned int i=0; i<handles.size(); ++i) { for(unsigned int i=0; i<handles.size(); ++i) {
torrent_handle &h = handles[i]; QTorrentHandle h = handles[i];
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("/!\\ Error: Invalid handle"); qDebug("/!\\ Error: Invalid handle");
continue; continue;
@ -758,13 +734,13 @@ void bittorrent::saveFastResumeAndRatioData(){
} }
// Write fast resume data // Write fast resume data
for(unsigned int i=0; i<handles.size(); ++i) { for(unsigned int i=0; i<handles.size(); ++i) {
torrent_handle &h = handles[i]; QTorrentHandle h = handles[i];
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("/!\\ Error: Invalid handle"); qDebug("/!\\ Error: Invalid handle");
continue; continue;
} }
QString fileHash = QString(misc::toString(h.info_hash()).c_str()); QString hash = h.hash();
while(!receivedPausedAlert(fileHash)){ while(!receivedPausedAlert(hash)) {
//qDebug("Sleeping while waiting that %s is paused", misc::toString(h.info_hash()).c_str()); //qDebug("Sleeping while waiting that %s is paused", misc::toString(h.info_hash()).c_str());
//printPausedTorrents(); //printPausedTorrents();
SleeperThread::msleep(300); SleeperThread::msleep(300);
@ -772,37 +748,37 @@ void bittorrent::saveFastResumeAndRatioData(){
} }
// Extracting resume data // Extracting resume data
if (h.has_metadata()) { if (h.has_metadata()) {
if(QFile::exists(torrentBackup.path()+QDir::separator()+fileHash+".torrent")){ if(QFile::exists(torrentBackup.path()+QDir::separator()+hash+".torrent")) {
// Remove old .fastresume data in case it exists // Remove old .fastresume data in case it exists
QFile::remove(torrentBackup.path()+QDir::separator()+fileHash + ".fastresume"); QFile::remove(torrentBackup.path()+QDir::separator()+hash + ".fastresume");
// Write fast resume data // Write fast resume data
entry resumeData = h.write_resume_data(); entry resumeData = h.write_resume_data();
file = fileHash + ".fastresume"; file = hash + ".fastresume";
boost::filesystem::ofstream out(fs::path((const char*)torrentBackup.path().toUtf8()) / (const char*)file.toUtf8(), std::ios_base::binary); boost::filesystem::ofstream out(fs::path(torrentBackup.path().toUtf8().data()) / file.toUtf8().data(), std::ios_base::binary);
out.unsetf(std::ios_base::skipws); out.unsetf(std::ios_base::skipws);
bencode(std::ostream_iterator<char>(out), resumeData); bencode(std::ostream_iterator<char>(out), resumeData);
} }
// Save ratio data // Save ratio data
saveDownloadUploadForTorrent(fileHash); saveDownloadUploadForTorrent(hash);
// Save trackers // Save trackers
saveTrackerFile(fileHash); saveTrackerFile(hash);
} }
// Remove torrent // Remove torrent
s->remove_torrent(h); s->remove_torrent(h.get_torrent_handle());
} }
qDebug("Fast resume and ratio data saved"); qDebug("Fast resume and ratio data saved");
} }
bool bittorrent::isFilePreviewPossible(QString hash) const{ bool bittorrent::isFilePreviewPossible(QString hash) const{
// See if there are supported files in the torrent // See if there are supported files in the torrent
torrent_handle h = s->find_torrent(misc::fromString<sha1_hash>((hash.toStdString()))); QTorrentHandle h = getTorrentHandle(hash);
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("/!\\ Error: Invalid handle"); qDebug("/!\\ Error: Invalid handle");
return false; return false;
} }
torrent_info torrentInfo = h.get_torrent_info(); unsigned int nbFiles = h.num_files();
for(int i=0; i<torrentInfo.num_files(); ++i){ for(unsigned int i=0; i<nbFiles; ++i) {
QString fileName = QString(torrentInfo.file_at(i).path.leaf().c_str()); QString fileName = h.file_at(i);
QString extension = fileName.split('.').last().toUpper(); QString extension = fileName.split('.').last().toUpper();
if(supported_preview_extensions.indexOf(extension) >= 0) { if(supported_preview_extensions.indexOf(extension) >= 0) {
return true; return true;
@ -823,8 +799,8 @@ void bittorrent::scanDirectory(){
QStringList files = dir.entryList(filters, QDir::Files, QDir::Unsorted); QStringList files = dir.entryList(filters, QDir::Files, QDir::Unsorted);
foreach(file, files) { foreach(file, files) {
QString fullPath = dir.path()+QDir::separator()+file; QString fullPath = dir.path()+QDir::separator()+file;
QFile::rename(fullPath, fullPath+QString(".old")); QFile::rename(fullPath, fullPath+QString::fromUtf8(".old"));
to_add << fullPath+QString(".old"); to_add << fullPath+QString::fromUtf8(".old");
} }
emit scanDirFoundTorrents(to_add); emit scanDirFoundTorrents(to_add);
} }
@ -886,7 +862,7 @@ void bittorrent::setGlobalRatio(float ratio){
std::vector<torrent_handle> handles = s->get_torrents(); std::vector<torrent_handle> handles = s->get_torrents();
unsigned int nbHandles = handles.size(); unsigned int nbHandles = handles.size();
for(unsigned int i=0; i<nbHandles; ++i) { for(unsigned int i=0; i<nbHandles; ++i) {
torrent_handle h = handles[i]; QTorrentHandle h = handles[i];
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("/!\\ Error: Invalid handle"); qDebug("/!\\ Error: Invalid handle");
continue; continue;
@ -900,7 +876,7 @@ bool bittorrent::loadTrackerFile(QString hash){
QFile tracker_file(torrentBackup.path()+QDir::separator()+ hash + ".trackers"); QFile tracker_file(torrentBackup.path()+QDir::separator()+ hash + ".trackers");
if(!tracker_file.exists()) return false; if(!tracker_file.exists()) return false;
tracker_file.open(QIODevice::ReadOnly | QIODevice::Text); tracker_file.open(QIODevice::ReadOnly | QIODevice::Text);
QStringList lines = QString(tracker_file.readAll().data()).split("\n"); QStringList lines = QString::fromUtf8(tracker_file.readAll().data()).split("\n");
std::vector<announce_entry> trackers; std::vector<announce_entry> trackers;
QString line; QString line;
foreach(line, lines) { foreach(line, lines) {
@ -911,7 +887,7 @@ bool bittorrent::loadTrackerFile(QString hash){
trackers.push_back(t); trackers.push_back(t);
} }
if(trackers.size() != 0) { if(trackers.size() != 0) {
torrent_handle h = getTorrentHandle(hash); QTorrentHandle h = getTorrentHandle(hash);
h.replace_trackers(trackers); h.replace_trackers(trackers);
return true; return true;
}else{ }else{
@ -926,7 +902,7 @@ void bittorrent::saveTrackerFile(QString hash){
tracker_file.remove(); tracker_file.remove();
} }
tracker_file.open(QIODevice::WriteOnly | QIODevice::Text); tracker_file.open(QIODevice::WriteOnly | QIODevice::Text);
torrent_handle h = getTorrentHandle(hash); QTorrentHandle h = getTorrentHandle(hash);
std::vector<announce_entry> trackers = h.trackers(); std::vector<announce_entry> trackers = h.trackers();
for(unsigned int i=0; i<trackers.size(); ++i) { for(unsigned int i=0; i<trackers.size(); ++i) {
tracker_file.write(QByteArray(trackers[i].url.c_str())+QByteArray("|")+QByteArray(misc::toString(i).c_str())+QByteArray("\n")); tracker_file.write(QByteArray(trackers[i].url.c_str())+QByteArray("|")+QByteArray(misc::toString(i).c_str())+QByteArray("\n"));
@ -958,9 +934,8 @@ void bittorrent::enableIPFilter(ip_filter filter){
// Disable IP Filtering // Disable IP Filtering
void bittorrent::disableIPFilter() { void bittorrent::disableIPFilter() {
qDebug("Disable IPFilter"); qDebug("Disabling IPFilter");
s->set_ip_filter(ip_filter()); s->set_ip_filter(ip_filter());
qDebug("IPFilter disabled");
} }
// Set BT session settings (user_agent) // Set BT session settings (user_agent)
@ -989,12 +964,14 @@ void bittorrent::readAlerts(){
std::auto_ptr<alert> a = s->pop_alert(); std::auto_ptr<alert> a = s->pop_alert();
while (a.get()) { while (a.get()) {
if (torrent_finished_alert* p = dynamic_cast<torrent_finished_alert*>(a.get())) { if (torrent_finished_alert* p = dynamic_cast<torrent_finished_alert*>(a.get())) {
QString hash = QString(misc::toString(p->handle.info_hash()).c_str()); QTorrentHandle h(p->handle);
QString hash = h.hash();
setFinishedTorrent(hash); setFinishedTorrent(hash);
emit finishedTorrent(p->handle); emit finishedTorrent(h);
} }
else if (file_error_alert* p = dynamic_cast<file_error_alert*>(a.get())) { else if (file_error_alert* p = dynamic_cast<file_error_alert*>(a.get())) {
emit fullDiskError(p->handle); QTorrentHandle h(p->handle);
emit fullDiskError(h);
} }
else if (dynamic_cast<listen_failed_alert*>(a.get())) { else if (dynamic_cast<listen_failed_alert*>(a.get())) {
// Level: fatal // Level: fatal
@ -1002,22 +979,23 @@ void bittorrent::readAlerts(){
} }
else if (tracker_alert* p = dynamic_cast<tracker_alert*>(a.get())) { else if (tracker_alert* p = dynamic_cast<tracker_alert*>(a.get())) {
// Level: fatal // Level: fatal
QString hash = QString(misc::toString(p->handle.info_hash()).c_str()); QTorrentHandle h(p->handle);
QString hash = h.hash();
QList<QPair<QString, QString> > errors = trackersErrors.value(hash, QList<QPair<QString, QString> >()); QList<QPair<QString, QString> > errors = trackersErrors.value(hash, QList<QPair<QString, QString> >());
if(errors.size() > 5) if(errors.size() > 5)
errors.removeAt(0); errors.removeAt(0);
errors << QPair<QString,QString>(QTime::currentTime().toString("hh:mm:ss"), QString(a->msg().c_str())); errors << QPair<QString,QString>(QTime::currentTime().toString("hh:mm:ss"), QString::fromUtf8(a->msg().c_str()));
trackersErrors[hash] = errors; trackersErrors[hash] = errors;
// Authentication // Authentication
if(p->status_code == 401) { if(p->status_code == 401) {
emit trackerAuthenticationRequired(p->handle); emit trackerAuthenticationRequired(h);
} }
} }
else if (torrent_paused_alert* p = dynamic_cast<torrent_paused_alert*>(a.get())) { else if (torrent_paused_alert* p = dynamic_cast<torrent_paused_alert*>(a.get())) {
QString hash = QString(misc::toString(p->handle.info_hash()).c_str()); QTorrentHandle h(p->handle);
qDebug("Received torrent_paused_alert for %s", (const char*)hash.toUtf8()); QString hash = h.hash();
qDebug("Received torrent_paused_alert for %s", hash.toUtf8().data());
if(!pausedTorrents.contains(hash)) { if(!pausedTorrents.contains(hash)) {
torrent_handle h = p->handle;
if(h.is_valid() && h.is_paused()) { if(h.is_valid() && h.is_paused()) {
pausedTorrents << hash; pausedTorrents << hash;
if(reloadingTorrents.indexOf(hash) != -1) { if(reloadingTorrents.indexOf(hash) != -1) {
@ -1031,23 +1009,25 @@ void bittorrent::readAlerts(){
} }
} }
else if (peer_blocked_alert* p = dynamic_cast<peer_blocked_alert*>(a.get())) { else if (peer_blocked_alert* p = dynamic_cast<peer_blocked_alert*>(a.get())) {
emit peerBlocked(QString(p->ip.to_string().c_str())); emit peerBlocked(QString::fromUtf8(p->ip.to_string().c_str()));
} }
else if (fastresume_rejected_alert* p = dynamic_cast<fastresume_rejected_alert*>(a.get())) { else if (fastresume_rejected_alert* p = dynamic_cast<fastresume_rejected_alert*>(a.get())) {
qDebug("/!\\ Fast resume failed for %s, reason: %s", p->handle.name().c_str(), p->msg().c_str()); QTorrentHandle h(p->handle);
emit fastResumeDataRejected(QString(p->handle.name().c_str())); 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<url_seed_alert*>(a.get())) { else if (url_seed_alert* p = dynamic_cast<url_seed_alert*>(a.get())) {
emit urlSeedProblem(QString(p->url.c_str()), QString(p->msg().c_str())); emit urlSeedProblem(QString::fromUtf8(p->url.c_str()), QString::fromUtf8(p->msg().c_str()));
} }
else if (torrent_checked_alert* p = dynamic_cast<torrent_checked_alert*>(a.get())) { else if (torrent_checked_alert* p = dynamic_cast<torrent_checked_alert*>(a.get())) {
QString hash = QString(misc::toString(p->handle.info_hash()).c_str()); QTorrentHandle h(p->handle);
qDebug("%s have just finished checking", (const char*)hash.toUtf8()); QString hash = h.hash();
qDebug("%s have just finished checking", hash.toUtf8().data());
int index = torrentsToPauseAfterChecking.indexOf(hash); int index = torrentsToPauseAfterChecking.indexOf(hash);
if(index != -1) { if(index != -1) {
// Pause torrent // Pause torrent
pauseTorrent(hash); pauseTorrent(hash);
qDebug("%s was paused after checking", (const char*)hash.toUtf8()); qDebug("%s was paused after checking", hash.toUtf8().data());
} }
emit torrentFinishedChecking(hash); emit torrentFinishedChecking(hash);
} }
@ -1065,14 +1045,14 @@ QStringList bittorrent::getTorrentsToPauseAfterChecking() const{
// Function to reload the torrent async after the torrent is actually // Function to reload the torrent async after the torrent is actually
// paused so that we can get fastresume data // paused so that we can get fastresume data
void bittorrent::pauseAndReloadTorrent(const torrent_handle &h){ void bittorrent::pauseAndReloadTorrent(QTorrentHandle h) {
if(!h.is_valid()) { if(!h.is_valid()) {
std::cerr << "/!\\ Error: Invalid handle\n"; std::cerr << "/!\\ Error: Invalid handle\n";
return; return;
} }
// ask to pause the torrent (async) // ask to pause the torrent (async)
h.pause(); 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 // Add it to reloadingTorrents list so that we now we
// we should reload the torrent once we receive the // we should reload the torrent once we receive the
// torrent_paused_alert. pause() is async now... // torrent_paused_alert. pause() is async now...
@ -1080,24 +1060,24 @@ void bittorrent::pauseAndReloadTorrent(const torrent_handle &h){
} }
// Reload a torrent with full allocation mode // Reload a torrent with full allocation mode
void bittorrent::reloadTorrent(const torrent_handle &h){ void bittorrent::reloadTorrent(const QTorrentHandle &h) {
qDebug("** Reloading a torrent"); qDebug("** Reloading a torrent");
if(!h.is_valid()) { if(!h.is_valid()) {
qDebug("/!\\ Error: Invalid handle"); qDebug("/!\\ Error: Invalid handle");
return; return;
} }
QDir torrentBackup(misc::qBittorrentPath() + "BT_backup"); QDir torrentBackup(misc::qBittorrentPath() + "BT_backup");
fs::path saveDir = h.save_path(); fs::path saveDir = h.save_path_boost();
QString fileName = QString(h.name().c_str()); QString fileName = h.name();
QString fileHash = QString(misc::toString(h.info_hash()).c_str()); QString hash = h.hash();
int index = fullAllocationModeList.indexOf(fileHash);
if(index == -1){
fullAllocationModeList << fileHash;
}
qDebug("Reloading torrent: %s", (const char*)fileName.toUtf8());
torrent_handle new_h;
entry resumeData;
torrent_info t = h.get_torrent_info(); 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 // Checking if torrentBackup Dir exists
// create it if it is not // create it if it is not
if(! torrentBackup.exists()) { if(! torrentBackup.exists()) {
@ -1105,44 +1085,39 @@ void bittorrent::reloadTorrent(const torrent_handle &h){
} }
// Write fast resume data // Write fast resume data
// Torrent is already paused // Torrent is already paused
Q_ASSERT(pausedTorrents.indexOf(fileHash) != -1); Q_ASSERT(pausedTorrents.indexOf(hash) != -1);
// Extracting resume data // Extracting resume data
if (h.has_metadata()) { if (h.has_metadata()) {
// get fast resume data // get fast resume data
resumeData = h.write_resume_data(); resumeData = h.write_resume_data();
} }
// Remove torrent // Remove torrent
s->remove_torrent(h); s->remove_torrent(h.get_torrent_handle());
// Add torrent again to session // Add torrent again to session
unsigned short timeout = 0; unsigned short timeout = 0;
while(h.is_valid() && timeout < 6) { while(h.is_valid() && timeout < 6) {
SleeperThread::msleep(1000); SleeperThread::msleep(1000);
++timeout; ++timeout;
} }
if(h.is_valid()){
std::cerr << "Error: Couldn't reload the torrent\n";
return;
}
new_h = s->add_torrent(t, saveDir, resumeData, false); new_h = s->add_torrent(t, saveDir, resumeData, false);
qDebug("Using full allocation mode"); qDebug("Using full allocation mode");
// new_h.set_max_connections(60);
new_h.set_max_uploads(-1); new_h.set_max_uploads(-1);
// Load filtered Files // Load filtered Files
loadFilesPriorities(new_h); loadFilesPriorities(new_h);
// Load speed limit from hard drive // Load speed limit from hard drive
loadTorrentSpeedLimits(fileHash); loadTorrentSpeedLimits(hash);
// Load custom url seeds // Load custom url seeds
loadWebSeeds(fileHash); loadWebSeeds(hash);
// Load ratio data // Load ratio data
loadDownloadUploadForTorrent(fileHash); loadDownloadUploadForTorrent(hash);
// Pause torrent if it was paused last time // 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(); new_h.pause();
} }
// Incremental download // Incremental download
if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".incremental")){ if(QFile::exists(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".incremental")) {
qDebug("Incremental download enabled for %s", (const char*)fileName.toUtf8()); qDebug("Incremental download enabled for %s", fileName.toUtf8().data());
new_h.set_sequenced_download_threshold(1); new_h.set_sequenced_download_threshold(1);
} }
} }
@ -1153,26 +1128,6 @@ int bittorrent::getListenPort() const{
return s->listen_port(); return s->listen_port();
} }
float bittorrent::getRealRatio(QString hash) const{
QPair<size_type,size_type> downUpInfo = ratioData.value(hash, QPair<size_type,size_type>(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{ session_status bittorrent::getSessionStatus() const{
return s->status(); return s->status();
} }
@ -1201,7 +1156,7 @@ QString bittorrent::getSavePath(QString hash){
QDir saveDir(savePath); QDir saveDir(savePath);
if(!saveDir.exists()) { if(!saveDir.exists()) {
if(!saveDir.mkpath(saveDir.path())) { if(!saveDir.mkpath(saveDir.path())) {
std::cerr << "Couldn't create the save directory: " << (const char*)saveDir.path().toUtf8() << "\n"; std::cerr << "Couldn't create the save directory: " << saveDir.path().toUtf8().data() << "\n";
// XXX: handle this better // XXX: handle this better
return QDir::homePath(); return QDir::homePath();
} }
@ -1248,18 +1203,13 @@ float bittorrent::getPayloadUploadRate() const{
return sessionStatus.payload_upload_rate; return sessionStatus.payload_upload_rate;
} }
// Return a vector with all torrent handles in it
std::vector<torrent_handle> bittorrent::getTorrentHandles() const{
return s->get_torrents();
}
// Save DHT entry to hard drive // Save DHT entry to hard drive
void bittorrent::saveDHTEntry() { void bittorrent::saveDHTEntry() {
// Save DHT entry // Save DHT entry
if(DHTEnabled) { if(DHTEnabled) {
try{ try{
entry dht_state = s->dht_state(); 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); out.unsetf(std::ios_base::skipws);
bencode(std::ostream_iterator<char>(out), dht_state); bencode(std::ostream_iterator<char>(out), dht_state);
qDebug("DHT entry saved"); qDebug("DHT entry saved");

View file

@ -26,8 +26,8 @@
#include <QPair> #include <QPair>
#include <QStringList> #include <QStringList>
#include <libtorrent/torrent_handle.hpp>
#include <libtorrent/session.hpp> #include <libtorrent/session.hpp>
#include "qtorrenthandle.h"
using namespace libtorrent; using namespace libtorrent;
@ -67,10 +67,8 @@ class bittorrent : public QObject{
// Constructor / Destructor // Constructor / Destructor
bittorrent(); bittorrent();
~bittorrent(); ~bittorrent();
torrent_handle getTorrentHandle(QString hash) const; QTorrentHandle getTorrentHandle(QString hash) const;
std::vector<torrent_handle> getTorrentHandles() const;
bool isPaused(QString hash) const; bool isPaused(QString hash) const;
bool hasFilteredFiles(QString fileHash) const;
bool isFilePreviewPossible(QString fileHash) const; bool isFilePreviewPossible(QString fileHash) const;
bool isDHTEnabled() const; bool isDHTEnabled() const;
float getPayloadDownloadRate() const; float getPayloadDownloadRate() const;
@ -79,7 +77,6 @@ class bittorrent : public QObject{
int getListenPort() const; int getListenPort() const;
QStringList getTorrentsToPauseAfterChecking() const; QStringList getTorrentsToPauseAfterChecking() const;
long getETA(QString hash) const; long getETA(QString hash) const;
size_type torrentEffectiveSize(QString hash) const;
bool inFullAllocationMode(QString hash) const; bool inFullAllocationMode(QString hash) const;
float getRealRatio(QString hash) const; float getRealRatio(QString hash) const;
session* getSession() const; session* getSession() const;
@ -89,6 +86,7 @@ class bittorrent : public QObject{
QStringList getFinishedTorrents() const; QStringList getFinishedTorrents() const;
QStringList getUnfinishedTorrents() const; QStringList getUnfinishedTorrents() const;
bool isFinished(QString hash) const; bool isFinished(QString hash) const;
bool has_filtered_files(QString hash) const;
public slots: public slots:
void addTorrent(QString path, bool fromScanDir = false, QString from_url = QString()); void addTorrent(QString path, bool fromScanDir = false, QString from_url = QString());
@ -106,7 +104,7 @@ class bittorrent : public QObject{
void enablePeerExchange(); void enablePeerExchange();
void enableIPFilter(ip_filter filter); void enableIPFilter(ip_filter filter);
void disableIPFilter(); void disableIPFilter();
void pauseAndReloadTorrent(const torrent_handle &h); void pauseAndReloadTorrent(QTorrentHandle h);
void resumeUnfinishedTorrents(); void resumeUnfinishedTorrents();
void updateETAs(); void updateETAs();
void saveTorrentSpeedLimits(QString hash); void saveTorrentSpeedLimits(QString hash);
@ -126,7 +124,7 @@ class bittorrent : public QObject{
void setSessionSettings(session_settings sessionSettings); void setSessionSettings(session_settings sessionSettings);
void setDefaultSavePath(QString savepath); void setDefaultSavePath(QString savepath);
void applyEncryptionSettings(pe_settings se); void applyEncryptionSettings(pe_settings se);
void loadFilesPriorities(torrent_handle& h); void loadFilesPriorities(QTorrentHandle& h);
void setDownloadLimit(QString hash, long val); void setDownloadLimit(QString hash, long val);
void setUploadLimit(QString hash, long val); void setUploadLimit(QString hash, long val);
void setUnfinishedTorrent(QString hash); void setUnfinishedTorrent(QString hash);
@ -138,17 +136,17 @@ class bittorrent : public QObject{
void processDownloadedFile(QString, QString); void processDownloadedFile(QString, QString);
bool loadTrackerFile(QString hash); bool loadTrackerFile(QString hash);
void saveTrackerFile(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: signals:
void invalidTorrent(QString path); void invalidTorrent(QString path);
void duplicateTorrent(QString path); void duplicateTorrent(QString path);
void addedTorrent(QString path, torrent_handle& h, bool fastResume); void addedTorrent(QString path, QTorrentHandle& h, bool fastResume);
void finishedTorrent(torrent_handle& h); void finishedTorrent(QTorrentHandle& h);
void fullDiskError(torrent_handle& h); void fullDiskError(QTorrentHandle& h);
void trackerError(QString hash, QString time, QString msg); void trackerError(QString hash, QString time, QString msg);
void portListeningFailure(); void portListeningFailure();
void trackerAuthenticationRequired(torrent_handle& h); void trackerAuthenticationRequired(QTorrentHandle& h);
void scanDirFoundTorrents(const QStringList& pathList); void scanDirFoundTorrents(const QStringList& pathList);
void newDownloadedTorrent(QString path, QString url); void newDownloadedTorrent(QString path, QString url);
void aboutToDownloadFromUrl(QString url); void aboutToDownloadFromUrl(QString url);

View file

@ -48,7 +48,7 @@ class downloadFromURL : public QDialog, private Ui::downloadFromURL{
public slots: public slots:
void on_downloadButton_clicked(){ void on_downloadButton_clicked(){
QString urls = textUrls->toPlainText(); QString urls = textUrls->toPlainText();
QStringList url_list = urls.split("\n"); QStringList url_list = urls.split(QString::fromUtf8("\n"));
QString url; QString url;
QStringList url_list_cleaned; QStringList url_list_cleaned;
foreach(url, url_list){ foreach(url, url_list){

View file

@ -26,6 +26,7 @@
#include <stdexcept> #include <stdexcept>
#include <QObject> #include <QObject>
#include <QString> #include <QString>
#include <QByteArray>
#include <QDir> #include <QDir>
#include <QList> #include <QList>
#include <QPair> #include <QPair>
@ -53,6 +54,26 @@ class misc : public QObject{
return o.str(); return o.str();
} }
template <class T> static QString toQString(const T& x, bool convert=false) {
std::ostringstream o;
if(!(o<<x)) {
throw std::runtime_error("::toString()");
}
if(o.str() == "-1" && convert)
return QString::fromUtf8("0");
return QString::fromUtf8(o.str().c_str());
}
template <class T> static QByteArray toQByteArray(const T& x, bool convert=false) {
std::ostringstream o;
if(!(o<<x)) {
throw std::runtime_error("::toString()");
}
if(o.str() == "-1" && convert)
return "0";
return QByteArray(o.str().c_str());
}
// Convert C++ string to any type of variable // Convert C++ string to any type of variable
template <class T> static T fromString(const std::string& s) { template <class T> static T fromString(const std::string& s) {
T x; T x;
@ -63,6 +84,24 @@ class misc : public QObject{
return x; return x;
} }
// template <class T> 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 <class T> 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) // return best userfriendly storage unit (B, KiB, MiB, GiB, TiB)
// use Binary prefix standards from IEC 60027-2 // use Binary prefix standards from IEC 60027-2
// see http://en.wikipedia.org/wiki/Kilobyte // see http://en.wikipedia.org/wiki/Kilobyte
@ -70,18 +109,18 @@ class misc : public QObject{
static QString friendlyUnit(float val) { static QString friendlyUnit(float val) {
char tmp[MAX_CHAR_TMP]; char tmp[MAX_CHAR_TMP];
if(val < 0) { if(val < 0) {
return QString(tr("Unknown", "Unknown (size)")); 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)")}; 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) { for(unsigned short i=0; i<5; ++i) {
if (val < 1024.) { if (val < 1024.) {
snprintf(tmp, MAX_CHAR_TMP, "%.1f", val); snprintf(tmp, MAX_CHAR_TMP, "%.1f", val);
return QString(tmp) + " " + units[i]; return QString::fromUtf8(tmp) + QString::fromUtf8(" ") + units[i];
} }
val /= 1024.; val /= 1024.;
} }
snprintf(tmp, MAX_CHAR_TMP, "%.1f", val); 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 // return qBittorrent config path
@ -91,9 +130,9 @@ class misc : public QObject{
return QString(); return QString();
} }
if(qBtPath[qBtPath.length()-1] == QDir::separator()) { if(qBtPath[qBtPath.length()-1] == QDir::separator()) {
qBtPath = qBtPath + ".qbittorrent" + QDir::separator(); qBtPath = qBtPath + QString::fromUtf8(".qbittorrent") + QDir::separator();
}else{ }else{
qBtPath = qBtPath + QDir::separator() + ".qbittorrent" + QDir::separator(); qBtPath = qBtPath + QDir::separator() + QString::fromUtf8(".qbittorrent") + QDir::separator();
} }
// Create dir if it does not exist // Create dir if it does not exist
QDir dir(qBtPath); QDir dir(qBtPath);
@ -104,7 +143,7 @@ class misc : public QObject{
} }
static bool removePath(QString path) { static bool removePath(QString path) {
qDebug((QString("file to delete:") + path).toUtf8()); qDebug((QString::fromUtf8("file to delete:") + path).toUtf8());
if(!QFile::remove(path)) { if(!QFile::remove(path)) {
// Probably a folder // Probably a folder
QDir current_dir(path); QDir current_dir(path);
@ -113,7 +152,7 @@ class misc : public QObject{
QStringList subItems = current_dir.entryList(); QStringList subItems = current_dir.entryList();
QString item; QString item;
foreach(item, subItems) { foreach(item, subItems) {
if(item != "." && item != ".."){ if(item != QString::fromUtf8(".") && item != QString::fromUtf8("..")) {
qDebug("-> Removing "+(path+QDir::separator()+item).toUtf8()); qDebug("-> Removing "+(path+QDir::separator()+item).toUtf8());
removePath(path+QDir::separator()+item); removePath(path+QDir::separator()+item);
} }
@ -204,26 +243,26 @@ class misc : public QObject{
// time duration like "1d 2h 10m". // time duration like "1d 2h 10m".
static QString userFriendlyDuration(const long int seconds) { static QString userFriendlyDuration(const long int seconds) {
if(seconds < 0) { if(seconds < 0) {
return QString::QString(tr("Unknown")); return tr("Unknown");
} }
if(seconds < 60) { if(seconds < 60) {
return tr("< 1m", "< 1 minute"); return tr("< 1m", "< 1 minute");
} }
int minutes = seconds / 60; int minutes = seconds / 60;
if(minutes < 60) { if(minutes < 60) {
return tr("%1m","e.g: 10minutes").arg(QString::QString(misc::toString(minutes).c_str())); return tr("%1m","e.g: 10minutes").arg(QString::QString::fromUtf8(misc::toString(minutes).c_str()));
} }
int hours = minutes / 60; int hours = minutes / 60;
minutes = minutes - hours*60; minutes = minutes - hours*60;
if(hours < 24) { 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())); 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; int days = hours / 24;
hours = hours - days * 24; hours = hours - days * 24;
if(days < 100) { 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())); 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");
} }
}; };

View file

@ -263,89 +263,89 @@ void options_imp::saveOptions(){
settings.beginGroup("Options"); settings.beginGroup("Options");
// Main options // Main options
settings.beginGroup("Main"); settings.beginGroup("Main");
settings.setValue("DLLimit", getLimits().first); settings.setValue(QString::fromUtf8("DLLimit"), getLimits().first);
settings.setValue("UPLimit", getLimits().second); settings.setValue(QString::fromUtf8("UPLimit"), getLimits().second);
settings.setValue("MaxConnecs", getMaxConnec()); settings.setValue(QString::fromUtf8("MaxConnecs"), getMaxConnec());
settings.setValue("PortRangeMin", getPorts().first); settings.setValue(QString::fromUtf8("PortRangeMin"), getPorts().first);
settings.setValue("PortRangeMax", getPorts().second); settings.setValue(QString::fromUtf8("PortRangeMax"), getPorts().second);
settings.setValue("ShareRatio", getRatio()); settings.setValue(QString::fromUtf8("ShareRatio"), getRatio());
settings.setValue("EncryptionState", getEncryptionSetting()); settings.setValue(QString::fromUtf8("EncryptionState"), getEncryptionSetting());
settings.setValue("PeXState", !isPeXDisabled()); settings.setValue(QString::fromUtf8("PeXState"), !isPeXDisabled());
settings.setValue("DHTPort", getDHTPort()); settings.setValue(QString::fromUtf8("DHTPort"), getDHTPort());
settings.setValue("ScanDir", getScanDir()); settings.setValue(QString::fromUtf8("ScanDir"), getScanDir());
// End Main options // End Main options
settings.endGroup(); settings.endGroup();
// Language options // Language options
settings.beginGroup("Language"); settings.beginGroup(QString::fromUtf8("Language"));
settings.setValue("Locale", getLocale()); settings.setValue(QString::fromUtf8("Locale"), getLocale());
// End Language options // End Language options
settings.endGroup(); settings.endGroup();
// IPFilter options // IPFilter options
settings.beginGroup("IPFilter"); settings.beginGroup(QString::fromUtf8("IPFilter"));
bool enabled = isFilteringEnabled(); bool enabled = isFilteringEnabled();
settings.setValue("Enabled", enabled); settings.setValue(QString::fromUtf8("Enabled"), enabled);
if(enabled){ if(enabled){
settings.setValue("File", filterFile->text()); settings.setValue(QString::fromUtf8("File"), filterFile->text());
} }
// End IPFilter options // End IPFilter options
settings.endGroup(); settings.endGroup();
// Proxy options // Proxy options
settings.beginGroup("Proxy"); settings.beginGroup(QString::fromUtf8("Proxy"));
enabled = isProxyEnabled(); enabled = isProxyEnabled();
settings.setValue("Enabled", enabled); settings.setValue(QString::fromUtf8("Enabled"), enabled);
if(enabled){ if(enabled){
settings.setValue("IP", getProxyIp()); settings.setValue(QString::fromUtf8("IP"), getProxyIp());
settings.setValue("Port", getProxyPort()); settings.setValue(QString::fromUtf8("Port"), getProxyPort());
unsigned short val = getProxyType(); unsigned short val = getProxyType();
if(val == HTTP || val == HTTP_PW){ if(val == HTTP || val == HTTP_PW){
settings.setValue("ProxyType", HTTP); settings.setValue(QString::fromUtf8("ProxyType"), HTTP);
}else{ }else{
settings.setValue("ProxyType", SOCKS5); settings.setValue(QString::fromUtf8("ProxyType"), SOCKS5);
} }
settings.setValue("UseProxyForTrackers", useProxyForTrackers()); settings.setValue(QString::fromUtf8("UseProxyForTrackers"), useProxyForTrackers());
settings.setValue("UseProxyForPeers", useProxyForPeers()); settings.setValue(QString::fromUtf8("UseProxyForPeers"), useProxyForPeers());
settings.setValue("UseProxyForWebseeds", useProxyForWebseeds()); settings.setValue(QString::fromUtf8("UseProxyForWebseeds"), useProxyForWebseeds());
settings.setValue("UseProxyForDHT", useProxyForDHT()); settings.setValue(QString::fromUtf8("UseProxyForDHT"), useProxyForDHT());
enabled = isProxyAuthEnabled(); enabled = isProxyAuthEnabled();
settings.beginGroup("Authentication"); settings.beginGroup(QString::fromUtf8("Authentication"));
settings.setValue("Enabled", enabled); settings.setValue(QString::fromUtf8("Enabled"), enabled);
if(enabled){ if(enabled){
settings.setValue("Username", getProxyUsername()); settings.setValue(QString::fromUtf8("Username"), getProxyUsername());
settings.setValue("Password", getProxyPassword()); settings.setValue(QString::fromUtf8("Password"), getProxyPassword());
} }
settings.endGroup(); settings.endGroup();
} }
// End Proxy options // End Proxy options
settings.endGroup(); settings.endGroup();
// Misc options // Misc options
settings.beginGroup("Misc"); settings.beginGroup(QString::fromUtf8("Misc"));
settings.beginGroup("TorrentAdditionDialog"); settings.beginGroup(QString::fromUtf8("TorrentAdditionDialog"));
enabled = useAdditionDialog(); enabled = useAdditionDialog();
settings.setValue("Enabled", enabled); settings.setValue(QString::fromUtf8("Enabled"), enabled);
if(!enabled){ if(!enabled){
settings.setValue("SavePath", getSavePath()); settings.setValue(QString::fromUtf8("SavePath"), getSavePath());
} }
settings.endGroup(); settings.endGroup();
settings.beginGroup("Behaviour"); settings.beginGroup(QString::fromUtf8("Behaviour"));
settings.setValue("ConfirmOnExit", getConfirmOnExit()); settings.setValue(QString::fromUtf8("ConfirmOnExit"), getConfirmOnExit());
settings.setValue("GoToSystray", getGoToSysTrayOnMinimizingWindow()); settings.setValue(QString::fromUtf8("GoToSystray"), getGoToSysTrayOnMinimizingWindow());
settings.setValue("GoToSystrayOnExit", getGoToSysTrayOnExitingWindow()); settings.setValue(QString::fromUtf8("GoToSystrayOnExit"), getGoToSysTrayOnExitingWindow());
settings.setValue("SystrayIntegration", useSystrayIntegration()); settings.setValue(QString::fromUtf8("SystrayIntegration"), useSystrayIntegration());
// End Behaviour group // End Behaviour group
settings.endGroup(); settings.endGroup();
settings.setValue("PreviewProgram", getPreviewProgram()); settings.setValue(QString::fromUtf8("PreviewProgram"), getPreviewProgram());
// End Misc options // End Misc options
settings.endGroup(); settings.endGroup();
if(getUseOSDAlways()){ if(getUseOSDAlways()){
settings.setValue("OSDEnabled", 1); settings.setValue(QString::fromUtf8("OSDEnabled"), 1);
}else{ }else{
if(getUseOSDWhenHiddenOnly()){ if(getUseOSDWhenHiddenOnly()){
settings.setValue("OSDEnabled", 2); settings.setValue(QString::fromUtf8("OSDEnabled"), 2);
}else{ }else{
settings.setValue("OSDEnabled", 0); settings.setValue(QString::fromUtf8("OSDEnabled"), 0);
} }
} }
settings.setValue("Style", getStyle()); settings.setValue(QString::fromUtf8("Style"), getStyle());
// End Options group // End Options group
settings.endGroup(); settings.endGroup();
} }
@ -387,39 +387,39 @@ bool options_imp::useProxyForDHT() const{
} }
QString options_imp::getStyle() const{ QString options_imp::getStyle() const{
if(radioPlastiqueStyle->isChecked()) return "Plastique"; if(radioPlastiqueStyle->isChecked()) return QString::fromUtf8("Plastique");
if(radioCleanlooksStyle->isChecked()) return "Cleanlooks"; if(radioCleanlooksStyle->isChecked()) return QString::fromUtf8("Cleanlooks");
if(radioMotifStyle->isChecked()) return "Motif"; if(radioMotifStyle->isChecked()) return QString::fromUtf8("Motif");
if(radioCDEStyle->isChecked()) return "CDE"; if(radioCDEStyle->isChecked()) return QString::fromUtf8("CDE");
if(radioMacOSStyle->isChecked()) return "MacOS"; if(radioMacOSStyle->isChecked()) return QString::fromUtf8("MacOS");
if(radioWinXPStyle->isChecked()) return "WinXP"; if(radioWinXPStyle->isChecked()) return QString::fromUtf8("WinXP");
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
return "WinXP"; return QString::fromUtf8("WinXP");
#endif #endif
#ifdef Q_WS_MAC #ifdef Q_WS_MAC
return "MacOS"; return QString::fromUtf8("MacOS");
#endif #endif
return "Plastique"; return QString::fromUtf8("Plastique");
} }
void options_imp::setStyle(QString style){ void options_imp::setStyle(QString style){
if(style == "Cleanlooks"){ if(style == QString::fromUtf8("Cleanlooks")){
radioCleanlooksStyle->setChecked(true); radioCleanlooksStyle->setChecked(true);
return; return;
} }
if(style == "Motif"){ if(style == QString::fromUtf8("Motif")){
radioMotifStyle->setChecked(true); radioMotifStyle->setChecked(true);
return; return;
} }
if(style == "CDE"){ if(style == QString::fromUtf8("CDE")){
radioCDEStyle->setChecked(true); radioCDEStyle->setChecked(true);
return; return;
} }
if(style == "MacOS"){ if(style == QString::fromUtf8("MacOS")){
radioMacOSStyle->setChecked(true); radioMacOSStyle->setChecked(true);
return; return;
} }
if(style == "WinXP"){ if(style == QString::fromUtf8("WinXP")){
radioWinXPStyle->setChecked(true); radioWinXPStyle->setChecked(true);
return; return;
} }
@ -434,10 +434,10 @@ void options_imp::loadOptions(){
QSettings settings("qBittorrent", "qBittorrent"); QSettings settings("qBittorrent", "qBittorrent");
// Check if min port < max port // Check if min port < max port
checkPortsLogic(); checkPortsLogic();
settings.beginGroup("Options"); settings.beginGroup(QString::fromUtf8("Options"));
// Main options // Main options
settings.beginGroup("Main"); settings.beginGroup(QString::fromUtf8("Main"));
value = settings.value("DLLimit", -1).toInt(); value = settings.value(QString::fromUtf8("DLLimit"), -1).toInt();
if(value < 0){ if(value < 0){
disableDLLimit->setChecked(true); disableDLLimit->setChecked(true);
spin_download->setEnabled(false); spin_download->setEnabled(false);
@ -446,7 +446,7 @@ void options_imp::loadOptions(){
spin_download->setEnabled(true); spin_download->setEnabled(true);
spin_download->setValue(value); spin_download->setValue(value);
} }
value = settings.value("UPLimit", -1).toInt(); value = settings.value(QString::fromUtf8("UPLimit"), -1).toInt();
if(value < 0){ if(value < 0){
disableUPLimit->setChecked(true); disableUPLimit->setChecked(true);
spin_upload->setEnabled(false); spin_upload->setEnabled(false);
@ -455,7 +455,7 @@ void options_imp::loadOptions(){
spin_upload->setEnabled(true); spin_upload->setEnabled(true);
spin_upload->setValue(value); spin_upload->setValue(value);
} }
value = settings.value("MaxConnecs", -1).toInt(); value = settings.value(QString::fromUtf8("MaxConnecs"), -1).toInt();
if(value < 0){ if(value < 0){
disableMaxConnec->setChecked(true); disableMaxConnec->setChecked(true);
spin_max_connec->setEnabled(false); spin_max_connec->setEnabled(false);
@ -464,9 +464,9 @@ void options_imp::loadOptions(){
spin_max_connec->setEnabled(true); spin_max_connec->setEnabled(true);
spin_max_connec->setValue(value); spin_max_connec->setValue(value);
} }
spin_port_min->setValue(settings.value("PortRangeMin", 6881).toInt()); spin_port_min->setValue(settings.value(QString::fromUtf8("PortRangeMin"), 6881).toInt());
spin_port_max->setValue(settings.value("PortRangeMax", 6889).toInt()); spin_port_max->setValue(settings.value(QString::fromUtf8("PortRangeMax"), 6889).toInt());
floatValue = settings.value("ShareRatio", 0).toDouble(); floatValue = settings.value(QString::fromUtf8("ShareRatio"), 0).toDouble();
if(floatValue == 0){ if(floatValue == 0){
disableRatio->setChecked(true); disableRatio->setChecked(true);
spin_ratio->setEnabled(false); spin_ratio->setEnabled(false);
@ -475,7 +475,7 @@ void options_imp::loadOptions(){
spin_ratio->setEnabled(true); spin_ratio->setEnabled(true);
spin_ratio->setValue(floatValue); spin_ratio->setValue(floatValue);
} }
value = settings.value("DHTPort", 6881).toInt(); value = settings.value(QString::fromUtf8("DHTPort"), 6881).toInt();
if(value < 0){ if(value < 0){
disableDHT->setChecked(true); disableDHT->setChecked(true);
groupDHT->setEnabled(false); groupDHT->setEnabled(false);
@ -487,9 +487,9 @@ void options_imp::loadOptions(){
} }
spin_dht_port->setValue(value); spin_dht_port->setValue(value);
} }
value = settings.value("EncryptionState", 0).toInt(); value = settings.value(QString::fromUtf8("EncryptionState"), 0).toInt();
comboEncryption->setCurrentIndex(value); comboEncryption->setCurrentIndex(value);
boolValue = settings.value("PeXState", true).toBool(); boolValue = settings.value(QString::fromUtf8("PeXState"), true).toBool();
if(boolValue){ if(boolValue){
// Pex disabled // Pex disabled
disablePeX->setChecked(false); disablePeX->setChecked(false);
@ -497,7 +497,7 @@ void options_imp::loadOptions(){
// PeX enabled // PeX enabled
disablePeX->setChecked(true); disablePeX->setChecked(true);
} }
strValue = settings.value("ScanDir", QString()).toString(); strValue = settings.value(QString::fromUtf8("ScanDir"), QString()).toString();
if(!strValue.isEmpty()){ if(!strValue.isEmpty()){
enableScan_checkBox->setChecked(true); enableScan_checkBox->setChecked(true);
lbl_scanDir->setEnabled(true); lbl_scanDir->setEnabled(true);
@ -513,15 +513,15 @@ void options_imp::loadOptions(){
// End Main options // End Main options
settings.endGroup(); settings.endGroup();
// Language options // Language options
settings.beginGroup("Language"); settings.beginGroup(QString::fromUtf8("Language"));
strValue = settings.value("Locale", "en_GB").toString(); strValue = settings.value(QString::fromUtf8("Locale"), QString::fromUtf8("en_GB")).toString();
setLocale(strValue); setLocale(strValue);
// End Language options // End Language options
settings.endGroup(); settings.endGroup();
// IPFilter options // IPFilter options
settings.beginGroup("IPFilter"); settings.beginGroup(QString::fromUtf8("IPFilter"));
if(settings.value("Enabled", false).toBool()){ if(settings.value(QString::fromUtf8("Enabled"), false).toBool()){
strValue = settings.value("File", QString()).toString(); strValue = settings.value(QString::fromUtf8("File"), QString()).toString();
activateFilter->setChecked(true); activateFilter->setChecked(true);
filterGroup->setEnabled(true); filterGroup->setEnabled(true);
filterFile->setText(strValue); filterFile->setText(strValue);
@ -533,9 +533,9 @@ void options_imp::loadOptions(){
// End IPFilter options // End IPFilter options
settings.endGroup(); settings.endGroup();
// Proxy options // Proxy options
settings.beginGroup("Proxy"); settings.beginGroup(QString::fromUtf8("Proxy"));
if(settings.value("Enabled", false).toBool()){ if(settings.value(QString::fromUtf8("Enabled"), false).toBool()){
strValue = settings.value("IP", QString()).toString(); strValue = settings.value(QString::fromUtf8("IP"), QString()).toString();
if(strValue.isEmpty()){ if(strValue.isEmpty()){
enableProxy_checkBox->setChecked(false); enableProxy_checkBox->setChecked(false);
groupProxy->setEnabled(false); groupProxy->setEnabled(false);
@ -543,18 +543,18 @@ void options_imp::loadOptions(){
enableProxy_checkBox->setChecked(true); enableProxy_checkBox->setChecked(true);
groupProxy->setEnabled(true); groupProxy->setEnabled(true);
proxy_ip->setText(strValue); proxy_ip->setText(strValue);
proxy_port->setValue(settings.value("Port", 8080).toInt()); proxy_port->setValue(settings.value(QString::fromUtf8("Port"), 8080).toInt());
comboProxyType->setCurrentIndex(settings.value("ProxyType", HTTP).toInt()); comboProxyType->setCurrentIndex(settings.value(QString::fromUtf8("ProxyType"), HTTP).toInt());
checkProxyTrackers->setChecked(settings.value("useProxyForTrackers", true).toBool()); checkProxyTrackers->setChecked(settings.value(QString::fromUtf8("useProxyForTrackers"), true).toBool());
checkProxyPeers->setChecked(settings.value("useProxyForPeers", true).toBool()); checkProxyPeers->setChecked(settings.value(QString::fromUtf8("useProxyForPeers"), true).toBool());
checkProxyWebseeds->setChecked(settings.value("useProxyForWebseeds", true).toBool()); checkProxyWebseeds->setChecked(settings.value(QString::fromUtf8("useProxyForWebseeds"), true).toBool());
checkProxyDHT->setChecked(settings.value("useProxyForDHT", true).toBool()); checkProxyDHT->setChecked(settings.value(QString::fromUtf8("useProxyForDHT"), true).toBool());
settings.beginGroup("Authentication"); settings.beginGroup(QString::fromUtf8("Authentication"));
if(settings.value("Enabled", false).toBool()){ if(settings.value(QString::fromUtf8("Enabled"), false).toBool()){
enableProxyAuth_checkBox->setChecked(true); enableProxyAuth_checkBox->setChecked(true);
groupProxyAuth->setEnabled(true); groupProxyAuth->setEnabled(true);
proxy_username->setText(settings.value("Username", QString()).toString()); proxy_username->setText(settings.value(QString::fromUtf8("Username"), QString()).toString());
proxy_password->setText(settings.value("Password", QString()).toString()); proxy_password->setText(settings.value(QString::fromUtf8("Password"), QString()).toString());
}else{ }else{
enableProxyAuth_checkBox->setChecked(false); enableProxyAuth_checkBox->setChecked(false);
groupProxyAuth->setEnabled(false); groupProxyAuth->setEnabled(false);
@ -568,30 +568,30 @@ void options_imp::loadOptions(){
// End Proxy options // End Proxy options
settings.endGroup(); settings.endGroup();
// Misc options // Misc options
settings.beginGroup("Misc"); settings.beginGroup(QString::fromUtf8("Misc"));
settings.beginGroup("TorrentAdditionDialog"); settings.beginGroup(QString::fromUtf8("TorrentAdditionDialog"));
if(settings.value("Enabled", true).toBool()){ if(settings.value(QString::fromUtf8("Enabled"), true).toBool()){
checkAdditionDialog->setChecked(true); checkAdditionDialog->setChecked(true);
groupSavePath->setEnabled(false); groupSavePath->setEnabled(false);
}else{ }else{
checkAdditionDialog->setChecked(false); checkAdditionDialog->setChecked(false);
groupSavePath->setEnabled(true); groupSavePath->setEnabled(true);
txt_savePath->setText(settings.value("SavePath", QString()).toString()); txt_savePath->setText(settings.value(QString::fromUtf8("SavePath"), QString()).toString());
} }
settings.endGroup(); settings.endGroup();
settings.beginGroup("Behaviour"); settings.beginGroup(QString::fromUtf8("Behaviour"));
confirmExit_checkBox->setChecked(settings.value("ConfirmOnExit", true).toBool()); confirmExit_checkBox->setChecked(settings.value(QString::fromUtf8("ConfirmOnExit"), true).toBool());
check_goToSysTray->setChecked(settings.value("GoToSystray", true).toBool()); check_goToSysTray->setChecked(settings.value(QString::fromUtf8("GoToSystray"), true).toBool());
check_closeToSysTray->setChecked(settings.value("GoToSystrayOnExit", false).toBool()); check_closeToSysTray->setChecked(settings.value(QString::fromUtf8("GoToSystrayOnExit"), false).toBool());
boolValue = settings.value("SystrayIntegration", true).toBool(); boolValue = settings.value(QString::fromUtf8("SystrayIntegration"), true).toBool();
check_disableSystray->setChecked(!boolValue); check_disableSystray->setChecked(!boolValue);
systrayDisabled(!boolValue); systrayDisabled(!boolValue);
// End Behaviour group // End Behaviour group
settings.endGroup(); settings.endGroup();
preview_program->setText(settings.value("PreviewProgram", QString()).toString()); preview_program->setText(settings.value(QString::fromUtf8("PreviewProgram"), QString()).toString());
// End Misc group // End Misc group
settings.endGroup(); settings.endGroup();
value = settings.value("OSDEnabled", 1).toInt(); value = settings.value(QString::fromUtf8("OSDEnabled"), 1).toInt();
if(value == 0){ if(value == 0){
neverOSD->setChecked(true); neverOSD->setChecked(true);
}else{ }else{
@ -601,7 +601,7 @@ void options_imp::loadOptions(){
alwaysOSD->setChecked(true); alwaysOSD->setChecked(true);
} }
} }
setStyle(settings.value("Style", QString()).toString()); setStyle(settings.value(QString::fromUtf8("Style"), QString()).toString());
// End Options group // End Options group
settings.endGroup(); settings.endGroup();
} }
@ -716,7 +716,7 @@ QString options_imp::getSavePath() const{
home += QDir::separator(); home += QDir::separator();
} }
if(txt_savePath->text().trimmed().isEmpty()){ if(txt_savePath->text().trimmed().isEmpty()){
txt_savePath->setText(home+"qBT_dir"); txt_savePath->setText(home+QString::fromUtf8("qBT_dir"));
} }
return txt_savePath->text(); return txt_savePath->text();
} }
@ -978,7 +978,7 @@ void options_imp::on_browse_button_clicked(){
void options_imp::processFilterFile(QString filePath){ void options_imp::processFilterFile(QString filePath){
qDebug("Processing filter files"); qDebug("Processing filter files");
filtersList->clear(); filtersList->clear();
QString manualFilters= misc::qBittorrentPath() + "ipfilter.dat"; QString manualFilters= misc::qBittorrentPath() + QString::fromUtf8("ipfilter.dat");
QStringList filterFiles(manualFilters); QStringList filterFiles(manualFilters);
filterFiles.append(filePath); filterFiles.append(filePath);
for(int i=0; i<2; ++i){ for(int i=0; i<2; ++i){
@ -1018,8 +1018,8 @@ void options_imp::processFilterFile(QString filePath){
} }
// Split IP // Split IP
QRegExp is_ipv6("^[0-9a-f]{4}(:[0-9a-f]{4}){7}$", 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("^(([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_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)) { if(strStartIP.contains(is_ipv4) && strEndIP.contains(is_ipv4)) {
// IPv4 // IPv4
@ -1032,9 +1032,9 @@ void options_imp::processFilterFile(QString filePath){
QStringList item(QString(start.to_string().c_str())); QStringList item(QString(start.to_string().c_str()));
item.append(QString(last.to_string().c_str())); item.append(QString(last.to_string().c_str()));
if(!i){ if(!i){
item.append("Manual"); item.append(QString::fromUtf8("Manual"));
}else{ }else{
item.append("ipfilter.dat"); item.append(QString::fromUtf8("ipfilter.dat"));
} }
item.append(strComment); item.append(strComment);
new QTreeWidgetItem(filtersList, item); new QTreeWidgetItem(filtersList, item);
@ -1051,9 +1051,9 @@ void options_imp::processFilterFile(QString filePath){
QStringList item(QString(start.to_string().c_str())); QStringList item(QString(start.to_string().c_str()));
item.append(QString(last.to_string().c_str())); item.append(QString(last.to_string().c_str()));
if(!i){ if(!i){
item.append("Manual"); item.append(QString::fromUtf8("Manual"));
}else{ }else{
item.append("ipfilter.dat"); item.append(QString::fromUtf8("ipfilter.dat"));
} }
item.append(strComment); item.append(strComment);
new QTreeWidgetItem(filtersList, item); new QTreeWidgetItem(filtersList, item);
@ -1082,12 +1082,12 @@ void options_imp::on_addFilterRange_clicked(){
// Ask user for start ip // Ask user for start ip
QString startIP = QInputDialog::getText(this, tr("Range Start IP"), QString startIP = QInputDialog::getText(this, tr("Range Start IP"),
tr("Start IP:"), QLineEdit::Normal, tr("Start IP:"), QLineEdit::Normal,
"0.0.0.0", &ok); QString::fromUtf8("0.0.0.0"), &ok);
QStringList IP1 = startIP.split('.'); QStringList IP1 = startIP.split('.');
// Check IP // Check IP
bool ipv4 = true; bool ipv4 = true;
QRegExp is_ipv6("^[0-9a-f]{4}(:[0-9a-f]{4}){7}$", 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("^(([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_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 // Ask user for Comment
QString comment = QInputDialog::getText(this, tr("IP Range Comment"), QString comment = QInputDialog::getText(this, tr("IP Range Comment"),
tr("Comment:"), QLineEdit::Normal, tr("Comment:"), QLineEdit::Normal,
"", &ok); QString::fromUtf8(""), &ok);
if (!ok){ if (!ok){
comment = QString(""); comment = QString::fromUtf8("");
return; return;
} }
QFile ipfilter(misc::qBittorrentPath() + "ipfilter.dat"); QFile ipfilter(misc::qBittorrentPath() + QString::fromUtf8("ipfilter.dat"));
if (!ipfilter.open(QIODevice::Append | QIODevice::WriteOnly | QIODevice::Text)){ if (!ipfilter.open(QIODevice::Append | QIODevice::WriteOnly | QIODevice::Text)){
std::cerr << "Error: Couldn't write in ipfilter.dat"; std::cerr << "Error: Couldn't write in ipfilter.dat";
return; return;
@ -1146,7 +1146,7 @@ void options_imp::on_delFilterRange_clicked(){
// Delete from list // Delete from list
for(int i=0;i<selectedItems.size();++i){ for(int i=0;i<selectedItems.size();++i){
QTreeWidgetItem *item = selectedItems.at(i); QTreeWidgetItem *item = selectedItems.at(i);
if(item->text(2) == "Manual"){ if(item->text(2) == QString::fromUtf8("Manual")){
delete item; delete item;
changed = true; changed = true;
} }
@ -1155,7 +1155,7 @@ void options_imp::on_delFilterRange_clicked(){
} }
} }
// Update ipfilter.dat // Update ipfilter.dat
QFile ipfilter(misc::qBittorrentPath() + "ipfilter.dat"); QFile ipfilter(misc::qBittorrentPath() + QString::fromUtf8("ipfilter.dat"));
if (!ipfilter.open(QIODevice::WriteOnly | QIODevice::Text)){ if (!ipfilter.open(QIODevice::WriteOnly | QIODevice::Text)){
std::cerr << "Error: Couldn't write in ipfilter.dat"; std::cerr << "Error: Couldn't write in ipfilter.dat";
return; return;
@ -1163,7 +1163,7 @@ void options_imp::on_delFilterRange_clicked(){
QTextStream out(&ipfilter); QTextStream out(&ipfilter);
for(int i=0; i<filtersList->topLevelItemCount();++i){ for(int i=0; i<filtersList->topLevelItemCount();++i){
QTreeWidgetItem *item = filtersList->topLevelItem(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"; out << item->text(0) << " - " << item->text(1) << ", 0, " << item->text(3) << "\n";
} }
} }

View file

@ -30,6 +30,7 @@
#include "ui_preview.h" #include "ui_preview.h"
#include "PreviewListDelegate.h" #include "PreviewListDelegate.h"
#include "misc.h" #include "misc.h"
#include "qtorrenthandle.h"
#define NAME 0 #define NAME 0
#define SIZE 1 #define SIZE 1
@ -44,7 +45,7 @@ class previewSelect: public QDialog, private Ui::preview {
QStandardItemModel *previewListModel; QStandardItemModel *previewListModel;
PreviewListDelegate *listDelegate; PreviewListDelegate *listDelegate;
QStringList supported_preview_extensions; QStringList supported_preview_extensions;
torrent_handle h; QTorrentHandle h;
signals: signals:
void readyToPreviewFile(QString) const; void readyToPreviewFile(QString) const;
@ -56,9 +57,9 @@ class previewSelect: public QDialog, private Ui::preview {
QModelIndexList selectedIndexes = previewList->selectionModel()->selectedIndexes(); QModelIndexList selectedIndexes = previewList->selectionModel()->selectedIndexes();
foreach(index, selectedIndexes){ foreach(index, selectedIndexes){
if(index.column() == NAME){ 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()){ if(root_path.at(root_path.length()-1) != QDir::separator()){
root_path += '/'; root_path += QString::fromUtf8("/");
} }
// Get the file name // Get the file name
QString fileName = index.data().toString(); QString fileName = index.data().toString();
@ -68,7 +69,7 @@ class previewSelect: public QDialog, private Ui::preview {
found = true; found = true;
}else{ }else{
// Folder // 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 // Will find the file even if it is in a sub directory
QString result = misc::findFileInDir(root_path+folder_name, fileName); QString result = misc::findFileInDir(root_path+folder_name, fileName);
if(!result.isNull()){ if(!result.isNull()){
@ -90,7 +91,7 @@ class previewSelect: public QDialog, private Ui::preview {
} }
public: public:
previewSelect(QWidget* parent, torrent_handle h): QDialog(parent){ previewSelect(QWidget* parent, QTorrentHandle h): QDialog(parent){
setupUi(this); setupUi(this);
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
// Preview list // Preview list
@ -101,21 +102,21 @@ class previewSelect: public QDialog, private Ui::preview {
previewList->setModel(previewListModel); previewList->setModel(previewListModel);
listDelegate = new PreviewListDelegate(this); listDelegate = new PreviewListDelegate(this);
previewList->setItemDelegate(listDelegate); 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); previewList->header()->resizeSection(0, 200);
// Fill list in // Fill list in
this->h = h; this->h = h;
torrent_info torrentInfo = h.get_torrent_info();
std::vector<float> fp; std::vector<float> fp;
h.file_progress(fp); h.file_progress(fp);
for(int i=0; i<torrentInfo.num_files(); ++i){ unsigned int nbFiles = h.num_files();
QString fileName = QString(torrentInfo.file_at(i).path.leaf().c_str()); for(unsigned int i=0; i<nbFiles; ++i){
QString extension = fileName.split('.').last().toUpper(); QString fileName = h.file_at(i);
QString extension = fileName.split(QString::fromUtf8(".")).last().toUpper();
if(supported_preview_extensions.indexOf(extension) >= 0){ if(supported_preview_extensions.indexOf(extension) >= 0){
int row = previewListModel->rowCount(); int row = previewListModel->rowCount();
previewListModel->insertRow(row); previewListModel->insertRow(row);
previewListModel->setData(previewListModel->index(row, NAME), QVariant(fileName)); 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])); previewListModel->setData(previewListModel->index(row, PROGRESS), QVariant((double)fp[i]));
} }
} }

View file

@ -31,7 +31,7 @@
#include <QStandardItemModel> #include <QStandardItemModel>
// Constructor // 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); setupUi(this);
this->BTSession = BTSession; this->BTSession = BTSession;
changedFilteredfiles = false; changedFilteredfiles = false;
@ -66,34 +66,32 @@ properties::properties(QWidget *parent, bittorrent *BTSession, torrent_handle &h
connect(addWS_button, SIGNAL(clicked()), this, SLOT(askWebSeed())); connect(addWS_button, SIGNAL(clicked()), this, SLOT(askWebSeed()));
connect(deleteWS_button, SIGNAL(clicked()), this, SLOT(deleteSelectedUrlSeeds())); connect(deleteWS_button, SIGNAL(clicked()), this, SLOT(deleteSelectedUrlSeeds()));
// get Infos from torrent handle // get Infos from torrent handle
fileHash = QString(misc::toString(h.info_hash()).c_str()); hash = h.hash();
torrent_status torrentStatus = h.status(); fileName->setText(h.name());
torrent_info torrentInfo = h.get_torrent_info();
fileName->setText(torrentInfo.name().c_str());
// Torrent Infos // Torrent Infos
save_path->setText(QString(h.save_path().string().c_str())); save_path->setText(h.save_path());
QString author = QString(torrentInfo.creator().c_str()).trimmed(); QString author = h.creator().trimmed();
if(author.isEmpty()) if(author.isEmpty())
author = tr("Unknown"); author = tr("Unknown");
creator->setText(author); creator->setText(author);
hash_lbl->setText(fileHash); hash_lbl->setText(hash);
comment_txt->setText(QString(torrentInfo.comment().c_str())); comment_txt->setText(h.comment());
//Trackers //Trackers
loadTrackers(); loadTrackers();
// Session infos // Session infos
char tmp[MAX_CHAR_TMP]; char tmp[MAX_CHAR_TMP];
failed->setText(misc::friendlyUnit(torrentStatus.total_failed_bytes)); failed->setText(misc::friendlyUnit(h.total_failed_bytes()));
upTotal->setText(misc::friendlyUnit(torrentStatus.total_payload_upload)); upTotal->setText(misc::friendlyUnit(h.total_payload_upload()));
dlTotal->setText(misc::friendlyUnit(torrentStatus.total_payload_download)); dlTotal->setText(misc::friendlyUnit(h.total_payload_download()));
// Update ratio info // Update ratio info
float ratio; float ratio;
if(torrentStatus.total_payload_download == 0){ if(h.total_payload_download() == 0){
if(torrentStatus.total_payload_upload == 0) if(h.total_payload_upload() == 0)
ratio = 1.; ratio = 1.;
else else
ratio = 10.; // Max ratio ratio = 10.; // Max ratio
}else{ }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.){ if(ratio > 10.){
ratio = 10.; ratio = 10.;
} }
@ -104,12 +102,12 @@ properties::properties(QWidget *parent, bittorrent *BTSession, torrent_handle &h
std::vector<float> fp; std::vector<float> fp;
h.file_progress(fp); h.file_progress(fp);
// List files in torrent // List files in torrent
unsigned int nbFiles = torrentInfo.num_files(); unsigned int nbFiles = h.num_files();
for(unsigned int i=0; i<nbFiles; ++i){ for(unsigned int i=0; i<nbFiles; ++i){
unsigned int row = PropListModel->rowCount(); unsigned int row = PropListModel->rowCount();
PropListModel->insertRow(row); PropListModel->insertRow(row);
PropListModel->setData(PropListModel->index(row, NAME), QVariant(torrentInfo.file_at(i).path.leaf().c_str())); PropListModel->setData(PropListModel->index(row, NAME), QVariant(h.file_at(i)));
PropListModel->setData(PropListModel->index(row, SIZE), QVariant((qlonglong)torrentInfo.file_at(i).size)); PropListModel->setData(PropListModel->index(row, SIZE), QVariant((qlonglong)h.filesize_at(i)));
PropListModel->setData(PropListModel->index(row, PROGRESS), QVariant((double)fp[i])); PropListModel->setData(PropListModel->index(row, PROGRESS), QVariant((double)fp[i]));
} }
loadPiecesPriorities(); loadPiecesPriorities();
@ -117,7 +115,7 @@ properties::properties(QWidget *parent, bittorrent *BTSession, torrent_handle &h
loadWebSeedsFromFile(); loadWebSeedsFromFile();
loadWebSeeds(); loadWebSeeds();
// Incremental download // 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); incrementalDownload->setChecked(true);
}else{ }else{
incrementalDownload->setChecked(false); incrementalDownload->setChecked(false);
@ -136,12 +134,12 @@ properties::~properties(){
void properties::loadTrackersErrors(){ void properties::loadTrackersErrors(){
// Tracker Errors // Tracker Errors
QList<QPair<QString, QString> > errors = BTSession->getTrackersErrors(fileHash); QList<QPair<QString, QString> > errors = BTSession->getTrackersErrors(hash);
unsigned int nbTrackerErrors = errors.size(); unsigned int nbTrackerErrors = errors.size();
trackerErrors->clear(); trackerErrors->clear();
for(unsigned int i=0; i < nbTrackerErrors; ++i){ for(unsigned int i=0; i < nbTrackerErrors; ++i){
QPair<QString, QString> pair = errors.at(i); QPair<QString, QString> pair = errors.at(i);
trackerErrors->append("<font color='grey'>"+pair.first+"</font> - <font color='red'>"+pair.second+"</font>"); trackerErrors->append(QString::fromUtf8("<font color='grey'>")+pair.first+QString::fromUtf8("</font> - <font color='red'>")+pair.second+QString::fromUtf8("</font>"));
} }
if(!nbTrackerErrors) if(!nbTrackerErrors)
trackerErrors->append(tr("None", "i.e: No error message")); trackerErrors->append(tr("None", "i.e: No error message"));
@ -154,15 +152,14 @@ void properties::loadWebSeeds(){
// Add manually added url seeds // Add manually added url seeds
foreach(url_seed, urlSeeds){ foreach(url_seed, urlSeeds){
listWebSeeds->addItem(url_seed); 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(){ void properties::loadPiecesPriorities(){
torrent_info torrentInfo = h.get_torrent_info(); unsigned int nbFiles = h.num_files();
unsigned int nbFiles = torrentInfo.num_files(); QString fileName = h.name();
QString fileName = QString(torrentInfo.name().c_str()); QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".priorities");
QFile pieces_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".priorities");
has_filtered_files = false; has_filtered_files = false;
qDebug("Loading pieces priorities"); qDebug("Loading pieces priorities");
// Read saved file // Read saved file
@ -308,8 +305,7 @@ void properties::loadTrackers(){
for(unsigned int i=0; i<nbTrackers; ++i){ for(unsigned int i=0; i<nbTrackers; ++i){
trackersURLS->addItem(QString(trackers[i].url.c_str())); trackersURLS->addItem(QString(trackers[i].url.c_str()));
} }
torrent_status torrentStatus = h.status(); QString tracker = h.current_tracker().trimmed();
QString tracker = QString(torrentStatus.current_tracker.c_str()).trimmed();
if(!tracker.isEmpty()){ if(!tracker.isEmpty()){
trackerURL->setText(tracker); trackerURL->setText(tracker);
}else{ }else{
@ -322,10 +318,9 @@ void properties::askWebSeed(){
// Ask user for a new url seed // Ask user for a new url seed
QString url_seed = QInputDialog::getText(this, tr("New url seed", "New HTTP source"), QString url_seed = QInputDialog::getText(this, tr("New url seed", "New HTTP source"),
tr("New url seed:"), QLineEdit::Normal, tr("New url seed:"), QLineEdit::Normal,
"http://www.", &ok); QString::fromUtf8("http://www."), &ok);
if(!ok) return; if(!ok) return;
torrent_info torrentInfo = h.get_torrent_info(); qDebug("Adding %s web seed", url_seed.toUtf8().data());
qDebug("Adding %s web seed", (const char*)url_seed.toUtf8());
if(urlSeeds.indexOf(url_seed) != -1) { if(urlSeeds.indexOf(url_seed) != -1) {
QMessageBox::warning(this, tr("qBittorrent"), QMessageBox::warning(this, tr("qBittorrent"),
tr("This url seed is already in the list."), tr("This url seed is already in the list."),
@ -333,7 +328,7 @@ void properties::askWebSeed(){
return; return;
} }
urlSeeds << url_seed; urlSeeds << url_seed;
torrentInfo.add_url_seed(url_seed.toStdString()); h.add_url_seed(url_seed);
saveWebSeeds(); saveWebSeeds();
// Refresh the seeds list // Refresh the seeds list
loadWebSeeds(); loadWebSeeds();
@ -351,7 +346,7 @@ void properties::askForTracker(){
if(!ok) return; if(!ok) return;
// Add the tracker to the list // Add the tracker to the list
std::vector<announce_entry> trackers = h.trackers(); std::vector<announce_entry> 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 new_tracker.tier = 0; // Will be fixed a bit later
trackers.push_back(new_tracker); trackers.push_back(new_tracker);
misc::fixTrackersTiers(trackers); misc::fixTrackersTiers(trackers);
@ -371,7 +366,7 @@ void properties::deleteSelectedUrlSeeds(){
int index = urlSeeds.indexOf(url_seed); int index = urlSeeds.indexOf(url_seed);
Q_ASSERT(index != -1); Q_ASSERT(index != -1);
urlSeeds.removeAt(index); urlSeeds.removeAt(index);
h.remove_url_seed(misc::toString((const char*)url_seed.toUtf8())); h.remove_url_seed(url_seed);
change = true; change = true;
} }
if(change){ if(change){
@ -397,7 +392,7 @@ void properties::deleteSelectedTrackers(){
foreach(item, selectedItems){ foreach(item, selectedItems){
QString url = item->text(); QString url = item->text();
for(unsigned int i=0; i<nbTrackers; ++i){ for(unsigned int i=0; i<nbTrackers; ++i){
if(QString(trackers.at(i).url.c_str()) == url){ if(misc::toQString(trackers.at(i).url) == url){
trackers.erase(trackers.begin()+i); trackers.erase(trackers.begin()+i);
break; break;
} }
@ -420,7 +415,7 @@ void properties::riseSelectedTracker(){
foreach(item, selectedItems){ foreach(item, selectedItems){
QString url = item->text(); QString url = item->text();
for(i=0; i<nbTrackers; ++i){ for(i=0; i<nbTrackers; ++i){
if(QString(trackers.at(i).url.c_str()) == url){ if(misc::toQString(trackers.at(i).url) == url){
qDebug("Asked to rise %s", trackers.at(i).url.c_str()); qDebug("Asked to rise %s", trackers.at(i).url.c_str());
qDebug("its tier was %d and will become %d", trackers[i].tier, trackers[i].tier-1); qDebug("its tier was %d and will become %d", trackers[i].tier, trackers[i].tier-1);
if(i > 0){ if(i > 0){
@ -481,8 +476,8 @@ void properties::updateInfos(){
std::vector<float> fp; std::vector<float> fp;
try{ try{
h.file_progress(fp); h.file_progress(fp);
torrent_info torrentInfo = h.get_torrent_info(); unsigned int nbFiles = h.num_files();
for(int i=0; i<torrentInfo.num_files(); ++i){ for(unsigned int i=0; i<nbFiles; ++i){
PropListModel->setData(PropListModel->index(i, PROGRESS), QVariant((double)fp[i])); PropListModel->setData(PropListModel->index(i, PROGRESS), QVariant((double)fp[i]));
} }
}catch(invalid_handle e){ }catch(invalid_handle e){
@ -490,8 +485,7 @@ void properties::updateInfos(){
close(); close();
} }
// Update current tracker // Update current tracker
torrent_status torrentStatus = h.status(); QString tracker = h.current_tracker().trimmed();
QString tracker = QString(torrentStatus.current_tracker.c_str()).trimmed();
if(!tracker.isEmpty()){ if(!tracker.isEmpty()){
trackerURL->setText(tracker); trackerURL->setText(tracker);
}else{ }else{
@ -501,14 +495,15 @@ void properties::updateInfos(){
// Set the color of a row in data model // Set the color of a row in data model
void properties::setRowColor(int row, QString color){ void properties::setRowColor(int row, QString color){
for(int i=0; i<PropListModel->columnCount(); ++i){ unsigned int nbCol = PropListModel->columnCount();
for(unsigned int i=0; i<nbCol; ++i){
PropListModel->setData(PropListModel->index(row, i), QVariant(QColor(color)), Qt::ForegroundRole); PropListModel->setData(PropListModel->index(row, i), QVariant(QColor(color)), Qt::ForegroundRole);
} }
} }
void properties::setAllPiecesState(unsigned short priority){ void properties::setAllPiecesState(unsigned short priority){
torrent_info torrentInfo = h.get_torrent_info(); unsigned int nbFiles = h.num_files();
for(int i=0; i<torrentInfo.num_files(); ++i){ for(unsigned int i=0; i<nbFiles; ++i){
if(priority){ if(priority){
setRowColor(i, "green"); setRowColor(i, "green");
}else{ }else{
@ -520,16 +515,17 @@ void properties::setAllPiecesState(unsigned short priority){
void properties::on_incrementalDownload_stateChanged(int){ void properties::on_incrementalDownload_stateChanged(int){
qDebug("Incremental download toggled"); qDebug("Incremental download toggled");
torrent_info torrentInfo = h.get_torrent_info();
if(incrementalDownload->isChecked()){ if(incrementalDownload->isChecked()){
if(!QFile::exists(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".incremental"))) {
// Create .incremental file // Create .incremental file
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.open(QIODevice::WriteOnly | QIODevice::Text);
incremental_file.close(); incremental_file.close();
h.set_sequenced_download_threshold(15); h.set_sequenced_download_threshold(1);
}
}else{ }else{
QFile::remove(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".incremental"); QFile::remove(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+hash+".incremental");
h.set_sequenced_download_threshold(100); h.set_sequenced_download_threshold(100); // Disabled
} }
} }
@ -539,7 +535,7 @@ void properties::on_okButton_clicked(){
} }
void properties::loadWebSeedsFromFile(){ 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; if(!urlseeds_file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
QByteArray urlseeds_lines = urlseeds_file.readAll(); QByteArray urlseeds_lines = urlseeds_file.readAll();
urlseeds_file.close(); urlseeds_file.close();
@ -551,13 +547,10 @@ void properties::loadWebSeedsFromFile(){
urlSeeds << url_seed; urlSeeds << url_seed;
} }
// Load the hard-coded url seeds // Load the hard-coded url seeds
torrent_info torrentInfo = h.get_torrent_info(); QStringList hc_seeds = h.url_seeds();
std::vector<std::string> hc_seeds = torrentInfo.url_seeds();
unsigned int nbSeeds = hc_seeds.size();
QString hc_seed; QString hc_seed;
// Add hard coded url seeds // Add hard coded url seeds
for(unsigned int i=0; i<nbSeeds; ++i){ foreach(hc_seed, hc_seeds){
hc_seed = QString(hc_seeds[i].c_str());
if(urlSeeds.indexOf(hc_seed) == -1){ if(urlSeeds.indexOf(hc_seed) == -1){
urlSeeds << hc_seed; urlSeeds << hc_seed;
} }
@ -565,14 +558,14 @@ void properties::loadWebSeedsFromFile(){
} }
void properties::saveWebSeeds(){ void properties::saveWebSeeds(){
QFile urlseeds_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".urlseeds"); QFile urlseeds_file(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".urlseeds"));
if(!urlseeds_file.open(QIODevice::WriteOnly | QIODevice::Text)){ if(!urlseeds_file.open(QIODevice::WriteOnly | QIODevice::Text)){
std::cerr << "Error: Could not save url seeds\n"; std::cerr << "Error: Could not save url seeds\n";
return; return;
} }
QString url_seed; QString url_seed;
foreach(url_seed, urlSeeds){ foreach(url_seed, urlSeeds){
urlseeds_file.write(QByteArray((const char*)(url_seed+"\n").toUtf8())); urlseeds_file.write((url_seed+"\n").toUtf8());
} }
urlseeds_file.close(); urlseeds_file.close();
qDebug("url seeds were saved"); qDebug("url seeds were saved");
@ -581,10 +574,9 @@ void properties::saveWebSeeds(){
void properties::savePiecesPriorities(){ void properties::savePiecesPriorities(){
if(!changedFilteredfiles) return; if(!changedFilteredfiles) return;
qDebug("Saving pieces priorities"); qDebug("Saving pieces priorities");
torrent_info torrentInfo = h.get_torrent_info();
bool hasFilteredFiles = false; bool hasFilteredFiles = false;
QString fileName = QString(torrentInfo.name().c_str()); QString fileName = h.name();
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 // First, remove old file
pieces_file.remove(); pieces_file.remove();
// Write new files // Write new files
@ -599,13 +591,13 @@ void properties::savePiecesPriorities(){
if(!priority) { if(!priority) {
hasFilteredFiles = true; hasFilteredFiles = true;
} }
pieces_file.write(QByteArray((misc::toString(priority)+"\n").c_str())); pieces_file.write(misc::toQByteArray(priority)+"\n");
} }
pieces_file.close(); pieces_file.close();
if(hasFilteredFiles && !BTSession->inFullAllocationMode(fileHash)){ if(hasFilteredFiles && !BTSession->inFullAllocationMode(hash)){
BTSession->pauseAndReloadTorrent(h); BTSession->pauseAndReloadTorrent(h);
} }
BTSession->loadFilesPriorities(h); BTSession->loadFilesPriorities(h);
emit filteredFilesChanged(fileHash); emit filteredFilesChanged(hash);
has_filtered_files = hasFilteredFiles; has_filtered_files = hasFilteredFiles;
} }

View file

@ -23,7 +23,7 @@
#define PROPERTIES_H #define PROPERTIES_H
#include "ui_properties.h" #include "ui_properties.h"
#include <libtorrent/torrent_handle.hpp> #include "qtorrenthandle.h"
class PropListDelegate; class PropListDelegate;
class QTimer; class QTimer;
@ -35,8 +35,8 @@ using namespace libtorrent;
class properties : public QDialog, private Ui::properties{ class properties : public QDialog, private Ui::properties{
Q_OBJECT Q_OBJECT
private: private:
torrent_handle h; QTorrentHandle h;
QString fileHash; QString hash;
PropListDelegate *PropDelegate; PropListDelegate *PropDelegate;
QStandardItemModel *PropListModel; QStandardItemModel *PropListModel;
QTimer *updateInfosTimer; QTimer *updateInfosTimer;
@ -71,12 +71,12 @@ class properties : public QDialog, private Ui::properties{
void loadTrackersErrors(); void loadTrackersErrors();
signals: signals:
void filteredFilesChanged(QString fileHash); void filteredFilesChanged(QString hash);
void fileSizeChanged(QString fileHash); void fileSizeChanged(QString hash);
public: public:
// Constructor // Constructor
properties(QWidget *parent, bittorrent *BTSession, torrent_handle &h); properties(QWidget *parent, bittorrent *BTSession, QTorrentHandle &h);
~properties(); ~properties();
bool onlyOneItem() const; bool onlyOneItem() const;
}; };

275
src/qtorrenthandle.cpp Normal file
View file

@ -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 <QString>
#include <QFile>
#include <QByteArray>
#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<std::string> existing_seeds = t.url_seeds();
unsigned int nbSeeds = existing_seeds.size();
QString existing_seed;
for(unsigned int i=0; i<nbSeeds; ++i){
res << misc::toQString(existing_seeds[i]);
}
return res;
}
// get the size of the torrent without the filtered files
size_type QTorrentHandle::actual_size() const{
unsigned int nbFiles = t.num_files();
if(!h.is_valid()){
qDebug("/!\\ Error: Invalid handle");
return t.total_size();
}
QString hash = misc::toQString(t.info_hash());
QFile pieces_file(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".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<QByteArray> 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<nbFiles; ++i){
int priority = pieces_priorities_list.at(i).toInt();
if( priority < 0 || priority > 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<announce_entry> 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<float>& 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<int> v) {
h.prioritize_files(v);
}
void QTorrentHandle::set_ratio(float ratio) const {
h.set_ratio(ratio);
}
void QTorrentHandle::replace_trackers(std::vector<announce_entry> 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());
}

111
src/qtorrenthandle.h Normal file
View file

@ -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 <libtorrent/torrent_handle.hpp>
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<announce_entry> 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<float>& 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<int> v);
void set_ratio(float ratio) const;
void replace_trackers(std::vector<announce_entry> 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

View file

@ -35,6 +35,7 @@ PKGCONFIG += libtorrent libccext2 libccgnu2
QT += network xml QT += network xml
DEFINES += QT_NO_CAST_TO_ASCII DEFINES += QT_NO_CAST_TO_ASCII
#QT_NO_CAST_FROM_ASCII
contains(DEBUG_MODE, 0){ contains(DEBUG_MODE, 0){
contains(QT_VERSION, 4.2.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 \ torrentAddition.h deleteThread.h \
bittorrent.h searchEngine.h \ bittorrent.h searchEngine.h \
rss.h rss_imp.h FinishedTorrents.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 \ FORMS += MainWindow.ui options.ui about.ui \
properties.ui createtorrent.ui preview.ui \ properties.ui createtorrent.ui preview.ui \
login.ui downloadFromURL.ui addTorrentDialog.ui \ login.ui downloadFromURL.ui addTorrentDialog.ui \
@ -155,5 +157,6 @@ SOURCES += GUI.cpp \
bittorrent.cpp \ bittorrent.cpp \
searchEngine.cpp \ searchEngine.cpp \
rss_imp.cpp \ rss_imp.cpp \
FinishedTorrents.cpp FinishedTorrents.cpp \
qtorrenthandle.cpp

View file

@ -49,7 +49,7 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{
private: private:
QString fileName; QString fileName;
QString fileHash; QString hash;
QString filePath; QString filePath;
bool fromScanDir; bool fromScanDir;
QString from_url; QString from_url;
@ -81,15 +81,15 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{
if(home[home.length()-1] != QDir::separator()){ if(home[home.length()-1] != QDir::separator()){
home += QDir::separator(); home += QDir::separator();
} }
QSettings settings("qBittorrent", "qBittorrent"); QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
savePathTxt->setText(settings.value("LastDirTorrentAdd", home+"qBT_dir").toString()); 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){ void showLoad(QString filePath, bool fromScanDir=false, QString from_url=QString::null){
this->filePath = filePath; this->filePath = filePath;
this->fromScanDir = fromScanDir; this->fromScanDir = fromScanDir;
this->from_url = from_url; 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); in.unsetf(std::ios_base::skipws);
try{ try{
// Decode torrent file // Decode torrent file
@ -97,39 +97,39 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{
// Getting torrent file informations // Getting torrent file informations
torrent_info t(e); torrent_info t(e);
// Setting file name // Setting file name
fileName = QString(t.name().c_str()); fileName = misc::toQString(t.name());
fileHash = QString(misc::toString(t.info_hash()).c_str()); hash = misc::toQString(t.info_hash());
// Use left() to remove .old extension // Use left() to remove .old extension
QString newFileName; QString newFileName;
if(fileName.endsWith(".old")){ if(fileName.endsWith(QString::fromUtf8(".old"))){
newFileName = fileName.left(fileName.size()-4); newFileName = fileName.left(fileName.size()-4);
}else{ }else{
newFileName = fileName; newFileName = fileName;
} }
fileNameLbl->setText("<center><b>"+newFileName+"</b></center>"); fileNameLbl->setText(QString::fromUtf8("<center><b>")+newFileName+QString::fromUtf8("</b></center>"));
// List files in torrent // List files in torrent
unsigned int nbFiles = t.num_files(); unsigned int nbFiles = t.num_files();
for(unsigned int i=0; i<nbFiles; ++i){ for(unsigned int i=0; i<nbFiles; ++i){
unsigned int row = PropListModel->rowCount(); unsigned int row = PropListModel->rowCount();
PropListModel->insertRow(row); 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(row, SIZE), QVariant((qlonglong)t.file_at(i).size));
PropListModel->setData(PropListModel->index(i, PRIORITY), QVariant(NORMAL)); 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 }catch (invalid_torrent_file&){ // Raised by torrent_info constructor
// Display warning to tell user we can't decode the torrent file // Display warning to tell user we can't decode the torrent file
if(!from_url.isNull()){ 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{ }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){ if(fromScanDir){
// Remove .corrupt file in case it already exists // 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 //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(); close();
} }
@ -137,16 +137,16 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{
std::cerr << "Could not decode file, reason: " << e.what() << '\n'; std::cerr << "Could not decode file, reason: " << e.what() << '\n';
// Display warning to tell user we can't decode the torrent file // Display warning to tell user we can't decode the torrent file
if(!from_url.isNull()){ 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{ }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){ if(fromScanDir){
// Remove .corrupt file in case it already exists // 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 //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(); close();
} }
@ -227,7 +227,7 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{
PropListModel->setData(index, QVariant(IGNORED)); PropListModel->setData(index, QVariant(IGNORED));
} }
for(int i=0; i<PropListModel->columnCount(); ++i){ for(int i=0; i<PropListModel->columnCount(); ++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)); PropListModel->setData(index, QVariant(NORMAL));
} }
for(int i=0; i<PropListModel->columnCount(); ++i){ for(int i=0; i<PropListModel->columnCount(); ++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)); PropListModel->setData(index, QVariant(MAXIMUM));
} }
for(int i=0; i<PropListModel->columnCount(); ++i){ for(int i=0; i<PropListModel->columnCount(); ++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(){ void savePiecesPriorities(){
qDebug("Saving pieces priorities"); 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 // First, remove old file
pieces_file.remove(); pieces_file.remove();
// Write new files // Write new files
@ -285,7 +285,7 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{
for(unsigned int i=0; i<nbRows; ++i){ for(unsigned int i=0; i<nbRows; ++i){
QStandardItem *item = PropListModel->item(i, PRIORITY); QStandardItem *item = PropListModel->item(i, PRIORITY);
unsigned short priority = item->text().toInt(); 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(); pieces_file.close();
} }
@ -304,28 +304,28 @@ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{
} }
} }
// Save savepath // 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.open(QIODevice::WriteOnly | QIODevice::Text);
savepath_file.write(savePath.path().toUtf8()); savepath_file.write(savePath.path().toUtf8());
savepath_file.close(); savepath_file.close();
// Save last dir to remember it // Save last dir to remember it
QSettings settings("qBittorrent", "qBittorrent"); QSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
settings.setValue("LastDirTorrentAdd", savePathTxt->text()); settings.setValue(QString::fromUtf8("LastDirTorrentAdd"), savePathTxt->text());
// Create .incremental file if necessary // Create .incremental file if necessary
if(checkIncrementalDL->isChecked()){ 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.open(QIODevice::WriteOnly | QIODevice::Text);
incremental_file.close(); incremental_file.close();
}else{ }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 // Create .paused file if necessary
if(addInPause->isChecked()){ 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.open(QIODevice::WriteOnly | QIODevice::Text);
paused_file.close(); paused_file.close();
}else{ }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 // Check if there is at least one selected file
if(!hasSelectedFiles()){ if(!hasSelectedFiles()){

View file

@ -26,6 +26,7 @@
#include <QMessageBox> #include <QMessageBox>
#include <libtorrent/session.hpp> #include <libtorrent/session.hpp>
#include "ui_login.h" #include "ui_login.h"
#include "qtorrenthandle.h"
using namespace libtorrent; using namespace libtorrent;
@ -33,34 +34,34 @@ class trackerLogin : public QDialog, private Ui::authentication{
Q_OBJECT Q_OBJECT
private: private:
torrent_handle h; QTorrentHandle h;
public: public:
trackerLogin(QWidget *parent, torrent_handle h): QDialog(parent){ trackerLogin(QWidget *parent, QTorrentHandle h): QDialog(parent){
setupUi(this); setupUi(this);
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
login_logo->setPixmap(QPixmap(QString::fromUtf8(":/Icons/encrypted.png"))); login_logo->setPixmap(QPixmap(QString::fromUtf8(":/Icons/encrypted.png")));
this->h = h; this->h = h;
tracker_url->setText(QString(h.status().current_tracker.c_str())); tracker_url->setText(h.current_tracker());
connect(this, SIGNAL(trackerLoginCancelled(QPair<torrent_handle,std::string>)), parent, SLOT(addUnauthenticatedTracker(QPair<torrent_handle,std::string>))); connect(this, SIGNAL(trackerLoginCancelled(QPair<QTorrentHandle,QString>)), parent, SLOT(addUnauthenticatedTracker(QPair<QTorrentHandle,QString>)));
show(); show();
} }
~trackerLogin(){} ~trackerLogin(){}
signals: signals:
void trackerLoginCancelled(QPair<torrent_handle,std::string> tracker); void trackerLoginCancelled(QPair<QTorrentHandle,QString> tracker);
public slots: public slots:
void on_loginButton_clicked(){ void on_loginButton_clicked(){
// login // 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(); close();
} }
void on_cancelButton_clicked(){ void on_cancelButton_clicked(){
// Emit a signal to GUI to stop asking for authentication // Emit a signal to GUI to stop asking for authentication
emit trackerLoginCancelled(QPair<torrent_handle,std::string>(h, h.status().current_tracker)); emit trackerLoginCancelled(QPair<QTorrentHandle,QString>(h, h.current_tracker()));
close(); close();
} }
}; };