Refactored code to better manage the encoder binary paths: They are now handled by...
[simple-x264-launcher.git] / src / win_main.cpp
blob935b9b3b52dcf35b6dee86f21cd5920771b2e76c
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2015 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 "binaries.h"
46 #include "resource.h"
48 //MUtils
49 #include <MUtils/OSSupport.h>
50 #include <MUtils/CPUFeatures.h>
51 #include <MUtils/IPCChannel.h>
52 #include <MUtils/GUI.h>
53 #include <MUtils/Sound.h>
54 #include <MUtils/Exception.h>
55 #include <MUtils/Taskbar7.h>
56 #include <MUtils/Version.h>
58 //Qt
59 #include <QDate>
60 #include <QTimer>
61 #include <QCloseEvent>
62 #include <QMessageBox>
63 #include <QDesktopServices>
64 #include <QUrl>
65 #include <QDir>
66 #include <QLibrary>
67 #include <QProcess>
68 #include <QProgressDialog>
69 #include <QScrollBar>
70 #include <QTextStream>
71 #include <QSettings>
72 #include <QFileDialog>
73 #include <QSystemTrayIcon>
74 #include <QMovie>
76 #include <ctime>
78 //Constants
79 static const char *tpl_last = "<LAST_USED>";
80 static const char *home_url = "http://muldersoft.com/";
81 static const char *update_url = "https://github.com/lordmulder/Simple-x264-Launcher/releases/latest";
82 static const char *avs_dl_url = "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/";
83 static const char *python_url = "https://www.python.org/downloads/";
84 static const char *vsynth_url = "http://www.vapoursynth.com/";
85 static const int vsynth_rev = 24;
87 //Macros
88 #define SET_FONT_BOLD(WIDGET,BOLD) do { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); } while(0)
89 #define SET_TEXT_COLOR(WIDGET,COLOR) do { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); } while(0)
90 #define LINK(URL) (QString("<a href=\"%1\">%1</a>").arg((URL)))
91 #define INIT_ERROR_EXIT() do { close(); qApp->exit(-1); return; } while(0)
92 #define SETUP_WEBLINK(OBJ, URL) do { (OBJ)->setData(QVariant(QUrl(URL))); connect((OBJ), SIGNAL(triggered()), this, SLOT(showWebLink())); } while(0)
93 #define APP_IS_READY (m_initialized && (!m_fileTimer->isActive()) && (QApplication::activeModalWidget() == NULL))
94 #define ENSURE_APP_IS_READY() do { if(!APP_IS_READY) { MUtils::Sound::beep(MUtils::Sound::BEEP_WRN); qWarning("Cannot perfrom this action at this time!"); return; } } while(0)
95 #define X264_STRCMP(X,Y) ((X).compare((Y), Qt::CaseInsensitive) == 0)
97 ///////////////////////////////////////////////////////////////////////////////
98 // Constructor & Destructor
99 ///////////////////////////////////////////////////////////////////////////////
102 * Constructor
104 MainWindow::MainWindow(const MUtils::CPUFetaures::cpu_info_t &cpuFeatures, MUtils::IPCChannel *const ipcChannel)
106 m_ipcChannel(ipcChannel),
107 m_sysinfo(NULL),
108 m_options(NULL),
109 m_jobList(NULL),
110 m_pendingFiles(new QStringList()),
111 m_preferences(NULL),
112 m_recentlyUsed(NULL),
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::Fixed);
170 ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
171 ui->jobsView->horizontalHeader()->resizeSection(1, 150);
172 ui->jobsView->horizontalHeader()->resizeSection(2, 90);
173 ui->jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
174 connect(ui->jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
176 //Setup key listener
177 m_inputFilter_jobList.reset(new InputEventFilter(ui->jobsView));
178 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Up, 1);
179 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Down, 2);
180 connect(m_inputFilter_jobList.data(), SIGNAL(keyPressed(int)), this, SLOT(jobListKeyPressed(int)));
182 //Setup mouse listener
183 m_inputFilter_version.reset(new InputEventFilter(ui->labelBuildDate));
184 m_inputFilter_version->addMouseFilter(Qt::LeftButton, 0);
185 m_inputFilter_version->addMouseFilter(Qt::RightButton, 0);
186 connect(m_inputFilter_version.data(), SIGNAL(mouseClicked(int)), this, SLOT(versionLabelMouseClicked(int)));
188 //Create context menu
189 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), ui->logView);
190 QAction *actionSaveToLog = new QAction(QIcon(":/buttons/disk.png"), tr("Save to File..."), ui->logView);
191 QAction *actionSeparator = new QAction(ui->logView);
192 QAction *actionWordwraps = new QAction(QIcon(":/buttons/text_wrapping.png"), tr("Enable Line-Wrapping"), ui->logView);
193 actionSeparator->setSeparator(true);
194 actionWordwraps->setCheckable(true);
195 actionClipboard->setEnabled(false);
196 actionSaveToLog->setEnabled(false);
197 actionWordwraps->setEnabled(false);
198 ui->logView->addAction(actionClipboard);
199 ui->logView->addAction(actionSaveToLog);
200 ui->logView->addAction(actionSeparator);
201 ui->logView->addAction(actionWordwraps);
202 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
203 connect(actionSaveToLog, SIGNAL(triggered(bool)), this, SLOT(saveLogToLocalFile(bool)));
204 connect(actionWordwraps, SIGNAL(triggered(bool)), this, SLOT(toggleLineWrapping(bool)));
205 ui->jobsView->addActions(ui->menuJob->actions());
207 //Enable buttons
208 connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed() ));
209 connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed() ));
210 connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed() ));
211 connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
212 connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed() ));
213 connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed() ));
214 connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed() ));
215 connect(ui->actionJob_MoveUp, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
216 connect(ui->actionJob_MoveDown, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
218 //Enable menu
219 connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
220 connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
221 connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
222 connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
224 //Setup web-links
225 SETUP_WEBLINK(ui->actionWebMulder, home_url);
226 SETUP_WEBLINK(ui->actionWebX264, "http://www.videolan.org/developers/x264.html");
227 SETUP_WEBLINK(ui->actionWebX265, "http://www.videolan.org/developers/x265.html");
228 SETUP_WEBLINK(ui->actionWebKomisar, "http://komisar.gin.by/");
229 SETUP_WEBLINK(ui->actionWebVideoLAN, "http://download.videolan.org/pub/x264/binaries/");
230 SETUP_WEBLINK(ui->actionWebJEEB, "http://x264.fushizen.eu/");
231 SETUP_WEBLINK(ui->actionWebFreeCodecs, "http://www.free-codecs.com/x264_video_codec_download.htm");
232 SETUP_WEBLINK(ui->actionWebX265BinRU, "http://x265.ru/en/builds/");
233 SETUP_WEBLINK(ui->actionWebX265BinEU, "http://builds.x265.eu/");
234 SETUP_WEBLINK(ui->actionWebX265BinORG, "http://chromashift.org/x265_builds/");
235 SETUP_WEBLINK(ui->actionWebX265BinFF, "http://ffmpeg.zeranoe.com/builds/");
236 SETUP_WEBLINK(ui->actionWebAvisynth32, "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/");
237 SETUP_WEBLINK(ui->actionWebAvisynth64, "http://code.google.com/p/avisynth64/downloads/list");
238 SETUP_WEBLINK(ui->actionWebAvisynthPlus, "http://www.avs-plus.net/");
239 SETUP_WEBLINK(ui->actionWebVapourSynth, "http://www.vapoursynth.com/");
240 SETUP_WEBLINK(ui->actionWebVapourSynthDocs, "http://www.vapoursynth.com/doc/");
241 SETUP_WEBLINK(ui->actionOnlineDocX264, "http://en.wikibooks.org/wiki/MeGUI/x264_Settings"); //http://mewiki.project357.com/wiki/X264_Settings
242 SETUP_WEBLINK(ui->actionOnlineDocX265, "http://x265.readthedocs.org/en/default/");
243 SETUP_WEBLINK(ui->actionWebBluRay, "http://www.x264bluray.com/");
244 SETUP_WEBLINK(ui->actionWebAvsWiki, "http://avisynth.nl/index.php/Main_Page#Usage");
245 SETUP_WEBLINK(ui->actionWebSupport, "http://forum.doom9.org/showthread.php?t=144140");
246 SETUP_WEBLINK(ui->actionWebSecret, "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
248 //Create floating label
249 m_label[0].reset(new QLabel(ui->jobsView->viewport()));
250 m_label[1].reset(new QLabel(ui->logView->viewport()));
251 if(!m_label[0].isNull())
253 m_label[0]->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
254 m_label[0]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
255 SET_TEXT_COLOR(m_label[0], Qt::darkGray);
256 SET_FONT_BOLD(m_label[0], true);
257 m_label[0]->setVisible(true);
258 m_label[0]->setContextMenuPolicy(Qt::ActionsContextMenu);
259 m_label[0]->addActions(ui->jobsView->actions());
261 if(!m_label[1].isNull())
263 m_animation.reset(new QMovie(":/images/spinner.gif"));
264 m_label[1]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
265 if(!m_animation.isNull())
267 m_label[1]->setMovie(m_animation.data());
268 m_animation->start();
271 connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
272 updateLabelPos();
274 //Init system tray icon
275 m_sysTray.reset(new QSystemTrayIcon(this));
276 m_sysTray->setToolTip(this->windowTitle());
277 m_sysTray->setIcon(this->windowIcon());
278 connect(m_sysTray.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(sysTrayActived()));
280 //Init taskbar progress
281 m_taskbar.reset(new MUtils::Taskbar7(this));
283 //Create corner widget
284 QLabel *checkUp = new QLabel(ui->menubar);
285 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")));
286 checkUp->setFixedHeight(ui->menubar->height());
287 checkUp->setCursor(QCursor(Qt::PointingHandCursor));
288 m_inputFilter_checkUp.reset(new InputEventFilter(checkUp));
289 m_inputFilter_checkUp->addMouseFilter(Qt::LeftButton, 0);
290 m_inputFilter_checkUp->addMouseFilter(Qt::RightButton, 0);
291 connect(m_inputFilter_checkUp.data(), SIGNAL(mouseClicked(int)), this, SLOT(checkUpdates()));
292 checkUp->hide();
293 ui->menubar->setCornerWidget(checkUp);
295 //Create timer
296 m_fileTimer.reset(new QTimer(this));
297 connect(m_fileTimer.data(), SIGNAL(timeout()), this, SLOT(handlePendingFiles()));
301 * Destructor
303 MainWindow::~MainWindow(void)
305 OptionsModel::saveTemplate(m_options.data(), QString::fromLatin1(tpl_last));
307 if(!m_ipcThread.isNull())
309 m_ipcThread->stop();
310 if(!m_ipcThread->wait(5000))
312 m_ipcThread->terminate();
313 m_ipcThread->wait();
317 delete ui;
320 ///////////////////////////////////////////////////////////////////////////////
321 // Slots
322 ///////////////////////////////////////////////////////////////////////////////
325 * The "add" button was clicked
327 void MainWindow::addButtonPressed()
329 ENSURE_APP_IS_READY();
331 qDebug("MainWindow::addButtonPressed");
332 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
333 QString sourceFileName, outputFileName;
335 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
337 appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
342 * The "open" action was triggered
344 void MainWindow::openActionTriggered()
346 ENSURE_APP_IS_READY();
348 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
349 if(!fileList.empty())
351 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
352 if(fileList.count() > 1)
354 createJobMultiple(fileList);
356 else
358 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
359 QString sourceFileName(fileList.first()), outputFileName;
360 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
362 appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
369 * The "start" button was clicked
371 void MainWindow::startButtonPressed(void)
373 ENSURE_APP_IS_READY();
374 m_jobList->startJob(ui->jobsView->currentIndex());
378 * The "abort" button was clicked
380 void MainWindow::abortButtonPressed(void)
382 ENSURE_APP_IS_READY();
384 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)
386 m_jobList->abortJob(ui->jobsView->currentIndex());
391 * The "delete" button was clicked
393 void MainWindow::deleteButtonPressed(void)
395 ENSURE_APP_IS_READY();
397 m_jobList->deleteJob(ui->jobsView->currentIndex());
398 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
402 * The "browse" button was clicked
404 void MainWindow::browseButtonPressed(void)
406 ENSURE_APP_IS_READY();
408 QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
409 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
411 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
413 else
415 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
420 * The "browse" button was clicked
422 void MainWindow::moveButtonPressed(void)
424 ENSURE_APP_IS_READY();
426 if(sender() == ui->actionJob_MoveUp)
428 qDebug("Move job %d (direction: UP)", ui->jobsView->currentIndex().row());
429 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_UP))
431 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
433 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
435 else if(sender() == ui->actionJob_MoveDown)
437 qDebug("Move job %d (direction: DOWN)", ui->jobsView->currentIndex().row());
438 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_DOWN))
440 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
442 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
444 else
446 qWarning("[moveButtonPressed] Error: Unknown sender!");
451 * The "pause" button was clicked
453 void MainWindow::pauseButtonPressed(bool checked)
455 if(!APP_IS_READY)
457 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
458 qWarning("Cannot perfrom this action at this time!");
459 ui->buttonPauseJob->setChecked(!checked);
462 if(checked)
464 m_jobList->pauseJob(ui->jobsView->currentIndex());
466 else
468 m_jobList->resumeJob(ui->jobsView->currentIndex());
473 * The "restart" button was clicked
475 void MainWindow::restartButtonPressed(void)
477 ENSURE_APP_IS_READY();
479 const QModelIndex index = ui->jobsView->currentIndex();
480 const OptionsModel *options = m_jobList->getJobOptions(index);
481 QString sourceFileName = m_jobList->getJobSourceFile(index);
482 QString outputFileName = m_jobList->getJobOutputFile(index);
484 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
486 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
487 OptionsModel *tempOptions = new OptionsModel(*options);
488 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
490 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
492 MUTILS_DELETE(tempOptions);
497 * Job item selected by user
499 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
501 qDebug("Job selected: %d", current.row());
503 if(ui->logView->model())
505 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
508 if(current.isValid())
510 ui->logView->setModel(m_jobList->getLogFile(current));
511 connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
512 foreach(QAction *action, ui->logView->actions())
514 action->setEnabled(true);
516 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
518 ui->progressBar->setValue(m_jobList->getJobProgress(current));
519 ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
520 updateButtons(m_jobList->getJobStatus(current));
521 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
523 else
525 ui->logView->setModel(NULL);
526 foreach(QAction *action, ui->logView->actions())
528 action->setEnabled(false);
530 ui->progressBar->setValue(0);
531 ui->editDetails->clear();
532 updateButtons(JobStatus_Undefined);
533 updateTaskbar(JobStatus_Undefined, QIcon());
536 ui->progressBar->repaint();
540 * Handle update of job info (status, progress, details, etc)
542 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
544 int selected = ui->jobsView->currentIndex().row();
546 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
548 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
550 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
551 if(i == selected)
553 qDebug("Current job changed status!");
554 updateButtons(status);
555 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
557 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
559 if(m_preferences->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
560 if(m_preferences->getSaveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
564 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
566 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
568 if(i == selected)
570 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
571 if(!m_taskbar.isNull())
573 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
575 break;
579 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
581 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
583 if(i == selected)
585 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
586 break;
593 * Handle new log file content
595 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
597 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
601 * About screen
603 void MainWindow::showAbout(void)
605 ENSURE_APP_IS_READY();
607 if(AboutDialog *aboutDialog = new AboutDialog(this))
609 aboutDialog->exec();
610 MUTILS_DELETE(aboutDialog);
615 * Open web-link
617 void MainWindow::showWebLink(void)
619 ENSURE_APP_IS_READY();
621 if(QObject *obj = QObject::sender())
623 if(QAction *action = dynamic_cast<QAction*>(obj))
625 if(action->data().type() == QVariant::Url)
627 QDesktopServices::openUrl(action->data().toUrl());
634 * Pereferences dialog
636 void MainWindow::showPreferences(void)
638 ENSURE_APP_IS_READY();
640 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences.data(), m_sysinfo.data());
641 preferences->exec();
643 MUTILS_DELETE(preferences);
647 * Launch next job, after running job has finished
649 void MainWindow::launchNextJob(void)
651 qDebug("Launching next job...");
653 if(countRunningJobs() >= m_preferences->getMaxRunningJobCount())
655 qDebug("Still have too many jobs running, won't launch next one yet!");
656 return;
659 const int rows = m_jobList->rowCount(QModelIndex());
661 for(int i = 0; i < rows; i++)
663 const QModelIndex currentIndex = m_jobList->index(i, 0, QModelIndex());
664 if(m_jobList->getJobStatus(currentIndex) == JobStatus_Enqueued)
666 if(m_jobList->startJob(currentIndex))
668 ui->jobsView->selectRow(currentIndex.row());
669 return;
674 qWarning("No enqueued jobs left to be started!");
676 if(m_preferences->getShutdownComputer())
678 QTimer::singleShot(0, this, SLOT(shutdownComputer()));
683 * Save log to text file
685 void MainWindow::saveLogFile(const QModelIndex &index)
687 if(index.isValid())
689 if(LogFileModel *log = m_jobList->getLogFile(index))
691 QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
692 QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
693 if(!log->saveToLocalFile(logFilePath))
695 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
702 * Shut down the computer (with countdown)
704 void MainWindow::shutdownComputer(void)
706 ENSURE_APP_IS_READY();
708 if(countPendingJobs() > 0)
710 qDebug("Still have pending jobs, won't shutdown yet!");
711 return;
714 const int iTimeout = 30;
715 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
716 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
718 qWarning("Initiating shutdown sequence!");
720 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
721 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
722 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
723 progressDialog.setModal(true);
724 progressDialog.setAutoClose(false);
725 progressDialog.setAutoReset(false);
726 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
727 progressDialog.setWindowTitle(windowTitle());
728 progressDialog.setCancelButton(cancelButton);
729 progressDialog.show();
731 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
732 QApplication::setOverrideCursor(Qt::WaitCursor);
733 MUtils::Sound::play_sound("shutdown", false);
734 QApplication::restoreOverrideCursor();
736 QTimer timer;
737 timer.setInterval(1000);
738 timer.start();
740 QEventLoop eventLoop(this);
741 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
742 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
744 for(int i = 1; i <= iTimeout; i++)
746 eventLoop.exec();
747 if(progressDialog.wasCanceled())
749 progressDialog.close();
750 return;
752 progressDialog.setValue(i+1);
753 progressDialog.setLabelText(text.arg(iTimeout-i));
754 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
755 QApplication::processEvents();
756 MUtils::Sound::play_sound(((i < iTimeout) ? "beep" : "beep2"), false);
759 qWarning("Shutting down !!!");
761 if(MUtils::OS::shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true, false))
763 qApp->closeAllWindows();
769 * Main initialization function (called only once!)
771 void MainWindow::init(void)
773 if(m_initialized)
775 qWarning("Already initialized -> skipping!");
776 return;
779 updateLabelPos();
780 const MUtils::OS::ArgumentMap &arguments = MUtils::OS::arguments();
781 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
783 //---------------------------------------
784 // Check required binaries
785 //---------------------------------------
787 qDebug("[Validating binaries]");
788 if(!BinariesCheckThread::check(m_sysinfo.data()))
790 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;"));
791 qFatal("At least one tool is missing or is not a valid Win32/Win64 binary!");
793 qDebug(" ");
795 //---------------------------------------
796 // Check for portable mode
797 //---------------------------------------
799 if(x264_is_portable())
801 bool ok = false;
802 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
803 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
804 if(writeTest.open(QIODevice::WriteOnly))
806 ok = (writeTest.write(data) == strlen(data));
807 writeTest.remove();
809 if(!ok)
811 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"));
812 if(val != 1) INIT_ERROR_EXIT();
816 //Pre-release popup
817 if(x264_is_prerelease())
819 qsrand(time(NULL)); int rnd = qrand() % 3;
820 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);
821 if(rnd != val) INIT_ERROR_EXIT();
824 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
826 //---------------------------------------
827 // Check CPU capabilities
828 //---------------------------------------
830 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
831 if(!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_MMX))
833 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"));
834 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
835 INIT_ERROR_EXIT();
837 else if(!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_SSE))
839 qWarning("WARNING: System does not support SSE (v1), x264/x265 probably will *not* work !!!\n");
840 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"));
841 if(val != 1) INIT_ERROR_EXIT();
844 //Skip version check (not recommended!)
845 if(arguments.contains(CLI_PARAM_SKIP_VERSION_CHECK))
847 qWarning("Version checks are disabled now, you have been warned!\n");
848 m_preferences->setSkipVersionTest(true);
851 //Don't abort encoding process on timeout (not recommended!)
852 if(arguments.contains(CLI_PARAM_NO_DEADLOCK))
854 qWarning("Deadlock detection disabled, you have been warned!\n");
855 m_preferences->setAbortOnTimeout(false);
858 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
860 //---------------------------------------
861 // Check Avisynth support
862 //---------------------------------------
864 if(!arguments.contains(CLI_PARAM_SKIP_AVS_CHECK))
866 qDebug("[Check for Avisynth support]");
867 if(!AvisynthCheckThread::detect(m_sysinfo.data()))
869 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
870 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
871 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
872 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
873 if(val != 1) INIT_ERROR_EXIT();
875 else if((!m_sysinfo->hasAvisynth()) && (!m_preferences->getDisableWarnings()))
877 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>");
878 text += tr("Please download and install Avisynth:").append("<br>").append(LINK(avs_dl_url));
879 int val = QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
880 if(val == 1)
882 m_preferences->setDisableWarnings(true);
883 PreferencesModel::savePreferences(m_preferences.data());
886 qDebug(" ");
889 //---------------------------------------
890 // Check VapurSynth support
891 //---------------------------------------
893 if(!arguments.contains(CLI_PARAM_SKIP_VPS_CHECK))
895 qDebug("[Check for VapourSynth support]");
896 if(!VapourSynthCheckThread::detect(m_sysinfo.data()))
898 QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
899 text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
900 text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
901 const int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
902 if(val != 1) INIT_ERROR_EXIT();
904 else if((!m_sysinfo->hasVapourSynth()) && (!m_preferences->getDisableWarnings()))
906 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>");
907 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>");
908 text += tr("Note that Python v3.4 is a prerequisite for installing VapourSynth:").append("<br>").append(LINK(python_url)).append("<br>");
909 const int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
910 if(val == 1)
912 m_preferences->setDisableWarnings(true);
913 PreferencesModel::savePreferences(m_preferences.data());
916 qDebug(" ");
919 //---------------------------------------
920 // Create the IPC listener thread
921 //---------------------------------------
923 if(m_ipcChannel)
925 m_ipcThread.reset(new IPCThread_Recv(m_ipcChannel));
926 connect(m_ipcThread.data(), SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
927 m_ipcThread->start();
930 //---------------------------------------
931 // Finish initialization
932 //---------------------------------------
934 //Set Window title
935 setWindowTitle(QString("%1 (%2)").arg(windowTitle(), m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_X64) ? "64-Bit" : "32-Bit"));
937 //Enable drag&drop support for this window, required for Qt v4.8.4+
938 setAcceptDrops(true);
940 //Update flag
941 m_initialized = true;
943 //Hide the spinner animation
944 if(!m_label[1].isNull())
946 if(!m_animation.isNull())
948 m_animation->stop();
950 m_label[1]->setVisible(false);
953 //---------------------------------------
954 // Check for Expiration
955 //---------------------------------------
957 if(MUtils::Version::app_build_date().addMonths(6) < MUtils::OS::current_date())
959 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
960 QString text;
961 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;"));
962 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;"));
963 text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace('-', "&minus;"));
964 QMessageBox msgBox(this);
965 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
966 msgBox.setWindowTitle(tr("Update Notification"));
967 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
968 msgBox.setText(text);
969 QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
970 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
971 QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
972 btn2->setEnabled(false);
973 btn3->setVisible(false);
974 QTimer::singleShot(7500, btn2, SLOT(hide()));
975 QTimer::singleShot(7500, btn3, SLOT(show()));
976 if(msgBox.exec() == 0)
978 QTimer::singleShot(0, this, SLOT(checkUpdates()));
979 return;
982 else if(!parseCommandLineArgs())
984 //Update reminder
985 if(arguments.contains(CLI_PARAM_FIRST_RUN))
987 qWarning("First run -> resetting update check now!");
988 m_recentlyUsed->setLastUpdateCheck(0);
989 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
991 else if(m_recentlyUsed->lastUpdateCheck() + 14 < MUtils::OS::current_date().toJulianDay())
993 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
994 if(!m_preferences->getNoUpdateReminder())
996 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)
998 QTimer::singleShot(0, this, SLOT(checkUpdates()));
999 return;
1005 //Load queued jobs
1006 if(m_jobList->loadQueuedJobs(m_sysinfo.data()) > 0)
1008 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1009 m_jobList->clearQueuedJobs();
1014 * Update the label position
1016 void MainWindow::updateLabelPos(void)
1018 for(int i = 0; i < 2; i++)
1020 //const QWidget *const viewPort = ui->jobsView->viewport();
1021 const QWidget *const viewPort = dynamic_cast<QWidget*>(m_label[i]->parent());
1022 if(viewPort)
1024 m_label[i]->setGeometry(0, 0, viewPort->width(), viewPort->height());
1030 * Copy the complete log to the clipboard
1032 void MainWindow::copyLogToClipboard(bool checked)
1034 qDebug("Coyping logfile to clipboard...");
1036 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1038 log->copyToClipboard();
1039 MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
1044 * Save log to local file
1046 void MainWindow::saveLogToLocalFile(bool checked)
1048 ENSURE_APP_IS_READY();
1050 const QModelIndex index = ui->jobsView->currentIndex();
1051 const QString initialName = index.isValid() ? QFileInfo(m_jobList->getJobOutputFile(index)).completeBaseName() : tr("Logfile");
1052 const QString fileName = QFileDialog::getSaveFileName(this, tr("Save Log File"), initialName, tr("Log File (*.log)"));
1053 if(!fileName.isEmpty())
1055 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1057 if(!log->saveToLocalFile(fileName))
1059 QMessageBox::warning(this, this->windowTitle(), tr("Error: Log file could not be saved!"));
1066 * Toggle line-wrapping
1068 void MainWindow::toggleLineWrapping(bool checked)
1070 ui->logView->setWordWrap(checked);
1074 * Process the dropped files
1076 void MainWindow::handlePendingFiles(void)
1078 qDebug("MainWindow::handlePendingFiles");
1080 if(!m_pendingFiles->isEmpty())
1082 QStringList pendingFiles(*m_pendingFiles);
1083 m_pendingFiles->clear();
1084 createJobMultiple(pendingFiles);
1087 qDebug("Leave from MainWindow::handlePendingFiles!");
1091 * Handle incoming IPC command
1093 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1095 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1097 qWarning("Cannot accapt commands at this time -> discarding!");
1098 return;
1101 if((!isVisible()) || m_sysTray->isVisible())
1103 sysTrayActived();
1106 MUtils::GUI::bring_to_front(this);
1108 #ifdef IPC_LOGGING
1109 qDebug("\n---------- IPC ----------");
1110 qDebug("CommandId: %d", command);
1111 for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1113 qDebug("Arguments: %s", iter->toUtf8().constData());
1115 qDebug("The Flags: 0x%08X", flags);
1116 qDebug("---------- IPC ----------\n");
1117 #endif //IPC_LOGGING
1119 switch(command)
1121 case IPC_OPCODE_PING:
1122 qDebug("Received a PING request from another instance!");
1123 MUtils::GUI::blink_window(this, 5, 125);
1124 break;
1125 case IPC_OPCODE_ADD_FILE:
1126 if(!args.isEmpty())
1128 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1130 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1131 if(!m_fileTimer->isActive())
1133 m_fileTimer->setSingleShot(true);
1134 m_fileTimer->start(5000);
1137 else
1139 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1142 break;
1143 case IPC_OPCODE_ADD_JOB:
1144 if(args.size() >= 3)
1146 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1148 OptionsModel options(m_sysinfo.data());
1149 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1150 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1152 if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1154 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1157 if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
1158 if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
1159 appendJob(args[0], args[1], &options, runImmediately);
1161 else
1163 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1166 break;
1167 default:
1168 MUTILS_THROW("Unknown command received!");
1173 * Check for new updates
1175 void MainWindow::checkUpdates(void)
1177 ENSURE_APP_IS_READY();
1179 if(countRunningJobs() > 0)
1181 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1182 return;
1185 UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo.data(), update_url);
1186 const int ret = updater->exec();
1188 if(updater->getSuccess())
1190 m_recentlyUsed->setLastUpdateCheck(MUtils::OS::current_date().toJulianDay());
1191 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
1192 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->hide();
1195 if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1197 qWarning("Exitting program to install update...");
1198 close();
1199 QApplication::quit();
1202 MUTILS_DELETE(updater);
1206 * Handle mouse event for version label
1208 void MainWindow::versionLabelMouseClicked(const int &tag)
1210 if(tag == 0)
1212 QTimer::singleShot(0, this, SLOT(showAbout()));
1217 * Handle key event for job list
1219 void MainWindow::jobListKeyPressed(const int &tag)
1221 switch(tag)
1223 case 1:
1224 ui->actionJob_MoveUp->trigger();
1225 break;
1226 case 2:
1227 ui->actionJob_MoveDown->trigger();
1228 break;
1233 * System tray was activated
1235 void MainWindow::sysTrayActived(void)
1237 m_sysTray->hide();
1238 showNormal();
1239 MUtils::GUI::bring_to_front(this);
1242 ///////////////////////////////////////////////////////////////////////////////
1243 // Event functions
1244 ///////////////////////////////////////////////////////////////////////////////
1247 * Window shown event
1249 void MainWindow::showEvent(QShowEvent *e)
1251 QMainWindow::showEvent(e);
1253 if(!m_initialized)
1255 QTimer::singleShot(0, this, SLOT(init()));
1260 * Window close event
1262 void MainWindow::closeEvent(QCloseEvent *e)
1264 if(!APP_IS_READY)
1266 e->ignore();
1267 qWarning("Cannot close window at this time!");
1268 return;
1271 //Make sure we have no running jobs left!
1272 if(countRunningJobs() > 0)
1274 e->ignore();
1275 if(!m_preferences->getNoSystrayWarning())
1277 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)
1279 m_preferences->setNoSystrayWarning(true);
1280 PreferencesModel::savePreferences(m_preferences.data());
1283 hide();
1284 m_sysTray->show();
1285 return;
1288 //Save pending jobs for next time, if desired by user
1289 if(countPendingJobs() > 0)
1291 int ret = QMessageBox::question(this, tr("Jobs Are Pending"), tr("You still have pending jobs. How do you want to proceed?"), tr("Save Pending Jobs"), tr("Discard"));
1292 if(ret == 0)
1294 m_jobList->saveQueuedJobs();
1296 else
1298 if(QMessageBox::warning(this, tr("Jobs Are Pending"), tr("Do you really want to discard all pending jobs?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
1300 e->ignore();
1301 return;
1306 //Delete remaining jobs
1307 while(m_jobList->rowCount(QModelIndex()) > 0)
1309 if((m_jobList->rowCount(QModelIndex()) % 10) == 0)
1311 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1313 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1315 e->ignore();
1316 QMessageBox::warning(this, tr("Failed To Exit"), tr("Warning: At least one job could not be deleted!"));
1320 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1321 QMainWindow::closeEvent(e);
1325 * Window resize event
1327 void MainWindow::resizeEvent(QResizeEvent *e)
1329 QMainWindow::resizeEvent(e);
1330 updateLabelPos();
1334 * File dragged over window
1336 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1338 bool accept[2] = {false, false};
1340 foreach(const QString &fmt, event->mimeData()->formats())
1342 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1343 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1346 if(accept[0] && accept[1])
1348 event->acceptProposedAction();
1353 * File dropped onto window
1355 void MainWindow::dropEvent(QDropEvent *event)
1357 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1359 qWarning("Cannot accept dropped files at this time -> discarding!");
1360 return;
1363 QStringList droppedFiles;
1364 QList<QUrl> urls = event->mimeData()->urls();
1366 while(!urls.isEmpty())
1368 QUrl currentUrl = urls.takeFirst();
1369 QFileInfo file(currentUrl.toLocalFile());
1370 if(file.exists() && file.isFile())
1372 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1373 droppedFiles << file.canonicalFilePath();
1377 if(droppedFiles.count() > 0)
1379 m_pendingFiles->append(droppedFiles);
1380 m_pendingFiles->sort();
1381 if(!m_fileTimer->isActive())
1383 m_fileTimer->setSingleShot(true);
1384 m_fileTimer->start(5000);
1389 ///////////////////////////////////////////////////////////////////////////////
1390 // Private functions
1391 ///////////////////////////////////////////////////////////////////////////////
1394 * Creates a new job
1396 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1398 bool okay = false;
1399 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed.data(), m_sysinfo.data(), m_preferences.data());
1401 addDialog->setRunImmediately(runImmediately);
1402 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1403 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1404 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1406 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1407 if(multiFile)
1409 addDialog->setSourceEditable(false);
1410 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1411 addDialog->setApplyToAllVisible(applyToAll);
1414 if(addDialog->exec() == QDialog::Accepted)
1416 sourceFileName = addDialog->sourceFile();
1417 outputFileName = addDialog->outputFile();
1418 runImmediately = addDialog->runImmediately();
1419 if(applyToAll)
1421 *applyToAll = addDialog->applyToAll();
1423 okay = true;
1426 MUTILS_DELETE(addDialog);
1427 return okay;
1431 * Creates a new job from *multiple* files
1433 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1435 QStringList::ConstIterator iter;
1436 bool applyToAll = false, runImmediately = false;
1437 int counter = 0;
1439 //Add files individually
1440 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1442 runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1443 QString sourceFileName(*iter), outputFileName;
1444 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1446 if(appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
1448 continue;
1451 return false;
1454 //Add remaining files
1455 while(applyToAll && (iter != filePathIn.constEnd()))
1457 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1458 const QString sourceFileName = *iter;
1459 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
1460 if(!appendJob(sourceFileName, outputFileName, m_options.data(), runImmediatelyTmp))
1462 return false;
1464 iter++;
1467 return true;
1471 * Append a new job
1473 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1475 bool okay = false;
1476 EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo.data(), m_preferences.data());
1477 QModelIndex newIndex = m_jobList->insertJob(thrd);
1479 if(newIndex.isValid())
1481 if(runImmediately)
1483 ui->jobsView->selectRow(newIndex.row());
1484 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1485 m_jobList->startJob(newIndex);
1488 okay = true;
1491 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1492 return okay;
1496 * Jobs that are not completed (or failed, or aborted) yet
1498 unsigned int MainWindow::countPendingJobs(void)
1500 unsigned int count = 0;
1501 const int rows = m_jobList->rowCount(QModelIndex());
1503 for(int i = 0; i < rows; i++)
1505 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1506 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1508 count++;
1512 return count;
1516 * Jobs that are still active, i.e. not terminated or enqueued
1518 unsigned int MainWindow::countRunningJobs(void)
1520 unsigned int count = 0;
1521 const int rows = m_jobList->rowCount(QModelIndex());
1523 for(int i = 0; i < rows; i++)
1525 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1526 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1528 count++;
1532 return count;
1536 * Update all buttons with respect to current job status
1538 void MainWindow::updateButtons(JobStatus status)
1540 qDebug("MainWindow::updateButtons(void)");
1542 ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1543 ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1544 ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1545 ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1547 ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1548 ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1549 ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1550 ui->actionJob_MoveUp->setEnabled(status != JobStatus_Undefined);
1551 ui->actionJob_MoveDown->setEnabled(status != JobStatus_Undefined);
1553 ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1554 ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1555 ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1556 ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1558 ui->editDetails->setEnabled(status != JobStatus_Paused);
1562 * Update the taskbar with current job status
1564 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1566 qDebug("MainWindow::updateTaskbar(void)");
1568 if(m_taskbar.isNull())
1570 return; /*taskbar object not created yet*/
1573 switch(status)
1575 case JobStatus_Undefined:
1576 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE);
1577 break;
1578 case JobStatus_Aborting:
1579 case JobStatus_Starting:
1580 case JobStatus_Pausing:
1581 case JobStatus_Resuming:
1582 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_INTERMEDIATE);
1583 break;
1584 case JobStatus_Aborted:
1585 case JobStatus_Failed:
1586 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR);
1587 break;
1588 case JobStatus_Paused:
1589 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_PAUSED);
1590 break;
1591 default:
1592 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL);
1593 break;
1596 switch(status)
1598 case JobStatus_Aborting:
1599 case JobStatus_Starting:
1600 case JobStatus_Pausing:
1601 case JobStatus_Resuming:
1602 break;
1603 default:
1604 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
1605 break;
1608 m_taskbar->setOverlayIcon(icon.isNull() ? NULL : &icon);
1612 * Parse command-line arguments
1614 bool MainWindow::parseCommandLineArgs(void)
1616 const MUtils::OS::ArgumentMap &args = MUtils::OS::arguments();
1618 quint32 flags = 0;
1619 bool commandSent = false;
1621 //Handle flags
1622 if(args.contains(CLI_PARAM_FORCE_START))
1624 flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1626 if(args.contains(CLI_PARAM_FORCE_ENQUEUE))
1628 flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1631 //Process all command-line arguments
1632 if(args.contains(CLI_PARAM_ADD_FILE))
1634 foreach(const QString &fileName, args.values(CLI_PARAM_ADD_FILE))
1636 handleCommand(IPC_OPCODE_ADD_FILE, QStringList() << fileName, flags);
1638 commandSent = true;
1640 if(args.contains(CLI_PARAM_ADD_JOB))
1642 foreach(const QString &options, args.values(CLI_PARAM_ADD_JOB))
1644 const QStringList optionValues = options.split('|', QString::SkipEmptyParts);
1645 if(optionValues.count() == 3)
1647 handleCommand(IPC_OPCODE_ADD_JOB, optionValues, flags);
1649 else
1651 qWarning("Invalid number of arguments for parameter \"--%s\" detected!", CLI_PARAM_ADD_JOB);
1654 commandSent = true;
1657 return commandSent;