Qt Utilities 6.21.0
Common Qt related C++ classes and routines used by my applications such as dialogs, widgets and models
Loading...
Searching...
No Matches
updater.cpp
Go to the documentation of this file.
1#include "./updater.h"
2
3#if defined(QT_UTILITIES_GUI_QTWIDGETS)
5#endif
6
7#include "resources/config.h"
8
9#include <QSettings>
10#include <QTimer>
11
12#include <c++utilities/application/argumentparser.h>
13
14#include <optional>
15
16#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
17#include <c++utilities/io/ansiescapecodes.h>
18#include <c++utilities/io/archive.h>
19
20#include <QCoreApplication>
21#include <QDebug>
22#include <QEventLoop>
23#include <QFile>
24#include <QFileInfo>
25#include <QFutureWatcher>
26#include <QJsonArray>
27#include <QJsonDocument>
28#include <QJsonObject>
29#include <QJsonParseError>
30#include <QList>
31#include <QMap>
32#include <QNetworkAccessManager>
33#include <QNetworkReply>
34#include <QProcess>
35#include <QRegularExpression>
36#include <QStringBuilder>
37#include <QVersionNumber>
38#include <QtConcurrentRun>
39#include <QtGlobal> // for QtProcessorDetection and QtSystemDetection keeping it Qt 5 compatible
40
41#if defined(QT_UTILITIES_GUI_QTWIDGETS)
42#include <QMessageBox>
43#endif
44
45#include <iostream>
46#endif
47
48#if defined(QT_UTILITIES_GUI_QTWIDGETS)
49#include <QCoreApplication>
50#include <QLabel>
51
52#if defined(QT_UTILITIES_SETUP_TOOLS_ENABLED)
53#include "ui_updateoptionpage.h"
54#else
55namespace QtUtilities {
56namespace Ui {
57class UpdateOptionPage {
58public:
59 void setupUi(QWidget *)
60 {
61 }
62 void retranslateUi(QWidget *)
63 {
64 }
65};
66} // namespace Ui
67} // namespace QtUtilities
68#endif
69#endif
70
71#include "resources/config.h"
72
73#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
74#define QT_UTILITIES_VERSION_SUFFIX QString()
75#else
76#define QT_UTILITIES_VERSION_SUFFIX QStringLiteral("-qt5")
77#endif
78
79#if defined(Q_OS_WINDOWS)
80#define QT_UTILITIES_EXE_REGEX "\\.exe"
81#else
82#define QT_UTILITIES_EXE_REGEX ""
83#endif
84
85#if defined(Q_OS_WIN64)
86#if defined(Q_PROCESSOR_X86_64)
87#define QT_UTILITIES_DOWNLOAD_REGEX "-.*-x86_64-w64-mingw32"
88#elif defined(Q_PROCESSOR_ARM_64)
89#define QT_UTILITIES_DOWNLOAD_REGEX "-.*-aarch64-w64-mingw32"
90#endif
91#elif defined(Q_OS_WIN32)
92#define QT_UTILITIES_DOWNLOAD_REGEX "-.*-i686-w64-mingw32"
93#elif defined(__GNUC__) && defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
94#if defined(Q_PROCESSOR_X86_64)
95#define QT_UTILITIES_DOWNLOAD_REGEX "-.*-x86_64-pc-linux-gnu"
96#elif defined(Q_PROCESSOR_ARM_64)
97#define QT_UTILITIES_DOWNLOAD_REGEX "-.*-aarch64-pc-linux-gnu"
98#endif
99#endif
100
101#if defined(Q_OS_WINDOWS) && (QT_VERSION >= QT_VERSION_CHECK(6, 6, 0))
102#include <QNtfsPermissionCheckGuard>
103#endif
104
105namespace QtUtilities {
106
107#if (QT_VERSION >= QT_VERSION_CHECK(6, 4, 0))
108using VersionSuffixIndex = qsizetype;
109#else
110using VersionSuffixIndex = int;
111#endif
112
113#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
114struct VersionAndSuffix {
115 operator bool() const
116 {
117 return !version.isNull();
118 }
119 bool operator>(const VersionAndSuffix &rhs) const
120 {
121 const auto cmp = QVersionNumber::compare(version, rhs.version);
122 if (cmp > 0) {
123 return true; // lhs is newer
124 } else if (cmp < 0) {
125 return false; // rhs is newer
126 }
127 if (!suffix.isEmpty() && rhs.suffix.isEmpty()) {
128 return false; // lhs is pre-release and rhs is regular release, so rhs is newer
129 }
130 if (suffix.isEmpty() && !rhs.suffix.isEmpty()) {
131 return true; // lhs is regular release and rhs is pre-release, so lhs is newer
132 }
133 // compare pre-release suffix
134 return suffix > rhs.suffix;
135 }
136 QString toString() const
137 {
138 return version.toString() + suffix;
139 }
140 static VersionAndSuffix fromString(const QString &versionString)
141 {
142 auto res = VersionAndSuffix();
143 auto suffixIndex = VersionSuffixIndex(-1);
144 res.version = QVersionNumber::fromString(versionString, &suffixIndex);
145 res.suffix = suffixIndex >= 0 ? versionString.mid(suffixIndex) : QString();
146 // ignore suffixes that are not like "alpha1", "beta2" and "rc3" (so e.g. Git revisions like "3224.493f60f2" are ignored)
147 if (static const auto validSuffixRegex = QRegularExpression(QRegularExpression::anchoredPattern(QStringLiteral("-?\\w+\\d?")));
148 !validSuffixRegex.match(res.suffix).hasMatch()) {
149 res.suffix.clear();
150 }
151 return res;
152 }
153 QVersionNumber version;
154 QString suffix;
155};
156
157struct UpdateNotifierPrivate {
158 QNetworkAccessManager *nm = nullptr;
159 CppUtilities::DateTime lastCheck;
161 QNetworkRequest::CacheLoadControl cacheLoadControl = QNetworkRequest::PreferNetwork;
162 VersionAndSuffix currentVersion;
163 QRegularExpression gitHubRegex = QRegularExpression(QStringLiteral(".*/github.com/([^/]+)/([^/]+)(/.*)?"));
164 QRegularExpression gitHubRegex2 = QRegularExpression(QStringLiteral(".*/([^/.]+)\\.github.io/([^/]+)(/.*)?"));
165 QRegularExpression assetRegex = QRegularExpression();
166 QString executableName;
167 QString previouslyFoundNewVersion;
168 QString newVersion;
169 QString latestVersion;
170 QString additionalInfo;
171 QString releaseNotes;
172 QString error;
173 QUrl downloadUrl;
174 QUrl signatureUrl;
175 QUrl releasesUrl;
176 QUrl previousVersionDownloadUrl;
177 QUrl previousVersionSignatureUrl;
178 QList<std::variant<QJsonArray, QString>> previousVersionAssets;
179 bool inProgress = false;
180 bool updateAvailable = false;
181 bool verbose = false;
182};
183#else
185 QString error;
186};
187#endif
188
190 : QObject(parent)
191 , m_p(std::make_unique<UpdateNotifierPrivate>())
192{
193#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
194 return;
195#else
196 m_p->verbose = qEnvironmentVariableIntValue(PROJECT_VARNAME_UPPER "_UPDATER_VERBOSE");
197
198 const auto &appInfo = CppUtilities::applicationInfo;
199 const auto url = QString::fromUtf8(appInfo.url);
200 auto gitHubMatch = m_p->gitHubRegex.match(url);
201 if (!gitHubMatch.hasMatch()) {
202 gitHubMatch = m_p->gitHubRegex2.match(url);
203 }
204 const auto gitHubOrga = gitHubMatch.captured(1);
205 const auto gitHubRepo = gitHubMatch.captured(2);
206 if (gitHubOrga.isNull() || gitHubRepo.isNull()) {
207 return;
208 }
209 m_p->executableName = gitHubRepo + QT_UTILITIES_VERSION_SUFFIX;
210 m_p->releasesUrl
211 = QStringLiteral("https://api.github.com/repos/") % gitHubOrga % QChar('/') % gitHubRepo % QStringLiteral("/releases?per_page=25");
212 m_p->currentVersion = VersionAndSuffix::fromString(QString::fromUtf8(appInfo.version));
213#ifdef QT_UTILITIES_DOWNLOAD_REGEX
214 m_p->assetRegex = QRegularExpression(m_p->executableName + QStringLiteral(QT_UTILITIES_DOWNLOAD_REGEX "\\..+"));
215#endif
216 if (m_p->verbose) {
217 qDebug() << "deduced executable name: " << m_p->executableName;
218 qDebug() << "assumed current version: " << m_p->currentVersion.version;
219 qDebug() << "asset regex for current platform: " << m_p->assetRegex;
220 }
221
222 connect(this, &UpdateNotifier::checkedForUpdate, this, &UpdateNotifier::lastCheckNow);
223#endif
224
225#ifdef QT_UTILITIES_FAKE_NEW_VERSION_AVAILABLE
226 QTimer::singleShot(10000, Qt::VeryCoarseTimer, this, [this] { emit updateAvailable(QStringLiteral("foo"), QString()); });
227#endif
228}
229
233
235{
236#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
237 return false;
238#else
239 return !m_p->assetRegex.pattern().isEmpty();
240#endif
241}
242
244{
245#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
246 return false;
247#else
248 return m_p->inProgress;
249#endif
250}
251
253{
254#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
255 return false;
256#else
257 return m_p->updateAvailable;
258#endif
259}
260
262{
263#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
265#else
266 return m_p->flags;
267#endif
268}
269
271{
272#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
273 Q_UNUSED(flags)
274#else
275 m_p->flags = flags;
276#endif
277}
278
279const QString &UpdateNotifier::executableName() const
280{
281#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
282 static const auto v = QString();
283 return v;
284#else
285 return m_p->executableName;
286#endif
287}
288
289const QString &UpdateNotifier::newVersion() const
290{
291#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
292 static const auto v = QString();
293 return v;
294#else
295 return m_p->newVersion;
296#endif
297}
298
299const QString &UpdateNotifier::latestVersion() const
300{
301#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
302 static const auto v = QString();
303 return v;
304#else
305 return m_p->latestVersion;
306#endif
307}
308
309const QString &UpdateNotifier::additionalInfo() const
310{
311#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
312 static const auto v = QString();
313 return v;
314#else
315 return m_p->additionalInfo;
316#endif
317}
318
319const QString &UpdateNotifier::releaseNotes() const
320{
321#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
322 static const auto v = QString();
323 return v;
324#else
325 return m_p->releaseNotes;
326#endif
327}
328
329const QString &UpdateNotifier::error() const
330{
331 return m_p->error;
332}
333
335{
336#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
337 static const auto v = QUrl();
338 return v;
339#else
340 return m_p->downloadUrl;
341#endif
342}
343
345{
346#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
347 static const auto v = QUrl();
348 return v;
349#else
350 return m_p->signatureUrl;
351#endif
352}
353
355{
356#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
357 static const auto v = QUrl();
358 return v;
359#else
360 return m_p->previousVersionDownloadUrl;
361#endif
362}
363
365{
366#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
367 static const auto v = QUrl();
368 return v;
369#else
370 return m_p->previousVersionSignatureUrl;
371#endif
372}
373
374CppUtilities::DateTime UpdateNotifier::lastCheck() const
375{
376#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
377 return CppUtilities::DateTime();
378#else
379 return m_p->lastCheck;
380#endif
381}
382
383void UpdateNotifier::restore(QSettings *settings)
384{
385#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
386 Q_UNUSED(settings)
387#else
388 settings->beginGroup(QStringLiteral("updating"));
389 m_p->newVersion = settings->value("newVersion").toString();
390 m_p->latestVersion = settings->value("latestVersion").toString();
391 m_p->releaseNotes = settings->value("releaseNotes").toString();
392 m_p->downloadUrl = settings->value("downloadUrl").toUrl();
393 m_p->signatureUrl = settings->value("signatureUrl").toUrl();
394 m_p->previousVersionDownloadUrl = settings->value("previousVersionDownloadUrl").toUrl();
395 m_p->previousVersionSignatureUrl = settings->value("previousVersionSignatureUrl").toUrl();
396 m_p->lastCheck = CppUtilities::DateTime(settings->value("lastCheck").toULongLong());
397 m_p->flags = static_cast<UpdateCheckFlags>(settings->value("flags").toULongLong());
398 settings->endGroup();
399#endif
400}
401
402void UpdateNotifier::save(QSettings *settings)
403{
404#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
405 Q_UNUSED(settings)
406#else
407 settings->beginGroup(QStringLiteral("updating"));
408 settings->setValue("newVersion", m_p->newVersion);
409 settings->setValue("latestVersion", m_p->latestVersion);
410 settings->setValue("releaseNotes", m_p->releaseNotes);
411 settings->setValue("downloadUrl", m_p->downloadUrl);
412 settings->setValue("signatureUrl", m_p->signatureUrl);
413 settings->setValue("previousVersionDownloadUrl", m_p->previousVersionDownloadUrl);
414 settings->setValue("previousVersionSignatureUrl", m_p->previousVersionSignatureUrl);
415 settings->setValue("lastCheck", static_cast<qulonglong>(m_p->lastCheck.ticks()));
416 settings->setValue("flags", static_cast<qulonglong>(m_p->flags));
417 settings->endGroup();
418#endif
419}
420
422{
423#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
424 if (m_p->inProgress) {
425 return tr("checking …");
426 }
427#endif
428 if (!m_p->error.isEmpty()) {
429 return tr("unable to check: %1").arg(m_p->error);
430 }
431#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
432 if (!m_p->newVersion.isEmpty()) {
433 return tr("new version available: %1 (last checked: %2)").arg(m_p->newVersion, QString::fromStdString(m_p->lastCheck.toIsoString()));
434 } else if (!m_p->latestVersion.isEmpty()) {
435 return tr("no new version available, latest release is: %1 (last checked: %2)")
436 .arg(m_p->latestVersion, QString::fromStdString(m_p->lastCheck.toIsoString()));
437 }
438#endif
439 return tr("unknown");
440}
441
442void UpdateNotifier::setNetworkAccessManager(QNetworkAccessManager *nm)
443{
444#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
445 Q_UNUSED(nm)
446#else
447 m_p->nm = nm;
448#endif
449}
450
451#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
452void UpdateNotifier::setCacheLoadControl(QNetworkRequest::CacheLoadControl cacheLoadControl)
453{
454 m_p->cacheLoadControl = cacheLoadControl;
455}
456#endif
457
458void UpdateNotifier::setError(const QString &context, QNetworkReply *reply)
459{
460#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
461 Q_UNUSED(context)
462 Q_UNUSED(reply)
463#else
464 m_p->error = context + reply->errorString();
465 emit checkedForUpdate();
466 emit inProgressChanged(m_p->inProgress = false);
467#endif
468}
469
470void UpdateNotifier::setError(const QString &context, const QJsonParseError &jsonError, const QByteArray &response)
471{
472#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
473 Q_UNUSED(context)
474 Q_UNUSED(jsonError)
475 Q_UNUSED(response)
476#else
477 m_p->error = context % jsonError.errorString() % QChar(' ') % QChar('(') % tr("at offset %1").arg(jsonError.offset) % QChar(')');
478 if (!response.isEmpty()) {
479 m_p->error += QStringLiteral("\nResponse was: ");
480 m_p->error += QString::fromUtf8(response);
481 }
482 emit inProgressChanged(m_p->inProgress = false);
483#endif
484}
485
487{
488#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
489 m_p->error = tr("This build of the application does not support checking for updates.");
490 emit inProgressChanged(false);
491 return;
492#else
493 if (!m_p->nm || m_p->inProgress) {
494 return;
495 }
496 emit inProgressChanged(m_p->inProgress = true);
497 auto request = QNetworkRequest(m_p->releasesUrl);
498 request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, m_p->cacheLoadControl);
499 auto *const reply = m_p->nm->get(request);
500 connect(reply, &QNetworkReply::finished, this, &UpdateNotifier::readReleases);
501#endif
502}
503
505{
506#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
507 m_p->updateAvailable = false;
508 m_p->downloadUrl.clear();
509 m_p->signatureUrl.clear();
510 m_p->latestVersion.clear();
511 m_p->newVersion.clear();
512 m_p->releaseNotes.clear();
513#endif
514}
515
516void UpdateNotifier::lastCheckNow() const
517{
518#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
519 m_p->lastCheck = CppUtilities::DateTime::now();
520#endif
521}
522
523#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
528bool UpdateNotifier::isVersionHigher(const QString &lhs, const QString &rhs)
529{
530 return VersionAndSuffix::fromString(lhs) > VersionAndSuffix::fromString(rhs);
531}
532#endif
533
534void UpdateNotifier::supplyNewReleaseData(const QByteArray &data)
535{
536#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
537 Q_UNUSED(data)
538#else
539 // parse JSON
540 auto jsonError = QJsonParseError();
541 const auto replyDoc = QJsonDocument::fromJson(data, &jsonError);
542 if (jsonError.error != QJsonParseError::NoError) {
543 setError(tr("Unable to parse releases: "), jsonError, data);
544 return;
545 }
547#if !defined(QT_JSON_READONLY)
548 if (m_p->verbose) {
549 qDebug().noquote() << "Update check: found releases: " << QString::fromUtf8(replyDoc.toJson(QJsonDocument::Indented));
550 }
551#endif
552 // determine the release with the highest version (within the current page)
553 const auto replyArray = replyDoc.array();
554 const auto skipPreReleases = !(m_p->flags && UpdateCheckFlags::IncludePreReleases);
555 const auto skipDrafts = !(m_p->flags && UpdateCheckFlags::IncludeDrafts);
556 auto latestVersionFound = VersionAndSuffix();
557 auto latestVersionAssets = QJsonValue();
558 auto latestVersionAssetsUrl = QString();
559 auto latestVersionReleaseNotes = QString();
560 auto previousVersionAssets = QMap<QVersionNumber, std::variant<QJsonArray, QString>>();
561 for (const auto &releaseInfoVal : replyArray) {
562 const auto releaseInfo = releaseInfoVal.toObject();
563 const auto tag = releaseInfo.value(QLatin1String("tag_name")).toString();
564 if ((skipPreReleases && releaseInfo.value(QLatin1String("prerelease")).toBool())
565 || (skipDrafts && releaseInfo.value(QLatin1String("draft")).toBool())) {
566 qDebug() << "Update check: skipping prerelease/draft: " << tag;
567 continue;
568 }
569 const auto versionStr = tag.startsWith(QChar('v')) ? tag.mid(1) : tag;
570 const auto version = VersionAndSuffix::fromString(versionStr);
571 const auto assets = releaseInfo.value(QLatin1String("assets"));
572 const auto assetsUrl = releaseInfo.value(QLatin1String("assets_url")).toString();
573 if (!latestVersionFound || version > latestVersionFound) {
574 latestVersionFound = version;
575 latestVersionAssets = assets;
576 latestVersionAssetsUrl = assetsUrl;
577 latestVersionReleaseNotes = releaseInfo.value(QLatin1String("body")).toString();
578 }
579 if (assets.isArray()) {
580 previousVersionAssets[version.version] = assets.toArray();
581 } else if (!assetsUrl.isEmpty()) {
582 previousVersionAssets[version.version] = assetsUrl;
583 }
584 if (m_p->verbose) {
585 qDebug() << "Update check: skipping release: " << tag;
586 }
587 }
588 if (latestVersionFound) {
589 m_p->latestVersion = latestVersionFound.toString();
590 m_p->releaseNotes = latestVersionReleaseNotes;
591 previousVersionAssets.remove(latestVersionFound.version);
592 }
593 m_p->previousVersionAssets = previousVersionAssets.values();
594 // process assets for latest version
595 const auto foundUpdate = latestVersionFound && latestVersionFound > m_p->currentVersion;
596 if (foundUpdate) {
597 m_p->newVersion = latestVersionFound.toString();
598 }
599 if (latestVersionAssets.isArray()) {
600 return processAssets(latestVersionAssets.toArray(), foundUpdate, false);
601 } else if (foundUpdate) {
602 return queryRelease(latestVersionAssetsUrl, foundUpdate, false);
603 }
604 emit checkedForUpdate();
605 emit inProgressChanged(m_p->inProgress = false);
606#endif
607}
608
609void UpdateNotifier::readReleases()
610{
611#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
612 auto *const reply = static_cast<QNetworkReply *>(sender());
613 reply->deleteLater();
614 switch (reply->error()) {
615 case QNetworkReply::NoError: {
616 supplyNewReleaseData(reply->readAll());
617 break;
618 }
619 case QNetworkReply::OperationCanceledError:
620 emit inProgressChanged(m_p->inProgress = false);
621 return;
622 default:
623 setError(tr("Unable to request releases: "), reply);
624 }
625#endif
626}
627
628void UpdateNotifier::queryRelease(const QUrl &releaseUrl, bool forUpdate, bool forPreviousVersion)
629{
630#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
631 Q_UNUSED(releaseUrl)
632 Q_UNUSED(forUpdate)
633 Q_UNUSED(forPreviousVersion)
634#else
635 auto request = QNetworkRequest(releaseUrl);
636 request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, m_p->cacheLoadControl);
637 auto *const reply = m_p->nm->get(request);
638 reply->setProperty("forUpdate", forUpdate);
639 reply->setProperty("forPreviousVersion", forPreviousVersion);
640 connect(reply, &QNetworkReply::finished, this, &UpdateNotifier::readRelease);
641#endif
642}
643
644void UpdateNotifier::readRelease()
645{
646#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
647 auto *const reply = static_cast<QNetworkReply *>(sender());
648 reply->deleteLater();
649 switch (reply->error()) {
650 case QNetworkReply::NoError: {
651 // parse JSON
652 auto jsonError = QJsonParseError();
653 const auto response = reply->readAll();
654 const auto replyDoc = QJsonDocument::fromJson(response, &jsonError);
655 if (jsonError.error != QJsonParseError::NoError) {
656 setError(tr("Unable to parse release: "), jsonError, response);
657 return;
658 }
659#if !defined(QT_JSON_READONLY)
660 if (m_p->verbose) {
661 qDebug().noquote() << "Update check: found release info: " << QString::fromUtf8(replyDoc.toJson(QJsonDocument::Indented));
662 }
663#endif
664 processAssets(replyDoc.object().value(QLatin1String("assets")).toArray(), reply->property("forUpdate").toBool(),
665 reply->property("forPreviousVersion").toBool());
666 break;
667 }
668 case QNetworkReply::OperationCanceledError:
669 emit inProgressChanged(m_p->inProgress = false);
670 return;
671 default:
672 setError(tr("Unable to request release: "), reply);
673 }
674#endif
675}
676
677void UpdateNotifier::processAssets(const QJsonArray &assets, bool forUpdate, bool forPreviousVersion)
678{
679#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
680 Q_UNUSED(assets)
681 Q_UNUSED(forUpdate)
682 Q_UNUSED(forPreviousVersion)
683#else
684 for (const auto &assetVal : assets) {
685 if (forPreviousVersion ? !m_p->previousVersionDownloadUrl.isEmpty() && !m_p->previousVersionSignatureUrl.isEmpty()
686 : !m_p->downloadUrl.isEmpty() && !m_p->signatureUrl.isEmpty()) {
687 break;
688 }
689 const auto asset = assetVal.toObject();
690 const auto assetName = asset.value(QLatin1String("name")).toString();
691 if (assetName.isEmpty()) {
692 continue;
693 }
694 if (!m_p->assetRegex.match(assetName).hasMatch()) {
695 if (m_p->verbose) {
696 qDebug() << "Update check: skipping asset: " << assetName;
697 }
698 continue;
699 }
700 const auto url = asset.value(QLatin1String("browser_download_url")).toString();
701 if (assetName.endsWith(QLatin1String(".sig"))) {
702 (forPreviousVersion ? m_p->previousVersionSignatureUrl : m_p->signatureUrl) = url;
703 } else {
704 (forPreviousVersion ? m_p->previousVersionDownloadUrl : m_p->downloadUrl) = url;
705 }
706 }
707 if (forUpdate) {
708 m_p->updateAvailable = !m_p->downloadUrl.isEmpty();
709 }
710 if (m_p->downloadUrl.isEmpty() && m_p->previousVersionDownloadUrl.isEmpty() && !m_p->previousVersionAssets.isEmpty()) {
711 auto previousVersionAssets = m_p->previousVersionAssets.takeLast();
712 if (std::holds_alternative<QJsonArray>(previousVersionAssets)) {
713 return processAssets(std::get<QJsonArray>(previousVersionAssets), forUpdate, true);
714 } else {
715 return queryRelease(std::get<QString>(previousVersionAssets), forUpdate, true);
716 }
717 }
718 emit checkedForUpdate();
719 emit inProgressChanged(m_p->inProgress = false);
720 if (forUpdate && m_p->updateAvailable && m_p->newVersion != m_p->previouslyFoundNewVersion) {
721 // emit updateAvailable() only if we not have already previously emitted it for this version
722 m_p->previouslyFoundNewVersion = m_p->newVersion;
723 emit updateAvailable(m_p->newVersion, m_p->additionalInfo);
724 }
725#endif
726}
727
728#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
729struct UpdaterPrivate {
730 QNetworkAccessManager *nm = nullptr;
731 QFile *fakeDownload = nullptr;
732 QNetworkReply *currentDownload = nullptr;
733 QNetworkReply *signatureDownload = nullptr;
734 QNetworkRequest::CacheLoadControl cacheLoadControl = QNetworkRequest::PreferNetwork;
735 QString error, statusMessage;
736 QByteArray signature;
737 QFutureWatcher<QPair<QString, QString>> watcher;
738 QString executableName;
739 QString signatureExtension;
740 QRegularExpression executableRegex = QRegularExpression();
741 QString storedPath;
742 Updater::VerifyFunction verifyFunction;
743};
744#else
746 QString error;
747};
748#endif
749
750Updater::Updater(const QString &executableName, QObject *parent)
751 : Updater(executableName, QString(), parent)
752{
753}
754
755Updater::Updater(const QString &executableName, const QString &signatureExtension, QObject *parent)
756 : QObject(parent)
757 , m_p(std::make_unique<UpdaterPrivate>())
758{
759#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
760 Q_UNUSED(executableName)
761 Q_UNUSED(signatureExtension)
762#else
763 connect(&m_p->watcher, &QFutureWatcher<void>::finished, this, &Updater::concludeUpdate);
764 m_p->executableName = executableName;
765 m_p->signatureExtension = signatureExtension;
766 const auto signatureRegex = signatureExtension.isEmpty()
767 ? QString()
768 : QString(QStringLiteral("(") % QRegularExpression::escape(signatureExtension) % QStringLiteral(")?"));
769#ifdef QT_UTILITIES_EXE_REGEX
770 m_p->executableRegex = QRegularExpression(executableName % QStringLiteral(QT_UTILITIES_EXE_REGEX) % signatureRegex);
771#endif
772#endif
773}
774
778
780{
781#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
782 return m_p->currentDownload != nullptr || m_p->signatureDownload != nullptr || m_p->watcher.isRunning();
783#else
784 return false;
785#endif
786}
787
789{
790#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
791 return isInProgress() ? tr("Update in progress …") : (m_p->error.isEmpty() ? tr("Update done") : tr("Update failed"));
792#else
793 return QString();
794#endif
795}
796
797const QString &Updater::error() const
798{
799 return m_p->error;
800}
801
803{
804#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
805 return m_p->statusMessage.isEmpty() ? m_p->error : m_p->statusMessage;
806#else
807 return m_p->error;
808#endif
809}
810
812{
813#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
814 return m_p->storedPath;
815#else
816 static const auto empty = QString();
817 return empty;
818#endif
819}
820
821void Updater::setNetworkAccessManager(QNetworkAccessManager *nm)
822{
823#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
824 m_p->nm = nm;
825#else
826 Q_UNUSED(nm)
827#endif
828}
829
831{
832#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
833 m_p->verifyFunction = std::move(verifyFunction);
834#else
835 Q_UNUSED(verifyFunction)
836#endif
837}
838
839#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
840void Updater::setCacheLoadControl(QNetworkRequest::CacheLoadControl cacheLoadControl)
841{
842 m_p->cacheLoadControl = cacheLoadControl;
843}
844#endif
845
846bool Updater::performUpdate(const QString &downloadUrl, const QString &signatureUrl)
847{
848#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
849 Q_UNUSED(downloadUrl)
850 Q_UNUSED(signatureUrl)
851 setError(tr("This build of the application does not support self-updating."));
852 return false;
853#else
854 if (isInProgress()) {
855 return false;
856 }
857 startDownload(downloadUrl, signatureUrl);
858 return true;
859#endif
860}
861
863{
864#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
865 if (m_p->currentDownload) {
866 m_p->currentDownload->abort();
867 }
868 if (m_p->signatureDownload) {
869 m_p->signatureDownload->abort();
870 }
871 if (m_p->watcher.isRunning()) {
872 m_p->watcher.cancel();
873 }
874#endif
875}
876
877void Updater::setError(const QString &error)
878{
879#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
880 m_p->statusMessage.clear();
881#endif
882 emit updateFailed(m_p->error = error);
883 emit updateStatusChanged(m_p->error);
884 emit updatePercentageChanged(0, 0);
885 emit inProgressChanged(false);
886}
887
888void Updater::startDownload(const QString &downloadUrl, const QString &signatureUrl)
889{
890#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
891 Q_UNUSED(downloadUrl)
892 Q_UNUSED(signatureUrl)
893#else
894 m_p->error.clear();
895 m_p->storedPath.clear();
896 m_p->signature.clear();
897
898 if (const auto fakeDownloadPath = qEnvironmentVariable(PROJECT_VARNAME_UPPER "_UPDATER_FAKE_DOWNLOAD"); !fakeDownloadPath.isEmpty()) {
899 m_p->fakeDownload = new QFile(fakeDownloadPath);
900 m_p->fakeDownload->open(QFile::ReadOnly);
901 emit inProgressChanged(true);
902 storeExecutable();
903 return;
904 }
905
906 auto request = QNetworkRequest(QUrl(downloadUrl));
907 request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, m_p->cacheLoadControl);
908 m_p->statusMessage = tr("Downloading %1").arg(downloadUrl);
909 m_p->currentDownload = m_p->nm->get(request);
910 emit updateStatusChanged(m_p->statusMessage);
911 emit updatePercentageChanged(0, 0);
912 emit inProgressChanged(true);
913 connect(m_p->currentDownload, &QNetworkReply::finished, this, &Updater::handleDownloadFinished);
914 connect(m_p->currentDownload, &QNetworkReply::downloadProgress, this, &Updater::updatePercentageChanged);
915 if (!signatureUrl.isEmpty()) {
916 request.setUrl(signatureUrl);
917 m_p->signatureDownload = m_p->nm->get(request);
918 connect(m_p->signatureDownload, &QNetworkReply::finished, this, &Updater::handleDownloadFinished);
919 }
920#endif
921}
922
923void Updater::handleDownloadFinished()
924{
925#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
926 if (m_p->signatureDownload && !m_p->signatureDownload->isFinished()) {
927 emit updateStatusChanged(tr("Waiting for signature download …"));
928 emit updatePercentageChanged(0, 0);
929 return;
930 }
931 if (!m_p->currentDownload->isFinished()) {
932 return;
933 }
934
935 if (m_p->signatureDownload) {
936 readSignature();
937 m_p->signatureDownload->deleteLater();
938 m_p->signatureDownload = nullptr;
939 }
940
941 if (m_p->error.isEmpty()) {
942 storeExecutable();
943 } else {
944 m_p->currentDownload->deleteLater();
945 }
946 m_p->currentDownload = nullptr;
947#endif
948}
949
950void Updater::readSignature()
951{
952#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
953 switch (m_p->signatureDownload->error()) {
954 case QNetworkReply::NoError:
955 m_p->signature = m_p->signatureDownload->readAll();
956 break;
957 default:
958 setError(tr("Unable to download signature: ") + m_p->signatureDownload->errorString());
959 }
960#endif
961}
962
963void Updater::storeExecutable()
964{
965#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
966 m_p->statusMessage = tr("Extracting …");
967 emit updateStatusChanged(m_p->statusMessage);
968 emit updatePercentageChanged(0, 0);
969 auto *reply = static_cast<QIODevice *>(m_p->fakeDownload);
970 auto archiveName = QString();
971 auto hasError = false;
972 if (reply) {
973 archiveName = m_p->fakeDownload->fileName();
974 hasError = m_p->fakeDownload->error() != QFileDevice::NoError;
975 } else {
976 reply = m_p->currentDownload;
977 archiveName = m_p->currentDownload->request().url().fileName();
978 hasError = m_p->currentDownload->error() != QNetworkReply::NoError;
979 }
980 if (hasError) {
981 reply->deleteLater();
982 setError(tr("Unable to download update: ") + reply->errorString());
983 return;
984 }
985 auto res = QtConcurrent::run([this, reply, archiveName] {
986 const auto data = reply->readAll();
987 const auto dataView = std::string_view(data.data(), static_cast<std::size_t>(data.size()));
988 auto foundExecutable = false, foundSignature = false;
989 auto error = QString(), storePath = QString();
990 auto newExeName = std::string(), signatureName = std::string();
991 auto newExeData = std::string();
992 auto newExe = QFile();
993 reply->deleteLater();
994
995 // determine current executable path
996 const auto appDirPath = QCoreApplication::applicationDirPath();
997 const auto appFilePath = QCoreApplication::applicationFilePath();
998 if (appDirPath.isEmpty() || appFilePath.isEmpty()) {
999 error = tr("Unable to determine application path.");
1000 return QPair<QString, QString>(error, storePath);
1001 }
1002
1003 // handle cancellations
1004 const auto checkCancellation = [this, &error] {
1005 if (m_p->watcher.isCanceled()) {
1006 error = tr("Extraction was cancelled.");
1007 return true;
1008 } else {
1009 return false;
1010 }
1011 };
1012 if (checkCancellation()) {
1013 return QPair<QString, QString>(error, storePath);
1014 }
1015
1016 try {
1017 CppUtilities::walkThroughArchiveFromBuffer(
1018 dataView, archiveName.toStdString(),
1019 [this](const char *filePath, const char *fileName, mode_t mode) {
1020 Q_UNUSED(filePath)
1021 Q_UNUSED(mode)
1022 if (m_p->watcher.isCanceled()) {
1023 return true;
1024 }
1025 return m_p->executableRegex.match(QString::fromUtf8(fileName)).hasMatch();
1026 },
1027 [&](std::string_view path, CppUtilities::ArchiveFile &&file) {
1028 Q_UNUSED(path)
1029 if (checkCancellation()) {
1030 return true;
1031 }
1032 if (file.type != CppUtilities::ArchiveFileType::Regular) {
1033 return false;
1034 }
1035
1036 // read signature file
1037 const auto fileName = QString::fromUtf8(file.name.data(), static_cast<QString::size_type>(file.name.size()));
1038 if (!m_p->signatureExtension.isEmpty() && fileName.endsWith(m_p->signatureExtension)) {
1039 m_p->signature = QByteArray::fromStdString(file.content);
1040 foundSignature = true;
1041 signatureName = file.name;
1042 return foundExecutable;
1043 }
1044
1045 // skip signature files (that don't match m_p->signatureExtension but are present anyway)
1046 if (fileName.endsWith(QLatin1String(".sig"))) {
1047 return false;
1048 }
1049
1050 // write executable from archive to disk (using a temporary filename)
1051 foundExecutable = true;
1052 newExeName = file.name;
1053 newExe.setFileName(appDirPath % QChar('/') % fileName % QStringLiteral(".tmp"));
1054 if (!newExe.open(QFile::WriteOnly | QFile::Truncate)) {
1055 error = tr("Unable to create new executable under \"%1\": %2").arg(newExe.fileName(), newExe.errorString());
1056 return true;
1057 }
1058 const auto size = static_cast<qint64>(file.content.size());
1059 if (!(newExe.write(file.content.data(), size) == size) || !newExe.flush()) {
1060 error = tr("Unable to write new executable under \"%1\": %2").arg(newExe.fileName(), newExe.errorString());
1061 return true;
1062 }
1063 if (!newExe.setPermissions(
1064 newExe.permissions() | QFileDevice::ExeOwner | QFileDevice::ExeUser | QFileDevice::ExeGroup | QFileDevice::ExeOther)) {
1065 error = tr("Unable to make new binary under \"%1\" executable.").arg(newExe.fileName());
1066 return true;
1067 }
1068
1069 storePath = newExe.fileName();
1070 newExeData = std::move(file.content);
1071 return foundSignature || m_p->signatureExtension.isEmpty();
1072 });
1073 } catch (const CppUtilities::ArchiveException &e) {
1074 error = tr("Unable to open downloaded archive: %1").arg(e.what());
1075 }
1076 if (error.isEmpty() && foundExecutable) {
1077 // verify whether downloaded binary is valid if a verify function was assigned
1078 if (m_p->verifyFunction) {
1079 if (const auto verifyError = m_p->verifyFunction(Updater::Update{ .executableName = newExeName,
1080 .signatureName = signatureName,
1081 .data = newExeData,
1082 .signature = std::string_view(m_p->signature.data(), static_cast<std::size_t>(m_p->signature.size())) });
1083 !verifyError.isEmpty()) {
1084 error = tr("Unable to verify whether downloaded binary is valid: %1").arg(verifyError);
1085 return QPair<QString, QString>(error, storePath);
1086 }
1087 }
1088
1089 // rename current executable to keep it as backup
1090 auto currentExeInfo = QFileInfo(appFilePath);
1091 auto currentExe = QFile(appFilePath);
1092 const auto completeSuffix = currentExeInfo.completeSuffix();
1093 const auto suffixWithDot = completeSuffix.isEmpty() ? QString() : QChar('.') + completeSuffix;
1094 for (auto i = 0; i < 100; ++i) {
1095 const auto backupNumber = i ? QString::number(i) : QString();
1096 const auto backupPath = QString(currentExeInfo.path() % QChar('/') % currentExeInfo.baseName() % QStringLiteral("-backup")
1097 % backupNumber % QChar('-') % QString::fromUtf8(CppUtilities::applicationInfo.version) % suffixWithDot);
1098 if (QFile::exists(backupPath)) {
1099 continue;
1100 }
1101 if (!currentExe.rename(backupPath)) {
1102 error = tr("Unable to move current executable to \"%1\": %2").arg(backupPath, currentExe.errorString());
1103 return QPair<QString, QString>(error, storePath);
1104 }
1105 break;
1106 }
1107
1108 // rename new executable to use it in place of current executable
1109 if (!newExe.rename(appFilePath)) {
1110 error = tr("Unable to rename new executable \"%1\" to \"%2\": %3").arg(newExe.fileName(), appFilePath, newExe.errorString());
1111 return QPair<QString, QString>(error, storePath);
1112 }
1113 storePath = newExe.fileName();
1114 }
1115 if (error.isEmpty() && !foundExecutable) {
1116 error = tr("Unable to find executable in downloaded archive.");
1117 }
1118 return QPair<QString, QString>(error, storePath);
1119 });
1120 m_p->watcher.setFuture(std::move(res));
1121#endif
1122}
1123
1124void Updater::concludeUpdate()
1125{
1126#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1127 auto res = m_p->watcher.result();
1128 m_p->error = res.first;
1129 m_p->storedPath = res.second;
1130 if (!m_p->error.isEmpty()) {
1131 m_p->statusMessage.clear();
1132 emit updateFailed(m_p->error);
1133 } else {
1134 m_p->statusMessage = tr("Update stored under: %1").arg(m_p->storedPath);
1135 emit updateStored();
1136 }
1137 emit updateStatusChanged(statusMessage());
1138 emit updatePercentageChanged(0, 0);
1139 emit inProgressChanged(false);
1140#endif
1141}
1142
1144 explicit UpdateHandlerPrivate(const QString &executableName, const QString &signatureExtension)
1145 : updater(executableName.isEmpty() ? notifier.executableName() : executableName, signatureExtension)
1146 {
1147 }
1148
1151 QTimer timer;
1152 QSettings *settings;
1153 std::optional<UpdateHandler::CheckInterval> checkInterval;
1156};
1157
1158UpdateHandler *UpdateHandler::s_mainInstance = nullptr;
1159
1163UpdateHandler::UpdateHandler(QSettings *settings, QNetworkAccessManager *nm, QObject *parent)
1164 : QtUtilities::UpdateHandler(QString(), QString(), settings, nm, parent)
1165{
1166}
1167
1172 const QString &executableName, const QString &signatureExtension, QSettings *settings, QNetworkAccessManager *nm, QObject *parent)
1173 : QObject(parent)
1174 , m_p(std::make_unique<UpdateHandlerPrivate>(executableName, signatureExtension))
1175{
1176 m_p->notifier.setNetworkAccessManager(nm);
1177 m_p->updater.setNetworkAccessManager(nm);
1178 m_p->timer.setSingleShot(true);
1179 m_p->timer.setTimerType(Qt::VeryCoarseTimer);
1180 m_p->settings = settings;
1181 connect(&m_p->timer, &QTimer::timeout, &m_p->notifier, &UpdateNotifier::checkForUpdate);
1182 connect(&m_p->notifier, &UpdateNotifier::checkedForUpdate, this, &UpdateHandler::handleUpdateCheckDone);
1183}
1184
1188
1190{
1191 return &m_p->notifier;
1192}
1193
1194Updater *UpdateHandler::updater()
1195{
1196 return &m_p->updater;
1197}
1198
1200{
1201 if (m_p->checkInterval.has_value()) {
1202 return m_p->checkInterval.value();
1203 }
1204 m_p->settings->beginGroup(QStringLiteral("updating"));
1205 auto &checkInterval = m_p->checkInterval.emplace();
1206 checkInterval.duration = CppUtilities::TimeSpan::fromMilliseconds(m_p->settings->value("checkIntervalMs", 60 * 60 * 1000).toInt());
1207 checkInterval.enabled = m_p->settings->value("automaticChecksEnabled", false).toBool();
1208 m_p->settings->endGroup();
1209 return checkInterval;
1210}
1211
1213{
1214 m_p->checkInterval = checkInterval;
1215 m_p->settings->beginGroup(QStringLiteral("updating"));
1216 m_p->settings->setValue("checkIntervalMs", checkInterval.duration.totalMilliseconds());
1217 m_p->settings->setValue("automaticChecksEnabled", checkInterval.enabled);
1218 m_p->settings->endGroup();
1219#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1220 scheduleNextUpdateCheck();
1221#endif
1222}
1223
1225{
1226 return m_p->considerSeparateSignature;
1227}
1228
1229void UpdateHandler::setConsideringSeparateSignature(bool consideringSeparateSignature)
1230{
1231 m_p->considerSeparateSignature = consideringSeparateSignature;
1232}
1233
1235{
1236 auto error = QString();
1237#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1238 static const auto appDirPath = QCoreApplication::applicationDirPath();
1239 if (appDirPath.isEmpty()) {
1240 return tr("Unable to determine the application directory.");
1241 }
1242#if defined(Q_OS_WINDOWS) && (QT_VERSION >= QT_VERSION_CHECK(6, 6, 0))
1243 const auto permissionGuard = QNtfsPermissionCheckGuard();
1244#endif
1245 const auto dirInfo = QFileInfo(appDirPath);
1246 if (!dirInfo.isWritable()) {
1247 return tr("The directory where the executable is stored (%1) is not writable.").arg(appDirPath);
1248 }
1249#endif
1250 return error;
1251}
1252
1253#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1254void UpdateHandler::setCacheLoadControl(QNetworkRequest::CacheLoadControl cacheLoadControl)
1255{
1256 m_p->notifier.setCacheLoadControl(cacheLoadControl);
1257 m_p->updater.setCacheLoadControl(cacheLoadControl);
1258}
1259#endif
1260
1262{
1263#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1264 m_p->notifier.restore(m_p->settings);
1265 scheduleNextUpdateCheck();
1266#endif
1267}
1268
1270{
1271 const auto &downloadUrl = !m_p->notifier.downloadUrl().isEmpty() ? m_p->notifier.downloadUrl() : m_p->notifier.previousVersionDownloadUrl();
1272 const auto &signatureUrl = !m_p->notifier.downloadUrl().isEmpty() ? m_p->notifier.signatureUrl() : m_p->notifier.previousVersionSignatureUrl();
1273 m_p->updater.performUpdate(downloadUrl.toString(), m_p->considerSeparateSignature ? signatureUrl.toString() : QString());
1274}
1275
1277{
1278#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1279 m_p->notifier.save(m_p->settings);
1280#endif
1281}
1282
1283void UpdateHandler::handleUpdateCheckDone()
1284{
1285#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1287 scheduleNextUpdateCheck();
1288#endif
1289}
1290
1291#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1292void UpdateHandler::scheduleNextUpdateCheck()
1293{
1294 m_p->timer.stop();
1295
1296 const auto &interval = checkInterval();
1297 if (!interval.enabled || (interval.duration.isNull() && m_p->hasCheckedOnceSinceStartup)) {
1298 return;
1299 }
1300 const auto timeLeft = interval.duration - (CppUtilities::DateTime::now() - m_p->notifier.lastCheck());
1301 std::cerr << CppUtilities::EscapeCodes::Phrases::Info
1302 << "Check for updates due in: " << timeLeft.toString(CppUtilities::TimeSpanOutputFormat::WithMeasures)
1303 << CppUtilities::EscapeCodes::Phrases::End;
1304 m_p->hasCheckedOnceSinceStartup = true; // the attempt counts
1305 m_p->timer.start(std::max(1000, static_cast<int>(timeLeft.totalMilliseconds())));
1306}
1307#endif
1308
1310{
1311 m_restartRequested = true;
1312#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1313 QCoreApplication::quit();
1314#endif
1315}
1316
1318{
1319#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1320 if (!m_restartRequested) {
1321 return;
1322 }
1323 auto *const process = new QProcess(QCoreApplication::instance());
1324 auto args = QCoreApplication::arguments();
1325 args.removeFirst();
1326 process->setProgram(QCoreApplication::applicationFilePath());
1327 process->setArguments(args);
1328 process->startDetached();
1329#endif
1330}
1331
1332#ifdef QT_UTILITIES_GUI_QTWIDGETS
1333struct UpdateOptionPagePrivate {
1334 UpdateOptionPagePrivate(UpdateHandler *updateHandler)
1335 : updateHandler(updateHandler)
1336 {
1337 }
1338 UpdateHandler *updateHandler = nullptr;
1339 std::function<void()> restartHandler;
1340};
1341
1342UpdateOptionPage::UpdateOptionPage(UpdateHandler *updateHandler, QWidget *parentWidget)
1343 : UpdateOptionPageBase(parentWidget)
1344#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1345 , m_p(std::make_unique<UpdateOptionPagePrivate>(updateHandler))
1346#endif
1347{
1348#ifndef QT_UTILITIES_SETUP_TOOLS_ENABLED
1349 Q_UNUSED(updateHandler)
1350#endif
1351}
1352
1353UpdateOptionPage::~UpdateOptionPage()
1354{
1355}
1356
1357void UpdateOptionPage::setRestartHandler(std::function<void()> &&handler)
1358{
1359 m_p->restartHandler = std::move(handler);
1360#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1361 if (ui() && m_p->restartHandler) {
1362 QObject::connect(ui()->restartPushButton, &QPushButton::clicked, widget(), m_p->restartHandler);
1363 }
1364#endif
1365}
1366
1367bool UpdateOptionPage::apply()
1368{
1369#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1370 if (!m_p->updateHandler) {
1371 return true;
1372 }
1373 m_p->updateHandler->setCheckInterval(UpdateHandler::CheckInterval{
1374 .duration = CppUtilities::TimeSpan::fromMinutes(ui()->checkIntervalSpinBox->value()), .enabled = ui()->enabledCheckBox->isChecked() });
1375 auto flags = UpdateCheckFlags::None;
1376 CppUtilities::modFlagEnum(flags, UpdateCheckFlags::IncludePreReleases, ui()->preReleasesCheckBox->isChecked());
1377 CppUtilities::modFlagEnum(flags, UpdateCheckFlags::IncludeDrafts, ui()->draftsCheckBox->isChecked());
1378 m_p->updateHandler->notifier()->setFlags(flags);
1379 m_p->updateHandler->saveNotifierState();
1380#endif
1381 return true;
1382}
1383
1384void UpdateOptionPage::reset()
1385{
1386#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1387 if (!m_p->updateHandler) {
1388 return;
1389 }
1390 const auto &checkInterval = m_p->updateHandler->checkInterval();
1391 ui()->checkIntervalSpinBox->setValue(static_cast<int>(checkInterval.duration.totalMinutes()));
1392 ui()->enabledCheckBox->setChecked(checkInterval.enabled);
1393 const auto flags = m_p->updateHandler->notifier()->flags();
1394 ui()->preReleasesCheckBox->setChecked(flags && UpdateCheckFlags::IncludePreReleases);
1395 ui()->draftsCheckBox->setChecked(flags && UpdateCheckFlags::IncludeDrafts);
1396#endif
1397}
1398
1399#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1400static QString formatReleaseNotes(const QString &version, const QString &releaseNotes)
1401{
1402 auto res = QCoreApplication::translate("QtGui::UpdateOptionPage", "**Release notes of version %1:**\n\n").arg(version) + releaseNotes;
1403
1404 // ensure links like "https://github.com/…/compare/v2.0.0...v2.0.1" are not cut short at the first "."
1405 static const auto re = QRegularExpression(R"(https://github\.com/[^\s)]+)");
1406 static constexpr auto replacementLengthDiff = qsizetype(2);
1407 auto offset = qsizetype();
1408 for (auto it = re.globalMatch(res); it.hasNext(); offset += replacementLengthDiff) {
1409 const auto match = it.next();
1410 const auto replacement = QChar('<') % match.captured(0) % QChar('>');
1411 res.replace(match.capturedStart() + offset, match.capturedLength(), replacement);
1412 }
1413
1414 return res;
1415}
1416#endif
1417
1418QWidget *UpdateOptionPage::setupWidget()
1419{
1420#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1421 if (m_p->updateHandler && m_p->updateHandler->notifier()->isSupported()) {
1422 auto *const widget = UpdateOptionPageBase::setupWidget(); // call base implementation first, so ui() is available
1423 ui()->versionInUseValueLabel->setText(QString::fromUtf8(CppUtilities::applicationInfo.version));
1424 ui()->updateWidget->hide();
1425 ui()->releaseNotesPushButton->hide();
1426 updateLatestVersion();
1427 QObject::connect(ui()->checkNowPushButton, &QPushButton::clicked, m_p->updateHandler->notifier(), &UpdateNotifier::checkForUpdate);
1428 QObject::connect(ui()->updatePushButton, &QPushButton::clicked, widget, [this, widget] {
1429 if (const auto preCheckError = m_p->updateHandler->preCheck(); preCheckError.isEmpty()
1430 || QMessageBox::critical(widget, QCoreApplication::applicationName(),
1431 QCoreApplication::translate("QtGui::UpdateOptionPage", "<p>%1</p><p><strong>Try the update nevertheless?</strong></p>")
1432 .arg(preCheckError),
1433 QMessageBox::Yes | QMessageBox::No)
1434 == QMessageBox::Yes) {
1435 m_p->updateHandler->performUpdate();
1436 }
1437 });
1438 QObject::connect(ui()->abortUpdatePushButton, &QPushButton::clicked, m_p->updateHandler->updater(), &Updater::abortUpdate);
1439 if (m_p->restartHandler) {
1440 QObject::connect(ui()->restartPushButton, &QPushButton::clicked, widget, m_p->restartHandler);
1441 }
1442 QObject::connect(ui()->releaseNotesPushButton, &QPushButton::clicked, widget, [this, widget] {
1443 const auto *const notifier = m_p->updateHandler->notifier();
1444 auto infobox = QMessageBox(widget);
1445 infobox.setWindowTitle(QCoreApplication::applicationName());
1446 infobox.setIcon(QMessageBox::Information);
1447 infobox.setText(formatReleaseNotes(notifier->latestVersion(), notifier->releaseNotes()));
1448#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
1449 infobox.setTextFormat(Qt::MarkdownText);
1450#else
1451 infobox.setTextFormat(Qt::PlainText);
1452#endif
1453 infobox.exec();
1454 });
1455 QObject::connect(
1456 m_p->updateHandler->notifier(), &UpdateNotifier::inProgressChanged, widget, [this](bool inProgress) { updateLatestVersion(inProgress); });
1457 QObject::connect(m_p->updateHandler->updater(), &Updater::inProgressChanged, widget, [this](bool inProgress) {
1458 const auto *const updater = m_p->updateHandler->updater();
1459 ui()->updateWidget->setVisible(true);
1460 ui()->updateInProgressLabel->setText(updater->overallStatus());
1461 ui()->updateProgressBar->setVisible(inProgress);
1462 ui()->abortUpdatePushButton->setVisible(inProgress);
1463 ui()->restartPushButton->setVisible(!inProgress && !updater->storedPath().isEmpty() && updater->error().isEmpty());
1464 });
1465 QObject::connect(m_p->updateHandler->updater(), &Updater::updateStatusChanged, widget,
1466 [this](const QString &statusMessage) { ui()->updateStatusLabel->setText(statusMessage); });
1467 QObject::connect(m_p->updateHandler->updater(), &Updater::updatePercentageChanged, widget, [this](qint64 bytesReceived, qint64 bytesTotal) {
1468 if (bytesTotal == 0) {
1469 ui()->updateProgressBar->setMaximum(0);
1470 } else {
1471 ui()->updateProgressBar->setValue(static_cast<int>(bytesReceived * 100 / bytesTotal));
1472 ui()->updateProgressBar->setMaximum(100);
1473 }
1474 });
1475 return widget;
1476 }
1477#endif
1478
1479 auto *const label = new QLabel;
1480 label->setWindowTitle(QCoreApplication::translate("QtGui::UpdateOptionPage", "Updating"));
1481 label->setAlignment(Qt::AlignCenter);
1482 label->setWordWrap(true);
1483#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1484 label->setText(QCoreApplication::translate("QtUtilities::UpdateOptionPage", "Checking for updates is not supported on this platform."));
1485#else
1486 label->setText(QCoreApplication::translate("QtUtilities::UpdateOptionPage",
1487 "This build of %1 has automatic updates disabled. You may update the application in an automated way via your package manager, though.")
1488 .arg(CppUtilities::applicationInfo.name));
1489#endif
1490 return label;
1491}
1492
1493void UpdateOptionPage::updateLatestVersion(bool)
1494{
1495#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1496 if (!m_p->updateHandler) {
1497 return;
1498 }
1499 const auto &notifier = *m_p->updateHandler->notifier();
1500 const auto &downloadUrl = notifier.downloadUrl();
1501 const auto &previousVersionDownloadUrl = notifier.previousVersionDownloadUrl();
1502 const auto downloadUrlEscaped = downloadUrl.toString().toHtmlEscaped();
1503 const auto previousVersionDownloadUrlEscaped = previousVersionDownloadUrl.toString().toHtmlEscaped();
1504 ui()->latestVersionValueLabel->setText(notifier.status());
1505 ui()->downloadUrlLabel->setText(downloadUrl.isEmpty()
1506 ? (notifier.latestVersion().isEmpty()
1507 ? QCoreApplication::translate("QtUtilities::UpdateOptionPage", "no new version available for download")
1508 : (QCoreApplication::translate("QtUtilities::UpdateOptionPage", "latest version provides no build for the current platform yet")
1509 + (previousVersionDownloadUrl.isEmpty()
1510 ? QString()
1511 : QString(QStringLiteral("<br>")
1512 % QCoreApplication::translate("QtUtilities::UpdateOptionPage", "for latest build: ")
1513 % QStringLiteral("<a href=\"") % previousVersionDownloadUrlEscaped % QStringLiteral("\">")
1514 % previousVersionDownloadUrlEscaped % QStringLiteral("</a>")))))
1515 : (QStringLiteral("<a href=\"") % downloadUrlEscaped % QStringLiteral("\">") % downloadUrlEscaped % QStringLiteral("</a>")));
1516 ui()->updatePushButton->setText(!downloadUrl.isEmpty() || previousVersionDownloadUrl.isEmpty()
1517 ? QCoreApplication::translate("QtUtilities::UpdateOptionPage", "Update to latest version")
1518 : QCoreApplication::translate("QtUtilities::UpdateOptionPage", "Update to latest available build"));
1519 ui()->updatePushButton->setDisabled(downloadUrl.isEmpty() && previousVersionDownloadUrl.isEmpty());
1520 ui()->releaseNotesPushButton->setHidden(notifier.releaseNotes().isEmpty());
1521#endif
1522}
1523
1524VerificationErrorMessageBox::VerificationErrorMessageBox()
1525{
1526#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1527 setWindowTitle(QCoreApplication::applicationName());
1528 setStandardButtons(QMessageBox::Cancel | QMessageBox::Ignore);
1529 setDefaultButton(QMessageBox::Cancel);
1530 setIcon(QMessageBox::Critical);
1531#endif
1532}
1533
1534VerificationErrorMessageBox::~VerificationErrorMessageBox()
1535{
1536}
1537
1538int VerificationErrorMessageBox::execForError(QString &errorMessage, const QString &explanation)
1539{
1540#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1541 auto loop = QEventLoop();
1542 QObject::connect(this, &QDialog::finished, &loop, &QEventLoop::exit);
1543 QMetaObject::invokeMethod(this, "openForError", Qt::QueuedConnection, Q_ARG(QString, errorMessage), Q_ARG(QString, explanation));
1544 auto res = loop.exec();
1545 if (res == QMessageBox::Ignore) {
1546 errorMessage.clear();
1547 }
1548 return res;
1549#else
1550 Q_UNUSED(errorMessage)
1551 Q_UNUSED(explanation)
1552 return 0;
1553#endif
1554}
1555
1556void VerificationErrorMessageBox::openForError(const QString &errorMessage, const QString &explanation)
1557{
1558#ifdef QT_UTILITIES_SETUP_TOOLS_ENABLED
1559 setText(tr("<p>The signature of the downloaded executable could not be verified: %1</p>").arg(errorMessage) + explanation);
1560 open();
1561#else
1562 Q_UNUSED(errorMessage)
1563 Q_UNUSED(explanation)
1564#endif
1565}
1566
1567struct UpdateDialogPrivate {
1568 UpdateOptionPage *updateOptionPage = nullptr;
1569};
1570
1571UpdateDialog::UpdateDialog(QWidget *parent)
1572 : SettingsDialog(parent)
1573 , m_p(std::make_unique<UpdateDialogPrivate>())
1574{
1575 auto *const category = new OptionCategory;
1576 m_p->updateOptionPage = new UpdateOptionPage(UpdateHandler::mainInstance(), this);
1577 category->assignPages({ m_p->updateOptionPage });
1578 setWindowTitle(m_p->updateOptionPage->widget()->windowTitle());
1579 setTabBarAlwaysVisible(false);
1580 setSingleCategory(category);
1581}
1582
1583UpdateDialog::~UpdateDialog()
1584{
1585}
1586
1587UpdateOptionPage *UpdateDialog::page()
1588{
1589 return m_p->updateOptionPage;
1590}
1591
1592const UpdateOptionPage *UpdateDialog::page() const
1593{
1594 return m_p->updateOptionPage;
1595}
1596
1597#endif
1598
1599} // namespace QtUtilities
1600
1601#if defined(QT_UTILITIES_GUI_QTWIDGETS)
1603#endif
The SettingsDialog class provides a framework for creating settings dialogs with different categories...
The UpdateHandler class manages the non-graphical aspects of checking for new updates and performing ...
Definition updater.h:189
bool isConsideringSeparateSignature() const
Definition updater.cpp:1224
static UpdateHandler * mainInstance()
Definition updater.h:239
void setConsideringSeparateSignature(bool consideringSeparateSignature)
Definition updater.cpp:1229
UpdateHandler(QSettings *settings, QNetworkAccessManager *nm, QObject *parent=nullptr)
Handles checking for updates and performing an update of the application if available.
Definition updater.cpp:1163
const CheckInterval & checkInterval() const
Definition updater.cpp:1199
UpdateNotifier * notifier
Definition updater.h:191
QString preCheck() const
Definition updater.cpp:1234
void setCheckInterval(CheckInterval checkInterval)
Definition updater.cpp:1212
The UpdateNotifier class allows checking for new updates.
Definition updater.h:61
void setFlags(UpdateCheckFlags flags)
Definition updater.cpp:270
void setNetworkAccessManager(QNetworkAccessManager *nm)
Definition updater.cpp:442
UpdateNotifier(QObject *parent=nullptr)
Definition updater.cpp:189
void save(QSettings *settings)
Definition updater.cpp:402
bool isUpdateAvailable() const
Definition updater.cpp:252
void inProgressChanged(bool inProgress)
void supplyNewReleaseData(const QByteArray &data)
Definition updater.cpp:534
UpdateCheckFlags flags() const
Definition updater.cpp:261
const QString & latestVersion() const
Definition updater.cpp:299
void restore(QSettings *settings)
Definition updater.cpp:383
CppUtilities::DateTime lastCheck() const
Definition updater.cpp:374
The Updater class allows downloading and applying an update.
Definition updater.h:131
Updater(const QString &executableName, QObject *parent=nullptr)
Definition updater.cpp:750
void updatePercentageChanged(qint64 bytesReceived, qint64 bytesTotal)
void updateStatusChanged(const QString &statusMessage)
void updateFailed(const QString &error)
QString overallStatus
Definition updater.h:134
std::function< QString(const Update &)> VerifyFunction
Definition updater.h:146
QString statusMessage
Definition updater.h:136
bool performUpdate(const QString &downloadUrl, const QString &signatureUrl)
Definition updater.cpp:846
void setVerifier(VerifyFunction &&verifyFunction)
Definition updater.cpp:830
void inProgressChanged(bool inProgress)
void setNetworkAccessManager(QNetworkAccessManager *nm)
Definition updater.cpp:821
~Updater() override
Definition updater.cpp:775
bool isInProgress() const
Definition updater.cpp:779
qsizetype VersionSuffixIndex
Definition updater.cpp:108
#define INSTANTIATE_UI_FILE_BASED_OPTION_PAGE(SomeClass)
Instantiates a class declared with BEGIN_DECLARE_UI_FILE_BASED_OPTION_PAGE in a convenient way.
Definition optionpage.h:250
UpdateHandlerPrivate(const QString &executableName, const QString &signatureExtension)
Definition updater.cpp:1144
std::optional< UpdateHandler::CheckInterval > checkInterval
Definition updater.cpp:1153
The CheckInterval struct specifies whether automatic checks for updates are enabled and of often they...
Definition updater.h:196
#define QT_UTILITIES_EXE_REGEX
Definition updater.cpp:82
#define QT_UTILITIES_VERSION_SUFFIX
Definition updater.cpp:74