OSDN Git Service

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