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 "input_filter.h"
39 #include "win_addJob.h"
40 #include "win_about.h"
41 #include "win_preferences.h"
42 #include "win_updater.h"
48 #include <QCloseEvent>
49 #include <QMessageBox>
50 #include <QDesktopServices>
55 #include <QProgressDialog>
57 #include <QTextStream>
59 #include <QFileDialog>
60 #include <QSystemTrayIcon>
65 static const char *home_url = "http://muldersoft.com/";
66 static const char *update_url = "https://github.com/lordmulder/Simple-x264-Launcher/releases/latest";
67 static const char *avs_dl_url = "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/";
68 static const char *vsynth_url = "http://www.vapoursynth.com/";
69 static const char *python_url = "https://www.python.org/downloads/";
70 static const char *tpl_last = "<LAST_USED>";
73 #define SET_FONT_BOLD(WIDGET,BOLD) do { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); } while(0)
74 #define SET_TEXT_COLOR(WIDGET,COLOR) do { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); } while(0)
75 #define LINK(URL) (QString("<a href=\"%1\">%1</a>").arg((URL)))
76 #define INIT_ERROR_EXIT() do { close(); qApp->exit(-1); return; } while(0)
77 #define NEXT(X) ((*reinterpret_cast<int*>(&(X)))++)
78 #define SETUP_WEBLINK(OBJ, URL) do { (OBJ)->setData(QVariant(QUrl(URL))); connect((OBJ), SIGNAL(triggered()), this, SLOT(showWebLink())); } while(0)
79 #define APP_IS_READY (m_initialized && (!m_fileTimer->isActive()) && (QApplication::activeModalWidget() == NULL))
80 #define ENSURE_APP_IS_READY() do { if(!APP_IS_READY) { x264_beep(x264_beep_warning); qWarning("Cannot perfrom this action at this time!"); return; } } while(0)
82 ///////////////////////////////////////////////////////////////////////////////
83 // Constructor & Destructor
84 ///////////////////////////////////////////////////////////////////////////////
89 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures, IPC *ipc)
95 m_pendingFiles(new QStringList()),
99 m_sysTray(new QSystemTrayIcon(this)),
100 ui(new Ui::MainWindow())
102 //Init the dialog, from the .ui file
104 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
106 //Register meta types
107 qRegisterMetaType<QUuid>("QUuid");
108 qRegisterMetaType<QUuid>("DWORD");
109 qRegisterMetaType<JobStatus>("JobStatus");
111 //Create and initialize the sysinfo object
112 m_sysinfo = new SysinfoModel();
113 m_sysinfo->setAppPath(QApplication::applicationDirPath());
114 m_sysinfo->setMMXSupport(cpuFeatures->mmx && cpuFeatures->mmx2);
115 m_sysinfo->setSSESupport(cpuFeatures->sse && cpuFeatures->mmx2); //SSE implies MMX2
116 m_sysinfo->setX64Support(cpuFeatures->x64 && cpuFeatures->sse2); //X64 implies SSE2
119 m_preferences = new PreferencesModel();
120 PreferencesModel::loadPreferences(m_preferences);
123 m_recentlyUsed = new RecentlyUsed();
124 RecentlyUsed::loadRecentlyUsed(m_recentlyUsed);
126 //Create options object
127 m_options = new OptionsModel(m_sysinfo);
128 OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
130 //Freeze minimum size
131 setMinimumSize(size());
132 ui->splitter->setSizes(QList<int>() << 16 << 196);
135 ui->labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
139 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
140 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
142 else if(x264_is_prerelease())
144 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
148 m_jobList = new JobListModel(m_preferences);
149 connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
150 ui->jobsView->setModel(m_jobList);
153 ui->jobsView->horizontalHeader()->setSectionHidden(3, true);
154 ui->jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
155 ui->jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
156 ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
157 ui->jobsView->horizontalHeader()->resizeSection(1, 150);
158 ui->jobsView->horizontalHeader()->resizeSection(2, 90);
159 ui->jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
160 connect(ui->jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
163 m_inputFilter_jobList = new InputEventFilter(ui->jobsView);
164 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Up, 1);
165 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Down, 2);
166 connect(m_inputFilter_jobList, SIGNAL(keyPressed(int)), this, SLOT(jobListKeyPressed(int)));
168 //Setup mouse listener
169 m_inputFilter_version = new InputEventFilter(ui->labelBuildDate);
170 m_inputFilter_version->addMouseFilter(Qt::LeftButton, 0);
171 m_inputFilter_version->addMouseFilter(Qt::RightButton, 0);
172 connect(m_inputFilter_version, SIGNAL(mouseClicked(int)), this, SLOT(versionLabelMouseClicked(int)));
174 //Create context menu
175 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), ui->logView);
176 actionClipboard->setEnabled(false);
177 ui->logView->addAction(actionClipboard);
178 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
179 ui->jobsView->addActions(ui->menuJob->actions());
182 connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed() ));
183 connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed() ));
184 connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed() ));
185 connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
186 connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed() ));
187 connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed() ));
188 connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed() ));
189 connect(ui->actionJob_MoveUp, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
190 connect(ui->actionJob_MoveDown, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
193 connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
194 connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
195 connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
196 connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
199 SETUP_WEBLINK(ui->actionWebMulder, home_url);
200 SETUP_WEBLINK(ui->actionWebX264, "http://www.videolan.org/developers/x264.html");
201 SETUP_WEBLINK(ui->actionWebX265, "http://www.videolan.org/developers/x265.html");
202 SETUP_WEBLINK(ui->actionWebKomisar, "http://komisar.gin.by/");
203 SETUP_WEBLINK(ui->actionWebVideoLAN, "http://download.videolan.org/pub/x264/binaries/");
204 SETUP_WEBLINK(ui->actionWebJEEB, "http://x264.fushizen.eu/");
205 SETUP_WEBLINK(ui->actionWebFreeCodecs, "http://www.free-codecs.com/x264_video_codec_download.htm");
206 SETUP_WEBLINK(ui->actionWebX265BinRU, "http://goo.gl/xRS6AW");
207 SETUP_WEBLINK(ui->actionWebX265BinEU, "http://builds.x265.eu/");
208 SETUP_WEBLINK(ui->actionWebX265BinORG, "http://chromashift.org/x265_builds/");
209 SETUP_WEBLINK(ui->actionWebX265BinFF, "http://ffmpeg.zeranoe.com/builds/");
210 SETUP_WEBLINK(ui->actionWebAvisynth32, "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/");
211 SETUP_WEBLINK(ui->actionWebAvisynth64, "http://code.google.com/p/avisynth64/downloads/list");
212 SETUP_WEBLINK(ui->actionWebAvisynthPlus, "http://www.avs-plus.net/");
213 SETUP_WEBLINK(ui->actionWebVapourSynth, "http://www.vapoursynth.com/");
214 SETUP_WEBLINK(ui->actionWebVapourSynthDocs, "http://www.vapoursynth.com/doc/");
215 SETUP_WEBLINK(ui->actionOnlineDocX264, "http://mewiki.project357.com/wiki/X264_Settings");
216 SETUP_WEBLINK(ui->actionOnlineDocX265, "http://x265.readthedocs.org/en/default/");
217 SETUP_WEBLINK(ui->actionWebBluRay, "http://www.x264bluray.com/");
218 SETUP_WEBLINK(ui->actionWebAvsWiki, "http://avisynth.nl/index.php/Main_Page#Usage");
219 SETUP_WEBLINK(ui->actionWebSupport, "http://forum.doom9.org/showthread.php?t=144140");
220 SETUP_WEBLINK(ui->actionWebSecret, "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
222 //Create floating label
223 m_label = new QLabel(ui->jobsView->viewport());
224 m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
225 m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
226 SET_TEXT_COLOR(m_label, Qt::darkGray);
227 SET_FONT_BOLD(m_label, true);
228 m_label->setVisible(true);
229 m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
230 m_label->addActions(ui->jobsView->actions());
231 connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
234 //Init system tray icon
235 m_sysTray->setToolTip(this->windowTitle());
236 m_sysTray->setIcon(this->windowIcon());
237 connect(m_sysTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(sysTrayActived()));
239 //Create corner widget
240 QLabel *checkUp = new QLabel(ui->menubar);
241 checkUp->setText(QString("<nobr><img src=\":/buttons/exclamation_small.png\"> <b style=\"color:darkred\">%1</b> </nobr>").arg(tr("Check for Updates")));
242 checkUp->setFixedHeight(ui->menubar->height());
243 checkUp->setCursor(QCursor(Qt::PointingHandCursor));
244 m_inputFilter_checkUp = new InputEventFilter(checkUp);
245 m_inputFilter_checkUp->addMouseFilter(Qt::LeftButton, 0);
246 m_inputFilter_checkUp->addMouseFilter(Qt::RightButton, 0);
247 connect(m_inputFilter_checkUp, SIGNAL(mouseClicked(int)), this, SLOT(checkUpdates()));
249 ui->menubar->setCornerWidget(checkUp);
252 m_fileTimer = new QTimer(this);
253 connect(m_fileTimer, SIGNAL(timeout()), this, SLOT(handlePendingFiles()));
259 MainWindow::~MainWindow(void)
261 OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
263 X264_DELETE(m_jobList);
264 X264_DELETE(m_options);
265 X264_DELETE(m_pendingFiles);
266 X264_DELETE(m_label);
267 X264_DELETE(m_inputFilter_jobList);
268 X264_DELETE(m_inputFilter_version);
269 X264_DELETE(m_inputFilter_checkUp);
271 while(!m_toolsList.isEmpty())
273 QFile *temp = m_toolsList.takeFirst();
277 if(m_ipc->isListening())
279 m_ipc->stopListening();
282 X264_DELETE(m_preferences);
283 X264_DELETE(m_recentlyUsed);
284 X264_DELETE(m_sysinfo);
285 X264_DELETE(m_fileTimer);
287 VapourSynthCheckThread::unload();
288 AvisynthCheckThread::unload();
294 ///////////////////////////////////////////////////////////////////////////////
296 ///////////////////////////////////////////////////////////////////////////////
299 * The "add" button was clicked
301 void MainWindow::addButtonPressed()
303 ENSURE_APP_IS_READY();
305 qDebug("MainWindow::addButtonPressed");
306 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
307 QString sourceFileName, outputFileName;
309 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
311 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
316 * The "open" action was triggered
318 void MainWindow::openActionTriggered()
320 ENSURE_APP_IS_READY();
322 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
323 if(!fileList.empty())
325 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
326 if(fileList.count() > 1)
328 createJobMultiple(fileList);
332 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
333 QString sourceFileName(fileList.first()), outputFileName;
334 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
336 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
343 * The "start" button was clicked
345 void MainWindow::startButtonPressed(void)
347 ENSURE_APP_IS_READY();
348 m_jobList->startJob(ui->jobsView->currentIndex());
352 * The "abort" button was clicked
354 void MainWindow::abortButtonPressed(void)
356 ENSURE_APP_IS_READY();
358 if(QMessageBox::question(this, tr("Abort Job?"), tr("<nobr>Do you really want to <b>abort</b> the selected job now?</nobr>"), tr("Back"), tr("Abort Job")) == 1)
360 m_jobList->abortJob(ui->jobsView->currentIndex());
365 * The "delete" button was clicked
367 void MainWindow::deleteButtonPressed(void)
369 ENSURE_APP_IS_READY();
371 m_jobList->deleteJob(ui->jobsView->currentIndex());
372 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
376 * The "browse" button was clicked
378 void MainWindow::browseButtonPressed(void)
380 ENSURE_APP_IS_READY();
382 QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
383 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
385 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
389 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
394 * The "browse" button was clicked
396 void MainWindow::moveButtonPressed(void)
398 ENSURE_APP_IS_READY();
400 if(sender() == ui->actionJob_MoveUp)
402 qDebug("Move job %d (direction: UP)", ui->jobsView->currentIndex().row());
403 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_UP))
405 x264_beep(x264_beep_error);
407 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
409 else if(sender() == ui->actionJob_MoveDown)
411 qDebug("Move job %d (direction: DOWN)", ui->jobsView->currentIndex().row());
412 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_DOWN))
414 x264_beep(x264_beep_error);
416 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
420 qWarning("[moveButtonPressed] Error: Unknown sender!");
425 * The "pause" button was clicked
427 void MainWindow::pauseButtonPressed(bool checked)
431 x264_beep(x264_beep_warning);
432 qWarning("Cannot perfrom this action at this time!");
433 ui->buttonPauseJob->setChecked(!checked);
438 m_jobList->pauseJob(ui->jobsView->currentIndex());
442 m_jobList->resumeJob(ui->jobsView->currentIndex());
447 * The "restart" button was clicked
449 void MainWindow::restartButtonPressed(void)
451 ENSURE_APP_IS_READY();
453 const QModelIndex index = ui->jobsView->currentIndex();
454 const OptionsModel *options = m_jobList->getJobOptions(index);
455 QString sourceFileName = m_jobList->getJobSourceFile(index);
456 QString outputFileName = m_jobList->getJobOutputFile(index);
458 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
460 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
461 OptionsModel *tempOptions = new OptionsModel(*options);
462 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
464 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
466 X264_DELETE(tempOptions);
471 * Job item selected by user
473 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
475 qDebug("Job selected: %d", current.row());
477 if(ui->logView->model())
479 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
482 if(current.isValid())
484 ui->logView->setModel(m_jobList->getLogFile(current));
485 connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
486 ui->logView->actions().first()->setEnabled(true);
487 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
489 ui->progressBar->setValue(m_jobList->getJobProgress(current));
490 ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
491 updateButtons(m_jobList->getJobStatus(current));
492 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
496 ui->logView->setModel(NULL);
497 ui->logView->actions().first()->setEnabled(false);
498 ui->progressBar->setValue(0);
499 ui->editDetails->clear();
500 updateButtons(JobStatus_Undefined);
501 updateTaskbar(JobStatus_Undefined, QIcon());
504 ui->progressBar->repaint();
508 * Handle update of job info (status, progress, details, etc)
510 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
512 int selected = ui->jobsView->currentIndex().row();
514 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
516 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
518 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
521 qDebug("Current job changed status!");
522 updateButtons(status);
523 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
525 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
527 if(m_preferences->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
528 if(m_preferences->getSaveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
532 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
534 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
538 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
539 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
544 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
546 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
550 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
558 * Handle new log file content
560 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
562 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
568 void MainWindow::showAbout(void)
570 ENSURE_APP_IS_READY();
572 if(AboutDialog *aboutDialog = new AboutDialog(this))
575 X264_DELETE(aboutDialog);
582 void MainWindow::showWebLink(void)
584 ENSURE_APP_IS_READY();
586 if(QObject *obj = QObject::sender())
588 if(QAction *action = dynamic_cast<QAction*>(obj))
590 if(action->data().type() == QVariant::Url)
592 QDesktopServices::openUrl(action->data().toUrl());
599 * Pereferences dialog
601 void MainWindow::showPreferences(void)
603 ENSURE_APP_IS_READY();
605 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences, m_sysinfo);
608 X264_DELETE(preferences);
612 * Launch next job, after running job has finished
614 void MainWindow::launchNextJob(void)
616 qDebug("Launching next job...");
618 if(countRunningJobs() >= m_preferences->getMaxRunningJobCount())
620 qDebug("Still have too many jobs running, won't launch next one yet!");
624 const int rows = m_jobList->rowCount(QModelIndex());
626 for(int i = 0; i < rows; i++)
628 const QModelIndex currentIndex = m_jobList->index(i, 0, QModelIndex());
629 if(m_jobList->getJobStatus(currentIndex) == JobStatus_Enqueued)
631 if(m_jobList->startJob(currentIndex))
633 ui->jobsView->selectRow(currentIndex.row());
639 qWarning("No enqueued jobs left to be started!");
641 if(m_preferences->getShutdownComputer())
643 QTimer::singleShot(0, this, SLOT(shutdownComputer()));
648 * Save log to text file
650 void MainWindow::saveLogFile(const QModelIndex &index)
654 if(LogFileModel *log = m_jobList->getLogFile(index))
656 QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
657 QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
658 QFile outFile(logFilePath);
659 if(outFile.open(QIODevice::WriteOnly))
661 QTextStream outStream(&outFile);
662 outStream.setCodec("UTF-8");
663 outStream.setGenerateByteOrderMark(true);
665 const int rows = log->rowCount(QModelIndex());
666 for(int i = 0; i < rows; i++)
668 outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
674 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
681 * Shut down the computer (with countdown)
683 void MainWindow::shutdownComputer(void)
685 ENSURE_APP_IS_READY();
687 if(countPendingJobs() > 0)
689 qDebug("Still have pending jobs, won't shutdown yet!");
693 const int iTimeout = 30;
694 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
695 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
697 qWarning("Initiating shutdown sequence!");
699 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
700 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
701 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
702 progressDialog.setModal(true);
703 progressDialog.setAutoClose(false);
704 progressDialog.setAutoReset(false);
705 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
706 progressDialog.setWindowTitle(windowTitle());
707 progressDialog.setCancelButton(cancelButton);
708 progressDialog.show();
710 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
711 QApplication::setOverrideCursor(Qt::WaitCursor);
712 x264_play_sound(IDR_WAVE1, false);
713 QApplication::restoreOverrideCursor();
716 timer.setInterval(1000);
719 QEventLoop eventLoop(this);
720 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
721 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
723 for(int i = 1; i <= iTimeout; i++)
726 if(progressDialog.wasCanceled())
728 progressDialog.close();
731 progressDialog.setValue(i+1);
732 progressDialog.setLabelText(text.arg(iTimeout-i));
733 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
734 QApplication::processEvents();
735 x264_play_sound(((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), false);
738 qWarning("Shutting down !!!");
740 if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
742 qApp->closeAllWindows();
748 * Main initialization function (called only once!)
750 void MainWindow::init(void)
754 qWarning("Already initialized -> skipping!");
760 const QStringList arguments = x264_arguments();
762 //---------------------------------------
763 // Create the IPC listener thread
764 //---------------------------------------
766 if(m_ipc->isInitialized())
768 connect(m_ipc, SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
769 m_ipc->startListening();
772 //---------------------------------------
773 // Check required binaries
774 //---------------------------------------
776 QStringList binFiles;
777 for(OptionsModel::EncArch arch = OptionsModel::EncArch_x32; arch <= OptionsModel::EncArch_x64; NEXT(arch))
779 for(OptionsModel::EncType encdr = OptionsModel::EncType_X264; encdr <= OptionsModel::EncType_X265; NEXT(encdr))
781 for(OptionsModel::EncVariant varnt = OptionsModel::EncVariant_LoBit; varnt <= OptionsModel::EncVariant_HiBit; NEXT(varnt))
783 binFiles << ENC_BINARY(m_sysinfo, encdr, arch, varnt);
786 binFiles << AVS_BINARY(m_sysinfo, arch == OptionsModel::EncArch_x64);
788 for(size_t i = 0; UpdaterDialog::BINARIES[i].name; i++)
790 if(UpdaterDialog::BINARIES[i].exec)
792 binFiles << QString("%1/toolset/common/%2").arg(m_sysinfo->getAppPath(), QString::fromLatin1(UpdaterDialog::BINARIES[i].name));
796 qDebug("[Validating binaries]");
797 for(QStringList::ConstIterator iter = binFiles.constBegin(); iter != binFiles.constEnd(); iter++)
799 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
800 QFile *file = new QFile(*iter);
801 qDebug("%s", file->fileName().toLatin1().constData());
802 if(file->open(QIODevice::ReadOnly))
804 if(!x264_is_executable(file->fileName()))
806 QMessageBox::critical(this, tr("Invalid File!"), tr("<nobr>At least on required tool is not a valid Win32 or Win64 binary:<br><tt style=\"whitespace:nowrap\">%1</tt><br><br>Please re-install the program in order to fix the problem!</nobr>").arg(QDir::toNativeSeparators(file->fileName())).replace("-", "−"));
807 qFatal(QString("Binary is invalid: %1").arg(file->fileName()).toLatin1().constData());
815 QMessageBox::critical(this, tr("File Not Found!"), tr("<nobr>At least on required tool could not be found:<br><tt style=\"whitespace:nowrap\">%1</tt><br><br>Please re-install the program in order to fix the problem!</nobr>").arg(QDir::toNativeSeparators(file->fileName())).replace("-", "−"));
816 qFatal(QString("Binary not found: %1/toolset/%2").arg(m_sysinfo->getAppPath(), file->fileName()).toLatin1().constData());
823 //---------------------------------------
824 // Check for portable mode
825 //---------------------------------------
830 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
831 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
832 if(writeTest.open(QIODevice::WriteOnly))
834 ok = (writeTest.write(data) == strlen(data));
839 int val = QMessageBox::warning(this, tr("Write Test Failed"), tr("<nobr>The application was launched in portable mode, but the program path is <b>not</b> writable!</nobr>"), tr("Quit"), tr("Ignore"));
840 if(val != 1) INIT_ERROR_EXIT();
845 if(x264_is_prerelease())
847 qsrand(time(NULL)); int rnd = qrand() % 3;
848 int val = QMessageBox::information(this, tr("Pre-Release Version"), tr("Note: This is a pre-release version. Please do NOT use for production!<br>Click the button #%1 in order to continue...<br><br>(There will be no such message box in the final version of this application)").arg(QString::number(rnd + 1)), tr("(1)"), tr("(2)"), tr("(3)"), qrand() % 3);
849 if(rnd != val) INIT_ERROR_EXIT();
852 //---------------------------------------
853 // Check CPU capabilities
854 //---------------------------------------
856 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
857 if(!m_sysinfo->hasMMXSupport())
859 QMessageBox::critical(this, tr("Unsupported CPU"), tr("<nobr>Sorry, but this machine is <b>not</b> physically capable of running x264 (with assembly).<br>Please get a CPU that supports at least the MMX and MMXEXT instruction sets!</nobr>"), tr("Quit"));
860 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
863 else if(!m_sysinfo->hasSSESupport())
865 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
866 int val = QMessageBox::warning(this, tr("Unsupported CPU"), tr("<nobr>It appears that this machine does <b>not</b> support the SSE1 instruction set.<br>Thus most builds of x264 will <b>not</b> run on this computer at all.<br><br>Please get a CPU that supports the MMX and SSE1 instruction sets!</nobr>"), tr("Quit"), tr("Ignore"));
867 if(val != 1) INIT_ERROR_EXIT();
870 //Skip version check (not recommended!)
871 if(CLIParser::checkFlag(CLI_PARAM_SKIP_X264_CHECK, arguments))
873 qWarning("x264 version check disabled, you have been warned!\n");
874 m_preferences->setSkipVersionTest(true);
877 //Don't abort encoding process on timeout (not recommended!)
878 if(CLIParser::checkFlag(CLI_PARAM_NO_DEADLOCK, arguments))
880 qWarning("Deadlock detection disabled, you have been warned!\n");
881 m_preferences->setAbortOnTimeout(false);
884 //---------------------------------------
885 // Check Avisynth support
886 //---------------------------------------
888 if(!CLIParser::checkFlag(CLI_PARAM_SKIP_AVS_CHECK, arguments))
890 qDebug("[Check for Avisynth support]");
891 volatile double avisynthVersion = 0.0;
892 const int result = AvisynthCheckThread::detect(&avisynthVersion);
895 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
896 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
897 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
898 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
899 if(val != 1) INIT_ERROR_EXIT();
901 if(result && (avisynthVersion >= 2.5))
903 qDebug("Avisynth support is officially enabled now!");
904 m_sysinfo->setAVSSupport(true);
908 if(!m_preferences->getDisableWarnings())
910 QString text = tr("It appears that Avisynth is <b>not</b> currently installed on your computer.<br>Therefore Avisynth (.avs) input will <b>not</b> be working at all!").append("<br><br>");
911 text += tr("Please download and install Avisynth:").append("<br>").append(LINK(avs_dl_url));
912 int val = QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Close"), tr("Disable this Warning"));
915 m_preferences->setDisableWarnings(true);
916 PreferencesModel::savePreferences(m_preferences);
924 //---------------------------------------
925 // Check VapurSynth support
926 //---------------------------------------
928 if(!CLIParser::checkFlag(CLI_PARAM_SKIP_VPS_CHECK, arguments))
930 qDebug("[Check for VapourSynth support]");
931 QString vapoursynthPath;
932 const int result = VapourSynthCheckThread::detect(vapoursynthPath);
935 QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
936 text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
937 text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
938 const int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
939 if(val != 1) INIT_ERROR_EXIT();
941 if(result && (!vapoursynthPath.isEmpty()))
943 qDebug("VapourSynth support is officially enabled now!");
944 m_sysinfo->setVPSSupport(true);
945 m_sysinfo->setVPSPath(vapoursynthPath);
949 if(!m_preferences->getDisableWarnings())
951 QString text = tr("It appears that VapourSynth is <b>not</b> currently installed on your computer.<br>Therefore VapourSynth (.vpy) input will <b>not</b> be working at all!").append("<br><br>");
952 text += tr("Please download and install VapourSynth for Windows (R24 or later):").append("<br>").append(LINK(vsynth_url)).append("<br><br>");
953 text += tr("Note that Python v3.4 is a prerequisite for installing VapourSynth:").append("<br>").append(LINK(python_url)).append("<br>");
954 const int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Close"), tr("Disable this Warning"));
957 m_preferences->setDisableWarnings(true);
958 PreferencesModel::savePreferences(m_preferences);
965 //---------------------------------------
966 // Finish initialization
967 //---------------------------------------
970 setWindowTitle(QString("%1 (%2)").arg(windowTitle(), m_sysinfo->hasX64Support() ? "64-Bit" : "32-Bit"));
972 //Enable drag&drop support for this window, required for Qt v4.8.4+
973 setAcceptDrops(true);
976 m_initialized = true;
978 //---------------------------------------
979 // Check for Expiration
980 //---------------------------------------
982 if(x264_version_date().addMonths(6) < x264_current_date_safe())
984 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
986 text += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(tr("Your version of Simple x264 Launcher is more than 6 months old!").replace('-', "−"));
987 text += QString("<nobr><tt>%1<br><a href=\"%2\">%3</a><br><br>").arg(tr("You can download the most recent version from the official web-site now:").replace('-', "−"), QString::fromLatin1(update_url), QString::fromLatin1(update_url).replace("-", "−"));
988 text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace('-', "−"));
989 QMessageBox msgBox(this);
990 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
991 msgBox.setWindowTitle(tr("Update Notification"));
992 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
993 msgBox.setText(text);
994 QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
995 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
996 QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
997 btn2->setEnabled(false);
998 btn3->setVisible(false);
999 QTimer::singleShot(7500, btn2, SLOT(hide()));
1000 QTimer::singleShot(7500, btn3, SLOT(show()));
1001 if(msgBox.exec() == 0)
1003 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1007 else if(!parseCommandLineArgs())
1010 if(CLIParser::checkFlag(CLI_PARAM_FIRST_RUN, arguments))
1012 qWarning("First run -> resetting update check now!");
1013 m_recentlyUsed->setLastUpdateCheck(0);
1014 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
1016 else if(m_recentlyUsed->lastUpdateCheck() + 14 < x264_current_date_safe().toJulianDay())
1018 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
1019 if(!m_preferences->getNoUpdateReminder())
1021 if(QMessageBox::warning(this, tr("Update Notification"), QString("<nobr>%1</nobr>").arg(tr("Your last update check was more than 14 days ago. Check for updates now?")), tr("Check for Updates"), tr("Discard")) == 0)
1023 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1031 if(m_jobList->loadQueuedJobs(m_sysinfo) > 0)
1033 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1034 m_jobList->clearQueuedJobs();
1039 * Update the label position
1041 void MainWindow::updateLabelPos(void)
1043 const QWidget *const viewPort = ui->jobsView->viewport();
1044 m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
1048 * Copy the complete log to the clipboard
1050 void MainWindow::copyLogToClipboard(bool checked)
1052 qDebug("Coyping logfile to clipboard...");
1054 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1056 log->copyToClipboard();
1057 x264_beep(x264_beep_info);
1062 * Process the dropped files
1064 void MainWindow::handlePendingFiles(void)
1066 qDebug("MainWindow::handlePendingFiles");
1068 if(!m_pendingFiles->isEmpty())
1070 QStringList pendingFiles(*m_pendingFiles);
1071 m_pendingFiles->clear();
1072 createJobMultiple(pendingFiles);
1075 qDebug("Leave from MainWindow::handlePendingFiles!");
1079 * Handle incoming IPC command
1081 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1083 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1085 qWarning("Cannot accapt commands at this time -> discarding!");
1089 if((!isVisible()) || m_sysTray->isVisible())
1094 x264_bring_to_front(this);
1097 qDebug("\n---------- IPC ----------");
1098 qDebug("CommandId: %d", command);
1099 for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1101 qDebug("Arguments: %s", iter->toUtf8().constData());
1103 qDebug("The Flags: 0x%08X", flags);
1104 qDebug("---------- IPC ----------\n");
1105 #endif //IPC_LOGGING
1109 case IPC_OPCODE_PING:
1110 qDebug("Received a PING request from another instance!");
1111 x264_blink_window(this, 5, 125);
1113 case IPC_OPCODE_ADD_FILE:
1116 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1118 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1119 if(!m_fileTimer->isActive())
1121 m_fileTimer->setSingleShot(true);
1122 m_fileTimer->start(5000);
1127 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1131 case IPC_OPCODE_ADD_JOB:
1132 if(args.size() >= 3)
1134 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1136 OptionsModel options(m_sysinfo);
1137 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1138 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1140 if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1142 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1145 if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
1146 if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
1147 appendJob(args[0], args[1], &options, runImmediately);
1151 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1156 THROW("Unknown command received!");
1161 * Check for new updates
1163 void MainWindow::checkUpdates(void)
1165 ENSURE_APP_IS_READY();
1167 if(countRunningJobs() > 0)
1169 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1173 UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo, update_url);
1174 const int ret = updater->exec();
1176 if(updater->getSuccess())
1178 m_recentlyUsed->setLastUpdateCheck(x264_current_date_safe().toJulianDay());
1179 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
1180 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->hide();
1183 if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1185 qWarning("Exitting program to install update...");
1187 QApplication::quit();
1190 X264_DELETE(updater);
1194 * Handle mouse event for version label
1196 void MainWindow::versionLabelMouseClicked(const int &tag)
1200 QTimer::singleShot(0, this, SLOT(showAbout()));
1205 * Handle key event for job list
1207 void MainWindow::jobListKeyPressed(const int &tag)
1212 ui->actionJob_MoveUp->trigger();
1215 ui->actionJob_MoveDown->trigger();
1221 * System tray was activated
1223 void MainWindow::sysTrayActived(void)
1227 x264_bring_to_front(this);
1230 ///////////////////////////////////////////////////////////////////////////////
1232 ///////////////////////////////////////////////////////////////////////////////
1235 * Window shown event
1237 void MainWindow::showEvent(QShowEvent *e)
1239 QMainWindow::showEvent(e);
1243 QTimer::singleShot(0, this, SLOT(init()));
1248 * Window close event
1250 void MainWindow::closeEvent(QCloseEvent *e)
1255 qWarning("Cannot close window at this time!");
1259 //Make sure we have no running jobs left!
1260 if(countRunningJobs() > 0)
1263 if(!m_preferences->getNoSystrayWarning())
1265 if(QMessageBox::warning(this, tr("Jobs Are Running"), tr("<nobr>You still have running jobs, application will be minimized to notification area!<nobr>"), tr("OK"), tr("Don't Show Again")) == 1)
1267 m_preferences->setNoSystrayWarning(true);
1268 PreferencesModel::savePreferences(m_preferences);
1276 //Save pending jobs for next time, if desired by user
1277 if(countPendingJobs() > 0)
1279 int ret = QMessageBox::question(this, tr("Jobs Are Pending"), tr("You still have pending jobs. How do you want to proceed?"), tr("Save Pending Jobs"), tr("Discard"));
1282 m_jobList->saveQueuedJobs();
1286 if(QMessageBox::warning(this, tr("Jobs Are Pending"), tr("Do you really want to discard all pending jobs?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
1294 //Delete remaining jobs
1295 while(m_jobList->rowCount(QModelIndex()) > 0)
1297 if((m_jobList->rowCount(QModelIndex()) % 10) == 0)
1299 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1301 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1304 QMessageBox::warning(this, tr("Failed To Exit"), tr("Warning: At least one job could not be deleted!"));
1308 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1309 QMainWindow::closeEvent(e);
1313 * Window resize event
1315 void MainWindow::resizeEvent(QResizeEvent *e)
1317 QMainWindow::resizeEvent(e);
1322 * Win32 message filter
1324 bool MainWindow::winEvent(MSG *message, long *result)
1326 return WinSevenTaskbar::handleWinEvent(message, result);
1330 * File dragged over window
1332 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1334 bool accept[2] = {false, false};
1336 foreach(const QString &fmt, event->mimeData()->formats())
1338 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1339 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1342 if(accept[0] && accept[1])
1344 event->acceptProposedAction();
1349 * File dropped onto window
1351 void MainWindow::dropEvent(QDropEvent *event)
1353 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1355 qWarning("Cannot accept dropped files at this time -> discarding!");
1359 QStringList droppedFiles;
1360 QList<QUrl> urls = event->mimeData()->urls();
1362 while(!urls.isEmpty())
1364 QUrl currentUrl = urls.takeFirst();
1365 QFileInfo file(currentUrl.toLocalFile());
1366 if(file.exists() && file.isFile())
1368 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1369 droppedFiles << file.canonicalFilePath();
1373 if(droppedFiles.count() > 0)
1375 m_pendingFiles->append(droppedFiles);
1376 m_pendingFiles->sort();
1377 if(!m_fileTimer->isActive())
1379 m_fileTimer->setSingleShot(true);
1380 m_fileTimer->start(5000);
1385 ///////////////////////////////////////////////////////////////////////////////
1386 // Private functions
1387 ///////////////////////////////////////////////////////////////////////////////
1392 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1395 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed, m_sysinfo, m_preferences);
1397 addDialog->setRunImmediately(runImmediately);
1398 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1399 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1400 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1402 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1405 addDialog->setSourceEditable(false);
1406 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1407 addDialog->setApplyToAllVisible(applyToAll);
1410 if(addDialog->exec() == QDialog::Accepted)
1412 sourceFileName = addDialog->sourceFile();
1413 outputFileName = addDialog->outputFile();
1414 runImmediately = addDialog->runImmediately();
1417 *applyToAll = addDialog->applyToAll();
1422 X264_DELETE(addDialog);
1427 * Creates a new job from *multiple* files
1429 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1431 QStringList::ConstIterator iter;
1432 bool applyToAll = false, runImmediately = false;
1435 //Add files individually
1436 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1438 runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1439 QString sourceFileName(*iter), outputFileName;
1440 if(createJob(sourceFileName, outputFileName, m_options, runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1442 if(appendJob(sourceFileName, outputFileName, m_options, runImmediately))
1450 //Add remaining files
1451 while(applyToAll && (iter != filePathIn.constEnd()))
1453 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1454 const QString sourceFileName = *iter;
1455 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
1456 if(!appendJob(sourceFileName, outputFileName, m_options, runImmediatelyTmp))
1469 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1472 EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo, m_preferences);
1473 QModelIndex newIndex = m_jobList->insertJob(thrd);
1475 if(newIndex.isValid())
1479 ui->jobsView->selectRow(newIndex.row());
1480 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1481 m_jobList->startJob(newIndex);
1487 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1492 * Jobs that are not completed (or failed, or aborted) yet
1494 unsigned int MainWindow::countPendingJobs(void)
1496 unsigned int count = 0;
1497 const int rows = m_jobList->rowCount(QModelIndex());
1499 for(int i = 0; i < rows; i++)
1501 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1502 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1512 * Jobs that are still active, i.e. not terminated or enqueued
1514 unsigned int MainWindow::countRunningJobs(void)
1516 unsigned int count = 0;
1517 const int rows = m_jobList->rowCount(QModelIndex());
1519 for(int i = 0; i < rows; i++)
1521 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1522 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1532 * Update all buttons with respect to current job status
1534 void MainWindow::updateButtons(JobStatus status)
1536 qDebug("MainWindow::updateButtons(void)");
1538 ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1539 ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1540 ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1541 ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1543 ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1544 ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1545 ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1546 ui->actionJob_MoveUp->setEnabled(status != JobStatus_Undefined);
1547 ui->actionJob_MoveDown->setEnabled(status != JobStatus_Undefined);
1549 ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1550 ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1551 ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1552 ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1554 ui->editDetails->setEnabled(status != JobStatus_Paused);
1558 * Update the taskbar with current job status
1560 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1562 qDebug("MainWindow::updateTaskbar(void)");
1566 case JobStatus_Undefined:
1567 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1569 case JobStatus_Aborting:
1570 case JobStatus_Starting:
1571 case JobStatus_Pausing:
1572 case JobStatus_Resuming:
1573 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1575 case JobStatus_Aborted:
1576 case JobStatus_Failed:
1577 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1579 case JobStatus_Paused:
1580 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1583 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1589 case JobStatus_Aborting:
1590 case JobStatus_Starting:
1591 case JobStatus_Pausing:
1592 case JobStatus_Resuming:
1595 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
1599 WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);
1603 * Parse command-line arguments
1605 bool MainWindow::parseCommandLineArgs(void)
1607 bool bCommandAccepted = false;
1608 unsigned int flags = 0;
1610 //Initialize command-line parser
1611 CLIParser parser(x264_arguments());
1613 QStringList options;
1615 //Process all command-line arguments
1616 while(parser.nextOption(identifier, &options))
1620 case CLI_PARAM_ADD_FILE:
1621 handleCommand(IPC_OPCODE_ADD_FILE, options, flags);
1622 bCommandAccepted = true;
1624 case CLI_PARAM_ADD_JOB:
1625 handleCommand(IPC_OPCODE_ADD_JOB, options, flags);
1626 bCommandAccepted = true;
1628 case CLI_PARAM_FORCE_START:
1629 flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1631 case CLI_PARAM_NO_FORCE_START:
1632 flags = (flags & (~IPC_FLAG_FORCE_START));
1634 case CLI_PARAM_FORCE_ENQUEUE:
1635 flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1637 case CLI_PARAM_NO_FORCE_ENQUEUE:
1638 flags = (flags & (~IPC_FLAG_FORCE_ENQUEUE));
1643 return bCommandAccepted;