1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2017 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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 ///////////////////////////////////////////////////////////////////////////////
23 #include "UIC_win_main.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"
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>
60 #include <QCloseEvent>
61 #include <QMessageBox>
62 #include <QDesktopServices>
67 #include <QProgressDialog>
69 #include <QTextStream>
71 #include <QFileDialog>
72 #include <QSystemTrayIcon>
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;
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 ///////////////////////////////////////////////////////////////////////////////
103 MainWindow::MainWindow(const MUtils::CPUFetaures::cpu_info_t
&cpuFeatures
, MUtils::IPCChannel
*const ipcChannel
)
105 m_ipcChannel(ipcChannel
),
109 m_pendingFiles(new QStringList()),
111 m_recentlyUsed(NULL
),
112 m_initialized(false),
113 ui(new Ui::MainWindow())
115 //Init the dialog, from the .ui file
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
132 m_preferences
.reset(new PreferencesModel());
133 PreferencesModel::loadPreferences(m_preferences
.data());
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);
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
)));
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()));
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());
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
)));
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());
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() ));
217 connect(ui
->actionOpen
, SIGNAL(triggered()), this, SLOT(openActionTriggered()));
218 connect(ui
->actionCleanup_Finished
, SIGNAL(triggered()), this, SLOT(cleanupActionTriggered()));
219 connect(ui
->actionCleanup_Enqueued
, SIGNAL(triggered()), this, SLOT(cleanupActionTriggered()));
220 connect(ui
->actionAbout
, SIGNAL(triggered()), this, SLOT(showAbout()));
221 connect(ui
->actionPreferences
, SIGNAL(triggered()), this, SLOT(showPreferences()));
222 connect(ui
->actionCheckForUpdates
, SIGNAL(triggered()), this, SLOT(checkUpdates()));
223 ui
->actionCleanup_Finished
->setData(QVariant(bool(0)));
224 ui
->actionCleanup_Enqueued
->setData(QVariant(bool(1)));
227 SETUP_WEBLINK(ui
->actionWebMulder
, home_url
);
228 SETUP_WEBLINK(ui
->actionWebX264
, "http://www.videolan.org/developers/x264.html");
229 SETUP_WEBLINK(ui
->actionWebX265
, "http://www.videolan.org/developers/x265.html");
230 SETUP_WEBLINK(ui
->actionWebX264Komisar
, "http://komisar.gin.by/");
231 SETUP_WEBLINK(ui
->actionWebX264VideoLAN
, "http://download.videolan.org/pub/x264/binaries/");
232 SETUP_WEBLINK(ui
->actionWebX264FreeCodecs
, "http://www.free-codecs.com/x264_video_codec_download.htm");
233 SETUP_WEBLINK(ui
->actionWebX265Fllear
, "http://x265.ru/en/builds/");
234 SETUP_WEBLINK(ui
->actionWebX265LigH
, "https://www.mediafire.com/?6lfp2jlygogwa");
235 SETUP_WEBLINK(ui
->actionWebX265Snowfag
, "http://builds.x265.eu/");
236 SETUP_WEBLINK(ui
->actionWebX265FreeCodecs
, "http://www.free-codecs.com/x265_hevc_encoder_download.htm");
237 SETUP_WEBLINK(ui
->actionWebAvisynth32
, "https://sourceforge.net/projects/avisynth2/files/AviSynth%202.6/");
238 SETUP_WEBLINK(ui
->actionWebAvisynth64
, "http://forum.doom9.org/showthread.php?t=152800");
239 SETUP_WEBLINK(ui
->actionWebAvisynthPlus
, "http://www.avs-plus.net/");
240 SETUP_WEBLINK(ui
->actionWebVapourSynth
, "http://www.vapoursynth.com/");
241 SETUP_WEBLINK(ui
->actionWebVapourSynthDocs
, "http://www.vapoursynth.com/doc/");
242 SETUP_WEBLINK(ui
->actionOnlineDocX264
, "http://en.wikibooks.org/wiki/MeGUI/x264_Settings"); //http://mewiki.project357.com/wiki/X264_Settings
243 SETUP_WEBLINK(ui
->actionOnlineDocX265
, "http://x265.readthedocs.org/en/default/");
244 SETUP_WEBLINK(ui
->actionWebBluRay
, "http://www.x264bluray.com/");
245 SETUP_WEBLINK(ui
->actionWebAvsWiki
, "http://avisynth.nl/index.php/Main_Page#Usage");
246 SETUP_WEBLINK(ui
->actionWebSupport
, "http://forum.doom9.org/showthread.php?t=144140");
247 SETUP_WEBLINK(ui
->actionWebSecret
, "http://www.youtube.com/watch_popup?v=AXIeHY-OYNI");
249 //Create floating label
250 m_label
[0].reset(new QLabel(ui
->jobsView
->viewport()));
251 m_label
[1].reset(new QLabel(ui
->logView
->viewport()));
252 if(!m_label
[0].isNull())
254 m_label
[0]->setText(tr("No job created yet. Please click the 'Add New Job' button!"));
255 m_label
[0]->setAlignment(Qt::AlignHCenter
| Qt::AlignVCenter
);
256 SET_TEXT_COLOR(m_label
[0], Qt::darkGray
);
257 SET_FONT_BOLD(m_label
[0], true);
258 m_label
[0]->setVisible(true);
259 m_label
[0]->setContextMenuPolicy(Qt::ActionsContextMenu
);
260 m_label
[0]->addActions(ui
->jobsView
->actions());
262 if(!m_label
[1].isNull())
264 m_animation
.reset(new QMovie(":/images/spinner.gif"));
265 m_label
[1]->setAlignment(Qt::AlignHCenter
| Qt::AlignVCenter
);
266 if(!m_animation
.isNull())
268 m_label
[1]->setMovie(m_animation
.data());
269 m_animation
->start();
272 connect(ui
->splitter
, SIGNAL(splitterMoved(int, int)), this, SLOT(updateLabelPos()));
275 //Init system tray icon
276 m_sysTray
.reset(new QSystemTrayIcon(this));
277 m_sysTray
->setToolTip(this->windowTitle());
278 m_sysTray
->setIcon(this->windowIcon());
279 connect(m_sysTray
.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason
)), this, SLOT(sysTrayActived()));
281 //Init taskbar progress
282 m_taskbar
.reset(new MUtils::Taskbar7(this));
284 //Create corner widget
285 QLabel
*checkUp
= new QLabel(ui
->menubar
);
286 checkUp
->setText(QString("<nobr><img src=\":/buttons/exclamation_small.png\"> <b style=\"color:darkred\">%1</b> </nobr>").arg(tr("Check for Updates")));
287 checkUp
->setFixedHeight(ui
->menubar
->height());
288 checkUp
->setCursor(QCursor(Qt::PointingHandCursor
));
289 m_inputFilter_checkUp
.reset(new InputEventFilter(checkUp
));
290 m_inputFilter_checkUp
->addMouseFilter(Qt::LeftButton
, 0);
291 m_inputFilter_checkUp
->addMouseFilter(Qt::RightButton
, 0);
292 connect(m_inputFilter_checkUp
.data(), SIGNAL(mouseClicked(int)), this, SLOT(checkUpdates()));
294 ui
->menubar
->setCornerWidget(checkUp
);
297 m_fileTimer
.reset(new QTimer(this));
298 connect(m_fileTimer
.data(), SIGNAL(timeout()), this, SLOT(handlePendingFiles()));
304 MainWindow::~MainWindow(void)
306 OptionsModel::saveTemplate(m_options
.data(), QString::fromLatin1(tpl_last
));
308 if(!m_ipcThread
.isNull())
311 if(!m_ipcThread
->wait(5000))
313 m_ipcThread
->terminate();
321 ///////////////////////////////////////////////////////////////////////////////
323 ///////////////////////////////////////////////////////////////////////////////
326 * The "add" button was clicked
328 void MainWindow::addButtonPressed()
330 ENSURE_APP_IS_READY();
332 qDebug("MainWindow::addButtonPressed");
333 bool runImmediately
= (countRunningJobs() < (m_preferences
->getAutoRunNextJob() ? m_preferences
->getMaxRunningJobCount() : 1));
334 QString sourceFileName
, outputFileName
;
336 if(createJob(sourceFileName
, outputFileName
, m_options
.data(), runImmediately
))
338 appendJob(sourceFileName
, outputFileName
, m_options
.data(), runImmediately
);
343 * The "open" action was triggered
345 void MainWindow::openActionTriggered()
347 ENSURE_APP_IS_READY();
348 qWarning("openActionTriggered()");
350 QStringList fileList
= QFileDialog::getOpenFileNames(this, tr("Open Source File(s)"), m_recentlyUsed
->sourceDirectory(), AddJobDialog::getInputFilterLst(), NULL
, QFileDialog::DontUseNativeDialog
);
351 if(!fileList
.empty())
353 m_recentlyUsed
->setSourceDirectory(QFileInfo(fileList
.last()).absolutePath());
354 if(fileList
.count() > 1)
356 createJobMultiple(fileList
);
360 bool runImmediately
= (countRunningJobs() < (m_preferences
->getAutoRunNextJob() ? m_preferences
->getMaxRunningJobCount() : 1));
361 QString
sourceFileName(fileList
.first()), outputFileName
;
362 if(createJob(sourceFileName
, outputFileName
, m_options
.data(), runImmediately
))
364 appendJob(sourceFileName
, outputFileName
, m_options
.data(), runImmediately
);
371 * The "clean-up" action was invoked
373 void MainWindow::cleanupActionTriggered(void)
375 ENSURE_APP_IS_READY();
377 QAction
*const sender
= dynamic_cast<QAction
*>(QObject::sender());
380 const QVariant data
= sender
->data();
381 if (data
.isValid() && (data
.type() == QVariant::Bool
))
383 const bool mode
= data
.toBool();
384 const int rows
= m_jobList
->rowCount(QModelIndex());
385 QList
<int> jobIndices
;
386 for (int i
= 0; i
< rows
; i
++)
388 const JobStatus status
= m_jobList
->getJobStatus(m_jobList
->index(i
, 0, QModelIndex()));
389 if (mode
&& (status
== JobStatus_Enqueued
))
391 jobIndices
.append(i
);
393 else if ((!mode
) && ((status
== JobStatus_Completed
) || (status
== JobStatus_Aborted
) || (status
== JobStatus_Failed
)))
395 jobIndices
.append(i
);
398 if (!jobIndices
.isEmpty())
400 QListIterator
<int> iter(jobIndices
);
402 while(iter
.hasPrevious())
404 m_jobList
->deleteJob(m_jobList
->index(iter
.previous(), 0, QModelIndex()));
409 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN
);
416 * The "start" button was clicked
418 void MainWindow::startButtonPressed(void)
420 ENSURE_APP_IS_READY();
421 m_jobList
->startJob(ui
->jobsView
->currentIndex());
425 * The "abort" button was clicked
427 void MainWindow::abortButtonPressed(void)
429 ENSURE_APP_IS_READY();
431 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)
433 m_jobList
->abortJob(ui
->jobsView
->currentIndex());
438 * The "delete" button was clicked
440 void MainWindow::deleteButtonPressed(void)
442 ENSURE_APP_IS_READY();
444 m_jobList
->deleteJob(ui
->jobsView
->currentIndex());
445 m_label
[0]->setVisible(m_jobList
->rowCount(QModelIndex()) == 0);
449 * The "browse" button was clicked
451 void MainWindow::browseButtonPressed(void)
453 ENSURE_APP_IS_READY();
455 QString outputFile
= m_jobList
->getJobOutputFile(ui
->jobsView
->currentIndex());
456 if((!outputFile
.isEmpty()) && QFileInfo(outputFile
).exists() && QFileInfo(outputFile
).isFile())
458 QProcess::startDetached(QString::fromLatin1("explorer.exe"), QStringList() << QString::fromLatin1("/select,") << QDir::toNativeSeparators(outputFile
), QFileInfo(outputFile
).path());
462 QMessageBox::warning(this, tr("Not Found"), tr("Sorry, the output file could not be found!"));
467 * The "browse" button was clicked
469 void MainWindow::moveButtonPressed(void)
471 ENSURE_APP_IS_READY();
473 if(sender() == ui
->actionJob_MoveUp
)
475 qDebug("Move job %d (direction: UP)", ui
->jobsView
->currentIndex().row());
476 if(!m_jobList
->moveJob(ui
->jobsView
->currentIndex(), JobListModel::MOVE_UP
))
478 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR
);
480 ui
->jobsView
->scrollTo(ui
->jobsView
->currentIndex(), QAbstractItemView::PositionAtCenter
);
482 else if(sender() == ui
->actionJob_MoveDown
)
484 qDebug("Move job %d (direction: DOWN)", ui
->jobsView
->currentIndex().row());
485 if(!m_jobList
->moveJob(ui
->jobsView
->currentIndex(), JobListModel::MOVE_DOWN
))
487 MUtils::Sound::beep(MUtils::Sound::BEEP_ERR
);
489 ui
->jobsView
->scrollTo(ui
->jobsView
->currentIndex(), QAbstractItemView::PositionAtCenter
);
493 qWarning("[moveButtonPressed] Error: Unknown sender!");
498 * The "pause" button was clicked
500 void MainWindow::pauseButtonPressed(bool checked
)
504 MUtils::Sound::beep(MUtils::Sound::BEEP_WRN
);
505 qWarning("Cannot perfrom this action at this time!");
506 ui
->buttonPauseJob
->setChecked(!checked
);
511 m_jobList
->pauseJob(ui
->jobsView
->currentIndex());
515 m_jobList
->resumeJob(ui
->jobsView
->currentIndex());
520 * The "restart" button was clicked
522 void MainWindow::restartButtonPressed(void)
524 ENSURE_APP_IS_READY();
526 const QModelIndex index
= ui
->jobsView
->currentIndex();
527 const OptionsModel
*options
= m_jobList
->getJobOptions(index
);
528 QString sourceFileName
= m_jobList
->getJobSourceFile(index
);
529 QString outputFileName
= m_jobList
->getJobOutputFile(index
);
531 if((options
) && (!sourceFileName
.isEmpty()) && (!outputFileName
.isEmpty()))
533 bool runImmediately
= (countRunningJobs() < (m_preferences
->getAutoRunNextJob() ? m_preferences
->getMaxRunningJobCount() : 1));
534 OptionsModel
*tempOptions
= new OptionsModel(*options
);
535 if(createJob(sourceFileName
, outputFileName
, tempOptions
, runImmediately
, true))
537 appendJob(sourceFileName
, outputFileName
, tempOptions
, runImmediately
);
539 MUTILS_DELETE(tempOptions
);
544 * Job item selected by user
546 void MainWindow::jobSelected(const QModelIndex
& current
, const QModelIndex
& previous
)
548 qDebug("Job selected: %d", current
.row());
550 if(ui
->logView
->model())
552 disconnect(ui
->logView
->model(), SIGNAL(rowsInserted(QModelIndex
, int, int)), this, SLOT(jobLogExtended(QModelIndex
, int, int)));
555 if(current
.isValid())
557 ui
->logView
->setModel(m_jobList
->getLogFile(current
));
558 connect(ui
->logView
->model(), SIGNAL(rowsInserted(QModelIndex
, int, int)), this, SLOT(jobLogExtended(QModelIndex
, int, int)));
559 foreach(QAction
*action
, ui
->logView
->actions())
561 action
->setEnabled(true);
563 QTimer::singleShot(0, ui
->logView
, SLOT(scrollToBottom()));
565 ui
->progressBar
->setValue(m_jobList
->getJobProgress(current
));
566 ui
->editDetails
->setText(m_jobList
->data(m_jobList
->index(current
.row(), 3, QModelIndex()), Qt::DisplayRole
).toString());
567 updateButtons(m_jobList
->getJobStatus(current
));
568 updateTaskbar(m_jobList
->getJobStatus(current
), m_jobList
->data(m_jobList
->index(current
.row(), 0, QModelIndex()), Qt::DecorationRole
).value
<QIcon
>());
572 ui
->logView
->setModel(NULL
);
573 foreach(QAction
*action
, ui
->logView
->actions())
575 action
->setEnabled(false);
577 ui
->progressBar
->setValue(0);
578 ui
->editDetails
->clear();
579 updateButtons(JobStatus_Undefined
);
580 updateTaskbar(JobStatus_Undefined
, QIcon());
583 ui
->progressBar
->repaint();
587 * Handle update of job info (status, progress, details, etc)
589 void MainWindow::jobChangedData(const QModelIndex
&topLeft
, const QModelIndex
&bottomRight
)
591 int selected
= ui
->jobsView
->currentIndex().row();
593 if(topLeft
.column() <= 1 && bottomRight
.column() >= 1) /*STATUS*/
595 for(int i
= topLeft
.row(); i
<= bottomRight
.row(); i
++)
597 JobStatus status
= m_jobList
->getJobStatus(m_jobList
->index(i
, 0, QModelIndex()));
600 qDebug("Current job changed status!");
601 updateButtons(status
);
602 updateTaskbar(status
, m_jobList
->data(m_jobList
->index(i
, 0, QModelIndex()), Qt::DecorationRole
).value
<QIcon
>());
604 if((status
== JobStatus_Completed
) || (status
== JobStatus_Failed
))
606 if(m_preferences
->getAutoRunNextJob()) QTimer::singleShot(0, this, SLOT(launchNextJob()));
607 if(m_preferences
->getSaveLogFiles()) saveLogFile(m_jobList
->index(i
, 1, QModelIndex()));
611 if(topLeft
.column() <= 2 && bottomRight
.column() >= 2) /*PROGRESS*/
613 for(int i
= topLeft
.row(); i
<= bottomRight
.row(); i
++)
617 ui
->progressBar
->setValue(m_jobList
->getJobProgress(m_jobList
->index(i
, 0, QModelIndex())));
618 if(!m_taskbar
.isNull())
620 m_taskbar
->setTaskbarProgress(ui
->progressBar
->value(), ui
->progressBar
->maximum());
626 if(topLeft
.column() <= 3 && bottomRight
.column() >= 3) /*DETAILS*/
628 for(int i
= topLeft
.row(); i
<= bottomRight
.row(); i
++)
632 ui
->editDetails
->setText(m_jobList
->data(m_jobList
->index(i
, 3, QModelIndex()), Qt::DisplayRole
).toString());
640 * Handle new log file content
642 void MainWindow::jobLogExtended(const QModelIndex
& parent
, int start
, int end
)
644 QTimer::singleShot(0, ui
->logView
, SLOT(scrollToBottom()));
650 void MainWindow::showAbout(void)
652 ENSURE_APP_IS_READY();
654 if(AboutDialog
*aboutDialog
= new AboutDialog(this))
657 MUTILS_DELETE(aboutDialog
);
664 void MainWindow::showWebLink(void)
666 ENSURE_APP_IS_READY();
668 if(QObject
*obj
= QObject::sender())
670 if(QAction
*action
= dynamic_cast<QAction
*>(obj
))
672 if(action
->data().type() == QVariant::Url
)
674 QDesktopServices::openUrl(action
->data().toUrl());
681 * Pereferences dialog
683 void MainWindow::showPreferences(void)
685 ENSURE_APP_IS_READY();
687 PreferencesDialog
*preferences
= new PreferencesDialog(this, m_preferences
.data(), m_sysinfo
.data());
690 MUTILS_DELETE(preferences
);
694 * Launch next job, after running job has finished
696 void MainWindow::launchNextJob(void)
698 qDebug("Launching next job...");
700 if(countRunningJobs() >= m_preferences
->getMaxRunningJobCount())
702 qDebug("Still have too many jobs running, won't launch next one yet!");
706 const int rows
= m_jobList
->rowCount(QModelIndex());
708 for(int i
= 0; i
< rows
; i
++)
710 const QModelIndex currentIndex
= m_jobList
->index(i
, 0, QModelIndex());
711 if(m_jobList
->getJobStatus(currentIndex
) == JobStatus_Enqueued
)
713 if(m_jobList
->startJob(currentIndex
))
715 ui
->jobsView
->selectRow(currentIndex
.row());
721 qWarning("No enqueued jobs left to be started!");
723 if(m_preferences
->getShutdownComputer())
725 QTimer::singleShot(0, this, SLOT(shutdownComputer()));
730 * Save log to text file
732 void MainWindow::saveLogFile(const QModelIndex
&index
)
736 if(LogFileModel
*log
= m_jobList
->getLogFile(index
))
738 const QString outputDir
= QString("%1/logs").arg(x264_data_path());
739 const QString timeStamp
= QDateTime::currentDateTime().toString("yyyy-MM-dd.HH-mm-ss");
740 QDir(outputDir
).mkpath(".");
741 const QString logFilePath
= MUtils::make_unique_file(outputDir
, QString("LOG.%1").arg(timeStamp
), QLatin1String("txt"));
742 if(logFilePath
.isEmpty())
744 qWarning("Failed to generate log file name. Giving up!");
747 if(!log
->saveToLocalFile(logFilePath
))
749 qWarning("Failed to open log file for writing:\n%s", logFilePath
.toUtf8().constData());
756 * Shut down the computer (with countdown)
758 void MainWindow::shutdownComputer(void)
760 ENSURE_APP_IS_READY();
762 if(countPendingJobs() > 0)
764 qDebug("Still have pending jobs, won't shutdown yet!");
768 const int iTimeout
= 30;
769 const Qt::WindowFlags flags
= Qt::WindowStaysOnTopHint
| Qt::CustomizeWindowHint
| Qt::WindowTitleHint
| Qt::MSWindowsFixedSizeDialogHint
| Qt::WindowSystemMenuHint
;
770 const QString text
= QString("%1%2%1").arg(QString().fill(' ', 18), tr("Warning: Computer will shutdown in %1 seconds..."));
772 qWarning("Initiating shutdown sequence!");
774 QProgressDialog
progressDialog(text
.arg(iTimeout
), tr("Cancel Shutdown"), 0, iTimeout
+ 1, this, flags
);
775 QPushButton
*cancelButton
= new QPushButton(tr("Cancel Shutdown"), &progressDialog
);
776 cancelButton
->setIcon(QIcon(":/buttons/power_on.png"));
777 progressDialog
.setModal(true);
778 progressDialog
.setAutoClose(false);
779 progressDialog
.setAutoReset(false);
780 progressDialog
.setWindowIcon(QIcon(":/buttons/power_off.png"));
781 progressDialog
.setWindowTitle(windowTitle());
782 progressDialog
.setCancelButton(cancelButton
);
783 progressDialog
.show();
785 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents
);
786 QApplication::setOverrideCursor(Qt::WaitCursor
);
787 MUtils::Sound::play_sound("shutdown", false);
788 QApplication::restoreOverrideCursor();
791 timer
.setInterval(1000);
794 QEventLoop
eventLoop(this);
795 connect(&timer
, SIGNAL(timeout()), &eventLoop
, SLOT(quit()));
796 connect(&progressDialog
, SIGNAL(canceled()), &eventLoop
, SLOT(quit()));
798 for(int i
= 1; i
<= iTimeout
; i
++)
801 if(progressDialog
.wasCanceled())
803 progressDialog
.close();
806 progressDialog
.setValue(i
+1);
807 progressDialog
.setLabelText(text
.arg(iTimeout
-i
));
808 if(iTimeout
-i
== 3) progressDialog
.setCancelButton(NULL
);
809 QApplication::processEvents();
810 MUtils::Sound::play_sound(((i
< iTimeout
) ? "beep" : "beep2"), false);
813 qWarning("Shutting down !!!");
815 if(MUtils::OS::shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true, false))
817 qApp
->closeAllWindows();
823 * Main initialization function (called only once!)
825 void MainWindow::init(void)
829 qWarning("Already initialized -> skipping!");
834 const MUtils::OS::ArgumentMap
&arguments
= MUtils::OS::arguments();
835 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
837 //---------------------------------------
838 // Check required binaries
839 //---------------------------------------
841 qDebug("[Validating binaries]");
842 if(!BinariesCheckThread::check(m_sysinfo
.data()))
844 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("-", "−"));
845 qFatal("At least one tool is missing or is not a valid Win32/Win64 binary!");
849 //---------------------------------------
850 // Check for portable mode
851 //---------------------------------------
853 if(x264_is_portable())
856 static const char *data
= "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
857 QFile
writeTest(QString("%1/%2").arg(x264_data_path(), QUuid::createUuid().toString()));
858 if(writeTest
.open(QIODevice::WriteOnly
))
860 ok
= (writeTest
.write(data
) == strlen(data
));
865 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"));
866 if(val
!= 1) INIT_ERROR_EXIT();
871 if(x264_is_prerelease())
873 qsrand(time(NULL
)); int rnd
= qrand() % 3;
874 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);
875 if(rnd
!= val
) INIT_ERROR_EXIT();
878 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
880 //---------------------------------------
881 // Check CPU capabilities
882 //---------------------------------------
884 //Make sure this CPU can run x264 (requires MMX + MMXEXT/iSSE to run x264 with ASM enabled, additionally requires SSE1 for most x264 builds)
885 if(!m_sysinfo
->getCPUFeatures(SysinfoModel::CPUFeatures_MMX
))
887 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"));
888 qFatal("System does not support MMX and MMXEXT, x264 will not work !!!");
891 else if(!m_sysinfo
->getCPUFeatures(SysinfoModel::CPUFeatures_SSE
))
893 qWarning("WARNING: System does not support SSE (v1), x264/x265 probably will *not* work !!!\n");
894 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"));
895 if(val
!= 1) INIT_ERROR_EXIT();
898 //Skip version check (not recommended!)
899 if(arguments
.contains(CLI_PARAM_SKIP_VERSION_CHECK
))
901 qWarning("Version checks are disabled now, you have been warned!\n");
902 m_preferences
->setSkipVersionTest(true);
905 //Don't abort encoding process on timeout (not recommended!)
906 if(arguments
.contains(CLI_PARAM_NO_DEADLOCK
))
908 qWarning("Deadlock detection disabled, you have been warned!\n");
909 m_preferences
->setAbortOnTimeout(false);
912 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
914 //---------------------------------------
915 // Check Avisynth support
916 //---------------------------------------
918 if(!arguments
.contains(CLI_PARAM_SKIP_AVS_CHECK
))
920 qDebug("[Check for Avisynth support]");
921 if(!AvisynthCheckThread::detect(m_sysinfo
.data()))
923 QString text
= tr("A critical error was encountered while checking your Avisynth version.").append("<br>");
924 text
+= tr("This is most likely caused by an erroneous Avisynth Plugin, please try to clean your Plugins folder!").append("<br>");
925 text
+= tr("We suggest to move all .dll and .avsi files out of your Avisynth Plugins folder and try again.");
926 int val
= QMessageBox::critical(this, tr("Avisynth Error"), QString("<nobr>%1</nobr>").arg(text
).replace("-", "−"), tr("Quit"), tr("Ignore"));
927 if(val
!= 1) INIT_ERROR_EXIT();
929 else if((!m_sysinfo
->hasAvisynth()) && (!m_preferences
->getDisableWarnings()))
931 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>");
932 text
+= tr("Please download and install Avisynth:").append("<br>").append(LINK(avs_dl_url
));
933 int val
= QMessageBox::warning(this, tr("Avisynth Missing"), QString("<nobr>%1</nobr>").arg(text
).replace("-", "−"), tr("Close"), tr("Disable this Warning"));
936 m_preferences
->setDisableWarnings(true);
937 PreferencesModel::savePreferences(m_preferences
.data());
943 //---------------------------------------
944 // Check VapurSynth support
945 //---------------------------------------
947 if(!arguments
.contains(CLI_PARAM_SKIP_VPS_CHECK
))
949 qDebug("[Check for VapourSynth support]");
950 if(!VapourSynthCheckThread::detect(m_sysinfo
.data()))
952 QString text
= tr("A critical error was encountered while checking your VapourSynth installation.").append("<br>");
953 text
+= tr("This is most likely caused by an erroneous VapourSynth Plugin, please try to clean your Filters folder!").append("<br>");
954 text
+= tr("We suggest to move all .dll files out of your VapourSynth Filters folder and try again.");
955 const int val
= QMessageBox::critical(this, tr("VapourSynth Error"), QString("<nobr>%1</nobr>").arg(text
).replace("-", "−"), tr("Quit"), tr("Ignore"));
956 if(val
!= 1) INIT_ERROR_EXIT();
958 else if((!m_sysinfo
->hasVapourSynth()) && (!m_preferences
->getDisableWarnings()))
960 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>");
961 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>");
962 text
+= tr("Note that Python v3.4 is a prerequisite for installing VapourSynth:").append("<br>").append(LINK(python_url
)).append("<br>");
963 const int val
= QMessageBox::warning(this, tr("VapourSynth Missing"), QString("<nobr>%1</nobr>").arg(text
).replace("-", "−"), tr("Close"), tr("Disable this Warning"));
966 m_preferences
->setDisableWarnings(true);
967 PreferencesModel::savePreferences(m_preferences
.data());
973 //---------------------------------------
974 // Create the IPC listener thread
975 //---------------------------------------
979 m_ipcThread
.reset(new IPCThread_Recv(m_ipcChannel
));
980 connect(m_ipcThread
.data(), SIGNAL(receivedCommand(int,QStringList
,quint32
)), this, SLOT(handleCommand(int,QStringList
,quint32
)), Qt::QueuedConnection
);
981 m_ipcThread
->start();
984 //---------------------------------------
985 // Finish initialization
986 //---------------------------------------
989 setWindowTitle(QString("%1 (%2)").arg(windowTitle(), m_sysinfo
->getCPUFeatures(SysinfoModel::CPUFeatures_X64
) ? "64-Bit" : "32-Bit"));
991 //Enable drag&drop support for this window, required for Qt v4.8.4+
992 setAcceptDrops(true);
995 m_initialized
= true;
997 //Hide the spinner animation
998 if(!m_label
[1].isNull())
1000 if(!m_animation
.isNull())
1002 m_animation
->stop();
1004 m_label
[1]->setVisible(false);
1007 //---------------------------------------
1008 // Check for Expiration
1009 //---------------------------------------
1011 if(MUtils::Version::app_build_date().addMonths(6) < MUtils::OS::current_date())
1013 if(QWidget
*cornerWidget
= ui
->menubar
->cornerWidget()) cornerWidget
->show();
1015 text
+= QString("<nobr><tt>%1</tt></nobr><br><br>").arg(tr("Your version of Simple x264 Launcher is more than 6 months old!").replace('-', "−"));
1016 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('-', "−"), QString::fromLatin1(update_url
), QString::fromLatin1(update_url
).replace("-", "−"));
1017 text
+= QString("<nobr><tt>%1</tt></nobr><br>").arg(tr("Alternatively, click 'Check for Updates' to run the auto-update utility.").replace('-', "−"));
1018 QMessageBox
msgBox(this);
1019 msgBox
.setIconPixmap(QIcon(":/images/update.png").pixmap(56,56));
1020 msgBox
.setWindowTitle(tr("Update Notification"));
1021 msgBox
.setWindowFlags(Qt::Window
| Qt::WindowTitleHint
| Qt::CustomizeWindowHint
);
1022 msgBox
.setText(text
);
1023 QPushButton
*btn1
= msgBox
.addButton(tr("Check for Updates"), QMessageBox::AcceptRole
);
1024 QPushButton
*btn2
= msgBox
.addButton(tr("Discard"), QMessageBox::NoRole
);
1025 QPushButton
*btn3
= msgBox
.addButton(btn2
->text(), QMessageBox::RejectRole
);
1026 btn2
->setEnabled(false);
1027 btn3
->setVisible(false);
1028 QTimer::singleShot(7500, btn2
, SLOT(hide()));
1029 QTimer::singleShot(7500, btn3
, SLOT(show()));
1030 if(msgBox
.exec() == 0)
1032 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1036 else if(!parseCommandLineArgs())
1039 if(arguments
.contains(CLI_PARAM_FIRST_RUN
))
1041 qWarning("First run -> resetting update check now!");
1042 m_recentlyUsed
->setLastUpdateCheck(0);
1043 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed
.data());
1045 else if(m_recentlyUsed
->lastUpdateCheck() + 14 < MUtils::OS::current_date().toJulianDay())
1047 if(QWidget
*cornerWidget
= ui
->menubar
->cornerWidget()) cornerWidget
->show();
1048 if(!m_preferences
->getNoUpdateReminder())
1050 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)
1052 QTimer::singleShot(0, this, SLOT(checkUpdates()));
1060 if(m_jobList
->loadQueuedJobs(m_sysinfo
.data()) > 0)
1062 m_label
[0]->setVisible(m_jobList
->rowCount(QModelIndex()) == 0);
1063 m_jobList
->clearQueuedJobs();
1068 * Update the label position
1070 void MainWindow::updateLabelPos(void)
1072 for(int i
= 0; i
< 2; i
++)
1074 //const QWidget *const viewPort = ui->jobsView->viewport();
1075 const QWidget
*const viewPort
= dynamic_cast<QWidget
*>(m_label
[i
]->parent());
1078 m_label
[i
]->setGeometry(0, 0, viewPort
->width(), viewPort
->height());
1084 * Copy the complete log to the clipboard
1086 void MainWindow::copyLogToClipboard(bool checked
)
1088 qDebug("Coyping logfile to clipboard...");
1090 if(LogFileModel
*log
= dynamic_cast<LogFileModel
*>(ui
->logView
->model()))
1092 log
->copyToClipboard();
1093 MUtils::Sound::beep(MUtils::Sound::BEEP_NFO
);
1098 * Save log to local file
1100 void MainWindow::saveLogToLocalFile(bool checked
)
1102 ENSURE_APP_IS_READY();
1104 const QModelIndex index
= ui
->jobsView
->currentIndex();
1105 const QString initialName
= index
.isValid() ? QFileInfo(m_jobList
->getJobOutputFile(index
)).completeBaseName() : tr("Logfile");
1106 const QString fileName
= QFileDialog::getSaveFileName(this, tr("Save Log File"), initialName
, tr("Log File (*.log)"));
1107 if(!fileName
.isEmpty())
1109 if(LogFileModel
*log
= dynamic_cast<LogFileModel
*>(ui
->logView
->model()))
1111 if(!log
->saveToLocalFile(fileName
))
1113 QMessageBox::warning(this, this->windowTitle(), tr("Error: Log file could not be saved!"));
1120 * Toggle line-wrapping
1122 void MainWindow::toggleLineWrapping(bool checked
)
1124 ui
->logView
->setWordWrap(checked
);
1128 * Process the dropped files
1130 void MainWindow::handlePendingFiles(void)
1132 qDebug("MainWindow::handlePendingFiles");
1134 if(!m_pendingFiles
->isEmpty())
1136 QStringList
pendingFiles(*m_pendingFiles
);
1137 m_pendingFiles
->clear();
1138 createJobMultiple(pendingFiles
);
1141 qDebug("Leave from MainWindow::handlePendingFiles!");
1145 * Handle incoming IPC command
1147 void MainWindow::handleCommand(const int &command
, const QStringList
&args
, const quint32
&flags
)
1149 if(!(m_initialized
&& (QApplication::activeModalWidget() == NULL
)))
1151 qWarning("Cannot accapt commands at this time -> discarding!");
1155 if((!isVisible()) || m_sysTray
->isVisible())
1160 MUtils::GUI::bring_to_front(this);
1163 qDebug("\n---------- IPC ----------");
1164 qDebug("CommandId: %d", command
);
1165 for(QStringList::ConstIterator iter
= args
.constBegin(); iter
!= args
.constEnd(); iter
++)
1167 qDebug("Arguments: %s", iter
->toUtf8().constData());
1169 qDebug("The Flags: 0x%08X", flags
);
1170 qDebug("---------- IPC ----------\n");
1171 #endif //IPC_LOGGING
1175 case IPC_OPCODE_PING
:
1176 qDebug("Received a PING request from another instance!");
1177 MUtils::GUI::blink_window(this, 5, 125);
1179 case IPC_OPCODE_ADD_FILE
:
1182 if(QFileInfo(args
[0]).exists() && QFileInfo(args
[0]).isFile())
1184 *m_pendingFiles
<< QFileInfo(args
[0]).canonicalFilePath();
1185 if(!m_fileTimer
->isActive())
1187 m_fileTimer
->setSingleShot(true);
1188 m_fileTimer
->start(5000);
1193 qWarning("File '%s' not found!", args
[0].toUtf8().constData());
1197 case IPC_OPCODE_ADD_JOB
:
1198 if(args
.size() >= 3)
1200 if(QFileInfo(args
[0]).exists() && QFileInfo(args
[0]).isFile())
1202 OptionsModel
options(m_sysinfo
.data());
1203 bool runImmediately
= (countRunningJobs() < (m_preferences
->getAutoRunNextJob() ? m_preferences
->getMaxRunningJobCount() : 1));
1204 if(!(args
[2].isEmpty() || X264_STRCMP(args
[2], "-")))
1206 if(!OptionsModel::loadTemplate(&options
, args
[2].trimmed()))
1208 qWarning("Template '%s' could not be found -> using defaults!", args
[2].trimmed().toUtf8().constData());
1211 if((flags
& IPC_FLAG_FORCE_START
) && (!(flags
& IPC_FLAG_FORCE_ENQUEUE
))) runImmediately
= true;
1212 if((flags
& IPC_FLAG_FORCE_ENQUEUE
) && (!(flags
& IPC_FLAG_FORCE_START
))) runImmediately
= false;
1213 appendJob(args
[0], args
[1], &options
, runImmediately
);
1217 qWarning("Source file '%s' not found!", args
[0].toUtf8().constData());
1222 MUTILS_THROW("Unknown command received!");
1227 * Check for new updates
1229 void MainWindow::checkUpdates(void)
1231 ENSURE_APP_IS_READY();
1233 if(countRunningJobs() > 0)
1235 QMessageBox::warning(this, tr("Jobs Are Running"), tr("Sorry, can not update while there still are running jobs!"));
1239 UpdaterDialog
*updater
= new UpdaterDialog(this, m_sysinfo
.data(), update_url
);
1240 const int ret
= updater
->exec();
1242 if(updater
->getSuccess())
1244 m_recentlyUsed
->setLastUpdateCheck(MUtils::OS::current_date().toJulianDay());
1245 RecentlyUsed::saveRecentlyUsed(m_recentlyUsed
.data());
1246 if(QWidget
*cornerWidget
= ui
->menubar
->cornerWidget()) cornerWidget
->hide();
1249 if(ret
== UpdaterDialog::READY_TO_INSTALL_UPDATE
)
1251 qWarning("Exitting program to install update...");
1253 QApplication::quit();
1256 MUTILS_DELETE(updater
);
1260 * Handle mouse event for version label
1262 void MainWindow::versionLabelMouseClicked(const int &tag
)
1266 QTimer::singleShot(0, this, SLOT(showAbout()));
1271 * Handle key event for job list
1273 void MainWindow::jobListKeyPressed(const int &tag
)
1278 ui
->actionJob_MoveUp
->trigger();
1281 ui
->actionJob_MoveDown
->trigger();
1287 * System tray was activated
1289 void MainWindow::sysTrayActived(void)
1293 MUtils::GUI::bring_to_front(this);
1296 ///////////////////////////////////////////////////////////////////////////////
1298 ///////////////////////////////////////////////////////////////////////////////
1301 * Window shown event
1303 void MainWindow::showEvent(QShowEvent
*e
)
1305 QMainWindow::showEvent(e
);
1309 QTimer::singleShot(0, this, SLOT(init()));
1314 * Window close event
1316 void MainWindow::closeEvent(QCloseEvent
*e
)
1321 qWarning("Cannot close window at this time!");
1325 //Make sure we have no running jobs left!
1326 if(countRunningJobs() > 0)
1329 if(!m_preferences
->getNoSystrayWarning())
1331 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)
1333 m_preferences
->setNoSystrayWarning(true);
1334 PreferencesModel::savePreferences(m_preferences
.data());
1342 //Save pending jobs for next time, if desired by user
1343 if(countPendingJobs() > 0)
1345 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"));
1348 m_jobList
->saveQueuedJobs();
1352 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
)
1360 //Delete remaining jobs
1361 while(m_jobList
->rowCount(QModelIndex()) > 0)
1363 if((m_jobList
->rowCount(QModelIndex()) % 10) == 0)
1365 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
1367 if(!m_jobList
->deleteJob(m_jobList
->index(0, 0, QModelIndex())))
1370 QMessageBox::warning(this, tr("Failed To Exit"), tr("Warning: At least one job could not be deleted!"));
1374 qApp
->processEvents(QEventLoop::ExcludeUserInputEvents
);
1375 QMainWindow::closeEvent(e
);
1379 * Window resize event
1381 void MainWindow::resizeEvent(QResizeEvent
*e
)
1383 QMainWindow::resizeEvent(e
);
1388 * File dragged over window
1390 void MainWindow::dragEnterEvent(QDragEnterEvent
*event
)
1392 bool accept
[2] = {false, false};
1394 foreach(const QString
&fmt
, event
->mimeData()->formats())
1396 accept
[0] = accept
[0] || fmt
.contains("text/uri-list", Qt::CaseInsensitive
);
1397 accept
[1] = accept
[1] || fmt
.contains("FileNameW", Qt::CaseInsensitive
);
1400 if(accept
[0] && accept
[1])
1402 event
->acceptProposedAction();
1407 * File dropped onto window
1409 void MainWindow::dropEvent(QDropEvent
*event
)
1411 if(!(m_initialized
&& (QApplication::activeModalWidget() == NULL
)))
1413 qWarning("Cannot accept dropped files at this time -> discarding!");
1417 QStringList droppedFiles
;
1418 QList
<QUrl
> urls
= event
->mimeData()->urls();
1420 while(!urls
.isEmpty())
1422 QUrl currentUrl
= urls
.takeFirst();
1423 QFileInfo
file(currentUrl
.toLocalFile());
1424 if(file
.exists() && file
.isFile())
1426 qDebug("MainWindow::dropEvent: %s", file
.canonicalFilePath().toUtf8().constData());
1427 droppedFiles
<< file
.canonicalFilePath();
1431 if(droppedFiles
.count() > 0)
1433 m_pendingFiles
->append(droppedFiles
);
1434 m_pendingFiles
->sort();
1435 if(!m_fileTimer
->isActive())
1437 m_fileTimer
->setSingleShot(true);
1438 m_fileTimer
->start(5000);
1443 ///////////////////////////////////////////////////////////////////////////////
1444 // Private functions
1445 ///////////////////////////////////////////////////////////////////////////////
1450 bool MainWindow::createJob(QString
&sourceFileName
, QString
&outputFileName
, OptionsModel
*options
, bool &runImmediately
, const bool restart
, int fileNo
, int fileTotal
, bool *applyToAll
)
1453 AddJobDialog
*addDialog
= new AddJobDialog(this, options
, m_recentlyUsed
.data(), m_sysinfo
.data(), m_preferences
.data());
1455 addDialog
->setRunImmediately(runImmediately
);
1456 if(!sourceFileName
.isEmpty()) addDialog
->setSourceFile(sourceFileName
);
1457 if(!outputFileName
.isEmpty()) addDialog
->setOutputFile(outputFileName
);
1458 if(restart
) addDialog
->setWindowTitle(tr("Restart Job"));
1460 const bool multiFile
= (fileNo
>= 0) && (fileTotal
> 1);
1463 addDialog
->setSourceEditable(false);
1464 addDialog
->setWindowTitle(addDialog
->windowTitle().append(tr(" (File %1 of %2)").arg(QString::number(fileNo
+1), QString::number(fileTotal
))));
1465 addDialog
->setApplyToAllVisible(applyToAll
);
1468 if(addDialog
->exec() == QDialog::Accepted
)
1470 sourceFileName
= addDialog
->sourceFile();
1471 outputFileName
= addDialog
->outputFile();
1472 runImmediately
= addDialog
->runImmediately();
1475 *applyToAll
= addDialog
->applyToAll();
1480 MUTILS_DELETE(addDialog
);
1485 * Creates a new job from *multiple* files
1487 bool MainWindow::createJobMultiple(const QStringList
&filePathIn
)
1489 QStringList::ConstIterator iter
;
1490 bool applyToAll
= false, runImmediately
= false;
1493 //Add files individually
1494 for(iter
= filePathIn
.constBegin(); (iter
!= filePathIn
.constEnd()) && (!applyToAll
); iter
++)
1496 runImmediately
= (countRunningJobs() < (m_preferences
->getAutoRunNextJob() ? m_preferences
->getMaxRunningJobCount() : 1));
1497 QString
sourceFileName(*iter
), outputFileName
;
1498 if(createJob(sourceFileName
, outputFileName
, m_options
.data(), runImmediately
, false, counter
++, filePathIn
.count(), &applyToAll
))
1500 if(appendJob(sourceFileName
, outputFileName
, m_options
.data(), runImmediately
))
1508 //Add remaining files
1509 while(applyToAll
&& (iter
!= filePathIn
.constEnd()))
1511 const bool runImmediatelyTmp
= runImmediately
&& (countRunningJobs() < (m_preferences
->getAutoRunNextJob() ? m_preferences
->getMaxRunningJobCount() : 1));
1512 const QString sourceFileName
= *iter
;
1513 const QString outputFileName
= AddJobDialog::generateOutputFileName(sourceFileName
, m_recentlyUsed
->outputDirectory(), m_recentlyUsed
->filterIndex(), m_preferences
->getSaveToSourcePath());
1514 if(!appendJob(sourceFileName
, outputFileName
, m_options
.data(), runImmediatelyTmp
))
1527 bool MainWindow::appendJob(const QString
&sourceFileName
, const QString
&outputFileName
, OptionsModel
*options
, const bool runImmediately
)
1530 EncodeThread
*thrd
= new EncodeThread(sourceFileName
, outputFileName
, options
, m_sysinfo
.data(), m_preferences
.data());
1531 QModelIndex newIndex
= m_jobList
->insertJob(thrd
);
1533 if(newIndex
.isValid())
1537 ui
->jobsView
->selectRow(newIndex
.row());
1538 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents
);
1539 m_jobList
->startJob(newIndex
);
1545 m_label
[0]->setVisible(m_jobList
->rowCount(QModelIndex()) == 0);
1550 * Jobs that are not completed (or failed, or aborted) yet
1552 unsigned int MainWindow::countPendingJobs(void)
1554 unsigned int count
= 0;
1555 const int rows
= m_jobList
->rowCount(QModelIndex());
1557 for(int i
= 0; i
< rows
; i
++)
1559 JobStatus status
= m_jobList
->getJobStatus(m_jobList
->index(i
, 0, QModelIndex()));
1560 if(status
!= JobStatus_Completed
&& status
!= JobStatus_Aborted
&& status
!= JobStatus_Failed
)
1570 * Jobs that are still active, i.e. not terminated or enqueued
1572 unsigned int MainWindow::countRunningJobs(void)
1574 unsigned int count
= 0;
1575 const int rows
= m_jobList
->rowCount(QModelIndex());
1577 for(int i
= 0; i
< rows
; i
++)
1579 JobStatus status
= m_jobList
->getJobStatus(m_jobList
->index(i
, 0, QModelIndex()));
1580 if(status
!= JobStatus_Completed
&& status
!= JobStatus_Aborted
&& status
!= JobStatus_Failed
&& status
!= JobStatus_Enqueued
)
1590 * Update all buttons with respect to current job status
1592 void MainWindow::updateButtons(JobStatus status
)
1594 qDebug("MainWindow::updateButtons(void)");
1596 ui
->buttonStartJob
->setEnabled(status
== JobStatus_Enqueued
);
1597 ui
->buttonAbortJob
->setEnabled(status
== JobStatus_Indexing
|| status
== JobStatus_Running
|| status
== JobStatus_Running_Pass1
|| status
== JobStatus_Running_Pass2
|| status
== JobStatus_Paused
);
1598 ui
->buttonPauseJob
->setEnabled(status
== JobStatus_Indexing
|| status
== JobStatus_Running
|| status
== JobStatus_Paused
|| status
== JobStatus_Running_Pass1
|| status
== JobStatus_Running_Pass2
);
1599 ui
->buttonPauseJob
->setChecked(status
== JobStatus_Paused
|| status
== JobStatus_Pausing
);
1601 ui
->actionJob_Delete
->setEnabled(status
== JobStatus_Completed
|| status
== JobStatus_Aborted
|| status
== JobStatus_Failed
|| status
== JobStatus_Enqueued
);
1602 ui
->actionJob_Restart
->setEnabled(status
== JobStatus_Completed
|| status
== JobStatus_Aborted
|| status
== JobStatus_Failed
|| status
== JobStatus_Enqueued
);
1603 ui
->actionJob_Browse
->setEnabled(status
== JobStatus_Completed
);
1604 ui
->actionJob_MoveUp
->setEnabled(status
!= JobStatus_Undefined
);
1605 ui
->actionJob_MoveDown
->setEnabled(status
!= JobStatus_Undefined
);
1607 ui
->actionJob_Start
->setEnabled(ui
->buttonStartJob
->isEnabled());
1608 ui
->actionJob_Abort
->setEnabled(ui
->buttonAbortJob
->isEnabled());
1609 ui
->actionJob_Pause
->setEnabled(ui
->buttonPauseJob
->isEnabled());
1610 ui
->actionJob_Pause
->setChecked(ui
->buttonPauseJob
->isChecked());
1612 ui
->editDetails
->setEnabled(status
!= JobStatus_Paused
);
1616 * Update the taskbar with current job status
1618 void MainWindow::updateTaskbar(JobStatus status
, const QIcon
&icon
)
1620 qDebug("MainWindow::updateTaskbar(void)");
1622 if(m_taskbar
.isNull())
1624 return; /*taskbar object not created yet*/
1629 case JobStatus_Undefined
:
1630 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NONE
);
1632 case JobStatus_Aborting
:
1633 case JobStatus_Starting
:
1634 case JobStatus_Pausing
:
1635 case JobStatus_Resuming
:
1636 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_INTERMEDIATE
);
1638 case JobStatus_Aborted
:
1639 case JobStatus_Failed
:
1640 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_ERROR
);
1642 case JobStatus_Paused
:
1643 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_PAUSED
);
1646 m_taskbar
->setTaskbarState(MUtils::Taskbar7::TASKBAR_STATE_NORMAL
);
1652 case JobStatus_Aborting
:
1653 case JobStatus_Starting
:
1654 case JobStatus_Pausing
:
1655 case JobStatus_Resuming
:
1658 m_taskbar
->setTaskbarProgress(ui
->progressBar
->value(), ui
->progressBar
->maximum());
1662 m_taskbar
->setOverlayIcon(icon
.isNull() ? NULL
: &icon
);
1666 * Parse command-line arguments
1668 bool MainWindow::parseCommandLineArgs(void)
1670 const MUtils::OS::ArgumentMap
&args
= MUtils::OS::arguments();
1673 bool commandSent
= false;
1676 if(args
.contains(CLI_PARAM_FORCE_START
))
1678 flags
= ((flags
| IPC_FLAG_FORCE_START
) & (~IPC_FLAG_FORCE_ENQUEUE
));
1680 if(args
.contains(CLI_PARAM_FORCE_ENQUEUE
))
1682 flags
= ((flags
| IPC_FLAG_FORCE_ENQUEUE
) & (~IPC_FLAG_FORCE_START
));
1685 //Process all command-line arguments
1686 if(args
.contains(CLI_PARAM_ADD_FILE
))
1688 foreach(const QString
&fileName
, args
.values(CLI_PARAM_ADD_FILE
))
1690 handleCommand(IPC_OPCODE_ADD_FILE
, QStringList() << fileName
, flags
);
1694 if(args
.contains(CLI_PARAM_ADD_JOB
))
1696 foreach(const QString
&options
, args
.values(CLI_PARAM_ADD_JOB
))
1698 const QStringList optionValues
= options
.split('|', QString::SkipEmptyParts
);
1699 if(optionValues
.count() == 3)
1701 handleCommand(IPC_OPCODE_ADD_JOB
, optionValues
, flags
);
1705 qWarning("Invalid number of arguments for parameter \"--%s\" detected!", CLI_PARAM_ADD_JOB
);