1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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.
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.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
23 #include "uic_win_main.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"
38 #include "win_addJob.h"
39 #include "win_preferences.h"
40 #include "win_updater.h"
45 #include <QCloseEvent>
46 #include <QMessageBox>
47 #include <QDesktopServices>
52 #include <QProgressDialog>
54 #include <QTextStream>
56 #include <QFileDialog>
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>";
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)
70 ///////////////////////////////////////////////////////////////////////////////
71 // Constructor & Destructor
72 ///////////////////////////////////////////////////////////////////////////////
77 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures, IPC *ipc)
83 m_pendingFiles(new QStringList()),
86 m_skipVersionTest(false),
87 m_abortOnTimeout(true),
88 m_status(STATUS_PRE_INIT),
90 ui(new Ui::MainWindow())
92 //Init the dialog, from the .ui file
94 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
97 qRegisterMetaType<QUuid>("QUuid");
98 qRegisterMetaType<QUuid>("DWORD");
99 qRegisterMetaType<JobStatus>("JobStatus");
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);
109 m_preferences = new PreferencesModel();
110 PreferencesModel::loadPreferences(m_preferences);
113 m_recentlyUsed = new RecentlyUsed();
114 RecentlyUsed::loadRecentlyUsed(m_recentlyUsed);
116 //Create options object
117 m_options = new OptionsModel();
118 OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
120 //Freeze minimum size
121 setMinimumSize(size());
122 ui->splitter->setSizes(QList<int>() << 16 << 196);
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"));
130 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
131 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
133 else if(x264_is_prerelease())
135 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
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);
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)));
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());
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()));
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()));
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()));
206 MainWindow::~MainWindow(void)
208 m_status = STATUS_EXITTING;
209 OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
211 X264_DELETE(m_jobList);
212 X264_DELETE(m_options);
213 X264_DELETE(m_pendingFiles);
214 X264_DELETE(m_label);
216 while(!m_toolsList.isEmpty())
218 QFile *temp = m_toolsList.takeFirst();
222 if(m_ipc->isListening())
224 m_ipc->stopListening();
227 X264_DELETE(m_preferences);
228 X264_DELETE(m_recentlyUsed);
229 X264_DELETE(m_sysinfo);
231 VapourSynthCheckThread::unload();
232 AvisynthCheckThread::unload();
237 ///////////////////////////////////////////////////////////////////////////////
239 ///////////////////////////////////////////////////////////////////////////////
242 * The "add" button was clicked
244 void MainWindow::addButtonPressed()
246 ENSURE_APP_IS_IDLE();
247 m_status = STATUS_BLOCKED;
249 qDebug("MainWindow::addButtonPressed");
250 bool runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
251 QString sourceFileName, outputFileName;
253 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
255 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
258 m_status = STATUS_IDLE;
262 * The "open" action was triggered
264 void MainWindow::openActionTriggered()
266 ENSURE_APP_IS_IDLE();
267 m_status = STATUS_BLOCKED;
269 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
270 if(!fileList.empty())
272 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
273 if(fileList.count() > 1)
275 createJobMultiple(fileList);
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))
283 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
288 m_status = STATUS_IDLE;
292 * The "start" button was clicked
294 void MainWindow::startButtonPressed(void)
296 ENSURE_APP_IS_IDLE();
297 m_jobList->startJob(ui->jobsView->currentIndex());
301 * The "abort" button was clicked
303 void MainWindow::abortButtonPressed(void)
305 ENSURE_APP_IS_IDLE();
306 m_jobList->abortJob(ui->jobsView->currentIndex());
310 * The "delete" button was clicked
312 void MainWindow::deleteButtonPressed(void)
314 ENSURE_APP_IS_IDLE();
315 m_jobList->deleteJob(ui->jobsView->currentIndex());
316 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
320 * The "browse" button was clicked
322 void MainWindow::browseButtonPressed(void)
324 ENSURE_APP_IS_IDLE();
325 m_status = STATUS_BLOCKED;
327 QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
328 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
330 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
334 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
337 m_status = STATUS_IDLE;
341 * The "pause" button was clicked
343 void MainWindow::pauseButtonPressed(bool checked)
345 ENSURE_APP_IS_IDLE();
349 m_jobList->pauseJob(ui->jobsView->currentIndex());
353 m_jobList->resumeJob(ui->jobsView->currentIndex());
358 * The "restart" button was clicked
360 void MainWindow::restartButtonPressed(void)
362 ENSURE_APP_IS_IDLE();
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);
369 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
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))
375 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
377 X264_DELETE(tempOptions);
382 * Job item selected by user
384 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
386 qDebug("Job selected: %d", current.row());
388 if(ui->logView->model())
390 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
393 if(current.isValid())
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()));
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>());
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());
415 ui->progressBar->repaint();
419 * Handle update of job info (status, progress, details, etc)
421 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
423 int selected = ui->jobsView->currentIndex().row();
425 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
427 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
429 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
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>());
436 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
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()));
444 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
446 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
450 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
451 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
456 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
458 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
462 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
470 * Handle new log file content
472 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
474 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
480 void MainWindow::showAbout(void)
482 ENSURE_APP_IS_IDLE();
483 m_status = STATUS_BLOCKED;
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 <mulder2@gmx.de>. 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 <http://www.gnu.org/>.<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);
494 QMessageBox aboutBox(this);
495 aboutBox.setIconPixmap(QIcon(":/images/movie.png").pixmap(64,64));
496 aboutBox.setWindowTitle(tr("About..."));
497 aboutBox.setText(text.replace("-", "−"));
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));
506 x264_beep(x264_beep_info);
507 switch(aboutBox.exec())
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");
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("-", "−"));
522 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
523 x264_beep(x264_beep_info);
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");
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("-", "−"));
540 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
541 x264_beep(x264_beep_info);
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");
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("-", "−"));
558 x264Box.setEscapeButton(x264Box.addButton(tr("Close"), QMessageBox::NoRole));
559 x264_beep(x264_beep_info);
564 QMessageBox::aboutQt(this);
567 m_status = STATUS_IDLE;
576 void MainWindow::showWebLink(void)
578 ENSURE_APP_IS_IDLE();
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"));
598 * Pereferences dialog
600 void MainWindow::showPreferences(void)
602 ENSURE_APP_IS_IDLE();
603 m_status = STATUS_BLOCKED;
605 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences, m_sysinfo);
608 X264_DELETE(preferences);
609 m_status = STATUS_IDLE;
613 * Launch next job, after running job has finished
615 void MainWindow::launchNextJob(void)
617 qDebug("launchNextJob(void)");
619 const int rows = m_jobList->rowCount(QModelIndex());
621 if(countRunningJobs() >= m_preferences->maxRunningJobCount())
623 qDebug("Still have too many jobs running, won't launch next one yet!");
627 int startIdx= ui->jobsView->currentIndex().isValid() ? qBound(0, ui->jobsView->currentIndex().row(), rows-1) : 0;
629 for(int i = 0; i < rows; i++)
631 int currentIdx = (i + startIdx) % rows;
632 JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
633 if(status == JobStatus_Enqueued)
635 if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
637 ui->jobsView->selectRow(currentIdx);
643 qWarning("No enqueued jobs left!");
647 * Save log to text file
649 void MainWindow::saveLogFile(const QModelIndex &index)
653 if(LogFileModel *log = m_jobList->getLogFile(index))
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))
660 QTextStream outStream(&outFile);
661 outStream.setCodec("UTF-8");
662 outStream.setGenerateByteOrderMark(true);
664 const int rows = log->rowCount(QModelIndex());
665 for(int i = 0; i < rows; i++)
667 outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
673 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
680 * Shut down the computer (with countdown)
682 void MainWindow::shutdownComputer(void)
684 qDebug("shutdownComputer(void)");
686 if((m_status != STATUS_IDLE) && (m_status != STATUS_EXITTING))
688 qWarning("Cannot shutdown computer at this time!");
692 if(countPendingJobs() > 0)
694 qDebug("Still have pending jobs, won't shutdown yet!");
698 const x264_status_t previousStatus = m_status;
699 m_status = STATUS_BLOCKED;
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..."));
705 qWarning("Initiating shutdown sequence!");
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();
718 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
719 QApplication::setOverrideCursor(Qt::WaitCursor);
720 x264_play_sound(IDR_WAVE1, false);
721 QApplication::restoreOverrideCursor();
724 timer.setInterval(1000);
727 QEventLoop eventLoop(this);
728 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
729 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
731 for(int i = 1; i <= iTimeout; i++)
734 if(progressDialog.wasCanceled())
736 progressDialog.close();
737 m_status = previousStatus;
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);
747 qWarning("Shutting down !!!");
748 m_status = previousStatus;
750 if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
752 qApp->closeAllWindows();
758 * Main initialization function (called only once!)
760 void MainWindow::init(void)
762 if(m_status != STATUS_PRE_INIT)
764 qWarning("Already initialized -> skipping!");
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);
774 //Create the IPC listener thread
775 if(m_ipc->isInitialized())
777 connect(m_ipc, SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
778 m_ipc->startListening();
782 while(!binaries.isEmpty())
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))
789 if(!x264_is_executable(file->fileName()))
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("-", "−"));
792 qFatal(QString("Binary is invalid: %1/toolset/%2").arg(m_sysinfo->getAppPath(), current).toLatin1().constData());
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("-", "−"));
801 qFatal(QString("Binary not found: %1/toolset/%2").arg(m_sysinfo->getAppPath(), current).toLatin1().constData());
806 //Check for portable mode
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))
814 ok = (writeTest.write(data) == strlen(data));
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();
825 if(x264_is_prerelease())
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();
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())
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 !!!");
839 else if(!m_sysinfo->hasSSESupport())
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();
846 //Skip version check (not recommended!)
847 if(CLIParser::checkFlag(CLI_PARAM_SKIP_X264_CHECK, arguments))
849 qWarning("x264 version check disabled, you have been warned!\n");
850 m_skipVersionTest = true;
853 //Don't abort encoding process on timeout (not recommended!)
854 if(CLIParser::checkFlag(CLI_PARAM_NO_DEADLOCK, arguments))
856 qWarning("Deadlock detection disabled, you have been warned!\n");
857 m_abortOnTimeout = false;
860 //Check for Avisynth support
861 if(!CLIParser::checkFlag(CLI_PARAM_SKIP_AVS_CHECK, arguments))
863 qDebug("[Check for Avisynth support]");
864 volatile double avisynthVersion = 0.0;
865 const int result = AvisynthCheckThread::detect(&avisynthVersion);
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("-", "−"), tr("Quit"), tr("Ignore"));
872 if(val != 1) INIT_ERROR_EXIT();
874 if(result && (avisynthVersion >= 2.5))
876 qDebug("Avisynth support is officially enabled now!");
877 m_sysinfo->setAVSSupport(true);
881 if(!m_preferences->disableWarnings())
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("-", "−"), tr("Quit"), tr("Ignore"));
886 if(val != 1) INIT_ERROR_EXIT();
892 //Check for VapourSynth support
893 if(!CLIParser::checkFlag(CLI_PARAM_SKIP_VPS_CHECK, arguments))
895 qDebug("[Check for VapourSynth support]");
896 QString vapoursynthPath;
897 const int result = VapourSynthCheckThread::detect(vapoursynthPath);
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("-", "−"), tr("Quit"), tr("Ignore"));
904 if(val != 1) INIT_ERROR_EXIT();
906 if(result && (!vapoursynthPath.isEmpty()))
908 qDebug("VapourSynth support is officially enabled now!");
909 m_sysinfo->setVPSSupport(true);
910 m_sysinfo->setVPSPath(vapoursynthPath);
914 if(!m_preferences->disableWarnings())
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("-", "−"), tr("Quit"), tr("Ignore"));
920 if(val != 1) INIT_ERROR_EXIT();
926 //Enable drag&drop support for this window, required for Qt v4.8.4+
927 setAcceptDrops(true);
929 //Check for expiration
930 if(x264_version_date().addMonths(6) < x264_current_date_safe())
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("-", "−"));
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("-", "−"), 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("-", "−"));
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)
950 m_status = STATUS_IDLE;
951 QTimer::singleShot(0, this, SLOT(checkUpdates()));
957 m_status = STATUS_IDLE;
959 //Try adding files from command-line
960 if(!parseCommandLineArgs())
963 if((!m_preferences->noUpdateReminder()) && (m_recentlyUsed->lastUpdateCheck() + 14 < x264_current_date_safe().toJulianDay()))
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)
967 QTimer::singleShot(0, this, SLOT(checkUpdates()));
975 * Update the label position
977 void MainWindow::updateLabelPos(void)
979 const QWidget *const viewPort = ui->jobsView->viewport();
980 m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
984 * Copy the complete log to the clipboard
986 void MainWindow::copyLogToClipboard(bool checked)
988 qDebug("copyLogToClipboard");
990 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
992 log->copyToClipboard();
993 x264_beep(x264_beep_info);
998 * Process the dropped files
1000 void MainWindow::handlePendingFiles(void)
1002 if((m_status == STATUS_IDLE) || (m_status == STATUS_AWAITING))
1004 qDebug("MainWindow::handlePendingFiles");
1005 if(!m_pendingFiles->isEmpty())
1007 QStringList pendingFiles(*m_pendingFiles);
1008 m_pendingFiles->clear();
1009 createJobMultiple(pendingFiles);
1011 qDebug("Leave from MainWindow::handlePendingFiles!");
1012 m_status = STATUS_IDLE;
1016 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1018 if((m_status != STATUS_IDLE) && (m_status != STATUS_AWAITING))
1020 qWarning("Cannot accapt commands at this time -> discarding!");
1024 x264_bring_to_front(this);
1027 qDebug("\n---------- IPC ----------");
1028 qDebug("CommandId: %d", command);
1029 for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1031 qDebug("Arguments: %s", iter->toUtf8().constData());
1033 qDebug("The Flags: 0x%08X", flags);
1034 qDebug("---------- IPC ----------\n");
1035 #endif //IPC_LOGGING
1039 case IPC_OPCODE_PING:
1040 qDebug("Received a PING request from another instance!");
1041 x264_blink_window(this, 5, 125);
1043 case IPC_OPCODE_ADD_FILE:
1046 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1048 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1049 if(m_status != STATUS_AWAITING)
1051 m_status = STATUS_AWAITING;
1052 QTimer::singleShot(5000, this, SLOT(handlePendingFiles()));
1057 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1061 case IPC_OPCODE_ADD_JOB:
1062 if(args.size() >= 3)
1064 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1066 OptionsModel options;
1067 bool runImmediately = (countRunningJobs() < (m_preferences->autoRunNextJob() ? m_preferences->maxRunningJobCount() : 1));
1068 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1070 if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1072 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
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);
1081 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1086 throw std::exception("Unknown command received!");
1090 void MainWindow::checkUpdates(void)
1092 ENSURE_APP_IS_IDLE();
1093 m_status = STATUS_BLOCKED;
1095 if(countRunningJobs() > 0)
1097 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1098 m_status = STATUS_IDLE;
1102 UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo);
1103 const int ret = updater->exec();
1105 if(updater->getSuccess())
1107 m_recentlyUsed->setLastUpdateCheck(x264_current_date_safe().toJulianDay());
1108 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
1111 if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1113 m_status = STATUS_EXITTING;
1114 qWarning("Exitting program to install update...");
1116 QApplication::quit();
1119 X264_DELETE(updater);
1121 if(m_status != STATUS_EXITTING)
1123 m_status = STATUS_IDLE;
1127 ///////////////////////////////////////////////////////////////////////////////
1129 ///////////////////////////////////////////////////////////////////////////////
1132 * Window shown event
1134 void MainWindow::showEvent(QShowEvent *e)
1136 QMainWindow::showEvent(e);
1140 m_firstShow = false;
1141 QTimer::singleShot(0, this, SLOT(init()));
1146 * Window close event
1148 void MainWindow::closeEvent(QCloseEvent *e)
1150 if((m_status != STATUS_IDLE) && (m_status != STATUS_EXITTING))
1153 qWarning("Cannot close window at this time!");
1157 if(m_status != STATUS_EXITTING)
1159 if(countRunningJobs() > 0)
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;
1168 if(countPendingJobs() > 0)
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)
1175 m_status = STATUS_IDLE;
1181 while(m_jobList->rowCount(QModelIndex()) > 0)
1183 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1184 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
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;
1194 m_status = STATUS_EXITTING;
1195 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1196 QMainWindow::closeEvent(e);
1200 * Window resize event
1202 void MainWindow::resizeEvent(QResizeEvent *e)
1204 QMainWindow::resizeEvent(e);
1211 bool MainWindow::eventFilter(QObject *o, QEvent *e)
1213 if((o == ui->labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
1215 QTimer::singleShot(0, this, SLOT(showAbout()));
1222 * Win32 message filter
1224 bool MainWindow::winEvent(MSG *message, long *result)
1226 return WinSevenTaskbar::handleWinEvent(message, result);
1230 * File dragged over window
1232 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1234 bool accept[2] = {false, false};
1236 foreach(const QString &fmt, event->mimeData()->formats())
1238 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1239 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1242 if(accept[0] && accept[1])
1244 event->acceptProposedAction();
1249 * File dropped onto window
1251 void MainWindow::dropEvent(QDropEvent *event)
1253 if((m_status != STATUS_IDLE) && (m_status != STATUS_AWAITING))
1255 qWarning("Cannot accept drooped files at this time -> discarding!");
1259 QStringList droppedFiles;
1260 QList<QUrl> urls = event->mimeData()->urls();
1262 while(!urls.isEmpty())
1264 QUrl currentUrl = urls.takeFirst();
1265 QFileInfo file(currentUrl.toLocalFile());
1266 if(file.exists() && file.isFile())
1268 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1269 droppedFiles << file.canonicalFilePath();
1273 if(droppedFiles.count() > 0)
1275 m_pendingFiles->append(droppedFiles);
1276 m_pendingFiles->sort();
1277 if(m_status != STATUS_AWAITING)
1279 m_status = STATUS_AWAITING;
1280 QTimer::singleShot(0, this, SLOT(handlePendingFiles()));
1285 ///////////////////////////////////////////////////////////////////////////////
1286 // Private functions
1287 ///////////////////////////////////////////////////////////////////////////////
1292 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1295 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed, m_sysinfo, m_preferences);
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"));
1302 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
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);
1310 if(addDialog->exec() == QDialog::Accepted)
1312 sourceFileName = addDialog->sourceFile();
1313 outputFileName = addDialog->outputFile();
1314 runImmediately = addDialog->runImmediately();
1317 *applyToAll = addDialog->applyToAll();
1322 X264_DELETE(addDialog);
1327 * Creates a new job from *multiple* files
1329 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1331 QStringList::ConstIterator iter;
1332 bool applyToAll = false, runImmediately = false;
1335 //Add files individually
1336 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
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))
1342 if(appendJob(sourceFileName, outputFileName, m_options, runImmediately))
1350 //Add remaining files
1351 while(applyToAll && (iter != filePathIn.constEnd()))
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))
1370 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1374 EncodeThread *thrd = NULL/*new EncodeThread
1380 m_preferences->useAvisyth64Bit(),
1382 m_preferences->processPriority(),
1386 QModelIndex newIndex = m_jobList->insertJob(thrd);
1388 if(newIndex.isValid())
1392 ui->jobsView->selectRow(newIndex.row());
1393 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1394 m_jobList->startJob(newIndex);
1400 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1405 * Jobs that are not completed (or failed, or aborted) yet
1407 unsigned int MainWindow::countPendingJobs(void)
1409 unsigned int count = 0;
1410 const int rows = m_jobList->rowCount(QModelIndex());
1412 for(int i = 0; i < rows; i++)
1414 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1415 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1425 * Jobs that are still active, i.e. not terminated or enqueued
1427 unsigned int MainWindow::countRunningJobs(void)
1429 unsigned int count = 0;
1430 const int rows = m_jobList->rowCount(QModelIndex());
1432 for(int i = 0; i < rows; i++)
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)
1445 * Update all buttons with respect to current job status
1447 void MainWindow::updateButtons(JobStatus status)
1449 qDebug("MainWindow::updateButtons(void)");
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);
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);
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());
1465 ui->editDetails->setEnabled(status != JobStatus_Paused);
1469 * Update the taskbar with current job status
1471 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1473 qDebug("MainWindow::updateTaskbar(void)");
1477 case JobStatus_Undefined:
1478 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1480 case JobStatus_Aborting:
1481 case JobStatus_Starting:
1482 case JobStatus_Pausing:
1483 case JobStatus_Resuming:
1484 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1486 case JobStatus_Aborted:
1487 case JobStatus_Failed:
1488 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1490 case JobStatus_Paused:
1491 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1494 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1500 case JobStatus_Aborting:
1501 case JobStatus_Starting:
1502 case JobStatus_Pausing:
1503 case JobStatus_Resuming:
1506 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
1510 WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);
1514 * Parse command-line arguments
1516 bool MainWindow::parseCommandLineArgs(void)
1518 bool bCommandAccepted = false;
1519 unsigned int flags = 0;
1521 //Initialize command-line parser
1522 CLIParser parser(x264_arguments());
1524 QStringList options;
1526 //Process all command-line arguments
1527 while(parser.nextOption(identifier, &options))
1531 case CLI_PARAM_ADD_FILE:
1532 handleCommand(IPC_OPCODE_ADD_FILE, options, flags);
1533 bCommandAccepted = true;
1535 case CLI_PARAM_ADD_JOB:
1536 handleCommand(IPC_OPCODE_ADD_JOB, options, flags);
1537 bCommandAccepted = true;
1539 case CLI_PARAM_FORCE_START:
1540 flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1542 case CLI_PARAM_NO_FORCE_START:
1543 flags = (flags & (~IPC_FLAG_FORCE_START));
1545 case CLI_PARAM_FORCE_ENQUEUE:
1546 flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1548 case CLI_PARAM_NO_FORCE_ENQUEUE:
1549 flags = (flags & (~IPC_FLAG_FORCE_ENQUEUE));
1554 return bCommandAccepted;