Show debug console only for "pre-release" builds.
[simple-x264-launcher.git] / src / win_main.cpp
blobb730fe0fffa4df01e09dc7966382707a8289cea0
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_vapoursynth.h"
37 #include "thread_encode.h"
38 #include "thread_ipc_recv.h"
39 #include "input_filter.h"
40 #include "win_addJob.h"
41 #include "win_about.h"
42 #include "win_preferences.h"
43 #include "win_updater.h"
44 #include "binaries.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>
74 #include <ctime>
76 //Constants
77 static const char *tpl_last = "<LAST_USED>";
78 static const char *home_url = "http://muldersoft.com/";
79 static const char *update_url = "https://github.com/lordmulder/Simple-x264-Launcher/releases/latest";
80 static const char *avs_dl_url = "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/";
81 static const char *python_url = "https://www.python.org/downloads/";
82 static const char *vsynth_url = "http://www.vapoursynth.com/";
83 static const int vsynth_rev = 24;
85 //Macros
86 #define SET_FONT_BOLD(WIDGET,BOLD) do { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); } while(0)
87 #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)
88 #define LINK(URL) (QString("<a href=\"%1\">%1</a>").arg((URL)))
89 #define INIT_ERROR_EXIT() do { close(); qApp->exit(-1); return; } while(0)
90 #define NEXT(X) ((*reinterpret_cast<int*>(&(X)))++)
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_initialized(false),
113 ui(new Ui::MainWindow())
115 //Init the dialog, from the .ui file
116 ui->setupUi(this);
117 setWindowFlags(windowFlags() & (~Qt::WindowMaximizeButtonHint));
119 //Register meta types
120 qRegisterMetaType<QUuid>("QUuid");
121 qRegisterMetaType<QUuid>("DWORD");
122 qRegisterMetaType<JobStatus>("JobStatus");
124 //Create and initialize the sysinfo object
125 m_sysinfo.reset(new SysinfoModel());
126 m_sysinfo->setAppPath(QApplication::applicationDirPath());
127 m_sysinfo->setMMXSupport(cpuFeatures.features && MUtils::CPUFetaures::FLAG_MMX);
128 m_sysinfo->setSSESupport(cpuFeatures.features && MUtils::CPUFetaures::FLAG_SSE); //SSE implies MMX2
129 m_sysinfo->setX64Support(cpuFeatures.x64 && (cpuFeatures.features && MUtils::CPUFetaures::FLAG_SSE2)); //X64 implies SSE2
131 //Load preferences
132 m_preferences.reset(new PreferencesModel());
133 PreferencesModel::loadPreferences(m_preferences.data());
135 //Load recently used
136 m_recentlyUsed.reset(new RecentlyUsed());
137 RecentlyUsed::loadRecentlyUsed(m_recentlyUsed.data());
139 //Create options object
140 m_options.reset(new OptionsModel(m_sysinfo.data()));
141 OptionsModel::loadTemplate(m_options.data(), QString::fromLatin1(tpl_last));
143 //Freeze minimum size
144 setMinimumSize(size());
145 ui->splitter->setSizes(QList<int>() << 16 << 196);
147 //Update title
148 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)));
150 if(MUTILS_DEBUG)
152 setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle()));
153 setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }");
155 else if(x264_is_prerelease())
157 setWindowTitle(QString("%1 | PRE-RELEASE VERSION").arg(windowTitle()));
160 //Create model
161 m_jobList.reset(new JobListModel(m_preferences.data()));
162 connect(m_jobList.data(), SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(jobChangedData(QModelIndex, QModelIndex)));
163 ui->jobsView->setModel(m_jobList.data());
165 //Setup view
166 ui->jobsView->horizontalHeader()->setSectionHidden(3, true);
167 ui->jobsView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
168 ui->jobsView->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed);
169 ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::Fixed);
170 ui->jobsView->horizontalHeader()->resizeSection(1, 150);
171 ui->jobsView->horizontalHeader()->resizeSection(2, 90);
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 actionClipboard->setEnabled(false);
190 ui->logView->addAction(actionClipboard);
191 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
192 ui->jobsView->addActions(ui->menuJob->actions());
194 //Enable buttons
195 connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed() ));
196 connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed() ));
197 connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed() ));
198 connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
199 connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed() ));
200 connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed() ));
201 connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed() ));
202 connect(ui->actionJob_MoveUp, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
203 connect(ui->actionJob_MoveDown, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
205 //Enable menu
206 connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
207 connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
208 connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
209 connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
211 //Setup web-links
212 SETUP_WEBLINK(ui->actionWebMulder, home_url);
213 SETUP_WEBLINK(ui->actionWebX264, "http://www.videolan.org/developers/x264.html");
214 SETUP_WEBLINK(ui->actionWebX265, "http://www.videolan.org/developers/x265.html");
215 SETUP_WEBLINK(ui->actionWebKomisar, "http://komisar.gin.by/");
216 SETUP_WEBLINK(ui->actionWebVideoLAN, "http://download.videolan.org/pub/x264/binaries/");
217 SETUP_WEBLINK(ui->actionWebJEEB, "http://x264.fushizen.eu/");
218 SETUP_WEBLINK(ui->actionWebFreeCodecs, "http://www.free-codecs.com/x264_video_codec_download.htm");
219 SETUP_WEBLINK(ui->actionWebX265BinRU, "http://x265.ru/en/builds/");
220 SETUP_WEBLINK(ui->actionWebX265BinEU, "http://builds.x265.eu/");
221 SETUP_WEBLINK(ui->actionWebX265BinORG, "http://chromashift.org/x265_builds/");
222 SETUP_WEBLINK(ui->actionWebX265BinFF, "http://ffmpeg.zeranoe.com/builds/");
223 SETUP_WEBLINK(ui->actionWebAvisynth32, "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/");
224 SETUP_WEBLINK(ui->actionWebAvisynth64, "http://code.google.com/p/avisynth64/downloads/list");
225 SETUP_WEBLINK(ui->actionWebAvisynthPlus, "http://www.avs-plus.net/");
226 SETUP_WEBLINK(ui->actionWebVapourSynth, "http://www.vapoursynth.com/");
227 SETUP_WEBLINK(ui->actionWebVapourSynthDocs, "http://www.vapoursynth.com/doc/");
228 SETUP_WEBLINK(ui->actionOnlineDocX264, "http://mewiki.project357.com/wiki/X264_Settings");
229 SETUP_WEBLINK(ui->actionOnlineDocX265, "http://x265.readthedocs.org/en/default/");
230 SETUP_WEBLINK(ui->actionWebBluRay, "http://www.x264bluray.com/");
231 SETUP_WEBLINK(ui->actionWebAvsWiki, "http://avisynth.nl/index.php/Main_Page#Usage");
232 SETUP_WEBLINK(ui->actionWebSupport, "http://forum.doom9.org/showthread.php?t=144140");
233 SETUP_WEBLINK(ui->actionWebSecret, "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
235 //Create floating label
236 m_label.reset(new QLabel(ui->jobsView->viewport()));
237 m_label->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
238 m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
239 SET_TEXT_COLOR(m_label, Qt::darkGray);
240 SET_FONT_BOLD(m_label, true);
241 m_label->setVisible(true);
242 m_label->setContextMenuPolicy(Qt::ActionsContextMenu);
243 m_label->addActions(ui->jobsView->actions());
244 connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
245 updateLabelPos();
247 //Init system tray icon
248 m_sysTray.reset(new QSystemTrayIcon(this));
249 m_sysTray->setToolTip(this->windowTitle());
250 m_sysTray->setIcon(this->windowIcon());
251 connect(m_sysTray.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(sysTrayActived()));
253 //Init taskbar progress
254 m_taskbar.reset(new MUtils::Taskbar7(this));
256 //Create corner widget
257 QLabel *checkUp = new QLabel(ui->menubar);
258 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")));
259 checkUp->setFixedHeight(ui->menubar->height());
260 checkUp->setCursor(QCursor(Qt::PointingHandCursor));
261 m_inputFilter_checkUp.reset(new InputEventFilter(checkUp));
262 m_inputFilter_checkUp->addMouseFilter(Qt::LeftButton, 0);
263 m_inputFilter_checkUp->addMouseFilter(Qt::RightButton, 0);
264 connect(m_inputFilter_checkUp.data(), SIGNAL(mouseClicked(int)), this, SLOT(checkUpdates()));
265 checkUp->hide();
266 ui->menubar->setCornerWidget(checkUp);
268 //Create timer
269 m_fileTimer.reset(new QTimer(this));
270 connect(m_fileTimer.data(), SIGNAL(timeout()), this, SLOT(handlePendingFiles()));
274 * Destructor
276 MainWindow::~MainWindow(void)
278 OptionsModel::saveTemplate(m_options.data(), QString::fromLatin1(tpl_last));
280 while(!m_toolsList->isEmpty())
282 QFile *temp = m_toolsList->takeFirst();
283 MUTILS_DELETE(temp);
286 if(!m_ipcThread.isNull())
288 m_ipcThread->stop();
289 if(!m_ipcThread->wait(5000))
291 m_ipcThread->terminate();
292 m_ipcThread->wait();
296 VapourSynthCheckThread::unload();
297 AvisynthCheckThread::unload();
299 delete ui;
302 ///////////////////////////////////////////////////////////////////////////////
303 // Slots
304 ///////////////////////////////////////////////////////////////////////////////
307 * The "add" button was clicked
309 void MainWindow::addButtonPressed()
311 ENSURE_APP_IS_READY();
313 qDebug("MainWindow::addButtonPressed");
314 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
315 QString sourceFileName, outputFileName;
317 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
319 appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
324 * The "open" action was triggered
326 void MainWindow::openActionTriggered()
328 ENSURE_APP_IS_READY();
330 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
331 if(!fileList.empty())
333 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
334 if(fileList.count() > 1)
336 createJobMultiple(fileList);
338 else
340 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
341 QString sourceFileName(fileList.first()), outputFileName;
342 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
344 appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
351 * The "start" button was clicked
353 void MainWindow::startButtonPressed(void)
355 ENSURE_APP_IS_READY();
356 m_jobList->startJob(ui->jobsView->currentIndex());
360 * The "abort" button was clicked
362 void MainWindow::abortButtonPressed(void)
364 ENSURE_APP_IS_READY();
366 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)
368 m_jobList->abortJob(ui->jobsView->currentIndex());
373 * The "delete" button was clicked
375 void MainWindow::deleteButtonPressed(void)
377 ENSURE_APP_IS_READY();
379 m_jobList->deleteJob(ui->jobsView->currentIndex());
380 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
384 * The "browse" button was clicked
386 void MainWindow::browseButtonPressed(void)
388 ENSURE_APP_IS_READY();
390 QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
391 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
393 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
395 else
397 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
402 * The "browse" button was clicked
404 void MainWindow::moveButtonPressed(void)
406 ENSURE_APP_IS_READY();
408 if(sender() == ui->actionJob_MoveUp)
410 qDebug("Move job %d (direction: UP)", ui->jobsView->currentIndex().row());
411 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_UP))
413 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
415 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
417 else if(sender() == ui->actionJob_MoveDown)
419 qDebug("Move job %d (direction: DOWN)", ui->jobsView->currentIndex().row());
420 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_DOWN))
422 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
424 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
426 else
428 qWarning("[moveButtonPressed] Error: Unknown sender!");
433 * The "pause" button was clicked
435 void MainWindow::pauseButtonPressed(bool checked)
437 if(!APP_IS_READY)
439 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
440 qWarning("Cannot perfrom this action at this time!");
441 ui->buttonPauseJob->setChecked(!checked);
444 if(checked)
446 m_jobList->pauseJob(ui->jobsView->currentIndex());
448 else
450 m_jobList->resumeJob(ui->jobsView->currentIndex());
455 * The "restart" button was clicked
457 void MainWindow::restartButtonPressed(void)
459 ENSURE_APP_IS_READY();
461 const QModelIndex index = ui->jobsView->currentIndex();
462 const OptionsModel *options = m_jobList->getJobOptions(index);
463 QString sourceFileName = m_jobList->getJobSourceFile(index);
464 QString outputFileName = m_jobList->getJobOutputFile(index);
466 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
468 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
469 OptionsModel *tempOptions = new OptionsModel(*options);
470 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
472 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
474 MUTILS_DELETE(tempOptions);
479 * Job item selected by user
481 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
483 qDebug("Job selected: %d", current.row());
485 if(ui->logView->model())
487 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
490 if(current.isValid())
492 ui->logView->setModel(m_jobList->getLogFile(current));
493 connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
494 ui->logView->actions().first()->setEnabled(true);
495 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
497 ui->progressBar->setValue(m_jobList->getJobProgress(current));
498 ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
499 updateButtons(m_jobList->getJobStatus(current));
500 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
502 else
504 ui->logView->setModel(NULL);
505 ui->logView->actions().first()->setEnabled(false);
506 ui->progressBar->setValue(0);
507 ui->editDetails->clear();
508 updateButtons(JobStatus_Undefined);
509 updateTaskbar(JobStatus_Undefined, QIcon());
512 ui->progressBar->repaint();
516 * Handle update of job info (status, progress, details, etc)
518 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
520 int selected = ui->jobsView->currentIndex().row();
522 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
524 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
526 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
527 if(i == selected)
529 qDebug("Current job changed status!");
530 updateButtons(status);
531 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
533 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
535 if(m_preferences->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
536 if(m_preferences->getSaveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
540 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
542 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
544 if(i == selected)
546 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
547 if(!m_taskbar.isNull())
549 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
551 break;
555 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
557 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
559 if(i == selected)
561 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
562 break;
569 * Handle new log file content
571 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
573 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
577 * About screen
579 void MainWindow::showAbout(void)
581 ENSURE_APP_IS_READY();
583 if(AboutDialog *aboutDialog = new AboutDialog(this))
585 aboutDialog->exec();
586 MUTILS_DELETE(aboutDialog);
591 * Open web-link
593 void MainWindow::showWebLink(void)
595 ENSURE_APP_IS_READY();
597 if(QObject *obj = QObject::sender())
599 if(QAction *action = dynamic_cast<QAction*>(obj))
601 if(action->data().type() == QVariant::Url)
603 QDesktopServices::openUrl(action->data().toUrl());
610 * Pereferences dialog
612 void MainWindow::showPreferences(void)
614 ENSURE_APP_IS_READY();
616 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences.data(), m_sysinfo.data());
617 preferences->exec();
619 MUTILS_DELETE(preferences);
623 * Launch next job, after running job has finished
625 void MainWindow::launchNextJob(void)
627 qDebug("Launching next job...");
629 if(countRunningJobs() >= m_preferences->getMaxRunningJobCount())
631 qDebug("Still have too many jobs running, won't launch next one yet!");
632 return;
635 const int rows = m_jobList->rowCount(QModelIndex());
637 for(int i = 0; i < rows; i++)
639 const QModelIndex currentIndex = m_jobList->index(i, 0, QModelIndex());
640 if(m_jobList->getJobStatus(currentIndex) == JobStatus_Enqueued)
642 if(m_jobList->startJob(currentIndex))
644 ui->jobsView->selectRow(currentIndex.row());
645 return;
650 qWarning("No enqueued jobs left to be started!");
652 if(m_preferences->getShutdownComputer())
654 QTimer::singleShot(0, this, SLOT(shutdownComputer()));
659 * Save log to text file
661 void MainWindow::saveLogFile(const QModelIndex &index)
663 if(index.isValid())
665 if(LogFileModel *log = m_jobList->getLogFile(index))
667 QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
668 QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
669 QFile outFile(logFilePath);
670 if(outFile.open(QIODevice::WriteOnly))
672 QTextStream outStream(&outFile);
673 outStream.setCodec("UTF-8");
674 outStream.setGenerateByteOrderMark(true);
676 const int rows = log->rowCount(QModelIndex());
677 for(int i = 0; i < rows; i++)
679 outStream << log->data(log->index(i, 0, QModelIndex()), Qt::DisplayRole).toString() << QLatin1String("\r\n");
681 outFile.close();
683 else
685 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
692 * Shut down the computer (with countdown)
694 void MainWindow::shutdownComputer(void)
696 ENSURE_APP_IS_READY();
698 if(countPendingJobs() > 0)
700 qDebug("Still have pending jobs, won't shutdown yet!");
701 return;
704 const int iTimeout = 30;
705 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
706 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
708 qWarning("Initiating shutdown sequence!");
710 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
711 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
712 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
713 progressDialog.setModal(true);
714 progressDialog.setAutoClose(false);
715 progressDialog.setAutoReset(false);
716 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
717 progressDialog.setWindowTitle(windowTitle());
718 progressDialog.setCancelButton(cancelButton);
719 progressDialog.show();
721 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
722 QApplication::setOverrideCursor(Qt::WaitCursor);
723 MUtils::Sound::play_sound("shutdown", false);
724 QApplication::restoreOverrideCursor();
726 QTimer timer;
727 timer.setInterval(1000);
728 timer.start();
730 QEventLoop eventLoop(this);
731 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
732 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
734 for(int i = 1; i <= iTimeout; i++)
736 eventLoop.exec();
737 if(progressDialog.wasCanceled())
739 progressDialog.close();
740 return;
742 progressDialog.setValue(i+1);
743 progressDialog.setLabelText(text.arg(iTimeout-i));
744 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
745 QApplication::processEvents();
746 MUtils::Sound::play_sound(((i < iTimeout) ? "beep" : "beep2"), false);
749 qWarning("Shutting down !!!");
751 if(MUtils::OS::shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true, false))
753 qApp->closeAllWindows();
759 * Main initialization function (called only once!)
761 void MainWindow::init(void)
763 if(m_initialized)
765 qWarning("Already initialized -> skipping!");
766 return;
769 updateLabelPos();
770 const MUtils::OS::ArgumentMap &arguments = MUtils::OS::arguments();
772 //---------------------------------------
773 // Check required binaries
774 //---------------------------------------
776 QStringList binFiles;
777 for(OptionsModel::EncArch arch = OptionsModel::EncArch_x32; arch <= OptionsModel::EncArch_x64; NEXT(arch))
779 for(OptionsModel::EncType encdr = OptionsModel::EncType_X264; encdr <= OptionsModel::EncType_X265; NEXT(encdr))
781 for(OptionsModel::EncVariant varnt = OptionsModel::EncVariant_LoBit; varnt <= OptionsModel::EncVariant_HiBit; NEXT(varnt))
783 binFiles << ENC_BINARY(m_sysinfo.data(), encdr, arch, varnt);
786 binFiles << AVS_BINARY(m_sysinfo.data(), arch == OptionsModel::EncArch_x64);
788 for(size_t i = 0; UpdaterDialog::BINARIES[i].name; i++)
790 if(UpdaterDialog::BINARIES[i].exec)
792 binFiles << QString("%1/toolset/common/%2").arg(m_sysinfo->getAppPath(), QString::fromLatin1(UpdaterDialog::BINARIES[i].name));
796 qDebug("[Validating binaries]");
797 for(QStringList::ConstIterator iter = binFiles.constBegin(); iter != binFiles.constEnd(); iter++)
799 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
800 QFile *file = new QFile(*iter);
801 qDebug("%s", file->fileName().toLatin1().constData());
802 if(file->open(QIODevice::ReadOnly))
804 if(!MUtils::OS::is_executable_file(file->fileName()))
806 QMessageBox::critical(this, tr("Invalid File!"), tr("<nobr>At least on required tool is not a valid Win32 or Win64 binary:<br><tt style=\"whitespace:nowrap\">%1</tt><br><br>Please re-install the program in order to fix the problem!</nobr>").arg(QDir::toNativeSeparators(file->fileName())).replace("-", "&minus;"));
807 qFatal(QString("Binary is invalid: %1").arg(file->fileName()).toLatin1().constData());
808 MUTILS_DELETE(file);
809 INIT_ERROR_EXIT();
811 if(m_toolsList.isNull())
813 m_toolsList.reset(new QFileList());
815 m_toolsList->append(file);
817 else
819 QMessageBox::critical(this, tr("File Not Found!"), tr("<nobr>At least on required tool could not be found:<br><tt style=\"whitespace:nowrap\">%1</tt><br><br>Please re-install the program in order to fix the problem!</nobr>").arg(QDir::toNativeSeparators(file->fileName())).replace("-", "&minus;"));
820 qFatal(QString("Binary not found: %1/toolset/%2").arg(m_sysinfo->getAppPath(), file->fileName()).toLatin1().constData());
821 MUTILS_DELETE(file);
822 INIT_ERROR_EXIT();
825 qDebug(" ");
827 //---------------------------------------
828 // Check for portable mode
829 //---------------------------------------
831 if(x264_is_portable())
833 bool ok = false;
834 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
835 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
836 if(writeTest.open(QIODevice::WriteOnly))
838 ok = (writeTest.write(data) == strlen(data));
839 writeTest.remove();
841 if(!ok)
843 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"));
844 if(val != 1) INIT_ERROR_EXIT();
848 //Pre-release popup
849 if(x264_is_prerelease())
851 qsrand(time(NULL)); int rnd = qrand() % 3;
852 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);
853 if(rnd != val) INIT_ERROR_EXIT();
856 //---------------------------------------
857 // Check CPU capabilities
858 //---------------------------------------
860 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
861 if(!m_sysinfo->hasMMXSupport())
863 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"));
864 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
865 INIT_ERROR_EXIT();
867 else if(!m_sysinfo->hasSSESupport())
869 qWarning("WARNING: System does not support SSE1, most x264 builds will not work !!!\n");
870 int val = QMessageBox::warning(this, tr("Unsupported CPU"), tr("<nobr>It appears that this machine does <b>not</b> support the SSE1 instruction set.<br>Thus most builds of x264 will <b>not</b> run on this computer at all.<br><br>Please get a CPU that supports the MMX and SSE1 instruction sets!</nobr>"), tr("Quit"), tr("Ignore"));
871 if(val != 1) INIT_ERROR_EXIT();
874 //Skip version check (not recommended!)
875 if(arguments.contains(CLI_PARAM_SKIP_VERSION_CHECK))
877 qWarning("Version checks are disabled now, you have been warned!\n");
878 m_preferences->setSkipVersionTest(true);
881 //Don't abort encoding process on timeout (not recommended!)
882 if(arguments.contains(CLI_PARAM_NO_DEADLOCK))
884 qWarning("Deadlock detection disabled, you have been warned!\n");
885 m_preferences->setAbortOnTimeout(false);
888 //---------------------------------------
889 // Check Avisynth support
890 //---------------------------------------
892 if(!arguments.contains(CLI_PARAM_SKIP_AVS_CHECK))
894 qDebug("[Check for Avisynth support]");
895 volatile double avisynthVersion = 0.0;
896 const int result = AvisynthCheckThread::detect(&avisynthVersion);
897 if(result < 0)
899 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
900 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
901 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
902 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
903 if(val != 1) INIT_ERROR_EXIT();
905 if(result && (avisynthVersion >= 2.5))
907 qDebug("Avisynth support is officially enabled now!");
908 m_sysinfo->setAVSSupport(true);
910 else
912 if(!m_preferences->getDisableWarnings())
914 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>");
915 text += tr("Please download and install Avisynth:").append("<br>").append(LINK(avs_dl_url));
916 int val = QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
917 if(val == 1)
919 m_preferences->setDisableWarnings(true);
920 PreferencesModel::savePreferences(m_preferences.data());
925 qDebug(" ");
928 //---------------------------------------
929 // Check VapurSynth support
930 //---------------------------------------
932 if(!arguments.contains(CLI_PARAM_SKIP_VPS_CHECK))
934 qDebug("[Check for VapourSynth support]");
935 QString vapoursynthPath;
936 const int result = VapourSynthCheckThread::detect(vapoursynthPath);
937 if(result < 0)
939 QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
940 text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
941 text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
942 const int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
943 if(val != 1) INIT_ERROR_EXIT();
945 if(result && (!vapoursynthPath.isEmpty()))
947 qDebug("VapourSynth support is officially enabled now!");
948 m_sysinfo->setVPSSupport(true);
949 m_sysinfo->setVPSPath(vapoursynthPath);
951 else
953 if(!m_preferences->getDisableWarnings())
955 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>");
956 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>");
957 text += tr("Note that Python v3.4 is a prerequisite for installing VapourSynth:").append("<br>").append(LINK(python_url)).append("<br>");
958 const int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
959 if(val == 1)
961 m_preferences->setDisableWarnings(true);
962 PreferencesModel::savePreferences(m_preferences.data());
966 qDebug(" ");
969 //---------------------------------------
970 // Finish initialization
971 //---------------------------------------
973 //Set Window title
974 setWindowTitle(QString("%1 (%2)").arg(windowTitle(), m_sysinfo->hasX64Support() ? "64-Bit" : "32-Bit"));
976 //Enable drag&drop support for this window, required for Qt v4.8.4+
977 setAcceptDrops(true);
979 //Update flag
980 m_initialized = true;
982 //---------------------------------------
983 // Check for Expiration
984 //---------------------------------------
986 if(MUtils::Version::app_build_date().addMonths(6) < MUtils::OS::current_date())
988 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
989 QString text;
990 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;"));
991 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;"));
992 text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace('-', "&minus;"));
993 QMessageBox msgBox(this);
994 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
995 msgBox.setWindowTitle(tr("Update Notification"));
996 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
997 msgBox.setText(text);
998 QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
999 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
1000 QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
1001 btn2->setEnabled(false);
1002 btn3->setVisible(false);
1003 QTimer::singleShot(7500, btn2, SLOT(hide()));
1004 QTimer::singleShot(7500, btn3, SLOT(show()));
1005 if(msgBox.exec() == 0)
1007 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1008 return;
1011 else if(!parseCommandLineArgs())
1013 //Update reminder
1014 if(arguments.contains(CLI_PARAM_FIRST_RUN))
1016 qWarning("First run -> resetting update check now!");
1017 m_recentlyUsed->setLastUpdateCheck(0);
1018 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
1020 else if(m_recentlyUsed->lastUpdateCheck() + 14 < MUtils::OS::current_date().toJulianDay())
1022 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
1023 if(!m_preferences->getNoUpdateReminder())
1025 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)
1027 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1028 return;
1034 //---------------------------------------
1035 // Create the IPC listener thread
1036 //---------------------------------------
1038 if(m_ipcChannel)
1040 m_ipcThread.reset(new IPCThread_Recv(m_ipcChannel));
1041 connect(m_ipcThread.data(), SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
1042 m_ipcThread->start();
1045 //Load queued jobs
1046 if(m_jobList->loadQueuedJobs(m_sysinfo.data()) > 0)
1048 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1049 m_jobList->clearQueuedJobs();
1054 * Update the label position
1056 void MainWindow::updateLabelPos(void)
1058 const QWidget *const viewPort = ui->jobsView->viewport();
1059 m_label->setGeometry(0, 0, viewPort->width(), viewPort->height());
1063 * Copy the complete log to the clipboard
1065 void MainWindow::copyLogToClipboard(bool checked)
1067 qDebug("Coyping logfile to clipboard...");
1069 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1071 log->copyToClipboard();
1072 MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
1077 * Process the dropped files
1079 void MainWindow::handlePendingFiles(void)
1081 qDebug("MainWindow::handlePendingFiles");
1083 if(!m_pendingFiles->isEmpty())
1085 QStringList pendingFiles(*m_pendingFiles);
1086 m_pendingFiles->clear();
1087 createJobMultiple(pendingFiles);
1090 qDebug("Leave from MainWindow::handlePendingFiles!");
1094 * Handle incoming IPC command
1096 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1098 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1100 qWarning("Cannot accapt commands at this time -> discarding!");
1101 return;
1104 if((!isVisible()) || m_sysTray->isVisible())
1106 sysTrayActived();
1109 MUtils::GUI::bring_to_front(this);
1111 #ifdef IPC_LOGGING
1112 qDebug("\n---------- IPC ----------");
1113 qDebug("CommandId: %d", command);
1114 for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1116 qDebug("Arguments: %s", iter->toUtf8().constData());
1118 qDebug("The Flags: 0x%08X", flags);
1119 qDebug("---------- IPC ----------\n");
1120 #endif //IPC_LOGGING
1122 switch(command)
1124 case IPC_OPCODE_PING:
1125 qDebug("Received a PING request from another instance!");
1126 MUtils::GUI::blink_window(this, 5, 125);
1127 break;
1128 case IPC_OPCODE_ADD_FILE:
1129 if(!args.isEmpty())
1131 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1133 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1134 if(!m_fileTimer->isActive())
1136 m_fileTimer->setSingleShot(true);
1137 m_fileTimer->start(5000);
1140 else
1142 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1145 break;
1146 case IPC_OPCODE_ADD_JOB:
1147 if(args.size() >= 3)
1149 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1151 OptionsModel options(m_sysinfo.data());
1152 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1153 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1155 if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1157 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1160 if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
1161 if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
1162 appendJob(args[0], args[1], &options, runImmediately);
1164 else
1166 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1169 break;
1170 default:
1171 MUTILS_THROW("Unknown command received!");
1176 * Check for new updates
1178 void MainWindow::checkUpdates(void)
1180 ENSURE_APP_IS_READY();
1182 if(countRunningJobs() > 0)
1184 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1185 return;
1188 UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo.data(), update_url);
1189 const int ret = updater->exec();
1191 if(updater->getSuccess())
1193 m_recentlyUsed->setLastUpdateCheck(MUtils::OS::current_date().toJulianDay());
1194 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
1195 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->hide();
1198 if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1200 qWarning("Exitting program to install update...");
1201 close();
1202 QApplication::quit();
1205 MUTILS_DELETE(updater);
1209 * Handle mouse event for version label
1211 void MainWindow::versionLabelMouseClicked(const int &tag)
1213 if(tag == 0)
1215 QTimer::singleShot(0, this, SLOT(showAbout()));
1220 * Handle key event for job list
1222 void MainWindow::jobListKeyPressed(const int &tag)
1224 switch(tag)
1226 case 1:
1227 ui->actionJob_MoveUp->trigger();
1228 break;
1229 case 2:
1230 ui->actionJob_MoveDown->trigger();
1231 break;
1236 * System tray was activated
1238 void MainWindow::sysTrayActived(void)
1240 m_sysTray->hide();
1241 showNormal();
1242 MUtils::GUI::bring_to_front(this);
1245 ///////////////////////////////////////////////////////////////////////////////
1246 // Event functions
1247 ///////////////////////////////////////////////////////////////////////////////
1250 * Window shown event
1252 void MainWindow::showEvent(QShowEvent *e)
1254 QMainWindow::showEvent(e);
1256 if(!m_initialized)
1258 QTimer::singleShot(0, this, SLOT(init()));
1263 * Window close event
1265 void MainWindow::closeEvent(QCloseEvent *e)
1267 if(!APP_IS_READY)
1269 e->ignore();
1270 qWarning("Cannot close window at this time!");
1271 return;
1274 //Make sure we have no running jobs left!
1275 if(countRunningJobs() > 0)
1277 e->ignore();
1278 if(!m_preferences->getNoSystrayWarning())
1280 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)
1282 m_preferences->setNoSystrayWarning(true);
1283 PreferencesModel::savePreferences(m_preferences.data());
1286 hide();
1287 m_sysTray->show();
1288 return;
1291 //Save pending jobs for next time, if desired by user
1292 if(countPendingJobs() > 0)
1294 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"));
1295 if(ret == 0)
1297 m_jobList->saveQueuedJobs();
1299 else
1301 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)
1303 e->ignore();
1304 return;
1309 //Delete remaining jobs
1310 while(m_jobList->rowCount(QModelIndex()) > 0)
1312 if((m_jobList->rowCount(QModelIndex()) % 10) == 0)
1314 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1316 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1318 e->ignore();
1319 QMessageBox::warning(this, tr("Failed To Exit"), tr("Warning: At least one job could not be deleted!"));
1323 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1324 QMainWindow::closeEvent(e);
1328 * Window resize event
1330 void MainWindow::resizeEvent(QResizeEvent *e)
1332 QMainWindow::resizeEvent(e);
1333 updateLabelPos();
1337 * File dragged over window
1339 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1341 bool accept[2] = {false, false};
1343 foreach(const QString &fmt, event->mimeData()->formats())
1345 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1346 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1349 if(accept[0] && accept[1])
1351 event->acceptProposedAction();
1356 * File dropped onto window
1358 void MainWindow::dropEvent(QDropEvent *event)
1360 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1362 qWarning("Cannot accept dropped files at this time -> discarding!");
1363 return;
1366 QStringList droppedFiles;
1367 QList<QUrl> urls = event->mimeData()->urls();
1369 while(!urls.isEmpty())
1371 QUrl currentUrl = urls.takeFirst();
1372 QFileInfo file(currentUrl.toLocalFile());
1373 if(file.exists() && file.isFile())
1375 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1376 droppedFiles << file.canonicalFilePath();
1380 if(droppedFiles.count() > 0)
1382 m_pendingFiles->append(droppedFiles);
1383 m_pendingFiles->sort();
1384 if(!m_fileTimer->isActive())
1386 m_fileTimer->setSingleShot(true);
1387 m_fileTimer->start(5000);
1392 ///////////////////////////////////////////////////////////////////////////////
1393 // Private functions
1394 ///////////////////////////////////////////////////////////////////////////////
1397 * Creates a new job
1399 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1401 bool okay = false;
1402 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed.data(), m_sysinfo.data(), m_preferences.data());
1404 addDialog->setRunImmediately(runImmediately);
1405 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1406 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1407 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1409 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1410 if(multiFile)
1412 addDialog->setSourceEditable(false);
1413 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1414 addDialog->setApplyToAllVisible(applyToAll);
1417 if(addDialog->exec() == QDialog::Accepted)
1419 sourceFileName = addDialog->sourceFile();
1420 outputFileName = addDialog->outputFile();
1421 runImmediately = addDialog->runImmediately();
1422 if(applyToAll)
1424 *applyToAll = addDialog->applyToAll();
1426 okay = true;
1429 MUTILS_DELETE(addDialog);
1430 return okay;
1434 * Creates a new job from *multiple* files
1436 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1438 QStringList::ConstIterator iter;
1439 bool applyToAll = false, runImmediately = false;
1440 int counter = 0;
1442 //Add files individually
1443 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1445 runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1446 QString sourceFileName(*iter), outputFileName;
1447 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1449 if(appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
1451 continue;
1454 return false;
1457 //Add remaining files
1458 while(applyToAll && (iter != filePathIn.constEnd()))
1460 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1461 const QString sourceFileName = *iter;
1462 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
1463 if(!appendJob(sourceFileName, outputFileName, m_options.data(), runImmediatelyTmp))
1465 return false;
1467 iter++;
1470 return true;
1474 * Append a new job
1476 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1478 bool okay = false;
1479 EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo.data(), m_preferences.data());
1480 QModelIndex newIndex = m_jobList->insertJob(thrd);
1482 if(newIndex.isValid())
1484 if(runImmediately)
1486 ui->jobsView->selectRow(newIndex.row());
1487 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1488 m_jobList->startJob(newIndex);
1491 okay = true;
1494 m_label->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1495 return okay;
1499 * Jobs that are not completed (or failed, or aborted) yet
1501 unsigned int MainWindow::countPendingJobs(void)
1503 unsigned int count = 0;
1504 const int rows = m_jobList->rowCount(QModelIndex());
1506 for(int i = 0; i < rows; i++)
1508 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1509 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1511 count++;
1515 return count;
1519 * Jobs that are still active, i.e. not terminated or enqueued
1521 unsigned int MainWindow::countRunningJobs(void)
1523 unsigned int count = 0;
1524 const int rows = m_jobList->rowCount(QModelIndex());
1526 for(int i = 0; i < rows; i++)
1528 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1529 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1531 count++;
1535 return count;
1539 * Update all buttons with respect to current job status
1541 void MainWindow::updateButtons(JobStatus status)
1543 qDebug("MainWindow::updateButtons(void)");
1545 ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1546 ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1547 ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1548 ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1550 ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1551 ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1552 ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1553 ui->actionJob_MoveUp->setEnabled(status != JobStatus_Undefined);
1554 ui->actionJob_MoveDown->setEnabled(status != JobStatus_Undefined);
1556 ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1557 ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1558 ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1559 ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1561 ui->editDetails->setEnabled(status != JobStatus_Paused);
1565 * Update the taskbar with current job status
1567 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1569 qDebug("MainWindow::updateTaskbar(void)");
1571 if(m_taskbar.isNull())
1573 return; /*taskbar object not created yet*/
1576 switch(status)
1578 case JobStatus_Undefined:
1579 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE);
1580 break;
1581 case JobStatus_Aborting:
1582 case JobStatus_Starting:
1583 case JobStatus_Pausing:
1584 case JobStatus_Resuming:
1585 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_INTERMEDIATE);
1586 break;
1587 case JobStatus_Aborted:
1588 case JobStatus_Failed:
1589 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR);
1590 break;
1591 case JobStatus_Paused:
1592 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_PAUSED);
1593 break;
1594 default:
1595 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL);
1596 break;
1599 switch(status)
1601 case JobStatus_Aborting:
1602 case JobStatus_Starting:
1603 case JobStatus_Pausing:
1604 case JobStatus_Resuming:
1605 break;
1606 default:
1607 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
1608 break;
1611 m_taskbar->setOverlayIcon(icon.isNull() ? NULL : &icon);
1615 * Parse command-line arguments
1617 bool MainWindow::parseCommandLineArgs(void)
1619 const MUtils::OS::ArgumentMap &args = MUtils::OS::arguments();
1621 quint32 flags = 0;
1622 bool commandSent = false;
1624 //Handle flags
1625 if(args.contains(CLI_PARAM_FORCE_START))
1627 flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1629 if(args.contains(CLI_PARAM_FORCE_ENQUEUE))
1631 flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1634 //Process all command-line arguments
1635 if(args.contains(CLI_PARAM_ADD_FILE))
1637 foreach(const QString &fileName, args.values(CLI_PARAM_ADD_FILE))
1639 handleCommand(IPC_OPCODE_ADD_FILE, QStringList() << fileName, flags);
1641 commandSent = true;
1643 if(args.contains(CLI_PARAM_ADD_JOB))
1645 foreach(const QString &options, args.values(CLI_PARAM_ADD_JOB))
1647 const QStringList optionValues = options.split('|', QString::SkipEmptyParts);
1648 if(optionValues.count() == 3)
1650 handleCommand(IPC_OPCODE_ADD_JOB, optionValues, flags);
1652 else
1654 qWarning("Invalid number of arguments for parameter \"--%s\" detected!", CLI_PARAM_ADD_JOB);
1657 commandSent = true;
1660 return commandSent;