Debian Codegraph @

src/Gui/DownloadItem.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2013 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library 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 Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 #include <cstdio>
24 #include <iostream>
25
26 #include <QAuthenticator>
27 #include <QContextMenuEvent>
28 #include <QDebug>
29 #include <QDesktopServices>
30 #include <QFileDialog>
31 #include <QFileInfo>
32 #include <QKeyEvent>
33 #include <QMenu>
34 #include <QMetaObject>
35 #include <QNetworkDiskCache>
36 #include <QNetworkRequest>
37 #include <QNetworkProxy>
38 #include <QSettings>
39 #include <QStandardPaths>
40
41 #include "DownloadItem.h"
42 #include "Application.h"
43 #include "Document.h"
44 #include "DownloadManager.h"
45 #include "FileDialog.h"
46 #include "MainWindow.h"
47 #include "Dialogs/ui_DlgAuthorization.h"
48 #include "Tools.h"
49 #include <App/Document.h>
50
51
52 using namespace Gui::Dialog;
53
54
55 EditTableView::EditTableView(QWidget* parent)
56 : QTableView(parent)
57 {}
58
59 void EditTableView::keyPressEvent(QKeyEvent* event)
60 {
61 if ((event->matches(QKeySequence::Delete) || event->matches(QKeySequence::Backspace)) && model()) {
62 removeOne();
63 }
64 else {
65 QAbstractItemView::keyPressEvent(event);
66 }
67 }
68
69 void EditTableView::removeOne()
70 {
71 if (!model() || !selectionModel()) {
72 return;
73 }
74 int row = currentIndex().row();
75 model()->removeRow(row, rootIndex());
76 QModelIndex idx = model()->index(row, 0, rootIndex());
77 if (!idx.isValid()) {
78 idx = model()->index(row - 1, 0, rootIndex());
79 }
80 selectionModel()->select(idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
81 }
82
83 void EditTableView::removeAll()
84 {
85 if (model()) {
86 model()->removeRows(0, model()->rowCount(rootIndex()), rootIndex());
87 }
88 }
89
90 // ----------------------------------------------------------------------------
91
92 SqueezeLabel::SqueezeLabel(QWidget* parent)
93 : QLabel(parent)
94 {}
95
96 void SqueezeLabel::paintEvent(QPaintEvent* event)
97 {
98 QFontMetrics fm = fontMetrics();
99 if (Gui::QtTools::horizontalAdvance(fm, text()) > contentsRect().width()) {
100 QString elided = fm.elidedText(text(), Qt::ElideMiddle, width());
101 QString oldText = text();
102 setText(elided);
103 QLabel::paintEvent(event);
104 setText(oldText);
105 }
106 else {
107 QLabel::paintEvent(event);
108 }
109 }
110
111 // ----------------------------------------------------------------------------
112
113 #define AUTOSAVE_IN 1000 * 3 // seconds
114 #define MAXWAIT 1000 * 15 // seconds
115
116 AutoSaver::AutoSaver(QObject* parent)
117 : QObject(parent)
118 {
119 Q_ASSERT(parent);
120 }
121
122 AutoSaver::~AutoSaver()
123 {
124 if (m_timer.isActive()) {
125 qWarning() << "AutoSaver: still active when destroyed, changes not saved.";
126 }
127 }
128
129 void AutoSaver::changeOccurred()
130 {
131 if (!m_firstChange.isValid()) {
132 m_firstChange.start();
133 }
134
135 if (m_firstChange.elapsed() > MAXWAIT) {
136 saveIfNecessary();
137 }
138 else {
139 m_timer.start(AUTOSAVE_IN, this);
140 }
141 }
142
143 void AutoSaver::timerEvent(QTimerEvent* event)
144 {
145 if (event->timerId() == m_timer.timerId()) {
146 saveIfNecessary();
147 }
148 else {
149 QObject::timerEvent(event);
150 }
151 }
152
153 void AutoSaver::saveIfNecessary()
154 {
155 if (!m_timer.isActive()) {
156 return;
157 }
158 m_timer.stop();
159 m_firstChange = QElapsedTimer();
160 if (!QMetaObject::invokeMethod(parent(), "save", Qt::DirectConnection)) {
161 qWarning() << "AutoSaver: error invoking slot save() on parent";
162 }
163 }
164
165 // ----------------------------------------------------------------------------
166
167 NetworkAccessManager::NetworkAccessManager(QObject* parent)
168 : QNetworkAccessManager(parent)
169 {
170 connect(
171 this,
172 &QNetworkAccessManager::authenticationRequired,
173 this,
174 &NetworkAccessManager::authenticationRequired
175 );
176 connect(
177 this,
178 &QNetworkAccessManager::proxyAuthenticationRequired,
179 this,
180 &NetworkAccessManager::proxyAuthenticationRequired
181 );
182
183 auto diskCache = new QNetworkDiskCache(this);
184 QString location = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
185 diskCache->setCacheDirectory(location);
186 setCache(diskCache);
187 }
188
189 void NetworkAccessManager::authenticationRequired(QNetworkReply* reply, QAuthenticator* auth)
190 {
191 QWidget* mainWindow = Gui::getMainWindow();
192
193 QDialog dialog(mainWindow);
194 dialog.setWindowFlags(Qt::Sheet);
195
196 Ui_DlgAuthorization passwordDialog;
197 passwordDialog.setupUi(&dialog);
198 dialog.adjustSize();
199
200 QString introMessage = tr("<qt>Enter username and password for \"%1\" at %2</qt>");
201 introMessage = introMessage.arg(
202 QString(reply->url().toString()).toHtmlEscaped(),
203 QString(reply->url().toString()).toHtmlEscaped()
204 );
205 passwordDialog.siteDescription->setText(introMessage);
206 passwordDialog.siteDescription->setWordWrap(true);
207
208 if (dialog.exec() == QDialog::Accepted) {
209 auth->setUser(passwordDialog.username->text());
210 auth->setPassword(passwordDialog.password->text());
211 }
212 }
213
214 void NetworkAccessManager::proxyAuthenticationRequired(const QNetworkProxy& proxy, QAuthenticator* auth)
215 {
216 QWidget* mainWindow = Gui::getMainWindow();
217
218 QDialog dialog(mainWindow);
219 dialog.setWindowFlags(Qt::Sheet);
220
221 Ui_DlgAuthorization proxyDialog;
222 proxyDialog.setupUi(&dialog);
223 dialog.adjustSize();
224
225 QString introMessage = tr("<qt>Connect to proxy \"%1\" using:</qt>");
226 introMessage = introMessage.arg(QString(proxy.hostName()).toHtmlEscaped());
227 proxyDialog.siteDescription->setText(introMessage);
228 proxyDialog.siteDescription->setWordWrap(true);
229
230 if (dialog.exec() == QDialog::Accepted) {
231 auth->setUser(proxyDialog.username->text());
232 auth->setPassword(proxyDialog.password->text());
233 }
234 }
235
236 // ----------------------------------------------------------------------------
237
238 DownloadItem::DownloadItem(QNetworkReply* reply, bool requestFileName, QWidget* parent)
239 : QWidget(parent)
240 , m_reply(reply)
241 , m_requestFileName(requestFileName)
242 , m_bytesReceived(0)
243 {
244 setupUi(this);
245 QPalette p = downloadInfoLabel->palette();
246 p.setColor(QPalette::Text, Qt::darkGray);
247 downloadInfoLabel->setPalette(p);
248 progressBar->setMaximum(0);
249 tryAgainButton->hide();
250 connect(stopButton, &QPushButton::clicked, this, &DownloadItem::stop);
251 connect(openButton, &QPushButton::clicked, this, &DownloadItem::open);
252 connect(tryAgainButton, &QPushButton::clicked, this, &DownloadItem::tryAgain);
253
254 init();
255 }
256
257 void DownloadItem::init()
258 {
259 // clang-format off
260 if (!m_reply)
261 return;
262
263 // attach to the m_reply
264 m_url = m_reply->url();
265 m_reply->setParent(this);
266 connect(m_reply, &QNetworkReply::readyRead, this, &DownloadItem::downloadReadyRead);
267 connect(m_reply, &QNetworkReply::errorOccurred, this, &DownloadItem::error);
268 connect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadItem::downloadProgress);
269 connect(m_reply, &QNetworkReply::metaDataChanged, this, &DownloadItem::metaDataChanged);
270 connect(m_reply, &QNetworkReply::finished, this, &DownloadItem::finished);
271
272 // reset info
273 downloadInfoLabel->clear();
274 progressBar->setValue(0);
275 getFileName();
276
277 // start timer for the download estimation
278 m_downloadTime.start();
279
280 if (m_reply->error() != QNetworkReply::NoError) {
281 error(m_reply->error());
282 finished();
283 }
284 // clang-format on
285 }
286
287 QString DownloadItem::getDownloadDirectory() const
288 {
289 QString exe = QString::fromStdString(App::Application::getExecutableName());
290 QString path = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
291 QString dirPath = QDir(path).filePath(exe);
292 Base::Reference<ParameterGrp> hPath = App::GetApplication()
293 .GetUserParameter()
294 .GetGroup("BaseApp")
295 ->GetGroup("Preferences")
296 ->GetGroup("General");
297 std::string dir = hPath->GetASCII("DownloadPath", "");
298 if (!dir.empty()) {
299 dirPath = QString::fromUtf8(dir.c_str());
300 }
301
302 if (QFileInfo::exists(dirPath) || QDir().mkpath(dirPath)) {
303 return dirPath;
304 }
305 else {
306 return path;
307 }
308 }
309
310 void DownloadItem::getFileName()
311 {
312 QSettings settings;
313 settings.beginGroup(QLatin1String("downloadmanager"));
314 QString defaultLocation = getDownloadDirectory();
315 QString downloadDirectory
316 = settings.value(QLatin1String("downloadDirectory"), defaultLocation).toString();
317 if (!downloadDirectory.isEmpty()) {
318 downloadDirectory += QLatin1Char('/');
319 }
320
321 QString defaultFileName = saveFileName(downloadDirectory);
322 QString fileName = defaultFileName;
323 if (m_requestFileName) {
324 fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName);
325 if (fileName.isEmpty()) {
326 m_reply->close();
327 fileNameLabel->setText(
328 tr("Download canceled: %1").arg(QFileInfo(defaultFileName).fileName())
329 );
330 return;
331 }
332 }
333 m_output.setFileName(fileName);
334 fileNameLabel->setText(QFileInfo(m_output.fileName()).fileName());
335 fileNameLabel->setToolTip(m_output.fileName());
336 if (m_requestFileName) {
337 downloadReadyRead();
338 }
339 }
340
341 QString DownloadItem::saveFileName(const QString& directory) const
342 {
343 // Move this function into QNetworkReply to also get file name sent from the server
344 QString path = m_url.path();
345 if (!m_fileName.isEmpty()) {
346 path = m_fileName;
347 }
348 QFileInfo info(path);
349 QString baseName = info.completeBaseName();
350 QString endName = info.suffix();
351
352 if (baseName.isEmpty()) {
353 baseName = QLatin1String("unnamed_download");
354 qDebug() << "DownloadManager:: downloading unknown file:" << m_url;
355 }
356 QString name = directory + baseName + QLatin1Char('.') + endName;
357 if (QFile::exists(name)) {
358 // already exists, don't overwrite
359 int i = 1;
360 do {
361 name = directory + baseName + QLatin1Char('-') + QString::number(i++) + QLatin1Char('.')
362 + endName;
363 } while (QFile::exists(name));
364 }
365 return name;
366 }
367
368
369 void DownloadItem::stop()
370 {
371 setUpdatesEnabled(false);
372 stopButton->setEnabled(false);
373 stopButton->hide();
374 tryAgainButton->setEnabled(true);
375 tryAgainButton->show();
376 setUpdatesEnabled(true);
377 m_reply->abort();
378 }
379
380 void DownloadItem::open()
381 {
382 QFileInfo info(m_output);
383 QString selectedFilter;
384 QStringList fileList;
385 fileList << info.absoluteFilePath();
386 SelectModule::Dict dict = SelectModule::importHandler(fileList, selectedFilter);
387
388 // load the files with the associated modules
389 if (!dict.isEmpty()) {
390 Gui::Document* doc = Gui::Application::Instance->activeDocument();
391 if (doc) {
392 for (SelectModule::Dict::iterator it = dict.begin(); it != dict.end(); ++it) {
393 Gui::Application::Instance->importFrom(
394 it.key().toUtf8(),
395 doc->getDocument()->getName(),
396 it.value().toLatin1()
397 );
398 }
399 }
400 else {
401 for (SelectModule::Dict::iterator it = dict.begin(); it != dict.end(); ++it) {
402 Gui::Application::Instance->open(it.key().toUtf8(), it.value().toLatin1());
403 }
404 }
405 }
406 else {
407 QUrl url = QUrl::fromLocalFile(info.absolutePath());
408 QDesktopServices::openUrl(url);
409 }
410 }
411
412 void DownloadItem::openFolder()
413 {
414 QFileInfo info(m_output);
415 QUrl url = QUrl::fromLocalFile(info.absolutePath());
416 QDesktopServices::openUrl(url);
417 }
418
419 void DownloadItem::tryAgain()
420 {
421 if (!tryAgainButton->isEnabled()) {
422 return;
423 }
424
425 tryAgainButton->setEnabled(false);
426 tryAgainButton->setVisible(false);
427 stopButton->setEnabled(true);
428 stopButton->setVisible(true);
429 progressBar->setVisible(true);
430
431 QNetworkReply* r = DownloadManager::getInstance()->networkAccessManager()->get(
432 QNetworkRequest(m_url)
433 );
434 if (m_reply) {
435 m_reply->deleteLater();
436 }
437 if (m_output.exists()) {
438 m_output.remove();
439 }
440 m_reply = r;
441 init();
442 Q_EMIT statusChanged();
443 }
444
445 void DownloadItem::contextMenuEvent(QContextMenuEvent* e)
446 {
447 QMenu menu;
448 QAction* a = menu.addAction(tr("Open Containing Folder"), this, &DownloadItem::openFolder);
449 a->setEnabled(m_output.exists());
450 menu.exec(e->globalPos());
451 }
452
453 void DownloadItem::downloadReadyRead()
454 {
455 if (m_requestFileName && m_output.fileName().isEmpty()) {
456 return;
457 }
458 if (!m_output.isOpen()) {
459 // in case someone else has already put a file there
460 if (!m_requestFileName) {
461 getFileName();
462 }
463 if (!m_output.open(QIODevice::WriteOnly)) {
464 downloadInfoLabel->setText(tr("Error opening saved file: %1").arg(m_output.errorString()));
465 stopButton->click();
466 Q_EMIT statusChanged();
467 return;
468 }
469 downloadInfoLabel->setToolTip(m_url.toString());
470 Q_EMIT statusChanged();
471 }
472 if (-1 == m_output.write(m_reply->readAll())) {
473 downloadInfoLabel->setText(tr("Error saving: %1").arg(m_output.errorString()));
474 stopButton->click();
475 }
476 }
477
478 void DownloadItem::error(QNetworkReply::NetworkError)
479 {
480 qDebug() << "DownloadItem::error" << m_reply->errorString() << m_url;
481 downloadInfoLabel->setText(tr("Network Error: %1").arg(m_reply->errorString()));
482 tryAgainButton->setEnabled(true);
483 tryAgainButton->setVisible(true);
484 }
485
486 void DownloadItem::metaDataChanged()
487 {
488 // https://tools.ietf.org/html/rfc6266
489 if (m_reply->hasRawHeader(QByteArray("Content-Disposition"))) {
490 QByteArray header = m_reply->rawHeader(QByteArray("Content-Disposition"));
491 int index = header.indexOf("filename=");
492 if (index >= 0) {
493 header = header.mid(index + 9);
494 if (header.startsWith("\"") || header.startsWith("'")) {
495 header = header.mid(1);
496 }
497 if ((index = header.lastIndexOf("\"")) > 0) {
498 header = header.left(index);
499 }
500 else if ((index = header.lastIndexOf("'")) > 0) {
501 header = header.left(index);
502 }
503 m_fileName = QUrl::fromPercentEncoding(header);
504 }
505 // Sometimes "filename=" and "filename*=UTF-8''" is set.
506 // So, search for this too.
507 index = header.indexOf("filename*=UTF-8''");
508 if (index >= 0) {
509 header = header.mid(index + 17);
510 if (header.startsWith("\"") || header.startsWith("'")) {
511 header = header.mid(1);
512 }
513 if ((index = header.lastIndexOf("\"")) > 0) {
514 header = header.left(index);
515 }
516 else if ((index = header.lastIndexOf("'")) > 0) {
517 header = header.left(index);
518 }
519 m_fileName = QUrl::fromPercentEncoding(header);
520 }
521 }
522
523 QUrl url = m_reply->url();
524
525 // If this is a redirected url use this instead
526 QUrl redirectUrl = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
527 if (!redirectUrl.isEmpty()) {
528 QString s = redirectUrl.toString();
529 std::cout << "Redirected to " << s.toStdString() << std::endl;
530
531 QVariant header = m_reply->header(QNetworkRequest::LocationHeader);
532 QString loc = header.toString();
533 Q_UNUSED(loc);
534
535 if (url != redirectUrl) {
536 url = redirectUrl;
537
538 disconnect(m_reply, &QNetworkReply::readyRead, this, &DownloadItem::downloadReadyRead);
539 disconnect(m_reply, &QNetworkReply::errorOccurred, this, &DownloadItem::error);
540 disconnect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadItem::downloadProgress);
541 disconnect(m_reply, &QNetworkReply::metaDataChanged, this, &DownloadItem::metaDataChanged);
542 disconnect(m_reply, &QNetworkReply::finished, this, &DownloadItem::finished);
543 m_reply->close();
544 m_reply->deleteLater();
545
546 m_reply = DownloadManager::getInstance()->networkAccessManager()->get(QNetworkRequest(url));
547 init();
548 }
549 }
550 }
551
552 void DownloadItem::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
553 {
554 m_bytesReceived = bytesReceived;
555 if (bytesTotal == -1) {
556 progressBar->setValue(0);
557 progressBar->setMaximum(0);
558 }
559 else {
560 progressBar->setValue(bytesReceived);
561 progressBar->setMaximum(bytesTotal);
562 }
563 updateInfoLabel();
564 }
565
566 void DownloadItem::updateInfoLabel()
567 {
568 qint64 bytesTotal = progressBar->maximum();
569 bool running = !downloadedSuccessfully();
570
571 // update info label
572 double speed = m_bytesReceived * 1000.0 / m_downloadTime.elapsed();
573 double timeRemaining = ((double)(bytesTotal - m_bytesReceived)) / speed;
574 QString timeRemainingString = tr("seconds");
575 if (timeRemaining > 60) {
576 timeRemaining = timeRemaining / 60;
577 timeRemainingString = tr("minutes");
578 }
579 timeRemaining = floor(timeRemaining);
580
581 // When downloading the eta should never be 0
582 if (timeRemaining == 0) {
583 timeRemaining = 1;
584 }
585
586 QString info;
587 if (running) {
588 QString remaining;
589 if (bytesTotal != 0) {
590 remaining = tr("- %4 %5 remaining").arg(timeRemaining).arg(timeRemainingString);
591 }
592 info = QString(tr("%1 of %2 (%3/sec) %4"))
593 .arg(
594 dataString(m_bytesReceived),
595 bytesTotal == 0 ? tr("?") : dataString(bytesTotal),
596 dataString((int)speed),
597 remaining
598 );
599 }
600 else {
601 if (m_bytesReceived == bytesTotal) {
602 info = dataString(m_output.size());
603 }
604 else {
605 info = tr("%1 of %2 - Stopped").arg(dataString(m_bytesReceived), dataString(bytesTotal));
606 }
607 }
608 downloadInfoLabel->setText(info);
609 }
610
611 QString DownloadItem::dataString(int size) const
612 {
613 QString unit;
614 if (size < 1024) {
615 unit = tr("bytes");
616 }
617 else if (size < 1024 * 1024) {
618 size /= 1024;
619 unit = tr("kB");
620 }
621 else {
622 size /= 1024 * 1024;
623 unit = tr("MB");
624 }
625 return QString(QLatin1String("%1 %2")).arg(size).arg(unit);
626 }
627
628 bool DownloadItem::downloading() const
629 {
630 return (progressBar->isVisible());
631 }
632
633 bool DownloadItem::downloadedSuccessfully() const
634 {
635 return (stopButton->isHidden() && tryAgainButton->isHidden());
636 }
637
638 void DownloadItem::finished()
639 {
640 progressBar->hide();
641 stopButton->setEnabled(false);
642 stopButton->hide();
643 m_output.close();
644 updateInfoLabel();
645 Q_EMIT statusChanged();
646 }
647
648 #include "moc_DownloadItem.cpp"