Added an option to hibernate the computer ("suspend to disk") instead of shutting...
[LameXP.git] / src / Dialog_Update.cpp
blob09f979a7dadf70f9f528dda2ca0bd81cf14eecbb
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 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.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "Dialog_Update.h"
24 #include "Global.h"
25 #include "Resource.h"
26 #include "Dialog_LogView.h"
27 #include "Model_Settings.h"
28 #include "WinSevenTaskbar.h"
30 #include <QClipboard>
31 #include <QFileDialog>
32 #include <QTimer>
33 #include <QProcess>
34 #include <QDate>
35 #include <QRegExp>
36 #include <QDesktopServices>
37 #include <QUrl>
38 #include <QCloseEvent>
39 #include <QMovie>
40 #include <QtConcurrentRun>
42 #include <time.h>
43 #include <MMSystem.h>
44 #include <WinInet.h>
46 ///////////////////////////////////////////////////////////////////////////////
48 static const char *header_id = "!Update";
49 static const char *section_id = "LameXP";
51 static const char *mirror_url_postfix[] =
53 "update.ver",
54 "update_beta.ver",
55 NULL
58 static const char *update_mirrors_prim[] =
60 "http://mulder.brhack.net/",
61 "http://mulder.bplaced.net/",
62 "http://lamexp.sourceforge.net/",
63 "http://free.pages.at/borschdfresser/",
64 NULL
67 static const char *update_mirrors_back[] =
69 "http://mplayer.savedonthe.net/",
70 "http://www.tricksoft.de/",
71 "http://mulder.dummwiedeutsch.de/",
72 "http://mplayer.somestuff.org/",
73 NULL
76 static const char *known_hosts[] =
78 "http://www.amazon.com/",
79 "http://www.aol.com/",
80 "http://www.apache.org/",
81 "http://www.avidemux.org/",
82 "http://www.bbc.co.uk/",
83 "http://www.bing.com/",
84 "http://www.ebay.com/",
85 "http://www.equation.com/",
86 "http://www.ffmpeg.org/",
87 "http://www.gitorious.org/",
88 "http://www.gnome.org/",
89 "http://www.gnu.org/",
90 "http://code.google.com/",
91 "http://haali.su/mkv/",
92 "http://www.heise.de/",
93 "http://www.iana.org/",
94 "http://www.imgburn.com/",
95 "http://www.kernel.org/",
96 "http://www.libav.org/",
97 "http://www.mozilla.org/",
98 "http://mplayerhq.hu/",
99 "http://www.msn.com/?st=1",
100 "http://oss.netfarm.it/",
101 "http://www.opera.com/",
102 "http://www.quakelive.com/",
103 "http://www.seamonkey-project.org/",
104 "http://sourceforge.net/",
105 "http://www.spiegel.de/",
106 "http://tdm-gcc.tdragon.net/",
107 "http://www.tdrsmusic.com/",
108 "http://www.videohelp.com/",
109 "http://www.videolan.org/",
110 "http://www.wikipedia.org/",
111 "http://www.yahoo.com/",
112 "http://www.youtube.com/",
113 NULL
116 static const int MIN_CONNSCORE = 3;
117 static const int VERSION_INFO_EXPIRES_MONTHS = 6;
118 static char *USER_AGENT_STR = "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.12) Gecko/20101101 IceCat/3.6.12 (like Firefox/3.6.12)";
120 static BOOL getInternetConnectedState(void)
122 DWORD lpdwFlags = NULL;
123 BOOL result = InternetGetConnectedState(&lpdwFlags, NULL);
124 return result;
127 ///////////////////////////////////////////////////////////////////////////////
129 class UpdateInfo
131 public:
132 UpdateInfo(void) { resetInfo(); }
134 void resetInfo(void)
136 m_buildNo = 0;
137 m_buildDate.setDate(1900, 1, 1);
138 m_downloadSite.clear();
139 m_downloadAddress.clear();
140 m_downloadFilename.clear();
141 m_downloadFilecode.clear();
144 unsigned int m_buildNo;
145 QDate m_buildDate;
146 QString m_downloadSite;
147 QString m_downloadAddress;
148 QString m_downloadFilename;
149 QString m_downloadFilecode;
152 ///////////////////////////////////////////////////////////////////////////////
154 UpdateDialog::UpdateDialog(SettingsModel *settings, QWidget *parent)
156 QDialog(parent),
157 m_binaryWGet(lamexp_lookup_tool("wget.exe")),
158 m_binaryGnuPG(lamexp_lookup_tool("gpgv.exe")),
159 m_binaryUpdater(lamexp_lookup_tool("wupdate.exe")),
160 m_binaryKeys(lamexp_lookup_tool("gpgv.gpg")),
161 m_updateInfo(NULL),
162 m_settings(settings),
163 m_logFile(new QStringList()),
164 m_betaUpdates(settings ? (settings->autoUpdateCheckBeta() || lamexp_version_demo()) : lamexp_version_demo()),
165 m_success(false),
166 m_updateReadyToInstall(false)
168 if(m_binaryWGet.isEmpty() || m_binaryGnuPG.isEmpty() || m_binaryUpdater.isEmpty() || m_binaryKeys.isEmpty())
170 throw "Tools not initialized correctly!";
173 //Init the dialog, from the .ui file
174 setupUi(this);
175 setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint);
177 //Disable "X" button
178 HMENU hMenu = GetSystemMenu((HWND) winId(), FALSE);
179 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
181 //Init animation
182 m_animator = new QMovie(":/images/Loading3.gif");
183 labelAnimationCenter->setMovie(m_animator);
184 m_animator->start();
186 //Indicate beta updates
187 if(m_betaUpdates)
189 setWindowTitle(windowTitle().append(" [Beta]"));
192 //Enable button
193 connect(retryButton, SIGNAL(clicked()), this, SLOT(checkForUpdates()));
194 connect(installButton, SIGNAL(clicked()), this, SLOT(applyUpdate()));
195 connect(infoLabel, SIGNAL(linkActivated(QString)), this, SLOT(linkActivated(QString)));
196 connect(logButton, SIGNAL(clicked()), this, SLOT(logButtonClicked()));
198 //Enable progress bar
199 connect(progressBar, SIGNAL(valueChanged(int)), this, SLOT(progressBarValueChanged(int)));
202 UpdateDialog::~UpdateDialog(void)
204 if(m_animator) m_animator->stop();
206 LAMEXP_DELETE(m_updateInfo);
207 LAMEXP_DELETE(m_logFile);
208 LAMEXP_DELETE(m_animator);
210 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
211 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
214 void UpdateDialog::showEvent(QShowEvent *event)
216 QDialog::showEvent(event);
218 labelVersionInstalled->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(lamexp_version_build()), lamexp_version_date().toString(Qt::ISODate)));
219 labelVersionLatest->setText(QString("(%1)").arg(tr("Unknown")));
221 QTimer::singleShot(0, this, SLOT(updateInit()));
222 installButton->setEnabled(false);
223 closeButton->setEnabled(false);
224 retryButton->setEnabled(false);
225 logButton->setEnabled(false);
226 retryButton->hide();
227 logButton->hide();
228 infoLabel->hide();
229 hintLabel->hide();
230 hintIcon->hide();
231 frameAnimation->hide();
233 int counter = 2;
234 for(int i = 0; known_hosts[i]; i++) counter++;
235 for(int i = 0; update_mirrors_prim[i]; i++) counter++;
236 for(int i = 0; update_mirrors_back[i]; i++) counter++;
238 progressBar->setMaximum(counter);
239 progressBar->setValue(0);
242 void UpdateDialog::closeEvent(QCloseEvent *event)
244 if(!closeButton->isEnabled())
246 event->ignore();
248 else
250 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
251 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
255 void UpdateDialog::keyPressEvent(QKeyEvent *e)
257 if(e->key() == Qt::Key_F11)
259 if(closeButton->isEnabled()) logButtonClicked();
261 else
263 QDialog::keyPressEvent(e);
267 void UpdateDialog::updateInit(void)
269 setMinimumSize(size());
270 setMaximumHeight(height());
272 checkForUpdates();
275 void UpdateDialog::checkForUpdates(void)
277 bool success = false;
278 int connectionScore = 0;
280 // ----- Initialization ----- //
282 m_updateInfo = new UpdateInfo;
284 progressBar->setValue(0);
285 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNormalState);
286 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
287 installButton->setEnabled(false);
288 closeButton->setEnabled(false);
289 retryButton->setEnabled(false);
290 logButton->setEnabled(false);
291 if(infoLabel->isVisible()) infoLabel->hide();
292 if(hintLabel->isVisible()) hintLabel->hide();
293 if(hintIcon->isVisible()) hintIcon->hide();
294 frameAnimation->show();
296 QApplication::processEvents();
297 QApplication::setOverrideCursor(Qt::WaitCursor);
299 // ----- Test Internet Connection ----- //
301 statusLabel->setText(tr("Testing your internet connection, please wait..."));
303 m_logFile->clear();
304 m_logFile->append("Checking internet connection...");
306 QFuture<BOOL> connectedState = QtConcurrent::run(getInternetConnectedState);
307 while(!connectedState.isFinished())
309 QApplication::processEvents(QEventLoop::WaitForMoreEvents);
312 if(!connectedState.result())
314 m_logFile->append(QStringList() << "" << "Operating system reports that the computer is currently offline !!!");
315 if(!retryButton->isVisible()) retryButton->show();
316 if(!logButton->isVisible()) logButton->show();
317 closeButton->setEnabled(true);
318 retryButton->setEnabled(true);
319 logButton->setEnabled(true);
320 if(frameAnimation->isVisible()) frameAnimation->hide();
321 statusLabel->setText(tr("It appears that the computer currently is offline!"));
322 progressBar->setValue(progressBar->maximum());
323 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
324 hintLabel->setText(tr("Please make sure your computer is connected to the internet and try again."));
325 hintIcon->show();
326 hintLabel->show();
327 LAMEXP_DELETE(m_updateInfo);
328 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
329 QApplication::restoreOverrideCursor();
330 progressBar->setValue(progressBar->maximum());
331 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
332 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
333 return;
336 // ----- Test Known Hosts Connectivity ----- //
338 QStringList hostList;
339 for(int i = 0; known_hosts[i]; i++)
341 hostList << QString::fromLatin1(known_hosts[i]);
344 qsrand(time(NULL));
345 while(!hostList.isEmpty())
347 progressBar->setValue(progressBar->value() + 1);
348 QString currentHost = hostList.takeAt(qrand() % hostList.count());
349 if(connectionScore < MIN_CONNSCORE)
351 m_logFile->append(QStringList() << "" << "Testing host:" << currentHost << "");
352 QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
353 if(getFile(currentHost, outFile, 0))
355 connectionScore++;
357 QFile::remove(outFile);
359 else
361 QApplication::processEvents();
362 Sleep(15);
366 if(connectionScore < MIN_CONNSCORE)
368 if(!retryButton->isVisible()) retryButton->show();
369 if(!logButton->isVisible()) logButton->show();
370 closeButton->setEnabled(true);
371 retryButton->setEnabled(true);
372 logButton->setEnabled(true);
373 if(frameAnimation->isVisible()) frameAnimation->hide();
374 statusLabel->setText(tr("Network connectivity test has failed!"));
375 progressBar->setValue(progressBar->maximum());
376 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
377 hintLabel->setText(tr("Please make sure your internet connection is working properly and try again."));
378 hintIcon->show();
379 hintLabel->show();
380 LAMEXP_DELETE(m_updateInfo);
381 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
382 QApplication::restoreOverrideCursor();
383 progressBar->setValue(progressBar->maximum());
384 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
385 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
386 return;
389 // ----- Build Mirror List ----- //
391 statusLabel->setText(tr("Checking for new updates online, please wait..."));
392 m_logFile->append(QStringList() << "" << "----" << "" << "Checking for updates online...");
394 QStringList mirrorList;
395 for(int index = 0; update_mirrors_prim[index]; index++)
397 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
400 qsrand(time(NULL));
401 for(int i = 0; i < 64; i++)
403 mirrorList.swap(i % mirrorList.count(), qrand() % mirrorList.count());
406 for(int index = 0; update_mirrors_back[index]; index++)
408 mirrorList << QString::fromLatin1(update_mirrors_back[index]);
411 // ----- Fetch Update Info From Server ----- //
413 while(!mirrorList.isEmpty())
415 QString currentMirror = mirrorList.takeFirst();
416 progressBar->setValue(progressBar->value() + 1);
417 if(!success)
419 if(tryUpdateMirror(m_updateInfo, currentMirror))
421 success = true;
424 else
426 QApplication::processEvents();
427 Sleep(15);
431 QApplication::restoreOverrideCursor();
432 progressBar->setValue(progressBar->maximum());
434 if(!success)
436 if(!retryButton->isVisible()) retryButton->show();
437 if(!logButton->isVisible()) logButton->show();
438 closeButton->setEnabled(true);
439 retryButton->setEnabled(true);
440 logButton->setEnabled(true);
441 if(frameAnimation->isVisible()) frameAnimation->hide();
442 statusLabel->setText(tr("Failed to fetch update information from server!"));
443 progressBar->setValue(progressBar->maximum());
444 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
445 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
446 hintIcon->setPixmap(QIcon(":/icons/server_error.png").pixmap(16,16));
447 hintLabel->setText(tr("Sorry, the update server might be busy at this time. Plase try again later."));
448 hintIcon->show();
449 hintLabel->show();
450 LAMEXP_DELETE(m_updateInfo);
451 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
452 return;
455 // ----- Download New Program Version ----- //
457 labelVersionLatest->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(m_updateInfo->m_buildNo), m_updateInfo->m_buildDate.toString(Qt::ISODate)));
458 infoLabel->show();
459 infoLabel->setText(QString("%1<br><a href=\"%2\">%2</a>").arg(tr("More information available at:"), m_updateInfo->m_downloadSite));
460 QApplication::processEvents();
462 if(m_updateInfo->m_buildNo > lamexp_version_build())
464 installButton->setEnabled(true);
465 statusLabel->setText(tr("A new version of LameXP is available!"));
466 hintIcon->setPixmap(QIcon(":/icons/shield_exclamation.png").pixmap(16,16));
467 hintLabel->setText(tr("We highly recommend all users to install this update as soon as possible."));
468 if(frameAnimation->isVisible()) frameAnimation->hide();
469 hintIcon->show();
470 hintLabel->show();
471 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_exclamation.png"));
472 MessageBeep(MB_ICONINFORMATION);
474 else if(m_updateInfo->m_buildNo == lamexp_version_build())
476 statusLabel->setText(tr("No new updates available at this time."));
477 hintIcon->setPixmap(QIcon(":/icons/shield_green.png").pixmap(16,16));
478 hintLabel->setText(tr("Your version of LameXP is still up-to-date. Please check for updates regularly!"));
479 if(frameAnimation->isVisible()) frameAnimation->hide();
480 hintIcon->show();
481 hintLabel->show();
482 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_green.png"));
483 MessageBeep(MB_ICONINFORMATION);
485 else
487 statusLabel->setText(tr("Your version appears to be newer than the latest release."));
488 hintIcon->setPixmap(QIcon(":/icons/shield_error.png").pixmap(16,16));
489 hintLabel->setText(tr("This usually indicates your are currently using a pre-release version of LameXP."));
490 if(frameAnimation->isVisible()) frameAnimation->hide();
491 hintIcon->show();
492 hintLabel->show();
493 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_error.png"));
494 MessageBeep(MB_ICONEXCLAMATION);
497 closeButton->setEnabled(true);
498 if(retryButton->isVisible()) retryButton->hide();
499 if(logButton->isVisible()) logButton->hide();
500 if(frameAnimation->isVisible()) frameAnimation->hide();
502 m_success = true;
505 bool UpdateDialog::tryUpdateMirror(UpdateInfo *updateInfo, const QString &url)
507 bool success = false;
508 m_logFile->append(QStringList() << "" << "Trying mirror:" << url);
510 QString randPart = lamexp_rand_str();
511 QString outFileVersionInfo = QString("%1/%2.ver").arg(lamexp_temp_folder2(), randPart);
512 QString outFileSignature = QString("%1/%2.sig").arg(lamexp_temp_folder2(), randPart);
514 m_logFile->append(QStringList() << "" << "Downloading update info:");
515 bool ok1 = getFile(QString("%1%2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVersionInfo);
517 m_logFile->append(QStringList() << "" << "Downloading signature:");
518 bool ok2 = getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSignature);
520 if(ok1 && ok2)
522 m_logFile->append(QStringList() << "" << "Download okay, checking signature:");
523 if(checkSignature(outFileVersionInfo, outFileSignature))
525 m_logFile->append(QStringList() << "" << "Signature okay, parsing info:");
526 success = parseVersionInfo(outFileVersionInfo, updateInfo);
528 else
530 m_logFile->append(QStringList() << "" << "Bad signature, take care!");
533 else
535 m_logFile->append(QStringList() << "" << "Download has failed!");
538 QFile::remove(outFileVersionInfo);
539 QFile::remove(outFileSignature);
541 return success;
544 bool UpdateDialog::getFile(const QString &url, const QString &outFile, unsigned int maxRedir)
546 QFileInfo output(outFile);
547 output.setCaching(false);
549 if(output.exists())
551 QFile::remove(output.canonicalFilePath());
552 if(output.exists())
554 return false;
558 QProcess process;
559 process.setProcessChannelMode(QProcess::MergedChannels);
560 process.setReadChannel(QProcess::StandardOutput);
561 process.setWorkingDirectory(output.absolutePath());
563 QStringList args;
564 args << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
565 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
566 args << "-O" << output.fileName() << url;
568 QEventLoop loop;
569 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
570 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
571 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
573 QTimer timer;
574 timer.setSingleShot(true);
575 timer.setInterval(15000);
576 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
578 process.start(m_binaryWGet, args);
580 if(!process.waitForStarted())
582 return false;
585 timer.start();
587 while(process.state() == QProcess::Running)
589 loop.exec();
590 if(!timer.isActive())
592 qWarning("WGet process timed out <-- killing!");
593 process.kill();
594 process.waitForFinished();
595 m_logFile->append("TIMEOUT !!!");
596 return false;
598 while(process.canReadLine())
600 m_logFile->append(QString::fromLatin1(process.readLine()).simplified());
604 timer.stop();
605 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
607 m_logFile->append(QString().sprintf("Exited with code %d", process.exitCode()));
608 return (process.exitCode() == 0) && output.exists() && output.isFile();
611 bool UpdateDialog::checkSignature(const QString &file, const QString &signature)
613 if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
615 qWarning("CheckSignature: File and signature should be in same folder!");
616 return false;
618 if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
620 qWarning("CheckSignature: File and keyring should be in same folder!");
621 return false;
624 QProcess process;
625 process.setProcessChannelMode(QProcess::MergedChannels);
626 process.setReadChannel(QProcess::StandardOutput);
627 process.setWorkingDirectory(QFileInfo(file).absolutePath());
629 QEventLoop loop;
630 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
631 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
632 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
634 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
636 if(!process.waitForStarted())
638 return false;
641 while(process.state() == QProcess::Running)
643 loop.exec();
644 while(process.canReadLine())
646 m_logFile->append(QString::fromLatin1(process.readLine()).simplified());
650 m_logFile->append(QString().sprintf("Exited with code %d", process.exitCode()));
651 return (process.exitCode() == 0);
654 bool UpdateDialog::parseVersionInfo(const QString &file, UpdateInfo *updateInfo)
656 QRegExp value("^(\\w+)=(.+)$");
657 QRegExp section("^\\[(.+)\\]$");
659 QDate updateInfoDate;
660 updateInfo->resetInfo();
662 QFile data(file);
663 if(!data.open(QIODevice::ReadOnly))
665 qWarning("Cannot open update info file for reading!");
666 return false;
669 bool inHeader = false;
670 bool inSection = false;
672 while(!data.atEnd())
674 QString line = QString::fromLatin1(data.readLine()).trimmed();
675 if(section.indexIn(line) >= 0)
677 m_logFile->append(QString("Sec: [%1]").arg(section.cap(1)));
678 inSection = (section.cap(1).compare(section_id, Qt::CaseInsensitive) == 0);
679 inHeader = (section.cap(1).compare(header_id, Qt::CaseInsensitive) == 0);
680 continue;
682 if(inSection && (value.indexIn(line) >= 0))
684 m_logFile->append(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
685 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
687 bool ok = false;
688 unsigned int temp = value.cap(2).toUInt(&ok);
689 if(ok) updateInfo->m_buildNo = temp;
691 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
693 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
694 if(temp.isValid()) updateInfo->m_buildDate = temp;
696 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
698 updateInfo->m_downloadSite = value.cap(2).trimmed();
700 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
702 updateInfo->m_downloadAddress = value.cap(2).trimmed();
704 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
706 updateInfo->m_downloadFilename = value.cap(2).trimmed();
708 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
710 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
713 if(inHeader && (value.indexIn(line) >= 0))
715 m_logFile->append(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
716 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
718 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
719 if(temp.isValid()) updateInfoDate = temp;
724 if(!updateInfoDate.isValid())
726 updateInfo->resetInfo();
727 m_logFile->append("WARNING: Version info timestamp is missing!");
728 return false;
730 else if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < QDate::currentDate())
732 updateInfo->resetInfo();
733 m_logFile->append(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
734 return false;
736 else if(QDate::currentDate() < updateInfoDate)
738 m_logFile->append("Version info is from the future, take care!");
739 qWarning("Version info is from the future, take care!");
742 bool complete = true;
744 if(!(updateInfo->m_buildNo > 0)) complete = false;
745 if(!(updateInfo->m_buildDate.year() >= 2010)) complete = false;
746 if(updateInfo->m_downloadSite.isEmpty()) complete = false;
747 if(updateInfo->m_downloadAddress.isEmpty()) complete = false;
748 if(updateInfo->m_downloadFilename.isEmpty()) complete = false;
749 if(updateInfo->m_downloadFilecode.isEmpty()) complete = false;
751 if(!complete)
753 m_logFile->append("WARNING: Version info is incomplete!");
756 return complete;
759 void UpdateDialog::linkActivated(const QString &link)
761 QDesktopServices::openUrl(QUrl(link));
764 void UpdateDialog::applyUpdate(void)
766 installButton->setEnabled(false);
767 closeButton->setEnabled(false);
768 retryButton->setEnabled(false);
770 if(m_updateInfo)
772 statusLabel->setText(tr("Update is being downloaded, please be patient..."));
773 frameAnimation->show();
774 if(hintLabel->isVisible()) hintLabel->hide();
775 if(hintIcon->isVisible()) hintIcon->hide();
776 int oldMax = progressBar->maximum();
777 int oldMin = progressBar->minimum();
778 progressBar->setRange(0, 0);
779 QApplication::processEvents();
781 QProcess process;
782 QStringList args;
783 QEventLoop loop;
785 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
786 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
788 args << QString("/Location=%1").arg(m_updateInfo->m_downloadAddress);
789 args << QString("/Filename=%1").arg(m_updateInfo->m_downloadFilename);
790 args << QString("/TicketID=%1").arg(m_updateInfo->m_downloadFilecode);
791 args << QString("/ToFolder=%1").arg(QDir::toNativeSeparators(QDir(QApplication::applicationDirPath()).canonicalPath()));
792 args << QString("/ToExFile=%1.exe").arg(QFileInfo(QFileInfo(QApplication::applicationFilePath()).canonicalFilePath()).completeBaseName());
793 args << QString("/AppTitle=LameXP (Build #%1)").arg(QString::number(m_updateInfo->m_buildNo));
795 QApplication::setOverrideCursor(Qt::WaitCursor);
796 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
797 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
799 process.start(m_binaryUpdater, args);
800 loop.exec();
801 QApplication::restoreOverrideCursor();
803 hintLabel->show();
804 hintIcon->show();
805 progressBar->setRange(oldMin, oldMax);
806 progressBar->setValue(oldMax);
807 frameAnimation->hide();
809 if(process.exitCode() == 0)
811 statusLabel->setText(tr("Update ready to install. Applicaion will quit..."));
812 m_updateReadyToInstall = true;
813 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
814 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
815 accept();
817 else
819 statusLabel->setText(tr("Update failed. Please try again or download manually!"));
820 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
821 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
822 WinSevenTaskbar::setTaskbarProgress(this->parentWidget(), 100, 100);
826 installButton->setEnabled(true);
827 closeButton->setEnabled(true);
830 void UpdateDialog::logButtonClicked(void)
832 LogViewDialog *logView = new LogViewDialog(this);
833 logView->exec(*m_logFile);
834 LAMEXP_DELETE(logView);
837 void UpdateDialog::progressBarValueChanged(int value)
839 WinSevenTaskbar::setTaskbarProgress(this->parentWidget(), value, progressBar->maximum());