Browse Source

- Big code cleanup

- Added a Qwrapper for torrent_handle to make code more readable
adaptive-webui-19844
Christophe Dumez 17 years ago
parent
commit
c9925eddb6
  1. 3
      TODO
  2. 6
      src/DLListDelegate.h
  3. 6
      src/FinishedListDelegate.h
  4. 42
      src/FinishedTorrents.cpp
  5. 4
      src/FinishedTorrents.h
  6. 920
      src/GUI.cpp
  7. 19
      src/GUI.h
  8. 11
      src/PreviewListDelegate.h
  9. 8
      src/PropListDelegate.h
  10. 26
      src/about_imp.h
  11. 20
      src/allocationDlg.h
  12. 668
      src/bittorrent.cpp
  13. 22
      src/bittorrent.h
  14. 2
      src/downloadFromURLImp.h
  15. 141
      src/misc.h
  16. 232
      src/options_imp.cpp
  17. 23
      src/previewSelect.h
  18. 122
      src/properties_imp.cpp
  19. 12
      src/properties_imp.h
  20. 275
      src/qtorrenthandle.cpp
  21. 111
      src/qtorrenthandle.h
  22. 7
      src/src.pro
  23. 64
      src/torrentAddition.h
  24. 15
      src/trackerLogin.h

3
TODO

@ -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

6
src/DLListDelegate.h

@ -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;

6
src/FinishedListDelegate.h

@ -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;

42
src/FinishedTorrents.cpp

@ -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;

4
src/FinishedTorrents.h

@ -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);
}; };

920
src/GUI.cpp

File diff suppressed because it is too large Load Diff

19
src/GUI.h

@ -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();

11
src/PreviewListDelegate.h

@ -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:

8
src/PropListDelegate.h

@ -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){

26
src/about_imp.h

@ -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();
} }
}; };

20
src/allocationDlg.h

@ -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();

668
src/bittorrent.cpp

File diff suppressed because it is too large Load Diff

22
src/bittorrent.h

@ -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);

2
src/downloadFromURLImp.h

