#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;
}
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
#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;
}
public:
TrDBusAdaptor( MyApp* );
- virtual ~TrDBusAdaptor() { }
+ virtual ~TrDBusAdaptor() {}
public slots:
bool PresentWindow();
****
***/
-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;
}
/***
***/
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;
-
- 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 );
+ hasBeenScanned = true;
+
+ 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);
}
}
}
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 );
-
- // 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 ) );
+ // 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));
}
}
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 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 );
+ // 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 ();
+
+ // notify listeners
+ emit pixmapReady (host);
}
}
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
myIsWanted (0),
myHaveSize (0),
myTotalSize (size),
- myFirstUnhashedRow (0) { }
+ myFirstUnhashedRow (0) {}
public:
void appendChild (FileTreeItem *child);
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;
{
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)
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
}
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)
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");
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");
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());
}
/***
#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;
}
/***
***/
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 )
-{
- addLabel( label );
- if( control ) {
- addControl( control );
- QLabel * l = qobject_cast<QLabel*>( label );
- if( l != 0 )
- l->setBuddy( buddy ? buddy : control );
+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);
}
- ++myRow;
+
+ ++myRow;
}
void
-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 );
+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);
}
- ++myRow;
+
+ ++myRow;
}
void
-HIG :: finish( )
-{
- if( !myHasTall ) {
- QWidget * w = new QWidget( this );
- myGrid->addWidget( w, myRow, 0, 1, 2 );
- myGrid->setRowStretch( myRow, 100 );
- ++myRow;
+HIG :: finish ()
+{
+ if (!myHasTall)
+ {
+ QWidget * w = new QWidget (this);
+ myGrid->addWidget (w, myRow, 0, 1, 2);
+ myGrid->setRowStretch (myRow, 100);
+ ++myRow;
}
}
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
***/
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 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 );
+ // 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);
+
+ // 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;
-
- // 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 );
+ 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);
}
}
- // 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 );
-
- // 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() );
+ // 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);
+
+ // 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());
}
/***
***/
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( );
+ 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 )
+MakeDialog :: onFolderSelected (const QStringList& list)
{
- if( !list.empty( ) )
- onFolderSelected( list.front( ) );
+ if (!list.empty ())
+ onFolderSelected (list.front ());
}
+
void
-MakeDialog :: onFolderSelected( const QString& filename )
+MakeDialog :: onFolderSelected (const QString& filename)
{
- myFolder = Utils::removeTrailingDirSeparator (filename);
- myFolderButton->setText( QFileInfo(myFolder).fileName() );
- onSourceChanged( );
+ myFolder = Utils::removeTrailingDirSeparator (filename);
+ myFolderButton->setText (QFileInfo(myFolder).fileName());
+ onSourceChanged ();
}
void
-MakeDialog :: onDestinationClicked( )
+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( );
+ 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 )
+MakeDialog :: onDestinationSelected (const QStringList& list)
{
- if( !list.empty( ) )
- onDestinationSelected( list.front() );
+ if (!list.empty ())
+ onDestinationSelected (list.front());
}
void
-MakeDialog :: onDestinationSelected( const QString& filename )
+MakeDialog :: onDestinationSelected (const QString& filename)
{
- myDestination = Utils::removeTrailingDirSeparator (filename);
- myDestinationButton->setText( QFileInfo(myDestination).fileName() );
+ myDestination = Utils::removeTrailingDirSeparator (filename);
+ myDestinationButton->setText (QFileInfo(myDestination).fileName());
}
void
-MakeDialog :: enableBuddyWhenChecked( QRadioButton * box, QWidget * buddy )
+MakeDialog :: enableBuddyWhenChecked (QRadioButton * box, QWidget * buddy)
{
- connect( box, SIGNAL(toggled(bool)), buddy, SLOT(setEnabled(bool)) );
- buddy->setEnabled( box->isChecked( ) );
+ connect (box, SIGNAL(toggled(bool)), buddy, SLOT(setEnabled(bool)));
+ buddy->setEnabled (box->isChecked ());
}
void
-MakeDialog :: enableBuddyWhenChecked( QCheckBox * box, QWidget * buddy )
+MakeDialog :: enableBuddyWhenChecked (QCheckBox * box, QWidget * buddy)
{
- connect( box, SIGNAL(toggled(bool)), buddy, SLOT(setEnabled(bool)) );
- buddy->setEnabled( box->isChecked( ) );
+ 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;
}
}
***/
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() );
-
- 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 ) );
+ 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));
}
- 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 );
-
- connect( &myTimer, SIGNAL(timeout()), this, SLOT(onProgress()) );
-
- 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" ) );
-
- 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 );
-
- 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 );
-
- 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 );
-
- myCommentCheck = new QCheckBox( tr( "Co&mment" ) );
- myCommentEdit = new QLineEdit( );
- hig->addRow( myCommentCheck, myCommentEdit );
- enableBuddyWhenChecked( myCommentCheck, myCommentEdit );
-
- myPrivateCheck = hig->addWideCheckBox( tr( "&Private torrent" ), false );
-
- hig->finish( );
- top->addWidget( hig, 1 );
-
- myButtonBox = new QDialogButtonBox( QDialogButtonBox::Ok
- | QDialogButtonBox::Close );
- connect( myButtonBox, SIGNAL(clicked(QAbstractButton*)),
- this, SLOT(onButtonBoxClicked(QAbstractButton*)) );
-
- top->addWidget( myButtonBox );
- onSourceChanged( );
+ setAcceptDrops (true);
+
+ connect (&myTimer, SIGNAL(timeout()), this, SLOT(onProgress()));
+
+ 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"));
+
+ 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);
+
+ 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);
+
+ 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);
+
+ myCommentCheck = new QCheckBox (tr ("Co&mment"));
+ myCommentEdit = new QLineEdit ();
+ hig->addRow (myCommentCheck, myCommentEdit);
+ enableBuddyWhenChecked (myCommentCheck, myCommentEdit);
+
+ myPrivateCheck = hig->addWideCheckBox (tr ("&Private torrent"), false);
+
+ hig->finish ();
+ top->addWidget (hig, 1);
+
+ myButtonBox = new QDialogButtonBox (QDialogButtonBox::Ok
+ | QDialogButtonBox::Close);
+ connect (myButtonBox, SIGNAL(clicked(QAbstractButton*)),
+ this, SLOT(onButtonBoxClicked(QAbstractButton*)));
+
+ top->addWidget (myButtonBox);
+ onSourceChanged ();
}
-MakeDialog :: ~MakeDialog( )
+MakeDialog :: ~MakeDialog ()
{
- if( myBuilder )
- tr_metaInfoBuilderFree( myBuilder );
+ if (myBuilder)
+ tr_metaInfoBuilderFree (myBuilder);
}
/***
***/
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);
}
}
}
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
#/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
if (tag != myTag)
return;
- if ( (result == "success") && !myDelFile.isEmpty ())
+ if ((result == "success") && !myDelFile.isEmpty ())
{
QFile file (myDelFile);
file.setPermissions (QFile::ReadOwner | QFile::WriteOwner);
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:
namespace
{
- const char * PREF_KEY( "pref-key" );
+ const char * PREF_KEY ("pref-key");
};
void
-PrefsDialog :: checkBoxToggled( bool checked )
+PrefsDialog :: checkBoxToggled (bool checked)
{
- const int key( sender( )->property( PREF_KEY ).toInt( ) );
- setPref( key, checked );
+ const int key (sender ()->property (PREF_KEY).toInt ());
+ setPref (key, checked);
}
QCheckBox *
-PrefsDialog :: checkBoxNew( const QString& text, int key )
+PrefsDialog :: checkBoxNew (const QString& text, int key)
{
- QCheckBox * box = new QCheckBox( text );
- box->setChecked( myPrefs.getBool( key ) );
- box->setProperty( PREF_KEY, key );
- connect( box, SIGNAL(toggled(bool)), this, SLOT(checkBoxToggled(bool)));
- myWidgets.insert( key, box );
- return box;
+ QCheckBox * box = new QCheckBox (text);
+ box->setChecked (myPrefs.getBool (key));
+ box->setProperty (PREF_KEY, key);
+ connect (box, SIGNAL(toggled(bool)), this, SLOT(checkBoxToggled(bool)));
+ myWidgets.insert (key, box);
+ return box;
}
void
-PrefsDialog :: enableBuddyWhenChecked( QCheckBox * box, QWidget * buddy )
+PrefsDialog :: enableBuddyWhenChecked (QCheckBox * box, QWidget * buddy)
{
- connect( box, SIGNAL(toggled(bool)), buddy, SLOT(setEnabled(bool)) );
- buddy->setEnabled( box->isChecked( ) );
+ connect (box, SIGNAL(toggled(bool)), buddy, SLOT(setEnabled(bool)));
+ buddy->setEnabled (box->isChecked ());
}
void
PrefsDialog :: spinBoxEditingFinished()
{
- const QObject * spin = sender();
- const int key = spin->property( PREF_KEY ).toInt( );
- const QDoubleSpinBox * d = qobject_cast<const QDoubleSpinBox*>( spin );
- if( d )
- setPref( key, d->value( ) );
- else
- setPref( key, qobject_cast<const QSpinBox*>(spin)->value( ) );
+ const QObject * spin = sender();
+ const int key = spin->property (PREF_KEY).toInt ();
+ const QDoubleSpinBox * d = qobject_cast<const QDoubleSpinBox*> (spin);
+
+ if (d)
+ setPref (key, d->value ());
+ else
+ setPref (key, qobject_cast<const QSpinBox*>(spin)->value ());
}
QSpinBox *
-PrefsDialog :: spinBoxNew( int key, int low, int high, int step )
+PrefsDialog :: spinBoxNew (int key, int low, int high, int step)
{
- QSpinBox * spin = new QSpinBox( );
- spin->setRange( low, high );
- spin->setSingleStep( step );
- spin->setValue( myPrefs.getInt( key ) );
- spin->setProperty( PREF_KEY, key );
- connect( spin, SIGNAL(editingFinished()), this, SLOT(spinBoxEditingFinished()));
- myWidgets.insert( key, spin );
- return spin;
+ QSpinBox * spin = new QSpinBox ();
+ spin->setRange (low, high);
+ spin->setSingleStep (step);
+ spin->setValue (myPrefs.getInt (key));
+ spin->setProperty (PREF_KEY, key);
+ connect (spin, SIGNAL(editingFinished()), this, SLOT(spinBoxEditingFinished()));
+ myWidgets.insert (key, spin);
+ return spin;
}
QDoubleSpinBox *
-PrefsDialog :: doubleSpinBoxNew( int key, double low, double high, double step, int decimals )
+PrefsDialog :: doubleSpinBoxNew (int key, double low, double high, double step, int decimals)
{
- QDoubleSpinBox * spin = new QDoubleSpinBox( );
- spin->setRange( low, high );
- spin->setSingleStep( step );
- spin->setDecimals( decimals );
- spin->setValue( myPrefs.getDouble( key ) );
- spin->setProperty( PREF_KEY, key );
- connect( spin, SIGNAL(editingFinished()), this, SLOT(spinBoxEditingFinished()));
- myWidgets.insert( key, spin );
- return spin;
+ QDoubleSpinBox * spin = new QDoubleSpinBox ();
+ spin->setRange (low, high);
+ spin->setSingleStep (step);
+ spin->setDecimals (decimals);
+ spin->setValue (myPrefs.getDouble (key));
+ spin->setProperty (PREF_KEY, key);
+ connect (spin, SIGNAL(editingFinished()), this, SLOT(spinBoxEditingFinished()));
+ myWidgets.insert (key, spin);
+ return spin;
}
void
-PrefsDialog :: timeEditingFinished( )
+PrefsDialog :: timeEditingFinished ()
{
- QTimeEdit * e = qobject_cast<QTimeEdit*>(sender());
- if( e )
+ QTimeEdit * e = qobject_cast<QTimeEdit*>(sender());
+ if (e)
{
- const int key( e->property( PREF_KEY ).toInt( ) );
- const QTime time( e->time( ) );
- const int seconds( QTime().secsTo( time ) );
- setPref( key, seconds / 60 );
+ const int key (e->property (PREF_KEY).toInt ());
+ const QTime time (e->time ());
+ const int seconds (QTime().secsTo (time));
+ setPref (key, seconds / 60);
}
}
+
QTimeEdit*
-PrefsDialog :: timeEditNew( int key )
+PrefsDialog :: timeEditNew (int key)
{
- const int minutes( myPrefs.getInt( key ) );
- QTimeEdit * e = new QTimeEdit( );
- e->setDisplayFormat( QString::fromUtf8( "hh:mm" ) );
- e->setProperty( PREF_KEY, key );
- e->setTime( QTime().addSecs( minutes * 60 ) );
- myWidgets.insert( key, e );
- connect( e, SIGNAL(editingFinished()), this, SLOT(timeEditingFinished()) );
- return e;
+ const int minutes (myPrefs.getInt (key));
+ QTimeEdit * e = new QTimeEdit ();
+ e->setDisplayFormat (QString::fromUtf8 ("hh:mm"));
+ e->setProperty (PREF_KEY, key);
+ e->setTime (QTime().addSecs (minutes * 60));
+ myWidgets.insert (key, e);
+ connect (e, SIGNAL(editingFinished()), this, SLOT(timeEditingFinished()));
+ return e;
}
void
-PrefsDialog :: lineEditingFinished( )
+PrefsDialog :: lineEditingFinished ()
{
- QLineEdit * e = qobject_cast<QLineEdit*>(sender());
- if( e && e->isModified( ) )
+ QLineEdit * e = qobject_cast<QLineEdit*>(sender());
+ if (e && e->isModified ())
{
- const int key( e->property( PREF_KEY ).toInt( ) );
- const QString text( e->text() );
- setPref( key, text );
+ const int key (e->property (PREF_KEY).toInt ());
+ const QString text (e->text());
+ setPref (key, text);
}
}
+
QLineEdit*
-PrefsDialog :: lineEditNew( int key, int echoMode )
+PrefsDialog :: lineEditNew (int key, int echoMode)
{
- QLineEdit * e = new QLineEdit( myPrefs.getString( key ) );
- e->setProperty( PREF_KEY, key );
- e->setEchoMode( QLineEdit::EchoMode( echoMode ) );
- myWidgets.insert( key, e );
- connect( e, SIGNAL(editingFinished()), this, SLOT(lineEditingFinished()) );
- return e;
+ QLineEdit * e = new QLineEdit (myPrefs.getString (key));
+ e->setProperty (PREF_KEY, key);
+ e->setEchoMode (QLineEdit::EchoMode (echoMode));
+ myWidgets.insert (key, e);
+ connect (e, SIGNAL(editingFinished()), this, SLOT(lineEditingFinished()));
+ return e;
}
/***
***/
QWidget *
-PrefsDialog :: createRemoteTab( Session& session )
-{
- HIG * hig = new HIG( this );
- hig->addSectionTitle( tr( "Remote Control" ) );
- QWidget * w;
- QHBoxLayout * h = new QHBoxLayout( );
- QPushButton * b = new QPushButton( tr( "&Open web client" ) );
- connect( b, SIGNAL(clicked()), &session, SLOT(launchWebInterface()) );
- h->addWidget( b, 0, Qt::AlignRight );
- QWidget * l = checkBoxNew( tr( "Allow &remote access" ), Prefs::RPC_ENABLED );
- myUnsupportedWhenRemote << l;
- hig->addRow( l, h, 0 );
- l = hig->addRow( tr( "HTTP &port:" ), w = spinBoxNew( Prefs::RPC_PORT, 0, 65535, 1 ) );
- myWebWidgets << l << w;
- hig->addWideControl( w = checkBoxNew( tr( "Use &authentication" ), Prefs::RPC_AUTH_REQUIRED ) );
- myWebWidgets << w;
- l = hig->addRow( tr( "&Username:" ), w = lineEditNew( Prefs::RPC_USERNAME ) );
- myWebAuthWidgets << l << w;
- l = hig->addRow( tr( "Pass&word:" ), w = lineEditNew( Prefs::RPC_PASSWORD, QLineEdit::Password ) );
- myWebAuthWidgets << l << w;
- hig->addWideControl( w = checkBoxNew( tr( "Only allow these IP a&ddresses:" ), Prefs::RPC_WHITELIST_ENABLED ) );
- myWebWidgets << w;
- l = hig->addRow( tr( "Addresses:" ), w = lineEditNew( Prefs::RPC_WHITELIST ) );
- myWebWhitelistWidgets << l << w;
- myUnsupportedWhenRemote << myWebWidgets << myWebAuthWidgets << myWebWhitelistWidgets;
- hig->finish( );
- return hig;
+PrefsDialog :: createRemoteTab (Session& session)
+{
+ HIG * hig = new HIG (this);
+ hig->addSectionTitle (tr ("Remote Control"));
+ QWidget * w;
+ QHBoxLayout * h = new QHBoxLayout ();
+ QPushButton * b = new QPushButton (tr ("&Open web client"));
+ connect (b, SIGNAL(clicked()), &session, SLOT(launchWebInterface()));
+ h->addWidget (b, 0, Qt::AlignRight);
+ QWidget * l = checkBoxNew (tr ("Allow &remote access"), Prefs::RPC_ENABLED);
+ myUnsupportedWhenRemote << l;
+ hig->addRow (l, h, 0);
+ l = hig->addRow (tr ("HTTP &port:"), w = spinBoxNew (Prefs::RPC_PORT, 0, 65535, 1));
+ myWebWidgets << l << w;
+ hig->addWideControl (w = checkBoxNew (tr ("Use &authentication"), Prefs::RPC_AUTH_REQUIRED));
+ myWebWidgets << w;
+ l = hig->addRow (tr ("&Username:"), w = lineEditNew (Prefs::RPC_USERNAME));
+ myWebAuthWidgets << l << w;
+ l = hig->addRow (tr ("Pass&word:"), w = lineEditNew (Prefs::RPC_PASSWORD, QLineEdit::Password));
+ myWebAuthWidgets << l << w;
+ hig->addWideControl (w = checkBoxNew (tr ("Only allow these IP a&ddresses:"), Prefs::RPC_WHITELIST_ENABLED));
+ myWebWidgets << w;
+ l = hig->addRow (tr ("Addresses:"), w = lineEditNew (Prefs::RPC_WHITELIST));
+ myWebWhitelistWidgets << l << w;
+ myUnsupportedWhenRemote << myWebWidgets << myWebAuthWidgets << myWebWhitelistWidgets;
+ hig->finish ();
+ return hig;
}
/***
***/
void
-PrefsDialog :: altSpeedDaysEdited( int i )
+PrefsDialog :: altSpeedDaysEdited (int i)
{
- const int value = qobject_cast<QComboBox*>(sender())->itemData(i).toInt();
- setPref( Prefs::ALT_SPEED_LIMIT_TIME_DAY, value );
+ const int value = qobject_cast<QComboBox*>(sender())->itemData(i).toInt();
+ setPref (Prefs::ALT_SPEED_LIMIT_TIME_DAY, value);
}
QWidget *
-PrefsDialog :: createSpeedTab( )
-{
- QWidget *l, *r;
- HIG * hig = new HIG( this );
- hig->addSectionTitle( tr( "Speed Limits" ) );
- const QString speed_K_str = Formatter::unitStr( Formatter::SPEED, Formatter::KB );
-
- l = checkBoxNew( tr( "&Upload (%1):" ).arg( speed_K_str ), Prefs::USPEED_ENABLED );
- r = spinBoxNew( Prefs::USPEED, 0, INT_MAX, 5 );
- hig->addRow( l, r );
- enableBuddyWhenChecked( qobject_cast<QCheckBox*>(l), r );
-
- l = checkBoxNew( tr( "&Download (%1):" ).arg( speed_K_str ), Prefs::DSPEED_ENABLED );
- r = spinBoxNew( Prefs::DSPEED, 0, INT_MAX, 5 );
- hig->addRow( l, r );
- enableBuddyWhenChecked( qobject_cast<QCheckBox*>(l), r );
-
- hig->addSectionDivider( );
- QHBoxLayout * h = new QHBoxLayout;
- h->setSpacing( HIG :: PAD );
- QLabel * label = new QLabel;
- label->setPixmap( QPixmap( QString::fromUtf8( ":/icons/alt-limit-off.png" ) ) );
- label->setAlignment( Qt::AlignLeft|Qt::AlignVCenter );
- h->addWidget( label );
- label = new QLabel( tr( "Alternative Speed Limits" ) );
- label->setStyleSheet( QString::fromUtf8( "font: bold" ) );
- label->setAlignment( Qt::AlignLeft|Qt::AlignVCenter );
- h->addWidget( label );
- hig->addSectionTitle( h );
-
- QString s = tr( "<small>Override normal speed limits manually or at scheduled times</small>" );
- hig->addWideControl( new QLabel( s ) );
-
- s = tr( "U&pload (%1):" ).arg( speed_K_str );
- r = spinBoxNew( Prefs :: ALT_SPEED_LIMIT_UP, 0, INT_MAX, 5 );
- hig->addRow( s, r );
-
- s = tr( "Do&wnload (%1):" ).arg( speed_K_str );
- r = spinBoxNew( Prefs :: ALT_SPEED_LIMIT_DOWN, 0, INT_MAX, 5 );
- hig->addRow( s, r );
-
- QCheckBox * c = checkBoxNew( tr( "&Scheduled times:" ), Prefs::ALT_SPEED_LIMIT_TIME_ENABLED );
- h = new QHBoxLayout( );
- h->setSpacing( HIG::PAD );
- QWidget * w = timeEditNew( Prefs :: ALT_SPEED_LIMIT_TIME_BEGIN );
- h->addWidget( w, 1 );
- mySchedWidgets << w;
- QLabel * nd = new QLabel( tr("&to") );
- h->addWidget( nd );
- mySchedWidgets << nd;
- w = timeEditNew( Prefs :: ALT_SPEED_LIMIT_TIME_END );
- nd->setBuddy( w );
- h->addWidget( w, 1 );
- mySchedWidgets << w;
- hig->addRow( c, h, 0 );
-
- s = tr( "&On days:" );
- QComboBox * box = new QComboBox;
- const QIcon noIcon;
- box->addItem( noIcon, tr( "Every Day" ), QVariant( TR_SCHED_ALL ) );
- box->addItem( noIcon, tr( "Weekdays" ), QVariant( TR_SCHED_WEEKDAY ) );
- box->addItem( noIcon, tr( "Weekends" ), QVariant( TR_SCHED_WEEKEND ) );
- box->addItem( noIcon, tr( "Sunday" ), QVariant( TR_SCHED_SUN ) );
- box->addItem( noIcon, tr( "Monday" ), QVariant( TR_SCHED_MON ) );
- box->addItem( noIcon, tr( "Tuesday" ), QVariant( TR_SCHED_TUES ) );
- box->addItem( noIcon, tr( "Wednesday" ), QVariant( TR_SCHED_WED ) );
- box->addItem( noIcon, tr( "Thursday" ), QVariant( TR_SCHED_THURS ) );
- box->addItem( noIcon, tr( "Friday" ), QVariant( TR_SCHED_FRI ) );
- box->addItem( noIcon, tr( "Saturday" ), QVariant( TR_SCHED_SAT ) );
- box->setCurrentIndex( box->findData( myPrefs.getInt( Prefs :: ALT_SPEED_LIMIT_TIME_DAY ) ) );
- connect( box, SIGNAL(activated(int)), this, SLOT(altSpeedDaysEdited(int)) );
- w = hig->addRow( s, box );
- mySchedWidgets << w << box;
-
- hig->finish( );
- return hig;
+PrefsDialog :: createSpeedTab ()
+{
+ QWidget *l, *r;
+ HIG * hig = new HIG (this);
+ hig->addSectionTitle (tr ("Speed Limits"));
+ const QString speed_K_str = Formatter::unitStr (Formatter::SPEED, Formatter::KB);
+
+ l = checkBoxNew (tr ("&Upload (%1):").arg (speed_K_str), Prefs::USPEED_ENABLED);
+ r = spinBoxNew (Prefs::USPEED, 0, INT_MAX, 5);
+ hig->addRow (l, r);
+ enableBuddyWhenChecked (qobject_cast<QCheckBox*>(l), r);
+
+ l = checkBoxNew (tr ("&Download (%1):").arg (speed_K_str), Prefs::DSPEED_ENABLED);
+ r = spinBoxNew (Prefs::DSPEED, 0, INT_MAX, 5);
+ hig->addRow (l, r);
+ enableBuddyWhenChecked (qobject_cast<QCheckBox*>(l), r);
+
+ hig->addSectionDivider ();
+ QHBoxLayout * h = new QHBoxLayout;
+ h->setSpacing (HIG :: PAD);
+ QLabel * label = new QLabel;
+ label->setPixmap (QPixmap (QString::fromUtf8 (":/icons/alt-limit-off.png")));
+ label->setAlignment (Qt::AlignLeft|Qt::AlignVCenter);
+ h->addWidget (label);
+ label = new QLabel (tr ("Alternative Speed Limits"));
+ label->setStyleSheet (QString::fromUtf8 ("font: bold"));
+ label->setAlignment (Qt::AlignLeft|Qt::AlignVCenter);
+ h->addWidget (label);
+ hig->addSectionTitle (h);
+
+ QString s = tr ("<small>Override normal speed limits manually or at scheduled times</small>");
+ hig->addWideControl (new QLabel (s));
+
+ s = tr ("U&pload (%1):").arg (speed_K_str);
+ r = spinBoxNew (Prefs :: ALT_SPEED_LIMIT_UP, 0, INT_MAX, 5);
+ hig->addRow (s, r);
+
+ s = tr ("Do&wnload (%1):").arg (speed_K_str);
+ r = spinBoxNew (Prefs :: ALT_SPEED_LIMIT_DOWN, 0, INT_MAX, 5);
+ hig->addRow (s, r);
+
+ QCheckBox * c = checkBoxNew (tr ("&Scheduled times:"), Prefs::ALT_SPEED_LIMIT_TIME_ENABLED);
+ h = new QHBoxLayout ();
+ h->setSpacing (HIG::PAD);
+ QWidget * w = timeEditNew (Prefs :: ALT_SPEED_LIMIT_TIME_BEGIN);
+ h->addWidget (w, 1);
+ mySchedWidgets << w;
+ QLabel * nd = new QLabel (tr("&to"));
+ h->addWidget (nd);
+ mySchedWidgets << nd;
+ w = timeEditNew (Prefs :: ALT_SPEED_LIMIT_TIME_END);
+ nd->setBuddy (w);
+ h->addWidget (w, 1);
+ mySchedWidgets << w;
+ hig->addRow (c, h, 0);
+
+ s = tr ("&On days:");
+ QComboBox * box = new QComboBox;
+ const QIcon noIcon;
+ box->addItem (noIcon, tr ("Every Day"), QVariant (TR_SCHED_ALL));
+ box->addItem (noIcon, tr ("Weekdays"), QVariant (TR_SCHED_WEEKDAY));
+ box->addItem (noIcon, tr ("Weekends"), QVariant (TR_SCHED_WEEKEND));
+ box->addItem (noIcon, tr ("Sunday"), QVariant (TR_SCHED_SUN));
+ box->addItem (noIcon, tr ("Monday"), QVariant (TR_SCHED_MON));
+ box->addItem (noIcon, tr ("Tuesday"), QVariant (TR_SCHED_TUES));
+ box->addItem (noIcon, tr ("Wednesday"), QVariant (TR_SCHED_WED));
+ box->addItem (noIcon, tr ("Thursday"), QVariant (TR_SCHED_THURS));
+ box->addItem (noIcon, tr ("Friday"), QVariant (TR_SCHED_FRI));
+ box->addItem (noIcon, tr ("Saturday"), QVariant (TR_SCHED_SAT));
+ box->setCurrentIndex (box->findData (myPrefs.getInt (Prefs :: ALT_SPEED_LIMIT_TIME_DAY)));
+ connect (box, SIGNAL(activated(int)), this, SLOT(altSpeedDaysEdited(int)));
+ w = hig->addRow (s, box);
+ mySchedWidgets << w << box;
+
+ hig->finish ();
+ return hig;
}
/***
***/
QWidget *
-PrefsDialog :: createDesktopTab( )
+PrefsDialog :: createDesktopTab ()
{
- HIG * hig = new HIG( this );
- hig->addSectionTitle( tr( "Desktop" ) );
+ HIG * hig = new HIG (this);
+ hig->addSectionTitle (tr ("Desktop"));
- hig->addWideControl( checkBoxNew( tr( "Show Transmission icon in the ¬ification area" ), Prefs::SHOW_TRAY_ICON ) );
- hig->addWideControl( checkBoxNew( tr( "Start &minimized in notification area" ), Prefs::START_MINIMIZED ) );
+ hig->addWideControl (checkBoxNew (tr ("Show Transmission icon in the ¬ification area"), Prefs::SHOW_TRAY_ICON));
+ hig->addWideControl (checkBoxNew (tr ("Start &minimized in notification area"), Prefs::START_MINIMIZED));
- hig->addSectionDivider( );
- hig->addSectionTitle( tr ("Notification") );
+ hig->addSectionDivider ();
+ hig->addSectionTitle (tr ("Notification"));
- hig->addWideControl( checkBoxNew( tr( "Show a notification when torrents are a&dded" ), Prefs::SHOW_NOTIFICATION_ON_ADD ) );
- hig->addWideControl( checkBoxNew( tr( "Show a notification when torrents &finish" ), Prefs::SHOW_NOTIFICATION_ON_COMPLETE ) );
- hig->addWideControl( checkBoxNew( tr( "Play a &sound when torrents finish" ), Prefs::COMPLETE_SOUND_ENABLED ) );
+ hig->addWideControl (checkBoxNew (tr ("Show a notification when torrents are a&dded"), Prefs::SHOW_NOTIFICATION_ON_ADD));
+ hig->addWideControl (checkBoxNew (tr ("Show a notification when torrents &finish"), Prefs::SHOW_NOTIFICATION_ON_COMPLETE));
+ hig->addWideControl (checkBoxNew (tr ("Play a &sound when torrents finish"), Prefs::COMPLETE_SOUND_ENABLED));
- hig->finish( );
- return hig;
+ hig->finish ();
+ return hig;
}
/***
***/
void
-PrefsDialog :: onPortTested( bool isOpen )
+PrefsDialog :: onPortTested (bool isOpen)
{
- myPortButton->setEnabled( true );
- myWidgets[Prefs::PEER_PORT]->setEnabled( true );
- myPortLabel->setText( isOpen ? tr( "Port is <b>open</b>" )
- : tr( "Port is <b>closed</b>" ) );
+ myPortButton->setEnabled (true);
+ myWidgets[Prefs::PEER_PORT]->setEnabled (true);
+ myPortLabel->setText (isOpen ? tr ("Port is <b>open</b>")
+ : tr ("Port is <b>closed</b>"));
}
void
-PrefsDialog :: onPortTest( )
+PrefsDialog :: onPortTest ()
{
- myPortLabel->setText( tr( "Testing TCP Port..." ) );
- myPortButton->setEnabled( false );
- myWidgets[Prefs::PEER_PORT]->setEnabled( false );
- mySession.portTest( );
+ myPortLabel->setText (tr ("Testing TCP Port..."));
+ myPortButton->setEnabled (false);
+ myWidgets[Prefs::PEER_PORT]->setEnabled (false);
+ mySession.portTest ();
}
QWidget *
-PrefsDialog :: createNetworkTab( )
-{
- HIG * hig = new HIG( this );
- hig->addSectionTitle( tr( "Incoming Peers" ) );
-
- QSpinBox * s = spinBoxNew( Prefs::PEER_PORT, 1, 65535, 1 );
- QHBoxLayout * h = new QHBoxLayout( );
- QPushButton * b = myPortButton = new QPushButton( tr( "Te&st Port" ) );
- QLabel * l = myPortLabel = new QLabel( tr( "Status unknown" ) );
- h->addWidget( l );
- h->addSpacing( HIG :: PAD_BIG );
- h->addWidget( b );
- h->setStretchFactor( l, 1 );
- connect( b, SIGNAL(clicked(bool)), this, SLOT(onPortTest()));
- connect( &mySession, SIGNAL(portTested(bool)), this, SLOT(onPortTested(bool)));
-
- hig->addRow( tr( "&Port for incoming connections:" ), s );
- hig->addRow( QString(), h, 0 );
- hig->addWideControl( checkBoxNew( tr( "Pick a &random port every time Transmission is started" ), Prefs :: PEER_PORT_RANDOM_ON_START ) );
- hig->addWideControl( checkBoxNew( tr( "Use UPnP or NAT-PMP port &forwarding from my router" ), Prefs::PORT_FORWARDING ) );
-
- hig->addSectionDivider( );
- hig->addSectionTitle( tr( "Peer Limits" ) );
- hig->addRow( tr( "Maximum peers per &torrent:" ), spinBoxNew( Prefs::PEER_LIMIT_TORRENT, 1, FD_SETSIZE, 5 ) );
- hig->addRow( tr( "Maximum peers &overall:" ), spinBoxNew( Prefs::PEER_LIMIT_GLOBAL, 1, FD_SETSIZE, 5 ) );
-
- hig->addSectionDivider( );
- hig->addSectionTitle( tr( "Options" ) );
-
- QWidget * w;
- hig->addWideControl( w = checkBoxNew( tr( "Enable &uTP for peer connections" ), Prefs::UTP_ENABLED ) );
- w->setToolTip( tr( "uTP is a tool for reducing network congestion." ) );
- hig->addWideControl( w = checkBoxNew( tr( "Use PE&X to find more peers" ), Prefs::PEX_ENABLED ) );
- w->setToolTip( tr( "PEX is a tool for exchanging peer lists with the peers you're connected to." ) );
- hig->addWideControl( w = checkBoxNew( tr( "Use &DHT to find more peers" ), Prefs::DHT_ENABLED ) );
- w->setToolTip( tr( "DHT is a tool for finding peers without a tracker." ) );
- hig->addWideControl( w = checkBoxNew( tr( "Use &Local Peer Discovery to find more peers" ), Prefs::LPD_ENABLED ) );
- w->setToolTip( tr( "LPD is a tool for finding peers on your local network." ) );
-
- hig->finish( );
- return hig;
+PrefsDialog :: createNetworkTab ()
+{
+ HIG * hig = new HIG (this);
+ hig->addSectionTitle (tr ("Incoming Peers"));
+
+ QSpinBox * s = spinBoxNew (Prefs::PEER_PORT, 1, 65535, 1);
+ QHBoxLayout * h = new QHBoxLayout ();
+ QPushButton * b = myPortButton = new QPushButton (tr ("Te&st Port"));
+ QLabel * l = myPortLabel = new QLabel (tr ("Status unknown"));
+ h->addWidget (l);
+ h->addSpacing (HIG :: PAD_BIG);
+ h->addWidget (b);
+ h->setStretchFactor (l, 1);
+ connect (b, SIGNAL(clicked(bool)), this, SLOT(onPortTest()));
+ connect (&mySession, SIGNAL(portTested(bool)), this, SLOT(onPortTested(bool)));
+
+ hig->addRow (tr ("&Port for incoming connections:"), s);
+ hig->addRow (QString(), h, 0);
+ hig->addWideControl (checkBoxNew (tr ("Pick a &random port every time Transmission is started"), Prefs :: PEER_PORT_RANDOM_ON_START));
+ hig->addWideControl (checkBoxNew (tr ("Use UPnP or NAT-PMP port &forwarding from my router"), Prefs::PORT_FORWARDING));
+
+ hig->addSectionDivider ();
+ hig->addSectionTitle (tr ("Peer Limits"));
+ hig->addRow (tr ("Maximum peers per &torrent:"), spinBoxNew (Prefs::PEER_LIMIT_TORRENT, 1, FD_SETSIZE, 5));
+ hig->addRow (tr ("Maximum peers &overall:"), spinBoxNew (Prefs::PEER_LIMIT_GLOBAL, 1, FD_SETSIZE, 5));
+
+ hig->addSectionDivider ();
+ hig->addSectionTitle (tr ("Options"));
+
+ QWidget * w;
+ hig->addWideControl (w = checkBoxNew (tr ("Enable &uTP for peer connections"), Prefs::UTP_ENABLED));
+ w->setToolTip (tr ("uTP is a tool for reducing network congestion."));
+ hig->addWideControl (w = checkBoxNew (tr ("Use PE&X to find more peers"), Prefs::PEX_ENABLED));
+ w->setToolTip (tr ("PEX is a tool for exchanging peer lists with the peers you're connected to."));
+ hig->addWideControl (w = checkBoxNew (tr ("Use &DHT to find more peers"), Prefs::DHT_ENABLED));
+ w->setToolTip (tr ("DHT is a tool for finding peers without a tracker."));
+ hig->addWideControl (w = checkBoxNew (tr ("Use &Local Peer Discovery to find more peers"), Prefs::LPD_ENABLED));
+ w->setToolTip (tr ("LPD is a tool for finding peers on your local network."));
+
+ hig->finish ();
+ return hig;
}
/***
***/
void
-PrefsDialog :: onBlocklistDialogDestroyed( QObject * o )
+PrefsDialog :: onBlocklistDialogDestroyed (QObject * o)
{
- Q_UNUSED( o );
+ Q_UNUSED (o);
- myBlocklistDialog = 0;
+ myBlocklistDialog = 0;
}
void
-PrefsDialog :: onUpdateBlocklistCancelled( )
+PrefsDialog :: onUpdateBlocklistCancelled ()
{
- disconnect( &mySession, SIGNAL(blocklistUpdated(int)), this, SLOT(onBlocklistUpdated(int))) ;
- myBlocklistDialog->deleteLater( );
+ disconnect (&mySession, SIGNAL(blocklistUpdated(int)), this, SLOT(onBlocklistUpdated(int)));
+ myBlocklistDialog->deleteLater ();
}
void
-PrefsDialog :: onBlocklistUpdated( int n )
+PrefsDialog :: onBlocklistUpdated (int n)
{
- myBlocklistDialog->setText( tr( "<b>Update succeeded!</b><p>Blocklist now has %Ln rules.", 0, n ) );
- myBlocklistDialog->setTextFormat( Qt::RichText );
+ myBlocklistDialog->setText (tr ("<b>Update succeeded!</b><p>Blocklist now has %Ln rules.", 0, n));
+ myBlocklistDialog->setTextFormat (Qt::RichText);
}
void
-PrefsDialog :: onUpdateBlocklistClicked( )
+PrefsDialog :: onUpdateBlocklistClicked ()
{
- myBlocklistDialog = new QMessageBox( QMessageBox::Information,
- QString(),
- tr( "<b>Update Blocklist</b><p>Getting new blocklist..." ),
- QMessageBox::Close,
- this );
- connect( myBlocklistDialog, SIGNAL(rejected()), this, SLOT(onUpdateBlocklistCancelled()) );
- connect( &mySession, SIGNAL(blocklistUpdated(int)), this, SLOT(onBlocklistUpdated(int))) ;
- myBlocklistDialog->show( );
- mySession.updateBlocklist( );
+ myBlocklistDialog = new QMessageBox (QMessageBox::Information,
+ QString(),
+ tr ("<b>Update Blocklist</b><p>Getting new blocklist..."),
+ QMessageBox::Close,
+ this);
+ connect (myBlocklistDialog, SIGNAL(rejected()), this, SLOT(onUpdateBlocklistCancelled()));
+ connect (&mySession, SIGNAL(blocklistUpdated(int)), this, SLOT(onBlocklistUpdated(int)));
+ myBlocklistDialog->show ();
+ mySession.updateBlocklist ();
}
void
-PrefsDialog :: encryptionEdited( int i )
+PrefsDialog :: encryptionEdited (int i)
{
- const int value( qobject_cast<QComboBox*>(sender())->itemData(i).toInt( ) );
- setPref( Prefs::ENCRYPTION, value );
+ const int value (qobject_cast<QComboBox*>(sender())->itemData(i).toInt ());
+ setPref (Prefs::ENCRYPTION, value);
}
QWidget *
-PrefsDialog :: createPrivacyTab( )
+PrefsDialog :: createPrivacyTab ()
{
- QWidget * w;
- HIG * hig = new HIG( this );
+ QWidget * w;
+ HIG * hig = new HIG (this);
- hig->addSectionTitle( tr( "Encryption" ) );
+ hig->addSectionTitle (tr ("Encryption"));
- QComboBox * box = new QComboBox( );
- box->addItem( tr( "Allow encryption" ), 0 );
- box->addItem( tr( "Prefer encryption" ), 1 );
- box->addItem( tr( "Require encryption" ), 2 );
- myWidgets.insert( Prefs :: ENCRYPTION, box );
- connect( box, SIGNAL(activated(int)), this, SLOT(encryptionEdited(int)));
+ QComboBox * box = new QComboBox ();
+ box->addItem (tr ("Allow encryption"), 0);
+ box->addItem (tr ("Prefer encryption"), 1);
+ box->addItem (tr ("Require encryption"), 2);
+ myWidgets.insert (Prefs :: ENCRYPTION, box);
+ connect (box, SIGNAL(activated(int)), this, SLOT(encryptionEdited(int)));
- hig->addRow( tr( "&Encryption mode:" ), box );
+ hig->addRow (tr ("&Encryption mode:"), box);
- hig->addSectionDivider( );
- hig->addSectionTitle( tr( "Blocklist" ) );
+ hig->addSectionDivider ();
+ hig->addSectionTitle (tr ("Blocklist"));
- QWidget * l = checkBoxNew( tr("Enable &blocklist:"), Prefs::BLOCKLIST_ENABLED );
- QWidget * e = lineEditNew( Prefs::BLOCKLIST_URL );
- myBlockWidgets << e;
- hig->addRow( l, e );
+ QWidget * l = checkBoxNew (tr("Enable &blocklist:"), Prefs::BLOCKLIST_ENABLED);
+ QWidget * e = lineEditNew (Prefs::BLOCKLIST_URL);
+ myBlockWidgets << e;
+ hig->addRow (l, e);
- l = myBlocklistLabel = new QLabel( );
- myBlockWidgets << l;
- w = new QPushButton( tr( "&Update" ) );
- connect( w, SIGNAL(clicked(bool)), this, SLOT(onUpdateBlocklistClicked()));
- myBlockWidgets << w;
- QHBoxLayout * h = new QHBoxLayout( );
- h->addWidget( l );
- h->addStretch( 1 );
- h->addWidget( w );
- hig->addWideControl( h );
+ l = myBlocklistLabel = new QLabel ();
+ myBlockWidgets << l;
+ w = new QPushButton (tr ("&Update"));
+ connect (w, SIGNAL(clicked(bool)), this, SLOT(onUpdateBlocklistClicked()));
+ myBlockWidgets << w;
+ QHBoxLayout * h = new QHBoxLayout ();
+ h->addWidget (l);
+ h->addStretch (1);
+ h->addWidget (w);
+ hig->addWideControl (h);
- l = checkBoxNew( tr( "Enable &automatic updates" ), Prefs::BLOCKLIST_UPDATES_ENABLED );
- myBlockWidgets << l;
- hig->addWideControl( l );
+ l = checkBoxNew (tr ("Enable &automatic updates"), Prefs::BLOCKLIST_UPDATES_ENABLED);
+ myBlockWidgets << l;
+ hig->addWideControl (l);
- hig->finish( );
- updateBlocklistLabel( );
- return hig;
+ hig->finish ();
+ updateBlocklistLabel ();
+ return hig;
}
/***
***/
void
-PrefsDialog :: onScriptClicked( void )
+PrefsDialog :: onScriptClicked (void)
{
- const QString title = tr( "Select \"Torrent Done\" Script" );
- const QString myPath = myPrefs.getString( Prefs::SCRIPT_TORRENT_DONE_FILENAME );
- const QString path = Utils::remoteFileChooser( this, title, myPath, false, mySession.isServer() );
+ const QString title = tr ("Select \"Torrent Done\" Script");
+ const QString myPath = myPrefs.getString (Prefs::SCRIPT_TORRENT_DONE_FILENAME);
+ const QString path = Utils::remoteFileChooser (this, title, myPath, false, mySession.isServer());
- if( !path.isEmpty() )
- onLocationSelected( path, Prefs::SCRIPT_TORRENT_DONE_FILENAME );
+ if (!path.isEmpty())
+ onLocationSelected (path, Prefs::SCRIPT_TORRENT_DONE_FILENAME);
}
void
-PrefsDialog :: onIncompleteClicked( void )
+PrefsDialog :: onIncompleteClicked (void)
{
- const QString title = tr( "Select Incomplete Directory" );
- const QString myPath = myPrefs.getString( Prefs::INCOMPLETE_DIR );
- const QString path = Utils::remoteFileChooser( this, title, myPath, true, mySession.isServer() );
+ const QString title = tr ("Select Incomplete Directory");
+ const QString myPath = myPrefs.getString (Prefs::INCOMPLETE_DIR);
+ const QString path = Utils::remoteFileChooser (this, title, myPath, true, mySession.isServer());
- if( !path.isEmpty() )
- onLocationSelected( path, Prefs::INCOMPLETE_DIR );
+ if (!path.isEmpty())
+ onLocationSelected (path, Prefs::INCOMPLETE_DIR);
}
void
-PrefsDialog :: onWatchClicked( void )
+PrefsDialog :: onWatchClicked (void)
{
- const QString title = tr( "Select Watch Directory" );
- const QString myPath = myPrefs.getString( Prefs::DIR_WATCH );
- const QString path = Utils::remoteFileChooser( this, title, myPath, true, true );
+ const QString title = tr ("Select Watch Directory");
+ const QString myPath = myPrefs.getString (Prefs::DIR_WATCH);
+ const QString path = Utils::remoteFileChooser (this, title, myPath, true, true);
- if( !path.isEmpty() )
- onLocationSelected( path, Prefs::DIR_WATCH );
+ if (!path.isEmpty())
+ onLocationSelected (path, Prefs::DIR_WATCH);
}
void
-PrefsDialog :: onDestinationClicked( void )
+PrefsDialog :: onDestinationClicked (void)
{
- const QString title = tr( "Select Destination" );
- const QString myPath = myPrefs.getString( Prefs::DOWNLOAD_DIR );
- const QString path = Utils::remoteFileChooser( this, title, myPath, true, mySession.isServer() );
+ const QString title = tr ("Select Destination");
+ const QString myPath = myPrefs.getString (Prefs::DOWNLOAD_DIR);
+ const QString path = Utils::remoteFileChooser (this, title, myPath, true, mySession.isServer());
- if( !path.isEmpty() )
- onLocationSelected( path, Prefs::DOWNLOAD_DIR );
+ if (!path.isEmpty())
+ onLocationSelected (path, Prefs::DOWNLOAD_DIR);
}
void
-PrefsDialog :: onLocationSelected( const QString& path, int key )
+PrefsDialog :: onLocationSelected (const QString& path, int key)
{
- setPref( key, path );
+ setPref (key, path);
}
QWidget *
-PrefsDialog :: createSeedingTab( )
+PrefsDialog :: createSeedingTab ()
{
- const int iconSize( style( )->pixelMetric( QStyle :: PM_SmallIconSize ) );
- const QFileIconProvider iconProvider;
- const QIcon folderIcon = iconProvider.icon( QFileIconProvider::Folder );
- const QPixmap folderPixmap = folderIcon.pixmap( iconSize );
- const QIcon fileIcon = iconProvider.icon( QFileIconProvider::File );
- const QPixmap filePixmap = fileIcon.pixmap( iconSize );
+ const int iconSize (style ()->pixelMetric (QStyle :: PM_SmallIconSize));
+ const QFileIconProvider iconProvider;
+ const QIcon folderIcon = iconProvider.icon (QFileIconProvider::Folder);
+ const QPixmap folderPixmap = folderIcon.pixmap (iconSize);
+ const QIcon fileIcon = iconProvider.icon (QFileIconProvider::File);
+ const QPixmap filePixmap = fileIcon.pixmap (iconSize);
- QWidget *l, *r;
- HIG * hig = new HIG( this );
- hig->addSectionTitle( tr( "Limits" ) );
+ QWidget *l, *r;
+ HIG * hig = new HIG (this);
+ hig->addSectionTitle (tr ("Limits"));
- l = checkBoxNew( tr( "Stop seeding at &ratio:" ), Prefs::RATIO_ENABLED );
- r = doubleSpinBoxNew( Prefs::RATIO, 0, INT_MAX, 0.5, 2 );
- hig->addRow( l, r );
- enableBuddyWhenChecked( qobject_cast<QCheckBox*>(l), r );
+ l = checkBoxNew (tr ("Stop seeding at &ratio:"), Prefs::RATIO_ENABLED);
+ r = doubleSpinBoxNew (Prefs::RATIO, 0, INT_MAX, 0.5, 2);
+ hig->addRow (l, r);
+ enableBuddyWhenChecked (qobject_cast<QCheckBox*>(l), r);
- l = checkBoxNew( tr( "Stop seeding if idle for &N minutes:" ), Prefs::IDLE_LIMIT_ENABLED );
- r = spinBoxNew( Prefs::IDLE_LIMIT, 1, INT_MAX, 5 );
- hig->addRow( l, r );
- enableBuddyWhenChecked( qobject_cast<QCheckBox*>(l), r );
+ l = checkBoxNew (tr ("Stop seeding if idle for &N minutes:"), Prefs::IDLE_LIMIT_ENABLED);
+ r = spinBoxNew (Prefs::IDLE_LIMIT, 1, INT_MAX, 5);
+ hig->addRow (l, r);
+ enableBuddyWhenChecked (qobject_cast<QCheckBox*>(l), r);
- hig->finish( );
- return hig;
+ hig->finish ();
+ return hig;
}
QWidget *
-PrefsDialog :: createDownloadingTab( )
-{
- const int iconSize( style( )->pixelMetric( QStyle :: PM_SmallIconSize ) );
- const QFileIconProvider iconProvider;
- const QIcon folderIcon = iconProvider.icon( QFileIconProvider::Folder );
- const QPixmap folderPixmap = folderIcon.pixmap( iconSize );
- const QIcon fileIcon = iconProvider.icon( QFileIconProvider::File );
- const QPixmap filePixmap = fileIcon.pixmap( iconSize );
-
- QWidget * l;
- QPushButton * b;
- HIG * hig = new HIG( this );
- hig->addSectionTitle( tr( "Adding" ) );
-
- l = checkBoxNew( tr( "Automatically add .torrent files &from:" ), Prefs::DIR_WATCH_ENABLED );
- b = myWatchButton = new QPushButton;
- b->setIcon( folderPixmap );
- b->setStyleSheet( QString::fromUtf8( "text-align: left; padding-left: 5; padding-right: 5" ) );
- connect( b, SIGNAL(clicked(bool)), this, SLOT(onWatchClicked(void)) );
- hig->addRow( l, b );
- enableBuddyWhenChecked( qobject_cast<QCheckBox*>(l), b );
-
- hig->addWideControl( checkBoxNew( tr( "Show the Torrent Options &dialog" ), Prefs::OPTIONS_PROMPT ) );
-
- hig->addWideControl( checkBoxNew( tr( "&Start added torrents" ), Prefs::START ) );
-
- hig->addWideControl( checkBoxNew( tr( "Mo&ve the .torrent file to the trash" ), Prefs::TRASH_ORIGINAL ) );
-
- b = myDestinationButton = new QPushButton;
- b->setIcon( folderPixmap );
- b->setStyleSheet( QString::fromUtf8( "text-align: left; padding-left: 5; padding-right: 5" ) );
- connect( b, SIGNAL(clicked(bool)), this, SLOT(onDestinationClicked(void)) );
- hig->addRow( tr( "Save to &Location:" ), b );
-
- const QString downloadDir (myPrefs.getString(Prefs::DOWNLOAD_DIR));
- l = myFreespaceLabel = new FreespaceLabel (mySession, downloadDir, this);
- QHBoxLayout * h = new QHBoxLayout ();
- h->addStretch (1);
- h->addWidget (l);
- hig->addWideControl (h);
-
- hig->addSectionDivider( );
- hig->addSectionTitle( tr( "Download Queue" ) );
+PrefsDialog :: createDownloadingTab ()
+{
+ const int iconSize (style ()->pixelMetric (QStyle :: PM_SmallIconSize));
+ const QFileIconProvider iconProvider;
+ const QIcon folderIcon = iconProvider.icon (QFileIconProvider::Folder);
+ const QPixmap folderPixmap = folderIcon.pixmap (iconSize);
+ const QIcon fileIcon = iconProvider.icon (QFileIconProvider::File);
+ const QPixmap filePixmap = fileIcon.pixmap (iconSize);
+
+ QWidget * l;
+ QPushButton * b;
+ HIG * hig = new HIG (this);
+ hig->addSectionTitle (tr ("Adding"));
+
+ l = checkBoxNew (tr ("Automatically add .torrent files &from:"), Prefs::DIR_WATCH_ENABLED);
+ b = myWatchButton = new QPushButton;
+ b->setIcon (folderPixmap);
+ b->setStyleSheet (QString::fromUtf8 ("text-align: left; padding-left: 5; padding-right: 5"));
+ connect (b, SIGNAL(clicked(bool)), this, SLOT(onWatchClicked(void)));
+ hig->addRow (l, b);
+ enableBuddyWhenChecked (qobject_cast<QCheckBox*>(l), b);
+
+ hig->addWideControl (checkBoxNew (tr ("Show the Torrent Options &dialog"), Prefs::OPTIONS_PROMPT));
+
+ hig->addWideControl (checkBoxNew (tr ("&Start added torrents"), Prefs::START));
+
+ hig->addWideControl (checkBoxNew (tr ("Mo&ve the .torrent file to the trash"), Prefs::TRASH_ORIGINAL));
+
+ b = myDestinationButton = new QPushButton;
+ b->setIcon (folderPixmap);
+ b->setStyleSheet (QString::fromUtf8 ("text-align: left; padding-left: 5; padding-right: 5"));
+ connect (b, SIGNAL(clicked(bool)), this, SLOT(onDestinationClicked(void)));
+ hig->addRow (tr ("Save to &Location:"), b);
+
+ const QString downloadDir (myPrefs.getString(Prefs::DOWNLOAD_DIR));
+ l = myFreespaceLabel = new FreespaceLabel (mySession, downloadDir, this);
+ QHBoxLayout * h = new QHBoxLayout ();
+ h->addStretch (1);
+ h->addWidget (l);
+ hig->addWideControl (h);
+
+ hig->addSectionDivider ();
+ hig->addSectionTitle (tr ("Download Queue"));
- hig->addRow( tr( "Ma&ximum active downloads:" ), spinBoxNew( Prefs::DOWNLOAD_QUEUE_SIZE, 1, INT_MAX, 1 ) );
- hig->addRow( tr( "Downloads sharing data in the last &N minutes are active:" ), spinBoxNew( Prefs::QUEUE_STALLED_MINUTES, 1, INT_MAX, 10 ) );
+ hig->addRow (tr ("Ma&ximum active downloads:"), spinBoxNew (Prefs::DOWNLOAD_QUEUE_SIZE, 1, INT_MAX, 1));
+ hig->addRow (tr ("Downloads sharing data in the last &N minutes are active:"), spinBoxNew (Prefs::QUEUE_STALLED_MINUTES, 1, INT_MAX, 10));
- hig->addSectionDivider( );
- hig->addSectionTitle( tr( "Incomplete" ) );
+ hig->addSectionDivider ();
+ hig->addSectionTitle (tr ("Incomplete"));
- hig->addWideControl( checkBoxNew( tr( "Append \".&part\" to incomplete files' names" ), Prefs::RENAME_PARTIAL_FILES ) );
+ hig->addWideControl (checkBoxNew (tr ("Append \".&part\" to incomplete files' names"), Prefs::RENAME_PARTIAL_FILES));
- l = myIncompleteCheckbox = checkBoxNew( tr( "Keep &incomplete files in:" ), Prefs::INCOMPLETE_DIR_ENABLED );
- b = myIncompleteButton = new QPushButton;
- b->setIcon( folderPixmap );
- b->setStyleSheet( QString::fromUtf8( "text-align: left; padding-left: 5; padding-right: 5" ) );
- connect( b, SIGNAL(clicked(bool)), this, SLOT(onIncompleteClicked(void)) );
- hig->addRow( myIncompleteCheckbox, b );
- enableBuddyWhenChecked( qobject_cast<QCheckBox*>(l), b );
+ l = myIncompleteCheckbox = checkBoxNew (tr ("Keep &incomplete files in:"), Prefs::INCOMPLETE_DIR_ENABLED);
+ b = myIncompleteButton = new QPushButton;
+ b->setIcon (folderPixmap);
+ b->setStyleSheet (QString::fromUtf8 ("text-align: left; padding-left: 5; padding-right: 5"));
+ connect (b, SIGNAL(clicked(bool)), this, SLOT(onIncompleteClicked(void)));
+ hig->addRow (myIncompleteCheckbox, b);
+ enableBuddyWhenChecked (qobject_cast<QCheckBox*>(l), b);
- l = myTorrentDoneScriptCheckbox = checkBoxNew( tr( "Call scrip&t when torrent is completed:" ), Prefs::SCRIPT_TORRENT_DONE_ENABLED );
- b = myTorrentDoneScriptButton = new QPushButton;
- b->setIcon( filePixmap );
- b->setStyleSheet( QString::fromUtf8( "text-align: left; padding-left: 5; padding-right: 5" ) );
- connect( b, SIGNAL(clicked(bool)), this, SLOT(onScriptClicked(void)) );
- hig->addRow( myTorrentDoneScriptCheckbox, b );
- enableBuddyWhenChecked( qobject_cast<QCheckBox*>(l), b );
+ l = myTorrentDoneScriptCheckbox = checkBoxNew (tr ("Call scrip&t when torrent is completed:"), Prefs::SCRIPT_TORRENT_DONE_ENABLED);
+ b = myTorrentDoneScriptButton = new QPushButton;
+ b->setIcon (filePixmap);
+ b->setStyleSheet (QString::fromUtf8 ("text-align: left; padding-left: 5; padding-right: 5"));
+ connect (b, SIGNAL(clicked(bool)), this, SLOT(onScriptClicked(void)));
+ hig->addRow (myTorrentDoneScriptCheckbox, b);
+ enableBuddyWhenChecked (qobject_cast<QCheckBox*>(l), b);
- hig->finish( );
- return hig;
+ hig->finish ();
+ return hig;
}
/***
****
***/
-PrefsDialog :: PrefsDialog( Session& session, Prefs& prefs, QWidget * parent ):
- QDialog( parent ),
- myIsServer( session.isServer( ) ),
- mySession( session ),
- myPrefs( prefs ),
- myLayout( new QVBoxLayout( this ) )
-{
- setWindowTitle( tr( "Transmission Preferences" ) );
-
- QTabWidget * t = new QTabWidget( this );
- t->addTab( createSpeedTab( ), tr( "Speed" ) );
- t->addTab( createDownloadingTab( ), tr( "Downloading" ) );
- t->addTab( createSeedingTab( ), tr( "Seeding" ) );
- t->addTab( createPrivacyTab( ), tr( "Privacy" ) );
- t->addTab( createNetworkTab( ), tr( "Network" ) );
- t->addTab( createDesktopTab( ), tr( "Desktop" ) );
- t->addTab( createRemoteTab(session), tr( "Remote" ) );
- myLayout->addWidget( t );
-
- QDialogButtonBox * buttons = new QDialogButtonBox( QDialogButtonBox::Close, Qt::Horizontal, this );
- connect( buttons, SIGNAL(rejected()), this, SLOT(close()) ); // "close" triggers rejected
- myLayout->addWidget( buttons );
- QWidget::setAttribute( Qt::WA_DeleteOnClose, true );
-
- connect( &mySession, SIGNAL(sessionUpdated()), this, SLOT(sessionUpdated()));
-
- QList<int> keys;
- keys << Prefs :: RPC_ENABLED
- << Prefs :: ALT_SPEED_LIMIT_ENABLED
- << Prefs :: ALT_SPEED_LIMIT_TIME_ENABLED
- << Prefs :: ENCRYPTION
- << Prefs :: BLOCKLIST_ENABLED
- << Prefs :: DIR_WATCH
- << Prefs :: DOWNLOAD_DIR
- << Prefs :: INCOMPLETE_DIR
- << Prefs :: INCOMPLETE_DIR_ENABLED
- << Prefs :: SCRIPT_TORRENT_DONE_FILENAME;
- foreach( int key, keys )
- refreshPref( key );
-
- // if it's a remote session, disable the preferences
- // that don't work in remote sessions
- if( !myIsServer ) {
- foreach( QWidget * w, myUnsupportedWhenRemote ) {
- w->setToolTip( tr( "Not supported by remote sessions" ) );
- w->setEnabled( false );
+PrefsDialog :: PrefsDialog (Session& session, Prefs& prefs, QWidget * parent):
+ QDialog (parent),
+ myIsServer (session.isServer ()),
+ mySession (session),
+ myPrefs (prefs),
+ myLayout (new QVBoxLayout (this))
+{
+ setWindowTitle (tr ("Transmission Preferences"));
+
+ QTabWidget * t = new QTabWidget (this);
+ t->addTab (createSpeedTab (), tr ("Speed"));
+ t->addTab (createDownloadingTab (), tr ("Downloading"));
+ t->addTab (createSeedingTab (), tr ("Seeding"));
+ t->addTab (createPrivacyTab (), tr ("Privacy"));
+ t->addTab (createNetworkTab (), tr ("Network"));
+ t->addTab (createDesktopTab (), tr ("Desktop"));
+ t->addTab (createRemoteTab(session), tr ("Remote"));
+ myLayout->addWidget (t);
+
+ QDialogButtonBox * buttons = new QDialogButtonBox (QDialogButtonBox::Close, Qt::Horizontal, this);
+ connect (buttons, SIGNAL(rejected()), this, SLOT(close())); // "close" triggers rejected
+ myLayout->addWidget (buttons);
+ QWidget::setAttribute (Qt::WA_DeleteOnClose, true);
+
+ connect (&mySession, SIGNAL(sessionUpdated()), this, SLOT(sessionUpdated()));
+
+ QList<int> keys;
+ keys << Prefs :: RPC_ENABLED
+ << Prefs :: ALT_SPEED_LIMIT_ENABLED
+ << Prefs :: ALT_SPEED_LIMIT_TIME_ENABLED
+ << Prefs :: ENCRYPTION
+ << Prefs :: BLOCKLIST_ENABLED
+ << Prefs :: DIR_WATCH
+ << Prefs :: DOWNLOAD_DIR
+ << Prefs :: INCOMPLETE_DIR
+ << Prefs :: INCOMPLETE_DIR_ENABLED
+ << Prefs :: SCRIPT_TORRENT_DONE_FILENAME;
+ foreach (int key, keys)
+ refreshPref (key);
+
+ // if it's a remote session, disable the preferences
+ // that don't work in remote sessions
+ if (!myIsServer)
+ {
+ foreach (QWidget * w, myUnsupportedWhenRemote)
+ {
+ w->setToolTip (tr ("Not supported by remote sessions"));
+ w->setEnabled (false);
}
}
}
-PrefsDialog :: ~PrefsDialog( )
+PrefsDialog :: ~PrefsDialog ()
{
}
void
-PrefsDialog :: setPref( int key, const QVariant& v )
+PrefsDialog :: setPref (int key, const QVariant& v)
{
- myPrefs.set( key, v );
- refreshPref( key );
+ myPrefs.set (key, v);
+ refreshPref (key);
}
/***
***/
void
-PrefsDialog :: sessionUpdated( )
+PrefsDialog :: sessionUpdated ()
{
- updateBlocklistLabel( );
+ updateBlocklistLabel ();
}
void
-PrefsDialog :: updateBlocklistLabel( )
+PrefsDialog :: updateBlocklistLabel ()
{
- const int n = mySession.blocklistSize( );
- myBlocklistLabel->setText( tr( "<i>Blocklist contains %Ln rules</i>", 0, n ) );
+ const int n = mySession.blocklistSize ();
+ myBlocklistLabel->setText (tr ("<i>Blocklist contains %Ln rules</i>", 0, n));
}
void
-PrefsDialog :: refreshPref( int key )
+PrefsDialog :: refreshPref (int key)
{
- switch( key )
+ switch (key)
{
- case Prefs :: RPC_ENABLED:
- case Prefs :: RPC_WHITELIST_ENABLED:
- case Prefs :: RPC_AUTH_REQUIRED: {
- const bool enabled( myPrefs.getBool( Prefs::RPC_ENABLED ) );
- const bool whitelist( myPrefs.getBool( Prefs::RPC_WHITELIST_ENABLED ) );
- const bool auth( myPrefs.getBool( Prefs::RPC_AUTH_REQUIRED ) );
- foreach( QWidget * w, myWebWhitelistWidgets ) w->setEnabled( enabled && whitelist );
- foreach( QWidget * w, myWebAuthWidgets ) w->setEnabled( enabled && auth );
- foreach( QWidget * w, myWebWidgets ) w->setEnabled( enabled );
- break;
+ case Prefs :: RPC_ENABLED:
+ case Prefs :: RPC_WHITELIST_ENABLED:
+ case Prefs :: RPC_AUTH_REQUIRED:
+ {
+ const bool enabled (myPrefs.getBool (Prefs::RPC_ENABLED));
+ const bool whitelist (myPrefs.getBool (Prefs::RPC_WHITELIST_ENABLED));
+ const bool auth (myPrefs.getBool (Prefs::RPC_AUTH_REQUIRED));
+ foreach (QWidget * w, myWebWhitelistWidgets)w->setEnabled (enabled && whitelist);
+ foreach (QWidget * w, myWebAuthWidgets)w->setEnabled (enabled && auth);
+ foreach (QWidget * w, myWebWidgets)w->setEnabled (enabled);
+ break;
}
- case Prefs :: ALT_SPEED_LIMIT_TIME_ENABLED: {
- const bool enabled = myPrefs.getBool( key );
- foreach( QWidget * w, mySchedWidgets ) w->setEnabled( enabled );
- break;
+ case Prefs :: ALT_SPEED_LIMIT_TIME_ENABLED:
+ {
+ const bool enabled = myPrefs.getBool (key);
+ foreach (QWidget * w, mySchedWidgets)w->setEnabled (enabled);
+ break;
}
- case Prefs :: BLOCKLIST_ENABLED: {
- const bool enabled = myPrefs.getBool( key );
- foreach( QWidget * w, myBlockWidgets ) w->setEnabled( enabled );
- break;
+ case Prefs :: BLOCKLIST_ENABLED:
+ {
+ const bool enabled = myPrefs.getBool (key);
+ foreach (QWidget * w, myBlockWidgets)w->setEnabled (enabled);
+ break;
}
- case Prefs :: DIR_WATCH:
- myWatchButton->setText( QFileInfo(myPrefs.getString(Prefs::DIR_WATCH)).fileName() );
- break;
+ case Prefs :: DIR_WATCH:
+ myWatchButton->setText (QFileInfo(myPrefs.getString(Prefs::DIR_WATCH)).fileName());
+ break;
- case Prefs :: SCRIPT_TORRENT_DONE_FILENAME: {
- const QString path( myPrefs.getString( key ) );
- myTorrentDoneScriptButton->setText( QFileInfo(path).fileName() );
- break;
+ case Prefs :: SCRIPT_TORRENT_DONE_FILENAME:
+ {
+ const QString path (myPrefs.getString (key));
+ myTorrentDoneScriptButton->setText (QFileInfo(path).fileName());
+ break;
}
- case Prefs :: PEER_PORT:
- myPortLabel->setText( tr( "Status unknown" ) );
- myPortButton->setEnabled( true );
- break;
+ case Prefs :: PEER_PORT:
+ myPortLabel->setText (tr ("Status unknown"));
+ myPortButton->setEnabled (true);
+ break;
- case Prefs :: DOWNLOAD_DIR: {
- const QString path( myPrefs.getString( key ) );
- myDestinationButton->setText( QFileInfo(path).fileName() );
- myFreespaceLabel->setPath (path);
- break;
+ case Prefs :: DOWNLOAD_DIR:
+ {
+ const QString path (myPrefs.getString (key));
+ myDestinationButton->setText (QFileInfo(path).fileName());
+ myFreespaceLabel->setPath (path);
+ break;
}
- case Prefs :: INCOMPLETE_DIR: {
- QString path( myPrefs.getString( key ) );
- myIncompleteButton->setText( QFileInfo(path).fileName() );
- break;
+ case Prefs :: INCOMPLETE_DIR:
+ {
+ QString path (myPrefs.getString (key));
+ myIncompleteButton->setText (QFileInfo(path).fileName());
+ break;
}
- case Prefs :: INCOMPLETE_DIR_ENABLED: {
- const bool enabled = myPrefs.getBool( key );
- myIncompleteButton->setEnabled( enabled );
- break;
+ case Prefs :: INCOMPLETE_DIR_ENABLED:
+ {
+ const bool enabled = myPrefs.getBool (key);
+ myIncompleteButton->setEnabled (enabled);
+ break;
}
- default:
- break;
+ default:
+ break;
}
- key2widget_t::iterator it( myWidgets.find( key ) );
- if( it != myWidgets.end( ) )
+ key2widget_t::iterator it (myWidgets.find (key));
+ if (it != myWidgets.end ())
{
- QWidget * w( it.value( ) );
- QCheckBox * checkBox;
- QSpinBox * spin;
- QDoubleSpinBox * doubleSpin;
- QTimeEdit * timeEdit;
- QLineEdit * lineEdit;
-
- if(( checkBox = qobject_cast<QCheckBox*>(w)))
+ QWidget * w (it.value ());
+ QCheckBox * checkBox;
+ QSpinBox * spin;
+ QDoubleSpinBox * doubleSpin;
+ QTimeEdit * timeEdit;
+ QLineEdit * lineEdit;
+
+ if ((checkBox = qobject_cast<QCheckBox*>(w)))
{
- checkBox->setChecked( myPrefs.getBool( key ) );
+ checkBox->setChecked (myPrefs.getBool (key));
}
- else if(( spin = qobject_cast<QSpinBox*>(w)))
+ else if ((spin = qobject_cast<QSpinBox*>(w)))
{
- spin->setValue( myPrefs.getInt( key ) );
+ spin->setValue (myPrefs.getInt (key));
}
- else if(( doubleSpin = qobject_cast<QDoubleSpinBox*>(w)))
+ else if ((doubleSpin = qobject_cast<QDoubleSpinBox*>(w)))
{
- doubleSpin->setValue( myPrefs.getDouble( key ) );
+ doubleSpin->setValue (myPrefs.getDouble (key));
}
- else if(( timeEdit = qobject_cast<QTimeEdit*>(w)))
+ else if ((timeEdit = qobject_cast<QTimeEdit*>(w)))
{
- const int minutes( myPrefs.getInt( key ) );
- timeEdit->setTime( QTime().addSecs( minutes * 60 ) );
+ const int minutes (myPrefs.getInt (key));
+ timeEdit->setTime (QTime().addSecs (minutes * 60));
}
- else if(( lineEdit = qobject_cast<QLineEdit*>(w)))
+ else if ((lineEdit = qobject_cast<QLineEdit*>(w)))
{
- lineEdit->setText( myPrefs.getString( key ) );
+ lineEdit->setText (myPrefs.getString (key));
}
- else if( key == Prefs::ENCRYPTION )
+ else if (key == Prefs::ENCRYPTION)
{
- QComboBox * comboBox( qobject_cast<QComboBox*>( w ) );
- const int index = comboBox->findData( myPrefs.getInt( key ) );
- comboBox->setCurrentIndex( index );
+ QComboBox * comboBox (qobject_cast<QComboBox*> (w));
+ const int index = comboBox->findData (myPrefs.getInt (key));
+ comboBox->setCurrentIndex (index);
}
}
}
bool
-PrefsDialog :: isAllowed( int key ) const
+PrefsDialog :: isAllowed (int key) const
{
- Q_UNUSED( key );
+ Q_UNUSED (key);
- return true;
+ return true;
}
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;
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
public:
RelocateDialog (Session&, TorrentModel&, const QSet<int>& ids, QWidget * parent = 0);
- ~RelocateDialog () { }
+ ~RelocateDialog () {}
};
#endif
***/
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);
}
class SessionDialog: public QDialog
{
- Q_OBJECT
-
- public:
- SessionDialog( Session& session, Prefs& prefs, QWidget * parent = 0 );
- ~SessionDialog( ) { }
-
- private slots:
- void onAccepted( );
- void resensitize( );
-
- private:
- QCheckBox * myAuthCheckBox;
- QRadioButton * myRemoteRadioButton;
- QLineEdit * myHostLineEdit;
- QSpinBox * myPortSpinBox;
- QLineEdit * myUsernameLineEdit;
- QLineEdit * myPasswordLineEdit;
- QCheckBox * myAutomaticCheckBox;
-
- private:
- Session& mySession;
- Prefs& myPrefs;
- QWidgetList myRemoteWidgets;
- QWidgetList myAuthWidgets;
+ Q_OBJECT
+
+ public:
+ SessionDialog (Session& session, Prefs& prefs, QWidget * parent = 0);
+ ~SessionDialog () {}
+
+ private slots:
+ void onAccepted ();
+ void resensitize ();
+
+ private:
+ QCheckBox * myAuthCheckBox;
+ QRadioButton * myRemoteRadioButton;
+ QLineEdit * myHostLineEdit;
+ QSpinBox * myPortSpinBox;
+ QLineEdit * myUsernameLineEdit;
+ QLineEdit * myPasswordLineEdit;
+ QCheckBox * myAutomaticCheckBox;
+
+ private:
+ Session& mySession;
+ Prefs& myPrefs;
+ QWidgetList myRemoteWidgets;
+ QWidgetList myAuthWidgets;
};
#endif
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; }
#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());
}
{
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
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
};
/***
***/
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 ) );
-
- 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 );
-
- 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 ) );
+ 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 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));
+
+ 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 ) );
-
- 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 ) );
-
- 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;
-
- painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight));
+ 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 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();
+
+ 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));
}
- 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;
-
- 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;
-
- 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( ) );
-
- // 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 );
+ 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;
+
+ 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;
+
+ 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());
+
+ // 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 );
-
- painter->restore( );
+ 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();
}
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
enum
{
- GUI_PAD = 6,
- BAR_HEIGHT = 12
+ GUI_PAD = 6,
+ BAR_HEIGHT = 12
};
QColor TorrentDelegate :: greenBrush;
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;
}
/***
***/
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 ) );
-
- if( isMagnet ) // magnet link with no metadata
+ 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
{
- /* %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
{
%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;
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());
}
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_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;
+ 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;
+
+ 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_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_SEED:
- str = tr( "Seeding to %1 of %n connected peer(s)", 0, tor.connectedPeers( ) )
- .arg( tor.peersWeAreUploadingTo( ) );
- break;
-
- default:
- str = tr( "Error" );
- 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_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;
}
/***
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 ) );
-
- 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() );
+ 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());
}
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( ) );
-
- 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;
-
- painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight));
+ 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 ();
+
+ 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));
}
- 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;
-
- 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;
-
- 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( ) );
-
- // 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 );
+ 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;
+
+ 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;
+
+ 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 ());
+
+ // 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 ();
}
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
#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)));
-
- 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 );
+ // listen for changes to the preferences to know when to refilter / resort
+ connect (&myPrefs, SIGNAL(changed(int)), this, SLOT(refreshPref(int)));
+
+ 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);
}
-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 :: SORT_MODE:
- case Prefs :: SORT_REVERSED:
- sort( 0, myPrefs.getBool(Prefs::SORT_REVERSED) ? Qt::AscendingOrder : Qt::DescendingOrder );
- invalidate( );
- break;
+ 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;
}
}
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;
}
***/
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
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];
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
#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
***/
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 ();
}
/***
***/
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 ();
}
/***
***/
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 );
+ 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 )
+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 );
+ 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 )
+TorrentModel :: updateTorrents (tr_variant * torrents, bool isCompleteList)
{
- QList<Torrent*> newTorrents;
- QSet<int> oldIds;
- QSet<int> addIds;
- QSet<int> newIds;
- int updatedCount = 0;
+ QList<Torrent*> newTorrents;
+ QSet<int> oldIds;
+ QSet<int> addIds;
+ QSet<int> newIds;
+ int updatedCount = 0;
- if ( isCompleteList )
- oldIds = getIds( );
+ if (isCompleteList)
+ oldIds = getIds ();
- if( tr_variantIsList( torrents ) )
+ if (tr_variantIsList (torrents))
{
- size_t i( 0 );
- tr_variant * child;
- while(( child = tr_variantListChild( torrents, i++ )))
+ size_t i (0);
+ tr_variant * child;
+ while( (child = tr_variantListChild (torrents, i++)))
{
- int64_t id;
- if( tr_variantDictFindInt( child, TR_KEY_id, &id ) )
+ int64_t id;
+ if (tr_variantDictFindInt (child, TR_KEY_id, &id))
{
- newIds.insert( id );
+ newIds.insert (id);
- Torrent * tor = getTorrentFromId( id );
- if( tor == 0 )
+ 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 );
-
- 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;
+ 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 ();
+
+ delete tor;
}
}
}
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;
}
class TorrentModel: public QAbstractListModel
{
- 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;
-
- 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;
-
- private:
- void addTorrent( Torrent * );
- QSet<int> getIds( ) const;
-
- public:
- void getTransferSpeed (Speed & uploadSpeed,
- size_t & uploadPeerCount,
- Speed & downloadSpeed,
- size_t & downloadPeerCount);
-
- signals:
- void torrentsAdded( QSet<int> );
-
- public slots:
- void updateTorrents( tr_variant * torrentList, bool isCompleteList );
- void removeTorrents( tr_variant * torrentList );
- void removeTorrent( int id );
-
- private slots:
- void onTorrentChanged( int propertyId );
-
- public:
- TorrentModel( Prefs& prefs );
- virtual ~TorrentModel( );
+ 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;
+
+ 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;
+
+ private:
+ void addTorrent (Torrent *);
+ QSet<int> getIds () const;
+
+ public:
+ void getTransferSpeed (Speed & uploadSpeed,
+ size_t & uploadPeerCount,
+ Speed & downloadSpeed,
+ size_t & downloadPeerCount);
+
+ signals:
+ void torrentsAdded (QSet<int>);
+
+ public slots:
+ void updateTorrents (tr_variant * torrentList, bool isCompleteList);
+ void removeTorrents (tr_variant * torrentList);
+ void removeTorrent (int id);
+
+ private slots:
+ void onTorrentChanged (int propertyId);
+
+ public:
+ TorrentModel (Prefs& prefs);
+ virtual ~TorrentModel ();
};
#endif
QString host;
QString lastAnnounceResult;
QString lastScrapeResult;
- QPixmap getFavicon( ) const;
+ QPixmap getFavicon () const;
};
typedef QList<TrackerStat> 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;
class Torrent: public QObject
{
- Q_OBJECT;
-
- 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,
-
- PROPERTY_COUNT
- };
-
- public:
- Torrent( Prefs&, int id );
- virtual ~Torrent( );
-
- signals:
- void torrentChanged( int id );
- void torrentCompleted( int id );
-
- 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
- };
-
- struct Property
- {
- int id;
- tr_quark key;
- int type;
- int group;
- };
-
- static Property myProperties[];
-
- bool magnetTorrent;
-
- 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:
- 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;
-
- 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:
- 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;
-
- public:
- void update( tr_variant * dict );
- void setMagnet( bool magnet ) { magnetTorrent = magnet; }
-
- private:
- const char * getMimeTypeString( ) const;
- void updateMimeIcon( );
-
- public:
- QIcon getMimeTypeIcon( ) const { return getIcon( MIME_ICON ); }
-
- private:
- Prefs& myPrefs;
- FileList myFiles;
+ Q_OBJECT;
+
+ 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,
+
+ PROPERTY_COUNT
+ };
+
+ public:
+ Torrent (Prefs&, int id);
+ virtual ~Torrent ();
+
+ signals:
+ void torrentChanged (int id);
+ void torrentCompleted (int id);
+
+ 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
+ };
+
+ struct Property
+ {
+ int id;
+ tr_quark key;
+ int type;
+ int group;
+ };
+
+ static Property myProperties[];
+
+ bool magnetTorrent;
+
+ 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:
+ 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;
+
+ 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:
+ 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;
+
+ public:
+ void update (tr_variant * dict);
+ void setMagnet (bool magnet) { magnetTorrent = magnet; }
+
+ private:
+ const char * getMimeTypeString () const;
+ void updateMimeIcon ();
+
+ public:
+ QIcon getMimeTypeIcon () const { return getIcon (MIME_ICON); }
+
+ private:
+ Prefs& myPrefs;
+ FileList myFiles;
};
Q_DECLARE_METATYPE(const Torrent*)
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;
}
/***
***/
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( );
-
- 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( ) ) );
-
- painter->restore( );
+ 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);
+
+ 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();
}
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>";
-
- // 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 )
+ 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>";
+
+ // 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_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_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_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;
}
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
#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;
}
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
#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;
}
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
#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);
}
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
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
#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
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))
{
#endif
QIcon
-Utils :: guessMimeIcon( const QString& filename )
+Utils :: guessMimeIcon (const QString& filename)
{
#ifdef WIN32
QIcon icon;
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 );
-
- 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 * 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 * 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 * 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 );
+ fallback = QApplication::style()->standardIcon (QStyle :: SP_FileIcon);
+
+ 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 * 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 * 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 * 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
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
****
***/
-WatchDir :: WatchDir( const TorrentModel& model ):
- myModel( model ),
- myWatcher( 0 )
+WatchDir :: WatchDir (const TorrentModel& model):
+ myModel (model),
+ myWatcher (0)
{
}
-WatchDir :: ~WatchDir( )
+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 );
-
- // 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;
+ 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;
+
+ // 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);
-
- // 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 );
+ 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);
+
+ // 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;
}
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