OSDN Git Service

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