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>
63 const char *home_url = "http://muldersoft.com/";
64 const char *update_url = "https://github.com/lordmulder/Simple-x264-Launcher/releases/latest";
65 const char *tpl_last = "<LAST_USED>";
67 #define SET_FONT_BOLD(WIDGET,BOLD) do { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); } while(0)
68 #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)
69 #define LINK(URL) "<a href=\"" URL "\">" URL "</a>"
70 #define INIT_ERROR_EXIT() do { m_status = STATUS_EXITTING; close(); qApp->exit(-1); return; } while(0)
71 #define ENSURE_APP_IS_IDLE() do { if(m_status != STATUS_IDLE) { x264_beep(x264_beep_warning); qWarning("Cannot perfrom this action at this time!"); return; } } while(0)
72 #define NEXT(X) ((*reinterpret_cast<int*>(&(X)))++)
73 #define SETUP_WEBLINK(OBJ, URL) do { (OBJ)->setData(QVariant(QUrl(URL))); connect((OBJ), SIGNAL(triggered()), this, SLOT(showWebLink())); } while(0)
75 ///////////////////////////////////////////////////////////////////////////////
76 // Constructor & Destructor
77 ///////////////////////////////////////////////////////////////////////////////
82 MainWindow::MainWindow(const x264_cpu_t *const cpuFeatures, IPC *ipc)
88 m_pendingFiles(new QStringList()),
91 m_status(STATUS_PRE_INIT),
92 ui(new Ui::MainWindow())
94 //Init the dialog, from the .ui file
96 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
99 qRegisterMetaType<QUuid>("QUuid");
100 qRegisterMetaType<QUuid>("DWORD");
101 qRegisterMetaType<JobStatus>("JobStatus");
103 //Create and initialize the sysinfo object
104 m_sysinfo = new SysinfoModel();
105 m_sysinfo->setAppPath(QApplication::applicationDirPath());
106 m_sysinfo->setMMXSupport(cpuFeatures->mmx && cpuFeatures->mmx2);
107 m_sysinfo->setSSESupport(cpuFeatures->sse && cpuFeatures->mmx2); //SSE implies MMX2
108 m_sysinfo->setX64Support(cpuFeatures->x64 && cpuFeatures->sse2); //X64 implies SSE2
111 m_preferences = new PreferencesModel();
112 PreferencesModel::loadPreferences(m_preferences);
115 m_recentlyUsed = new RecentlyUsed();
116 RecentlyUsed::loadRecentlyUsed(m_recentlyUsed);
118 //Create options object
119 m_options = new OptionsModel(m_sysinfo);
120 OptionsModel::loadTemplate(m_options, QString::fromLatin1(tpl_last));
122 //Freeze minimum size
123 setMinimumSize(size());
124 ui->splitter->setSizes(QList<int>() << 16 << 196);
127 ui->labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time())));
131 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
132 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
134 else if(x264_is_prerelease())
136 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
140 m_jobList = new JobListModel(m_preferences);
141 connect(m_jobList, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
142 ui->jobsView->setModel(m_jobList);
145 ui->jobsView->horizontalHeader()->setSectionHidden(3, true);
146 ui->jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
147 ui->jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
148 ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
149 ui->jobsView->horizontalHeader()->resizeSection(1, 150);
150 ui->jobsView->horizontalHeader()->resizeSection(2, 90);
151 ui->jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
152 connect(ui->jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
155 m_inputFilter_jobList = new InputEventFilter(ui->jobsView);
156 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Up, 1);
157 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Down, 2);
158 connect(m_inputFilter_jobList, SIGNAL(keyPressed(int)), this, SLOT(jobListKeyPressed(int)));
160 //Setup mouse listener
161 m_inputFilter_version = new InputEventFilter(ui->labelBuildDate);
162 m_inputFilter_version->addMouseFilter(Qt::LeftButton, 0);
163 m_inputFilter_version->addMouseFilter(Qt::RightButton, 0);
164 connect(m_inputFilter_version, SIGNAL(mouseClicked(int)), this, SLOT(versionLabelMouseClicked(int)));
166 //Create context menu
167 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), ui->logView);
168 actionClipboard->setEnabled(false);
169 ui->logView->addAction(actionClipboard);
170 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
171 ui->jobsView->addActions(ui->menuJob->actions());
174 connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed() ));
175 connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed() ));
176 connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed() ));
177 connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
178 connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed() ));
179 connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed() ));
180 connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed() ));
181 connect(ui->actionJob_MoveUp, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
182 connect(ui->actionJob_MoveDown, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
185 connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
186 connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
187 connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
188 connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
191 SETUP_WEBLINK(ui->actionWebMulder, home_url);
192 SETUP_WEBLINK(ui->actionWebX264, "http://www.videolan.org/developers/x264.html");
193 SETUP_WEBLINK(ui->actionWebX265, "http://www.videolan.org/developers/x265.html");
194 SETUP_WEBLINK(ui->actionWebKomisar, "http://komisar.gin.by/");
195 SETUP_WEBLINK(ui->actionWebVideoLAN, "http://download.videolan.org/pub/x264/binaries/");
196 SETUP_WEBLINK(ui->actionWebJEEB, "http://x264.fushizen.eu/");
197 SETUP_WEBLINK(ui->actionWebFreeCodecs, "http://www.free-codecs.com/x264_video_codec_download.htm");
198 SETUP_WEBLINK(ui->actionWebX265BinRU, "http://goo.gl/xRS6AW");
199 SETUP_WEBLINK(ui->actionWebX265BinEU, "http://builds.x265.eu/");
200 SETUP_WEBLINK(ui->actionWebX265BinORG, "http://chromashift.org/x265_builds/");
201 SETUP_WEBLINK(ui->actionWebX265BinFF, "http://ffmpeg.zeranoe.com/builds/");
202 SETUP_WEBLINK(ui->actionWebAvisynth32, "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/");
203 SETUP_WEBLINK(ui->actionWebAvisynth64, "http://code.google.com/p/avisynth64/downloads/list");
204 SETUP_WEBLINK(ui->actionWebAvisynthPlus, "http://www.avs-plus.net/");
205 SETUP_WEBLINK(ui->actionWebVapourSynth, "http://www.vapoursynth.com/");
206 SETUP_WEBLINK(ui->actionWebVapourSynthDocs, "http://www.vapoursynth.com/doc/");
207 SETUP_WEBLINK(ui->actionWebWiki, "http://mewiki.project357.com/wiki/X264_Settings");
208 SETUP_WEBLINK(ui->actionWebBluRay, "http://www.x264bluray.com/");
209 SETUP_WEBLINK(ui->actionWebAvsWiki, "http://avisynth.nl/index.php/Main_Page#Usage");
210 SETUP_WEBLINK(ui->actionWebSupport, "http://forum.doom9.org/showthread.php?t=144140");
211 SETUP_WEBLINK(ui->actionWebSecret, "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
213 //Create floating label
214 m_label = new QLabel(ui->jobsView->viewport());
215 m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
216 m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
217 SET_TEXT_COLOR(m_label, Qt::darkGray);
218 SET_FONT_BOLD(m_label, true);
219 m_label->setVisible(true);
220 m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
221 m_label->addActions(ui->jobsView->actions());
222 connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
229 MainWindow::~MainWindow(void)
231 m_status = STATUS_EXITTING;
232 OptionsModel::saveTemplate(m_options, QString::fromLatin1(tpl_last));
234 X264_DELETE(m_jobList);
235 X264_DELETE(m_options);
236 X264_DELETE(m_pendingFiles);
237 X264_DELETE(m_label);
238 X264_DELETE(m_inputFilter_jobList);
239 X264_DELETE(m_inputFilter_version);
241 while(!m_toolsList.isEmpty())
243 QFile *temp = m_toolsList.takeFirst();
247 if(m_ipc->isListening())
249 m_ipc->stopListening();
252 X264_DELETE(m_preferences);
253 X264_DELETE(m_recentlyUsed);
254 X264_DELETE(m_sysinfo);
256 VapourSynthCheckThread::unload();
257 AvisynthCheckThread::unload();
262 ///////////////////////////////////////////////////////////////////////////////
264 ///////////////////////////////////////////////////////////////////////////////
267 * The "add" button was clicked
269 void MainWindow::addButtonPressed()
271 ENSURE_APP_IS_IDLE();
272 m_status = STATUS_BLOCKED;
274 qDebug("MainWindow::addButtonPressed");
275 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
276 QString sourceFileName, outputFileName;
278 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
280 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
283 m_status = STATUS_IDLE;
287 * The "open" action was triggered
289 void MainWindow::openActionTriggered()
291 ENSURE_APP_IS_IDLE();
292 m_status = STATUS_BLOCKED;
294 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
295 if(!fileList.empty())
297 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
298 if(fileList.count() > 1)
300 createJobMultiple(fileList);
304 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
305 QString sourceFileName(fileList.first()), outputFileName;
306 if(createJob(sourceFileName, outputFileName, m_options, runImmediately))
308 appendJob(sourceFileName, outputFileName, m_options, runImmediately);
313 m_status = STATUS_IDLE;
317 * The "start" button was clicked
319 void MainWindow::startButtonPressed(void)
321 ENSURE_APP_IS_IDLE();
322 m_jobList->startJob(ui->jobsView->currentIndex());
326 * The "abort" button was clicked
328 void MainWindow::abortButtonPressed(void)
330 ENSURE_APP_IS_IDLE();
331 m_status = STATUS_BLOCKED;
333 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)
335 m_jobList->abortJob(ui->jobsView->currentIndex());
338 m_status = STATUS_IDLE;
342 * The "delete" button was clicked
344 void MainWindow::deleteButtonPressed(void)
346 ENSURE_APP_IS_IDLE();
347 m_jobList->deleteJob(ui->jobsView->currentIndex());
348 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
352 * The "browse" button was clicked
354 void MainWindow::browseButtonPressed(void)
356 ENSURE_APP_IS_IDLE();
357 m_status = STATUS_BLOCKED;
359 QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
360 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
362 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
366 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
369 m_status = STATUS_IDLE;
373 * The "browse" button was clicked
375 void MainWindow::moveButtonPressed(void)
377 ENSURE_APP_IS_IDLE();
379 if(sender() == ui->actionJob_MoveUp)
381 qDebug("Move job %d (direction: UP)", ui->jobsView->currentIndex().row());
382 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_UP))
384 x264_beep(x264_beep_error);
386 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
388 else if(sender() == ui->actionJob_MoveDown)
390 qDebug("Move job %d (direction: DOWN)", ui->jobsView->currentIndex().row());
391 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_DOWN))
393 x264_beep(x264_beep_error);
395 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
399 qWarning("[moveButtonPressed] Error: Unknown sender!");
404 * The "pause" button was clicked
406 void MainWindow::pauseButtonPressed(bool checked)
408 ENSURE_APP_IS_IDLE();
412 m_jobList->pauseJob(ui->jobsView->currentIndex());
416 m_jobList->resumeJob(ui->jobsView->currentIndex());
421 * The "restart" button was clicked
423 void MainWindow::restartButtonPressed(void)
425 ENSURE_APP_IS_IDLE();
427 const QModelIndex index = ui->jobsView->currentIndex();
428 const OptionsModel *options = m_jobList->getJobOptions(index);
429 QString sourceFileName = m_jobList->getJobSourceFile(index);
430 QString outputFileName = m_jobList->getJobOutputFile(index);
432 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
434 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
435 OptionsModel *tempOptions = new OptionsModel(*options);
436 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
438 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
440 X264_DELETE(tempOptions);
445 * Job item selected by user
447 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
449 qDebug("Job selected: %d", current.row());
451 if(ui->logView->model())
453 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
456 if(current.isValid())
458 ui->logView->setModel(m_jobList->getLogFile(current));
459 connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
460 ui->logView->actions().first()->setEnabled(true);
461 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
463 ui->progressBar->setValue(m_jobList->getJobProgress(current));
464 ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
465 updateButtons(m_jobList->getJobStatus(current));
466 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
470 ui->logView->setModel(NULL);
471 ui->logView->actions().first()->setEnabled(false);
472 ui->progressBar->setValue(0);
473 ui->editDetails->clear();
474 updateButtons(JobStatus_Undefined);
475 updateTaskbar(JobStatus_Undefined, QIcon());
478 ui->progressBar->repaint();
482 * Handle update of job info (status, progress, details, etc)
484 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
486 int selected = ui->jobsView->currentIndex().row();
488 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
490 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
492 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
495 qDebug("Current job changed status!");
496 updateButtons(status);
497 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
499 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
501 if(m_preferences->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
502 if(m_preferences->getShutdownComputer()) QTimer::singleShot(0, this, SLOT(shutdownComputer()));
503 if(m_preferences->getSaveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
507 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
509 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
513 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
514 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
519 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
521 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
525 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
533 * Handle new log file content
535 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
537 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
543 void MainWindow::showAbout(void)
545 ENSURE_APP_IS_IDLE();
546 m_status = STATUS_BLOCKED;
548 if(AboutDialog *aboutDialog = new AboutDialog(this))
551 X264_DELETE(aboutDialog);
554 m_status = STATUS_IDLE;
560 void MainWindow::showWebLink(void)
562 ENSURE_APP_IS_IDLE();
564 if(QObject *obj = QObject::sender())
566 if(QAction *action = dynamic_cast<QAction*>(obj))
568 if(action->data().type() == QVariant::Url)
570 QDesktopServices::openUrl(action->data().toUrl());
577 * Pereferences dialog
579 void MainWindow::showPreferences(void)
581 ENSURE_APP_IS_IDLE();
582 m_status = STATUS_BLOCKED;
584 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences, m_sysinfo);
587 X264_DELETE(preferences);
588 m_status = STATUS_IDLE;
592 * Launch next job, after running job has finished
594 void MainWindow::launchNextJob(void)
596 qDebug("launchNextJob(void)");
598 const int rows = m_jobList->rowCount(QModelIndex());
600 if(countRunningJobs() >= m_preferences->getMaxRunningJobCount())
602 qDebug("Still have too many jobs running, won't launch next one yet!");
606 int startIdx= ui->jobsView->currentIndex().isValid() ? qBound(0, ui->jobsView->currentIndex().row(), rows-1) : 0;
608 for(int i = 0; i < rows; i++)
610 int currentIdx = (i + startIdx) % rows;
611 JobStatus status = m_jobList->getJobStatus(m_jobList->index(currentIdx, 0, QModelIndex()));
612 if(status == JobStatus_Enqueued)
614 if(m_jobList->startJob(m_jobList->index(currentIdx, 0, QModelIndex())))
616 ui->jobsView->selectRow(currentIdx);
622 qWarning("No enqueued jobs left!");
626 * Save log to text file
628 void MainWindow::saveLogFile(const QModelIndex &index)
632 if(LogFileModel *log = m_jobList->getLogFile(index))
634 QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
635 QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
636 QFile outFile(logFilePath);
637 if(outFile.open(QIODevice::WriteOnly))
639 QTextStream outStream(&outFile);
640 outStream.setCodec("UTF-8");
641 outStream.setGenerateByteOrderMark(true);
643 const int rows = log->rowCount(QModelIndex());
644 for(int i = 0; i < rows; i++)
646 outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
652 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
659 * Shut down the computer (with countdown)
661 void MainWindow::shutdownComputer(void)
663 qDebug("shutdownComputer(void)");
665 if((m_status != STATUS_IDLE) && (m_status != STATUS_EXITTING))
667 qWarning("Cannot shutdown computer at this time!");
671 if(countPendingJobs() > 0)
673 qDebug("Still have pending jobs, won't shutdown yet!");
677 const x264_status_t previousStatus = m_status;
678 m_status = STATUS_BLOCKED;
680 const int iTimeout = 30;
681 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
682 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
684 qWarning("Initiating shutdown sequence!");
686 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
687 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
688 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
689 progressDialog.setModal(true);
690 progressDialog.setAutoClose(false);
691 progressDialog.setAutoReset(false);
692 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
693 progressDialog.setWindowTitle(windowTitle());
694 progressDialog.setCancelButton(cancelButton);
695 progressDialog.show();
697 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
698 QApplication::setOverrideCursor(Qt::WaitCursor);
699 x264_play_sound(IDR_WAVE1, false);
700 QApplication::restoreOverrideCursor();
703 timer.setInterval(1000);
706 QEventLoop eventLoop(this);
707 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
708 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
710 for(int i = 1; i <= iTimeout; i++)
713 if(progressDialog.wasCanceled())
715 progressDialog.close();
716 m_status = previousStatus;
719 progressDialog.setValue(i+1);
720 progressDialog.setLabelText(text.arg(iTimeout-i));
721 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
722 QApplication::processEvents();
723 x264_play_sound(((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), false);
726 qWarning("Shutting down !!!");
727 m_status = previousStatus;
729 if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true))
731 qApp->closeAllWindows();
737 * Main initialization function (called only once!)
739 void MainWindow::init(void)
741 if(m_status != STATUS_PRE_INIT)
743 qWarning("Already initialized -> skipping!");
749 //---------------------------------------
750 // Create the IPC listener thread
751 //---------------------------------------
753 if(m_ipc->isInitialized())
755 connect(m_ipc, SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
756 m_ipc->startListening();
759 //---------------------------------------
760 // Check required binaries
761 //---------------------------------------
763 QStringList binFiles;
764 for(OptionsModel::EncArch arch = OptionsModel::EncArch_x32; arch <= OptionsModel::EncArch_x64; NEXT(arch))
766 for(OptionsModel::EncVariant varnt = OptionsModel::EncVariant_LoBit; varnt <= OptionsModel::EncVariant_HiBit; NEXT(varnt))
768 binFiles << ENC_BINARY(m_sysinfo, OptionsModel::EncType_X264, arch, varnt);
770 binFiles << AVS_BINARY(m_sysinfo, arch == OptionsModel::EncArch_x64);
773 qDebug("[Validating binaries]");
774 for(QStringList::ConstIterator iter = binFiles.constBegin(); iter != binFiles.constEnd(); iter++)
776 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
777 QFile *file = new QFile(*iter);
778 qDebug("%s", file->fileName().toLatin1().constData());
779 if(file->open(QIODevice::ReadOnly))
781 if(!x264_is_executable(file->fileName()))
783 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("-", "−"));
784 qFatal(QString("Binary is invalid: %1").arg(file->fileName()).toLatin1().constData());
792 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("-", "−"));
793 qFatal(QString("Binary not found: %1/toolset/%2").arg(m_sysinfo->getAppPath(), file->fileName()).toLatin1().constData());
800 //---------------------------------------
801 // Check x265 binaries
802 //---------------------------------------
805 for(OptionsModel::EncArch arch = OptionsModel::EncArch_x32; arch <= OptionsModel::EncArch_x64; NEXT(arch))
807 for(OptionsModel::EncVariant varnt = OptionsModel::EncVariant_LoBit; varnt <= OptionsModel::EncVariant_HiBit; NEXT(varnt))
809 binFiles << ENC_BINARY(m_sysinfo, OptionsModel::EncType_X265, arch, varnt);
813 qDebug("[Checking for x265 support]");
814 bool bHaveX265 = true;
815 for(QStringList::ConstIterator iter = binFiles.constBegin(); iter != binFiles.constEnd(); iter++)
817 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
818 QFile *file = new QFile(*iter);
819 qDebug("%s", file->fileName().toLatin1().constData());
820 if(file->open(QIODevice::ReadOnly))
822 if(x264_is_executable(file->fileName()))
830 qWarning("x265 binaries not found or incomplete -> disable x265 support!");
835 qDebug("x265 support is officially enabled now!");
836 m_sysinfo->set256Support(true);
840 //---------------------------------------
841 // Check for portable mode
842 //---------------------------------------
847 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
848 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
849 if(writeTest.open(QIODevice::WriteOnly))
851 ok = (writeTest.write(data) == strlen(data));
856 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"));
857 if(val != 1) INIT_ERROR_EXIT();
862 if(x264_is_prerelease())
864 qsrand(time(NULL)); int rnd = qrand() % 3;
865 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);
866 if(rnd != val) INIT_ERROR_EXIT();
869 //---------------------------------------
870 // Check CPU capabilities
871 //---------------------------------------
873 const QStringList arguments = x264_arguments();
875 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
876 if(!m_sysinfo->hasMMXSupport())
878 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"));
879 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
882 else if(!m_sysinfo->hasSSESupport())
884 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
885 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"));
886 if(val != 1) INIT_ERROR_EXIT();
889 //Skip version check (not recommended!)
890 if(CLIParser::checkFlag(CLI_PARAM_SKIP_X264_CHECK, arguments))
892 qWarning("x264 version check disabled, you have been warned!\n");
893 m_preferences->setSkipVersionTest(true);
896 //Don't abort encoding process on timeout (not recommended!)
897 if(CLIParser::checkFlag(CLI_PARAM_NO_DEADLOCK, arguments))
899 qWarning("Deadlock detection disabled, you have been warned!\n");
900 m_preferences->setAbortOnTimeout(false);
903 //---------------------------------------
904 // Check Avisynth support
905 //---------------------------------------
907 if(!CLIParser::checkFlag(CLI_PARAM_SKIP_AVS_CHECK, arguments))
909 qDebug("[Check for Avisynth support]");
910 volatile double avisynthVersion = 0.0;
911 const int result = AvisynthCheckThread::detect(&avisynthVersion);
914 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
915 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
916 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
917 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
918 if(val != 1) INIT_ERROR_EXIT();
920 if(result && (avisynthVersion >= 2.5))
922 qDebug("Avisynth support is officially enabled now!");
923 m_sysinfo->setAVSSupport(true);
927 if(!m_preferences->getDisableWarnings())
929 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>");
930 text += tr("Please download and install Avisynth:").append("<br>").append(LINK("http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/"));
931 int val = QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Close"), tr("Disable this Warning"));
934 m_preferences->setDisableWarnings(true);
935 PreferencesModel::savePreferences(m_preferences);
943 //---------------------------------------
944 // Check VapurSynth support
945 //---------------------------------------
947 if(!CLIParser::checkFlag(CLI_PARAM_SKIP_VPS_CHECK, arguments))
949 qDebug("[Check for VapourSynth support]");
950 QString vapoursynthPath;
951 const int result = VapourSynthCheckThread::detect(vapoursynthPath);
954 QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
955 text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
956 text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
957 const int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Quit"), tr("Ignore"));
958 if(val != 1) INIT_ERROR_EXIT();
960 if(result && (!vapoursynthPath.isEmpty()))
962 qDebug("VapourSynth support is officially enabled now!");
963 m_sysinfo->setVPSSupport(true);
964 m_sysinfo->setVPSPath(vapoursynthPath);
968 if(!m_preferences->getDisableWarnings())
970 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>");
971 text += tr("Please download and install VapourSynth for Windows (R19 or later):").append("<br>").append(LINK("http://www.vapoursynth.com/")).append("<br><br>");
972 text += tr("Note that Python 3.3 (x86) is a prerequisite for installing VapourSynth:").append("<br>").append(LINK("http://www.python.org/getit/")).append("<br>");
973 const int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "−"), tr("Close"), tr("Disable this Warning"));
976 m_preferences->setDisableWarnings(true);
977 PreferencesModel::savePreferences(m_preferences);
984 //---------------------------------------
985 // Check for Expiration
986 //---------------------------------------
988 if(x264_version_date().addMonths(6) < x264_current_date_safe())
991 text += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(tr("Your version of Simple x264 Launcher is more than 6 months old!").replace("-", "−"));
992 text += QString("<nobr><tt>%1<br><a href=\"%2\">%2</a><br><br>").arg(tr("You can download the most recent version from the official web-site now:").replace("-", "−"), QString::fromLatin1(update_url));
993 text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace("-", "−"));
994 QMessageBox msgBox(this);
995 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
996 msgBox.setWindowTitle(tr("Update Notification"));
997 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
998 msgBox.setText(text);
999 QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
1000 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
1001 QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
1002 btn2->setEnabled(false);
1003 btn3->setVisible(false);
1004 QTimer::singleShot(7500, btn2, SLOT(hide()));
1005 QTimer::singleShot(7500, btn3, SLOT(show()));
1006 if(msgBox.exec() == 0)
1008 m_status = STATUS_IDLE;
1009 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1014 //---------------------------------------
1015 // Finish initialization
1016 //---------------------------------------
1019 setWindowTitle(QString("%1 (%2)").arg(windowTitle(), m_sysinfo->hasX64Support() ? "64-Bit" : "32-Bit"));
1021 //Enable drag&drop support for this window, required for Qt v4.8.4+
1022 setAcceptDrops(true);
1025 m_status = STATUS_IDLE;
1027 //Try adding files from command-line
1028 if(!parseCommandLineArgs())
1031 if((!m_preferences->getNoUpdateReminder()) && (m_recentlyUsed->lastUpdateCheck() + 14 < x264_current_date_safe().toJulianDay()))
1033 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)
1035 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1042 if(m_jobList->loadQueuedJobs(m_sysinfo) > 0)
1044 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1045 m_jobList->clearQueuedJobs();
1050 * Update the label position
1052 void MainWindow::updateLabelPos(void)
1054 const QWidget *const viewPort = ui->jobsView->viewport();
1055 m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
1059 * Copy the complete log to the clipboard
1061 void MainWindow::copyLogToClipboard(bool checked)
1063 qDebug("copyLogToClipboard");
1065 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1067 log->copyToClipboard();
1068 x264_beep(x264_beep_info);
1073 * Process the dropped files
1075 void MainWindow::handlePendingFiles(void)
1077 if((m_status == STATUS_IDLE) || (m_status == STATUS_AWAITING))
1079 qDebug("MainWindow::handlePendingFiles");
1080 if(!m_pendingFiles->isEmpty())
1082 QStringList pendingFiles(*m_pendingFiles);
1083 m_pendingFiles->clear();
1084 createJobMultiple(pendingFiles);
1086 qDebug("Leave from MainWindow::handlePendingFiles!");
1087 m_status = STATUS_IDLE;
1091 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1093 if((m_status != STATUS_IDLE) && (m_status != STATUS_AWAITING))
1095 qWarning("Cannot accapt commands at this time -> discarding!");
1099 x264_bring_to_front(this);
1102 qDebug("\n---------- IPC ----------");
1103 qDebug("CommandId: %d", command);
1104 for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1106 qDebug("Arguments: %s", iter->toUtf8().constData());
1108 qDebug("The Flags: 0x%08X", flags);
1109 qDebug("---------- IPC ----------\n");
1110 #endif //IPC_LOGGING
1114 case IPC_OPCODE_PING:
1115 qDebug("Received a PING request from another instance!");
1116 x264_blink_window(this, 5, 125);
1118 case IPC_OPCODE_ADD_FILE:
1121 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1123 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1124 if(m_status != STATUS_AWAITING)
1126 m_status = STATUS_AWAITING;
1127 QTimer::singleShot(5000, this, SLOT(handlePendingFiles()));
1132 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1136 case IPC_OPCODE_ADD_JOB:
1137 if(args.size() >= 3)
1139 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1141 OptionsModel options(m_sysinfo);
1142 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1143 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1145 if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1147 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1150 if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
1151 if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
1152 appendJob(args[0], args[1], &options, runImmediately);
1156 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1161 THROW("Unknown command received!");
1165 void MainWindow::checkUpdates(void)
1167 ENSURE_APP_IS_IDLE();
1168 m_status = STATUS_BLOCKED;
1170 if(countRunningJobs() > 0)
1172 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1173 m_status = STATUS_IDLE;
1177 UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo);
1178 const int ret = updater->exec();
1180 if(updater->getSuccess())
1182 m_recentlyUsed->setLastUpdateCheck(x264_current_date_safe().toJulianDay());
1183 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed);
1186 if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1188 m_status = STATUS_EXITTING;
1189 qWarning("Exitting program to install update...");
1191 QApplication::quit();
1194 X264_DELETE(updater);
1196 if(m_status != STATUS_EXITTING)
1198 m_status = STATUS_IDLE;
1202 void MainWindow::versionLabelMouseClicked(const int &tag)
1206 QTimer::singleShot(0, this, SLOT(showAbout()));
1210 void MainWindow::jobListKeyPressed(const int &tag)
1215 ui->actionJob_MoveUp->trigger();
1218 ui->actionJob_MoveDown->trigger();
1223 ///////////////////////////////////////////////////////////////////////////////
1225 ///////////////////////////////////////////////////////////////////////////////
1228 * Window shown event
1230 void MainWindow::showEvent(QShowEvent *e)
1232 QMainWindow::showEvent(e);
1234 if(m_status == STATUS_PRE_INIT)
1236 QTimer::singleShot(0, this, SLOT(init()));
1241 * Window close event
1243 void MainWindow::closeEvent(QCloseEvent *e)
1245 if((m_status != STATUS_IDLE) && (m_status != STATUS_EXITTING))
1248 qWarning("Cannot close window at this time!");
1252 //Make sure we have no running jobs left!
1253 if(m_status != STATUS_EXITTING)
1255 if(countRunningJobs() > 0)
1258 m_status = STATUS_BLOCKED;
1259 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not exit while there still are running jobs!"));
1260 m_status = STATUS_IDLE;
1264 //Save pending jobs for next time, if desired by user
1265 if(countPendingJobs() > 0)
1267 m_status = STATUS_BLOCKED;
1268 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"));
1271 m_jobList->saveQueuedJobs();
1275 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)
1278 m_status = STATUS_IDLE;
1285 //Delete remaining jobs
1286 while(m_jobList->rowCount(QModelIndex()) > 0)
1288 if((m_jobList->rowCount(QModelIndex()) % 10) == 0)
1290 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1292 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1295 m_status = STATUS_BLOCKED;
1296 QMessageBox::warning(this, tr("Failed To Exit"), tr("Warning: At least one job could not be deleted!"));
1297 m_status = STATUS_IDLE;
1301 m_status = STATUS_EXITTING;
1302 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1303 QMainWindow::closeEvent(e);
1307 * Window resize event
1309 void MainWindow::resizeEvent(QResizeEvent *e)
1311 QMainWindow::resizeEvent(e);
1316 * Win32 message filter
1318 bool MainWindow::winEvent(MSG *message, long *result)
1320 return WinSevenTaskbar::handleWinEvent(message, result);
1324 * File dragged over window
1326 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1328 bool accept[2] = {false, false};
1330 foreach(const QString &fmt, event->mimeData()->formats())
1332 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1333 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1336 if(accept[0] && accept[1])
1338 event->acceptProposedAction();
1343 * File dropped onto window
1345 void MainWindow::dropEvent(QDropEvent *event)
1347 if((m_status != STATUS_IDLE) && (m_status != STATUS_AWAITING))
1349 qWarning("Cannot accept drooped files at this time -> discarding!");
1353 QStringList droppedFiles;
1354 QList<QUrl> urls = event->mimeData()->urls();
1356 while(!urls.isEmpty())
1358 QUrl currentUrl = urls.takeFirst();
1359 QFileInfo file(currentUrl.toLocalFile());
1360 if(file.exists() && file.isFile())
1362 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1363 droppedFiles << file.canonicalFilePath();
1367 if(droppedFiles.count() > 0)
1369 m_pendingFiles->append(droppedFiles);
1370 m_pendingFiles->sort();
1371 if(m_status != STATUS_AWAITING)
1373 m_status = STATUS_AWAITING;
1374 QTimer::singleShot(0, this, SLOT(handlePendingFiles()));
1379 ///////////////////////////////////////////////////////////////////////////////
1380 // Private functions
1381 ///////////////////////////////////////////////////////////////////////////////
1386 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1389 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed, m_sysinfo, m_preferences);
1391 addDialog->setRunImmediately(runImmediately);
1392 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1393 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1394 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1396 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1399 addDialog->setSourceEditable(false);
1400 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1401 addDialog->setApplyToAllVisible(applyToAll);
1404 if(addDialog->exec() == QDialog::Accepted)
1406 sourceFileName = addDialog->sourceFile();
1407 outputFileName = addDialog->outputFile();
1408 runImmediately = addDialog->runImmediately();
1411 *applyToAll = addDialog->applyToAll();
1416 X264_DELETE(addDialog);
1421 * Creates a new job from *multiple* files
1423 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1425 QStringList::ConstIterator iter;
1426 bool applyToAll = false, runImmediately = false;
1429 //Add files individually
1430 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1432 runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1433 QString sourceFileName(*iter), outputFileName;
1434 if(createJob(sourceFileName, outputFileName, m_options, runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1436 if(appendJob(sourceFileName, outputFileName, m_options, runImmediately))
1444 //Add remaining files
1445 while(applyToAll && (iter != filePathIn.constEnd()))
1447 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1448 const QString sourceFileName = *iter;
1449 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
1450 if(!appendJob(sourceFileName, outputFileName, m_options, runImmediatelyTmp))
1463 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1466 EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo, m_preferences);
1467 QModelIndex newIndex = m_jobList->insertJob(thrd);
1469 if(newIndex.isValid())
1473 ui->jobsView->selectRow(newIndex.row());
1474 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1475 m_jobList->startJob(newIndex);
1481 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1486 * Jobs that are not completed (or failed, or aborted) yet
1488 unsigned int MainWindow::countPendingJobs(void)
1490 unsigned int count = 0;
1491 const int rows = m_jobList->rowCount(QModelIndex());
1493 for(int i = 0; i < rows; i++)
1495 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1496 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1506 * Jobs that are still active, i.e. not terminated or enqueued
1508 unsigned int MainWindow::countRunningJobs(void)
1510 unsigned int count = 0;
1511 const int rows = m_jobList->rowCount(QModelIndex());
1513 for(int i = 0; i < rows; i++)
1515 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1516 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1526 * Update all buttons with respect to current job status
1528 void MainWindow::updateButtons(JobStatus status)
1530 qDebug("MainWindow::updateButtons(void)");
1532 ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1533 ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1534 ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1535 ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1537 ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1538 ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1539 ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1540 ui->actionJob_MoveUp->setEnabled(status != JobStatus_Undefined);
1541 ui->actionJob_MoveDown->setEnabled(status != JobStatus_Undefined);
1543 ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1544 ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1545 ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1546 ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1548 ui->editDetails->setEnabled(status != JobStatus_Paused);
1552 * Update the taskbar with current job status
1554 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1556 qDebug("MainWindow::updateTaskbar(void)");
1560 case JobStatus_Undefined:
1561 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNoState);
1563 case JobStatus_Aborting:
1564 case JobStatus_Starting:
1565 case JobStatus_Pausing:
1566 case JobStatus_Resuming:
1567 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarIndeterminateState);
1569 case JobStatus_Aborted:
1570 case JobStatus_Failed:
1571 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarErrorState);
1573 case JobStatus_Paused:
1574 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarPausedState);
1577 WinSevenTaskbar::setTaskbarState(this, WinSevenTaskbar::WinSevenTaskbarNormalState);
1583 case JobStatus_Aborting:
1584 case JobStatus_Starting:
1585 case JobStatus_Pausing:
1586 case JobStatus_Resuming:
1589 WinSevenTaskbar::setTaskbarProgress(this, ui->progressBar->value(), ui->progressBar->maximum());
1593 WinSevenTaskbar::setOverlayIcon(this, icon.isNull() ? NULL : &icon);
1597 * Parse command-line arguments
1599 bool MainWindow::parseCommandLineArgs(void)
1601 bool bCommandAccepted = false;
1602 unsigned int flags = 0;
1604 //Initialize command-line parser
1605 CLIParser parser(x264_arguments());
1607 QStringList options;
1609 //Process all command-line arguments
1610 while(parser.nextOption(identifier, &options))
1614 case CLI_PARAM_ADD_FILE:
1615 handleCommand(IPC_OPCODE_ADD_FILE, options, flags);
1616 bCommandAccepted = true;
1618 case CLI_PARAM_ADD_JOB:
1619 handleCommand(IPC_OPCODE_ADD_JOB, options, flags);
1620 bCommandAccepted = true;
1622 case CLI_PARAM_FORCE_START:
1623 flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1625 case CLI_PARAM_NO_FORCE_START:
1626 flags = (flags & (~IPC_FLAG_FORCE_START));
1628 case CLI_PARAM_FORCE_ENQUEUE:
1629 flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1631 case CLI_PARAM_NO_FORCE_ENQUEUE:
1632 flags = (flags & (~IPC_FLAG_FORCE_ENQUEUE));
1637 return bCommandAccepted;