OSDN Git Service

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