1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2014 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 ///////////////////////////////////////////////////////////////////////////////
23 #include "uic_win_main.h"
27 #include "model_status.h"
28 #include "model_jobList.h"
29 #include "model_options.h"
30 #include "model_preferences.h"
31 #include "model_recently.h"
32 #include "thread_avisynth.h"
33 #include "thread_vapoursynth.h"
34 #include "thread_encode.h"
36 #include "win_addJob.h"
37 #include "win_preferences.h"
38 #include "win_updater.h"
43 #include <QCloseEvent>
44 #include <QMessageBox>
45 #include <QDesktopServices>
50 #include <QProgressDialog>
52 #include <QTextStream>
54 #include <QFileDialog>
58 const char *home_url = "http://muldersoft.com/";
59 const char *update_url = "https://github.com/lordmulder/Simple-x264-Launcher/releases/latest";
60 const char *tpl_last = "<LAST_USED>";
62 #define SET_FONT_BOLD(WIDGET,BOLD) do { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); } while(0)
63 #define SET_TEXT_COLOR(WIDGET,COLOR) do { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); } while(0)
64 #define LINK(URL) "<a href=\"" URL "\">" URL "</a>"
65 #define INIT_ERROR_EXIT() do { m_status = STATUS_EXITTING; close(); qApp->exit(-1); return; } while(0)
66 #define ENSURE_APP_IS_IDLE() do { if(m_status != STATUS_IDLE) return; } while(0)
68 //static int exceptionFilter(_EXCEPTION_RECORD *dst, _EXCEPTION_POINTERS *src) { memcpy(dst, src->ExceptionRecord, sizeof(_EXCEPTION_RECORD)); return EXCEPTION_EXECUTE_HANDLER; }
70 ///////////////////////////////////////////////////////////////////////////////
71 // Constructor & Destructor
72 ///////////////////////////////////////////////////////////////////////////////
77 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures, IPC *ipc)
79 m_cpuFeatures(cpuFeatures),
81 m_appDir(QApplication::applicationDirPath()),
84 m_pendingFiles(new QStringList()),
87 m_skipVersionTest(false),
88 m_abortOnTimeout(true),
89 m_status(STATUS_PRE_INIT),
91 ui(new Ui::MainWindow())
93 //Init the dialog, from the .ui file
95 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
98 qRegisterMetaType<QUuid>("QUuid");
99 qRegisterMetaType<QUuid>("DWORD");
100 qRegisterMetaType<JobStatus>("JobStatus");
103 m_preferences = new PreferencesModel();
104 PreferencesModel::loadPreferences(m_preferences);
107 m_recentlyUsed = new RecentlyUsed();
108 RecentlyUsed::loadRecentlyUsed(m_recentlyUsed);
110 //Create options object
111 m_options = new OptionsModel();
112 OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
114 //Freeze minimum size
115 setMinimumSize(size());
116 ui->splitter->setSizes(QList<int>() << 16 << 196);
119 ui->labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
120 ui->labelBuildDate->installEventFilter(this);
121 setWindowTitle(QString("%1 (%2 Mode)").arg(windowTitle(), m_cpuFeatures->x64 ? "64-Bit" : "32-Bit"));
124 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
125 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
127 else if(x264_is_prerelease())
129 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
133 m_jobList = new JobListModel(m_preferences);
134 connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
135 ui->jobsView->setModel(m_jobList);
138 ui->jobsView->horizontalHeader()->setSectionHidden(3, true);
139 ui->jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
140 ui->jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
141 ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
142 ui->jobsView->horizontalHeader()->resizeSection(1, 150);
143 ui->jobsView->horizontalHeader()->resizeSection(2, 90);
144 ui->jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
145 connect(ui->jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
147 //Create context menu
148 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), ui->logView);
149 actionClipboard->setEnabled(false);
150 ui->logView->addAction(actionClipboard);
151 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
152 ui->jobsView->addActions(ui->menuJob->actions());
155 connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed()));
156 connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed()));
157 connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed()));
158 connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
159 connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed()));
160 connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed()));
161 connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed()));
164 connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
165 connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
166 connect(ui->actionWebMulder, SIGNAL(triggered()), this, SLOT(showWebLink()));
167 connect(ui->actionWebX264, SIGNAL(triggered()), this, SLOT(showWebLink()));
168 connect(ui->actionWebKomisar, SIGNAL(triggered()), this, SLOT(showWebLink()));
169 connect(ui->actionWebVideoLAN, SIGNAL(triggered()), this, SLOT(showWebLink()));
170 connect(ui->actionWebJEEB, SIGNAL(triggered()), this, SLOT(showWebLink()));
171 connect(ui->actionWebAvisynth32, SIGNAL(triggered()), this, SLOT(showWebLink()));
172 connect(ui->actionWebAvisynth64, SIGNAL(triggered()), this, SLOT(showWebLink()));
173 connect(ui->actionWebVapourSynth, SIGNAL(triggered()), this, SLOT(showWebLink()));
174 connect(ui->actionWebVapourSynthDocs, SIGNAL(triggered()), this, SLOT(showWebLink()));
175 connect(ui->actionWebWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
176 connect(ui->actionWebBluRay, SIGNAL(triggered()), this, SLOT(showWebLink()));
177 connect(ui->actionWebAvsWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
178 connect(ui->actionWebSecret, SIGNAL(triggered()), this, SLOT(showWebLink()));
179 connect(ui->actionWebSupport, SIGNAL(triggered()), this, SLOT(showWebLink()));
180 connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
181 connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
183 //Create floating label
184 m_label = new QLabel(ui->jobsView->viewport());
185 m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
186 m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
187 SET_TEXT_COLOR(m_label, Qt::darkGray);
188 SET_FONT_BOLD(m_label, true);
189 m_label->setVisible(true);
190 m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
191 m_label->addActions(ui->jobsView->actions());
192 connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
199 MainWindow::~MainWindow(void)
201 OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
203 X264_DELETE(m_jobList);
204 X264_DELETE(m_options);
205 X264_DELETE(m_pendingFiles);
206 X264_DELETE(m_label);
208 while(!m_toolsList.isEmpty())
210 QFile *temp = m_toolsList.takeFirst();
215 if(m_ipcThread->isRunning())
217 m_ipcThread->setAbort();
218 if(!m_ipcThread->wait(5000))
220 m_ipcThread->terminate();
226 X264_DELETE(m_preferences);
227 X264_DELETE(m_recentlyUsed);
228 VapourSynthCheckThread::unload();
229 AvisynthCheckThread::unload();
234 ///////////////////////////////////////////////////////////////////////////////
236 ///////////////////////////////////////////////////////////////////////////////
239 * The "add" button was clicked
241 void MainWindow::addButtonPressed()
243 ENSURE_APP_IS_IDLE();
244 m_status = STATUS_BLOCKED;
246 qDebug("MainWindow::addButtonPressed");
247 bool runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
248 QString sourceFileName, outputFileName;
250 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
252 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
255 m_status = STATUS_IDLE;
259 * The "open" action was triggered
261 void MainWindow::openActionTriggered()
263 ENSURE_APP_IS_IDLE();
264 m_status = STATUS_BLOCKED;
266 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
267 if(!fileList.empty())
269 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
270 if(fileList.count() > 1)
272 createJobMultiple(fileList);
276 bool runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
277 QString sourceFileName(fileList.first()), outputFileName;
278 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
280 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
285 m_status = STATUS_IDLE;
289 * The "start" button was clicked
291 void MainWindow::startButtonPressed(void)
293 ENSURE_APP_IS_IDLE();
294 m_jobList->startJob(ui->jobsView->currentIndex());
298 * The "abort" button was clicked
300 void MainWindow::abortButtonPressed(void)
302 ENSURE_APP_IS_IDLE();
303 m_jobList->abortJob(ui->jobsView->currentIndex());
307 * The "delete" button was clicked
309 void MainWindow::deleteButtonPressed(void)
311 ENSURE_APP_IS_IDLE();
312 m_jobList->deleteJob(ui->jobsView->currentIndex());
313 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
317 * The "browse" button was clicked
319 void MainWindow::browseButtonPressed(void)
321 ENSURE_APP_IS_IDLE();
322 m_status = STATUS_BLOCKED;
324 QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
325 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
327 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
331 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
334 m_status = STATUS_IDLE;
338 * The "pause" button was clicked
340 void MainWindow::pauseButtonPressed(bool checked)
344 m_jobList->pauseJob(ui->jobsView->currentIndex());
348 m_jobList->resumeJob(ui->jobsView->currentIndex());
353 * The "restart" button was clicked
355 void MainWindow::restartButtonPressed(void)
357 ENSURE_APP_IS_IDLE();
359 const QModelIndex index = ui->jobsView->currentIndex();
360 const OptionsModel *options = m_jobList->getJobOptions(index);
361 QString sourceFileName = m_jobList->getJobSourceFile(index);
362 QString outputFileName = m_jobList->getJobOutputFile(index);
364 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
366 bool runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1)); //bool runImmediately = true;
367 OptionsModel *tempOptions = new OptionsModel(*options);
368 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
370 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
372 X264_DELETE(tempOptions);
377 * Job item selected by user
379 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
381 qDebug("Job selected: %d", current.row());
383 if(ui->logView->model())
385 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
388 if(current.isValid())
390 ui->logView->setModel(m_jobList->getLogFile(current));
391 connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
392 ui->logView->actions().first()->setEnabled(true);
393 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
395 ui->progressBar->setValue(m_jobList->getJobProgress(current));
396 ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
397 updateButtons(m_jobList->getJobStatus(current));
398 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
402 ui->logView->setModel(NULL);
403 ui->logView->actions().first()->setEnabled(false);
404 ui->progressBar->setValue(0);
405 ui->editDetails->clear();
406 updateButtons(JobStatus_Undefined);
407 updateTaskbar(JobStatus_Undefined, QIcon());
410 ui->progressBar->repaint();
414 * Handle update of job info (status, progress, details, etc)
416 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
418 int selected = ui->jobsView->currentIndex().row();
420 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
422 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
424 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
427 qDebug("Current job changed status!");
428 updateButtons(status);
429 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
431 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
433 if(m_preferences->autoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
434 if(m_preferences->shutdownComputer()) QTimer::singleShot(0, this, SLOT(shutdownComputer()));
435 if(m_preferences->saveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
439 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
441 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
445 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
446 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
451 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
453 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
457 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
465 * Handle new log file content
467 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
469 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
475 void MainWindow::showAbout(void)
477 ENSURE_APP_IS_IDLE();
478 m_status = STATUS_BLOCKED;
481 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());
482 text += QString().sprintf("Copyright (c) 2004-%04d LoRd_MuldeR <mulder2@gmx.de>. Some rights reserved.<br>", qMax(x264_version_date().year(),QDate::currentDate().year()));
483 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());
484 text += QString().sprintf("This program is free software: you can redistribute it and/or modify<br>");
485 text += QString().sprintf("it under the terms of the GNU General Public License <http://www.gnu.org/>.<br>");
486 text += QString().sprintf("Note that this program is distributed with ABSOLUTELY NO WARRANTY.<br><br>");
487 text += QString().sprintf("Please check the web-site at <a href=\"%s\">%s</a> for updates !!!<br></tt></nobr>", home_url, home_url);
489 QMessageBox aboutBox(this);
490 aboutBox.setIconPixmap(QIcon(":/images/movie.png").pixmap(64,64));
491 aboutBox.setWindowTitle(tr("About..."));
492 aboutBox.setText(text.replace("-", "−"));
493 aboutBox.addButton(tr("About x264"), QMessageBox::NoRole);
494 aboutBox.addButton(tr("About AVS"), QMessageBox::NoRole);
495 aboutBox.addButton(tr("About VPY"), QMessageBox::NoRole);
496 aboutBox.addButton(tr("About Qt"), QMessageBox::NoRole);
497 aboutBox.setEscapeButton(aboutBox.addButton(tr("Close"), QMessageBox::NoRole));
501 x264_beep(x264_beep_info);
502 switch(aboutBox.exec())
507 text2 += tr("<nobr><tt>x264 - the best H.264/AVC encoder. Copyright (c) 2003-2013 x264 project.<br>");
508 text2 += tr("Free software library for encoding video streams into the H.264/MPEG-4 AVC format.<br>");
509 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
510 text2 += tr("Please visit <a href=\"%1\">%1</a> for obtaining a commercial x264 license.<br>").arg("http://x264licensing.com/");
511 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");
513 QMessageBox x264Box(this);
514 x264Box.setIconPixmap(QIcon(":/images/x264.png").pixmap(48,48));
515 x264Box.setWindowTitle(tr("About x264"));
516 x264Box.setText(text2.replace("-", "−"));
517 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
518 x264_beep(x264_beep_info);
525 text2 += tr("<nobr><tt>Avisynth - powerful video processing scripting language.<br>");
526 text2 += tr("Copyright (c) 2000 Ben Rudiak-Gould and all subsequent developers.<br>");
527 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
528 text2 += tr("Please visit the web-site <a href=\"%1\">%1</a> for more information.<br>").arg("http://avisynth.org/");
529 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.nl/index.php/First_script", "http://forum.doom9.org/forumdisplay.php?f=33");
531 QMessageBox x264Box(this);
532 x264Box.setIconPixmap(QIcon(":/images/avisynth.png").pixmap(48,67));
533 x264Box.setWindowTitle(tr("About Avisynth"));
534 x264Box.setText(text2.replace("-", "−"));
535 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
536 x264_beep(x264_beep_info);
543 text2 += tr("<nobr><tt>VapourSynth - application for video manipulation based on Python.<br>");
544 text2 += tr("Copyright (c) 2012 Fredrik Mellbin.<br>");
545 text2 += tr("Released under the terms of the GNU Lesser General Public.<br><br>");
546 text2 += tr("Please visit the web-site <a href=\"%1\">%1</a> for more information.<br>").arg("http://www.vapoursynth.com/");
547 text2 += tr("Read the <a href=\"%1\">documentation</a> to get started and use the <a href=\"%2\">support forum</a> for help!<br></tt></nobr>").arg("http://www.vapoursynth.com/doc/", "http://forum.doom9.org/showthread.php?t=165771");
549 QMessageBox x264Box(this);
550 x264Box.setIconPixmap(QIcon(":/images/python.png").pixmap(48,48));
551 x264Box.setWindowTitle(tr("About VapourSynth"));
552 x264Box.setText(text2.replace("-", "−"));
553 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
554 x264_beep(x264_beep_info);
559 QMessageBox::aboutQt(this);
562 m_status = STATUS_IDLE;
571 void MainWindow::showWebLink(void)
573 if(QObject::sender() == ui->actionWebMulder) QDesktopServices::openUrl(QUrl(home_url));
574 if(QObject::sender() == ui->actionWebX264) QDesktopServices::openUrl(QUrl("http://www.x264.com/"));
575 if(QObject::sender() == ui->actionWebKomisar) QDesktopServices::openUrl(QUrl("http://komisar.gin.by/"));
576 if(QObject::sender() == ui->actionWebVideoLAN) QDesktopServices::openUrl(QUrl("http://download.videolan.org/pub/x264/binaries/"));
577 if(QObject::sender() == ui->actionWebJEEB) QDesktopServices::openUrl(QUrl("http://x264.fushizen.eu/"));
578 if(QObject::sender() == ui->actionWebAvisynth32) QDesktopServices::openUrl(QUrl("http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/"));
579 if(QObject::sender() == ui->actionWebAvisynth64) QDesktopServices::openUrl(QUrl("http://code.google.com/p/avisynth64/downloads/list"));
580 if(QObject::sender() == ui->actionWebVapourSynth) QDesktopServices::openUrl(QUrl("http://www.vapoursynth.com/"));
581 if(QObject::sender() == ui->actionWebVapourSynthDocs) QDesktopServices::openUrl(QUrl("http://www.vapoursynth.com/doc/"));
582 if(QObject::sender() == ui->actionWebWiki) QDesktopServices::openUrl(QUrl("http://mewiki.project357.com/wiki/X264_Settings"));
583 if(QObject::sender() == ui->actionWebBluRay) QDesktopServices::openUrl(QUrl("http://www.x264bluray.com/"));
584 if(QObject::sender() == ui->actionWebAvsWiki) QDesktopServices::openUrl(QUrl("http://avisynth.nl/index.php/Main_Page#Usage"));
585 if(QObject::sender() == ui->actionWebSupport) QDesktopServices::openUrl(QUrl("http://forum.doom9.org/showthread.php?t=144140"));
586 if(QObject::sender() == ui->actionWebSecret) QDesktopServices::openUrl(QUrl("http://www.youtube.com/watch_popup?v=AXIeHY-OYNI"));
590 * Pereferences dialog
592 void MainWindow::showPreferences(void)
594 ENSURE_APP_IS_IDLE();
595 m_status = STATUS_BLOCKED;
597 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences, m_cpuFeatures->x64);
600 X264_DELETE(preferences);
601 m_status = STATUS_IDLE;
605 * Launch next job, after running job has finished
607 void MainWindow::launchNextJob(void)
609 qDebug("launchNextJob(void)");
611 const int rows = m_jobList->rowCount(QModelIndex());
613 if(countRunningJobs() >= m_preferences->maxRunningJobCount())
615 qDebug("Still have too many jobs running, won't launch next one yet!");
619 int startIdx= ui->jobsView->currentIndex().isValid() ? qBound(0, ui->jobsView->currentIndex().row(), rows-1) : 0;
621 for(int i = 0; i < rows; i++)
623 int currentIdx = (i + startIdx) % rows;
624 JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
625 if(status == JobStatus_Enqueued)
627 if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
629 ui->jobsView->selectRow(currentIdx);
635 qWarning("No enqueued jobs left!");
639 * Save log to text file
641 void MainWindow::saveLogFile(const QModelIndex &index)
645 if(LogFileModel *log = m_jobList->getLogFile(index))
647 QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
648 QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
649 QFile outFile(logFilePath);
650 if(outFile.open(QIODevice::WriteOnly))
652 QTextStream outStream(&outFile);
653 outStream.setCodec("UTF-8");
654 outStream.setGenerateByteOrderMark(true);
656 const int rows = log->rowCount(QModelIndex());
657 for(int i = 0; i < rows; i++)
659 outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
665 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
672 * Shut down the computer (with countdown)
674 void MainWindow::shutdownComputer(void)
676 qDebug("shutdownComputer(void)");
678 if(countPendingJobs() > 0)
680 qDebug("Still have pending jobs, won't shutdown yet!");
684 const int iTimeout = 30;
685 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
686 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
688 qWarning("Initiating shutdown sequence!");
690 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
691 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
692 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
693 progressDialog.setModal(true);
694 progressDialog.setAutoClose(false);
695 progressDialog.setAutoReset(false);
696 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
697 progressDialog.setWindowTitle(windowTitle());
698 progressDialog.setCancelButton(cancelButton);
699 progressDialog.show();
701 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
702 QApplication::setOverrideCursor(Qt::WaitCursor);
703 x264_play_sound(IDR_WAVE1, false);
704 QApplication::restoreOverrideCursor();
707 timer.setInterval(1000);
710 QEventLoop eventLoop(this);
711 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
712 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
714 for(int i = 1; i <= iTimeout; i++)
717 if(progressDialog.wasCanceled())
719 progressDialog.close();
722 progressDialog.setValue(i+1);
723 progressDialog.setLabelText(text.arg(iTimeout-i));
724 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
725 QApplication::processEvents();
726 x264_play_sound(((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), false);
729 qWarning("Shutting down !!!");
731 if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
733 qApp->closeAllWindows();
738 * Main initialization function (called only once!)
740 void MainWindow::init(void)
742 if(m_status != STATUS_PRE_INIT)
744 qWarning("Already initialized -> skipping!");
748 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";
749 QStringList binaries = QString::fromLatin1(binFiles).split(":", QString::SkipEmptyParts);
753 //Create the IPC listener thread
754 if(m_ipc->isInitialized())
756 connect(m_ipc, SIGNAL(receivedCommand(int,QStringList)), this, SLOT(handleCommand(int,QStringList)), Qt::QueuedConnection);
757 m_ipc->startListening();
761 while(!binaries.isEmpty())
763 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
764 QString current = binaries.takeFirst();
765 QFile *file = new QFile(QString("%1/toolset/%2").arg(m_appDir, current));
766 if(file->open(QIODevice::ReadOnly))
768 if(!x264_is_executable(file->fileName()))
770 QMessageBox::critical(this, tr("Invalid File!"), tr("<nobr>At least on required tool is not a valid Win32 or Win64 binary:<br><tt style=\"whitespace:nowrap\">%1</tt><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("-", "−"));
771 qFatal(QString("Binary is invalid: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
779 QMessageBox::critical(this, tr("File Not Found!"), tr("<nobr>At least on required tool could not be found:<br><tt style=\"whitespace:nowrap\">%1</tt><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("-", "−"));
780 qFatal(QString("Binary not found: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
785 //Check for portable mode
789 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
790 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
791 if(writeTest.open(QIODevice::WriteOnly))
793 ok = (writeTest.write(data) == strlen(data));
798 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"));
799 if(val != 1) INIT_ERROR_EXIT();
804 if(x264_is_prerelease())
806 qsrand(time(NULL)); int rnd = qrand() % 3;
807 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);
808 if(rnd != val) INIT_ERROR_EXIT();
811 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
812 if(!(m_cpuFeatures->mmx && m_cpuFeatures->mmx2))
814 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"));
815 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
818 else if(!(m_cpuFeatures->mmx && m_cpuFeatures->sse))
820 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
821 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"));
822 if(val != 1) INIT_ERROR_EXIT();
825 //Skip version check (not recommended!)
826 if(qApp->arguments().contains("--skip-x264-version-check", Qt::CaseInsensitive))
828 qWarning("x264 version check disabled, you have been warned!\n");
829 m_skipVersionTest = true;
832 //Don't abort encoding process on timeout (not recommended!)
833 if(qApp->arguments().contains("--no-deadlock-detection", Qt::CaseInsensitive))
835 qWarning("Deadlock detection disabled, you have been warned!\n");
836 m_abortOnTimeout = false;
839 //Check for Avisynth support
840 if(!qApp->arguments().contains("--skip-avisynth-check", Qt::CaseInsensitive))
842 qDebug("[Check for Avisynth support]");
843 volatile double avisynthVersion = 0.0;
844 const int result = AvisynthCheckThread::detect(&avisynthVersion);
847 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
848 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
849 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
850 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
851 if(val != 1) INIT_ERROR_EXIT();
853 if((!result) || (avisynthVersion < 2.5))
855 if(!m_preferences->disableWarnings())
857 QString text = tr("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!").append("<br><br>");
858 text += tr("Please download and install Avisynth:").append("<br>").append(LINK("http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/"));
859 int val = QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
860 if(val != 1) INIT_ERROR_EXIT();
866 //Check for VapourSynth support
867 if(!qApp->arguments().contains("--skip-vapoursynth-check", Qt::CaseInsensitive))
869 qDebug("[Check for VapourSynth support]");
870 volatile double avisynthVersion = 0.0;
871 const int result = VapourSynthCheckThread::detect(m_vapoursynthPath);
874 QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
875 text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
876 text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
877 int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
878 if(val != 1) INIT_ERROR_EXIT();
880 if((!result) || (m_vapoursynthPath.isEmpty()))
882 if(!m_preferences->disableWarnings())
884 QString text = tr("It appears that VapourSynth is <b>not</b> currently installed on your computer.<br>Therefore VapourSynth (.vpy) input will <b>not</b> be working at all!").append("<br><br>");
885 text += tr("Please download and install VapourSynth for Windows (R19 or later):").append("<br>").append(LINK("http://www.vapoursynth.com/")).append("<br><br>");
886 text += tr("Note that Python 3.3 (x86) is a prerequisite for installing VapourSynth:").append("<br>").append(LINK("http://www.python.org/getit/")).append("<br>");
887 int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
888 if(val != 1) INIT_ERROR_EXIT();
894 //Enable drag&drop support for this window, required for Qt v4.8.4+
895 setAcceptDrops(true);
897 //Check for expiration
898 if(x264_version_date().addMonths(6) < x264_current_date_safe())
901 text += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(tr("Your version of Simple x264 Launcher is more than 6 months old!").replace("-", "−"));
902 text += QString("<nobr><tt>%1<br><a href=\"%2\">%2</a><br><br>").arg(tr("You can download the most recent version from the official web-site now:").replace("-", "−"), QString::fromLatin1(update_url));
903 text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace("-", "−"));
904 QMessageBox msgBox(this);
905 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
906 msgBox.setWindowTitle(tr("Update Notification"));
907 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
908 msgBox.setText(text);
909 QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
910 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
911 QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
912 btn2->setEnabled(false);
913 btn3->setVisible(false);
914 QTimer::singleShot(7500, btn2, SLOT(hide()));
915 QTimer::singleShot(7500, btn3, SLOT(show()));
916 if(msgBox.exec() == 0)
918 m_status = STATUS_IDLE;
919 QTimer::singleShot(0, this, SLOT(checkUpdates()));
925 m_status = STATUS_IDLE;
927 //Try adding files from command-line
928 if(!parseCommandLineArgs())
931 if((!m_preferences->noUpdateReminder()) && (m_recentlyUsed->lastUpdateCheck() + 14 < x264_current_date_safe().toJulianDay()))
933 if(QMessageBox::warning(this, tr("Update Notification"), QString("<nobr>%1</nobr>").arg(tr("Your last update check was more than 14 days ago. Check for updates now?")), tr("Check for Updates"), tr("Discard")) == 0)
935 QTimer::singleShot(0, this, SLOT(checkUpdates()));
943 * Update the label position
945 void MainWindow::updateLabelPos(void)
947 const QWidget *const viewPort = ui->jobsView->viewport();
948 m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
952 * Copy the complete log to the clipboard
954 void MainWindow::copyLogToClipboard(bool checked)
956 qDebug("copyLogToClipboard");
958 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
960 log->copyToClipboard();
961 x264_beep(x264_beep_info);
966 * Process the dropped files
968 void MainWindow::handlePendingFiles(void)
970 if((m_status == STATUS_IDLE) || (m_status == STATUS_AWAITING))
972 qDebug("MainWindow::handlePendingFiles");
973 if(!m_pendingFiles->isEmpty())
975 QStringList pendingFiles(*m_pendingFiles);
976 m_pendingFiles->clear();
977 createJobMultiple(pendingFiles);
979 qDebug("Leave from MainWindow::handlePendingFiles!");
980 m_status = STATUS_IDLE;
984 void MainWindow::handleCommand(const int &command, const QStringList &args)
986 if((m_status != STATUS_IDLE) && (m_status != STATUS_AWAITING))
988 qWarning("Cannot accapt commands at this time -> discarding!");
991 x264_bring_to_front(this);
994 qDebug("\n---------- IPC ----------");
995 qDebug("CommandId: %d", command);
996 for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
998 qDebug("Arguments: %s", iter->toUtf8().constData());
1000 qDebug("---------- IPC ----------\n");
1001 #endif //IPC_LOGGING
1005 case IPC::IPC_OPCODE_PING:
1006 qDebug("Received a PING request from another instance!");
1007 x264_blink_window(this, 5, 125);
1009 case IPC::IPC_OPCODE_ADD_FILE:
1012 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1014 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1015 if(m_status != STATUS_AWAITING)
1017 m_status = STATUS_AWAITING;
1018 QTimer::singleShot(3333, this, SLOT(handlePendingFiles()));
1023 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1027 case IPC::IPC_OPCODE_ADD_JOB:
1028 if(args.size() >= 3)
1030 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1032 OptionsModel options;
1033 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1035 if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1037 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1040 appendJob(args[0], args[1], &options, true);
1044 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1049 throw std::exception("Unknown command received!");
1053 void MainWindow::checkUpdates(void)
1055 ENSURE_APP_IS_IDLE();
1056 m_status = STATUS_BLOCKED;
1058 if(countRunningJobs() > 0)
1060 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1061 m_status = STATUS_IDLE;
1065 UpdaterDialog *updater = new UpdaterDialog(this, QString("%1/toolset").arg(m_appDir));
1066 const int ret = updater->exec();
1068 if(updater->getSuccess())
1070 m_recentlyUsed->setLastUpdateCheck(x264_current_date_safe().toJulianDay());
1071 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
1074 if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1076 m_status = STATUS_EXITTING;
1077 qWarning("Exitting program to install update...");
1079 QApplication::quit();
1082 X264_DELETE(updater);
1084 if(m_status != STATUS_EXITTING)
1086 m_status = STATUS_IDLE;
1090 ///////////////////////////////////////////////////////////////////////////////
1092 ///////////////////////////////////////////////////////////////////////////////
1095 * Window shown event
1097 void MainWindow::showEvent(QShowEvent *e)
1099 QMainWindow::showEvent(e);
1103 m_firstShow = false;
1104 QTimer::singleShot(0, this, SLOT(init()));
1109 * Window close event
1111 void MainWindow::closeEvent(QCloseEvent *e)
1113 if((m_status != STATUS_IDLE) && (m_status != STATUS_EXITTING))
1115 qWarning("Cannot close window at this time!");
1119 if(m_status != STATUS_EXITTING)
1121 if(countRunningJobs() > 0)
1124 m_status = STATUS_BLOCKED;
1125 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
1126 m_status = STATUS_IDLE;
1130 if(countPendingJobs() > 0)
1132 m_status = STATUS_BLOCKED;
1133 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);
1134 if(ret != QMessageBox::Yes)
1137 m_status = STATUS_IDLE;
1143 while(m_jobList->rowCount(QModelIndex()) > 0)
1145 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1146 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1149 m_status = STATUS_BLOCKED;
1150 QMessageBox::warning(this, tr("Failed To Exit"), tr("Sorry, at least one job could not be deleted!"));
1151 m_status = STATUS_IDLE;
1156 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1157 QMainWindow::closeEvent(e);
1161 * Window resize event
1163 void MainWindow::resizeEvent(QResizeEvent *e)
1165 QMainWindow::resizeEvent(e);
1172 bool MainWindow::eventFilter(QObject *o, QEvent *e)
1174 if((o == ui->labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
1176 QTimer::singleShot(0, this, SLOT(showAbout()));
1183 * Win32 message filter
1185 bool MainWindow::winEvent(MSG *message, long *result)
1187 return WinSevenTaskbar::handleWinEvent(message, result);
1191 * File dragged over window
1193 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1195 bool accept[2] = {false, false};
1197 foreach(const QString &fmt, event->mimeData()->formats())
1199 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1200 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1203 if(accept[0] && accept[1])
1205 event->acceptProposedAction();
1210 * File dropped onto window
1212 void MainWindow::dropEvent(QDropEvent *event)
1214 QStringList droppedFiles;
1215 QList<QUrl> urls = event->mimeData()->urls();
1217 while(!urls.isEmpty())
1219 QUrl currentUrl = urls.takeFirst();
1220 QFileInfo file(currentUrl.toLocalFile());
1221 if(file.exists() && file.isFile())
1223 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1224 droppedFiles << file.canonicalFilePath();
1228 if(droppedFiles.count() > 0)
1230 m_pendingFiles->append(droppedFiles);
1231 m_pendingFiles->sort();
1232 QTimer::singleShot(0, this, SLOT(handlePendingFiles()));
1236 ///////////////////////////////////////////////////////////////////////////////
1237 // Private functions
1238 ///////////////////////////////////////////////////////////////////////////////
1243 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1246 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed, m_cpuFeatures->x64, m_preferences->use10BitEncoding(), m_preferences->saveToSourcePath());
1248 addDialog->setRunImmediately(runImmediately);
1249 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1250 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1251 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1253 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1256 addDialog->setSourceEditable(false);
1257 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1258 addDialog->setApplyToAllVisible(applyToAll);
1261 if(addDialog->exec() == QDialog::Accepted)
1263 sourceFileName = addDialog->sourceFile();
1264 outputFileName = addDialog->outputFile();
1265 runImmediately = addDialog->runImmediately();
1268 *applyToAll = addDialog->applyToAll();
1273 X264_DELETE(addDialog);
1278 * Creates a new job from *multiple* files
1280 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1282 QStringList::ConstIterator iter;
1283 bool applyToAll = false, runImmediately = false;
1286 //Add files individually
1287 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1289 runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
1290 QString sourceFileName(*iter), outputFileName;
1291 if(createJob(sourceFileName, outputFileName, m_options, runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1293 if(appendJob(sourceFileName, outputFileName, m_options, runImmediately))
1301 //Add remaining files
1302 while(applyToAll && (iter != filePathIn.constEnd()))
1304 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
1305 const QString sourceFileName = *iter;
1306 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->saveToSourcePath());
1307 if(!appendJob(sourceFileName, outputFileName, m_options, runImmediatelyTmp))
1321 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1325 EncodeThread *thrd = new EncodeThread
1330 QString("%1/toolset").arg(m_appDir),
1333 m_preferences->use10BitEncoding(),
1334 m_cpuFeatures->x64 && m_preferences->useAvisyth64Bit(),
1336 m_preferences->processPriority(),
1340 QModelIndex newIndex = m_jobList->insertJob(thrd);
1342 if(newIndex.isValid())
1346 ui->jobsView->selectRow(newIndex.row());
1347 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1348 m_jobList->startJob(newIndex);
1354 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1359 * Jobs that are not completed (or failed, or aborted) yet
1361 unsigned int MainWindow::countPendingJobs(void)
1363 unsigned int count = 0;
1364 const int rows = m_jobList->rowCount(QModelIndex());
1366 for(int i = 0; i < rows; i++)
1368 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1369 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1379 * Jobs that are still active, i.e. not terminated or enqueued
1381 unsigned int MainWindow::countRunningJobs(void)
1383 unsigned int count = 0;
1384 const int rows = m_jobList->rowCount(QModelIndex());
1386 for(int i = 0; i < rows; i++)
1388 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1389 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1399 * Update all buttons with respect to current job status
1401 void MainWindow::updateButtons(JobStatus status)
1403 qDebug("MainWindow::updateButtons(void)");
1405 ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1406 ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1407 ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1408 ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1410 ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1411 ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1412 ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1414 ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1415 ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1416 ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1417 ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1419 ui->editDetails->setEnabled(status != JobStatus_Paused);
1423 * Update the taskbar with current job status
1425 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1427 qDebug("MainWindow::updateTaskbar(void)");
1431 case JobStatus_Undefined:
1432 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1434 case JobStatus_Aborting:
1435 case JobStatus_Starting:
1436 case JobStatus_Pausing:
1437 case JobStatus_Resuming:
1438 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1440 case JobStatus_Aborted:
1441 case JobStatus_Failed:
1442 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1444 case JobStatus_Paused:
1445 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1448 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1454 case JobStatus_Aborting:
1455 case JobStatus_Starting:
1456 case JobStatus_Pausing:
1457 case JobStatus_Resuming:
1460 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
1464 WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);
1468 * Parse command-line arguments
1470 bool MainWindow::parseCommandLineArgs(void)
1472 bool bCommandAccepted = false;
1475 QStringList args = x264_arguments();
1477 args.takeFirst(); //Pop argv[0]
1479 while(!args.isEmpty())
1481 QString current = args.takeFirst();
1482 if(X264_STRCMP(current, "--add") || X264_STRCMP(current, "--add-file"))
1484 bCommandAccepted = true;
1487 handleCommand(IPC::IPC_OPCODE_ADD_FILE, QStringList() << args.takeFirst());
1491 qWarning("Argument for '--add-file' is missing!");
1494 else if(X264_STRCMP(current, "--add-job"))
1496 bCommandAccepted = true;
1497 if(args.size() >= 3)
1500 for(int i = 0; i < 3; i++)
1502 lst << args.takeFirst();
1504 handleCommand(IPC::IPC_OPCODE_ADD_JOB, lst);
1508 qWarning("Argument(s) for '--add-job' are missing!");
1514 if(!current.startsWith("--"))
1516 qWarning("Unknown argument: %s", current.toUtf8().constData());
1522 return bCommandAccepted;