OSDN Git Service

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