OSDN Git Service

Implemented initial queue saving/loading support.
[x264-launcher/x264-launcher.git] / src / win_main.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
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.
9 //
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.
14 //
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.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "win_main.h"
23 #include "uic_win_main.h"
24
25 #include "global.h"
26 #include "cli.h"
27 #include "ipc.h"
28 #include "model_status.h"
29 #include "model_sysinfo.h"
30 #include "model_jobList.h"
31 #include "model_options.h"
32 #include "model_preferences.h"
33 #include "model_recently.h"
34 #include "thread_avisynth.h"
35 #include "thread_vapoursynth.h"
36 #include "thread_encode.h"
37 #include "taskbar7.h"
38 #include "win_addJob.h"
39 #include "win_about.h"
40 #include "win_preferences.h"
41 #include "win_updater.h"
42 #include "binaries.h"
43 #include "resource.h"
44
45 #include <QDate>
46 #include <QTimer>
47 #include <QCloseEvent>
48 #include <QMessageBox>
49 #include <QDesktopServices>
50 #include <QUrl>
51 #include <QDir>
52 #include <QLibrary>
53 #include <QProcess>
54 #include <QProgressDialog>
55 #include <QScrollBar>
56 #include <QTextStream>
57 #include <QSettings>
58 #include <QFileDialog>
59
60 #include <ctime>
61
62 const char *home_url = "http://muldersoft.com/";
63 const char *update_url = "https://github.com/lordmulder/Simple-x264-Launcher/releases/latest";
64 const char *tpl_last = "<LAST_USED>";
65
66 #define SET_FONT_BOLD(WIDGET,BOLD) do { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); } while(0)
67 #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)
68 #define LINK(URL) "<a href=\"" URL "\">" URL "</a>"
69 #define INIT_ERROR_EXIT() do { m_status = STATUS_EXITTING; close(); qApp->exit(-1); return; } while(0)
70 #define ENSURE_APP_IS_IDLE() do { if(m_status != STATUS_IDLE) { x264_beep(x264_beep_warning); qWarning("Cannot perfrom this action at this time!"); return; } } while(0)
71 #define NEXT(X) ((*reinterpret_cast<int*>(&(X)))++)
72 #define SETUP_WEBLINK(OBJ, URL) do { (OBJ)->setData(QVariant(QUrl(URL))); connect((OBJ), SIGNAL(triggered()), this, SLOT(showWebLink())); } while(0)
73
74
75 ///////////////////////////////////////////////////////////////////////////////
76 // Constructor & Destructor
77 ///////////////////////////////////////////////////////////////////////////////
78
79 /*
80  * Constructor
81  */
82 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures, IPC *ipc)
83 :
84         m_ipc(ipc),
85         m_sysinfo(NULL),
86         m_options(NULL),
87         m_jobList(NULL),
88         m_pendingFiles(new QStringList()),
89         m_preferences(NULL),
90         m_recentlyUsed(NULL),
91         m_status(STATUS_PRE_INIT),
92         ui(new Ui::MainWindow())
93 {
94         //Init the dialog, from the .ui file
95         ui->setupUi(this);
96         setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
97
98         //Register meta types
99         qRegisterMetaType<QUuid>("QUuid");
100         qRegisterMetaType<QUuid>("DWORD");
101         qRegisterMetaType<JobStatus>("JobStatus");
102
103         //Create and initialize the sysinfo object
104         m_sysinfo = new SysinfoModel();
105         m_sysinfo->setAppPath(QApplication::applicationDirPath());
106         m_sysinfo->setMMXSupport(cpuFeatures->mmx && cpuFeatures->mmx2);
107         m_sysinfo->setSSESupport(cpuFeatures->sse && cpuFeatures->mmx2); //SSE implies MMX2
108         m_sysinfo->setX64Support(cpuFeatures->x64 && cpuFeatures->sse2); //X64 implies SSE2
109
110         //Load preferences
111         m_preferences = new PreferencesModel();
112         PreferencesModel::loadPreferences(m_preferences);
113
114         //Load recently used
115         m_recentlyUsed = new RecentlyUsed();
116         RecentlyUsed::loadRecentlyUsed(m_recentlyUsed);
117
118         //Create options object
119         m_options = new OptionsModel(m_sysinfo);
120         OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
121
122         //Freeze minimum size
123         setMinimumSize(size());
124         ui->splitter->setSizes(QList<int>() << 16 << 196);
125
126         //Update title
127         ui->labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
128         ui->labelBuildDate->installEventFilter(this);
129         
130         if(X264_DEBUG)
131         {
132                 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
133                 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
134         }
135         else if(x264_is_prerelease())
136         {
137                 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
138         }
139         
140         //Create model
141         m_jobList = new JobListModel(m_preferences);
142         connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
143         ui->jobsView->setModel(m_jobList);
144         
145         //Setup view
146         ui->jobsView->horizontalHeader()->setSectionHidden(3, true);
147         ui->jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
148         ui->jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
149         ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
150         ui->jobsView->horizontalHeader()->resizeSection(1, 150);
151         ui->jobsView->horizontalHeader()->resizeSection(2, 90);
152         ui->jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
153         connect(ui->jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
154
155         //Create context menu
156         QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), ui->logView);
157         actionClipboard->setEnabled(false);
158         ui->logView->addAction(actionClipboard);
159         connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
160         ui->jobsView->addActions(ui->menuJob->actions());
161
162         //Enable buttons
163         connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed()));
164         connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed()));
165         connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed()));
166         connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
167         connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed()));
168         connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed()));
169         connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed()));
170
171         //Enable menu
172         connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
173         connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
174         connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
175         connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
176
177         //Setup web-links
178         SETUP_WEBLINK(ui->actionWebMulder,          home_url);
179         SETUP_WEBLINK(ui->actionWebX264,            "http://www.videolan.org/developers/x264.html");
180         SETUP_WEBLINK(ui->actionWebX265,            "http://www.videolan.org/developers/x265.html");
181         SETUP_WEBLINK(ui->actionWebKomisar,         "http://komisar.gin.by/");
182         SETUP_WEBLINK(ui->actionWebVideoLAN,        "http://download.videolan.org/pub/x264/binaries/");
183         SETUP_WEBLINK(ui->actionWebJEEB,            "http://x264.fushizen.eu/");
184         SETUP_WEBLINK(ui->actionWebFreeCodecs,      "http://www.free-codecs.com/x264_video_codec_download.htm");
185         SETUP_WEBLINK(ui->actionWebX265BinRU,       "http://goo.gl/xRS6AW");
186         SETUP_WEBLINK(ui->actionWebX265BinEU,       "http://builds.x265.eu/");
187         SETUP_WEBLINK(ui->actionWebX265BinORG,      "http://chromashift.org/x265_builds/");
188         SETUP_WEBLINK(ui->actionWebX265BinFF,       "http://ffmpeg.zeranoe.com/builds/");
189         SETUP_WEBLINK(ui->actionWebAvisynth32,      "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/");
190         SETUP_WEBLINK(ui->actionWebAvisynth64,      "http://code.google.com/p/avisynth64/downloads/list");
191         SETUP_WEBLINK(ui->actionWebAvisynthPlus,    "http://www.avs-plus.net/");
192         SETUP_WEBLINK(ui->actionWebVapourSynth,     "http://www.vapoursynth.com/");
193         SETUP_WEBLINK(ui->actionWebVapourSynthDocs, "http://www.vapoursynth.com/doc/");
194         SETUP_WEBLINK(ui->actionWebWiki,            "http://mewiki.project357.com/wiki/X264_Settings");
195         SETUP_WEBLINK(ui->actionWebBluRay,          "http://www.x264bluray.com/");
196         SETUP_WEBLINK(ui->actionWebAvsWiki,         "http://avisynth.nl/index.php/Main_Page#Usage");
197         SETUP_WEBLINK(ui->actionWebSupport,         "http://forum.doom9.org/showthread.php?t=144140");
198         SETUP_WEBLINK(ui->actionWebSecret,          "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
199
200         //Create floating label
201         m_label = new QLabel(ui->jobsView->viewport());
202         m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
203         m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
204         SET_TEXT_COLOR(m_label, Qt::darkGray);
205         SET_FONT_BOLD(m_label, true);
206         m_label->setVisible(true);
207         m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
208         m_label->addActions(ui->jobsView->actions());
209         connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
210         updateLabelPos();
211 }
212
213 /*
214  * Destructor
215  */
216 MainWindow::~MainWindow(void)
217 {
218         m_status = STATUS_EXITTING;
219         OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
220         
221         X264_DELETE(m_jobList);
222         X264_DELETE(m_options);
223         X264_DELETE(m_pendingFiles);
224         X264_DELETE(m_label);
225
226         while(!m_toolsList.isEmpty())
227         {
228                 QFile *temp = m_toolsList.takeFirst();
229                 X264_DELETE(temp);
230         }
231
232         if(m_ipc->isListening())
233         {
234                 m_ipc->stopListening();
235         }
236
237         X264_DELETE(m_preferences);
238         X264_DELETE(m_recentlyUsed);
239         X264_DELETE(m_sysinfo);
240
241         VapourSynthCheckThread::unload();
242         AvisynthCheckThread::unload();
243
244         delete ui;
245 }
246
247 ///////////////////////////////////////////////////////////////////////////////
248 // Slots
249 ///////////////////////////////////////////////////////////////////////////////
250
251 /*
252  * The "add" button was clicked
253  */
254 void MainWindow::addButtonPressed()
255 {
256         ENSURE_APP_IS_IDLE();
257         m_status = STATUS_BLOCKED;
258
259         qDebug("MainWindow::addButtonPressed");
260         bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
261         QString sourceFileName, outputFileName;
262
263         if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
264         {
265                 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
266         }
267
268         m_status = STATUS_IDLE;
269 }
270
271 /*
272  * The "open" action was triggered
273  */
274 void MainWindow::openActionTriggered()
275 {
276         ENSURE_APP_IS_IDLE();
277         m_status = STATUS_BLOCKED;
278
279         QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
280         if(!fileList.empty())
281         {
282                 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
283                 if(fileList.count() > 1)
284                 {
285                         createJobMultiple(fileList);
286                 }
287                 else
288                 {
289                         bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
290                         QString sourceFileName(fileList.first()), outputFileName;
291                         if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
292                         {
293                                 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
294                         }
295                 }
296         }
297
298         m_status = STATUS_IDLE;
299 }
300
301 /*
302  * The "start" button was clicked
303  */
304 void MainWindow::startButtonPressed(void)
305 {
306         ENSURE_APP_IS_IDLE();
307         m_jobList->startJob(ui->jobsView->currentIndex());
308 }
309
310 /*
311  * The "abort" button was clicked
312  */
313 void MainWindow::abortButtonPressed(void)
314 {
315         ENSURE_APP_IS_IDLE();
316         m_status = STATUS_BLOCKED;
317
318         if(QMessageBox::question(this, tr("Abort Job?"), tr("<nobr>Do you really want to <b>abort</b> the selected job now?</nobr>"), tr("Back"), tr("Abort Job")) == 1)
319         {
320                 m_jobList->abortJob(ui->jobsView->currentIndex());
321         }
322
323         m_status = STATUS_IDLE;
324 }
325
326 /*
327  * The "delete" button was clicked
328  */
329 void MainWindow::deleteButtonPressed(void)
330 {
331         ENSURE_APP_IS_IDLE();
332         m_jobList->deleteJob(ui->jobsView->currentIndex());
333         m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
334 }
335
336 /*
337  * The "browse" button was clicked
338  */
339 void MainWindow::browseButtonPressed(void)
340 {
341         ENSURE_APP_IS_IDLE();
342         m_status = STATUS_BLOCKED;
343
344         QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
345         if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
346         {
347                 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
348         }
349         else
350         {
351                 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
352         }
353
354         m_status = STATUS_IDLE;
355 }
356
357 /*
358  * The "pause" button was clicked
359  */
360 void MainWindow::pauseButtonPressed(bool checked)
361 {
362         ENSURE_APP_IS_IDLE();
363
364         if(checked)
365         {
366                 m_jobList->pauseJob(ui->jobsView->currentIndex());
367         }
368         else
369         {
370                 m_jobList->resumeJob(ui->jobsView->currentIndex());
371         }
372 }
373
374 /*
375  * The "restart" button was clicked
376  */
377 void MainWindow::restartButtonPressed(void)
378 {
379         ENSURE_APP_IS_IDLE();
380
381         const QModelIndex index = ui->jobsView->currentIndex();
382         const OptionsModel *options = m_jobList->getJobOptions(index);
383         QString sourceFileName = m_jobList->getJobSourceFile(index);
384         QString outputFileName = m_jobList->getJobOutputFile(index);
385
386         if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
387         {
388                 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
389                 OptionsModel *tempOptions = new OptionsModel(*options);
390                 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
391                 {
392                         appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
393                 }
394                 X264_DELETE(tempOptions);
395         }
396 }
397
398 /*
399  * Job item selected by user
400  */
401 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
402 {
403         qDebug("Job selected: %d", current.row());
404         
405         if(ui->logView->model())
406         {
407                 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
408         }
409         
410         if(current.isValid())
411         {
412                 ui->logView->setModel(m_jobList->getLogFile(current));
413                 connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
414                 ui->logView->actions().first()->setEnabled(true);
415                 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
416
417                 ui->progressBar->setValue(m_jobList->getJobProgress(current));
418                 ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
419                 updateButtons(m_jobList->getJobStatus(current));
420                 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
421         }
422         else
423         {
424                 ui->logView->setModel(NULL);
425                 ui->logView->actions().first()->setEnabled(false);
426                 ui->progressBar->setValue(0);
427                 ui->editDetails->clear();
428                 updateButtons(JobStatus_Undefined);
429                 updateTaskbar(JobStatus_Undefined, QIcon());
430         }
431
432         ui->progressBar->repaint();
433 }
434
435 /*
436  * Handle update of job info (status, progress, details, etc)
437  */
438 void MainWindow::jobChangedData(const QModelIndex &topLeft, const  QModelIndex &bottomRight)
439 {
440         int selected = ui->jobsView->currentIndex().row();
441         
442         if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
443         {
444                 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
445                 {
446                         JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
447                         if(i == selected)
448                         {
449                                 qDebug("Current job changed status!");
450                                 updateButtons(status);
451                                 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
452                         }
453                         if((status == JobStatus_Completed) || (status == JobStatus_Failed))
454                         {
455                                 if(m_preferences->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
456                                 if(m_preferences->getShutdownComputer()) QTimer::singleShot(0, this, SLOT(shutdownComputer()));
457                                 if(m_preferences->getSaveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
458                         }
459                 }
460         }
461         if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
462         {
463                 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
464                 {
465                         if(i == selected)
466                         {
467                                 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
468                                 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
469                                 break;
470                         }
471                 }
472         }
473         if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
474         {
475                 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
476                 {
477                         if(i == selected)
478                         {
479                                 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
480                                 break;
481                         }
482                 }
483         }
484 }
485
486 /*
487  * Handle new log file content
488  */
489 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
490 {
491         QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
492 }
493
494 /*
495  * About screen
496  */
497 void MainWindow::showAbout(void)
498 {
499         ENSURE_APP_IS_IDLE();
500         m_status = STATUS_BLOCKED;
501         
502         if(AboutDialog *aboutDialog = new AboutDialog(this))
503         {
504                 aboutDialog->exec();
505                 X264_DELETE(aboutDialog);
506         }
507         
508         m_status = STATUS_IDLE;
509 }
510
511 /*
512  * Open web-link
513  */
514 void MainWindow::showWebLink(void)
515 {
516         ENSURE_APP_IS_IDLE();
517         
518         if(QObject *obj = QObject::sender())
519         {
520                 if(QAction *action = dynamic_cast<QAction*>(obj))
521                 {
522                         if(action->data().type() == QVariant::Url)
523                         {
524                                 QDesktopServices::openUrl(action->data().toUrl());
525                         }
526                 }
527         }
528 }
529
530 /*
531  * Pereferences dialog
532  */
533 void MainWindow::showPreferences(void)
534 {
535         ENSURE_APP_IS_IDLE();
536         m_status = STATUS_BLOCKED;
537
538         PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences, m_sysinfo);
539         preferences->exec();
540
541         X264_DELETE(preferences);
542         m_status = STATUS_IDLE;
543 }
544
545 /*
546  * Launch next job, after running job has finished
547  */
548 void MainWindow::launchNextJob(void)
549 {
550         qDebug("launchNextJob(void)");
551         
552         const int rows = m_jobList->rowCount(QModelIndex());
553
554         if(countRunningJobs() >= m_preferences->getMaxRunningJobCount())
555         {
556                 qDebug("Still have too many jobs running, won't launch next one yet!");
557                 return;
558         }
559
560         int startIdx= ui->jobsView->currentIndex().isValid() ? qBound(0, ui->jobsView->currentIndex().row(), rows-1) : 0;
561
562         for(int i = 0; i < rows; i++)
563         {
564                 int currentIdx = (i + startIdx) % rows;
565                 JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
566                 if(status == JobStatus_Enqueued)
567                 {
568                         if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
569                         {
570                                 ui->jobsView->selectRow(currentIdx);
571                                 return;
572                         }
573                 }
574         }
575                 
576         qWarning("No enqueued jobs left!");
577 }
578
579 /*
580  * Save log to text file
581  */
582 void MainWindow::saveLogFile(const QModelIndex &index)
583 {
584         if(index.isValid())
585         {
586                 if(LogFileModel *log = m_jobList->getLogFile(index))
587                 {
588                         QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
589                         QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
590                         QFile outFile(logFilePath);
591                         if(outFile.open(QIODevice::WriteOnly))
592                         {
593                                 QTextStream outStream(&outFile);
594                                 outStream.setCodec("UTF-8");
595                                 outStream.setGenerateByteOrderMark(true);
596                                 
597                                 const int rows = log->rowCount(QModelIndex());
598                                 for(int i = 0; i < rows; i++)
599                                 {
600                                         outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
601                                 }
602                                 outFile.close();
603                         }
604                         else
605                         {
606                                 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
607                         }
608                 }
609         }
610 }
611
612 /*
613  * Shut down the computer (with countdown)
614  */
615 void MainWindow::shutdownComputer(void)
616 {
617         qDebug("shutdownComputer(void)");
618         
619         if((m_status != STATUS_IDLE) && (m_status != STATUS_EXITTING))
620         {
621                 qWarning("Cannot shutdown computer at this time!");
622                 return;
623         }
624
625         if(countPendingJobs() > 0)
626         {
627                 qDebug("Still have pending jobs, won't shutdown yet!");
628                 return;
629         }
630         
631         const x264_status_t previousStatus = m_status;
632         m_status = STATUS_BLOCKED;
633
634         const int iTimeout = 30;
635         const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
636         const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
637         
638         qWarning("Initiating shutdown sequence!");
639         
640         QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
641         QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
642         cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
643         progressDialog.setModal(true);
644         progressDialog.setAutoClose(false);
645         progressDialog.setAutoReset(false);
646         progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
647         progressDialog.setWindowTitle(windowTitle());
648         progressDialog.setCancelButton(cancelButton);
649         progressDialog.show();
650         
651         QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
652         QApplication::setOverrideCursor(Qt::WaitCursor);
653         x264_play_sound(IDR_WAVE1, false);
654         QApplication::restoreOverrideCursor();
655         
656         QTimer timer;
657         timer.setInterval(1000);
658         timer.start();
659
660         QEventLoop eventLoop(this);
661         connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
662         connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
663
664         for(int i = 1; i <= iTimeout; i++)
665         {
666                 eventLoop.exec();
667                 if(progressDialog.wasCanceled())
668                 {
669                         progressDialog.close();
670                         m_status = previousStatus;
671                         return;
672                 }
673                 progressDialog.setValue(i+1);
674                 progressDialog.setLabelText(text.arg(iTimeout-i));
675                 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
676                 QApplication::processEvents();
677                 x264_play_sound(((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), false);
678         }
679         
680         qWarning("Shutting down !!!");
681         m_status = previousStatus;
682
683         if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
684         {
685                 qApp->closeAllWindows();
686         }
687
688 }
689
690 /*
691  * Main initialization function (called only once!)
692  */
693 void MainWindow::init(void)
694 {
695         if(m_status != STATUS_PRE_INIT)
696         {
697                 qWarning("Already initialized -> skipping!");
698                 return;
699         }
700
701         updateLabelPos();
702
703         //---------------------------------------
704         // Create the IPC listener thread
705         //---------------------------------------
706
707         if(m_ipc->isInitialized())
708         {
709                 connect(m_ipc, SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
710                 m_ipc->startListening();
711         }
712
713         //---------------------------------------
714         // Check required binaries
715         //---------------------------------------
716
717         QStringList binFiles;
718         for(OptionsModel::EncArch arch = OptionsModel::EncArch_x32; arch <= OptionsModel::EncArch_x64; NEXT(arch))
719         {
720                 for(OptionsModel::EncVariant varnt = OptionsModel::EncVariant_LoBit; varnt <= OptionsModel::EncVariant_HiBit; NEXT(varnt))
721                 {
722                         binFiles << ENC_BINARY(m_sysinfo, OptionsModel::EncType_X264, arch, varnt);
723                 }
724                 binFiles << AVS_BINARY(m_sysinfo, arch == OptionsModel::EncArch_x64);
725         }
726                 
727         qDebug("[Validating binaries]");
728         for(QStringList::ConstIterator iter = binFiles.constBegin(); iter != binFiles.constEnd(); iter++)
729         {
730                 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
731                 QFile *file = new QFile(*iter);
732                 qDebug("%s", file->fileName().toLatin1().constData());
733                 if(file->open(QIODevice::ReadOnly))
734                 {
735                         if(!x264_is_executable(file->fileName()))
736                         {
737                                 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(file->fileName())).replace("-", "&minus;"));
738                                 qFatal(QString("Binary is invalid: %1").arg(file->fileName()).toLatin1().constData());
739                                 X264_DELETE(file);
740                                 INIT_ERROR_EXIT();
741                         }
742                         m_toolsList << file;
743                 }
744                 else
745                 {
746                         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(file->fileName())).replace("-", "&minus;"));
747                         qFatal(QString("Binary not found: %1/toolset/%2").arg(m_sysinfo->getAppPath(), file->fileName()).toLatin1().constData());
748                         X264_DELETE(file);
749                         INIT_ERROR_EXIT();
750                 }
751         }
752         qDebug(" ");
753
754         //---------------------------------------
755         // Check x265 binaries
756         //---------------------------------------
757
758         binFiles.clear();
759         for(OptionsModel::EncArch arch = OptionsModel::EncArch_x32; arch <= OptionsModel::EncArch_x64; NEXT(arch))
760         {
761                 for(OptionsModel::EncVariant varnt = OptionsModel::EncVariant_LoBit; varnt <= OptionsModel::EncVariant_HiBit; NEXT(varnt))
762                 {
763                         binFiles << ENC_BINARY(m_sysinfo, OptionsModel::EncType_X265, arch, varnt);
764                 }
765         }
766
767         qDebug("[Checking for x265 support]");
768         bool bHaveX265 = true;
769         for(QStringList::ConstIterator iter = binFiles.constBegin(); iter != binFiles.constEnd(); iter++)
770         {
771                 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
772                 QFile *file = new QFile(*iter);
773                 qDebug("%s", file->fileName().toLatin1().constData());
774                 if(file->open(QIODevice::ReadOnly))
775                 {
776                         if(x264_is_executable(file->fileName()))
777                         {
778                                 m_toolsList << file;
779                                 continue;
780                         }
781                         X264_DELETE(file);
782                 }
783                 bHaveX265 = false;
784                 qWarning("x265 binaries not found or incomplete -> disable x265 support!");
785                 break;
786         }
787         if(bHaveX265)
788         {
789                 qDebug("x265 support is officially enabled now!");
790                 m_sysinfo->set256Support(true);
791         }
792         qDebug(" ");
793         
794         //---------------------------------------
795         // Check for portable mode
796         //---------------------------------------
797
798         if(x264_portable())
799         {
800                 bool ok = false;
801                 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
802                 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
803                 if(writeTest.open(QIODevice::WriteOnly))
804                 {
805                         ok = (writeTest.write(data) == strlen(data));
806                         writeTest.remove();
807                 }
808                 if(!ok)
809                 {
810                         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"));
811                         if(val != 1) INIT_ERROR_EXIT();
812                 }
813         }
814
815         //Pre-release popup
816         if(x264_is_prerelease())
817         {
818                 qsrand(time(NULL)); int rnd = qrand() % 3;
819                 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);
820                 if(rnd != val) INIT_ERROR_EXIT();
821         }
822
823         //---------------------------------------
824         // Check CPU capabilities
825         //---------------------------------------
826         
827         const QStringList arguments = x264_arguments();
828
829         //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
830         if(!m_sysinfo->hasMMXSupport())
831         {
832                 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"));
833                 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
834                 INIT_ERROR_EXIT();
835         }
836         else if(!m_sysinfo->hasSSESupport())
837         {
838                 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
839                 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"));
840                 if(val != 1) INIT_ERROR_EXIT();
841         }
842
843         //Skip version check (not recommended!)
844         if(CLIParser::checkFlag(CLI_PARAM_SKIP_X264_CHECK, arguments))
845         {
846                 qWarning("x264 version check disabled, you have been warned!\n");
847                 m_preferences->setSkipVersionTest(true);
848         }
849         
850         //Don't abort encoding process on timeout (not recommended!)
851         if(CLIParser::checkFlag(CLI_PARAM_NO_DEADLOCK, arguments))
852         {
853                 qWarning("Deadlock detection disabled, you have been warned!\n");
854                 m_preferences->setAbortOnTimeout(false);
855         }
856
857         //---------------------------------------
858         // Check Avisynth support
859         //---------------------------------------
860
861         if(!CLIParser::checkFlag(CLI_PARAM_SKIP_AVS_CHECK, arguments))
862         {
863                 qDebug("[Check for Avisynth support]");
864                 volatile double avisynthVersion = 0.0;
865                 const int result = AvisynthCheckThread::detect(&avisynthVersion);
866                 if(result < 0)
867                 {
868                         QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
869                         text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
870                         text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
871                         int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
872                         if(val != 1) INIT_ERROR_EXIT();
873                 }
874                 if(result && (avisynthVersion >= 2.5))
875                 {
876                         qDebug("Avisynth support is officially enabled now!");
877                         m_sysinfo->setAVSSupport(true);
878                 }
879                 else
880                 {
881                         if(!m_preferences->getDisableWarnings())
882                         {
883                                 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>");
884                                 text += tr("Please download and install Avisynth:").append("<br>").append(LINK("http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/"));
885                                 int val = QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
886                                 if(val == 1)
887                                 {
888                                         m_preferences->setDisableWarnings(true);
889                                         PreferencesModel::savePreferences(m_preferences);
890                                 }
891
892                         }
893                 }
894                 qDebug(" ");
895         }
896
897         //---------------------------------------
898         // Check VapurSynth support
899         //---------------------------------------
900
901         if(!CLIParser::checkFlag(CLI_PARAM_SKIP_VPS_CHECK, arguments))
902         {
903                 qDebug("[Check for VapourSynth support]");
904                 QString vapoursynthPath;
905                 const int result = VapourSynthCheckThread::detect(vapoursynthPath);
906                 if(result < 0)
907                 {
908                         QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
909                         text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
910                         text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
911                         const int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
912                         if(val != 1) INIT_ERROR_EXIT();
913                 }
914                 if(result && (!vapoursynthPath.isEmpty()))
915                 {
916                         qDebug("VapourSynth support is officially enabled now!");
917                         m_sysinfo->setVPSSupport(true);
918                         m_sysinfo->setVPSPath(vapoursynthPath);
919                 }
920                 else
921                 {
922                         if(!m_preferences->getDisableWarnings())
923                         {
924                                 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>");
925                                 text += tr("Please download and install VapourSynth for Windows (R19 or later):").append("<br>").append(LINK("http://www.vapoursynth.com/")).append("<br><br>");
926                                 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>");
927                                 const int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
928                                 if(val == 1)
929                                 {
930                                         m_preferences->setDisableWarnings(true);
931                                         PreferencesModel::savePreferences(m_preferences);
932                                 }
933                         }
934                 }
935                 qDebug(" ");
936         }
937
938         //---------------------------------------
939         // Check for Expiration
940         //---------------------------------------
941
942         if(x264_version_date().addMonths(6) < x264_current_date_safe())
943         {
944                 QString text;
945                 text += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(tr("Your version of Simple x264 Launcher is more than 6 months old!").replace("-", "&minus;"));
946                 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("-", "&minus;"), QString::fromLatin1(update_url));
947                 text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace("-", "&minus;"));
948                 QMessageBox msgBox(this);
949                 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
950                 msgBox.setWindowTitle(tr("Update Notification"));
951                 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
952                 msgBox.setText(text);
953                 QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
954                 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
955                 QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
956                 btn2->setEnabled(false);
957                 btn3->setVisible(false);
958                 QTimer::singleShot(7500, btn2, SLOT(hide()));
959                 QTimer::singleShot(7500, btn3, SLOT(show()));
960                 if(msgBox.exec() == 0)
961                 {
962                         m_status = STATUS_IDLE;
963                         QTimer::singleShot(0, this, SLOT(checkUpdates()));
964                         return;
965                 }
966         }
967
968         //---------------------------------------
969         // Finish initialization
970         //---------------------------------------
971
972         //Set Window title
973         setWindowTitle(QString("%1 (%2)").arg(windowTitle(), m_sysinfo->hasX64Support() ? "64-Bit" : "32-Bit"));
974
975         //Enable drag&drop support for this window, required for Qt v4.8.4+
976         setAcceptDrops(true);
977
978         //Update app staus
979         m_status = STATUS_IDLE;
980
981         //Try adding files from command-line
982         if(!parseCommandLineArgs())
983         {
984                 //Update reminder
985                 if((!m_preferences->getNoUpdateReminder()) && (m_recentlyUsed->lastUpdateCheck() + 14 < x264_current_date_safe().toJulianDay()))
986                 {
987                         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)
988                         {
989                                 QTimer::singleShot(0, this, SLOT(checkUpdates()));
990                                 return;
991                         }
992                 }
993         }
994
995         //Load queued jobs
996         if(m_jobList->loadQueuedJobs(m_sysinfo) > 0)
997         {
998                 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
999         }
1000 }
1001
1002 /*
1003  * Update the label position
1004  */
1005 void MainWindow::updateLabelPos(void)
1006 {
1007         const QWidget *const viewPort = ui->jobsView->viewport();
1008         m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
1009 }
1010
1011 /*
1012  * Copy the complete log to the clipboard
1013  */
1014 void MainWindow::copyLogToClipboard(bool checked)
1015 {
1016         qDebug("copyLogToClipboard");
1017         
1018         if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1019         {
1020                 log->copyToClipboard();
1021                 x264_beep(x264_beep_info);
1022         }
1023 }
1024
1025 /*
1026  * Process the dropped files
1027  */
1028 void MainWindow::handlePendingFiles(void)
1029 {
1030         if((m_status == STATUS_IDLE) || (m_status == STATUS_AWAITING))
1031         {
1032                 qDebug("MainWindow::handlePendingFiles");
1033                 if(!m_pendingFiles->isEmpty())
1034                 {
1035                         QStringList pendingFiles(*m_pendingFiles);
1036                         m_pendingFiles->clear();
1037                         createJobMultiple(pendingFiles);
1038                 }
1039                 qDebug("Leave from MainWindow::handlePendingFiles!");
1040                 m_status = STATUS_IDLE;
1041         }
1042 }
1043
1044 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1045 {
1046         if((m_status != STATUS_IDLE) && (m_status != STATUS_AWAITING))
1047         {
1048                 qWarning("Cannot accapt commands at this time -> discarding!");
1049                 return;
1050         }
1051         
1052         x264_bring_to_front(this);
1053         
1054 #ifdef IPC_LOGGING
1055         qDebug("\n---------- IPC ----------");
1056         qDebug("CommandId: %d", command);
1057         for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1058         {
1059                 qDebug("Arguments: %s", iter->toUtf8().constData());
1060         }
1061         qDebug("The Flags: 0x%08X", flags);
1062         qDebug("---------- IPC ----------\n");
1063 #endif //IPC_LOGGING
1064
1065         switch(command)
1066         {
1067         case IPC_OPCODE_PING:
1068                 qDebug("Received a PING request from another instance!");
1069                 x264_blink_window(this, 5, 125);
1070                 break;
1071         case IPC_OPCODE_ADD_FILE:
1072                 if(!args.isEmpty())
1073                 {
1074                         if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1075                         {
1076                                 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1077                                 if(m_status != STATUS_AWAITING)
1078                                 {
1079                                         m_status = STATUS_AWAITING;
1080                                         QTimer::singleShot(5000, this, SLOT(handlePendingFiles()));
1081                                 }
1082                         }
1083                         else
1084                         {
1085                                 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1086                         }
1087                 }
1088                 break;
1089         case IPC_OPCODE_ADD_JOB:
1090                 if(args.size() >= 3)
1091                 {
1092                         if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1093                         {
1094                                 OptionsModel options(m_sysinfo);
1095                                 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1096                                 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1097                                 {
1098                                         if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1099                                         {
1100                                                 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1101                                         }
1102                                 }
1103                                 if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
1104                                 if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
1105                                 appendJob(args[0], args[1], &options, runImmediately);
1106                         }
1107                         else
1108                         {
1109                                 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1110                         }
1111                 }
1112                 break;
1113         default:
1114                 THROW("Unknown command received!");
1115         }
1116 }
1117
1118 void MainWindow::checkUpdates(void)
1119 {
1120         ENSURE_APP_IS_IDLE();
1121         m_status = STATUS_BLOCKED;
1122
1123         if(countRunningJobs() > 0)
1124         {
1125                 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1126                 m_status = STATUS_IDLE;
1127                 return;
1128         }
1129
1130         UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo);
1131         const int ret = updater->exec();
1132
1133         if(updater->getSuccess())
1134         {
1135                 m_recentlyUsed->setLastUpdateCheck(x264_current_date_safe().toJulianDay());
1136                 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
1137         }
1138
1139         if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1140         {
1141                 m_status = STATUS_EXITTING;
1142                 qWarning("Exitting program to install update...");
1143                 close();
1144                 QApplication::quit();
1145         }
1146
1147         X264_DELETE(updater);
1148
1149         if(m_status != STATUS_EXITTING)
1150         {
1151                 m_status = STATUS_IDLE;
1152         }
1153 }
1154
1155 ///////////////////////////////////////////////////////////////////////////////
1156 // Event functions
1157 ///////////////////////////////////////////////////////////////////////////////
1158
1159 /*
1160  * Window shown event
1161  */
1162 void MainWindow::showEvent(QShowEvent *e)
1163 {
1164         QMainWindow::showEvent(e);
1165
1166         if(m_status == STATUS_PRE_INIT)
1167         {
1168                 QTimer::singleShot(0, this, SLOT(init()));
1169         }
1170 }
1171
1172 /*
1173  * Window close event
1174  */
1175 void MainWindow::closeEvent(QCloseEvent *e)
1176 {
1177         bool bJobsHaveBeenSaved = false;
1178
1179         if((m_status != STATUS_IDLE) && (m_status != STATUS_EXITTING))
1180         {
1181                 e->ignore();
1182                 qWarning("Cannot close window at this time!");
1183                 return;
1184         }
1185
1186         //Make sure we have no running jobs left!
1187         if(m_status != STATUS_EXITTING)
1188         {
1189                 if(countRunningJobs() > 0)
1190                 {
1191                         e->ignore();
1192                         m_status = STATUS_BLOCKED;
1193                         QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
1194                         m_status = STATUS_IDLE;
1195                         return;
1196                 }
1197
1198                 //Save pending jobs for next time, if desired by user
1199                 if(countPendingJobs() > 0)
1200                 {
1201                         m_status = STATUS_BLOCKED;
1202                         int ret = QMessageBox::question(this, tr("Jobs Are Pending"), tr("You still have pending jobs. How do you want to proceed?"), tr("Save Pending Jobs"), tr("Discard"));
1203                         if(ret == 0)
1204                         {
1205                                 if(m_jobList->saveQueuedJobs() > 0)
1206                                 {
1207                                         bJobsHaveBeenSaved = true;
1208                                 }
1209                         }
1210                         else
1211                         {
1212                                 if(QMessageBox::warning(this, tr("Jobs Are Pending"), tr("Do you really want to discard all pending jobs?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
1213                                 {
1214                                         e->ignore();
1215                                         m_status = STATUS_IDLE;
1216                                         return;
1217                                 }
1218                         }
1219                 }
1220         }
1221         
1222         //Clear "old" pending jobs for next startup (only if we have not saved "new" jobs already!)
1223         if(!bJobsHaveBeenSaved)
1224         {
1225                 m_jobList->clearQueuedJobs();
1226         }
1227
1228         //Delete remaining jobs
1229         while(m_jobList->rowCount(QModelIndex()) > 0)
1230         {
1231                 if((m_jobList->rowCount(QModelIndex()) % 10) == 0)
1232                 {
1233                         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1234                 }
1235                 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1236                 {
1237                         e->ignore();
1238                         m_status = STATUS_BLOCKED;
1239                         QMessageBox::warning(this, tr("Failed To Exit"), tr("Warning: At least one job could not be deleted!"));
1240                         m_status = STATUS_IDLE;
1241                 }
1242         }
1243         
1244         m_status = STATUS_EXITTING;
1245         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1246         QMainWindow::closeEvent(e);
1247 }
1248
1249 /*
1250  * Window resize event
1251  */
1252 void MainWindow::resizeEvent(QResizeEvent *e)
1253 {
1254         QMainWindow::resizeEvent(e);
1255         updateLabelPos();
1256 }
1257
1258 /*
1259  * Event filter
1260  */
1261 bool MainWindow::eventFilter(QObject *o, QEvent *e)
1262 {
1263         if((o == ui->labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
1264         {
1265                 QTimer::singleShot(0, this, SLOT(showAbout()));
1266                 return true;
1267         }
1268         return false;
1269 }
1270
1271 /*
1272  * Win32 message filter
1273  */
1274 bool MainWindow::winEvent(MSG *message, long *result)
1275 {
1276         return WinSevenTaskbar::handleWinEvent(message, result);
1277 }
1278
1279 /*
1280  * File dragged over window
1281  */
1282 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1283 {
1284         bool accept[2] = {false, false};
1285
1286         foreach(const QString &fmt, event->mimeData()->formats())
1287         {
1288                 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1289                 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1290         }
1291
1292         if(accept[0] && accept[1])
1293         {
1294                 event->acceptProposedAction();
1295         }
1296 }
1297
1298 /*
1299  * File dropped onto window
1300  */
1301 void MainWindow::dropEvent(QDropEvent *event)
1302 {
1303         if((m_status != STATUS_IDLE) && (m_status != STATUS_AWAITING))
1304         {
1305                 qWarning("Cannot accept drooped files at this time -> discarding!");
1306                 return;
1307         }
1308
1309         QStringList droppedFiles;
1310         QList<QUrl> urls = event->mimeData()->urls();
1311
1312         while(!urls.isEmpty())
1313         {
1314                 QUrl currentUrl = urls.takeFirst();
1315                 QFileInfo file(currentUrl.toLocalFile());
1316                 if(file.exists() && file.isFile())
1317                 {
1318                         qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1319                         droppedFiles << file.canonicalFilePath();
1320                 }
1321         }
1322         
1323         if(droppedFiles.count() > 0)
1324         {
1325                 m_pendingFiles->append(droppedFiles);
1326                 m_pendingFiles->sort();
1327                 if(m_status != STATUS_AWAITING)
1328                 {
1329                         m_status = STATUS_AWAITING;
1330                         QTimer::singleShot(0, this, SLOT(handlePendingFiles()));
1331                 }
1332         }
1333 }
1334
1335 ///////////////////////////////////////////////////////////////////////////////
1336 // Private functions
1337 ///////////////////////////////////////////////////////////////////////////////
1338
1339 /*
1340  * Creates a new job
1341  */
1342 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1343 {
1344         bool okay = false;
1345         AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed, m_sysinfo, m_preferences);
1346
1347         addDialog->setRunImmediately(runImmediately);
1348         if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1349         if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1350         if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1351
1352         const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1353         if(multiFile)
1354         {
1355                 addDialog->setSourceEditable(false);
1356                 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1357                 addDialog->setApplyToAllVisible(applyToAll);
1358         }
1359
1360         if(addDialog->exec() == QDialog::Accepted)
1361         {
1362                 sourceFileName = addDialog->sourceFile();
1363                 outputFileName = addDialog->outputFile();
1364                 runImmediately = addDialog->runImmediately();
1365                 if(applyToAll)
1366                 {
1367                         *applyToAll = addDialog->applyToAll();
1368                 }
1369                 okay = true;
1370         }
1371
1372         X264_DELETE(addDialog);
1373         return okay;
1374 }
1375
1376 /*
1377  * Creates a new job from *multiple* files
1378  */
1379 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1380 {
1381         QStringList::ConstIterator iter;
1382         bool applyToAll = false, runImmediately = false;
1383         int counter = 0;
1384
1385         //Add files individually
1386         for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1387         {
1388                 runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1389                 QString sourceFileName(*iter), outputFileName;
1390                 if(createJob(sourceFileName, outputFileName, m_options, runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1391                 {
1392                         if(appendJob(sourceFileName, outputFileName, m_options, runImmediately))
1393                         {
1394                                 continue;
1395                         }
1396                 }
1397                 return false;
1398         }
1399
1400         //Add remaining files
1401         while(applyToAll && (iter != filePathIn.constEnd()))
1402         {
1403                 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1404                 const QString sourceFileName = *iter;
1405                 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
1406                 if(!appendJob(sourceFileName, outputFileName, m_options, runImmediatelyTmp))
1407                 {
1408                         return false;
1409                 }
1410                 iter++;
1411         }
1412
1413         return true;
1414 }
1415
1416 /*
1417  * Append a new job
1418  */
1419 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1420 {
1421         bool okay = false;
1422         EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo, m_preferences);
1423         QModelIndex newIndex = m_jobList->insertJob(thrd);
1424
1425         if(newIndex.isValid())
1426         {
1427                 if(runImmediately)
1428                 {
1429                         ui->jobsView->selectRow(newIndex.row());
1430                         QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1431                         m_jobList->startJob(newIndex);
1432                 }
1433
1434                 okay = true;
1435         }
1436
1437         m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1438         return okay;
1439 }
1440
1441 /*
1442  * Jobs that are not completed (or failed, or aborted) yet
1443  */
1444 unsigned int MainWindow::countPendingJobs(void)
1445 {
1446         unsigned int count = 0;
1447         const int rows = m_jobList->rowCount(QModelIndex());
1448
1449         for(int i = 0; i < rows; i++)
1450         {
1451                 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1452                 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1453                 {
1454                         count++;
1455                 }
1456         }
1457
1458         return count;
1459 }
1460
1461 /*
1462  * Jobs that are still active, i.e. not terminated or enqueued
1463  */
1464 unsigned int MainWindow::countRunningJobs(void)
1465 {
1466         unsigned int count = 0;
1467         const int rows = m_jobList->rowCount(QModelIndex());
1468
1469         for(int i = 0; i < rows; i++)
1470         {
1471                 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1472                 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1473                 {
1474                         count++;
1475                 }
1476         }
1477
1478         return count;
1479 }
1480
1481 /*
1482  * Update all buttons with respect to current job status
1483  */
1484 void MainWindow::updateButtons(JobStatus status)
1485 {
1486         qDebug("MainWindow::updateButtons(void)");
1487
1488         ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1489         ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1490         ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1491         ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1492
1493         ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1494         ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1495         ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1496
1497         ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1498         ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1499         ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1500         ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1501
1502         ui->editDetails->setEnabled(status != JobStatus_Paused);
1503 }
1504
1505 /*
1506  * Update the taskbar with current job status
1507  */
1508 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1509 {
1510         qDebug("MainWindow::updateTaskbar(void)");
1511
1512         switch(status)
1513         {
1514         case JobStatus_Undefined:
1515                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1516                 break;
1517         case JobStatus_Aborting:
1518         case JobStatus_Starting:
1519         case JobStatus_Pausing:
1520         case JobStatus_Resuming:
1521                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1522                 break;
1523         case JobStatus_Aborted:
1524         case JobStatus_Failed:
1525                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1526                 break;
1527         case JobStatus_Paused:
1528                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1529                 break;
1530         default:
1531                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1532                 break;
1533         }
1534
1535         switch(status)
1536         {
1537         case JobStatus_Aborting:
1538         case JobStatus_Starting:
1539         case JobStatus_Pausing:
1540         case JobStatus_Resuming:
1541                 break;
1542         default:
1543                 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
1544                 break;
1545         }
1546
1547         WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);
1548 }
1549
1550 /*
1551  * Parse command-line arguments
1552  */
1553 bool MainWindow::parseCommandLineArgs(void)
1554 {
1555         bool bCommandAccepted = false;
1556         unsigned int flags = 0;
1557
1558         //Initialize command-line parser
1559         CLIParser parser(x264_arguments());
1560         int identifier;
1561         QStringList options;
1562
1563         //Process all command-line arguments
1564         while(parser.nextOption(identifier, &options))
1565         {
1566                 switch(identifier)
1567                 {
1568                 case CLI_PARAM_ADD_FILE:
1569                         handleCommand(IPC_OPCODE_ADD_FILE, options, flags);
1570                         bCommandAccepted = true;
1571                         break;
1572                 case CLI_PARAM_ADD_JOB:
1573                         handleCommand(IPC_OPCODE_ADD_JOB, options, flags);
1574                         bCommandAccepted = true;
1575                         break;
1576                 case CLI_PARAM_FORCE_START:
1577                         flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1578                         break;
1579                 case CLI_PARAM_NO_FORCE_START:
1580                         flags = (flags & (~IPC_FLAG_FORCE_START));
1581                         break;
1582                 case CLI_PARAM_FORCE_ENQUEUE:
1583                         flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1584                         break;
1585                 case CLI_PARAM_NO_FORCE_ENQUEUE:
1586                         flags = (flags & (~IPC_FLAG_FORCE_ENQUEUE));
1587                         break;
1588                 }
1589         }
1590
1591         return bCommandAccepted;
1592 }