copyediting: indentation cleanups

This commit is contained in:
Jordan Lee 2013-09-14 22:45:04 +00:00
parent d9a6539e19
commit da317c441d
48 changed files with 3016 additions and 2825 deletions

View File

@ -20,89 +20,101 @@
#include "utils.h"
int
AddData :: set( const QString& key )
AddData :: set (const QString& key)
{
if( Utils::isMagnetLink( key ) )
if (Utils::isMagnetLink (key))
{
magnet = key;
type = MAGNET;
magnet = key;
type = MAGNET;
}
else if ( Utils::isUriWithSupportedScheme( key ) )
else if (Utils::isUriWithSupportedScheme (key))
{
url = key;
type = URL;
url = key;
type = URL;
}
else if( QFile(key).exists( ) )
else if (QFile(key).exists ())
{
filename = QDir::fromNativeSeparators( key );
type = FILENAME;
filename = QDir::fromNativeSeparators (key);
type = FILENAME;
QFile file( key );
file.open( QIODevice::ReadOnly );
metainfo = file.readAll( );
file.close( );
QFile file (key);
file.open (QIODevice::ReadOnly);
metainfo = file.readAll ();
file.close ();
}
else if( Utils::isHexHashcode( key ) )
else if (Utils::isHexHashcode (key))
{
magnet = QString::fromUtf8("magnet:?xt=urn:btih:") + key;
type = MAGNET;
magnet = QString::fromUtf8("magnet:?xt=urn:btih:") + key;
type = MAGNET;
}
else
else
{
int len;
char * raw = tr_base64_decode( key.toUtf8().constData(), key.toUtf8().size(), &len );
if( raw ) {
metainfo.append( raw, len );
tr_free( raw );
type = METAINFO;
int len;
char * raw = tr_base64_decode (key.toUtf8().constData(), key.toUtf8().size(), &len);
if (raw)
{
metainfo.append (raw, len);
tr_free (raw);
type = METAINFO;
}
else
{
type = NONE;
}
else type = NONE;
}
return type;
return type;
}
QByteArray
AddData :: toBase64( ) const
AddData :: toBase64 () const
{
QByteArray ret;
QByteArray ret;
if( !metainfo.isEmpty( ) )
if (!metainfo.isEmpty ())
{
int len = 0;
char * b64 = tr_base64_encode( metainfo.constData(), metainfo.size(), &len );
ret = QByteArray( b64, len );
tr_free( b64 );
int len = 0;
char * b64 = tr_base64_encode (metainfo.constData(), metainfo.size(), &len);
ret = QByteArray (b64, len);
tr_free (b64);
}
return ret;
return ret;
}
QString
AddData :: readableName( ) const
AddData :: readableName () const
{
QString ret;
QString ret;
switch( type )
switch (type)
{
case FILENAME: ret = filename; break;
case FILENAME:
ret = filename;
break;
case MAGNET: ret = magnet; break;
case MAGNET:
ret = magnet;
break;
case URL: ret = url.toString(); break;
case URL:
ret = url.toString();
break;
case METAINFO: {
tr_info inf;
tr_ctor * ctor = tr_ctorNew( NULL );
tr_ctorSetMetainfo( ctor, (const quint8*)metainfo.constData(), metainfo.size() );
if( tr_torrentParse( ctor, &inf ) == TR_PARSE_OK ) {
ret = QString::fromUtf8( inf.name ); // metainfo is required to be UTF-8
tr_metainfoFree( &inf );
case METAINFO:
{
tr_info inf;
tr_ctor * ctor = tr_ctorNew (NULL);
tr_ctorSetMetainfo (ctor, (const quint8*)metainfo.constData(), metainfo.size());
if (tr_torrentParse (ctor, &inf) == TR_PARSE_OK )
{
ret = QString::fromUtf8 (inf.name); // metainfo is required to be UTF-8
tr_metainfoFree (&inf);
}
tr_ctorFree( ctor );
break;
tr_ctorFree (ctor);
break;
}
}
return ret;
return ret;
}

View File

@ -19,29 +19,28 @@
class AddData
{
public:
public:
enum { NONE, MAGNET, URL, FILENAME, METAINFO };
int type;
enum { NONE, MAGNET, URL, FILENAME, METAINFO };
int type;
QByteArray metainfo;
QString filename;
QString magnet;
QUrl url;
QByteArray metainfo;
QString filename;
QString magnet;
QUrl url;
public:
public:
int set( const QString& );
AddData( const QString& str ) { set(str); }
AddData( ): type(NONE) { }
int set (const QString&);
AddData (const QString& str) { set(str); }
AddData (): type(NONE) {}
QByteArray toBase64( ) const;
QByteArray toBase64 () const;
QString readableName () const;
QString readableName( ) const;
public:
public:
static bool isSupported( const QString& str ) { return AddData(str).type != NONE; }
static bool isSupported (const QString& str) { return AddData(str).type != NONE; }
};
#endif

View File

@ -14,26 +14,26 @@
#include "app.h"
#include "dbus-adaptor.h"
TrDBusAdaptor :: TrDBusAdaptor( MyApp* app ):
QDBusAbstractAdaptor( app ),
myApp( app )
TrDBusAdaptor :: TrDBusAdaptor (MyApp* app):
QDBusAbstractAdaptor (app),
myApp (app)
{
}
bool
TrDBusAdaptor :: PresentWindow( )
TrDBusAdaptor :: PresentWindow ()
{
myApp->raise( );
return true;
myApp->raise ();
return true;
}
bool
TrDBusAdaptor :: AddMetainfo( const QString& key )
TrDBusAdaptor :: AddMetainfo (const QString& key)
{
AddData addme( key );
AddData addme (key);
if( addme.type != addme.NONE )
myApp->addTorrent( addme );
if (addme.type != addme.NONE)
myApp->addTorrent (addme);
return true;
return true;
}

View File

@ -27,7 +27,7 @@ class TrDBusAdaptor: public QDBusAbstractAdaptor
public:
TrDBusAdaptor( MyApp* );
virtual ~TrDBusAdaptor() { }
virtual ~TrDBusAdaptor() {}
public slots:
bool PresentWindow();

View File

@ -27,15 +27,15 @@
****
***/
Favicons :: Favicons( )
Favicons :: Favicons ()
{
myNAM = new QNetworkAccessManager( );
connect( myNAM, SIGNAL(finished(QNetworkReply*)), this, SLOT(onRequestFinished(QNetworkReply*)) );
myNAM = new QNetworkAccessManager ();
connect (myNAM, SIGNAL(finished(QNetworkReply*)), this, SLOT(onRequestFinished(QNetworkReply*)));
}
Favicons :: ~Favicons( )
Favicons :: ~Favicons ()
{
delete myNAM;
delete myNAM;
}
/***
@ -43,121 +43,122 @@ Favicons :: ~Favicons( )
***/
QString
Favicons :: getCacheDir( )
Favicons :: getCacheDir ()
{
const QString base =
const QString base =
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
QDesktopServices::storageLocation( QDesktopServices::CacheLocation );
QDesktopServices::storageLocation (QDesktopServices::CacheLocation);
#else
QStandardPaths::writableLocation( QStandardPaths::CacheLocation );
QStandardPaths::writableLocation (QStandardPaths::CacheLocation);
#endif
return QDir( base ).absoluteFilePath( "favicons" );
return QDir(base).absoluteFilePath ("favicons");
}
void
Favicons :: ensureCacheDirHasBeenScanned( )
Favicons :: ensureCacheDirHasBeenScanned ()
{
static bool hasBeenScanned = false;
static bool hasBeenScanned = false;
if( !hasBeenScanned )
if (!hasBeenScanned)
{
hasBeenScanned = true;
hasBeenScanned = true;
QDir cacheDir( getCacheDir( ) );
cacheDir.mkpath( cacheDir.absolutePath( ) );
QDir cacheDir (getCacheDir ());
cacheDir.mkpath (cacheDir.absolutePath ());
QStringList files = cacheDir.entryList( QDir::Files|QDir::Readable );
foreach( QString file, files ) {
QPixmap pixmap;
pixmap.load( cacheDir.absoluteFilePath( file ) );
if( !pixmap.isNull( ) )
myPixmaps.insert( file, pixmap );
QStringList files = cacheDir.entryList (QDir::Files|QDir::Readable);
foreach (QString file, files)
{
QPixmap pixmap;
pixmap.load (cacheDir.absoluteFilePath (file));
if (!pixmap.isNull ())
myPixmaps.insert (file, pixmap);
}
}
}
QString
Favicons :: getHost( const QUrl& url )
Favicons :: getHost (const QUrl& url)
{
QString host = url.host( );
const int first_dot = host.indexOf( '.' );
const int last_dot = host.lastIndexOf( '.' );
QString host = url.host ();
const int first_dot = host.indexOf ('.');
const int last_dot = host.lastIndexOf ('.');
if( ( first_dot != -1 ) && ( last_dot != -1 ) && ( first_dot != last_dot ) )
host.remove( 0, first_dot + 1 );
if ((first_dot != -1) && (last_dot != -1) && (first_dot != last_dot))
host.remove (0, first_dot + 1);
return host;
return host;
}
QPixmap
Favicons :: find( const QUrl& url )
Favicons :: find (const QUrl& url)
{
return findFromHost( getHost( url ) );
return findFromHost (getHost (url));
}
namespace
{
const QSize rightSize( 16, 16 );
const QSize rightSize (16, 16);
};
QPixmap
Favicons :: findFromHost( const QString& host )
Favicons :: findFromHost (const QString& host)
{
ensureCacheDirHasBeenScanned( );
ensureCacheDirHasBeenScanned ();
const QPixmap pixmap = myPixmaps[ host ];
return pixmap.size()==rightSize ? pixmap : pixmap.scaled(rightSize);
const QPixmap pixmap = myPixmaps[ host ];
return pixmap.size()==rightSize ? pixmap : pixmap.scaled(rightSize);
}
void
Favicons :: add( const QUrl& url )
Favicons :: add (const QUrl& url)
{
ensureCacheDirHasBeenScanned( );
ensureCacheDirHasBeenScanned ();
const QString host = getHost( url );
const QString host = getHost (url);
if( !myPixmaps.contains( host ) )
if (!myPixmaps.contains (host))
{
// add a placholder s.t. we only ping the server once per session
QPixmap tmp( rightSize );
tmp.fill( Qt::transparent );
myPixmaps.insert( host, tmp );
// add a placholder s.t. we only ping the server once per session
QPixmap tmp (rightSize);
tmp.fill (Qt::transparent);
myPixmaps.insert (host, tmp);
// try to download the favicon
const QString path = "http://" + host + "/favicon.";
QStringList suffixes;
suffixes << "ico" << "png" << "gif" << "jpg";
foreach( QString suffix, suffixes )
myNAM->get( QNetworkRequest( path + suffix ) );
// try to download the favicon
const QString path = "http://" + host + "/favicon.";
QStringList suffixes;
suffixes << "ico" << "png" << "gif" << "jpg";
foreach (QString suffix, suffixes)
myNAM->get (QNetworkRequest (path + suffix));
}
}
void
Favicons :: onRequestFinished( QNetworkReply * reply )
Favicons :: onRequestFinished (QNetworkReply * reply)
{
const QString host = reply->url().host();
const QString host = reply->url().host();
QPixmap pixmap;
QPixmap pixmap;
const QByteArray content = reply->readAll( );
if( !reply->error( ) )
pixmap.loadFromData( content );
const QByteArray content = reply->readAll ();
if (!reply->error ())
pixmap.loadFromData (content);
if( !pixmap.isNull( ) )
if (!pixmap.isNull ())
{
// save it in memory...
myPixmaps.insert( host, pixmap );
// save it in memory...
myPixmaps.insert (host, pixmap);
// save it on disk...
QDir cacheDir( getCacheDir( ) );
cacheDir.mkpath( cacheDir.absolutePath( ) );
QFile file( cacheDir.absoluteFilePath( host ) );
file.open( QIODevice::WriteOnly );
file.write( content );
file.close( );
// save it on disk...
QDir cacheDir (getCacheDir ());
cacheDir.mkpath (cacheDir.absolutePath ());
QFile file (cacheDir.absoluteFilePath (host));
file.open (QIODevice::WriteOnly);
file.write (content);
file.close ();
// notify listeners
emit pixmapReady( host );
// notify listeners
emit pixmapReady (host);
}
}

View File

@ -24,41 +24,41 @@ class QUrl;
class Favicons: public QObject
{
Q_OBJECT;
Q_OBJECT;
public:
public:
static QString getHost( const QUrl& url );
static QString getHost( const QUrl& url );
public:
public:
Favicons();
virtual ~Favicons();
Favicons();
virtual ~Favicons();
/* returns a cached pixmap, or a NULL pixmap if there's no match in the cache */
QPixmap find( const QUrl& url );
// returns a cached pixmap, or a NULL pixmap if there's no match in the cache
QPixmap find (const QUrl& url);
/* returns a cached pixmap, or a NULL pixmap if there's no match in the cache */
QPixmap findFromHost( const QString& host );
// returns a cached pixmap, or a NULL pixmap if there's no match in the cache
QPixmap findFromHost (const QString& host);
/* this will emit a signal when (if) the icon becomes ready */
void add( const QUrl& url );
// this will emit a signal when (if) the icon becomes ready
void add (const QUrl& url);
signals:
signals:
void pixmapReady( const QString& host );
void pixmapReady (const QString& host);
private:
private:
QNetworkAccessManager * myNAM;
QMap<QString,QPixmap> myPixmaps;
QNetworkAccessManager * myNAM;
QMap<QString,QPixmap> myPixmaps;
QString getCacheDir( );
void ensureCacheDirHasBeenScanned( );
QString getCacheDir ();
void ensureCacheDirHasBeenScanned ();
private slots:
private slots:
void onRequestFinished( QNetworkReply * reply );
void onRequestFinished (QNetworkReply * reply);
};
#endif

View File

@ -51,7 +51,7 @@ class FileTreeItem: public QObject
myIsWanted (0),
myHaveSize (0),
myTotalSize (size),
myFirstUnhashedRow (0) { }
myFirstUnhashedRow (0) {}
public:
void appendChild (FileTreeItem *child);
@ -149,8 +149,8 @@ class FileTreeDelegate: public QItemDelegate
Q_OBJECT
public:
FileTreeDelegate (QObject * parent=0): QItemDelegate(parent) { }
virtual ~FileTreeDelegate() { }
FileTreeDelegate (QObject * parent=0): QItemDelegate(parent) {}
virtual ~FileTreeDelegate() {}
public:
virtual QSize sizeHint (const QStyleOptionViewItem&, const QModelIndex&) const;

View File

@ -590,7 +590,7 @@ FilterBar :: recount ()
{
QAbstractItemModel * model = myActivityCombo->model ();
int torrentsPerMode[FilterMode::NUM_MODES] = { };
int torrentsPerMode[FilterMode::NUM_MODES] = {};
myFilter.countTorrentsPerMode (torrentsPerMode);
for (int row=0, n=model->rowCount (); row<n; ++row)

View File

@ -14,43 +14,46 @@
const QString FilterMode::names[NUM_MODES] =
{
"show-all",
"show-active",
"show-downloading",
"show-seeding",
"show-paused",
"show-finished",
"show-verifying",
"show-error",
"show-all",
"show-active",
"show-downloading",
"show-seeding",
"show-paused",
"show-finished",
"show-verifying",
"show-error",
};
int
FilterMode :: modeFromName( const QString& name )
{
for( int i=0; i<NUM_MODES; ++i )
if( names[i] == name )
return i;
return FilterMode().mode(); // use the default value
for (int i=0; i<NUM_MODES; ++i)
if( names[i] == name )
return i;
return FilterMode().mode(); // use the default value
}
const QString SortMode::names[NUM_MODES] = {
"sort-by-activity",
"sort-by-age",
"sort-by-eta",
"sort-by-name",
"sort-by-progress",
"sort-by-queue"
"sort-by-ratio",
"sort-by-size",
"sort-by-state",
"sort-by-id"
const QString SortMode::names[NUM_MODES] =
{
"sort-by-activity",
"sort-by-age",
"sort-by-eta",
"sort-by-name",
"sort-by-progress",
"sort-by-queue"
"sort-by-ratio",
"sort-by-size",
"sort-by-state",
"sort-by-id"
};
int
SortMode :: modeFromName( const QString& name )
SortMode :: modeFromName (const QString& name)
{
for( int i=0; i<NUM_MODES; ++i )
if( names[i] == name )
return i;
return SortMode().mode(); // use the default value
for (int i=0; i<NUM_MODES; ++i)
if (names[i] == name)
return i;
return SortMode().mode(); // use the default value
}

View File

@ -19,35 +19,37 @@
class FilterMode
{
private:
int myMode;
public:
FilterMode( int mode=SHOW_ALL ): myMode(mode) { }
FilterMode( const QString& name ): myMode(modeFromName(name)) { }
static const QString names[];
enum { SHOW_ALL, SHOW_ACTIVE, SHOW_DOWNLOADING, SHOW_SEEDING, SHOW_PAUSED,
SHOW_FINISHED, SHOW_VERIFYING, SHOW_ERROR, NUM_MODES };
static int modeFromName( const QString& name );
static const QString& nameFromMode( int mode ) { return names[mode]; }
int mode() const { return myMode; }
const QString& name() const { return names[myMode]; }
private:
int myMode;
public:
FilterMode( int mode=SHOW_ALL ): myMode(mode) {}
FilterMode( const QString& name ): myMode(modeFromName(name)) {}
static const QString names[];
enum { SHOW_ALL, SHOW_ACTIVE, SHOW_DOWNLOADING, SHOW_SEEDING, SHOW_PAUSED,
SHOW_FINISHED, SHOW_VERIFYING, SHOW_ERROR, NUM_MODES };
static int modeFromName( const QString& name );
static const QString& nameFromMode( int mode ) { return names[mode]; }
int mode() const { return myMode; }
const QString& name() const { return names[myMode]; }
};
class SortMode
{
private:
int myMode;
public:
SortMode( int mode=SORT_BY_ID ): myMode(mode) { }
SortMode( const QString& name ): myMode(modeFromName(name)) { }
static const QString names[];
enum { SORT_BY_ACTIVITY, SORT_BY_AGE, SORT_BY_ETA, SORT_BY_NAME,
SORT_BY_PROGRESS, SORT_BY_QUEUE, SORT_BY_RATIO, SORT_BY_SIZE,
SORT_BY_STATE, SORT_BY_ID, NUM_MODES };
static int modeFromName( const QString& name );
static const QString& nameFromMode( int mode );
int mode() const { return myMode; }
const QString& name() const { return names[myMode]; }
private:
int myMode;
public:
SortMode( int mode=SORT_BY_ID ): myMode(mode) {}
SortMode( const QString& name ): myMode(modeFromName(name)) {}
static const QString names[];
enum { SORT_BY_ACTIVITY, SORT_BY_AGE, SORT_BY_ETA, SORT_BY_NAME,
SORT_BY_PROGRESS, SORT_BY_QUEUE, SORT_BY_RATIO, SORT_BY_SIZE,
SORT_BY_STATE, SORT_BY_ID, NUM_MODES };
static int modeFromName( const QString& name );
static const QString& nameFromMode( int mode );
int mode() const { return myMode; }
const QString& name() const { return names[myMode]; }
};
Q_DECLARE_METATYPE(FilterMode)

View File

@ -41,10 +41,10 @@ Formatter :: initUnits ()
unitStrings[SPEED][GB] = tr ("GB/s");
unitStrings[SPEED][TB] = tr ("TB/s");
tr_formatter_speed_init (speed_K,
unitStrings[SPEED][KB].toUtf8 ().constData (),
unitStrings[SPEED][MB].toUtf8 ().constData (),
unitStrings[SPEED][GB].toUtf8 ().constData (),
unitStrings[SPEED][TB].toUtf8 ().constData ());
unitStrings[SPEED][KB].toUtf8().constData(),
unitStrings[SPEED][MB].toUtf8().constData(),
unitStrings[SPEED][GB].toUtf8().constData(),
unitStrings[SPEED][TB].toUtf8().constData());
size_K = 1000;
unitStrings[SIZE][B] = tr ( "B");
@ -53,10 +53,10 @@ Formatter :: initUnits ()
unitStrings[SIZE][GB] = tr ("GB");
unitStrings[SIZE][TB] = tr ("TB");
tr_formatter_size_init (size_K,
unitStrings[SIZE][KB].toUtf8 ().constData (),
unitStrings[SIZE][MB].toUtf8 ().constData (),
unitStrings[SIZE][GB].toUtf8 ().constData (),
unitStrings[SIZE][TB].toUtf8 ().constData ());
unitStrings[SIZE][KB].toUtf8().constData(),
unitStrings[SIZE][MB].toUtf8().constData(),
unitStrings[SIZE][GB].toUtf8().constData(),
unitStrings[SIZE][TB].toUtf8().constData());
mem_K = 1024;
unitStrings[MEM][B] = tr ( "B");
@ -65,10 +65,10 @@ Formatter :: initUnits ()
unitStrings[MEM][GB] = tr ("GiB");
unitStrings[MEM][TB] = tr ("TiB");
tr_formatter_mem_init (mem_K,
unitStrings[MEM][KB].toUtf8 ().constData (),
unitStrings[MEM][MB].toUtf8 ().constData (),
unitStrings[MEM][GB].toUtf8 ().constData (),
unitStrings[MEM][TB].toUtf8 ().constData ());
unitStrings[MEM][KB].toUtf8().constData(),
unitStrings[MEM][MB].toUtf8().constData(),
unitStrings[MEM][GB].toUtf8().constData(),
unitStrings[MEM][TB].toUtf8().constData());
}
/***

243
qt/hig.cc
View File

@ -20,21 +20,21 @@
#include "hig.h"
HIG :: HIG( QWidget * parent ):
QWidget( parent ),
myRow( 0 ),
myHasTall( false ),
myGrid( new QGridLayout( this ) )
HIG :: HIG (QWidget * parent):
QWidget (parent),
myRow (0),
myHasTall (false),
myGrid (new QGridLayout (this))
{
myGrid->setContentsMargins( PAD_BIG, PAD_BIG, PAD_BIG, PAD_BIG );
myGrid->setHorizontalSpacing( PAD_BIG );
myGrid->setVerticalSpacing( PAD );
myGrid->setColumnStretch ( 1, 1 );
myGrid->setContentsMargins (PAD_BIG, PAD_BIG, PAD_BIG, PAD_BIG);
myGrid->setHorizontalSpacing (PAD_BIG);
myGrid->setVerticalSpacing (PAD);
myGrid->setColumnStretch (1, 1);
}
HIG :: ~HIG( )
HIG :: ~HIG ()
{
delete myGrid;
delete myGrid;
}
/***
@ -42,193 +42,202 @@ HIG :: ~HIG( )
***/
void
HIG :: addSectionDivider( )
HIG :: addSectionDivider ()
{
QWidget * w = new QWidget( this );
myGrid->addWidget( w, myRow, 0, 1, 2 );
++myRow;
QWidget * w = new QWidget (this);
myGrid->addWidget (w, myRow, 0, 1, 2);
++myRow;
}
void
HIG :: addSectionTitle( const QString& title )
HIG :: addSectionTitle (const QString& title)
{
QLabel * label = new QLabel( this );
label->setText( title );
label->setStyleSheet( "font: bold" );
label->setAlignment( Qt::AlignLeft|Qt::AlignVCenter );
addSectionTitle( label );
QLabel * label = new QLabel (this);
label->setText (title);
label->setStyleSheet ("font: bold");
label->setAlignment (Qt::AlignLeft|Qt::AlignVCenter);
addSectionTitle (label);
}
void
HIG :: addSectionTitle( QWidget * w )
HIG :: addSectionTitle (QWidget * w)
{
myGrid->addWidget( w, myRow, 0, 1, 2, Qt::AlignLeft|Qt::AlignVCenter );
++myRow;
myGrid->addWidget (w, myRow, 0, 1, 2, Qt::AlignLeft|Qt::AlignVCenter);
++myRow;
}
void
HIG :: addSectionTitle( QLayout * l )
HIG :: addSectionTitle (QLayout * l)
{
myGrid->addLayout( l, myRow, 0, 1, 2, Qt::AlignLeft|Qt::AlignVCenter );
++myRow;
myGrid->addLayout (l, myRow, 0, 1, 2, Qt::AlignLeft|Qt::AlignVCenter);
++myRow;
}
QLayout *
HIG :: addRow( QWidget * w )
HIG :: addRow (QWidget * w)
{
QHBoxLayout * h = new QHBoxLayout( );
h->addSpacing( 18 );
h->addWidget( w );
QHBoxLayout * h = new QHBoxLayout ();
h->addSpacing (18);
h->addWidget (w);
QLabel * l;
if( ( l = qobject_cast<QLabel*>(w) ) )
l->setAlignment( Qt::AlignLeft );
QLabel * l;
if ((l = qobject_cast<QLabel*>(w)))
l->setAlignment (Qt::AlignLeft);
return h;
return h;
}
void
HIG :: addWideControl( QLayout * l )
HIG :: addWideControl (QLayout * l)
{
QHBoxLayout * h = new QHBoxLayout( );
h->addSpacing( 18 );
h->addLayout( l );
myGrid->addLayout( h, myRow, 0, 1, 2, Qt::AlignLeft|Qt::AlignVCenter );
++myRow;
QHBoxLayout * h = new QHBoxLayout ();
h->addSpacing (18);
h->addLayout (l);
myGrid->addLayout (h, myRow, 0, 1, 2, Qt::AlignLeft|Qt::AlignVCenter);
++myRow;
}
void
HIG :: addWideControl( QWidget * w )
HIG :: addWideControl (QWidget * w)
{
QHBoxLayout * h = new QHBoxLayout( );
h->addSpacing( 18 );
h->addWidget( w );
myGrid->addLayout( h, myRow, 0, 1, 2, Qt::AlignLeft|Qt::AlignVCenter );
++myRow;
QHBoxLayout * h = new QHBoxLayout ();
h->addSpacing (18);
h->addWidget (w);
myGrid->addLayout (h, myRow, 0, 1, 2, Qt::AlignLeft|Qt::AlignVCenter);
++myRow;
}
QCheckBox*
HIG :: addWideCheckBox( const QString& text, bool isChecked )
HIG :: addWideCheckBox (const QString& text, bool isChecked)
{
QCheckBox * check = new QCheckBox( text, this );
check->setChecked( isChecked );
addWideControl( check );
return check;
QCheckBox * check = new QCheckBox (text, this);
check->setChecked (isChecked);
addWideControl (check);
return check;
}
void
HIG :: addLabel( QWidget * w )
HIG :: addLabel (QWidget * w)
{
QHBoxLayout * h = new QHBoxLayout( );
h->addSpacing( 18 );
h->addWidget( w );
myGrid->addLayout( h, myRow, 0, 1, 1, Qt::AlignLeft|Qt::AlignVCenter );
QHBoxLayout * h = new QHBoxLayout ();
h->addSpacing (18);
h->addWidget (w);
myGrid->addLayout (h, myRow, 0, 1, 1, Qt::AlignLeft|Qt::AlignVCenter);
}
QLabel*
HIG :: addLabel( const QString& text )
HIG :: addLabel (const QString& text)
{
QLabel * label = new QLabel( text, this );
addLabel( label );
return label;
QLabel * label = new QLabel (text, this);
addLabel (label);
return label;
}
void
HIG :: addTallLabel( QWidget * w )
HIG :: addTallLabel (QWidget * w)
{
QHBoxLayout * h = new QHBoxLayout( );
h->addSpacing( 18 );
h->addWidget( w );
myGrid->addLayout( h, myRow, 0, 1, 1, Qt::AlignLeft|Qt::AlignTop );
QHBoxLayout * h = new QHBoxLayout ();
h->addSpacing (18);
h->addWidget (w);
myGrid->addLayout (h, myRow, 0, 1, 1, Qt::AlignLeft|Qt::AlignTop);
}
QLabel*
HIG :: addTallLabel( const QString& text )
HIG :: addTallLabel (const QString& text)
{
QLabel * label = new QLabel( text, this );
addTallLabel( label );
return label;
QLabel * label = new QLabel (text, this);
addTallLabel (label);
return label;
}
void
HIG :: addControl( QWidget * w )
HIG :: addControl (QWidget * w)
{
myGrid->addWidget( w, myRow, 1, 1, 1 );
myGrid->addWidget (w, myRow, 1, 1, 1);
}
void
HIG :: addControl( QLayout * l )
HIG :: addControl (QLayout * l)
{
myGrid->addLayout( l, myRow, 1, 1, 1 );
myGrid->addLayout (l, myRow, 1, 1, 1);
}
QLabel *
HIG :: addRow( const QString& text, QWidget * control, QWidget * buddy )
HIG :: addRow (const QString& text, QWidget * control, QWidget * buddy)
{
QLabel * label = addLabel( text );
addControl( control );
label->setBuddy( buddy ? buddy : control );
++myRow;
return label;
QLabel * label = addLabel (text);
addControl (control);
label->setBuddy (buddy ? buddy : control);
++myRow;
return label;
}
QLabel *
HIG :: addTallRow( const QString& text, QWidget * control, QWidget * buddy )
HIG :: addTallRow (const QString& text, QWidget * control, QWidget * buddy)
{
QLabel* label = addTallLabel( text );
label->setBuddy( buddy ? buddy : control );
addControl( control );
myHasTall = true;
myGrid->setRowStretch ( myRow, 1 );
++myRow;
return label;
QLabel* label = addTallLabel (text);
label->setBuddy (buddy ? buddy : control);
addControl (control);
myHasTall = true;
myGrid->setRowStretch (myRow, 1);
++myRow;
return label;
}
QLabel *
HIG :: addRow( const QString& text, QLayout * control, QWidget * buddy )
HIG :: addRow (const QString& text, QLayout * control, QWidget * buddy)
{
QLabel * label = addLabel( text );
addControl( control );
if( buddy != 0 )
label->setBuddy( buddy );
++myRow;
return label;
QLabel * label = addLabel (text);
addControl (control);
if (buddy != 0)
label->setBuddy (buddy);
++myRow;
return label;
}
void
HIG :: addRow( QWidget * label, QWidget * control, QWidget * buddy )
HIG :: addRow (QWidget * label, QWidget * control, QWidget * buddy)
{
addLabel( label );
if( control ) {
addControl( control );
QLabel * l = qobject_cast<QLabel*>( label );
if( l != 0 )
l->setBuddy( buddy ? buddy : control );
addLabel (label);
if (control)
{
addControl (control);
QLabel * l = qobject_cast<QLabel*> (label);
if (l != 0)
l->setBuddy (buddy ? buddy : control);
}
++myRow;
++myRow;
}
void
HIG :: addRow( QWidget * label, QLayout * control, QWidget * buddy )
HIG :: addRow (QWidget * label, QLayout * control, QWidget * buddy)
{
addLabel( label );
if( control ) {
addControl( control );
QLabel * l = qobject_cast<QLabel*>( label );
if( l != 0 && buddy != 0 )
l->setBuddy( buddy );
addLabel (label);
if (control)
{
addControl (control);
QLabel * l = qobject_cast<QLabel*> (label);
if (l != 0 && buddy != 0)
l->setBuddy (buddy);
}
++myRow;
++myRow;
}
void
HIG :: finish( )
HIG :: finish ()
{
if( !myHasTall ) {
QWidget * w = new QWidget( this );
myGrid->addWidget( w, myRow, 0, 1, 2 );
myGrid->setRowStretch( myRow, 100 );
++myRow;
if (!myHasTall)
{
QWidget * w = new QWidget (this);
myGrid->addWidget (w, myRow, 0, 1, 2);
myGrid->setRowStretch (myRow, 100);
++myRow;
}
}

View File

@ -23,48 +23,52 @@ class QLayout;
class HIG: public QWidget
{
Q_OBJECT
Q_OBJECT
public:
enum {
PAD_SMALL = 3,
PAD = 6,
PAD_BIG = 12,
PAD_LARGE = PAD_BIG
};
public:
public:
HIG( QWidget * parent = 0 );
virtual ~HIG( );
enum
{
PAD_SMALL = 3,
PAD = 6,
PAD_BIG = 12,
PAD_LARGE = PAD_BIG
};
public:
void addSectionDivider( );
void addSectionTitle( const QString& );
void addSectionTitle( QWidget* );
void addSectionTitle( QLayout* );
void addWideControl( QLayout * );
void addWideControl( QWidget * );
QCheckBox* addWideCheckBox( const QString&, bool isChecked );
QLabel* addLabel( const QString& );
QLabel* addTallLabel( const QString& );
void addLabel( QWidget * );
void addTallLabel( QWidget * );
void addControl( QWidget * );
void addControl( QLayout * );
QLabel* addRow( const QString & label, QWidget * control, QWidget * buddy=0 );
QLabel* addRow( const QString & label, QLayout * control, QWidget * buddy );
void addRow( QWidget * label, QWidget * control, QWidget * buddy=0 );
void addRow( QWidget * label, QLayout * control, QWidget * buddy );
QLabel* addTallRow( const QString & label, QWidget * control, QWidget * buddy=0 );
void finish( );
public:
private:
QLayout* addRow( QWidget* w );
HIG (QWidget * parent = 0);
virtual ~HIG ();
private:
int myRow;
bool myHasTall;
QGridLayout * myGrid;
public:
void addSectionDivider ();
void addSectionTitle (const QString&);
void addSectionTitle (QWidget*);
void addSectionTitle (QLayout*);
void addWideControl (QLayout *);
void addWideControl (QWidget *);
QCheckBox* addWideCheckBox (const QString&, bool isChecked);
QLabel* addLabel (const QString&);
QLabel* addTallLabel (const QString&);
void addLabel (QWidget *);
void addTallLabel (QWidget *);
void addControl (QWidget *);
void addControl (QLayout *);
QLabel* addRow (const QString & label, QWidget * control, QWidget * buddy=0);
QLabel* addRow (const QString & label, QLayout * control, QWidget * buddy);
void addRow (QWidget * label, QWidget * control, QWidget * buddy=0);
void addRow (QWidget * label, QLayout * control, QWidget * buddy);
QLabel* addTallRow (const QString & label, QWidget * control, QWidget * buddy=0);
void finish ();
private:
QLayout* addRow (QWidget* w);
private:
int myRow;
bool myHasTall;
QGridLayout * myGrid;
};
#endif // QTR_HIG_H

View File

@ -46,122 +46,128 @@
***/
void
MakeDialog :: onNewDialogDestroyed( QObject * o )
MakeDialog :: onNewDialogDestroyed (QObject * o)
{
Q_UNUSED( o );
Q_UNUSED (o);
myTimer.stop( );
myTimer.stop ();
}
void
MakeDialog :: onNewButtonBoxClicked( QAbstractButton * button )
MakeDialog :: onNewButtonBoxClicked (QAbstractButton * button)
{
switch( myNewButtonBox->standardButton( button ) )
switch (myNewButtonBox->standardButton (button))
{
case QDialogButtonBox::Open:
mySession.addNewlyCreatedTorrent( myTarget, QFileInfo(QString::fromUtf8(myBuilder->top)).dir().path() );
break;
case QDialogButtonBox::Abort:
myBuilder->abortFlag = true;
break;
default: // QDialogButtonBox::Ok:
break;
case QDialogButtonBox::Open:
mySession.addNewlyCreatedTorrent (myTarget, QFileInfo(QString::fromUtf8(myBuilder->top)).dir().path());
break;
case QDialogButtonBox::Abort:
myBuilder->abortFlag = true;
break;
default: // QDialogButtonBox::Ok:
break;
}
myNewDialog->deleteLater( );
myNewDialog->deleteLater ();
}
void
MakeDialog :: onProgress( )
MakeDialog :: onProgress ()
{
// progress bar
const tr_metainfo_builder * b = myBuilder;
const double denom = b->pieceCount ? b->pieceCount : 1;
myNewProgress->setValue( (int) ((100.0 * b->pieceIndex) / denom ) );
// progress bar
const tr_metainfo_builder * b = myBuilder;
const double denom = b->pieceCount ? b->pieceCount : 1;
myNewProgress->setValue ((int) ((100.0 * b->pieceIndex) / denom));
// progress label
const QString top = QString::fromLocal8Bit( myBuilder->top );
const QString base( QFileInfo(top).completeBaseName() );
QString str;
if( !b->isDone )
str = tr( "Creating \"%1\"" ).arg( base );
else if( b->result == TR_MAKEMETA_OK )
str = tr( "Created \"%1\"!" ).arg( base );
else if( b->result == TR_MAKEMETA_URL )
str = tr( "Error: invalid announce URL \"%1\"" ).arg( QString::fromLocal8Bit( b->errfile ) );
else if( b->result == TR_MAKEMETA_CANCELLED )
str = tr( "Cancelled" );
else if( b->result == TR_MAKEMETA_IO_READ )
str = tr( "Error reading \"%1\": %2" ).arg( QString::fromLocal8Bit(b->errfile) ).arg( QString::fromLocal8Bit(strerror(b->my_errno)) );
else if( b->result == TR_MAKEMETA_IO_WRITE )
str = tr( "Error writing \"%1\": %2" ).arg( QString::fromLocal8Bit(b->errfile) ).arg( QString::fromLocal8Bit(strerror(b->my_errno)) );
myNewLabel->setText( str );
// progress label
const QString top = QString::fromLocal8Bit (myBuilder->top);
const QString base (QFileInfo(top).completeBaseName());
QString str;
if (!b->isDone)
str = tr ("Creating \"%1\"").arg (base);
else if (b->result == TR_MAKEMETA_OK)
str = tr ("Created \"%1\"!").arg (base);
else if (b->result == TR_MAKEMETA_URL)
str = tr ("Error: invalid announce URL \"%1\"").arg (QString::fromLocal8Bit (b->errfile));
else if (b->result == TR_MAKEMETA_CANCELLED)
str = tr ("Cancelled");
else if (b->result == TR_MAKEMETA_IO_READ)
str = tr ("Error reading \"%1\": %2").arg (QString::fromLocal8Bit(b->errfile)).arg (QString::fromLocal8Bit(strerror(b->my_errno)));
else if (b->result == TR_MAKEMETA_IO_WRITE)
str = tr ("Error writing \"%1\": %2").arg (QString::fromLocal8Bit(b->errfile)).arg (QString::fromLocal8Bit(strerror(b->my_errno)));
myNewLabel->setText (str);
// buttons
(myNewButtonBox->button(QDialogButtonBox::Abort))->setEnabled( !b->isDone );
(myNewButtonBox->button(QDialogButtonBox::Ok))->setEnabled( b->isDone );
(myNewButtonBox->button(QDialogButtonBox::Open))->setEnabled( b->isDone && !b->result );
// buttons
(myNewButtonBox->button(QDialogButtonBox::Abort))->setEnabled (!b->isDone);
(myNewButtonBox->button(QDialogButtonBox::Ok))->setEnabled (b->isDone);
(myNewButtonBox->button(QDialogButtonBox::Open))->setEnabled (b->isDone && !b->result);
}
void
MakeDialog :: makeTorrent( )
MakeDialog :: makeTorrent ()
{
if( !myBuilder )
return;
if (!myBuilder)
return;
// get the tiers
int tier = 0;
QVector<tr_tracker_info> trackers;
foreach( QString line, myTrackerEdit->toPlainText().split("\n") ) {
line = line.trimmed( );
if( line.isEmpty( ) )
++tier;
else {
tr_tracker_info tmp;
tmp.announce = tr_strdup( line.toUtf8().constData( ) );
tmp.tier = tier;
trackers.append( tmp );
// get the tiers
int tier = 0;
QVector<tr_tracker_info> trackers;
foreach (QString line, myTrackerEdit->toPlainText().split("\n"))
{
line = line.trimmed ();
if (line.isEmpty ())
{
++tier;
}
else
{
tr_tracker_info tmp;
tmp.announce = tr_strdup (line.toUtf8().constData ());
tmp.tier = tier;
trackers.append (tmp);
}
}
// pop up the dialog
QDialog * dialog = new QDialog( this );
dialog->setWindowTitle( tr( "New Torrent" ) );
myNewDialog = dialog;
QVBoxLayout * top = new QVBoxLayout( dialog );
top->addWidget(( myNewLabel = new QLabel));
top->addWidget(( myNewProgress = new QProgressBar ));
QDialogButtonBox * buttons = new QDialogButtonBox( QDialogButtonBox::Ok
| QDialogButtonBox::Open
| QDialogButtonBox::Abort );
myNewButtonBox = buttons;
connect( buttons, SIGNAL(clicked(QAbstractButton*)),
this, SLOT(onNewButtonBoxClicked(QAbstractButton*)) );
top->addWidget( buttons );
onProgress( );
dialog->show( );
connect( dialog, SIGNAL(destroyed(QObject*)),
this, SLOT(onNewDialogDestroyed(QObject*)) );
myTimer.start( 100 );
// pop up the dialog
QDialog * dialog = new QDialog (this);
dialog->setWindowTitle (tr ("New Torrent"));
myNewDialog = dialog;
QVBoxLayout * top = new QVBoxLayout (dialog);
top->addWidget( (myNewLabel = new QLabel));
top->addWidget( (myNewProgress = new QProgressBar));
QDialogButtonBox * buttons = new QDialogButtonBox (QDialogButtonBox::Ok
| QDialogButtonBox::Open
| QDialogButtonBox::Abort);
myNewButtonBox = buttons;
connect (buttons, SIGNAL(clicked(QAbstractButton*)),
this, SLOT(onNewButtonBoxClicked(QAbstractButton*)));
top->addWidget (buttons);
onProgress ();
dialog->show ();
connect (dialog, SIGNAL(destroyed(QObject*)),
this, SLOT(onNewDialogDestroyed(QObject*)));
myTimer.start (100);
// the file to create
const QString path = QString::fromUtf8( myBuilder->top );
const QString torrentName = QFileInfo(path).completeBaseName() + ".torrent";
myTarget = QDir( myDestination ).filePath( torrentName );
// the file to create
const QString path = QString::fromUtf8 (myBuilder->top);
const QString torrentName = QFileInfo(path).completeBaseName() + ".torrent";
myTarget = QDir (myDestination).filePath (torrentName);
// comment
QString comment;
if( myCommentCheck->isChecked() )
comment = myCommentEdit->text();
// comment
QString comment;
if (myCommentCheck->isChecked())
comment = myCommentEdit->text();
// start making the torrent
tr_makeMetaInfo( myBuilder,
myTarget.toUtf8().constData(),
(trackers.isEmpty() ? NULL : trackers.data()),
trackers.size(),
(comment.isEmpty() ? NULL : comment.toUtf8().constData()),
myPrivateCheck->isChecked() );
// start making the torrent
tr_makeMetaInfo (myBuilder,
myTarget.toUtf8().constData(),
(trackers.isEmpty() ? NULL : trackers.data()),
trackers.size(),
(comment.isEmpty() ? NULL : comment.toUtf8().constData()),
myPrivateCheck->isChecked());
}
/***
@ -169,109 +175,111 @@ MakeDialog :: makeTorrent( )
***/
void
MakeDialog :: onFileClicked( )
MakeDialog :: onFileClicked ()
{
QFileDialog * d = new QFileDialog( this, tr( "Select File" ) );
d->setFileMode( QFileDialog::ExistingFile );
d->setAttribute( Qt::WA_DeleteOnClose );
connect( d, SIGNAL(filesSelected(const QStringList&)),
this, SLOT(onFileSelected(const QStringList&)) );
d->show( );
QFileDialog * d = new QFileDialog (this, tr ("Select File"));
d->setFileMode (QFileDialog::ExistingFile);
d->setAttribute (Qt::WA_DeleteOnClose);
connect (d, SIGNAL(filesSelected(const QStringList&)),
this, SLOT(onFileSelected(const QStringList&)));
d->show ();
}
void
MakeDialog :: onFileSelected( const QStringList& list )
MakeDialog :: onFileSelected (const QStringList& list)
{
if( !list.empty( ) )
onFileSelected( list.front( ) );
if (!list.empty ())
onFileSelected (list.front ());
}
void
MakeDialog :: onFileSelected( const QString& filename )
MakeDialog :: onFileSelected (const QString& filename)
{
myFile = Utils::removeTrailingDirSeparator (filename);
myFileButton->setText( QFileInfo(myFile).fileName() );
onSourceChanged( );
myFile = Utils::removeTrailingDirSeparator (filename);
myFileButton->setText (QFileInfo(myFile).fileName());
onSourceChanged ();
}
void
MakeDialog :: onFolderClicked( )
MakeDialog :: onFolderClicked ()
{
QFileDialog * d = new QFileDialog( this, tr( "Select Folder" ) );
d->setFileMode( QFileDialog::Directory );
d->setOption( QFileDialog::ShowDirsOnly );
d->setAttribute( Qt::WA_DeleteOnClose );
connect( d, SIGNAL(filesSelected(const QStringList&)),
this, SLOT(onFolderSelected(const QStringList&)) );
d->show( );
}
void
MakeDialog :: onFolderSelected( const QStringList& list )
{
if( !list.empty( ) )
onFolderSelected( list.front( ) );
}
void
MakeDialog :: onFolderSelected( const QString& filename )
{
myFolder = Utils::removeTrailingDirSeparator (filename);
myFolderButton->setText( QFileInfo(myFolder).fileName() );
onSourceChanged( );
QFileDialog * d = new QFileDialog (this, tr ("Select Folder"));
d->setFileMode (QFileDialog::Directory);
d->setOption (QFileDialog::ShowDirsOnly);
d->setAttribute (Qt::WA_DeleteOnClose);
connect (d, SIGNAL(filesSelected(const QStringList&)),
this, SLOT(onFolderSelected(const QStringList&)));
d->show ();
}
void
MakeDialog :: onDestinationClicked( )
MakeDialog :: onFolderSelected (const QStringList& list)
{
QFileDialog * d = new QFileDialog( this, tr( "Select Folder" ) );
d->setFileMode( QFileDialog::Directory );
d->setOption( QFileDialog::ShowDirsOnly );
d->setAttribute( Qt::WA_DeleteOnClose );
connect( d, SIGNAL(filesSelected(const QStringList&)),
this, SLOT(onDestinationSelected(const QStringList&)) );
d->show( );
}
void
MakeDialog :: onDestinationSelected( const QStringList& list )
{
if( !list.empty( ) )
onDestinationSelected( list.front() );
}
void
MakeDialog :: onDestinationSelected( const QString& filename )
{
myDestination = Utils::removeTrailingDirSeparator (filename);
myDestinationButton->setText( QFileInfo(myDestination).fileName() );
if (!list.empty ())
onFolderSelected (list.front ());
}
void
MakeDialog :: enableBuddyWhenChecked( QRadioButton * box, QWidget * buddy )
MakeDialog :: onFolderSelected (const QString& filename)
{
connect( box, SIGNAL(toggled(bool)), buddy, SLOT(setEnabled(bool)) );
buddy->setEnabled( box->isChecked( ) );
myFolder = Utils::removeTrailingDirSeparator (filename);
myFolderButton->setText (QFileInfo(myFolder).fileName());
onSourceChanged ();
}
void
MakeDialog :: onDestinationClicked ()
{
QFileDialog * d = new QFileDialog (this, tr ("Select Folder"));
d->setFileMode (QFileDialog::Directory);
d->setOption (QFileDialog::ShowDirsOnly);
d->setAttribute (Qt::WA_DeleteOnClose);
connect (d, SIGNAL(filesSelected(const QStringList&)),
this, SLOT(onDestinationSelected(const QStringList&)));
d->show ();
}
void
MakeDialog :: enableBuddyWhenChecked( QCheckBox * box, QWidget * buddy )
MakeDialog :: onDestinationSelected (const QStringList& list)
{
connect( box, SIGNAL(toggled(bool)), buddy, SLOT(setEnabled(bool)) );
buddy->setEnabled( box->isChecked( ) );
if (!list.empty ())
onDestinationSelected (list.front());
}
void
MakeDialog :: onDestinationSelected (const QString& filename)
{
myDestination = Utils::removeTrailingDirSeparator (filename);
myDestinationButton->setText (QFileInfo(myDestination).fileName());
}
void
MakeDialog :: enableBuddyWhenChecked (QRadioButton * box, QWidget * buddy)
{
connect (box, SIGNAL(toggled(bool)), buddy, SLOT(setEnabled(bool)));
buddy->setEnabled (box->isChecked ());
}
void
MakeDialog :: enableBuddyWhenChecked (QCheckBox * box, QWidget * buddy)
{
connect (box, SIGNAL(toggled(bool)), buddy, SLOT(setEnabled(bool)));
buddy->setEnabled (box->isChecked ());
}
QString
MakeDialog :: getSource( ) const
MakeDialog :: getSource () const
{
return myFileRadio->isChecked( ) ? myFile : myFolder;
return myFileRadio->isChecked () ? myFile : myFolder;
}
void
MakeDialog :: onButtonBoxClicked( QAbstractButton * button )
MakeDialog :: onButtonBoxClicked (QAbstractButton * button)
{
switch( myButtonBox->standardButton( button ) )
switch (myButtonBox->standardButton (button))
{
case QDialogButtonBox::Ok:
makeTorrent( );
break;
case QDialogButtonBox::Ok:
makeTorrent ();
break;
default: // QDialogButtonBox::Close:
deleteLater( );
break;
default: // QDialogButtonBox::Close:
deleteLater ();
break;
}
}
@ -280,140 +288,144 @@ MakeDialog :: onButtonBoxClicked( QAbstractButton * button )
***/
void
MakeDialog :: onSourceChanged( )
MakeDialog :: onSourceChanged ()
{
if( myBuilder )
if (myBuilder)
{
tr_metaInfoBuilderFree( myBuilder );
myBuilder = 0;
tr_metaInfoBuilderFree (myBuilder);
myBuilder = 0;
}
const QString filename = getSource( );
if( !filename.isEmpty( ) )
myBuilder = tr_metaInfoBuilderCreate( filename.toUtf8().constData() );
const QString filename = getSource ();
if (!filename.isEmpty ())
myBuilder = tr_metaInfoBuilderCreate (filename.toUtf8().constData());
QString text;
if( !myBuilder )
text = tr( "<i>No source selected<i>" );
else {
QString files = tr( "%Ln File(s)", 0, myBuilder->fileCount );
QString pieces = tr( "%Ln Piece(s)", 0, myBuilder->pieceCount );
text = tr( "%1 in %2; %3 @ %4" )
.arg( Formatter::sizeToString( myBuilder->totalSize ) )
.arg( files )
.arg( pieces )
.arg( Formatter::sizeToString( myBuilder->pieceSize ) );
QString text;
if (!myBuilder)
{
text = tr ("<i>No source selected<i>");
}
else
{
QString files = tr ("%Ln File(s)", 0, myBuilder->fileCount);
QString pieces = tr ("%Ln Piece(s)", 0, myBuilder->pieceCount);
text = tr ("%1 in %2; %3 @ %4")
.arg (Formatter::sizeToString (myBuilder->totalSize))
.arg (files)
.arg (pieces)
.arg (Formatter::sizeToString (myBuilder->pieceSize));
}
mySourceLabel->setText( text );
mySourceLabel->setText (text);
}
// bah, there doesn't seem to be any cleaner way to override
// QPlainTextEdit's default desire to be 12 lines tall
class ShortPlainTextEdit: public QPlainTextEdit {
public:
virtual ~ShortPlainTextEdit( ) { }
ShortPlainTextEdit( QWidget * parent = 0 ): QPlainTextEdit(parent) { }
virtual QSize sizeHint ( ) const { return QSize( 256, 50 ); }
class ShortPlainTextEdit: public QPlainTextEdit
{
public:
virtual ~ShortPlainTextEdit () {}
ShortPlainTextEdit (QWidget * parent = 0): QPlainTextEdit(parent) {}
virtual QSize sizeHint () const { return QSize (256, 50); }
};
MakeDialog :: MakeDialog( Session & session, QWidget * parent ):
QDialog( parent, Qt::Dialog ),
mySession( session ),
myBuilder( 0 )
MakeDialog :: MakeDialog (Session & session, QWidget * parent):
QDialog (parent, Qt::Dialog),
mySession (session),
myBuilder (0)
{
setAcceptDrops( true );
setAcceptDrops (true);
connect( &myTimer, SIGNAL(timeout()), this, SLOT(onProgress()) );
connect (&myTimer, SIGNAL(timeout()), this, SLOT(onProgress()));
setWindowTitle( tr( "New Torrent" ) );
QVBoxLayout * top = new QVBoxLayout( this );
top->setSpacing( HIG :: PAD );
setWindowTitle (tr ("New Torrent"));
QVBoxLayout * top = new QVBoxLayout (this);
top->setSpacing (HIG :: PAD);
HIG * hig = new HIG;
hig->setContentsMargins( 0, 0, 0, 0 );
hig->addSectionTitle( tr( "Files" ) );
HIG * hig = new HIG;
hig->setContentsMargins (0, 0, 0, 0);
hig->addSectionTitle (tr ("Files"));
QFileIconProvider iconProvider;
const int iconSize( style()->pixelMetric( QStyle::PM_SmallIconSize ) );
const QIcon folderIcon = iconProvider.icon( QFileIconProvider::Folder );
const QPixmap folderPixmap = folderIcon.pixmap( iconSize );
QPushButton * b = new QPushButton;
b->setIcon( folderPixmap );
b->setStyleSheet( QString::fromUtf8( "text-align: left; padding-left: 5; padding-right: 5" ) );
myDestination = QDir::homePath();
b->setText( myDestination );
connect( b, SIGNAL(clicked(bool)),
this, SLOT(onDestinationClicked(void)) );
myDestinationButton = b;
hig->addRow( tr( "Sa&ve to:" ), b );
QFileIconProvider iconProvider;
const int iconSize (style()->pixelMetric (QStyle::PM_SmallIconSize));
const QIcon folderIcon = iconProvider.icon (QFileIconProvider::Folder);
const QPixmap folderPixmap = folderIcon.pixmap (iconSize);
QPushButton * b = new QPushButton;
b->setIcon (folderPixmap);
b->setStyleSheet (QString::fromUtf8 ("text-align: left; padding-left: 5; padding-right: 5"));
myDestination = QDir::homePath();
b->setText (myDestination);
connect (b, SIGNAL(clicked(bool)),
this, SLOT(onDestinationClicked(void)));
myDestinationButton = b;
hig->addRow (tr ("Sa&ve to:"), b);
myFolderRadio = new QRadioButton( tr( "Source F&older:" ) );
connect( myFolderRadio, SIGNAL(toggled(bool)),
this, SLOT(onSourceChanged()) );
myFolderButton = new QPushButton;
myFolderButton->setIcon( folderPixmap );
myFolderButton->setText( tr( "(None)" ) );
myFolderButton->setStyleSheet( QString::fromUtf8( "text-align: left; padding-left: 5; padding-right: 5" ) );
connect( myFolderButton, SIGNAL(clicked(bool)),
this, SLOT(onFolderClicked(void)) );
hig->addRow( myFolderRadio, myFolderButton );
enableBuddyWhenChecked( myFolderRadio, myFolderButton );
myFolderRadio = new QRadioButton (tr ("Source F&older:"));
connect (myFolderRadio, SIGNAL(toggled(bool)),
this, SLOT(onSourceChanged()));
myFolderButton = new QPushButton;
myFolderButton->setIcon (folderPixmap);
myFolderButton->setText (tr ("(None)"));
myFolderButton->setStyleSheet (QString::fromUtf8 ("text-align: left; padding-left: 5; padding-right: 5"));
connect (myFolderButton, SIGNAL(clicked(bool)),
this, SLOT(onFolderClicked(void)));
hig->addRow (myFolderRadio, myFolderButton);
enableBuddyWhenChecked (myFolderRadio, myFolderButton);
const QIcon fileIcon = iconProvider.icon( QFileIconProvider::File );
const QPixmap filePixmap = fileIcon.pixmap( iconSize );
myFileRadio = new QRadioButton( tr( "Source &File:" ) );
myFileRadio->setChecked( true );
connect( myFileRadio, SIGNAL(toggled(bool)),
this, SLOT(onSourceChanged()) );
myFileButton = new QPushButton;
myFileButton->setText( tr( "(None)" ) );
myFileButton->setIcon( filePixmap );
myFileButton->setStyleSheet( QString::fromUtf8( "text-align: left; padding-left: 5; padding-right: 5" ) );
connect( myFileButton, SIGNAL(clicked(bool)),
this, SLOT(onFileClicked(void)) );
hig->addRow( myFileRadio, myFileButton );
enableBuddyWhenChecked( myFileRadio, myFileButton );
const QIcon fileIcon = iconProvider.icon (QFileIconProvider::File);
const QPixmap filePixmap = fileIcon.pixmap (iconSize);
myFileRadio = new QRadioButton (tr ("Source &File:"));
myFileRadio->setChecked (true);
connect (myFileRadio, SIGNAL(toggled(bool)),
this, SLOT(onSourceChanged()));
myFileButton = new QPushButton;
myFileButton->setText (tr ("(None)"));
myFileButton->setIcon (filePixmap);
myFileButton->setStyleSheet (QString::fromUtf8 ("text-align: left; padding-left: 5; padding-right: 5"));
connect (myFileButton, SIGNAL(clicked(bool)),
this, SLOT(onFileClicked(void)));
hig->addRow (myFileRadio, myFileButton);
enableBuddyWhenChecked (myFileRadio, myFileButton);
mySourceLabel = new QLabel( this );
hig->addRow( tr( "" ), mySourceLabel );
mySourceLabel = new QLabel (this);
hig->addRow (tr (""), mySourceLabel);
hig->addSectionDivider( );
hig->addSectionTitle( tr( "Properties" ) );
hig->addSectionDivider ();
hig->addSectionTitle (tr ("Properties"));
hig->addWideControl( myTrackerEdit = new ShortPlainTextEdit );
const int height = fontMetrics().size( 0, QString::fromUtf8("\n\n\n\n") ).height( );
myTrackerEdit->setMinimumHeight( height );
hig->addTallRow( tr( "&Trackers:" ), myTrackerEdit );
QLabel * l = new QLabel( tr( "To add a backup URL, add it on the line after the primary URL.\nTo add another primary URL, add it after a blank line." ) );
l->setAlignment( Qt::AlignLeft );
hig->addRow( tr( "" ), l );
myTrackerEdit->resize( 500, height );
hig->addWideControl (myTrackerEdit = new ShortPlainTextEdit);
const int height = fontMetrics().size (0, QString::fromUtf8("\n\n\n\n")).height ();
myTrackerEdit->setMinimumHeight (height);
hig->addTallRow (tr ("&Trackers:"), myTrackerEdit);
QLabel * l = new QLabel (tr ("To add a backup URL, add it on the line after the primary URL.\nTo add another primary URL, add it after a blank line."));
l->setAlignment (Qt::AlignLeft);
hig->addRow (tr (""), l);
myTrackerEdit->resize (500, height);
myCommentCheck = new QCheckBox( tr( "Co&mment" ) );
myCommentEdit = new QLineEdit( );
hig->addRow( myCommentCheck, myCommentEdit );
enableBuddyWhenChecked( myCommentCheck, myCommentEdit );
myCommentCheck = new QCheckBox (tr ("Co&mment"));
myCommentEdit = new QLineEdit ();
hig->addRow (myCommentCheck, myCommentEdit);
enableBuddyWhenChecked (myCommentCheck, myCommentEdit);
myPrivateCheck = hig->addWideCheckBox( tr( "&Private torrent" ), false );
myPrivateCheck = hig->addWideCheckBox (tr ("&Private torrent"), false);
hig->finish( );
top->addWidget( hig, 1 );
hig->finish ();
top->addWidget (hig, 1);
myButtonBox = new QDialogButtonBox( QDialogButtonBox::Ok
| QDialogButtonBox::Close );
connect( myButtonBox, SIGNAL(clicked(QAbstractButton*)),
this, SLOT(onButtonBoxClicked(QAbstractButton*)) );
myButtonBox = new QDialogButtonBox (QDialogButtonBox::Ok
| QDialogButtonBox::Close);
connect (myButtonBox, SIGNAL(clicked(QAbstractButton*)),
this, SLOT(onButtonBoxClicked(QAbstractButton*)));
top->addWidget( myButtonBox );
onSourceChanged( );
top->addWidget (myButtonBox);
onSourceChanged ();
}
MakeDialog :: ~MakeDialog( )
MakeDialog :: ~MakeDialog ()
{
if( myBuilder )
tr_metaInfoBuilderFree( myBuilder );
if (myBuilder)
tr_metaInfoBuilderFree (myBuilder);
}
/***
@ -421,31 +433,31 @@ MakeDialog :: ~MakeDialog( )
***/
void
MakeDialog :: dragEnterEvent( QDragEnterEvent * event )
MakeDialog :: dragEnterEvent (QDragEnterEvent * event)
{
const QMimeData * mime = event->mimeData( );
const QMimeData * mime = event->mimeData ();
if( mime->urls().size() && QFile(mime->urls().front().path()).exists( ) )
event->acceptProposedAction();
if (mime->urls().size() && QFile(mime->urls().front().path()).exists ())
event->acceptProposedAction();
}
void
MakeDialog :: dropEvent( QDropEvent * event )
MakeDialog :: dropEvent (QDropEvent * event)
{
const QString filename = event->mimeData()->urls().front().path();
const QFileInfo fileInfo( filename );
const QString filename = event->mimeData()->urls().front().path();
const QFileInfo fileInfo (filename);
if( fileInfo.exists( ) )
if (fileInfo.exists ())
{
if( fileInfo.isDir( ) )
if (fileInfo.isDir ())
{
myFolderRadio->setChecked( true );
onFolderSelected( filename );
myFolderRadio->setChecked (true);
onFolderSelected (filename );
}
else // it's a file
else // it's a file
{
myFileRadio->setChecked( true );
onFileSelected( filename );
myFileRadio->setChecked (true);
onFileSelected (filename);
}
}
}

View File

@ -34,64 +34,64 @@ extern "C"
class MakeDialog: public QDialog
{
Q_OBJECT
Q_OBJECT
private slots:
void onSourceChanged( );
void onButtonBoxClicked( QAbstractButton* );
void onNewButtonBoxClicked( QAbstractButton* );
void onNewDialogDestroyed( QObject* );
void onProgress( );
private slots:
void onSourceChanged ();
void onButtonBoxClicked (QAbstractButton*);
void onNewButtonBoxClicked (QAbstractButton*);
void onNewDialogDestroyed (QObject*);
void onProgress ();
void onFolderClicked( );
void onFolderSelected( const QString& );
void onFolderSelected( const QStringList& );
void onFolderClicked ();
void onFolderSelected (const QString&);
void onFolderSelected (const QStringList&);
void onFileClicked( );
void onFileSelected( const QString& );
void onFileSelected( const QStringList& );
void onFileClicked ();
void onFileSelected (const QString&);
void onFileSelected (const QStringList&);
void onDestinationClicked( );
void onDestinationSelected( const QString& );
void onDestinationSelected( const QStringList& );
void onDestinationClicked ();
void onDestinationSelected (const QString&);
void onDestinationSelected (const QStringList&);
private:
void makeTorrent( );
QString getSource( ) const;
void enableBuddyWhenChecked( QCheckBox *, QWidget * );
void enableBuddyWhenChecked( QRadioButton *, QWidget * );
private:
void makeTorrent ();
QString getSource () const;
void enableBuddyWhenChecked (QCheckBox *, QWidget *);
void enableBuddyWhenChecked (QRadioButton *, QWidget *);
private:
Session& mySession;
QString myDestination;
QString myTarget;
QString myFile;
QString myFolder;
QTimer myTimer;
QRadioButton * myFolderRadio;
QRadioButton * myFileRadio;
QPushButton * myDestinationButton;
QPushButton * myFileButton;
QPushButton * myFolderButton;
QPlainTextEdit * myTrackerEdit;
QCheckBox * myCommentCheck;
QLineEdit * myCommentEdit;
QCheckBox * myPrivateCheck;
QLabel * mySourceLabel;
QDialogButtonBox * myButtonBox;
QProgressBar * myNewProgress;
QLabel * myNewLabel;
QDialogButtonBox * myNewButtonBox;
QDialog * myNewDialog;
struct tr_metainfo_builder * myBuilder;
private:
Session& mySession;
QString myDestination;
QString myTarget;
QString myFile;
QString myFolder;
QTimer myTimer;
QRadioButton * myFolderRadio;
QRadioButton * myFileRadio;
QPushButton * myDestinationButton;
QPushButton * myFileButton;
QPushButton * myFolderButton;
QPlainTextEdit * myTrackerEdit;
QCheckBox * myCommentCheck;
QLineEdit * myCommentEdit;
QCheckBox * myPrivateCheck;
QLabel * mySourceLabel;
QDialogButtonBox * myButtonBox;
QProgressBar * myNewProgress;
QLabel * myNewLabel;
QDialogButtonBox * myNewButtonBox;
QDialog * myNewDialog;
struct tr_metainfo_builder * myBuilder;
protected:
virtual void dragEnterEvent( QDragEnterEvent * );
virtual void dropEvent( QDropEvent * );
protected:
virtual void dragEnterEvent (QDragEnterEvent *);
virtual void dropEvent (QDropEvent *);
public:
MakeDialog( Session&, QWidget * parent = 0 );
~MakeDialog( );
public:
MakeDialog (Session&, QWidget * parent = 0);
~MakeDialog ();
};
#endif

View File

@ -1,4 +1,4 @@
#/bin/sh
#valgrind --tool=cachegrind ./transmission-qt 2>&1 | tee runlog
valgrind --tool=massif --threshold=0.2 ./transmission-qt 2>&1 | tee runlog
#valgrind --tool=memcheck --leak-check=full --leak-resolution=high --num-callers=48 --log-file=x-valgrind --show-reachable=no ./transmission-qt 2>&1 | tee runlog
#valgrind --tool=massif --threshold=0.2 ./transmission-qt 2>&1 | tee runlog
valgrind --tool=memcheck --leak-check=full --leak-resolution=high --num-callers=16 --log-file=x-valgrind --show-reachable=no ./transmission-qt 2>&1 | tee runlog

View File

@ -56,7 +56,7 @@ FileAdded :: executed (int64_t tag, const QString& result, struct tr_variant * a
if (tag != myTag)
return;
if ( (result == "success") && !myDelFile.isEmpty ())
if ((result == "success") && !myDelFile.isEmpty ())
{
QFile file (myDelFile);
file.setPermissions (QFile::ReadOwner | QFile::WriteOwner);

View File

@ -50,8 +50,8 @@ class FileAdded: public QObject
Q_OBJECT
public:
FileAdded (int tag, const QString& name): myTag (tag), myName (name) { }
~FileAdded () { }
FileAdded (int tag, const QString& name): myTag (tag), myName (name) {}
~FileAdded () {}
void setFileToDelete (const QString& file) { myDelFile = file; }
public slots:

File diff suppressed because it is too large Load Diff

View File

@ -19,18 +19,18 @@
class QAbstractButton;
class QCheckBox;
class QString;
class QDoubleSpinBox;
class QSpinBox;
class QHttp;
class QLabel;
class QLineEdit;
class QVBoxLayout;
class QMessageBox;
class QPushButton;
class QSpinBox;
class QString;
class QTime;
class QTimeEdit;
class QVBoxLayout;
class QWidget;
class QPushButton;
class QMessageBox;
class QHttp;
class FreespaceLabel;
class Prefs;
@ -38,83 +38,83 @@ class Session;
class PrefsDialog: public QDialog
{
Q_OBJECT
Q_OBJECT
private slots:
void checkBoxToggled( bool checked );
void spinBoxEditingFinished( );
void timeEditingFinished( );
void lineEditingFinished( );
void refreshPref( int key );
void encryptionEdited( int );
void altSpeedDaysEdited( int );
void sessionUpdated( );
void onWatchClicked( );
void onScriptClicked( );
void onIncompleteClicked( );
void onDestinationClicked( );
void onLocationSelected( const QString&, int key );
void onPortTested( bool );
void onPortTest( );
private slots:
void checkBoxToggled (bool checked);
void spinBoxEditingFinished ();
void timeEditingFinished ();
void lineEditingFinished ();
void refreshPref (int key);
void encryptionEdited (int);
void altSpeedDaysEdited (int);
void sessionUpdated ();
void onWatchClicked ();
void onScriptClicked ();
void onIncompleteClicked ();
void onDestinationClicked ();
void onLocationSelected (const QString&, int key);
void onPortTested (bool);
void onPortTest ();
void onUpdateBlocklistClicked( );
void onUpdateBlocklistCancelled( );
void onBlocklistDialogDestroyed( QObject * );
void onBlocklistUpdated( int n );
void onUpdateBlocklistClicked ();
void onUpdateBlocklistCancelled ();
void onBlocklistDialogDestroyed (QObject *);
void onBlocklistUpdated (int n);
private:
QDoubleSpinBox * doubleSpinBoxNew( int key, double low, double high, double step, int decimals );
QCheckBox * checkBoxNew( const QString& text, int key );
QSpinBox * spinBoxNew( int key, int low, int high, int step );
QTimeEdit * timeEditNew( int key );
QLineEdit * lineEditNew( int key, int mode = 0 );
void enableBuddyWhenChecked( QCheckBox *, QWidget * );
void updateBlocklistLabel( );
private:
QDoubleSpinBox * doubleSpinBoxNew (int key, double low, double high, double step, int decimals);
QCheckBox * checkBoxNew (const QString& text, int key);
QSpinBox * spinBoxNew (int key, int low, int high, int step);
QTimeEdit * timeEditNew (int key);
QLineEdit * lineEditNew (int key, int mode = 0);
void enableBuddyWhenChecked (QCheckBox *, QWidget *);
void updateBlocklistLabel ();
public:
PrefsDialog( Session&, Prefs&, QWidget * parent = 0 );
~PrefsDialog( );
public:
PrefsDialog (Session&, Prefs&, QWidget * parent = 0);
~PrefsDialog ();
private:
void setPref( int key, const QVariant& v );
bool isAllowed( int key ) const;
QWidget * createDownloadingTab( );
QWidget * createSeedingTab( );
QWidget * createSpeedTab( );
QWidget * createPrivacyTab( );
QWidget * createNetworkTab( );
QWidget * createDesktopTab( );
QWidget * createRemoteTab( Session& );
private:
void setPref (int key, const QVariant& v);
bool isAllowed (int key) const;
QWidget * createDownloadingTab ();
QWidget * createSeedingTab ();
QWidget * createSpeedTab ();
QWidget * createPrivacyTab ();
QWidget * createNetworkTab ();
QWidget * createDesktopTab ();
QWidget * createRemoteTab (Session&);
private:
typedef QMap<int,QWidget*> key2widget_t;
key2widget_t myWidgets;
const bool myIsServer;
Session& mySession;
Prefs& myPrefs;
QVBoxLayout * myLayout;
QLabel * myPortLabel;
QPushButton * myPortButton;
QPushButton * myWatchButton;
QPushButton * myTorrentDoneScriptButton;
QCheckBox * myTorrentDoneScriptCheckbox;
QCheckBox * myIncompleteCheckbox;
QPushButton * myIncompleteButton;
QPushButton * myDestinationButton;
QWidgetList myWebWidgets;
QWidgetList myWebAuthWidgets;
QWidgetList myWebWhitelistWidgets;
QWidgetList myProxyWidgets;
QWidgetList myProxyAuthWidgets;
QWidgetList mySchedWidgets;
QWidgetList myBlockWidgets;
QWidgetList myUnsupportedWhenRemote;
FreespaceLabel * myFreespaceLabel;
private:
typedef QMap<int,QWidget*> key2widget_t;
key2widget_t myWidgets;
const bool myIsServer;
Session& mySession;
Prefs& myPrefs;
QVBoxLayout * myLayout;
QLabel * myPortLabel;
QPushButton * myPortButton;
QPushButton * myWatchButton;
QPushButton * myTorrentDoneScriptButton;
QCheckBox * myTorrentDoneScriptCheckbox;
QCheckBox * myIncompleteCheckbox;
QPushButton * myIncompleteButton;
QPushButton * myDestinationButton;
QWidgetList myWebWidgets;
QWidgetList myWebAuthWidgets;
QWidgetList myWebWhitelistWidgets;
QWidgetList myProxyWidgets;
QWidgetList myProxyAuthWidgets;
QWidgetList mySchedWidgets;
QWidgetList myBlockWidgets;
QWidgetList myUnsupportedWhenRemote;
FreespaceLabel * myFreespaceLabel;
int myBlocklistHttpTag;
QHttp * myBlocklistHttp;
QMessageBox * myBlocklistDialog;
QLabel * myBlocklistLabel;
int myBlocklistHttpTag;
QHttp * myBlocklistHttp;
QMessageBox * myBlocklistDialog;
QLabel * myBlocklistLabel;
};
#endif

View File

@ -46,7 +46,7 @@ class RelocateDialog: public QDialog
public:
RelocateDialog (Session&, TorrentModel&, const QSet<int>& ids, QWidget * parent = 0);
~RelocateDialog () { }
~RelocateDialog () {}
};
#endif

View File

@ -28,90 +28,90 @@
***/
void
SessionDialog :: onAccepted( )
SessionDialog :: onAccepted ()
{
myPrefs.set( Prefs::SESSION_IS_REMOTE, myRemoteRadioButton->isChecked( ) );
myPrefs.set( Prefs::SESSION_REMOTE_HOST, myHostLineEdit->text( ) );
myPrefs.set( Prefs::SESSION_REMOTE_PORT, myPortSpinBox->value( ) );
myPrefs.set( Prefs::SESSION_REMOTE_AUTH, myAuthCheckBox->isChecked( ) );
myPrefs.set( Prefs::SESSION_REMOTE_USERNAME, myUsernameLineEdit->text( ) );
myPrefs.set( Prefs::SESSION_REMOTE_PASSWORD, myPasswordLineEdit->text( ) );
mySession.restart( );
hide( );
myPrefs.set (Prefs::SESSION_IS_REMOTE, myRemoteRadioButton->isChecked ());
myPrefs.set (Prefs::SESSION_REMOTE_HOST, myHostLineEdit->text ());
myPrefs.set (Prefs::SESSION_REMOTE_PORT, myPortSpinBox->value ());
myPrefs.set (Prefs::SESSION_REMOTE_AUTH, myAuthCheckBox->isChecked ());
myPrefs.set (Prefs::SESSION_REMOTE_USERNAME, myUsernameLineEdit->text ());
myPrefs.set (Prefs::SESSION_REMOTE_PASSWORD, myPasswordLineEdit->text ());
mySession.restart ();
hide ();
}
void
SessionDialog :: resensitize( )
SessionDialog :: resensitize ()
{
const bool isRemote = myRemoteRadioButton->isChecked();
const bool useAuth = myAuthCheckBox->isChecked();
const bool isRemote = myRemoteRadioButton->isChecked();
const bool useAuth = myAuthCheckBox->isChecked();
foreach( QWidget * w, myRemoteWidgets )
w->setEnabled( isRemote );
foreach (QWidget * w, myRemoteWidgets)
w->setEnabled (isRemote);
foreach( QWidget * w, myAuthWidgets )
w->setEnabled( isRemote && useAuth );
foreach (QWidget * w, myAuthWidgets)
w->setEnabled (isRemote && useAuth);
}
/***
****
***/
SessionDialog :: SessionDialog( Session& session, Prefs& prefs, QWidget * parent ):
QDialog( parent ),
mySession( session ),
myPrefs( prefs )
SessionDialog :: SessionDialog (Session& session, Prefs& prefs, QWidget * parent):
QDialog (parent),
mySession (session),
myPrefs (prefs)
{
QWidget * l;
QSpinBox * sb;
QCheckBox * cb;
QLineEdit * le;
QRadioButton * rb;
QWidget * l;
QSpinBox * sb;
QCheckBox * cb;
QLineEdit * le;
QRadioButton * rb;
setWindowTitle( tr( "Change Session" ) );
QVBoxLayout * top = new QVBoxLayout( this );
top->setSpacing( HIG :: PAD );
setWindowTitle (tr ("Change Session"));
QVBoxLayout * top = new QVBoxLayout (this);
top->setSpacing (HIG :: PAD);
HIG * hig = new HIG;
hig->setContentsMargins( 0, 0, 0, 0 );
hig->addSectionTitle( tr( "Source" ) );
rb = new QRadioButton( tr( "Start &Local Session" ) );
rb->setChecked( !prefs.get<bool>(Prefs::SESSION_IS_REMOTE) );
connect( rb, SIGNAL(toggled(bool)), this, SLOT(resensitize()));
hig->addWideControl( rb );
rb = myRemoteRadioButton = new QRadioButton( tr( "Connect to &Remote Session" ) );
rb->setChecked( prefs.get<bool>(Prefs::SESSION_IS_REMOTE) );
connect( rb, SIGNAL(toggled(bool)), this, SLOT(resensitize()));
hig->addWideControl( rb );
le = myHostLineEdit = new QLineEdit( );
le->setText( prefs.get<QString>(Prefs::SESSION_REMOTE_HOST) );
l = hig->addRow( tr( "&Host:" ), le );
myRemoteWidgets << l << le;
sb = myPortSpinBox = new QSpinBox;
sb->setRange( 1, 65535 );
sb->setValue( prefs.get<int>(Prefs::SESSION_REMOTE_PORT) );
l = hig->addRow( tr( "&Port:" ), sb );
myRemoteWidgets << l << sb;
cb = myAuthCheckBox = new QCheckBox( tr( "&Authentication required" ) );
cb->setChecked( prefs.get<bool>(Prefs::SESSION_REMOTE_AUTH) );
connect( cb, SIGNAL(toggled(bool)), this, SLOT(resensitize()));
myRemoteWidgets << cb;
hig->addWideControl( cb );
le = myUsernameLineEdit = new QLineEdit( );
le->setText( prefs.get<QString>(Prefs::SESSION_REMOTE_USERNAME) );
l = hig->addRow( tr( "&Username:" ), le );
myAuthWidgets << l << le;
le = myPasswordLineEdit = new QLineEdit( );
le->setEchoMode( QLineEdit::Password );
le->setText( prefs.get<QString>(Prefs::SESSION_REMOTE_PASSWORD) );
l = hig->addRow( tr( "Pass&word:" ), le );
myAuthWidgets << l << le;
hig->finish( );
top->addWidget( hig, 1 );
resensitize( );
HIG * hig = new HIG;
hig->setContentsMargins (0, 0, 0, 0);
hig->addSectionTitle (tr ("Source"));
rb = new QRadioButton (tr ("Start &Local Session"));
rb->setChecked (!prefs.get<bool>(Prefs::SESSION_IS_REMOTE));
connect (rb, SIGNAL(toggled(bool)), this, SLOT(resensitize()));
hig->addWideControl (rb);
rb = myRemoteRadioButton = new QRadioButton (tr ("Connect to &Remote Session"));
rb->setChecked (prefs.get<bool>(Prefs::SESSION_IS_REMOTE));
connect (rb, SIGNAL(toggled(bool)), this, SLOT(resensitize()));
hig->addWideControl (rb);
le = myHostLineEdit = new QLineEdit ();
le->setText (prefs.get<QString>(Prefs::SESSION_REMOTE_HOST));
l = hig->addRow (tr ("&Host:"), le);
myRemoteWidgets << l << le;
sb = myPortSpinBox = new QSpinBox;
sb->setRange (1, 65535);
sb->setValue (prefs.get<int>(Prefs::SESSION_REMOTE_PORT));
l = hig->addRow (tr ("&Port:"), sb);
myRemoteWidgets << l << sb;
cb = myAuthCheckBox = new QCheckBox (tr ("&Authentication required"));
cb->setChecked (prefs.get<bool>(Prefs::SESSION_REMOTE_AUTH));
connect (cb, SIGNAL(toggled(bool)), this, SLOT(resensitize()));
myRemoteWidgets << cb;
hig->addWideControl (cb);
le = myUsernameLineEdit = new QLineEdit ();
le->setText (prefs.get<QString>(Prefs::SESSION_REMOTE_USERNAME));
l = hig->addRow (tr ("&Username:"), le);
myAuthWidgets << l << le;
le = myPasswordLineEdit = new QLineEdit ();
le->setEchoMode (QLineEdit::Password);
le->setText (prefs.get<QString>(Prefs::SESSION_REMOTE_PASSWORD));
l = hig->addRow (tr ("Pass&word:"), le);
myAuthWidgets << l << le;
hig->finish ();
top->addWidget (hig, 1);
resensitize ();
QDialogButtonBox * buttons = new QDialogButtonBox( QDialogButtonBox::Cancel|QDialogButtonBox::Ok );
connect( buttons, SIGNAL(rejected()), this, SLOT(hide()));
connect( buttons, SIGNAL(accepted()), this, SLOT(onAccepted()));
top->addWidget( buttons, 0 );
QDialogButtonBox * buttons = new QDialogButtonBox (QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
connect (buttons, SIGNAL(rejected()), this, SLOT(hide()));
connect (buttons, SIGNAL(accepted()), this, SLOT(onAccepted()));
top->addWidget (buttons, 0);
}

View File

@ -25,30 +25,30 @@ class QSpinBox;
class SessionDialog: public QDialog
{
Q_OBJECT
Q_OBJECT
public:
SessionDialog( Session& session, Prefs& prefs, QWidget * parent = 0 );
~SessionDialog( ) { }
public:
SessionDialog (Session& session, Prefs& prefs, QWidget * parent = 0);
~SessionDialog () {}
private slots:
void onAccepted( );
void resensitize( );
private slots:
void onAccepted ();
void resensitize ();
private:
QCheckBox * myAuthCheckBox;
QRadioButton * myRemoteRadioButton;
QLineEdit * myHostLineEdit;
QSpinBox * myPortSpinBox;
QLineEdit * myUsernameLineEdit;
QLineEdit * myPasswordLineEdit;
QCheckBox * myAutomaticCheckBox;
private:
QCheckBox * myAuthCheckBox;
QRadioButton * myRemoteRadioButton;
QLineEdit * myHostLineEdit;
QSpinBox * myPortSpinBox;
QLineEdit * myUsernameLineEdit;
QLineEdit * myPasswordLineEdit;
QCheckBox * myAutomaticCheckBox;
private:
Session& mySession;
Prefs& myPrefs;
QWidgetList myRemoteWidgets;
QWidgetList myAuthWidgets;
private:
Session& mySession;
Prefs& myPrefs;
QWidgetList myRemoteWidgets;
QWidgetList myAuthWidgets;
};
#endif

View File

@ -22,7 +22,7 @@ class Speed
Speed (int Bps): _Bps (Bps) {}
public:
Speed (): _Bps (0) { }
Speed (): _Bps (0) {}
double KBps () const;
int Bps () const { return _Bps; }
bool isZero () const { return _Bps == 0; }

View File

@ -46,29 +46,39 @@
#include "squeezelabel.h"
void SqueezeLabel::init()
void
SqueezeLabel :: init ()
{
setTextInteractionFlags(Qt::TextSelectableByMouse);
setTextInteractionFlags(Qt::TextSelectableByMouse);
}
SqueezeLabel::SqueezeLabel(const QString& text, QWidget *parent): QLabel(text, parent)
SqueezeLabel :: SqueezeLabel (const QString& text, QWidget *parent):
QLabel (text, parent)
{
init();
init();
}
SqueezeLabel::SqueezeLabel(QWidget *parent) : QLabel(parent)
SqueezeLabel :: SqueezeLabel (QWidget * parent):
QLabel (parent)
{
init();
init();
}
void SqueezeLabel::paintEvent(QPaintEvent* paintEvent)
void
SqueezeLabel :: paintEvent (QPaintEvent * paintEvent)
{
Q_UNUSED(paintEvent);
Q_UNUSED (paintEvent);
QPainter painter(this);
QFontMetrics fm = fontMetrics();
QStyleOption opt;
opt.initFrom(this);
const QString elidedText = fm.elidedText( text(), Qt::ElideMiddle, width());
style()->drawItemText(&painter, contentsRect(), alignment(), opt.palette, isEnabled(), elidedText, foregroundRole());
QPainter painter (this);
QFontMetrics fm = fontMetrics ();
QStyleOption opt;
opt.initFrom (this);
const QString elidedText = fm.elidedText (text(), Qt::ElideMiddle, width());
style()->drawItemText (&painter,
contentsRect(),
alignment(),
opt.palette,
isEnabled(),
elidedText,
foregroundRole());
}

View File

@ -48,13 +48,13 @@ class SqueezeLabel : public QLabel
{
Q_OBJECT
public:
SqueezeLabel(QWidget *parent = 0);
SqueezeLabel(const QString& text, QWidget *parent = 0);
public:
SqueezeLabel (QWidget *parent=0);
SqueezeLabel (const QString& text, QWidget *parent=0);
protected:
void init();
void paintEvent(QPaintEvent* paintEvent);
protected:
void init ();
void paintEvent (QPaintEvent* paintEvent);
};
#endif // SQUEEZELABEL_H

View File

@ -32,10 +32,10 @@
enum
{
GUI_PAD = 6,
BAR_WIDTH = 50,
BAR_HEIGHT = 12,
LINE_SPACING = 4
GUI_PAD = 6,
BAR_WIDTH = 50,
BAR_HEIGHT = 12,
LINE_SPACING = 4
};
/***
@ -47,136 +47,153 @@ enum
***/
QSize
TorrentDelegateMin :: sizeHint( const QStyleOptionViewItem& option, const Torrent& tor ) const
TorrentDelegateMin :: sizeHint (const QStyleOptionViewItem & option,
const Torrent & tor) const
{
const QStyle* style( QApplication::style( ) );
static const int iconSize( style->pixelMetric( QStyle :: PM_SmallIconSize ) );
const QStyle* style (QApplication::style());
static const int iconSize (style->pixelMetric (QStyle :: PM_SmallIconSize));
QFont nameFont( option.font );
const QFontMetrics nameFM( nameFont );
const bool isMagnet( !tor.hasMetadata( ) );
const QString nameStr = (isMagnet ? progressString( tor ) : tor.name( ) );
const int nameWidth = nameFM.width( nameStr );
QFont nameFont (option.font);
const QFontMetrics nameFM (nameFont);
const bool isMagnet (!tor.hasMetadata());
const QString nameStr = (isMagnet ? progressString (tor) : tor.name());
const int nameWidth = nameFM.width (nameStr);
QFont statusFont( option.font );
statusFont.setPointSize( int( option.font.pointSize( ) * 0.85 ) );
const QFontMetrics statusFM( statusFont );
const QString statusStr( shortStatusString( tor ) );
const int statusWidth = statusFM.width( statusStr );
QFont statusFont (option.font);
statusFont.setPointSize (int (option.font.pointSize() * 0.85));
const QFontMetrics statusFM (statusFont);
const QString statusStr (shortStatusString (tor));
const int statusWidth = statusFM.width (statusStr);
const QSize m( margin( *style ) );
const QSize m (margin (*style));
return QSize( m.width()*2 + iconSize + GUI_PAD + nameWidth
+ GUI_PAD + statusWidth
+ GUI_PAD + BAR_WIDTH,
m.height()*2 + std::max( nameFM.height(), (int)BAR_HEIGHT ) );
return QSize (m.width()*2 + iconSize + GUI_PAD + nameWidth
+ GUI_PAD + statusWidth
+ GUI_PAD + BAR_WIDTH,
m.height()*2 + std::max (nameFM.height(), (int)BAR_HEIGHT));
}
void
TorrentDelegateMin :: drawTorrent( QPainter * painter, const QStyleOptionViewItem& option, const Torrent& tor ) const
TorrentDelegateMin :: drawTorrent (QPainter * painter,
const QStyleOptionViewItem & option,
const Torrent & tor) const
{
const bool isPaused( tor.isPaused( ) );
const QStyle * style( QApplication::style( ) );
static const int iconSize( style->pixelMetric( QStyle :: PM_SmallIconSize ) );
const bool isPaused (tor.isPaused());
const QStyle * style (QApplication::style());
static const int iconSize (style->pixelMetric (QStyle :: PM_SmallIconSize));
QFont nameFont( option.font );
const QFontMetrics nameFM( nameFont );
const bool isMagnet( !tor.hasMetadata( ) );
const QString nameStr = (isMagnet ? progressString( tor ) : tor.name( ) );
QFont nameFont (option.font);
const QFontMetrics nameFM (nameFont);
const bool isMagnet (!tor.hasMetadata());
const QString nameStr = (isMagnet ? progressString (tor) : tor.name());
QFont statusFont( option.font );
statusFont.setPointSize( int( option.font.pointSize( ) * 0.85 ) );
const QFontMetrics statusFM( statusFont );
const QString statusStr( shortStatusString( tor ) );
const QSize statusSize( statusFM.size( 0, statusStr ) );
QFont statusFont (option.font);
statusFont.setPointSize (int (option.font.pointSize() * 0.85));
const QFontMetrics statusFM (statusFont);
const QString statusStr (shortStatusString (tor));
const QSize statusSize (statusFM.size (0, statusStr));
painter->save( );
painter->save();
if (option.state & QStyle::State_Selected) {
QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
? QPalette::Normal : QPalette::Disabled;
if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
cg = QPalette::Inactive;
if (option.state & QStyle::State_Selected)
{
QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
? QPalette::Normal : QPalette::Disabled;
if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
cg = QPalette::Inactive;
painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight));
painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight));
}
QIcon::Mode im;
if( isPaused || !(option.state & QStyle::State_Enabled ) ) im = QIcon::Disabled;
else if( option.state & QStyle::State_Selected ) im = QIcon::Selected;
else im = QIcon::Normal;
QIcon::Mode im;
if (isPaused || !(option.state & QStyle::State_Enabled))
im = QIcon::Disabled;
else if (option.state & QStyle::State_Selected)
im = QIcon::Selected;
else
im = QIcon::Normal;
QIcon::State qs;
if( isPaused ) qs = QIcon::Off;
else qs = QIcon::On;
QIcon::State qs;
if (isPaused)
qs = QIcon::Off;
else
qs = QIcon::On;
QPalette::ColorGroup cg = QPalette::Normal;
if( isPaused || !(option.state & QStyle::State_Enabled ) ) cg = QPalette::Disabled;
if( cg == QPalette::Normal && !(option.state & QStyle::State_Active ) ) cg = QPalette::Inactive;
QPalette::ColorGroup cg = QPalette::Normal;
if (isPaused || !(option.state & QStyle::State_Enabled))
cg = QPalette::Disabled;
if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
cg = QPalette::Inactive;
QPalette::ColorRole cr;
if( option.state & QStyle::State_Selected ) cr = QPalette::HighlightedText;
else cr = QPalette::Text;
QPalette::ColorRole cr;
if (option.state & QStyle::State_Selected)
cr = QPalette::HighlightedText;
else
cr = QPalette::Text;
QStyle::State progressBarState( option.state );
if( isPaused ) progressBarState = QStyle::State_None;
progressBarState |= QStyle::State_Small;
QStyle::State progressBarState (option.state);
if (isPaused)
progressBarState = QStyle::State_None;
progressBarState |= QStyle::State_Small;
// layout
const QSize m( margin( *style ) );
QRect fillArea( option.rect );
fillArea.adjust( m.width(), m.height(), -m.width(), -m.height() );
const QRect iconArea( fillArea.x( ),
fillArea.y( ) + ( fillArea.height( ) - iconSize ) / 2,
iconSize,
iconSize );
const QRect barArea( fillArea.x( ) + fillArea.width( ) - BAR_WIDTH,
fillArea.y( ) + ( fillArea.height( ) - BAR_HEIGHT ) / 2,
BAR_WIDTH,
BAR_HEIGHT );
const QRect statusArea( barArea.x( ) - GUI_PAD - statusSize.width( ),
fillArea.y( ) + ( fillArea.height( ) - statusSize.height( ) ) / 2,
fillArea.width( ),
fillArea.height( ) );
const QRect nameArea( iconArea.x( ) + iconArea.width( ) + GUI_PAD,
fillArea.y( ),
statusArea.x( ) - ( iconArea.x( ) + iconArea.width( ) + GUI_PAD * 2 ),
fillArea.height( ) );
// layout
const QSize m (margin (*style));
QRect fillArea (option.rect);
fillArea.adjust (m.width(), m.height(), -m.width(), -m.height());
const QRect iconArea (fillArea.x(),
fillArea.y() + (fillArea.height() - iconSize) / 2,
iconSize,
iconSize);
const QRect barArea (fillArea.x() + fillArea.width() - BAR_WIDTH,
fillArea.y() + (fillArea.height() - BAR_HEIGHT) / 2,
BAR_WIDTH,
BAR_HEIGHT);
const QRect statusArea (barArea.x() - GUI_PAD - statusSize.width(),
fillArea.y() + (fillArea.height() - statusSize.height()) / 2,
fillArea.width(),
fillArea.height());
const QRect nameArea (iconArea.x() + iconArea.width() + GUI_PAD,
fillArea.y(),
statusArea.x() - (iconArea.x() + iconArea.width() + GUI_PAD * 2),
fillArea.height());
// render
if( tor.hasError( ) )
painter->setPen( QColor( "red" ) );
else
painter->setPen( option.palette.color( cg, cr ) );
tor.getMimeTypeIcon().paint( painter, iconArea, Qt::AlignCenter, im, qs );
painter->setFont( nameFont );
painter->drawText( nameArea, 0, nameFM.elidedText( nameStr, Qt::ElideRight, nameArea.width( ) ) );
painter->setFont( statusFont );
painter->drawText( statusArea, 0, statusStr );
myProgressBarStyle->rect = barArea;
if ( tor.isDownloading() ) {
myProgressBarStyle->palette.setBrush( QPalette::Highlight, blueBrush );
myProgressBarStyle->palette.setColor( QPalette::Base, blueBack );
myProgressBarStyle->palette.setColor( QPalette::Window, blueBack );
// render
if (tor.hasError())
painter->setPen (QColor ("red"));
else
painter->setPen (option.palette.color (cg, cr));
tor.getMimeTypeIcon().paint (painter, iconArea, Qt::AlignCenter, im, qs);
painter->setFont (nameFont);
painter->drawText (nameArea, 0, nameFM.elidedText (nameStr, Qt::ElideRight, nameArea.width()));
painter->setFont (statusFont);
painter->drawText (statusArea, 0, statusStr);
myProgressBarStyle->rect = barArea;
if (tor.isDownloading())
{
myProgressBarStyle->palette.setBrush (QPalette::Highlight, blueBrush);
myProgressBarStyle->palette.setColor (QPalette::Base, blueBack);
myProgressBarStyle->palette.setColor (QPalette::Window, blueBack);
}
else if ( tor.isSeeding() ) {
myProgressBarStyle->palette.setBrush( QPalette::Highlight, greenBrush );
myProgressBarStyle->palette.setColor( QPalette::Base, greenBack );
myProgressBarStyle->palette.setColor( QPalette::Window, greenBack );
else if (tor.isSeeding())
{
myProgressBarStyle->palette.setBrush (QPalette::Highlight, greenBrush);
myProgressBarStyle->palette.setColor (QPalette::Base, greenBack);
myProgressBarStyle->palette.setColor (QPalette::Window, greenBack);
}
else {
myProgressBarStyle->palette.setBrush( QPalette::Highlight, silverBrush );
myProgressBarStyle->palette.setColor( QPalette::Base, silverBack );
myProgressBarStyle->palette.setColor( QPalette::Window, silverBack );
else
{
myProgressBarStyle->palette.setBrush (QPalette::Highlight, silverBrush);
myProgressBarStyle->palette.setColor (QPalette::Base, silverBack);
myProgressBarStyle->palette.setColor (QPalette::Window, silverBack);
}
myProgressBarStyle->state = progressBarState;
char buf[32];
tr_snprintf( buf, sizeof( buf ), "%d%%", (int)tr_truncd( 100.0 * tor.percentDone( ), 0 ) );
myProgressBarStyle->text = buf;
myProgressBarStyle->textVisible = true;
myProgressBarStyle->textAlignment = Qt::AlignCenter;
setProgressBarPercentDone( option, tor );
style->drawControl( QStyle::CE_ProgressBar, myProgressBarStyle, painter );
myProgressBarStyle->state = progressBarState;
char buf[32];
tr_snprintf (buf, sizeof (buf), "%d%%", (int)tr_truncd (100.0 * tor.percentDone(), 0));
myProgressBarStyle->text = buf;
myProgressBarStyle->textVisible = true;
myProgressBarStyle->textAlignment = Qt::AlignCenter;
setProgressBarPercentDone (option, tor);
style->drawControl (QStyle::CE_ProgressBar, myProgressBarStyle, painter);
painter->restore( );
painter->restore();
}

View File

@ -23,15 +23,15 @@ class Torrent;
class TorrentDelegateMin: public TorrentDelegate
{
Q_OBJECT
Q_OBJECT
protected:
virtual QSize sizeHint( const QStyleOptionViewItem&, const Torrent& ) const;
void drawTorrent( QPainter* painter, const QStyleOptionViewItem& option, const Torrent& ) const;
protected:
virtual QSize sizeHint (const QStyleOptionViewItem&, const Torrent&) const;
void drawTorrent (QPainter* painter, const QStyleOptionViewItem& option, const Torrent&) const;
public:
explicit TorrentDelegateMin( QObject * parent=0 ): TorrentDelegate(parent) { }
virtual ~TorrentDelegateMin( ) { }
public:
explicit TorrentDelegateMin (QObject * parent=0): TorrentDelegate(parent) {}
virtual ~TorrentDelegateMin () {}
};
#endif

View File

@ -29,8 +29,8 @@
enum
{
GUI_PAD = 6,
BAR_HEIGHT = 12
GUI_PAD = 6,
BAR_HEIGHT = 12
};
QColor TorrentDelegate :: greenBrush;
@ -40,26 +40,26 @@ QColor TorrentDelegate :: greenBack;
QColor TorrentDelegate :: blueBack;
QColor TorrentDelegate :: silverBack;
TorrentDelegate :: TorrentDelegate( QObject * parent ):
QStyledItemDelegate( parent ),
myProgressBarStyle( new QStyleOptionProgressBar )
TorrentDelegate :: TorrentDelegate (QObject * parent):
QStyledItemDelegate (parent),
myProgressBarStyle (new QStyleOptionProgressBar)
{
myProgressBarStyle->minimum = 0;
myProgressBarStyle->maximum = 1000;
myProgressBarStyle->minimum = 0;
myProgressBarStyle->maximum = 1000;
greenBrush = QColor("forestgreen");
greenBack = QColor("darkseagreen");
greenBrush = QColor ("forestgreen");
greenBack = QColor ("darkseagreen");
blueBrush = QColor("steelblue");
blueBack = QColor("lightgrey");
blueBrush = QColor ("steelblue");
blueBack = QColor ("lightgrey");
silverBrush = QColor("silver");
silverBack = QColor("grey");
silverBrush = QColor ("silver");
silverBack = QColor ("grey");
}
TorrentDelegate :: ~TorrentDelegate( )
TorrentDelegate :: ~TorrentDelegate ()
{
delete myProgressBarStyle;
delete myProgressBarStyle;
}
/***
@ -67,56 +67,57 @@ TorrentDelegate :: ~TorrentDelegate( )
***/
QSize
TorrentDelegate :: margin( const QStyle& style ) const
TorrentDelegate :: margin (const QStyle& style) const
{
Q_UNUSED( style );
Q_UNUSED (style);
return QSize( 4, 4 );
return QSize (4, 4);
}
QString
TorrentDelegate :: progressString( const Torrent& tor ) const
TorrentDelegate :: progressString (const Torrent& tor) const
{
const bool isMagnet( !tor.hasMetadata( ) );
const bool isDone( tor.isDone( ) );
const bool isSeed( tor.isSeed( ) );
const uint64_t haveTotal( tor.haveTotal( ) );
QString str;
double seedRatio;
const bool hasSeedRatio( tor.getSeedRatio( seedRatio ) );
const bool isMagnet (!tor.hasMetadata());
const bool isDone (tor.isDone ());
const bool isSeed (tor.isSeed ());
const uint64_t haveTotal (tor.haveTotal());
QString str;
double seedRatio;
const bool hasSeedRatio (tor.getSeedRatio (seedRatio));
if( isMagnet ) // magnet link with no metadata
if (isMagnet) // magnet link with no metadata
{
/* %1 is the percentage of torrent metadata downloaded */
str = tr( "Magnetized transfer - retrieving metadata (%1%)" )
.arg( Formatter::percentToString( tor.metadataPercentDone() * 100.0 ) );
// %1 is the percentage of torrent metadata downloaded
str = tr ("Magnetized transfer - retrieving metadata (%1%)")
.arg (Formatter::percentToString (tor.metadataPercentDone() * 100.0));
}
else if( !isDone ) // downloading
else if (!isDone) // downloading
{
/* %1 is how much we've got,
%2 is how much we'll have when done,
%3 is a percentage of the two */
str = tr( "%1 of %2 (%3%)" ).arg( Formatter::sizeToString( haveTotal ) )
.arg( Formatter::sizeToString( tor.sizeWhenDone( ) ) )
.arg( Formatter::percentToString( tor.percentDone( ) * 100.0 ) );
/* %1 is how much we've got,
%2 is how much we'll have when done,
%3 is a percentage of the two */
str = tr ("%1 of %2 (%3%)")
.arg (Formatter::sizeToString (haveTotal))
.arg (Formatter::sizeToString (tor.sizeWhenDone()))
.arg (Formatter::percentToString (tor.percentDone() * 100.0));
}
else if( !isSeed ) // partial seed
else if (!isSeed) // partial seed
{
if( hasSeedRatio )
if (hasSeedRatio)
{
/* %1 is how much we've got,
%2 is the torrent's total size,
%3 is a percentage of the two,
%4 is how much we've uploaded,
%5 is our upload-to-download ratio
%6 is the ratio we want to reach before we stop uploading */
str = tr( "%1 of %2 (%3%), uploaded %4 (Ratio: %5 Goal: %6)" )
.arg( Formatter::sizeToString( haveTotal ) )
.arg( Formatter::sizeToString( tor.totalSize( ) ) )
.arg( Formatter::percentToString( tor.percentComplete( ) * 100.0 ) )
.arg( Formatter::sizeToString( tor.uploadedEver( ) ) )
.arg( Formatter::ratioToString( tor.ratio( ) ) )
.arg( Formatter::ratioToString( seedRatio ) );
/* %1 is how much we've got,
%2 is the torrent's total size,
%3 is a percentage of the two,
%4 is how much we've uploaded,
%5 is our upload-to-download ratio
%6 is the ratio we want to reach before we stop uploading */
str = tr ("%1 of %2 (%3%), uploaded %4 (Ratio: %5 Goal: %6)")
.arg (Formatter::sizeToString (haveTotal))
.arg (Formatter::sizeToString (tor.totalSize()))
.arg (Formatter::percentToString (tor.percentComplete() * 100.0))
.arg (Formatter::sizeToString (tor.uploadedEver()))
.arg (Formatter::ratioToString (tor.ratio()))
.arg (Formatter::ratioToString (seedRatio));
}
else
{
@ -125,48 +126,48 @@ TorrentDelegate :: progressString( const Torrent& tor ) const
%3 is a percentage of the two,
%4 is how much we've uploaded,
%5 is our upload-to-download ratio */
str = tr( "%1 of %2 (%3%), uploaded %4 (Ratio: %5)" )
.arg( Formatter::sizeToString( haveTotal ) )
.arg( Formatter::sizeToString( tor.totalSize( ) ) )
.arg( Formatter::percentToString( tor.percentComplete( ) * 100.0 ) )
.arg( Formatter::sizeToString( tor.uploadedEver( ) ) )
.arg( Formatter::ratioToString( tor.ratio( ) ) );
str = tr ("%1 of %2 (%3%), uploaded %4 (Ratio: %5)")
.arg (Formatter::sizeToString (haveTotal))
.arg (Formatter::sizeToString (tor.totalSize()))
.arg (Formatter::percentToString (tor.percentComplete() * 100.0))
.arg (Formatter::sizeToString (tor.uploadedEver()))
.arg (Formatter::ratioToString (tor.ratio()));
}
}
else // seeding
else // seeding
{
if( hasSeedRatio )
if (hasSeedRatio)
{
/* %1 is the torrent's total size,
%2 is how much we've uploaded,
%3 is our upload-to-download ratio,
%4 is the ratio we want to reach before we stop uploading */
str = tr( "%1, uploaded %2 (Ratio: %3 Goal: %4)" )
.arg( Formatter::sizeToString( haveTotal ) )
.arg( Formatter::sizeToString( tor.uploadedEver( ) ) )
.arg( Formatter::ratioToString( tor.ratio( ) ) )
.arg( Formatter::ratioToString( seedRatio ) );
/* %1 is the torrent's total size,
%2 is how much we've uploaded,
%3 is our upload-to-download ratio,
%4 is the ratio we want to reach before we stop uploading */
str = tr ("%1, uploaded %2 (Ratio: %3 Goal: %4)")
.arg (Formatter::sizeToString (haveTotal))
.arg (Formatter::sizeToString (tor.uploadedEver()))
.arg (Formatter::ratioToString (tor.ratio()))
.arg (Formatter::ratioToString (seedRatio));
}
else /* seeding w/o a ratio */
else // seeding w/o a ratio
{
/* %1 is the torrent's total size,
%2 is how much we've uploaded,
%3 is our upload-to-download ratio */
str = tr( "%1, uploaded %2 (Ratio: %3)" )
.arg( Formatter::sizeToString( haveTotal ) )
.arg( Formatter::sizeToString( tor.uploadedEver( ) ) )
.arg( Formatter::ratioToString( tor.ratio( ) ) );
/* %1 is the torrent's total size,
%2 is how much we've uploaded,
%3 is our upload-to-download ratio */
str = tr ("%1, uploaded %2 (Ratio: %3)")
.arg (Formatter::sizeToString (haveTotal))
.arg (Formatter::sizeToString (tor.uploadedEver()))
.arg (Formatter::ratioToString (tor.ratio()));
}
}
/* add time when downloading */
if( ( hasSeedRatio && tor.isSeeding( ) ) || tor.isDownloading( ) )
// add time when downloading
if ((hasSeedRatio && tor.isSeeding()) || tor.isDownloading())
{
str += tr( " - " );
if( tor.hasETA( ) )
str += tr( "%1 left" ).arg( Formatter::timeToString( tor.getETA( ) ) );
else
str += tr( "Remaining time unknown" );
str += tr (" - ");
if (tor.hasETA ())
str += tr ("%1 left").arg (Formatter::timeToString (tor.getETA ()));
else
str += tr ("Remaining time unknown");
}
return str;
@ -181,8 +182,9 @@ TorrentDelegate :: shortTransferString (const Torrent& tor) const
const bool haveUp (haveMeta && tor.peersWeAreUploadingTo()>0);
if (haveDown)
str = tr( "%1 %2" ).arg(Formatter::downloadSpeedToString(tor.downloadSpeed()))
.arg(Formatter::uploadSpeedToString(tor.uploadSpeed()));
str = tr ("%1 %2")
.arg(Formatter::downloadSpeedToString(tor.downloadSpeed()))
.arg(Formatter::uploadSpeedToString(tor.uploadSpeed()));
else if (haveUp)
str = Formatter::uploadSpeedToString(tor.uploadSpeed());
@ -191,81 +193,87 @@ TorrentDelegate :: shortTransferString (const Torrent& tor) const
}
QString
TorrentDelegate :: shortStatusString( const Torrent& tor ) const
TorrentDelegate :: shortStatusString (const Torrent& tor) const
{
QString str;
static const QChar ratioSymbol (0x262F);
QString str;
static const QChar ratioSymbol (0x262F);
switch( tor.getActivity( ) )
switch (tor.getActivity ())
{
case TR_STATUS_CHECK:
str = tr( "Verifying local data (%1% tested)" ).arg( Formatter::percentToString( tor.getVerifyProgress()*100.0 ) );
break;
case TR_STATUS_CHECK:
str = tr ("Verifying local data (%1% tested)").arg (Formatter::percentToString (tor.getVerifyProgress()*100.0));
break;
case TR_STATUS_DOWNLOAD:
case TR_STATUS_SEED:
str = tr("%1 %2 %3").arg(shortTransferString(tor))
.arg(tr("Ratio:"))
.arg(Formatter::ratioToString(tor.ratio()));
break;
case TR_STATUS_DOWNLOAD:
case TR_STATUS_SEED:
str = tr("%1 %2 %3")
.arg(shortTransferString(tor))
.arg(tr("Ratio:"))
.arg(Formatter::ratioToString(tor.ratio()));
break;
default:
str = tor.activityString( );
break;
default:
str = tor.activityString ();
break;
}
return str;
return str;
}
QString
TorrentDelegate :: statusString( const Torrent& tor ) const
TorrentDelegate :: statusString (const Torrent& tor) const
{
QString str;
QString str;
if( tor.hasError( ) )
if (tor.hasError ())
{
str = tor.getError( );
str = tor.getError ();
}
else switch( tor.getActivity( ) )
else switch (tor.getActivity ())
{
case TR_STATUS_STOPPED:
case TR_STATUS_CHECK_WAIT:
case TR_STATUS_CHECK:
case TR_STATUS_DOWNLOAD_WAIT:
case TR_STATUS_SEED_WAIT:
str = shortStatusString( tor );
break;
case TR_STATUS_STOPPED:
case TR_STATUS_CHECK_WAIT:
case TR_STATUS_CHECK:
case TR_STATUS_DOWNLOAD_WAIT:
case TR_STATUS_SEED_WAIT:
str = shortStatusString (tor);
break;
case TR_STATUS_DOWNLOAD:
if( !tor.hasMetadata() ) {
str = tr( "Downloading metadata from %n peer(s) (%1% done)", 0, tor.peersWeAreDownloadingFrom( ) )
.arg( Formatter::percentToString( 100.0 * tor.metadataPercentDone( ) ) );
} else {
/* it would be nicer for translation if this was all one string, but I don't see how to do multiple %n's in tr() */
str = tr( "Downloading from %1 of %n connected peer(s)", 0, tor.connectedPeersAndWebseeds( ) )
.arg( tor.peersWeAreDownloadingFrom( ) );
if (tor.webseedsWeAreDownloadingFrom())
str += tr(" and %n web seed(s)", "", tor.webseedsWeAreDownloadingFrom());
}
break;
case TR_STATUS_DOWNLOAD:
if (!tor.hasMetadata())
{
str = tr ("Downloading metadata from %n peer(s) (%1% done)", 0, tor.peersWeAreDownloadingFrom ())
.arg (Formatter::percentToString (100.0 * tor.metadataPercentDone ()));
}
else
{
/* it would be nicer for translation if this was all one string, but I don't see how to do multiple %n's in tr() */
str = tr ("Downloading from %1 of %n connected peer(s)", 0, tor.connectedPeersAndWebseeds ())
.arg (tor.peersWeAreDownloadingFrom ());
case TR_STATUS_SEED:
str = tr( "Seeding to %1 of %n connected peer(s)", 0, tor.connectedPeers( ) )
.arg( tor.peersWeAreUploadingTo( ) );
break;
if (tor.webseedsWeAreDownloadingFrom())
str += tr(" and %n web seed(s)", "", tor.webseedsWeAreDownloadingFrom());
}
break;
default:
str = tr( "Error" );
break;
case TR_STATUS_SEED:
str = tr ("Seeding to %1 of %n connected peer(s)", 0, tor.connectedPeers ())
.arg (tor.peersWeAreUploadingTo ());
break;
default:
str = tr ("Error");
break;
}
if( tor.isReadyToTransfer( ) ) {
QString s = shortTransferString( tor );
if( !s.isEmpty( ) )
str += tr( " - " ) + s;
if (tor.isReadyToTransfer ())
{
QString s = shortTransferString (tor);
if (!s.isEmpty ())
str += tr (" - ") + s;
}
return str;
return str;
}
/***
@ -274,176 +282,193 @@ TorrentDelegate :: statusString( const Torrent& tor ) const
namespace
{
int MAX3( int a, int b, int c )
int MAX3 (int a, int b, int c)
{
const int ab( a > b ? a : b );
return ab > c ? ab : c;
const int ab (a > b ? a : b);
return ab > c ? ab : c;
}
}
QSize
TorrentDelegate :: sizeHint( const QStyleOptionViewItem& option, const Torrent& tor ) const
TorrentDelegate :: sizeHint (const QStyleOptionViewItem& option, const Torrent& tor) const
{
const QStyle* style( QApplication::style( ) );
static const int iconSize( style->pixelMetric( QStyle::PM_MessageBoxIconSize ) );
const QStyle* style (QApplication::style ());
static const int iconSize (style->pixelMetric (QStyle::PM_MessageBoxIconSize));
QFont nameFont( option.font );
nameFont.setWeight( QFont::Bold );
const QFontMetrics nameFM( nameFont );
const QString nameStr( tor.name( ) );
const int nameWidth = nameFM.width( nameStr );
QFont statusFont( option.font );
statusFont.setPointSize( int( option.font.pointSize( ) * 0.9 ) );
const QFontMetrics statusFM( statusFont );
const QString statusStr( statusString( tor ) );
const int statusWidth = statusFM.width( statusStr );
QFont progressFont( statusFont );
const QFontMetrics progressFM( progressFont );
const QString progressStr( progressString( tor ) );
const int progressWidth = progressFM.width( progressStr );
const QSize m( margin( *style ) );
return QSize( m.width()*2 + iconSize + GUI_PAD + MAX3( nameWidth, statusWidth, progressWidth ),
//m.height()*3 + nameFM.lineSpacing() + statusFM.lineSpacing()*2 + progressFM.lineSpacing() );
m.height()*3 + nameFM.lineSpacing() + statusFM.lineSpacing() + BAR_HEIGHT + progressFM.lineSpacing() );
QFont nameFont (option.font);
nameFont.setWeight (QFont::Bold);
const QFontMetrics nameFM (nameFont);
const QString nameStr (tor.name ());
const int nameWidth = nameFM.width (nameStr);
QFont statusFont (option.font);
statusFont.setPointSize (int (option.font.pointSize () * 0.9));
const QFontMetrics statusFM (statusFont);
const QString statusStr (statusString (tor));
const int statusWidth = statusFM.width (statusStr);
QFont progressFont (statusFont);
const QFontMetrics progressFM (progressFont);
const QString progressStr (progressString (tor));
const int progressWidth = progressFM.width (progressStr);
const QSize m (margin (*style));
return QSize (m.width()*2 + iconSize + GUI_PAD + MAX3 (nameWidth, statusWidth, progressWidth),
//m.height()*3 + nameFM.lineSpacing() + statusFM.lineSpacing()*2 + progressFM.lineSpacing());
m.height()*3 + nameFM.lineSpacing() + statusFM.lineSpacing() + BAR_HEIGHT + progressFM.lineSpacing());
}
QSize
TorrentDelegate :: sizeHint( const QStyleOptionViewItem & option,
const QModelIndex & index ) const
TorrentDelegate :: sizeHint (const QStyleOptionViewItem & option,
const QModelIndex & index) const
{
const Torrent * tor( index.data( TorrentModel::TorrentRole ).value<const Torrent*>() );
return sizeHint( option, *tor );
const Torrent * tor (index.data (TorrentModel::TorrentRole).value<const Torrent*>());
return sizeHint (option, *tor);
}
void
TorrentDelegate :: paint( QPainter * painter,
TorrentDelegate :: paint (QPainter * painter,
const QStyleOptionViewItem & option,
const QModelIndex & index) const
{
const Torrent * tor( index.data( TorrentModel::TorrentRole ).value<const Torrent*>() );
painter->save( );
painter->setClipRect( option.rect );
drawTorrent( painter, option, *tor );
painter->restore( );
const Torrent * tor (index.data (TorrentModel::TorrentRole).value<const Torrent*>());
painter->save ();
painter->setClipRect (option.rect);
drawTorrent (painter, option, *tor);
painter->restore ();
}
void
TorrentDelegate :: setProgressBarPercentDone( const QStyleOptionViewItem& option, const Torrent& tor ) const
TorrentDelegate :: setProgressBarPercentDone (const QStyleOptionViewItem & option,
const Torrent & tor) const
{
double seedRatioLimit;
if (tor.isSeeding() && tor.getSeedRatio(seedRatioLimit))
double seedRatioLimit;
if (tor.isSeeding() && tor.getSeedRatio(seedRatioLimit))
{
const double seedRateRatio = tor.ratio() / seedRatioLimit;
const int scaledProgress = seedRateRatio * (myProgressBarStyle->maximum - myProgressBarStyle->minimum);
myProgressBarStyle->progress = myProgressBarStyle->minimum + scaledProgress;
const double seedRateRatio = tor.ratio() / seedRatioLimit;
const int scaledProgress = seedRateRatio * (myProgressBarStyle->maximum - myProgressBarStyle->minimum);
myProgressBarStyle->progress = myProgressBarStyle->minimum + scaledProgress;
}
else
else
{
const bool isMagnet( !tor.hasMetadata( ) );
myProgressBarStyle->direction = option.direction;
myProgressBarStyle->progress = int(myProgressBarStyle->minimum + (((isMagnet ? tor.metadataPercentDone() : tor.percentDone()) * (myProgressBarStyle->maximum - myProgressBarStyle->minimum))));
const bool isMagnet (!tor.hasMetadata ());
myProgressBarStyle->direction = option.direction;
myProgressBarStyle->progress = int(myProgressBarStyle->minimum + (((isMagnet ? tor.metadataPercentDone() : tor.percentDone()) * (myProgressBarStyle->maximum - myProgressBarStyle->minimum))));
}
}
void
TorrentDelegate :: drawTorrent( QPainter * painter, const QStyleOptionViewItem& option, const Torrent& tor ) const
TorrentDelegate :: drawTorrent (QPainter * painter,
const QStyleOptionViewItem & option,
const Torrent & tor) const
{
const QStyle * style( QApplication::style( ) );
static const int iconSize( style->pixelMetric( QStyle::PM_LargeIconSize ) );
QFont nameFont( option.font );
nameFont.setWeight( QFont::Bold );
const QFontMetrics nameFM( nameFont );
const QString nameStr( tor.name( ) );
const QSize nameSize( nameFM.size( 0, nameStr ) );
QFont statusFont( option.font );
statusFont.setPointSize( int( option.font.pointSize( ) * 0.9 ) );
const QFontMetrics statusFM( statusFont );
const QString statusStr( progressString( tor ) );
QFont progressFont( statusFont );
const QFontMetrics progressFM( progressFont );
const QString progressStr( statusString( tor ) );
const bool isPaused( tor.isPaused( ) );
const QStyle * style (QApplication::style ());
static const int iconSize (style->pixelMetric (QStyle::PM_LargeIconSize));
QFont nameFont (option.font);
nameFont.setWeight (QFont::Bold);
const QFontMetrics nameFM (nameFont);
const QString nameStr (tor.name ());
const QSize nameSize (nameFM.size (0, nameStr));
QFont statusFont (option.font);
statusFont.setPointSize (int (option.font.pointSize () * 0.9));
const QFontMetrics statusFM (statusFont);
const QString statusStr (progressString (tor));
QFont progressFont (statusFont);
const QFontMetrics progressFM (progressFont);
const QString progressStr (statusString (tor));
const bool isPaused (tor.isPaused ());
painter->save( );
painter->save ();
if (option.state & QStyle::State_Selected) {
QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
? QPalette::Normal : QPalette::Disabled;
if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
cg = QPalette::Inactive;
if (option.state & QStyle::State_Selected)
{
QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
? QPalette::Normal : QPalette::Disabled;
if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
cg = QPalette::Inactive;
painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight));
painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight));
}
QIcon::Mode im;
if( isPaused || !(option.state & QStyle::State_Enabled ) ) im = QIcon::Disabled;
else if( option.state & QStyle::State_Selected ) im = QIcon::Selected;
else im = QIcon::Normal;
QIcon::Mode im;
if (isPaused || !(option.state & QStyle::State_Enabled))
im = QIcon::Disabled;
else if (option.state & QStyle::State_Selected)
im = QIcon::Selected;
else
im = QIcon::Normal;
QIcon::State qs;
if( isPaused ) qs = QIcon::Off;
else qs = QIcon::On;
QIcon::State qs;
if (isPaused)
qs = QIcon::Off;
else
qs = QIcon::On;
QPalette::ColorGroup cg = QPalette::Normal;
if( isPaused || !(option.state & QStyle::State_Enabled ) ) cg = QPalette::Disabled;
if( cg == QPalette::Normal && !(option.state & QStyle::State_Active ) ) cg = QPalette::Inactive;
QPalette::ColorGroup cg = QPalette::Normal;
if (isPaused || !(option.state & QStyle::State_Enabled))
cg = QPalette::Disabled;
if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
cg = QPalette::Inactive;
QPalette::ColorRole cr;
if( option.state & QStyle::State_Selected ) cr = QPalette::HighlightedText;
else cr = QPalette::Text;
QPalette::ColorRole cr;
if (option.state & QStyle::State_Selected)
cr = QPalette::HighlightedText;
else
cr = QPalette::Text;
QStyle::State progressBarState( option.state );
if( isPaused ) progressBarState = QStyle::State_None;
progressBarState |= QStyle::State_Small;
QStyle::State progressBarState (option.state);
if (isPaused)
progressBarState = QStyle::State_None;
progressBarState |= QStyle::State_Small;
// layout
const QSize m( margin( *style ) );
QRect fillArea( option.rect );
fillArea.adjust( m.width(), m.height(), -m.width(), -m.height() );
QRect iconArea( fillArea.x( ), fillArea.y( ) + ( fillArea.height( ) - iconSize ) / 2, iconSize, iconSize );
QRect nameArea( iconArea.x( ) + iconArea.width( ) + GUI_PAD, fillArea.y( ),
fillArea.width( ) - GUI_PAD - iconArea.width( ), nameSize.height( ) );
QRect statusArea( nameArea );
statusArea.moveTop( nameArea.y( ) + nameFM.lineSpacing( ) );
statusArea.setHeight( nameSize.height( ) );
QRect barArea( statusArea );
barArea.setHeight( BAR_HEIGHT );
barArea.moveTop( statusArea.y( ) + statusFM.lineSpacing( ) );
QRect progArea( statusArea );
progArea.moveTop( barArea.y( ) + barArea.height( ) );
// layout
const QSize m (margin (*style));
QRect fillArea (option.rect);
fillArea.adjust (m.width(), m.height(), -m.width(), -m.height());
QRect iconArea (fillArea.x (), fillArea.y () + (fillArea.height () - iconSize) / 2, iconSize, iconSize);
QRect nameArea (iconArea.x () + iconArea.width () + GUI_PAD, fillArea.y (),
fillArea.width () - GUI_PAD - iconArea.width (), nameSize.height ());
QRect statusArea (nameArea);
statusArea.moveTop (nameArea.y () + nameFM.lineSpacing ());
statusArea.setHeight (nameSize.height ());
QRect barArea (statusArea);
barArea.setHeight (BAR_HEIGHT);
barArea.moveTop (statusArea.y () + statusFM.lineSpacing ());
QRect progArea (statusArea);
progArea.moveTop (barArea.y () + barArea.height ());
// render
if( tor.hasError( ) )
painter->setPen( QColor( "red" ) );
else
painter->setPen( option.palette.color( cg, cr ) );
tor.getMimeTypeIcon().paint( painter, iconArea, Qt::AlignCenter, im, qs );
painter->setFont( nameFont );
painter->drawText( nameArea, 0, nameFM.elidedText( nameStr, Qt::ElideRight, nameArea.width( ) ) );
painter->setFont( statusFont );
painter->drawText( statusArea, 0, statusFM.elidedText( statusStr, Qt::ElideRight, statusArea.width( ) ) );
painter->setFont( progressFont );
painter->drawText( progArea, 0, progressFM.elidedText( progressStr, Qt::ElideRight, progArea.width( ) ) );
myProgressBarStyle->rect = barArea;
if ( tor.isDownloading() ) {
myProgressBarStyle->palette.setBrush( QPalette::Highlight, blueBrush );
myProgressBarStyle->palette.setColor( QPalette::Base, blueBack );
myProgressBarStyle->palette.setColor( QPalette::Window, blueBack );
// render
if (tor.hasError ())
painter->setPen (QColor ("red"));
else
painter->setPen (option.palette.color (cg, cr));
tor.getMimeTypeIcon().paint (painter, iconArea, Qt::AlignCenter, im, qs);
painter->setFont (nameFont);
painter->drawText (nameArea, 0, nameFM.elidedText (nameStr, Qt::ElideRight, nameArea.width ()));
painter->setFont (statusFont);
painter->drawText (statusArea, 0, statusFM.elidedText (statusStr, Qt::ElideRight, statusArea.width ()));
painter->setFont (progressFont);
painter->drawText (progArea, 0, progressFM.elidedText (progressStr, Qt::ElideRight, progArea.width ()));
myProgressBarStyle->rect = barArea;
if (tor.isDownloading())
{
myProgressBarStyle->palette.setBrush (QPalette::Highlight, blueBrush);
myProgressBarStyle->palette.setColor (QPalette::Base, blueBack);
myProgressBarStyle->palette.setColor (QPalette::Window, blueBack);
}
else if ( tor.isSeeding() ) {
myProgressBarStyle->palette.setBrush( QPalette::Highlight, greenBrush );
myProgressBarStyle->palette.setColor( QPalette::Base, greenBack );
myProgressBarStyle->palette.setColor( QPalette::Window, greenBack );
else if (tor.isSeeding())
{
myProgressBarStyle->palette.setBrush (QPalette::Highlight, greenBrush);
myProgressBarStyle->palette.setColor (QPalette::Base, greenBack);
myProgressBarStyle->palette.setColor (QPalette::Window, greenBack);
}
else {
myProgressBarStyle->palette.setBrush( QPalette::Highlight, silverBrush );
myProgressBarStyle->palette.setColor( QPalette::Base, silverBack );
myProgressBarStyle->palette.setColor( QPalette::Window, silverBack );
else
{
myProgressBarStyle->palette.setBrush (QPalette::Highlight, silverBrush);
myProgressBarStyle->palette.setColor (QPalette::Base, silverBack);
myProgressBarStyle->palette.setColor (QPalette::Window, silverBack);
}
myProgressBarStyle->state = progressBarState;
setProgressBarPercentDone( option, tor );
myProgressBarStyle->state = progressBarState;
setProgressBarPercentDone (option, tor);
style->drawControl( QStyle::CE_ProgressBar, myProgressBarStyle, painter );
style->drawControl (QStyle::CE_ProgressBar, myProgressBarStyle, painter);
painter->restore( );
painter->restore ();
}

View File

@ -24,34 +24,33 @@ class Torrent;
class TorrentDelegate: public QStyledItemDelegate
{
Q_OBJECT
Q_OBJECT
public:
static QColor blueBrush, greenBrush, silverBrush;
static QColor blueBack, greenBack, silverBack;
public:
static QColor blueBrush, greenBrush, silverBrush;
static QColor blueBack, greenBack, silverBack;
protected:
QStyleOptionProgressBar * myProgressBarStyle;
protected:
QStyleOptionProgressBar * myProgressBarStyle;
protected:
QString statusString( const Torrent& tor ) const;
QString progressString( const Torrent& tor ) const;
QString shortStatusString( const Torrent& tor ) const;
QString shortTransferString( const Torrent& tor ) const;
protected:
QString statusString (const Torrent& tor) const;
QString progressString (const Torrent& tor) const;
QString shortStatusString (const Torrent& tor) const;
QString shortTransferString (const Torrent& tor) const;
protected:
QSize margin( const QStyle& style ) const;
virtual QSize sizeHint( const QStyleOptionViewItem&, const Torrent& ) const;
virtual void setProgressBarPercentDone( const QStyleOptionViewItem& option, const Torrent& ) const;
virtual void drawTorrent( QPainter* painter, const QStyleOptionViewItem& option, const Torrent& ) const;
protected:
QSize margin (const QStyle& style) const;
virtual QSize sizeHint (const QStyleOptionViewItem&, const Torrent&) const;
virtual void setProgressBarPercentDone (const QStyleOptionViewItem& option, const Torrent&) const;
virtual void drawTorrent (QPainter* painter, const QStyleOptionViewItem& option, const Torrent&) const;
public:
explicit TorrentDelegate( QObject * parent=0 );
virtual ~TorrentDelegate( );
QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
public:
explicit TorrentDelegate (QObject * parent=0);
virtual ~TorrentDelegate ();
QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
};
#endif

View File

@ -21,45 +21,45 @@
#include "torrent-model.h"
#include "utils.h"
TorrentFilter :: TorrentFilter( Prefs& prefs ):
myPrefs( prefs )
TorrentFilter :: TorrentFilter (Prefs& prefs):
myPrefs (prefs)
{
// listen for changes to the preferences to know when to refilter / resort
connect( &myPrefs, SIGNAL(changed(int)), this, SLOT(refreshPref(int)));
// listen for changes to the preferences to know when to refilter / resort
connect (&myPrefs, SIGNAL(changed(int)), this, SLOT(refreshPref(int)));
setDynamicSortFilter( true );
setDynamicSortFilter (true);
// initialize our state from the current prefs
QList<int> initKeys;
initKeys << Prefs :: SORT_MODE
<< Prefs :: FILTER_MODE
<< Prefs :: FILTER_TRACKERS
<< Prefs :: FILTER_TEXT;
foreach( int key, initKeys )
refreshPref( key );
// initialize our state from the current prefs
QList<int> initKeys;
initKeys << Prefs :: SORT_MODE
<< Prefs :: FILTER_MODE
<< Prefs :: FILTER_TRACKERS
<< Prefs :: FILTER_TEXT;
foreach (int key, initKeys)
refreshPref (key);
}
TorrentFilter :: ~TorrentFilter( )
TorrentFilter :: ~TorrentFilter ()
{
}
void
TorrentFilter :: refreshPref( int key )
TorrentFilter :: refreshPref (int key)
{
switch( key )
switch (key)
{
case Prefs :: FILTER_TEXT:
case Prefs :: FILTER_MODE:
case Prefs :: FILTER_TRACKERS:
invalidateFilter( );
/* force a re-sort */
sort( 0, !myPrefs.getBool(Prefs::SORT_REVERSED) ? Qt::AscendingOrder : Qt::DescendingOrder );
case Prefs :: FILTER_TEXT:
case Prefs :: FILTER_MODE:
case Prefs :: FILTER_TRACKERS:
invalidateFilter ();
/* force a re-sort */
sort (0, !myPrefs.getBool(Prefs::SORT_REVERSED) ? Qt::AscendingOrder : Qt::DescendingOrder);
case Prefs :: SORT_MODE:
case Prefs :: SORT_REVERSED:
sort( 0, myPrefs.getBool(Prefs::SORT_REVERSED) ? Qt::AscendingOrder : Qt::DescendingOrder );
invalidate( );
break;
case Prefs :: SORT_MODE:
case Prefs :: SORT_REVERSED:
sort (0, myPrefs.getBool(Prefs::SORT_REVERSED) ? Qt::AscendingOrder : Qt::DescendingOrder);
invalidate ();
break;
}
}
@ -69,64 +69,94 @@ TorrentFilter :: refreshPref( int key )
namespace
{
template <typename T> int compare( const T a, const T b )
template <typename T> int compare (const T a, const T b)
{
if( a < b ) return -1;
if( b < a ) return 1;
return 0;
if (a < b)
return -1;
if (b < a)
return 1;
return 0;
}
}
bool
TorrentFilter :: lessThan( const QModelIndex& left, const QModelIndex& right ) const
TorrentFilter :: lessThan (const QModelIndex& left, const QModelIndex& right) const
{
int val = 0;
const Torrent * a = sourceModel()->data( left, TorrentModel::TorrentRole ).value<const Torrent*>();
const Torrent * b = sourceModel()->data( right, TorrentModel::TorrentRole ).value<const Torrent*>();
int val = 0;
const Torrent * a = sourceModel()->data (left, TorrentModel::TorrentRole).value<const Torrent*>();
const Torrent * b = sourceModel()->data (right, TorrentModel::TorrentRole).value<const Torrent*>();
switch( myPrefs.get<SortMode>(Prefs::SORT_MODE).mode() )
switch (myPrefs.get<SortMode>(Prefs::SORT_MODE).mode())
{
case SortMode :: SORT_BY_QUEUE:
if( !val ) val = -compare( a->queuePosition(), b->queuePosition() );
break;
case SortMode :: SORT_BY_SIZE:
if( !val ) val = compare( a->sizeWhenDone(), b->sizeWhenDone() );
break;
case SortMode :: SORT_BY_AGE:
val = compare( a->dateAdded().toTime_t(), b->dateAdded().toTime_t() );
break;
case SortMode :: SORT_BY_ID:
if( !val ) val = compare( a->id(), b->id() );
break;
case SortMode :: SORT_BY_ACTIVITY:
if( !val ) val = compare( a->downloadSpeed() + a->uploadSpeed(), b->downloadSpeed() + b->uploadSpeed() );
if( !val ) val = compare( a->peersWeAreUploadingTo() + a->webseedsWeAreDownloadingFrom(),
b->peersWeAreUploadingTo() + b->webseedsWeAreDownloadingFrom());
// fall through
case SortMode :: SORT_BY_STATE:
if( !val ) val = -compare( a->isPaused(), b->isPaused() );
if( !val ) val = compare( a->getActivity(), b->getActivity() );
if( !val ) val = -compare( a->queuePosition(), b->queuePosition() );
if( !val ) val = compare( a->hasError(), b->hasError() );
// fall through
case SortMode :: SORT_BY_PROGRESS:
if( !val ) val = compare( a->percentComplete(), b->percentComplete() );
if( !val ) val = a->compareSeedRatio( *b );
if( !val ) val = -compare( a->queuePosition(), b->queuePosition() );
case SortMode :: SORT_BY_RATIO:
if( !val ) val = a->compareRatio( *b );
break;
case SortMode :: SORT_BY_ETA:
if( !val ) val = a->compareETA( *b );
break;
default:
break;
case SortMode :: SORT_BY_QUEUE:
if (!val)
val = -compare (a->queuePosition(), b->queuePosition());
break;
case SortMode :: SORT_BY_SIZE:
if (!val)
val = compare (a->sizeWhenDone(), b->sizeWhenDone());
break;
case SortMode :: SORT_BY_AGE:
val = compare (a->dateAdded().toTime_t(), b->dateAdded().toTime_t());
break;
case SortMode :: SORT_BY_ID:
if (!val)
val = compare (a->id(), b->id());
break;
case SortMode :: SORT_BY_ACTIVITY:
if (!val)
val = compare (a->downloadSpeed() + a->uploadSpeed(), b->downloadSpeed() + b->uploadSpeed());
if (!val)
val = compare (a->peersWeAreUploadingTo() + a->webseedsWeAreDownloadingFrom(),
b->peersWeAreUploadingTo() + b->webseedsWeAreDownloadingFrom());
// fall through
case SortMode :: SORT_BY_STATE:
if (!val)
val = -compare (a->isPaused(), b->isPaused());
if (!val)
val = compare (a->getActivity(), b->getActivity());
if (!val)
val = -compare (a->queuePosition(), b->queuePosition());
if (!val)
val = compare (a->hasError(), b->hasError());
// fall through
case SortMode :: SORT_BY_PROGRESS:
if (!val)
val = compare (a->percentComplete(), b->percentComplete());
if (!val)
val = a->compareSeedRatio (*b);
if (!val)
val = -compare (a->queuePosition(), b->queuePosition());
case SortMode :: SORT_BY_RATIO:
if (!val)
val = a->compareRatio (*b);
break;
case SortMode :: SORT_BY_ETA:
if (!val)
val = a->compareETA (*b);
break;
default:
break;
}
if( val == 0 )
val = -a->name().compare( b->name(), Qt::CaseInsensitive );
if( val == 0 )
val = compare( a->hashString(), b->hashString() );
return val < 0;
if (val == 0)
val = -a->name().compare (b->name(), Qt::CaseInsensitive);
if (val == 0)
val = compare (a->hashString(), b->hashString());
return val < 0;
}
@ -135,77 +165,87 @@ TorrentFilter :: lessThan( const QModelIndex& left, const QModelIndex& right ) c
***/
bool
TorrentFilter :: trackerFilterAcceptsTorrent( const Torrent * tor, const QString& tracker ) const
TorrentFilter :: trackerFilterAcceptsTorrent (const Torrent * tor, const QString& tracker) const
{
return tracker.isEmpty() || tor->hasTrackerSubstring( tracker );
return tracker.isEmpty() || tor->hasTrackerSubstring (tracker);
}
bool
TorrentFilter :: activityFilterAcceptsTorrent( const Torrent * tor, const FilterMode& m ) const
TorrentFilter :: activityFilterAcceptsTorrent (const Torrent * tor, const FilterMode& m) const
{
bool accepts;
bool accepts;
switch( m.mode( ) )
switch (m.mode ())
{
case FilterMode::SHOW_ACTIVE:
accepts = tor->peersWeAreUploadingTo( ) > 0 || tor->peersWeAreDownloadingFrom( ) > 0 || tor->isVerifying( );
break;
case FilterMode::SHOW_DOWNLOADING:
accepts = tor->isDownloading( ) || tor->isWaitingToDownload( );
break;
case FilterMode::SHOW_SEEDING:
accepts = tor->isSeeding( ) || tor->isWaitingToSeed( );
break;
case FilterMode::SHOW_PAUSED:
accepts = tor->isPaused( );
break;
case FilterMode::SHOW_FINISHED:
accepts = tor->isFinished( );
break;
case FilterMode::SHOW_VERIFYING:
accepts = tor->isVerifying( ) || tor->isWaitingToVerify( );
break;
case FilterMode::SHOW_ERROR:
accepts = tor->hasError( );
break;
default: // FilterMode::SHOW_ALL
accepts = true;
break;
case FilterMode::SHOW_ACTIVE:
accepts = tor->peersWeAreUploadingTo () > 0 || tor->peersWeAreDownloadingFrom () > 0 || tor->isVerifying ();
break;
case FilterMode::SHOW_DOWNLOADING:
accepts = tor->isDownloading () || tor->isWaitingToDownload ();
break;
case FilterMode::SHOW_SEEDING:
accepts = tor->isSeeding () || tor->isWaitingToSeed ();
break;
case FilterMode::SHOW_PAUSED:
accepts = tor->isPaused ();
break;
case FilterMode::SHOW_FINISHED:
accepts = tor->isFinished ();
break;
case FilterMode::SHOW_VERIFYING:
accepts = tor->isVerifying () || tor->isWaitingToVerify ();
break;
case FilterMode::SHOW_ERROR:
accepts = tor->hasError ();
break;
default: // FilterMode::SHOW_ALL
accepts = true;
break;
}
return accepts;
return accepts;
}
bool
TorrentFilter :: filterAcceptsRow( int sourceRow, const QModelIndex& sourceParent ) const
TorrentFilter :: filterAcceptsRow (int sourceRow, const QModelIndex& sourceParent) const
{
QModelIndex childIndex = sourceModel()->index( sourceRow, 0, sourceParent );
const Torrent * tor = childIndex.model()->data( childIndex, TorrentModel::TorrentRole ).value<const Torrent*>();
bool accepts = true;
QModelIndex childIndex = sourceModel()->index (sourceRow, 0, sourceParent);
const Torrent * tor = childIndex.model()->data (childIndex, TorrentModel::TorrentRole).value<const Torrent*>();
bool accepts = true;
if( accepts ) {
const FilterMode m = myPrefs.get<FilterMode>(Prefs::FILTER_MODE);
accepts = activityFilterAcceptsTorrent( tor, m );
if (accepts)
{
const FilterMode m = myPrefs.get<FilterMode>(Prefs::FILTER_MODE);
accepts = activityFilterAcceptsTorrent (tor, m);
}
if( accepts ) {
const QString trackers = myPrefs.getString(Prefs::FILTER_TRACKERS);
accepts = trackerFilterAcceptsTorrent( tor, trackers );
if (accepts)
{
const QString trackers = myPrefs.getString(Prefs::FILTER_TRACKERS);
accepts = trackerFilterAcceptsTorrent (tor, trackers);
}
if( accepts ) {
const QString text = myPrefs.getString( Prefs::FILTER_TEXT );
if( !text.isEmpty( ) )
accepts = tor->name().contains( text, Qt::CaseInsensitive );
if (accepts)
{
const QString text = myPrefs.getString (Prefs::FILTER_TEXT);
if (!text.isEmpty ())
accepts = tor->name().contains (text, Qt::CaseInsensitive);
}
return accepts;
return accepts;
}
int
TorrentFilter :: hiddenRowCount( ) const
TorrentFilter :: hiddenRowCount () const
{
return sourceModel()->rowCount( ) - rowCount( );
return sourceModel()->rowCount () - rowCount ();
}
void
@ -219,7 +259,7 @@ TorrentFilter :: countTorrentsPerMode (int * setmeCounts) const
if (!index.isValid())
break;
const Torrent * tor (index.data( TorrentModel::TorrentRole ).value<const Torrent*>());
const Torrent * tor (index.data (TorrentModel::TorrentRole).value<const Torrent*>());
for (int mode(0); mode<FilterMode::NUM_MODES; ++mode)
if (activityFilterAcceptsTorrent (tor, mode))
++setmeCounts[mode];

View File

@ -26,32 +26,32 @@ class Torrent;
class TorrentFilter: public QSortFilterProxyModel
{
Q_OBJECT
Q_OBJECT
public:
TorrentFilter( Prefs& prefs );
virtual ~TorrentFilter( );
public:
TorrentFilter (Prefs& prefs);
virtual ~TorrentFilter ();
public:
enum TextMode { FILTER_BY_NAME, FILTER_BY_FILES, FILTER_BY_TRACKER };
int hiddenRowCount( ) const;
public:
enum TextMode { FILTER_BY_NAME, FILTER_BY_FILES, FILTER_BY_TRACKER };
int hiddenRowCount () const;
private slots:
void refreshPref( int key );
private slots:
void refreshPref (int key);
protected:
virtual bool filterAcceptsRow( int, const QModelIndex& ) const;
virtual bool lessThan( const QModelIndex&, const QModelIndex& ) const;
protected:
virtual bool filterAcceptsRow (int, const QModelIndex&) const;
virtual bool lessThan (const QModelIndex&, const QModelIndex&) const;
private:
bool activityFilterAcceptsTorrent( const Torrent * tor, const FilterMode& mode ) const;
bool trackerFilterAcceptsTorrent( const Torrent * tor, const QString& tracker ) const;
private:
bool activityFilterAcceptsTorrent (const Torrent * tor, const FilterMode& mode) const;
bool trackerFilterAcceptsTorrent (const Torrent * tor, const QString& tracker) const;
public:
void countTorrentsPerMode (int * setmeCounts) const;
public:
void countTorrentsPerMode (int * setmeCounts) const;
private:
Prefs& myPrefs;
private:
Prefs& myPrefs;
};
#endif

View File

@ -20,24 +20,24 @@
#include "torrent-model.h"
void
TorrentModel :: clear( )
TorrentModel :: clear ()
{
beginResetModel ();
beginResetModel ();
myIdToRow.clear( );
myIdToTorrent.clear( );
foreach( Torrent * tor, myTorrents ) delete tor;
myTorrents.clear( );
myIdToRow.clear ();
myIdToTorrent.clear ();
foreach (Torrent * tor, myTorrents) delete tor;
myTorrents.clear ();
endResetModel ();
endResetModel ();
}
int
TorrentModel :: rowCount( const QModelIndex& parent ) const
TorrentModel :: rowCount (const QModelIndex& parent) const
{
Q_UNUSED( parent );
Q_UNUSED (parent);
return myTorrents.size( );
return myTorrents.size ();
}
QVariant
@ -76,21 +76,21 @@ TorrentModel :: data (const QModelIndex& index, int role) const
***/
void
TorrentModel :: addTorrent( Torrent * t )
TorrentModel :: addTorrent (Torrent * t)
{
myIdToTorrent.insert( t->id( ), t );
myIdToRow.insert( t->id( ), myTorrents.size( ) );
myTorrents.append( t );
myIdToTorrent.insert (t->id (), t);
myIdToRow.insert (t->id (), myTorrents.size ());
myTorrents.append (t);
}
TorrentModel :: TorrentModel( Prefs& prefs ):
myPrefs( prefs )
TorrentModel :: TorrentModel (Prefs& prefs):
myPrefs (prefs)
{
}
TorrentModel :: ~TorrentModel( )
TorrentModel :: ~TorrentModel ()
{
clear( );
clear ();
}
/***
@ -98,17 +98,17 @@ TorrentModel :: ~TorrentModel( )
***/
Torrent*
TorrentModel :: getTorrentFromId( int id )
TorrentModel :: getTorrentFromId (int id)
{
id_to_torrent_t::iterator it( myIdToTorrent.find( id ) );
return it == myIdToTorrent.end() ? 0 : it.value( );
id_to_torrent_t::iterator it (myIdToTorrent.find (id));
return it == myIdToTorrent.end() ? 0 : it.value ();
}
const Torrent*
TorrentModel :: getTorrentFromId( int id ) const
TorrentModel :: getTorrentFromId (int id) const
{
id_to_torrent_t::const_iterator it( myIdToTorrent.find( id ) );
return it == myIdToTorrent.end() ? 0 : it.value( );
id_to_torrent_t::const_iterator it (myIdToTorrent.find (id));
return it == myIdToTorrent.end() ? 0 : it.value ();
}
/***
@ -116,120 +116,124 @@ TorrentModel :: getTorrentFromId( int id ) const
***/
void
TorrentModel :: onTorrentChanged( int torrentId )
TorrentModel :: onTorrentChanged (int torrentId)
{
const int row( myIdToRow.value( torrentId, -1 ) );
if( row >= 0 ) {
QModelIndex qmi( index( row, 0 ) );
emit dataChanged( qmi, qmi );
}
}
void
TorrentModel :: removeTorrents( tr_variant * torrents )
{
int i = 0;
tr_variant * child;
while(( child = tr_variantListChild( torrents, i++ ))) {
int64_t intVal;
if( tr_variantGetInt( child, &intVal ) )
removeTorrent( intVal );
}
}
void
TorrentModel :: updateTorrents( tr_variant * torrents, bool isCompleteList )
{
QList<Torrent*> newTorrents;
QSet<int> oldIds;
QSet<int> addIds;
QSet<int> newIds;
int updatedCount = 0;
if ( isCompleteList )
oldIds = getIds( );
if( tr_variantIsList( torrents ) )
const int row (myIdToRow.value (torrentId, -1));
if (row >= 0)
{
size_t i( 0 );
tr_variant * child;
while(( child = tr_variantListChild( torrents, i++ )))
{
int64_t id;
if( tr_variantDictFindInt( child, TR_KEY_id, &id ) )
{
newIds.insert( id );
QModelIndex qmi (index (row, 0));
emit dataChanged (qmi, qmi);
}
}
Torrent * tor = getTorrentFromId( id );
if( tor == 0 )
void
TorrentModel :: removeTorrents (tr_variant * torrents)
{
int i = 0;
tr_variant * child;
while( (child = tr_variantListChild (torrents, i++)))
{
int64_t intVal;
if (tr_variantGetInt (child, &intVal))
removeTorrent (intVal);
}
}
void
TorrentModel :: updateTorrents (tr_variant * torrents, bool isCompleteList)
{
QList<Torrent*> newTorrents;
QSet<int> oldIds;
QSet<int> addIds;
QSet<int> newIds;
int updatedCount = 0;
if (isCompleteList)
oldIds = getIds ();
if (tr_variantIsList (torrents))
{
size_t i (0);
tr_variant * child;
while( (child = tr_variantListChild (torrents, i++)))
{
int64_t id;
if (tr_variantDictFindInt (child, TR_KEY_id, &id))
{
newIds.insert (id);
Torrent * tor = getTorrentFromId (id);
if (tor == 0)
{
tor = new Torrent( myPrefs, id );
tor->update( child );
if( !tor->hasMetadata() )
tor->setMagnet( true );
newTorrents.append( tor );
connect( tor, SIGNAL(torrentChanged(int)), this, SLOT(onTorrentChanged(int)));
tor = new Torrent (myPrefs, id);
tor->update (child);
if (!tor->hasMetadata())
tor->setMagnet (true);
newTorrents.append (tor);
connect (tor, SIGNAL(torrentChanged(int)), this, SLOT(onTorrentChanged(int)));
}
else
else
{
tor->update( child );
++updatedCount;
if( tor->isMagnet() && tor->hasMetadata() )
tor->update (child);
++updatedCount;
if (tor->isMagnet() && tor->hasMetadata())
{
addIds.insert( tor->id() );
tor->setMagnet( false );
addIds.insert (tor->id());
tor->setMagnet (false);
}
}
}
}
}
if( !newTorrents.isEmpty( ) )
if (!newTorrents.isEmpty ())
{
const int oldCount( rowCount( ) );
const int newCount( oldCount + newTorrents.size( ) );
QSet<int> ids;
const int oldCount (rowCount ());
const int newCount (oldCount + newTorrents.size ());
QSet<int> ids;
beginInsertRows( QModelIndex(), oldCount, newCount - 1 );
beginInsertRows (QModelIndex(), oldCount, newCount - 1);
foreach( Torrent * tor, newTorrents ) {
addTorrent( tor );
addIds.insert( tor->id( ) );
foreach (Torrent * tor, newTorrents)
{
addTorrent (tor);
addIds.insert (tor->id ());
}
endInsertRows( );
endInsertRows ();
}
if( !addIds.isEmpty() )
emit torrentsAdded( addIds );
if (!addIds.isEmpty())
emit torrentsAdded (addIds);
if( isCompleteList )
if (isCompleteList)
{
QSet<int> removedIds( oldIds );
removedIds -= newIds;
foreach( int id, removedIds )
removeTorrent( id );
QSet<int> removedIds (oldIds);
removedIds -= newIds;
foreach (int id, removedIds)
removeTorrent (id);
}
}
void
TorrentModel :: removeTorrent( int id )
TorrentModel :: removeTorrent (int id)
{
const int row = myIdToRow.value( id, -1 );
if( row >= 0 )
const int row = myIdToRow.value (id, -1);
if (row >= 0)
{
Torrent * tor = myIdToTorrent.value( id, 0 );
Torrent * tor = myIdToTorrent.value (id, 0);
beginRemoveRows( QModelIndex(), row, row );
// make the myIdToRow map consistent with list view/model
for( QMap<int,int>::iterator i = myIdToRow.begin(); i != myIdToRow.end(); ++i )
if( i.value() > row )
--i.value();
myIdToRow.remove( id );
myIdToTorrent.remove( id );
myTorrents.remove( myTorrents.indexOf( tor ) );
endRemoveRows( );
beginRemoveRows (QModelIndex(), row, row);
// make the myIdToRow map consistent with list view/model
for (QMap<int,int>::iterator i = myIdToRow.begin(); i != myIdToRow.end(); ++i)
if (i.value() > row)
--i.value();
myIdToRow.remove (id);
myIdToTorrent.remove (id);
myTorrents.remove (myTorrents.indexOf (tor));
endRemoveRows ();
delete tor;
delete tor;
}
}
@ -270,10 +274,11 @@ TorrentModel :: getIds () const
}
bool
TorrentModel :: hasTorrent( const QString& hashString ) const
TorrentModel :: hasTorrent (const QString& hashString) const
{
foreach( const Torrent * tor, myTorrents )
if( tor->hashString( ) == hashString )
return true;
return false;
foreach (const Torrent * tor, myTorrents)
if (tor->hashString () == hashString)
return true;
return false;
}

View File

@ -30,52 +30,52 @@ extern "C"
class TorrentModel: public QAbstractListModel
{
Q_OBJECT
Q_OBJECT
private:
typedef QMap<int,int> id_to_row_t;
typedef QMap<int,Torrent*> id_to_torrent_t;
typedef QVector<Torrent*> torrents_t;
id_to_row_t myIdToRow;
id_to_torrent_t myIdToTorrent;
torrents_t myTorrents;
Prefs& myPrefs;
private:
typedef QMap<int,int> id_to_row_t;
typedef QMap<int,Torrent*> id_to_torrent_t;
typedef QVector<Torrent*> torrents_t;
id_to_row_t myIdToRow;
id_to_torrent_t myIdToTorrent;
torrents_t myTorrents;
Prefs& myPrefs;
public:
void clear( );
bool hasTorrent( const QString& hashString ) const;
virtual int rowCount( const QModelIndex& parent = QModelIndex() ) const;
virtual QVariant data( const QModelIndex& index, int role = Qt::DisplayRole ) const;
enum Role { TorrentRole = Qt::UserRole };
public:
void clear ();
bool hasTorrent (const QString& hashString) const;
virtual int rowCount (const QModelIndex& parent = QModelIndex()) const;
virtual QVariant data (const QModelIndex& index, int role = Qt::DisplayRole) const;
enum Role { TorrentRole = Qt::UserRole };
public:
Torrent* getTorrentFromId( int id );
const Torrent* getTorrentFromId( int id ) const;
public:
Torrent* getTorrentFromId (int id);
const Torrent* getTorrentFromId (int id) const;
private:
void addTorrent( Torrent * );
QSet<int> getIds( ) const;
private:
void addTorrent (Torrent *);
QSet<int> getIds () const;
public:
void getTransferSpeed (Speed & uploadSpeed,
size_t & uploadPeerCount,
Speed & downloadSpeed,
size_t & downloadPeerCount);
public:
void getTransferSpeed (Speed & uploadSpeed,
size_t & uploadPeerCount,
Speed & downloadSpeed,
size_t & downloadPeerCount);
signals:
void torrentsAdded( QSet<int> );
signals:
void torrentsAdded (QSet<int>);
public slots:
void updateTorrents( tr_variant * torrentList, bool isCompleteList );
void removeTorrents( tr_variant * torrentList );
void removeTorrent( int id );
public slots:
void updateTorrents (tr_variant * torrentList, bool isCompleteList);
void removeTorrents (tr_variant * torrentList);
void removeTorrent (int id);
private slots:
void onTorrentChanged( int propertyId );
private slots:
void onTorrentChanged (int propertyId);
public:
TorrentModel( Prefs& prefs );
virtual ~TorrentModel( );
public:
TorrentModel (Prefs& prefs);
virtual ~TorrentModel ();
};
#endif

View File

@ -92,7 +92,7 @@ struct TrackerStat
QString host;
QString lastAnnounceResult;
QString lastScrapeResult;
QPixmap getFavicon( ) const;
QPixmap getFavicon () const;
};
typedef QList<TrackerStat> TrackerStatsList;
@ -101,7 +101,7 @@ Q_DECLARE_METATYPE(TrackerStatsList)
struct TrFile
{
TrFile(): wanted(true), index(-1), priority(0), size(0), have(0) { }
TrFile(): wanted(true), index(-1), priority(0), size(0), have(0) {}
bool wanted;
int index;
@ -118,233 +118,234 @@ Q_DECLARE_METATYPE(FileList)
class Torrent: public QObject
{
Q_OBJECT;
Q_OBJECT;
public:
public:
enum
{
ID,
UPLOAD_SPEED,
DOWNLOAD_SPEED,
DOWNLOAD_DIR,
ACTIVITY,
NAME,
ERROR,
ERROR_STRING,
SIZE_WHEN_DONE,
LEFT_UNTIL_DONE,
HAVE_UNCHECKED,
HAVE_VERIFIED,
DESIRED_AVAILABLE,
TOTAL_SIZE,
PIECE_SIZE,
PIECE_COUNT,
PEERS_GETTING_FROM_US,
PEERS_SENDING_TO_US,
WEBSEEDS_SENDING_TO_US,
PERCENT_DONE,
METADATA_PERCENT_DONE,
PERCENT_VERIFIED,
DATE_ACTIVITY,
DATE_ADDED,
DATE_STARTED,
DATE_CREATED,
PEERS_CONNECTED,
ETA,
RATIO,
DOWNLOADED_EVER,
UPLOADED_EVER,
FAILED_EVER,
TRACKERS,
HOSTS,
TRACKERSTATS,
MIME_ICON,
SEED_RATIO_LIMIT,
SEED_RATIO_MODE,
SEED_IDLE_LIMIT,
SEED_IDLE_MODE,
DOWN_LIMIT,
DOWN_LIMITED,
UP_LIMIT,
UP_LIMITED,
HONORS_SESSION_LIMITS,
PEER_LIMIT,
HASH_STRING,
IS_FINISHED,
IS_PRIVATE,
IS_STALLED,
COMMENT,
CREATOR,
MANUAL_ANNOUNCE_TIME,
PEERS,
BANDWIDTH_PRIORITY,
QUEUE_POSITION,
enum
{
ID,
UPLOAD_SPEED,
DOWNLOAD_SPEED,
DOWNLOAD_DIR,
ACTIVITY,
NAME,
ERROR,
ERROR_STRING,
SIZE_WHEN_DONE,
LEFT_UNTIL_DONE,
HAVE_UNCHECKED,
HAVE_VERIFIED,
DESIRED_AVAILABLE,
TOTAL_SIZE,
PIECE_SIZE,
PIECE_COUNT,
PEERS_GETTING_FROM_US,
PEERS_SENDING_TO_US,
WEBSEEDS_SENDING_TO_US,
PERCENT_DONE,
METADATA_PERCENT_DONE,
PERCENT_VERIFIED,
DATE_ACTIVITY,
DATE_ADDED,
DATE_STARTED,
DATE_CREATED,
PEERS_CONNECTED,
ETA,
RATIO,
DOWNLOADED_EVER,
UPLOADED_EVER,
FAILED_EVER,
TRACKERS,
HOSTS,
TRACKERSTATS,
MIME_ICON,
SEED_RATIO_LIMIT,
SEED_RATIO_MODE,
SEED_IDLE_LIMIT,
SEED_IDLE_MODE,
DOWN_LIMIT,
DOWN_LIMITED,
UP_LIMIT,
UP_LIMITED,
HONORS_SESSION_LIMITS,
PEER_LIMIT,
HASH_STRING,
IS_FINISHED,
IS_PRIVATE,
IS_STALLED,
COMMENT,
CREATOR,
MANUAL_ANNOUNCE_TIME,
PEERS,
BANDWIDTH_PRIORITY,
QUEUE_POSITION,
PROPERTY_COUNT
};
PROPERTY_COUNT
};
public:
Torrent( Prefs&, int id );
virtual ~Torrent( );
public:
Torrent (Prefs&, int id);
virtual ~Torrent ();
signals:
void torrentChanged( int id );
void torrentCompleted( int id );
signals:
void torrentChanged (int id);
void torrentCompleted (int id);
private:
private:
enum Group
{
INFO, // info fields that only need to be loaded once
STAT, // commonly-used stats that should be refreshed often
STAT_EXTRA, // rarely used; only refresh if details dialog is open
DERIVED // doesn't come from RPC
};
enum Group
{
INFO, // info fields that only need to be loaded once
STAT, // commonly-used stats that should be refreshed often
STAT_EXTRA, // rarely used; only refresh if details dialog is open
DERIVED // doesn't come from RPC
};
struct Property
{
int id;
tr_quark key;
int type;
int group;
};
struct Property
{
int id;
tr_quark key;
int type;
int group;
};
static Property myProperties[];
static Property myProperties[];
bool magnetTorrent;
bool magnetTorrent;
public:
typedef QList<tr_quark> KeyList;
static const KeyList& getInfoKeys( );
static const KeyList& getStatKeys( );
static const KeyList& getExtraStatKeys( );
public:
typedef QList<tr_quark> KeyList;
static const KeyList& getInfoKeys ();
static const KeyList& getStatKeys ();
static const KeyList& getExtraStatKeys ();
private:
static KeyList buildKeyList( Group group );
private:
static KeyList buildKeyList (Group group);
private:
QVariant myValues[PROPERTY_COUNT];
private:
QVariant myValues[PROPERTY_COUNT];
int getInt ( int key ) const;
bool getBool ( int key ) const;
QTime getTime ( int key ) const;
QIcon getIcon ( int key ) const;
double getDouble ( int key ) const;
qulonglong getSize ( int key ) const;
QString getString ( int key ) const;
QDateTime getDateTime ( int key ) const;
int getInt (int key) const;
bool getBool (int key) const;
QTime getTime (int key) const;
QIcon getIcon (int key) const;
double getDouble (int key) const;
qulonglong getSize (int key) const;
QString getString (int key) const;
QDateTime getDateTime (int key) const;
bool setInt ( int key, int value );
bool setBool ( int key, bool value );
bool setIcon ( int key, const QIcon& );
bool setDouble ( int key, double );
bool setString ( int key, const char * );
bool setSize ( int key, qulonglong );
bool setDateTime ( int key, const QDateTime& );
bool setInt (int key, int value);
bool setBool (int key, bool value);
bool setIcon (int key, const QIcon&);
bool setDouble (int key, double);
bool setString (int key, const char *);
bool setSize (int key, qulonglong);
bool setDateTime (int key, const QDateTime&);
public:
int getBandwidthPriority( ) const { return getInt( BANDWIDTH_PRIORITY ); }
int id( ) const { return getInt( ID ); }
QString name( ) const { return getString( NAME ); }
QString creator( ) const { return getString( CREATOR ); }
QString comment( ) const { return getString( COMMENT ); }
QString getPath( ) const { return getString( DOWNLOAD_DIR ); }
QString getError( ) const;
QString hashString( ) const { return getString( HASH_STRING ); }
bool hasError( ) const { return !getError( ).isEmpty( ); }
bool isDone( ) const { return getSize( LEFT_UNTIL_DONE ) == 0; }
bool isSeed( ) const { return haveVerified() >= totalSize(); }
bool isPrivate( ) const { return getBool( IS_PRIVATE ); }
bool getSeedRatio( double& setme ) const;
uint64_t haveVerified( ) const { return getSize( HAVE_VERIFIED ); }
uint64_t haveUnverified( ) const { return getSize( HAVE_UNCHECKED ); }
uint64_t desiredAvailable( ) const { return getSize( DESIRED_AVAILABLE ); }
uint64_t haveTotal( ) const { return haveVerified( ) + haveUnverified(); }
uint64_t totalSize( ) const { return getSize( TOTAL_SIZE ); }
uint64_t sizeWhenDone( ) const { return getSize( SIZE_WHEN_DONE ); }
uint64_t leftUntilDone( ) const { return getSize( LEFT_UNTIL_DONE ); }
uint64_t pieceSize( ) const { return getSize( PIECE_SIZE ); }
bool hasMetadata( ) const { return getDouble( METADATA_PERCENT_DONE ) >= 1.0; }
bool isMagnet( ) const { return magnetTorrent; }
int pieceCount( ) const { return getInt( PIECE_COUNT ); }
double ratio( ) const { return getDouble( RATIO ); }
double percentComplete( ) const { return haveTotal() / (double)totalSize(); }
double percentDone( ) const { return getDouble( PERCENT_DONE ); }
double metadataPercentDone( ) const { return getDouble( METADATA_PERCENT_DONE ); }
uint64_t downloadedEver( ) const { return getSize( DOWNLOADED_EVER ); }
uint64_t uploadedEver( ) const { return getSize( UPLOADED_EVER ); }
uint64_t failedEver( ) const { return getSize( FAILED_EVER ); }
int compareTracker( const Torrent& ) const;
int compareSeedRatio( const Torrent& ) const;
int compareRatio( const Torrent& ) const;
int compareETA( const Torrent& ) const;
bool hasETA( ) const { return getETA( ) >= 0; }
int getETA( ) const { return getInt( ETA ); }
QDateTime lastActivity( ) const { return getDateTime( DATE_ACTIVITY ); }
QDateTime lastStarted( ) const { return getDateTime( DATE_STARTED ); }
QDateTime dateAdded( ) const { return getDateTime( DATE_ADDED ); }
QDateTime dateCreated( ) const { return getDateTime( DATE_CREATED ); }
QDateTime manualAnnounceTime( ) const { return getDateTime( MANUAL_ANNOUNCE_TIME ); }
bool canManualAnnounce( ) const { return isReadyToTransfer() && (manualAnnounceTime()<=QDateTime::currentDateTime()); }
int peersWeAreDownloadingFrom( ) const { return getInt( PEERS_SENDING_TO_US ); }
int webseedsWeAreDownloadingFrom( ) const { return getInt( WEBSEEDS_SENDING_TO_US ); }
int peersWeAreUploadingTo( ) const { return getInt( PEERS_GETTING_FROM_US ); }
bool isUploading( ) const { return peersWeAreUploadingTo( ) > 0; }
int connectedPeers( ) const { return getInt( PEERS_CONNECTED ); }
int connectedPeersAndWebseeds( ) const { return connectedPeers( ) + getInt( WEBSEEDS_SENDING_TO_US ); }
Speed downloadSpeed( ) const { return Speed::fromBps( getSize( DOWNLOAD_SPEED ) ); }
Speed uploadSpeed( ) const { return Speed::fromBps( getSize( UPLOAD_SPEED ) ); }
double getVerifyProgress( ) const { return getDouble( PERCENT_VERIFIED ); }
bool hasFileSubstring( const QString& substr ) const;
bool hasTrackerSubstring( const QString& substr ) const;
Speed uploadLimit( ) const { return Speed::fromKBps( getInt( UP_LIMIT ) ); }
Speed downloadLimit( ) const { return Speed::fromKBps( getInt( DOWN_LIMIT ) ); }
bool uploadIsLimited( ) const { return getBool( UP_LIMITED ); }
bool downloadIsLimited( ) const { return getBool( DOWN_LIMITED ); }
bool honorsSessionLimits( ) const { return getBool( HONORS_SESSION_LIMITS ); }
int peerLimit( ) const { return getInt( PEER_LIMIT ); }
double seedRatioLimit( ) const { return getDouble( SEED_RATIO_LIMIT ); }
tr_ratiolimit seedRatioMode( ) const { return (tr_ratiolimit) getInt( SEED_RATIO_MODE ); }
int seedIdleLimit( ) const { return getInt( SEED_IDLE_LIMIT ); }
tr_idlelimit seedIdleMode( ) const { return (tr_idlelimit) getInt( SEED_IDLE_MODE ); }
TrackerStatsList trackerStats( ) const{ return myValues[TRACKERSTATS].value<TrackerStatsList>(); }
QStringList trackers() const { return myValues[TRACKERS].value<QStringList>(); }
QStringList hosts() const { return myValues[HOSTS].value<QStringList>(); }
PeerList peers( ) const{ return myValues[PEERS].value<PeerList>(); }
const FileList& files( ) const { return myFiles; }
int queuePosition( ) const { return getInt( QUEUE_POSITION ); }
bool isStalled( ) const { return getBool( IS_STALLED ); }
public:
public:
QString activityString( ) const;
tr_torrent_activity getActivity( ) const { return (tr_torrent_activity) getInt( ACTIVITY ); }
bool isFinished( ) const { return getBool( IS_FINISHED ); }
bool isPaused( ) const { return getActivity( ) == TR_STATUS_STOPPED; }
bool isWaitingToVerify( ) const { return getActivity( ) == TR_STATUS_CHECK_WAIT; }
bool isVerifying( ) const { return getActivity( ) == TR_STATUS_CHECK; }
bool isDownloading( ) const { return getActivity( ) == TR_STATUS_DOWNLOAD; }
bool isWaitingToDownload( ) const { return getActivity( ) == TR_STATUS_DOWNLOAD_WAIT; }
bool isSeeding( ) const { return getActivity( ) == TR_STATUS_SEED; }
bool isWaitingToSeed( ) const { return getActivity( ) == TR_STATUS_SEED_WAIT; }
bool isReadyToTransfer( ) const { return getActivity()==TR_STATUS_DOWNLOAD || getActivity()==TR_STATUS_SEED; }
bool isQueued( ) const { return isWaitingToDownload() || isWaitingToSeed(); }
void notifyComplete( ) const;
int getBandwidthPriority () const { return getInt (BANDWIDTH_PRIORITY); }
int id () const { return getInt (ID); }
QString name () const { return getString (NAME); }
QString creator () const { return getString (CREATOR); }
QString comment () const { return getString (COMMENT); }
QString getPath () const { return getString (DOWNLOAD_DIR); }
QString getError () const;
QString hashString () const { return getString (HASH_STRING); }
bool hasError () const { return !getError ().isEmpty (); }
bool isDone () const { return getSize (LEFT_UNTIL_DONE) == 0; }
bool isSeed () const { return haveVerified() >= totalSize(); }
bool isPrivate () const { return getBool (IS_PRIVATE); }
bool getSeedRatio (double& setme) const;
uint64_t haveVerified () const { return getSize (HAVE_VERIFIED); }
uint64_t haveUnverified () const { return getSize (HAVE_UNCHECKED); }
uint64_t desiredAvailable () const { return getSize (DESIRED_AVAILABLE); }
uint64_t haveTotal () const { return haveVerified () + haveUnverified(); }
uint64_t totalSize () const { return getSize (TOTAL_SIZE); }
uint64_t sizeWhenDone () const { return getSize (SIZE_WHEN_DONE); }
uint64_t leftUntilDone () const { return getSize (LEFT_UNTIL_DONE); }
uint64_t pieceSize () const { return getSize (PIECE_SIZE); }
bool hasMetadata () const { return getDouble (METADATA_PERCENT_DONE) >= 1.0; }
bool isMagnet () const { return magnetTorrent; }
int pieceCount () const { return getInt (PIECE_COUNT); }
double ratio () const { return getDouble (RATIO); }
double percentComplete () const { return haveTotal() / (double)totalSize(); }
double percentDone () const { return getDouble (PERCENT_DONE); }
double metadataPercentDone () const { return getDouble (METADATA_PERCENT_DONE); }
uint64_t downloadedEver () const { return getSize (DOWNLOADED_EVER); }
uint64_t uploadedEver () const { return getSize (UPLOADED_EVER); }
uint64_t failedEver () const { return getSize (FAILED_EVER); }
int compareTracker (const Torrent&) const;
int compareSeedRatio (const Torrent&) const;
int compareRatio (const Torrent&) const;
int compareETA (const Torrent&) const;
bool hasETA () const { return getETA () >= 0; }
int getETA () const { return getInt (ETA); }
QDateTime lastActivity () const { return getDateTime (DATE_ACTIVITY); }
QDateTime lastStarted () const { return getDateTime (DATE_STARTED); }
QDateTime dateAdded () const { return getDateTime (DATE_ADDED); }
QDateTime dateCreated () const { return getDateTime (DATE_CREATED); }
QDateTime manualAnnounceTime () const { return getDateTime (MANUAL_ANNOUNCE_TIME); }
bool canManualAnnounce () const { return isReadyToTransfer() && (manualAnnounceTime()<=QDateTime::currentDateTime()); }
int peersWeAreDownloadingFrom () const { return getInt (PEERS_SENDING_TO_US); }
int webseedsWeAreDownloadingFrom () const { return getInt (WEBSEEDS_SENDING_TO_US); }
int peersWeAreUploadingTo () const { return getInt (PEERS_GETTING_FROM_US); }
bool isUploading () const { return peersWeAreUploadingTo () > 0; }
int connectedPeers () const { return getInt (PEERS_CONNECTED); }
int connectedPeersAndWebseeds () const { return connectedPeers () + getInt (WEBSEEDS_SENDING_TO_US); }
Speed downloadSpeed () const { return Speed::fromBps (getSize (DOWNLOAD_SPEED)); }
Speed uploadSpeed () const { return Speed::fromBps (getSize (UPLOAD_SPEED)); }
double getVerifyProgress () const { return getDouble (PERCENT_VERIFIED); }
bool hasFileSubstring (const QString& substr) const;
bool hasTrackerSubstring (const QString& substr) const;
Speed uploadLimit () const { return Speed::fromKBps (getInt (UP_LIMIT)); }
Speed downloadLimit () const { return Speed::fromKBps (getInt (DOWN_LIMIT)); }
bool uploadIsLimited () const { return getBool (UP_LIMITED); }
bool downloadIsLimited () const { return getBool (DOWN_LIMITED); }
bool honorsSessionLimits () const { return getBool (HONORS_SESSION_LIMITS); }
int peerLimit () const { return getInt (PEER_LIMIT); }
double seedRatioLimit () const { return getDouble (SEED_RATIO_LIMIT); }
tr_ratiolimit seedRatioMode () const { return (tr_ratiolimit) getInt (SEED_RATIO_MODE); }
int seedIdleLimit () const { return getInt (SEED_IDLE_LIMIT); }
tr_idlelimit seedIdleMode () const { return (tr_idlelimit) getInt (SEED_IDLE_MODE); }
TrackerStatsList trackerStats () const{ return myValues[TRACKERSTATS].value<TrackerStatsList>(); }
QStringList trackers() const { return myValues[TRACKERS].value<QStringList>(); }
QStringList hosts() const { return myValues[HOSTS].value<QStringList>(); }
PeerList peers () const{ return myValues[PEERS].value<PeerList>(); }
const FileList& files () const { return myFiles; }
int queuePosition () const { return getInt (QUEUE_POSITION); }
bool isStalled () const { return getBool (IS_STALLED); }
public:
void update( tr_variant * dict );
void setMagnet( bool magnet ) { magnetTorrent = magnet; }
public:
QString activityString () const;
tr_torrent_activity getActivity () const { return (tr_torrent_activity) getInt (ACTIVITY); }
bool isFinished () const { return getBool (IS_FINISHED); }
bool isPaused () const { return getActivity () == TR_STATUS_STOPPED; }
bool isWaitingToVerify () const { return getActivity () == TR_STATUS_CHECK_WAIT; }
bool isVerifying () const { return getActivity () == TR_STATUS_CHECK; }
bool isDownloading () const { return getActivity () == TR_STATUS_DOWNLOAD; }
bool isWaitingToDownload () const { return getActivity () == TR_STATUS_DOWNLOAD_WAIT; }
bool isSeeding () const { return getActivity () == TR_STATUS_SEED; }
bool isWaitingToSeed () const { return getActivity () == TR_STATUS_SEED_WAIT; }
bool isReadyToTransfer () const { return getActivity()==TR_STATUS_DOWNLOAD || getActivity()==TR_STATUS_SEED; }
bool isQueued () const { return isWaitingToDownload() || isWaitingToSeed(); }
void notifyComplete () const;
private:
const char * getMimeTypeString( ) const;
void updateMimeIcon( );
public:
void update (tr_variant * dict);
void setMagnet (bool magnet) { magnetTorrent = magnet; }
public:
QIcon getMimeTypeIcon( ) const { return getIcon( MIME_ICON ); }
private:
const char * getMimeTypeString () const;
void updateMimeIcon ();
private:
Prefs& myPrefs;
FileList myFiles;
public:
QIcon getMimeTypeIcon () const { return getIcon (MIME_ICON); }
private:
Prefs& myPrefs;
FileList myFiles;
};
Q_DECLARE_METATYPE(const Torrent*)

View File

@ -31,16 +31,16 @@
namespace
{
const int mySpacing = 6;
const QSize myMargin( 10, 6 );
const int mySpacing = 6;
const QSize myMargin (10, 6);
}
QSize
TrackerDelegate :: margin( const QStyle& style ) const
TrackerDelegate :: margin (const QStyle& style) const
{
Q_UNUSED( style );
Q_UNUSED (style);
return myMargin;
return myMargin;
}
/***
@ -48,220 +48,227 @@ TrackerDelegate :: margin( const QStyle& style ) const
***/
QSize
TrackerDelegate :: sizeHint( const QStyleOptionViewItem& option, const TrackerInfo& info ) const
TrackerDelegate :: sizeHint (const QStyleOptionViewItem & option,
const TrackerInfo & info) const
{
Q_UNUSED( option );
Q_UNUSED (option);
QPixmap favicon = info.st.getFavicon( );
QPixmap favicon = info.st.getFavicon ();
const QString text = TrackerDelegate :: getText( info );
QTextDocument textDoc;
textDoc.setHtml( text );
const QSize textSize = textDoc.size().toSize();
const QString text = TrackerDelegate :: getText(info);
QTextDocument textDoc;
textDoc.setHtml (text);
const QSize textSize = textDoc.size().toSize();
return QSize( myMargin.width() + favicon.width() + mySpacing + textSize.width() + myMargin.width(),
myMargin.height() + qMax<int>( favicon.height(), textSize.height() ) + myMargin.height() );
return QSize (myMargin.width() + favicon.width() + mySpacing + textSize.width() + myMargin.width(),
myMargin.height() + qMax<int> (favicon.height(), textSize.height()) + myMargin.height());
}
QSize
TrackerDelegate :: sizeHint( const QStyleOptionViewItem & option,
const QModelIndex & index ) const
TrackerDelegate :: sizeHint (const QStyleOptionViewItem & option,
const QModelIndex & index) const
{
const TrackerInfo trackerInfo = index.data( TrackerModel::TrackerRole ).value<TrackerInfo>();
return sizeHint( option, trackerInfo );
const TrackerInfo trackerInfo = index.data (TrackerModel::TrackerRole).value<TrackerInfo>();
return sizeHint (option, trackerInfo);
}
void
TrackerDelegate :: paint( QPainter * painter,
TrackerDelegate :: paint (QPainter * painter,
const QStyleOptionViewItem & option,
const QModelIndex & index) const
{
const TrackerInfo trackerInfo = index.data( TrackerModel::TrackerRole ).value<TrackerInfo>();
painter->save( );
painter->setClipRect( option.rect );
drawBackground( painter, option, index );
drawTracker( painter, option, trackerInfo );
drawFocus(painter, option, option.rect );
painter->restore( );
const TrackerInfo trackerInfo = index.data (TrackerModel::TrackerRole).value<TrackerInfo>();
painter->save();
painter->setClipRect (option.rect);
drawBackground (painter, option, index);
drawTracker (painter, option, trackerInfo);
drawFocus(painter, option, option.rect);
painter->restore();
}
void
TrackerDelegate :: drawTracker( QPainter * painter,
TrackerDelegate :: drawTracker (QPainter * painter,
const QStyleOptionViewItem & option,
const TrackerInfo & inf ) const
const TrackerInfo & inf) const
{
painter->save( );
painter->save();
QPixmap icon = inf.st.getFavicon( );
QRect iconArea( option.rect.x() + myMargin.width(),
option.rect.y() + myMargin.height(),
icon.width(),
icon.height() );
painter->drawPixmap( iconArea.x(), iconArea.y()+4, icon );
QPixmap icon = inf.st.getFavicon();
QRect iconArea (option.rect.x() + myMargin.width(),
option.rect.y() + myMargin.height(),
icon.width(),
icon.height());
painter->drawPixmap (iconArea.x(), iconArea.y()+4, icon);
const int textWidth = option.rect.width() - myMargin.width()*2 - mySpacing - icon.width();
const int textX = myMargin.width() + icon.width() + mySpacing;
const QString text = getText( inf );
QTextDocument textDoc;
textDoc.setHtml( text );
const QRect textRect( textX, iconArea.y(), textWidth, option.rect.height() - myMargin.height()*2 );
painter->translate( textRect.topLeft( ) );
textDoc.drawContents( painter, textRect.translated( -textRect.topLeft( ) ) );
const int textWidth = option.rect.width() - myMargin.width()*2 - mySpacing - icon.width();
const int textX = myMargin.width() + icon.width() + mySpacing;
const QString text = getText (inf);
QTextDocument textDoc;
textDoc.setHtml (text);
const QRect textRect (textX, iconArea.y(), textWidth, option.rect.height() - myMargin.height()*2);
painter->translate (textRect.topLeft());
textDoc.drawContents (painter, textRect.translated (-textRect.topLeft()));
painter->restore( );
painter->restore();
}
void
TrackerDelegate :: setShowMore( bool b )
TrackerDelegate :: setShowMore (bool b)
{
myShowMore = b;
myShowMore = b;
}
namespace
{
QString timeToStringRounded( int seconds )
QString timeToStringRounded (int seconds)
{
if( seconds > 60 ) seconds -= ( seconds % 60 );
return Formatter::timeToString ( seconds );
if (seconds > 60)
seconds -= (seconds % 60);
return Formatter::timeToString (seconds);
}
}
QString
TrackerDelegate :: getText( const TrackerInfo& inf ) const
TrackerDelegate :: getText (const TrackerInfo& inf) const
{
QString key;
QString str;
const time_t now( time( 0 ) );
const QString err_markup_begin = "<span style=\"color:red\">";
const QString err_markup_end = "</span>";
const QString timeout_markup_begin = "<span style=\"color:#224466\">";
const QString timeout_markup_end = "</span>";
const QString success_markup_begin = "<span style=\"color:#008B00\">";
const QString success_markup_end = "</span>";
QString key;
QString str;
const time_t now (time (0));
const QString err_markup_begin = "<span style=\"color:red\">";
const QString err_markup_end = "</span>";
const QString timeout_markup_begin = "<span style=\"color:#224466\">";
const QString timeout_markup_end = "</span>";
const QString success_markup_begin = "<span style=\"color:#008B00\">";
const QString success_markup_end = "</span>";
// hostname
str += inf.st.isBackup ? "<i>" : "<b>";
char * host = NULL;
int port = 0;
tr_urlParse( inf.st.announce.toUtf8().constData(), -1, NULL, &host, &port, NULL );
str += QString( "%1:%2" ).arg( host ).arg( port );
tr_free( host );
if( !key.isEmpty( ) ) str += " - " + key;
str += inf.st.isBackup ? "</i>" : "</b>";
// hostname
str += inf.st.isBackup ? "<i>" : "<b>";
char * host = NULL;
int port = 0;
tr_urlParse (inf.st.announce.toUtf8().constData(), -1, NULL, &host, &port, NULL);
str += QString ("%1:%2").arg (host).arg (port);
tr_free (host);
if (!key.isEmpty()) str += " - " + key;
str += inf.st.isBackup ? "</i>" : "</b>";
// announce & scrape info
if( !inf.st.isBackup )
// announce & scrape info
if (!inf.st.isBackup)
{
if( inf.st.hasAnnounced && inf.st.announceState != TR_TRACKER_INACTIVE )
if (inf.st.hasAnnounced && inf.st.announceState != TR_TRACKER_INACTIVE)
{
const QString tstr( timeToStringRounded( now - inf.st.lastAnnounceTime ) );
str += "<br/>\n";
if( inf.st.lastAnnounceSucceeded )
const QString tstr (timeToStringRounded (now - inf.st.lastAnnounceTime));
str += "<br/>\n";
if (inf.st.lastAnnounceSucceeded)
{
str += tr( "Got a list of %1%2 peers%3 %4 ago" )
.arg( success_markup_begin )
.arg( inf.st.lastAnnouncePeerCount )
.arg( success_markup_end )
.arg( tstr );
str += tr ("Got a list of %1%2 peers%3 %4 ago")
.arg (success_markup_begin)
.arg (inf.st.lastAnnouncePeerCount)
.arg (success_markup_end)
.arg (tstr);
}
else if( inf.st.lastAnnounceTimedOut )
else if (inf.st.lastAnnounceTimedOut)
{
str += tr( "Peer list request %1timed out%2 %3 ago; will retry" )
.arg( timeout_markup_begin )
.arg( timeout_markup_end )
.arg( tstr );
str += tr ("Peer list request %1timed out%2 %3 ago; will retry")
.arg (timeout_markup_begin)
.arg (timeout_markup_end)
.arg (tstr);
}
else
else
{
str += tr( "Got an error %1\"%2\"%3 %4 ago" )
.arg( err_markup_begin )
.arg( inf.st.lastAnnounceResult )
.arg( err_markup_end )
.arg( tstr );
str += tr ("Got an error %1\"%2\"%3 %4 ago")
.arg (err_markup_begin)
.arg (inf.st.lastAnnounceResult)
.arg (err_markup_end)
.arg (tstr);
}
}
switch( inf.st.announceState )
{
switch (inf.st.announceState)
{
case TR_TRACKER_INACTIVE:
str += "<br/>\n";
str += tr( "No updates scheduled" );
break;
str += "<br/>\n";
str += tr ("No updates scheduled");
break;
case TR_TRACKER_WAITING: {
const QString tstr( timeToStringRounded( inf.st.nextAnnounceTime - now ) );
case TR_TRACKER_WAITING:
{
const QString tstr (timeToStringRounded (inf.st.nextAnnounceTime - now));
str += "<br/>\n";
str += tr( "Asking for more peers in %1" ).arg( tstr );
str += tr ("Asking for more peers in %1").arg (tstr);
break;
}
}
case TR_TRACKER_QUEUED:
str += "<br/>\n";
str += tr( "Queued to ask for more peers" );
break;
str += "<br/>\n";
str += tr ("Queued to ask for more peers");
break;
case TR_TRACKER_ACTIVE: {
const QString tstr( timeToStringRounded( now - inf.st.lastAnnounceStartTime ) );
str += "<br/>\n";
str += tr( "Asking for more peers now... <small>%1</small>" ).arg( tstr );
break;
const QString tstr (timeToStringRounded (now - inf.st.lastAnnounceStartTime));
str += "<br/>\n";
str += tr ("Asking for more peers now... <small>%1</small>").arg (tstr);
break;
}
}
if( myShowMore )
if (myShowMore)
{
if( inf.st.hasScraped )
if (inf.st.hasScraped)
{
str += "<br/>\n";
const QString tstr( timeToStringRounded( now - inf.st.lastScrapeTime ) );
if( inf.st.lastScrapeSucceeded )
str += "<br/>\n";
const QString tstr (timeToStringRounded (now - inf.st.lastScrapeTime));
if (inf.st.lastScrapeSucceeded)
{
str += tr( "Tracker had %1%2 seeders%3 and %4%5 leechers%6 %7 ago" )
.arg( success_markup_begin )
.arg( inf.st.seederCount )
.arg( success_markup_end )
.arg( success_markup_begin )
.arg( inf.st.leecherCount )
.arg( success_markup_end )
.arg( tstr );
str += tr ("Tracker had %1%2 seeders%3 and %4%5 leechers%6 %7 ago")
.arg (success_markup_begin)
.arg (inf.st.seederCount)
.arg (success_markup_end)
.arg (success_markup_begin)
.arg (inf.st.leecherCount)
.arg (success_markup_end)
.arg (tstr);
}
else
else
{
str += tr( "Got a scrape error %1\"%2\"%3 %4 ago" )
.arg( err_markup_begin )
.arg( inf.st.lastScrapeResult )
.arg( err_markup_end )
.arg( tstr );
str += tr ("Got a scrape error %1\"%2\"%3 %4 ago")
.arg (err_markup_begin)
.arg (inf.st.lastScrapeResult)
.arg (err_markup_end)
.arg (tstr);
}
}
switch( inf.st.scrapeState )
switch (inf.st.scrapeState)
{
case TR_TRACKER_INACTIVE:
break;
case TR_TRACKER_INACTIVE:
break;
case TR_TRACKER_WAITING: {
str += "<br/>\n";
const QString tstr( timeToStringRounded( inf.st.nextScrapeTime - now ) );
str += tr( "Asking for peer counts in %1" ).arg( tstr );
break;
case TR_TRACKER_WAITING:
{
str += "<br/>\n";
const QString tstr (timeToStringRounded (inf.st.nextScrapeTime - now));
str += tr ("Asking for peer counts in %1").arg (tstr);
break;
}
case TR_TRACKER_QUEUED: {
str += "<br/>\n";
str += tr( "Queued to ask for peer counts" );
break;
case TR_TRACKER_QUEUED:
{
str += "<br/>\n";
str += tr ("Queued to ask for peer counts");
break;
}
case TR_TRACKER_ACTIVE: {
str += "<br/>\n";
const QString tstr( timeToStringRounded( now - inf.st.lastScrapeStartTime ) );
str += tr( "Asking for peer counts now... <small>%1</small>" ).arg( tstr );
break;
case TR_TRACKER_ACTIVE:
{
str += "<br/>\n";
const QString tstr (timeToStringRounded (now - inf.st.lastScrapeStartTime));
str += tr ("Asking for peer counts now... <small>%1</small>").arg (tstr);
break;
}
}
}
}
return str;
return str;
}

View File

@ -24,27 +24,27 @@ struct TrackerInfo;
class TrackerDelegate: public QItemDelegate
{
Q_OBJECT
Q_OBJECT
public:
TrackerDelegate( QObject * parent=0 ): QItemDelegate(parent), myShowMore(false) { }
virtual ~TrackerDelegate( ) { }
public:
TrackerDelegate (QObject * parent=0): QItemDelegate(parent), myShowMore(false) {}
virtual ~TrackerDelegate () {}
public:
QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
public:
QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
public:
void setShowMore( bool b );
public:
void setShowMore (bool b);
protected:
QString getText( const TrackerInfo& ) const;
QSize margin( const QStyle& style ) const;
virtual QSize sizeHint( const QStyleOptionViewItem&, const TrackerInfo& ) const;
void drawTracker( QPainter*, const QStyleOptionViewItem&, const TrackerInfo& ) const;
protected:
QString getText (const TrackerInfo&) const;
QSize margin (const QStyle& style) const;
virtual QSize sizeHint (const QStyleOptionViewItem&, const TrackerInfo&) const;
void drawTracker (QPainter*, const QStyleOptionViewItem&, const TrackerInfo&) const;
private:
bool myShowMore;
private:
bool myShowMore;
};
#endif

View File

@ -13,24 +13,24 @@
#include "tracker-model.h"
#include "tracker-model-filter.h"
TrackerModelFilter :: TrackerModelFilter( QObject * parent ):
QSortFilterProxyModel( parent ),
myShowBackups( false )
TrackerModelFilter :: TrackerModelFilter (QObject * parent):
QSortFilterProxyModel (parent),
myShowBackups (false)
{
}
void
TrackerModelFilter :: setShowBackupTrackers( bool b )
TrackerModelFilter :: setShowBackupTrackers (bool b)
{
myShowBackups = b;
invalidateFilter( );
myShowBackups = b;
invalidateFilter ();
}
bool
TrackerModelFilter :: filterAcceptsRow( int sourceRow,
const QModelIndex & sourceParent ) const
TrackerModelFilter :: filterAcceptsRow (int sourceRow,
const QModelIndex & sourceParent) const
{
QModelIndex index = sourceModel()->index( sourceRow, 0, sourceParent );
const TrackerInfo trackerInfo = index.data( TrackerModel::TrackerRole ).value<TrackerInfo>();
return myShowBackups || !trackerInfo.st.isBackup;
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
const TrackerInfo trackerInfo = index.data(TrackerModel::TrackerRole).value<TrackerInfo>();
return myShowBackups || !trackerInfo.st.isBackup;
}

View File

@ -17,20 +17,20 @@
class TrackerModelFilter : public QSortFilterProxyModel
{
Q_OBJECT
Q_OBJECT
public:
TrackerModelFilter( QObject *parent = 0 );
public:
TrackerModelFilter (QObject *parent = 0);
public:
void setShowBackupTrackers( bool );
bool showBackupTrackers( ) const { return myShowBackups; }
public:
void setShowBackupTrackers (bool);
bool showBackupTrackers () const { return myShowBackups; }
protected:
bool filterAcceptsRow( int sourceRow, const QModelIndex&sourceParent ) const;
protected:
bool filterAcceptsRow (int sourceRow, const QModelIndex&sourceParent) const;
private:
bool myShowBackups;
private:
bool myShowBackups;
};
#endif

View File

@ -18,138 +18,152 @@
#include "tracker-model.h"
int
TrackerModel :: rowCount( const QModelIndex& parent ) const
TrackerModel :: rowCount (const QModelIndex& parent) const
{
Q_UNUSED( parent );
Q_UNUSED (parent);
return parent.isValid() ? 0 : myRows.size();
return parent.isValid() ? 0 : myRows.size();
}
QVariant
TrackerModel :: data( const QModelIndex& index, int role ) const
TrackerModel :: data (const QModelIndex& index, int role) const
{
QVariant var;
QVariant var;
const int row = index.row( );
if( ( 0<=row ) && ( row<myRows.size( ) ) )
const int row = index.row ();
if ((0<=row) && (row<myRows.size()))
{
const TrackerInfo& trackerInfo = myRows.at( row );
const TrackerInfo& trackerInfo = myRows.at (row);
switch( role )
switch (role)
{
case Qt::DisplayRole:
var = QString( trackerInfo.st.announce );
break;
case Qt::DisplayRole:
var = QString (trackerInfo.st.announce);
break;
case Qt::DecorationRole:
var = trackerInfo.st.getFavicon( );
break;
case Qt::DecorationRole:
var = trackerInfo.st.getFavicon ();
break;
case TrackerRole:
var = qVariantFromValue( trackerInfo );
break;
case TrackerRole:
var = qVariantFromValue (trackerInfo);
break;
default:
break;
default:
break;
}
}
return var;
return var;
}
/***
****
***/
struct CompareTrackers {
bool operator()( const TrackerInfo& a, const TrackerInfo& b ) const {
if( a.torrentId != b.torrentId ) return a.torrentId < b.torrentId;
if( a.st.tier != b.st.tier ) return a.st.tier < b.st.tier;
if( a.st.isBackup != b.st.isBackup ) return !a.st.isBackup;
return a.st.announce < b.st.announce;
}
struct CompareTrackers
{
bool operator() (const TrackerInfo& a, const TrackerInfo& b) const
{
if (a.torrentId != b.torrentId )
return a.torrentId < b.torrentId;
if (a.st.tier != b.st.tier)
return a.st.tier < b.st.tier;
if (a.st.isBackup != b.st.isBackup)
return !a.st.isBackup;
return a.st.announce < b.st.announce;
}
};
void
TrackerModel :: refresh( const TorrentModel& torrentModel, const QSet<int>& ids )
TrackerModel :: refresh (const TorrentModel& torrentModel, const QSet<int>& ids)
{
// build a list of the TrackerInfos
QVector<TrackerInfo> trackers;
foreach( int id, ids ) {
const Torrent * tor = torrentModel.getTorrentFromId( id );
if( tor != 0 ) {
const TrackerStatsList trackerList = tor->trackerStats( );
foreach( const TrackerStat& st, trackerList ) {
TrackerInfo trackerInfo;
trackerInfo.st = st;
trackerInfo.torrentId = id;
trackers.append( trackerInfo );
// build a list of the TrackerInfos
QVector<TrackerInfo> trackers;
foreach (int id, ids)
{
const Torrent * tor = torrentModel.getTorrentFromId (id);
if (tor != 0)
{
const TrackerStatsList trackerList = tor->trackerStats ();
foreach (const TrackerStat& st, trackerList)
{
TrackerInfo trackerInfo;
trackerInfo.st = st;
trackerInfo.torrentId = id;
trackers.append (trackerInfo);
}
}
}
// sort 'em
CompareTrackers comp;
std::sort( trackers.begin(), trackers.end(), comp );
// sort 'em
CompareTrackers comp;
std::sort (trackers.begin(), trackers.end(), comp);
// merge 'em with the existing list
int old_index = 0;
int new_index = 0;
// merge 'em with the existing list
int old_index = 0;
int new_index = 0;
while( ( old_index < myRows.size() ) || ( new_index < trackers.size() ) )
while ((old_index < myRows.size()) || (new_index < trackers.size()))
{
if( old_index == myRows.size() )
if (old_index == myRows.size())
{
// add this new row
beginInsertRows( QModelIndex( ), old_index, old_index );
myRows.insert( old_index, trackers.at( new_index ) );
endInsertRows( );
++old_index;
++new_index;
// add this new row
beginInsertRows (QModelIndex (), old_index, old_index);
myRows.insert (old_index, trackers.at (new_index));
endInsertRows ();
++old_index;
++new_index;
}
else if( new_index == trackers.size() )
else if (new_index == trackers.size())
{
// remove this old row
beginRemoveRows( QModelIndex( ), old_index, old_index );
myRows.remove( old_index );
endRemoveRows( );
// remove this old row
beginRemoveRows (QModelIndex (), old_index, old_index);
myRows.remove (old_index);
endRemoveRows ();
}
else if( comp( myRows.at(old_index), trackers.at(new_index) ) )
else if (comp (myRows.at(old_index), trackers.at(new_index)))
{
// remove this old row
beginRemoveRows( QModelIndex( ), old_index, old_index );
myRows.remove( old_index );
endRemoveRows( );
// remove this old row
beginRemoveRows (QModelIndex (), old_index, old_index);
myRows.remove (old_index);
endRemoveRows ();
}
else if( comp( trackers.at(new_index), myRows.at(old_index) ) )
else if (comp (trackers.at(new_index), myRows.at(old_index)))
{
// add this new row
beginInsertRows( QModelIndex( ), old_index, old_index );
myRows.insert( old_index, trackers.at( new_index ) );
endInsertRows( );
++old_index;
++new_index;
// add this new row
beginInsertRows (QModelIndex (), old_index, old_index);
myRows.insert (old_index, trackers.at (new_index));
endInsertRows ();
++old_index;
++new_index;
}
else // update existing row
else // update existing row
{
myRows[old_index].st = trackers.at(new_index).st;
QModelIndex topLeft;
QModelIndex bottomRight;
dataChanged( index(old_index,0), index(old_index,0) );
++old_index;
++new_index;
myRows[old_index].st = trackers.at(new_index).st;
QModelIndex topLeft;
QModelIndex bottomRight;
dataChanged (index(old_index,0), index(old_index,0));
++old_index;
++new_index;
}
}
}
int
TrackerModel :: find( int torrentId, const QString& url ) const
TrackerModel :: find (int torrentId, const QString& url) const
{
for( int i=0, n=myRows.size(); i<n; ++i ) {
const TrackerInfo& inf = myRows.at(i);
if( ( inf.torrentId == torrentId ) && ( url == inf.st.announce ) )
return i;
for (int i=0, n=myRows.size(); i<n; ++i)
{
const TrackerInfo& inf = myRows.at(i);
if ((inf.torrentId == torrentId) && (url == inf.st.announce))
return i;
}
return -1;
return -1;
}

View File

@ -29,23 +29,23 @@ Q_DECLARE_METATYPE(TrackerInfo)
class TrackerModel: public QAbstractListModel
{
Q_OBJECT
Q_OBJECT
typedef QVector<TrackerInfo> rows_t;
rows_t myRows;
typedef QVector<TrackerInfo> rows_t;
rows_t myRows;
public:
void refresh( const TorrentModel&, const QSet<int>& ids );
int find( int torrentId, const QString& url ) const;
public:
void refresh (const TorrentModel&, const QSet<int>& ids);
int find (int torrentId, const QString& url) const;
public:
virtual int rowCount( const QModelIndex& parent = QModelIndex() ) const;
virtual QVariant data( const QModelIndex& index, int role = Qt::DisplayRole ) const;
enum Role { TrackerRole = Qt::UserRole };
public:
virtual int rowCount (const QModelIndex& parent = QModelIndex()) const;
virtual QVariant data (const QModelIndex& index, int role = Qt::DisplayRole) const;
enum Role { TrackerRole = Qt::UserRole };
public:
TrackerModel( ) { }
virtual ~TrackerModel( ) { }
public:
TrackerModel () {}
virtual ~TrackerModel () {}
};
#endif

View File

@ -19,46 +19,46 @@
#include "hig.h"
#include "triconpushbutton.h"
TrIconPushButton :: TrIconPushButton( QWidget * parent ):
QPushButton( parent )
TrIconPushButton :: TrIconPushButton (QWidget * parent):
QPushButton (parent)
{
}
TrIconPushButton :: TrIconPushButton( const QIcon& icon, QWidget * parent ):
QPushButton( parent )
TrIconPushButton :: TrIconPushButton (const QIcon& icon, QWidget * parent):
QPushButton (parent)
{
setIcon( icon );
setIcon (icon);
}
QSize
TrIconPushButton :: sizeHint () const
{
QSize s = iconSize( );
s.rwidth() += HIG::PAD_SMALL*2;
return s;
QSize s = iconSize ();
s.rwidth() += HIG::PAD_SMALL*2;
return s;
}
void
TrIconPushButton :: paintEvent( QPaintEvent * )
TrIconPushButton :: paintEvent (QPaintEvent *)
{
QStylePainter p( this );
QStyleOptionButton opt;
initStyleOption( &opt );
QStylePainter p (this);
QStyleOptionButton opt;
initStyleOption (&opt);
QIcon::Mode mode = opt.state & QStyle::State_Enabled ? QIcon::Normal : QIcon::Disabled;
if( ( mode == QIcon::Normal ) && ( opt.state & QStyle::State_HasFocus ) )
mode = QIcon::Active;
QPixmap pixmap = opt.icon.pixmap( opt.iconSize, QIcon::Active, QIcon::On );
QRect iconRect( opt.rect.x() + HIG::PAD_SMALL,
opt.rect.y() + (opt.rect.height() - pixmap.height())/2,
pixmap.width(),
pixmap.height());
if( opt.state & ( QStyle::State_On | QStyle::State_Sunken ) )
iconRect.translate( style()->pixelMetric( QStyle::PM_ButtonShiftHorizontal, &opt, this ),
style()->pixelMetric( QStyle::PM_ButtonShiftVertical, &opt, this ) );
QIcon::Mode mode = opt.state & QStyle::State_Enabled ? QIcon::Normal : QIcon::Disabled;
if ((mode == QIcon::Normal) && (opt.state & QStyle::State_HasFocus))
mode = QIcon::Active;
QPixmap pixmap = opt.icon.pixmap (opt.iconSize, QIcon::Active, QIcon::On);
QRect iconRect (opt.rect.x() + HIG::PAD_SMALL,
opt.rect.y() + (opt.rect.height() - pixmap.height())/2,
pixmap.width(),
pixmap.height());
if (opt.state & (QStyle::State_On | QStyle::State_Sunken))
iconRect.translate (style()->pixelMetric (QStyle::PM_ButtonShiftHorizontal, &opt, this),
style()->pixelMetric (QStyle::PM_ButtonShiftVertical, &opt, this));
p.drawPixmap(iconRect, pixmap);
p.drawPixmap(iconRect, pixmap);
if( opt.state & QStyle::State_HasFocus )
p.drawPrimitive( QStyle::PE_FrameFocusRect, opt );
if (opt.state & QStyle::State_HasFocus)
p.drawPrimitive (QStyle::PE_FrameFocusRect, opt);
}

View File

@ -19,16 +19,16 @@ class QIcon;
class TrIconPushButton: public QPushButton
{
Q_OBJECT
Q_OBJECT
public:
TrIconPushButton( QWidget * parent = 0 );
TrIconPushButton( const QIcon&, QWidget * parent = 0 );
virtual ~TrIconPushButton( ) { }
QSize sizeHint () const;
public:
TrIconPushButton (QWidget * parent = 0);
TrIconPushButton (const QIcon&, QWidget * parent = 0);
virtual ~TrIconPushButton () {}
QSize sizeHint () const;
protected:
void paintEvent( QPaintEvent * event );
protected:
void paintEvent (QPaintEvent * event);
};
#endif // QTR_IconPushButton_H

View File

@ -17,16 +17,16 @@
class TrTypes
{
public:
public:
enum
{
TrackerStatsList = QVariant::UserType,
PeerList = QVariant::UserType,
FileList,
FilterModeType,
SortModeType
};
enum
{
TrackerStatsList = QVariant::UserType,
PeerList = QVariant::UserType,
FileList,
FilterModeType,
SortModeType
};
};
#endif

View File

@ -43,27 +43,29 @@ extern QPixmap qt_pixmapFromWinHICON(HICON icon);
#endif
QString
Utils :: remoteFileChooser( QWidget * parent, const QString& title, const QString& myPath, bool dir, bool local )
Utils :: remoteFileChooser (QWidget * parent, const QString& title, const QString& myPath, bool dir, bool local)
{
QString path;
QString path;
if( local )
if (local)
{
if( dir )
path = QFileDialog::getExistingDirectory( parent, title, myPath );
else
path = QFileDialog::getOpenFileName( parent, title, myPath );
if (dir)
path = QFileDialog::getExistingDirectory (parent, title, myPath);
else
path = QFileDialog::getOpenFileName (parent, title, myPath);
}
else
{
path = QInputDialog::getText (parent, title, tr ("Enter a location:"), QLineEdit::Normal, myPath, NULL);
}
else
path = QInputDialog::getText( parent, title, tr( "Enter a location:" ), QLineEdit::Normal, myPath, NULL );
return path;
return path;
}
void
Utils :: toStderr( const QString& str )
Utils :: toStderr (const QString& str)
{
std::cerr << qPrintable(str) << std::endl;
std::cerr << qPrintable(str) << std::endl;
}
#ifdef WIN32
@ -72,8 +74,11 @@ namespace
void
addAssociatedFileIcon (const QFileInfo& fileInfo, UINT iconSize, QIcon& icon)
{
QString const pixmapCacheKey = QLatin1String ("tr_file_ext_") +
QString::number (iconSize) + "_" + fileInfo.suffix ();
QString const pixmapCacheKey = QLatin1String ("tr_file_ext_")
+ QString::number (iconSize)
+ "_"
+ fileInfo.suffix ();
QPixmap pixmap;
if (!QPixmapCache::find (pixmapCacheKey, &pixmap))
{
@ -105,7 +110,7 @@ namespace
#endif
QIcon
Utils :: guessMimeIcon( const QString& filename )
Utils :: guessMimeIcon (const QString& filename)
{
#ifdef WIN32
QIcon icon;
@ -124,87 +129,88 @@ Utils :: guessMimeIcon( const QString& filename )
return icon;
#else
enum { DISK, DOCUMENT, PICTURE, VIDEO, ARCHIVE, AUDIO, APP, TYPE_COUNT };
static QIcon fallback;
static QIcon fileIcons[TYPE_COUNT];
static QSet<QString> suffixes[TYPE_COUNT];
enum { DISK, DOCUMENT, PICTURE, VIDEO, ARCHIVE, AUDIO, APP, TYPE_COUNT };
static QIcon fallback;
static QIcon fileIcons[TYPE_COUNT];
static QSet<QString> suffixes[TYPE_COUNT];
if( fileIcons[0].isNull( ) )
if (fileIcons[0].isNull ())
{
fallback = QApplication::style()->standardIcon( QStyle :: SP_FileIcon );
fallback = QApplication::style()->standardIcon (QStyle :: SP_FileIcon);
suffixes[DISK] << QString::fromLatin1("iso");
fileIcons[DISK]= QIcon::fromTheme( QString::fromLatin1("media-optical"), fallback );
suffixes[DISK] << QString::fromLatin1("iso");
fileIcons[DISK]= QIcon::fromTheme (QString::fromLatin1("media-optical"), fallback);
const char * doc_types[] = {
"abw", "csv", "doc", "dvi", "htm", "html", "ini", "log", "odp",
"ods", "odt", "pdf", "ppt", "ps", "rtf", "tex", "txt", "xml" };
for( int i=0, n=sizeof(doc_types)/sizeof(doc_types[0]); i<n; ++i )
suffixes[DOCUMENT] << QString::fromLatin1(doc_types[i] );
fileIcons[DOCUMENT] = QIcon::fromTheme( QString::fromLatin1("text-x-generic"), fallback );
const char * doc_types[] = {
"abw", "csv", "doc", "dvi", "htm", "html", "ini", "log", "odp",
"ods", "odt", "pdf", "ppt", "ps", "rtf", "tex", "txt", "xml" };
for (int i=0, n=sizeof(doc_types)/sizeof(doc_types[0]); i<n; ++i)
suffixes[DOCUMENT] << QString::fromLatin1(doc_types[i]);
fileIcons[DOCUMENT] = QIcon::fromTheme (QString::fromLatin1("text-x-generic"), fallback);
const char * pic_types[] = {
"bmp", "gif", "jpg", "jpeg", "pcx", "png", "psd", "ras", "tga", "tiff" };
for( int i=0, n=sizeof(pic_types)/sizeof(pic_types[0]); i<n; ++i )
suffixes[PICTURE] << QString::fromLatin1(pic_types[i]);
fileIcons[PICTURE] = QIcon::fromTheme( QString::fromLatin1("image-x-generic"), fallback );
const char * pic_types[] = {
"bmp", "gif", "jpg", "jpeg", "pcx", "png", "psd", "ras", "tga", "tiff" };
for (int i=0, n=sizeof(pic_types)/sizeof(pic_types[0]); i<n; ++i)
suffixes[PICTURE] << QString::fromLatin1(pic_types[i]);
fileIcons[PICTURE] = QIcon::fromTheme (QString::fromLatin1("image-x-generic"), fallback);
const char * vid_types[] = {
"3gp", "asf", "avi", "mkv", "mov", "mpeg", "mpg", "mp4",
"ogm", "ogv", "qt", "rm", "wmv" };
for( int i=0, n=sizeof(vid_types)/sizeof(vid_types[0]); i<n; ++i )
suffixes[VIDEO] << QString::fromLatin1(vid_types[i]);
fileIcons[VIDEO] = QIcon::fromTheme( QString::fromLatin1("video-x-generic"), fallback );
const char * vid_types[] = {
"3gp", "asf", "avi", "mkv", "mov", "mpeg", "mpg", "mp4",
"ogm", "ogv", "qt", "rm", "wmv" };
for (int i=0, n=sizeof(vid_types)/sizeof(vid_types[0]); i<n; ++i)
suffixes[VIDEO] << QString::fromLatin1(vid_types[i]);
fileIcons[VIDEO] = QIcon::fromTheme (QString::fromLatin1("video-x-generic"), fallback);
const char * arc_types[] = {
"7z", "ace", "bz2", "cbz", "gz", "gzip", "lzma", "rar", "sft", "tar", "zip" };
for( int i=0, n=sizeof(arc_types)/sizeof(arc_types[0]); i<n; ++i )
suffixes[ARCHIVE] << QString::fromLatin1(arc_types[i]);
fileIcons[ARCHIVE] = QIcon::fromTheme( QString::fromLatin1("package-x-generic"), fallback );
const char * arc_types[] = {
"7z", "ace", "bz2", "cbz", "gz", "gzip", "lzma", "rar", "sft", "tar", "zip" };
for (int i=0, n=sizeof(arc_types)/sizeof(arc_types[0]); i<n; ++i)
suffixes[ARCHIVE] << QString::fromLatin1(arc_types[i]);
fileIcons[ARCHIVE] = QIcon::fromTheme (QString::fromLatin1("package-x-generic"), fallback);
const char * aud_types[] = {
"aac", "ac3", "aiff", "ape", "au", "flac", "m3u", "m4a", "mid", "midi", "mp2",
"mp3", "mpc", "nsf", "oga", "ogg", "ra", "ram", "shn", "voc", "wav", "wma" };
for( int i=0, n=sizeof(aud_types)/sizeof(aud_types[0]); i<n; ++i )
suffixes[AUDIO] << QString::fromLatin1(aud_types[i]);
fileIcons[AUDIO] = QIcon::fromTheme( QString::fromLatin1("audio-x-generic"), fallback );
const char * aud_types[] = {
"aac", "ac3", "aiff", "ape", "au", "flac", "m3u", "m4a", "mid", "midi", "mp2",
"mp3", "mpc", "nsf", "oga", "ogg", "ra", "ram", "shn", "voc", "wav", "wma" };
for (int i=0, n=sizeof(aud_types)/sizeof(aud_types[0]); i<n; ++i)
suffixes[AUDIO] << QString::fromLatin1(aud_types[i]);
fileIcons[AUDIO] = QIcon::fromTheme (QString::fromLatin1("audio-x-generic"), fallback);
const char * exe_types[] = { "bat", "cmd", "com", "exe" };
for( int i=0, n=sizeof(exe_types)/sizeof(exe_types[0]); i<n; ++i )
suffixes[APP] << QString::fromLatin1(exe_types[i]);
fileIcons[APP] = QIcon::fromTheme( QString::fromLatin1("application-x-executable"), fallback );
const char * exe_types[] = { "bat", "cmd", "com", "exe" };
for (int i=0, n=sizeof(exe_types)/sizeof(exe_types[0]); i<n; ++i)
suffixes[APP] << QString::fromLatin1(exe_types[i]);
fileIcons[APP] = QIcon::fromTheme (QString::fromLatin1("application-x-executable"), fallback);
}
QString suffix( QFileInfo( filename ).suffix( ).toLower( ) );
QString suffix (QFileInfo (filename).suffix ().toLower ());
for( int i=0; i<TYPE_COUNT; ++i )
if( suffixes[i].contains( suffix ) )
return fileIcons[i];
for (int i=0; i<TYPE_COUNT; ++i)
if (suffixes[i].contains (suffix))
return fileIcons[i];
return fallback;
return fallback;
#endif
}
bool
Utils :: isValidUtf8 ( const char *s )
Utils :: isValidUtf8 (const char *s)
{
int n; // number of bytes in a UTF-8 sequence
int n; // number of bytes in a UTF-8 sequence
for ( const char *c = s; *c; c += n )
for (const char *c = s; *c; c += n)
{
if ( (*c & 0x80) == 0x00 ) n = 1; // ASCII
else if ((*c & 0xc0) == 0x80) return false; // not valid
else if ((*c & 0xe0) == 0xc0) n = 2;
else if ((*c & 0xf0) == 0xe0) n = 3;
else if ((*c & 0xf8) == 0xf0) n = 4;
else if ((*c & 0xfc) == 0xf8) n = 5;
else if ((*c & 0xfe) == 0xfc) n = 6;
else return false;
for ( int m = 1; m < n; m++ )
if ( (c[m] & 0xc0) != 0x80 )
return false;
if ((*c & 0x80) == 0x00) n = 1; // ASCII
else if ((*c & 0xc0) == 0x80) return false; // not valid
else if ((*c & 0xe0) == 0xc0) n = 2;
else if ((*c & 0xf0) == 0xe0) n = 3;
else if ((*c & 0xf8) == 0xf0) n = 4;
else if ((*c & 0xfc) == 0xf8) n = 5;
else if ((*c & 0xfe) == 0xfc) n = 6;
else return false;
for (int m = 1; m < n; m++)
if ((c[m] & 0xc0) != 0x80)
return false;
}
return true;
return true;
}
QString

View File

@ -23,44 +23,47 @@
class Utils: public QObject
{
Q_OBJECT
Q_OBJECT
public:
Utils( ) { }
virtual ~Utils( ) { }
public:
Utils () {}
virtual ~Utils () {}
public:
static QString remoteFileChooser( QWidget * parent, const QString& title, const QString& myPath, bool dir, bool local );
static QIcon guessMimeIcon( const QString& filename );
// Test if string is UTF-8 or not
static bool isValidUtf8 ( const char *s );
public:
static QString remoteFileChooser (QWidget * parent, const QString& title, const QString& myPath, bool dir, bool local);
static QIcon guessMimeIcon (const QString& filename);
// Test if string is UTF-8 or not
static bool isValidUtf8 (const char *s);
static QString removeTrailingDirSeparator (const QString& path);
static QString removeTrailingDirSeparator (const QString& path);
// meh
static void toStderr( const QString& qstr );
// meh
static void toStderr (const QString& qstr);
///
/// URLs
///
///
/// URLs
///
static bool isMagnetLink( const QString& s ) { return s.startsWith( QString::fromUtf8( "magnet:?" ) ); }
static bool isMagnetLink (const QString& s)
{
return s.startsWith (QString::fromUtf8 ("magnet:?"));
}
static bool isHexHashcode( const QString& s )
{
if( s.length() != 40 ) return false;
foreach( QChar ch, s ) if( !isxdigit( ch.unicode() ) ) return false;
return true;
}
static bool isUriWithSupportedScheme( const QString& s )
{
static const QString ftp = QString::fromUtf8( "ftp://" );
static const QString http = QString::fromUtf8( "http://" );
static const QString https = QString::fromUtf8( "https://" );
return s.startsWith(http) || s.startsWith(https) || s.startsWith(ftp);
}
static bool isHexHashcode (const QString& s)
{
if (s.length() != 40)
return false;
foreach (QChar ch, s) if (!isxdigit (ch.unicode())) return false;
return true;
}
static bool isUriWithSupportedScheme (const QString& s)
{
static const QString ftp = QString::fromUtf8 ("ftp://");
static const QString http = QString::fromUtf8 ("http://");
static const QString https = QString::fromUtf8 ("https://");
return s.startsWith(http) || s.startsWith(https) || s.startsWith(ftp);
}
};
#endif

View File

@ -26,13 +26,13 @@
****
***/
WatchDir :: WatchDir( const TorrentModel& model ):
myModel( model ),
myWatcher( 0 )
WatchDir :: WatchDir (const TorrentModel& model):
myModel (model),
myWatcher (0)
{
}
WatchDir :: ~WatchDir( )
WatchDir :: ~WatchDir ()
{
}
@ -41,94 +41,105 @@ WatchDir :: ~WatchDir( )
***/
int
WatchDir :: metainfoTest( const QString& filename ) const
WatchDir :: metainfoTest (const QString& filename) const
{
int ret;
tr_info inf;
tr_ctor * ctor = tr_ctorNew( 0 );
int ret;
tr_info inf;
tr_ctor * ctor = tr_ctorNew (0);
// parse
tr_ctorSetMetainfoFromFile( ctor, filename.toUtf8().constData() );
const int err = tr_torrentParse( ctor, &inf );
if( err )
ret = ERROR;
else if( myModel.hasTorrent( QString::fromUtf8( inf.hashString ) ) )
ret = DUPLICATE;
else
ret = OK;
// parse
tr_ctorSetMetainfoFromFile (ctor, filename.toUtf8().constData());
const int err = tr_torrentParse( ctor, &inf );
if (err)
ret = ERROR;
else if (myModel.hasTorrent (QString::fromUtf8 (inf.hashString)))
ret = DUPLICATE;
else
ret = OK;
// cleanup
if( !err )
tr_metainfoFree( &inf );
tr_ctorFree( ctor );
return ret;
// cleanup
if (!err)
tr_metainfoFree (&inf);
tr_ctorFree (ctor);
return ret;
}
void
WatchDir :: onTimeout( )
WatchDir :: onTimeout ()
{
QTimer * t = qobject_cast<QTimer*>(sender());
const QString filename = t->objectName( );
if( metainfoTest( filename ) == OK )
emit torrentFileAdded( filename );
t->deleteLater( );
QTimer * t = qobject_cast<QTimer*>(sender());
const QString filename = t->objectName ();
if (metainfoTest (filename) == OK)
emit torrentFileAdded( filename );
t->deleteLater( );
}
void
WatchDir :: setPath( const QString& path, bool isEnabled )
WatchDir :: setPath (const QString& path, bool isEnabled)
{
// clear out any remnants of the previous watcher, if any
myWatchDirFiles.clear( );
if( myWatcher ) {
delete myWatcher;
myWatcher = 0;
// clear out any remnants of the previous watcher, if any
myWatchDirFiles.clear ();
if (myWatcher)
{
delete myWatcher;
myWatcher = 0;
}
// maybe create a new watcher
if( isEnabled ) {
myWatcher = new QFileSystemWatcher( );
myWatcher->addPath( path );
connect( myWatcher, SIGNAL(directoryChanged(const QString&)), this, SLOT(watcherActivated(const QString&)));
//std::cerr << "watching " << qPrintable(path) << " for new .torrent files" << std::endl;
watcherActivated( path ); // trigger the watchdir for .torrent files in there already
// maybe create a new watcher
if (isEnabled)
{
myWatcher = new QFileSystemWatcher ();
myWatcher->addPath( path );
connect (myWatcher, SIGNAL(directoryChanged(const QString&)),
this, SLOT(watcherActivated(const QString&)));
//std::cerr << "watching " << qPrintable(path) << " for new .torrent files" << std::endl;
watcherActivated (path); // trigger the watchdir for .torrent files in there already
}
}
void
WatchDir :: watcherActivated( const QString& path )
WatchDir :: watcherActivated (const QString& path)
{
const QDir dir(path);
const QDir dir(path);
// get the list of files currently in the watch directory
QSet<QString> files;
foreach( QString str, dir.entryList( QDir::Readable|QDir::Files ) )
files.insert( str );
// get the list of files currently in the watch directory
QSet<QString> files;
foreach (QString str, dir.entryList (QDir::Readable|QDir::Files))
files.insert (str);
// try to add any new files which end in .torrent
const QSet<QString> newFiles( files - myWatchDirFiles );
const QString torrentSuffix = QString::fromUtf8( ".torrent" );
foreach( QString name, newFiles ) {
if( name.endsWith( torrentSuffix, Qt::CaseInsensitive ) ) {
const QString filename = dir.absoluteFilePath( name );
switch( metainfoTest( filename ) ) {
case OK:
emit torrentFileAdded( filename );
break;
case DUPLICATE:
break;
case ERROR: {
// give the .torrent a few seconds to finish downloading
QTimer * t = new QTimer( this );
t->setObjectName( dir.absoluteFilePath( name ) );
t->setSingleShot( true );
connect( t, SIGNAL(timeout()), this, SLOT(onTimeout()));
t->start( 5000 );
// try to add any new files which end in .torrent
const QSet<QString> newFiles (files - myWatchDirFiles);
const QString torrentSuffix = QString::fromUtf8 (".torrent");
foreach (QString name, newFiles)
{
if (name.endsWith (torrentSuffix, Qt::CaseInsensitive))
{
const QString filename = dir.absoluteFilePath (name);
switch (metainfoTest (filename))
{
case OK:
emit torrentFileAdded (filename);
break;
case DUPLICATE:
break;
case ERROR:
{
// give the .torrent a few seconds to finish downloading
QTimer * t = new QTimer (this);
t->setObjectName (dir.absoluteFilePath (name));
t->setSingleShot (true);
connect( t, SIGNAL(timeout()), this, SLOT(onTimeout()));
t->start (5000);
}
}
}
}
// update our file list so that we can use it
// for comparison the next time around
myWatchDirFiles = files;
// update our file list so that we can use it
// for comparison the next time around
myWatchDirFiles = files;
}

View File

@ -22,31 +22,30 @@ class QFileSystemWatcher;
class WatchDir: public QObject
{
Q_OBJECT
Q_OBJECT
public:
WatchDir( const TorrentModel& );
~WatchDir( );
public:
WatchDir (const TorrentModel&);
~WatchDir ();
public:
void setPath( const QString& path, bool isEnabled );
public:
void setPath (const QString& path, bool isEnabled);
private:
enum { OK, DUPLICATE, ERROR };
int metainfoTest( const QString& filename ) const;
private:
enum { OK, DUPLICATE, ERROR };
int metainfoTest (const QString& filename) const;
signals:
void torrentFileAdded (QString filename);
signals:
void torrentFileAdded( QString filename );
private slots:
void watcherActivated (const QString& path);
void onTimeout ();
private slots:
void watcherActivated( const QString& path );
void onTimeout( );
private:
const TorrentModel& myModel;
QSet<QString> myWatchDirFiles;
QFileSystemWatcher * myWatcher;
private:
const TorrentModel& myModel;
QSet<QString> myWatchDirFiles;
QFileSystemWatcher * myWatcher;
};
#endif