OSDN Git Service

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