source: trunk/qt/torrent-delegate.cc @ 14377

Last change on this file since 14377 was 14377, checked in by mikedld, 8 years ago

Strip spaces around :: in C++ code (Qt client)

  • Property svn:keywords set to Date Rev Author Id
File size: 15.2 KB
Line 
1/*
2 * This file Copyright (C) 2009-2014 Mnemosyne LLC
3 *
4 * It may be used under the GNU Public License v2 or v3 licenses,
5 * or any future license endorsed by Mnemosyne LLC.
6 *
7 * $Id: torrent-delegate.cc 14377 2014-12-12 23:05:10Z mikedld $
8 */
9
10
11#include <iostream>
12
13#include <QApplication>
14#include <QFont>
15#include <QFontMetrics>
16#include <QIcon>
17#include <QModelIndex>
18#include <QPainter>
19#include <QPixmap>
20#include <QPixmapCache>
21#include <QStyleOptionProgressBar>
22
23#include "formatter.h"
24#include "torrent.h"
25#include "torrent-delegate.h"
26#include "torrent-model.h"
27
28enum
29{
30  GUI_PAD = 6,
31  BAR_HEIGHT = 12
32};
33
34QColor TorrentDelegate::greenBrush;
35QColor TorrentDelegate::blueBrush;
36QColor TorrentDelegate::silverBrush;
37QColor TorrentDelegate::greenBack;
38QColor TorrentDelegate::blueBack;
39QColor TorrentDelegate::silverBack;
40
41TorrentDelegate::TorrentDelegate (QObject * parent):
42  QStyledItemDelegate (parent),
43  myProgressBarStyle (new QStyleOptionProgressBar)
44{
45  myProgressBarStyle->minimum = 0;
46  myProgressBarStyle->maximum = 1000;
47
48  greenBrush = QColor ("forestgreen");
49  greenBack = QColor ("darkseagreen");
50
51  blueBrush = QColor ("steelblue");
52  blueBack = QColor ("lightgrey");
53
54  silverBrush = QColor ("silver");
55  silverBack = QColor ("grey");
56}
57
58TorrentDelegate::~TorrentDelegate ()
59{
60  delete myProgressBarStyle;
61}
62
63/***
64****
65***/
66
67QSize
68TorrentDelegate::margin (const QStyle& style) const
69{
70  Q_UNUSED (style);
71
72  return QSize (4, 4);
73}
74
75QString
76TorrentDelegate::progressString (const Torrent& tor) const
77{
78  const bool isMagnet (!tor.hasMetadata());
79  const bool isDone (tor.isDone ());
80  const bool isSeed (tor.isSeed ());
81  const uint64_t haveTotal (tor.haveTotal());
82  QString str;
83  double seedRatio;
84  const bool hasSeedRatio (tor.getSeedRatio (seedRatio));
85
86  if (isMagnet) // magnet link with no metadata
87    {
88      // %1 is the percentage of torrent metadata downloaded
89      str = tr ("Magnetized transfer - retrieving metadata (%1%)")
90            .arg (Formatter::percentToString (tor.metadataPercentDone() * 100.0));
91    }
92  else if (!isDone) // downloading
93    {
94      /* %1 is how much we've got,
95         %2 is how much we'll have when done,
96         %3 is a percentage of the two */
97      str = tr ("%1 of %2 (%3%)")
98            .arg (Formatter::sizeToString (haveTotal))
99            .arg (Formatter::sizeToString (tor.sizeWhenDone()))
100            .arg (Formatter::percentToString (tor.percentDone() * 100.0));
101    }
102  else if (!isSeed) // partial seed
103    {
104      if (hasSeedRatio)
105        {
106          /* %1 is how much we've got,
107             %2 is the torrent's total size,
108             %3 is a percentage of the two,
109             %4 is how much we've uploaded,
110             %5 is our upload-to-download ratio
111             %6 is the ratio we want to reach before we stop uploading */
112          str = tr ("%1 of %2 (%3%), uploaded %4 (Ratio: %5 Goal: %6)")
113                .arg (Formatter::sizeToString (haveTotal))
114                .arg (Formatter::sizeToString (tor.totalSize()))
115                .arg (Formatter::percentToString (tor.percentComplete() * 100.0))
116                .arg (Formatter::sizeToString (tor.uploadedEver()))
117                .arg (Formatter::ratioToString (tor.ratio()))
118                .arg (Formatter::ratioToString (seedRatio));
119        }
120        else
121        {
122            /* %1 is how much we've got,
123               %2 is the torrent's total size,
124               %3 is a percentage of the two,
125               %4 is how much we've uploaded,
126               %5 is our upload-to-download ratio */
127            str = tr ("%1 of %2 (%3%), uploaded %4 (Ratio: %5)")
128                  .arg (Formatter::sizeToString (haveTotal))
129                  .arg (Formatter::sizeToString (tor.totalSize()))
130                  .arg (Formatter::percentToString (tor.percentComplete() * 100.0))
131                  .arg (Formatter::sizeToString (tor.uploadedEver()))
132                  .arg (Formatter::ratioToString (tor.ratio()));
133        }
134    }
135  else // seeding
136    {
137      if (hasSeedRatio)
138        {
139          /* %1 is the torrent's total size,
140             %2 is how much we've uploaded,
141             %3 is our upload-to-download ratio,
142             %4 is the ratio we want to reach before we stop uploading */
143          str = tr ("%1, uploaded %2 (Ratio: %3 Goal: %4)")
144                .arg (Formatter::sizeToString (haveTotal))
145                .arg (Formatter::sizeToString (tor.uploadedEver()))
146                .arg (Formatter::ratioToString (tor.ratio()))
147                .arg (Formatter::ratioToString (seedRatio));
148        }
149      else // seeding w/o a ratio
150        {
151          /* %1 is the torrent's total size,
152             %2 is how much we've uploaded,
153             %3 is our upload-to-download ratio */
154          str = tr ("%1, uploaded %2 (Ratio: %3)")
155                .arg (Formatter::sizeToString (haveTotal))
156                .arg (Formatter::sizeToString (tor.uploadedEver()))
157                .arg (Formatter::ratioToString (tor.ratio()));
158        }
159    }
160
161  // add time when downloading
162  if ((hasSeedRatio && tor.isSeeding()) || tor.isDownloading())
163    {
164      str += tr (" - ");
165      if (tor.hasETA ())
166        str += tr ("%1 left").arg (Formatter::timeToString (tor.getETA ()));
167      else
168        str += tr ("Remaining time unknown");
169    }
170
171    return str;
172}
173
174QString
175TorrentDelegate::shortTransferString (const Torrent& tor) const
176{
177  QString str;
178  const bool haveMeta (tor.hasMetadata());
179  const bool haveDown (haveMeta && ((tor.webseedsWeAreDownloadingFrom()>0) || (tor.peersWeAreDownloadingFrom()>0)));
180  const bool haveUp (haveMeta && tor.peersWeAreUploadingTo()>0);
181
182  if (haveDown)
183    str = tr ("%1   %2")
184          .arg(Formatter::downloadSpeedToString(tor.downloadSpeed()))
185          .arg(Formatter::uploadSpeedToString(tor.uploadSpeed()));
186
187  else if (haveUp)
188    str = Formatter::uploadSpeedToString(tor.uploadSpeed());
189
190  return str;
191}
192
193QString
194TorrentDelegate::shortStatusString (const Torrent& tor) const
195{
196  QString str;
197  static const QChar ratioSymbol (0x262F);
198
199  switch (tor.getActivity ())
200    {
201      case TR_STATUS_CHECK:
202        str = tr ("Verifying local data (%1% tested)").arg (Formatter::percentToString (tor.getVerifyProgress()*100.0));
203        break;
204
205      case TR_STATUS_DOWNLOAD:
206      case TR_STATUS_SEED:
207        str = tr("%1    %2 %3")
208              .arg(shortTransferString(tor))
209              .arg(tr("Ratio:"))
210              .arg(Formatter::ratioToString(tor.ratio()));
211        break;
212
213      default:
214        str = tor.activityString ();
215        break;
216    }
217
218  return str;
219}
220
221QString
222TorrentDelegate::statusString (const Torrent& tor) const
223{
224  QString str;
225
226  if (tor.hasError ())
227    {
228      str = tor.getError ();
229    }
230  else switch (tor.getActivity ())
231    {
232      case TR_STATUS_STOPPED:
233      case TR_STATUS_CHECK_WAIT:
234      case TR_STATUS_CHECK:
235      case TR_STATUS_DOWNLOAD_WAIT:
236      case TR_STATUS_SEED_WAIT:
237        str = shortStatusString (tor);
238        break;
239
240      case TR_STATUS_DOWNLOAD:
241        if (!tor.hasMetadata())
242          {
243            str = tr ("Downloading metadata from %n peer(s) (%1% done)", 0, tor.peersWeAreDownloadingFrom ())
244                  .arg (Formatter::percentToString (100.0 * tor.metadataPercentDone ()));
245          }
246        else
247          {
248            /* 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() */
249            str = tr ("Downloading from %1 of %n connected peer(s)", 0, tor.connectedPeersAndWebseeds ())
250                  .arg (tor.peersWeAreDownloadingFrom ());
251
252            if (tor.webseedsWeAreDownloadingFrom())
253              str += tr(" and %n web seed(s)", "", tor.webseedsWeAreDownloadingFrom());
254          }
255        break;
256
257      case TR_STATUS_SEED:
258        str = tr ("Seeding to %1 of %n connected peer(s)", 0, tor.connectedPeers ())
259              .arg (tor.peersWeAreUploadingTo ());
260        break;
261
262      default:
263        str = tr ("Error");
264        break;
265    }
266
267  if (tor.isReadyToTransfer ())
268    {
269      QString s = shortTransferString (tor);
270      if (!s.isEmpty ())
271        str += tr (" - ") + s;
272    }
273
274  return str;
275}
276
277/***
278****
279***/
280
281namespace
282{
283  int MAX3 (int a, int b, int c)
284    {
285      const int ab (a > b ? a : b);
286      return ab > c ? ab : c;
287    }
288}
289
290QSize
291TorrentDelegate::sizeHint (const QStyleOptionViewItem& option, const Torrent& tor) const
292{
293  const QStyle* style (QApplication::style ());
294  static const int iconSize (style->pixelMetric (QStyle::PM_MessageBoxIconSize));
295
296  QFont nameFont (option.font);
297  nameFont.setWeight (QFont::Bold);
298  const QFontMetrics nameFM (nameFont);
299  const QString nameStr (tor.name ());
300  const int nameWidth = nameFM.width (nameStr);
301  QFont statusFont (option.font);
302  statusFont.setPointSize (int (option.font.pointSize () * 0.9));
303  const QFontMetrics statusFM (statusFont);
304  const QString statusStr (statusString (tor));
305  const int statusWidth = statusFM.width (statusStr);
306  QFont progressFont (statusFont);
307  const QFontMetrics progressFM (progressFont);
308  const QString progressStr (progressString (tor));
309  const int progressWidth = progressFM.width (progressStr);
310  const QSize m (margin (*style));
311  return QSize (m.width()*2 + iconSize + GUI_PAD + MAX3 (nameWidth, statusWidth, progressWidth),
312                //m.height()*3 + nameFM.lineSpacing() + statusFM.lineSpacing()*2 + progressFM.lineSpacing());
313                m.height()*3 + nameFM.lineSpacing() + statusFM.lineSpacing() + BAR_HEIGHT + progressFM.lineSpacing());
314}
315
316QSize
317TorrentDelegate::sizeHint (const QStyleOptionViewItem  & option,
318                           const QModelIndex           & index) const
319{
320  const Torrent * tor (index.data (TorrentModel::TorrentRole).value<const Torrent*>());
321  return sizeHint (option, *tor);
322}
323
324void
325TorrentDelegate::paint (QPainter                    * painter,
326                        const QStyleOptionViewItem  & option,
327                        const QModelIndex           & index) const
328{
329  const Torrent * tor (index.data (TorrentModel::TorrentRole).value<const Torrent*>());
330  painter->save ();
331  painter->setClipRect (option.rect);
332  drawTorrent (painter, option, *tor);
333  painter->restore ();
334}
335
336void
337TorrentDelegate::setProgressBarPercentDone (const QStyleOptionViewItem & option,
338                                            const Torrent              & tor) const
339{
340  double seedRatioLimit;
341  if (tor.isSeeding() && tor.getSeedRatio(seedRatioLimit))
342    {
343      const double seedRateRatio = tor.ratio() / seedRatioLimit;
344      const int scaledProgress = seedRateRatio * (myProgressBarStyle->maximum - myProgressBarStyle->minimum);
345      myProgressBarStyle->progress = myProgressBarStyle->minimum + scaledProgress;
346    }
347  else
348    {
349      const bool isMagnet (!tor.hasMetadata ());
350      myProgressBarStyle->direction = option.direction;
351      myProgressBarStyle->progress = int(myProgressBarStyle->minimum + (((isMagnet ? tor.metadataPercentDone() : tor.percentDone()) * (myProgressBarStyle->maximum - myProgressBarStyle->minimum))));
352    }
353}
354
355void
356TorrentDelegate::drawTorrent (QPainter                   * painter,
357                              const QStyleOptionViewItem & option,
358                              const Torrent              & tor) const
359{
360  const QStyle * style (QApplication::style ());
361  static const int iconSize (style->pixelMetric (QStyle::PM_LargeIconSize));
362  QFont nameFont (option.font);
363  nameFont.setWeight (QFont::Bold);
364  const QFontMetrics nameFM (nameFont);
365  const QString nameStr (tor.name ());
366  const QSize nameSize (nameFM.size (0, nameStr));
367  QFont statusFont (option.font);
368  statusFont.setPointSize (int (option.font.pointSize () * 0.9));
369  const QFontMetrics statusFM (statusFont);
370  const QString statusStr (progressString (tor));
371  QFont progressFont (statusFont);
372  const QFontMetrics progressFM (progressFont);
373  const QString progressStr (statusString (tor));
374  const bool isPaused (tor.isPaused ());
375
376  painter->save ();
377
378  if (option.state & QStyle::State_Selected)
379    {
380      QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
381                              ? QPalette::Normal : QPalette::Disabled;
382      if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
383        cg = QPalette::Inactive;
384
385      painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight));
386    }
387
388  QIcon::Mode im;
389  if (isPaused || !(option.state & QStyle::State_Enabled))
390    im = QIcon::Disabled;
391  else if (option.state & QStyle::State_Selected)
392    im = QIcon::Selected;
393  else
394    im = QIcon::Normal;
395
396  QIcon::State qs;
397  if (isPaused)
398    qs = QIcon::Off;
399  else
400    qs = QIcon::On;
401
402  QPalette::ColorGroup cg = QPalette::Normal;
403  if (isPaused || !(option.state & QStyle::State_Enabled))
404    cg = QPalette::Disabled;
405  if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
406    cg = QPalette::Inactive;
407
408  QPalette::ColorRole cr;
409  if (option.state & QStyle::State_Selected)
410    cr = QPalette::HighlightedText;
411  else
412    cr = QPalette::Text;
413
414  QStyle::State progressBarState (option.state);
415  if (isPaused)
416    progressBarState = QStyle::State_None;
417  progressBarState |= QStyle::State_Small;
418
419  // layout
420  const QSize m (margin (*style));
421  QRect fillArea (option.rect);
422  fillArea.adjust (m.width(), m.height(), -m.width(), -m.height());
423  QRect iconArea (fillArea.x (), fillArea.y () +  (fillArea.height () - iconSize) / 2, iconSize, iconSize);
424  QRect nameArea (iconArea.x () + iconArea.width () + GUI_PAD, fillArea.y (),
425                  fillArea.width () - GUI_PAD - iconArea.width (), nameSize.height ());
426  QRect statusArea (nameArea);
427  statusArea.moveTop (nameArea.y () + nameFM.lineSpacing ());
428  statusArea.setHeight (nameSize.height ());
429  QRect barArea (statusArea);
430  barArea.setHeight (BAR_HEIGHT);
431  barArea.moveTop (statusArea.y () + statusFM.lineSpacing ());
432  QRect progArea (statusArea);
433  progArea.moveTop (barArea.y () + barArea.height ());
434
435  // render
436  if (tor.hasError ())
437    painter->setPen (QColor ("red"));
438  else
439    painter->setPen (option.palette.color (cg, cr));
440  tor.getMimeTypeIcon().paint (painter, iconArea, Qt::AlignCenter, im, qs);
441  painter->setFont (nameFont);
442  painter->drawText (nameArea, 0, nameFM.elidedText (nameStr, Qt::ElideRight, nameArea.width ()));
443  painter->setFont (statusFont);
444  painter->drawText (statusArea, 0, statusFM.elidedText (statusStr, Qt::ElideRight, statusArea.width ()));
445  painter->setFont (progressFont);
446  painter->drawText (progArea, 0, progressFM.elidedText (progressStr, Qt::ElideRight, progArea.width ()));
447  myProgressBarStyle->rect = barArea;
448  if (tor.isDownloading())
449    {
450      myProgressBarStyle->palette.setBrush (QPalette::Highlight, blueBrush);
451      myProgressBarStyle->palette.setColor (QPalette::Base, blueBack);
452      myProgressBarStyle->palette.setColor (QPalette::Window, blueBack);
453    }
454  else if (tor.isSeeding())
455    {
456      myProgressBarStyle->palette.setBrush (QPalette::Highlight, greenBrush);
457      myProgressBarStyle->palette.setColor (QPalette::Base, greenBack);
458      myProgressBarStyle->palette.setColor (QPalette::Window, greenBack);
459    }
460  else
461    {
462      myProgressBarStyle->palette.setBrush (QPalette::Highlight, silverBrush);
463      myProgressBarStyle->palette.setColor (QPalette::Base, silverBack);
464      myProgressBarStyle->palette.setColor (QPalette::Window, silverBack);
465    }
466  myProgressBarStyle->state = progressBarState;
467  setProgressBarPercentDone (option, tor);
468
469  style->drawControl (QStyle::CE_ProgressBar, myProgressBarStyle, painter);
470
471  painter->restore ();
472}
Note: See TracBrowser for help on using the repository browser.