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 *tpl_last = "<LAST_USED>";
66 static const char *home_url = "http://muldersoft.com/";
67 static const char *update_url = "https://github.com/lordmulder/Simple-x264-Launcher/releases/latest";
68 static const char *avs_dl_url = "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/";
69 static const char *python_url = "https://www.python.org/downloads/";
70 static const char *vsynth_url = "http://www.vapoursynth.com/";
71 static const int vsynth_rev = 24;
74 #define SET_FONT_BOLD(WIDGET,BOLD) do { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); } while(0)
75 #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)
76 #define LINK(URL) (QString("<a href=\"%1\">%1</a>").arg((URL)))
77 #define INIT_ERROR_EXIT() do { close(); qApp->exit(-1); return; } while(0)
78 #define NEXT(X) ((*reinterpret_cast<int*>(&(X)))++)
79 #define SETUP_WEBLINK(OBJ, URL) do { (OBJ)->setData(QVariant(QUrl(URL))); connect((OBJ), SIGNAL(triggered()), this, SLOT(showWebLink())); } while(0)
80 #define APP_IS_READY (m_initialized && (!m_fileTimer->isActive()) && (QApplication::activeModalWidget() == NULL))
81 #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)
83 ///////////////////////////////////////////////////////////////////////////////
84 // Constructor & Destructor
85 ///////////////////////////////////////////////////////////////////////////////
90 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures, IPC *ipc)
96 m_pendingFiles(new QStringList()),
100 m_sysTray(new QSystemTrayIcon(this)),
101 ui(new Ui::MainWindow())
103 //Init the dialog, from the .ui file
105 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
107 //Register meta types
108 qRegisterMetaType<QUuid>("QUuid");
109 qRegisterMetaType<QUuid>("DWORD");
110 qRegisterMetaType<JobStatus>("JobStatus");
112 //Create and initialize the sysinfo object
113 m_sysinfo = new SysinfoModel();
114 m_sysinfo->setAppPath(QApplication::applicationDirPath());
115 m_sysinfo->setMMXSupport(cpuFeatures->mmx && cpuFeatures->mmx2);
116 m_sysinfo->setSSESupport(cpuFeatures->sse && cpuFeatures->mmx2); //SSE implies MMX2
117 m_sysinfo->setX64Support(cpuFeatures->x64 && cpuFeatures->sse2); //X64 implies SSE2
120 m_preferences = new PreferencesModel();
121 PreferencesModel::loadPreferences(m_preferences);
124 m_recentlyUsed = new RecentlyUsed();
125 RecentlyUsed::loadRecentlyUsed(m_recentlyUsed);
127 //Create options object
128 m_options = new OptionsModel(m_sysinfo);
129 OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
131 //Freeze minimum size
132 setMinimumSize(size());
133 ui->splitter->setSizes(QList<int>() << 16 << 196);
136 ui->labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
140 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
141 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
143 else if(x264_is_prerelease())
145 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
149 m_jobList = new JobListModel(m_preferences);
150 connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
151 ui->jobsView->setModel(m_jobList);
154 ui->jobsView->horizontalHeader()->setSectionHidden(3, true);
155 ui->jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
156 ui->jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
157 ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
158 ui->jobsView->horizontalHeader()->resizeSection(1, 150);
159 ui->jobsView->horizontalHeader()->resizeSection(2, 90);
160 ui->jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
161 connect(ui->jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
164 m_inputFilter_jobList = new InputEventFilter(ui->jobsView);
165 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Up, 1);
166 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Down, 2);
167 connect(m_inputFilter_jobList, SIGNAL(keyPressed(int)), this, SLOT(jobListKeyPressed(int)));
169 //Setup mouse listener
170 m_inputFilter_version = new InputEventFilter(ui->labelBuildDate);
171 m_inputFilter_version->addMouseFilter(Qt::LeftButton, 0);
172 m_inputFilter_version->addMouseFilter(Qt::RightButton, 0);
173 connect(m_inputFilter_version, SIGNAL(mouseClicked(int)), this, SLOT(versionLabelMouseClicked(int)));
175 //Create context menu
176 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), ui->logView);
177 actionClipboard->setEnabled(false);
178 ui->logView->addAction(actionClipboard);
179 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
180 ui->jobsView->addActions(ui->menuJob->actions());
183 connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed() ));
184 connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed() ));
185 connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed() ));
186 connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
187 connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed() ));
188 connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed() ));
189 connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed() ));
190 connect(ui->actionJob_MoveUp, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
191 connect(ui->actionJob_MoveDown, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
194 connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
195 connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
196 connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
197 connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
200 SETUP_WEBLINK(ui->actionWebMulder, home_url);
201 SETUP_WEBLINK(ui->actionWebX264, "http://www.videolan.org/developers/x264.html");
202 SETUP_WEBLINK(ui->actionWebX265, "http://www.videolan.org/developers/x265.html");
203 SETUP_WEBLINK(ui->actionWebKomisar, "http://komisar.gin.by/");
204 SETUP_WEBLINK(ui->actionWebVideoLAN, "http://download.videolan.org/pub/x264/binaries/");
205 SETUP_WEBLINK(ui->actionWebJEEB, "http://x264.fushizen.eu/");
206 SETUP_WEBLINK(ui->actionWebFreeCodecs, "http://www.free-codecs.com/x264_video_codec_download.htm");
207 SETUP_WEBLINK(ui->actionWebX265BinRU, "http://x265.ru/en/builds/");
208 SETUP_WEBLINK(ui->actionWebX265BinEU, "http://builds.x265.eu/");
209 SETUP_WEBLINK(ui->actionWebX265BinORG, "http://chromashift.org/x265_builds/");
210 SETUP_WEBLINK(ui->actionWebX265BinFF, "http://ffmpeg.zeranoe.com/builds/");
211 SETUP_WEBLINK(ui->actionWebAvisynth32, "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/");
212 SETUP_WEBLINK(ui->actionWebAvisynth64, "http://code.google.com/p/avisynth64/downloads/list");
213 SETUP_WEBLINK(ui->actionWebAvisynthPlus, "http://www.avs-plus.net/");
214 SETUP_WEBLINK(ui->actionWebVapourSynth, "http://www.vapoursynth.com/");
215 SETUP_WEBLINK(ui->actionWebVapourSynthDocs, "http://www.vapoursynth.com/doc/");
216 SETUP_WEBLINK(ui->actionOnlineDocX264, "http://mewiki.project357.com/wiki/X264_Settings");
217 SETUP_WEBLINK(ui->actionOnlineDocX265, "http://x265.readthedocs.org/en/default/");
218 SETUP_WEBLINK(ui->actionWebBluRay, "http://www.x264bluray.com/");
219 SETUP_WEBLINK(ui->actionWebAvsWiki, "http://avisynth.nl/index.php/Main_Page#Usage");
220 SETUP_WEBLINK(ui->actionWebSupport, "http://forum.doom9.org/showthread.php?t=144140");
221 SETUP_WEBLINK(ui->actionWebSecret, "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
223 //Create floating label
224 m_label = new QLabel(ui->jobsView->viewport());
225 m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
226 m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
227 SET_TEXT_COLOR(m_label, Qt::darkGray);
228 SET_FONT_BOLD(m_label, true);
229 m_label->setVisible(true);
230 m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
231 m_label->addActions(ui->jobsView->actions());
232 connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
235 //Init system tray icon
236 m_sysTray->setToolTip(this->windowTitle());
237 m_sysTray->setIcon(this->windowIcon());
238 connect(m_sysTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(sysTrayActived()));
240 //Create corner widget
241 QLabel *checkUp = new QLabel(ui->menubar);
242 checkUp->setText(QString("<nobr><img src=\":/buttons/exclamation_small.png\"> <b style=\"color:darkred\">%1</b> </nobr>").arg(tr("Check for Updates")));
243 checkUp->setFixedHeight(ui->menubar->height());
244 checkUp->setCursor(QCursor(Qt::PointingHandCursor));
245 m_inputFilter_checkUp = new InputEventFilter(checkUp);
246 m_inputFilter_checkUp->addMouseFilter(Qt::LeftButton, 0);
247 m_inputFilter_checkUp->addMouseFilter(Qt::RightButton, 0);
248 connect(m_inputFilter_checkUp, SIGNAL(mouseClicked(int)), this, SLOT(checkUpdates()));
250 ui->menubar->setCornerWidget(checkUp);
253 m_fileTimer = new QTimer(this);
254 connect(m_fileTimer, SIGNAL(timeout()), this, SLOT(handlePendingFiles()));
260 MainWindow::~MainWindow(void)
262 OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
264 X264_DELETE(m_jobList);
265 X264_DELETE(m_options);
266 X264_DELETE(m_pendingFiles);
267 X264_DELETE(m_label);
268 X264_DELETE(m_inputFilter_jobList);
269 X264_DELETE(m_inputFilter_version);
270 X264_DELETE(m_inputFilter_checkUp);
272 while(!m_toolsList.isEmpty())
274 QFile *temp = m_toolsList.takeFirst();
278 if(m_ipc->isListening())
280 m_ipc->stopListening();
283 X264_DELETE(m_preferences);
284 X264_DELETE(m_recentlyUsed);
285 X264_DELETE(m_sysinfo);
286 X264_DELETE(m_fileTimer);
288 VapourSynthCheckThread::unload();
289 AvisynthCheckThread::unload();
295 ///////////////////////////////////////////////////////////////////////////////
297 ///////////////////////////////////////////////////////////////////////////////
300 * The "add" button was clicked
302 void MainWindow::addButtonPressed()
304 ENSURE_APP_IS_READY();
306 qDebug("MainWindow::addButtonPressed");
307 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
308 QString sourceFileName, outputFileName;
310 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
312 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
317 * The "open" action was triggered
319 void MainWindow::openActionTriggered()
321 ENSURE_APP_IS_READY();
323 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
324 if(!fileList.empty())
326 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
327 if(fileList.count() > 1)
329 createJobMultiple(fileList);
333 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
334 QString sourceFileName(fileList.first()), outputFileName;
335 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
337 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
344 * The "start" button was clicked
346 void MainWindow::startButtonPressed(void)
348 ENSURE_APP_IS_READY();
349 m_jobList->startJob(ui->jobsView->currentIndex());
353 * The "abort" button was clicked
355 void MainWindow::abortButtonPressed(void)
357 ENSURE_APP_IS_READY();
359 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)
361 m_jobList->abortJob(ui->jobsView->currentIndex());
366 * The "delete" button was clicked
368 void MainWindow::deleteButtonPressed(void)
370 ENSURE_APP_IS_READY();
372 m_jobList->deleteJob(ui->jobsView->currentIndex());
373 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
377 * The "browse" button was clicked
379 void MainWindow::browseButtonPressed(void)
381 ENSURE_APP_IS_READY();
383 QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
384 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
386 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
390 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
395 * The "browse" button was clicked
397 void MainWindow::moveButtonPressed(void)
399 ENSURE_APP_IS_READY();
401 if(sender() == ui->actionJob_MoveUp)
403 qDebug("Move job %d (direction: UP)", ui->jobsView->currentIndex().row());
404 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_UP))
406 x264_beep(x264_beep_error);
408 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
410 else if(sender() == ui->actionJob_MoveDown)
412 qDebug("Move job %d (direction: DOWN)", ui->jobsView->currentIndex().row());
413 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_DOWN))
415 x264_beep(x264_beep_error);
417 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
421 qWarning("[moveButtonPressed] Error: Unknown sender!");
426 * The "pause" button was clicked
428 void MainWindow::pauseButtonPressed(bool checked)
432 x264_beep(x264_beep_warning);
433 qWarning("Cannot perfrom this action at this time!");
434 ui->buttonPauseJob->setChecked(!checked);
439 m_jobList->pauseJob(ui->jobsView->currentIndex());
443 m_jobList->resumeJob(ui->jobsView->currentIndex());
448 * The "restart" button was clicked
450 void MainWindow::restartButtonPressed(void)
452 ENSURE_APP_IS_READY();
454 const QModelIndex index = ui->jobsView->currentIndex();
455 const OptionsModel *options = m_jobList->getJobOptions(index);
456 QString sourceFileName = m_jobList->getJobSourceFile(index);
457 QString outputFileName = m_jobList->getJobOutputFile(index);
459 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
461 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
462 OptionsModel *tempOptions = new OptionsModel(*options);
463 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
465 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
467 X264_DELETE(tempOptions);
472 * Job item selected by user
474 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
476 qDebug("Job selected: %d", current.row());
478 if(ui->logView->model())
480 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
483 if(current.isValid())
485 ui->logView->setModel(m_jobList->getLogFile(current));
486 connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
487 ui->logView->actions().first()->setEnabled(true);
488 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
490 ui->progressBar->setValue(m_jobList->getJobProgress(current));
491 ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
492 updateButtons(m_jobList->getJobStatus(current));
493 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
497 ui->logView->setModel(NULL);
498 ui->logView->actions().first()->setEnabled(false);
499 ui->progressBar->setValue(0);
500 ui->editDetails->clear();
501 updateButtons(JobStatus_Undefined);
502 updateTaskbar(JobStatus_Undefined, QIcon());
505 ui->progressBar->repaint();
509 * Handle update of job info (status, progress, details, etc)
511 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
513 int selected = ui->jobsView->currentIndex().row();
515 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
517 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
519 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
522 qDebug("Current job changed status!");
523 updateButtons(status);
524 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
526 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
528 if(m_preferences->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
529 if(m_preferences->getSaveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
533 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
535 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
539 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
540 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
545 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
547 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
551 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
559 * Handle new log file content
561 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
563 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
569 void MainWindow::showAbout(void)
571 ENSURE_APP_IS_READY();
573 if(AboutDialog *aboutDialog = new AboutDialog(this))
576 X264_DELETE(aboutDialog);
583 void MainWindow::showWebLink(void)
585 ENSURE_APP_IS_READY();
587 if(QObject *obj = QObject::sender())
589 if(QAction *action = dynamic_cast<QAction*>(obj))
591 if(action->data().type() == QVariant::Url)
593 QDesktopServices::openUrl(action->data().toUrl());
600 * Pereferences dialog
602 void MainWindow::showPreferences(void)
604 ENSURE_APP_IS_READY();
606 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences, m_sysinfo);
609 X264_DELETE(preferences);
613 * Launch next job, after running job has finished
615 void MainWindow::launchNextJob(void)
617 qDebug("Launching next job...");
619 if(countRunningJobs() >= m_preferences->getMaxRunningJobCount())
621 qDebug("Still have too many jobs running, won't launch next one yet!");
625 const int rows = m_jobList->rowCount(QModelIndex());
627 for(int i = 0; i < rows; i++)
629 const QModelIndex currentIndex = m_jobList->index(i, 0, QModelIndex());
630 if(m_jobList->getJobStatus(currentIndex) == JobStatus_Enqueued)
632 if(m_jobList->startJob(currentIndex))
634 ui->jobsView->selectRow(currentIndex.row());
640 qWarning("No enqueued jobs left to be started!");
642 if(m_preferences->getShutdownComputer())
644 QTimer::singleShot(0, this, SLOT(shutdownComputer()));
649 * Save log to text file
651 void MainWindow::saveLogFile(const QModelIndex &index)
655 if(LogFileModel *log = m_jobList->getLogFile(index))
657 QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
658 QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
659 QFile outFile(logFilePath);
660 if(outFile.open(QIODevice::WriteOnly))
662 QTextStream outStream(&outFile);
663 outStream.setCodec("UTF-8");
664 outStream.setGenerateByteOrderMark(true);
666 const int rows = log->rowCount(QModelIndex());
667 for(int i = 0; i < rows; i++)
669 outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
675 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
682 * Shut down the computer (with countdown)
684 void MainWindow::shutdownComputer(void)
686 ENSURE_APP_IS_READY();
688 if(countPendingJobs() > 0)
690 qDebug("Still have pending jobs, won't shutdown yet!");
694 const int iTimeout = 30;
695 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
696 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
698 qWarning("Initiating shutdown sequence!");
700 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
701 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
702 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
703 progressDialog.setModal(true);
704 progressDialog.setAutoClose(false);
705 progressDialog.setAutoReset(false);
706 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
707 progressDialog.setWindowTitle(windowTitle());
708 progressDialog.setCancelButton(cancelButton);
709 progressDialog.show();
711 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
712 QApplication::setOverrideCursor(Qt::WaitCursor);
713 x264_play_sound(IDR_WAVE1, false);
714 QApplication::restoreOverrideCursor();
717 timer.setInterval(1000);
720 QEventLoop eventLoop(this);
721 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
722 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
724 for(int i = 1; i <= iTimeout; i++)
727 if(progressDialog.wasCanceled())
729 progressDialog.close();
732 progressDialog.setValue(i+1);
733 progressDialog.setLabelText(text.arg(iTimeout-i));
734 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
735 QApplication::processEvents();
736 x264_play_sound(((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), false);
739 qWarning("Shutting down !!!");
741 if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
743 qApp->closeAllWindows();
749 * Main initialization function (called only once!)
751 void MainWindow::init(void)
755 qWarning("Already initialized -> skipping!");
761 const QStringList arguments = x264_arguments();
763 //---------------------------------------
764 // Create the IPC listener thread
765 //---------------------------------------
767 if(m_ipc->isInitialized())
769 connect(m_ipc, SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
770 m_ipc->startListening();
773 //---------------------------------------
774 // Check required binaries
775 //---------------------------------------
777 QStringList binFiles;
778 for(OptionsModel::EncArch arch = OptionsModel::EncArch_x32; arch <= OptionsModel::EncArch_x64; NEXT(arch))
780 for(OptionsModel::EncType encdr = OptionsModel::EncType_X264; encdr <= OptionsModel::EncType_X265; NEXT(encdr))
782 for(OptionsModel::EncVariant varnt = OptionsModel::EncVariant_LoBit; varnt <= OptionsModel::EncVariant_HiBit; NEXT(varnt))
784 binFiles << ENC_BINARY(m_sysinfo, encdr, arch, varnt);
787 binFiles << AVS_BINARY(m_sysinfo, arch == OptionsModel::EncArch_x64);
789 for(size_t i = 0; UpdaterDialog::BINARIES[i].name; i++)
791 if(UpdaterDialog::BINARIES[i].exec)
793 binFiles << QString("%1/toolset/common/%2").arg(m_sysinfo->getAppPath(), QString::fromLatin1(UpdaterDialog::BINARIES[i].name));
797 qDebug("[Validating binaries]");
798 for(QStringList::ConstIterator iter = binFiles.constBegin(); iter != binFiles.constEnd(); iter++)
800 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
801 QFile *file = new QFile(*iter);
802 qDebug("%s", file->fileName().toLatin1().constData());
803 if(file->open(QIODevice::ReadOnly))
805 if(!x264_is_executable(file->fileName()))
807 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("-", "−"));
808 qFatal(QString("Binary is invalid: %1").arg(file->fileName()).toLatin1().constData());
816 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("-", "−"));
817 qFatal(QString("Binary not found: %1/toolset/%2").arg(m_sysinfo->getAppPath(), file->fileName()).toLatin1().constData());
824 //---------------------------------------
825 // Check for portable mode
826 //---------------------------------------
831 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
832 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
833 if(writeTest.open(QIODevice::WriteOnly))
835 ok = (writeTest.write(data) == strlen(data));
840 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"));
841 if(val != 1) INIT_ERROR_EXIT();
846 if(x264_is_prerelease())
848 qsrand(time(NULL)); int rnd = qrand() % 3;
849 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);
850 if(rnd != val) INIT_ERROR_EXIT();
853 //---------------------------------------
854 // Check CPU capabilities
855 //---------------------------------------
857 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
858 if(!m_sysinfo->hasMMXSupport())
860 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"));
861 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
864 else if(!m_sysinfo->hasSSESupport())
866 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
867 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"));
868 if(val != 1) INIT_ERROR_EXIT();
871 //Skip version check (not recommended!)
872 if(CLIParser::checkFlag(CLI_PARAM_SKIP_VERSION_CHECK, arguments))
874 qWarning("Version checks are disabled now, you have been warned!\n");
875 m_preferences->setSkipVersionTest(true);
878 //Don't abort encoding process on timeout (not recommended!)
879 if(CLIParser::checkFlag(CLI_PARAM_NO_DEADLOCK, arguments))
881 qWarning("Deadlock detection disabled, you have been warned!\n");
882 m_preferences->setAbortOnTimeout(false);
885 //---------------------------------------
886 // Check Avisynth support
887 //---------------------------------------
889 if(!CLIParser::checkFlag(CLI_PARAM_SKIP_AVS_CHECK, arguments))
891 qDebug("[Check for Avisynth support]");
892 volatile double avisynthVersion = 0.0;
893 const int result = AvisynthCheckThread::detect(&avisynthVersion);
896 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
897 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
898 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
899 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
900 if(val != 1) INIT_ERROR_EXIT();
902 if(result && (avisynthVersion >= 2.5))
904 qDebug("Avisynth support is officially enabled now!");
905 m_sysinfo->setAVSSupport(true);
909 if(!m_preferences->getDisableWarnings())
911 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>");
912 text += tr("Please download and install Avisynth:").append("<br>").append(LINK(avs_dl_url));
913 int val = QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Close"), tr("Disable this Warning"));
916 m_preferences->setDisableWarnings(true);
917 PreferencesModel::savePreferences(m_preferences);
925 //---------------------------------------
926 // Check VapurSynth support
927 //---------------------------------------
929 if(!CLIParser::checkFlag(CLI_PARAM_SKIP_VPS_CHECK, arguments))
931 qDebug("[Check for VapourSynth support]");
932 QString vapoursynthPath;
933 const int result = VapourSynthCheckThread::detect(vapoursynthPath);
936 QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
937 text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
938 text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
939 const int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
940 if(val != 1) INIT_ERROR_EXIT();
942 if(result && (!vapoursynthPath.isEmpty()))
944 qDebug("VapourSynth support is officially enabled now!");
945 m_sysinfo->setVPSSupport(true);
946 m_sysinfo->setVPSPath(vapoursynthPath);
950 if(!m_preferences->getDisableWarnings())
952 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>");
953 text += tr("Please download and install VapourSynth (<b>r%1</b> or later) for Windows:").arg(QString::number(vsynth_rev)).append("<br>").append(LINK(vsynth_url)).append("<br><br>");
954 text += tr("Note that Python v3.4 is a prerequisite for installing VapourSynth:").append("<br>").append(LINK(python_url)).append("<br>");
955 const int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Close"), tr("Disable this Warning"));
958 m_preferences->setDisableWarnings(true);
959 PreferencesModel::savePreferences(m_preferences);
966 //---------------------------------------
967 // Finish initialization
968 //---------------------------------------
971 setWindowTitle(QString("%1 (%2)").arg(windowTitle(), m_sysinfo->hasX64Support() ? "64-Bit" : "32-Bit"));
973 //Enable drag&drop support for this window, required for Qt v4.8.4+
974 setAcceptDrops(true);
977 m_initialized = true;
979 //---------------------------------------
980 // Check for Expiration
981 //---------------------------------------
983 if(x264_version_date().addMonths(6) < x264_current_date_safe())
985 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
987 text += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(tr("Your version of Simple x264 Launcher is more than 6 months old!").replace('-', "−"));
988 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("-", "−"));
989 text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace('-', "−"));
990 QMessageBox msgBox(this);
991 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
992 msgBox.setWindowTitle(tr("Update Notification"));
993 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
994 msgBox.setText(text);
995 QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
996 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
997 QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
998 btn2->setEnabled(false);
999 btn3->setVisible(false);
1000 QTimer::singleShot(7500, btn2, SLOT(hide()));
1001 QTimer::singleShot(7500, btn3, SLOT(show()));
1002 if(msgBox.exec() == 0)
1004 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1008 else if(!parseCommandLineArgs())
1011 if(CLIParser::checkFlag(CLI_PARAM_FIRST_RUN, arguments))
1013 qWarning("First run -> resetting update check now!");
1014 m_recentlyUsed->setLastUpdateCheck(0);
1015 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
1017 else if(m_recentlyUsed->lastUpdateCheck() + 14 < x264_current_date_safe().toJulianDay())
1019 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
1020 if(!m_preferences->getNoUpdateReminder())
1022 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)
1024 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1032 if(m_jobList->loadQueuedJobs(m_sysinfo) > 0)
1034 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1035 m_jobList->clearQueuedJobs();
1040 * Update the label position
1042 void MainWindow::updateLabelPos(void)
1044 const QWidget *const viewPort = ui->jobsView->viewport();
1045 m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
1049 * Copy the complete log to the clipboard
1051 void MainWindow::copyLogToClipboard(bool checked)
1053 qDebug("Coyping logfile to clipboard...");
1055 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1057 log->copyToClipboard();
1058 x264_beep(x264_beep_info);
1063 * Process the dropped files
1065 void MainWindow::handlePendingFiles(void)
1067 qDebug("MainWindow::handlePendingFiles");
1069 if(!m_pendingFiles->isEmpty())
1071 QStringList pendingFiles(*m_pendingFiles);
1072 m_pendingFiles->clear();
1073 createJobMultiple(pendingFiles);
1076 qDebug("Leave from MainWindow::handlePendingFiles!");
1080 * Handle incoming IPC command
1082 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1084 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1086 qWarning("Cannot accapt commands at this time -> discarding!");
1090 if((!isVisible()) || m_sysTray->isVisible())
1095 x264_bring_to_front(this);
1098 qDebug("\n---------- IPC ----------");
1099 qDebug("CommandId: %d", command);
1100 for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1102 qDebug("Arguments: %s", iter->toUtf8().constData());
1104 qDebug("The Flags: 0x%08X", flags);
1105 qDebug("---------- IPC ----------\n");
1106 #endif //IPC_LOGGING
1110 case IPC_OPCODE_PING:
1111 qDebug("Received a PING request from another instance!");
1112 x264_blink_window(this, 5, 125);
1114 case IPC_OPCODE_ADD_FILE:
1117 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1119 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1120 if(!m_fileTimer->isActive())
1122 m_fileTimer->setSingleShot(true);
1123 m_fileTimer->start(5000);
1128 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1132 case IPC_OPCODE_ADD_JOB:
1133 if(args.size() >= 3)
1135 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1137 OptionsModel options(m_sysinfo);
1138 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1139 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1141 if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1143 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1146 if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
1147 if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
1148 appendJob(args[0], args[1], &options, runImmediately);
1152 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1157 THROW("Unknown command received!");
1162 * Check for new updates
1164 void MainWindow::checkUpdates(void)
1166 ENSURE_APP_IS_READY();
1168 if(countRunningJobs() > 0)
1170 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1174 UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo, update_url);
1175 const int ret = updater->exec();
1177 if(updater->getSuccess())
1179 m_recentlyUsed->setLastUpdateCheck(x264_current_date_safe().toJulianDay());
1180 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
1181 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->hide();
1184 if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1186 qWarning("Exitting program to install update...");
1188 QApplication::quit();
1191 X264_DELETE(updater);
1195 * Handle mouse event for version label
1197 void MainWindow::versionLabelMouseClicked(const int &tag)
1201 QTimer::singleShot(0, this, SLOT(showAbout()));
1206 * Handle key event for job list
1208 void MainWindow::jobListKeyPressed(const int &tag)
1213 ui->actionJob_MoveUp->trigger();
1216 ui->actionJob_MoveDown->trigger();
1222 * System tray was activated
1224 void MainWindow::sysTrayActived(void)
1228 x264_bring_to_front(this);
1231 ///////////////////////////////////////////////////////////////////////////////
1233 ///////////////////////////////////////////////////////////////////////////////
1236 * Window shown event
1238 void MainWindow::showEvent(QShowEvent *e)
1240 QMainWindow::showEvent(e);
1244 QTimer::singleShot(0, this, SLOT(init()));
1249 * Window close event
1251 void MainWindow::closeEvent(QCloseEvent *e)
1256 qWarning("Cannot close window at this time!");
1260 //Make sure we have no running jobs left!
1261 if(countRunningJobs() > 0)
1264 if(!m_preferences->getNoSystrayWarning())
1266 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)
1268 m_preferences->setNoSystrayWarning(true);
1269 PreferencesModel::savePreferences(m_preferences);
1277 //Save pending jobs for next time, if desired by user
1278 if(countPendingJobs() > 0)
1280 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"));
1283 m_jobList->saveQueuedJobs();
1287 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)
1295 //Delete remaining jobs
1296 while(m_jobList->rowCount(QModelIndex()) > 0)
1298 if((m_jobList->rowCount(QModelIndex()) % 10) == 0)
1300 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1302 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1305 QMessageBox::warning(this, tr("Failed To Exit"), tr("Warning: At least one job could not be deleted!"));
1309 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1310 QMainWindow::closeEvent(e);
1314 * Window resize event
1316 void MainWindow::resizeEvent(QResizeEvent *e)
1318 QMainWindow::resizeEvent(e);
1323 * Win32 message filter
1325 bool MainWindow::winEvent(MSG *message, long *result)
1327 return WinSevenTaskbar::handleWinEvent(message, result);
1331 * File dragged over window
1333 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1335 bool accept[2] = {false, false};
1337 foreach(const QString &fmt, event->mimeData()->formats())
1339 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1340 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1343 if(accept[0] && accept[1])
1345 event->acceptProposedAction();
1350 * File dropped onto window
1352 void MainWindow::dropEvent(QDropEvent *event)
1354 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1356 qWarning("Cannot accept dropped files at this time -> discarding!");
1360 QStringList droppedFiles;
1361 QList<QUrl> urls = event->mimeData()->urls();
1363 while(!urls.isEmpty())
1365 QUrl currentUrl = urls.takeFirst();
1366 QFileInfo file(currentUrl.toLocalFile());
1367 if(file.exists() && file.isFile())
1369 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1370 droppedFiles << file.canonicalFilePath();
1374 if(droppedFiles.count() > 0)
1376 m_pendingFiles->append(droppedFiles);
1377 m_pendingFiles->sort();
1378 if(!m_fileTimer->isActive())
1380 m_fileTimer->setSingleShot(true);
1381 m_fileTimer->start(5000);
1386 ///////////////////////////////////////////////////////////////////////////////
1387 // Private functions
1388 ///////////////////////////////////////////////////////////////////////////////
1393 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1396 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed, m_sysinfo, m_preferences);
1398 addDialog->setRunImmediately(runImmediately);
1399 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1400 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1401 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1403 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1406 addDialog->setSourceEditable(false);
1407 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1408 addDialog->setApplyToAllVisible(applyToAll);
1411 if(addDialog->exec() == QDialog::Accepted)
1413 sourceFileName = addDialog->sourceFile();
1414 outputFileName = addDialog->outputFile();
1415 runImmediately = addDialog->runImmediately();
1418 *applyToAll = addDialog->applyToAll();
1423 X264_DELETE(addDialog);
1428 * Creates a new job from *multiple* files
1430 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1432 QStringList::ConstIterator iter;
1433 bool applyToAll = false, runImmediately = false;
1436 //Add files individually
1437 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1439 runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1440 QString sourceFileName(*iter), outputFileName;
1441 if(createJob(sourceFileName, outputFileName, m_options, runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1443 if(appendJob(sourceFileName, outputFileName, m_options, runImmediately))
1451 //Add remaining files
1452 while(applyToAll && (iter != filePathIn.constEnd()))
1454 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1455 const QString sourceFileName = *iter;
1456 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
1457 if(!appendJob(sourceFileName, outputFileName, m_options, runImmediatelyTmp))
1470 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1473 EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo, m_preferences);
1474 QModelIndex newIndex = m_jobList->insertJob(thrd);
1476 if(newIndex.isValid())
1480 ui->jobsView->selectRow(newIndex.row());
1481 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1482 m_jobList->startJob(newIndex);
1488 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1493 * Jobs that are not completed (or failed, or aborted) yet
1495 unsigned int MainWindow::countPendingJobs(void)
1497 unsigned int count = 0;
1498 const int rows = m_jobList->rowCount(QModelIndex());
1500 for(int i = 0; i < rows; i++)
1502 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1503 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1513 * Jobs that are still active, i.e. not terminated or enqueued
1515 unsigned int MainWindow::countRunningJobs(void)
1517 unsigned int count = 0;
1518 const int rows = m_jobList->rowCount(QModelIndex());
1520 for(int i = 0; i < rows; i++)
1522 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1523 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1533 * Update all buttons with respect to current job status
1535 void MainWindow::updateButtons(JobStatus status)
1537 qDebug("MainWindow::updateButtons(void)");
1539 ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1540 ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1541 ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1542 ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1544 ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1545 ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1546 ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1547 ui->actionJob_MoveUp->setEnabled(status != JobStatus_Undefined);
1548 ui->actionJob_MoveDown->setEnabled(status != JobStatus_Undefined);
1550 ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1551 ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1552 ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1553 ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1555 ui->editDetails->setEnabled(status != JobStatus_Paused);
1559 * Update the taskbar with current job status
1561 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1563 qDebug("MainWindow::updateTaskbar(void)");
1567 case JobStatus_Undefined:
1568 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1570 case JobStatus_Aborting:
1571 case JobStatus_Starting:
1572 case JobStatus_Pausing:
1573 case JobStatus_Resuming:
1574 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1576 case JobStatus_Aborted:
1577 case JobStatus_Failed:
1578 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1580 case JobStatus_Paused:
1581 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1584 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1590 case JobStatus_Aborting:
1591 case JobStatus_Starting:
1592 case JobStatus_Pausing:
1593 case JobStatus_Resuming:
1596 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
1600 WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);
1604 * Parse command-line arguments
1606 bool MainWindow::parseCommandLineArgs(void)
1608 bool bCommandAccepted = false;
1609 unsigned int flags = 0;
1611 //Initialize command-line parser
1612 CLIParser parser(x264_arguments());
1614 QStringList options;
1616 //Process all command-line arguments
1617 while(parser.nextOption(identifier, &options))
1621 case CLI_PARAM_ADD_FILE:
1622 handleCommand(IPC_OPCODE_ADD_FILE, options, flags);
1623 bCommandAccepted = true;
1625 case CLI_PARAM_ADD_JOB:
1626 handleCommand(IPC_OPCODE_ADD_JOB, options, flags);
1627 bCommandAccepted = true;
1629 case CLI_PARAM_FORCE_START:
1630 flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1632 case CLI_PARAM_NO_FORCE_START:
1633 flags = (flags & (~IPC_FLAG_FORCE_START));
1635 case CLI_PARAM_FORCE_ENQUEUE:
1636 flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1638 case CLI_PARAM_NO_FORCE_ENQUEUE:
1639 flags = (flags & (~IPC_FLAG_FORCE_ENQUEUE));
1644 return bCommandAccepted;