OSDN Git Service

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