Implemented a more correct way to initialize the ITaskbarList3 interface. We now...
[LameXP.git] / src / Dialog_Update.cpp
blob3553668f3e7c9c68a4eea13e00db8a4ab70db3dc
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 bool UpdateDialog::winEvent(MSG *message, long *result)
269 return WinSevenTaskbar::handleWinEvent(message, result);
272 void UpdateDialog::updateInit(void)
274 setMinimumSize(size());
275 setMaximumHeight(height());
277 checkForUpdates();
280 void UpdateDialog::checkForUpdates(void)
282 bool success = false;
283 int connectionScore = 0;
285 // ----- Initialization ----- //
287 m_updateInfo = new UpdateInfo;
289 progressBar->setValue(0);
290 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNormalState);
291 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
292 installButton->setEnabled(false);
293 closeButton->setEnabled(false);
294 retryButton->setEnabled(false);
295 logButton->setEnabled(false);
296 if(infoLabel->isVisible()) infoLabel->hide();
297 if(hintLabel->isVisible()) hintLabel->hide();
298 if(hintIcon->isVisible()) hintIcon->hide();
299 frameAnimation->show();
301 QApplication::processEvents();
302 QApplication::setOverrideCursor(Qt::WaitCursor);
304 // ----- Test Internet Connection ----- //
306 statusLabel->setText(tr("Testing your internet connection, please wait..."));
308 m_logFile->clear();
309 m_logFile->append("Checking internet connection...");
311 QFuture<BOOL> connectedState = QtConcurrent::run(getInternetConnectedState);
312 while(!connectedState.isFinished())
314 QApplication::processEvents(QEventLoop::WaitForMoreEvents);
317 if(!connectedState.result())
319 m_logFile->append(QStringList() << "" << "Operating system reports that the computer is currently offline !!!");
320 if(!retryButton->isVisible()) retryButton->show();
321 if(!logButton->isVisible()) logButton->show();
322 closeButton->setEnabled(true);
323 retryButton->setEnabled(true);
324 logButton->setEnabled(true);
325 if(frameAnimation->isVisible()) frameAnimation->hide();
326 statusLabel->setText(tr("It appears that the computer currently is offline!"));
327 progressBar->setValue(progressBar->maximum());
328 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
329 hintLabel->setText(tr("Please make sure your computer is connected to the internet and try again."));
330 hintIcon->show();
331 hintLabel->show();
332 LAMEXP_DELETE(m_updateInfo);
333 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
334 QApplication::restoreOverrideCursor();
335 progressBar->setValue(progressBar->maximum());
336 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
337 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
338 return;
341 // ----- Test Known Hosts Connectivity ----- //
343 QStringList hostList;
344 for(int i = 0; known_hosts[i]; i++)
346 hostList << QString::fromLatin1(known_hosts[i]);
349 qsrand(time(NULL));
350 while(!hostList.isEmpty())
352 progressBar->setValue(progressBar->value() + 1);
353 QString currentHost = hostList.takeAt(qrand() % hostList.count());
354 if(connectionScore < MIN_CONNSCORE)
356 m_logFile->append(QStringList() << "" << "Testing host:" << currentHost << "");
357 QString outFile = QString("%1/%2.htm").arg(lamexp_temp_folder2(), lamexp_rand_str());
358 if(getFile(currentHost, outFile, 0))
360 connectionScore++;
362 QFile::remove(outFile);
364 else
366 QApplication::processEvents();
367 Sleep(15);
371 if(connectionScore < MIN_CONNSCORE)
373 if(!retryButton->isVisible()) retryButton->show();
374 if(!logButton->isVisible()) logButton->show();
375 closeButton->setEnabled(true);
376 retryButton->setEnabled(true);
377 logButton->setEnabled(true);
378 if(frameAnimation->isVisible()) frameAnimation->hide();
379 statusLabel->setText(tr("Network connectivity test has failed!"));
380 progressBar->setValue(progressBar->maximum());
381 hintIcon->setPixmap(QIcon(":/icons/network_error.png").pixmap(16,16));
382 hintLabel->setText(tr("Please make sure your internet connection is working properly and try again."));
383 hintIcon->show();
384 hintLabel->show();
385 LAMEXP_DELETE(m_updateInfo);
386 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
387 QApplication::restoreOverrideCursor();
388 progressBar->setValue(progressBar->maximum());
389 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
390 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
391 return;
394 // ----- Build Mirror List ----- //
396 statusLabel->setText(tr("Checking for new updates online, please wait..."));
397 m_logFile->append(QStringList() << "" << "----" << "" << "Checking for updates online...");
399 QStringList mirrorList;
400 for(int index = 0; update_mirrors_prim[index]; index++)
402 mirrorList << QString::fromLatin1(update_mirrors_prim[index]);
405 qsrand(time(NULL));
406 for(int i = 0; i < 64; i++)
408 mirrorList.swap(i % mirrorList.count(), qrand() % mirrorList.count());
411 for(int index = 0; update_mirrors_back[index]; index++)
413 mirrorList << QString::fromLatin1(update_mirrors_back[index]);
416 // ----- Fetch Update Info From Server ----- //
418 while(!mirrorList.isEmpty())
420 QString currentMirror = mirrorList.takeFirst();
421 progressBar->setValue(progressBar->value() + 1);
422 if(!success)
424 if(tryUpdateMirror(m_updateInfo, currentMirror))
426 success = true;
429 else
431 QApplication::processEvents();
432 Sleep(15);
436 QApplication::restoreOverrideCursor();
437 progressBar->setValue(progressBar->maximum());
439 if(!success)
441 if(!retryButton->isVisible()) retryButton->show();
442 if(!logButton->isVisible()) logButton->show();
443 closeButton->setEnabled(true);
444 retryButton->setEnabled(true);
445 logButton->setEnabled(true);
446 if(frameAnimation->isVisible()) frameAnimation->hide();
447 statusLabel->setText(tr("Failed to fetch update information from server!"));
448 progressBar->setValue(progressBar->maximum());
449 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
450 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
451 hintIcon->setPixmap(QIcon(":/icons/server_error.png").pixmap(16,16));
452 hintLabel->setText(tr("Sorry, the update server might be busy at this time. Plase try again later."));
453 hintIcon->show();
454 hintLabel->show();
455 LAMEXP_DELETE(m_updateInfo);
456 if(m_settings->soundsEnabled()) PlaySound(MAKEINTRESOURCE(IDR_WAVE_ERROR), GetModuleHandle(NULL), SND_RESOURCE | SND_ASYNC);
457 return;
460 // ----- Download New Program Version ----- //
462 labelVersionLatest->setText(QString("%1 %2 (%3)").arg(tr("Build"), QString::number(m_updateInfo->m_buildNo), m_updateInfo->m_buildDate.toString(Qt::ISODate)));
463 infoLabel->show();
464 infoLabel->setText(QString("%1<br><a href=\"%2\">%2</a>").arg(tr("More information available at:"), m_updateInfo->m_downloadSite));
465 QApplication::processEvents();
467 if(m_updateInfo->m_buildNo > lamexp_version_build())
469 installButton->setEnabled(true);
470 statusLabel->setText(tr("A new version of LameXP is available!"));
471 hintIcon->setPixmap(QIcon(":/icons/shield_exclamation.png").pixmap(16,16));
472 hintLabel->setText(tr("We highly recommend all users to install this update as soon as possible."));
473 if(frameAnimation->isVisible()) frameAnimation->hide();
474 hintIcon->show();
475 hintLabel->show();
476 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_exclamation.png"));
477 MessageBeep(MB_ICONINFORMATION);
479 else if(m_updateInfo->m_buildNo == lamexp_version_build())
481 statusLabel->setText(tr("No new updates available at this time."));
482 hintIcon->setPixmap(QIcon(":/icons/shield_green.png").pixmap(16,16));
483 hintLabel->setText(tr("Your version of LameXP is still up-to-date. Please check for updates regularly!"));
484 if(frameAnimation->isVisible()) frameAnimation->hide();
485 hintIcon->show();
486 hintLabel->show();
487 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_green.png"));
488 MessageBeep(MB_ICONINFORMATION);
490 else
492 statusLabel->setText(tr("Your version appears to be newer than the latest release."));
493 hintIcon->setPixmap(QIcon(":/icons/shield_error.png").pixmap(16,16));
494 hintLabel->setText(tr("This usually indicates your are currently using a pre-release version of LameXP."));
495 if(frameAnimation->isVisible()) frameAnimation->hide();
496 hintIcon->show();
497 hintLabel->show();
498 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/shield_error.png"));
499 MessageBeep(MB_ICONEXCLAMATION);
502 closeButton->setEnabled(true);
503 if(retryButton->isVisible()) retryButton->hide();
504 if(logButton->isVisible()) logButton->hide();
505 if(frameAnimation->isVisible()) frameAnimation->hide();
507 m_success = true;
510 bool UpdateDialog::tryUpdateMirror(UpdateInfo *updateInfo, const QString &url)
512 bool success = false;
513 m_logFile->append(QStringList() << "" << "Trying mirror:" << url);
515 QString randPart = lamexp_rand_str();
516 QString outFileVersionInfo = QString("%1/%2.ver").arg(lamexp_temp_folder2(), randPart);
517 QString outFileSignature = QString("%1/%2.sig").arg(lamexp_temp_folder2(), randPart);
519 m_logFile->append(QStringList() << "" << "Downloading update info:");
520 bool ok1 = getFile(QString("%1%2").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileVersionInfo);
522 m_logFile->append(QStringList() << "" << "Downloading signature:");
523 bool ok2 = getFile(QString("%1%2.sig").arg(url, mirror_url_postfix[m_betaUpdates ? 1 : 0]), outFileSignature);
525 if(ok1 && ok2)
527 m_logFile->append(QStringList() << "" << "Download okay, checking signature:");
528 if(checkSignature(outFileVersionInfo, outFileSignature))
530 m_logFile->append(QStringList() << "" << "Signature okay, parsing info:");
531 success = parseVersionInfo(outFileVersionInfo, updateInfo);
533 else
535 m_logFile->append(QStringList() << "" << "Bad signature, take care!");
538 else
540 m_logFile->append(QStringList() << "" << "Download has failed!");
543 QFile::remove(outFileVersionInfo);
544 QFile::remove(outFileSignature);
546 return success;
549 bool UpdateDialog::getFile(const QString &url, const QString &outFile, unsigned int maxRedir)
551 QFileInfo output(outFile);
552 output.setCaching(false);
554 if(output.exists())
556 QFile::remove(output.canonicalFilePath());
557 if(output.exists())
559 return false;
563 QProcess process;
564 process.setProcessChannelMode(QProcess::MergedChannels);
565 process.setReadChannel(QProcess::StandardOutput);
566 process.setWorkingDirectory(output.absolutePath());
568 QStringList args;
569 args << "--no-cache" << "--no-dns-cache" << QString().sprintf("--max-redirect=%u", maxRedir);
570 args << QString("--referer=%1://%2/").arg(QUrl(url).scheme(), QUrl(url).host()) << "-U" << USER_AGENT_STR;
571 args << "-O" << output.fileName() << url;
573 QEventLoop loop;
574 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
575 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
576 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
578 QTimer timer;
579 timer.setSingleShot(true);
580 timer.setInterval(15000);
581 connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
583 process.start(m_binaryWGet, args);
585 if(!process.waitForStarted())
587 return false;
590 timer.start();
592 while(process.state() == QProcess::Running)
594 loop.exec();
595 if(!timer.isActive())
597 qWarning("WGet process timed out <-- killing!");
598 process.kill();
599 process.waitForFinished();
600 m_logFile->append("TIMEOUT !!!");
601 return false;
603 while(process.canReadLine())
605 m_logFile->append(QString::fromLatin1(process.readLine()).simplified());
609 timer.stop();
610 timer.disconnect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
612 m_logFile->append(QString().sprintf("Exited with code %d", process.exitCode()));
613 return (process.exitCode() == 0) && output.exists() && output.isFile();
616 bool UpdateDialog::checkSignature(const QString &file, const QString &signature)
618 if(QFileInfo(file).absolutePath().compare(QFileInfo(signature).absolutePath(), Qt::CaseInsensitive) != 0)
620 qWarning("CheckSignature: File and signature should be in same folder!");
621 return false;
623 if(QFileInfo(file).absolutePath().compare(QFileInfo(m_binaryKeys).absolutePath(), Qt::CaseInsensitive) != 0)
625 qWarning("CheckSignature: File and keyring should be in same folder!");
626 return false;
629 QProcess process;
630 process.setProcessChannelMode(QProcess::MergedChannels);
631 process.setReadChannel(QProcess::StandardOutput);
632 process.setWorkingDirectory(QFileInfo(file).absolutePath());
634 QEventLoop loop;
635 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
636 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
637 connect(&process, SIGNAL(readyRead()), &loop, SLOT(quit()));
639 process.start(m_binaryGnuPG, QStringList() << "--homedir" << "." << "--keyring" << QFileInfo(m_binaryKeys).fileName() << QFileInfo(signature).fileName() << QFileInfo(file).fileName());
641 if(!process.waitForStarted())
643 return false;
646 while(process.state() == QProcess::Running)
648 loop.exec();
649 while(process.canReadLine())
651 m_logFile->append(QString::fromLatin1(process.readLine()).simplified());
655 m_logFile->append(QString().sprintf("Exited with code %d", process.exitCode()));
656 return (process.exitCode() == 0);
659 bool UpdateDialog::parseVersionInfo(const QString &file, UpdateInfo *updateInfo)
661 QRegExp value("^(\\w+)=(.+)$");
662 QRegExp section("^\\[(.+)\\]$");
664 QDate updateInfoDate;
665 updateInfo->resetInfo();
667 QFile data(file);
668 if(!data.open(QIODevice::ReadOnly))
670 qWarning("Cannot open update info file for reading!");
671 return false;
674 bool inHeader = false;
675 bool inSection = false;
677 while(!data.atEnd())
679 QString line = QString::fromLatin1(data.readLine()).trimmed();
680 if(section.indexIn(line) >= 0)
682 m_logFile->append(QString("Sec: [%1]").arg(section.cap(1)));
683 inSection = (section.cap(1).compare(section_id, Qt::CaseInsensitive) == 0);
684 inHeader = (section.cap(1).compare(header_id, Qt::CaseInsensitive) == 0);
685 continue;
687 if(inSection && (value.indexIn(line) >= 0))
689 m_logFile->append(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
690 if(value.cap(1).compare("BuildNo", Qt::CaseInsensitive) == 0)
692 bool ok = false;
693 unsigned int temp = value.cap(2).toUInt(&ok);
694 if(ok) updateInfo->m_buildNo = temp;
696 else if(value.cap(1).compare("BuildDate", Qt::CaseInsensitive) == 0)
698 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
699 if(temp.isValid()) updateInfo->m_buildDate = temp;
701 else if(value.cap(1).compare("DownloadSite", Qt::CaseInsensitive) == 0)
703 updateInfo->m_downloadSite = value.cap(2).trimmed();
705 else if(value.cap(1).compare("DownloadAddress", Qt::CaseInsensitive) == 0)
707 updateInfo->m_downloadAddress = value.cap(2).trimmed();
709 else if(value.cap(1).compare("DownloadFilename", Qt::CaseInsensitive) == 0)
711 updateInfo->m_downloadFilename = value.cap(2).trimmed();
713 else if(value.cap(1).compare("DownloadFilecode", Qt::CaseInsensitive) == 0)
715 updateInfo->m_downloadFilecode = value.cap(2).trimmed();
718 if(inHeader && (value.indexIn(line) >= 0))
720 m_logFile->append(QString("Val: '%1' ==> '%2").arg(value.cap(1), value.cap(2)));
721 if(value.cap(1).compare("TimestampCreated", Qt::CaseInsensitive) == 0)
723 QDate temp = QDate::fromString(value.cap(2).trimmed(), Qt::ISODate);
724 if(temp.isValid()) updateInfoDate = temp;
729 if(!updateInfoDate.isValid())
731 updateInfo->resetInfo();
732 m_logFile->append("WARNING: Version info timestamp is missing!");
733 return false;
735 else if(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS) < QDate::currentDate())
737 updateInfo->resetInfo();
738 m_logFile->append(QString::fromLatin1("WARNING: This version info has expired at %1!").arg(updateInfoDate.addMonths(VERSION_INFO_EXPIRES_MONTHS).toString(Qt::ISODate)));
739 return false;
741 else if(QDate::currentDate() < updateInfoDate)
743 m_logFile->append("Version info is from the future, take care!");
744 qWarning("Version info is from the future, take care!");
747 bool complete = true;
749 if(!(updateInfo->m_buildNo > 0)) complete = false;
750 if(!(updateInfo->m_buildDate.year() >= 2010)) complete = false;
751 if(updateInfo->m_downloadSite.isEmpty()) complete = false;
752 if(updateInfo->m_downloadAddress.isEmpty()) complete = false;
753 if(updateInfo->m_downloadFilename.isEmpty()) complete = false;
754 if(updateInfo->m_downloadFilecode.isEmpty()) complete = false;
756 if(!complete)
758 m_logFile->append("WARNING: Version info is incomplete!");
761 return complete;
764 void UpdateDialog::linkActivated(const QString &link)
766 QDesktopServices::openUrl(QUrl(link));
769 void UpdateDialog::applyUpdate(void)
771 installButton->setEnabled(false);
772 closeButton->setEnabled(false);
773 retryButton->setEnabled(false);
775 if(m_updateInfo)
777 statusLabel->setText(tr("Update is being downloaded, please be patient..."));
778 frameAnimation->show();
779 if(hintLabel->isVisible()) hintLabel->hide();
780 if(hintIcon->isVisible()) hintIcon->hide();
781 int oldMax = progressBar->maximum();
782 int oldMin = progressBar->minimum();
783 progressBar->setRange(0, 0);
784 QApplication::processEvents();
786 QProcess process;
787 QStringList args;
788 QEventLoop loop;
790 connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit()));
791 connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()));
793 args << QString("/Location=%1").arg(m_updateInfo->m_downloadAddress);
794 args << QString("/Filename=%1").arg(m_updateInfo->m_downloadFilename);
795 args << QString("/TicketID=%1").arg(m_updateInfo->m_downloadFilecode);
796 args << QString("/ToFolder=%1").arg(QDir::toNativeSeparators(QDir(QApplication::applicationDirPath()).canonicalPath()));
797 args << QString("/ToExFile=%1.exe").arg(QFileInfo(QFileInfo(QApplication::applicationFilePath()).canonicalFilePath()).completeBaseName());
798 args << QString("/AppTitle=LameXP (Build #%1)").arg(QString::number(m_updateInfo->m_buildNo));
800 QApplication::setOverrideCursor(Qt::WaitCursor);
801 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
802 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/transmit_blue.png"));
804 process.start(m_binaryUpdater, args);
805 loop.exec();
806 QApplication::restoreOverrideCursor();
808 hintLabel->show();
809 hintIcon->show();
810 progressBar->setRange(oldMin, oldMax);
811 progressBar->setValue(oldMax);
812 frameAnimation->hide();
814 if(process.exitCode() == 0)
816 statusLabel->setText(tr("Update ready to install. Applicaion will quit..."));
817 m_updateReadyToInstall = true;
818 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarNoState);
819 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), NULL);
820 accept();
822 else
824 statusLabel->setText(tr("Update failed. Please try again or download manually!"));
825 WinSevenTaskbar::setTaskbarState(this->parentWidget(), WinSevenTaskbar::WinSevenTaskbarErrorState);
826 WinSevenTaskbar::setOverlayIcon(this->parentWidget(), &QIcon(":/icons/exclamation.png"));
827 WinSevenTaskbar::setTaskbarProgress(this->parentWidget(), 100, 100);
831 installButton->setEnabled(true);
832 closeButton->setEnabled(true);
835 void UpdateDialog::logButtonClicked(void)
837 LogViewDialog *logView = new LogViewDialog(this);
838 logView->exec(*m_logFile);
839 LAMEXP_DELETE(logView);
842 void UpdateDialog::progressBarValueChanged(int value)
844 WinSevenTaskbar::setTaskbarProgress(this->parentWidget(), value, progressBar->maximum());