OSDN Git Service

Bump version.
[lamexp/LameXP.git] / src / Dialog_Update.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2020 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU GENERAL PUBLIC LICENSE as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version; always including the non-optional
9 // LAMEXP GNU GENERAL PUBLIC LICENSE ADDENDUM. See "License.txt" file!
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 //
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
22
23 #include "Dialog_Update.h"
24
25 //UIC includes
26 #include "UIC_UpdateDialog.h"
27
28 //LameXP includes
29 #include "Global.h"
30 #include "Dialog_LogView.h"
31 #include "Model_Settings.h"
32
33 //MUtils
34 #include <MUtils/UpdateChecker.h>
35 #include <MUtils/Version.h>
36 #include <MUtils/Exception.h>
37 #include <MUtils/Sound.h>
38 #include <MUtils/GUI.h>
39 #include <MUtils/OSSupport.h>
40 #include <MUtils/Taskbar7.h>
41
42 //Qt includes
43 #include <QClipboard>
44 #include <QFileDialog>
45 #include <QTimer>
46 #include <QProcess>
47 #include <QDesktopServices>
48 #include <QUrl>
49 #include <QCloseEvent>
50 #include <QMovie>
51 #include <QMessageBox>
52
53 ///////////////////////////////////////////////////////////////////////////////
54
55 #define SHOW_HINT(TEXT, ICON) do \
56 { \
57         ui->hintLabel->setText((TEXT)); \
58         ui->hintIcon->setPixmap(QIcon((ICON)).pixmap(16,16)); \
59         ui->hintIcon->show(); \
60         ui->hintLabel->show(); \
61 } \
62 while(0)
63
64 #define UPDATE_TASKBAR(STATE, ICON) do \
65 { \
66         m_taskbar->setTaskbarState((STATE)); \
67         m_taskbar->setOverlayIcon(&QIcon((ICON))); \
68 } \
69 while(0)
70
71 ///////////////////////////////////////////////////////////////////////////////
72
73 UpdateDialog::UpdateDialog(const SettingsModel *const settings, QWidget *parent)
74 :
75         QDialog(parent),
76         ui(new Ui::UpdateDialog),
77         m_taskbar(new MUtils::Taskbar7(parent)),
78         m_settings(settings),
79         m_logFile(new QStringList()),
80         m_betaUpdates(settings ? (settings->autoUpdateCheckBeta() || lamexp_version_demo()) : lamexp_version_demo()),
81         m_success(false),
82         m_haveNewVersion(false),
83         m_firstShow(true),
84         m_updateReadyToInstall(false),
85         m_updaterProcess(NULL),
86         m_binaryUpdater(lamexp_tools_lookup("wupdate.exe")),
87         m_binaryCurl(lamexp_tools_lookup("curl.exe")),
88         m_binaryGnuPG(lamexp_tools_lookup("gpgv.exe")),
89         m_binaryKeys(lamexp_tools_lookup("keyring.gpg"))
90 {
91         if(m_binaryUpdater.isEmpty() || m_binaryCurl.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryKeys.isEmpty())
92         {
93                 MUTILS_THROW("Tools not initialized correctly!");
94         }
95
96         //Init the dialog, from the .ui file
97         ui->setupUi(this);
98         setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
99
100         //Disable "X" button
101         MUtils::GUI::enable_close_button(this, false);
102
103         //Init animation
104         m_animator.reset(new QMovie(":/images/Loading3.gif"));
105         ui->labelAnimationCenter->setMovie(m_animator.data());
106         m_animator->start();
107
108         //Indicate beta updates
109         if(m_betaUpdates)
110         {
111                 setWindowTitle(windowTitle().append(" [Beta]"));
112         }
113         
114         //Enable button
115         connect(ui->retryButton, SIGNAL(clicked()), this, SLOT(checkForUpdates()));
116         connect(ui->installButton, SIGNAL(clicked()), this, SLOT(applyUpdate()));
117         connect(ui->infoLabel, SIGNAL(linkActivated(QString)), this, SLOT(linkActivated(QString)));
118         connect(ui->logButton, SIGNAL(clicked()), this, SLOT(logButtonClicked()));
119
120         //Enable progress bar
121         connect(ui->progressBar, SIGNAL(valueChanged(int)), this, SLOT(progressBarValueChanged(int)));
122 }
123
124 UpdateDialog::~UpdateDialog(void)
125 {
126         if(m_animator)
127         {
128                 m_animator->stop();
129         }
130
131         if(!m_thread.isNull())
132         {
133                 if(!m_thread->wait(1000))
134                 {
135                         m_thread->terminate();
136                         m_thread->wait();
137                 }
138         }
139
140         m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE);
141         m_taskbar->setOverlayIcon(NULL);
142
143         delete ui;
144 }
145
146 void UpdateDialog::showEvent(QShowEvent *event)
147 {
148         QDialog::showEvent(event);
149         
150         if(m_firstShow)
151         {
152                 if(m_thread.isNull())
153                 {
154                         m_thread.reset(new MUtils::UpdateChecker(m_binaryCurl, m_binaryGnuPG, m_binaryKeys, QLatin1String("LameXP"), lamexp_version_build(), m_betaUpdates));
155                         connect(m_thread.data(), SIGNAL(statusChanged(int)), this, SLOT(threadStatusChanged(int)));
156                         connect(m_thread.data(), SIGNAL(progressChanged(int)), this, SLOT(threadProgressChanged(int)));
157                         connect(m_thread.data(), SIGNAL(messageLogged(QString)), this, SLOT(threadMessageLogged(QString)));
158                         connect(m_thread.data(), SIGNAL(finished()), this, SLOT(threadFinished()));
159                         connect(m_thread.data(), SIGNAL(terminated()), this, SLOT(threadFinished()));
160                 }
161
162                 threadStatusChanged(m_thread->getUpdateStatus());
163                 ui->labelVersionInstalled->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(lamexp_version_build()), MUtils::Version::app_build_date().toString(Qt::ISODate)));
164                 ui->labelVersionLatest->setText(QString("(%1)").arg(tr("Unknown")));
165
166                 ui->installButton->setEnabled(false);
167                 ui->closeButton->setEnabled(false);
168                 ui->retryButton->setEnabled(false);
169                 ui->logButton->setEnabled(false);
170                 ui->retryButton->hide();
171                 ui->logButton->hide();
172                 ui->infoLabel->hide();
173                 ui->hintLabel->hide();
174                 ui->hintIcon->hide();
175                 ui->frameAnimation->hide();
176                 ui->cancelLabel->hide();
177         
178                 ui->progressBar->setMaximum(m_thread->getMaximumProgress());
179                 ui->progressBar->setValue(0);
180
181                 m_updaterProcess = NULL;
182
183                 QTimer::singleShot(0, this, SLOT(updateInit()));
184                 m_firstShow = false;
185         }
186 }
187
188 void UpdateDialog::closeEvent(QCloseEvent *event)
189 {
190         if(!ui->closeButton->isEnabled())
191         {
192                 event->ignore();
193         }
194         else
195         {
196                 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE);
197                 m_taskbar->setOverlayIcon(NULL);
198         }
199 }
200
201 void UpdateDialog::keyPressEvent(QKeyEvent *e)
202 {
203         if (e->key() == Qt::Key_Escape)
204         {
205                 if (!m_thread.isNull() && m_thread->isRunning())
206                 {
207                         ui->cancelLabel->hide();
208                         ui->statusLabel->setText(tr("Stopping update check, please wait..."));
209                         m_thread->cancel();
210                 }
211         }
212         else if(e->key() == Qt::Key_F11)
213         {
214                 if(ui->closeButton->isEnabled()) logButtonClicked();
215         }
216         else if((e->key() == Qt::Key_F12) && e->modifiers().testFlag(Qt::ControlModifier))
217         {
218                 if(ui->closeButton->isEnabled()) testKnownHosts();
219         }
220         else
221         {
222                 QDialog::keyPressEvent(e);
223         }
224 }
225
226 bool UpdateDialog::event(QEvent *e)
227 {
228         if((e->type() == QEvent::ActivationChange) && (m_updaterProcess != NULL))
229         {
230                 MUtils::GUI::bring_to_front(m_updaterProcess);
231         }
232         return QDialog::event(e);
233 }
234
235 void UpdateDialog::updateInit(void)
236 {
237         setMinimumSize(size());
238         setMaximumHeight(height());
239         QTimer::singleShot(0, this, SLOT(checkForUpdates()));
240 }
241
242 void UpdateDialog::checkForUpdates(void)
243 {
244         if(m_thread->isRunning())
245         {
246                 qWarning("Update in progress, cannot check for updates now!");
247         }
248
249         if(!MUtils::OS::user_is_admin())
250         {
251                 qWarning("User is not in the \"admin\" group, cannot update!");
252                 QString message;
253                 message += QString("<nobr>%1</nobr><br>").arg(tr("Sorry, but only users in the \"Administrators\" group can install updates."));
254                 message += QString("<nobr>%1</nobr>").arg(tr("Please start application from an administrator account and try again!"));
255                 if(QMessageBox::critical(this, this->windowTitle(), message, tr("Discard"), tr("Ignore")) != 1)
256                 {
257                         ui->closeButton->setEnabled(true);
258                         close(); return;
259                 }
260         }
261
262         m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL);
263         m_taskbar->setOverlayIcon(&QIcon(":/icons/transmit_blue.png"));
264
265         ui->progressBar->setValue(0);
266         ui->installButton->setEnabled(false);
267         ui->closeButton->setEnabled(false);
268         ui->retryButton->setEnabled(false);
269         ui->logButton->setEnabled(false);
270         if(ui->infoLabel->isVisible()) ui->infoLabel->hide();
271         if(ui->hintLabel->isVisible()) ui->hintLabel->hide();
272         if(ui->hintIcon->isVisible()) ui->hintIcon->hide();
273         ui->cancelLabel->show();
274         ui->frameAnimation->show();
275
276         QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
277         QApplication::setOverrideCursor(Qt::WaitCursor);
278
279         m_logFile->clear();
280         m_thread->start();
281 }
282
283 void UpdateDialog::threadStatusChanged(const int status)
284 {
285         switch(status)
286         {
287         case MUtils::UpdateChecker::UpdateStatus_NotStartedYet:
288                 ui->statusLabel->setText(tr("Initializing, please wait..."));
289                 break;
290         case MUtils::UpdateChecker::UpdateStatus_CheckingConnection:
291                 ui->statusLabel->setText(tr("Testing your internet connection, please wait..."));
292                 break;
293         case MUtils::UpdateChecker::UpdateStatus_FetchingUpdates:
294                 ui->statusLabel->setText(tr("Checking for new updates online, please wait..."));
295                 break;
296         case MUtils::UpdateChecker::UpdateStatus_CompletedUpdateAvailable:
297                 ui->statusLabel->setText(tr("A new version of LameXP is available!"));
298                 SHOW_HINT(tr("We highly recommend all users to install this update as soon as possible."), ":/icons/shield_exclamation.png");
299                 UPDATE_TASKBAR(MUtils::Taskbar7::TASKBAR_STATE_NORMAL, ":/icons/shield_exclamation.png");
300                 break;
301         case MUtils::UpdateChecker::UpdateStatus_CompletedNoUpdates:
302                 ui->statusLabel->setText(tr("No new updates available at this time."));
303                 SHOW_HINT(tr("Your version of LameXP is still up-to-date. Please check for updates regularly!"), ":/icons/shield_green.png");
304                 UPDATE_TASKBAR(MUtils::Taskbar7::TASKBAR_STATE_NORMAL, ":/icons/shield_green.png");
305                 break;
306         case MUtils::UpdateChecker::UpdateStatus_CompletedNewVersionOlder:
307                 ui->statusLabel->setText(tr("Your version appears to be newer than the latest release."));
308                 SHOW_HINT(tr("This usually indicates your are currently using a pre-release version of LameXP."), ":/icons/shield_blue.png");
309                 UPDATE_TASKBAR(MUtils::Taskbar7::TASKBAR_STATE_NORMAL, ":/icons/shield_error.png");
310                 break;
311         case MUtils::UpdateChecker::UpdateStatus_ErrorNoConnection:
312                 ui->statusLabel->setText(tr("It appears that the computer currently is offline!"));
313                 SHOW_HINT(tr("Please make sure your computer is connected to the internet and try again."), ":/icons/network_error.png");
314                 UPDATE_TASKBAR(MUtils::Taskbar7::TASKBAR_STATE_NORMAL, ":/icons/exclamation.png");
315                 break;
316         case MUtils::UpdateChecker::UpdateStatus_ErrorConnectionTestFailed:
317                 ui->statusLabel->setText(tr("Network connectivity test has failed!"));
318                 SHOW_HINT(tr("Please make sure your computer is connected to the internet and try again."), ":/icons/network_error.png");
319                 UPDATE_TASKBAR(MUtils::Taskbar7::TASKBAR_STATE_NORMAL, ":/icons/exclamation.png");
320                 break;
321         case MUtils::UpdateChecker::UpdateStatus_ErrorFetchUpdateInfo:
322                 ui->statusLabel->setText(tr("Failed to fetch update information from server!"));
323                 SHOW_HINT(tr("Sorry, the update server might be busy at this time. Plase try again later."), ":/icons/server_error.png");
324                 UPDATE_TASKBAR(MUtils::Taskbar7::TASKBAR_STATE_NORMAL, ":/icons/exclamation.png");
325                 break;
326         case MUtils::UpdateChecker::UpdateStatus_CancelledByUser:
327                 ui->statusLabel->setText(tr("Update check has been cancelled!"));
328                 SHOW_HINT(tr("The update check has been cancelled by the user. Please try again later."), ":/icons/server_error.png");
329                 UPDATE_TASKBAR(MUtils::Taskbar7::TASKBAR_STATE_NORMAL, ":/icons/exclamation.png");
330                 break;
331         default:
332                 qWarning("Unknown status %d !!!", int(status));
333         }
334 }
335
336 void UpdateDialog::threadProgressChanged(const int progress)
337 {
338         ui->progressBar->setValue(progress);
339 }
340
341 void UpdateDialog::threadMessageLogged(const QString &message)
342 {
343         (*m_logFile) << message;
344 }
345
346 void UpdateDialog::threadFinished(void)
347 {
348         const bool bSuccess = m_thread->getSuccess();
349         
350         ui->closeButton->setEnabled(true);
351         ui->cancelLabel->hide();
352         if(ui->frameAnimation->isVisible()) ui->frameAnimation->hide();
353         ui->progressBar->setValue(ui->progressBar->maximum());
354
355         if(!bSuccess)
356         {
357                 if(m_settings->soundsEnabled()) MUtils::Sound::play_sound("error", true);
358         }
359         else
360         {
361                 const bool bHaveNewVersion = (m_thread->getUpdateStatus() == MUtils::UpdateChecker::UpdateStatus_CompletedUpdateAvailable);
362                 ui->installButton->setEnabled(bHaveNewVersion);
363                 MUtils::Sound::beep(bHaveNewVersion ? MUtils::Sound::BEEP_NFO : MUtils::Sound::BEEP_WRN);
364
365                 if(const MUtils::UpdateCheckerInfo *const updateInfo = m_thread->getUpdateInfo())
366                 {
367                         ui->infoLabel->setText(QString("%1<br><a href=\"%2\">%2</a>").arg(tr("More information available at:"), updateInfo->getDownloadSite()));
368                         ui->labelVersionLatest->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(updateInfo->getBuildNo()), updateInfo->getBuildDate().toString(Qt::ISODate)));
369                         ui->infoLabel->show();
370                 }
371
372                 m_success = true;
373                 m_haveNewVersion = bHaveNewVersion;
374         }
375
376         ui->retryButton->setVisible(!bSuccess);
377         ui->logButton->setVisible(!bSuccess);
378         ui->retryButton->setEnabled(!bSuccess);
379         ui->logButton->setEnabled(!bSuccess);
380
381         QApplication::restoreOverrideCursor();
382 }
383
384 void UpdateDialog::linkActivated(const QString &link)
385 {
386         QDesktopServices::openUrl(QUrl(link));
387 }
388
389 void UpdateDialog::applyUpdate(void)
390 {
391         ui->installButton->setEnabled(false);
392         ui->closeButton->setEnabled(false);
393         ui->retryButton->setEnabled(false);
394
395         if(const MUtils::UpdateCheckerInfo *updateInfo = m_thread->getUpdateInfo())
396         {
397                 ui->statusLabel->setText(tr("Update is being downloaded, please be patient..."));
398                 ui->frameAnimation->show();
399                 if(ui->hintLabel->isVisible()) ui->hintLabel->hide();
400                 if(ui->hintIcon->isVisible()) ui->hintIcon->hide();
401                 int oldMax = ui->progressBar->maximum();
402                 int oldMin = ui->progressBar->minimum();
403                 ui->progressBar->setRange(0, 0);
404                 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
405                 
406                 QProcess process;
407                 QStringList args;
408                 QEventLoop loop;
409
410                 MUtils::init_process(process, QFileInfo(m_binaryUpdater).absolutePath(), false);
411
412                 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
413                 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
414
415                 args << QString("/Location=%1").arg(updateInfo->getDownloadAddress());
416                 args << QString("/Filename=%1").arg(updateInfo->getDownloadFilename());
417                 args << QString("/TicketID=%1").arg(updateInfo->getDownloadFilecode());
418                 args << QString("/CheckSum=%1").arg(updateInfo->getDownloadChecksum());
419                 args << QString("/ToFolder=%1").arg(QDir::toNativeSeparators(QDir(QApplication::applicationDirPath()).canonicalPath()));
420                 args << QString("/ToExFile=%1.exe").arg(QFileInfo(QFileInfo(QApplication::applicationFilePath()).canonicalFilePath()).completeBaseName());
421                 args << QString("/AppTitle=LameXP (Build #%1)").arg(QString::number(updateInfo->getBuildNo()));
422
423                 QApplication::setOverrideCursor(Qt::WaitCursor);
424                 UPDATE_TASKBAR(MUtils::Taskbar7::TASKBAR_STATE_INTERMEDIATE, ":/icons/transmit_blue.png");
425
426                 process.start(m_binaryUpdater, args);
427                 bool updateStarted = process.waitForStarted();
428                 if(updateStarted)
429                 {
430                         m_updaterProcess = MUtils::OS::process_id(&process);
431                         loop.exec(QEventLoop::ExcludeUserInputEvents);
432                 }
433
434                 m_updaterProcess = NULL;
435                 QApplication::restoreOverrideCursor();
436
437                 ui->hintLabel->show();
438                 ui->hintIcon->show();
439                 ui->progressBar->setRange(oldMin, oldMax);
440                 ui->progressBar->setValue(oldMax);
441                 ui->frameAnimation->hide();
442
443                 if(updateStarted && (process.exitCode() == 0))
444                 {
445                         ui->statusLabel->setText(tr("Update ready to install. Applicaion will quit..."));
446                         m_updateReadyToInstall = true;
447                         m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE);
448                         m_taskbar->setOverlayIcon(NULL);
449                         accept();
450                 }
451                 else
452                 {
453                         ui->statusLabel->setText(tr("Update failed. Please try again or download manually!"));
454                         m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR);
455                         m_taskbar->setOverlayIcon(&QIcon(":/icons/exclamation.png"));
456                         m_taskbar->setTaskbarProgress(100, 100);
457                 }
458         }
459
460         ui->installButton->setEnabled(true);
461         ui->closeButton->setEnabled(true);
462 }
463
464 void UpdateDialog::logButtonClicked(void)
465 {
466         LogViewDialog *logView = new LogViewDialog(this);
467         logView->exec(*m_logFile);
468         MUTILS_DELETE(logView);
469 }
470
471 void UpdateDialog::progressBarValueChanged(int value)
472 {
473         m_taskbar->setTaskbarProgress(value, ui->progressBar->maximum());
474 }
475
476 void UpdateDialog::testKnownHosts(void)
477 {
478         ui->statusLabel->setText("Testing all known hosts, this may take a few minutes...");
479         
480         if(MUtils::UpdateChecker *testThread = new MUtils::UpdateChecker(m_binaryCurl, m_binaryGnuPG, m_binaryKeys, QLatin1String("LameXP"), lamexp_version_build(), m_betaUpdates, true))
481         {
482                 QEventLoop loop;
483                 m_logFile->clear();
484
485                 connect(testThread, SIGNAL(messageLogged(QString)), this, SLOT(threadMessageLogged(QString)));
486                 connect(testThread, SIGNAL(finished()), &loop, SLOT(quit()));
487                 connect(testThread, SIGNAL(terminated()), &loop, SLOT(quit()));
488
489                 testThread->start();
490
491                 ui->progressBar->setMaximum(0);
492                 ui->progressBar->setMinimum(0);
493
494                 bool status[4];
495                 status[0] = ui->closeButton  ->isEnabled(); ui->closeButton  ->setEnabled(false);
496                 status[1] = ui->installButton->isEnabled(); ui->installButton->setEnabled(false);
497                 status[2] = ui->retryButton  ->isEnabled(); ui->retryButton  ->setEnabled(false);
498                 status[3] = ui->logButton    ->isEnabled(); ui->logButton    ->setEnabled(false);
499
500                 while(testThread->isRunning())
501                 {
502                         QTimer::singleShot(8000, &loop, SLOT(quit()));
503                         loop.exec(QEventLoop::ExcludeUserInputEvents);
504                 }
505
506                 ui->progressBar->setMaximum(m_thread.isNull() ? 100 : m_thread->getMaximumProgress());
507                 ui->progressBar->setValue(ui->progressBar->maximum());
508
509                 ui->closeButton  ->setEnabled(status[0]);
510                 ui->installButton->setEnabled(status[1]);
511                 ui->retryButton  ->setEnabled(status[2]);
512                 ui->logButton    ->setEnabled(status[3]);
513
514                 MUTILS_DELETE(testThread);
515                 logButtonClicked();
516         }
517
518         ui->statusLabel->setText("Test completed.");
519         MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
520 }