OSDN Git Service

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