OSDN Git Service

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