Combine all the column filter related widgets
[qBittorrent.git] / src / gui / transferlistmodel.cpp
blobdbfb11e82cf7e370787073bd452d66e48fc06cfd
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2015 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2010 Christophe Dumez <chris@qbittorrent.org>
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * In addition, as a special exception, the copyright holders give permission to
21 * link this program with the OpenSSL project's "OpenSSL" library (or with
22 * modified versions of it that use the same license as the "OpenSSL" library),
23 * and distribute the linked executables. You must obey the GNU General Public
24 * License in all respects for all of the code used other than "OpenSSL". If you
25 * modify file(s), you may extend this exception to your version of the file(s),
26 * but you are not obligated to do so. If you do not wish to do so, delete this
27 * exception statement from your version.
30 #include "transferlistmodel.h"
32 #include <QApplication>
33 #include <QDateTime>
34 #include <QDebug>
36 #include "base/bittorrent/infohash.h"
37 #include "base/bittorrent/session.h"
38 #include "base/bittorrent/torrent.h"
39 #include "base/global.h"
40 #include "base/preferences.h"
41 #include "base/types.h"
42 #include "base/unicodestrings.h"
43 #include "base/utils/fs.h"
44 #include "base/utils/misc.h"
45 #include "base/utils/string.h"
46 #include "uithememanager.h"
48 namespace
50 QHash<BitTorrent::TorrentState, QColor> torrentStateColorsFromUITheme()
52 struct TorrentStateColorDescriptor
54 const BitTorrent::TorrentState state;
55 const QString id;
58 const TorrentStateColorDescriptor colorDescriptors[] =
60 {BitTorrent::TorrentState::Downloading, u"TransferList.Downloading"_qs},
61 {BitTorrent::TorrentState::StalledDownloading, u"TransferList.StalledDownloading"_qs},
62 {BitTorrent::TorrentState::DownloadingMetadata, u"TransferList.DownloadingMetadata"_qs},
63 {BitTorrent::TorrentState::ForcedDownloadingMetadata, u"TransferList.ForcedDownloadingMetadata"_qs},
64 {BitTorrent::TorrentState::ForcedDownloading, u"TransferList.ForcedDownloading"_qs},
65 {BitTorrent::TorrentState::Uploading, u"TransferList.Uploading"_qs},
66 {BitTorrent::TorrentState::StalledUploading, u"TransferList.StalledUploading"_qs},
67 {BitTorrent::TorrentState::ForcedUploading, u"TransferList.ForcedUploading"_qs},
68 {BitTorrent::TorrentState::QueuedDownloading, u"TransferList.QueuedDownloading"_qs},
69 {BitTorrent::TorrentState::QueuedUploading, u"TransferList.QueuedUploading"_qs},
70 {BitTorrent::TorrentState::CheckingDownloading, u"TransferList.CheckingDownloading"_qs},
71 {BitTorrent::TorrentState::CheckingUploading, u"TransferList.CheckingUploading"_qs},
72 {BitTorrent::TorrentState::CheckingResumeData, u"TransferList.CheckingResumeData"_qs},
73 {BitTorrent::TorrentState::PausedDownloading, u"TransferList.PausedDownloading"_qs},
74 {BitTorrent::TorrentState::PausedUploading, u"TransferList.PausedUploading"_qs},
75 {BitTorrent::TorrentState::Moving, u"TransferList.Moving"_qs},
76 {BitTorrent::TorrentState::MissingFiles, u"TransferList.MissingFiles"_qs},
77 {BitTorrent::TorrentState::Error, u"TransferList.Error"_qs}
80 QHash<BitTorrent::TorrentState, QColor> colors;
81 for (const TorrentStateColorDescriptor &colorDescriptor : colorDescriptors)
83 const QColor themeColor = UIThemeManager::instance()->getColor(colorDescriptor.id);
84 colors.insert(colorDescriptor.state, themeColor);
86 return colors;
90 // TransferListModel
92 TransferListModel::TransferListModel(QObject *parent)
93 : QAbstractListModel {parent}
94 , m_statusStrings
96 {BitTorrent::TorrentState::Downloading, tr("Downloading")},
97 {BitTorrent::TorrentState::StalledDownloading, tr("Stalled", "Torrent is waiting for download to begin")},
98 {BitTorrent::TorrentState::DownloadingMetadata, tr("Downloading metadata", "Used when loading a magnet link")},
99 {BitTorrent::TorrentState::ForcedDownloadingMetadata, tr("[F] Downloading metadata", "Used when forced to load a magnet link. You probably shouldn't translate the F.")},
100 {BitTorrent::TorrentState::ForcedDownloading, tr("[F] Downloading", "Used when the torrent is forced started. You probably shouldn't translate the F.")},
101 {BitTorrent::TorrentState::Uploading, tr("Seeding", "Torrent is complete and in upload-only mode")},
102 {BitTorrent::TorrentState::StalledUploading, tr("Seeding", "Torrent is complete and in upload-only mode")},
103 {BitTorrent::TorrentState::ForcedUploading, tr("[F] Seeding", "Used when the torrent is forced started. You probably shouldn't translate the F.")},
104 {BitTorrent::TorrentState::QueuedDownloading, tr("Queued", "Torrent is queued")},
105 {BitTorrent::TorrentState::QueuedUploading, tr("Queued", "Torrent is queued")},
106 {BitTorrent::TorrentState::CheckingDownloading, tr("Checking", "Torrent local data is being checked")},
107 {BitTorrent::TorrentState::CheckingUploading, tr("Checking", "Torrent local data is being checked")},
108 {BitTorrent::TorrentState::CheckingResumeData, tr("Checking resume data", "Used when loading the torrents from disk after qbt is launched. It checks the correctness of the .fastresume file. Normally it is completed in a fraction of a second, unless loading many many torrents.")},
109 {BitTorrent::TorrentState::PausedDownloading, tr("Paused")},
110 {BitTorrent::TorrentState::PausedUploading, tr("Completed")},
111 {BitTorrent::TorrentState::Moving, tr("Moving", "Torrent local data are being moved/relocated")},
112 {BitTorrent::TorrentState::MissingFiles, tr("Missing Files")},
113 {BitTorrent::TorrentState::Error, tr("Errored", "Torrent status, the torrent has an error")}
115 , m_stateThemeColors {torrentStateColorsFromUITheme()}
116 , m_checkingIcon {UIThemeManager::instance()->getIcon(u"force-recheck"_qs, u"checking"_qs)}
117 , m_completedIcon {UIThemeManager::instance()->getIcon(u"checked-completed"_qs, u"completed"_qs)}
118 , m_downloadingIcon {UIThemeManager::instance()->getIcon(u"downloading"_qs)}
119 , m_errorIcon {UIThemeManager::instance()->getIcon(u"error"_qs)}
120 , m_pausedIcon {UIThemeManager::instance()->getIcon(u"stopped"_qs, u"media-playback-pause"_qs)}
121 , m_queuedIcon {UIThemeManager::instance()->getIcon(u"queued"_qs)}
122 , m_stalledDLIcon {UIThemeManager::instance()->getIcon(u"stalledDL"_qs)}
123 , m_stalledUPIcon {UIThemeManager::instance()->getIcon(u"stalledUP"_qs)}
124 , m_uploadingIcon {UIThemeManager::instance()->getIcon(u"upload"_qs, u"uploading"_qs)}
126 configure();
127 connect(Preferences::instance(), &Preferences::changed, this, &TransferListModel::configure);
129 // Load the torrents
130 using namespace BitTorrent;
131 addTorrents(Session::instance()->torrents());
133 // Listen for torrent changes
134 connect(Session::instance(), &Session::torrentsLoaded, this, &TransferListModel::addTorrents);
135 connect(Session::instance(), &Session::torrentAboutToBeRemoved, this, &TransferListModel::handleTorrentAboutToBeRemoved);
136 connect(Session::instance(), &Session::torrentsUpdated, this, &TransferListModel::handleTorrentsUpdated);
138 connect(Session::instance(), &Session::torrentFinished, this, &TransferListModel::handleTorrentStatusUpdated);
139 connect(Session::instance(), &Session::torrentMetadataReceived, this, &TransferListModel::handleTorrentStatusUpdated);
140 connect(Session::instance(), &Session::torrentResumed, this, &TransferListModel::handleTorrentStatusUpdated);
141 connect(Session::instance(), &Session::torrentPaused, this, &TransferListModel::handleTorrentStatusUpdated);
142 connect(Session::instance(), &Session::torrentFinishedChecking, this, &TransferListModel::handleTorrentStatusUpdated);
145 int TransferListModel::rowCount(const QModelIndex &) const
147 return m_torrentList.size();
150 int TransferListModel::columnCount(const QModelIndex &) const
152 return NB_COLUMNS;
155 QVariant TransferListModel::headerData(const int section, const Qt::Orientation orientation, const int role) const
157 if (orientation == Qt::Horizontal)
159 if (role == Qt::DisplayRole)
161 switch (section)
163 case TR_QUEUE_POSITION: return QChar(u'#');
164 case TR_NAME: return tr("Name", "i.e: torrent name");
165 case TR_SIZE: return tr("Size", "i.e: torrent size");
166 case TR_PROGRESS: return tr("Progress", "% Done");
167 case TR_STATUS: return tr("Status", "Torrent status (e.g. downloading, seeding, paused)");
168 case TR_SEEDS: return tr("Seeds", "i.e. full sources (often untranslated)");
169 case TR_PEERS: return tr("Peers", "i.e. partial sources (often untranslated)");
170 case TR_DLSPEED: return tr("Down Speed", "i.e: Download speed");
171 case TR_UPSPEED: return tr("Up Speed", "i.e: Upload speed");
172 case TR_RATIO: return tr("Ratio", "Share ratio");
173 case TR_ETA: return tr("ETA", "i.e: Estimated Time of Arrival / Time left");
174 case TR_CATEGORY: return tr("Category");
175 case TR_TAGS: return tr("Tags");
176 case TR_ADD_DATE: return tr("Added On", "Torrent was added to transfer list on 01/01/2010 08:00");
177 case TR_SEED_DATE: return tr("Completed On", "Torrent was completed on 01/01/2010 08:00");
178 case TR_TRACKER: return tr("Tracker");
179 case TR_DLLIMIT: return tr("Down Limit", "i.e: Download limit");
180 case TR_UPLIMIT: return tr("Up Limit", "i.e: Upload limit");
181 case TR_AMOUNT_DOWNLOADED: return tr("Downloaded", "Amount of data downloaded (e.g. in MB)");
182 case TR_AMOUNT_UPLOADED: return tr("Uploaded", "Amount of data uploaded (e.g. in MB)");
183 case TR_AMOUNT_DOWNLOADED_SESSION: return tr("Session Download", "Amount of data downloaded since program open (e.g. in MB)");
184 case TR_AMOUNT_UPLOADED_SESSION: return tr("Session Upload", "Amount of data uploaded since program open (e.g. in MB)");
185 case TR_AMOUNT_LEFT: return tr("Remaining", "Amount of data left to download (e.g. in MB)");
186 case TR_TIME_ELAPSED: return tr("Time Active", "Time (duration) the torrent is active (not paused)");
187 case TR_SAVE_PATH: return tr("Save Path", "Torrent save path");
188 case TR_DOWNLOAD_PATH: return tr("Incomplete Save Path", "Torrent incomplete save path");
189 case TR_COMPLETED: return tr("Completed", "Amount of data completed (e.g. in MB)");
190 case TR_RATIO_LIMIT: return tr("Ratio Limit", "Upload share ratio limit");
191 case TR_SEEN_COMPLETE_DATE: return tr("Last Seen Complete", "Indicates the time when the torrent was last seen complete/whole");
192 case TR_LAST_ACTIVITY: return tr("Last Activity", "Time passed since a chunk was downloaded/uploaded");
193 case TR_TOTAL_SIZE: return tr("Total Size", "i.e. Size including unwanted data");
194 case TR_AVAILABILITY: return tr("Availability", "The number of distributed copies of the torrent");
195 case TR_INFOHASH_V1: return tr("Info Hash v1", "i.e: torrent info hash v1");
196 case TR_INFOHASH_V2: return tr("Info Hash v2", "i.e: torrent info hash v2");
197 default: return {};
200 else if (role == Qt::TextAlignmentRole)
202 switch (section)
204 case TR_AMOUNT_DOWNLOADED:
205 case TR_AMOUNT_UPLOADED:
206 case TR_AMOUNT_DOWNLOADED_SESSION:
207 case TR_AMOUNT_UPLOADED_SESSION:
208 case TR_AMOUNT_LEFT:
209 case TR_COMPLETED:
210 case TR_SIZE:
211 case TR_TOTAL_SIZE:
212 case TR_ETA:
213 case TR_SEEDS:
214 case TR_PEERS:
215 case TR_UPSPEED:
216 case TR_DLSPEED:
217 case TR_UPLIMIT:
218 case TR_DLLIMIT:
219 case TR_RATIO_LIMIT:
220 case TR_RATIO:
221 case TR_QUEUE_POSITION:
222 case TR_LAST_ACTIVITY:
223 case TR_AVAILABILITY:
224 return QVariant(Qt::AlignRight | Qt::AlignVCenter);
225 default:
226 return QAbstractListModel::headerData(section, orientation, role);
231 return QAbstractListModel::headerData(section, orientation, role);
234 QString TransferListModel::displayValue(const BitTorrent::Torrent *torrent, const int column) const
236 bool hideValues = false;
237 if (m_hideZeroValuesMode == HideZeroValuesMode::Always)
238 hideValues = true;
239 else if (m_hideZeroValuesMode == HideZeroValuesMode::Paused)
240 hideValues = (torrent->state() == BitTorrent::TorrentState::PausedDownloading);
242 const auto availabilityString = [hideValues](const qreal value) -> QString
244 if (hideValues && (value == 0))
245 return {};
246 return (value >= 0)
247 ? Utils::String::fromDouble(value, 3)
248 : tr("N/A");
251 const auto unitString = [hideValues](const qint64 value, const bool isSpeedUnit = false) -> QString
253 return (hideValues && (value == 0))
254 ? QString {} : Utils::Misc::friendlyUnit(value, isSpeedUnit);
257 const auto limitString = [hideValues](const qint64 value) -> QString
259 if (hideValues && (value <= 0))
260 return {};
262 return (value > 0)
263 ? Utils::Misc::friendlyUnit(value, true)
264 : C_INFINITY;
267 const auto amountString = [hideValues](const qint64 value, const qint64 total) -> QString
269 if (hideValues && (value == 0) && (total == 0))
270 return {};
271 return u"%1 (%2)"_qs.arg(QString::number(value), QString::number(total));
274 const auto etaString = [hideValues](const qlonglong value) -> QString
276 if (hideValues && (value >= MAX_ETA))
277 return {};
278 return Utils::Misc::userFriendlyDuration(value, MAX_ETA);
281 const auto ratioString = [hideValues](const qreal value) -> QString
283 if (hideValues && (value <= 0))
284 return {};
286 return ((static_cast<int>(value) == -1) || (value > BitTorrent::Torrent::MAX_RATIO))
287 ? C_INFINITY : Utils::String::fromDouble(value, 2);
290 const auto queuePositionString = [](const qint64 value) -> QString
292 return (value >= 0) ? QString::number(value + 1) : u"*"_qs;
295 const auto lastActivityString = [hideValues](qint64 value) -> QString
297 if (hideValues && ((value < 0) || (value >= MAX_ETA)))
298 return {};
300 // Show '< 1m ago' when elapsed time is 0
301 if (value == 0)
302 value = 1;
304 return (value >= 0)
305 ? tr("%1 ago", "e.g.: 1h 20m ago").arg(Utils::Misc::userFriendlyDuration(value))
306 : Utils::Misc::userFriendlyDuration(value);
309 const auto timeElapsedString = [hideValues](const qint64 elapsedTime, const qint64 seedingTime) -> QString
311 if (seedingTime <= 0)
313 if (hideValues && (elapsedTime == 0))
314 return {};
315 return Utils::Misc::userFriendlyDuration(elapsedTime);
318 return tr("%1 (seeded for %2)", "e.g. 4m39s (seeded for 3m10s)")
319 .arg(Utils::Misc::userFriendlyDuration(elapsedTime)
320 , Utils::Misc::userFriendlyDuration(seedingTime));
323 const auto progressString = [](const qreal progress) -> QString
325 return (progress >= 1)
326 ? u"100%"_qs
327 : (Utils::String::fromDouble((progress * 100), 1) + u'%');
330 const auto statusString = [this](const BitTorrent::TorrentState state, const QString &errorMessage) -> QString
332 return (state == BitTorrent::TorrentState::Error)
333 ? m_statusStrings[state] + u": " + errorMessage
334 : m_statusStrings[state];
337 const auto hashString = [hideValues](const auto &hash) -> QString
339 if (hideValues && !hash.isValid())
340 return {};
341 return hash.isValid() ? hash.toString() : tr("N/A");
344 switch (column)
346 case TR_NAME:
347 return torrent->name();
348 case TR_QUEUE_POSITION:
349 return queuePositionString(torrent->queuePosition());
350 case TR_SIZE:
351 return unitString(torrent->wantedSize());
352 case TR_PROGRESS:
353 return progressString(torrent->progress());
354 case TR_STATUS:
355 return statusString(torrent->state(), torrent->error());
356 case TR_SEEDS:
357 return amountString(torrent->seedsCount(), torrent->totalSeedsCount());
358 case TR_PEERS:
359 return amountString(torrent->leechsCount(), torrent->totalLeechersCount());
360 case TR_DLSPEED:
361 return unitString(torrent->downloadPayloadRate(), true);
362 case TR_UPSPEED:
363 return unitString(torrent->uploadPayloadRate(), true);
364 case TR_ETA:
365 return etaString(torrent->eta());
366 case TR_RATIO:
367 return ratioString(torrent->realRatio());
368 case TR_RATIO_LIMIT:
369 return ratioString(torrent->maxRatio());
370 case TR_CATEGORY:
371 return torrent->category();
372 case TR_TAGS:
373 return torrent->tags().join(u", "_qs);
374 case TR_ADD_DATE:
375 return QLocale().toString(torrent->addedTime().toLocalTime(), QLocale::ShortFormat);
376 case TR_SEED_DATE:
377 return QLocale().toString(torrent->completedTime().toLocalTime(), QLocale::ShortFormat);
378 case TR_TRACKER:
379 return torrent->currentTracker();
380 case TR_DLLIMIT:
381 return limitString(torrent->downloadLimit());
382 case TR_UPLIMIT:
383 return limitString(torrent->uploadLimit());
384 case TR_AMOUNT_DOWNLOADED:
385 return unitString(torrent->totalDownload());
386 case TR_AMOUNT_UPLOADED:
387 return unitString(torrent->totalUpload());
388 case TR_AMOUNT_DOWNLOADED_SESSION:
389 return unitString(torrent->totalPayloadDownload());
390 case TR_AMOUNT_UPLOADED_SESSION:
391 return unitString(torrent->totalPayloadUpload());
392 case TR_AMOUNT_LEFT:
393 return unitString(torrent->remainingSize());
394 case TR_TIME_ELAPSED:
395 return timeElapsedString(torrent->activeTime(), torrent->finishedTime());
396 case TR_SAVE_PATH:
397 return torrent->savePath().toString();
398 case TR_DOWNLOAD_PATH:
399 return torrent->downloadPath().toString();
400 case TR_COMPLETED:
401 return unitString(torrent->completedSize());
402 case TR_SEEN_COMPLETE_DATE:
403 return QLocale().toString(torrent->lastSeenComplete().toLocalTime(), QLocale::ShortFormat);
404 case TR_LAST_ACTIVITY:
405 return lastActivityString(torrent->timeSinceActivity());
406 case TR_AVAILABILITY:
407 return availabilityString(torrent->distributedCopies());
408 case TR_TOTAL_SIZE:
409 return unitString(torrent->totalSize());
410 case TR_INFOHASH_V1:
411 return hashString(torrent->infoHash().v1());
412 case TR_INFOHASH_V2:
413 return hashString(torrent->infoHash().v2());
416 return {};
419 QVariant TransferListModel::internalValue(const BitTorrent::Torrent *torrent, const int column, const bool alt) const
421 switch (column)
423 case TR_NAME:
424 return torrent->name();
425 case TR_QUEUE_POSITION:
426 return torrent->queuePosition();
427 case TR_SIZE:
428 return torrent->wantedSize();
429 case TR_PROGRESS:
430 return torrent->progress() * 100;
431 case TR_STATUS:
432 return QVariant::fromValue(torrent->state());
433 case TR_SEEDS:
434 return !alt ? torrent->seedsCount() : torrent->totalSeedsCount();
435 case TR_PEERS:
436 return !alt ? torrent->leechsCount() : torrent->totalLeechersCount();
437 case TR_DLSPEED:
438 return torrent->downloadPayloadRate();
439 case TR_UPSPEED:
440 return torrent->uploadPayloadRate();
441 case TR_ETA:
442 return torrent->eta();
443 case TR_RATIO:
444 return torrent->realRatio();
445 case TR_CATEGORY:
446 return torrent->category();
447 case TR_TAGS:
448 return QVariant::fromValue(torrent->tags());
449 case TR_ADD_DATE:
450 return torrent->addedTime();
451 case TR_SEED_DATE:
452 return torrent->completedTime();
453 case TR_TRACKER:
454 return torrent->currentTracker();
455 case TR_DLLIMIT:
456 return torrent->downloadLimit();
457 case TR_UPLIMIT:
458 return torrent->uploadLimit();
459 case TR_AMOUNT_DOWNLOADED:
460 return torrent->totalDownload();
461 case TR_AMOUNT_UPLOADED:
462 return torrent->totalUpload();
463 case TR_AMOUNT_DOWNLOADED_SESSION:
464 return torrent->totalPayloadDownload();
465 case TR_AMOUNT_UPLOADED_SESSION:
466 return torrent->totalPayloadUpload();
467 case TR_AMOUNT_LEFT:
468 return torrent->remainingSize();
469 case TR_TIME_ELAPSED:
470 return !alt ? torrent->activeTime() : torrent->finishedTime();
471 case TR_DOWNLOAD_PATH:
472 return torrent->downloadPath().data();
473 case TR_SAVE_PATH:
474 return torrent->savePath().data();
475 case TR_COMPLETED:
476 return torrent->completedSize();
477 case TR_RATIO_LIMIT:
478 return torrent->maxRatio();
479 case TR_SEEN_COMPLETE_DATE:
480 return torrent->lastSeenComplete();
481 case TR_LAST_ACTIVITY:
482 return torrent->timeSinceActivity();
483 case TR_AVAILABILITY:
484 return torrent->distributedCopies();
485 case TR_TOTAL_SIZE:
486 return torrent->totalSize();
487 case TR_INFOHASH_V1:
488 return QVariant::fromValue(torrent->infoHash().v1());
489 case TR_INFOHASH_V2:
490 return QVariant::fromValue(torrent->infoHash().v2());
493 return {};
496 QVariant TransferListModel::data(const QModelIndex &index, const int role) const
498 if (!index.isValid()) return {};
500 const BitTorrent::Torrent *torrent = m_torrentList.value(index.row());
501 if (!torrent) return {};
503 switch (role)
505 case Qt::ForegroundRole:
506 return m_stateThemeColors.value(torrent->state());
507 case Qt::DisplayRole:
508 return displayValue(torrent, index.column());
509 case UnderlyingDataRole:
510 return internalValue(torrent, index.column(), false);
511 case AdditionalUnderlyingDataRole:
512 return internalValue(torrent, index.column(), true);
513 case Qt::DecorationRole:
514 if (index.column() == TR_NAME)
515 return getIconByState(torrent->state());
516 break;
517 case Qt::ToolTipRole:
518 switch (index.column())
520 case TR_NAME:
521 case TR_STATUS:
522 case TR_CATEGORY:
523 case TR_TAGS:
524 case TR_TRACKER:
525 case TR_SAVE_PATH:
526 case TR_DOWNLOAD_PATH:
527 case TR_INFOHASH_V1:
528 case TR_INFOHASH_V2:
529 return displayValue(torrent, index.column());
531 break;
532 case Qt::TextAlignmentRole:
533 switch (index.column())
535 case TR_AMOUNT_DOWNLOADED:
536 case TR_AMOUNT_UPLOADED:
537 case TR_AMOUNT_DOWNLOADED_SESSION:
538 case TR_AMOUNT_UPLOADED_SESSION:
539 case TR_AMOUNT_LEFT:
540 case TR_COMPLETED:
541 case TR_SIZE:
542 case TR_TOTAL_SIZE:
543 case TR_ETA:
544 case TR_SEEDS:
545 case TR_PEERS:
546 case TR_UPSPEED:
547 case TR_DLSPEED:
548 case TR_UPLIMIT:
549 case TR_DLLIMIT:
550 case TR_RATIO_LIMIT:
551 case TR_RATIO:
552 case TR_QUEUE_POSITION:
553 case TR_LAST_ACTIVITY:
554 case TR_AVAILABILITY:
555 return QVariant(Qt::AlignRight | Qt::AlignVCenter);
557 break;
558 default:
559 break;
562 return {};
565 bool TransferListModel::setData(const QModelIndex &index, const QVariant &value, int role)
567 if (!index.isValid() || (role != Qt::DisplayRole)) return false;
569 BitTorrent::Torrent *const torrent = m_torrentList.value(index.row());
570 if (!torrent) return false;
572 // Category and Name columns can be edited
573 switch (index.column())
575 case TR_NAME:
576 torrent->setName(value.toString());
577 break;
578 case TR_CATEGORY:
579 torrent->setCategory(value.toString());
580 break;
581 default:
582 return false;
585 return true;
588 void TransferListModel::addTorrents(const QVector<BitTorrent::Torrent *> &torrents)
590 qsizetype row = m_torrentList.size();
591 const qsizetype total = row + torrents.size();
593 beginInsertRows({}, row, total);
595 m_torrentList.reserve(total);
596 for (BitTorrent::Torrent *torrent : torrents)
598 Q_ASSERT(!m_torrentMap.contains(torrent));
600 m_torrentList.append(torrent);
601 m_torrentMap[torrent] = row++;
604 endInsertRows();
607 Qt::ItemFlags TransferListModel::flags(const QModelIndex &index) const
609 if (!index.isValid()) return Qt::NoItemFlags;
611 // Explicitly mark as editable
612 return QAbstractListModel::flags(index) | Qt::ItemIsEditable;
615 BitTorrent::Torrent *TransferListModel::torrentHandle(const QModelIndex &index) const
617 if (!index.isValid()) return nullptr;
619 return m_torrentList.value(index.row());
622 void TransferListModel::handleTorrentAboutToBeRemoved(BitTorrent::Torrent *const torrent)
624 const int row = m_torrentMap.value(torrent, -1);
625 Q_ASSERT(row >= 0);
627 beginRemoveRows({}, row, row);
628 m_torrentList.removeAt(row);
629 m_torrentMap.remove(torrent);
630 for (int &value : m_torrentMap)
632 if (value > row)
633 --value;
635 endRemoveRows();
638 void TransferListModel::handleTorrentStatusUpdated(BitTorrent::Torrent *const torrent)
640 const int row = m_torrentMap.value(torrent, -1);
641 Q_ASSERT(row >= 0);
643 emit dataChanged(index(row, 0), index(row, columnCount() - 1));
646 void TransferListModel::handleTorrentsUpdated(const QVector<BitTorrent::Torrent *> &torrents)
648 const int columns = (columnCount() - 1);
650 if (torrents.size() <= (m_torrentList.size() * 0.5))
652 for (BitTorrent::Torrent *const torrent : torrents)
654 const int row = m_torrentMap.value(torrent, -1);
655 Q_ASSERT(row >= 0);
657 emit dataChanged(index(row, 0), index(row, columns));
660 else
662 // save the overhead when more than half of the torrent list needs update
663 emit dataChanged(index(0, 0), index((rowCount() - 1), columns));
667 void TransferListModel::configure()
669 const Preferences *pref = Preferences::instance();
671 HideZeroValuesMode hideZeroValuesMode = HideZeroValuesMode::Never;
672 if (pref->getHideZeroValues())
674 if (pref->getHideZeroComboValues() == 1)
675 hideZeroValuesMode = HideZeroValuesMode::Paused;
676 else
677 hideZeroValuesMode = HideZeroValuesMode::Always;
680 if (m_hideZeroValuesMode != hideZeroValuesMode)
682 m_hideZeroValuesMode = hideZeroValuesMode;
683 emit dataChanged(index(0, 0), index((rowCount() - 1), (columnCount() - 1)));
687 QIcon TransferListModel::getIconByState(const BitTorrent::TorrentState state) const
689 switch (state)
691 case BitTorrent::TorrentState::Downloading:
692 case BitTorrent::TorrentState::ForcedDownloading:
693 case BitTorrent::TorrentState::DownloadingMetadata:
694 case BitTorrent::TorrentState::ForcedDownloadingMetadata:
695 return m_downloadingIcon;
696 case BitTorrent::TorrentState::StalledDownloading:
697 return m_stalledDLIcon;
698 case BitTorrent::TorrentState::StalledUploading:
699 return m_stalledUPIcon;
700 case BitTorrent::TorrentState::Uploading:
701 case BitTorrent::TorrentState::ForcedUploading:
702 return m_uploadingIcon;
703 case BitTorrent::TorrentState::PausedDownloading:
704 return m_pausedIcon;
705 case BitTorrent::TorrentState::PausedUploading:
706 return m_completedIcon;
707 case BitTorrent::TorrentState::QueuedDownloading:
708 case BitTorrent::TorrentState::QueuedUploading:
709 return m_queuedIcon;
710 case BitTorrent::TorrentState::CheckingDownloading:
711 case BitTorrent::TorrentState::CheckingUploading:
712 case BitTorrent::TorrentState::CheckingResumeData:
713 case BitTorrent::TorrentState::Moving:
714 return m_checkingIcon;
715 case BitTorrent::TorrentState::Unknown:
716 case BitTorrent::TorrentState::MissingFiles:
717 case BitTorrent::TorrentState::Error:
718 return m_errorIcon;
719 default:
720 Q_ASSERT(false);
721 return m_errorIcon;