OSDN Git Service

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