Use appropriate icon for "moving" torrents in transfer list
[qBittorrent.git] / src / gui / transferlistmodel.cpp
blob272ea253cfe118f780e3363f72ca97a6f4c84812
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"_s},
61 {BitTorrent::TorrentState::StalledDownloading, u"TransferList.StalledDownloading"_s},
62 {BitTorrent::TorrentState::DownloadingMetadata, u"TransferList.DownloadingMetadata"_s},
63 {BitTorrent::TorrentState::ForcedDownloadingMetadata, u"TransferList.ForcedDownloadingMetadata"_s},
64 {BitTorrent::TorrentState::ForcedDownloading, u"TransferList.ForcedDownloading"_s},
65 {BitTorrent::TorrentState::Uploading, u"TransferList.Uploading"_s},
66 {BitTorrent::TorrentState::StalledUploading, u"TransferList.StalledUploading"_s},
67 {BitTorrent::TorrentState::ForcedUploading, u"TransferList.ForcedUploading"_s},
68 {BitTorrent::TorrentState::QueuedDownloading, u"TransferList.QueuedDownloading"_s},
69 {BitTorrent::TorrentState::QueuedUploading, u"TransferList.QueuedUploading"_s},
70 {BitTorrent::TorrentState::CheckingDownloading, u"TransferList.CheckingDownloading"_s},
71 {BitTorrent::TorrentState::CheckingUploading, u"TransferList.CheckingUploading"_s},
72 {BitTorrent::TorrentState::CheckingResumeData, u"TransferList.CheckingResumeData"_s},
73 {BitTorrent::TorrentState::PausedDownloading, u"TransferList.PausedDownloading"_s},
74 {BitTorrent::TorrentState::PausedUploading, u"TransferList.PausedUploading"_s},
75 {BitTorrent::TorrentState::Moving, u"TransferList.Moving"_s},
76 {BitTorrent::TorrentState::MissingFiles, u"TransferList.MissingFiles"_s},
77 {BitTorrent::TorrentState::Error, u"TransferList.Error"_s}
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"_s, u"checking"_s)}
117 , m_completedIcon {UIThemeManager::instance()->getIcon(u"checked-completed"_s, u"completed"_s)}
118 , m_downloadingIcon {UIThemeManager::instance()->getIcon(u"downloading"_s)}
119 , m_errorIcon {UIThemeManager::instance()->getIcon(u"error"_s)}
120 , m_movingIcon {UIThemeManager::instance()->getIcon(u"set-location"_s)}
121 , m_pausedIcon {UIThemeManager::instance()->getIcon(u"stopped"_s, u"media-playback-pause"_s)}
122 , m_queuedIcon {UIThemeManager::instance()->getIcon(u"queued"_s)}
123 , m_stalledDLIcon {UIThemeManager::instance()->getIcon(u"stalledDL"_s)}
124 , m_stalledUPIcon {UIThemeManager::instance()->getIcon(u"stalledUP"_s)}
125 , m_uploadingIcon {UIThemeManager::instance()->getIcon(u"upload"_s, u"uploading"_s)}
127 configure();
128 connect(Preferences::instance(), &Preferences::changed, this, &TransferListModel::configure);
130 // Load the torrents
131 using namespace BitTorrent;
132 addTorrents(Session::instance()->torrents());
134 // Listen for torrent changes
135 connect(Session::instance(), &Session::torrentsLoaded, this, &TransferListModel::addTorrents);
136 connect(Session::instance(), &Session::torrentAboutToBeRemoved, this, &TransferListModel::handleTorrentAboutToBeRemoved);
137 connect(Session::instance(), &Session::torrentsUpdated, this, &TransferListModel::handleTorrentsUpdated);
139 connect(Session::instance(), &Session::torrentFinished, this, &TransferListModel::handleTorrentStatusUpdated);
140 connect(Session::instance(), &Session::torrentMetadataReceived, this, &TransferListModel::handleTorrentStatusUpdated);
141 connect(Session::instance(), &Session::torrentResumed, this, &TransferListModel::handleTorrentStatusUpdated);
142 connect(Session::instance(), &Session::torrentPaused, this, &TransferListModel::handleTorrentStatusUpdated);
143 connect(Session::instance(), &Session::torrentFinishedChecking, this, &TransferListModel::handleTorrentStatusUpdated);
146 int TransferListModel::rowCount(const QModelIndex &) const
148 return m_torrentList.size();
151 int TransferListModel::columnCount(const QModelIndex &) const
153 return NB_COLUMNS;
156 QVariant TransferListModel::headerData(const int section, const Qt::Orientation orientation, const int role) const
158 if (orientation == Qt::Horizontal)
160 if (role == Qt::DisplayRole)
162 switch (section)
164 case TR_QUEUE_POSITION: return QChar(u'#');
165 case TR_NAME: return tr("Name", "i.e: torrent name");
166 case TR_SIZE: return tr("Size", "i.e: torrent size");
167 case TR_PROGRESS: return tr("Progress", "% Done");
168 case TR_STATUS: return tr("Status", "Torrent status (e.g. downloading, seeding, paused)");
169 case TR_SEEDS: return tr("Seeds", "i.e. full sources (often untranslated)");
170 case TR_PEERS: return tr("Peers", "i.e. partial sources (often untranslated)");
171 case TR_DLSPEED: return tr("Down Speed", "i.e: Download speed");
172 case TR_UPSPEED: return tr("Up Speed", "i.e: Upload speed");
173 case TR_RATIO: return tr("Ratio", "Share ratio");
174 case TR_ETA: return tr("ETA", "i.e: Estimated Time of Arrival / Time left");
175 case TR_CATEGORY: return tr("Category");
176 case TR_TAGS: return tr("Tags");
177 case TR_ADD_DATE: return tr("Added On", "Torrent was added to transfer list on 01/01/2010 08:00");
178 case TR_SEED_DATE: return tr("Completed On", "Torrent was completed on 01/01/2010 08:00");
179 case TR_TRACKER: return tr("Tracker");
180 case TR_DLLIMIT: return tr("Down Limit", "i.e: Download limit");
181 case TR_UPLIMIT: return tr("Up Limit", "i.e: Upload limit");
182 case TR_AMOUNT_DOWNLOADED: return tr("Downloaded", "Amount of data downloaded (e.g. in MB)");
183 case TR_AMOUNT_UPLOADED: return tr("Uploaded", "Amount of data uploaded (e.g. in MB)");
184 case TR_AMOUNT_DOWNLOADED_SESSION: return tr("Session Download", "Amount of data downloaded since program open (e.g. in MB)");
185 case TR_AMOUNT_UPLOADED_SESSION: return tr("Session Upload", "Amount of data uploaded since program open (e.g. in MB)");
186 case TR_AMOUNT_LEFT: return tr("Remaining", "Amount of data left to download (e.g. in MB)");
187 case TR_TIME_ELAPSED: return tr("Time Active", "Time (duration) the torrent is active (not paused)");
188 case TR_SAVE_PATH: return tr("Save Path", "Torrent save path");
189 case TR_DOWNLOAD_PATH: return tr("Incomplete Save Path", "Torrent incomplete save path");
190 case TR_COMPLETED: return tr("Completed", "Amount of data completed (e.g. in MB)");
191 case TR_RATIO_LIMIT: return tr("Ratio Limit", "Upload share ratio limit");
192 case TR_SEEN_COMPLETE_DATE: return tr("Last Seen Complete", "Indicates the time when the torrent was last seen complete/whole");
193 case TR_LAST_ACTIVITY: return tr("Last Activity", "Time passed since a chunk was downloaded/uploaded");
194 case TR_TOTAL_SIZE: return tr("Total Size", "i.e. Size including unwanted data");
195 case TR_AVAILABILITY: return tr("Availability", "The number of distributed copies of the torrent");
196 case TR_INFOHASH_V1: return tr("Info Hash v1", "i.e: torrent info hash v1");
197 case TR_INFOHASH_V2: return tr("Info Hash v2", "i.e: torrent info hash v2");
198 case TR_REANNOUNCE: return tr("Reannounce In", "Indicates the time until next trackers reannounce");
199 default: return {};
202 else if (role == Qt::TextAlignmentRole)
204 switch (section)
206 case TR_AMOUNT_DOWNLOADED:
207 case TR_AMOUNT_UPLOADED:
208 case TR_AMOUNT_DOWNLOADED_SESSION:
209 case TR_AMOUNT_UPLOADED_SESSION:
210 case TR_AMOUNT_LEFT:
211 case TR_COMPLETED:
212 case TR_SIZE:
213 case TR_TOTAL_SIZE:
214 case TR_ETA:
215 case TR_SEEDS:
216 case TR_PEERS:
217 case TR_UPSPEED:
218 case TR_DLSPEED:
219 case TR_UPLIMIT:
220 case TR_DLLIMIT:
221 case TR_RATIO_LIMIT:
222 case TR_RATIO:
223 case TR_QUEUE_POSITION:
224 case TR_LAST_ACTIVITY:
225 case TR_AVAILABILITY:
226 case TR_REANNOUNCE:
227 return QVariant(Qt::AlignRight | Qt::AlignVCenter);
228 default:
229 return QAbstractListModel::headerData(section, orientation, role);
234 return QAbstractListModel::headerData(section, orientation, role);
237 QString TransferListModel::displayValue(const BitTorrent::Torrent *torrent, const int column) const
239 bool hideValues = false;
240 if (m_hideZeroValuesMode == HideZeroValuesMode::Always)
241 hideValues = true;
242 else if (m_hideZeroValuesMode == HideZeroValuesMode::Paused)
243 hideValues = (torrent->state() == BitTorrent::TorrentState::PausedDownloading);
245 const auto availabilityString = [hideValues](const qreal value) -> QString
247 if (hideValues && (value == 0))
248 return {};
249 return (value >= 0)
250 ? Utils::String::fromDouble(value, 3)
251 : tr("N/A");
254 const auto unitString = [hideValues](const qint64 value, const bool isSpeedUnit = false) -> QString
256 return (hideValues && (value == 0))
257 ? QString {} : Utils::Misc::friendlyUnit(value, isSpeedUnit);
260 const auto limitString = [hideValues](const qint64 value) -> QString
262 if (hideValues && (value <= 0))
263 return {};
265 return (value > 0)
266 ? Utils::Misc::friendlyUnit(value, true)
267 : C_INFINITY;
270 const auto amountString = [hideValues](const qint64 value, const qint64 total) -> QString
272 if (hideValues && (value == 0) && (total == 0))
273 return {};
274 return u"%1 (%2)"_s.arg(QString::number(value), QString::number(total));
277 const auto etaString = [hideValues](const qlonglong value) -> QString
279 if (hideValues && (value >= MAX_ETA))
280 return {};
281 return Utils::Misc::userFriendlyDuration(value, MAX_ETA);
284 const auto ratioString = [hideValues](const qreal value) -> QString
286 if (hideValues && (value <= 0))
287 return {};
289 return ((static_cast<int>(value) == -1) || (value > BitTorrent::Torrent::MAX_RATIO))
290 ? C_INFINITY : Utils::String::fromDouble(value, 2);
293 const auto queuePositionString = [](const qint64 value) -> QString
295 return (value >= 0) ? QString::number(value + 1) : u"*"_s;
298 const auto lastActivityString = [hideValues](qint64 value) -> QString
300 if (hideValues && ((value < 0) || (value >= MAX_ETA)))
301 return {};
303 // Show '< 1m ago' when elapsed time is 0
304 if (value == 0)
305 value = 1;
307 return (value >= 0)
308 ? tr("%1 ago", "e.g.: 1h 20m ago").arg(Utils::Misc::userFriendlyDuration(value))
309 : Utils::Misc::userFriendlyDuration(value);
312 const auto timeElapsedString = [hideValues](const qint64 elapsedTime, const qint64 seedingTime) -> QString
314 if (seedingTime <= 0)
316 if (hideValues && (elapsedTime == 0))
317 return {};
318 return Utils::Misc::userFriendlyDuration(elapsedTime);
321 return tr("%1 (seeded for %2)", "e.g. 4m39s (seeded for 3m10s)")
322 .arg(Utils::Misc::userFriendlyDuration(elapsedTime)
323 , Utils::Misc::userFriendlyDuration(seedingTime));
326 const auto progressString = [](const qreal progress) -> QString
328 return (progress >= 1)
329 ? u"100%"_s
330 : (Utils::String::fromDouble((progress * 100), 1) + u'%');
333 const auto statusString = [this](const BitTorrent::TorrentState state, const QString &errorMessage) -> QString
335 return (state == BitTorrent::TorrentState::Error)
336 ? m_statusStrings[state] + u": " + errorMessage
337 : m_statusStrings[state];
340 const auto hashString = [hideValues](const auto &hash) -> QString
342 if (hideValues && !hash.isValid())
343 return {};
344 return hash.isValid() ? hash.toString() : tr("N/A");
347 const auto reannounceString = [hideValues](const qint64 time) -> QString
349 if (hideValues && (time == 0))
350 return {};
351 return Utils::Misc::userFriendlyDuration(time);
354 switch (column)
356 case TR_NAME:
357 return torrent->name();
358 case TR_QUEUE_POSITION:
359 return queuePositionString(torrent->queuePosition());
360 case TR_SIZE:
361 return unitString(torrent->wantedSize());
362 case TR_PROGRESS:
363 return progressString(torrent->progress());
364 case TR_STATUS:
365 return statusString(torrent->state(), torrent->error());
366 case TR_SEEDS:
367 return amountString(torrent->seedsCount(), torrent->totalSeedsCount());
368 case TR_PEERS:
369 return amountString(torrent->leechsCount(), torrent->totalLeechersCount());
370 case TR_DLSPEED:
371 return unitString(torrent->downloadPayloadRate(), true);
372 case TR_UPSPEED:
373 return unitString(torrent->uploadPayloadRate(), true);
374 case TR_ETA:
375 return etaString(torrent->eta());
376 case TR_RATIO:
377 return ratioString(torrent->realRatio());
378 case TR_RATIO_LIMIT:
379 return ratioString(torrent->maxRatio());
380 case TR_CATEGORY:
381 return torrent->category();
382 case TR_TAGS:
383 return torrent->tags().join(u", "_s);
384 case TR_ADD_DATE:
385 return QLocale().toString(torrent->addedTime().toLocalTime(), QLocale::ShortFormat);
386 case TR_SEED_DATE:
387 return QLocale().toString(torrent->completedTime().toLocalTime(), QLocale::ShortFormat);
388 case TR_TRACKER:
389 return torrent->currentTracker();
390 case TR_DLLIMIT:
391 return limitString(torrent->downloadLimit());
392 case TR_UPLIMIT:
393 return limitString(torrent->uploadLimit());
394 case TR_AMOUNT_DOWNLOADED:
395 return unitString(torrent->totalDownload());
396 case TR_AMOUNT_UPLOADED:
397 return unitString(torrent->totalUpload());
398 case TR_AMOUNT_DOWNLOADED_SESSION:
399 return unitString(torrent->totalPayloadDownload());
400 case TR_AMOUNT_UPLOADED_SESSION:
401 return unitString(torrent->totalPayloadUpload());
402 case TR_AMOUNT_LEFT:
403 return unitString(torrent->remainingSize());
404 case TR_TIME_ELAPSED:
405 return timeElapsedString(torrent->activeTime(), torrent->finishedTime());
406 case TR_SAVE_PATH:
407 return torrent->savePath().toString();
408 case TR_DOWNLOAD_PATH:
409 return torrent->downloadPath().toString();
410 case TR_COMPLETED:
411 return unitString(torrent->completedSize());
412 case TR_SEEN_COMPLETE_DATE:
413 return QLocale().toString(torrent->lastSeenComplete().toLocalTime(), QLocale::ShortFormat);
414 case TR_LAST_ACTIVITY:
415 return lastActivityString(torrent->timeSinceActivity());
416 case TR_AVAILABILITY:
417 return availabilityString(torrent->distributedCopies());
418 case TR_TOTAL_SIZE:
419 return unitString(torrent->totalSize());
420 case TR_INFOHASH_V1:
421 return hashString(torrent->infoHash().v1());
422 case TR_INFOHASH_V2:
423 return hashString(torrent->infoHash().v2());
424 case TR_REANNOUNCE:
425 return reannounceString(torrent->nextAnnounce());
428 return {};
431 QVariant TransferListModel::internalValue(const BitTorrent::Torrent *torrent, const int column, const bool alt) const
433 switch (column)
435 case TR_NAME:
436 return torrent->name();
437 case TR_QUEUE_POSITION:
438 return torrent->queuePosition();
439 case TR_SIZE:
440 return torrent->wantedSize();
441 case TR_PROGRESS:
442 return torrent->progress() * 100;
443 case TR_STATUS:
444 return QVariant::fromValue(torrent->state());
445 case TR_SEEDS:
446 return !alt ? torrent->seedsCount() : torrent->totalSeedsCount();
447 case TR_PEERS:
448 return !alt ? torrent->leechsCount() : torrent->totalLeechersCount();
449 case TR_DLSPEED:
450 return torrent->downloadPayloadRate();
451 case TR_UPSPEED:
452 return torrent->uploadPayloadRate();
453 case TR_ETA:
454 return torrent->eta();
455 case TR_RATIO:
456 return torrent->realRatio();
457 case TR_CATEGORY:
458 return torrent->category();
459 case TR_TAGS:
460 return QVariant::fromValue(torrent->tags());
461 case TR_ADD_DATE:
462 return torrent->addedTime();
463 case TR_SEED_DATE:
464 return torrent->completedTime();
465 case TR_TRACKER:
466 return torrent->currentTracker();
467 case TR_DLLIMIT:
468 return torrent->downloadLimit();
469 case TR_UPLIMIT:
470 return torrent->uploadLimit();
471 case TR_AMOUNT_DOWNLOADED:
472 return torrent->totalDownload();
473 case TR_AMOUNT_UPLOADED:
474 return torrent->totalUpload();
475 case TR_AMOUNT_DOWNLOADED_SESSION:
476 return torrent->totalPayloadDownload();
477 case TR_AMOUNT_UPLOADED_SESSION:
478 return torrent->totalPayloadUpload();
479 case TR_AMOUNT_LEFT:
480 return torrent->remainingSize();
481 case TR_TIME_ELAPSED:
482 return !alt ? torrent->activeTime() : torrent->finishedTime();
483 case TR_DOWNLOAD_PATH:
484 return torrent->downloadPath().data();
485 case TR_SAVE_PATH:
486 return torrent->savePath().data();
487 case TR_COMPLETED:
488 return torrent->completedSize();
489 case TR_RATIO_LIMIT:
490 return torrent->maxRatio();
491 case TR_SEEN_COMPLETE_DATE:
492 return torrent->lastSeenComplete();
493 case TR_LAST_ACTIVITY:
494 return torrent->timeSinceActivity();
495 case TR_AVAILABILITY:
496 return torrent->distributedCopies();
497 case TR_TOTAL_SIZE:
498 return torrent->totalSize();
499 case TR_INFOHASH_V1:
500 return QVariant::fromValue(torrent->infoHash().v1());
501 case TR_INFOHASH_V2:
502 return QVariant::fromValue(torrent->infoHash().v2());
503 case TR_REANNOUNCE:
504 return torrent->nextAnnounce();
507 return {};
510 QVariant TransferListModel::data(const QModelIndex &index, const int role) const
512 if (!index.isValid()) return {};
514 const BitTorrent::Torrent *torrent = m_torrentList.value(index.row());
515 if (!torrent) return {};
517 switch (role)
519 case Qt::ForegroundRole:
520 return m_stateThemeColors.value(torrent->state());
521 case Qt::DisplayRole:
522 return displayValue(torrent, index.column());
523 case UnderlyingDataRole:
524 return internalValue(torrent, index.column(), false);
525 case AdditionalUnderlyingDataRole:
526 return internalValue(torrent, index.column(), true);
527 case Qt::DecorationRole:
528 if (index.column() == TR_NAME)
529 return getIconByState(torrent->state());
530 break;
531 case Qt::ToolTipRole:
532 switch (index.column())
534 case TR_NAME:
535 case TR_STATUS:
536 case TR_CATEGORY:
537 case TR_TAGS:
538 case TR_TRACKER:
539 case TR_SAVE_PATH:
540 case TR_DOWNLOAD_PATH:
541 case TR_INFOHASH_V1:
542 case TR_INFOHASH_V2:
543 return displayValue(torrent, index.column());
545 break;
546 case Qt::TextAlignmentRole:
547 switch (index.column())
549 case TR_AMOUNT_DOWNLOADED:
550 case TR_AMOUNT_UPLOADED:
551 case TR_AMOUNT_DOWNLOADED_SESSION:
552 case TR_AMOUNT_UPLOADED_SESSION:
553 case TR_AMOUNT_LEFT:
554 case TR_COMPLETED:
555 case TR_SIZE:
556 case TR_TOTAL_SIZE:
557 case TR_ETA:
558 case TR_SEEDS:
559 case TR_PEERS:
560 case TR_UPSPEED:
561 case TR_DLSPEED:
562 case TR_UPLIMIT:
563 case TR_DLLIMIT:
564 case TR_RATIO_LIMIT:
565 case TR_RATIO:
566 case TR_QUEUE_POSITION:
567 case TR_LAST_ACTIVITY:
568 case TR_AVAILABILITY:
569 case TR_REANNOUNCE:
570 return QVariant(Qt::AlignRight | Qt::AlignVCenter);
572 break;
573 default:
574 break;
577 return {};
580 bool TransferListModel::setData(const QModelIndex &index, const QVariant &value, int role)
582 if (!index.isValid() || (role != Qt::DisplayRole)) return false;
584 BitTorrent::Torrent *const torrent = m_torrentList.value(index.row());
585 if (!torrent) return false;
587 // Category and Name columns can be edited
588 switch (index.column())
590 case TR_NAME:
591 torrent->setName(value.toString());
592 break;
593 case TR_CATEGORY:
594 torrent->setCategory(value.toString());
595 break;
596 default:
597 return false;
600 return true;
603 void TransferListModel::addTorrents(const QVector<BitTorrent::Torrent *> &torrents)
605 qsizetype row = m_torrentList.size();
606 const qsizetype total = row + torrents.size();
608 beginInsertRows({}, row, total);
610 m_torrentList.reserve(total);
611 for (BitTorrent::Torrent *torrent : torrents)
613 Q_ASSERT(!m_torrentMap.contains(torrent));
615 m_torrentList.append(torrent);
616 m_torrentMap[torrent] = row++;
619 endInsertRows();
622 Qt::ItemFlags TransferListModel::flags(const QModelIndex &index) const
624 if (!index.isValid()) return Qt::NoItemFlags;
626 // Explicitly mark as editable
627 return QAbstractListModel::flags(index) | Qt::ItemIsEditable;
630 BitTorrent::Torrent *TransferListModel::torrentHandle(const QModelIndex &index) const
632 if (!index.isValid()) return nullptr;
634 return m_torrentList.value(index.row());
637 void TransferListModel::handleTorrentAboutToBeRemoved(BitTorrent::Torrent *const torrent)
639 const int row = m_torrentMap.value(torrent, -1);
640 Q_ASSERT(row >= 0);
642 beginRemoveRows({}, row, row);
643 m_torrentList.removeAt(row);
644 m_torrentMap.remove(torrent);
645 for (int &value : m_torrentMap)
647 if (value > row)
648 --value;
650 endRemoveRows();
653 void TransferListModel::handleTorrentStatusUpdated(BitTorrent::Torrent *const torrent)
655 const int row = m_torrentMap.value(torrent, -1);
656 Q_ASSERT(row >= 0);
658 emit dataChanged(index(row, 0), index(row, columnCount() - 1));
661 void TransferListModel::handleTorrentsUpdated(const QVector<BitTorrent::Torrent *> &torrents)
663 const int columns = (columnCount() - 1);
665 if (torrents.size() <= (m_torrentList.size() * 0.5))
667 for (BitTorrent::Torrent *const torrent : torrents)
669 const int row = m_torrentMap.value(torrent, -1);
670 Q_ASSERT(row >= 0);
672 emit dataChanged(index(row, 0), index(row, columns));
675 else
677 // save the overhead when more than half of the torrent list needs update
678 emit dataChanged(index(0, 0), index((rowCount() - 1), columns));
682 void TransferListModel::configure()
684 const Preferences *pref = Preferences::instance();
686 HideZeroValuesMode hideZeroValuesMode = HideZeroValuesMode::Never;
687 if (pref->getHideZeroValues())
689 if (pref->getHideZeroComboValues() == 1)
690 hideZeroValuesMode = HideZeroValuesMode::Paused;
691 else
692 hideZeroValuesMode = HideZeroValuesMode::Always;
695 if (m_hideZeroValuesMode != hideZeroValuesMode)
697 m_hideZeroValuesMode = hideZeroValuesMode;
698 emit dataChanged(index(0, 0), index((rowCount() - 1), (columnCount() - 1)));
702 QIcon TransferListModel::getIconByState(const BitTorrent::TorrentState state) const
704 switch (state)
706 case BitTorrent::TorrentState::Downloading:
707 case BitTorrent::TorrentState::ForcedDownloading:
708 case BitTorrent::TorrentState::DownloadingMetadata:
709 case BitTorrent::TorrentState::ForcedDownloadingMetadata:
710 return m_downloadingIcon;
711 case BitTorrent::TorrentState::StalledDownloading:
712 return m_stalledDLIcon;
713 case BitTorrent::TorrentState::StalledUploading:
714 return m_stalledUPIcon;
715 case BitTorrent::TorrentState::Uploading:
716 case BitTorrent::TorrentState::ForcedUploading:
717 return m_uploadingIcon;
718 case BitTorrent::TorrentState::PausedDownloading:
719 return m_pausedIcon;
720 case BitTorrent::TorrentState::PausedUploading:
721 return m_completedIcon;
722 case BitTorrent::TorrentState::QueuedDownloading:
723 case BitTorrent::TorrentState::QueuedUploading:
724 return m_queuedIcon;
725 case BitTorrent::TorrentState::CheckingDownloading:
726 case BitTorrent::TorrentState::CheckingUploading:
727 case BitTorrent::TorrentState::CheckingResumeData:
728 return m_checkingIcon;
729 case BitTorrent::TorrentState::Moving:
730 return m_movingIcon;
731 case BitTorrent::TorrentState::Unknown:
732 case BitTorrent::TorrentState::MissingFiles:
733 case BitTorrent::TorrentState::Error:
734 return m_errorIcon;
735 default:
736 Q_ASSERT(false);
737 return m_errorIcon;