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"
28 #include "thread_avisynth.h"
34 #include <QCloseEvent>
35 #include <QMessageBox>
36 #include <QDesktopServices>
41 #include <QProgressDialog>
43 #include <QTextStream>
48 const char *home_url = "http://mulder.brhack.net/";
49 const char *update_url = "http://code.google.com/p/mulder/downloads/list";
50 const char *tpl_last = "<LAST_USED>";
52 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
53 #define SET_TEXT_COLOR(WIDGET,COLOR) { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); }
55 static int exceptionFilter(_EXCEPTION_RECORD *dst, _EXCEPTION_POINTERS *src) { memcpy(dst, src->ExceptionRecord, sizeof(_EXCEPTION_RECORD)); return EXCEPTION_EXECUTE_HANDLER; }
57 ///////////////////////////////////////////////////////////////////////////////
58 // Constructor & Destructor
59 ///////////////////////////////////////////////////////////////////////////////
64 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures)
66 m_cpuFeatures(cpuFeatures),
67 m_appDir(QApplication::applicationDirPath()),
73 //Init the dialog, from the .ui file
75 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
78 qRegisterMetaType<QUuid>("QUuid");
79 qRegisterMetaType<QUuid>("DWORD");
80 qRegisterMetaType<EncodeThread::JobStatus>("EncodeThread::JobStatus");
83 PreferencesDialog::initPreferences(&m_preferences);
84 PreferencesDialog::loadPreferences(&m_preferences);
86 //Create options object
87 m_options = new OptionsModel();
88 OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
90 //Create IPC thread object
91 m_ipcThread = new IPCThread();
92 connect(m_ipcThread, SIGNAL(instanceCreated(DWORD)), this, SLOT(instanceCreated(DWORD)), Qt::QueuedConnection);
95 setMinimumSize(size());
96 splitter->setSizes(QList<int>() << 16 << 196);
99 labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
100 labelBuildDate->installEventFilter(this);
101 setWindowTitle(QString("%1 (%2 Mode)").arg(windowTitle(), m_cpuFeatures->x64 ? "64-Bit" : "32-Bit"));
104 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
105 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
107 else if(x264_is_prerelease())
109 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
113 m_jobList = new JobListModel();
114 connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
115 jobsView->setModel(m_jobList);
118 jobsView->horizontalHeader()->setSectionHidden(3, true);
119 jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
120 jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
121 jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
122 jobsView->horizontalHeader()->resizeSection(1, 150);
123 jobsView->horizontalHeader()->resizeSection(2, 90);
124 jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
125 connect(jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
127 //Create context menu
128 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), logView);
129 actionClipboard->setEnabled(false);
130 logView->addAction(actionClipboard);
131 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
132 jobsView->addActions(menuJob->actions());
135 connect(buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed()));
136 connect(buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed()));
137 connect(buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed()));
138 connect(buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
139 connect(actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed()));
140 connect(actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed()));
141 connect(actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed()));
144 connect(actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
145 connect(actionWebMulder, SIGNAL(triggered()), this, SLOT(showWebLink()));
146 connect(actionWebX264, SIGNAL(triggered()), this, SLOT(showWebLink()));
147 connect(actionWebKomisar, SIGNAL(triggered()), this, SLOT(showWebLink()));
148 connect(actionWebJarod, SIGNAL(triggered()), this, SLOT(showWebLink()));
149 connect(actionWebJEEB, SIGNAL(triggered()), this, SLOT(showWebLink()));
150 connect(actionWebAvisynth32, SIGNAL(triggered()), this, SLOT(showWebLink()));
151 connect(actionWebAvisynth64, SIGNAL(triggered()), this, SLOT(showWebLink()));
152 connect(actionWebWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
153 connect(actionWebBluRay, SIGNAL(triggered()), this, SLOT(showWebLink()));
154 connect(actionWebAvsWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
155 connect(actionWebSecret, SIGNAL(triggered()), this, SLOT(showWebLink()));
156 connect(actionWebSupport, SIGNAL(triggered()), this, SLOT(showWebLink()));
157 connect(actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
159 //Create floating label
160 m_label = new QLabel(jobsView->viewport());
161 m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
162 m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
163 SET_TEXT_COLOR(m_label, Qt::darkGray);
164 SET_FONT_BOLD(m_label, true);
165 m_label->setVisible(true);
166 m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
167 m_label->addActions(jobsView->actions());
168 connect(splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
175 MainWindow::~MainWindow(void)
177 OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
179 X264_DELETE(m_jobList);
180 X264_DELETE(m_options);
181 X264_DELETE(m_droppedFiles);
182 X264_DELETE(m_label);
184 while(!m_toolsList.isEmpty())
186 QFile *temp = m_toolsList.takeFirst();
190 if(m_ipcThread->isRunning())
192 m_ipcThread->setAbort();
193 if(!m_ipcThread->wait(5000))
195 m_ipcThread->terminate();
200 X264_DELETE(m_ipcThread);
201 AvisynthCheckThread::unload();
204 ///////////////////////////////////////////////////////////////////////////////
206 ///////////////////////////////////////////////////////////////////////////////
209 * The "add" button was clicked
211 void MainWindow::addButtonPressed()
213 qDebug("MainWindow::addButtonPressed");
214 bool runImmediately = (countRunningJobs() < (m_preferences.autoRunNextJob ? m_preferences.maxRunningJobCount : 1));
215 QString sourceFileName, outputFileName;
217 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
219 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
224 * The "start" button was clicked
226 void MainWindow::startButtonPressed(void)
228 m_jobList->startJob(jobsView->currentIndex());
232 * The "abort" button was clicked
234 void MainWindow::abortButtonPressed(void)
236 m_jobList->abortJob(jobsView->currentIndex());
240 * The "delete" button was clicked
242 void MainWindow::deleteButtonPressed(void)
244 m_jobList->deleteJob(jobsView->currentIndex());
245 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
249 * The "browse" button was clicked
251 void MainWindow::browseButtonPressed(void)
253 QString outputFile = m_jobList->getJobOutputFile(jobsView->currentIndex());
254 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
256 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
260 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
265 * The "pause" button was clicked
267 void MainWindow::pauseButtonPressed(bool checked)
271 m_jobList->pauseJob(jobsView->currentIndex());
275 m_jobList->resumeJob(jobsView->currentIndex());
280 * The "restart" button was clicked
282 void MainWindow::restartButtonPressed(void)
284 const QModelIndex index = jobsView->currentIndex();
285 const OptionsModel *options = m_jobList->getJobOptions(index);
286 QString sourceFileName = m_jobList->getJobSourceFile(index);
287 QString outputFileName = m_jobList->getJobOutputFile(index);
289 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
291 bool runImmediately = true;
292 OptionsModel *tempOptions = new OptionsModel(*options);
293 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
295 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
297 X264_DELETE(tempOptions);
302 * Job item selected by user
304 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
306 qDebug("Job selected: %d", current.row());
310 disconnect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
313 if(current.isValid())
315 logView->setModel(m_jobList->getLogFile(current));
316 connect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
317 logView->actions().first()->setEnabled(true);
318 QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
320 progressBar->setValue(m_jobList->getJobProgress(current));
321 editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
322 updateButtons(m_jobList->getJobStatus(current));
323 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
327 logView->setModel(NULL);
328 logView->actions().first()->setEnabled(false);
329 progressBar->setValue(0);
330 editDetails->clear();
331 updateButtons(EncodeThread::JobStatus_Undefined);
332 updateTaskbar(EncodeThread::JobStatus_Undefined, QIcon());
335 progressBar->repaint();
339 * Handle update of job info (status, progress, details, etc)
341 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
343 int selected = jobsView->currentIndex().row();
345 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
347 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
349 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
352 qDebug("Current job changed status!");
353 updateButtons(status);
354 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
356 if((status == EncodeThread::JobStatus_Completed) || (status == EncodeThread::JobStatus_Failed))
358 if(m_preferences.autoRunNextJob) QTimer::singleShot(0, this, SLOT(launchNextJob()));
359 if(m_preferences.shutdownComputer) QTimer::singleShot(0, this, SLOT(shutdownComputer()));
360 if(m_preferences.saveLogFiles) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
364 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
366 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
370 progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
371 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
376 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
378 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
382 editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
390 * Handle new log file content
392 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
394 QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
400 void MainWindow::showAbout(void)
404 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());
405 text += QString().sprintf("Copyright (c) 2004-%04d LoRd_MuldeR <mulder2@gmx.de>. Some rights reserved.<br>", qMax(x264_version_date().year(),QDate::currentDate().year()));
406 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());
407 text += QString().sprintf("This program is free software: you can redistribute it and/or modify<br>");
408 text += QString().sprintf("it under the terms of the GNU General Public License <http://www.gnu.org/>.<br>");
409 text += QString().sprintf("Note that this program is distributed with ABSOLUTELY NO WARRANTY.<br><br>");
410 text += QString().sprintf("Please check the web-site at <a href=\"%s\">%s</a> for updates !!!<br></tt></nobr>", home_url, home_url);
412 QMessageBox aboutBox(this);
413 aboutBox.setIconPixmap(QIcon(":/images/movie.png").pixmap(64,64));
414 aboutBox.setWindowTitle(tr("About..."));
415 aboutBox.setText(text.replace("-", "−"));
416 aboutBox.addButton(tr("About x264"), QMessageBox::NoRole);
417 aboutBox.addButton(tr("About AVS"), QMessageBox::NoRole);
418 aboutBox.addButton(tr("About Qt"), QMessageBox::NoRole);
419 aboutBox.setEscapeButton(aboutBox.addButton(tr("Close"), QMessageBox::NoRole));
423 MessageBeep(MB_ICONINFORMATION);
424 switch(aboutBox.exec())
429 text2 += tr("<nobr><tt>x264 - the best H.264/AVC encoder. Copyright (c) 2003-2012 x264 project.<br>");
430 text2 += tr("Free software library for encoding video streams into the H.264/MPEG-4 AVC format.<br>");
431 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
432 text2 += tr("Please visit <a href=\"%1\">%1</a> for obtaining a commercial x264 license.<br>").arg("http://x264licensing.com/");
433 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");
435 QMessageBox x264Box(this);
436 x264Box.setIconPixmap(QIcon(":/images/x264.png").pixmap(48,48));
437 x264Box.setWindowTitle(tr("About x264"));
438 x264Box.setText(text2.replace("-", "−"));
439 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
440 MessageBeep(MB_ICONINFORMATION);
447 text2 += tr("<nobr><tt>Avisynth - powerful video processing scripting language.<br>");
448 text2 += tr("Copyright (c) 2000 Ben Rudiak-Gould and all subsequent developers.<br>");
449 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
450 text2 += tr("Please visit the web-site <a href=\"%1\">%1</a> for more information.<br>").arg("http://avisynth.org/");
451 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");
453 QMessageBox x264Box(this);
454 x264Box.setIconPixmap(QIcon(":/images/avisynth.png").pixmap(48,67));
455 x264Box.setWindowTitle(tr("About Avisynth"));
456 x264Box.setText(text2.replace("-", "−"));
457 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
458 MessageBeep(MB_ICONINFORMATION);
463 QMessageBox::aboutQt(this);
474 void MainWindow::showWebLink(void)
476 if(QObject::sender() == actionWebMulder) QDesktopServices::openUrl(QUrl(home_url));
477 if(QObject::sender() == actionWebX264) QDesktopServices::openUrl(QUrl("http://www.x264.com/"));
478 if(QObject::sender() == actionWebKomisar) QDesktopServices::openUrl(QUrl("http://komisar.gin.by/"));
479 if(QObject::sender() == actionWebJarod) QDesktopServices::openUrl(QUrl("http://www.x264.nl/"));
480 if(QObject::sender() == actionWebJEEB) QDesktopServices::openUrl(QUrl("http://x264.fushizen.eu/"));
481 if(QObject::sender() == actionWebAvisynth32) QDesktopServices::openUrl(QUrl("http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/"));
482 if(QObject::sender() == actionWebAvisynth64) QDesktopServices::openUrl(QUrl("http://code.google.com/p/avisynth64/downloads/list"));
483 if(QObject::sender() == actionWebWiki) QDesktopServices::openUrl(QUrl("http://mewiki.project357.com/wiki/X264_Settings"));
484 if(QObject::sender() == actionWebBluRay) QDesktopServices::openUrl(QUrl("http://www.x264bluray.com/"));
485 if(QObject::sender() == actionWebAvsWiki) QDesktopServices::openUrl(QUrl("http://avisynth.org/mediawiki/Main_Page#Usage"));
486 if(QObject::sender() == actionWebSupport) QDesktopServices::openUrl(QUrl("http://forum.doom9.org/showthread.php?t=144140"));
487 if(QObject::sender() == actionWebSecret) QDesktopServices::openUrl(QUrl("http://www.youtube.com/watch_popup?v=AXIeHY-OYNI"));
491 * Pereferences dialog
493 void MainWindow::showPreferences(void)
495 PreferencesDialog *preferences = new PreferencesDialog(this, &m_preferences, m_cpuFeatures->x64);
497 X264_DELETE(preferences);
501 * Launch next job, after running job has finished
503 void MainWindow::launchNextJob(void)
505 qDebug("launchNextJob(void)");
507 const int rows = m_jobList->rowCount(QModelIndex());
509 if(countRunningJobs() >= m_preferences.maxRunningJobCount)
511 qDebug("Still have too many jobs running, won't launch next one yet!");
515 int startIdx= jobsView->currentIndex().isValid() ? qBound(0, jobsView->currentIndex().row(), rows-1) : 0;
517 for(int i = 0; i < rows; i++)
519 int currentIdx = (i + startIdx) % rows;
520 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
521 if(status == EncodeThread::JobStatus_Enqueued)
523 if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
525 jobsView->selectRow(currentIdx);
531 qWarning("No enqueued jobs left!");
535 * Save log to text file
537 void MainWindow::saveLogFile(const QModelIndex &index)
541 if(LogFileModel *log = m_jobList->getLogFile(index))
543 QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
544 QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
545 QFile outFile(logFilePath);
546 if(outFile.open(QIODevice::WriteOnly))
548 QTextStream outStream(&outFile);
549 outStream.setCodec("UTF-8");
550 outStream.setGenerateByteOrderMark(true);
552 const int rows = log->rowCount(QModelIndex());
553 for(int i = 0; i < rows; i++)
555 outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
561 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
568 * Shut down the computer (with countdown)
570 void MainWindow::shutdownComputer(void)
572 qDebug("shutdownComputer(void)");
574 if(countPendingJobs() > 0)
576 qDebug("Still have pending jobs, won't shutdown yet!");
580 const int iTimeout = 30;
581 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
582 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
584 qWarning("Initiating shutdown sequence!");
586 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
587 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
588 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
589 progressDialog.setModal(true);
590 progressDialog.setAutoClose(false);
591 progressDialog.setAutoReset(false);
592 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
593 progressDialog.setWindowTitle(windowTitle());
594 progressDialog.setCancelButton(cancelButton);
595 progressDialog.show();
597 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
598 QApplication::setOverrideCursor(Qt::WaitCursor);
599 PlaySound(MAKEINTRESOURCE(IDR_WAVE1), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
600 QApplication::restoreOverrideCursor();
603 timer.setInterval(1000);
606 QEventLoop eventLoop(this);
607 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
608 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
610 for(int i = 1; i <= iTimeout; i++)
613 if(progressDialog.wasCanceled())
615 progressDialog.close();
618 progressDialog.setValue(i+1);
619 progressDialog.setLabelText(text.arg(iTimeout-i));
620 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
621 QApplication::processEvents();
622 PlaySound(MAKEINTRESOURCE((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
625 qWarning("Shutting down !!!");
627 if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
629 qApp->closeAllWindows();
634 * Main initialization function (called only once!)
636 void MainWindow::init(void)
638 static const char *binFiles = "x86/x264_8bit_x86.exe:x64/x264_8bit_x64.exe:x86/x264_10bit_x86.exe:x64/x264_10bit_x64.exe:x86/avs2yuv_x86.exe:x64/avs2yuv_x64.exe";
639 QStringList binaries = QString::fromLatin1(binFiles).split(":", QString::SkipEmptyParts);
643 //Check for a running instance
644 bool firstInstance = false;
645 if(m_ipcThread->initialize(&firstInstance))
647 m_ipcThread->start();
650 if(!m_ipcThread->wait(5000))
652 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"));
653 m_ipcThread->terminate();
656 close(); qApp->exit(-1); return;
661 while(!binaries.isEmpty())
663 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
664 QString current = binaries.takeFirst();
665 QFile *file = new QFile(QString("%1/toolset/%2").arg(m_appDir, current));
666 if(file->open(QIODevice::ReadOnly))
668 bool binaryTypeOkay = false;
670 if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(file->fileName())), &binaryType))
672 binaryTypeOkay = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
676 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("-", "−"));
677 qFatal(QString("Binary is invalid: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
678 close(); qApp->exit(-1); return;
685 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("-", "−"));
686 qFatal(QString("Binary not found: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
687 close(); qApp->exit(-1); return;
691 //Check for portable mode
695 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
696 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
697 if(writeTest.open(QIODevice::WriteOnly))
699 ok = (writeTest.write(data) == strlen(data));
704 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"));
705 if(val != 1) { close(); qApp->exit(-1); return; }
710 if(x264_is_prerelease())
712 qsrand(time(NULL)); int rnd = qrand() % 3;
713 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);
714 if(rnd != val) { close(); qApp->exit(-1); return; }
717 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
718 if(!(m_cpuFeatures->mmx && m_cpuFeatures->mmx2))
720 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"));
721 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
722 close(); qApp->exit(-1); return;
724 else if(!(m_cpuFeatures->mmx && m_cpuFeatures->sse))
726 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
727 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"));
728 if(val != 1) { close(); qApp->exit(-1); return; }
731 //Check for Avisynth support
732 if(!qApp->arguments().contains("--skip-avisynth-check", Qt::CaseInsensitive))
734 qDebug("[Check for Avisynth support]");
735 volatile double avisynthVersion = 0.0;
736 const int result = AvisynthCheckThread::detect(&avisynthVersion);
739 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
740 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
741 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
742 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
743 if(val != 1) { close(); qApp->exit(-1); return; }
745 if((!result) || (avisynthVersion < 2.5))
747 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"));
748 if(val != 1) { close(); qApp->exit(-1); return; }
753 //Check for expiration
754 if(x264_version_date().addMonths(6) < QDate::currentDate())
756 QMessageBox msgBox(this);
757 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
758 msgBox.setWindowTitle(tr("Update Notification"));
759 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
760 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));
761 QPushButton *btn1 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
762 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::AcceptRole);
763 btn1->setEnabled(false);
764 btn2->setVisible(false);
765 QTimer::singleShot(5000, btn1, SLOT(hide()));
766 QTimer::singleShot(5000, btn2, SLOT(show()));
770 //Add files from command-line
771 bool bAddFile = false;
772 QStringList files, args = qApp->arguments();
773 while(!args.isEmpty())
775 QString current = args.takeFirst();
778 bAddFile = (current.compare("--add", Qt::CaseInsensitive) == 0);
781 if((!current.startsWith("--")) && QFileInfo(current).exists() && QFileInfo(current).isFile())
783 files << QFileInfo(current).canonicalFilePath();
786 if(int totalFiles = files.count())
788 bool ok = true; int n = 0;
789 while((!files.isEmpty()) && ok)
791 QString currentFile = files.takeFirst();
792 qDebug("Adding file: %s", currentFile.toUtf8().constData());
793 /*TODO: Add multiple files!*/
794 //ok = createJob(currentFile, QString(), NULL, n++, totalFiles);
798 //Enable drag&drop support for this window, required for Qt v4.8.4+
799 setAcceptDrops(true);
803 * Update the label position
805 void MainWindow::updateLabelPos(void)
807 const QWidget *const viewPort = jobsView->viewport();
808 m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
812 * Copy the complete log to the clipboard
814 void MainWindow::copyLogToClipboard(bool checked)
816 qDebug("copyLogToClipboard");
818 if(LogFileModel *log = dynamic_cast<LogFileModel*>(logView->model()))
820 log->copyToClipboard();
821 MessageBeep(MB_ICONINFORMATION);
826 * Process the dropped files
828 void MainWindow::handleDroppedFiles(void)
830 qDebug("MainWindow::handleDroppedFiles");
833 QStringList droppedFiles(*m_droppedFiles);
834 m_droppedFiles->clear();
836 int totalFiles = droppedFiles.count();
837 bool ok = true; int n = 0;
838 while((!droppedFiles.isEmpty()) && ok)
840 QString currentFile = droppedFiles.takeFirst();
841 qDebug("Adding file: %s", currentFile.toUtf8().constData());
842 ok = createJob(currentFile, QString(), NULL, n++, totalFiles);
845 //createJobMultiple(droppedFiles);
847 qDebug("Leave from MainWindow::handleDroppedFiles!");
850 void MainWindow::instanceCreated(DWORD pid)
852 qDebug("Notification from other instance (PID=0x%X) received!", pid);
854 FLASHWINFO flashWinInfo;
855 memset(&flashWinInfo, 0, sizeof(FLASHWINFO));
856 flashWinInfo.cbSize = sizeof(FLASHWINFO);
857 flashWinInfo.hwnd = this->winId();
858 flashWinInfo.dwFlags = FLASHW_ALL;
859 flashWinInfo.dwTimeout = 125;
860 flashWinInfo.uCount = 5;
862 SwitchToThisWindow(this->winId(), TRUE);
863 SetForegroundWindow(this->winId());
864 qApp->processEvents();
865 FlashWindowEx(&flashWinInfo);
868 ///////////////////////////////////////////////////////////////////////////////
870 ///////////////////////////////////////////////////////////////////////////////
875 void MainWindow::showEvent(QShowEvent *e)
877 QMainWindow::showEvent(e);
882 QTimer::singleShot(0, this, SLOT(init()));
889 void MainWindow::closeEvent(QCloseEvent *e)
891 if(countRunningJobs() > 0)
894 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
898 if(countPendingJobs() > 0)
900 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);
901 if(ret != QMessageBox::Yes)
908 while(m_jobList->rowCount(QModelIndex()) > 0)
910 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
911 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
914 QMessageBox::warning(this, tr("Failed To Exit"), tr("Sorry, at least one job could not be deleted!"));
919 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
920 QMainWindow::closeEvent(e);
924 * Window resize event
926 void MainWindow::resizeEvent(QResizeEvent *e)
928 QMainWindow::resizeEvent(e);
935 bool MainWindow::eventFilter(QObject *o, QEvent *e)
937 if((o == labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
939 QTimer::singleShot(0, this, SLOT(showAbout()));
946 * Win32 message filter
948 bool MainWindow::winEvent(MSG *message, long *result)
950 return WinSevenTaskbar::handleWinEvent(message, result);
954 * File dragged over window
956 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
958 bool accept[2] = {false, false};
960 foreach(const QString &fmt, event->mimeData()->formats())
962 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
963 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
966 if(accept[0] && accept[1])
968 event->acceptProposedAction();
973 * File dropped onto window
975 void MainWindow::dropEvent(QDropEvent *event)
977 QStringList droppedFiles;
978 QList<QUrl> urls = event->mimeData()->urls();
980 while(!urls.isEmpty())
982 QUrl currentUrl = urls.takeFirst();
983 QFileInfo file(currentUrl.toLocalFile());
984 if(file.exists() && file.isFile())
986 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
987 droppedFiles << file.canonicalFilePath();
991 if(droppedFiles.count() > 0)
995 m_droppedFiles = new QStringList();
997 m_droppedFiles->append(droppedFiles);
998 m_droppedFiles->sort();
999 QTimer::singleShot(0, this, SLOT(handleDroppedFiles()));
1003 ///////////////////////////////////////////////////////////////////////////////
1004 // Private functions
1005 ///////////////////////////////////////////////////////////////////////////////
1010 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1013 AddJobDialog *addDialog = new AddJobDialog(this, options, m_cpuFeatures->x64, m_preferences.use10BitEncoding, m_preferences.saveToSourcePath);
1015 addDialog->setRunImmediately(runImmediately);
1016 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1017 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1018 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1020 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1023 addDialog->setSourceEditable(false);
1024 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1025 addDialog->setApplyToAllVisible(applyToAll);
1028 if(addDialog->exec() == QDialog::Accepted)
1030 sourceFileName = addDialog->sourceFile();
1031 outputFileName = addDialog->outputFile();
1032 runImmediately = addDialog->runImmediately();
1035 *applyToAll = addDialog->applyToAll();
1040 X264_DELETE(addDialog);
1047 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1051 EncodeThread *thrd = new EncodeThread
1056 QString("%1/toolset").arg(m_appDir),
1058 m_preferences.use10BitEncoding,
1059 m_cpuFeatures->x64 && m_preferences.useAvisyth64Bit
1062 QModelIndex newIndex = m_jobList->insertJob(thrd);
1064 if(newIndex.isValid())
1068 jobsView->selectRow(newIndex.row());
1069 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1070 m_jobList->startJob(newIndex);
1076 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1083 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1085 //bool ok = true, force = false; int counter = 0;
1088 //QStringList::ConstIterator iter = filePathIn.constBegin();
1089 //while(ok && (!force) && (iter != filePathIn.constEnd()))
1091 // ok = createJob(*iter, QString(), NULL, ++counter, filePathIn.count(), &force);
1095 //if(force) qWarning("Force mode!");
1097 ////Add remaining files
1098 //if(force && (iter != filePathIn.constEnd()))
1100 // QSettings settings(QString("%1/last.ini").arg(x264_data_path()), QSettings::IniFormat);
1101 // QString outDirectory = settings.value("path/directory_saveTo", QDesktopServices::storageLocation(QDesktopServices::MoviesLocation)).toString();
1103 // while(iter != filePathIn.constEnd())
1106 // QString outBaseName = QFileInfo(*iter).completeBaseName();
1107 // QString outPath = QString("%1/%2.mkv").arg(outDirectory, outBaseName);
1108 // while(QFileInfo(outPath).exists())
1110 // outPath = QString("%1/%2 (%3).mkv").arg(outDirectory, outBaseName, QString::number(n++));
1112 // ok = createJob(*iter, outPath, NULL, ++counter, filePathIn.count(), &force);
1123 * Jobs that are not completed (or failed, or aborted) yet
1125 unsigned int MainWindow::countPendingJobs(void)
1127 unsigned int count = 0;
1128 const int rows = m_jobList->rowCount(QModelIndex());
1130 for(int i = 0; i < rows; i++)
1132 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1133 if(status != EncodeThread::JobStatus_Completed && status != EncodeThread::JobStatus_Aborted && status != EncodeThread::JobStatus_Failed)
1143 * Jobs that are still active, i.e. not terminated or enqueued
1145 unsigned int MainWindow::countRunningJobs(void)
1147 unsigned int count = 0;
1148 const int rows = m_jobList->rowCount(QModelIndex());
1150 for(int i = 0; i < rows; i++)
1152 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1153 if(status != EncodeThread::JobStatus_Completed && status != EncodeThread::JobStatus_Aborted && status != EncodeThread::JobStatus_Failed && status != EncodeThread::JobStatus_Enqueued)
1163 * Update all buttons with respect to current job status
1165 void MainWindow::updateButtons(EncodeThread::JobStatus status)
1167 qDebug("MainWindow::updateButtons(void)");
1169 buttonStartJob->setEnabled(status == EncodeThread::JobStatus_Enqueued);
1170 buttonAbortJob->setEnabled(status == EncodeThread::JobStatus_Indexing || status == EncodeThread::JobStatus_Running || status == EncodeThread::JobStatus_Running_Pass1 || status == EncodeThread::JobStatus_Running_Pass2 || status == EncodeThread::JobStatus_Paused);
1171 buttonPauseJob->setEnabled(status == EncodeThread::JobStatus_Indexing || status == EncodeThread::JobStatus_Running || status == EncodeThread::JobStatus_Paused || status == EncodeThread::JobStatus_Running_Pass1 || status == EncodeThread::JobStatus_Running_Pass2);
1172 buttonPauseJob->setChecked(status == EncodeThread::JobStatus_Paused || status == EncodeThread::JobStatus_Pausing);
1174 actionJob_Delete->setEnabled(status == EncodeThread::JobStatus_Completed || status == EncodeThread::JobStatus_Aborted || status == EncodeThread::JobStatus_Failed || status == EncodeThread::JobStatus_Enqueued);
1175 actionJob_Restart->setEnabled(status == EncodeThread::JobStatus_Completed || status == EncodeThread::JobStatus_Aborted || status == EncodeThread::JobStatus_Failed || status == EncodeThread::JobStatus_Enqueued);
1176 actionJob_Browse->setEnabled(status == EncodeThread::JobStatus_Completed);
1178 actionJob_Start->setEnabled(buttonStartJob->isEnabled());
1179 actionJob_Abort->setEnabled(buttonAbortJob->isEnabled());
1180 actionJob_Pause->setEnabled(buttonPauseJob->isEnabled());
1181 actionJob_Pause->setChecked(buttonPauseJob->isChecked());
1183 editDetails->setEnabled(status != EncodeThread::JobStatus_Paused);
1187 * Update the taskbar with current job status
1189 void MainWindow::updateTaskbar(EncodeThread::JobStatus status, const QIcon &icon)
1191 qDebug("MainWindow::updateTaskbar(void)");
1195 case EncodeThread::JobStatus_Undefined:
1196 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1198 case EncodeThread::JobStatus_Aborting:
1199 case EncodeThread::JobStatus_Starting:
1200 case EncodeThread::JobStatus_Pausing:
1201 case EncodeThread::JobStatus_Resuming:
1202 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1204 case EncodeThread::JobStatus_Aborted:
1205 case EncodeThread::JobStatus_Failed:
1206 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1208 case EncodeThread::JobStatus_Paused:
1209 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1212 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1218 case EncodeThread::JobStatus_Aborting:
1219 case EncodeThread::JobStatus_Starting:
1220 case EncodeThread::JobStatus_Pausing:
1221 case EncodeThread::JobStatus_Resuming:
1224 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
1228 WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);