1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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 ///////////////////////////////////////////////////////////////////////////////
24 #include "model_jobList.h"
25 #include "model_options.h"
26 #include "win_addJob.h"
27 #include "win_preferences.h"
33 #include <QCloseEvent>
34 #include <QMessageBox>
35 #include <QDesktopServices>
40 #include <QProgressDialog>
44 const char *home_url = "http://mulder.brhack.net/";
45 const char *update_url = "http://code.google.com/p/mulder/downloads/list";
46 const char *tpl_last = "<LAST_USED>";
48 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
49 #define SET_TEXT_COLOR(WIDGET,COLOR) { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); }
51 ///////////////////////////////////////////////////////////////////////////////
52 // Constructor & Destructor
53 ///////////////////////////////////////////////////////////////////////////////
58 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures)
60 m_cpuFeatures(cpuFeatures),
61 m_appDir(QApplication::applicationDirPath()),
67 //Init the dialog, from the .ui file
69 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
72 qRegisterMetaType<QUuid>("QUuid");
73 qRegisterMetaType<EncodeThread::JobStatus>("EncodeThread::JobStatus");
76 PreferencesDialog::initPreferences(&m_preferences);
77 PreferencesDialog::loadPreferences(&m_preferences);
79 //Create options object
80 m_options = new OptionsModel();
81 OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
84 setMinimumSize(size());
85 splitter->setSizes(QList<int>() << 16 << 196);
88 labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
89 labelBuildDate->installEventFilter(this);
90 setWindowTitle(QString("%1 (%2 Mode)").arg(windowTitle(), m_cpuFeatures->x64 ? "64-Bit" : "32-Bit"));
93 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
94 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
96 else if(x264_is_prerelease())
98 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
102 m_jobList = new JobListModel();
103 connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
104 jobsView->setModel(m_jobList);
107 jobsView->horizontalHeader()->setSectionHidden(3, true);
108 jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
109 jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
110 jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
111 jobsView->horizontalHeader()->resizeSection(1, 150);
112 jobsView->horizontalHeader()->resizeSection(2, 90);
113 jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
114 connect(jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
116 //Create context menu
117 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), logView);
118 actionClipboard->setEnabled(false);
119 logView->addAction(actionClipboard);
120 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
121 jobsView->addActions(menuJob->actions());
124 connect(buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed()));
125 connect(buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed()));
126 connect(buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed()));
127 connect(buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
128 connect(actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed()));
129 connect(actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed()));
132 connect(actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
133 connect(actionWebMulder, SIGNAL(triggered()), this, SLOT(showWebLink()));
134 connect(actionWebX264, SIGNAL(triggered()), this, SLOT(showWebLink()));
135 connect(actionWebKomisar, SIGNAL(triggered()), this, SLOT(showWebLink()));
136 connect(actionWebJarod, SIGNAL(triggered()), this, SLOT(showWebLink()));
137 connect(actionWebJEEB, SIGNAL(triggered()), this, SLOT(showWebLink()));
138 connect(actionWebAvisynth32, SIGNAL(triggered()), this, SLOT(showWebLink()));
139 connect(actionWebAvisynth64, SIGNAL(triggered()), this, SLOT(showWebLink()));
140 connect(actionWebWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
141 connect(actionWebBluRay, SIGNAL(triggered()), this, SLOT(showWebLink()));
142 connect(actionWebSecret, SIGNAL(triggered()), this, SLOT(showWebLink()));
143 connect(actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
145 //Create floating label
146 m_label = new QLabel(jobsView->viewport());
147 m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
148 m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
149 SET_TEXT_COLOR(m_label, Qt::darkGray);
150 SET_FONT_BOLD(m_label, true);
151 m_label->setVisible(true);
152 m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
153 m_label->addActions(jobsView->actions());
154 connect(splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
161 MainWindow::~MainWindow(void)
163 OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
165 X264_DELETE(m_jobList);
166 X264_DELETE(m_options);
167 X264_DELETE(m_droppedFiles);
168 X264_DELETE(m_label);
170 while(!m_toolsList.isEmpty())
172 QFile *temp = m_toolsList.takeFirst();
177 ///////////////////////////////////////////////////////////////////////////////
179 ///////////////////////////////////////////////////////////////////////////////
182 * The "add" button was clicked
184 void MainWindow::addButtonPressed(const QString &filePath, int fileNo, int fileTotal, bool *ok)
186 qDebug("MainWindow::addButtonPressed");
190 AddJobDialog *addDialog = new AddJobDialog(this, m_options, m_cpuFeatures->x64);
191 addDialog->setRunImmediately(countRunningJobs() < (m_preferences.autoRunNextJob ? m_preferences.maxRunningJobCount : 1));
192 if((fileNo >= 0) && (fileTotal > 1)) addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
193 if(!filePath.isEmpty()) addDialog->setSourceFile(filePath);
195 int result = addDialog->exec();
196 if(result == QDialog::Accepted)
198 EncodeThread *thrd = new EncodeThread
200 addDialog->sourceFile(),
201 addDialog->outputFile(),
203 QString("%1/toolset").arg(m_appDir),
205 m_cpuFeatures->x64 && m_preferences.useAvisyth64Bit
208 QModelIndex newIndex = m_jobList->insertJob(thrd);
210 if(newIndex.isValid())
212 if(addDialog->runImmediately())
214 jobsView->selectRow(newIndex.row());
215 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
216 m_jobList->startJob(newIndex);
223 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
224 X264_DELETE(addDialog);
228 * The "start" button was clicked
230 void MainWindow::startButtonPressed(void)
232 m_jobList->startJob(jobsView->currentIndex());
236 * The "abort" button was clicked
238 void MainWindow::abortButtonPressed(void)
240 m_jobList->abortJob(jobsView->currentIndex());
244 * The "delete" button was clicked
246 void MainWindow::deleteButtonPressed(void)
248 m_jobList->deleteJob(jobsView->currentIndex());
249 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
253 * The "browse" button was clicked
255 void MainWindow::browseButtonPressed(void)
257 QString outputFile = m_jobList->getJobOutputFile(jobsView->currentIndex());
258 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
260 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
264 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
269 * The "pause" button was clicked
271 void MainWindow::pauseButtonPressed(bool checked)
275 m_jobList->pauseJob(jobsView->currentIndex());
279 m_jobList->resumeJob(jobsView->currentIndex());
284 * Job item selected by user
286 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
288 qDebug("Job selected: %d", current.row());
292 disconnect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
295 if(current.isValid())
297 logView->setModel(m_jobList->getLogFile(current));
298 connect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
299 logView->actions().first()->setEnabled(true);
300 QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
302 progressBar->setValue(m_jobList->getJobProgress(current));
303 editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
304 updateButtons(m_jobList->getJobStatus(current));
305 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
309 logView->setModel(NULL);
310 logView->actions().first()->setEnabled(false);
311 progressBar->setValue(0);
312 editDetails->clear();
313 updateButtons(EncodeThread::JobStatus_Undefined);
314 updateTaskbar(EncodeThread::JobStatus_Undefined, QIcon());
317 progressBar->repaint();
321 * Handle update of job info (status, progress, details, etc)
323 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
325 int selected = jobsView->currentIndex().row();
327 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
329 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
331 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
334 qDebug("Current job changed status!");
335 updateButtons(status);
336 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
338 if((status == EncodeThread::JobStatus_Completed) || (status == EncodeThread::JobStatus_Failed))
340 if(m_preferences.autoRunNextJob) QTimer::singleShot(0, this, SLOT(launchNextJob()));
341 if(m_preferences.shutdownComputer) QTimer::singleShot(0, this, SLOT(shutdownComputer()));
345 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
347 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
351 progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
352 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
357 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
359 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
363 editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
371 * Handle new log file content
373 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
375 QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
381 void MainWindow::showAbout(void)
385 text += QString().sprintf("<nobr><tt>Simple x264 Launcher v%u.%02u.%u - use 64-Bit x264 with 32-Bit Avisynth<br>", x264_version_major(), x264_version_minor(), x264_version_patch());
386 text += QString().sprintf("Copyright (c) 2004-%04d LoRd_MuldeR <mulder2@gmx.de>. Some rights reserved.<br>", qMax(x264_version_date().year(),QDate::currentDate().year()));
387 text += QString().sprintf("Built on %s at %s with %s for Win-%s.<br><br>", x264_version_date().toString(Qt::ISODate).toLatin1().constData(), x264_version_time(), x264_version_compiler(), x264_version_arch());
388 text += QString().sprintf("This program is free software: you can redistribute it and/or modify<br>");
389 text += QString().sprintf("it under the terms of the GNU General Public License <http://www.gnu.org/>.<br>");
390 text += QString().sprintf("Note that this program is distributed with ABSOLUTELY NO WARRANTY.<br><br>");
391 text += QString().sprintf("Please check the web-site at <a href=\"%s\">%s</a> for updates !!!<br></tt></nobr>", home_url, home_url);
393 QMessageBox aboutBox(this);
394 aboutBox.setIconPixmap(QIcon(":/images/movie.png").pixmap(64,64));
395 aboutBox.setWindowTitle(tr("About..."));
396 aboutBox.setText(text.replace("-", "−"));
397 aboutBox.addButton(tr("About x264"), QMessageBox::NoRole);
398 aboutBox.addButton(tr("About Qt"), QMessageBox::NoRole);
399 aboutBox.setEscapeButton(aboutBox.addButton(tr("Close"), QMessageBox::NoRole));
403 MessageBeep(MB_ICONINFORMATION);
404 switch(aboutBox.exec())
409 text2 += tr("<nobr><tt>x264 - the best H.264/AVC encoder. Copyright (c) 2003-2012 x264 project.<br>");
410 text2 += tr("Free software library for encoding video streams into the H.264/MPEG-4 AVC format.<br>");
411 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
412 text2 += tr("Please visit <a href=\"%1\">%1</a> for obtaining a <u>commercial</u> x264 license!<br></tt></nobr>").arg("http://x264licensing.com/");
414 QMessageBox x264Box(this);
415 x264Box.setIconPixmap(QIcon(":/images/x264.png").pixmap(48,48));
416 x264Box.setWindowTitle(tr("About x264"));
417 x264Box.setText(text2.replace("-", "−"));
418 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
419 MessageBeep(MB_ICONINFORMATION);
424 QMessageBox::aboutQt(this);
435 void MainWindow::showWebLink(void)
437 if(QObject::sender() == actionWebMulder) QDesktopServices::openUrl(QUrl(home_url));
438 if(QObject::sender() == actionWebX264) QDesktopServices::openUrl(QUrl("http://www.x264.com/"));
439 if(QObject::sender() == actionWebKomisar) QDesktopServices::openUrl(QUrl("http://komisar.gin.by/"));
440 if(QObject::sender() == actionWebJarod) QDesktopServices::openUrl(QUrl("http://www.x264.nl/"));
441 if(QObject::sender() == actionWebJEEB) QDesktopServices::openUrl(QUrl("http://x264.fushizen.eu/"));
442 if(QObject::sender() == actionWebAvisynth32) QDesktopServices::openUrl(QUrl("http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/"));
443 if(QObject::sender() == actionWebAvisynth64) QDesktopServices::openUrl(QUrl("http://code.google.com/p/avisynth64/downloads/list"));
444 if(QObject::sender() == actionWebWiki) QDesktopServices::openUrl(QUrl("http://mewiki.project357.com/wiki/X264_Settings"));
445 if(QObject::sender() == actionWebBluRay) QDesktopServices::openUrl(QUrl("http://www.x264bluray.com/"));
446 if(QObject::sender() == actionWebSecret) QDesktopServices::openUrl(QUrl("http://www.youtube.com/watch_popup?v=AXIeHY-OYNI"));
450 * Pereferences dialog
452 void MainWindow::showPreferences(void)
454 PreferencesDialog *preferences = new PreferencesDialog(this, &m_preferences, m_cpuFeatures->x64);
456 X264_DELETE(preferences);
460 * Launch next job, after running job has finished
462 void MainWindow::launchNextJob(void)
464 qDebug("launchNextJob(void)");
467 const int rows = m_jobList->rowCount(QModelIndex());
469 if(countRunningJobs() >= m_preferences.maxRunningJobCount)
471 qDebug("Still have too many jobs running, won't launch next one yet!");
475 int startIdx= jobsView->currentIndex().isValid() ? qBound(0, jobsView->currentIndex().row(), rows-1) : 0;
477 for(int i = 0; i < rows; i++)
479 int currentIdx = (i + startIdx) % rows;
480 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
481 if(status == EncodeThread::JobStatus_Enqueued)
483 if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
485 jobsView->selectRow(currentIdx);
491 qWarning("No enqueued jobs left!");
495 * Shut down the computer (with countdown)
497 void MainWindow::shutdownComputer(void)
499 qDebug("shutdownComputer(void)");
501 if(countPendingJobs() > 0)
503 qDebug("Still have pending jobs, won't shutdown yet!");
507 const int iTimeout = 30;
508 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
509 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
511 qWarning("Initiating shutdown sequence!");
513 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
514 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
515 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
516 progressDialog.setModal(true);
517 progressDialog.setAutoClose(false);
518 progressDialog.setAutoReset(false);
519 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
520 progressDialog.setWindowTitle(windowTitle());
521 progressDialog.setCancelButton(cancelButton);
522 progressDialog.show();
524 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
525 QApplication::setOverrideCursor(Qt::WaitCursor);
526 PlaySound(MAKEINTRESOURCE(IDR_WAVE1), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
527 QApplication::restoreOverrideCursor();
530 timer.setInterval(1000);
533 QEventLoop eventLoop(this);
534 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
535 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
537 for(int i = 1; i <= iTimeout; i++)
540 if(progressDialog.wasCanceled())
542 progressDialog.close();
545 progressDialog.setValue(i+1);
546 progressDialog.setLabelText(text.arg(iTimeout-i));
547 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
548 QApplication::processEvents();
549 PlaySound(MAKEINTRESOURCE((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
552 qWarning("Shutting down !!!");
554 if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
556 qApp->closeAllWindows();
561 * Main initialization function (called only once!)
563 void MainWindow::init(void)
565 static const char *binFiles = "x264.exe:x264_x64.exe:avs2yuv.exe:avs2yuv_x64.exe";
566 QStringList binaries = QString::fromLatin1(binFiles).split(":", QString::SkipEmptyParts);
571 while(!binaries.isEmpty())
573 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
574 QString current = binaries.takeFirst();
575 QFile *file = new QFile(QString("%1/toolset/%2").arg(m_appDir, current));
576 if(file->open(QIODevice::ReadOnly))
578 bool binaryTypeOkay = false;
580 if(GetBinaryType(QWCHAR(file->fileName()), &binaryType))
582 binaryTypeOkay = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
586 QMessageBox::critical(this, tr("Invalid File!"), tr("<nobr>At least on required tool is not a valid Win32 or Win64 binary:<br>%1<br><br>Please re-install the program in order to fix the problem!</nobr>").arg(QDir::toNativeSeparators(QString("%1/toolset/%2").arg(m_appDir, current))).replace("-", "−"));
587 qFatal(QString("Binary is invalid: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
588 close(); qApp->exit(-1); return;
595 QMessageBox::critical(this, tr("File Not Found!"), tr("<nobr>At least on required tool could not be found:<br>%1<br><br>Please re-install the program in order to fix the problem!</nobr>").arg(QDir::toNativeSeparators(QString("%1/toolset/%2").arg(m_appDir, current))).replace("-", "−"));
596 qFatal(QString("Binary not found: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
597 close(); qApp->exit(-1); return;
601 //Check for portable mode
605 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
606 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
607 if(writeTest.open(QIODevice::WriteOnly))
609 ok = (writeTest.write(data) == strlen(data));
614 int val = QMessageBox::warning(this, tr("Write Test Failed"), tr("<nobr>The application was launched in portable mode, but the program path is <b>not</b> writable!</nobr>"), tr("Quit"), tr("Ignore"));
615 if(val != 1) { close(); qApp->exit(-1); return; }
620 if(x264_is_prerelease())
622 qsrand(time(NULL)); int rnd = qrand() % 3;
623 int val = QMessageBox::information(this, tr("Pre-Release Version"), tr("Note: This is a pre-release version. Please do NOT use for production!<br>Click the button #%1 in order to continue...<br><br>(There will be no such message box in the final version of this application)").arg(QString::number(rnd + 1)), tr("(1)"), tr("(2)"), tr("(3)"), qrand() % 3);
624 if(rnd != val) { close(); qApp->exit(-1); return; }
627 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
628 if(!(m_cpuFeatures->mmx && m_cpuFeatures->mmx2))
630 QMessageBox::critical(this, tr("Unsupported CPU"), tr("<nobr>Sorry, but this machine is <b>not</b> physically capable of running x264 (with assembly).<br>Please get a CPU that supports at least the MMX and MMXEXT instruction sets!</nobr>"), tr("Quit"));
631 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
632 close(); qApp->exit(-1); return;
634 else if(!(m_cpuFeatures->mmx && m_cpuFeatures->sse))
636 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
637 int val = QMessageBox::warning(this, tr("Unsupported CPU"), tr("<nobr>It appears that this machine does <b>not</b> support the SSE1 instruction set.<br>Thus most builds of x264 will <b>not</b> run on this computer at all.<br><br>Please get a CPU that supports the MMX and SSE1 instruction sets!</nobr>"), tr("Quit"), tr("Ignore"));
638 if(val != 1) { close(); qApp->exit(-1); return; }
641 //Check for Avisynth support
642 bool avsAvailable = false;
643 QLibrary *avsLib = new QLibrary("avisynth.dll");
646 avsAvailable = (avsLib->resolve("avs_create_script_environment") != NULL);
650 avsLib->unload(); X264_DELETE(avsLib);
651 int val = QMessageBox::warning(this, tr("Avisynth Missing"), tr("<nobr>It appears that Avisynth is <b>not</b> currently installed on your computer.<br>Thus Avisynth (.avs) input will <b>not</b> be working at all!<br><br>Please download and install Avisynth:<br><a href=\"http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/\">http://sourceforge.net/projects/avisynth2/files/AviSynth 2.5/</a></nobr>").replace("-", "−"), tr("Quit"), tr("Ignore"));
652 if(val != 1) { close(); qApp->exit(-1); return; }
655 //Check for expiration
656 if(x264_version_date().addMonths(6) < QDate::currentDate())
658 QMessageBox msgBox(this);
659 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
660 msgBox.setWindowTitle(tr("Update Notification"));
661 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
662 msgBox.setText(tr("<nobr><tt>Your version of 'Simple x264 Launcher' is more than 6 months old!<br><br>Please download the most recent version from the official web-site at:<br><a href=\"%1\">%1</a><br></tt></nobr>").replace("-", "−").arg(update_url));
663 QPushButton *btn1 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
664 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::AcceptRole);
665 btn1->setEnabled(false);
666 btn2->setVisible(false);
667 QTimer::singleShot(5000, btn1, SLOT(hide()));
668 QTimer::singleShot(5000, btn2, SLOT(show()));
672 //Add files from command-line
673 bool bAddFile = false;
674 QStringList files, args = qApp->arguments();
675 while(!args.isEmpty())
677 QString current = args.takeFirst();
680 bAddFile = (current.compare("--add", Qt::CaseInsensitive) == 0);
683 if((!current.startsWith("--")) && QFileInfo(current).exists() && QFileInfo(current).isFile())
685 files << QFileInfo(current).canonicalFilePath();
688 if(int totalFiles = files.count())
690 bool ok = true; int n = 0;
691 while((!files.isEmpty()) && ok)
693 QString currentFile = files.takeFirst();
694 qDebug("Adding file: %s", currentFile.toUtf8().constData());
695 addButtonPressed(currentFile, n++, totalFiles, &ok);
701 * Update the label position
703 void MainWindow::updateLabelPos(void)
705 const QWidget *const viewPort = jobsView->viewport();
706 m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
710 * Copy the complete log to the clipboard
712 void MainWindow::copyLogToClipboard(bool checked)
714 qDebug("copyLogToClipboard");
716 if(LogFileModel *log = dynamic_cast<LogFileModel*>(logView->model()))
718 log->copyToClipboard();
719 MessageBeep(MB_ICONINFORMATION);
724 * Process the dropped files
726 void MainWindow::handleDroppedFiles(void)
728 qDebug("MainWindow::handleDroppedFiles");
731 QStringList droppedFiles(*m_droppedFiles);
732 m_droppedFiles->clear();
733 int totalFiles = droppedFiles.count();
734 bool ok = true; int n = 0;
735 while((!droppedFiles.isEmpty()) && ok)
737 QString currentFile = droppedFiles.takeFirst();
738 qDebug("Adding file: %s", currentFile.toUtf8().constData());
739 addButtonPressed(currentFile, n++, totalFiles, &ok);
742 qDebug("Leave from MainWindow::handleDroppedFiles!");
745 ///////////////////////////////////////////////////////////////////////////////
747 ///////////////////////////////////////////////////////////////////////////////
752 void MainWindow::showEvent(QShowEvent *e)
754 QMainWindow::showEvent(e);
759 QTimer::singleShot(0, this, SLOT(init()));
766 void MainWindow::closeEvent(QCloseEvent *e)
768 if(countRunningJobs() > 0)
771 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
775 if(countPendingJobs() > 0)
777 int ret = QMessageBox::question(this, tr("Jobs Are Pending"), tr("Do you really want to quit and discard the pending jobs?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
778 if(ret != QMessageBox::Yes)
785 while(m_jobList->rowCount(QModelIndex()) > 0)
787 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
788 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
791 QMessageBox::warning(this, tr("Failed To Exit"), tr("Sorry, at least one job could not be deleted!"));
796 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
797 QMainWindow::closeEvent(e);
801 * Window resize event
803 void MainWindow::resizeEvent(QResizeEvent *e)
805 QMainWindow::resizeEvent(e);
812 bool MainWindow::eventFilter(QObject *o, QEvent *e)
814 if((o == labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
816 QTimer::singleShot(0, this, SLOT(showAbout()));
823 * Win32 message filter
825 bool MainWindow::winEvent(MSG *message, long *result)
827 return WinSevenTaskbar::handleWinEvent(message, result);
831 * File dragged over window
833 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
835 QStringList formats = event->mimeData()->formats();
837 if(formats.contains("application/x-qt-windows-mime;value=\"FileNameW\"", Qt::CaseInsensitive) && formats.contains("text/uri-list", Qt::CaseInsensitive))
839 event->acceptProposedAction();
844 * File dropped onto window
846 void MainWindow::dropEvent(QDropEvent *event)
848 QStringList droppedFiles;
849 QList<QUrl> urls = event->mimeData()->urls();
851 while(!urls.isEmpty())
853 QUrl currentUrl = urls.takeFirst();
854 QFileInfo file(currentUrl.toLocalFile());
855 if(file.exists() && file.isFile())
857 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
858 droppedFiles << file.canonicalFilePath();
862 if(droppedFiles.count() > 0)
866 m_droppedFiles = new QStringList();
868 m_droppedFiles->append(droppedFiles);
869 m_droppedFiles->sort();
870 QTimer::singleShot(0, this, SLOT(handleDroppedFiles()));
874 ///////////////////////////////////////////////////////////////////////////////
876 ///////////////////////////////////////////////////////////////////////////////
879 * Jobs that are not completed (or failed, or aborted) yet
881 unsigned int MainWindow::countPendingJobs(void)
883 unsigned int count = 0;
884 const int rows = m_jobList->rowCount(QModelIndex());
886 for(int i = 0; i < rows; i++)
888 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
889 if(status != EncodeThread::JobStatus_Completed && status != EncodeThread::JobStatus_Aborted && status != EncodeThread::JobStatus_Failed)
899 * Jobs that are still active, i.e. not terminated or enqueued
901 unsigned int MainWindow::countRunningJobs(void)
903 unsigned int count = 0;
904 const int rows = m_jobList->rowCount(QModelIndex());
906 for(int i = 0; i < rows; i++)
908 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
909 if(status != EncodeThread::JobStatus_Completed && status != EncodeThread::JobStatus_Aborted && status != EncodeThread::JobStatus_Failed && status != EncodeThread::JobStatus_Enqueued)
919 * Update all buttons with respect to current job status
921 void MainWindow::updateButtons(EncodeThread::JobStatus status)
923 qDebug("MainWindow::updateButtons(void)");
925 buttonStartJob->setEnabled(status == EncodeThread::JobStatus_Enqueued);
926 buttonAbortJob->setEnabled(status == EncodeThread::JobStatus_Indexing || status == EncodeThread::JobStatus_Running || status == EncodeThread::JobStatus_Running_Pass1 || status == EncodeThread::JobStatus_Running_Pass2 || status == EncodeThread::JobStatus_Paused);
927 buttonPauseJob->setEnabled(status == EncodeThread::JobStatus_Indexing || status == EncodeThread::JobStatus_Running || status == EncodeThread::JobStatus_Paused || status == EncodeThread::JobStatus_Running_Pass1 || status == EncodeThread::JobStatus_Running_Pass2);
928 buttonPauseJob->setChecked(status == EncodeThread::JobStatus_Paused || status == EncodeThread::JobStatus_Pausing);
930 actionJob_Delete->setEnabled(status == EncodeThread::JobStatus_Completed || status == EncodeThread::JobStatus_Aborted || status == EncodeThread::JobStatus_Failed || status == EncodeThread::JobStatus_Enqueued);
931 actionJob_Browse->setEnabled(status == EncodeThread::JobStatus_Completed);
933 actionJob_Start->setEnabled(buttonStartJob->isEnabled());
934 actionJob_Abort->setEnabled(buttonAbortJob->isEnabled());
935 actionJob_Pause->setEnabled(buttonPauseJob->isEnabled());
936 actionJob_Pause->setChecked(buttonPauseJob->isChecked());
938 editDetails->setEnabled(status != EncodeThread::JobStatus_Paused);
942 * Update the taskbar with current job status
944 void MainWindow::updateTaskbar(EncodeThread::JobStatus status, const QIcon &icon)
946 qDebug("MainWindow::updateTaskbar(void)");
950 case EncodeThread::JobStatus_Undefined:
951 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
953 case EncodeThread::JobStatus_Aborting:
954 case EncodeThread::JobStatus_Starting:
955 case EncodeThread::JobStatus_Pausing:
956 case EncodeThread::JobStatus_Resuming:
957 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
959 case EncodeThread::JobStatus_Aborted:
960 case EncodeThread::JobStatus_Failed:
961 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
963 case EncodeThread::JobStatus_Paused:
964 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
967 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
973 case EncodeThread::JobStatus_Aborting:
974 case EncodeThread::JobStatus_Starting:
975 case EncodeThread::JobStatus_Pausing:
976 case EncodeThread::JobStatus_Resuming:
979 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
983 WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);