Bump version + updated changelog.
[simple-x264-launcher.git] / src / win_main.cpp
blob82c17e2c3020a95dba701009f1015902327e92e1
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2018 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>
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 //Freeze minimum size
145 setMinimumSize(size());
146 ui->splitter->setSizes(QList<int>() << 16 << 196);
148 //Update title
149 ui->labelBuildDate->setText(tr("Built on %1 at %2").arg(MUtils::Version::app_build_date().toString(Qt::ISODate), MUtils::Version::app_build_time().toString(Qt::ISODate)));
151 if(MUTILS_DEBUG)
153 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
154 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
156 else if(x264_is_prerelease())
158 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
161 //Create model
162 m_jobList.reset(new JobListModel(m_preferences.data()));
163 connect(m_jobList.data(), SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
164 ui->jobsView->setModel(m_jobList.data());
166 //Setup view
167 ui->jobsView->horizontalHeader()->setSectionHidden(3, true);
168 ui->jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
169 ui->jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents);
170 ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents);
171 ui->jobsView->horizontalHeader()->setMinimumSectionSize(96);
172 ui->jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
173 connect(ui->jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
175 //Setup key listener
176 m_inputFilter_jobList.reset(new InputEventFilter(ui->jobsView));
177 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Up, 1);
178 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Down, 2);
179 connect(m_inputFilter_jobList.data(), SIGNAL(keyPressed(int)), this, SLOT(jobListKeyPressed(int)));
181 //Setup mouse listener
182 m_inputFilter_version.reset(new InputEventFilter(ui->labelBuildDate));
183 m_inputFilter_version->addMouseFilter(Qt::LeftButton, 0);
184 m_inputFilter_version->addMouseFilter(Qt::RightButton, 0);
185 connect(m_inputFilter_version.data(), SIGNAL(mouseClicked(int)), this, SLOT(versionLabelMouseClicked(int)));
187 //Create context menu
188 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), ui->logView);
189 QAction *actionSaveToLog = new QAction(QIcon(":/buttons/disk.png"), tr("Save to File..."), ui->logView);
190 QAction *actionSeparator = new QAction(ui->logView);
191 QAction *actionWordwraps = new QAction(QIcon(":/buttons/text_wrapping.png"), tr("Enable Line-Wrapping"), ui->logView);
192 actionSeparator->setSeparator(true);
193 actionWordwraps->setCheckable(true);
194 actionClipboard->setEnabled(false);
195 actionSaveToLog->setEnabled(false);
196 actionWordwraps->setEnabled(false);
197 ui->logView->addAction(actionClipboard);
198 ui->logView->addAction(actionSaveToLog);
199 ui->logView->addAction(actionSeparator);
200 ui->logView->addAction(actionWordwraps);
201 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
202 connect(actionSaveToLog, SIGNAL(triggered(bool)), this, SLOT(saveLogToLocalFile(bool)));
203 connect(actionWordwraps, SIGNAL(triggered(bool)), this, SLOT(toggleLineWrapping(bool)));
204 ui->jobsView->addActions(ui->menuJob->actions());
206 //Enable buttons
207 connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed() ));
208 connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed() ));
209 connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed() ));
210 connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
211 connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed() ));
212 connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed() ));
213 connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed() ));
214 connect(ui->actionJob_MoveUp, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
215 connect(ui->actionJob_MoveDown, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
217 //Enable menu
218 connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
219 connect(ui->actionCleanup_Finished, SIGNAL(triggered()), this, SLOT(cleanupActionTriggered()));
220 connect(ui->actionCleanup_Enqueued, SIGNAL(triggered()), this, SLOT(cleanupActionTriggered()));
221 connect(ui->actionPostOp_DoNothing, SIGNAL(triggered()), this, SLOT(postOpActionTriggered()));
222 connect(ui->actionPostOp_PowerDown, SIGNAL(triggered()), this, SLOT(postOpActionTriggered()));
223 connect(ui->actionPostOp_Hibernate, SIGNAL(triggered()), this, SLOT(postOpActionTriggered()));
224 connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
225 connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
226 connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
227 ui->actionCleanup_Finished->setData(QVariant(bool(0)));
228 ui->actionCleanup_Enqueued->setData(QVariant(bool(1)));
229 ui->actionPostOp_DoNothing->setData(QVariant(POST_OP_DONOTHING));
230 ui->actionPostOp_PowerDown->setData(QVariant(POST_OP_POWERDOWN));
231 ui->actionPostOp_Hibernate->setData(QVariant(POST_OP_HIBERNATE));
232 ui->actionPostOp_Hibernate->setEnabled(MUtils::OS::is_hibernation_supported());
234 //Setup web-links
235 SETUP_WEBLINK(ui->actionWebMulder, home_url);
236 SETUP_WEBLINK(ui->actionWebX264, "http://www.videolan.org/developers/x264.html");
237 SETUP_WEBLINK(ui->actionWebX265, "http://www.videolan.org/developers/x265.html");
238 SETUP_WEBLINK(ui->actionWebX264Komisar, "http://komisar.gin.by/");
239 SETUP_WEBLINK(ui->actionWebX264VideoLAN, "http://download.videolan.org/pub/x264/binaries/");
240 SETUP_WEBLINK(ui->actionWebX264FreeCodecs, "http://www.free-codecs.com/x264_video_codec_download.htm");
241 SETUP_WEBLINK(ui->actionWebX265Fllear, "http://x265.ru/en/builds/");
242 SETUP_WEBLINK(ui->actionWebX265LigH, "https://www.mediafire.com/?6lfp2jlygogwa");
243 SETUP_WEBLINK(ui->actionWebX265Snowfag, "http://builds.x265.eu/");
244 SETUP_WEBLINK(ui->actionWebX265FreeCodecs, "http://www.free-codecs.com/x265_hevc_encoder_download.htm");
245 SETUP_WEBLINK(ui->actionWebAvisynth32, "https://sourceforge.net/projects/avisynth2/files/AviSynth%202.6/");
246 SETUP_WEBLINK(ui->actionWebAvisynth64, "http://forum.doom9.org/showthread.php?t=152800");
247 SETUP_WEBLINK(ui->actionWebAvisynthPlus, "http://www.avs-plus.net/");
248 SETUP_WEBLINK(ui->actionWebVapourSynth, "http://www.vapoursynth.com/");
249 SETUP_WEBLINK(ui->actionWebVapourSynthDocs, "http://www.vapoursynth.com/doc/");
250 SETUP_WEBLINK(ui->actionOnlineDocX264, "http://en.wikibooks.org/wiki/MeGUI/x264_Settings"); //http://mewiki.project357.com/wiki/X264_Settings
251 SETUP_WEBLINK(ui->actionOnlineDocX265, "http://x265.readthedocs.org/en/default/");
252 SETUP_WEBLINK(ui->actionWebBluRay, "http://www.x264bluray.com/");
253 SETUP_WEBLINK(ui->actionWebAvsWiki, "http://avisynth.nl/index.php/Main_Page#Usage");
254 SETUP_WEBLINK(ui->actionWebSupport, "http://forum.doom9.org/showthread.php?t=144140");
255 SETUP_WEBLINK(ui->actionWebSecret, "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
257 //Create floating label
258 m_label[0].reset(new QLabel(ui->jobsView->viewport()));
259 m_label[1].reset(new QLabel(ui->logView->viewport()));
260 if(!m_label[0].isNull())
262 m_label[0]->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
263 m_label[0]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
264 SET_TEXT_COLOR(m_label[0], Qt::darkGray);
265 SET_FONT_BOLD(m_label[0], true);
266 m_label[0]->setVisible(true);
267 m_label[0]->setContextMenuPolicy(Qt::ActionsContextMenu);
268 m_label[0]->addActions(ui->jobsView->actions());
270 if(!m_label[1].isNull())
272 m_animation.reset(new QMovie(":/images/spinner.gif"));
273 m_label[1]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
274 if(!m_animation.isNull())
276 m_label[1]->setMovie(m_animation.data());
277 m_animation->start();
280 connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
281 updateLabelPos();
283 //Init system tray icon
284 m_sysTray.reset(new QSystemTrayIcon(this));
285 m_sysTray->setToolTip(this->windowTitle());
286 m_sysTray->setIcon(this->windowIcon());
287 connect(m_sysTray.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(sysTrayActived()));
289 //Init taskbar progress
290 m_taskbar.reset(new MUtils::Taskbar7(this));
292 //Create corner widget
293 QLabel *checkUp = new QLabel(ui->menubar);
294 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")));
295 checkUp->setFixedHeight(ui->menubar->height());
296 checkUp->setCursor(QCursor(Qt::PointingHandCursor));
297 m_inputFilter_checkUp.reset(new InputEventFilter(checkUp));
298 m_inputFilter_checkUp->addMouseFilter(Qt::LeftButton, 0);
299 m_inputFilter_checkUp->addMouseFilter(Qt::RightButton, 0);
300 connect(m_inputFilter_checkUp.data(), SIGNAL(mouseClicked(int)), this, SLOT(checkUpdates()));
301 checkUp->hide();
302 ui->menubar->setCornerWidget(checkUp);
304 //Create timer
305 m_fileTimer.reset(new QTimer(this));
306 connect(m_fileTimer.data(), SIGNAL(timeout()), this, SLOT(handlePendingFiles()));
310 * Destructor
312 MainWindow::~MainWindow(void)
314 OptionsModel::saveTemplate(m_options.data(), QString::fromLatin1(tpl_last));
316 if(!m_ipcThread.isNull())
318 m_ipcThread->stop();
319 if(!m_ipcThread->wait(5000))
321 m_ipcThread->terminate();
322 m_ipcThread->wait();
326 delete ui;
329 ///////////////////////////////////////////////////////////////////////////////
330 // Slots
331 ///////////////////////////////////////////////////////////////////////////////
334 * The "add" button was clicked
336 void MainWindow::addButtonPressed()
338 ENSURE_APP_IS_READY();
340 qDebug("MainWindow::addButtonPressed");
341 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
342 QString sourceFileName, outputFileName;
344 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
346 appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
351 * The "open" action was triggered
353 void MainWindow::openActionTriggered()
355 ENSURE_APP_IS_READY();
356 qWarning("openActionTriggered()");
358 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
359 if(!fileList.empty())
361 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
362 if(fileList.count() > 1)
364 createJobMultiple(fileList);
366 else
368 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
369 QString sourceFileName(fileList.first()), outputFileName;
370 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
372 appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
379 * The "clean-up" action was invoked
381 void MainWindow::cleanupActionTriggered(void)
383 ENSURE_APP_IS_READY();
385 QAction *const sender = dynamic_cast<QAction*>(QObject::sender());
386 if (sender)
388 const QVariant data = sender->data();
389 if (data.isValid() && (data.type() == QVariant::Bool))
391 const bool mode = data.toBool();
392 const int rows = m_jobList->rowCount(QModelIndex());
393 QList<int> jobIndices;
394 for (int i = 0; i < rows; i++)
396 const JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
397 if (mode && (status == JobStatus_Enqueued))
399 jobIndices.append(i);
401 else if ((!mode) && ((status == JobStatus_Completed) || (status == JobStatus_Aborted) || (status == JobStatus_Failed)))
403 jobIndices.append(i);
406 if (!jobIndices.isEmpty())
408 QListIterator<int> iter(jobIndices);
409 iter.toBack();
410 while(iter.hasPrevious())
412 m_jobList->deleteJob(m_jobList->index(iter.previous(), 0, QModelIndex()));
415 else
417 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
424 * The "clean-up" action was invoked
426 void MainWindow::postOpActionTriggered(void)
428 ENSURE_APP_IS_READY();
430 QAction *const sender = dynamic_cast<QAction*>(QObject::sender());
431 if (sender)
433 const QVariant data = sender->data();
434 if (data.isValid() && (data.type() == QVariant::Int))
436 const postOp_t mode = (postOp_t)data.toInt();
437 if ((mode >= POST_OP_DONOTHING) && (mode <= POST_OP_HIBERNATE))
439 m_postOperation = mode;
440 ui->actionPostOp_PowerDown->setChecked(mode == POST_OP_POWERDOWN);
441 ui->actionPostOp_Hibernate->setChecked(mode == POST_OP_HIBERNATE);
442 ui->actionPostOp_DoNothing->setChecked(mode == POST_OP_DONOTHING);
449 * The "start" button was clicked
451 void MainWindow::startButtonPressed(void)
453 ENSURE_APP_IS_READY();
454 m_jobList->startJob(ui->jobsView->currentIndex());
458 * The "abort" button was clicked
460 void MainWindow::abortButtonPressed(void)
462 ENSURE_APP_IS_READY();
464 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)
466 m_jobList->abortJob(ui->jobsView->currentIndex());
471 * The "delete" button was clicked
473 void MainWindow::deleteButtonPressed(void)
475 ENSURE_APP_IS_READY();
477 m_jobList->deleteJob(ui->jobsView->currentIndex());
478 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
482 * The "browse" button was clicked
484 void MainWindow::browseButtonPressed(void)
486 ENSURE_APP_IS_READY();
488 QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
489 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
491 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
493 else
495 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
500 * The "browse" button was clicked
502 void MainWindow::moveButtonPressed(void)
504 ENSURE_APP_IS_READY();
506 if(sender() == ui->actionJob_MoveUp)
508 qDebug("Move job %d (direction: UP)", ui->jobsView->currentIndex().row());
509 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_UP))
511 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
513 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
515 else if(sender() == ui->actionJob_MoveDown)
517 qDebug("Move job %d (direction: DOWN)", ui->jobsView->currentIndex().row());
518 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_DOWN))
520 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
522 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
524 else
526 qWarning("[moveButtonPressed] Error: Unknown sender!");
531 * The "pause" button was clicked
533 void MainWindow::pauseButtonPressed(bool checked)
535 if(!APP_IS_READY)
537 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
538 qWarning("Cannot perfrom this action at this time!");
539 ui->buttonPauseJob->setChecked(!checked);
542 if(checked)
544 m_jobList->pauseJob(ui->jobsView->currentIndex());
546 else
548 m_jobList->resumeJob(ui->jobsView->currentIndex());
553 * The "restart" button was clicked
555 void MainWindow::restartButtonPressed(void)
557 ENSURE_APP_IS_READY();
559 const QModelIndex index = ui->jobsView->currentIndex();
560 const OptionsModel *options = m_jobList->getJobOptions(index);
561 QString sourceFileName = m_jobList->getJobSourceFile(index);
562 QString outputFileName = m_jobList->getJobOutputFile(index);
564 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
566 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
567 OptionsModel *tempOptions = new OptionsModel(*options);
568 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
570 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
572 MUTILS_DELETE(tempOptions);
577 * Job item selected by user
579 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
581 qDebug("Job selected: %d", current.row());
583 if(ui->logView->model())
585 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
588 if(current.isValid())
590 ui->logView->setModel(m_jobList->getLogFile(current));
591 connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
592 foreach(QAction *action, ui->logView->actions())
594 action->setEnabled(true);
596 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
598 ui->progressBar->setValue(m_jobList->getJobProgress(current));
599 ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
600 updateButtons(m_jobList->getJobStatus(current));
601 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
603 else
605 ui->logView->setModel(NULL);
606 foreach(QAction *action, ui->logView->actions())
608 action->setEnabled(false);
610 ui->progressBar->setValue(0);
611 ui->editDetails->clear();
612 updateButtons(JobStatus_Undefined);
613 updateTaskbar(JobStatus_Undefined, QIcon());
616 ui->progressBar->repaint();
620 * Handle update of job info (status, progress, details, etc)
622 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
624 int selected = ui->jobsView->currentIndex().row();
626 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
628 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
630 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
631 if(i == selected)
633 qDebug("Current job changed status!");
634 updateButtons(status);
635 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
637 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
639 if(m_preferences->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
640 if(m_preferences->getSaveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
644 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
646 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
648 if(i == selected)
650 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
651 if(!m_taskbar.isNull())
653 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
655 break;
659 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
661 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
663 if(i == selected)
665 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
666 break;
673 * Handle new log file content
675 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
677 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
681 * About screen
683 void MainWindow::showAbout(void)
685 ENSURE_APP_IS_READY();
687 if(AboutDialog *aboutDialog = new AboutDialog(this))
689 aboutDialog->exec();
690 MUTILS_DELETE(aboutDialog);
695 * Open web-link
697 void MainWindow::showWebLink(void)
699 ENSURE_APP_IS_READY();
701 if(QObject *obj = QObject::sender())
703 if(QAction *action = dynamic_cast<QAction*>(obj))
705 if(action->data().type() == QVariant::Url)
707 QDesktopServices::openUrl(action->data().toUrl());
714 * Pereferences dialog
716 void MainWindow::showPreferences(void)
718 ENSURE_APP_IS_READY();
720 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences.data(), m_sysinfo.data());
721 preferences->exec();
723 MUTILS_DELETE(preferences);
727 * Launch next job, after running job has finished
729 void MainWindow::launchNextJob(void)
731 qDebug("Launching next job...");
733 if(countRunningJobs() >= m_preferences->getMaxRunningJobCount())
735 qDebug("Still have too many jobs running, won't launch next one yet!");
736 return;
739 const int rows = m_jobList->rowCount(QModelIndex());
741 for(int i = 0; i < rows; i++)
743 const QModelIndex currentIndex = m_jobList->index(i, 0, QModelIndex());
744 if(m_jobList->getJobStatus(currentIndex) == JobStatus_Enqueued)
746 if(m_jobList->startJob(currentIndex))
748 ui->jobsView->selectRow(currentIndex.row());
749 return;
754 qWarning("No enqueued jobs left to be started!");
756 if(m_postOperation)
758 qDebug("Post operation has been scheduled! (m_postOperation: %d)", m_postOperation);
759 QTimer::singleShot(0, this, SLOT(shutdownComputer()));
764 * Save log to text file
766 void MainWindow::saveLogFile(const QModelIndex &index)
768 if(index.isValid())
770 const LogFileModel *const logData = m_jobList->getLogFile(index);
771 const QString &outputFilePath = m_jobList->getJobOutputFile(index);
772 if(logData && (!outputFilePath.isEmpty()))
774 const QFileInfo outputFileInfo(outputFilePath);
775 if (outputFileInfo.absoluteDir().exists())
777 const QString outputDir = outputFileInfo.absolutePath(), outputName = outputFileInfo.fileName();
778 const QString logFilePath = MUtils::make_unique_file(outputDir, outputName, QLatin1String("log"), true);
779 if (!logFilePath.isEmpty())
781 qDebug("Saving log file to: \"%s\"", MUTILS_UTF8(logFilePath));
782 if (!logData->saveToLocalFile(logFilePath))
784 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
787 else
789 qWarning("Failed to generate log file name. Giving up!");
792 else
794 qWarning("Output directory does not seem to exist. Giving up!");
801 * Shut down the computer (with countdown)
803 void MainWindow::shutdownComputer(void)
805 ENSURE_APP_IS_READY();
806 qDebug("shutdownComputer (m_postOperation: %d)", m_postOperation);
808 if(countPendingJobs() > 0)
810 qWarning("Still have pending jobs, won't shutdown yet!");
811 return;
814 if ((m_postOperation != POST_OP_POWERDOWN) && (m_postOperation != POST_OP_HIBERNATE))
816 qWarning("No post-operation has been schedule!");
819 const int iTimeout = 30;
820 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
821 const bool hibernate = (m_postOperation == POST_OP_HIBERNATE);
822 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..."));
824 qWarning("Initiating shutdown sequence!");
826 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
827 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
828 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
829 progressDialog.setModal(true);
830 progressDialog.setAutoClose(false);
831 progressDialog.setAutoReset(false);
832 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
833 progressDialog.setWindowTitle(windowTitle());
834 progressDialog.setCancelButton(cancelButton);
835 progressDialog.show();
837 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
838 QApplication::setOverrideCursor(Qt::WaitCursor);
839 MUtils::Sound::play_sound("shutdown", false);
840 QApplication::restoreOverrideCursor();
842 QTimer timer;
843 timer.setInterval(1000);
844 timer.start();
846 QEventLoop eventLoop(this);
847 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
848 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
850 for(int i = 1; i <= iTimeout; i++)
852 eventLoop.exec();
853 if(progressDialog.wasCanceled())
855 progressDialog.close();
856 return;
858 progressDialog.setValue(i+1);
859 progressDialog.setLabelText(text.arg(iTimeout-i));
860 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
861 QApplication::processEvents();
862 MUtils::Sound::play_sound(((i < iTimeout) ? "beep" : "beep2"), false);
865 qWarning("Shutting down !!!");
867 if(MUtils::OS::shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true, hibernate))
869 qApp->closeAllWindows();
875 * Main initialization function (called only once!)
877 void MainWindow::init(void)
879 if(m_initialized)
881 qWarning("Already initialized -> skipping!");
882 return;
885 updateLabelPos();
886 const MUtils::OS::ArgumentMap &arguments = MUtils::OS::arguments();
887 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
889 //---------------------------------------
890 // Check required binaries
891 //---------------------------------------
893 qDebug("[Validating binaries]");
894 if(!BinariesCheckThread::check(m_sysinfo.data()))
896 QMessageBox::critical(this, tr("Invalid File!"), tr("<nobr>At least one tool is missing or is not a valid Win32/Win64 binary.<br>Please re-install the program in order to fix the problem!</nobr>").replace("-", "&minus;"));
897 qFatal("At least one tool is missing or is not a valid Win32/Win64 binary!");
899 qDebug(" ");
901 //---------------------------------------
902 // Check for portable mode
903 //---------------------------------------
905 if(x264_is_portable())
907 bool ok = false;
908 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
909 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
910 if(writeTest.open(QIODevice::WriteOnly))
912 ok = (writeTest.write(data) == strlen(data));
913 writeTest.remove();
915 if(!ok)
917 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"));
918 if(val != 1) INIT_ERROR_EXIT();
922 //Pre-release popup
923 if(x264_is_prerelease())
925 qsrand(time(NULL)); int rnd = qrand() % 3;
926 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);
927 if(rnd != val) INIT_ERROR_EXIT();
930 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
932 //---------------------------------------
933 // Check CPU capabilities
934 //---------------------------------------
936 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
937 if(!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_MMX))
939 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"));
940 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
941 INIT_ERROR_EXIT();
943 else if(!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_SSE))
945 qWarning("WARNING: System does not support SSE (v1), x264/x265 probably will *not* work !!!\n");
946 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"));
947 if(val != 1) INIT_ERROR_EXIT();
950 //Skip version check (not recommended!)
951 if(arguments.contains(CLI_PARAM_SKIP_VERSION_CHECK))
953 qWarning("Version checks are disabled now, you have been warned!\n");
954 m_preferences->setSkipVersionTest(true);
957 //Don't abort encoding process on timeout (not recommended!)
958 if(arguments.contains(CLI_PARAM_NO_DEADLOCK))
960 qWarning("Deadlock detection disabled, you have been warned!\n");
961 m_preferences->setAbortOnTimeout(false);
964 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
966 //---------------------------------------
967 // Check Avisynth support
968 //---------------------------------------
970 if(!arguments.contains(CLI_PARAM_SKIP_AVS_CHECK))
972 qDebug("[Check for Avisynth support]");
973 if(!AvisynthCheckThread::detect(m_sysinfo.data()))
975 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
976 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
977 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
978 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
979 if(val != 1) INIT_ERROR_EXIT();
981 else if((!m_sysinfo->hasAvisynth()) && (!m_preferences->getDisableWarnings()))
983 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>");
984 text += tr("Please download and install Avisynth:").append("<br>").append(LINK(avs_dl_url));
985 int val = QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
986 if(val == 1)
988 m_preferences->setDisableWarnings(true);
989 PreferencesModel::savePreferences(m_preferences.data());
992 qDebug(" ");
995 //---------------------------------------
996 // Check VapurSynth support
997 //---------------------------------------
999 if(!arguments.contains(CLI_PARAM_SKIP_VPS_CHECK))
1001 qDebug("[Check for VapourSynth support]");
1002 if(!VapourSynthCheckThread::detect(m_sysinfo.data()))
1004 QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
1005 text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
1006 text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
1007 const int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
1008 if(val != 1) INIT_ERROR_EXIT();
1010 else if((!m_sysinfo->hasVapourSynth()) && (!m_preferences->getDisableWarnings()))
1012 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>");
1013 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>");
1014 text += tr("Note that Python v3.4 is a prerequisite for installing VapourSynth:").append("<br>").append(LINK(python_url)).append("<br>");
1015 const int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
1016 if(val == 1)
1018 m_preferences->setDisableWarnings(true);
1019 PreferencesModel::savePreferences(m_preferences.data());
1022 qDebug(" ");
1025 //---------------------------------------
1026 // Create the IPC listener thread
1027 //---------------------------------------
1029 if(m_ipcChannel)
1031 m_ipcThread.reset(new IPCThread_Recv(m_ipcChannel));
1032 connect(m_ipcThread.data(), SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
1033 m_ipcThread->start();
1036 //---------------------------------------
1037 // Finish initialization
1038 //---------------------------------------
1040 //Set Window title
1041 setWindowTitle(QString("%1 (%2)").arg(windowTitle(), m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_X64) ? "64-Bit" : "32-Bit"));
1043 //Enable drag&drop support for this window, required for Qt v4.8.4+
1044 setAcceptDrops(true);
1046 //Update flag
1047 m_initialized = true;
1049 //Hide the spinner animation
1050 if(!m_label[1].isNull())
1052 if(!m_animation.isNull())
1054 m_animation->stop();
1056 m_label[1]->setVisible(false);
1059 //---------------------------------------
1060 // Check for Expiration
1061 //---------------------------------------
1063 if(MUtils::Version::app_build_date().addMonths(6) < MUtils::OS::current_date())
1065 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
1066 QString text;
1067 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;"));
1068 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;"));
1069 text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace('-', "&minus;"));
1070 QMessageBox msgBox(this);
1071 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
1072 msgBox.setWindowTitle(tr("Update Notification"));
1073 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
1074 msgBox.setText(text);
1075 QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
1076 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
1077 QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
1078 btn2->setEnabled(false);
1079 btn3->setVisible(false);
1080 QTimer::singleShot(7500, btn2, SLOT(hide()));
1081 QTimer::singleShot(7500, btn3, SLOT(show()));
1082 if(msgBox.exec() == 0)
1084 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1085 return;
1088 else if(!parseCommandLineArgs())
1090 //Update reminder
1091 if(arguments.contains(CLI_PARAM_FIRST_RUN))
1093 qWarning("First run -> resetting update check now!");
1094 m_recentlyUsed->setLastUpdateCheck(0);
1095 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
1097 else if(m_recentlyUsed->lastUpdateCheck() + 14 < MUtils::OS::current_date().toJulianDay())
1099 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
1100 if(!m_preferences->getNoUpdateReminder())
1102 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)
1104 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1105 return;
1111 //Load queued jobs
1112 if(m_jobList->loadQueuedJobs(m_sysinfo.data()) > 0)
1114 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1115 m_jobList->clearQueuedJobs();
1120 * Update the label position
1122 void MainWindow::updateLabelPos(void)
1124 for(int i = 0; i < 2; i++)
1126 //const QWidget *const viewPort = ui->jobsView->viewport();
1127 const QWidget *const viewPort = dynamic_cast<QWidget*>(m_label[i]->parent());
1128 if(viewPort)
1130 m_label[i]->setGeometry(0, 0, viewPort->width(), viewPort->height());
1136 * Copy the complete log to the clipboard
1138 void MainWindow::copyLogToClipboard(bool checked)
1140 qDebug("Coyping logfile to clipboard...");
1142 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1144 log->copyToClipboard();
1145 MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
1150 * Save log to local file
1152 void MainWindow::saveLogToLocalFile(bool checked)
1154 ENSURE_APP_IS_READY();
1156 const QModelIndex index = ui->jobsView->currentIndex();
1157 const QString initialName = index.isValid() ? QFileInfo(m_jobList->getJobOutputFile(index)).completeBaseName() : tr("Logfile");
1158 const QString fileName = QFileDialog::getSaveFileName(this, tr("Save Log File"), initialName, tr("Log File (*.log)"));
1159 if(!fileName.isEmpty())
1161 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1163 if(!log->saveToLocalFile(fileName))
1165 QMessageBox::warning(this, this->windowTitle(), tr("Error: Log file could not be saved!"));
1172 * Toggle line-wrapping
1174 void MainWindow::toggleLineWrapping(bool checked)
1176 ui->logView->setWordWrap(checked);
1180 * Process the dropped files
1182 void MainWindow::handlePendingFiles(void)
1184 qDebug("MainWindow::handlePendingFiles");
1186 if(!m_pendingFiles->isEmpty())
1188 QStringList pendingFiles(*m_pendingFiles);
1189 m_pendingFiles->clear();
1190 createJobMultiple(pendingFiles);
1193 qDebug("Leave from MainWindow::handlePendingFiles!");
1197 * Handle incoming IPC command
1199 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1201 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1203 qWarning("Cannot accapt commands at this time -> discarding!");
1204 return;
1207 if((!isVisible()) || m_sysTray->isVisible())
1209 sysTrayActived();
1212 MUtils::GUI::bring_to_front(this);
1214 #ifdef IPC_LOGGING
1215 qDebug("\n---------- IPC ----------");
1216 qDebug("CommandId: %d", command);
1217 for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1219 qDebug("Arguments: %s", iter->toUtf8().constData());
1221 qDebug("The Flags: 0x%08X", flags);
1222 qDebug("---------- IPC ----------\n");
1223 #endif //IPC_LOGGING
1225 switch(command)
1227 case IPC_OPCODE_PING:
1228 qDebug("Received a PING request from another instance!");
1229 MUtils::GUI::blink_window(this, 5, 125);
1230 break;
1231 case IPC_OPCODE_ADD_FILE:
1232 if(!args.isEmpty())
1234 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1236 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1237 if(!m_fileTimer->isActive())
1239 m_fileTimer->setSingleShot(true);
1240 m_fileTimer->start(5000);
1243 else
1245 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1248 break;
1249 case IPC_OPCODE_ADD_JOB:
1250 if(args.size() >= 3)
1252 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1254 OptionsModel options(m_sysinfo.data());
1255 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1256 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1258 if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1260 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1263 if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
1264 if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
1265 appendJob(args[0], args[1], &options, runImmediately);
1267 else
1269 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1272 break;
1273 default:
1274 MUTILS_THROW("Unknown command received!");
1279 * Check for new updates
1281 void MainWindow::checkUpdates(void)
1283 ENSURE_APP_IS_READY();
1285 if(countRunningJobs() > 0)
1287 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1288 return;
1291 UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo.data(), update_url);
1292 const int ret = updater->exec();
1294 if(updater->getSuccess())
1296 m_recentlyUsed->setLastUpdateCheck(MUtils::OS::current_date().toJulianDay());
1297 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
1298 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->hide();
1301 if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1303 qWarning("Exitting program to install update...");
1304 close();
1305 QApplication::quit();
1308 MUTILS_DELETE(updater);
1312 * Handle mouse event for version label
1314 void MainWindow::versionLabelMouseClicked(const int &tag)
1316 if(tag == 0)
1318 QTimer::singleShot(0, this, SLOT(showAbout()));
1323 * Handle key event for job list
1325 void MainWindow::jobListKeyPressed(const int &tag)
1327 switch(tag)
1329 case 1:
1330 ui->actionJob_MoveUp->trigger();
1331 break;
1332 case 2:
1333 ui->actionJob_MoveDown->trigger();
1334 break;
1339 * System tray was activated
1341 void MainWindow::sysTrayActived(void)
1343 m_sysTray->hide();
1344 showNormal();
1345 MUtils::GUI::bring_to_front(this);
1348 ///////////////////////////////////////////////////////////////////////////////
1349 // Event functions
1350 ///////////////////////////////////////////////////////////////////////////////
1353 * Window shown event
1355 void MainWindow::showEvent(QShowEvent *e)
1357 QMainWindow::showEvent(e);
1359 if(!m_initialized)
1361 QTimer::singleShot(0, this, SLOT(init()));
1366 * Window close event
1368 void MainWindow::closeEvent(QCloseEvent *e)
1370 if(!APP_IS_READY)
1372 e->ignore();
1373 qWarning("Cannot close window at this time!");
1374 return;
1377 //Make sure we have no running jobs left!
1378 if(countRunningJobs() > 0)
1380 e->ignore();
1381 if(!m_preferences->getNoSystrayWarning())
1383 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)
1385 m_preferences->setNoSystrayWarning(true);
1386 PreferencesModel::savePreferences(m_preferences.data());
1389 hide();
1390 m_sysTray->show();
1391 return;
1394 //Save pending jobs for next time, if desired by user
1395 if(countPendingJobs() > 0)
1397 if (!m_preferences->getSaveQueueNoConfirm())
1399 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"));
1400 if ((ret >= 0) && (ret <= 1))
1402 if (ret > 0)
1404 m_preferences->setSaveQueueNoConfirm(true);
1405 PreferencesModel::savePreferences(m_preferences.data());
1407 m_jobList->saveQueuedJobs();
1410 else
1412 m_jobList->saveQueuedJobs();
1416 //Delete remaining jobs
1417 while(m_jobList->rowCount(QModelIndex()) > 0)
1419 if((m_jobList->rowCount(QModelIndex()) % 10) == 0)
1421 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1423 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1425 e->ignore();
1426 QMessageBox::warning(this, tr("Failed To Exit"), tr("Warning: At least one job could not be deleted!"));
1430 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1431 QMainWindow::closeEvent(e);
1435 * Window resize event
1437 void MainWindow::resizeEvent(QResizeEvent *e)
1439 QMainWindow::resizeEvent(e);
1440 updateLabelPos();
1444 * File dragged over window
1446 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1448 bool accept[2] = {false, false};
1450 foreach(const QString &fmt, event->mimeData()->formats())
1452 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1453 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1456 if(accept[0] && accept[1])
1458 event->acceptProposedAction();
1463 * File dropped onto window
1465 void MainWindow::dropEvent(QDropEvent *event)
1467 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1469 qWarning("Cannot accept dropped files at this time -> discarding!");
1470 return;
1473 QStringList droppedFiles;
1474 QList<QUrl> urls = event->mimeData()->urls();
1476 while(!urls.isEmpty())
1478 QUrl currentUrl = urls.takeFirst();
1479 QFileInfo file(currentUrl.toLocalFile());
1480 if(file.exists() && file.isFile())
1482 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1483 droppedFiles << file.canonicalFilePath();
1487 if(droppedFiles.count() > 0)
1489 m_pendingFiles->append(droppedFiles);
1490 m_pendingFiles->sort();
1491 if(!m_fileTimer->isActive())
1493 m_fileTimer->setSingleShot(true);
1494 m_fileTimer->start(5000);
1499 ///////////////////////////////////////////////////////////////////////////////
1500 // Private functions
1501 ///////////////////////////////////////////////////////////////////////////////
1504 * Creates a new job
1506 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1508 bool okay = false;
1509 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed.data(), m_sysinfo.data(), m_preferences.data());
1511 addDialog->setRunImmediately(runImmediately);
1512 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1513 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1514 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1516 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1517 if(multiFile)
1519 addDialog->setSourceEditable(false);
1520 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1521 addDialog->setApplyToAllVisible(applyToAll);
1524 if(addDialog->exec() == QDialog::Accepted)
1526 sourceFileName = addDialog->sourceFile();
1527 outputFileName = addDialog->outputFile();
1528 runImmediately = addDialog->runImmediately();
1529 if(applyToAll)
1531 *applyToAll = addDialog->applyToAll();
1533 okay = true;
1536 MUTILS_DELETE(addDialog);
1537 return okay;
1541 * Creates a new job from *multiple* files
1543 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1545 QStringList::ConstIterator iter;
1546 bool applyToAll = false, runImmediately = false;
1547 int counter = 0;
1549 //Add files individually
1550 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1552 runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1553 QString sourceFileName(*iter), outputFileName;
1554 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1556 if(appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
1558 continue;
1561 return false;
1564 //Add remaining files
1565 while(applyToAll && (iter != filePathIn.constEnd()))
1567 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1568 const QString sourceFileName = *iter;
1569 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
1570 if(!appendJob(sourceFileName, outputFileName, m_options.data(), runImmediatelyTmp))
1572 return false;
1574 iter++;
1577 return true;
1581 * Append a new job
1583 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1585 bool okay = false;
1586 EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo.data(), m_preferences.data());
1587 QModelIndex newIndex = m_jobList->insertJob(thrd);
1589 if(newIndex.isValid())
1591 if(runImmediately)
1593 ui->jobsView->selectRow(newIndex.row());
1594 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1595 m_jobList->startJob(newIndex);
1598 okay = true;
1601 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1602 return okay;
1606 * Jobs that are not completed (or failed, or aborted) yet
1608 unsigned int MainWindow::countPendingJobs(void)
1610 unsigned int count = 0;
1611 const int rows = m_jobList->rowCount(QModelIndex());
1613 for(int i = 0; i < rows; i++)
1615 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1616 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1618 count++;
1622 return count;
1626 * Jobs that are still active, i.e. not terminated or enqueued
1628 unsigned int MainWindow::countRunningJobs(void)
1630 unsigned int count = 0;
1631 const int rows = m_jobList->rowCount(QModelIndex());
1633 for(int i = 0; i < rows; i++)
1635 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1636 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1638 count++;
1642 return count;
1646 * Update all buttons with respect to current job status
1648 void MainWindow::updateButtons(JobStatus status)
1650 qDebug("MainWindow::updateButtons(void)");
1652 ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1653 ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1654 ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1655 ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1657 ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1658 ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1659 ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1660 ui->actionJob_MoveUp->setEnabled(status != JobStatus_Undefined);
1661 ui->actionJob_MoveDown->setEnabled(status != JobStatus_Undefined);
1663 ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1664 ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1665 ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1666 ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1668 ui->editDetails->setEnabled(status != JobStatus_Paused);
1672 * Update the taskbar with current job status
1674 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1676 qDebug("MainWindow::updateTaskbar(void)");
1678 if(m_taskbar.isNull())
1680 return; /*taskbar object not created yet*/
1683 switch(status)
1685 case JobStatus_Undefined:
1686 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE);
1687 break;
1688 case JobStatus_Aborting:
1689 case JobStatus_Starting:
1690 case JobStatus_Pausing:
1691 case JobStatus_Resuming:
1692 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_INTERMEDIATE);
1693 break;
1694 case JobStatus_Aborted:
1695 case JobStatus_Failed:
1696 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR);
1697 break;
1698 case JobStatus_Paused:
1699 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_PAUSED);
1700 break;
1701 default:
1702 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL);
1703 break;
1706 switch(status)
1708 case JobStatus_Aborting:
1709 case JobStatus_Starting:
1710 case JobStatus_Pausing:
1711 case JobStatus_Resuming:
1712 break;
1713 default:
1714 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
1715 break;
1718 m_taskbar->setOverlayIcon(icon.isNull() ? NULL : &icon);
1722 * Parse command-line arguments
1724 bool MainWindow::parseCommandLineArgs(void)
1726 const MUtils::OS::ArgumentMap &args = MUtils::OS::arguments();
1728 quint32 flags = 0;
1729 bool commandSent = false;
1731 //Handle flags
1732 if(args.contains(CLI_PARAM_FORCE_START))
1734 flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1736 if(args.contains(CLI_PARAM_FORCE_ENQUEUE))
1738 flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1741 //Process all command-line arguments
1742 if(args.contains(CLI_PARAM_ADD_FILE))
1744 foreach(const QString &fileName, args.values(CLI_PARAM_ADD_FILE))
1746 handleCommand(IPC_OPCODE_ADD_FILE, QStringList() << fileName, flags);
1748 commandSent = true;
1750 if(args.contains(CLI_PARAM_ADD_JOB))
1752 foreach(const QString &options, args.values(CLI_PARAM_ADD_JOB))
1754 const QStringList optionValues = options.split('|', QString::SkipEmptyParts);
1755 if(optionValues.count() == 3)
1757 handleCommand(IPC_OPCODE_ADD_JOB, optionValues, flags);
1759 else
1761 qWarning("Invalid number of arguments for parameter \"--%s\" detected!", CLI_PARAM_ADD_JOB);
1764 commandSent = true;
1767 return commandSent;