1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2013 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 "model_preferences.h"
27 #include "model_recently.h"
28 #include "thread_avisynth.h"
30 #include "win_addJob.h"
31 #include "win_preferences.h"
36 #include <QCloseEvent>
37 #include <QMessageBox>
38 #include <QDesktopServices>
43 #include <QProgressDialog>
45 #include <QTextStream>
47 #include <QFileDialog>
51 const char *home_url = "http://muldersoft.com/";
52 const char *update_url = "http://code.google.com/p/mulder/downloads/list";
53 const char *tpl_last = "<LAST_USED>";
55 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
56 #define SET_TEXT_COLOR(WIDGET,COLOR) { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); }
58 static int exceptionFilter(_EXCEPTION_RECORD *dst, _EXCEPTION_POINTERS *src) { memcpy(dst, src->ExceptionRecord, sizeof(_EXCEPTION_RECORD)); return EXCEPTION_EXECUTE_HANDLER; }
60 ///////////////////////////////////////////////////////////////////////////////
61 // Constructor & Destructor
62 ///////////////////////////////////////////////////////////////////////////////
67 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures)
69 m_cpuFeatures(cpuFeatures),
70 m_appDir(QApplication::applicationDirPath()),
78 //Init the dialog, from the .ui file
80 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
83 qRegisterMetaType<QUuid>("QUuid");
84 qRegisterMetaType<QUuid>("DWORD");
85 qRegisterMetaType<EncodeThread::JobStatus>("EncodeThread::JobStatus");
88 m_preferences = new PreferencesModel();
89 PreferencesModel::loadPreferences(m_preferences);
92 m_recentlyUsed = new RecentlyUsed();
93 RecentlyUsed::loadRecentlyUsed(m_recentlyUsed);
95 //Create options object
96 m_options = new OptionsModel();
97 OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
99 //Create IPC thread object
100 m_ipcThread = new IPCThread();
101 connect(m_ipcThread, SIGNAL(instanceCreated(DWORD)), this, SLOT(instanceCreated(DWORD)), Qt::QueuedConnection);
103 //Freeze minimum size
104 setMinimumSize(size());
105 splitter->setSizes(QList<int>() << 16 << 196);
108 labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
109 labelBuildDate->installEventFilter(this);
110 setWindowTitle(QString("%1 (%2 Mode)").arg(windowTitle(), m_cpuFeatures->x64 ? "64-Bit" : "32-Bit"));
113 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
114 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
116 else if(x264_is_prerelease())
118 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
122 m_jobList = new JobListModel(m_preferences);
123 connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
124 jobsView->setModel(m_jobList);
127 jobsView->horizontalHeader()->setSectionHidden(3, true);
128 jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
129 jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
130 jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
131 jobsView->horizontalHeader()->resizeSection(1, 150);
132 jobsView->horizontalHeader()->resizeSection(2, 90);
133 jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
134 connect(jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
136 //Create context menu
137 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), logView);
138 actionClipboard->setEnabled(false);
139 logView->addAction(actionClipboard);
140 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
141 jobsView->addActions(menuJob->actions());
144 connect(buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed()));
145 connect(buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed()));
146 connect(buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed()));
147 connect(buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
148 connect(actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed()));
149 connect(actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed()));
150 connect(actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed()));
153 connect(actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
154 connect(actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
155 connect(actionWebMulder, SIGNAL(triggered()), this, SLOT(showWebLink()));
156 connect(actionWebX264, SIGNAL(triggered()), this, SLOT(showWebLink()));
157 connect(actionWebKomisar, SIGNAL(triggered()), this, SLOT(showWebLink()));
158 connect(actionWebJarod, SIGNAL(triggered()), this, SLOT(showWebLink()));
159 connect(actionWebJEEB, SIGNAL(triggered()), this, SLOT(showWebLink()));
160 connect(actionWebAvisynth32, SIGNAL(triggered()), this, SLOT(showWebLink()));
161 connect(actionWebAvisynth64, SIGNAL(triggered()), this, SLOT(showWebLink()));
162 connect(actionWebWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
163 connect(actionWebBluRay, SIGNAL(triggered()), this, SLOT(showWebLink()));
164 connect(actionWebAvsWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
165 connect(actionWebSecret, SIGNAL(triggered()), this, SLOT(showWebLink()));
166 connect(actionWebSupport, SIGNAL(triggered()), this, SLOT(showWebLink()));
167 connect(actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
169 //Create floating label
170 m_label = new QLabel(jobsView->viewport());
171 m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
172 m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
173 SET_TEXT_COLOR(m_label, Qt::darkGray);
174 SET_FONT_BOLD(m_label, true);
175 m_label->setVisible(true);
176 m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
177 m_label->addActions(jobsView->actions());
178 connect(splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
185 MainWindow::~MainWindow(void)
187 OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
189 X264_DELETE(m_jobList);
190 X264_DELETE(m_options);
191 X264_DELETE(m_droppedFiles);
192 X264_DELETE(m_label);
194 while(!m_toolsList.isEmpty())
196 QFile *temp = m_toolsList.takeFirst();
200 if(m_ipcThread->isRunning())
202 m_ipcThread->setAbort();
203 if(!m_ipcThread->wait(5000))
205 m_ipcThread->terminate();
210 X264_DELETE(m_ipcThread);
211 AvisynthCheckThread::unload();
212 X264_DELETE(m_preferences);
213 X264_DELETE(m_recentlyUsed);
216 ///////////////////////////////////////////////////////////////////////////////
218 ///////////////////////////////////////////////////////////////////////////////
221 * The "add" button was clicked
223 void MainWindow::addButtonPressed()
225 qDebug("MainWindow::addButtonPressed");
226 bool runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
227 QString sourceFileName, outputFileName;
229 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
231 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
236 * The "open" action was triggered
238 void MainWindow::openActionTriggered()
240 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
241 if(!fileList.empty())
243 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
244 if(fileList.count() > 1)
246 createJobMultiple(fileList);
250 bool runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
251 QString sourceFileName(fileList.first()), outputFileName;
252 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
254 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
261 * The "start" button was clicked
263 void MainWindow::startButtonPressed(void)
265 m_jobList->startJob(jobsView->currentIndex());
269 * The "abort" button was clicked
271 void MainWindow::abortButtonPressed(void)
273 m_jobList->abortJob(jobsView->currentIndex());
277 * The "delete" button was clicked
279 void MainWindow::deleteButtonPressed(void)
281 m_jobList->deleteJob(jobsView->currentIndex());
282 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
286 * The "browse" button was clicked
288 void MainWindow::browseButtonPressed(void)
290 QString outputFile = m_jobList->getJobOutputFile(jobsView->currentIndex());
291 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
293 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
297 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
302 * The "pause" button was clicked
304 void MainWindow::pauseButtonPressed(bool checked)
308 m_jobList->pauseJob(jobsView->currentIndex());
312 m_jobList->resumeJob(jobsView->currentIndex());
317 * The "restart" button was clicked
319 void MainWindow::restartButtonPressed(void)
321 const QModelIndex index = jobsView->currentIndex();
322 const OptionsModel *options = m_jobList->getJobOptions(index);
323 QString sourceFileName = m_jobList->getJobSourceFile(index);
324 QString outputFileName = m_jobList->getJobOutputFile(index);
326 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
328 bool runImmediately = true;
329 OptionsModel *tempOptions = new OptionsModel(*options);
330 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
332 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
334 X264_DELETE(tempOptions);
339 * Job item selected by user
341 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
343 qDebug("Job selected: %d", current.row());
347 disconnect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
350 if(current.isValid())
352 logView->setModel(m_jobList->getLogFile(current));
353 connect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
354 logView->actions().first()->setEnabled(true);
355 QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
357 progressBar->setValue(m_jobList->getJobProgress(current));
358 editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
359 updateButtons(m_jobList->getJobStatus(current));
360 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
364 logView->setModel(NULL);
365 logView->actions().first()->setEnabled(false);
366 progressBar->setValue(0);
367 editDetails->clear();
368 updateButtons(EncodeThread::JobStatus_Undefined);
369 updateTaskbar(EncodeThread::JobStatus_Undefined, QIcon());
372 progressBar->repaint();
376 * Handle update of job info (status, progress, details, etc)
378 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
380 int selected = jobsView->currentIndex().row();
382 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
384 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
386 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
389 qDebug("Current job changed status!");
390 updateButtons(status);
391 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
393 if((status == EncodeThread::JobStatus_Completed) || (status == EncodeThread::JobStatus_Failed))
395 if(m_preferences->autoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
396 if(m_preferences->shutdownComputer()) QTimer::singleShot(0, this, SLOT(shutdownComputer()));
397 if(m_preferences->saveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
401 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
403 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
407 progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
408 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
413 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
415 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
419 editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
427 * Handle new log file content
429 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
431 QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
437 void MainWindow::showAbout(void)
441 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());
442 text += QString().sprintf("Copyright (c) 2004-%04d LoRd_MuldeR <mulder2@gmx.de>. Some rights reserved.<br>", qMax(x264_version_date().year(),QDate::currentDate().year()));
443 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());
444 text += QString().sprintf("This program is free software: you can redistribute it and/or modify<br>");
445 text += QString().sprintf("it under the terms of the GNU General Public License <http://www.gnu.org/>.<br>");
446 text += QString().sprintf("Note that this program is distributed with ABSOLUTELY NO WARRANTY.<br><br>");
447 text += QString().sprintf("Please check the web-site at <a href=\"%s\">%s</a> for updates !!!<br></tt></nobr>", home_url, home_url);
449 QMessageBox aboutBox(this);
450 aboutBox.setIconPixmap(QIcon(":/images/movie.png").pixmap(64,64));
451 aboutBox.setWindowTitle(tr("About..."));
452 aboutBox.setText(text.replace("-", "−"));
453 aboutBox.addButton(tr("About x264"), QMessageBox::NoRole);
454 aboutBox.addButton(tr("About AVS"), QMessageBox::NoRole);
455 aboutBox.addButton(tr("About Qt"), QMessageBox::NoRole);
456 aboutBox.setEscapeButton(aboutBox.addButton(tr("Close"), QMessageBox::NoRole));
460 MessageBeep(MB_ICONINFORMATION);
461 switch(aboutBox.exec())
466 text2 += tr("<nobr><tt>x264 - the best H.264/AVC encoder. Copyright (c) 2003-2013 x264 project.<br>");
467 text2 += tr("Free software library for encoding video streams into the H.264/MPEG-4 AVC format.<br>");
468 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
469 text2 += tr("Please visit <a href=\"%1\">%1</a> for obtaining a commercial x264 license.<br>").arg("http://x264licensing.com/");
470 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");
472 QMessageBox x264Box(this);
473 x264Box.setIconPixmap(QIcon(":/images/x264.png").pixmap(48,48));
474 x264Box.setWindowTitle(tr("About x264"));
475 x264Box.setText(text2.replace("-", "−"));
476 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
477 MessageBeep(MB_ICONINFORMATION);
484 text2 += tr("<nobr><tt>Avisynth - powerful video processing scripting language.<br>");
485 text2 += tr("Copyright (c) 2000 Ben Rudiak-Gould and all subsequent developers.<br>");
486 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
487 text2 += tr("Please visit the web-site <a href=\"%1\">%1</a> for more information.<br>").arg("http://avisynth.org/");
488 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");
490 QMessageBox x264Box(this);
491 x264Box.setIconPixmap(QIcon(":/images/avisynth.png").pixmap(48,67));
492 x264Box.setWindowTitle(tr("About Avisynth"));
493 x264Box.setText(text2.replace("-", "−"));
494 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
495 MessageBeep(MB_ICONINFORMATION);
500 QMessageBox::aboutQt(this);
511 void MainWindow::showWebLink(void)
513 if(QObject::sender() == actionWebMulder) QDesktopServices::openUrl(QUrl(home_url));
514 if(QObject::sender() == actionWebX264) QDesktopServices::openUrl(QUrl("http://www.x264.com/"));
515 if(QObject::sender() == actionWebKomisar) QDesktopServices::openUrl(QUrl("http://komisar.gin.by/"));
516 if(QObject::sender() == actionWebJarod) QDesktopServices::openUrl(QUrl("http://www.x264.nl/"));
517 if(QObject::sender() == actionWebJEEB) QDesktopServices::openUrl(QUrl("http://x264.fushizen.eu/"));
518 if(QObject::sender() == actionWebAvisynth32) QDesktopServices::openUrl(QUrl("http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/"));
519 if(QObject::sender() == actionWebAvisynth64) QDesktopServices::openUrl(QUrl("http://code.google.com/p/avisynth64/downloads/list"));
520 if(QObject::sender() == actionWebWiki) QDesktopServices::openUrl(QUrl("http://mewiki.project357.com/wiki/X264_Settings"));
521 if(QObject::sender() == actionWebBluRay) QDesktopServices::openUrl(QUrl("http://www.x264bluray.com/"));
522 if(QObject::sender() == actionWebAvsWiki) QDesktopServices::openUrl(QUrl("http://avisynth.org/mediawiki/Main_Page#Usage"));
523 if(QObject::sender() == actionWebSupport) QDesktopServices::openUrl(QUrl("http://forum.doom9.org/showthread.php?t=144140"));
524 if(QObject::sender() == actionWebSecret) QDesktopServices::openUrl(QUrl("http://www.youtube.com/watch_popup?v=AXIeHY-OYNI"));
528 * Pereferences dialog
530 void MainWindow::showPreferences(void)
532 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences, m_cpuFeatures->x64);
534 X264_DELETE(preferences);
538 * Launch next job, after running job has finished
540 void MainWindow::launchNextJob(void)
542 qDebug("launchNextJob(void)");
544 const int rows = m_jobList->rowCount(QModelIndex());
546 if(countRunningJobs() >= m_preferences->maxRunningJobCount())
548 qDebug("Still have too many jobs running, won't launch next one yet!");
552 int startIdx= jobsView->currentIndex().isValid() ? qBound(0, jobsView->currentIndex().row(), rows-1) : 0;
554 for(int i = 0; i < rows; i++)
556 int currentIdx = (i + startIdx) % rows;
557 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
558 if(status == EncodeThread::JobStatus_Enqueued)
560 if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
562 jobsView->selectRow(currentIdx);
568 qWarning("No enqueued jobs left!");
572 * Save log to text file
574 void MainWindow::saveLogFile(const QModelIndex &index)
578 if(LogFileModel *log = m_jobList->getLogFile(index))
580 QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
581 QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
582 QFile outFile(logFilePath);
583 if(outFile.open(QIODevice::WriteOnly))
585 QTextStream outStream(&outFile);
586 outStream.setCodec("UTF-8");
587 outStream.setGenerateByteOrderMark(true);
589 const int rows = log->rowCount(QModelIndex());
590 for(int i = 0; i < rows; i++)
592 outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
598 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
605 * Shut down the computer (with countdown)
607 void MainWindow::shutdownComputer(void)
609 qDebug("shutdownComputer(void)");
611 if(countPendingJobs() > 0)
613 qDebug("Still have pending jobs, won't shutdown yet!");
617 const int iTimeout = 30;
618 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
619 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
621 qWarning("Initiating shutdown sequence!");
623 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
624 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
625 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
626 progressDialog.setModal(true);
627 progressDialog.setAutoClose(false);
628 progressDialog.setAutoReset(false);
629 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
630 progressDialog.setWindowTitle(windowTitle());
631 progressDialog.setCancelButton(cancelButton);
632 progressDialog.show();
634 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
635 QApplication::setOverrideCursor(Qt::WaitCursor);
636 PlaySound(MAKEINTRESOURCE(IDR_WAVE1), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
637 QApplication::restoreOverrideCursor();
640 timer.setInterval(1000);
643 QEventLoop eventLoop(this);
644 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
645 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
647 for(int i = 1; i <= iTimeout; i++)
650 if(progressDialog.wasCanceled())
652 progressDialog.close();
655 progressDialog.setValue(i+1);
656 progressDialog.setLabelText(text.arg(iTimeout-i));
657 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
658 QApplication::processEvents();
659 PlaySound(MAKEINTRESOURCE((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
662 qWarning("Shutting down !!!");
664 if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
666 qApp->closeAllWindows();
671 * Main initialization function (called only once!)
673 void MainWindow::init(void)
675 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";
676 QStringList binaries = QString::fromLatin1(binFiles).split(":", QString::SkipEmptyParts);
680 //Check for a running instance
681 bool firstInstance = false;
682 if(m_ipcThread->initialize(&firstInstance))
684 m_ipcThread->start();
687 if(!m_ipcThread->wait(5000))
689 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"));
690 m_ipcThread->terminate();
693 close(); qApp->exit(-1); return;
698 while(!binaries.isEmpty())
700 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
701 QString current = binaries.takeFirst();
702 QFile *file = new QFile(QString("%1/toolset/%2").arg(m_appDir, current));
703 if(file->open(QIODevice::ReadOnly))
705 bool binaryTypeOkay = false;
707 if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(file->fileName())), &binaryType))
709 binaryTypeOkay = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
713 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("-", "−"));
714 qFatal(QString("Binary is invalid: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
715 close(); qApp->exit(-1); return;
722 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("-", "−"));
723 qFatal(QString("Binary not found: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
724 close(); qApp->exit(-1); return;
728 //Check for portable mode
732 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
733 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
734 if(writeTest.open(QIODevice::WriteOnly))
736 ok = (writeTest.write(data) == strlen(data));
741 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"));
742 if(val != 1) { close(); qApp->exit(-1); return; }
747 if(x264_is_prerelease())
749 qsrand(time(NULL)); int rnd = qrand() % 3;
750 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);
751 if(rnd != val) { close(); qApp->exit(-1); return; }
754 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
755 if(!(m_cpuFeatures->mmx && m_cpuFeatures->mmx2))
757 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"));
758 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
759 close(); qApp->exit(-1); return;
761 else if(!(m_cpuFeatures->mmx && m_cpuFeatures->sse))
763 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
764 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"));
765 if(val != 1) { close(); qApp->exit(-1); return; }
768 //Check for Avisynth support
769 if(!qApp->arguments().contains("--skip-avisynth-check", Qt::CaseInsensitive))
771 qDebug("[Check for Avisynth support]");
772 volatile double avisynthVersion = 0.0;
773 const int result = AvisynthCheckThread::detect(&avisynthVersion);
776 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
777 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
778 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
779 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
780 if(val != 1) { close(); qApp->exit(-1); return; }
782 if((!result) || (avisynthVersion < 2.5))
784 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"));
785 if(val != 1) { close(); qApp->exit(-1); return; }
790 //Check for expiration
791 if(x264_version_date().addMonths(6) < QDate::currentDate())
793 QMessageBox msgBox(this);
794 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
795 msgBox.setWindowTitle(tr("Update Notification"));
796 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
797 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));
798 QPushButton *btn1 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
799 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::AcceptRole);
800 btn1->setEnabled(false);
801 btn2->setVisible(false);
802 QTimer::singleShot(5000, btn1, SLOT(hide()));
803 QTimer::singleShot(5000, btn2, SLOT(show()));
807 //Add files from command-line
808 bool bAddFile = false;
809 QStringList files, args = qApp->arguments();
810 while(!args.isEmpty())
812 QString current = args.takeFirst();
815 bAddFile = (current.compare("--add", Qt::CaseInsensitive) == 0);
818 if((!current.startsWith("--")) && QFileInfo(current).exists() && QFileInfo(current).isFile())
820 files << QFileInfo(current).canonicalFilePath();
823 if(files.count() > 0)
825 createJobMultiple(files);
828 //Enable drag&drop support for this window, required for Qt v4.8.4+
829 setAcceptDrops(true);
833 * Update the label position
835 void MainWindow::updateLabelPos(void)
837 const QWidget *const viewPort = jobsView->viewport();
838 m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
842 * Copy the complete log to the clipboard
844 void MainWindow::copyLogToClipboard(bool checked)
846 qDebug("copyLogToClipboard");
848 if(LogFileModel *log = dynamic_cast<LogFileModel*>(logView->model()))
850 log->copyToClipboard();
851 MessageBeep(MB_ICONINFORMATION);
856 * Process the dropped files
858 void MainWindow::handleDroppedFiles(void)
860 qDebug("MainWindow::handleDroppedFiles");
863 QStringList droppedFiles(*m_droppedFiles);
864 m_droppedFiles->clear();
865 createJobMultiple(droppedFiles);
867 qDebug("Leave from MainWindow::handleDroppedFiles!");
870 void MainWindow::instanceCreated(DWORD pid)
872 qDebug("Notification from other instance (PID=0x%X) received!", pid);
874 FLASHWINFO flashWinInfo;
875 memset(&flashWinInfo, 0, sizeof(FLASHWINFO));
876 flashWinInfo.cbSize = sizeof(FLASHWINFO);
877 flashWinInfo.hwnd = this->winId();
878 flashWinInfo.dwFlags = FLASHW_ALL;
879 flashWinInfo.dwTimeout = 125;
880 flashWinInfo.uCount = 5;
882 SwitchToThisWindow(this->winId(), TRUE);
883 SetForegroundWindow(this->winId());
884 qApp->processEvents();
885 FlashWindowEx(&flashWinInfo);
888 ///////////////////////////////////////////////////////////////////////////////
890 ///////////////////////////////////////////////////////////////////////////////
895 void MainWindow::showEvent(QShowEvent *e)
897 QMainWindow::showEvent(e);
902 QTimer::singleShot(0, this, SLOT(init()));
909 void MainWindow::closeEvent(QCloseEvent *e)
911 if(countRunningJobs() > 0)
914 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
918 if(countPendingJobs() > 0)
920 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);
921 if(ret != QMessageBox::Yes)
928 while(m_jobList->rowCount(QModelIndex()) > 0)
930 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
931 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
934 QMessageBox::warning(this, tr("Failed To Exit"), tr("Sorry, at least one job could not be deleted!"));
939 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
940 QMainWindow::closeEvent(e);
944 * Window resize event
946 void MainWindow::resizeEvent(QResizeEvent *e)
948 QMainWindow::resizeEvent(e);
955 bool MainWindow::eventFilter(QObject *o, QEvent *e)
957 if((o == labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
959 QTimer::singleShot(0, this, SLOT(showAbout()));
966 * Win32 message filter
968 bool MainWindow::winEvent(MSG *message, long *result)
970 return WinSevenTaskbar::handleWinEvent(message, result);
974 * File dragged over window
976 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
978 bool accept[2] = {false, false};
980 foreach(const QString &fmt, event->mimeData()->formats())
982 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
983 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
986 if(accept[0] && accept[1])
988 event->acceptProposedAction();
993 * File dropped onto window
995 void MainWindow::dropEvent(QDropEvent *event)
997 QStringList droppedFiles;
998 QList<QUrl> urls = event->mimeData()->urls();
1000 while(!urls.isEmpty())
1002 QUrl currentUrl = urls.takeFirst();
1003 QFileInfo file(currentUrl.toLocalFile());
1004 if(file.exists() && file.isFile())
1006 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1007 droppedFiles << file.canonicalFilePath();
1011 if(droppedFiles.count() > 0)
1015 m_droppedFiles = new QStringList();
1017 m_droppedFiles->append(droppedFiles);
1018 m_droppedFiles->sort();
1019 QTimer::singleShot(0, this, SLOT(handleDroppedFiles()));
1023 ///////////////////////////////////////////////////////////////////////////////
1024 // Private functions
1025 ///////////////////////////////////////////////////////////////////////////////
1030 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1033 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed, m_cpuFeatures->x64, m_preferences->use10BitEncoding(), m_preferences->saveToSourcePath());
1035 addDialog->setRunImmediately(runImmediately);
1036 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1037 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1038 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1040 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1043 addDialog->setSourceEditable(false);
1044 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1045 addDialog->setApplyToAllVisible(applyToAll);
1048 if(addDialog->exec() == QDialog::Accepted)
1050 sourceFileName = addDialog->sourceFile();
1051 outputFileName = addDialog->outputFile();
1052 runImmediately = addDialog->runImmediately();
1055 *applyToAll = addDialog->applyToAll();
1060 X264_DELETE(addDialog);
1065 * Creates a new job from *multiple* files
1067 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1069 QStringList::ConstIterator iter;
1070 bool applyToAll = false, runImmediately = false;
1073 //Add files individually
1074 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1076 runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
1077 QString sourceFileName(*iter), outputFileName;
1078 if(createJob(sourceFileName, outputFileName, m_options, runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1080 if(appendJob(sourceFileName, outputFileName, m_options, runImmediately))
1088 //Add remaining files
1089 while(applyToAll && (iter != filePathIn.constEnd()))
1091 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
1092 const QString sourceFileName = *iter;
1093 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->saveToSourcePath());
1094 if(!appendJob(sourceFileName, outputFileName, m_options, runImmediatelyTmp))
1108 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1112 EncodeThread *thrd = new EncodeThread
1117 QString("%1/toolset").arg(m_appDir),
1119 m_preferences->use10BitEncoding(),
1120 m_cpuFeatures->x64 && m_preferences->useAvisyth64Bit(),
1121 m_preferences->processPriority()
1124 QModelIndex newIndex = m_jobList->insertJob(thrd);
1126 if(newIndex.isValid())
1130 jobsView->selectRow(newIndex.row());
1131 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1132 m_jobList->startJob(newIndex);
1138 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1143 * Jobs that are not completed (or failed, or aborted) yet
1145 unsigned int MainWindow::countPendingJobs(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)
1163 * Jobs that are still active, i.e. not terminated or enqueued
1165 unsigned int MainWindow::countRunningJobs(void)
1167 unsigned int count = 0;
1168 const int rows = m_jobList->rowCount(QModelIndex());
1170 for(int i = 0; i < rows; i++)
1172 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1173 if(status != EncodeThread::JobStatus_Completed && status != EncodeThread::JobStatus_Aborted && status != EncodeThread::JobStatus_Failed && status != EncodeThread::JobStatus_Enqueued)
1183 * Update all buttons with respect to current job status
1185 void MainWindow::updateButtons(EncodeThread::JobStatus status)
1187 qDebug("MainWindow::updateButtons(void)");
1189 buttonStartJob->setEnabled(status == EncodeThread::JobStatus_Enqueued);
1190 buttonAbortJob->setEnabled(status == EncodeThread::JobStatus_Indexing || status == EncodeThread::JobStatus_Running || status == EncodeThread::JobStatus_Running_Pass1 || status == EncodeThread::JobStatus_Running_Pass2 || status == EncodeThread::JobStatus_Paused);
1191 buttonPauseJob->setEnabled(status == EncodeThread::JobStatus_Indexing || status == EncodeThread::JobStatus_Running || status == EncodeThread::JobStatus_Paused || status == EncodeThread::JobStatus_Running_Pass1 || status == EncodeThread::JobStatus_Running_Pass2);
1192 buttonPauseJob->setChecked(status == EncodeThread::JobStatus_Paused || status == EncodeThread::JobStatus_Pausing);
1194 actionJob_Delete->setEnabled(status == EncodeThread::JobStatus_Completed || status == EncodeThread::JobStatus_Aborted || status == EncodeThread::JobStatus_Failed || status == EncodeThread::JobStatus_Enqueued);
1195 actionJob_Restart->setEnabled(status == EncodeThread::JobStatus_Completed || status == EncodeThread::JobStatus_Aborted || status == EncodeThread::JobStatus_Failed || status == EncodeThread::JobStatus_Enqueued);
1196 actionJob_Browse->setEnabled(status == EncodeThread::JobStatus_Completed);
1198 actionJob_Start->setEnabled(buttonStartJob->isEnabled());
1199 actionJob_Abort->setEnabled(buttonAbortJob->isEnabled());
1200 actionJob_Pause->setEnabled(buttonPauseJob->isEnabled());
1201 actionJob_Pause->setChecked(buttonPauseJob->isChecked());
1203 editDetails->setEnabled(status != EncodeThread::JobStatus_Paused);
1207 * Update the taskbar with current job status
1209 void MainWindow::updateTaskbar(EncodeThread::JobStatus status, const QIcon &icon)
1211 qDebug("MainWindow::updateTaskbar(void)");
1215 case EncodeThread::JobStatus_Undefined:
1216 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1218 case EncodeThread::JobStatus_Aborting:
1219 case EncodeThread::JobStatus_Starting:
1220 case EncodeThread::JobStatus_Pausing:
1221 case EncodeThread::JobStatus_Resuming:
1222 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1224 case EncodeThread::JobStatus_Aborted:
1225 case EncodeThread::JobStatus_Failed:
1226 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1228 case EncodeThread::JobStatus_Paused:
1229 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1232 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1238 case EncodeThread::JobStatus_Aborting:
1239 case EncodeThread::JobStatus_Starting:
1240 case EncodeThread::JobStatus_Pausing:
1241 case EncodeThread::JobStatus_Resuming:
1244 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
1248 WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);