Bump x265 minimum required version to 3.4.
[simple-x264-launcher.git] / src / win_main.cpp
blobe2722d533b18d15c84a30f6bc453d1ad29ff34fb
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2020 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "win_main.h"
23 #include "UIC_win_main.h"
25 //Internal
26 #include "global.h"
27 #include "cli.h"
28 #include "ipc.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"
45 #include "resource.h"
47 //MUtils
48 #include <MUtils/OSSupport.h>
49 #include <MUtils/CPUFeatures.h>
50 #include <MUtils/IPCChannel.h>
51 #include <MUtils/GUI.h>
52 #include <MUtils/Sound.h>
53 #include <MUtils/Exception.h>
54 #include <MUtils/Taskbar7.h>
55 #include <MUtils/Version.h>
57 //Qt
58 #include <QDate>
59 #include <QTimer>
60 #include <QCloseEvent>
61 #include <QMessageBox>
62 #include <QDesktopServices>
63 #include <QUrl>
64 #include <QDir>
65 #include <QLibrary>
66 #include <QProcess>
67 #include <QProgressDialog>
68 #include <QScrollBar>
69 #include <QTextStream>
70 #include <QSettings>
71 #include <QFileDialog>
72 #include <QSystemTrayIcon>
73 #include <QMovie>
74 #include <QTextDocument>
75 #include <ctime>
77 //Constants
78 static const char *tpl_last = "<LAST_USED>";
79 static const char *home_url = "http://muldersoft.com/";
80 static const char *update_url = "https://github.com/lordmulder/Simple-x264-Launcher/releases/latest";
81 static const char *avs_dl_url = "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/";
82 static const char *python_url = "https://www.python.org/downloads/";
83 static const char *vsynth_url = "http://www.vapoursynth.com/";
84 static const int vsynth_rev = 24;
86 //Macros
87 #define SET_FONT_BOLD(WIDGET,BOLD) do { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); } while(0)
88 #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)
89 #define LINK(URL) (QString("<a href=\"%1\">%1</a>").arg((URL)))
90 #define INIT_ERROR_EXIT() do { close(); qApp->exit(-1); return; } while(0)
91 #define SETUP_WEBLINK(OBJ, URL) do { (OBJ)->setData(QVariant(QUrl(URL))); connect((OBJ), SIGNAL(triggered()), this, SLOT(showWebLink())); } while(0)
92 #define APP_IS_READY (m_initialized && (!m_fileTimer->isActive()) && (QApplication::activeModalWidget() == NULL))
93 #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)
94 #define X264_STRCMP(X,Y) ((X).compare((Y), Qt::CaseInsensitive) == 0)
96 ///////////////////////////////////////////////////////////////////////////////
97 // Constructor & Destructor
98 ///////////////////////////////////////////////////////////////////////////////
101 * Constructor
103 MainWindow::MainWindow(const MUtils::CPUFetaures::cpu_info_t &cpuFeatures, MUtils::IPCChannel *const ipcChannel)
105 m_ipcChannel(ipcChannel),
106 m_sysinfo(NULL),
107 m_options(NULL),
108 m_jobList(NULL),
109 m_pendingFiles(new QStringList()),
110 m_preferences(NULL),
111 m_recentlyUsed(NULL),
112 m_postOperation(POST_OP_DONOTHING),
113 m_initialized(false),
114 ui(new Ui::MainWindow())
116 //Init the dialog, from the .ui file
117 ui->setupUi(this);
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
132 //Load preferences
133 m_preferences.reset(new PreferencesModel());
134 PreferencesModel::loadPreferences(m_preferences.data());
136 //Load recently used
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 //DPI scaling
145 MUtils::GUI::scale_widget(this);
147 //Freeze minimum size
148 setMinimumSize(size());
149 ui->splitter->setSizes(QList<int>() << 16 << 196);
151 //Update title
152 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)));
154 if(MUTILS_DEBUG)
156 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
157 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
159 else if(x264_is_prerelease())
161 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
164 //Create model
165 m_jobList.reset(new JobListModel(m_preferences.data()));
166 connect(m_jobList.data(), SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
167 ui->jobsView->setModel(m_jobList.data());
169 //Setup view
170 ui->jobsView->horizontalHeader()->setSectionHidden(3, true);
171 ui->jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
172 ui->jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents);
173 ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents);
174 ui->jobsView->horizontalHeader()->setMinimumSectionSize(96);
175 ui->jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
176 connect(ui->jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
178 //Setup key listener
179 m_inputFilter_jobList.reset(new InputEventFilter(ui->jobsView));
180 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Up, 1);
181 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Down, 2);
182 connect(m_inputFilter_jobList.data(), SIGNAL(keyPressed(int)), this, SLOT(jobListKeyPressed(int)));
184 //Setup mouse listener
185 m_inputFilter_version.reset(new InputEventFilter(ui->labelBuildDate));
186 m_inputFilter_version->addMouseFilter(Qt::LeftButton, 0);
187 m_inputFilter_version->addMouseFilter(Qt::RightButton, 0);
188 connect(m_inputFilter_version.data(), SIGNAL(mouseClicked(int)), this, SLOT(versionLabelMouseClicked(int)));
190 //Create context menu
191 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), ui->logView);
192 QAction *actionSaveToLog = new QAction(QIcon(":/buttons/disk.png"), tr("Save to File..."), ui->logView);
193 QAction *actionSeparator = new QAction(ui->logView);
194 QAction *actionWordwraps = new QAction(QIcon(":/buttons/text_wrapping.png"), tr("Enable Line-Wrapping"), ui->logView);
195 actionSeparator->setSeparator(true);
196 actionWordwraps->setCheckable(true);
197 actionClipboard->setEnabled(false);
198 actionSaveToLog->setEnabled(false);
199 actionWordwraps->setEnabled(false);
200 ui->logView->addAction(actionClipboard);
201 ui->logView->addAction(actionSaveToLog);
202 ui->logView->addAction(actionSeparator);
203 ui->logView->addAction(actionWordwraps);
204 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
205 connect(actionSaveToLog, SIGNAL(triggered(bool)), this, SLOT(saveLogToLocalFile(bool)));
206 connect(actionWordwraps, SIGNAL(triggered(bool)), this, SLOT(toggleLineWrapping(bool)));
207 ui->jobsView->addActions(ui->menuJob->actions());
209 //Enable buttons
210 connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed() ));
211 connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed() ));
212 connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed() ));
213 connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
214 connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed() ));
215 connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed() ));
216 connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed() ));
217 connect(ui->actionJob_MoveUp, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
218 connect(ui->actionJob_MoveDown, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
220 //Enable menu
221 connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
222 connect(ui->actionCleanup_Finished, SIGNAL(triggered()), this, SLOT(cleanupActionTriggered()));
223 connect(ui->actionCleanup_Enqueued, SIGNAL(triggered()), this, SLOT(cleanupActionTriggered()));
224 connect(ui->actionPostOp_DoNothing, SIGNAL(triggered()), this, SLOT(postOpActionTriggered()));
225 connect(ui->actionPostOp_PowerDown, SIGNAL(triggered()), this, SLOT(postOpActionTriggered()));
226 connect(ui->actionPostOp_Hibernate, SIGNAL(triggered()), this, SLOT(postOpActionTriggered()));
227 connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
228 connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
229 connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
230 ui->actionCleanup_Finished->setData(QVariant(bool(0)));
231 ui->actionCleanup_Enqueued->setData(QVariant(bool(1)));
232 ui->actionPostOp_DoNothing->setData(QVariant(POST_OP_DONOTHING));
233 ui->actionPostOp_PowerDown->setData(QVariant(POST_OP_POWERDOWN));
234 ui->actionPostOp_Hibernate->setData(QVariant(POST_OP_HIBERNATE));
235 ui->actionPostOp_Hibernate->setEnabled(MUtils::OS::is_hibernation_supported());
237 //Setup web-links
238 SETUP_WEBLINK(ui->actionWebMulder, home_url);
239 SETUP_WEBLINK(ui->actionWebX264, "http://www.videolan.org/developers/x264.html");
240 SETUP_WEBLINK(ui->actionWebX265, "http://www.videolan.org/developers/x265.html");
241 SETUP_WEBLINK(ui->actionWebX264LigH, "http://www.mediafire.com/?bxvu1vvld31k1");
242 SETUP_WEBLINK(ui->actionWebX264VideoLAN, "http://artifacts.videolan.org/x264/");
243 SETUP_WEBLINK(ui->actionWebX264Komisar, "http://komisar.gin.by/");
244 SETUP_WEBLINK(ui->actionWebX265LigH, "http://www.mediafire.com/?6lfp2jlygogwa");
245 SETUP_WEBLINK(ui->actionWebX264FreeCodecs, "http://www.free-codecs.com/x264_video_codec_download.htm");
246 SETUP_WEBLINK(ui->actionWebX265Fllear, "http://x265.ru/en/builds/");
247 SETUP_WEBLINK(ui->actionWebX265Snowfag, "http://builds.x265.eu/");
248 SETUP_WEBLINK(ui->actionWebX265FreeCodecs, "http://www.free-codecs.com/x265_hevc_encoder_download.htm");
249 SETUP_WEBLINK(ui->actionWebAvisynth32, "https://sourceforge.net/projects/avisynth2/files/AviSynth%202.6/");
250 SETUP_WEBLINK(ui->actionWebAvisynth64, "http://forum.doom9.org/showthread.php?t=152800");
251 SETUP_WEBLINK(ui->actionWebAvisynthPlus, "http://www.avs-plus.net/");
252 SETUP_WEBLINK(ui->actionWebVapourSynth, "http://www.vapoursynth.com/");
253 SETUP_WEBLINK(ui->actionWebVapourSynthDocs, "http://www.vapoursynth.com/doc/");
254 SETUP_WEBLINK(ui->actionOnlineDocX264, "http://en.wikibooks.org/wiki/MeGUI/x264_Settings"); //http://mewiki.project357.com/wiki/X264_Settings
255 SETUP_WEBLINK(ui->actionOnlineDocX265, "http://x265.readthedocs.org/en/default/");
256 SETUP_WEBLINK(ui->actionWebBluRay, "http://www.x264bluray.com/");
257 SETUP_WEBLINK(ui->actionWebAvsWiki, "http://avisynth.nl/index.php/Main_Page#Usage");
258 SETUP_WEBLINK(ui->actionWebSupport, "http://forum.doom9.org/showthread.php?t=144140");
259 SETUP_WEBLINK(ui->actionWebSecret, "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
261 //Create floating label
262 m_label[0].reset(new QLabel(ui->jobsView->viewport()));
263 m_label[1].reset(new QLabel(ui->logView->viewport()));
264 if(!m_label[0].isNull())
266 m_label[0]->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
267 m_label[0]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
268 SET_TEXT_COLOR(m_label[0], Qt::darkGray);
269 SET_FONT_BOLD(m_label[0], true);
270 m_label[0]->setVisible(true);
271 m_label[0]->setContextMenuPolicy(Qt::ActionsContextMenu);
272 m_label[0]->addActions(ui->jobsView->actions());
274 if(!m_label[1].isNull())
276 m_animation.reset(new QMovie(":/images/spinner.gif"));
277 m_label[1]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
278 if(!m_animation.isNull())
280 m_label[1]->setMovie(m_animation.data());
281 m_animation->start();
284 connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
285 updateLabelPos();
287 //Init system tray icon
288 m_sysTray.reset(new QSystemTrayIcon(this));
289 m_sysTray->setToolTip(this->windowTitle());
290 m_sysTray->setIcon(this->windowIcon());
291 connect(m_sysTray.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(sysTrayActived()));
293 //Init taskbar progress
294 m_taskbar.reset(new MUtils::Taskbar7(this));
296 //Create corner widget
297 QLabel *checkUp = new QLabel(ui->menubar);
298 checkUp->setText(QString("<nobr><img src=\":/buttons/exclamation_small.png\">&nbsp;<b style=\"color:darkred\">%1</b>&nbsp;&nbsp;&nbsp;</nobr>").arg(tr("Check for Updates")));
299 checkUp->setFixedHeight(ui->menubar->height());
300 checkUp->setCursor(QCursor(Qt::PointingHandCursor));
301 m_inputFilter_checkUp.reset(new InputEventFilter(checkUp));
302 m_inputFilter_checkUp->addMouseFilter(Qt::LeftButton, 0);
303 m_inputFilter_checkUp->addMouseFilter(Qt::RightButton, 0);
304 connect(m_inputFilter_checkUp.data(), SIGNAL(mouseClicked(int)), this, SLOT(checkUpdates()));
305 checkUp->hide();
306 ui->menubar->setCornerWidget(checkUp);
308 //Create timer
309 m_fileTimer.reset(new QTimer(this));
310 connect(m_fileTimer.data(), SIGNAL(timeout()), this, SLOT(handlePendingFiles()));
314 * Destructor
316 MainWindow::~MainWindow(void)
318 OptionsModel::saveTemplate(m_options.data(), QString::fromLatin1(tpl_last));
320 if(!m_ipcThread.isNull())
322 m_ipcThread->stop();
323 if(!m_ipcThread->wait(5000))
325 m_ipcThread->terminate();
326 m_ipcThread->wait();
330 delete ui;
333 ///////////////////////////////////////////////////////////////////////////////
334 // Slots
335 ///////////////////////////////////////////////////////////////////////////////
338 * The "add" button was clicked
340 void MainWindow::addButtonPressed()
342 ENSURE_APP_IS_READY();
344 qDebug("MainWindow::addButtonPressed");
345 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
346 QString sourceFileName, outputFileName;
348 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
350 appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
355 * The "open" action was triggered
357 void MainWindow::openActionTriggered()
359 ENSURE_APP_IS_READY();
360 qWarning("openActionTriggered()");
362 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
363 if(!fileList.empty())
365 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
366 if(fileList.count() > 1)
368 createJobMultiple(fileList);
370 else
372 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
373 QString sourceFileName(fileList.first()), outputFileName;
374 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
376 appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
383 * The "clean-up" action was invoked
385 void MainWindow::cleanupActionTriggered(void)
387 ENSURE_APP_IS_READY();
389 QAction *const sender = dynamic_cast<QAction*>(QObject::sender());
390 if (sender)
392 const QVariant data = sender->data();
393 if (data.isValid() && (data.type() == QVariant::Bool))
395 const bool mode = data.toBool();
396 const int rows = m_jobList->rowCount(QModelIndex());
397 QList<int> jobIndices;
398 for (int i = 0; i < rows; i++)
400 const JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
401 if (mode && (status == JobStatus_Enqueued))
403 jobIndices.append(i);
405 else if ((!mode) && ((status == JobStatus_Completed) || (status == JobStatus_Aborted) || (status == JobStatus_Failed)))
407 jobIndices.append(i);
410 if (!jobIndices.isEmpty())
412 QListIterator<int> iter(jobIndices);
413 iter.toBack();
414 while(iter.hasPrevious())
416 m_jobList->deleteJob(m_jobList->index(iter.previous(), 0, QModelIndex()));
419 else
421 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
428 * The "clean-up" action was invoked
430 void MainWindow::postOpActionTriggered(void)
432 ENSURE_APP_IS_READY();
434 QAction *const sender = dynamic_cast<QAction*>(QObject::sender());
435 if (sender)
437 const QVariant data = sender->data();
438 if (data.isValid() && (data.type() == QVariant::Int))
440 const postOp_t mode = (postOp_t)data.toInt();
441 if ((mode >= POST_OP_DONOTHING) && (mode <= POST_OP_HIBERNATE))
443 m_postOperation = mode;
444 ui->actionPostOp_PowerDown->setChecked(mode == POST_OP_POWERDOWN);
445 ui->actionPostOp_Hibernate->setChecked(mode == POST_OP_HIBERNATE);
446 ui->actionPostOp_DoNothing->setChecked(mode == POST_OP_DONOTHING);
453 * The "start" button was clicked
455 void MainWindow::startButtonPressed(void)
457 ENSURE_APP_IS_READY();
458 m_jobList->startJob(ui->jobsView->currentIndex());
462 * The "abort" button was clicked
464 void MainWindow::abortButtonPressed(void)
466 ENSURE_APP_IS_READY();
468 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)
470 m_jobList->abortJob(ui->jobsView->currentIndex());
475 * The "delete" button was clicked
477 void MainWindow::deleteButtonPressed(void)
479 ENSURE_APP_IS_READY();
481 m_jobList->deleteJob(ui->jobsView->currentIndex());
482 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
486 * The "browse" button was clicked
488 void MainWindow::browseButtonPressed(void)
490 ENSURE_APP_IS_READY();
492 QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
493 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
495 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
497 else
499 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
504 * The "browse" button was clicked
506 void MainWindow::moveButtonPressed(void)
508 ENSURE_APP_IS_READY();
510 if(sender() == ui->actionJob_MoveUp)
512 qDebug("Move job %d (direction: UP)", ui->jobsView->currentIndex().row());
513 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_UP))
515 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
517 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
519 else if(sender() == ui->actionJob_MoveDown)
521 qDebug("Move job %d (direction: DOWN)", ui->jobsView->currentIndex().row());
522 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_DOWN))
524 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
526 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
528 else
530 qWarning("[moveButtonPressed] Error: Unknown sender!");
535 * The "pause" button was clicked
537 void MainWindow::pauseButtonPressed(bool checked)
539 if(!APP_IS_READY)
541 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
542 qWarning("Cannot perfrom this action at this time!");
543 ui->buttonPauseJob->setChecked(!checked);
546 if(checked)
548 m_jobList->pauseJob(ui->jobsView->currentIndex());
550 else
552 m_jobList->resumeJob(ui->jobsView->currentIndex());
557 * The "restart" button was clicked
559 void MainWindow::restartButtonPressed(void)
561 ENSURE_APP_IS_READY();
563 const QModelIndex index = ui->jobsView->currentIndex();
564 const OptionsModel *options = m_jobList->getJobOptions(index);
565 QString sourceFileName = m_jobList->getJobSourceFile(index);
566 QString outputFileName = m_jobList->getJobOutputFile(index);
568 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
570 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
571 OptionsModel *tempOptions = new OptionsModel(*options);
572 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
574 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
576 MUTILS_DELETE(tempOptions);
581 * Job item selected by user
583 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
585 qDebug("Job selected: %d", current.row());
587 if(ui->logView->model())
589 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
592 if(current.isValid())
594 ui->logView->setModel(m_jobList->getLogFile(current));
595 connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
596 foreach(QAction *action, ui->logView->actions())
598 action->setEnabled(true);
600 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
602 ui->progressBar->setValue(m_jobList->getJobProgress(current));
603 ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
604 updateButtons(m_jobList->getJobStatus(current));
605 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
607 else
609 ui->logView->setModel(NULL);
610 foreach(QAction *action, ui->logView->actions())
612 action->setEnabled(false);
614 ui->progressBar->setValue(0);
615 ui->editDetails->clear();
616 updateButtons(JobStatus_Undefined);
617 updateTaskbar(JobStatus_Undefined, QIcon());
620 ui->progressBar->repaint();
624 * Handle update of job info (status, progress, details, etc)
626 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
628 int selected = ui->jobsView->currentIndex().row();
630 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
632 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
634 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
635 if(i == selected)
637 qDebug("Current job changed status!");
638 updateButtons(status);
639 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
641 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
643 if(m_preferences->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
644 if(m_preferences->getSaveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
648 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
650 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
652 if(i == selected)
654 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
655 if(!m_taskbar.isNull())
657 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
659 break;
663 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
665 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
667 if(i == selected)
669 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
670 break;
677 * Handle new log file content
679 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
681 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
685 * About screen
687 void MainWindow::showAbout(void)
689 ENSURE_APP_IS_READY();
691 if(AboutDialog *aboutDialog = new AboutDialog(this))
693 aboutDialog->exec();
694 MUTILS_DELETE(aboutDialog);
699 * Open web-link
701 void MainWindow::showWebLink(void)
703 ENSURE_APP_IS_READY();
705 if(QObject *obj = QObject::sender())
707 if(QAction *action = dynamic_cast<QAction*>(obj))
709 if(action->data().type() == QVariant::Url)
711 QDesktopServices::openUrl(action->data().toUrl());
718 * Pereferences dialog
720 void MainWindow::showPreferences(void)
722 ENSURE_APP_IS_READY();
724 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences.data(), m_sysinfo.data());
725 preferences->exec();
727 MUTILS_DELETE(preferences);
731 * Launch next job, after running job has finished
733 void MainWindow::launchNextJob(void)
735 qDebug("Launching next job...");
737 if(countRunningJobs() >= m_preferences->getMaxRunningJobCount())
739 qDebug("Still have too many jobs running, won't launch next one yet!");
740 return;
743 const int rows = m_jobList->rowCount(QModelIndex());
745 for(int i = 0; i < rows; i++)
747 const QModelIndex currentIndex = m_jobList->index(i, 0, QModelIndex());
748 if(m_jobList->getJobStatus(currentIndex) == JobStatus_Enqueued)
750 if(m_jobList->startJob(currentIndex))
752 ui->jobsView->selectRow(currentIndex.row());
753 return;
758 qWarning("No enqueued jobs left to be started!");
760 if(m_postOperation)
762 qDebug("Post operation has been scheduled! (m_postOperation: %d)", m_postOperation);
763 QTimer::singleShot(0, this, SLOT(shutdownComputer()));
768 * Save log to text file
770 void MainWindow::saveLogFile(const QModelIndex &index)
772 if(index.isValid())
774 const LogFileModel *const logData = m_jobList->getLogFile(index);
775 const QString &outputFilePath = m_jobList->getJobOutputFile(index);
776 if(logData && (!outputFilePath.isEmpty()))
778 const QFileInfo outputFileInfo(outputFilePath);
779 if (outputFileInfo.absoluteDir().exists())
781 const QString outputDir = outputFileInfo.absolutePath(), outputName = outputFileInfo.fileName();
782 const QString logFilePath = MUtils::make_unique_file(outputDir, outputName, QLatin1String("log"), true);
783 if (!logFilePath.isEmpty())
785 qDebug("Saving log file to: \"%s\"", MUTILS_UTF8(logFilePath));
786 if (!logData->saveToLocalFile(logFilePath))
788 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
791 else
793 qWarning("Failed to generate log file name. Giving up!");
796 else
798 qWarning("Output directory does not seem to exist. Giving up!");
805 * Shut down the computer (with countdown)
807 void MainWindow::shutdownComputer(void)
809 ENSURE_APP_IS_READY();
810 qDebug("shutdownComputer (m_postOperation: %d)", m_postOperation);
812 if(countPendingJobs() > 0)
814 qWarning("Still have pending jobs, won't shutdown yet!");
815 return;
818 if ((m_postOperation != POST_OP_POWERDOWN) && (m_postOperation != POST_OP_HIBERNATE))
820 qWarning("No post-operation has been schedule!");
823 const int iTimeout = 30;
824 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
825 const bool hibernate = (m_postOperation == POST_OP_HIBERNATE);
826 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), hibernate ? tr("Warning: Computer will hibernate in %1 seconds...") : tr("Warning: Computer will shutdown in %1 seconds..."));
828 qWarning("Initiating shutdown sequence!");
830 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
831 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
832 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
833 progressDialog.setModal(true);
834 progressDialog.setAutoClose(false);
835 progressDialog.setAutoReset(false);
836 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
837 progressDialog.setWindowTitle(windowTitle());
838 progressDialog.setCancelButton(cancelButton);
839 progressDialog.show();
841 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
842 QApplication::setOverrideCursor(Qt::WaitCursor);
843 MUtils::Sound::play_sound("shutdown", false);
844 QApplication::restoreOverrideCursor();
846 QTimer timer;
847 timer.setInterval(1000);
848 timer.start();
850 QEventLoop eventLoop(this);
851 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
852 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
854 for(int i = 1; i <= iTimeout; i++)
856 eventLoop.exec();
857 if(progressDialog.wasCanceled())
859 progressDialog.close();
860 return;
862 progressDialog.setValue(i+1);
863 progressDialog.setLabelText(text.arg(iTimeout-i));
864 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
865 QApplication::processEvents();
866 MUtils::Sound::play_sound(((i < iTimeout) ? "beep" : "beep2"), false);
869 qWarning("Shutting down !!!");
871 if(MUtils::OS::shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true, hibernate))
873 qApp->closeAllWindows();
879 * Main initialization function (called only once!)
881 void MainWindow::init(void)
883 if(m_initialized)
885 qWarning("Already initialized -> skipping!");
886 return;
889 updateLabelPos();
890 const MUtils::OS::ArgumentMap &arguments = MUtils::OS::arguments();
891 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
893 //---------------------------------------
894 // Check required binaries
895 //---------------------------------------
897 qDebug("[Validating binaries]");
898 QString failedPath;
899 if(!BinariesCheckThread::check(m_sysinfo.data(), &failedPath))
901 QMessageBox::critical(this, tr("Invalid File!"), tr("<nobr>At least one tool is missing or is not a valid Win32/Win64 binary:</nobr><br><tt>%1</tt><br><br><nobr>Please re-install the program in order to fix the problem!</nobr>").replace("-", "&minus;").arg(Qt::escape(QDir::toNativeSeparators(failedPath))));
902 qFatal("At least one tool is missing or is not a valid Win32/Win64 binary. Program will exit now!");
904 qDebug(" ");
906 //---------------------------------------
907 // Check for portable mode
908 //---------------------------------------
910 if(x264_is_portable())
912 bool ok = false;
913 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
914 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
915 if(writeTest.open(QIODevice::WriteOnly))
917 ok = (writeTest.write(data) == strlen(data));
918 writeTest.remove();
920 if(!ok)
922 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"));
923 if(val != 1) INIT_ERROR_EXIT();
927 //Pre-release popup
928 if(x264_is_prerelease())
930 qsrand(time(NULL)); int rnd = qrand() % 3;
931 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);
932 if(rnd != val) INIT_ERROR_EXIT();
935 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
937 //---------------------------------------
938 // Check CPU capabilities
939 //---------------------------------------
941 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
942 if(!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_MMX))
944 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"));
945 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
946 INIT_ERROR_EXIT();
948 else if(!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_SSE))
950 qWarning("WARNING: System does not support SSE (v1), x264/x265 probably will *not* work !!!\n");
951 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"));
952 if(val != 1) INIT_ERROR_EXIT();
955 //Skip version check (not recommended!)
956 if(arguments.contains(CLI_PARAM_SKIP_VERSION_CHECK))
958 qWarning("Version checks are disabled now, you have been warned!\n");
959 m_preferences->setSkipVersionTest(true);
962 //Don't abort encoding process on timeout (not recommended!)
963 if(arguments.contains(CLI_PARAM_NO_DEADLOCK))
965 qWarning("Deadlock detection disabled, you have been warned!\n");
966 m_preferences->setAbortOnTimeout(false);
969 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
971 //---------------------------------------
972 // Check Avisynth support
973 //---------------------------------------
975 if(!arguments.contains(CLI_PARAM_SKIP_AVS_CHECK))
977 qDebug("[Check for Avisynth support]");
978 if(!AvisynthCheckThread::detect(m_sysinfo.data()))
980 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
981 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
982 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
983 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
984 if(val != 1) INIT_ERROR_EXIT();
986 else if((!m_sysinfo->hasAvisynth()) && (!m_preferences->getDisableWarnings()))
988 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>");
989 text += tr("Please download and install Avisynth:").append("<br>").append(LINK(avs_dl_url));
990 int val = QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
991 if(val == 1)
993 m_preferences->setDisableWarnings(true);
994 PreferencesModel::savePreferences(m_preferences.data());
997 qDebug(" ");
1000 //---------------------------------------
1001 // Check VapurSynth support
1002 //---------------------------------------
1004 if(!arguments.contains(CLI_PARAM_SKIP_VPS_CHECK))
1006 qDebug("[Check for VapourSynth support]");
1007 if(!VapourSynthCheckThread::detect(m_sysinfo.data()))
1009 QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
1010 text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
1011 text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
1012 const int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
1013 if(val != 1) INIT_ERROR_EXIT();
1015 else if((!m_sysinfo->hasVapourSynth()) && (!m_preferences->getDisableWarnings()))
1017 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>");
1018 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>");
1019 text += tr("Note that Python v3.4 is a prerequisite for installing VapourSynth:").append("<br>").append(LINK(python_url)).append("<br>");
1020 const int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
1021 if(val == 1)
1023 m_preferences->setDisableWarnings(true);
1024 PreferencesModel::savePreferences(m_preferences.data());
1027 qDebug(" ");
1030 //---------------------------------------
1031 // Create the IPC listener thread
1032 //---------------------------------------
1034 if(m_ipcChannel)
1036 m_ipcThread.reset(new IPCThread_Recv(m_ipcChannel));
1037 connect(m_ipcThread.data(), SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
1038 m_ipcThread->start();
1041 //---------------------------------------
1042 // Finish initialization
1043 //---------------------------------------
1045 //Set Window title
1046 setWindowTitle(QString("%1 (%2)").arg(windowTitle(), m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_X64) ? "64-Bit" : "32-Bit"));
1048 //Enable drag&drop support for this window, required for Qt v4.8.4+
1049 setAcceptDrops(true);
1051 //Update flag
1052 m_initialized = true;
1054 //Hide the spinner animation
1055 if(!m_label[1].isNull())
1057 if(!m_animation.isNull())
1059 m_animation->stop();
1061 m_label[1]->setVisible(false);
1064 //---------------------------------------
1065 // Check for Expiration
1066 //---------------------------------------
1068 if(MUtils::Version::app_build_date().addMonths(6) < MUtils::OS::current_date())
1070 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
1071 QString text;
1072 text += QString("<nobr><tt>%1</tt></nobr><br><br>").arg(tr("Your version of Simple x264 Launcher is more than 6 months old!").replace('-', "&minus;"));
1073 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('-', "&minus;"), QString::fromLatin1(update_url), QString::fromLatin1(update_url).replace("-", "&minus;"));
1074 text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace('-', "&minus;"));
1075 QMessageBox msgBox(this);
1076 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
1077 msgBox.setWindowTitle(tr("Update Notification"));
1078 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
1079 msgBox.setText(text);
1080 QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
1081 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
1082 QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
1083 btn2->setEnabled(false);
1084 btn3->setVisible(false);
1085 QTimer::singleShot(7500, btn2, SLOT(hide()));
1086 QTimer::singleShot(7500, btn3, SLOT(show()));
1087 if(msgBox.exec() == 0)
1089 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1090 return;
1093 else if(!parseCommandLineArgs())
1095 //Update reminder
1096 if(arguments.contains(CLI_PARAM_FIRST_RUN))
1098 qWarning("First run -> resetting update check now!");
1099 m_recentlyUsed->setLastUpdateCheck(0);
1100 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
1102 else if(m_recentlyUsed->lastUpdateCheck() + 14 < MUtils::OS::current_date().toJulianDay())
1104 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
1105 if(!m_preferences->getNoUpdateReminder())
1107 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)
1109 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1110 return;
1116 //Load queued jobs
1117 if(m_jobList->loadQueuedJobs(m_sysinfo.data()) > 0)
1119 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1120 m_jobList->clearQueuedJobs();
1125 * Update the label position
1127 void MainWindow::updateLabelPos(void)
1129 for(int i = 0; i < 2; i++)
1131 //const QWidget *const viewPort = ui->jobsView->viewport();
1132 const QWidget *const viewPort = dynamic_cast<QWidget*>(m_label[i]->parent());
1133 if(viewPort)
1135 m_label[i]->setGeometry(0, 0, viewPort->width(), viewPort->height());
1141 * Copy the complete log to the clipboard
1143 void MainWindow::copyLogToClipboard(bool checked)
1145 qDebug("Coyping logfile to clipboard...");
1147 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1149 log->copyToClipboard();
1150 MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
1155 * Save log to local file
1157 void MainWindow::saveLogToLocalFile(bool checked)
1159 ENSURE_APP_IS_READY();
1161 const QModelIndex index = ui->jobsView->currentIndex();
1162 const QString initialName = index.isValid() ? QFileInfo(m_jobList->getJobOutputFile(index)).completeBaseName() : tr("Logfile");
1163 const QString fileName = QFileDialog::getSaveFileName(this, tr("Save Log File"), initialName, tr("Log File (*.log)"));
1164 if(!fileName.isEmpty())
1166 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1168 if(!log->saveToLocalFile(fileName))
1170 QMessageBox::warning(this, this->windowTitle(), tr("Error: Log file could not be saved!"));
1177 * Toggle line-wrapping
1179 void MainWindow::toggleLineWrapping(bool checked)
1181 ui->logView->setWordWrap(checked);
1185 * Process the dropped files
1187 void MainWindow::handlePendingFiles(void)
1189 qDebug("MainWindow::handlePendingFiles");
1191 if(!m_pendingFiles->isEmpty())
1193 QStringList pendingFiles(*m_pendingFiles);
1194 m_pendingFiles->clear();
1195 createJobMultiple(pendingFiles);
1198 qDebug("Leave from MainWindow::handlePendingFiles!");
1202 * Handle incoming IPC command
1204 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1206 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1208 qWarning("Cannot accapt commands at this time -> discarding!");
1209 return;
1212 if((!isVisible()) || m_sysTray->isVisible())
1214 sysTrayActived();
1217 MUtils::GUI::bring_to_front(this);
1219 #ifdef IPC_LOGGING
1220 qDebug("\n---------- IPC ----------");
1221 qDebug("CommandId: %d", command);
1222 for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1224 qDebug("Arguments: %s", iter->toUtf8().constData());
1226 qDebug("The Flags: 0x%08X", flags);
1227 qDebug("---------- IPC ----------\n");
1228 #endif //IPC_LOGGING
1230 switch(command)
1232 case IPC_OPCODE_PING:
1233 qDebug("Received a PING request from another instance!");
1234 MUtils::GUI::blink_window(this, 5, 125);
1235 break;
1236 case IPC_OPCODE_ADD_FILE:
1237 if(!args.isEmpty())
1239 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1241 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1242 if(!m_fileTimer->isActive())
1244 m_fileTimer->setSingleShot(true);
1245 m_fileTimer->start(5000);
1248 else
1250 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1253 break;
1254 case IPC_OPCODE_ADD_JOB:
1255 if(args.size() >= 3)
1257 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1259 OptionsModel options(m_sysinfo.data());
1260 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1261 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1263 if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1265 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1268 if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
1269 if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
1270 appendJob(args[0], args[1], &options, runImmediately);
1272 else
1274 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1277 break;
1278 default:
1279 MUTILS_THROW("Unknown command received!");
1284 * Check for new updates
1286 void MainWindow::checkUpdates(void)
1288 ENSURE_APP_IS_READY();
1290 if(countRunningJobs() > 0)
1292 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1293 return;
1296 UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo.data(), update_url);
1297 const int ret = updater->exec();
1299 if(updater->getSuccess())
1301 m_recentlyUsed->setLastUpdateCheck(MUtils::OS::current_date().toJulianDay());
1302 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
1303 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->hide();
1306 if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1308 qWarning("Exitting program to install update...");
1309 close();
1310 QApplication::quit();
1313 MUTILS_DELETE(updater);
1317 * Handle mouse event for version label
1319 void MainWindow::versionLabelMouseClicked(const int &tag)
1321 if(tag == 0)
1323 QTimer::singleShot(0, this, SLOT(showAbout()));
1328 * Handle key event for job list
1330 void MainWindow::jobListKeyPressed(const int &tag)
1332 switch(tag)
1334 case 1:
1335 ui->actionJob_MoveUp->trigger();
1336 break;
1337 case 2:
1338 ui->actionJob_MoveDown->trigger();
1339 break;
1344 * System tray was activated
1346 void MainWindow::sysTrayActived(void)
1348 m_sysTray->hide();
1349 showNormal();
1350 MUtils::GUI::bring_to_front(this);
1353 ///////////////////////////////////////////////////////////////////////////////
1354 // Event functions
1355 ///////////////////////////////////////////////////////////////////////////////
1358 * Window shown event
1360 void MainWindow::showEvent(QShowEvent *e)
1362 QMainWindow::showEvent(e);
1364 if(!m_initialized)
1366 QTimer::singleShot(0, this, SLOT(init()));
1371 * Window close event
1373 void MainWindow::closeEvent(QCloseEvent *e)
1375 if(!APP_IS_READY)
1377 e->ignore();
1378 qWarning("Cannot close window at this time!");
1379 return;
1382 //Make sure we have no running jobs left!
1383 if(countRunningJobs() > 0)
1385 e->ignore();
1386 if(!m_preferences->getNoSystrayWarning())
1388 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)
1390 m_preferences->setNoSystrayWarning(true);
1391 PreferencesModel::savePreferences(m_preferences.data());
1394 hide();
1395 m_sysTray->show();
1396 return;
1399 //Save pending jobs for next time, if desired by user
1400 if(countPendingJobs() > 0)
1402 if (!m_preferences->getSaveQueueNoConfirm())
1404 const int ret = QMessageBox::question(this, tr("Jobs Are Pending"), tr("<nobr>You still have some pending jobs in your queue. How do you want to proceed?</nobr>"), tr("Save Jobs"), tr("Always Save Jobs"), tr("Discard Jobs"));
1405 if ((ret >= 0) && (ret <= 1))
1407 if (ret > 0)
1409 m_preferences->setSaveQueueNoConfirm(true);
1410 PreferencesModel::savePreferences(m_preferences.data());
1412 m_jobList->saveQueuedJobs();
1415 else
1417 m_jobList->saveQueuedJobs();
1421 //Delete remaining jobs
1422 while(m_jobList->rowCount(QModelIndex()) > 0)
1424 if((m_jobList->rowCount(QModelIndex()) % 10) == 0)
1426 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1428 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1430 e->ignore();
1431 QMessageBox::warning(this, tr("Failed To Exit"), tr("Warning: At least one job could not be deleted!"));
1435 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1436 QMainWindow::closeEvent(e);
1440 * Window resize event
1442 void MainWindow::resizeEvent(QResizeEvent *e)
1444 QMainWindow::resizeEvent(e);
1445 updateLabelPos();
1449 * File dragged over window
1451 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1453 bool accept[2] = {false, false};
1455 foreach(const QString &fmt, event->mimeData()->formats())
1457 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1458 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1461 if(accept[0] && accept[1])
1463 event->acceptProposedAction();
1468 * File dropped onto window
1470 void MainWindow::dropEvent(QDropEvent *event)
1472 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1474 qWarning("Cannot accept dropped files at this time -> discarding!");
1475 return;
1478 QStringList droppedFiles;
1479 QList<QUrl> urls = event->mimeData()->urls();
1481 while(!urls.isEmpty())
1483 QUrl currentUrl = urls.takeFirst();
1484 QFileInfo file(currentUrl.toLocalFile());
1485 if(file.exists() && file.isFile())
1487 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1488 droppedFiles << file.canonicalFilePath();
1492 if(droppedFiles.count() > 0)
1494 m_pendingFiles->append(droppedFiles);
1495 m_pendingFiles->sort();
1496 if(!m_fileTimer->isActive())
1498 m_fileTimer->setSingleShot(true);
1499 m_fileTimer->start(5000);
1504 ///////////////////////////////////////////////////////////////////////////////
1505 // Private functions
1506 ///////////////////////////////////////////////////////////////////////////////
1509 * Creates a new job
1511 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1513 bool okay = false;
1514 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed.data(), m_sysinfo.data(), m_preferences.data());
1516 addDialog->setRunImmediately(runImmediately);
1517 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1518 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1519 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1521 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1522 if(multiFile)
1524 addDialog->setSourceEditable(false);
1525 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1526 addDialog->setApplyToAllVisible(applyToAll);
1529 if(addDialog->exec() == QDialog::Accepted)
1531 sourceFileName = addDialog->sourceFile();
1532 outputFileName = addDialog->outputFile();
1533 runImmediately = addDialog->runImmediately();
1534 if(applyToAll)
1536 *applyToAll = addDialog->applyToAll();
1538 okay = true;
1541 MUTILS_DELETE(addDialog);
1542 return okay;
1546 * Creates a new job from *multiple* files
1548 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1550 QStringList::ConstIterator iter;
1551 bool applyToAll = false, runImmediately = false;
1552 int counter = 0;
1554 //Add files individually
1555 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1557 runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1558 QString sourceFileName(*iter), outputFileName;
1559 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1561 if(appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
1563 continue;
1566 return false;
1569 //Add remaining files
1570 while(applyToAll && (iter != filePathIn.constEnd()))
1572 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1573 const QString sourceFileName = *iter;
1574 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
1575 if(!appendJob(sourceFileName, outputFileName, m_options.data(), runImmediatelyTmp))
1577 return false;
1579 iter++;
1582 return true;
1586 * Append a new job
1588 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1590 bool okay = false;
1591 EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo.data(), m_preferences.data());
1592 QModelIndex newIndex = m_jobList->insertJob(thrd);
1594 if(newIndex.isValid())
1596 if(runImmediately)
1598 ui->jobsView->selectRow(newIndex.row());
1599 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1600 m_jobList->startJob(newIndex);
1603 okay = true;
1606 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1607 return okay;
1611 * Jobs that are not completed (or failed, or aborted) yet
1613 unsigned int MainWindow::countPendingJobs(void)
1615 unsigned int count = 0;
1616 const int rows = m_jobList->rowCount(QModelIndex());
1618 for(int i = 0; i < rows; i++)
1620 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1621 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1623 count++;
1627 return count;
1631 * Jobs that are still active, i.e. not terminated or enqueued
1633 unsigned int MainWindow::countRunningJobs(void)
1635 unsigned int count = 0;
1636 const int rows = m_jobList->rowCount(QModelIndex());
1638 for(int i = 0; i < rows; i++)
1640 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1641 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1643 count++;
1647 return count;
1651 * Update all buttons with respect to current job status
1653 void MainWindow::updateButtons(JobStatus status)
1655 qDebug("MainWindow::updateButtons(void)");
1657 ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1658 ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1659 ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1660 ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1662 ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1663 ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1664 ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1665 ui->actionJob_MoveUp->setEnabled(status != JobStatus_Undefined);
1666 ui->actionJob_MoveDown->setEnabled(status != JobStatus_Undefined);
1668 ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1669 ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1670 ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1671 ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1673 ui->editDetails->setEnabled(status != JobStatus_Paused);
1677 * Update the taskbar with current job status
1679 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1681 qDebug("MainWindow::updateTaskbar(void)");
1683 if(m_taskbar.isNull())
1685 return; /*taskbar object not created yet*/
1688 switch(status)
1690 case JobStatus_Undefined:
1691 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE);
1692 break;
1693 case JobStatus_Aborting:
1694 case JobStatus_Starting:
1695 case JobStatus_Pausing:
1696 case JobStatus_Resuming:
1697 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_INTERMEDIATE);
1698 break;
1699 case JobStatus_Aborted:
1700 case JobStatus_Failed:
1701 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR);
1702 break;
1703 case JobStatus_Paused:
1704 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_PAUSED);
1705 break;
1706 default:
1707 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL);
1708 break;
1711 switch(status)
1713 case JobStatus_Aborting:
1714 case JobStatus_Starting:
1715 case JobStatus_Pausing:
1716 case JobStatus_Resuming:
1717 break;
1718 default:
1719 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
1720 break;
1723 m_taskbar->setOverlayIcon(icon.isNull() ? NULL : &icon);
1727 * Parse command-line arguments
1729 bool MainWindow::parseCommandLineArgs(void)
1731 const MUtils::OS::ArgumentMap &args = MUtils::OS::arguments();
1733 quint32 flags = 0;
1734 bool commandSent = false;
1736 //Handle flags
1737 if(args.contains(CLI_PARAM_FORCE_START))
1739 flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1741 if(args.contains(CLI_PARAM_FORCE_ENQUEUE))
1743 flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1746 //Process all command-line arguments
1747 if(args.contains(CLI_PARAM_ADD_FILE))
1749 foreach(const QString &fileName, args.values(CLI_PARAM_ADD_FILE))
1751 handleCommand(IPC_OPCODE_ADD_FILE, QStringList() << fileName, flags);
1753 commandSent = true;
1755 if(args.contains(CLI_PARAM_ADD_JOB))
1757 foreach(const QString &options, args.values(CLI_PARAM_ADD_JOB))
1759 const QStringList optionValues = options.split('|', QString::SkipEmptyParts);
1760 if(optionValues.count() == 3)
1762 handleCommand(IPC_OPCODE_ADD_JOB, optionValues, flags);
1764 else
1766 qWarning("Invalid number of arguments for parameter \"--%s\" detected!", CLI_PARAM_ADD_JOB);
1769 commandSent = true;
1772 return commandSent;