1 /****************************************************************************
3 ** Copyright (C) 2015 The Qt Company Ltd.
4 ** Contact: http://www.qt.io/licensing/
6 ** This file is part of the demonstration applications of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see http://www.qt.io/terms-conditions. For further
15 ** information use the contact form at http://www.qt.io/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 or version 3 as published by the Free
20 ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
21 ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
22 ** following information to ensure the GNU Lesser General Public License
23 ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
24 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
26 ** As a special exception, The Qt Company gives you certain additional
27 ** rights. These rights are described in The Qt Company LGPL Exception
28 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
30 ** GNU General Public License Usage
31 ** Alternatively, this file may be used under the terms of the GNU
32 ** General Public License version 3.0 as published by the Free Software
33 ** Foundation and appearing in the file LICENSE.GPL included in the
34 ** packaging of this file. Please review the following information to
35 ** ensure the GNU General Public License version 3.0 requirements will be
36 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
42 #include "downloadmanager.h"
44 #include "autosaver.h"
45 #include "browserapplication.h"
46 #include "networkaccessmanager.h"
50 #include <QtCore/QMetaEnum>
51 #include <QtCore/QSettings>
53 #include <QtGui/QDesktopServices>
54 #include <QtGui/QFileDialog>
55 #include <QtGui/QHeaderView>
56 #include <QtGui/QFileIconProvider>
58 #include <QtCore/QDebug>
60 #include <QtWebKit/QWebSettings>
63 DownloadItem is a widget that is displayed in the download manager list.
64 It moves the data from the QNetworkReply into the QFile as well
65 as update the information/progressbar and report errors.
67 DownloadItem::DownloadItem(QNetworkReply *reply, bool requestFileName, QWidget *parent)
70 , m_requestFileName(requestFileName)
74 QPalette p = downloadInfoLabel->palette();
75 p.setColor(QPalette::Text, Qt::darkGray);
76 downloadInfoLabel->setPalette(p);
77 progressBar->setMaximum(0);
78 tryAgainButton->hide();
79 connect(stopButton, SIGNAL(clicked()), this, SLOT(stop()));
80 connect(openButton, SIGNAL(clicked()), this, SLOT(open()));
81 connect(tryAgainButton, SIGNAL(clicked()), this, SLOT(tryAgain()));
86 void DownloadItem::init()
91 // attach to the m_reply
92 m_url = m_reply->url();
93 m_reply->setParent(this);
94 connect(m_reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead()));
95 connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),
96 this, SLOT(error(QNetworkReply::NetworkError)));
97 connect(m_reply, SIGNAL(downloadProgress(qint64,qint64)),
98 this, SLOT(downloadProgress(qint64,qint64)));
99 connect(m_reply, SIGNAL(metaDataChanged()),
100 this, SLOT(metaDataChanged()));
101 connect(m_reply, SIGNAL(finished()),
102 this, SLOT(finished()));
105 downloadInfoLabel->clear();
106 progressBar->setValue(0);
109 // start timer for the download estimation
110 m_downloadTime.start();
112 if (m_reply->error() != QNetworkReply::NoError) {
113 error(m_reply->error());
118 void DownloadItem::getFileName()
121 settings.beginGroup(QLatin1String("downloadmanager"));
122 QString defaultLocation = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
123 QString downloadDirectory = settings.value(QLatin1String("downloadDirectory"), defaultLocation).toString();
124 if (!downloadDirectory.isEmpty())
125 downloadDirectory += QLatin1Char('/');
127 QString defaultFileName = saveFileName(downloadDirectory);
128 QString fileName = defaultFileName;
129 if (m_requestFileName) {
130 fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName);
131 if (fileName.isEmpty()) {
133 fileNameLabel->setText(tr("Download canceled: %1").arg(QFileInfo(defaultFileName).fileName()));
137 m_output.setFileName(fileName);
138 fileNameLabel->setText(QFileInfo(m_output.fileName()).fileName());
139 if (m_requestFileName)
143 QString DownloadItem::saveFileName(const QString &directory) const
145 // Move this function into QNetworkReply to also get file name sent from the server
146 QString path = m_url.path();
147 QFileInfo info(path);
148 QString baseName = info.completeBaseName();
149 QString endName = info.suffix();
151 if (baseName.isEmpty()) {
152 baseName = QLatin1String("unnamed_download");
153 qDebug() << "DownloadManager:: downloading unknown file:" << m_url;
155 QString name = directory + baseName + QLatin1Char('.') + endName;
156 if (QFile::exists(name)) {
157 // already exists, don't overwrite
160 name = directory + baseName + QLatin1Char('-') + QString::number(i++) + QLatin1Char('.') + endName;
161 } while (QFile::exists(name));
167 void DownloadItem::stop()
169 setUpdatesEnabled(false);
170 stopButton->setEnabled(false);
172 tryAgainButton->setEnabled(true);
173 tryAgainButton->show();
174 setUpdatesEnabled(true);
178 void DownloadItem::open()
180 QFileInfo info(m_output);
181 QUrl url = QUrl::fromLocalFile(info.absolutePath());
182 QDesktopServices::openUrl(url);
185 void DownloadItem::tryAgain()
187 if (!tryAgainButton->isEnabled())
190 tryAgainButton->setEnabled(false);
191 tryAgainButton->setVisible(false);
192 stopButton->setEnabled(true);
193 stopButton->setVisible(true);
194 progressBar->setVisible(true);
196 QNetworkReply *r = BrowserApplication::networkAccessManager()->get(QNetworkRequest(m_url));
198 m_reply->deleteLater();
199 if (m_output.exists())
203 emit statusChanged();
206 void DownloadItem::downloadReadyRead()
208 if (m_requestFileName && m_output.fileName().isEmpty())
210 if (!m_output.isOpen()) {
211 // in case someone else has already put a file there
212 if (!m_requestFileName)
214 if (!m_output.open(QIODevice::WriteOnly)) {
215 downloadInfoLabel->setText(tr("Error opening save file: %1")
216 .arg(m_output.errorString()));
218 emit statusChanged();
221 emit statusChanged();
223 if (-1 == m_output.write(m_reply->readAll())) {
224 downloadInfoLabel->setText(tr("Error saving: %1")
225 .arg(m_output.errorString()));
230 void DownloadItem::error(QNetworkReply::NetworkError)
232 qDebug() << "DownloadItem::error" << m_reply->errorString() << m_url;
233 downloadInfoLabel->setText(tr("Network Error: %1").arg(m_reply->errorString()));
234 tryAgainButton->setEnabled(true);
235 tryAgainButton->setVisible(true);
238 void DownloadItem::metaDataChanged()
240 qDebug() << "DownloadItem::metaDataChanged: not handled.";
243 void DownloadItem::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
245 m_bytesReceived = bytesReceived;
246 if (bytesTotal == -1) {
247 progressBar->setValue(0);
248 progressBar->setMaximum(0);
250 progressBar->setValue(bytesReceived);
251 progressBar->setMaximum(bytesTotal);
256 void DownloadItem::updateInfoLabel()
258 if (m_reply->error() == QNetworkReply::NoError)
261 qint64 bytesTotal = progressBar->maximum();
262 bool running = !downloadedSuccessfully();
265 double speed = m_bytesReceived * 1000.0 / m_downloadTime.elapsed();
266 double timeRemaining = ((double)(bytesTotal - m_bytesReceived)) / speed;
267 QString timeRemainingString = tr("seconds");
268 if (timeRemaining > 60) {
269 timeRemaining = timeRemaining / 60;
270 timeRemainingString = tr("minutes");
272 timeRemaining = floor(timeRemaining);
274 // When downloading the eta should never be 0
275 if (timeRemaining == 0)
282 remaining = tr("- %4 %5 remaining")
284 .arg(timeRemainingString);
285 info = tr("%1 of %2 (%3/sec) %4")
286 .arg(dataString(m_bytesReceived))
287 .arg(bytesTotal == 0 ? tr("?") : dataString(bytesTotal))
288 .arg(dataString((int)speed))
291 if (m_bytesReceived == bytesTotal)
292 info = dataString(m_output.size());
294 info = tr("%1 of %2 - Stopped")
295 .arg(dataString(m_bytesReceived))
296 .arg(dataString(bytesTotal));
298 downloadInfoLabel->setText(info);
301 QString DownloadItem::dataString(int size) const
306 } else if (size < 1024*1024) {
313 return QString(QLatin1String("%1 %2")).arg(size).arg(unit);
316 bool DownloadItem::downloading() const
318 return (progressBar->isVisible());
321 bool DownloadItem::downloadedSuccessfully() const
323 return (stopButton->isHidden() && tryAgainButton->isHidden());
326 void DownloadItem::finished()
329 stopButton->setEnabled(false);
333 emit statusChanged();
337 DownloadManager is a Dialog that contains a list of DownloadItems
339 It is a basic download manager. It only downloads the file, doesn't do BitTorrent,
340 extract zipped files or anything fancy.
342 DownloadManager::DownloadManager(QWidget *parent)
344 , m_autoSaver(new AutoSaver(this))
345 , m_manager(BrowserApplication::networkAccessManager())
347 , m_removePolicy(Never)
350 downloadsView->setShowGrid(false);
351 downloadsView->verticalHeader()->hide();
352 downloadsView->horizontalHeader()->hide();
353 downloadsView->setAlternatingRowColors(true);
354 downloadsView->horizontalHeader()->setStretchLastSection(true);
355 m_model = new DownloadModel(this);
356 downloadsView->setModel(m_model);
357 connect(cleanupButton, SIGNAL(clicked()), this, SLOT(cleanup()));
361 DownloadManager::~DownloadManager()
363 m_autoSaver->changeOccurred();
364 m_autoSaver->saveIfNeccessary();
366 delete m_iconProvider;
369 int DownloadManager::activeDownloads() const
372 for (int i = 0; i < m_downloads.count(); ++i) {
373 if (m_downloads.at(i)->stopButton->isEnabled())
379 void DownloadManager::download(const QNetworkRequest &request, bool requestFileName)
381 if (request.url().isEmpty())
383 handleUnsupportedContent(m_manager->get(request), requestFileName);
386 void DownloadManager::handleUnsupportedContent(QNetworkReply *reply, bool requestFileName)
388 if (!reply || reply->url().isEmpty())
390 QVariant header = reply->header(QNetworkRequest::ContentLengthHeader);
392 int size = header.toInt(&ok);
396 qDebug() << "DownloadManager::handleUnsupportedContent" << reply->url() << "requestFileName" << requestFileName;
397 DownloadItem *item = new DownloadItem(reply, requestFileName, this);
401 void DownloadManager::addItem(DownloadItem *item)
403 connect(item, SIGNAL(statusChanged()), this, SLOT(updateRow()));
404 int row = m_downloads.count();
405 m_model->beginInsertRows(QModelIndex(), row, row);
406 m_downloads.append(item);
407 m_model->endInsertRows();
411 downloadsView->setIndexWidget(m_model->index(row, 0), item);
412 QIcon icon = style()->standardIcon(QStyle::SP_FileIcon);
413 item->fileIcon->setPixmap(icon.pixmap(48, 48));
414 downloadsView->setRowHeight(row, item->sizeHint().height());
417 void DownloadManager::updateRow()
419 DownloadItem *item = qobject_cast<DownloadItem*>(sender());
420 int row = m_downloads.indexOf(item);
424 m_iconProvider = new QFileIconProvider();
425 QIcon icon = m_iconProvider->icon(item->m_output.fileName());
427 icon = style()->standardIcon(QStyle::SP_FileIcon);
428 item->fileIcon->setPixmap(icon.pixmap(48, 48));
429 downloadsView->setRowHeight(row, item->minimumSizeHint().height());
432 QWebSettings *globalSettings = QWebSettings::globalSettings();
433 if (!item->downloading()
434 && globalSettings->testAttribute(QWebSettings::PrivateBrowsingEnabled))
437 if (item->downloadedSuccessfully()
438 && removePolicy() == DownloadManager::SuccessFullDownload) {
442 m_model->removeRow(row);
444 cleanupButton->setEnabled(m_downloads.count() - activeDownloads() > 0);
447 DownloadManager::RemovePolicy DownloadManager::removePolicy() const
449 return m_removePolicy;
452 void DownloadManager::setRemovePolicy(RemovePolicy policy)
454 if (policy == m_removePolicy)
456 m_removePolicy = policy;
457 m_autoSaver->changeOccurred();
460 void DownloadManager::save() const
463 settings.beginGroup(QLatin1String("downloadmanager"));
464 QMetaEnum removePolicyEnum = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("RemovePolicy"));
465 settings.setValue(QLatin1String("removeDownloadsPolicy"), QLatin1String(removePolicyEnum.valueToKey(m_removePolicy)));
466 settings.setValue(QLatin1String("size"), size());
467 if (m_removePolicy == Exit)
470 for (int i = 0; i < m_downloads.count(); ++i) {
471 QString key = QString(QLatin1String("download_%1_")).arg(i);
472 settings.setValue(key + QLatin1String("url"), m_downloads[i]->m_url);
473 settings.setValue(key + QLatin1String("location"), QFileInfo(m_downloads[i]->m_output).filePath());
474 settings.setValue(key + QLatin1String("done"), m_downloads[i]->downloadedSuccessfully());
476 int i = m_downloads.count();
477 QString key = QString(QLatin1String("download_%1_")).arg(i);
478 while (settings.contains(key + QLatin1String("url"))) {
479 settings.remove(key + QLatin1String("url"));
480 settings.remove(key + QLatin1String("location"));
481 settings.remove(key + QLatin1String("done"));
482 key = QString(QLatin1String("download_%1_")).arg(++i);
486 void DownloadManager::load()
489 settings.beginGroup(QLatin1String("downloadmanager"));
490 QSize size = settings.value(QLatin1String("size")).toSize();
493 QByteArray value = settings.value(QLatin1String("removeDownloadsPolicy"), QLatin1String("Never")).toByteArray();
494 QMetaEnum removePolicyEnum = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("RemovePolicy"));
495 m_removePolicy = removePolicyEnum.keyToValue(value) == -1 ?
497 static_cast<RemovePolicy>(removePolicyEnum.keyToValue(value));
500 QString key = QString(QLatin1String("download_%1_")).arg(i);
501 while (settings.contains(key + QLatin1String("url"))) {
502 QUrl url = settings.value(key + QLatin1String("url")).toUrl();
503 QString fileName = settings.value(key + QLatin1String("location")).toString();
504 bool done = settings.value(key + QLatin1String("done"), true).toBool();
505 if (!url.isEmpty() && !fileName.isEmpty()) {
506 DownloadItem *item = new DownloadItem(0, this);
507 item->m_output.setFileName(fileName);
508 item->fileNameLabel->setText(QFileInfo(item->m_output.fileName()).fileName());
510 item->stopButton->setVisible(false);
511 item->stopButton->setEnabled(false);
512 item->tryAgainButton->setVisible(!done);
513 item->tryAgainButton->setEnabled(!done);
514 item->progressBar->setVisible(!done);
517 key = QString(QLatin1String("download_%1_")).arg(++i);
519 cleanupButton->setEnabled(m_downloads.count() - activeDownloads() > 0);
522 void DownloadManager::cleanup()
524 if (m_downloads.isEmpty())
526 m_model->removeRows(0, m_downloads.count());
528 if (m_downloads.isEmpty() && m_iconProvider) {
529 delete m_iconProvider;
532 m_autoSaver->changeOccurred();
535 void DownloadManager::updateItemCount()
537 int count = m_downloads.count();
538 itemCount->setText(count == 1 ? tr("1 Download") : tr("%1 Downloads").arg(count));
541 DownloadModel::DownloadModel(DownloadManager *downloadManager, QObject *parent)
542 : QAbstractListModel(parent)
543 , m_downloadManager(downloadManager)
547 QVariant DownloadModel::data(const QModelIndex &index, int role) const
549 if (index.row() < 0 || index.row() >= rowCount(index.parent()))
551 if (role == Qt::ToolTipRole)
552 if (!m_downloadManager->m_downloads.at(index.row())->downloadedSuccessfully())
553 return m_downloadManager->m_downloads.at(index.row())->downloadInfoLabel->text();
557 int DownloadModel::rowCount(const QModelIndex &parent) const
559 return (parent.isValid()) ? 0 : m_downloadManager->m_downloads.count();
562 bool DownloadModel::removeRows(int row, int count, const QModelIndex &parent)
564 if (parent.isValid())
567 int lastRow = row + count - 1;
568 for (int i = lastRow; i >= row; --i) {
569 if (m_downloadManager->m_downloads.at(i)->downloadedSuccessfully()
570 || m_downloadManager->m_downloads.at(i)->tryAgainButton->isEnabled()) {
571 beginRemoveRows(parent, i, i);
572 m_downloadManager->m_downloads.takeAt(i)->deleteLater();
576 m_downloadManager->m_autoSaver->changeOccurred();