Changed the resize-mode for the "Status" and "Progress" columns to "ResizeToContents".
[simple-x264-launcher.git] / src / win_main.cpp
blob963dfa82f9526565e090b88278d4f4f1329d6db9
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 "resource.h"
47 //MUtils
48 #include <MUtils/OSSupport.h>
49 #include <MUtils/CPUFeatures.h>
50 #include <MUtils/IPCChannel.h>
51 #include <MUtils/GUI.h>
52 #include <MUtils/Sound.h>
53 #include <MUtils/Exception.h>
54 #include <MUtils/Taskbar7.h>
55 #include <MUtils/Version.h>
57 //Qt
58 #include <QDate>
59 #include <QTimer>
60 #include <QCloseEvent>
61 #include <QMessageBox>
62 #include <QDesktopServices>
63 #include <QUrl>
64 #include <QDir>
65 #include <QLibrary>
66 #include <QProcess>
67 #include <QProgressDialog>
68 #include <QScrollBar>
69 #include <QTextStream>
70 #include <QSettings>
71 #include <QFileDialog>
72 #include <QSystemTrayIcon>
73 #include <QMovie>
75 #include <ctime>
77 //Constants
78 static const char *tpl_last = "<LAST_USED>";
79 static const char *home_url = "http://muldersoft.com/";
80 static const char *update_url = "https://github.com/lordmulder/Simple-x264-Launcher/releases/latest";
81 static const char *avs_dl_url = "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/";
82 static const char *python_url = "https://www.python.org/downloads/";
83 static const char *vsynth_url = "http://www.vapoursynth.com/";
84 static const int vsynth_rev = 24;
86 //Macros
87 #define SET_FONT_BOLD(WIDGET,BOLD) do { QFont _font = WIDGET->font(); _font.setBold(BOLD); WIDGET->setFont(_font); } while(0)
88 #define SET_TEXT_COLOR(WIDGET,COLOR) do { QPalette _palette = WIDGET->palette(); _palette.setColor(QPalette::WindowText, (COLOR)); _palette.setColor(QPalette::Text, (COLOR)); WIDGET->setPalette(_palette); } while(0)
89 #define LINK(URL) (QString("<a href=\"%1\">%1</a>").arg((URL)))
90 #define INIT_ERROR_EXIT() do { close(); qApp->exit(-1); return; } while(0)
91 #define SETUP_WEBLINK(OBJ, URL) do { (OBJ)->setData(QVariant(QUrl(URL))); connect((OBJ), SIGNAL(triggered()), this, SLOT(showWebLink())); } while(0)
92 #define APP_IS_READY (m_initialized && (!m_fileTimer->isActive()) && (QApplication::activeModalWidget() == NULL))
93 #define ENSURE_APP_IS_READY() do { if(!APP_IS_READY) { MUtils::Sound::beep(MUtils::Sound::BEEP_WRN); qWarning("Cannot perfrom this action at this time!"); return; } } while(0)
94 #define X264_STRCMP(X,Y) ((X).compare((Y), Qt::CaseInsensitive) == 0)
96 ///////////////////////////////////////////////////////////////////////////////
97 // Constructor & Destructor
98 ///////////////////////////////////////////////////////////////////////////////
101 * Constructor
103 MainWindow::MainWindow(const MUtils::CPUFetaures::cpu_info_t &cpuFeatures, MUtils::IPCChannel *const ipcChannel)
105 m_ipcChannel(ipcChannel),
106 m_sysinfo(NULL),
107 m_options(NULL),
108 m_jobList(NULL),
109 m_pendingFiles(new QStringList()),
110 m_preferences(NULL),
111 m_recentlyUsed(NULL),
112 m_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->setCPUFeatures(SysinfoModel::CPUFeatures_MMX, cpuFeatures.features & MUtils::CPUFetaures::FLAG_MMX);
128 m_sysinfo->setCPUFeatures(SysinfoModel::CPUFeatures_SSE, cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE);
129 m_sysinfo->setCPUFeatures(SysinfoModel::CPUFeatures_X64, 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::ResizeToContents);
169 ui->jobsView->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents);
170 ui->jobsView->horizontalHeader()->setMinimumSectionSize(96);
171 ui->jobsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
172 connect(ui->jobsView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(jobSelected(QModelIndex, QModelIndex)));
174 //Setup key listener
175 m_inputFilter_jobList.reset(new InputEventFilter(ui->jobsView));
176 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Up, 1);
177 m_inputFilter_jobList->addKeyFilter(Qt::ControlModifier | Qt::Key_Down, 2);
178 connect(m_inputFilter_jobList.data(), SIGNAL(keyPressed(int)), this, SLOT(jobListKeyPressed(int)));
180 //Setup mouse listener
181 m_inputFilter_version.reset(new InputEventFilter(ui->labelBuildDate));
182 m_inputFilter_version->addMouseFilter(Qt::LeftButton, 0);
183 m_inputFilter_version->addMouseFilter(Qt::RightButton, 0);
184 connect(m_inputFilter_version.data(), SIGNAL(mouseClicked(int)), this, SLOT(versionLabelMouseClicked(int)));
186 //Create context menu
187 QAction *actionClipboard = new QAction(QIcon(":/buttons/page_paste.png"), tr("Copy to Clipboard"), ui->logView);
188 QAction *actionSaveToLog = new QAction(QIcon(":/buttons/disk.png"), tr("Save to File..."), ui->logView);
189 QAction *actionSeparator = new QAction(ui->logView);
190 QAction *actionWordwraps = new QAction(QIcon(":/buttons/text_wrapping.png"), tr("Enable Line-Wrapping"), ui->logView);
191 actionSeparator->setSeparator(true);
192 actionWordwraps->setCheckable(true);
193 actionClipboard->setEnabled(false);
194 actionSaveToLog->setEnabled(false);
195 actionWordwraps->setEnabled(false);
196 ui->logView->addAction(actionClipboard);
197 ui->logView->addAction(actionSaveToLog);
198 ui->logView->addAction(actionSeparator);
199 ui->logView->addAction(actionWordwraps);
200 connect(actionClipboard, SIGNAL(triggered(bool)), this, SLOT(copyLogToClipboard(bool)));
201 connect(actionSaveToLog, SIGNAL(triggered(bool)), this, SLOT(saveLogToLocalFile(bool)));
202 connect(actionWordwraps, SIGNAL(triggered(bool)), this, SLOT(toggleLineWrapping(bool)));
203 ui->jobsView->addActions(ui->menuJob->actions());
205 //Enable buttons
206 connect(ui->buttonAddJob, SIGNAL(clicked()), this, SLOT(addButtonPressed() ));
207 connect(ui->buttonStartJob, SIGNAL(clicked()), this, SLOT(startButtonPressed() ));
208 connect(ui->buttonAbortJob, SIGNAL(clicked()), this, SLOT(abortButtonPressed() ));
209 connect(ui->buttonPauseJob, SIGNAL(toggled(bool)), this, SLOT(pauseButtonPressed(bool)));
210 connect(ui->actionJob_Delete, SIGNAL(triggered()), this, SLOT(deleteButtonPressed() ));
211 connect(ui->actionJob_Restart, SIGNAL(triggered()), this, SLOT(restartButtonPressed() ));
212 connect(ui->actionJob_Browse, SIGNAL(triggered()), this, SLOT(browseButtonPressed() ));
213 connect(ui->actionJob_MoveUp, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
214 connect(ui->actionJob_MoveDown, SIGNAL(triggered()), this, SLOT(moveButtonPressed() ));
216 //Enable menu
217 connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
218 connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
219 connect(ui->actionPreferences, SIGNAL(triggered()), this, SLOT(showPreferences()));
220 connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this, SLOT(checkUpdates()));
222 //Setup web-links
223 SETUP_WEBLINK(ui->actionWebMulder, home_url);
224 SETUP_WEBLINK(ui->actionWebX264, "http://www.videolan.org/developers/x264.html");
225 SETUP_WEBLINK(ui->actionWebX265, "http://www.videolan.org/developers/x265.html");
226 SETUP_WEBLINK(ui->actionWebKomisar, "http://komisar.gin.by/");
227 SETUP_WEBLINK(ui->actionWebVideoLAN, "http://download.videolan.org/pub/x264/binaries/");
228 SETUP_WEBLINK(ui->actionWebJEEB, "http://x264.fushizen.eu/");
229 SETUP_WEBLINK(ui->actionWebFreeCodecs, "http://www.free-codecs.com/x264_video_codec_download.htm");
230 SETUP_WEBLINK(ui->actionWebX265BinRU, "http://x265.ru/en/builds/");
231 SETUP_WEBLINK(ui->actionWebX265BinEU, "http://builds.x265.eu/");
232 SETUP_WEBLINK(ui->actionWebX265BinORG, "http://chromashift.org/x265_builds/");
233 SETUP_WEBLINK(ui->actionWebX265BinFF, "http://ffmpeg.zeranoe.com/builds/");
234 SETUP_WEBLINK(ui->actionWebAvisynth32, "http://sourceforge.net/projects/avisynth2/files/AviSynth%202.5/");
235 SETUP_WEBLINK(ui->actionWebAvisynth64, "http://code.google.com/p/avisynth64/downloads/list");
236 SETUP_WEBLINK(ui->actionWebAvisynthPlus, "http://www.avs-plus.net/");
237 SETUP_WEBLINK(ui->actionWebVapourSynth, "http://www.vapoursynth.com/");
238 SETUP_WEBLINK(ui->actionWebVapourSynthDocs, "http://www.vapoursynth.com/doc/");
239 SETUP_WEBLINK(ui->actionOnlineDocX264, "http://en.wikibooks.org/wiki/MeGUI/x264_Settings"); //http://mewiki.project357.com/wiki/X264_Settings
240 SETUP_WEBLINK(ui->actionOnlineDocX265, "http://x265.readthedocs.org/en/default/");
241 SETUP_WEBLINK(ui->actionWebBluRay, "http://www.x264bluray.com/");
242 SETUP_WEBLINK(ui->actionWebAvsWiki, "http://avisynth.nl/index.php/Main_Page#Usage");
243 SETUP_WEBLINK(ui->actionWebSupport, "http://forum.doom9.org/showthread.php?t=144140");
244 SETUP_WEBLINK(ui->actionWebSecret, "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
246 //Create floating label
247 m_label[0].reset(new QLabel(ui->jobsView->viewport()));
248 m_label[1].reset(new QLabel(ui->logView->viewport()));
249 if(!m_label[0].isNull())
251 m_label[0]->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
252 m_label[0]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
253 SET_TEXT_COLOR(m_label[0], Qt::darkGray);
254 SET_FONT_BOLD(m_label[0], true);
255 m_label[0]->setVisible(true);
256 m_label[0]->setContextMenuPolicy(Qt::ActionsContextMenu);
257 m_label[0]->addActions(ui->jobsView->actions());
259 if(!m_label[1].isNull())
261 m_animation.reset(new QMovie(":/images/spinner.gif"));
262 m_label[1]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
263 if(!m_animation.isNull())
265 m_label[1]->setMovie(m_animation.data());
266 m_animation->start();
269 connect(ui->splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
270 updateLabelPos();
272 //Init system tray icon
273 m_sysTray.reset(new QSystemTrayIcon(this));
274 m_sysTray->setToolTip(this->windowTitle());
275 m_sysTray->setIcon(this->windowIcon());
276 connect(m_sysTray.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(sysTrayActived()));
278 //Init taskbar progress
279 m_taskbar.reset(new MUtils::Taskbar7(this));
281 //Create corner widget
282 QLabel *checkUp = new QLabel(ui->menubar);
283 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")));
284 checkUp->setFixedHeight(ui->menubar->height());
285 checkUp->setCursor(QCursor(Qt::PointingHandCursor));
286 m_inputFilter_checkUp.reset(new InputEventFilter(checkUp));
287 m_inputFilter_checkUp->addMouseFilter(Qt::LeftButton, 0);
288 m_inputFilter_checkUp->addMouseFilter(Qt::RightButton, 0);
289 connect(m_inputFilter_checkUp.data(), SIGNAL(mouseClicked(int)), this, SLOT(checkUpdates()));
290 checkUp->hide();
291 ui->menubar->setCornerWidget(checkUp);
293 //Create timer
294 m_fileTimer.reset(new QTimer(this));
295 connect(m_fileTimer.data(), SIGNAL(timeout()), this, SLOT(handlePendingFiles()));
299 * Destructor
301 MainWindow::~MainWindow(void)
303 OptionsModel::saveTemplate(m_options.data(), QString::fromLatin1(tpl_last));
305 if(!m_ipcThread.isNull())
307 m_ipcThread->stop();
308 if(!m_ipcThread->wait(5000))
310 m_ipcThread->terminate();
311 m_ipcThread->wait();
315 delete ui;
318 ///////////////////////////////////////////////////////////////////////////////
319 // Slots
320 ///////////////////////////////////////////////////////////////////////////////
323 * The "add" button was clicked
325 void MainWindow::addButtonPressed()
327 ENSURE_APP_IS_READY();
329 qDebug("MainWindow::addButtonPressed");
330 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
331 QString sourceFileName, outputFileName;
333 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
335 appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
340 * The "open" action was triggered
342 void MainWindow::openActionTriggered()
344 ENSURE_APP_IS_READY();
346 QStringList fileList = QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL, QFileDialog::DontUseNativeDialog);
347 if(!fileList.empty())
349 m_recentlyUsed->setSourceDirectory(QFileInfo(fileList.last()).absolutePath());
350 if(fileList.count() > 1)
352 createJobMultiple(fileList);
354 else
356 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
357 QString sourceFileName(fileList.first()), outputFileName;
358 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
360 appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately);
367 * The "start" button was clicked
369 void MainWindow::startButtonPressed(void)
371 ENSURE_APP_IS_READY();
372 m_jobList->startJob(ui->jobsView->currentIndex());
376 * The "abort" button was clicked
378 void MainWindow::abortButtonPressed(void)
380 ENSURE_APP_IS_READY();
382 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)
384 m_jobList->abortJob(ui->jobsView->currentIndex());
389 * The "delete" button was clicked
391 void MainWindow::deleteButtonPressed(void)
393 ENSURE_APP_IS_READY();
395 m_jobList->deleteJob(ui->jobsView->currentIndex());
396 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
400 * The "browse" button was clicked
402 void MainWindow::browseButtonPressed(void)
404 ENSURE_APP_IS_READY();
406 QString outputFile = m_jobList->getJobOutputFile(ui->jobsView->currentIndex());
407 if((!outputFile.isEmpty()) && QFileInfo(outputFile).exists() && QFileInfo(outputFile).isFile())
409 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile), QFileInfo(outputFile).path());
411 else
413 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
418 * The "browse" button was clicked
420 void MainWindow::moveButtonPressed(void)
422 ENSURE_APP_IS_READY();
424 if(sender() == ui->actionJob_MoveUp)
426 qDebug("Move job %d (direction: UP)", ui->jobsView->currentIndex().row());
427 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_UP))
429 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
431 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
433 else if(sender() == ui->actionJob_MoveDown)
435 qDebug("Move job %d (direction: DOWN)", ui->jobsView->currentIndex().row());
436 if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_DOWN))
438 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR);
440 ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter);
442 else
444 qWarning("[moveButtonPressed] Error: Unknown sender!");
449 * The "pause" button was clicked
451 void MainWindow::pauseButtonPressed(bool checked)
453 if(!APP_IS_READY)
455 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN);
456 qWarning("Cannot perfrom this action at this time!");
457 ui->buttonPauseJob->setChecked(!checked);
460 if(checked)
462 m_jobList->pauseJob(ui->jobsView->currentIndex());
464 else
466 m_jobList->resumeJob(ui->jobsView->currentIndex());
471 * The "restart" button was clicked
473 void MainWindow::restartButtonPressed(void)
475 ENSURE_APP_IS_READY();
477 const QModelIndex index = ui->jobsView->currentIndex();
478 const OptionsModel *options = m_jobList->getJobOptions(index);
479 QString sourceFileName = m_jobList->getJobSourceFile(index);
480 QString outputFileName = m_jobList->getJobOutputFile(index);
482 if((options) && (!sourceFileName.isEmpty()) && (!outputFileName.isEmpty()))
484 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
485 OptionsModel *tempOptions = new OptionsModel(*options);
486 if(createJob(sourceFileName, outputFileName, tempOptions, runImmediately, true))
488 appendJob(sourceFileName, outputFileName, tempOptions, runImmediately);
490 MUTILS_DELETE(tempOptions);
495 * Job item selected by user
497 void MainWindow::jobSelected(const QModelIndex & current, const QModelIndex & previous)
499 qDebug("Job selected: %d", current.row());
501 if(ui->logView->model())
503 disconnect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
506 if(current.isValid())
508 ui->logView->setModel(m_jobList->getLogFile(current));
509 connect(ui->logView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(jobLogExtended(QModelIndex, int, int)));
510 foreach(QAction *action, ui->logView->actions())
512 action->setEnabled(true);
514 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
516 ui->progressBar->setValue(m_jobList->getJobProgress(current));
517 ui->editDetails->setText(m_jobList->data(m_jobList->index(current.row(), 3, QModelIndex()), Qt::DisplayRole).toString());
518 updateButtons(m_jobList->getJobStatus(current));
519 updateTaskbar(m_jobList->getJobStatus(current), m_jobList->data(m_jobList->index(current.row(), 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
521 else
523 ui->logView->setModel(NULL);
524 foreach(QAction *action, ui->logView->actions())
526 action->setEnabled(false);
528 ui->progressBar->setValue(0);
529 ui->editDetails->clear();
530 updateButtons(JobStatus_Undefined);
531 updateTaskbar(JobStatus_Undefined, QIcon());
534 ui->progressBar->repaint();
538 * Handle update of job info (status, progress, details, etc)
540 void MainWindow::jobChangedData(const QModelIndex &topLeft, const QModelIndex &bottomRight)
542 int selected = ui->jobsView->currentIndex().row();
544 if(topLeft.column() <= 1 && bottomRight.column() >= 1) /*STATUS*/
546 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
548 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
549 if(i == selected)
551 qDebug("Current job changed status!");
552 updateButtons(status);
553 updateTaskbar(status, m_jobList->data(m_jobList->index(i, 0, QModelIndex()), Qt::DecorationRole).value<QIcon>());
555 if((status == JobStatus_Completed) || (status == JobStatus_Failed))
557 if(m_preferences->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
558 if(m_preferences->getSaveLogFiles()) saveLogFile(m_jobList->index(i, 1, QModelIndex()));
562 if(topLeft.column() <= 2 && bottomRight.column() >= 2) /*PROGRESS*/
564 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
566 if(i == selected)
568 ui->progressBar->setValue(m_jobList->getJobProgress(m_jobList->index(i, 0, QModelIndex())));
569 if(!m_taskbar.isNull())
571 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
573 break;
577 if(topLeft.column() <= 3 && bottomRight.column() >= 3) /*DETAILS*/
579 for(int i = topLeft.row(); i <= bottomRight.row(); i++)
581 if(i == selected)
583 ui->editDetails->setText(m_jobList->data(m_jobList->index(i, 3, QModelIndex()), Qt::DisplayRole).toString());
584 break;
591 * Handle new log file content
593 void MainWindow::jobLogExtended(const QModelIndex & parent, int start, int end)
595 QTimer::singleShot(0, ui->logView, SLOT(scrollToBottom()));
599 * About screen
601 void MainWindow::showAbout(void)
603 ENSURE_APP_IS_READY();
605 if(AboutDialog *aboutDialog = new AboutDialog(this))
607 aboutDialog->exec();
608 MUTILS_DELETE(aboutDialog);
613 * Open web-link
615 void MainWindow::showWebLink(void)
617 ENSURE_APP_IS_READY();
619 if(QObject *obj = QObject::sender())
621 if(QAction *action = dynamic_cast<QAction*>(obj))
623 if(action->data().type() == QVariant::Url)
625 QDesktopServices::openUrl(action->data().toUrl());
632 * Pereferences dialog
634 void MainWindow::showPreferences(void)
636 ENSURE_APP_IS_READY();
638 PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences.data(), m_sysinfo.data());
639 preferences->exec();
641 MUTILS_DELETE(preferences);
645 * Launch next job, after running job has finished
647 void MainWindow::launchNextJob(void)
649 qDebug("Launching next job...");
651 if(countRunningJobs() >= m_preferences->getMaxRunningJobCount())
653 qDebug("Still have too many jobs running, won't launch next one yet!");
654 return;
657 const int rows = m_jobList->rowCount(QModelIndex());
659 for(int i = 0; i < rows; i++)
661 const QModelIndex currentIndex = m_jobList->index(i, 0, QModelIndex());
662 if(m_jobList->getJobStatus(currentIndex) == JobStatus_Enqueued)
664 if(m_jobList->startJob(currentIndex))
666 ui->jobsView->selectRow(currentIndex.row());
667 return;
672 qWarning("No enqueued jobs left to be started!");
674 if(m_preferences->getShutdownComputer())
676 QTimer::singleShot(0, this, SLOT(shutdownComputer()));
681 * Save log to text file
683 void MainWindow::saveLogFile(const QModelIndex &index)
685 if(index.isValid())
687 if(LogFileModel *log = m_jobList->getLogFile(index))
689 QDir(QString("%1/logs").arg(x264_data_path())).mkpath(".");
690 QString logFilePath = QString("%1/logs/LOG.%2.%3.txt").arg(x264_data_path(), QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate).replace(':', "-"));
691 if(!log->saveToLocalFile(logFilePath))
693 qWarning("Failed to open log file for writing:\n%s", logFilePath.toUtf8().constData());
700 * Shut down the computer (with countdown)
702 void MainWindow::shutdownComputer(void)
704 ENSURE_APP_IS_READY();
706 if(countPendingJobs() > 0)
708 qDebug("Still have pending jobs, won't shutdown yet!");
709 return;
712 const int iTimeout = 30;
713 const Qt::WindowFlags flags = Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowSystemMenuHint;
714 const QString text = QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
716 qWarning("Initiating shutdown sequence!");
718 QProgressDialog progressDialog(text.arg(iTimeout), tr("Cancel Shutdown"), 0, iTimeout + 1, this, flags);
719 QPushButton *cancelButton = new QPushButton(tr("Cancel Shutdown"), &progressDialog);
720 cancelButton->setIcon(QIcon(":/buttons/power_on.png"));
721 progressDialog.setModal(true);
722 progressDialog.setAutoClose(false);
723 progressDialog.setAutoReset(false);
724 progressDialog.setWindowIcon(QIcon(":/buttons/power_off.png"));
725 progressDialog.setWindowTitle(windowTitle());
726 progressDialog.setCancelButton(cancelButton);
727 progressDialog.show();
729 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
730 QApplication::setOverrideCursor(Qt::WaitCursor);
731 MUtils::Sound::play_sound("shutdown", false);
732 QApplication::restoreOverrideCursor();
734 QTimer timer;
735 timer.setInterval(1000);
736 timer.start();
738 QEventLoop eventLoop(this);
739 connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
740 connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit()));
742 for(int i = 1; i <= iTimeout; i++)
744 eventLoop.exec();
745 if(progressDialog.wasCanceled())
747 progressDialog.close();
748 return;
750 progressDialog.setValue(i+1);
751 progressDialog.setLabelText(text.arg(iTimeout-i));
752 if(iTimeout-i == 3) progressDialog.setCancelButton(NULL);
753 QApplication::processEvents();
754 MUtils::Sound::play_sound(((i < iTimeout) ? "beep" : "beep2"), false);
757 qWarning("Shutting down !!!");
759 if(MUtils::OS::shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true, false))
761 qApp->closeAllWindows();
767 * Main initialization function (called only once!)
769 void MainWindow::init(void)
771 if(m_initialized)
773 qWarning("Already initialized -> skipping!");
774 return;
777 updateLabelPos();
778 const MUtils::OS::ArgumentMap &arguments = MUtils::OS::arguments();
779 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
781 //---------------------------------------
782 // Check required binaries
783 //---------------------------------------
785 qDebug("[Validating binaries]");
786 if(!BinariesCheckThread::check(m_sysinfo.data()))
788 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;"));
789 qFatal("At least one tool is missing or is not a valid Win32/Win64 binary!");
791 qDebug(" ");
793 //---------------------------------------
794 // Check for portable mode
795 //---------------------------------------
797 if(x264_is_portable())
799 bool ok = false;
800 static const char *data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
801 QFile writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
802 if(writeTest.open(QIODevice::WriteOnly))
804 ok = (writeTest.write(data) == strlen(data));
805 writeTest.remove();
807 if(!ok)
809 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"));
810 if(val != 1) INIT_ERROR_EXIT();
814 //Pre-release popup
815 if(x264_is_prerelease())
817 qsrand(time(NULL)); int rnd = qrand() % 3;
818 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);
819 if(rnd != val) INIT_ERROR_EXIT();
822 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
824 //---------------------------------------
825 // Check CPU capabilities
826 //---------------------------------------
828 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
829 if(!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_MMX))
831 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"));
832 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
833 INIT_ERROR_EXIT();
835 else if(!m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_SSE))
837 qWarning("WARNING: System does not support SSE (v1), x264/x265 probably will *not* work !!!\n");
838 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"));
839 if(val != 1) INIT_ERROR_EXIT();
842 //Skip version check (not recommended!)
843 if(arguments.contains(CLI_PARAM_SKIP_VERSION_CHECK))
845 qWarning("Version checks are disabled now, you have been warned!\n");
846 m_preferences->setSkipVersionTest(true);
849 //Don't abort encoding process on timeout (not recommended!)
850 if(arguments.contains(CLI_PARAM_NO_DEADLOCK))
852 qWarning("Deadlock detection disabled, you have been warned!\n");
853 m_preferences->setAbortOnTimeout(false);
856 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
858 //---------------------------------------
859 // Check Avisynth support
860 //---------------------------------------
862 if(!arguments.contains(CLI_PARAM_SKIP_AVS_CHECK))
864 qDebug("[Check for Avisynth support]");
865 if(!AvisynthCheckThread::detect(m_sysinfo.data()))
867 QString text = tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
868 text += tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
869 text += tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
870 int val = QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
871 if(val != 1) INIT_ERROR_EXIT();
873 else if((!m_sysinfo->hasAvisynth()) && (!m_preferences->getDisableWarnings()))
875 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>");
876 text += tr("Please download and install Avisynth:").append("<br>").append(LINK(avs_dl_url));
877 int val = QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
878 if(val == 1)
880 m_preferences->setDisableWarnings(true);
881 PreferencesModel::savePreferences(m_preferences.data());
884 qDebug(" ");
887 //---------------------------------------
888 // Check VapurSynth support
889 //---------------------------------------
891 if(!arguments.contains(CLI_PARAM_SKIP_VPS_CHECK))
893 qDebug("[Check for VapourSynth support]");
894 if(!VapourSynthCheckThread::detect(m_sysinfo.data()))
896 QString text = tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
897 text += tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
898 text += tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
899 const int val = QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Quit"), tr("Ignore"));
900 if(val != 1) INIT_ERROR_EXIT();
902 else if((!m_sysinfo->hasVapourSynth()) && (!m_preferences->getDisableWarnings()))
904 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>");
905 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>");
906 text += tr("Note that Python v3.4 is a prerequisite for installing VapourSynth:").append("<br>").append(LINK(python_url)).append("<br>");
907 const int val = QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text).replace("-", "&minus;"), tr("Close"), tr("Disable this Warning"));
908 if(val == 1)
910 m_preferences->setDisableWarnings(true);
911 PreferencesModel::savePreferences(m_preferences.data());
914 qDebug(" ");
917 //---------------------------------------
918 // Create the IPC listener thread
919 //---------------------------------------
921 if(m_ipcChannel)
923 m_ipcThread.reset(new IPCThread_Recv(m_ipcChannel));
924 connect(m_ipcThread.data(), SIGNAL(receivedCommand(int,QStringList,quint32)), this, SLOT(handleCommand(int,QStringList,quint32)), Qt::QueuedConnection);
925 m_ipcThread->start();
928 //---------------------------------------
929 // Finish initialization
930 //---------------------------------------
932 //Set Window title
933 setWindowTitle(QString("%1 (%2)").arg(windowTitle(), m_sysinfo->getCPUFeatures(SysinfoModel::CPUFeatures_X64) ? "64-Bit" : "32-Bit"));
935 //Enable drag&drop support for this window, required for Qt v4.8.4+
936 setAcceptDrops(true);
938 //Update flag
939 m_initialized = true;
941 //Hide the spinner animation
942 if(!m_label[1].isNull())
944 if(!m_animation.isNull())
946 m_animation->stop();
948 m_label[1]->setVisible(false);
951 //---------------------------------------
952 // Check for Expiration
953 //---------------------------------------
955 if(MUtils::Version::app_build_date().addMonths(6) < MUtils::OS::current_date())
957 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
958 QString text;
959 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;"));
960 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;"));
961 text += QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace('-', "&minus;"));
962 QMessageBox msgBox(this);
963 msgBox.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
964 msgBox.setWindowTitle(tr("Update Notification"));
965 msgBox.setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
966 msgBox.setText(text);
967 QPushButton *btn1 = msgBox.addButton(tr("Check for Updates"), QMessageBox::AcceptRole);
968 QPushButton *btn2 = msgBox.addButton(tr("Discard"), QMessageBox::NoRole);
969 QPushButton *btn3 = msgBox.addButton(btn2->text(), QMessageBox::RejectRole);
970 btn2->setEnabled(false);
971 btn3->setVisible(false);
972 QTimer::singleShot(7500, btn2, SLOT(hide()));
973 QTimer::singleShot(7500, btn3, SLOT(show()));
974 if(msgBox.exec() == 0)
976 QTimer::singleShot(0, this, SLOT(checkUpdates()));
977 return;
980 else if(!parseCommandLineArgs())
982 //Update reminder
983 if(arguments.contains(CLI_PARAM_FIRST_RUN))
985 qWarning("First run -> resetting update check now!");
986 m_recentlyUsed->setLastUpdateCheck(0);
987 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
989 else if(m_recentlyUsed->lastUpdateCheck() + 14 < MUtils::OS::current_date().toJulianDay())
991 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show();
992 if(!m_preferences->getNoUpdateReminder())
994 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)
996 QTimer::singleShot(0, this, SLOT(checkUpdates()));
997 return;
1003 //Load queued jobs
1004 if(m_jobList->loadQueuedJobs(m_sysinfo.data()) > 0)
1006 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1007 m_jobList->clearQueuedJobs();
1012 * Update the label position
1014 void MainWindow::updateLabelPos(void)
1016 for(int i = 0; i < 2; i++)
1018 //const QWidget *const viewPort = ui->jobsView->viewport();
1019 const QWidget *const viewPort = dynamic_cast<QWidget*>(m_label[i]->parent());
1020 if(viewPort)
1022 m_label[i]->setGeometry(0, 0, viewPort->width(), viewPort->height());
1028 * Copy the complete log to the clipboard
1030 void MainWindow::copyLogToClipboard(bool checked)
1032 qDebug("Coyping logfile to clipboard...");
1034 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1036 log->copyToClipboard();
1037 MUtils::Sound::beep(MUtils::Sound::BEEP_NFO);
1042 * Save log to local file
1044 void MainWindow::saveLogToLocalFile(bool checked)
1046 ENSURE_APP_IS_READY();
1048 const QModelIndex index = ui->jobsView->currentIndex();
1049 const QString initialName = index.isValid() ? QFileInfo(m_jobList->getJobOutputFile(index)).completeBaseName() : tr("Logfile");
1050 const QString fileName = QFileDialog::getSaveFileName(this, tr("Save Log File"), initialName, tr("Log File (*.log)"));
1051 if(!fileName.isEmpty())
1053 if(LogFileModel *log = dynamic_cast<LogFileModel*>(ui->logView->model()))
1055 if(!log->saveToLocalFile(fileName))
1057 QMessageBox::warning(this, this->windowTitle(), tr("Error: Log file could not be saved!"));
1064 * Toggle line-wrapping
1066 void MainWindow::toggleLineWrapping(bool checked)
1068 ui->logView->setWordWrap(checked);
1072 * Process the dropped files
1074 void MainWindow::handlePendingFiles(void)
1076 qDebug("MainWindow::handlePendingFiles");
1078 if(!m_pendingFiles->isEmpty())
1080 QStringList pendingFiles(*m_pendingFiles);
1081 m_pendingFiles->clear();
1082 createJobMultiple(pendingFiles);
1085 qDebug("Leave from MainWindow::handlePendingFiles!");
1089 * Handle incoming IPC command
1091 void MainWindow::handleCommand(const int &command, const QStringList &args, const quint32 &flags)
1093 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1095 qWarning("Cannot accapt commands at this time -> discarding!");
1096 return;
1099 if((!isVisible()) || m_sysTray->isVisible())
1101 sysTrayActived();
1104 MUtils::GUI::bring_to_front(this);
1106 #ifdef IPC_LOGGING
1107 qDebug("\n---------- IPC ----------");
1108 qDebug("CommandId: %d", command);
1109 for(QStringList::ConstIterator iter = args.constBegin(); iter != args.constEnd(); iter++)
1111 qDebug("Arguments: %s", iter->toUtf8().constData());
1113 qDebug("The Flags: 0x%08X", flags);
1114 qDebug("---------- IPC ----------\n");
1115 #endif //IPC_LOGGING
1117 switch(command)
1119 case IPC_OPCODE_PING:
1120 qDebug("Received a PING request from another instance!");
1121 MUtils::GUI::blink_window(this, 5, 125);
1122 break;
1123 case IPC_OPCODE_ADD_FILE:
1124 if(!args.isEmpty())
1126 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1128 *m_pendingFiles << QFileInfo(args[0]).canonicalFilePath();
1129 if(!m_fileTimer->isActive())
1131 m_fileTimer->setSingleShot(true);
1132 m_fileTimer->start(5000);
1135 else
1137 qWarning("File '%s' not found!", args[0].toUtf8().constData());
1140 break;
1141 case IPC_OPCODE_ADD_JOB:
1142 if(args.size() >= 3)
1144 if(QFileInfo(args[0]).exists() && QFileInfo(args[0]).isFile())
1146 OptionsModel options(m_sysinfo.data());
1147 bool runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1148 if(!(args[2].isEmpty() || X264_STRCMP(args[2], "-")))
1150 if(!OptionsModel::loadTemplate(&options, args[2].trimmed()))
1152 qWarning("Template '%s' could not be found -> using defaults!", args[2].trimmed().toUtf8().constData());
1155 if((flags & IPC_FLAG_FORCE_START) && (!(flags & IPC_FLAG_FORCE_ENQUEUE))) runImmediately = true;
1156 if((flags & IPC_FLAG_FORCE_ENQUEUE) && (!(flags & IPC_FLAG_FORCE_START))) runImmediately = false;
1157 appendJob(args[0], args[1], &options, runImmediately);
1159 else
1161 qWarning("Source file '%s' not found!", args[0].toUtf8().constData());
1164 break;
1165 default:
1166 MUTILS_THROW("Unknown command received!");
1171 * Check for new updates
1173 void MainWindow::checkUpdates(void)
1175 ENSURE_APP_IS_READY();
1177 if(countRunningJobs() > 0)
1179 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1180 return;
1183 UpdaterDialog *updater = new UpdaterDialog(this, m_sysinfo.data(), update_url);
1184 const int ret = updater->exec();
1186 if(updater->getSuccess())
1188 m_recentlyUsed->setLastUpdateCheck(MUtils::OS::current_date().toJulianDay());
1189 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data());
1190 if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->hide();
1193 if(ret == UpdaterDialog::READY_TO_INSTALL_UPDATE)
1195 qWarning("Exitting program to install update...");
1196 close();
1197 QApplication::quit();
1200 MUTILS_DELETE(updater);
1204 * Handle mouse event for version label
1206 void MainWindow::versionLabelMouseClicked(const int &tag)
1208 if(tag == 0)
1210 QTimer::singleShot(0, this, SLOT(showAbout()));
1215 * Handle key event for job list
1217 void MainWindow::jobListKeyPressed(const int &tag)
1219 switch(tag)
1221 case 1:
1222 ui->actionJob_MoveUp->trigger();
1223 break;
1224 case 2:
1225 ui->actionJob_MoveDown->trigger();
1226 break;
1231 * System tray was activated
1233 void MainWindow::sysTrayActived(void)
1235 m_sysTray->hide();
1236 showNormal();
1237 MUtils::GUI::bring_to_front(this);
1240 ///////////////////////////////////////////////////////////////////////////////
1241 // Event functions
1242 ///////////////////////////////////////////////////////////////////////////////
1245 * Window shown event
1247 void MainWindow::showEvent(QShowEvent *e)
1249 QMainWindow::showEvent(e);
1251 if(!m_initialized)
1253 QTimer::singleShot(0, this, SLOT(init()));
1258 * Window close event
1260 void MainWindow::closeEvent(QCloseEvent *e)
1262 if(!APP_IS_READY)
1264 e->ignore();
1265 qWarning("Cannot close window at this time!");
1266 return;
1269 //Make sure we have no running jobs left!
1270 if(countRunningJobs() > 0)
1272 e->ignore();
1273 if(!m_preferences->getNoSystrayWarning())
1275 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)
1277 m_preferences->setNoSystrayWarning(true);
1278 PreferencesModel::savePreferences(m_preferences.data());
1281 hide();
1282 m_sysTray->show();
1283 return;
1286 //Save pending jobs for next time, if desired by user
1287 if(countPendingJobs() > 0)
1289 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"));
1290 if(ret == 0)
1292 m_jobList->saveQueuedJobs();
1294 else
1296 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)
1298 e->ignore();
1299 return;
1304 //Delete remaining jobs
1305 while(m_jobList->rowCount(QModelIndex()) > 0)
1307 if((m_jobList->rowCount(QModelIndex()) % 10) == 0)
1309 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1311 if(!m_jobList->deleteJob(m_jobList->index(0, 0, QModelIndex())))
1313 e->ignore();
1314 QMessageBox::warning(this, tr("Failed To Exit"), tr("Warning: At least one job could not be deleted!"));
1318 qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1319 QMainWindow::closeEvent(e);
1323 * Window resize event
1325 void MainWindow::resizeEvent(QResizeEvent *e)
1327 QMainWindow::resizeEvent(e);
1328 updateLabelPos();
1332 * File dragged over window
1334 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1336 bool accept[2] = {false, false};
1338 foreach(const QString &fmt, event->mimeData()->formats())
1340 accept[0] = accept[0] || fmt.contains("text/uri-list", Qt::CaseInsensitive);
1341 accept[1] = accept[1] || fmt.contains("FileNameW", Qt::CaseInsensitive);
1344 if(accept[0] && accept[1])
1346 event->acceptProposedAction();
1351 * File dropped onto window
1353 void MainWindow::dropEvent(QDropEvent *event)
1355 if(!(m_initialized && (QApplication::activeModalWidget() == NULL)))
1357 qWarning("Cannot accept dropped files at this time -> discarding!");
1358 return;
1361 QStringList droppedFiles;
1362 QList<QUrl> urls = event->mimeData()->urls();
1364 while(!urls.isEmpty())
1366 QUrl currentUrl = urls.takeFirst();
1367 QFileInfo file(currentUrl.toLocalFile());
1368 if(file.exists() && file.isFile())
1370 qDebug("MainWindow::dropEvent: %s", file.canonicalFilePath().toUtf8().constData());
1371 droppedFiles << file.canonicalFilePath();
1375 if(droppedFiles.count() > 0)
1377 m_pendingFiles->append(droppedFiles);
1378 m_pendingFiles->sort();
1379 if(!m_fileTimer->isActive())
1381 m_fileTimer->setSingleShot(true);
1382 m_fileTimer->start(5000);
1387 ///////////////////////////////////////////////////////////////////////////////
1388 // Private functions
1389 ///////////////////////////////////////////////////////////////////////////////
1392 * Creates a new job
1394 bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, OptionsModel *options, bool &runImmediately, const bool restart, int fileNo, int fileTotal, bool *applyToAll)
1396 bool okay = false;
1397 AddJobDialog *addDialog = new AddJobDialog(this, options, m_recentlyUsed.data(), m_sysinfo.data(), m_preferences.data());
1399 addDialog->setRunImmediately(runImmediately);
1400 if(!sourceFileName.isEmpty()) addDialog->setSourceFile(sourceFileName);
1401 if(!outputFileName.isEmpty()) addDialog->setOutputFile(outputFileName);
1402 if(restart) addDialog->setWindowTitle(tr("Restart Job"));
1404 const bool multiFile = (fileNo >= 0) && (fileTotal > 1);
1405 if(multiFile)
1407 addDialog->setSourceEditable(false);
1408 addDialog->setWindowTitle(addDialog->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo+1), QString::number(fileTotal))));
1409 addDialog->setApplyToAllVisible(applyToAll);
1412 if(addDialog->exec() == QDialog::Accepted)
1414 sourceFileName = addDialog->sourceFile();
1415 outputFileName = addDialog->outputFile();
1416 runImmediately = addDialog->runImmediately();
1417 if(applyToAll)
1419 *applyToAll = addDialog->applyToAll();
1421 okay = true;
1424 MUTILS_DELETE(addDialog);
1425 return okay;
1429 * Creates a new job from *multiple* files
1431 bool MainWindow::createJobMultiple(const QStringList &filePathIn)
1433 QStringList::ConstIterator iter;
1434 bool applyToAll = false, runImmediately = false;
1435 int counter = 0;
1437 //Add files individually
1438 for(iter = filePathIn.constBegin(); (iter != filePathIn.constEnd()) && (!applyToAll); iter++)
1440 runImmediately = (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1441 QString sourceFileName(*iter), outputFileName;
1442 if(createJob(sourceFileName, outputFileName, m_options.data(), runImmediately, false, counter++, filePathIn.count(), &applyToAll))
1444 if(appendJob(sourceFileName, outputFileName, m_options.data(), runImmediately))
1446 continue;
1449 return false;
1452 //Add remaining files
1453 while(applyToAll && (iter != filePathIn.constEnd()))
1455 const bool runImmediatelyTmp = runImmediately && (countRunningJobs() < (m_preferences->getAutoRunNextJob() ? m_preferences->getMaxRunningJobCount() : 1));
1456 const QString sourceFileName = *iter;
1457 const QString outputFileName = AddJobDialog::generateOutputFileName(sourceFileName, m_recentlyUsed->outputDirectory(), m_recentlyUsed->filterIndex(), m_preferences->getSaveToSourcePath());
1458 if(!appendJob(sourceFileName, outputFileName, m_options.data(), runImmediatelyTmp))
1460 return false;
1462 iter++;
1465 return true;
1469 * Append a new job
1471 bool MainWindow::appendJob(const QString &sourceFileName, const QString &outputFileName, OptionsModel *options, const bool runImmediately)
1473 bool okay = false;
1474 EncodeThread *thrd = new EncodeThread(sourceFileName, outputFileName, options, m_sysinfo.data(), m_preferences.data());
1475 QModelIndex newIndex = m_jobList->insertJob(thrd);
1477 if(newIndex.isValid())
1479 if(runImmediately)
1481 ui->jobsView->selectRow(newIndex.row());
1482 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1483 m_jobList->startJob(newIndex);
1486 okay = true;
1489 m_label[0]->setVisible(m_jobList->rowCount(QModelIndex()) == 0);
1490 return okay;
1494 * Jobs that are not completed (or failed, or aborted) yet
1496 unsigned int MainWindow::countPendingJobs(void)
1498 unsigned int count = 0;
1499 const int rows = m_jobList->rowCount(QModelIndex());
1501 for(int i = 0; i < rows; i++)
1503 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1504 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed)
1506 count++;
1510 return count;
1514 * Jobs that are still active, i.e. not terminated or enqueued
1516 unsigned int MainWindow::countRunningJobs(void)
1518 unsigned int count = 0;
1519 const int rows = m_jobList->rowCount(QModelIndex());
1521 for(int i = 0; i < rows; i++)
1523 JobStatus status = m_jobList->getJobStatus(m_jobList->index(i, 0, QModelIndex()));
1524 if(status != JobStatus_Completed && status != JobStatus_Aborted && status != JobStatus_Failed && status != JobStatus_Enqueued)
1526 count++;
1530 return count;
1534 * Update all buttons with respect to current job status
1536 void MainWindow::updateButtons(JobStatus status)
1538 qDebug("MainWindow::updateButtons(void)");
1540 ui->buttonStartJob->setEnabled(status == JobStatus_Enqueued);
1541 ui->buttonAbortJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2 || status == JobStatus_Paused);
1542 ui->buttonPauseJob->setEnabled(status == JobStatus_Indexing || status == JobStatus_Running || status == JobStatus_Paused || status == JobStatus_Running_Pass1 || status == JobStatus_Running_Pass2);
1543 ui->buttonPauseJob->setChecked(status == JobStatus_Paused || status == JobStatus_Pausing);
1545 ui->actionJob_Delete->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1546 ui->actionJob_Restart->setEnabled(status == JobStatus_Completed || status == JobStatus_Aborted || status == JobStatus_Failed || status == JobStatus_Enqueued);
1547 ui->actionJob_Browse->setEnabled(status == JobStatus_Completed);
1548 ui->actionJob_MoveUp->setEnabled(status != JobStatus_Undefined);
1549 ui->actionJob_MoveDown->setEnabled(status != JobStatus_Undefined);
1551 ui->actionJob_Start->setEnabled(ui->buttonStartJob->isEnabled());
1552 ui->actionJob_Abort->setEnabled(ui->buttonAbortJob->isEnabled());
1553 ui->actionJob_Pause->setEnabled(ui->buttonPauseJob->isEnabled());
1554 ui->actionJob_Pause->setChecked(ui->buttonPauseJob->isChecked());
1556 ui->editDetails->setEnabled(status != JobStatus_Paused);
1560 * Update the taskbar with current job status
1562 void MainWindow::updateTaskbar(JobStatus status, const QIcon &icon)
1564 qDebug("MainWindow::updateTaskbar(void)");
1566 if(m_taskbar.isNull())
1568 return; /*taskbar object not created yet*/
1571 switch(status)
1573 case JobStatus_Undefined:
1574 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE);
1575 break;
1576 case JobStatus_Aborting:
1577 case JobStatus_Starting:
1578 case JobStatus_Pausing:
1579 case JobStatus_Resuming:
1580 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_INTERMEDIATE);
1581 break;
1582 case JobStatus_Aborted:
1583 case JobStatus_Failed:
1584 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR);
1585 break;
1586 case JobStatus_Paused:
1587 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_PAUSED);
1588 break;
1589 default:
1590 m_taskbar->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL);
1591 break;
1594 switch(status)
1596 case JobStatus_Aborting:
1597 case JobStatus_Starting:
1598 case JobStatus_Pausing:
1599 case JobStatus_Resuming:
1600 break;
1601 default:
1602 m_taskbar->setTaskbarProgress(ui->progressBar->value(), ui->progressBar->maximum());
1603 break;
1606 m_taskbar->setOverlayIcon(icon.isNull() ? NULL : &icon);
1610 * Parse command-line arguments
1612 bool MainWindow::parseCommandLineArgs(void)
1614 const MUtils::OS::ArgumentMap &args = MUtils::OS::arguments();
1616 quint32 flags = 0;
1617 bool commandSent = false;
1619 //Handle flags
1620 if(args.contains(CLI_PARAM_FORCE_START))
1622 flags = ((flags | IPC_FLAG_FORCE_START) & (~IPC_FLAG_FORCE_ENQUEUE));
1624 if(args.contains(CLI_PARAM_FORCE_ENQUEUE))
1626 flags = ((flags | IPC_FLAG_FORCE_ENQUEUE) & (~IPC_FLAG_FORCE_START));
1629 //Process all command-line arguments
1630 if(args.contains(CLI_PARAM_ADD_FILE))
1632 foreach(const QString &fileName, args.values(CLI_PARAM_ADD_FILE))
1634 handleCommand(IPC_OPCODE_ADD_FILE, QStringList() << fileName, flags);
1636 commandSent = true;
1638 if(args.contains(CLI_PARAM_ADD_JOB))
1640 foreach(const QString &options, args.values(CLI_PARAM_ADD_JOB))
1642 const QStringList optionValues = options.split('|', QString::SkipEmptyParts);
1643 if(optionValues.count() == 3)
1645 handleCommand(IPC_OPCODE_ADD_JOB, optionValues, flags);
1647 else
1649 qWarning("Invalid number of arguments for parameter \"--%s\" detected!", CLI_PARAM_ADD_JOB);
1652 commandSent = true;
1655 return commandSent;