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"
29 #include "thread_ipc.h"
30 #include "thread_encode.h"
32 #include "win_addJob.h"
33 #include "win_preferences.h"
38 #include <QCloseEvent>
39 #include <QMessageBox>
40 #include <QDesktopServices>
45 #include <QProgressDialog>
47 #include <QTextStream>
49 #include <QFileDialog>
53 const char *home_url = "http://muldersoft.com/";
54 const char *update_url = "http://code.google.com/p/mulder/downloads/list";
55 const char *tpl_last = "<LAST_USED>";
57 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
58 #define SET_TEXT_COLOR(WIDGET,COLOR) { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); }
60 static int exceptionFilter(_EXCEPTION_RECORD *dst, _EXCEPTION_POINTERS *src) { memcpy(dst, src->ExceptionRecord, sizeof(_EXCEPTION_RECORD)); return EXCEPTION_EXECUTE_HANDLER; }
62 ///////////////////////////////////////////////////////////////////////////////
63 // Constructor & Destructor
64 ///////////////////////////////////////////////////////////////////////////////
69 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures)
71 m_cpuFeatures(cpuFeatures),
72 m_appDir(QApplication::applicationDirPath()),
80 //Init the dialog, from the .ui file
82 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
85 qRegisterMetaType<QUuid>("QUuid");
86 qRegisterMetaType<QUuid>("DWORD");
87 qRegisterMetaType<JobStatus>("EncodeThread::JobStatus");
90 m_preferences = new PreferencesModel();
91 PreferencesModel::loadPreferences(m_preferences);
94 m_recentlyUsed = new RecentlyUsed();
95 RecentlyUsed::loadRecentlyUsed(m_recentlyUsed);
97 //Create options object
98 m_options = new OptionsModel();
99 OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
101 //Create IPC thread object
102 m_ipcThread = new IPCThread();
103 connect(m_ipcThread, SIGNAL(instanceCreated(DWORD)), this, SLOT(instanceCreated(DWORD)), Qt::QueuedConnection);
105 //Freeze minimum size
106 setMinimumSize(size());
107 splitter->setSizes(QList<int>() << 16 << 196);
110 labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
111 labelBuildDate->installEventFilter(this);
112 setWindowTitle(QString("%1 (%2 Mode)").arg(windowTitle(), m_cpuFeatures->x64 ? "64-Bit" : "32-Bit"));
115 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
116 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
118 else if(x264_is_prerelease())
120 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
124 m_jobList = new JobListModel(m_preferences);
125 connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
126 jobsView->setModel(m_jobList);
129 jobsView->horizontalHeader()->setSectionHidden(3, true);
130 jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
131 jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
132 jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
133 jobsView->horizontalHeader()->resizeSection(1, 150);
134 jobsView->horizontalHeader()->resizeSection(2, 90);
135 jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
136 connect(jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
138 //Create context menu
139 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), logView);
140 actionClipboard->setEnabled(false);
141 logView->addAction(actionClipboard);
142 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
143 jobsView->addActions(menuJob->actions());
146 connect(buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed()));
147 connect(buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed()));
148 connect(buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed()));
149 connect(buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
150 connect(actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed()));
151 connect(actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed()));
152 connect(actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed()));
155 connect(actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
156 connect(actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
157 connect(actionWebMulder, SIGNAL(triggered()), this, SLOT(showWebLink()));
158 connect(actionWebX264, SIGNAL(triggered()), this, SLOT(showWebLink()));
159 connect(actionWebKomisar, SIGNAL(triggered()), this, SLOT(showWebLink()));
160 connect(actionWebJarod, SIGNAL(triggered()), this, SLOT(showWebLink()));
161 connect(actionWebJEEB, SIGNAL(triggered()), this, SLOT(showWebLink()));
162 connect(actionWebAvisynth32, SIGNAL(triggered()), this, SLOT(showWebLink()));
163 connect(actionWebAvisynth64, SIGNAL(triggered()), this, SLOT(showWebLink()));
164 connect(actionWebWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
165 connect(actionWebBluRay, SIGNAL(triggered()), this, SLOT(showWebLink()));
166 connect(actionWebAvsWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
167 connect(actionWebSecret, SIGNAL(triggered()), this, SLOT(showWebLink()));
168 connect(actionWebSupport, SIGNAL(triggered()), this, SLOT(showWebLink()));
169 connect(actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
171 //Create floating label
172 m_label = new QLabel(jobsView->viewport());
173 m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
174 m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
175 SET_TEXT_COLOR(m_label, Qt::darkGray);
176 SET_FONT_BOLD(m_label, true);
177 m_label->setVisible(true);
178 m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
179 m_label->addActions(jobsView->actions());
180 connect(splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
187 MainWindow::~MainWindow(void)
189 OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
191 X264_DELETE(m_jobList);
192 X264_DELETE(m_options);
193 X264_DELETE(m_droppedFiles);
194 X264_DELETE(m_label);
196 while(!m_toolsList.isEmpty())
198 QFile *temp = m_toolsList.takeFirst();
202 if(m_ipcThread->isRunning())
204 m_ipcThread->setAbort();
205 if(!m_ipcThread->wait(5000))
207 m_ipcThread->terminate();
212 X264_DELETE(m_ipcThread);
213 AvisynthCheckThread::unload();
214 X264_DELETE(m_preferences);
215 X264_DELETE(m_recentlyUsed);
218 ///////////////////////////////////////////////////////////////////////////////
220 ///////////////////////////////////////////////////////////////////////////////
223 * The "add" button was clicked
225 void MainWindow::addButtonPressed()
227 qDebug("MainWindow::addButtonPressed");
228 bool runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
229 QString sourceFileName, outputFileName;
231 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
233 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
238 * The "open" action was triggered
240 void MainWindow::openActionTriggered()
242 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
243 if(!fileList.empty())
245 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
246 if(fileList.count() > 1)
248 createJobMultiple(fileList);
252 bool runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
253 QString sourceFileName(fileList.first()), outputFileName;
254 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
256 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
263 * The "start" button was clicked
265 void MainWindow::startButtonPressed(void)
267 m_jobList->startJob(jobsView->currentIndex());
271 * The "abort" button was clicked
273 void MainWindow::abortButtonPressed(void)
275 m_jobList->abortJob(jobsView->currentIndex());
279 * The "delete" button was clicked
281 void MainWindow::deleteButtonPressed(void)
283 m_jobList->deleteJob(jobsView->currentIndex());
284 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
288 * The "browse" button was clicked
290 void MainWindow::browseButtonPressed(void)
292 QString outputFile = m_jobList->getJobOutputFile(jobsView->currentIndex());
293 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
295 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
299 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
304 * The "pause" button was clicked
306 void MainWindow::pauseButtonPressed(bool checked)
310 m_jobList->pauseJob(jobsView->currentIndex());
314 m_jobList->resumeJob(jobsView->currentIndex());
319 * The "restart" button was clicked
321 void MainWindow::restartButtonPressed(void)
323 const QModelIndex index = jobsView->currentIndex();
324 const OptionsModel *options = m_jobList->getJobOptions(index);
325 QString sourceFileName = m_jobList->getJobSourceFile(index);
326 QString outputFileName = m_jobList->getJobOutputFile(index);
328 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
330 bool runImmediately = true;
331 OptionsModel *tempOptions = new OptionsModel(*options);
332 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
334 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
336 X264_DELETE(tempOptions);
341 * Job item selected by user
343 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
345 qDebug("Job selected: %d", current.row());
349 disconnect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
352 if(current.isValid())
354 logView->setModel(m_jobList->getLogFile(current));
355 connect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
356 logView->actions().first()->setEnabled(true);
357 QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
359 progressBar->setValue(m_jobList->getJobProgress(current));
360 editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
361 updateButtons(m_jobList->getJobStatus(current));
362 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
366 logView->setModel(NULL);
367 logView->actions().first()->setEnabled(false);
368 progressBar->setValue(0);
369 editDetails->clear();
370 updateButtons(JobStatus_Undefined);
371 updateTaskbar(JobStatus_Undefined, QIcon());
374 progressBar->repaint();
378 * Handle update of job info (status, progress, details, etc)
380 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
382 int selected = jobsView->currentIndex().row();
384 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
386 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
388 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
391 qDebug("Current job changed status!");
392 updateButtons(status);
393 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
395 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
397 if(m_preferences->autoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
398 if(m_preferences->shutdownComputer()) QTimer::singleShot(0, this, SLOT(shutdownComputer()));
399 if(m_preferences->saveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
403 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
405 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
409 progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
410 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
415 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
417 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
421 editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
429 * Handle new log file content
431 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
433 QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
439 void MainWindow::showAbout(void)
443 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());
444 text += QString().sprintf("Copyright (c) 2004-%04d LoRd_MuldeR <mulder2@gmx.de>. Some rights reserved.<br>", qMax(x264_version_date().year(),QDate::currentDate().year()));
445 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());
446 text += QString().sprintf("This program is free software: you can redistribute it and/or modify<br>");
447 text += QString().sprintf("it under the terms of the GNU General Public License <http://www.gnu.org/>.<br>");
448 text += QString().sprintf("Note that this program is distributed with ABSOLUTELY NO WARRANTY.<br><br>");
449 text += QString().sprintf("Please check the web-site at <a href=\"%s\">%s</a> for updates !!!<br></tt></nobr>", home_url, home_url);
451 QMessageBox aboutBox(this);
452 aboutBox.setIconPixmap(QIcon(":/images/movie.png").pixmap(64,64));
453 aboutBox.setWindowTitle(tr("About..."));
454 aboutBox.setText(text.replace("-", "−"));
455 aboutBox.addButton(tr("About x264"), QMessageBox::NoRole);
456 aboutBox.addButton(tr("About AVS"), QMessageBox::NoRole);
457 aboutBox.addButton(tr("About Qt"), QMessageBox::NoRole);
458 aboutBox.setEscapeButton(aboutBox.addButton(tr("Close"), QMessageBox::NoRole));
462 MessageBeep(MB_ICONINFORMATION);
463 switch(aboutBox.exec())
468 text2 += tr("<nobr><tt>x264 - the best H.264/AVC encoder. Copyright (c) 2003-2013 x264 project.<br>");
469 text2 += tr("Free software library for encoding video streams into the H.264/MPEG-4 AVC format.<br>");
470 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
471 text2 += tr("Please visit <a href=\"%1\">%1</a> for obtaining a commercial x264 license.<br>").arg("http://x264licensing.com/");
472 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");
474 QMessageBox x264Box(this);
475 x264Box.setIconPixmap(QIcon(":/images/x264.png").pixmap(48,48));
476 x264Box.setWindowTitle(tr("About x264"));
477 x264Box.setText(text2.replace("-", "−"));
478 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
479 MessageBeep(MB_ICONINFORMATION);
486 text2 += tr("<nobr><tt>Avisynth - powerful video processing scripting language.<br>");
487 text2 += tr("Copyright (c) 2000 Ben Rudiak-Gould and all subsequent developers.<br>");
488 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
489 text2 += tr("Please visit the web-site <a href=\"%1\">%1</a> for more information.<br>").arg("http://avisynth.org/");
490 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");
492 QMessageBox x264Box(this);
493 x264Box.setIconPixmap(QIcon(":/images/avisynth.png").pixmap(48,67));
494 x264Box.setWindowTitle(tr("About Avisynth"));
495 x264Box.setText(text2.replace("-", "−"));
496 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
497 MessageBeep(MB_ICONINFORMATION);
502 QMessageBox::aboutQt(this);
513 void MainWindow::showWebLink(void)
515 if(QObject::sender() == actionWebMulder) QDesktopServices::openUrl(QUrl(home_url));
516 if(QObject::sender() == actionWebX264) QDesktopServices::openUrl(QUrl("http://www.x264.com/"));
517 if(QObject::sender() == actionWebKomisar) QDesktopServices::openUrl(QUrl("http://komisar.gin.by/"));
518 if(QObject::sender() == actionWebJarod) QDesktopServices::openUrl(QUrl("http://www.x264.nl/"));
519 if(QObject::sender() == actionWebJEEB) QDesktopServices::openUrl(QUrl("http://x264.fushizen.eu/"));
520 if(QObject::sender() == actionWebAvisynth32) QDesktopServices::openUrl(QUrl("http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/"));
521 if(QObject::sender() == actionWebAvisynth64) QDesktopServices::openUrl(QUrl("http://code.google.com/p/avisynth64/downloads/list"));
522 if(QObject::sender() == actionWebWiki) QDesktopServices::openUrl(QUrl("http://mewiki.project357.com/wiki/X264_Settings"));
523 if(QObject::sender() == actionWebBluRay) QDesktopServices::openUrl(QUrl("http://www.x264bluray.com/"));
524 if(QObject::sender() == actionWebAvsWiki) QDesktopServices::openUrl(QUrl("http://avisynth.org/mediawiki/Main_Page#Usage"));
525 if(QObject::sender() == actionWebSupport) QDesktopServices::openUrl(QUrl("http://forum.doom9.org/showthread.php?t=144140"));
526 if(QObject::sender() == actionWebSecret) QDesktopServices::openUrl(QUrl("http://www.youtube.com/watch_popup?v=AXIeHY-OYNI"));
530 * Pereferences dialog
532 void MainWindow::showPreferences(void)
534 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences, m_cpuFeatures->x64);
536 X264_DELETE(preferences);
540 * Launch next job, after running job has finished
542 void MainWindow::launchNextJob(void)
544 qDebug("launchNextJob(void)");
546 const int rows = m_jobList->rowCount(QModelIndex());
548 if(countRunningJobs() >= m_preferences->maxRunningJobCount())
550 qDebug("Still have too many jobs running, won't launch next one yet!");
554 int startIdx= jobsView->currentIndex().isValid() ? qBound(0, jobsView->currentIndex().row(), rows-1) : 0;
556 for(int i = 0; i < rows; i++)
558 int currentIdx = (i + startIdx) % rows;
559 JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
560 if(status == JobStatus_Enqueued)
562 if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
564 jobsView->selectRow(currentIdx);
570 qWarning("No enqueued jobs left!");
574 * Save log to text file
576 void MainWindow::saveLogFile(const QModelIndex &index)
580 if(LogFileModel *log = m_jobList->getLogFile(index))
582 QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
583 QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
584 QFile outFile(logFilePath);
585 if(outFile.open(QIODevice::WriteOnly))
587 QTextStream outStream(&outFile);
588 outStream.setCodec("UTF-8");
589 outStream.setGenerateByteOrderMark(true);
591 const int rows = log->rowCount(QModelIndex());
592 for(int i = 0; i < rows; i++)
594 outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
600 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
607 * Shut down the computer (with countdown)
609 void MainWindow::shutdownComputer(void)
611 qDebug("shutdownComputer(void)");
613 if(countPendingJobs() > 0)
615 qDebug("Still have pending jobs, won't shutdown yet!");
619 const int iTimeout = 30;
620 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
621 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
623 qWarning("Initiating shutdown sequence!");
625 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
626 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
627 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
628 progressDialog.setModal(true);
629 progressDialog.setAutoClose(false);
630 progressDialog.setAutoReset(false);
631 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
632 progressDialog.setWindowTitle(windowTitle());
633 progressDialog.setCancelButton(cancelButton);
634 progressDialog.show();
636 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
637 QApplication::setOverrideCursor(Qt::WaitCursor);
638 PlaySound(MAKEINTRESOURCE(IDR_WAVE1), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
639 QApplication::restoreOverrideCursor();
642 timer.setInterval(1000);
645 QEventLoop eventLoop(this);
646 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
647 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
649 for(int i = 1; i <= iTimeout; i++)
652 if(progressDialog.wasCanceled())
654 progressDialog.close();
657 progressDialog.setValue(i+1);
658 progressDialog.setLabelText(text.arg(iTimeout-i));
659 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
660 QApplication::processEvents();
661 PlaySound(MAKEINTRESOURCE((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
664 qWarning("Shutting down !!!");
666 if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
668 qApp->closeAllWindows();
673 * Main initialization function (called only once!)
675 void MainWindow::init(void)
677 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";
678 QStringList binaries = QString::fromLatin1(binFiles).split(":", QString::SkipEmptyParts);
682 //Check for a running instance
683 bool firstInstance = false;
684 if(m_ipcThread->initialize(&firstInstance))
686 m_ipcThread->start();
689 if(!m_ipcThread->wait(5000))
691 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"));
692 m_ipcThread->terminate();
695 close(); qApp->exit(-1); return;
700 while(!binaries.isEmpty())
702 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
703 QString current = binaries.takeFirst();
704 QFile *file = new QFile(QString("%1/toolset/%2").arg(m_appDir, current));
705 if(file->open(QIODevice::ReadOnly))
707 bool binaryTypeOkay = false;
709 if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(file->fileName())), &binaryType))
711 binaryTypeOkay = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
715 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("-", "−"));
716 qFatal(QString("Binary is invalid: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
717 close(); qApp->exit(-1); return;
724 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("-", "−"));
725 qFatal(QString("Binary not found: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
726 close(); qApp->exit(-1); return;
730 //Check for portable mode
734 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
735 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
736 if(writeTest.open(QIODevice::WriteOnly))
738 ok = (writeTest.write(data) == strlen(data));
743 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"));
744 if(val != 1) { close(); qApp->exit(-1); return; }
749 if(x264_is_prerelease())
751 qsrand(time(NULL)); int rnd = qrand() % 3;
752 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);
753 if(rnd != val) { close(); qApp->exit(-1); return; }
756 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
757 if(!(m_cpuFeatures->mmx && m_cpuFeatures->mmx2))
759 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"));
760 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
761 close(); qApp->exit(-1); return;
763 else if(!(m_cpuFeatures->mmx && m_cpuFeatures->sse))
765 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
766 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"));
767 if(val != 1) { close(); qApp->exit(-1); return; }
770 //Check for Avisynth support
771 if(!qApp->arguments().contains("--skip-avisynth-check", Qt::CaseInsensitive))
773 qDebug("[Check for Avisynth support]");
774 volatile double avisynthVersion = 0.0;
775 const int result = AvisynthCheckThread::detect(&avisynthVersion);
778 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
779 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
780 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
781 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
782 if(val != 1) { close(); qApp->exit(-1); return; }
784 if((!result) || (avisynthVersion < 2.5))
786 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"));
787 if(val != 1) { close(); qApp->exit(-1); return; }
792 //Check for expiration
793 if(x264_version_date().addMonths(6) < QDate::currentDate())
795 QMessageBox msgBox(this);
796 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
797 msgBox.setWindowTitle(tr("Update Notification"));
798 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
799 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));
800 QPushButton *btn1 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
801 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::AcceptRole);
802 btn1->setEnabled(false);
803 btn2->setVisible(false);
804 QTimer::singleShot(5000, btn1, SLOT(hide()));
805 QTimer::singleShot(5000, btn2, SLOT(show()));
809 //Add files from command-line
810 bool bAddFile = false;
811 QStringList files, args = qApp->arguments();
812 while(!args.isEmpty())
814 QString current = args.takeFirst();
817 bAddFile = (current.compare("--add", Qt::CaseInsensitive) == 0);
820 if((!current.startsWith("--")) && QFileInfo(current).exists() && QFileInfo(current).isFile())
822 files << QFileInfo(current).canonicalFilePath();
825 if(files.count() > 0)
827 createJobMultiple(files);
830 //Enable drag&drop support for this window, required for Qt v4.8.4+
831 setAcceptDrops(true);
835 * Update the label position
837 void MainWindow::updateLabelPos(void)
839 const QWidget *const viewPort = jobsView->viewport();
840 m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
844 * Copy the complete log to the clipboard
846 void MainWindow::copyLogToClipboard(bool checked)
848 qDebug("copyLogToClipboard");
850 if(LogFileModel *log = dynamic_cast<LogFileModel*>(logView->model()))
852 log->copyToClipboard();
853 MessageBeep(MB_ICONINFORMATION);
858 * Process the dropped files
860 void MainWindow::handleDroppedFiles(void)
862 qDebug("MainWindow::handleDroppedFiles");
865 QStringList droppedFiles(*m_droppedFiles);
866 m_droppedFiles->clear();
867 createJobMultiple(droppedFiles);
869 qDebug("Leave from MainWindow::handleDroppedFiles!");
872 void MainWindow::instanceCreated(DWORD pid)
874 qDebug("Notification from other instance (PID=0x%X) received!", pid);
876 FLASHWINFO flashWinInfo;
877 memset(&flashWinInfo, 0, sizeof(FLASHWINFO));
878 flashWinInfo.cbSize = sizeof(FLASHWINFO);
879 flashWinInfo.hwnd = this->winId();
880 flashWinInfo.dwFlags = FLASHW_ALL;
881 flashWinInfo.dwTimeout = 125;
882 flashWinInfo.uCount = 5;
884 SwitchToThisWindow(this->winId(), TRUE);
885 SetForegroundWindow(this->winId());
886 qApp->processEvents();
887 FlashWindowEx(&flashWinInfo);
890 ///////////////////////////////////////////////////////////////////////////////
892 ///////////////////////////////////////////////////////////////////////////////
897 void MainWindow::showEvent(QShowEvent *e)
899 QMainWindow::showEvent(e);
904 QTimer::singleShot(0, this, SLOT(init()));
911 void MainWindow::closeEvent(QCloseEvent *e)
913 if(countRunningJobs() > 0)
916 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
920 if(countPendingJobs() > 0)
922 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);
923 if(ret != QMessageBox::Yes)
930 while(m_jobList->rowCount(QModelIndex()) > 0)
932 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
933 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
936 QMessageBox::warning(this, tr("Failed To Exit"), tr("Sorry, at least one job could not be deleted!"));
941 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
942 QMainWindow::closeEvent(e);
946 * Window resize event
948 void MainWindow::resizeEvent(QResizeEvent *e)
950 QMainWindow::resizeEvent(e);
957 bool MainWindow::eventFilter(QObject *o, QEvent *e)
959 if((o == labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
961 QTimer::singleShot(0, this, SLOT(showAbout()));
968 * Win32 message filter
970 bool MainWindow::winEvent(MSG *message, long *result)
972 return WinSevenTaskbar::handleWinEvent(message, result);
976 * File dragged over window
978 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
980 bool accept[2] = {false, false};
982 foreach(const QString &fmt, event->mimeData()->formats())
984 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
985 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
988 if(accept[0] && accept[1])
990 event->acceptProposedAction();
995 * File dropped onto window
997 void MainWindow::dropEvent(QDropEvent *event)
999 QStringList droppedFiles;
1000 QList<QUrl> urls = event->mimeData()->urls();
1002 while(!urls.isEmpty())
1004 QUrl currentUrl = urls.takeFirst();
1005 QFileInfo file(currentUrl.toLocalFile());
1006 if(file.exists() && file.isFile())
1008 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1009 droppedFiles << file.canonicalFilePath();
1013 if(droppedFiles.count() > 0)
1017 m_droppedFiles = new QStringList();
1019 m_droppedFiles->append(droppedFiles);
1020 m_droppedFiles->sort();
1021 QTimer::singleShot(0, this, SLOT(handleDroppedFiles()));
1025 ///////////////////////////////////////////////////////////////////////////////
1026 // Private functions
1027 ///////////////////////////////////////////////////////////////////////////////
1032 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1035 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed, m_cpuFeatures->x64, m_preferences->use10BitEncoding(), m_preferences->saveToSourcePath());
1037 addDialog->setRunImmediately(runImmediately);
1038 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1039 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1040 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1042 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1045 addDialog->setSourceEditable(false);
1046 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1047 addDialog->setApplyToAllVisible(applyToAll);
1050 if(addDialog->exec() == QDialog::Accepted)
1052 sourceFileName = addDialog->sourceFile();
1053 outputFileName = addDialog->outputFile();
1054 runImmediately = addDialog->runImmediately();
1057 *applyToAll = addDialog->applyToAll();
1062 X264_DELETE(addDialog);
1067 * Creates a new job from *multiple* files
1069 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1071 QStringList::ConstIterator iter;
1072 bool applyToAll = false, runImmediately = false;
1075 //Add files individually
1076 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1078 runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
1079 QString sourceFileName(*iter), outputFileName;
1080 if(createJob(sourceFileName, outputFileName, m_options, runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1082 if(appendJob(sourceFileName, outputFileName, m_options, runImmediately))
1090 //Add remaining files
1091 while(applyToAll && (iter != filePathIn.constEnd()))
1093 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
1094 const QString sourceFileName = *iter;
1095 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->saveToSourcePath());
1096 if(!appendJob(sourceFileName, outputFileName, m_options, runImmediatelyTmp))
1110 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1114 EncodeThread *thrd = new EncodeThread
1119 QString("%1/toolset").arg(m_appDir),
1121 m_preferences->use10BitEncoding(),
1122 m_cpuFeatures->x64 && m_preferences->useAvisyth64Bit(),
1123 m_preferences->processPriority()
1126 QModelIndex newIndex = m_jobList->insertJob(thrd);
1128 if(newIndex.isValid())
1132 jobsView->selectRow(newIndex.row());
1133 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1134 m_jobList->startJob(newIndex);
1140 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1145 * Jobs that are not completed (or failed, or aborted) yet
1147 unsigned int MainWindow::countPendingJobs(void)
1149 unsigned int count = 0;
1150 const int rows = m_jobList->rowCount(QModelIndex());
1152 for(int i = 0; i < rows; i++)
1154 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1155 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1165 * Jobs that are still active, i.e. not terminated or enqueued
1167 unsigned int MainWindow::countRunningJobs(void)
1169 unsigned int count = 0;
1170 const int rows = m_jobList->rowCount(QModelIndex());
1172 for(int i = 0; i < rows; i++)
1174 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1175 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1185 * Update all buttons with respect to current job status
1187 void MainWindow::updateButtons(JobStatus status)
1189 qDebug("MainWindow::updateButtons(void)");
1191 buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1192 buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1193 buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1194 buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1196 actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1197 actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1198 actionJob_Browse->setEnabled(status == JobStatus_Completed);
1200 actionJob_Start->setEnabled(buttonStartJob->isEnabled());
1201 actionJob_Abort->setEnabled(buttonAbortJob->isEnabled());
1202 actionJob_Pause->setEnabled(buttonPauseJob->isEnabled());
1203 actionJob_Pause->setChecked(buttonPauseJob->isChecked());
1205 editDetails->setEnabled(status != JobStatus_Paused);
1209 * Update the taskbar with current job status
1211 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1213 qDebug("MainWindow::updateTaskbar(void)");
1217 case JobStatus_Undefined:
1218 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1220 case JobStatus_Aborting:
1221 case JobStatus_Starting:
1222 case JobStatus_Pausing:
1223 case JobStatus_Resuming:
1224 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1226 case JobStatus_Aborted:
1227 case JobStatus_Failed:
1228 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1230 case JobStatus_Paused:
1231 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1234 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1240 case JobStatus_Aborting:
1241 case JobStatus_Starting:
1242 case JobStatus_Pausing:
1243 case JobStatus_Resuming:
1246 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
1250 WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);