@ -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){

141
src/misc.h

@ -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>
@ -43,7 +44,7 @@ class misc : public QObject{
public: public:
// Convert any type of variable to C++ String // Convert any type of variable to C++ String
// convert=true will convert -1 to 0 // convert=true will convert -1 to 0
template <class T> static std::string toString(const T& x, bool convert=false){ template <class T> static std::string toString(const T& x, bool convert=false) {
std::ostringstream o; std::ostringstream o;
if(!(o<<x)) { if(!(o<<x)) {
throw std::runtime_error("::toString()"); throw std::runtime_error("::toString()");
@ -53,73 +54,111 @@ 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;
std::istringstream i(s); std::istringstream i(s);
if(!(i>>x)){ if(!(i>>x)) {
throw std::runtime_error("::fromString()"); throw std::runtime_error("::fromString()");
} }
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
// value must be given in bytes // value must be given in bytes
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
static QString qBittorrentPath() { static QString qBittorrentPath() {
QString qBtPath = QDir::homePath(); QString qBtPath = QDir::homePath();
if(qBtPath.isNull()){ if(qBtPath.isNull()) {
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);
if(!dir.exists()){ if(!dir.exists()) {
dir.mkpath(qBtPath); dir.mkpath(qBtPath);
} }
return qBtPath; return qBtPath;
} }
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);
if(current_dir.exists()){ if(current_dir.exists()) {
//Remove sub items //Remove sub items
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);
} }
} }
// Remove empty folder // Remove empty folder
if(current_dir.rmdir(path)){ if(current_dir.rmdir(path)) {
return true; return true;
}else{ }else{
return false; return false;
@ -131,53 +170,53 @@ class misc : public QObject{
return true; return true;
} }
static QString findFileInDir(QString dir_path, QString fileName){ static QString findFileInDir(QString dir_path, QString fileName) {
QDir dir(dir_path); QDir dir(dir_path);
if(dir.exists(fileName)){ if(dir.exists(fileName)) {
return dir.filePath(fileName); return dir.filePath(fileName);
} }
QStringList subDirs = dir.entryList(QDir::Dirs); QStringList subDirs = dir.entryList(QDir::Dirs);
QString subdir_name; QString subdir_name;
foreach(subdir_name, subDirs){ foreach(subdir_name, subDirs) {
QString result = findFileInDir(dir.path()+QDir::separator()+subdir_name, fileName); QString result = findFileInDir(dir.path()+QDir::separator()+subdir_name, fileName);
if(!result.isNull()){ if(!result.isNull()) {
return result; return result;
} }
} }
return QString(); return QString();
} }
static void fixTrackersTiers(std::vector<announce_entry> trackers){ static void fixTrackersTiers(std::vector<announce_entry> trackers) {
unsigned int nbTrackers = trackers.size(); unsigned int nbTrackers = trackers.size();
for(unsigned int i=0; i<nbTrackers; ++i){ for(unsigned int i=0; i<nbTrackers; ++i) {
trackers[i].tier = i; trackers[i].tier = i;
} }
} }
// Insertion sort, used instead of bubble sort because it is // Insertion sort, used instead of bubble sort because it is
// approx. 5 times faster. // approx. 5 times faster.
template <class T> static void insertSort(QList<QPair<int, T> > &list, const QPair<int, T>& value, Qt::SortOrder sortOrder){ template <class T> static void insertSort(QList<QPair<int, T> > &list, const QPair<int, T>& value, Qt::SortOrder sortOrder) {
int i = 0; int i = 0;
if(sortOrder == Qt::AscendingOrder){ if(sortOrder == Qt::AscendingOrder) {
while(i < list.size() and value.second > list.at(i).second){ while(i < list.size() and value.second > list.at(i).second) {
++i; ++i;
} }
}else{ }else{
while(i < list.size() and value.second < list.at(i).second){ while(i < list.size() and value.second < list.at(i).second) {
++i; ++i;
} }
} }
list.insert(i, value); list.insert(i, value);
} }
template <class T> static void insertSort2(QList<QPair<int, T> > &list, const QPair<int, T>& value, Qt::SortOrder sortOrder){ template <class T> static void insertSort2(QList<QPair<int, T> > &list, const QPair<int, T>& value, Qt::SortOrder sortOrder) {
int i = 0; int i = 0;
if(sortOrder == Qt::AscendingOrder){ if(sortOrder == Qt::AscendingOrder) {
while(i < list.size() and value.first > list.at(i).first){ while(i < list.size() and value.first > list.at(i).first) {
++i; ++i;
} }
}else{ }else{
while(i < list.size() and value.first < list.at(i).first){ while(i < list.size() and value.first < list.at(i).first) {
++i; ++i;
} }
} }
@ -186,14 +225,14 @@ class misc : public QObject{
// Can't use template class for QString because >,< use unicode code for sorting // Can't use template class for QString because >,< use unicode code for sorting
// which is not what a human would expect when sorting strings. // which is not what a human would expect when sorting strings.
static void insertSortString(QList<QPair<int, QString> > &list, QPair<int, QString> value, Qt::SortOrder sortOrder){ static void insertSortString(QList<QPair<int, QString> > &list, QPair<int, QString> value, Qt::SortOrder sortOrder) {
int i = 0; int i = 0;
if(sortOrder == Qt::AscendingOrder){ if(sortOrder == Qt::AscendingOrder) {
while(i < list.size() and QString::localeAwareCompare(value.second, list.at(i).second) > 0){ while(i < list.size() and QString::localeAwareCompare(value.second, list.at(i).second) > 0) {
++i; ++i;
} }
}else{ }else{
while(i < list.size() and QString::localeAwareCompare(value.second, list.at(i).second) < 0){ while(i < list.size() and QString::localeAwareCompare(value.second, list.at(i).second) < 0) {
++i; ++i;
} }
} }
@ -202,28 +241,28 @@ class misc : public QObject{
// Take a number of seconds and return an user-friendly // Take a number of seconds and return an user-friendly
// 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");
} }
}; };

232
src/options_imp.cpp

@ -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";
} }
} }

23
src/previewSelect.h

@ -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]));
} }
} }

122
src/properties_imp.cpp

@ -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()){
// Create .incremental file if(!QFile::exists(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".incremental"))) {
QFile incremental_file(misc::qBittorrentPath()+"BT_backup"+QDir::separator()+fileHash+".incremental"); // Create .incremental file
incremental_file.open(QIODevice::WriteOnly | QIODevice::Text); QFile incremental_file(misc::qBittorrentPath()+QString::fromUtf8("BT_backup")+QDir::separator()+hash+QString::fromUtf8(".incremental"));
incremental_file.close(); incremental_file.open(QIODevice::WriteOnly | QIODevice::Text);
h.set_sequenced_download_threshold(15); incremental_file.close();
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;
} }

12
src/properties_imp.h

@ -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

@ -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

@ -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

7
src/src.pro

@ -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

64
src/torrentAddition.h

@ -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()){

15
src/trackerLogin.h

@ -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();
} }
}; };

Loading…
Cancel
Save