OSDN Git Service

Each encoder now can return an AbstractEncoderInfo object, which contains the 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(tr("Simple %1 Launcher").arg(m_sysinfo->has256Support() ? "x264/x265" : "x264"), 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
996 /*
997  * Update the label position
998  */
999 void MainWindow::updateLabelPos(void)
1000 {
1001         const QWidget *const viewPort = ui->jobsView->viewport();
1002         m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
1003 }
1004
1005 /*
1006  * Copy the complete log to the clipboard
1007  */
1008 void MainWindow::copyLogToClipboard(bool checked)
1009 {
1010         qDebug("copyLogToClipboard");
1011         
1012         if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1013         {
1014                 log->copyToClipboard();
1015                 x264_beep(x264_beep_info);
1016         }
1017 }
1018
1019 /*
1020  * Process the dropped files
1021  */
1022 void MainWindow::handlePendingFiles(void)
1023 {
1024         if((m_status == STATUS_IDLE) || (m_status == STATUS_AWAITING))
1025         {
1026                 qDebug("MainWindow::handlePendingFiles");
1027                 if(!m_pendingFiles->isEmpty())
1028                 {
1029                         QStringList pendingFiles(*m_pendingFiles);
1030                         m_pendingFiles->clear();
1031                         createJobMultiple(pendingFiles);
1032                 }
1033                 qDebug("Leave from MainWindow::handlePendingFiles!");
1034                 m_status = STATUS_IDLE;
1035         }
1036 }
1037
1038 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1039 {
1040         if((m_status != STATUS_IDLE) && (m_status != STATUS_AWAITING))
1041         {
1042                 qWarning("Cannot accapt commands at this time -> discarding!");
1043                 return;
1044         }
1045         
1046         x264_bring_to_front(this);
1047         
1048 #ifdef IPC_LOGGING
1049         qDebug("\n---------- IPC ----------");
1050         qDebug("CommandId: %d", command);
1051         for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1052         {
1053                 qDebug("Arguments: %s", iter->toUtf8().constData());
1054         }
1055         qDebug("The Flags: 0x%08X", flags);
1056         qDebug("---------- IPC ----------\n");
1057 #endif //IPC_LOGGING
1058
1059         switch(command)
1060         {
1061         case IPC_OPCODE_PING:
1062                 qDebug("Received a PING request from another instance!");
1063                 x264_blink_window(this, 5, 125);
1064                 break;
1065         case IPC_OPCODE_ADD_FILE:
1066                 if(!args.isEmpty())
1067                 {
1068                         if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1069                         {
1070                                 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1071                                 if(m_status != STATUS_AWAITING)
1072                                 {
1073                                         m_status = STATUS_AWAITING;
1074                                         QTimer::singleShot(5000, this, SLOT(handlePendingFiles()));
1075                                 }
1076                         }
1077                         else
1078                         {
1079                                 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1080                         }
1081                 }
1082                 break;
1083         case IPC_OPCODE_ADD_JOB:
1084                 if(args.size() >= 3)
1085                 {
1086                         if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1087                         {
1088                                 OptionsModel options(m_sysinfo);
1089                                 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1090                                 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1091                                 {
1092                                         if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1093                                         {
1094                                                 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1095                                         }
1096                                 }
1097                                 if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
1098                                 if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
1099                                 appendJob(args[0], args[1], &options, runImmediately);
1100                         }
1101                         else
1102                         {
1103                                 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1104                         }
1105                 }
1106                 break;
1107         default:
1108                 throw std::exception("Unknown command received!");
1109         }
1110 }
1111
1112 void MainWindow::checkUpdates(void)
1113 {
1114         ENSURE_APP_IS_IDLE();
1115         m_status = STATUS_BLOCKED;
1116
1117         if(countRunningJobs() > 0)
1118         {
1119                 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1120                 m_status = STATUS_IDLE;
1121                 return;
1122         }
1123
1124         UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo);
1125         const int ret = updater->exec();
1126
1127         if(updater->getSuccess())
1128         {
1129                 m_recentlyUsed->setLastUpdateCheck(x264_current_date_safe().toJulianDay());
1130                 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
1131         }
1132
1133         if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1134         {
1135                 m_status = STATUS_EXITTING;
1136                 qWarning("Exitting program to install update...");
1137                 close();
1138                 QApplication::quit();
1139         }
1140
1141         X264_DELETE(updater);
1142
1143         if(m_status != STATUS_EXITTING)
1144         {
1145                 m_status = STATUS_IDLE;
1146         }
1147 }
1148
1149 ///////////////////////////////////////////////////////////////////////////////
1150 // Event functions
1151 ///////////////////////////////////////////////////////////////////////////////
1152
1153 /*
1154  * Window shown event
1155  */
1156 void MainWindow::showEvent(QShowEvent *e)
1157 {
1158         QMainWindow::showEvent(e);
1159
1160         if(m_status == STATUS_PRE_INIT)
1161         {
1162                 setWindowTitle(tr("%1 - Starting...").arg(windowTitle()));
1163                 QTimer::singleShot(0, this, SLOT(init()));
1164         }
1165 }
1166
1167 /*
1168  * Window close event
1169  */
1170 void MainWindow::closeEvent(QCloseEvent *e)
1171 {
1172         if((m_status != STATUS_IDLE) && (m_status != STATUS_EXITTING))
1173         {
1174                 e->ignore();
1175                 qWarning("Cannot close window at this time!");
1176                 return;
1177         }
1178
1179         if(m_status != STATUS_EXITTING)
1180         {
1181                 if(countRunningJobs() > 0)
1182                 {
1183                         e->ignore();
1184                         m_status = STATUS_BLOCKED;
1185                         QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
1186                         m_status = STATUS_IDLE;
1187                         return;
1188                 }
1189         
1190                 if(countPendingJobs() > 0)
1191                 {
1192                         m_status = STATUS_BLOCKED;
1193                         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);
1194                         if(ret != QMessageBox::Yes)
1195                         {
1196                                 e->ignore();
1197                                 m_status = STATUS_IDLE;
1198                                 return;
1199                         }
1200                 }
1201         }
1202
1203         while(m_jobList->rowCount(QModelIndex()) > 0)
1204         {
1205                 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1206                 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1207                 {
1208                         e->ignore();
1209                         m_status = STATUS_BLOCKED;
1210                         QMessageBox::warning(this, tr("Failed To Exit"), tr("Sorry, at least one job could not be deleted!"));
1211                         m_status = STATUS_IDLE;
1212                         return;
1213                 }
1214         }
1215         
1216         m_status = STATUS_EXITTING;
1217         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1218         QMainWindow::closeEvent(e);
1219 }
1220
1221 /*
1222  * Window resize event
1223  */
1224 void MainWindow::resizeEvent(QResizeEvent *e)
1225 {
1226         QMainWindow::resizeEvent(e);
1227         updateLabelPos();
1228 }
1229
1230 /*
1231  * Event filter
1232  */
1233 bool MainWindow::eventFilter(QObject *o, QEvent *e)
1234 {
1235         if((o == ui->labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
1236         {
1237                 QTimer::singleShot(0, this, SLOT(showAbout()));
1238                 return true;
1239         }
1240         return false;
1241 }
1242
1243 /*
1244  * Win32 message filter
1245  */
1246 bool MainWindow::winEvent(MSG *message, long *result)
1247 {
1248         return WinSevenTaskbar::handleWinEvent(message, result);
1249 }
1250
1251 /*
1252  * File dragged over window
1253  */
1254 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1255 {
1256         bool accept[2] = {false, false};
1257
1258         foreach(const QString &fmt, event->mimeData()->formats())
1259         {
1260                 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1261                 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1262         }
1263
1264         if(accept[0] && accept[1])
1265         {
1266                 event->acceptProposedAction();
1267         }
1268 }
1269
1270 /*
1271  * File dropped onto window
1272  */
1273 void MainWindow::dropEvent(QDropEvent *event)
1274 {
1275         if((m_status != STATUS_IDLE) && (m_status != STATUS_AWAITING))
1276         {
1277                 qWarning("Cannot accept drooped files at this time -> discarding!");
1278                 return;
1279         }
1280
1281         QStringList droppedFiles;
1282         QList<QUrl> urls = event->mimeData()->urls();
1283
1284         while(!urls.isEmpty())
1285         {
1286                 QUrl currentUrl = urls.takeFirst();
1287                 QFileInfo file(currentUrl.toLocalFile());
1288                 if(file.exists() && file.isFile())
1289                 {
1290                         qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1291                         droppedFiles << file.canonicalFilePath();
1292                 }
1293         }
1294         
1295         if(droppedFiles.count() > 0)
1296         {
1297                 m_pendingFiles->append(droppedFiles);
1298                 m_pendingFiles->sort();
1299                 if(m_status != STATUS_AWAITING)
1300                 {
1301                         m_status = STATUS_AWAITING;
1302                         QTimer::singleShot(0, this, SLOT(handlePendingFiles()));
1303                 }
1304         }
1305 }
1306
1307 ///////////////////////////////////////////////////////////////////////////////
1308 // Private functions
1309 ///////////////////////////////////////////////////////////////////////////////
1310
1311 /*
1312  * Creates a new job
1313  */
1314 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1315 {
1316         bool okay = false;
1317         AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed, m_sysinfo, m_preferences);
1318
1319         addDialog->setRunImmediately(runImmediately);
1320         if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1321         if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1322         if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1323
1324         const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1325         if(multiFile)
1326         {
1327                 addDialog->setSourceEditable(false);
1328                 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1329                 addDialog->setApplyToAllVisible(applyToAll);
1330         }
1331
1332         if(addDialog->exec() == QDialog::Accepted)
1333         {
1334                 sourceFileName = addDialog->sourceFile();
1335                 outputFileName = addDialog->outputFile();
1336                 runImmediately = addDialog->runImmediately();
1337                 if(applyToAll)
1338                 {
1339                         *applyToAll = addDialog->applyToAll();
1340                 }
1341                 okay = true;
1342         }
1343
1344         X264_DELETE(addDialog);
1345         return okay;
1346 }
1347
1348 /*
1349  * Creates a new job from *multiple* files
1350  */
1351 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1352 {
1353         QStringList::ConstIterator iter;
1354         bool applyToAll = false, runImmediately = false;
1355         int counter = 0;
1356
1357         //Add files individually
1358         for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1359         {
1360                 runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1361                 QString sourceFileName(*iter), outputFileName;
1362                 if(createJob(sourceFileName, outputFileName, m_options, runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1363                 {
1364                         if(appendJob(sourceFileName, outputFileName, m_options, runImmediately))
1365                         {
1366                                 continue;
1367                         }
1368                 }
1369                 return false;
1370         }
1371
1372         //Add remaining files
1373         while(applyToAll && (iter != filePathIn.constEnd()))
1374         {
1375                 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1376                 const QString sourceFileName = *iter;
1377                 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
1378                 if(!appendJob(sourceFileName, outputFileName, m_options, runImmediatelyTmp))
1379                 {
1380                         return false;
1381                 }
1382                 iter++;
1383         }
1384
1385         return true;
1386 }
1387
1388 /*
1389  * Append a new job
1390  */
1391 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1392 {
1393         bool okay = false;
1394         EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo, m_preferences);
1395         QModelIndex newIndex = m_jobList->insertJob(thrd);
1396
1397         if(newIndex.isValid())
1398         {
1399                 if(runImmediately)
1400                 {
1401                         ui->jobsView->selectRow(newIndex.row());
1402                         QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1403                         m_jobList->startJob(newIndex);
1404                 }
1405
1406                 okay = true;
1407         }
1408
1409         m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1410         return okay;
1411 }
1412
1413 /*
1414  * Jobs that are not completed (or failed, or aborted) yet
1415  */
1416 unsigned int MainWindow::countPendingJobs(void)
1417 {
1418         unsigned int count = 0;
1419         const int rows = m_jobList->rowCount(QModelIndex());
1420
1421         for(int i = 0; i < rows; i++)
1422         {
1423                 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1424                 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1425                 {
1426                         count++;
1427                 }
1428         }
1429
1430         return count;
1431 }
1432
1433 /*
1434  * Jobs that are still active, i.e. not terminated or enqueued
1435  */
1436 unsigned int MainWindow::countRunningJobs(void)
1437 {
1438         unsigned int count = 0;
1439         const int rows = m_jobList->rowCount(QModelIndex());
1440
1441         for(int i = 0; i < rows; i++)
1442         {
1443                 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1444                 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1445                 {
1446                         count++;
1447                 }
1448         }
1449
1450         return count;
1451 }
1452
1453 /*
1454  * Update all buttons with respect to current job status
1455  */
1456 void MainWindow::updateButtons(JobStatus status)
1457 {
1458         qDebug("MainWindow::updateButtons(void)");
1459
1460         ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1461         ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1462         ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1463         ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1464
1465         ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1466         ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1467         ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1468
1469         ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1470         ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1471         ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1472         ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1473
1474         ui->editDetails->setEnabled(status != JobStatus_Paused);
1475 }
1476
1477 /*
1478  * Update the taskbar with current job status
1479  */
1480 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1481 {
1482         qDebug("MainWindow::updateTaskbar(void)");
1483
1484         switch(status)
1485         {
1486         case JobStatus_Undefined:
1487                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1488                 break;
1489         case JobStatus_Aborting:
1490         case JobStatus_Starting:
1491         case JobStatus_Pausing:
1492         case JobStatus_Resuming:
1493                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1494                 break;
1495         case JobStatus_Aborted:
1496         case JobStatus_Failed:
1497                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1498                 break;
1499         case JobStatus_Paused:
1500                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1501                 break;
1502         default:
1503                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1504                 break;
1505         }
1506
1507         switch(status)
1508         {
1509         case JobStatus_Aborting:
1510         case JobStatus_Starting:
1511         case JobStatus_Pausing:
1512         case JobStatus_Resuming:
1513                 break;
1514         default:
1515                 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
1516                 break;
1517         }
1518
1519         WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);
1520 }
1521
1522 /*
1523  * Parse command-line arguments
1524  */
1525 bool MainWindow::parseCommandLineArgs(void)
1526 {
1527         bool bCommandAccepted = false;
1528         unsigned int flags = 0;
1529
1530         //Initialize command-line parser
1531         CLIParser parser(x264_arguments());
1532         int identifier;
1533         QStringList options;
1534
1535         //Process all command-line arguments
1536         while(parser.nextOption(identifier, &options))
1537         {
1538                 switch(identifier)
1539                 {
1540                 case CLI_PARAM_ADD_FILE:
1541                         handleCommand(IPC_OPCODE_ADD_FILE, options, flags);
1542                         bCommandAccepted = true;
1543                         break;
1544                 case CLI_PARAM_ADD_JOB:
1545                         handleCommand(IPC_OPCODE_ADD_JOB, options, flags);
1546                         bCommandAccepted = true;
1547                         break;
1548                 case CLI_PARAM_FORCE_START:
1549                         flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1550                         break;
1551                 case CLI_PARAM_NO_FORCE_START:
1552                         flags = (flags & (~IPC_FLAG_FORCE_START));
1553                         break;
1554                 case CLI_PARAM_FORCE_ENQUEUE:
1555                         flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1556                         break;
1557                 case CLI_PARAM_NO_FORCE_ENQUEUE:
1558                         flags = (flags & (~IPC_FLAG_FORCE_ENQUEUE));
1559                         break;
1560                 }
1561         }
1562
1563         return bCommandAccepted;
1564 }