OSDN Git Service

Added option to choose between 8-Bit and 10-Bit encoding at runtime. We now include...
[x264-launcher/x264-launcher.git] / src / win_main.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2012 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
24 #include "model_jobList.h"
25 #include "model_options.h"
26 #include "win_addJob.h"
27 #include "win_preferences.h"
28 #include "taskbar7.h"
29 #include "resource.h"
30 #include "avisynth_c.h"
31
32 #include <QDate>
33 #include <QTimer>
34 #include <QCloseEvent>
35 #include <QMessageBox>
36 #include <QDesktopServices>
37 #include <QUrl>
38 #include <QDir>
39 #include <QLibrary>
40 #include <QProcess>
41 #include <QProgressDialog>
42 #include <QScrollBar>
43
44 #include <Mmsystem.h>
45
46 const char *home_url = "http://mulder.brhack.net/";
47 const char *update_url = "http://code.google.com/p/mulder/downloads/list";
48 const char *tpl_last = "<LAST_USED>";
49
50 #define SET_FONT_BOLD(WIDGET,BOLD) { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); }
51 #define SET_TEXT_COLOR(WIDGET,COLOR) { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); }
52
53 ///////////////////////////////////////////////////////////////////////////////
54 // Constructor & Destructor
55 ///////////////////////////////////////////////////////////////////////////////
56
57 /*
58  * Constructor
59  */
60 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures)
61 :
62         m_cpuFeatures(cpuFeatures),
63         m_appDir(QApplication::applicationDirPath()),
64         m_options(NULL),
65         m_jobList(NULL),
66         m_droppedFiles(NULL),
67         m_firstShow(true)
68 {
69         //Init the dialog, from the .ui file
70         setupUi(this);
71         setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
72
73         //Register meta types
74         qRegisterMetaType<QUuid>("QUuid");
75         qRegisterMetaType<QUuid>("DWORD");
76         qRegisterMetaType<EncodeThread::JobStatus>("EncodeThread::JobStatus");
77
78         //Load preferences
79         PreferencesDialog::initPreferences(&m_preferences);
80         PreferencesDialog::loadPreferences(&m_preferences);
81
82         //Create options object
83         m_options = new OptionsModel();
84         OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
85
86         //Create IPC thread object
87         m_ipcThread = new IPCThread();
88         connect(m_ipcThread, SIGNAL(instanceCreated(DWORD)), this, SLOT(instanceCreated(DWORD)), Qt::QueuedConnection);
89
90         //Freeze minimum size
91         setMinimumSize(size());
92         splitter->setSizes(QList<int>() << 16 << 196);
93
94         //Update title
95         labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
96         labelBuildDate->installEventFilter(this);
97         setWindowTitle(QString("%1 (%2 Mode)").arg(windowTitle(), m_cpuFeatures->x64 ? "64-Bit" : "32-Bit"));
98         if(X264_DEBUG)
99         {
100                 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
101                 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
102         }
103         else if(x264_is_prerelease())
104         {
105                 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
106         }
107         
108         //Create model
109         m_jobList = new JobListModel();
110         connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
111         jobsView->setModel(m_jobList);
112         
113         //Setup view
114         jobsView->horizontalHeader()->setSectionHidden(3, true);
115         jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
116         jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
117         jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
118         jobsView->horizontalHeader()->resizeSection(1, 150);
119         jobsView->horizontalHeader()->resizeSection(2, 90);
120         jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
121         connect(jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
122
123         //Create context menu
124         QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), logView);
125         actionClipboard->setEnabled(false);
126         logView->addAction(actionClipboard);
127         connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
128         jobsView->addActions(menuJob->actions());
129
130         //Enable buttons
131         connect(buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed()));
132         connect(buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed()));
133         connect(buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed()));
134         connect(buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
135         connect(actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed()));
136         connect(actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed()));
137         connect(actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed()));
138
139         //Enable menu
140         connect(actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
141         connect(actionWebMulder, SIGNAL(triggered()), this, SLOT(showWebLink()));
142         connect(actionWebX264, SIGNAL(triggered()), this, SLOT(showWebLink()));
143         connect(actionWebKomisar, SIGNAL(triggered()), this, SLOT(showWebLink()));
144         connect(actionWebJarod, SIGNAL(triggered()), this, SLOT(showWebLink()));
145         connect(actionWebJEEB, SIGNAL(triggered()), this, SLOT(showWebLink()));
146         connect(actionWebAvisynth32, SIGNAL(triggered()), this, SLOT(showWebLink()));
147         connect(actionWebAvisynth64, SIGNAL(triggered()), this, SLOT(showWebLink()));
148         connect(actionWebWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
149         connect(actionWebBluRay, SIGNAL(triggered()), this, SLOT(showWebLink()));
150         connect(actionWebAvsWiki, SIGNAL(triggered()), this, SLOT(showWebLink()));
151         connect(actionWebSecret, SIGNAL(triggered()), this, SLOT(showWebLink()));
152         connect(actionWebSupport, SIGNAL(triggered()), this, SLOT(showWebLink()));
153         connect(actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
154
155         //Create floating label
156         m_label = new QLabel(jobsView->viewport());
157         m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
158         m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
159         SET_TEXT_COLOR(m_label, Qt::darkGray);
160         SET_FONT_BOLD(m_label, true);
161         m_label->setVisible(true);
162         m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
163         m_label->addActions(jobsView->actions());
164         connect(splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
165         updateLabelPos();
166 }
167
168 /*
169  * Destructor
170  */
171 MainWindow::~MainWindow(void)
172 {
173         OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
174         
175         X264_DELETE(m_jobList);
176         X264_DELETE(m_options);
177         X264_DELETE(m_droppedFiles);
178         X264_DELETE(m_label);
179
180         while(!m_toolsList.isEmpty())
181         {
182                 QFile *temp = m_toolsList.takeFirst();
183                 X264_DELETE(temp);
184         }
185
186         if(m_ipcThread->isRunning())
187         {
188                 m_ipcThread->setAbort();
189                 if(!m_ipcThread->wait(5000))
190                 {
191                         m_ipcThread->terminate();
192                         m_ipcThread->wait();
193                 }
194         }
195
196         X264_DELETE(m_ipcThread);
197 }
198
199 ///////////////////////////////////////////////////////////////////////////////
200 // Slots
201 ///////////////////////////////////////////////////////////////////////////////
202
203 /*
204  * The "add" button was clicked
205  */
206 void MainWindow::addButtonPressed(const QString &filePathIn, const QString &filePathOut, OptionsModel *options, int fileNo, int fileTotal, bool *ok)
207 {
208         qDebug("MainWindow::addButtonPressed");
209         
210         if(ok) *ok = false;
211
212         AddJobDialog *addDialog = new AddJobDialog(this, options ? options : m_options, m_cpuFeatures->x64);
213         addDialog->setRunImmediately(countRunningJobs() < (m_preferences.autoRunNextJob ? m_preferences.maxRunningJobCount : 1));
214         
215         if(options) addDialog->setWindowTitle(tr("Restart Job"));
216         if((fileNo >= 0) && (fileTotal > 1)) addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
217         if(!filePathIn.isEmpty()) addDialog->setSourceFile(filePathIn);
218         if(!filePathOut.isEmpty()) addDialog->setOutputFile(filePathOut);
219
220         int result = addDialog->exec();
221         if(result == QDialog::Accepted)
222         {
223                 EncodeThread *thrd = new EncodeThread
224                 (
225                         addDialog->sourceFile(),
226                         addDialog->outputFile(),
227                         options ? options : m_options,
228                         QString("%1/toolset").arg(m_appDir),
229                         m_cpuFeatures->x64,
230                         m_preferences.use10BitEncoding,
231                         m_cpuFeatures->x64 && m_preferences.useAvisyth64Bit
232                 );
233
234                 QModelIndex newIndex = m_jobList->insertJob(thrd);
235
236                 if(newIndex.isValid())
237                 {
238                         if(addDialog->runImmediately())
239                         {
240                                 jobsView->selectRow(newIndex.row());
241                                 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
242                                 m_jobList->startJob(newIndex);
243                         }
244
245                         if(ok) *ok = true;
246                 }
247
248                 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
249         }
250         
251         X264_DELETE(addDialog);
252 }
253
254 /*
255  * The "start" button was clicked
256  */
257 void MainWindow::startButtonPressed(void)
258 {
259         m_jobList->startJob(jobsView->currentIndex());
260 }
261
262 /*
263  * The "abort" button was clicked
264  */
265 void MainWindow::abortButtonPressed(void)
266 {
267         m_jobList->abortJob(jobsView->currentIndex());
268 }
269
270 /*
271  * The "delete" button was clicked
272  */
273 void MainWindow::deleteButtonPressed(void)
274 {
275         m_jobList->deleteJob(jobsView->currentIndex());
276         m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
277 }
278
279 /*
280  * The "browse" button was clicked
281  */
282 void MainWindow::browseButtonPressed(void)
283 {
284         QString outputFile = m_jobList->getJobOutputFile(jobsView->currentIndex());
285         if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
286         {
287                 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
288         }
289         else
290         {
291                 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
292         }
293 }
294
295 /*
296  * The "pause" button was clicked
297  */
298 void MainWindow::pauseButtonPressed(bool checked)
299 {
300         if(checked)
301         {
302                 m_jobList->pauseJob(jobsView->currentIndex());
303         }
304         else
305         {
306                 m_jobList->resumeJob(jobsView->currentIndex());
307         }
308 }
309
310 /*
311  * The "restart" button was clicked
312  */
313 void MainWindow::restartButtonPressed(void)
314 {
315         const QModelIndex index = jobsView->currentIndex();
316         
317         const QString &source = m_jobList->getJobSourceFile(index);
318         const QString &output = m_jobList->getJobOutputFile(index);
319         const OptionsModel *options = m_jobList->getJobOptions(index);
320
321         if((options) && (!source.isEmpty()) && (!output.isEmpty()))
322         {
323                 OptionsModel *tempOptions = new OptionsModel(*options);
324                 addButtonPressed(source, output, tempOptions);
325                 X264_DELETE(tempOptions);
326         }
327 }
328
329 /*
330  * Job item selected by user
331  */
332 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
333 {
334         qDebug("Job selected: %d", current.row());
335         
336         if(logView->model())
337         {
338                 disconnect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
339         }
340         
341         if(current.isValid())
342         {
343                 logView->setModel(m_jobList->getLogFile(current));
344                 connect(logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
345                 logView->actions().first()->setEnabled(true);
346                 QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
347
348                 progressBar->setValue(m_jobList->getJobProgress(current));
349                 editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
350                 updateButtons(m_jobList->getJobStatus(current));
351                 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
352         }
353         else
354         {
355                 logView->setModel(NULL);
356                 logView->actions().first()->setEnabled(false);
357                 progressBar->setValue(0);
358                 editDetails->clear();
359                 updateButtons(EncodeThread::JobStatus_Undefined);
360                 updateTaskbar(EncodeThread::JobStatus_Undefined, QIcon());
361         }
362
363         progressBar->repaint();
364 }
365
366 /*
367  * Handle update of job info (status, progress, details, etc)
368  */
369 void MainWindow::jobChangedData(const QModelIndex &topLeft, const  QModelIndex &bottomRight)
370 {
371         int selected = jobsView->currentIndex().row();
372         
373         if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
374         {
375                 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
376                 {
377                         EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
378                         if(i == selected)
379                         {
380                                 qDebug("Current job changed status!");
381                                 updateButtons(status);
382                                 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
383                         }
384                         if((status == EncodeThread::JobStatus_Completed) || (status == EncodeThread::JobStatus_Failed))
385                         {
386                                 if(m_preferences.autoRunNextJob) QTimer::singleShot(0, this, SLOT(launchNextJob()));
387                                 if(m_preferences.shutdownComputer) QTimer::singleShot(0, this, SLOT(shutdownComputer()));
388                         }
389                 }
390         }
391         if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
392         {
393                 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
394                 {
395                         if(i == selected)
396                         {
397                                 progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
398                                 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
399                                 break;
400                         }
401                 }
402         }
403         if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
404         {
405                 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
406                 {
407                         if(i == selected)
408                         {
409                                 editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
410                                 break;
411                         }
412                 }
413         }
414 }
415
416 /*
417  * Handle new log file content
418  */
419 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
420 {
421         QTimer::singleShot(0, logView, SLOT(scrollToBottom()));
422 }
423
424 /*
425  * About screen
426  */
427 void MainWindow::showAbout(void)
428 {
429         QString text;
430
431         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());
432         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()));
433         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());
434         text += QString().sprintf("This program is free software: you can redistribute it and/or modify<br>");
435         text += QString().sprintf("it under the terms of the GNU General Public License &lt;http://www.gnu.org/&gt;.<br>");
436         text += QString().sprintf("Note that this program is distributed with ABSOLUTELY NO WARRANTY.<br><br>");
437         text += QString().sprintf("Please check the web-site at <a href=\"%s\">%s</a> for updates !!!<br></tt></nobr>", home_url, home_url);
438
439         QMessageBox aboutBox(this);
440         aboutBox.setIconPixmap(QIcon(":/images/movie.png").pixmap(64,64));
441         aboutBox.setWindowTitle(tr("About..."));
442         aboutBox.setText(text.replace("-", "&minus;"));
443         aboutBox.addButton(tr("About x264"), QMessageBox::NoRole);
444         aboutBox.addButton(tr("About AVS"), QMessageBox::NoRole);
445         aboutBox.addButton(tr("About Qt"), QMessageBox::NoRole);
446         aboutBox.setEscapeButton(aboutBox.addButton(tr("Close"), QMessageBox::NoRole));
447                 
448         forever
449         {
450                 MessageBeep(MB_ICONINFORMATION);
451                 switch(aboutBox.exec())
452                 {
453                 case 0:
454                         {
455                                 QString text2;
456                                 text2 += tr("<nobr><tt>x264 - the best H.264/AVC encoder. Copyright (c) 2003-2012 x264 project.<br>");
457                                 text2 += tr("Free software library for encoding video streams into the H.264/MPEG-4 AVC format.<br>");
458                                 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
459                                 text2 += tr("Please visit <a href=\"%1\">%1</a> for obtaining a commercial x264 license.<br>").arg("http://x264licensing.com/");
460                                 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");
461
462                                 QMessageBox x264Box(this);
463                                 x264Box.setIconPixmap(QIcon(":/images/x264.png").pixmap(48,48));
464                                 x264Box.setWindowTitle(tr("About x264"));
465                                 x264Box.setText(text2.replace("-", "&minus;"));
466                                 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
467                                 MessageBeep(MB_ICONINFORMATION);
468                                 x264Box.exec();
469                         }
470                         break;
471                 case 1:
472                         {
473                                 QString text2;
474                                 text2 += tr("<nobr><tt>Avisynth - powerful video processing scripting language.<br>");
475                                 text2 += tr("Copyright (c) 2000 Ben Rudiak-Gould and all subsequent developers.<br>");
476                                 text2 += tr("Released under the terms of the GNU General Public License.<br><br>");
477                                 text2 += tr("Please visit the web-site <a href=\"%1\">%1</a> for more information.<br>").arg("http://avisynth.org/");
478                                 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.org/mediawiki/First_script", "http://forum.doom9.org/forumdisplay.php?f=33");
479
480                                 QMessageBox x264Box(this);
481                                 x264Box.setIconPixmap(QIcon(":/images/avisynth.png").pixmap(48,67));
482                                 x264Box.setWindowTitle(tr("About Avisynth"));
483                                 x264Box.setText(text2.replace("-", "&minus;"));
484                                 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
485                                 MessageBeep(MB_ICONINFORMATION);
486                                 x264Box.exec();
487                         }
488                         break;
489                 case 2:
490                         QMessageBox::aboutQt(this);
491                         break;
492                 default:
493                         return;
494                 }
495         }
496 }
497
498 /*
499  * Open web-link
500  */
501 void MainWindow::showWebLink(void)
502 {
503         if(QObject::sender() == actionWebMulder)     QDesktopServices::openUrl(QUrl(home_url));
504         if(QObject::sender() == actionWebX264)       QDesktopServices::openUrl(QUrl("http://www.x264.com/"));
505         if(QObject::sender() == actionWebKomisar)    QDesktopServices::openUrl(QUrl("http://komisar.gin.by/"));
506         if(QObject::sender() == actionWebJarod)      QDesktopServices::openUrl(QUrl("http://www.x264.nl/"));
507         if(QObject::sender() == actionWebJEEB)       QDesktopServices::openUrl(QUrl("http://x264.fushizen.eu/"));
508         if(QObject::sender() == actionWebAvisynth32) QDesktopServices::openUrl(QUrl("http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/"));
509         if(QObject::sender() == actionWebAvisynth64) QDesktopServices::openUrl(QUrl("http://code.google.com/p/avisynth64/downloads/list"));
510         if(QObject::sender() == actionWebWiki)       QDesktopServices::openUrl(QUrl("http://mewiki.project357.com/wiki/X264_Settings"));
511         if(QObject::sender() == actionWebBluRay)     QDesktopServices::openUrl(QUrl("http://www.x264bluray.com/"));
512         if(QObject::sender() == actionWebAvsWiki)    QDesktopServices::openUrl(QUrl("http://avisynth.org/mediawiki/Main_Page#Usage"));
513         if(QObject::sender() == actionWebSupport)    QDesktopServices::openUrl(QUrl("http://forum.doom9.org/showthread.php?t=144140"));
514         if(QObject::sender() == actionWebSecret)     QDesktopServices::openUrl(QUrl("http://www.youtube.com/watch_popup?v=AXIeHY-OYNI"));
515 }
516
517 /*
518  * Pereferences dialog
519  */
520 void MainWindow::showPreferences(void)
521 {
522         PreferencesDialog *preferences = new PreferencesDialog(this, &m_preferences, m_cpuFeatures->x64);
523         preferences->exec();
524         X264_DELETE(preferences);
525 }
526
527 /*
528  * Launch next job, after running job has finished
529  */
530 void MainWindow::launchNextJob(void)
531 {
532         qDebug("launchNextJob(void)");
533
534         
535         const int rows = m_jobList->rowCount(QModelIndex());
536
537         if(countRunningJobs() >= m_preferences.maxRunningJobCount)
538         {
539                 qDebug("Still have too many jobs running, won't launch next one yet!");
540                 return;
541         }
542
543         int startIdx= jobsView->currentIndex().isValid() ? qBound(0, jobsView->currentIndex().row(), rows-1) : 0;
544
545         for(int i = 0; i < rows; i++)
546         {
547                 int currentIdx = (i + startIdx) % rows;
548                 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
549                 if(status == EncodeThread::JobStatus_Enqueued)
550                 {
551                         if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
552                         {
553                                 jobsView->selectRow(currentIdx);
554                                 return;
555                         }
556                 }
557         }
558                 
559         qWarning("No enqueued jobs left!");
560 }
561
562 /*
563  * Shut down the computer (with countdown)
564  */
565 void MainWindow::shutdownComputer(void)
566 {
567         qDebug("shutdownComputer(void)");
568         
569         if(countPendingJobs() > 0)
570         {
571                 qDebug("Still have pending jobs, won't shutdown yet!");
572                 return;
573         }
574         
575         const int iTimeout = 30;
576         const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
577         const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
578         
579         qWarning("Initiating shutdown sequence!");
580         
581         QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
582         QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
583         cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
584         progressDialog.setModal(true);
585         progressDialog.setAutoClose(false);
586         progressDialog.setAutoReset(false);
587         progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
588         progressDialog.setWindowTitle(windowTitle());
589         progressDialog.setCancelButton(cancelButton);
590         progressDialog.show();
591         
592         QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
593         QApplication::setOverrideCursor(Qt::WaitCursor);
594         PlaySound(MAKEINTRESOURCE(IDR_WAVE1), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
595         QApplication::restoreOverrideCursor();
596         
597         QTimer timer;
598         timer.setInterval(1000);
599         timer.start();
600
601         QEventLoop eventLoop(this);
602         connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
603         connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
604
605         for(int i = 1; i <= iTimeout; i++)
606         {
607                 eventLoop.exec();
608                 if(progressDialog.wasCanceled())
609                 {
610                         progressDialog.close();
611                         return;
612                 }
613                 progressDialog.setValue(i+1);
614                 progressDialog.setLabelText(text.arg(iTimeout-i));
615                 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
616                 QApplication::processEvents();
617                 PlaySound(MAKEINTRESOURCE((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), GetModuleHandle(NULL), SND_RESOURCE | SND_SYNC);
618         }
619         
620         qWarning("Shutting down !!!");
621
622         if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
623         {
624                 qApp->closeAllWindows();
625         }
626 }
627
628 /*
629  * Main initialization function (called only once!)
630  */
631 void MainWindow::init(void)
632 {
633         static const char *binFiles = "x264_8bit_x86.exe:x264_8bit_x64.exe:x264_10bit_x86.exe:x264_10bit_x64.exe:avs2yuv.exe:avs2yuv_x64.exe";
634         QStringList binaries = QString::fromLatin1(binFiles).split(":", QString::SkipEmptyParts);
635
636         updateLabelPos();
637
638         //Check for a running instance
639         bool firstInstance = false;
640         if(m_ipcThread->initialize(&firstInstance))
641         {
642                 m_ipcThread->start();
643                 if(!firstInstance)
644                 {
645                         if(!m_ipcThread->wait(5000))
646                         {
647                                 QMessageBox::warning(this, tr("Not Responding"), tr("<nobr>Another instance of this application is already running, but did not respond in time.<br>If the problem persists, please kill the running instance from the task manager!</nobr>"), tr("Quit"));
648                                 m_ipcThread->terminate();
649                                 m_ipcThread->wait();
650                         }
651                         close(); qApp->exit(-1); return;
652                 }
653         }
654
655         //Check all binaries
656         while(!binaries.isEmpty())
657         {
658                 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
659                 QString current = binaries.takeFirst();
660                 QFile *file = new QFile(QString("%1/toolset/%2").arg(m_appDir, current));
661                 if(file->open(QIODevice::ReadOnly))
662                 {
663                         bool binaryTypeOkay = false;
664                         DWORD binaryType;
665                         if(GetBinaryType(QWCHAR(file->fileName()), &binaryType))
666                         {
667                                 binaryTypeOkay = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
668                         }
669                         if(!binaryTypeOkay)
670                         {
671                                 QMessageBox::critical(this, tr("Invalid File!"), tr("<nobr>At least on required tool is not a valid Win32 or Win64 binary:<br>%1<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;"));
672                                 qFatal(QString("Binary is invalid: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
673                                 close(); qApp->exit(-1); return;
674                         }
675                         m_toolsList << file;
676                 }
677                 else
678                 {
679                         X264_DELETE(file);
680                         QMessageBox::critical(this, tr("File Not Found!"), tr("<nobr>At least on required tool could not be found:<br>%1<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;"));
681                         qFatal(QString("Binary not found: %1/toolset/%2").arg(m_appDir, current).toLatin1().constData());
682                         close(); qApp->exit(-1); return;
683                 }
684         }
685
686         //Check for portable mode
687         if(x264_portable())
688         {
689                 bool ok = false;
690                 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
691                 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
692                 if(writeTest.open(QIODevice::WriteOnly))
693                 {
694                         ok = (writeTest.write(data) == strlen(data));
695                         writeTest.remove();
696                 }
697                 if(!ok)
698                 {
699                         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"));
700                         if(val != 1) { close(); qApp->exit(-1); return; }
701                 }
702         }
703
704         //Pre-release popup
705         if(x264_is_prerelease())
706         {
707                 qsrand(time(NULL)); int rnd = qrand() % 3;
708                 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);
709                 if(rnd != val) { close(); qApp->exit(-1); return; }
710         }
711
712         //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
713         if(!(m_cpuFeatures->mmx && m_cpuFeatures->mmx2))
714         {
715                 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"));
716                 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
717                 close(); qApp->exit(-1); return;
718         }
719         else if(!(m_cpuFeatures->mmx && m_cpuFeatures->sse))
720         {
721                 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
722                 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"));
723                 if(val != 1) { close(); qApp->exit(-1); return; }
724         }
725
726         //Check for Avisynth support
727         if(!qApp->arguments().contains("--skip-avisynth-check", Qt::CaseInsensitive))
728         {
729                 double avisynthVersion = 0.0;
730                 QLibrary *avsLib = new QLibrary("avisynth.dll");
731                 if(avsLib->load())
732                 {
733                         avisynthVersion = detectAvisynthVersion(avsLib);
734                         if(avisynthVersion < 0.0)
735                         {
736                                 int val = QMessageBox::critical(this, tr("Avisynth Error"), tr("<nobr>A critical error was encountered while checking your Avisynth version!</nobr>").replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
737                                 if(val != 1) { close(); qApp->exit(-1); return; }
738                         }
739                 }
740                 if(avisynthVersion < 2.5)
741                 {
742                         int val = QMessageBox::warning(this, tr("Avisynth Missing"), tr("<nobr>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!<br><br>Please download and install Avisynth:<br><a href=\"http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/\">http://sourceforge.net/projects/avisynth2/files/AviSynth 2.5/</a></nobr>").replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
743                         avsLib->unload(); X264_DELETE(avsLib);
744                         if(val != 1) { close(); qApp->exit(-1); return; }
745                 }
746         }
747
748         //Check for expiration
749         if(x264_version_date().addMonths(6) < QDate::currentDate())
750         {
751                 QMessageBox msgBox(this);
752                 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
753                 msgBox.setWindowTitle(tr("Update Notification"));
754                 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
755                 msgBox.setText(tr("<nobr><tt>Your version of 'Simple x264 Launcher' is more than 6 months old!<br><br>Please download the most recent version from the official web-site at:<br><a href=\"%1\">%1</a><br></tt></nobr>").replace("-", "&minus;").arg(update_url));
756                 QPushButton *btn1 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
757                 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::AcceptRole);
758                 btn1->setEnabled(false);
759                 btn2->setVisible(false);
760                 QTimer::singleShot(5000, btn1, SLOT(hide()));
761                 QTimer::singleShot(5000, btn2, SLOT(show()));
762                 msgBox.exec();
763         }
764
765         //Add files from command-line
766         bool bAddFile = false;
767         QStringList files, args = qApp->arguments();
768         while(!args.isEmpty())
769         {
770                 QString current = args.takeFirst();
771                 if(!bAddFile)
772                 {
773                         bAddFile = (current.compare("--add", Qt::CaseInsensitive) == 0);
774                         continue;
775                 }
776                 if((!current.startsWith("--")) && QFileInfo(current).exists() && QFileInfo(current).isFile())
777                 {
778                         files << QFileInfo(current).canonicalFilePath();
779                 }
780         }
781         if(int totalFiles = files.count())
782         {
783                 bool ok = true; int n = 0;
784                 while((!files.isEmpty()) && ok)
785                 {
786                         QString currentFile = files.takeFirst();
787                         qDebug("Adding file: %s", currentFile.toUtf8().constData());
788                         addButtonPressed(currentFile, QString(), NULL, n++, totalFiles, &ok);
789                 }
790         }
791 }
792
793 /*
794  * Update the label position
795  */
796 void MainWindow::updateLabelPos(void)
797 {
798         const QWidget *const viewPort = jobsView->viewport();
799         m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
800 }
801
802 /*
803  * Copy the complete log to the clipboard
804  */
805 void MainWindow::copyLogToClipboard(bool checked)
806 {
807         qDebug("copyLogToClipboard");
808         
809         if(LogFileModel *log = dynamic_cast<LogFileModel*>(logView->model()))
810         {
811                 log->copyToClipboard();
812                 MessageBeep(MB_ICONINFORMATION);
813         }
814 }
815
816 /*
817  * Process the dropped files
818  */
819 void MainWindow::handleDroppedFiles(void)
820 {
821         qDebug("MainWindow::handleDroppedFiles");
822         if(m_droppedFiles)
823         {
824                 QStringList droppedFiles(*m_droppedFiles);
825                 m_droppedFiles->clear();
826                 int totalFiles = droppedFiles.count();
827                 bool ok = true; int n = 0;
828                 while((!droppedFiles.isEmpty()) && ok)
829                 {
830                         QString currentFile = droppedFiles.takeFirst();
831                         qDebug("Adding file: %s", currentFile.toUtf8().constData());
832                         addButtonPressed(currentFile, QString(), NULL, n++, totalFiles, &ok);
833                 }
834         }
835         qDebug("Leave from MainWindow::handleDroppedFiles!");
836 }
837
838 void MainWindow::instanceCreated(DWORD pid)
839 {
840         qDebug("Notification from other instance (PID=0x%X) received!", pid);
841         
842         FLASHWINFO flashWinInfo;
843         memset(&flashWinInfo, 0, sizeof(FLASHWINFO));
844         flashWinInfo.cbSize = sizeof(FLASHWINFO);
845         flashWinInfo.hwnd = this->winId();
846         flashWinInfo.dwFlags = FLASHW_ALL;
847         flashWinInfo.dwTimeout = 125;
848         flashWinInfo.uCount = 5;
849
850         SwitchToThisWindow(this->winId(), TRUE);
851         SetForegroundWindow(this->winId());
852         qApp->processEvents();
853         FlashWindowEx(&flashWinInfo);
854 }
855
856 ///////////////////////////////////////////////////////////////////////////////
857 // Event functions
858 ///////////////////////////////////////////////////////////////////////////////
859
860 /*
861  * Window shown event
862  */
863 void MainWindow::showEvent(QShowEvent *e)
864 {
865         QMainWindow::showEvent(e);
866
867         if(m_firstShow)
868         {
869                 m_firstShow = false;
870                 QTimer::singleShot(0, this, SLOT(init()));
871         }
872 }
873
874 /*
875  * Window close event
876  */
877 void MainWindow::closeEvent(QCloseEvent *e)
878 {
879         if(countRunningJobs() > 0)
880         {
881                 e->ignore();
882                 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
883                 return;
884         }
885         
886         if(countPendingJobs() > 0)
887         {
888                 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);
889                 if(ret != QMessageBox::Yes)
890                 {
891                         e->ignore();
892                         return;
893                 }
894         }
895
896         while(m_jobList->rowCount(QModelIndex()) > 0)
897         {
898                 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
899                 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
900                 {
901                         e->ignore();
902                         QMessageBox::warning(this, tr("Failed To Exit"), tr("Sorry, at least one job could not be deleted!"));
903                         return;
904                 }
905         }
906
907         qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
908         QMainWindow::closeEvent(e);
909 }
910
911 /*
912  * Window resize event
913  */
914 void MainWindow::resizeEvent(QResizeEvent *e)
915 {
916         QMainWindow::resizeEvent(e);
917         updateLabelPos();
918 }
919
920 /*
921  * Event filter
922  */
923 bool MainWindow::eventFilter(QObject *o, QEvent *e)
924 {
925         if((o == labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
926         {
927                 QTimer::singleShot(0, this, SLOT(showAbout()));
928                 return true;
929         }
930         return false;
931 }
932
933 /*
934  * Win32 message filter
935  */
936 bool MainWindow::winEvent(MSG *message, long *result)
937 {
938         return WinSevenTaskbar::handleWinEvent(message, result);
939 }
940
941 /*
942  * File dragged over window
943  */
944 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
945 {
946         QStringList formats = event->mimeData()->formats();
947         
948         if(formats.contains("application/x-qt-windows-mime;value=\"FileNameW\"", Qt::CaseInsensitive) && formats.contains("text/uri-list", Qt::CaseInsensitive))
949         {
950                 event->acceptProposedAction();
951         }
952 }
953
954 /*
955  * File dropped onto window
956  */
957 void MainWindow::dropEvent(QDropEvent *event)
958 {
959         QStringList droppedFiles;
960         QList<QUrl> urls = event->mimeData()->urls();
961
962         while(!urls.isEmpty())
963         {
964                 QUrl currentUrl = urls.takeFirst();
965                 QFileInfo file(currentUrl.toLocalFile());
966                 if(file.exists() && file.isFile())
967                 {
968                         qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
969                         droppedFiles << file.canonicalFilePath();
970                 }
971         }
972         
973         if(droppedFiles.count() > 0)
974         {
975                 if(!m_droppedFiles)
976                 {
977                         m_droppedFiles = new QStringList();
978                 }
979                 m_droppedFiles->append(droppedFiles);
980                 m_droppedFiles->sort();
981                 QTimer::singleShot(0, this, SLOT(handleDroppedFiles()));
982         }
983 }
984
985 ///////////////////////////////////////////////////////////////////////////////
986 // Private functions
987 ///////////////////////////////////////////////////////////////////////////////
988
989 /*
990  * Jobs that are not completed (or failed, or aborted) yet
991  */
992 unsigned int MainWindow::countPendingJobs(void)
993 {
994         unsigned int count = 0;
995         const int rows = m_jobList->rowCount(QModelIndex());
996
997         for(int i = 0; i < rows; i++)
998         {
999                 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1000                 if(status != EncodeThread::JobStatus_Completed && status != EncodeThread::JobStatus_Aborted && status != EncodeThread::JobStatus_Failed)
1001                 {
1002                         count++;
1003                 }
1004         }
1005
1006         return count;
1007 }
1008
1009 /*
1010  * Jobs that are still active, i.e. not terminated or enqueued
1011  */
1012 unsigned int MainWindow::countRunningJobs(void)
1013 {
1014         unsigned int count = 0;
1015         const int rows = m_jobList->rowCount(QModelIndex());
1016
1017         for(int i = 0; i < rows; i++)
1018         {
1019                 EncodeThread::JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1020                 if(status != EncodeThread::JobStatus_Completed && status != EncodeThread::JobStatus_Aborted && status != EncodeThread::JobStatus_Failed && status != EncodeThread::JobStatus_Enqueued)
1021                 {
1022                         count++;
1023                 }
1024         }
1025
1026         return count;
1027 }
1028
1029 /*
1030  * Update all buttons with respect to current job status
1031  */
1032 void MainWindow::updateButtons(EncodeThread::JobStatus status)
1033 {
1034         qDebug("MainWindow::updateButtons(void)");
1035
1036         buttonStartJob->setEnabled(status == EncodeThread::JobStatus_Enqueued);
1037         buttonAbortJob->setEnabled(status == EncodeThread::JobStatus_Indexing || status == EncodeThread::JobStatus_Running || status == EncodeThread::JobStatus_Running_Pass1 || status == EncodeThread::JobStatus_Running_Pass2 || status == EncodeThread::JobStatus_Paused);
1038         buttonPauseJob->setEnabled(status == EncodeThread::JobStatus_Indexing || status == EncodeThread::JobStatus_Running || status == EncodeThread::JobStatus_Paused || status == EncodeThread::JobStatus_Running_Pass1 || status == EncodeThread::JobStatus_Running_Pass2);
1039         buttonPauseJob->setChecked(status == EncodeThread::JobStatus_Paused || status == EncodeThread::JobStatus_Pausing);
1040
1041         actionJob_Delete->setEnabled(status == EncodeThread::JobStatus_Completed || status == EncodeThread::JobStatus_Aborted || status == EncodeThread::JobStatus_Failed || status == EncodeThread::JobStatus_Enqueued);
1042         actionJob_Restart->setEnabled(status == EncodeThread::JobStatus_Completed || status == EncodeThread::JobStatus_Aborted || status == EncodeThread::JobStatus_Failed || status == EncodeThread::JobStatus_Enqueued);
1043         actionJob_Browse->setEnabled(status == EncodeThread::JobStatus_Completed);
1044
1045         actionJob_Start->setEnabled(buttonStartJob->isEnabled());
1046         actionJob_Abort->setEnabled(buttonAbortJob->isEnabled());
1047         actionJob_Pause->setEnabled(buttonPauseJob->isEnabled());
1048         actionJob_Pause->setChecked(buttonPauseJob->isChecked());
1049
1050         editDetails->setEnabled(status != EncodeThread::JobStatus_Paused);
1051 }
1052
1053 /*
1054  * Update the taskbar with current job status
1055  */
1056 void MainWindow::updateTaskbar(EncodeThread::JobStatus status, const QIcon &icon)
1057 {
1058         qDebug("MainWindow::updateTaskbar(void)");
1059
1060         switch(status)
1061         {
1062         case EncodeThread::JobStatus_Undefined:
1063                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1064                 break;
1065         case EncodeThread::JobStatus_Aborting:
1066         case EncodeThread::JobStatus_Starting:
1067         case EncodeThread::JobStatus_Pausing:
1068         case EncodeThread::JobStatus_Resuming:
1069                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1070                 break;
1071         case EncodeThread::JobStatus_Aborted:
1072         case EncodeThread::JobStatus_Failed:
1073                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1074                 break;
1075         case EncodeThread::JobStatus_Paused:
1076                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1077                 break;
1078         default:
1079                 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1080                 break;
1081         }
1082
1083         switch(status)
1084         {
1085         case EncodeThread::JobStatus_Aborting:
1086         case EncodeThread::JobStatus_Starting:
1087         case EncodeThread::JobStatus_Pausing:
1088         case EncodeThread::JobStatus_Resuming:
1089                 break;
1090         default:
1091                 WinSevenTaskbar::setTaskbarProgress(this, progressBar->value(), progressBar->maximum());
1092                 break;
1093         }
1094
1095         WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);
1096 }
1097
1098 /*
1099  * Detect Avisynth version
1100  */
1101 double MainWindow::detectAvisynthVersion(QLibrary *avsLib)
1102 {
1103         double version_number = 0.0;
1104         
1105         __try
1106         {
1107                 avs_create_script_environment_func avs_create_script_environment_ptr = (avs_create_script_environment_func) avsLib->resolve("avs_create_script_environment");
1108                 avs_invoke_func avs_invoke_ptr = (avs_invoke_func) avsLib->resolve("avs_invoke");
1109                 avs_function_exists_func avs_function_exists_ptr = (avs_function_exists_func) avsLib->resolve("avs_function_exists");
1110                 avs_delete_script_environment_func avs_delete_script_environment_ptr = (avs_delete_script_environment_func) avsLib->resolve("avs_delete_script_environment");
1111
1112                 if((avs_create_script_environment_ptr != NULL) && (avs_invoke_ptr != NULL) && (avs_function_exists_ptr != NULL))
1113                 {
1114                         AVS_ScriptEnvironment* avs_env = avs_create_script_environment_ptr(AVS_INTERFACE_25);
1115                         if(avs_env != NULL)
1116                         {
1117                                 if(avs_function_exists_ptr(avs_env, "VersionNumber"))
1118                                 {
1119                                         AVS_Value avs_version = avs_invoke_ptr(avs_env, "VersionNumber", avs_new_value_array(NULL, 0), NULL);
1120                                         if(!avs_is_error(avs_version))
1121                                         {
1122                                                 if(avs_is_float(avs_version))
1123                                                 {
1124                                                         qDebug("Avisynth version: v%.2f", avs_as_float(avs_version));
1125                                                         version_number = avs_as_float(avs_version);
1126                                                 }
1127                                         }
1128                                 }
1129                                 if(avs_delete_script_environment_ptr != NULL)
1130                                 {
1131                                         avs_delete_script_environment_ptr(avs_env);
1132                                         avs_env = NULL;
1133                                 }
1134                         }
1135                 }
1136                 else
1137                 {
1138                         qWarning("It seems the Avisynth DLL is missing required API functions!");
1139                 }
1140         }
1141         __except(1)
1142         {
1143                 qWarning("Exception in Avisynth initialization code!");
1144                 version_number = -1.0;
1145         }
1146
1147         return version_number;
1148 }
1149