1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2015 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"
29 #include "model_status.h"
30 #include "model_sysinfo.h"
31 #include "model_jobList.h"
32 #include "model_options.h"
33 #include "model_preferences.h"
34 #include "model_recently.h"
35 #include "thread_avisynth.h"
36 #include "thread_binaries.h"
37 #include "thread_vapoursynth.h"
38 #include "thread_encode.h"
39 #include "thread_ipc_recv.h"
40 #include "input_filter.h"
41 #include "win_addJob.h"
42 #include "win_about.h"
43 #include "win_preferences.h"
44 #include "win_updater.h"
49 #include <MUtils/OSSupport.h>
50 #include <MUtils/CPUFeatures.h>
51 #include <MUtils/IPCChannel.h>
52 #include <MUtils/GUI.h>
53 #include <MUtils/Sound.h>
54 #include <MUtils/Exception.h>
55 #include <MUtils/Taskbar7.h>
56 #include <MUtils/Version.h>
61 #include <QCloseEvent>
62 #include <QMessageBox>
63 #include <QDesktopServices>
68 #include <QProgressDialog>
70 #include <QTextStream>
72 #include <QFileDialog>
73 #include <QSystemTrayIcon>
79 static const char *tpl_last = "<LAST_USED>";
80 static const char *home_url = "http://muldersoft.com/";
81 static const char *update_url = "https://github.com/lordmulder/Simple-x264-Launcher/releases/latest";
82 static const char *avs_dl_url = "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/";
83 static const char *python_url = "https://www.python.org/downloads/";
84 static const char *vsynth_url = "http://www.vapoursynth.com/";
85 static const int vsynth_rev = 24;
88 #define SET_FONT_BOLD(WIDGET,BOLD) do { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); } while(0)
89 #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)
90 #define LINK(URL) (QString("<a href=\"%1\">%1</a>").arg((URL)))
91 #define INIT_ERROR_EXIT() do { close(); qApp->exit(-1); return; } while(0)
92 #define SETUP_WEBLINK(OBJ, URL) do { (OBJ)->setData(QVariant(QUrl(URL))); connect((OBJ), SIGNAL(triggered()), this, SLOT(showWebLink())); } while(0)
93 #define APP_IS_READY (m_initialized && (!m_fileTimer->isActive()) && (QApplication::activeModalWidget() == NULL))
94 #define ENSURE_APP_IS_READY() do { if(!APP_IS_READY) { MUtils::Sound::beep(MUtils::Sound::BEEP_WRN); qWarning("Cannot perfrom this action at this time!"); return; } } while(0)
95 #define X264_STRCMP(X,Y) ((X).compare((Y), Qt::CaseInsensitive) == 0)
97 ///////////////////////////////////////////////////////////////////////////////
98 // Constructor & Destructor
99 ///////////////////////////////////////////////////////////////////////////////
104 MainWindow::MainWindow(const MUtils::CPUFetaures::cpu_info_t &cpuFeatures, MUtils::IPCChannel *const ipcChannel)
106 m_ipcChannel(ipcChannel),
110 m_pendingFiles(new QStringList()),
112 m_recentlyUsed(NULL),
113 m_initialized(false),
114 ui(new Ui::MainWindow())
116 //Init the dialog, from the .ui file
118 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
120 //Register meta types
121 qRegisterMetaType<QUuid>("QUuid");
122 qRegisterMetaType<QUuid>("DWORD");
123 qRegisterMetaType<JobStatus>("JobStatus");
125 //Create and initialize the sysinfo object
126 m_sysinfo.reset(new SysinfoModel());
127 m_sysinfo->setAppPath(QApplication::applicationDirPath());
128 m_sysinfo->setCPUFeatures(SysinfoModel::CPUFeatures_MMX, cpuFeatures.features & MUtils::CPUFetaures::FLAG_MMX);
129 m_sysinfo->setCPUFeatures(SysinfoModel::CPUFeatures_SSE, cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE);
130 m_sysinfo->setCPUFeatures(SysinfoModel::CPUFeatures_X64, cpuFeatures.x64 && (cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE2)); //X64 implies SSE2
133 m_preferences.reset(new PreferencesModel());
134 PreferencesModel::loadPreferences(m_preferences.data());
137 m_recentlyUsed.reset(new RecentlyUsed());
138 RecentlyUsed::loadRecentlyUsed(m_recentlyUsed.data());
140 //Create options object
141 m_options.reset(new OptionsModel(m_sysinfo.data()));
142 OptionsModel::loadTemplate(m_options.data(), QString::fromLatin1(tpl_last));
144 //Freeze minimum size
145 setMinimumSize(size());
146 ui->splitter->setSizes(QList<int>() << 16 << 196);
149 ui->labelBuildDate->setText(tr("Built on %1 at %2").arg(MUtils::Version::app_build_date().toString(Qt::ISODate), MUtils::Version::app_build_time().toString(Qt::ISODate)));
153 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
154 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
156 else if(x264_is_prerelease())
158 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
162 m_jobList.reset(new JobListModel(m_preferences.data()));
163 connect(m_jobList.data(), SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
164 ui->jobsView->setModel(m_jobList.data());
167 ui->jobsView->horizontalHeader()->setSectionHidden(3, true);
168 ui->jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
169 ui->jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
170 ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
171 ui->jobsView->horizontalHeader()->resizeSection(1, 150);
172 ui->jobsView->horizontalHeader()->resizeSection(2, 90);
173 ui->jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
174 connect(ui->jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
177 m_inputFilter_jobList.reset(new InputEventFilter(ui->jobsView));
178 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Up, 1);
179 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Down, 2);
180 connect(m_inputFilter_jobList.data(), SIGNAL(keyPressed(int)), this, SLOT(jobListKeyPressed(int)));
182 //Setup mouse listener
183 m_inputFilter_version.reset(new InputEventFilter(ui->labelBuildDate));
184 m_inputFilter_version->addMouseFilter(Qt::LeftButton, 0);
185 m_inputFilter_version->addMouseFilter(Qt::RightButton, 0);
186 connect(m_inputFilter_version.data(), SIGNAL(mouseClicked(int)), this, SLOT(versionLabelMouseClicked(int)));
188 //Create context menu
189 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), ui->logView);
190 actionClipboard->setEnabled(false);
191 ui->logView->addAction(actionClipboard);
192 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
193 ui->jobsView->addActions(ui->menuJob->actions());
196 connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed() ));
197 connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed() ));
198 connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed() ));
199 connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
200 connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed() ));
201 connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed() ));
202 connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed() ));
203 connect(ui->actionJob_MoveUp, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
204 connect(ui->actionJob_MoveDown, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
207 connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
208 connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
209 connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
210 connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
213 SETUP_WEBLINK(ui->actionWebMulder, home_url);
214 SETUP_WEBLINK(ui->actionWebX264, "http://www.videolan.org/developers/x264.html");
215 SETUP_WEBLINK(ui->actionWebX265, "http://www.videolan.org/developers/x265.html");
216 SETUP_WEBLINK(ui->actionWebKomisar, "http://komisar.gin.by/");
217 SETUP_WEBLINK(ui->actionWebVideoLAN, "http://download.videolan.org/pub/x264/binaries/");
218 SETUP_WEBLINK(ui->actionWebJEEB, "http://x264.fushizen.eu/");
219 SETUP_WEBLINK(ui->actionWebFreeCodecs, "http://www.free-codecs.com/x264_video_codec_download.htm");
220 SETUP_WEBLINK(ui->actionWebX265BinRU, "http://x265.ru/en/builds/");
221 SETUP_WEBLINK(ui->actionWebX265BinEU, "http://builds.x265.eu/");
222 SETUP_WEBLINK(ui->actionWebX265BinORG, "http://chromashift.org/x265_builds/");
223 SETUP_WEBLINK(ui->actionWebX265BinFF, "http://ffmpeg.zeranoe.com/builds/");
224 SETUP_WEBLINK(ui->actionWebAvisynth32, "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/");
225 SETUP_WEBLINK(ui->actionWebAvisynth64, "http://code.google.com/p/avisynth64/downloads/list");
226 SETUP_WEBLINK(ui->actionWebAvisynthPlus, "http://www.avs-plus.net/");
227 SETUP_WEBLINK(ui->actionWebVapourSynth, "http://www.vapoursynth.com/");
228 SETUP_WEBLINK(ui->actionWebVapourSynthDocs, "http://www.vapoursynth.com/doc/");
229 SETUP_WEBLINK(ui->actionOnlineDocX264, "http://en.wikibooks.org/wiki/MeGUI/x264_Settings"); //http://mewiki.project357.com/wiki/X264_Settings
230 SETUP_WEBLINK(ui->actionOnlineDocX265, "http://x265.readthedocs.org/en/default/");
231 SETUP_WEBLINK(ui->actionWebBluRay, "http://www.x264bluray.com/");
232 SETUP_WEBLINK(ui->actionWebAvsWiki, "http://avisynth.nl/index.php/Main_Page#Usage");
233 SETUP_WEBLINK(ui->actionWebSupport, "http://forum.doom9.org/showthread.php?t=144140");
234 SETUP_WEBLINK(ui->actionWebSecret, "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
236 //Create floating label
237 m_label[0].reset(new QLabel(ui->jobsView->viewport()));
238 m_label[1].reset(new QLabel(ui->logView->viewport()));
239 if(!m_label[0].isNull())
241 m_label[0]->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
242 m_label[0]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
243 SET_TEXT_COLOR(m_label[0], Qt::darkGray);
244 SET_FONT_BOLD(m_label[0], true);
245 m_label[0]->setVisible(true);
246 m_label[0]->setContextMenuPolicy(Qt::ActionsContextMenu);
247 m_label[0]->addActions(ui->jobsView->actions());
249 if(!m_label[1].isNull())
251 m_animation.reset(new QMovie(":/images/spinner.gif"));
252 m_label[1]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
253 if(!m_animation.isNull())
255 m_label[1]->setMovie(m_animation.data());
256 m_animation->start();
259 connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
262 //Init system tray icon
263 m_sysTray.reset(new QSystemTrayIcon(this));
264 m_sysTray->setToolTip(this->windowTitle());
265 m_sysTray->setIcon(this->windowIcon());
266 connect(m_sysTray.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(sysTrayActived()));
268 //Init taskbar progress
269 m_taskbar.reset(new MUtils::Taskbar7(this));
271 //Create corner widget
272 QLabel *checkUp = new QLabel(ui->menubar);
273 checkUp->setText(QString("<nobr><img src=\":/buttons/exclamation_small.png\"> <b style=\"color:darkred\">%1</b> </nobr>").arg(tr("Check for Updates")));
274 checkUp->setFixedHeight(ui->menubar->height());
275 checkUp->setCursor(QCursor(Qt::PointingHandCursor));
276 m_inputFilter_checkUp.reset(new InputEventFilter(checkUp));
277 m_inputFilter_checkUp->addMouseFilter(Qt::LeftButton, 0);
278 m_inputFilter_checkUp->addMouseFilter(Qt::RightButton, 0);
279 connect(m_inputFilter_checkUp.data(), SIGNAL(mouseClicked(int)), this, SLOT(checkUpdates()));
281 ui->menubar->setCornerWidget(checkUp);
284 m_fileTimer.reset(new QTimer(this));
285 connect(m_fileTimer.data(), SIGNAL(timeout()), this, SLOT(handlePendingFiles()));
291 MainWindow::~MainWindow(void)
293 OptionsModel::saveTemplate(m_options.data(), QString::fromLatin1(tpl_last));
295 if(!m_ipcThread.isNull())
298 if(!m_ipcThread->wait(5000))
300 m_ipcThread->terminate();
308 ///////////////////////////////////////////////////////////////////////////////
310 ///////////////////////////////////////////////////////////////////////////////
313 * The "add" button was clicked
315 void MainWindow::addButtonPressed()
317 ENSURE_APP_IS_READY();
319 qDebug("MainWindow::addButtonPressed");
320 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
321 QString sourceFileName, outputFileName;
323 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
325 appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
330 * The "open" action was triggered
332 void MainWindow::openActionTriggered()
334 ENSURE_APP_IS_READY();
336 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
337 if(!fileList.empty())
339 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
340 if(fileList.count() > 1)
342 createJobMultiple(fileList);
346 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
347 QString sourceFileName(fileList.first()), outputFileName;
348 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
350 appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
357 * The "start" button was clicked
359 void MainWindow::startButtonPressed(void)
361 ENSURE_APP_IS_READY();
362 m_jobList->startJob(ui->jobsView->currentIndex());
366 * The "abort" button was clicked
368 void MainWindow::abortButtonPressed(void)
370 ENSURE_APP_IS_READY();
372 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)
374 m_jobList->abortJob(ui->jobsView->currentIndex());
379 * The "delete" button was clicked
381 void MainWindow::deleteButtonPressed(void)
383 ENSURE_APP_IS_READY();
385 m_jobList->deleteJob(ui->jobsView->currentIndex());
386 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
390 * The "browse" button was clicked
392 void MainWindow::browseButtonPressed(void)
394 ENSURE_APP_IS_READY();
396 QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
397 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
399 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
403 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
408 * The "browse" button was clicked
410 void MainWindow::moveButtonPressed(void)
412 ENSURE_APP_IS_READY();
414 if(sender() == ui->actionJob_MoveUp)
416 qDebug("Move job %d (direction: UP)", ui->jobsView->currentIndex().row());
417 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_UP))
419 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
421 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
423 else if(sender() == ui->actionJob_MoveDown)
425 qDebug("Move job %d (direction: DOWN)", ui->jobsView->currentIndex().row());
426 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_DOWN))
428 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
430 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
434 qWarning("[moveButtonPressed] Error: Unknown sender!");
439 * The "pause" button was clicked
441 void MainWindow::pauseButtonPressed(bool checked)
445 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
446 qWarning("Cannot perfrom this action at this time!");
447 ui->buttonPauseJob->setChecked(!checked);
452 m_jobList->pauseJob(ui->jobsView->currentIndex());
456 m_jobList->resumeJob(ui->jobsView->currentIndex());
461 * The "restart" button was clicked
463 void MainWindow::restartButtonPressed(void)
465 ENSURE_APP_IS_READY();
467 const QModelIndex index = ui->jobsView->currentIndex();
468 const OptionsModel *options = m_jobList->getJobOptions(index);
469 QString sourceFileName = m_jobList->getJobSourceFile(index);
470 QString outputFileName = m_jobList->getJobOutputFile(index);
472 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
474 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
475 OptionsModel *tempOptions = new OptionsModel(*options);
476 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
478 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
480 MUTILS_DELETE(tempOptions);
485 * Job item selected by user
487 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
489 qDebug("Job selected: %d", current.row());
491 if(ui->logView->model())
493 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
496 if(current.isValid())
498 ui->logView->setModel(m_jobList->getLogFile(current));
499 connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
500 ui->logView->actions().first()->setEnabled(true);
501 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
503 ui->progressBar->setValue(m_jobList->getJobProgress(current));
504 ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
505 updateButtons(m_jobList->getJobStatus(current));
506 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
510 ui->logView->setModel(NULL);
511 ui->logView->actions().first()->setEnabled(false);
512 ui->progressBar->setValue(0);
513 ui->editDetails->clear();
514 updateButtons(JobStatus_Undefined);
515 updateTaskbar(JobStatus_Undefined, QIcon());
518 ui->progressBar->repaint();
522 * Handle update of job info (status, progress, details, etc)
524 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
526 int selected = ui->jobsView->currentIndex().row();
528 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
530 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
532 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
535 qDebug("Current job changed status!");
536 updateButtons(status);
537 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
539 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
541 if(m_preferences->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
542 if(m_preferences->getSaveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
546 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
548 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
552 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
553 if(!m_taskbar.isNull())
555 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
561 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
563 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
567 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
575 * Handle new log file content
577 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
579 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
585 void MainWindow::showAbout(void)
587 ENSURE_APP_IS_READY();
589 if(AboutDialog *aboutDialog = new AboutDialog(this))
592 MUTILS_DELETE(aboutDialog);
599 void MainWindow::showWebLink(void)
601 ENSURE_APP_IS_READY();
603 if(QObject *obj = QObject::sender())
605 if(QAction *action = dynamic_cast<QAction*>(obj))
607 if(action->data().type() == QVariant::Url)
609 QDesktopServices::openUrl(action->data().toUrl());
616 * Pereferences dialog
618 void MainWindow::showPreferences(void)
620 ENSURE_APP_IS_READY();
622 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences.data(), m_sysinfo.data());
625 MUTILS_DELETE(preferences);
629 * Launch next job, after running job has finished
631 void MainWindow::launchNextJob(void)
633 qDebug("Launching next job...");
635 if(countRunningJobs() >= m_preferences->getMaxRunningJobCount())
637 qDebug("Still have too many jobs running, won't launch next one yet!");
641 const int rows = m_jobList->rowCount(QModelIndex());
643 for(int i = 0; i < rows; i++)
645 const QModelIndex currentIndex = m_jobList->index(i, 0, QModelIndex());
646 if(m_jobList->getJobStatus(currentIndex) == JobStatus_Enqueued)
648 if(m_jobList->startJob(currentIndex))
650 ui->jobsView->selectRow(currentIndex.row());
656 qWarning("No enqueued jobs left to be started!");
658 if(m_preferences->getShutdownComputer())
660 QTimer::singleShot(0, this, SLOT(shutdownComputer()));
665 * Save log to text file
667 void MainWindow::saveLogFile(const QModelIndex &index)
671 if(LogFileModel *log = m_jobList->getLogFile(index))
673 QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
674 QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
675 QFile outFile(logFilePath);
676 if(outFile.open(QIODevice::WriteOnly))
678 QTextStream outStream(&outFile);
679 outStream.setCodec("UTF-8");
680 outStream.setGenerateByteOrderMark(true);
682 const int rows = log->rowCount(QModelIndex());
683 for(int i = 0; i < rows; i++)
685 outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
691 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
698 * Shut down the computer (with countdown)
700 void MainWindow::shutdownComputer(void)
702 ENSURE_APP_IS_READY();
704 if(countPendingJobs() > 0)
706 qDebug("Still have pending jobs, won't shutdown yet!");
710 const int iTimeout = 30;
711 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
712 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
714 qWarning("Initiating shutdown sequence!");
716 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
717 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
718 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
719 progressDialog.setModal(true);
720 progressDialog.setAutoClose(false);
721 progressDialog.setAutoReset(false);
722 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
723 progressDialog.setWindowTitle(windowTitle());
724 progressDialog.setCancelButton(cancelButton);
725 progressDialog.show();
727 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
728 QApplication::setOverrideCursor(Qt::WaitCursor);
729 MUtils::Sound::play_sound("shutdown", false);
730 QApplication::restoreOverrideCursor();
733 timer.setInterval(1000);
736 QEventLoop eventLoop(this);
737 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
738 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
740 for(int i = 1; i <= iTimeout; i++)
743 if(progressDialog.wasCanceled())
745 progressDialog.close();
748 progressDialog.setValue(i+1);
749 progressDialog.setLabelText(text.arg(iTimeout-i));
750 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
751 QApplication::processEvents();
752 MUtils::Sound::play_sound(((i < iTimeout) ? "beep" : "beep2"), false);
755 qWarning("Shutting down !!!");
757 if(MUtils::OS::shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true, false))
759 qApp->closeAllWindows();
765 * Main initialization function (called only once!)
767 void MainWindow::init(void)
771 qWarning("Already initialized -> skipping!");
776 const MUtils::OS::ArgumentMap &arguments = MUtils::OS::arguments();
777 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
779 //---------------------------------------
780 // Check required binaries
781 //---------------------------------------
783 qDebug("[Validating binaries]");
784 if(!BinariesCheckThread::check(m_sysinfo.data()))
786 QMessageBox::critical(this, tr("Invalid File!"), tr("<nobr>At least one required tool is missing or is not a valid Win32/Win64 binary.<br>Please re-install the program in order to fix the problem!</nobr>").replace("-", "−"));
787 qFatal("At least one required tool is missing or is not a valid Win32/Win64 binary!");
791 //---------------------------------------
792 // Check for portable mode
793 //---------------------------------------
795 if(x264_is_portable())
798 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
799 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
800 if(writeTest.open(QIODevice::WriteOnly))
802 ok = (writeTest.write(data) == strlen(data));
807 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"));
808 if(val != 1) INIT_ERROR_EXIT();
813 if(x264_is_prerelease())
815 qsrand(time(NULL)); int rnd = qrand() % 3;
816 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);
817 if(rnd != val) INIT_ERROR_EXIT();
820 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
822 //---------------------------------------
823 // Check CPU capabilities
824 //---------------------------------------
826 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
827 if(!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_MMX))
829 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"));
830 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
833 else if(!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_SSE))
835 qWarning("WARNING: System does not support SSE (v1), x264/x265 probably will *not* work !!!\n");
836 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/x265 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"));
837 if(val != 1) INIT_ERROR_EXIT();
840 //Skip version check (not recommended!)
841 if(arguments.contains(CLI_PARAM_SKIP_VERSION_CHECK))
843 qWarning("Version checks are disabled now, you have been warned!\n");
844 m_preferences->setSkipVersionTest(true);
847 //Don't abort encoding process on timeout (not recommended!)
848 if(arguments.contains(CLI_PARAM_NO_DEADLOCK))
850 qWarning("Deadlock detection disabled, you have been warned!\n");
851 m_preferences->setAbortOnTimeout(false);
854 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
856 //---------------------------------------
857 // Check Avisynth support
858 //---------------------------------------
860 if(!arguments.contains(CLI_PARAM_SKIP_AVS_CHECK))
862 qDebug("[Check for Avisynth support]");
863 if(!AvisynthCheckThread::detect(m_sysinfo.data()))
865 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
866 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
867 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
868 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
869 if(val != 1) INIT_ERROR_EXIT();
871 else if((!m_sysinfo->hasAvisynth()) && (!m_preferences->getDisableWarnings()))
873 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>");
874 text += tr("Please download and install Avisynth:").append("<br>").append(LINK(avs_dl_url));
875 int val = QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Close"), tr("Disable this Warning"));
878 m_preferences->setDisableWarnings(true);
879 PreferencesModel::savePreferences(m_preferences.data());
885 //---------------------------------------
886 // Check VapurSynth support
887 //---------------------------------------
889 if(!arguments.contains(CLI_PARAM_SKIP_VPS_CHECK))
891 qDebug("[Check for VapourSynth support]");
892 if(!VapourSynthCheckThread::detect(m_sysinfo.data()))
894 QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
895 text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
896 text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
897 const int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
898 if(val != 1) INIT_ERROR_EXIT();
900 else if((!m_sysinfo->hasVapourSynth()) && (!m_preferences->getDisableWarnings()))
902 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>");
903 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>");
904 text += tr("Note that Python v3.4 is a prerequisite for installing VapourSynth:").append("<br>").append(LINK(python_url)).append("<br>");
905 const int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Close"), tr("Disable this Warning"));
908 m_preferences->setDisableWarnings(true);
909 PreferencesModel::savePreferences(m_preferences.data());
915 //---------------------------------------
916 // Create the IPC listener thread
917 //---------------------------------------
921 m_ipcThread.reset(new IPCThread_Recv(m_ipcChannel));
922 connect(m_ipcThread.data(), SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
923 m_ipcThread->start();
926 //---------------------------------------
927 // Finish initialization
928 //---------------------------------------
931 setWindowTitle(QString("%1 (%2)").arg(windowTitle(), m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_X64) ? "64-Bit" : "32-Bit"));
933 //Enable drag&drop support for this window, required for Qt v4.8.4+
934 setAcceptDrops(true);
937 m_initialized = true;
939 //Hide the spinner animation
940 if(!m_label[1].isNull())
942 if(!m_animation.isNull())
946 m_label[1]->setVisible(false);
949 //---------------------------------------
950 // Check for Expiration
951 //---------------------------------------
953 if(MUtils::Version::app_build_date().addMonths(6) < MUtils::OS::current_date())
955 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
957 text += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(tr("Your version of Simple x264 Launcher is more than 6 months old!").replace('-', "−"));
958 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("-", "−"));
959 text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace('-', "−"));
960 QMessageBox msgBox(this);
961 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
962 msgBox.setWindowTitle(tr("Update Notification"));
963 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
964 msgBox.setText(text);
965 QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
966 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
967 QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
968 btn2->setEnabled(false);
969 btn3->setVisible(false);
970 QTimer::singleShot(7500, btn2, SLOT(hide()));
971 QTimer::singleShot(7500, btn3, SLOT(show()));
972 if(msgBox.exec() == 0)
974 QTimer::singleShot(0, this, SLOT(checkUpdates()));
978 else if(!parseCommandLineArgs())
981 if(arguments.contains(CLI_PARAM_FIRST_RUN))
983 qWarning("First run -> resetting update check now!");
984 m_recentlyUsed->setLastUpdateCheck(0);
985 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
987 else if(m_recentlyUsed->lastUpdateCheck() + 14 < MUtils::OS::current_date().toJulianDay())
989 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
990 if(!m_preferences->getNoUpdateReminder())
992 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)
994 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1002 if(m_jobList->loadQueuedJobs(m_sysinfo.data()) > 0)
1004 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1005 m_jobList->clearQueuedJobs();
1010 * Update the label position
1012 void MainWindow::updateLabelPos(void)
1014 for(int i = 0; i < 2; i++)
1016 //const QWidget *const viewPort = ui->jobsView->viewport();
1017 const QWidget *const viewPort = dynamic_cast<QWidget*>(m_label[i]->parent());
1020 m_label[i]->setGeometry(0, 0, viewPort->width(), viewPort->height());
1026 * Copy the complete log to the clipboard
1028 void MainWindow::copyLogToClipboard(bool checked)
1030 qDebug("Coyping logfile to clipboard...");
1032 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1034 log->copyToClipboard();
1035 MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
1040 * Process the dropped files
1042 void MainWindow::handlePendingFiles(void)
1044 qDebug("MainWindow::handlePendingFiles");
1046 if(!m_pendingFiles->isEmpty())
1048 QStringList pendingFiles(*m_pendingFiles);
1049 m_pendingFiles->clear();
1050 createJobMultiple(pendingFiles);
1053 qDebug("Leave from MainWindow::handlePendingFiles!");
1057 * Handle incoming IPC command
1059 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1061 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1063 qWarning("Cannot accapt commands at this time -> discarding!");
1067 if((!isVisible()) || m_sysTray->isVisible())
1072 MUtils::GUI::bring_to_front(this);
1075 qDebug("\n---------- IPC ----------");
1076 qDebug("CommandId: %d", command);
1077 for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1079 qDebug("Arguments: %s", iter->toUtf8().constData());
1081 qDebug("The Flags: 0x%08X", flags);
1082 qDebug("---------- IPC ----------\n");
1083 #endif //IPC_LOGGING
1087 case IPC_OPCODE_PING:
1088 qDebug("Received a PING request from another instance!");
1089 MUtils::GUI::blink_window(this, 5, 125);
1091 case IPC_OPCODE_ADD_FILE:
1094 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1096 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1097 if(!m_fileTimer->isActive())
1099 m_fileTimer->setSingleShot(true);
1100 m_fileTimer->start(5000);
1105 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1109 case IPC_OPCODE_ADD_JOB:
1110 if(args.size() >= 3)
1112 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1114 OptionsModel options(m_sysinfo.data());
1115 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1116 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1118 if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1120 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1123 if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
1124 if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
1125 appendJob(args[0], args[1], &options, runImmediately);
1129 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1134 MUTILS_THROW("Unknown command received!");
1139 * Check for new updates
1141 void MainWindow::checkUpdates(void)
1143 ENSURE_APP_IS_READY();
1145 if(countRunningJobs() > 0)
1147 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1151 UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo.data(), update_url);
1152 const int ret = updater->exec();
1154 if(updater->getSuccess())
1156 m_recentlyUsed->setLastUpdateCheck(MUtils::OS::current_date().toJulianDay());
1157 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
1158 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->hide();
1161 if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1163 qWarning("Exitting program to install update...");
1165 QApplication::quit();
1168 MUTILS_DELETE(updater);
1172 * Handle mouse event for version label
1174 void MainWindow::versionLabelMouseClicked(const int &tag)
1178 QTimer::singleShot(0, this, SLOT(showAbout()));
1183 * Handle key event for job list
1185 void MainWindow::jobListKeyPressed(const int &tag)
1190 ui->actionJob_MoveUp->trigger();
1193 ui->actionJob_MoveDown->trigger();
1199 * System tray was activated
1201 void MainWindow::sysTrayActived(void)
1205 MUtils::GUI::bring_to_front(this);
1208 ///////////////////////////////////////////////////////////////////////////////
1210 ///////////////////////////////////////////////////////////////////////////////
1213 * Window shown event
1215 void MainWindow::showEvent(QShowEvent *e)
1217 QMainWindow::showEvent(e);
1221 QTimer::singleShot(0, this, SLOT(init()));
1226 * Window close event
1228 void MainWindow::closeEvent(QCloseEvent *e)
1233 qWarning("Cannot close window at this time!");
1237 //Make sure we have no running jobs left!
1238 if(countRunningJobs() > 0)
1241 if(!m_preferences->getNoSystrayWarning())
1243 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)
1245 m_preferences->setNoSystrayWarning(true);
1246 PreferencesModel::savePreferences(m_preferences.data());
1254 //Save pending jobs for next time, if desired by user
1255 if(countPendingJobs() > 0)
1257 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"));
1260 m_jobList->saveQueuedJobs();
1264 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)
1272 //Delete remaining jobs
1273 while(m_jobList->rowCount(QModelIndex()) > 0)
1275 if((m_jobList->rowCount(QModelIndex()) % 10) == 0)
1277 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1279 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1282 QMessageBox::warning(this, tr("Failed To Exit"), tr("Warning: At least one job could not be deleted!"));
1286 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1287 QMainWindow::closeEvent(e);
1291 * Window resize event
1293 void MainWindow::resizeEvent(QResizeEvent *e)
1295 QMainWindow::resizeEvent(e);
1300 * File dragged over window
1302 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1304 bool accept[2] = {false, false};
1306 foreach(const QString &fmt, event->mimeData()->formats())
1308 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1309 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1312 if(accept[0] && accept[1])
1314 event->acceptProposedAction();
1319 * File dropped onto window
1321 void MainWindow::dropEvent(QDropEvent *event)
1323 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1325 qWarning("Cannot accept dropped files at this time -> discarding!");
1329 QStringList droppedFiles;
1330 QList<QUrl> urls = event->mimeData()->urls();
1332 while(!urls.isEmpty())
1334 QUrl currentUrl = urls.takeFirst();
1335 QFileInfo file(currentUrl.toLocalFile());
1336 if(file.exists() && file.isFile())
1338 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1339 droppedFiles << file.canonicalFilePath();
1343 if(droppedFiles.count() > 0)
1345 m_pendingFiles->append(droppedFiles);
1346 m_pendingFiles->sort();
1347 if(!m_fileTimer->isActive())
1349 m_fileTimer->setSingleShot(true);
1350 m_fileTimer->start(5000);
1355 ///////////////////////////////////////////////////////////////////////////////
1356 // Private functions
1357 ///////////////////////////////////////////////////////////////////////////////
1362 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1365 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed.data(), m_sysinfo.data(), m_preferences.data());
1367 addDialog->setRunImmediately(runImmediately);
1368 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1369 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1370 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1372 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1375 addDialog->setSourceEditable(false);
1376 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1377 addDialog->setApplyToAllVisible(applyToAll);
1380 if(addDialog->exec() == QDialog::Accepted)
1382 sourceFileName = addDialog->sourceFile();
1383 outputFileName = addDialog->outputFile();
1384 runImmediately = addDialog->runImmediately();
1387 *applyToAll = addDialog->applyToAll();
1392 MUTILS_DELETE(addDialog);
1397 * Creates a new job from *multiple* files
1399 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1401 QStringList::ConstIterator iter;
1402 bool applyToAll = false, runImmediately = false;
1405 //Add files individually
1406 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1408 runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1409 QString sourceFileName(*iter), outputFileName;
1410 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1412 if(appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
1420 //Add remaining files
1421 while(applyToAll && (iter != filePathIn.constEnd()))
1423 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1424 const QString sourceFileName = *iter;
1425 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
1426 if(!appendJob(sourceFileName, outputFileName, m_options.data(), runImmediatelyTmp))
1439 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1442 EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo.data(), m_preferences.data());
1443 QModelIndex newIndex = m_jobList->insertJob(thrd);
1445 if(newIndex.isValid())
1449 ui->jobsView->selectRow(newIndex.row());
1450 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1451 m_jobList->startJob(newIndex);
1457 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1462 * Jobs that are not completed (or failed, or aborted) yet
1464 unsigned int MainWindow::countPendingJobs(void)
1466 unsigned int count = 0;
1467 const int rows = m_jobList->rowCount(QModelIndex());
1469 for(int i = 0; i < rows; i++)
1471 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1472 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1482 * Jobs that are still active, i.e. not terminated or enqueued
1484 unsigned int MainWindow::countRunningJobs(void)
1486 unsigned int count = 0;
1487 const int rows = m_jobList->rowCount(QModelIndex());
1489 for(int i = 0; i < rows; i++)
1491 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1492 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1502 * Update all buttons with respect to current job status
1504 void MainWindow::updateButtons(JobStatus status)
1506 qDebug("MainWindow::updateButtons(void)");
1508 ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1509 ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1510 ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1511 ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1513 ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1514 ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1515 ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1516 ui->actionJob_MoveUp->setEnabled(status != JobStatus_Undefined);
1517 ui->actionJob_MoveDown->setEnabled(status != JobStatus_Undefined);
1519 ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1520 ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1521 ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1522 ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1524 ui->editDetails->setEnabled(status != JobStatus_Paused);
1528 * Update the taskbar with current job status
1530 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1532 qDebug("MainWindow::updateTaskbar(void)");
1534 if(m_taskbar.isNull())
1536 return; /*taskbar object not created yet*/
1541 case JobStatus_Undefined:
1542 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE);
1544 case JobStatus_Aborting:
1545 case JobStatus_Starting:
1546 case JobStatus_Pausing:
1547 case JobStatus_Resuming:
1548 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_INTERMEDIATE);
1550 case JobStatus_Aborted:
1551 case JobStatus_Failed:
1552 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR);
1554 case JobStatus_Paused:
1555 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_PAUSED);
1558 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL);
1564 case JobStatus_Aborting:
1565 case JobStatus_Starting:
1566 case JobStatus_Pausing:
1567 case JobStatus_Resuming:
1570 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
1574 m_taskbar->setOverlayIcon(icon.isNull() ? NULL : &icon);
1578 * Parse command-line arguments
1580 bool MainWindow::parseCommandLineArgs(void)
1582 const MUtils::OS::ArgumentMap &args = MUtils::OS::arguments();
1585 bool commandSent = false;
1588 if(args.contains(CLI_PARAM_FORCE_START))
1590 flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1592 if(args.contains(CLI_PARAM_FORCE_ENQUEUE))
1594 flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1597 //Process all command-line arguments
1598 if(args.contains(CLI_PARAM_ADD_FILE))
1600 foreach(const QString &fileName, args.values(CLI_PARAM_ADD_FILE))
1602 handleCommand(IPC_OPCODE_ADD_FILE, QStringList() << fileName, flags);
1606 if(args.contains(CLI_PARAM_ADD_JOB))
1608 foreach(const QString &options, args.values(CLI_PARAM_ADD_JOB))
1610 const QStringList optionValues = options.split('|', QString::SkipEmptyParts);
1611 if(optionValues.count() == 3)
1613 handleCommand(IPC_OPCODE_ADD_JOB, optionValues, flags);
1617 qWarning("Invalid number of arguments for parameter \"--%s\" detected!", CLI_PARAM_ADD_JOB);