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"
30 #include "avisynth_c.h"
34 #include <QCloseEvent>
35 #include <QMessageBox>
36 #include <QDesktopServices>
41 #include <QProgressDialog>
46 const char *home_url = "http://mulder.brhack.net/";
47 const char *update_url = "http://code.google.com/p/mulder/downloads/list";
48 const char *tpl_last = "<LAST_USED>";
50 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
51 #define SET_TEXT_COLOR(WIDGET,COLOR) { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); }
53 ///////////////////////////////////////////////////////////////////////////////
54 // Constructor & Destructor
55 ///////////////////////////////////////////////////////////////////////////////
60 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures)
62 m_cpuFeatures(cpuFeatures),
63 m_appDir(QApplication::applicationDirPath()),
69 //Init the dialog, from the .ui file
71 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
74 qRegisterMetaType<QUuid>("QUuid");
75 qRegisterMetaType<QUuid>("DWORD");
76 qRegisterMetaType<EncodeThread::JobStatus>("EncodeThread::JobStatus");
79 PreferencesDialog::initPreferences(&m_preferences);
80 PreferencesDialog::loadPreferences(&m_preferences);
82 //Create options object
83 m_options = new OptionsModel();
84 OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
86 //Create IPC thread object
87 m_ipcThread = new IPCThread();
88 connect(m_ipcThread, SIGNAL(instanceCreated(DWORD)), this, SLOT(instanceCreated(DWORD)), Qt::QueuedConnection);
91 setMinimumSize(size());
92 splitter->setSizes(QList<int>() << 16 << 196);
95 labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
96 labelBuildDate->installEventFilter(this);
97 setWindowTitle(QString("%1 (%2 Mode)").arg(windowTitle(), m_cpuFeatures->x64 ? "64-Bit" : "32-Bit"));
100 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
101 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
103 else if(x264_is_prerelease())
105 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
109 m_jobList = new JobListModel();
110 connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
111 jobsView->setModel(m_jobList);
114 jobsView->horizontalHeader()->setSectionHidden(3, true);
115 jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
116 jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
117 jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
118 jobsView->horizontalHeader()->resizeSection(1, 150);
119 jobsView->horizontalHeader()->resizeSection(2, 90);
120 jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
121 connect(jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
123 //Create context menu
124 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), logView);
125 actionClipboard->setEnabled(false);
126 logView->addAction(actionClipboard);
127 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
128 jobsView->addActions(menuJob->actions());
131 connect(buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed()));
132 connect(buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed()));
133 connect(buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed()));
134 connect(buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
135 connect(actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed()));
136 connect(actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed()));
137 connect(actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed()));
140 connect(actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
141 connect(actionWebMulder, SIGNAL(triggered()), this, SLOT(showWebLink()));
142 connect(actionWebX264, SIGNAL(triggered()), this, SLOT(showWebLink()));
143 connect(actionWebKomisar, SIGNAL(triggered()), this, SLOT(showWebLink()));
144 connect(actionWebJarod, SIGNAL(triggered()), this, SLOT(showWebLink()));
145 connect(actionWebJEEB, SIGNAL(triggered()), this, SLOT(showWebLink()));
146 connect(actionWebAvisynth32, SIGNAL(triggered()), this, SLOT(showWebLink()));
147 connect(actionWebAvisynth64, SIGNAL(triggered()), this, SLOT(showWebLink()));
148 connect(actionWebWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
149 connect(actionWebBluRay, SIGNAL(triggered()), this, SLOT(showWebLink()));
150 connect(actionWebAvsWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
151 connect(actionWebSecret, SIGNAL(triggered()), this, SLOT(showWebLink()));
152 connect(actionWebSupport, SIGNAL(triggered()), this, SLOT(showWebLink()));
153 connect(actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
155 //Create floating label
156 m_label = new QLabel(jobsView->viewport());
157 m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
158 m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
159 SET_TEXT_COLOR(m_label, Qt::darkGray);
160 SET_FONT_BOLD(m_label, true);
161 m_label->setVisible(true);
162 m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
163 m_label->addActions(jobsView->actions());
164 connect(splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
171 MainWindow::~MainWindow(void)
173 OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
175 X264_DELETE(m_jobList);
176 X264_DELETE(m_options);
177 X264_DELETE(m_droppedFiles);
178 X264_DELETE(m_label);
180 while(!m_toolsList.isEmpty())
182 QFile *temp = m_toolsList.takeFirst();
186 if(m_ipcThread->isRunning())
188 m_ipcThread->setAbort();
189 if(!m_ipcThread->wait(5000))
191 m_ipcThread->terminate();
196 X264_DELETE(m_ipcThread);
199 ///////////////////////////////////////////////////////////////////////////////
201 ///////////////////////////////////////////////////////////////////////////////
204 * The "add" button was clicked
206 void MainWindow::addButtonPressed(const QString &filePathIn, const QString &filePathOut, OptionsModel *options, int fileNo, int fileTotal, bool *ok)
208 qDebug("MainWindow::addButtonPressed");
212 AddJobDialog *addDialog = new AddJobDialog(this, options ? options : m_options, m_cpuFeatures->x64);
213 addDialog->setRunImmediately(countRunningJobs() < (m_preferences.autoRunNextJob ? m_preferences.maxRunningJobCount : 1));
215 if(options) addDialog->setWindowTitle(tr("Restart Job"));
216 if((fileNo >= 0) && (fileTotal > 1)) addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
217 if(!filePathIn.isEmpty()) addDialog->setSourceFile(filePathIn);
218 if(!filePathOut.isEmpty()) addDialog->setOutputFile(filePathOut);
220 int result = addDialog->exec();
221 if(result == QDialog::Accepted)
223 EncodeThread *thrd = new EncodeThread
225 addDialog->sourceFile(),
226 addDialog->outputFile(),
227 options ? options : m_options,
228 QString("%1/toolset").arg(m_appDir),
230 m_preferences.use10BitEncoding,
231 m_cpuFeatures->x64 && m_preferences.useAvisyth64Bit
234 QModelIndex newIndex = m_jobList->insertJob(thrd);
236 if(newIndex.isValid())
238 if(addDialog->runImmediately())
240 jobsView->selectRow(newIndex.row());
241 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
242 m_jobList->startJob(newIndex);
248 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
251 X264_DELETE(addDialog);
255 * The "start" button was clicked
257 void MainWindow::startButtonPressed(void)
259 m_jobList->startJob(jobsView->currentIndex());
263 * The "abort" button was clicked
265 void MainWindow::abortButtonPressed(void)
267 m_jobList->abortJob(jobsView->currentIndex());
271 * The "delete" button was clicked
273 void MainWindow::deleteButtonPressed(void)
275 m_jobList->deleteJob(jobsView->currentIndex());
276 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
280 * The "browse" button was clicked
282 void MainWindow::browseButtonPressed(void)
284 QString outputFile = m_jobList->getJobOutputFile(jobsView->currentIndex());
285 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
287 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
291 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
296 * The "pause" button was clicked
298 void MainWindow::pauseButtonPressed(bool checked)
302 m_jobList->pauseJob(jobsView->currentIndex());
306 m_jobList->resumeJob(jobsView->currentIndex());
311 * The "restart" button was clicked
313 void MainWindow::restartButtonPressed(void)
315 const QModelIndex index = jobsView->currentIndex();
317 const QString &source = m_jobList->getJobSourceFile(index);
318 const QString &output = m_jobList->getJobOutputFile(index);
319 const OptionsModel *options = m_jobList->getJobOptions(index);
321 if((options) && (!source.isEmpty()) && (!output.isEmpty()))
323 OptionsModel *tempOptions = new OptionsModel(*options);
324 addButtonPressed(source, output, tempOptions);
325 X264_DELETE(tempOptions);
330 * Job item selected by user
332 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
334 qDebug("Job selected: %d", current.row());
338 disconnect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
341 if(current.isValid())
343 logView->setModel(m_jobList->getLogFile(current));
344 connect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
345 logView->actions().first()->setEnabled(true);
346 QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
348 progressBar->setValue(m_jobList->getJobProgress(current));
349 editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
350 updateButtons(m_jobList->getJobStatus(current));
351 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
355 logView->setModel(NULL);
356 logView->actions().first()->setEnabled(false);
357 progressBar->setValue(0);
358 editDetails->clear();
359 updateButtons(EncodeThread::JobStatus_Undefined);
360 updateTaskbar(EncodeThread::JobStatus_Undefined, QIcon());
363 progressBar->repaint();
367 * Handle update of job info (status, progress, details, etc)
369 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
371 int selected = jobsView->currentIndex().row();
373 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
375 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
377 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
380 qDebug("Current job changed status!");
381 updateButtons(status);
382 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
384 if((status == EncodeThread::JobStatus_Completed) || (status == EncodeThread::JobStatus_Failed))
386 if(m_preferences.autoRunNextJob) QTimer::singleShot(0, this, SLOT(launchNextJob()));
387 if(m_preferences.shutdownComputer) QTimer::singleShot(0, this, SLOT(shutdownComputer()));
391 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
393 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
397 progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
398 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
403 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
405 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
409 editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
417 * Handle new log file content
419 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
421 QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
427 void MainWindow::showAbout(void)
431 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_build());
432 text += QString().sprintf("Copyright (c) 2004-%04d LoRd_MuldeR <mulder2@gmx.de>. Some rights reserved.<br>", qMax(x264_version_date().year(),QDate::currentDate().year()));
433 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());
434 text += QString().sprintf("This program is free software: you can redistribute it and/or modify<br>");
435 text += QString().sprintf("it under the terms of the GNU General Public License <http://www.gnu.org/>.<br>");
436 text += QString().sprintf("Note that this program is distributed with ABSOLUTELY NO WARRANTY.<br><br>");
437 text += QString().sprintf("Please check the web-site at <a href=\"%s\">%s</a> for updates !!!<br></tt></nobr>", home_url, home_url);
439 QMessageBox aboutBox(this);
440 aboutBox.setIconPixmap(QIcon(":/images/movie.png").pixmap(64,64));
441 aboutBox.setWindowTitle(tr("About..."));
442 aboutBox.setText(text.replace("-", "−"));
443 aboutBox.addButton(tr("About x264"), QMessageBox::NoRole);
444 aboutBox.addButton(tr("About AVS"), QMessageBox::NoRole);
445 aboutBox.addButton(tr("About Qt"), QMessageBox::NoRole);
446 aboutBox.setEscapeButton(aboutBox.addButton(tr("Close"), QMessageBox::NoRole));
450 MessageBeep(MB_ICONINFORMATION);
451 switch(aboutBox.exec())
456 text2 += tr("<nobr><tt>x264 - the best H.264/AVC encoder. Copyright (c) 2003-2012 x264 project.<br>");
457 text2 += tr("Free software library for encoding video streams into the H.264/MPEG-4 AVC format.<br>");
458 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
459 text2 += tr("Please visit <a href=\"%1\">%1</a> for obtaining a commercial x264 license.<br>").arg("http://x264licensing.com/");
460 text2 += tr("Read the <a href=\"%1\">user's manual</a> to get started and use the <a href=\"%2\">support forum</a> for help!<br></tt></nobr>").arg("http://mewiki.project357.com/wiki/X264_Settings", "http://forum.doom9.org/forumdisplay.php?f=77");
462 QMessageBox x264Box(this);
463 x264Box.setIconPixmap(QIcon(":/images/x264.png").pixmap(48,48));
464 x264Box.setWindowTitle(tr("About x264"));
465 x264Box.setText(text2.replace("-", "−"));
466 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
467 MessageBeep(MB_ICONINFORMATION);
474 text2 += tr("<nobr><tt>Avisynth - powerful video processing scripting language.<br>");
475 text2 += tr("Copyright (c) 2000 Ben Rudiak-Gould and all subsequent developers.<br>");
476 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
477 text2 += tr("Please visit the web-site <a href=\"%1\">%1</a> for more information.<br>").arg("http://avisynth.org/");
478 text2 += tr("Read the <a href=\"%1\">guide</a> to get started and use the <a href=\"%2\">support forum</a> for help!<br></tt></nobr>").arg("http://avisynth.org/mediawiki/First_script", "http://forum.doom9.org/forumdisplay.php?f=33");
480 QMessageBox x264Box(this);
481 x264Box.setIconPixmap(QIcon(":/images/avisynth.png").pixmap(48,67));
482 x264Box.setWindowTitle(tr("About Avisynth"));
483 x264Box.setText(text2.replace("-", "−"));
484 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
485 MessageBeep(MB_ICONINFORMATION);
490 QMessageBox::aboutQt(this);
501 void MainWindow::showWebLink(void)
503 if(QObject::sender() == actionWebMulder) QDesktopServices::openUrl(QUrl(home_url));
504 if(QObject::sender() == actionWebX264) QDesktopServices::openUrl(QUrl("http://www.x264.com/"));
505 if(QObject::sender() == actionWebKomisar) QDesktopServices::openUrl(QUrl("http://komisar.gin.by/"));
506 if(QObject::sender() == actionWebJarod) QDesktopServices::openUrl(QUrl("http://www.x264.nl/"));
507 if(QObject::sender() == actionWebJEEB) QDesktopServices::openUrl(QUrl("http://x264.fushizen.eu/"));
508 if(QObject::sender() == actionWebAvisynth32) QDesktopServices::openUrl(QUrl("http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/"));
509 if(QObject::sender() == actionWebAvisynth64) QDesktopServices::openUrl(QUrl("http://code.google.com/p/avisynth64/downloads/list"));
510 if(QObject::sender() == actionWebWiki) QDesktopServices::openUrl(QUrl("http://mewiki.project357.com/wiki/X264_Settings"));
511 if(QObject::sender() == actionWebBluRay) QDesktopServices::openUrl(QUrl("http://www.x264bluray.com/"));
512 if(QObject::sender() == actionWebAvsWiki) QDesktopServices::openUrl(QUrl("http://avisynth.org/mediawiki/Main_Page#Usage"));
513 if(QObject::sender() == actionWebSupport) QDesktopServices::openUrl(QUrl("http://forum.doom9.org/showthread.php?t=144140"));
514 if(QObject::sender() == actionWebSecret) QDesktopServices::openUrl(QUrl("http://www.youtube.com/watch_popup?v=AXIeHY-OYNI"));
518 * Pereferences dialog
520 void MainWindow::showPreferences(void)
522 PreferencesDialog *preferences = new PreferencesDialog(this, &m_preferences, m_cpuFeatures->x64);
524 X264_DELETE(preferences);
528 * Launch next job, after running job has finished
530 void MainWindow::launchNextJob(void)
532 qDebug("launchNextJob(void)");
535 const int rows = m_jobList->rowCount(QModelIndex());
537 if(countRunningJobs() >= m_preferences.maxRunningJobCount)
539 qDebug("Still have too many jobs running, won't launch next one yet!");
543 int startIdx= jobsView->currentIndex().isValid() ? qBound(0, jobsView->currentIndex().row(), rows-1) : 0;
545 for(int i = 0; i < rows; i++)
547 int currentIdx = (i + startIdx) % rows;
548 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
549 if(status == EncodeThread::JobStatus_Enqueued)
551 if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
553 jobsView->selectRow(currentIdx);
559 qWarning("No enqueued jobs left!");
563 * Shut down the computer (with countdown)
565 void MainWindow::shutdownComputer(void)
567 qDebug("shutdownComputer(void)");
569 if(countPendingJobs() > 0)
571 qDebug("Still have pending jobs, won't shutdown yet!");
575 const int iTimeout = 30;
576 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
577 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
579 qWarning("Initiating shutdown sequence!");
581 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
582 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
583 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
584 progressDialog.setModal(true);
585 progressDialog.setAutoClose(false);
586 progressDialog.setAutoReset(false);
587 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
588 progressDialog.setWindowTitle(windowTitle());
589 progressDialog.setCancelButton(cancelButton);
590 progressDialog.show();
592 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
593 QApplication::setOverrideCursor(Qt::WaitCursor);
594 PlaySound(MAKEINTRESOURCE(IDR_WAVE1), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
595 QApplication::restoreOverrideCursor();
598 timer.setInterval(1000);
601 QEventLoop eventLoop(this);
602 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
603 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
605 for(int i = 1; i <= iTimeout; i++)
608 if(progressDialog.wasCanceled())
610 progressDialog.close();
613 progressDialog.setValue(i+1);
614 progressDialog.setLabelText(text.arg(iTimeout-i));
615 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
616 QApplication::processEvents();
617 PlaySound(MAKEINTRESOURCE((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
620 qWarning("Shutting down !!!");
622 if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
624 qApp->closeAllWindows();
629 * Main initialization function (called only once!)
631 void MainWindow::init(void)
633 static const char *binFiles = "x264_8bit_x86.exe:x264_8bit_x64.exe:x264_10bit_x86.exe:x264_10bit_x64.exe:avs2yuv.exe:avs2yuv_x64.exe";
634 QStringList binaries = QString::fromLatin1(binFiles).split(":", QString::SkipEmptyParts);
638 //Check for a running instance
639 bool firstInstance = false;
640 if(m_ipcThread->initialize(&firstInstance))
642 m_ipcThread->start();
645 if(!m_ipcThread->wait(5000))
647 QMessageBox::warning(this, tr("Not Responding"), tr("<nobr>Another instance of this application is already running, but did not respond in time.<br>If the problem persists, please kill the running instance from the task manager!</nobr>"), tr("Quit"));
648 m_ipcThread->terminate();
651 close(); qApp->exit(-1); return;
656 while(!binaries.isEmpty())
658 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
659 QString current = binaries.takeFirst();
660 QFile *file = new QFile(QString("%1/toolset/%2").arg(m_appDir, current));
661 if(file->open(QIODevice::ReadOnly))
663 bool binaryTypeOkay = false;
665 if(GetBinaryType(QWCHAR(file->fileName()), &binaryType))
667 binaryTypeOkay = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
671 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("-", "−"));
672 qFatal(QString("Binary is invalid: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
673 close(); qApp->exit(-1); return;
680 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("-", "−"));
681 qFatal(QString("Binary not found: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
682 close(); qApp->exit(-1); return;
686 //Check for portable mode
690 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
691 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
692 if(writeTest.open(QIODevice::WriteOnly))
694 ok = (writeTest.write(data) == strlen(data));
699 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"));
700 if(val != 1) { close(); qApp->exit(-1); return; }
705 if(x264_is_prerelease())
707 qsrand(time(NULL)); int rnd = qrand() % 3;
708 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);
709 if(rnd != val) { close(); qApp->exit(-1); return; }
712 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
713 if(!(m_cpuFeatures->mmx && m_cpuFeatures->mmx2))
715 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"));
716 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
717 close(); qApp->exit(-1); return;
719 else if(!(m_cpuFeatures->mmx && m_cpuFeatures->sse))
721 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
722 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"));
723 if(val != 1) { close(); qApp->exit(-1); return; }
726 //Check for Avisynth support
727 if(!qApp->arguments().contains("--skip-avisynth-check", Qt::CaseInsensitive))
729 double avisynthVersion = 0.0;
730 QLibrary *avsLib = new QLibrary("avisynth.dll");
733 avisynthVersion = detectAvisynthVersion(avsLib);
734 if(avisynthVersion < 0.0)
736 int val = QMessageBox::critical(this, tr("Avisynth Error"), tr("<nobr>A critical error was encountered while checking your Avisynth version!</nobr>").replace("-", "−"), tr("Quit"), tr("Ignore"));
737 if(val != 1) { close(); qApp->exit(-1); return; }
740 if(avisynthVersion < 2.5)
742 int val = QMessageBox::warning(this, tr("Avisynth Missing"), tr("<nobr>It appears that Avisynth is <b>not</b> currently installed on your computer.<br>Therefore 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"));
743 avsLib->unload(); X264_DELETE(avsLib);
744 if(val != 1) { close(); qApp->exit(-1); return; }
748 //Check for expiration
749 if(x264_version_date().addMonths(6) < QDate::currentDate())
751 QMessageBox msgBox(this);
752 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
753 msgBox.setWindowTitle(tr("Update Notification"));
754 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
755 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));
756 QPushButton *btn1 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
757 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::AcceptRole);
758 btn1->setEnabled(false);
759 btn2->setVisible(false);
760 QTimer::singleShot(5000, btn1, SLOT(hide()));
761 QTimer::singleShot(5000, btn2, SLOT(show()));
765 //Add files from command-line
766 bool bAddFile = false;
767 QStringList files, args = qApp->arguments();
768 while(!args.isEmpty())
770 QString current = args.takeFirst();
773 bAddFile = (current.compare("--add", Qt::CaseInsensitive) == 0);
776 if((!current.startsWith("--")) && QFileInfo(current).exists() && QFileInfo(current).isFile())
778 files << QFileInfo(current).canonicalFilePath();
781 if(int totalFiles = files.count())
783 bool ok = true; int n = 0;
784 while((!files.isEmpty()) && ok)
786 QString currentFile = files.takeFirst();
787 qDebug("Adding file: %s", currentFile.toUtf8().constData());
788 addButtonPressed(currentFile, QString(), NULL, n++, totalFiles, &ok);
794 * Update the label position
796 void MainWindow::updateLabelPos(void)
798 const QWidget *const viewPort = jobsView->viewport();
799 m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
803 * Copy the complete log to the clipboard
805 void MainWindow::copyLogToClipboard(bool checked)
807 qDebug("copyLogToClipboard");
809 if(LogFileModel *log = dynamic_cast<LogFileModel*>(logView->model()))
811 log->copyToClipboard();
812 MessageBeep(MB_ICONINFORMATION);
817 * Process the dropped files
819 void MainWindow::handleDroppedFiles(void)
821 qDebug("MainWindow::handleDroppedFiles");
824 QStringList droppedFiles(*m_droppedFiles);
825 m_droppedFiles->clear();
826 int totalFiles = droppedFiles.count();
827 bool ok = true; int n = 0;
828 while((!droppedFiles.isEmpty()) && ok)
830 QString currentFile = droppedFiles.takeFirst();
831 qDebug("Adding file: %s", currentFile.toUtf8().constData());
832 addButtonPressed(currentFile, QString(), NULL, n++, totalFiles, &ok);
835 qDebug("Leave from MainWindow::handleDroppedFiles!");
838 void MainWindow::instanceCreated(DWORD pid)
840 qDebug("Notification from other instance (PID=0x%X) received!", pid);
842 FLASHWINFO flashWinInfo;
843 memset(&flashWinInfo, 0, sizeof(FLASHWINFO));
844 flashWinInfo.cbSize = sizeof(FLASHWINFO);
845 flashWinInfo.hwnd = this->winId();
846 flashWinInfo.dwFlags = FLASHW_ALL;
847 flashWinInfo.dwTimeout = 125;
848 flashWinInfo.uCount = 5;
850 SwitchToThisWindow(this->winId(), TRUE);
851 SetForegroundWindow(this->winId());
852 qApp->processEvents();
853 FlashWindowEx(&flashWinInfo);
856 ///////////////////////////////////////////////////////////////////////////////
858 ///////////////////////////////////////////////////////////////////////////////
863 void MainWindow::showEvent(QShowEvent *e)
865 QMainWindow::showEvent(e);
870 QTimer::singleShot(0, this, SLOT(init()));
877 void MainWindow::closeEvent(QCloseEvent *e)
879 if(countRunningJobs() > 0)
882 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
886 if(countPendingJobs() > 0)
888 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);
889 if(ret != QMessageBox::Yes)
896 while(m_jobList->rowCount(QModelIndex()) > 0)
898 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
899 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
902 QMessageBox::warning(this, tr("Failed To Exit"), tr("Sorry, at least one job could not be deleted!"));
907 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
908 QMainWindow::closeEvent(e);
912 * Window resize event
914 void MainWindow::resizeEvent(QResizeEvent *e)
916 QMainWindow::resizeEvent(e);
923 bool MainWindow::eventFilter(QObject *o, QEvent *e)
925 if((o == labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
927 QTimer::singleShot(0, this, SLOT(showAbout()));
934 * Win32 message filter
936 bool MainWindow::winEvent(MSG *message, long *result)
938 return WinSevenTaskbar::handleWinEvent(message, result);
942 * File dragged over window
944 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
946 QStringList formats = event->mimeData()->formats();
948 if(formats.contains("application/x-qt-windows-mime;value=\"FileNameW\"", Qt::CaseInsensitive) && formats.contains("text/uri-list", Qt::CaseInsensitive))
950 event->acceptProposedAction();
955 * File dropped onto window
957 void MainWindow::dropEvent(QDropEvent *event)
959 QStringList droppedFiles;
960 QList<QUrl> urls = event->mimeData()->urls();
962 while(!urls.isEmpty())
964 QUrl currentUrl = urls.takeFirst();
965 QFileInfo file(currentUrl.toLocalFile());
966 if(file.exists() && file.isFile())
968 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
969 droppedFiles << file.canonicalFilePath();
973 if(droppedFiles.count() > 0)
977 m_droppedFiles = new QStringList();
979 m_droppedFiles->append(droppedFiles);
980 m_droppedFiles->sort();
981 QTimer::singleShot(0, this, SLOT(handleDroppedFiles()));
985 ///////////////////////////////////////////////////////////////////////////////
987 ///////////////////////////////////////////////////////////////////////////////
990 * Jobs that are not completed (or failed, or aborted) yet
992 unsigned int MainWindow::countPendingJobs(void)
994 unsigned int count = 0;
995 const int rows = m_jobList->rowCount(QModelIndex());
997 for(int i = 0; i < rows; i++)
999 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1000 if(status != EncodeThread::JobStatus_Completed && status != EncodeThread::JobStatus_Aborted && status != EncodeThread::JobStatus_Failed)
1010 * Jobs that are still active, i.e. not terminated or enqueued
1012 unsigned int MainWindow::countRunningJobs(void)
1014 unsigned int count = 0;
1015 const int rows = m_jobList->rowCount(QModelIndex());
1017 for(int i = 0; i < rows; i++)
1019 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1020 if(status != EncodeThread::JobStatus_Completed && status != EncodeThread::JobStatus_Aborted && status != EncodeThread::JobStatus_Failed && status != EncodeThread::JobStatus_Enqueued)
1030 * Update all buttons with respect to current job status
1032 void MainWindow::updateButtons(EncodeThread::JobStatus status)
1034 qDebug("MainWindow::updateButtons(void)");
1036 buttonStartJob->setEnabled(status == EncodeThread::JobStatus_Enqueued);
1037 buttonAbortJob->setEnabled(status == EncodeThread::JobStatus_Indexing || status == EncodeThread::JobStatus_Running || status == EncodeThread::JobStatus_Running_Pass1 || status == EncodeThread::JobStatus_Running_Pass2 || status == EncodeThread::JobStatus_Paused);
1038 buttonPauseJob->setEnabled(status == EncodeThread::JobStatus_Indexing || status == EncodeThread::JobStatus_Running || status == EncodeThread::JobStatus_Paused || status == EncodeThread::JobStatus_Running_Pass1 || status == EncodeThread::JobStatus_Running_Pass2);
1039 buttonPauseJob->setChecked(status == EncodeThread::JobStatus_Paused || status == EncodeThread::JobStatus_Pausing);
1041 actionJob_Delete->setEnabled(status == EncodeThread::JobStatus_Completed || status == EncodeThread::JobStatus_Aborted || status == EncodeThread::JobStatus_Failed || status == EncodeThread::JobStatus_Enqueued);
1042 actionJob_Restart->setEnabled(status == EncodeThread::JobStatus_Completed || status == EncodeThread::JobStatus_Aborted || status == EncodeThread::JobStatus_Failed || status == EncodeThread::JobStatus_Enqueued);
1043 actionJob_Browse->setEnabled(status == EncodeThread::JobStatus_Completed);
1045 actionJob_Start->setEnabled(buttonStartJob->isEnabled());
1046 actionJob_Abort->setEnabled(buttonAbortJob->isEnabled());
1047 actionJob_Pause->setEnabled(buttonPauseJob->isEnabled());
1048 actionJob_Pause->setChecked(buttonPauseJob->isChecked());
1050 editDetails->setEnabled(status != EncodeThread::JobStatus_Paused);
1054 * Update the taskbar with current job status
1056 void MainWindow::updateTaskbar(EncodeThread::JobStatus status, const QIcon &icon)
1058 qDebug("MainWindow::updateTaskbar(void)");
1062 case EncodeThread::JobStatus_Undefined:
1063 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1065 case EncodeThread::JobStatus_Aborting:
1066 case EncodeThread::JobStatus_Starting:
1067 case EncodeThread::JobStatus_Pausing:
1068 case EncodeThread::JobStatus_Resuming:
1069 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1071 case EncodeThread::JobStatus_Aborted:
1072 case EncodeThread::JobStatus_Failed:
1073 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1075 case EncodeThread::JobStatus_Paused:
1076 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1079 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1085 case EncodeThread::JobStatus_Aborting:
1086 case EncodeThread::JobStatus_Starting:
1087 case EncodeThread::JobStatus_Pausing:
1088 case EncodeThread::JobStatus_Resuming:
1091 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
1095 WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);
1099 * Detect Avisynth version
1101 double MainWindow::detectAvisynthVersion(QLibrary *avsLib)
1103 double version_number = 0.0;
1107 avs_create_script_environment_func avs_create_script_environment_ptr = (avs_create_script_environment_func) avsLib->resolve("avs_create_script_environment");
1108 avs_invoke_func avs_invoke_ptr = (avs_invoke_func) avsLib->resolve("avs_invoke");
1109 avs_function_exists_func avs_function_exists_ptr = (avs_function_exists_func) avsLib->resolve("avs_function_exists");
1110 avs_delete_script_environment_func avs_delete_script_environment_ptr = (avs_delete_script_environment_func) avsLib->resolve("avs_delete_script_environment");
1112 if((avs_create_script_environment_ptr != NULL) && (avs_invoke_ptr != NULL) && (avs_function_exists_ptr != NULL))
1114 AVS_ScriptEnvironment* avs_env = avs_create_script_environment_ptr(AVS_INTERFACE_25);
1117 if(avs_function_exists_ptr(avs_env, "VersionNumber"))
1119 AVS_Value avs_version = avs_invoke_ptr(avs_env, "VersionNumber", avs_new_value_array(NULL, 0), NULL);
1120 if(!avs_is_error(avs_version))
1122 if(avs_is_float(avs_version))
1124 qDebug("Avisynth version: v%.2f", avs_as_float(avs_version));
1125 version_number = avs_as_float(avs_version);
1129 if(avs_delete_script_environment_ptr != NULL)
1131 avs_delete_script_environment_ptr(avs_env);
1138 qWarning("It seems the Avisynth DLL is missing required API functions!");
1143 qWarning("Exception in Avisynth initialization code!");
1144 version_number = -1.0;
1147 return version_number;