diff --git a/README.md b/README.md index 28fda65..afc102f 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ ui/backend/recording records draw calls — the test harness ui/backend/qt QtCanvas, QtPaintedWidget, QtTheme — Qt6 Widgets ui/backend/qt/update release check, verified download, installer, issue log — Qt6 Network + …/widgets update banner, update assistant, issue report — Qt6 Widgets ``` Still to come: `ui/model` (FormSpec, TableModel), `ui/sim`, diff --git a/doc/portability.md b/doc/portability.md index 60e9d4f..d00b2d7 100644 --- a/doc/portability.md +++ b/doc/portability.md @@ -78,17 +78,28 @@ banner and dialogs. Nothing in it names a product: the caller passes the release its current version, its issue page and its log file name. It is Qt-only because it is HTTP, files, processes and JSON, which Qt already does on every desktop platform the tools ship on. -| Component | What it does | -|----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------| -| `ReleaseVersion` | Parses and orders `vMAJOR.MINOR.PATCH` tags | -| `ReleaseFeed` | Reads a GitHub "latest release": its version, page, every asset downloadable over HTTPS with its SHA-256, and the installer for this platform | -| `UpdateChecker` | Fetches the feed and says whether a newer release exists | -| `UpdateDownloader` | Downloads an installer next to a `.part` file, checks its size and SHA-256, and refuses an asset without a published checksum or with a path | -| `UpdateInstallation` | Tells a packaged install from a portable one and builds the command that installs an update (`apt-get` through `pkexec`, or the NSIS setup) | -| `UpdateInstaller` | Runs that command and reports whether the tool must exit first | -| `UpdateSession` | Offer, download, install, cancel and dismiss as one state machine; `SetBlocked` holds the install back while the tool is busy with hardware | -| `IssueLog` | A rotating log file plus the recent lines in memory, optionally capturing Qt's own messages | -| `IssueReport` | Builds the new-issue URL with the product, version, platform and recent log, trimmed to fit a URL | +| Component | What it does | +|----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------| +| `ReleaseVersion` | Parses and orders `vMAJOR.MINOR.PATCH` tags | +| `ReleaseFeed` | Reads a GitHub "latest release": its version, page, every asset downloadable over HTTPS with its SHA-256, and the installer for this platform | +| `UpdateChecker` | Fetches the feed and says whether a newer release exists | +| `UpdateDownloader` | Downloads an installer next to a `.part` file, checks its size and SHA-256, and refuses an asset without a published checksum or with a path | +| `UpdateInstallation` | Tells a packaged install from a portable one and builds the command that installs an update (`apt-get` through `pkexec`, or the NSIS setup) | +| `UpdateInstaller` | Runs that command and reports whether the tool must exit first | +| `UpdateSession` | Offer, download, install, cancel and dismiss as one state machine; `SetBlocked` holds the install back while the tool is busy with hardware | +| `IssueLog` | A rotating log file plus the recent lines in memory, optionally capturing Qt's own messages | +| `IssueReport` | Builds the new-issue URL with the product, version, platform and recent log, trimmed to fit a URL | + +`ui.backend.qt.update_widgets` (`ui/backend/qt/update/widgets`) adds the Widgets side every tool repeated: the banner, the +check-download-install flow behind it and the issue report. A tool describes itself once in an `UpdateProduct` +(names, version, feed, release and issue pages, user agent, and the action that releases a blocked install) and places +the banner in its window. + +| Component | What it does | +|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------| +| `UpdateBanner` | Offer, download progress, ready, installing and failure, with Install, Release Notes, Skip, Cancel and Later | +| `UpdateAssistant` | Owns the checker, session and banner: automatic daily checks (a setting), skipped versions, the install confirmation and the restart signals | +| `OpenIssueReport` | Opens the prefilled new-issue page with the recent log, or says where to report it when no browser opens | The installer asset is found by its name's suffix: `-linux-x86_64.deb` on Linux and `-windows-x86_64-setup.exe` on Windows, so a release attaches one of each per tool. diff --git a/ui/backend/qt/update/CMakeLists.txt b/ui/backend/qt/update/CMakeLists.txt index bf00009..af349e5 100644 --- a/ui/backend/qt/update/CMakeLists.txt +++ b/ui/backend/qt/update/CMakeLists.txt @@ -26,3 +26,4 @@ ui_add_library(ui.backend.qt.update QT ) add_subdirectory(test) +add_subdirectory(widgets) diff --git a/ui/backend/qt/update/widgets/CMakeLists.txt b/ui/backend/qt/update/widgets/CMakeLists.txt new file mode 100644 index 0000000..83ee6a9 --- /dev/null +++ b/ui/backend/qt/update/widgets/CMakeLists.txt @@ -0,0 +1,14 @@ +ui_add_library(ui.backend.qt.update_widgets QT + SOURCES + UpdateAssistant.cpp + UpdateAssistant.hpp + UpdateBanner.cpp + UpdateBanner.hpp + UpdateProduct.hpp + LINK + ui.backend.qt + ui.backend.qt.update + Qt6::Widgets +) + +add_subdirectory(test) diff --git a/ui/backend/qt/update/widgets/UpdateAssistant.cpp b/ui/backend/qt/update/widgets/UpdateAssistant.cpp new file mode 100644 index 0000000..94403c3 --- /dev/null +++ b/ui/backend/qt/update/widgets/UpdateAssistant.cpp @@ -0,0 +1,228 @@ +#include "ui/backend/qt/update/widgets/UpdateAssistant.hpp" +#include "ui/backend/qt/update/IssueReport.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ui::backend::qt::update +{ + namespace + { + const QString skippedVersionKey{ "updates/skippedVersion" }; + const QString automaticKey{ "updates/checkAtStartup" }; + + void RemoveStaleDownloads(const QString& directory) + { + QDirIterator files{ directory, QDir::Files }; + while (files.hasNext()) + QFile::remove(files.next()); + } + } + + UpdateAssistant::UpdateAssistant(const UpdateProduct& product, QWidget& window, UpdateSession::CommandFactory commandFor) + : QObject(&window) + , product(product) + , window(window) + , checker(ReleaseVersion::Parse(product.version.toStdString()).value_or(ReleaseVersion{}), product.feedUrl, product.userAgent) + , session(DownloadDirectory(), product.userAgent, std::move(commandFor)) + , banner(new UpdateBanner(product, &window)) + { + ConnectChecker(); + ConnectSession(); + RemoveStaleDownloads(DownloadDirectory()); + connect(&automaticTimer, &QTimer::timeout, this, [this]() + { + if (Automatic()) + Check(false); + }); + } + + UpdateBanner& UpdateAssistant::Banner() + { + return *banner; + } + + const UpdateState& UpdateAssistant::State() const + { + return session.State(); + } + + void UpdateAssistant::Check(bool userInitiated) + { + userRequested = userRequested || userInitiated; + if (userInitiated) + emit Checking(); + checker.Check(); + } + + void UpdateAssistant::StartAutomaticChecks() + { + automaticTimer.start(automaticInterval); + if (Automatic()) + Check(false); + } + + bool UpdateAssistant::Automatic() const + { + return QSettings{}.value(automaticKey, true).toBool(); + } + + void UpdateAssistant::SetAutomatic(bool automatic) const + { + QSettings{}.setValue(automaticKey, automatic); + } + + void UpdateAssistant::SetBlocked(bool blocked) + { + session.SetBlocked(blocked); + } + + std::optional UpdateAssistant::DefaultCommand(const QString& installerPath) + { + return DefaultUpdateCommand(CurrentInstallerPlatform(), installerPath, QCoreApplication::applicationFilePath(), QCoreApplication::applicationPid()); + } + + QString UpdateAssistant::DownloadDirectory() + { + return QDir{ QStandardPaths::writableLocation(QStandardPaths::CacheLocation) }.filePath("updates"); + } + + void UpdateAssistant::ConnectChecker() + { + connect(&checker, &UpdateChecker::UpdateAvailable, this, &UpdateAssistant::OnAvailable); + connect(&checker, &UpdateChecker::UpToDate, this, [this](const ReleaseInfo& latest) + { + emit Report(IssueSeverity::info, QString("Up to date (latest release %1)").arg(latest.tag)); + if (std::exchange(userRequested, false)) + QMessageBox::information(&window, "Check for Updates", QString("You are running the latest version (%1).").arg(product.version)); + }); + connect(&checker, &UpdateChecker::CheckFailed, this, [this](const QString& reason) + { + emit Report(IssueSeverity::warning, QString("Update check failed: %1").arg(reason)); + if (std::exchange(userRequested, false)) + QMessageBox::warning(&window, "Check for Updates", + QString("Could not check for updates: %1\n\nReleases are also listed at %2").arg(reason, product.releasesUrl.toString())); + }); + } + + void UpdateAssistant::ConnectSession() + { + connect(&session, &UpdateSession::StateChanged, this, &UpdateAssistant::OnStateChanged); + connect(&session, &UpdateSession::RestartRequested, this, [this]() + { + emit Report(IssueSeverity::info, QString("Closing so the installer can update to %1").arg(session.State().release->tag)); + emit RestartRequested(); + }); + connect(&session, &UpdateSession::Relaunch, this, [this]() + { + emit Report(IssueSeverity::info, QString("Update %1 installed; restarting").arg(session.State().release->tag)); + emit RelaunchRequested(); + }); + connect(banner, &UpdateBanner::InstallRequested, this, &UpdateAssistant::RequestInstall); + connect(banner, &UpdateBanner::CancelRequested, &session, &UpdateSession::Cancel); + connect(banner, &UpdateBanner::DismissRequested, &session, &UpdateSession::Dismiss); + connect(banner, &UpdateBanner::SkipRequested, this, &UpdateAssistant::Skip); + } + + void UpdateAssistant::OnAvailable(const ReleaseInfo& release) + { + const auto requested = std::exchange(userRequested, false); + if (!requested && QSettings{}.value(skippedVersionKey).toString() == release.tag) + { + emit Report(IssueSeverity::info, QString("Update available: %1 (skipped)").arg(release.tag)); + return; + } + + emit Report(IssueSeverity::info, QString("Update available: %1").arg(release.tag)); + session.Offer(release); + } + + void UpdateAssistant::OnStateChanged(const UpdateState& state) + { + banner->Render(state); + + if (std::exchange(lastPhase, state.phase) == state.phase || !state.release) + return; + + if (const auto report = PhaseReport(state)) + emit Report(report->severity, report->message); + } + + void UpdateAssistant::RequestInstall() + { + const auto& state = session.State(); + if (state.phase == UpdatePhase::available || state.phase == UpdatePhase::failed) + { + QMessageBox confirm{ &window }; + confirm.setIcon(QMessageBox::Question); + confirm.setWindowTitle("Install Update"); + confirm.setText(QString("Install %1 %2?").arg(product.displayName, QString::fromStdString(state.release->version.ToString()))); + confirm.setInformativeText(InstallSteps() + (state.blocked ? QString("\n\nInstalling waits until you %1.").arg(product.blockedAction.toLower()) : QString{})); + auto* install = confirm.addButton("&Install and Restart", QMessageBox::AcceptRole); + confirm.addButton(QMessageBox::Cancel); + confirm.setDefaultButton(install); + confirm.exec(); + if (confirm.clickedButton() != install) + return; + } + + session.Install(); + } + + void UpdateAssistant::Skip() + { + if (const auto& release = session.State().release) + { + QSettings{}.setValue(skippedVersionKey, release->tag); + emit Report(IssueSeverity::info, QString("Update %1 skipped").arg(release->tag)); + } + session.Dismiss(); + } + + QString UpdateAssistant::InstallSteps() const + { + if (CurrentInstallerPlatform() == InstallerPlatform::windowsX64) + return QString("%1 downloads the installer and checks it against the release. It then closes, Windows asks for permission, and the new version starts when the installation is done.").arg(product.shortName); + + return QString("%1 downloads the package and checks it against the release, then asks for your password to install it and restarts.").arg(product.shortName); + } + + std::optional PhaseReport(const UpdateState& state) + { + if (!state.release) + return std::nullopt; + + const auto& tag = state.release->tag; + switch (state.phase) + { + case UpdatePhase::downloading: + return PhaseMessage{ IssueSeverity::info, QString("Downloading update %1 from %2").arg(tag, state.release->installer ? state.release->installer->url.toString() : state.release->pageUrl.toString()) }; + case UpdatePhase::ready: + return PhaseMessage{ IssueSeverity::info, QString("Update %1 downloaded and verified").arg(tag) }; + case UpdatePhase::installing: + return PhaseMessage{ IssueSeverity::info, QString("Installing update %1").arg(tag) }; + case UpdatePhase::failed: + return PhaseMessage{ IssueSeverity::warning, QString("Update to %1 failed: %2").arg(tag, state.failure) }; + default: + return std::nullopt; + } + } + + bool OpenIssueReport(const UpdateProduct& product, const IssueLog& log, QWidget* parent) + { + const auto environment = CurrentIssueEnvironment(IssueProduct{ product.displayName, product.shortName }, product.version, log.FilePath()); + const auto url = BuildIssueUrl(product.newIssueUrl, environment, log.RecentLines(60)); + if (QDesktopServices::openUrl(url)) + return true; + + QMessageBox::warning(parent, "Report Issue", + QString("Could not open a web browser.\n\nPlease report the issue at %1 and attach the log file:\n%2") + .arg(product.newIssueUrl.toString(), QDir::toNativeSeparators(log.FilePath()))); + return false; + } +} diff --git a/ui/backend/qt/update/widgets/UpdateAssistant.hpp b/ui/backend/qt/update/widgets/UpdateAssistant.hpp new file mode 100644 index 0000000..149bb61 --- /dev/null +++ b/ui/backend/qt/update/widgets/UpdateAssistant.hpp @@ -0,0 +1,73 @@ +#pragma once + +#include "ui/backend/qt/update/IssueLog.hpp" +#include "ui/backend/qt/update/UpdateChecker.hpp" +#include "ui/backend/qt/update/UpdateInstallation.hpp" +#include "ui/backend/qt/update/UpdateSession.hpp" +#include "ui/backend/qt/update/widgets/UpdateBanner.hpp" +#include "ui/backend/qt/update/widgets/UpdateProduct.hpp" +#include +#include +#include +#include +#include +#include + +namespace ui::backend::qt::update +{ + class UpdateAssistant + : public QObject + { + Q_OBJECT + + public: + static constexpr std::chrono::hours automaticInterval{ 24 }; + + UpdateAssistant(const UpdateProduct& product, QWidget& window, UpdateSession::CommandFactory commandFor = DefaultCommand); + + UpdateBanner& Banner(); + const UpdateState& State() const; + + void Check(bool userInitiated); + void StartAutomaticChecks(); + bool Automatic() const; + void SetAutomatic(bool automatic) const; + void SetBlocked(bool blocked); + + static std::optional DefaultCommand(const QString& installerPath); + static QString DownloadDirectory(); + + signals: + void Report(ui::backend::qt::update::IssueSeverity severity, const QString& message); + void Checking(); + void RestartRequested(); + void RelaunchRequested(); + + private: + void ConnectChecker(); + void ConnectSession(); + void OnAvailable(const ReleaseInfo& release); + void OnStateChanged(const UpdateState& state); + void RequestInstall(); + void Skip(); + QString InstallSteps() const; + + UpdateProduct product; + QWidget& window; + UpdateChecker checker; + UpdateSession session; + UpdateBanner* banner; + QTimer automaticTimer; + bool userRequested{ false }; + UpdatePhase lastPhase{ UpdatePhase::idle }; + }; + + struct PhaseMessage + { + IssueSeverity severity; + QString message; + }; + + std::optional PhaseReport(const UpdateState& state); + bool OpenIssueReport(const UpdateProduct& product, const IssueLog& log, QWidget* parent); +} diff --git a/ui/backend/qt/update/widgets/UpdateBanner.cpp b/ui/backend/qt/update/widgets/UpdateBanner.cpp new file mode 100644 index 0000000..b79625a --- /dev/null +++ b/ui/backend/qt/update/widgets/UpdateBanner.cpp @@ -0,0 +1,169 @@ +#include "ui/backend/qt/update/widgets/UpdateBanner.hpp" +#include "ui/backend/qt/QtTheme.hpp" +#include "ui/theme/Theme.hpp" +#include + +namespace ui::backend::qt::update +{ + namespace + { + QString Megabytes(qint64 bytes) + { + return QString::number(static_cast(bytes) / (1024.0 * 1024.0), 'f', 1); + } + } + + UpdateBanner::UpdateBanner(const UpdateProduct& product, QWidget* parent) + : QFrame(parent) + , product(product) + { + setFrameShape(QFrame::StyledPanel); + setAccessibleName("Update"); + + message.setWordWrap(true); + layout.addWidget(&message, 1); + + progress.setAccessibleName("Download progress"); + progress.setMaximumWidth(220); + layout.addWidget(&progress); + + skipButton.setToolTip("Do not offer this version again at automatic checks"); + dismissButton.setToolTip("Hide this message until the next check"); + for (auto* button : { &primaryButton, ¬esButton, &skipButton, &cancelButton, &dismissButton }) + layout.addWidget(button); + + connect(&primaryButton, &QPushButton::clicked, this, &UpdateBanner::OnPrimary); + connect(¬esButton, &QPushButton::clicked, this, [this]() + { + QDesktopServices::openUrl(notesUrl); + }); + connect(&skipButton, &QPushButton::clicked, this, &UpdateBanner::SkipRequested); + connect(&cancelButton, &QPushButton::clicked, this, &UpdateBanner::CancelRequested); + connect(&dismissButton, &QPushButton::clicked, this, &UpdateBanner::DismissRequested); + + hide(); + } + + void UpdateBanner::Render(const UpdateState& state) + { + if (state.phase == UpdatePhase::idle || !state.release) + { + hide(); + return; + } + + notesUrl = state.release->pageUrl; + downloadUrl = state.release->installer ? state.release->installer->url : state.release->pageUrl; + const auto version = QString::fromStdString(state.release->version.ToString()); + progress.setVisible(state.phase == UpdatePhase::downloading); + StyleStatusLabel(message, state.phase == UpdatePhase::failed ? theme::StatusLevel::Warning : theme::StatusLevel::Ok); + + switch (state.phase) + { + case UpdatePhase::available: + RenderOffer(state, version); + break; + case UpdatePhase::downloading: + RenderDownload(state, version); + break; + case UpdatePhase::ready: + RenderReady(state, version); + break; + case UpdatePhase::installing: + message.setText(QString("Installing %1 %2 — %3 restarts when it is done.").arg(product.displayName, version, product.shortName)); + ShowButtons(false, false, false, false, false); + break; + case UpdatePhase::failed: + RenderFailure(state, version); + break; + default: + break; + } + + show(); + } + + QString UpdateBanner::Message() const + { + return message.text(); + } + + QString UpdateBanner::PrimaryText() const + { + return primaryButton.isVisibleTo(this) ? primaryButton.text() : QString{}; + } + + bool UpdateBanner::PrimaryEnabled() const + { + return primaryButton.isEnabled(); + } + + void UpdateBanner::RenderOffer(const UpdateState& state, const QString& version) + { + message.setText(QString("%1 %2 is available — you have %3.").arg(product.displayName, version, product.version)); + primaryInstalls = state.automaticInstall; + if (state.automaticInstall) + primaryButton.setText("&Install Update…"); + else + primaryButton.setText(state.release->installer ? "Do&wnload Installer" : "Open Do&wnload Page"); + EnablePrimary(true); + primaryButton.setToolTip(state.automaticInstall ? "Download, verify and install this version, then restart" : "This installation cannot update itself; download the installer instead"); + ShowButtons(true, true, true, false, true); + } + + void UpdateBanner::RenderDownload(const UpdateState& state, const QString& version) + { + const auto total = state.total > 0 ? state.total : 0; + progress.setRange(0, total > 0 ? 1000 : 0); + progress.setValue(total > 0 ? static_cast(state.received * 1000 / total) : 0); + message.setText(total > 0 ? QString("Downloading %1 — %2 of %3 MB").arg(version, Megabytes(state.received), Megabytes(total)) + : QString("Downloading %1 — %2 MB").arg(version, Megabytes(state.received))); + ShowButtons(false, true, false, true, false); + } + + void UpdateBanner::RenderReady(const UpdateState& state, const QString& version) + { + primaryInstalls = true; + primaryButton.setText("&Install and Restart"); + EnablePrimary(!state.blocked); + primaryButton.setToolTip(state.blocked ? QString("%1 first — installing closes %2").arg(product.blockedAction, product.shortName) : QString{}); + message.setText(state.blocked ? QString("%1 is downloaded and verified. %2 to install it.").arg(version, product.blockedAction) + : QString("%1 is downloaded and verified.").arg(version)); + ShowButtons(true, true, false, true, false); + } + + void UpdateBanner::RenderFailure(const UpdateState& state, const QString& version) + { + message.setText(QString("Could not update to %1: %2.").arg(version, state.failure)); + primaryInstalls = state.automaticInstall; + primaryButton.setText(state.automaticInstall ? "&Try Again" : "Open Do&wnload Page"); + EnablePrimary(true); + primaryButton.setToolTip({}); + if (!state.automaticInstall) + downloadUrl = state.release->pageUrl; + ShowButtons(true, true, false, false, true); + } + + void UpdateBanner::EnablePrimary(bool enabled) + { + primaryButton.setEnabled(enabled); + StyleButton(primaryButton, enabled ? theme::ButtonRole::Primary : theme::ButtonRole::Default); + } + + void UpdateBanner::ShowButtons(bool primary, bool notes, bool skip, bool cancel, bool dismiss) + { + primaryButton.setVisible(primary); + notesButton.setVisible(notes); + skipButton.setVisible(skip); + cancelButton.setVisible(cancel); + dismissButton.setVisible(dismiss); + } + + void UpdateBanner::OnPrimary() + { + if (primaryInstalls) + emit InstallRequested(); + else + QDesktopServices::openUrl(downloadUrl); + } +} diff --git a/ui/backend/qt/update/widgets/UpdateBanner.hpp b/ui/backend/qt/update/widgets/UpdateBanner.hpp new file mode 100644 index 0000000..204f7e4 --- /dev/null +++ b/ui/backend/qt/update/widgets/UpdateBanner.hpp @@ -0,0 +1,56 @@ +#pragma once + +#include "ui/backend/qt/update/UpdateSession.hpp" +#include "ui/backend/qt/update/widgets/UpdateProduct.hpp" +#include +#include +#include +#include +#include +#include + +namespace ui::backend::qt::update +{ + class UpdateBanner + : public QFrame + { + Q_OBJECT + + public: + explicit UpdateBanner(const UpdateProduct& product, QWidget* parent = nullptr); + + void Render(const UpdateState& state); + + QString Message() const; + QString PrimaryText() const; + bool PrimaryEnabled() const; + + signals: + void InstallRequested(); + void CancelRequested(); + void SkipRequested(); + void DismissRequested(); + + private: + void RenderOffer(const UpdateState& state, const QString& version); + void RenderDownload(const UpdateState& state, const QString& version); + void RenderReady(const UpdateState& state, const QString& version); + void RenderFailure(const UpdateState& state, const QString& version); + void EnablePrimary(bool enabled); + void ShowButtons(bool primary, bool notes, bool skip, bool cancel, bool dismiss); + void OnPrimary(); + + UpdateProduct product; + QHBoxLayout layout{ this }; + QLabel message; + QProgressBar progress; + QPushButton primaryButton; + QPushButton notesButton{ "&Release Notes" }; + QPushButton skipButton{ "S&kip This Version" }; + QPushButton cancelButton{ "Cancel" }; + QPushButton dismissButton{ "Later" }; + QUrl notesUrl; + QUrl downloadUrl; + bool primaryInstalls{ false }; + }; +} diff --git a/ui/backend/qt/update/widgets/UpdateProduct.hpp b/ui/backend/qt/update/widgets/UpdateProduct.hpp new file mode 100644 index 0000000..cc54503 --- /dev/null +++ b/ui/backend/qt/update/widgets/UpdateProduct.hpp @@ -0,0 +1,20 @@ +#pragma once + +#include +#include +#include + +namespace ui::backend::qt::update +{ + struct UpdateProduct + { + QString displayName; + QString shortName; + QString version; + QUrl feedUrl; + QUrl releasesUrl; + QUrl newIssueUrl; + QByteArray userAgent; + QString blockedAction; + }; +} diff --git a/ui/backend/qt/update/widgets/test/CMakeLists.txt b/ui/backend/qt/update/widgets/test/CMakeLists.txt new file mode 100644 index 0000000..97e3c5f --- /dev/null +++ b/ui/backend/qt/update/widgets/test/CMakeLists.txt @@ -0,0 +1,13 @@ +ui_add_test(ui.backend.qt.update_widgets_test CUSTOM_MAIN + SOURCES + DialogAnswerer.hpp + Main.cpp + TestUpdateAssistant.cpp + TestUpdateBanner.cpp + LINK + ui.backend.qt.update_widgets +) + +if (TARGET ui.backend.qt.update_widgets_test) + set_target_properties(ui.backend.qt.update_widgets_test PROPERTIES AUTOMOC ON) +endif() diff --git a/ui/backend/qt/update/widgets/test/DialogAnswerer.hpp b/ui/backend/qt/update/widgets/test/DialogAnswerer.hpp new file mode 100644 index 0000000..d44837d --- /dev/null +++ b/ui/backend/qt/update/widgets/test/DialogAnswerer.hpp @@ -0,0 +1,57 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ui::backend::qt::update::test +{ + inline void AnswerNextDialog(bool accept) + { + auto* timer = new QTimer; + QObject::connect(timer, &QTimer::timeout, timer, [timer, accept]() + { + auto* box = qobject_cast(QApplication::activeModalWidget()); + if (box == nullptr) + return; + + if (accept) + box->defaultButton()->click(); + else + box->reject(); + timer->deleteLater(); + }); + timer->start(10); + } + + class UrlCatcher + : public QObject + { + Q_OBJECT + + public: + UrlCatcher() + { + QDesktopServices::setUrlHandler("https", this, "Open"); + } + + ~UrlCatcher() override + { + QDesktopServices::unsetUrlHandler("https"); + } + + std::vector urls; + + public slots: + + void Open(const QUrl& url) + { + urls.push_back(url); + } + }; +} diff --git a/ui/backend/qt/update/widgets/test/Main.cpp b/ui/backend/qt/update/widgets/test/Main.cpp new file mode 100644 index 0000000..c9800da --- /dev/null +++ b/ui/backend/qt/update/widgets/test/Main.cpp @@ -0,0 +1,17 @@ +#include +#include +#include + +int main(int argc, char** argv) +{ + if (qEnvironmentVariableIsEmpty("QT_QPA_PLATFORM")) + qputenv("QT_QPA_PLATFORM", "offscreen"); + + QStandardPaths::setTestModeEnabled(true); + QApplication application{ argc, argv }; + QApplication::setOrganizationName("ui-cpp-test"); + QApplication::setApplicationName("update-widgets-test"); + ::testing::InitGoogleMock(&argc, argv); + + return RUN_ALL_TESTS(); +} diff --git a/ui/backend/qt/update/widgets/test/TestUpdateAssistant.cpp b/ui/backend/qt/update/widgets/test/TestUpdateAssistant.cpp new file mode 100644 index 0000000..e57b0f6 --- /dev/null +++ b/ui/backend/qt/update/widgets/test/TestUpdateAssistant.cpp @@ -0,0 +1,244 @@ +#include "ui/backend/qt/update/widgets/UpdateAssistant.hpp" +#include "ui/backend/qt/update/widgets/test/DialogAnswerer.hpp" +#include "gtest/gtest.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace ui::backend::qt::update; + + class TestUpdateAssistant + : public testing::Test + { + public: + TestUpdateAssistant() + { + QSettings{}.clear(); + QObject::connect(&assistant, &UpdateAssistant::Report, [this](IssueSeverity, const QString& message) + { + reports.push_back(message); + }); + } + + ~TestUpdateAssistant() override + { + QSettings{}.clear(); + } + + QUrl Feed(const QString& tag) + { + return WriteFeed(QString(R"({ "tag_name": "%1", "html_url": "https://github.com/example/project/releases/tag/%1", "assets": [] })").arg(tag).toUtf8()); + } + + QUrl WriteFeed(const QByteArray& content) + { + const auto path = QDir{ temporary.path() }.filePath("latest.json"); + QFile file{ path }; + EXPECT_TRUE(file.open(QIODevice::WriteOnly)); + file.write(content); + return QUrl::fromLocalFile(path); + } + + void WaitForReport(std::size_t count) + { + QElapsedTimer timer; + timer.start(); + while (reports.size() < count && timer.elapsed() < 5000) + QCoreApplication::processEvents(QEventLoop::AllEvents, 20); + } + + QTemporaryDir temporary; + QWidget window; + UpdateProduct product{ "Example Tool", "Example", "1.1.0", Feed("v1.2.0"), QUrl{ "https://github.com/example/project/releases" }, {}, "example-tool/1.1.0", "Disconnect the device" }; + UpdateAssistant assistant{ product, window }; + std::vector reports; + }; +} + +TEST_F(TestUpdateAssistant, an_automatic_check_offers_a_newer_release_in_the_banner) +{ + assistant.Check(false); + WaitForReport(1); + + ASSERT_EQ(1u, reports.size()); + EXPECT_EQ("Update available: v1.2.0", reports.front()); + EXPECT_EQ(UpdatePhase::available, assistant.State().phase); + EXPECT_FALSE(assistant.Banner().isHidden()); +} + +TEST_F(TestUpdateAssistant, an_automatic_check_does_not_offer_a_skipped_version_again) +{ + QSettings{}.setValue("updates/skippedVersion", "v1.2.0"); + + assistant.Check(false); + WaitForReport(1); + + ASSERT_EQ(1u, reports.size()); + EXPECT_EQ("Update available: v1.2.0 (skipped)", reports.front()); + EXPECT_EQ(UpdatePhase::idle, assistant.State().phase); +} + +TEST_F(TestUpdateAssistant, skipping_remembers_the_version_and_hides_the_banner) +{ + assistant.Check(false); + WaitForReport(1); + + emit assistant.Banner().SkipRequested(); + + EXPECT_EQ("v1.2.0", QSettings{}.value("updates/skippedVersion").toString()); + EXPECT_EQ(UpdatePhase::idle, assistant.State().phase); + EXPECT_TRUE(assistant.Banner().isHidden()); +} + +TEST_F(TestUpdateAssistant, automatic_checks_are_on_until_turned_off) +{ + EXPECT_TRUE(assistant.Automatic()); + + assistant.SetAutomatic(false); + + EXPECT_FALSE(assistant.Automatic()); +} + +TEST_F(TestUpdateAssistant, blocking_holds_the_session) +{ + assistant.SetBlocked(true); + + EXPECT_TRUE(assistant.State().blocked); +} + +TEST_F(TestUpdateAssistant, an_automatic_check_that_finds_no_newer_release_only_reports_it) +{ + Feed("v1.1.0"); + + assistant.Check(false); + WaitForReport(1); + + ASSERT_EQ(1u, reports.size()); + EXPECT_EQ("Up to date (latest release v1.1.0)", reports.front()); + EXPECT_TRUE(assistant.Banner().isHidden()); +} + +TEST_F(TestUpdateAssistant, an_automatic_check_that_fails_only_reports_it) +{ + QFile::remove(QDir{ temporary.path() }.filePath("latest.json")); + + assistant.Check(false); + WaitForReport(1); + + ASSERT_EQ(1u, reports.size()); + EXPECT_TRUE(reports.front().startsWith("Update check failed: ")); +} + +TEST_F(TestUpdateAssistant, a_requested_check_says_so_and_answers_with_a_dialog) +{ + Feed("v1.1.0"); + int checking{ 0 }; + QObject::connect(&assistant, &UpdateAssistant::Checking, [&checking]() + { + ++checking; + }); + + ui::backend::qt::update::test::AnswerNextDialog(true); + assistant.Check(true); + WaitForReport(1); + + EXPECT_EQ(1, checking); + ASSERT_EQ(1u, reports.size()); + EXPECT_EQ("Up to date (latest release v1.1.0)", reports.front()); +} + +TEST_F(TestUpdateAssistant, a_requested_check_that_fails_answers_with_a_dialog) +{ + QFile::remove(QDir{ temporary.path() }.filePath("latest.json")); + + ui::backend::qt::update::test::AnswerNextDialog(true); + assistant.Check(true); + WaitForReport(1); + + ASSERT_EQ(1u, reports.size()); + EXPECT_TRUE(reports.front().startsWith("Update check failed: ")); +} + +TEST_F(TestUpdateAssistant, a_requested_check_offers_even_a_skipped_version) +{ + QSettings{}.setValue("updates/skippedVersion", "v1.2.0"); + + assistant.Check(true); + WaitForReport(1); + + EXPECT_EQ(UpdatePhase::available, assistant.State().phase); +} + +TEST_F(TestUpdateAssistant, automatic_checks_start_only_when_turned_on) +{ + assistant.SetAutomatic(false); + assistant.StartAutomaticChecks(); + QCoreApplication::processEvents(QEventLoop::AllEvents, 100); + + EXPECT_TRUE(reports.empty()); + + assistant.SetAutomatic(true); + assistant.StartAutomaticChecks(); + WaitForReport(1); + + EXPECT_EQ(1u, reports.size()); +} + +TEST_F(TestUpdateAssistant, declining_the_install_confirmation_leaves_the_offer) +{ + assistant.Check(false); + WaitForReport(1); + + ui::backend::qt::update::test::AnswerNextDialog(false); + emit assistant.Banner().InstallRequested(); + + EXPECT_EQ(UpdatePhase::available, assistant.State().phase); +} + +TEST_F(TestUpdateAssistant, downloads_go_to_the_cache_and_the_default_command_follows_the_platform) +{ + EXPECT_TRUE(UpdateAssistant::DownloadDirectory().endsWith("/updates")); + EXPECT_EQ(DefaultUpdateCommand(CurrentInstallerPlatform(), "/tmp/example.deb", QCoreApplication::applicationFilePath(), QCoreApplication::applicationPid()).has_value(), + UpdateAssistant::DefaultCommand("/tmp/example.deb").has_value()); +} + +TEST_F(TestUpdateAssistant, each_update_phase_reports_what_happened) +{ + UpdateState state; + EXPECT_FALSE(PhaseReport(state).has_value()); + + state.release = ReleaseInfo{ ReleaseVersion{ 1, 2, 0 }, "v1.2.0", QUrl{ "https://github.com/example/project/releases/tag/v1.2.0" }, + InstallerAsset{ "example.deb", QUrl{ "https://github.com/example/project/releases/download/v1.2.0/example.deb" }, 1, {} }, {} }; + state.phase = UpdatePhase::downloading; + EXPECT_EQ("Downloading update v1.2.0 from https://github.com/example/project/releases/download/v1.2.0/example.deb", PhaseReport(state)->message); + state.phase = UpdatePhase::ready; + EXPECT_EQ("Update v1.2.0 downloaded and verified", PhaseReport(state)->message); + state.phase = UpdatePhase::installing; + EXPECT_EQ("Installing update v1.2.0", PhaseReport(state)->message); + state.phase = UpdatePhase::failed; + state.failure = "checksum mismatch"; + EXPECT_EQ(IssueSeverity::warning, PhaseReport(state)->severity); + EXPECT_EQ("Update to v1.2.0 failed: checksum mismatch", PhaseReport(state)->message); + state.phase = UpdatePhase::available; + EXPECT_FALSE(PhaseReport(state).has_value()); +} + +TEST_F(TestUpdateAssistant, an_issue_report_opens_the_prefilled_new_issue_page) +{ + ui::backend::qt::update::test::UrlCatcher browser; + product.newIssueUrl = QUrl{ "https://github.com/example/project/issues/new" }; + IssueLog log{ IssueLog::Config{ temporary.path(), "example" } }; + log.Write(IssueSeverity::info, "Session started"); + + EXPECT_TRUE(OpenIssueReport(product, log, &window)); + + ASSERT_EQ(1u, browser.urls.size()); + EXPECT_EQ("/example/project/issues/new", browser.urls.front().path()); +} diff --git a/ui/backend/qt/update/widgets/test/TestUpdateBanner.cpp b/ui/backend/qt/update/widgets/test/TestUpdateBanner.cpp new file mode 100644 index 0000000..a8ae2a4 --- /dev/null +++ b/ui/backend/qt/update/widgets/test/TestUpdateBanner.cpp @@ -0,0 +1,146 @@ +#include "ui/backend/qt/update/widgets/UpdateBanner.hpp" +#include "ui/backend/qt/update/widgets/test/DialogAnswerer.hpp" +#include "gtest/gtest.h" +#include + +namespace +{ + using namespace ui::backend::qt::update; + + class TestUpdateBanner + : public testing::Test + { + public: + static UpdateState State(UpdatePhase phase) + { + UpdateState state; + state.phase = phase; + state.release = ReleaseInfo{ ReleaseVersion{ 1, 2, 0 }, "v1.2.0", QUrl{ "https://github.com/example/project/releases/tag/v1.2.0" }, + InstallerAsset{ "example-tool-v1.2.0-linux-x86_64.deb", QUrl{ "https://github.com/example/project/releases/download/v1.2.0/example-tool-v1.2.0-linux-x86_64.deb" }, 2048, QByteArray(32, 'a') }, {} }; + state.automaticInstall = true; + return state; + } + + const UpdateProduct product{ "Example Tool", "Example", "1.1.0", {}, {}, {}, "example-tool/1.1.0", "Disconnect the device" }; + UpdateBanner banner{ product }; + }; +} + +TEST_F(TestUpdateBanner, is_hidden_while_no_update_is_offered) +{ + banner.Render(UpdateState{}); + + EXPECT_TRUE(banner.isHidden()); +} + +TEST_F(TestUpdateBanner, offers_the_new_version_against_the_running_one) +{ + banner.Render(State(UpdatePhase::available)); + + EXPECT_FALSE(banner.isHidden()); + EXPECT_EQ("Example Tool 1.2.0 is available — you have 1.1.0.", banner.Message()); + EXPECT_EQ("&Install Update…", banner.PrimaryText()); +} + +TEST_F(TestUpdateBanner, a_portable_installation_offers_the_installer_download_instead) +{ + auto state = State(UpdatePhase::available); + state.automaticInstall = false; + banner.Render(state); + + EXPECT_EQ("Do&wnload Installer", banner.PrimaryText()); +} + +TEST_F(TestUpdateBanner, a_blocked_install_names_what_the_operator_must_do_first) +{ + auto state = State(UpdatePhase::ready); + state.blocked = true; + banner.Render(state); + + EXPECT_EQ("1.2.0 is downloaded and verified. Disconnect the device to install it.", banner.Message()); + EXPECT_FALSE(banner.PrimaryEnabled()); + + state.blocked = false; + banner.Render(state); + + EXPECT_EQ("1.2.0 is downloaded and verified.", banner.Message()); + EXPECT_TRUE(banner.PrimaryEnabled()); +} + +TEST_F(TestUpdateBanner, installing_names_the_product_that_restarts) +{ + banner.Render(State(UpdatePhase::installing)); + + EXPECT_EQ("Installing Example Tool 1.2.0 — Example restarts when it is done.", banner.Message()); + EXPECT_TRUE(banner.PrimaryText().isEmpty()); +} + +TEST_F(TestUpdateBanner, a_failure_says_why_and_offers_another_try) +{ + auto state = State(UpdatePhase::failed); + state.failure = "the download did not match its checksum"; + banner.Render(state); + + EXPECT_EQ("Could not update to 1.2.0: the download did not match its checksum.", banner.Message()); + EXPECT_EQ("&Try Again", banner.PrimaryText()); +} + +TEST_F(TestUpdateBanner, a_download_shows_its_progress_in_megabytes) +{ + auto state = State(UpdatePhase::downloading); + state.received = 1024 * 1024; + state.total = 4 * 1024 * 1024; + banner.Render(state); + + EXPECT_EQ("Downloading 1.2.0 — 1.0 of 4.0 MB", banner.Message()); + + state.total = 0; + banner.Render(state); + + EXPECT_EQ("Downloading 1.2.0 — 1.0 MB", banner.Message()); +} + +TEST_F(TestUpdateBanner, a_failure_without_automatic_install_offers_the_download_page) +{ + auto state = State(UpdatePhase::failed); + state.automaticInstall = false; + state.failure = "no installer for this platform"; + banner.Render(state); + + EXPECT_EQ("Open Do&wnload Page", banner.PrimaryText()); +} + +TEST_F(TestUpdateBanner, the_primary_button_asks_to_install_or_opens_the_download) +{ + ui::backend::qt::update::test::UrlCatcher browser; + int installs{ 0 }; + QObject::connect(&banner, &UpdateBanner::InstallRequested, [&installs]() + { + ++installs; + }); + + banner.Render(State(UpdatePhase::available)); + banner.findChildren().front()->click(); + + auto portable = State(UpdatePhase::available); + portable.automaticInstall = false; + banner.Render(portable); + banner.findChildren().front()->click(); + + EXPECT_EQ(1, installs); + ASSERT_EQ(1u, browser.urls.size()); + EXPECT_TRUE(browser.urls.front().path().endsWith("example-tool-v1.2.0-linux-x86_64.deb")); +} + +TEST_F(TestUpdateBanner, release_notes_open_the_release_page) +{ + ui::backend::qt::update::test::UrlCatcher browser; + banner.Render(State(UpdatePhase::available)); + + for (auto* button : banner.findChildren()) + if (button->text() == "&Release Notes") + button->click(); + + ASSERT_EQ(1u, browser.urls.size()); + EXPECT_EQ("/example/project/releases/tag/v1.2.0", browser.urls.front().path()); +}