OSDN Git Service

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