OSDN Git Service

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