Updated web-site URL's to make them more consistent.
[simple-x264-launcher.git] / src / win_main.cpp
blobaf033230dc9e4aa5557b781f736166bfea2d3c4a
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.
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 ///////////////////////////////////////////////////////////////////////////////
22 #include "win_main.h"
23 #include "uic_win_main.h"
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_about.h"
40 #include "win_preferences.h"
41 #include "win_updater.h"
42 #include "binaries.h"
43 #include "resource.h"
45 #include <QDate>
46 #include <QTimer>
47 #include <QCloseEvent>
48 #include <QMessageBox>
49 #include <QDesktopServices>
50 #include <QUrl>
51 #include <QDir>
52 #include <QLibrary>
53 #include <QProcess>
54 #include <QProgressDialog>
55 #include <QScrollBar>
56 #include <QTextStream>
57 #include <QSettings>
58 #include <QFileDialog>
60 #include <ctime>
62 const char *home_url = "http://muldersoft.com/";
63 const char *update_url = "https://github.com/lordmulder/Simple-x264-Launcher/releases/latest";
64 const char *tpl_last = "<LAST_USED>";
66 #define SET_FONT_BOLD(WIDGET,BOLD) do { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); } while(0)
67 #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)
68 #define LINK(URL) "<a href=\"" URL "\">" URL "</a>"
69 #define INIT_ERROR_EXIT() do { m_status = STATUS_EXITTING; close(); qApp->exit(-1); return; } while(0)
70 #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)
71 #define NEXT(X) ((*reinterpret_cast<int*>(&(X)))++)
72 #define SETUP_WEBLINK(OBJ, URL) do { (OBJ)->setData(QVariant(QUrl(URL))); connect((OBJ), SIGNAL(triggered()), this, SLOT(showWebLink())); } while(0)
75 ///////////////////////////////////////////////////////////////////////////////
76 // Constructor & Destructor
77 ///////////////////////////////////////////////////////////////////////////////
80 * Constructor
82 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures, IPC *ipc)
84 m_ipc(ipc),
85 m_sysinfo(NULL),
86 m_options(NULL),
87 m_jobList(NULL),
88 m_pendingFiles(new QStringList()),
89 m_preferences(NULL),
90 m_recentlyUsed(NULL),
91 m_status(STATUS_PRE_INIT),
92 ui(new Ui::MainWindow())
94 //Init the dialog, from the .ui file
95 ui->setupUi(this);
96 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
98 //Register meta types
99 qRegisterMetaType<QUuid>("QUuid");
100 qRegisterMetaType<QUuid>("DWORD");
101 qRegisterMetaType<JobStatus>("JobStatus");
103 //Create and initialize the sysinfo object
104 m_sysinfo = new SysinfoModel();
105 m_sysinfo->setAppPath(QApplication::applicationDirPath());
106 m_sysinfo->setMMXSupport(cpuFeatures->mmx && cpuFeatures->mmx2);
107 m_sysinfo->setSSESupport(cpuFeatures->sse && cpuFeatures->mmx2); //SSE implies MMX2
108 m_sysinfo->setX64Support(cpuFeatures->x64 && cpuFeatures->sse2); //X64 implies SSE2
110 //Load preferences
111 m_preferences = new PreferencesModel();
112 PreferencesModel::loadPreferences(m_preferences);
114 //Load recently used
115 m_recentlyUsed = new RecentlyUsed();
116 RecentlyUsed::loadRecentlyUsed(m_recentlyUsed);
118 //Create options object
119 m_options = new OptionsModel(m_sysinfo);
120 OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
122 //Freeze minimum size
123 setMinimumSize(size());
124 ui->splitter->setSizes(QList<int>() << 16 << 196);
126 //Update title
127 ui->labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
128 ui->labelBuildDate->installEventFilter(this);
130 if(X264_DEBUG)
132 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
133 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
135 else if(x264_is_prerelease())
137 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
140 //Create model
141 m_jobList = new JobListModel(m_preferences);
142 connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
143 ui->jobsView->setModel(m_jobList);
145 //Setup view
146 ui->jobsView->horizontalHeader()->setSectionHidden(3, true);
147 ui->jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
148 ui->jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
149 ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
150 ui->jobsView->horizontalHeader()->resizeSection(1, 150);
151 ui->jobsView->horizontalHeader()->resizeSection(2, 90);
152 ui->jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
153 connect(ui->jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
155 //Create context menu
156 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), ui->logView);
157 actionClipboard->setEnabled(false);
158 ui->logView->addAction(actionClipboard);
159 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
160 ui->jobsView->addActions(ui->menuJob->actions());
162 //Enable buttons
163 connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed()));
164 connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed()));
165 connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed()));
166 connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
167 connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed()));
168 connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed()));
169 connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed()));
171 //Enable menu
172 connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
173 connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
174 connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
175 connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
177 //Setup web-links
178 SETUP_WEBLINK(ui->actionWebMulder, home_url);
179 SETUP_WEBLINK(ui->actionWebX264, "http://www.videolan.org/developers/x264.html");
180 SETUP_WEBLINK(ui->actionWebX265, "http://www.videolan.org/developers/x265.html");
181 SETUP_WEBLINK(ui->actionWebKomisar, "http://komisar.gin.by/");
182 SETUP_WEBLINK(ui->actionWebVideoLAN, "http://download.videolan.org/pub/x264/binaries/");
183 SETUP_WEBLINK(ui->actionWebJEEB, "http://x264.fushizen.eu/");
184 SETUP_WEBLINK(ui->actionWebFreeCodecs, "http://www.free-codecs.com/x264_video_codec_download.htm");
185 SETUP_WEBLINK(ui->actionWebX265BinRU, "http://goo.gl/xRS6AW");
186 SETUP_WEBLINK(ui->actionWebX265BinEU, "http://builds.x265.eu/");
187 SETUP_WEBLINK(ui->actionWebX265BinORG, "http://chromashift.org/x265_builds/");
188 SETUP_WEBLINK(ui->actionWebX265BinFF, "http://ffmpeg.zeranoe.com/builds/");
189 SETUP_WEBLINK(ui->actionWebAvisynth32, "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/");
190 SETUP_WEBLINK(ui->actionWebAvisynth64, "http://code.google.com/p/avisynth64/downloads/list");
191 SETUP_WEBLINK(ui->actionWebAvisynthPlus, "http://www.avs-plus.net/");
192 SETUP_WEBLINK(ui->actionWebVapourSynth, "http://www.vapoursynth.com/");
193 SETUP_WEBLINK(ui->actionWebVapourSynthDocs, "http://www.vapoursynth.com/doc/");
194 SETUP_WEBLINK(ui->actionWebWiki, "http://mewiki.project357.com/wiki/X264_Settings");
195 SETUP_WEBLINK(ui->actionWebBluRay, "http://www.x264bluray.com/");
196 SETUP_WEBLINK(ui->actionWebAvsWiki, "http://avisynth.nl/index.php/Main_Page#Usage");
197 SETUP_WEBLINK(ui->actionWebSupport, "http://forum.doom9.org/showthread.php?t=144140");
198 SETUP_WEBLINK(ui->actionWebSecret, "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
200 //Create floating label
201 m_label = new QLabel(ui->jobsView->viewport());
202 m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
203 m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
204 SET_TEXT_COLOR(m_label, Qt::darkGray);
205 SET_FONT_BOLD(m_label, true);
206 m_label->setVisible(true);
207 m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
208 m_label->addActions(ui->jobsView->actions());
209 connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
210 updateLabelPos();
214 * Destructor
216 MainWindow::~MainWindow(void)
218 m_status = STATUS_EXITTING;
219 OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
221 X264_DELETE(m_jobList);
222 X264_DELETE(m_options);
223 X264_DELETE(m_pendingFiles);
224 X264_DELETE(m_label);
226 while(!m_toolsList.isEmpty())
228 QFile *temp = m_toolsList.takeFirst();
229 X264_DELETE(temp);
232 if(m_ipc->isListening())
234 m_ipc->stopListening();
237 X264_DELETE(m_preferences);
238 X264_DELETE(m_recentlyUsed);
239 X264_DELETE(m_sysinfo);
241 VapourSynthCheckThread::unload();
242 AvisynthCheckThread::unload();
244 delete ui;
247 ///////////////////////////////////////////////////////////////////////////////
248 // Slots
249 ///////////////////////////////////////////////////////////////////////////////
252 * The "add" button was clicked
254 void MainWindow::addButtonPressed()
256 ENSURE_APP_IS_IDLE();
257 m_status = STATUS_BLOCKED;
259 qDebug("MainWindow::addButtonPressed");
260 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
261 QString sourceFileName, outputFileName;
263 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
265 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
268 m_status = STATUS_IDLE;
272 * The "open" action was triggered
274 void MainWindow::openActionTriggered()
276 ENSURE_APP_IS_IDLE();
277 m_status = STATUS_BLOCKED;
279 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
280 if(!fileList.empty())
282 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
283 if(fileList.count() > 1)
285 createJobMultiple(fileList);
287 else
289 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
290 QString sourceFileName(fileList.first()), outputFileName;
291 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
293 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
298 m_status = STATUS_IDLE;
302 * The "start" button was clicked
304 void MainWindow::startButtonPressed(void)
306 ENSURE_APP_IS_IDLE();
307 m_jobList->startJob(ui->jobsView->currentIndex());
311 * The "abort" button was clicked
313 void MainWindow::abortButtonPressed(void)
315 ENSURE_APP_IS_IDLE();
316 m_status = STATUS_BLOCKED;
318 if(QMessageBox::question(this, tr("Abort Job?"), tr("<nobr>Do you really want to <b>abort</b> the selected job now?</nobr>"), tr("Back"), tr("Abort Job")) == 1)
320 m_jobList->abortJob(ui->jobsView->currentIndex());
323 m_status = STATUS_IDLE;
327 * The "delete" button was clicked
329 void MainWindow::deleteButtonPressed(void)
331 ENSURE_APP_IS_IDLE();
332 m_jobList->deleteJob(ui->jobsView->currentIndex());
333 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
337 * The "browse" button was clicked
339 void MainWindow::browseButtonPressed(void)
341 ENSURE_APP_IS_IDLE();
342 m_status = STATUS_BLOCKED;
344 QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
345 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
347 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
349 else
351 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
354 m_status = STATUS_IDLE;
358 * The "pause" button was clicked
360 void MainWindow::pauseButtonPressed(bool checked)
362 ENSURE_APP_IS_IDLE();
364 if(checked)
366 m_jobList->pauseJob(ui->jobsView->currentIndex());
368 else
370 m_jobList->resumeJob(ui->jobsView->currentIndex());
375 * The "restart" button was clicked
377 void MainWindow::restartButtonPressed(void)
379 ENSURE_APP_IS_IDLE();
381 const QModelIndex index = ui->jobsView->currentIndex();
382 const OptionsModel *options = m_jobList->getJobOptions(index);
383 QString sourceFileName = m_jobList->getJobSourceFile(index);
384 QString outputFileName = m_jobList->getJobOutputFile(index);
386 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
388 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
389 OptionsModel *tempOptions = new OptionsModel(*options);
390 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
392 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
394 X264_DELETE(tempOptions);
399 * Job item selected by user
401 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
403 qDebug("Job selected: %d", current.row());
405 if(ui->logView->model())
407 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
410 if(current.isValid())
412 ui->logView->setModel(m_jobList->getLogFile(current));
413 connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
414 ui->logView->actions().first()->setEnabled(true);
415 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
417 ui->progressBar->setValue(m_jobList->getJobProgress(current));
418 ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
419 updateButtons(m_jobList->getJobStatus(current));
420 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
422 else
424 ui->logView->setModel(NULL);
425 ui->logView->actions().first()->setEnabled(false);
426 ui->progressBar->setValue(0);
427 ui->editDetails->clear();
428 updateButtons(JobStatus_Undefined);
429 updateTaskbar(JobStatus_Undefined, QIcon());
432 ui->progressBar->repaint();
436 * Handle update of job info (status, progress, details, etc)
438 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
440 int selected = ui->jobsView->currentIndex().row();
442 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
444 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
446 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
447 if(i == selected)
449 qDebug("Current job changed status!");
450 updateButtons(status);
451 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
453 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
455 if(m_preferences->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
456 if(m_preferences->getShutdownComputer()) QTimer::singleShot(0, this, SLOT(shutdownComputer()));
457 if(m_preferences->getSaveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
461 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
463 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
465 if(i == selected)
467 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
468 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
469 break;
473 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
475 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
477 if(i == selected)
479 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
480 break;
487 * Handle new log file content
489 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
491 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
495 * About screen
497 void MainWindow::showAbout(void)
499 ENSURE_APP_IS_IDLE();
500 m_status = STATUS_BLOCKED;
502 if(AboutDialog *aboutDialog = new AboutDialog(this))
504 aboutDialog->exec();
505 X264_DELETE(aboutDialog);
508 m_status = STATUS_IDLE;
512 * Open web-link
514 void MainWindow::showWebLink(void)
516 ENSURE_APP_IS_IDLE();
518 if(QObject *obj = QObject::sender())
520 if(QAction *action = dynamic_cast<QAction*>(obj))
522 if(action->data().type() == QVariant::Url)
524 QDesktopServices::openUrl(action->data().toUrl());
531 * Pereferences dialog
533 void MainWindow::showPreferences(void)
535 ENSURE_APP_IS_IDLE();
536 m_status = STATUS_BLOCKED;
538 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences, m_sysinfo);
539 preferences->exec();
541 X264_DELETE(preferences);
542 m_status = STATUS_IDLE;
546 * Launch next job, after running job has finished
548 void MainWindow::launchNextJob(void)
550 qDebug("launchNextJob(void)");
552 const int rows = m_jobList->rowCount(QModelIndex());
554 if(countRunningJobs() >= m_preferences->getMaxRunningJobCount())
556 qDebug("Still have too many jobs running, won't launch next one yet!");
557 return;
560 int startIdx= ui->jobsView->currentIndex().isValid() ? qBound(0, ui->jobsView->currentIndex().row(), rows-1) : 0;
562 for(int i = 0; i < rows; i++)
564 int currentIdx = (i + startIdx) % rows;
565 JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
566 if(status == JobStatus_Enqueued)
568 if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
570 ui->jobsView->selectRow(currentIdx);
571 return;
576 qWarning("No enqueued jobs left!");
580 * Save log to text file
582 void MainWindow::saveLogFile(const QModelIndex &index)
584 if(index.isValid())
586 if(LogFileModel *log = m_jobList->getLogFile(index))
588 QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
589 QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
590 QFile outFile(logFilePath);
591 if(outFile.open(QIODevice::WriteOnly))
593 QTextStream outStream(&outFile);
594 outStream.setCodec("UTF-8");
595 outStream.setGenerateByteOrderMark(true);
597 const int rows = log->rowCount(QModelIndex());
598 for(int i = 0; i < rows; i++)
600 outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
602 outFile.close();
604 else
606 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
613 * Shut down the computer (with countdown)
615 void MainWindow::shutdownComputer(void)
617 qDebug("shutdownComputer(void)");
619 if((m_status != STATUS_IDLE) && (m_status != STATUS_EXITTING))
621 qWarning("Cannot shutdown computer at this time!");
622 return;
625 if(countPendingJobs() > 0)
627 qDebug("Still have pending jobs, won't shutdown yet!");
628 return;
631 const x264_status_t previousStatus = m_status;
632 m_status = STATUS_BLOCKED;
634 const int iTimeout = 30;
635 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
636 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
638 qWarning("Initiating shutdown sequence!");
640 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
641 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
642 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
643 progressDialog.setModal(true);
644 progressDialog.setAutoClose(false);
645 progressDialog.setAutoReset(false);
646 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
647 progressDialog.setWindowTitle(windowTitle());
648 progressDialog.setCancelButton(cancelButton);
649 progressDialog.show();
651 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
652 QApplication::setOverrideCursor(Qt::WaitCursor);
653 x264_play_sound(IDR_WAVE1, false);
654 QApplication::restoreOverrideCursor();
656 QTimer timer;
657 timer.setInterval(1000);
658 timer.start();
660 QEventLoop eventLoop(this);
661 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
662 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
664 for(int i = 1; i <= iTimeout; i++)
666 eventLoop.exec();
667 if(progressDialog.wasCanceled())
669 progressDialog.close();
670 m_status = previousStatus;
671 return;
673 progressDialog.setValue(i+1);
674 progressDialog.setLabelText(text.arg(iTimeout-i));
675 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
676 QApplication::processEvents();
677 x264_play_sound(((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), false);
680 qWarning("Shutting down !!!");
681 m_status = previousStatus;
683 if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
685 qApp->closeAllWindows();
691 * Main initialization function (called only once!)
693 void MainWindow::init(void)
695 if(m_status != STATUS_PRE_INIT)
697 qWarning("Already initialized -> skipping!");
698 return;
701 updateLabelPos();
703 //---------------------------------------
704 // Create the IPC listener thread
705 //---------------------------------------
707 if(m_ipc->isInitialized())
709 connect(m_ipc, SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
710 m_ipc->startListening();
713 //---------------------------------------
714 // Check required binaries
715 //---------------------------------------
717 QStringList binFiles;
718 for(OptionsModel::EncArch arch = OptionsModel::EncArch_x32; arch <= OptionsModel::EncArch_x64; NEXT(arch))
720 for(OptionsModel::EncVariant varnt = OptionsModel::EncVariant_LoBit; varnt <= OptionsModel::EncVariant_HiBit; NEXT(varnt))
722 binFiles << ENC_BINARY(m_sysinfo, OptionsModel::EncType_X264, arch, varnt);
724 binFiles << AVS_BINARY(m_sysinfo, arch == OptionsModel::EncArch_x64);
727 qDebug("[Validating binaries]");
728 for(QStringList::ConstIterator iter = binFiles.constBegin(); iter != binFiles.constEnd(); iter++)
730 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
731 QFile *file = new QFile(*iter);
732 qDebug("%s", file->fileName().toLatin1().constData());
733 if(file->open(QIODevice::ReadOnly))
735 if(!x264_is_executable(file->fileName()))
737 QMessageBox::critical(this, tr("Invalid File!"), tr("<nobr>At least on required tool is not a valid Win32 or Win64 binary:<br><tt style=\"whitespace:nowrap\">%1</tt><br><br>Please re-install the program in order to fix the problem!</nobr>").arg(QDir::toNativeSeparators(file->fileName())).replace("-", "&minus;"));
738 qFatal(QString("Binary is invalid: %1").arg(file->fileName()).toLatin1().constData());
739 X264_DELETE(file);
740 INIT_ERROR_EXIT();
742 m_toolsList << file;
744 else
746 QMessageBox::critical(this, tr("File Not Found!"), tr("<nobr>At least on required tool could not be found:<br><tt style=\"whitespace:nowrap\">%1</tt><br><br>Please re-install the program in order to fix the problem!</nobr>").arg(QDir::toNativeSeparators(file->fileName())).replace("-", "&minus;"));
747 qFatal(QString("Binary not found: %1/toolset/%2").arg(m_sysinfo->getAppPath(), file->fileName()).toLatin1().constData());
748 X264_DELETE(file);
749 INIT_ERROR_EXIT();
752 qDebug(" ");
754 //---------------------------------------
755 // Check x265 binaries
756 //---------------------------------------
758 binFiles.clear();
759 for(OptionsModel::EncArch arch = OptionsModel::EncArch_x32; arch <= OptionsModel::EncArch_x64; NEXT(arch))
761 for(OptionsModel::EncVariant varnt = OptionsModel::EncVariant_LoBit; varnt <= OptionsModel::EncVariant_HiBit; NEXT(varnt))
763 binFiles << ENC_BINARY(m_sysinfo, OptionsModel::EncType_X265, arch, varnt);
767 qDebug("[Checking for x265 support]");
768 bool bHaveX265 = true;
769 for(QStringList::ConstIterator iter = binFiles.constBegin(); iter != binFiles.constEnd(); iter++)
771 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
772 QFile *file = new QFile(*iter);
773 qDebug("%s", file->fileName().toLatin1().constData());
774 if(file->open(QIODevice::ReadOnly))
776 if(x264_is_executable(file->fileName()))
778 m_toolsList << file;
779 continue;
781 X264_DELETE(file);
783 bHaveX265 = false;
784 qWarning("x265 binaries not found or incomplete -> disable x265 support!");
785 break;
787 if(bHaveX265)
789 qDebug("x265 support is officially enabled now!");
790 m_sysinfo->set256Support(true);
792 qDebug(" ");
794 //---------------------------------------
795 // Check for portable mode
796 //---------------------------------------
798 if(x264_portable())
800 bool ok = false;
801 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
802 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
803 if(writeTest.open(QIODevice::WriteOnly))
805 ok = (writeTest.write(data) == strlen(data));
806 writeTest.remove();
808 if(!ok)
810 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"));
811 if(val != 1) INIT_ERROR_EXIT();
815 //Pre-release popup
816 if(x264_is_prerelease())
818 qsrand(time(NULL)); int rnd = qrand() % 3;
819 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);
820 if(rnd != val) INIT_ERROR_EXIT();
823 //---------------------------------------
824 // Check CPU capabilities
825 //---------------------------------------
827 const QStringList arguments = x264_arguments();
829 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
830 if(!m_sysinfo->hasMMXSupport())
832 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"));
833 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
834 INIT_ERROR_EXIT();
836 else if(!m_sysinfo->hasSSESupport())
838 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
839 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"));
840 if(val != 1) INIT_ERROR_EXIT();
843 //Skip version check (not recommended!)
844 if(CLIParser::checkFlag(CLI_PARAM_SKIP_X264_CHECK, arguments))
846 qWarning("x264 version check disabled, you have been warned!\n");
847 m_preferences->setSkipVersionTest(true);
850 //Don't abort encoding process on timeout (not recommended!)
851 if(CLIParser::checkFlag(CLI_PARAM_NO_DEADLOCK, arguments))
853 qWarning("Deadlock detection disabled, you have been warned!\n");
854 m_preferences->setAbortOnTimeout(false);
857 //---------------------------------------
858 // Check Avisynth support
859 //---------------------------------------
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);
866 if(result < 0)
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();
874 if(result && (avisynthVersion >= 2.5))
876 qDebug("Avisynth support is officially enabled now!");
877 m_sysinfo->setAVSSupport(true);
879 else
881 if(!m_preferences->getDisableWarnings())
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("Close"), tr("Disable this Warning"));
886 if(val == 1)
888 m_preferences->setDisableWarnings(true);
889 PreferencesModel::savePreferences(m_preferences);
894 qDebug(" ");
897 //---------------------------------------
898 // Check VapurSynth support
899 //---------------------------------------
901 if(!CLIParser::checkFlag(CLI_PARAM_SKIP_VPS_CHECK, arguments))
903 qDebug("[Check for VapourSynth support]");
904 QString vapoursynthPath;
905 const int result = VapourSynthCheckThread::detect(vapoursynthPath);
906 if(result < 0)
908 QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
909 text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
910 text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
911 const int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
912 if(val != 1) INIT_ERROR_EXIT();
914 if(result && (!vapoursynthPath.isEmpty()))
916 qDebug("VapourSynth support is officially enabled now!");
917 m_sysinfo->setVPSSupport(true);
918 m_sysinfo->setVPSPath(vapoursynthPath);
920 else
922 if(!m_preferences->getDisableWarnings())
924 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>");
925 text += tr("Please download and install VapourSynth for Windows (R19 or later):").append("<br>").append(LINK("http://www.vapoursynth.com/")).append("<br><br>");
926 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>");
927 const int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
928 if(val == 1)
930 m_preferences->setDisableWarnings(true);
931 PreferencesModel::savePreferences(m_preferences);
935 qDebug(" ");
938 //---------------------------------------
939 // Check for Expiration
940 //---------------------------------------
942 if(x264_version_date().addMonths(6) < x264_current_date_safe())
944 QString text;
945 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;"));
946 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));
947 text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace("-", "&minus;"));
948 QMessageBox msgBox(this);
949 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
950 msgBox.setWindowTitle(tr("Update Notification"));
951 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
952 msgBox.setText(text);
953 QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
954 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
955 QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
956 btn2->setEnabled(false);
957 btn3->setVisible(false);
958 QTimer::singleShot(7500, btn2, SLOT(hide()));
959 QTimer::singleShot(7500, btn3, SLOT(show()));
960 if(msgBox.exec() == 0)
962 m_status = STATUS_IDLE;
963 QTimer::singleShot(0, this, SLOT(checkUpdates()));
964 return;
968 //---------------------------------------
969 // Finish initialization
970 //---------------------------------------
972 //Set Window title
973 setWindowTitle(QString("%1 (%2)").arg(tr("Simple %1 Launcher").arg(m_sysinfo->has256Support() ? "x264/x265" : "x264"), m_sysinfo->hasX64Support() ? "64-Bit" : "32-Bit"));
975 //Enable drag&drop support for this window, required for Qt v4.8.4+
976 setAcceptDrops(true);
978 //Update app staus
979 m_status = STATUS_IDLE;
981 //Try adding files from command-line
982 if(!parseCommandLineArgs())
984 //Update reminder
985 if((!m_preferences->getNoUpdateReminder()) && (m_recentlyUsed->lastUpdateCheck() + 14 < x264_current_date_safe().toJulianDay()))
987 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)
989 QTimer::singleShot(0, this, SLOT(checkUpdates()));
990 return;
997 * Update the label position
999 void MainWindow::updateLabelPos(void)
1001 const QWidget *const viewPort = ui->jobsView->viewport();
1002 m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
1006 * Copy the complete log to the clipboard
1008 void MainWindow::copyLogToClipboard(bool checked)
1010 qDebug("copyLogToClipboard");
1012 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1014 log->copyToClipboard();
1015 x264_beep(x264_beep_info);
1020 * Process the dropped files
1022 void MainWindow::handlePendingFiles(void)
1024 if((m_status == STATUS_IDLE) || (m_status == STATUS_AWAITING))
1026 qDebug("MainWindow::handlePendingFiles");
1027 if(!m_pendingFiles->isEmpty())
1029 QStringList pendingFiles(*m_pendingFiles);
1030 m_pendingFiles->clear();
1031 createJobMultiple(pendingFiles);
1033 qDebug("Leave from MainWindow::handlePendingFiles!");
1034 m_status = STATUS_IDLE;
1038 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1040 if((m_status != STATUS_IDLE) && (m_status != STATUS_AWAITING))
1042 qWarning("Cannot accapt commands at this time -> discarding!");
1043 return;
1046 x264_bring_to_front(this);
1048 #ifdef IPC_LOGGING
1049 qDebug("\n---------- IPC ----------");
1050 qDebug("CommandId: %d", command);
1051 for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1053 qDebug("Arguments: %s", iter->toUtf8().constData());
1055 qDebug("The Flags: 0x%08X", flags);
1056 qDebug("---------- IPC ----------\n");
1057 #endif //IPC_LOGGING
1059 switch(command)
1061 case IPC_OPCODE_PING:
1062 qDebug("Received a PING request from another instance!");
1063 x264_blink_window(this, 5, 125);
1064 break;
1065 case IPC_OPCODE_ADD_FILE:
1066 if(!args.isEmpty())
1068 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1070 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1071 if(m_status != STATUS_AWAITING)
1073 m_status = STATUS_AWAITING;
1074 QTimer::singleShot(5000, this, SLOT(handlePendingFiles()));
1077 else
1079 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1082 break;
1083 case IPC_OPCODE_ADD_JOB:
1084 if(args.size() >= 3)
1086 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1088 OptionsModel options(m_sysinfo);
1089 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1090 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1092 if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1094 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1097 if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
1098 if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
1099 appendJob(args[0], args[1], &options, runImmediately);
1101 else
1103 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1106 break;
1107 default:
1108 throw std::exception("Unknown command received!");
1112 void MainWindow::checkUpdates(void)
1114 ENSURE_APP_IS_IDLE();
1115 m_status = STATUS_BLOCKED;
1117 if(countRunningJobs() > 0)
1119 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1120 m_status = STATUS_IDLE;
1121 return;
1124 UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo);
1125 const int ret = updater->exec();
1127 if(updater->getSuccess())
1129 m_recentlyUsed->setLastUpdateCheck(x264_current_date_safe().toJulianDay());
1130 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
1133 if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1135 m_status = STATUS_EXITTING;
1136 qWarning("Exitting program to install update...");
1137 close();
1138 QApplication::quit();
1141 X264_DELETE(updater);
1143 if(m_status != STATUS_EXITTING)
1145 m_status = STATUS_IDLE;
1149 ///////////////////////////////////////////////////////////////////////////////
1150 // Event functions
1151 ///////////////////////////////////////////////////////////////////////////////
1154 * Window shown event
1156 void MainWindow::showEvent(QShowEvent *e)
1158 QMainWindow::showEvent(e);
1160 if(m_status == STATUS_PRE_INIT)
1162 setWindowTitle(tr("%1 - Starting...").arg(windowTitle()));
1163 QTimer::singleShot(0, this, SLOT(init()));
1168 * Window close event
1170 void MainWindow::closeEvent(QCloseEvent *e)
1172 if((m_status != STATUS_IDLE) && (m_status != STATUS_EXITTING))
1174 e->ignore();
1175 qWarning("Cannot close window at this time!");
1176 return;
1179 if(m_status != STATUS_EXITTING)
1181 if(countRunningJobs() > 0)
1183 e->ignore();
1184 m_status = STATUS_BLOCKED;
1185 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
1186 m_status = STATUS_IDLE;
1187 return;
1190 if(countPendingJobs() > 0)
1192 m_status = STATUS_BLOCKED;
1193 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);
1194 if(ret != QMessageBox::Yes)
1196 e->ignore();
1197 m_status = STATUS_IDLE;
1198 return;
1203 while(m_jobList->rowCount(QModelIndex()) > 0)
1205 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1206 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1208 e->ignore();
1209 m_status = STATUS_BLOCKED;
1210 QMessageBox::warning(this, tr("Failed To Exit"), tr("Sorry, at least one job could not be deleted!"));
1211 m_status = STATUS_IDLE;
1212 return;
1216 m_status = STATUS_EXITTING;
1217 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1218 QMainWindow::closeEvent(e);
1222 * Window resize event
1224 void MainWindow::resizeEvent(QResizeEvent *e)
1226 QMainWindow::resizeEvent(e);
1227 updateLabelPos();
1231 * Event filter
1233 bool MainWindow::eventFilter(QObject *o, QEvent *e)
1235 if((o == ui->labelBuildDate) && (e->type() == QEvent::MouseButtonPress))
1237 QTimer::singleShot(0, this, SLOT(showAbout()));
1238 return true;
1240 return false;
1244 * Win32 message filter
1246 bool MainWindow::winEvent(MSG *message, long *result)
1248 return WinSevenTaskbar::handleWinEvent(message, result);
1252 * File dragged over window
1254 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1256 bool accept[2] = {false, false};
1258 foreach(const QString &fmt, event->mimeData()->formats())
1260 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1261 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1264 if(accept[0] && accept[1])
1266 event->acceptProposedAction();
1271 * File dropped onto window
1273 void MainWindow::dropEvent(QDropEvent *event)
1275 if((m_status != STATUS_IDLE) && (m_status != STATUS_AWAITING))
1277 qWarning("Cannot accept drooped files at this time -> discarding!");
1278 return;
1281 QStringList droppedFiles;
1282 QList<QUrl> urls = event->mimeData()->urls();
1284 while(!urls.isEmpty())
1286 QUrl currentUrl = urls.takeFirst();
1287 QFileInfo file(currentUrl.toLocalFile());
1288 if(file.exists() && file.isFile())
1290 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1291 droppedFiles << file.canonicalFilePath();
1295 if(droppedFiles.count() > 0)
1297 m_pendingFiles->append(droppedFiles);
1298 m_pendingFiles->sort();
1299 if(m_status != STATUS_AWAITING)
1301 m_status = STATUS_AWAITING;
1302 QTimer::singleShot(0, this, SLOT(handlePendingFiles()));
1307 ///////////////////////////////////////////////////////////////////////////////
1308 // Private functions
1309 ///////////////////////////////////////////////////////////////////////////////
1312 * Creates a new job
1314 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1316 bool okay = false;
1317 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed, m_sysinfo, m_preferences);
1319 addDialog->setRunImmediately(runImmediately);
1320 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1321 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1322 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1324 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1325 if(multiFile)
1327 addDialog->setSourceEditable(false);
1328 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1329 addDialog->setApplyToAllVisible(applyToAll);
1332 if(addDialog->exec() == QDialog::Accepted)
1334 sourceFileName = addDialog->sourceFile();
1335 outputFileName = addDialog->outputFile();
1336 runImmediately = addDialog->runImmediately();
1337 if(applyToAll)
1339 *applyToAll = addDialog->applyToAll();
1341 okay = true;
1344 X264_DELETE(addDialog);
1345 return okay;
1349 * Creates a new job from *multiple* files
1351 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1353 QStringList::ConstIterator iter;
1354 bool applyToAll = false, runImmediately = false;
1355 int counter = 0;
1357 //Add files individually
1358 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1360 runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1361 QString sourceFileName(*iter), outputFileName;
1362 if(createJob(sourceFileName, outputFileName, m_options, runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1364 if(appendJob(sourceFileName, outputFileName, m_options, runImmediately))
1366 continue;
1369 return false;
1372 //Add remaining files
1373 while(applyToAll && (iter != filePathIn.constEnd()))
1375 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1376 const QString sourceFileName = *iter;
1377 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
1378 if(!appendJob(sourceFileName, outputFileName, m_options, runImmediatelyTmp))
1380 return false;
1382 iter++;
1385 return true;
1389 * Append a new job
1391 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1393 bool okay = false;
1394 EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo, m_preferences);
1395 QModelIndex newIndex = m_jobList->insertJob(thrd);
1397 if(newIndex.isValid())
1399 if(runImmediately)
1401 ui->jobsView->selectRow(newIndex.row());
1402 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1403 m_jobList->startJob(newIndex);
1406 okay = true;
1409 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1410 return okay;
1414 * Jobs that are not completed (or failed, or aborted) yet
1416 unsigned int MainWindow::countPendingJobs(void)
1418 unsigned int count = 0;
1419 const int rows = m_jobList->rowCount(QModelIndex());
1421 for(int i = 0; i < rows; i++)
1423 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1424 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1426 count++;
1430 return count;
1434 * Jobs that are still active, i.e. not terminated or enqueued
1436 unsigned int MainWindow::countRunningJobs(void)
1438 unsigned int count = 0;
1439 const int rows = m_jobList->rowCount(QModelIndex());
1441 for(int i = 0; i < rows; i++)
1443 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1444 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1446 count++;
1450 return count;
1454 * Update all buttons with respect to current job status
1456 void MainWindow::updateButtons(JobStatus status)
1458 qDebug("MainWindow::updateButtons(void)");
1460 ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1461 ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1462 ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1463 ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1465 ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1466 ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1467 ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1469 ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1470 ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1471 ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1472 ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1474 ui->editDetails->setEnabled(status != JobStatus_Paused);
1478 * Update the taskbar with current job status
1480 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1482 qDebug("MainWindow::updateTaskbar(void)");
1484 switch(status)
1486 case JobStatus_Undefined:
1487 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1488 break;
1489 case JobStatus_Aborting:
1490 case JobStatus_Starting:
1491 case JobStatus_Pausing:
1492 case JobStatus_Resuming:
1493 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1494 break;
1495 case JobStatus_Aborted:
1496 case JobStatus_Failed:
1497 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1498 break;
1499 case JobStatus_Paused:
1500 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1501 break;
1502 default:
1503 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1504 break;
1507 switch(status)
1509 case JobStatus_Aborting:
1510 case JobStatus_Starting:
1511 case JobStatus_Pausing:
1512 case JobStatus_Resuming:
1513 break;
1514 default:
1515 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
1516 break;
1519 WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);
1523 * Parse command-line arguments
1525 bool MainWindow::parseCommandLineArgs(void)
1527 bool bCommandAccepted = false;
1528 unsigned int flags = 0;
1530 //Initialize command-line parser
1531 CLIParser parser(x264_arguments());
1532 int identifier;
1533 QStringList options;
1535 //Process all command-line arguments
1536 while(parser.nextOption(identifier, &options))
1538 switch(identifier)
1540 case CLI_PARAM_ADD_FILE:
1541 handleCommand(IPC_OPCODE_ADD_FILE, options, flags);
1542 bCommandAccepted = true;
1543 break;
1544 case CLI_PARAM_ADD_JOB:
1545 handleCommand(IPC_OPCODE_ADD_JOB, options, flags);
1546 bCommandAccepted = true;
1547 break;
1548 case CLI_PARAM_FORCE_START:
1549 flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1550 break;
1551 case CLI_PARAM_NO_FORCE_START:
1552 flags = (flags & (~IPC_FLAG_FORCE_START));
1553 break;
1554 case CLI_PARAM_FORCE_ENQUEUE:
1555 flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1556 break;
1557 case CLI_PARAM_NO_FORCE_ENQUEUE:
1558 flags = (flags & (~IPC_FLAG_FORCE_ENQUEUE));
1559 break;
1563 return bCommandAccepted;