OSDN Git Service

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