OSDN Git Service

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